1ec2b103cSEd Schouten //===--- CGExprConstant.cpp - Emit LLVM Code from Constant Expressions ----===//
2ec2b103cSEd Schouten //
322989816SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
422989816SDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
522989816SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6ec2b103cSEd Schouten //
7ec2b103cSEd Schouten //===----------------------------------------------------------------------===//
8ec2b103cSEd Schouten //
9ec2b103cSEd Schouten // This contains code to emit Constant Expr nodes as LLVM code.
10ec2b103cSEd Schouten //
11ec2b103cSEd Schouten //===----------------------------------------------------------------------===//
12ec2b103cSEd Schouten
13ac9a064cSDimitry Andric #include "ABIInfoImpl.h"
143d1dcd9bSDimitry Andric #include "CGCXXABI.h"
15ec2b103cSEd Schouten #include "CGObjCRuntime.h"
1611d2b2d2SRoman Divacky #include "CGRecordLayout.h"
17706b4fc4SDimitry Andric #include "CodeGenFunction.h"
18809500fcSDimitry Andric #include "CodeGenModule.h"
19461a67faSDimitry Andric #include "ConstantEmitter.h"
20bab175ecSDimitry Andric #include "TargetInfo.h"
21ec2b103cSEd Schouten #include "clang/AST/APValue.h"
22ec2b103cSEd Schouten #include "clang/AST/ASTContext.h"
23706b4fc4SDimitry Andric #include "clang/AST/Attr.h"
244c8b2481SRoman Divacky #include "clang/AST/RecordLayout.h"
25ec2b103cSEd Schouten #include "clang/AST/StmtVisitor.h"
267ef7bab7SEd Schouten #include "clang/Basic/Builtins.h"
2722989816SDimitry Andric #include "llvm/ADT/STLExtras.h"
28706b4fc4SDimitry Andric #include "llvm/ADT/Sequence.h"
29b1c73532SDimitry Andric #include "llvm/Analysis/ConstantFolding.h"
30809500fcSDimitry Andric #include "llvm/IR/Constants.h"
31809500fcSDimitry Andric #include "llvm/IR/DataLayout.h"
32809500fcSDimitry Andric #include "llvm/IR/Function.h"
33809500fcSDimitry Andric #include "llvm/IR/GlobalVariable.h"
34e3b55780SDimitry Andric #include <optional>
35ec2b103cSEd Schouten using namespace clang;
36ec2b103cSEd Schouten using namespace CodeGen;
37ec2b103cSEd Schouten
380883ccd9SRoman Divacky //===----------------------------------------------------------------------===//
3922989816SDimitry Andric // ConstantAggregateBuilder
400883ccd9SRoman Divacky //===----------------------------------------------------------------------===//
410883ccd9SRoman Divacky
42ec2b103cSEd Schouten namespace {
432e645aa5SDimitry Andric class ConstExprEmitter;
4422989816SDimitry Andric
4522989816SDimitry Andric struct ConstantAggregateBuilderUtils {
464c8b2481SRoman Divacky CodeGenModule &CGM;
474c8b2481SRoman Divacky
ConstantAggregateBuilderUtils__anon4cd729e60111::ConstantAggregateBuilderUtils4822989816SDimitry Andric ConstantAggregateBuilderUtils(CodeGenModule &CGM) : CGM(CGM) {}
490883ccd9SRoman Divacky
getAlignment__anon4cd729e60111::ConstantAggregateBuilderUtils5001af97d3SDimitry Andric CharUnits getAlignment(const llvm::Constant *C) const {
5101af97d3SDimitry Andric return CharUnits::fromQuantity(
52e3b55780SDimitry Andric CGM.getDataLayout().getABITypeAlign(C->getType()));
530883ccd9SRoman Divacky }
540883ccd9SRoman Divacky
getSize__anon4cd729e60111::ConstantAggregateBuilderUtils5522989816SDimitry Andric CharUnits getSize(llvm::Type *Ty) const {
5622989816SDimitry Andric return CharUnits::fromQuantity(CGM.getDataLayout().getTypeAllocSize(Ty));
5722989816SDimitry Andric }
5822989816SDimitry Andric
getSize__anon4cd729e60111::ConstantAggregateBuilderUtils5922989816SDimitry Andric CharUnits getSize(const llvm::Constant *C) const {
6022989816SDimitry Andric return getSize(C->getType());
6122989816SDimitry Andric }
6222989816SDimitry Andric
getPadding__anon4cd729e60111::ConstantAggregateBuilderUtils6322989816SDimitry Andric llvm::Constant *getPadding(CharUnits PadSize) const {
64b60736ecSDimitry Andric llvm::Type *Ty = CGM.CharTy;
6522989816SDimitry Andric if (PadSize > CharUnits::One())
6622989816SDimitry Andric Ty = llvm::ArrayType::get(Ty, PadSize.getQuantity());
6722989816SDimitry Andric return llvm::UndefValue::get(Ty);
6822989816SDimitry Andric }
6922989816SDimitry Andric
getZeroes__anon4cd729e60111::ConstantAggregateBuilderUtils7022989816SDimitry Andric llvm::Constant *getZeroes(CharUnits ZeroSize) const {
71b60736ecSDimitry Andric llvm::Type *Ty = llvm::ArrayType::get(CGM.CharTy, ZeroSize.getQuantity());
7222989816SDimitry Andric return llvm::ConstantAggregateZero::get(Ty);
730883ccd9SRoman Divacky }
740883ccd9SRoman Divacky };
750883ccd9SRoman Divacky
7622989816SDimitry Andric /// Incremental builder for an llvm::Constant* holding a struct or array
7722989816SDimitry Andric /// constant.
7822989816SDimitry Andric class ConstantAggregateBuilder : private ConstantAggregateBuilderUtils {
7922989816SDimitry Andric /// The elements of the constant. These two arrays must have the same size;
8022989816SDimitry Andric /// Offsets[i] describes the offset of Elems[i] within the constant. The
8122989816SDimitry Andric /// elements are kept in increasing offset order, and we ensure that there
8222989816SDimitry Andric /// is no overlap: Offsets[i+1] >= Offsets[i] + getSize(Elemes[i]).
8322989816SDimitry Andric ///
8422989816SDimitry Andric /// This may contain explicit padding elements (in order to create a
8522989816SDimitry Andric /// natural layout), but need not. Gaps between elements are implicitly
8622989816SDimitry Andric /// considered to be filled with undef.
8722989816SDimitry Andric llvm::SmallVector<llvm::Constant*, 32> Elems;
8822989816SDimitry Andric llvm::SmallVector<CharUnits, 32> Offsets;
8922989816SDimitry Andric
9022989816SDimitry Andric /// The size of the constant (the maximum end offset of any added element).
9122989816SDimitry Andric /// May be larger than the end of Elems.back() if we split the last element
9222989816SDimitry Andric /// and removed some trailing undefs.
9322989816SDimitry Andric CharUnits Size = CharUnits::Zero();
9422989816SDimitry Andric
9522989816SDimitry Andric /// This is true only if laying out Elems in order as the elements of a
9622989816SDimitry Andric /// non-packed LLVM struct will give the correct layout.
9722989816SDimitry Andric bool NaturalLayout = true;
9822989816SDimitry Andric
9922989816SDimitry Andric bool split(size_t Index, CharUnits Hint);
100e3b55780SDimitry Andric std::optional<size_t> splitAt(CharUnits Pos);
10122989816SDimitry Andric
10222989816SDimitry Andric static llvm::Constant *buildFrom(CodeGenModule &CGM,
10322989816SDimitry Andric ArrayRef<llvm::Constant *> Elems,
10422989816SDimitry Andric ArrayRef<CharUnits> Offsets,
10522989816SDimitry Andric CharUnits StartOffset, CharUnits Size,
10622989816SDimitry Andric bool NaturalLayout, llvm::Type *DesiredTy,
10722989816SDimitry Andric bool AllowOversized);
10822989816SDimitry Andric
10922989816SDimitry Andric public:
ConstantAggregateBuilder(CodeGenModule & CGM)11022989816SDimitry Andric ConstantAggregateBuilder(CodeGenModule &CGM)
11122989816SDimitry Andric : ConstantAggregateBuilderUtils(CGM) {}
11222989816SDimitry Andric
11322989816SDimitry Andric /// Update or overwrite the value starting at \p Offset with \c C.
11422989816SDimitry Andric ///
11522989816SDimitry Andric /// \param AllowOverwrite If \c true, this constant might overwrite (part of)
11622989816SDimitry Andric /// a constant that has already been added. This flag is only used to
11722989816SDimitry Andric /// detect bugs.
11822989816SDimitry Andric bool add(llvm::Constant *C, CharUnits Offset, bool AllowOverwrite);
11922989816SDimitry Andric
12022989816SDimitry Andric /// Update or overwrite the bits starting at \p OffsetInBits with \p Bits.
12122989816SDimitry Andric bool addBits(llvm::APInt Bits, uint64_t OffsetInBits, bool AllowOverwrite);
12222989816SDimitry Andric
12322989816SDimitry Andric /// Attempt to condense the value starting at \p Offset to a constant of type
12422989816SDimitry Andric /// \p DesiredTy.
12522989816SDimitry Andric void condense(CharUnits Offset, llvm::Type *DesiredTy);
12622989816SDimitry Andric
12722989816SDimitry Andric /// Produce a constant representing the entire accumulated value, ideally of
12822989816SDimitry Andric /// the specified type. If \p AllowOversized, the constant might be larger
12922989816SDimitry Andric /// than implied by \p DesiredTy (eg, if there is a flexible array member).
13022989816SDimitry Andric /// Otherwise, the constant will be of exactly the same size as \p DesiredTy
13122989816SDimitry Andric /// even if we can't represent it as that type.
build(llvm::Type * DesiredTy,bool AllowOversized) const13222989816SDimitry Andric llvm::Constant *build(llvm::Type *DesiredTy, bool AllowOversized) const {
13322989816SDimitry Andric return buildFrom(CGM, Elems, Offsets, CharUnits::Zero(), Size,
13422989816SDimitry Andric NaturalLayout, DesiredTy, AllowOversized);
13522989816SDimitry Andric }
13622989816SDimitry Andric };
13722989816SDimitry Andric
13822989816SDimitry Andric template<typename Container, typename Range = std::initializer_list<
13922989816SDimitry Andric typename Container::value_type>>
replace(Container & C,size_t BeginOff,size_t EndOff,Range Vals)14022989816SDimitry Andric static void replace(Container &C, size_t BeginOff, size_t EndOff, Range Vals) {
14122989816SDimitry Andric assert(BeginOff <= EndOff && "invalid replacement range");
14222989816SDimitry Andric llvm::replace(C, C.begin() + BeginOff, C.begin() + EndOff, Vals);
14322989816SDimitry Andric }
14422989816SDimitry Andric
add(llvm::Constant * C,CharUnits Offset,bool AllowOverwrite)14522989816SDimitry Andric bool ConstantAggregateBuilder::add(llvm::Constant *C, CharUnits Offset,
14622989816SDimitry Andric bool AllowOverwrite) {
14722989816SDimitry Andric // Common case: appending to a layout.
14822989816SDimitry Andric if (Offset >= Size) {
14922989816SDimitry Andric CharUnits Align = getAlignment(C);
15022989816SDimitry Andric CharUnits AlignedSize = Size.alignTo(Align);
15122989816SDimitry Andric if (AlignedSize > Offset || Offset.alignTo(Align) != Offset)
15222989816SDimitry Andric NaturalLayout = false;
15322989816SDimitry Andric else if (AlignedSize < Offset) {
15422989816SDimitry Andric Elems.push_back(getPadding(Offset - Size));
15522989816SDimitry Andric Offsets.push_back(Size);
15622989816SDimitry Andric }
15722989816SDimitry Andric Elems.push_back(C);
15822989816SDimitry Andric Offsets.push_back(Offset);
15922989816SDimitry Andric Size = Offset + getSize(C);
16022989816SDimitry Andric return true;
16122989816SDimitry Andric }
16222989816SDimitry Andric
16322989816SDimitry Andric // Uncommon case: constant overlaps what we've already created.
164e3b55780SDimitry Andric std::optional<size_t> FirstElemToReplace = splitAt(Offset);
16522989816SDimitry Andric if (!FirstElemToReplace)
16622989816SDimitry Andric return false;
16722989816SDimitry Andric
16822989816SDimitry Andric CharUnits CSize = getSize(C);
169e3b55780SDimitry Andric std::optional<size_t> LastElemToReplace = splitAt(Offset + CSize);
17022989816SDimitry Andric if (!LastElemToReplace)
17122989816SDimitry Andric return false;
17222989816SDimitry Andric
17322989816SDimitry Andric assert((FirstElemToReplace == LastElemToReplace || AllowOverwrite) &&
17422989816SDimitry Andric "unexpectedly overwriting field");
17522989816SDimitry Andric
17622989816SDimitry Andric replace(Elems, *FirstElemToReplace, *LastElemToReplace, {C});
17722989816SDimitry Andric replace(Offsets, *FirstElemToReplace, *LastElemToReplace, {Offset});
17822989816SDimitry Andric Size = std::max(Size, Offset + CSize);
17922989816SDimitry Andric NaturalLayout = false;
18022989816SDimitry Andric return true;
18122989816SDimitry Andric }
18222989816SDimitry Andric
addBits(llvm::APInt Bits,uint64_t OffsetInBits,bool AllowOverwrite)18322989816SDimitry Andric bool ConstantAggregateBuilder::addBits(llvm::APInt Bits, uint64_t OffsetInBits,
18422989816SDimitry Andric bool AllowOverwrite) {
18522989816SDimitry Andric const ASTContext &Context = CGM.getContext();
18622989816SDimitry Andric const uint64_t CharWidth = CGM.getContext().getCharWidth();
18722989816SDimitry Andric
18822989816SDimitry Andric // Offset of where we want the first bit to go within the bits of the
18922989816SDimitry Andric // current char.
19022989816SDimitry Andric unsigned OffsetWithinChar = OffsetInBits % CharWidth;
19122989816SDimitry Andric
19222989816SDimitry Andric // We split bit-fields up into individual bytes. Walk over the bytes and
19322989816SDimitry Andric // update them.
19422989816SDimitry Andric for (CharUnits OffsetInChars =
19522989816SDimitry Andric Context.toCharUnitsFromBits(OffsetInBits - OffsetWithinChar);
19622989816SDimitry Andric /**/; ++OffsetInChars) {
19722989816SDimitry Andric // Number of bits we want to fill in this char.
19822989816SDimitry Andric unsigned WantedBits =
19922989816SDimitry Andric std::min((uint64_t)Bits.getBitWidth(), CharWidth - OffsetWithinChar);
20022989816SDimitry Andric
20122989816SDimitry Andric // Get a char containing the bits we want in the right places. The other
20222989816SDimitry Andric // bits have unspecified values.
20322989816SDimitry Andric llvm::APInt BitsThisChar = Bits;
20422989816SDimitry Andric if (BitsThisChar.getBitWidth() < CharWidth)
20522989816SDimitry Andric BitsThisChar = BitsThisChar.zext(CharWidth);
20622989816SDimitry Andric if (CGM.getDataLayout().isBigEndian()) {
20722989816SDimitry Andric // Figure out how much to shift by. We may need to left-shift if we have
20822989816SDimitry Andric // less than one byte of Bits left.
20922989816SDimitry Andric int Shift = Bits.getBitWidth() - CharWidth + OffsetWithinChar;
21022989816SDimitry Andric if (Shift > 0)
21122989816SDimitry Andric BitsThisChar.lshrInPlace(Shift);
21222989816SDimitry Andric else if (Shift < 0)
21322989816SDimitry Andric BitsThisChar = BitsThisChar.shl(-Shift);
21422989816SDimitry Andric } else {
21522989816SDimitry Andric BitsThisChar = BitsThisChar.shl(OffsetWithinChar);
21622989816SDimitry Andric }
21722989816SDimitry Andric if (BitsThisChar.getBitWidth() > CharWidth)
21822989816SDimitry Andric BitsThisChar = BitsThisChar.trunc(CharWidth);
21922989816SDimitry Andric
22022989816SDimitry Andric if (WantedBits == CharWidth) {
22122989816SDimitry Andric // Got a full byte: just add it directly.
22222989816SDimitry Andric add(llvm::ConstantInt::get(CGM.getLLVMContext(), BitsThisChar),
22322989816SDimitry Andric OffsetInChars, AllowOverwrite);
22422989816SDimitry Andric } else {
22522989816SDimitry Andric // Partial byte: update the existing integer if there is one. If we
22622989816SDimitry Andric // can't split out a 1-CharUnit range to update, then we can't add
22722989816SDimitry Andric // these bits and fail the entire constant emission.
228e3b55780SDimitry Andric std::optional<size_t> FirstElemToUpdate = splitAt(OffsetInChars);
22922989816SDimitry Andric if (!FirstElemToUpdate)
23022989816SDimitry Andric return false;
231e3b55780SDimitry Andric std::optional<size_t> LastElemToUpdate =
23222989816SDimitry Andric splitAt(OffsetInChars + CharUnits::One());
23322989816SDimitry Andric if (!LastElemToUpdate)
23422989816SDimitry Andric return false;
23522989816SDimitry Andric assert(*LastElemToUpdate - *FirstElemToUpdate < 2 &&
23622989816SDimitry Andric "should have at most one element covering one byte");
23722989816SDimitry Andric
23822989816SDimitry Andric // Figure out which bits we want and discard the rest.
23922989816SDimitry Andric llvm::APInt UpdateMask(CharWidth, 0);
24022989816SDimitry Andric if (CGM.getDataLayout().isBigEndian())
24122989816SDimitry Andric UpdateMask.setBits(CharWidth - OffsetWithinChar - WantedBits,
24222989816SDimitry Andric CharWidth - OffsetWithinChar);
24322989816SDimitry Andric else
24422989816SDimitry Andric UpdateMask.setBits(OffsetWithinChar, OffsetWithinChar + WantedBits);
24522989816SDimitry Andric BitsThisChar &= UpdateMask;
24622989816SDimitry Andric
24722989816SDimitry Andric if (*FirstElemToUpdate == *LastElemToUpdate ||
24822989816SDimitry Andric Elems[*FirstElemToUpdate]->isNullValue() ||
24922989816SDimitry Andric isa<llvm::UndefValue>(Elems[*FirstElemToUpdate])) {
25022989816SDimitry Andric // All existing bits are either zero or undef.
25122989816SDimitry Andric add(llvm::ConstantInt::get(CGM.getLLVMContext(), BitsThisChar),
25222989816SDimitry Andric OffsetInChars, /*AllowOverwrite*/ true);
25322989816SDimitry Andric } else {
25422989816SDimitry Andric llvm::Constant *&ToUpdate = Elems[*FirstElemToUpdate];
25522989816SDimitry Andric // In order to perform a partial update, we need the existing bitwise
25622989816SDimitry Andric // value, which we can only extract for a constant int.
25722989816SDimitry Andric auto *CI = dyn_cast<llvm::ConstantInt>(ToUpdate);
25822989816SDimitry Andric if (!CI)
25922989816SDimitry Andric return false;
26022989816SDimitry Andric // Because this is a 1-CharUnit range, the constant occupying it must
26122989816SDimitry Andric // be exactly one CharUnit wide.
26222989816SDimitry Andric assert(CI->getBitWidth() == CharWidth && "splitAt failed");
26322989816SDimitry Andric assert((!(CI->getValue() & UpdateMask) || AllowOverwrite) &&
26422989816SDimitry Andric "unexpectedly overwriting bitfield");
26522989816SDimitry Andric BitsThisChar |= (CI->getValue() & ~UpdateMask);
26622989816SDimitry Andric ToUpdate = llvm::ConstantInt::get(CGM.getLLVMContext(), BitsThisChar);
26722989816SDimitry Andric }
26822989816SDimitry Andric }
26922989816SDimitry Andric
27022989816SDimitry Andric // Stop if we've added all the bits.
27122989816SDimitry Andric if (WantedBits == Bits.getBitWidth())
27222989816SDimitry Andric break;
27322989816SDimitry Andric
27422989816SDimitry Andric // Remove the consumed bits from Bits.
27522989816SDimitry Andric if (!CGM.getDataLayout().isBigEndian())
27622989816SDimitry Andric Bits.lshrInPlace(WantedBits);
27722989816SDimitry Andric Bits = Bits.trunc(Bits.getBitWidth() - WantedBits);
27822989816SDimitry Andric
27922989816SDimitry Andric // The remanining bits go at the start of the following bytes.
28022989816SDimitry Andric OffsetWithinChar = 0;
28122989816SDimitry Andric }
28222989816SDimitry Andric
28322989816SDimitry Andric return true;
28422989816SDimitry Andric }
28522989816SDimitry Andric
28622989816SDimitry Andric /// Returns a position within Elems and Offsets such that all elements
28722989816SDimitry Andric /// before the returned index end before Pos and all elements at or after
28822989816SDimitry Andric /// the returned index begin at or after Pos. Splits elements as necessary
289e3b55780SDimitry Andric /// to ensure this. Returns std::nullopt if we find something we can't split.
splitAt(CharUnits Pos)290e3b55780SDimitry Andric std::optional<size_t> ConstantAggregateBuilder::splitAt(CharUnits Pos) {
29122989816SDimitry Andric if (Pos >= Size)
29222989816SDimitry Andric return Offsets.size();
29322989816SDimitry Andric
29422989816SDimitry Andric while (true) {
29522989816SDimitry Andric auto FirstAfterPos = llvm::upper_bound(Offsets, Pos);
29622989816SDimitry Andric if (FirstAfterPos == Offsets.begin())
29722989816SDimitry Andric return 0;
29822989816SDimitry Andric
29922989816SDimitry Andric // If we already have an element starting at Pos, we're done.
30022989816SDimitry Andric size_t LastAtOrBeforePosIndex = FirstAfterPos - Offsets.begin() - 1;
30122989816SDimitry Andric if (Offsets[LastAtOrBeforePosIndex] == Pos)
30222989816SDimitry Andric return LastAtOrBeforePosIndex;
30322989816SDimitry Andric
30422989816SDimitry Andric // We found an element starting before Pos. Check for overlap.
30522989816SDimitry Andric if (Offsets[LastAtOrBeforePosIndex] +
30622989816SDimitry Andric getSize(Elems[LastAtOrBeforePosIndex]) <= Pos)
30722989816SDimitry Andric return LastAtOrBeforePosIndex + 1;
30822989816SDimitry Andric
30922989816SDimitry Andric // Try to decompose it into smaller constants.
31022989816SDimitry Andric if (!split(LastAtOrBeforePosIndex, Pos))
311e3b55780SDimitry Andric return std::nullopt;
31222989816SDimitry Andric }
31322989816SDimitry Andric }
31422989816SDimitry Andric
31522989816SDimitry Andric /// Split the constant at index Index, if possible. Return true if we did.
31622989816SDimitry Andric /// Hint indicates the location at which we'd like to split, but may be
31722989816SDimitry Andric /// ignored.
split(size_t Index,CharUnits Hint)31822989816SDimitry Andric bool ConstantAggregateBuilder::split(size_t Index, CharUnits Hint) {
31922989816SDimitry Andric NaturalLayout = false;
32022989816SDimitry Andric llvm::Constant *C = Elems[Index];
32122989816SDimitry Andric CharUnits Offset = Offsets[Index];
32222989816SDimitry Andric
32322989816SDimitry Andric if (auto *CA = dyn_cast<llvm::ConstantAggregate>(C)) {
324cfca06d7SDimitry Andric // Expand the sequence into its contained elements.
325cfca06d7SDimitry Andric // FIXME: This assumes vector elements are byte-sized.
32622989816SDimitry Andric replace(Elems, Index, Index + 1,
32722989816SDimitry Andric llvm::map_range(llvm::seq(0u, CA->getNumOperands()),
32822989816SDimitry Andric [&](unsigned Op) { return CA->getOperand(Op); }));
329cfca06d7SDimitry Andric if (isa<llvm::ArrayType>(CA->getType()) ||
330cfca06d7SDimitry Andric isa<llvm::VectorType>(CA->getType())) {
33122989816SDimitry Andric // Array or vector.
332cfca06d7SDimitry Andric llvm::Type *ElemTy =
333cfca06d7SDimitry Andric llvm::GetElementPtrInst::getTypeAtIndex(CA->getType(), (uint64_t)0);
334cfca06d7SDimitry Andric CharUnits ElemSize = getSize(ElemTy);
33522989816SDimitry Andric replace(
33622989816SDimitry Andric Offsets, Index, Index + 1,
33722989816SDimitry Andric llvm::map_range(llvm::seq(0u, CA->getNumOperands()),
33822989816SDimitry Andric [&](unsigned Op) { return Offset + Op * ElemSize; }));
33922989816SDimitry Andric } else {
34022989816SDimitry Andric // Must be a struct.
34122989816SDimitry Andric auto *ST = cast<llvm::StructType>(CA->getType());
34222989816SDimitry Andric const llvm::StructLayout *Layout =
34322989816SDimitry Andric CGM.getDataLayout().getStructLayout(ST);
34422989816SDimitry Andric replace(Offsets, Index, Index + 1,
34522989816SDimitry Andric llvm::map_range(
34622989816SDimitry Andric llvm::seq(0u, CA->getNumOperands()), [&](unsigned Op) {
34722989816SDimitry Andric return Offset + CharUnits::fromQuantity(
34822989816SDimitry Andric Layout->getElementOffset(Op));
34922989816SDimitry Andric }));
35022989816SDimitry Andric }
35122989816SDimitry Andric return true;
35222989816SDimitry Andric }
35322989816SDimitry Andric
35422989816SDimitry Andric if (auto *CDS = dyn_cast<llvm::ConstantDataSequential>(C)) {
355cfca06d7SDimitry Andric // Expand the sequence into its contained elements.
356cfca06d7SDimitry Andric // FIXME: This assumes vector elements are byte-sized.
35722989816SDimitry Andric // FIXME: If possible, split into two ConstantDataSequentials at Hint.
35822989816SDimitry Andric CharUnits ElemSize = getSize(CDS->getElementType());
35922989816SDimitry Andric replace(Elems, Index, Index + 1,
36022989816SDimitry Andric llvm::map_range(llvm::seq(0u, CDS->getNumElements()),
36122989816SDimitry Andric [&](unsigned Elem) {
36222989816SDimitry Andric return CDS->getElementAsConstant(Elem);
36322989816SDimitry Andric }));
36422989816SDimitry Andric replace(Offsets, Index, Index + 1,
36522989816SDimitry Andric llvm::map_range(
36622989816SDimitry Andric llvm::seq(0u, CDS->getNumElements()),
36722989816SDimitry Andric [&](unsigned Elem) { return Offset + Elem * ElemSize; }));
36822989816SDimitry Andric return true;
36922989816SDimitry Andric }
37022989816SDimitry Andric
37122989816SDimitry Andric if (isa<llvm::ConstantAggregateZero>(C)) {
372cfca06d7SDimitry Andric // Split into two zeros at the hinted offset.
37322989816SDimitry Andric CharUnits ElemSize = getSize(C);
37422989816SDimitry Andric assert(Hint > Offset && Hint < Offset + ElemSize && "nothing to split");
37522989816SDimitry Andric replace(Elems, Index, Index + 1,
37622989816SDimitry Andric {getZeroes(Hint - Offset), getZeroes(Offset + ElemSize - Hint)});
37722989816SDimitry Andric replace(Offsets, Index, Index + 1, {Offset, Hint});
37822989816SDimitry Andric return true;
37922989816SDimitry Andric }
38022989816SDimitry Andric
38122989816SDimitry Andric if (isa<llvm::UndefValue>(C)) {
382cfca06d7SDimitry Andric // Drop undef; it doesn't contribute to the final layout.
38322989816SDimitry Andric replace(Elems, Index, Index + 1, {});
38422989816SDimitry Andric replace(Offsets, Index, Index + 1, {});
38522989816SDimitry Andric return true;
38622989816SDimitry Andric }
38722989816SDimitry Andric
38822989816SDimitry Andric // FIXME: We could split a ConstantInt if the need ever arose.
38922989816SDimitry Andric // We don't need to do this to handle bit-fields because we always eagerly
39022989816SDimitry Andric // split them into 1-byte chunks.
39122989816SDimitry Andric
39222989816SDimitry Andric return false;
39322989816SDimitry Andric }
39422989816SDimitry Andric
39522989816SDimitry Andric static llvm::Constant *
39622989816SDimitry Andric EmitArrayConstant(CodeGenModule &CGM, llvm::ArrayType *DesiredType,
397ac9a064cSDimitry Andric llvm::Type *CommonElementType, uint64_t ArrayBound,
39822989816SDimitry Andric SmallVectorImpl<llvm::Constant *> &Elements,
39922989816SDimitry Andric llvm::Constant *Filler);
40022989816SDimitry Andric
buildFrom(CodeGenModule & CGM,ArrayRef<llvm::Constant * > Elems,ArrayRef<CharUnits> Offsets,CharUnits StartOffset,CharUnits Size,bool NaturalLayout,llvm::Type * DesiredTy,bool AllowOversized)40122989816SDimitry Andric llvm::Constant *ConstantAggregateBuilder::buildFrom(
40222989816SDimitry Andric CodeGenModule &CGM, ArrayRef<llvm::Constant *> Elems,
40322989816SDimitry Andric ArrayRef<CharUnits> Offsets, CharUnits StartOffset, CharUnits Size,
40422989816SDimitry Andric bool NaturalLayout, llvm::Type *DesiredTy, bool AllowOversized) {
40522989816SDimitry Andric ConstantAggregateBuilderUtils Utils(CGM);
40622989816SDimitry Andric
40722989816SDimitry Andric if (Elems.empty())
40822989816SDimitry Andric return llvm::UndefValue::get(DesiredTy);
40922989816SDimitry Andric
41022989816SDimitry Andric auto Offset = [&](size_t I) { return Offsets[I] - StartOffset; };
41122989816SDimitry Andric
41222989816SDimitry Andric // If we want an array type, see if all the elements are the same type and
41322989816SDimitry Andric // appropriately spaced.
41422989816SDimitry Andric if (llvm::ArrayType *ATy = dyn_cast<llvm::ArrayType>(DesiredTy)) {
41522989816SDimitry Andric assert(!AllowOversized && "oversized array emission not supported");
41622989816SDimitry Andric
41722989816SDimitry Andric bool CanEmitArray = true;
41822989816SDimitry Andric llvm::Type *CommonType = Elems[0]->getType();
41922989816SDimitry Andric llvm::Constant *Filler = llvm::Constant::getNullValue(CommonType);
42022989816SDimitry Andric CharUnits ElemSize = Utils.getSize(ATy->getElementType());
42122989816SDimitry Andric SmallVector<llvm::Constant*, 32> ArrayElements;
42222989816SDimitry Andric for (size_t I = 0; I != Elems.size(); ++I) {
42322989816SDimitry Andric // Skip zeroes; we'll use a zero value as our array filler.
42422989816SDimitry Andric if (Elems[I]->isNullValue())
42522989816SDimitry Andric continue;
42622989816SDimitry Andric
42722989816SDimitry Andric // All remaining elements must be the same type.
42822989816SDimitry Andric if (Elems[I]->getType() != CommonType ||
42922989816SDimitry Andric Offset(I) % ElemSize != 0) {
43022989816SDimitry Andric CanEmitArray = false;
43122989816SDimitry Andric break;
43222989816SDimitry Andric }
43322989816SDimitry Andric ArrayElements.resize(Offset(I) / ElemSize + 1, Filler);
43422989816SDimitry Andric ArrayElements.back() = Elems[I];
43522989816SDimitry Andric }
43622989816SDimitry Andric
43722989816SDimitry Andric if (CanEmitArray) {
43822989816SDimitry Andric return EmitArrayConstant(CGM, ATy, CommonType, ATy->getNumElements(),
43922989816SDimitry Andric ArrayElements, Filler);
44022989816SDimitry Andric }
44122989816SDimitry Andric
44222989816SDimitry Andric // Can't emit as an array, carry on to emit as a struct.
44322989816SDimitry Andric }
44422989816SDimitry Andric
445145449b1SDimitry Andric // The size of the constant we plan to generate. This is usually just
446145449b1SDimitry Andric // the size of the initialized type, but in AllowOversized mode (i.e.
447145449b1SDimitry Andric // flexible array init), it can be larger.
44822989816SDimitry Andric CharUnits DesiredSize = Utils.getSize(DesiredTy);
449145449b1SDimitry Andric if (Size > DesiredSize) {
450145449b1SDimitry Andric assert(AllowOversized && "Elems are oversized");
451145449b1SDimitry Andric DesiredSize = Size;
452145449b1SDimitry Andric }
453145449b1SDimitry Andric
454145449b1SDimitry Andric // The natural alignment of an unpacked LLVM struct with the given elements.
45522989816SDimitry Andric CharUnits Align = CharUnits::One();
45622989816SDimitry Andric for (llvm::Constant *C : Elems)
45722989816SDimitry Andric Align = std::max(Align, Utils.getAlignment(C));
458145449b1SDimitry Andric
459145449b1SDimitry Andric // The natural size of an unpacked LLVM struct with the given elements.
46022989816SDimitry Andric CharUnits AlignedSize = Size.alignTo(Align);
46122989816SDimitry Andric
46222989816SDimitry Andric bool Packed = false;
46322989816SDimitry Andric ArrayRef<llvm::Constant*> UnpackedElems = Elems;
46422989816SDimitry Andric llvm::SmallVector<llvm::Constant*, 32> UnpackedElemStorage;
465145449b1SDimitry Andric if (DesiredSize < AlignedSize || DesiredSize.alignTo(Align) != DesiredSize) {
466145449b1SDimitry Andric // The natural layout would be too big; force use of a packed layout.
46722989816SDimitry Andric NaturalLayout = false;
46822989816SDimitry Andric Packed = true;
46922989816SDimitry Andric } else if (DesiredSize > AlignedSize) {
470145449b1SDimitry Andric // The natural layout would be too small. Add padding to fix it. (This
471145449b1SDimitry Andric // is ignored if we choose a packed layout.)
47222989816SDimitry Andric UnpackedElemStorage.assign(Elems.begin(), Elems.end());
47322989816SDimitry Andric UnpackedElemStorage.push_back(Utils.getPadding(DesiredSize - Size));
47422989816SDimitry Andric UnpackedElems = UnpackedElemStorage;
47522989816SDimitry Andric }
47622989816SDimitry Andric
47722989816SDimitry Andric // If we don't have a natural layout, insert padding as necessary.
47822989816SDimitry Andric // As we go, double-check to see if we can actually just emit Elems
47922989816SDimitry Andric // as a non-packed struct and do so opportunistically if possible.
48022989816SDimitry Andric llvm::SmallVector<llvm::Constant*, 32> PackedElems;
48122989816SDimitry Andric if (!NaturalLayout) {
48222989816SDimitry Andric CharUnits SizeSoFar = CharUnits::Zero();
48322989816SDimitry Andric for (size_t I = 0; I != Elems.size(); ++I) {
48422989816SDimitry Andric CharUnits Align = Utils.getAlignment(Elems[I]);
48522989816SDimitry Andric CharUnits NaturalOffset = SizeSoFar.alignTo(Align);
48622989816SDimitry Andric CharUnits DesiredOffset = Offset(I);
48722989816SDimitry Andric assert(DesiredOffset >= SizeSoFar && "elements out of order");
48822989816SDimitry Andric
48922989816SDimitry Andric if (DesiredOffset != NaturalOffset)
49022989816SDimitry Andric Packed = true;
49122989816SDimitry Andric if (DesiredOffset != SizeSoFar)
49222989816SDimitry Andric PackedElems.push_back(Utils.getPadding(DesiredOffset - SizeSoFar));
49322989816SDimitry Andric PackedElems.push_back(Elems[I]);
49422989816SDimitry Andric SizeSoFar = DesiredOffset + Utils.getSize(Elems[I]);
49522989816SDimitry Andric }
49622989816SDimitry Andric // If we're using the packed layout, pad it out to the desired size if
49722989816SDimitry Andric // necessary.
49822989816SDimitry Andric if (Packed) {
499145449b1SDimitry Andric assert(SizeSoFar <= DesiredSize &&
50022989816SDimitry Andric "requested size is too small for contents");
50122989816SDimitry Andric if (SizeSoFar < DesiredSize)
50222989816SDimitry Andric PackedElems.push_back(Utils.getPadding(DesiredSize - SizeSoFar));
50322989816SDimitry Andric }
50422989816SDimitry Andric }
50522989816SDimitry Andric
50622989816SDimitry Andric llvm::StructType *STy = llvm::ConstantStruct::getTypeForElements(
50722989816SDimitry Andric CGM.getLLVMContext(), Packed ? PackedElems : UnpackedElems, Packed);
50822989816SDimitry Andric
50922989816SDimitry Andric // Pick the type to use. If the type is layout identical to the desired
51022989816SDimitry Andric // type then use it, otherwise use whatever the builder produced for us.
51122989816SDimitry Andric if (llvm::StructType *DesiredSTy = dyn_cast<llvm::StructType>(DesiredTy)) {
51222989816SDimitry Andric if (DesiredSTy->isLayoutIdentical(STy))
51322989816SDimitry Andric STy = DesiredSTy;
51422989816SDimitry Andric }
51522989816SDimitry Andric
51622989816SDimitry Andric return llvm::ConstantStruct::get(STy, Packed ? PackedElems : UnpackedElems);
51722989816SDimitry Andric }
51822989816SDimitry Andric
condense(CharUnits Offset,llvm::Type * DesiredTy)51922989816SDimitry Andric void ConstantAggregateBuilder::condense(CharUnits Offset,
52022989816SDimitry Andric llvm::Type *DesiredTy) {
52122989816SDimitry Andric CharUnits Size = getSize(DesiredTy);
52222989816SDimitry Andric
523e3b55780SDimitry Andric std::optional<size_t> FirstElemToReplace = splitAt(Offset);
52422989816SDimitry Andric if (!FirstElemToReplace)
52522989816SDimitry Andric return;
52622989816SDimitry Andric size_t First = *FirstElemToReplace;
52722989816SDimitry Andric
528e3b55780SDimitry Andric std::optional<size_t> LastElemToReplace = splitAt(Offset + Size);
52922989816SDimitry Andric if (!LastElemToReplace)
53022989816SDimitry Andric return;
53122989816SDimitry Andric size_t Last = *LastElemToReplace;
53222989816SDimitry Andric
53322989816SDimitry Andric size_t Length = Last - First;
53422989816SDimitry Andric if (Length == 0)
53522989816SDimitry Andric return;
53622989816SDimitry Andric
53722989816SDimitry Andric if (Length == 1 && Offsets[First] == Offset &&
53822989816SDimitry Andric getSize(Elems[First]) == Size) {
53922989816SDimitry Andric // Re-wrap single element structs if necessary. Otherwise, leave any single
54022989816SDimitry Andric // element constant of the right size alone even if it has the wrong type.
54122989816SDimitry Andric auto *STy = dyn_cast<llvm::StructType>(DesiredTy);
54222989816SDimitry Andric if (STy && STy->getNumElements() == 1 &&
54322989816SDimitry Andric STy->getElementType(0) == Elems[First]->getType())
54422989816SDimitry Andric Elems[First] = llvm::ConstantStruct::get(STy, Elems[First]);
54522989816SDimitry Andric return;
54622989816SDimitry Andric }
54722989816SDimitry Andric
54822989816SDimitry Andric llvm::Constant *Replacement = buildFrom(
549e3b55780SDimitry Andric CGM, ArrayRef(Elems).slice(First, Length),
550e3b55780SDimitry Andric ArrayRef(Offsets).slice(First, Length), Offset, getSize(DesiredTy),
55122989816SDimitry Andric /*known to have natural layout=*/false, DesiredTy, false);
55222989816SDimitry Andric replace(Elems, First, Last, {Replacement});
55322989816SDimitry Andric replace(Offsets, First, Last, {Offset});
55422989816SDimitry Andric }
55522989816SDimitry Andric
55622989816SDimitry Andric //===----------------------------------------------------------------------===//
55722989816SDimitry Andric // ConstStructBuilder
55822989816SDimitry Andric //===----------------------------------------------------------------------===//
55922989816SDimitry Andric
56022989816SDimitry Andric class ConstStructBuilder {
56122989816SDimitry Andric CodeGenModule &CGM;
56222989816SDimitry Andric ConstantEmitter &Emitter;
56322989816SDimitry Andric ConstantAggregateBuilder &Builder;
56422989816SDimitry Andric CharUnits StartOffset;
56522989816SDimitry Andric
56622989816SDimitry Andric public:
56722989816SDimitry Andric static llvm::Constant *BuildStruct(ConstantEmitter &Emitter,
568ac9a064cSDimitry Andric const InitListExpr *ILE,
569ac9a064cSDimitry Andric QualType StructTy);
57022989816SDimitry Andric static llvm::Constant *BuildStruct(ConstantEmitter &Emitter,
57122989816SDimitry Andric const APValue &Value, QualType ValTy);
57222989816SDimitry Andric static bool UpdateStruct(ConstantEmitter &Emitter,
57322989816SDimitry Andric ConstantAggregateBuilder &Const, CharUnits Offset,
574ac9a064cSDimitry Andric const InitListExpr *Updater);
57522989816SDimitry Andric
57622989816SDimitry Andric private:
ConstStructBuilder(ConstantEmitter & Emitter,ConstantAggregateBuilder & Builder,CharUnits StartOffset)57722989816SDimitry Andric ConstStructBuilder(ConstantEmitter &Emitter,
57822989816SDimitry Andric ConstantAggregateBuilder &Builder, CharUnits StartOffset)
57922989816SDimitry Andric : CGM(Emitter.CGM), Emitter(Emitter), Builder(Builder),
58022989816SDimitry Andric StartOffset(StartOffset) {}
58122989816SDimitry Andric
58222989816SDimitry Andric bool AppendField(const FieldDecl *Field, uint64_t FieldOffset,
58322989816SDimitry Andric llvm::Constant *InitExpr, bool AllowOverwrite = false);
58422989816SDimitry Andric
58522989816SDimitry Andric bool AppendBytes(CharUnits FieldOffsetInChars, llvm::Constant *InitCst,
58622989816SDimitry Andric bool AllowOverwrite = false);
58722989816SDimitry Andric
58822989816SDimitry Andric bool AppendBitField(const FieldDecl *Field, uint64_t FieldOffset,
589ac9a064cSDimitry Andric llvm::Constant *InitExpr, bool AllowOverwrite = false);
59022989816SDimitry Andric
591ac9a064cSDimitry Andric bool Build(const InitListExpr *ILE, bool AllowOverwrite);
59222989816SDimitry Andric bool Build(const APValue &Val, const RecordDecl *RD, bool IsPrimaryBase,
59322989816SDimitry Andric const CXXRecordDecl *VTableClass, CharUnits BaseOffset);
59422989816SDimitry Andric llvm::Constant *Finalize(QualType Ty);
59522989816SDimitry Andric };
59622989816SDimitry Andric
AppendField(const FieldDecl * Field,uint64_t FieldOffset,llvm::Constant * InitCst,bool AllowOverwrite)59722989816SDimitry Andric bool ConstStructBuilder::AppendField(
59822989816SDimitry Andric const FieldDecl *Field, uint64_t FieldOffset, llvm::Constant *InitCst,
59922989816SDimitry Andric bool AllowOverwrite) {
60001af97d3SDimitry Andric const ASTContext &Context = CGM.getContext();
60101af97d3SDimitry Andric
60201af97d3SDimitry Andric CharUnits FieldOffsetInChars = Context.toCharUnitsFromBits(FieldOffset);
60301af97d3SDimitry Andric
60422989816SDimitry Andric return AppendBytes(FieldOffsetInChars, InitCst, AllowOverwrite);
605dbe13110SDimitry Andric }
606dbe13110SDimitry Andric
AppendBytes(CharUnits FieldOffsetInChars,llvm::Constant * InitCst,bool AllowOverwrite)60722989816SDimitry Andric bool ConstStructBuilder::AppendBytes(CharUnits FieldOffsetInChars,
60822989816SDimitry Andric llvm::Constant *InitCst,
60922989816SDimitry Andric bool AllowOverwrite) {
61022989816SDimitry Andric return Builder.add(InitCst, StartOffset + FieldOffsetInChars, AllowOverwrite);
61106d4ba38SDimitry Andric }
61206d4ba38SDimitry Andric
AppendBitField(const FieldDecl * Field,uint64_t FieldOffset,llvm::Constant * C,bool AllowOverwrite)613ac9a064cSDimitry Andric bool ConstStructBuilder::AppendBitField(const FieldDecl *Field,
614ac9a064cSDimitry Andric uint64_t FieldOffset, llvm::Constant *C,
61522989816SDimitry Andric bool AllowOverwrite) {
616ac9a064cSDimitry Andric
617ac9a064cSDimitry Andric llvm::ConstantInt *CI = dyn_cast<llvm::ConstantInt>(C);
618ac9a064cSDimitry Andric if (!CI) {
619ac9a064cSDimitry Andric // Constants for long _BitInt types are sometimes split into individual
620ac9a064cSDimitry Andric // bytes. Try to fold these back into an integer constant. If that doesn't
621ac9a064cSDimitry Andric // work out, then we are trying to initialize a bitfield with a non-trivial
622ac9a064cSDimitry Andric // constant, this must require run-time code.
623ac9a064cSDimitry Andric llvm::Type *LoadType =
624ac9a064cSDimitry Andric CGM.getTypes().convertTypeForLoadStore(Field->getType(), C->getType());
625ac9a064cSDimitry Andric llvm::Constant *FoldedConstant = llvm::ConstantFoldLoadFromConst(
626ac9a064cSDimitry Andric C, LoadType, llvm::APInt::getZero(32), CGM.getDataLayout());
627ac9a064cSDimitry Andric CI = dyn_cast_if_present<llvm::ConstantInt>(FoldedConstant);
628ac9a064cSDimitry Andric if (!CI)
629ac9a064cSDimitry Andric return false;
630ac9a064cSDimitry Andric }
631ac9a064cSDimitry Andric
632cfca06d7SDimitry Andric const CGRecordLayout &RL =
633cfca06d7SDimitry Andric CGM.getTypes().getCGRecordLayout(Field->getParent());
634cfca06d7SDimitry Andric const CGBitFieldInfo &Info = RL.getBitFieldInfo(Field);
6354c8b2481SRoman Divacky llvm::APInt FieldValue = CI->getValue();
6364c8b2481SRoman Divacky
6374c8b2481SRoman Divacky // Promote the size of FieldValue if necessary
6384c8b2481SRoman Divacky // FIXME: This should never occur, but currently it can because initializer
6394c8b2481SRoman Divacky // constants are cast to bool, and because clang is not enforcing bitfield
6404c8b2481SRoman Divacky // width limits.
641cfca06d7SDimitry Andric if (Info.Size > FieldValue.getBitWidth())
642cfca06d7SDimitry Andric FieldValue = FieldValue.zext(Info.Size);
6434c8b2481SRoman Divacky
6444c8b2481SRoman Divacky // Truncate the size of FieldValue to the bit field size.
645cfca06d7SDimitry Andric if (Info.Size < FieldValue.getBitWidth())
646cfca06d7SDimitry Andric FieldValue = FieldValue.trunc(Info.Size);
6474c8b2481SRoman Divacky
64822989816SDimitry Andric return Builder.addBits(FieldValue,
64922989816SDimitry Andric CGM.getContext().toBits(StartOffset) + FieldOffset,
65022989816SDimitry Andric AllowOverwrite);
65122989816SDimitry Andric }
6524c8b2481SRoman Divacky
EmitDesignatedInitUpdater(ConstantEmitter & Emitter,ConstantAggregateBuilder & Const,CharUnits Offset,QualType Type,const InitListExpr * Updater)65322989816SDimitry Andric static bool EmitDesignatedInitUpdater(ConstantEmitter &Emitter,
65422989816SDimitry Andric ConstantAggregateBuilder &Const,
65522989816SDimitry Andric CharUnits Offset, QualType Type,
656ac9a064cSDimitry Andric const InitListExpr *Updater) {
65722989816SDimitry Andric if (Type->isRecordType())
65822989816SDimitry Andric return ConstStructBuilder::UpdateStruct(Emitter, Const, Offset, Updater);
6594c8b2481SRoman Divacky
66022989816SDimitry Andric auto CAT = Emitter.CGM.getContext().getAsConstantArrayType(Type);
66122989816SDimitry Andric if (!CAT)
66222989816SDimitry Andric return false;
66322989816SDimitry Andric QualType ElemType = CAT->getElementType();
66422989816SDimitry Andric CharUnits ElemSize = Emitter.CGM.getContext().getTypeSizeInChars(ElemType);
66522989816SDimitry Andric llvm::Type *ElemTy = Emitter.CGM.getTypes().ConvertTypeForMem(ElemType);
6664c8b2481SRoman Divacky
66722989816SDimitry Andric llvm::Constant *FillC = nullptr;
668ac9a064cSDimitry Andric if (const Expr *Filler = Updater->getArrayFiller()) {
66922989816SDimitry Andric if (!isa<NoInitExpr>(Filler)) {
67022989816SDimitry Andric FillC = Emitter.tryEmitAbstractForMemory(Filler, ElemType);
67122989816SDimitry Andric if (!FillC)
67222989816SDimitry Andric return false;
67322989816SDimitry Andric }
67422989816SDimitry Andric }
6754c8b2481SRoman Divacky
67622989816SDimitry Andric unsigned NumElementsToUpdate =
677ac9a064cSDimitry Andric FillC ? CAT->getZExtSize() : Updater->getNumInits();
67822989816SDimitry Andric for (unsigned I = 0; I != NumElementsToUpdate; ++I, Offset += ElemSize) {
679ac9a064cSDimitry Andric const Expr *Init = nullptr;
68022989816SDimitry Andric if (I < Updater->getNumInits())
68122989816SDimitry Andric Init = Updater->getInit(I);
6824c8b2481SRoman Divacky
68322989816SDimitry Andric if (!Init && FillC) {
68422989816SDimitry Andric if (!Const.add(FillC, Offset, true))
68522989816SDimitry Andric return false;
68622989816SDimitry Andric } else if (!Init || isa<NoInitExpr>(Init)) {
68722989816SDimitry Andric continue;
688ac9a064cSDimitry Andric } else if (const auto *ChildILE = dyn_cast<InitListExpr>(Init)) {
68922989816SDimitry Andric if (!EmitDesignatedInitUpdater(Emitter, Const, Offset, ElemType,
69022989816SDimitry Andric ChildILE))
69122989816SDimitry Andric return false;
69222989816SDimitry Andric // Attempt to reduce the array element to a single constant if necessary.
69322989816SDimitry Andric Const.condense(Offset, ElemTy);
6944c8b2481SRoman Divacky } else {
69522989816SDimitry Andric llvm::Constant *Val = Emitter.tryEmitPrivateForMemory(Init, ElemType);
69622989816SDimitry Andric if (!Const.add(Val, Offset, true))
69722989816SDimitry Andric return false;
6984c8b2481SRoman Divacky }
6994c8b2481SRoman Divacky }
7004c8b2481SRoman Divacky
70122989816SDimitry Andric return true;
7024c8b2481SRoman Divacky }
7034c8b2481SRoman Divacky
Build(const InitListExpr * ILE,bool AllowOverwrite)704ac9a064cSDimitry Andric bool ConstStructBuilder::Build(const InitListExpr *ILE, bool AllowOverwrite) {
705519fc96cSDimitry Andric RecordDecl *RD = ILE->getType()->castAs<RecordType>()->getDecl();
7064c8b2481SRoman Divacky const ASTRecordLayout &Layout = CGM.getContext().getASTRecordLayout(RD);
7074c8b2481SRoman Divacky
70822989816SDimitry Andric unsigned FieldNo = -1;
7094c8b2481SRoman Divacky unsigned ElementNo = 0;
71001af97d3SDimitry Andric
7112b6b257fSDimitry Andric // Bail out if we have base classes. We could support these, but they only
7122b6b257fSDimitry Andric // arise in C++1z where we will have already constant folded most interesting
7132b6b257fSDimitry Andric // cases. FIXME: There are still a few more cases we can handle this way.
7142b6b257fSDimitry Andric if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD))
7152b6b257fSDimitry Andric if (CXXRD->getNumBases())
7162b6b257fSDimitry Andric return false;
7172b6b257fSDimitry Andric
71822989816SDimitry Andric for (FieldDecl *Field : RD->fields()) {
71922989816SDimitry Andric ++FieldNo;
72022989816SDimitry Andric
7210883ccd9SRoman Divacky // If this is a union, skip all the fields that aren't being initialized.
72222989816SDimitry Andric if (RD->isUnion() &&
72322989816SDimitry Andric !declaresSameEntity(ILE->getInitializedFieldInUnion(), Field))
7244c8b2481SRoman Divacky continue;
7254c8b2481SRoman Divacky
726145449b1SDimitry Andric // Don't emit anonymous bitfields.
727ac9a064cSDimitry Andric if (Field->isUnnamedBitField())
7284c8b2481SRoman Divacky continue;
7294c8b2481SRoman Divacky
7300883ccd9SRoman Divacky // Get the initializer. A struct can include fields without initializers,
7310883ccd9SRoman Divacky // we just use explicit null values for them.
732ac9a064cSDimitry Andric const Expr *Init = nullptr;
7330883ccd9SRoman Divacky if (ElementNo < ILE->getNumInits())
73422989816SDimitry Andric Init = ILE->getInit(ElementNo++);
735ac9a064cSDimitry Andric if (isa_and_nonnull<NoInitExpr>(Init))
73622989816SDimitry Andric continue;
7370883ccd9SRoman Divacky
738145449b1SDimitry Andric // Zero-sized fields are not emitted, but their initializers may still
739145449b1SDimitry Andric // prevent emission of this struct as a constant.
740ac9a064cSDimitry Andric if (isEmptyFieldForLayout(CGM.getContext(), Field)) {
741145449b1SDimitry Andric if (Init->HasSideEffects(CGM.getContext()))
742145449b1SDimitry Andric return false;
743145449b1SDimitry Andric continue;
744145449b1SDimitry Andric }
745145449b1SDimitry Andric
74622989816SDimitry Andric // When emitting a DesignatedInitUpdateExpr, a nested InitListExpr
74722989816SDimitry Andric // represents additional overwriting of our current constant value, and not
74822989816SDimitry Andric // a new constant to emit independently.
74922989816SDimitry Andric if (AllowOverwrite &&
75022989816SDimitry Andric (Field->getType()->isArrayType() || Field->getType()->isRecordType())) {
75122989816SDimitry Andric if (auto *SubILE = dyn_cast<InitListExpr>(Init)) {
75222989816SDimitry Andric CharUnits Offset = CGM.getContext().toCharUnitsFromBits(
75322989816SDimitry Andric Layout.getFieldOffset(FieldNo));
75422989816SDimitry Andric if (!EmitDesignatedInitUpdater(Emitter, Builder, StartOffset + Offset,
75522989816SDimitry Andric Field->getType(), SubILE))
75622989816SDimitry Andric return false;
75722989816SDimitry Andric // If we split apart the field's value, try to collapse it down to a
75822989816SDimitry Andric // single value now.
75922989816SDimitry Andric Builder.condense(StartOffset + Offset,
76022989816SDimitry Andric CGM.getTypes().ConvertTypeForMem(Field->getType()));
76122989816SDimitry Andric continue;
76222989816SDimitry Andric }
76322989816SDimitry Andric }
76422989816SDimitry Andric
76522989816SDimitry Andric llvm::Constant *EltInit =
76622989816SDimitry Andric Init ? Emitter.tryEmitPrivateForMemory(Init, Field->getType())
76722989816SDimitry Andric : Emitter.emitNullForMemory(Field->getType());
7683d1dcd9bSDimitry Andric if (!EltInit)
7693d1dcd9bSDimitry Andric return false;
7703d1dcd9bSDimitry Andric
7710883ccd9SRoman Divacky if (!Field->isBitField()) {
7720883ccd9SRoman Divacky // Handle non-bitfield members.
77322989816SDimitry Andric if (!AppendField(Field, Layout.getFieldOffset(FieldNo), EltInit,
77422989816SDimitry Andric AllowOverwrite))
77522989816SDimitry Andric return false;
77622989816SDimitry Andric // After emitting a non-empty field with [[no_unique_address]], we may
77722989816SDimitry Andric // need to overwrite its tail padding.
77822989816SDimitry Andric if (Field->hasAttr<NoUniqueAddressAttr>())
77922989816SDimitry Andric AllowOverwrite = true;
7804c8b2481SRoman Divacky } else {
7810883ccd9SRoman Divacky // Otherwise we have a bitfield.
782ac9a064cSDimitry Andric if (!AppendBitField(Field, Layout.getFieldOffset(FieldNo), EltInit,
78322989816SDimitry Andric AllowOverwrite))
78422989816SDimitry Andric return false;
7854c8b2481SRoman Divacky }
7864c8b2481SRoman Divacky }
7874c8b2481SRoman Divacky
788dbe13110SDimitry Andric return true;
789dbe13110SDimitry Andric }
790dbe13110SDimitry Andric
791dbe13110SDimitry Andric namespace {
792dbe13110SDimitry Andric struct BaseInfo {
BaseInfo__anon4cd729e60111::__anon4cd729e60811::BaseInfo793dbe13110SDimitry Andric BaseInfo(const CXXRecordDecl *Decl, CharUnits Offset, unsigned Index)
794dbe13110SDimitry Andric : Decl(Decl), Offset(Offset), Index(Index) {
795dbe13110SDimitry Andric }
796dbe13110SDimitry Andric
797dbe13110SDimitry Andric const CXXRecordDecl *Decl;
798dbe13110SDimitry Andric CharUnits Offset;
799dbe13110SDimitry Andric unsigned Index;
800dbe13110SDimitry Andric
operator <__anon4cd729e60111::__anon4cd729e60811::BaseInfo801dbe13110SDimitry Andric bool operator<(const BaseInfo &O) const { return Offset < O.Offset; }
802dbe13110SDimitry Andric };
803dbe13110SDimitry Andric }
804dbe13110SDimitry Andric
Build(const APValue & Val,const RecordDecl * RD,bool IsPrimaryBase,const CXXRecordDecl * VTableClass,CharUnits Offset)805461a67faSDimitry Andric bool ConstStructBuilder::Build(const APValue &Val, const RecordDecl *RD,
806bfef3995SDimitry Andric bool IsPrimaryBase,
807dbe13110SDimitry Andric const CXXRecordDecl *VTableClass,
808dbe13110SDimitry Andric CharUnits Offset) {
809dbe13110SDimitry Andric const ASTRecordLayout &Layout = CGM.getContext().getASTRecordLayout(RD);
810dbe13110SDimitry Andric
811dbe13110SDimitry Andric if (const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD)) {
812dbe13110SDimitry Andric // Add a vtable pointer, if we need one and it hasn't already been added.
813cfca06d7SDimitry Andric if (Layout.hasOwnVFPtr()) {
814bfef3995SDimitry Andric llvm::Constant *VTableAddressPoint =
815ac9a064cSDimitry Andric CGM.getCXXABI().getVTableAddressPoint(BaseSubobject(CD, Offset),
816ac9a064cSDimitry Andric VTableClass);
817ac9a064cSDimitry Andric if (auto Authentication = CGM.getVTablePointerAuthentication(CD)) {
818ac9a064cSDimitry Andric VTableAddressPoint = Emitter.tryEmitConstantSignedPointer(
819ac9a064cSDimitry Andric VTableAddressPoint, *Authentication);
820ac9a064cSDimitry Andric if (!VTableAddressPoint)
821ac9a064cSDimitry Andric return false;
822ac9a064cSDimitry Andric }
82322989816SDimitry Andric if (!AppendBytes(Offset, VTableAddressPoint))
82422989816SDimitry Andric return false;
825bfef3995SDimitry Andric }
826dbe13110SDimitry Andric
827dbe13110SDimitry Andric // Accumulate and sort bases, in order to visit them in address order, which
828dbe13110SDimitry Andric // may not be the same as declaration order.
829809500fcSDimitry Andric SmallVector<BaseInfo, 8> Bases;
830dbe13110SDimitry Andric Bases.reserve(CD->getNumBases());
831dbe13110SDimitry Andric unsigned BaseNo = 0;
832dbe13110SDimitry Andric for (CXXRecordDecl::base_class_const_iterator Base = CD->bases_begin(),
833dbe13110SDimitry Andric BaseEnd = CD->bases_end(); Base != BaseEnd; ++Base, ++BaseNo) {
834dbe13110SDimitry Andric assert(!Base->isVirtual() && "should not have virtual bases here");
835dbe13110SDimitry Andric const CXXRecordDecl *BD = Base->getType()->getAsCXXRecordDecl();
836dbe13110SDimitry Andric CharUnits BaseOffset = Layout.getBaseClassOffset(BD);
837dbe13110SDimitry Andric Bases.push_back(BaseInfo(BD, BaseOffset, BaseNo));
838dbe13110SDimitry Andric }
83922989816SDimitry Andric llvm::stable_sort(Bases);
840dbe13110SDimitry Andric
841dbe13110SDimitry Andric for (unsigned I = 0, N = Bases.size(); I != N; ++I) {
842dbe13110SDimitry Andric BaseInfo &Base = Bases[I];
843dbe13110SDimitry Andric
844dbe13110SDimitry Andric bool IsPrimaryBase = Layout.getPrimaryBase() == Base.Decl;
845dbe13110SDimitry Andric Build(Val.getStructBase(Base.Index), Base.Decl, IsPrimaryBase,
846bfef3995SDimitry Andric VTableClass, Offset + Base.Offset);
847dbe13110SDimitry Andric }
848dbe13110SDimitry Andric }
849dbe13110SDimitry Andric
850dbe13110SDimitry Andric unsigned FieldNo = 0;
851dbe13110SDimitry Andric uint64_t OffsetBits = CGM.getContext().toBits(Offset);
852dbe13110SDimitry Andric
85322989816SDimitry Andric bool AllowOverwrite = false;
854dbe13110SDimitry Andric for (RecordDecl::field_iterator Field = RD->field_begin(),
855dbe13110SDimitry Andric FieldEnd = RD->field_end(); Field != FieldEnd; ++Field, ++FieldNo) {
856dbe13110SDimitry Andric // If this is a union, skip all the fields that aren't being initialized.
85722989816SDimitry Andric if (RD->isUnion() && !declaresSameEntity(Val.getUnionField(), *Field))
858dbe13110SDimitry Andric continue;
859dbe13110SDimitry Andric
86022989816SDimitry Andric // Don't emit anonymous bitfields or zero-sized fields.
861ac9a064cSDimitry Andric if (Field->isUnnamedBitField() ||
862ac9a064cSDimitry Andric isEmptyFieldForLayout(CGM.getContext(), *Field))
863dbe13110SDimitry Andric continue;
864dbe13110SDimitry Andric
865dbe13110SDimitry Andric // Emit the value of the initializer.
866dbe13110SDimitry Andric const APValue &FieldValue =
867dbe13110SDimitry Andric RD->isUnion() ? Val.getUnionValue() : Val.getStructField(FieldNo);
868dbe13110SDimitry Andric llvm::Constant *EltInit =
869461a67faSDimitry Andric Emitter.tryEmitPrivateForMemory(FieldValue, Field->getType());
870461a67faSDimitry Andric if (!EltInit)
871461a67faSDimitry Andric return false;
872dbe13110SDimitry Andric
873dbe13110SDimitry Andric if (!Field->isBitField()) {
874dbe13110SDimitry Andric // Handle non-bitfield members.
87522989816SDimitry Andric if (!AppendField(*Field, Layout.getFieldOffset(FieldNo) + OffsetBits,
87622989816SDimitry Andric EltInit, AllowOverwrite))
87722989816SDimitry Andric return false;
87822989816SDimitry Andric // After emitting a non-empty field with [[no_unique_address]], we may
87922989816SDimitry Andric // need to overwrite its tail padding.
88022989816SDimitry Andric if (Field->hasAttr<NoUniqueAddressAttr>())
88122989816SDimitry Andric AllowOverwrite = true;
882dbe13110SDimitry Andric } else {
883dbe13110SDimitry Andric // Otherwise we have a bitfield.
88422989816SDimitry Andric if (!AppendBitField(*Field, Layout.getFieldOffset(FieldNo) + OffsetBits,
885ac9a064cSDimitry Andric EltInit, AllowOverwrite))
88622989816SDimitry Andric return false;
887dbe13110SDimitry Andric }
888dbe13110SDimitry Andric }
889461a67faSDimitry Andric
890461a67faSDimitry Andric return true;
891dbe13110SDimitry Andric }
892dbe13110SDimitry Andric
Finalize(QualType Type)89322989816SDimitry Andric llvm::Constant *ConstStructBuilder::Finalize(QualType Type) {
894ecbca9f5SDimitry Andric Type = Type.getNonReferenceType();
895519fc96cSDimitry Andric RecordDecl *RD = Type->castAs<RecordType>()->getDecl();
89622989816SDimitry Andric llvm::Type *ValTy = CGM.getTypes().ConvertType(Type);
89722989816SDimitry Andric return Builder.build(ValTy, RD->hasFlexibleArrayMember());
8982e645aa5SDimitry Andric }
8992e645aa5SDimitry Andric
BuildStruct(ConstantEmitter & Emitter,const InitListExpr * ILE,QualType ValTy)900461a67faSDimitry Andric llvm::Constant *ConstStructBuilder::BuildStruct(ConstantEmitter &Emitter,
901ac9a064cSDimitry Andric const InitListExpr *ILE,
902461a67faSDimitry Andric QualType ValTy) {
90322989816SDimitry Andric ConstantAggregateBuilder Const(Emitter.CGM);
90422989816SDimitry Andric ConstStructBuilder Builder(Emitter, Const, CharUnits::Zero());
905dbe13110SDimitry Andric
90622989816SDimitry Andric if (!Builder.Build(ILE, /*AllowOverwrite*/false))
9079f4dbff6SDimitry Andric return nullptr;
908dbe13110SDimitry Andric
909461a67faSDimitry Andric return Builder.Finalize(ValTy);
910dbe13110SDimitry Andric }
911dbe13110SDimitry Andric
BuildStruct(ConstantEmitter & Emitter,const APValue & Val,QualType ValTy)912461a67faSDimitry Andric llvm::Constant *ConstStructBuilder::BuildStruct(ConstantEmitter &Emitter,
913dbe13110SDimitry Andric const APValue &Val,
914dbe13110SDimitry Andric QualType ValTy) {
91522989816SDimitry Andric ConstantAggregateBuilder Const(Emitter.CGM);
91622989816SDimitry Andric ConstStructBuilder Builder(Emitter, Const, CharUnits::Zero());
917dbe13110SDimitry Andric
918dbe13110SDimitry Andric const RecordDecl *RD = ValTy->castAs<RecordType>()->getDecl();
919dbe13110SDimitry Andric const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD);
920461a67faSDimitry Andric if (!Builder.Build(Val, RD, false, CD, CharUnits::Zero()))
921461a67faSDimitry Andric return nullptr;
922dbe13110SDimitry Andric
923dbe13110SDimitry Andric return Builder.Finalize(ValTy);
924dbe13110SDimitry Andric }
925dbe13110SDimitry Andric
UpdateStruct(ConstantEmitter & Emitter,ConstantAggregateBuilder & Const,CharUnits Offset,const InitListExpr * Updater)92622989816SDimitry Andric bool ConstStructBuilder::UpdateStruct(ConstantEmitter &Emitter,
92722989816SDimitry Andric ConstantAggregateBuilder &Const,
928ac9a064cSDimitry Andric CharUnits Offset,
929ac9a064cSDimitry Andric const InitListExpr *Updater) {
93022989816SDimitry Andric return ConstStructBuilder(Emitter, Const, Offset)
93122989816SDimitry Andric .Build(Updater, /*AllowOverwrite*/ true);
93222989816SDimitry Andric }
9330883ccd9SRoman Divacky
9340883ccd9SRoman Divacky //===----------------------------------------------------------------------===//
9350883ccd9SRoman Divacky // ConstExprEmitter
9360883ccd9SRoman Divacky //===----------------------------------------------------------------------===//
9374c8b2481SRoman Divacky
938e3b55780SDimitry Andric static ConstantAddress
tryEmitGlobalCompoundLiteral(ConstantEmitter & emitter,const CompoundLiteralExpr * E)939e3b55780SDimitry Andric tryEmitGlobalCompoundLiteral(ConstantEmitter &emitter,
940461a67faSDimitry Andric const CompoundLiteralExpr *E) {
941e3b55780SDimitry Andric CodeGenModule &CGM = emitter.CGM;
942461a67faSDimitry Andric CharUnits Align = CGM.getContext().getTypeAlignInChars(E->getType());
943461a67faSDimitry Andric if (llvm::GlobalVariable *Addr =
944461a67faSDimitry Andric CGM.getAddrOfConstantCompoundLiteralIfEmitted(E))
94577fc4c14SDimitry Andric return ConstantAddress(Addr, Addr->getValueType(), Align);
946461a67faSDimitry Andric
947461a67faSDimitry Andric LangAS addressSpace = E->getType().getAddressSpace();
948461a67faSDimitry Andric llvm::Constant *C = emitter.tryEmitForInitializer(E->getInitializer(),
949461a67faSDimitry Andric addressSpace, E->getType());
950461a67faSDimitry Andric if (!C) {
951461a67faSDimitry Andric assert(!E->isFileScope() &&
952461a67faSDimitry Andric "file-scope compound literal did not have constant initializer!");
953461a67faSDimitry Andric return ConstantAddress::invalid();
954461a67faSDimitry Andric }
955461a67faSDimitry Andric
9567fa27ce4SDimitry Andric auto GV = new llvm::GlobalVariable(
9577fa27ce4SDimitry Andric CGM.getModule(), C->getType(),
958b1c73532SDimitry Andric E->getType().isConstantStorage(CGM.getContext(), true, false),
9597fa27ce4SDimitry Andric llvm::GlobalValue::InternalLinkage, C, ".compoundliteral", nullptr,
960461a67faSDimitry Andric llvm::GlobalVariable::NotThreadLocal,
961461a67faSDimitry Andric CGM.getContext().getTargetAddressSpace(addressSpace));
962461a67faSDimitry Andric emitter.finalize(GV);
963519fc96cSDimitry Andric GV->setAlignment(Align.getAsAlign());
964461a67faSDimitry Andric CGM.setAddrOfConstantCompoundLiteral(E, GV);
96577fc4c14SDimitry Andric return ConstantAddress(GV, GV->getValueType(), Align);
966461a67faSDimitry Andric }
967461a67faSDimitry Andric
96848675466SDimitry Andric static llvm::Constant *
EmitArrayConstant(CodeGenModule & CGM,llvm::ArrayType * DesiredType,llvm::Type * CommonElementType,uint64_t ArrayBound,SmallVectorImpl<llvm::Constant * > & Elements,llvm::Constant * Filler)96922989816SDimitry Andric EmitArrayConstant(CodeGenModule &CGM, llvm::ArrayType *DesiredType,
970ac9a064cSDimitry Andric llvm::Type *CommonElementType, uint64_t ArrayBound,
97148675466SDimitry Andric SmallVectorImpl<llvm::Constant *> &Elements,
97248675466SDimitry Andric llvm::Constant *Filler) {
97348675466SDimitry Andric // Figure out how long the initial prefix of non-zero elements is.
974ac9a064cSDimitry Andric uint64_t NonzeroLength = ArrayBound;
97548675466SDimitry Andric if (Elements.size() < NonzeroLength && Filler->isNullValue())
97648675466SDimitry Andric NonzeroLength = Elements.size();
97748675466SDimitry Andric if (NonzeroLength == Elements.size()) {
97848675466SDimitry Andric while (NonzeroLength > 0 && Elements[NonzeroLength - 1]->isNullValue())
97948675466SDimitry Andric --NonzeroLength;
98048675466SDimitry Andric }
98148675466SDimitry Andric
98222989816SDimitry Andric if (NonzeroLength == 0)
98322989816SDimitry Andric return llvm::ConstantAggregateZero::get(DesiredType);
98448675466SDimitry Andric
98548675466SDimitry Andric // Add a zeroinitializer array filler if we have lots of trailing zeroes.
986ac9a064cSDimitry Andric uint64_t TrailingZeroes = ArrayBound - NonzeroLength;
98748675466SDimitry Andric if (TrailingZeroes >= 8) {
98848675466SDimitry Andric assert(Elements.size() >= NonzeroLength &&
98948675466SDimitry Andric "missing initializer for non-zero element");
99048675466SDimitry Andric
99148675466SDimitry Andric // If all the elements had the same type up to the trailing zeroes, emit a
99248675466SDimitry Andric // struct of two arrays (the nonzero data and the zeroinitializer).
99348675466SDimitry Andric if (CommonElementType && NonzeroLength >= 8) {
99448675466SDimitry Andric llvm::Constant *Initial = llvm::ConstantArray::get(
99548675466SDimitry Andric llvm::ArrayType::get(CommonElementType, NonzeroLength),
996e3b55780SDimitry Andric ArrayRef(Elements).take_front(NonzeroLength));
99748675466SDimitry Andric Elements.resize(2);
99848675466SDimitry Andric Elements[0] = Initial;
99948675466SDimitry Andric } else {
100048675466SDimitry Andric Elements.resize(NonzeroLength + 1);
100148675466SDimitry Andric }
100248675466SDimitry Andric
100348675466SDimitry Andric auto *FillerType =
100422989816SDimitry Andric CommonElementType ? CommonElementType : DesiredType->getElementType();
100548675466SDimitry Andric FillerType = llvm::ArrayType::get(FillerType, TrailingZeroes);
100648675466SDimitry Andric Elements.back() = llvm::ConstantAggregateZero::get(FillerType);
100748675466SDimitry Andric CommonElementType = nullptr;
100848675466SDimitry Andric } else if (Elements.size() != ArrayBound) {
100948675466SDimitry Andric // Otherwise pad to the right size with the filler if necessary.
101048675466SDimitry Andric Elements.resize(ArrayBound, Filler);
101148675466SDimitry Andric if (Filler->getType() != CommonElementType)
101248675466SDimitry Andric CommonElementType = nullptr;
101348675466SDimitry Andric }
101448675466SDimitry Andric
101548675466SDimitry Andric // If all elements have the same type, just emit an array constant.
101648675466SDimitry Andric if (CommonElementType)
101748675466SDimitry Andric return llvm::ConstantArray::get(
101848675466SDimitry Andric llvm::ArrayType::get(CommonElementType, ArrayBound), Elements);
101948675466SDimitry Andric
102048675466SDimitry Andric // We have mixed types. Use a packed struct.
102148675466SDimitry Andric llvm::SmallVector<llvm::Type *, 16> Types;
102248675466SDimitry Andric Types.reserve(Elements.size());
102348675466SDimitry Andric for (llvm::Constant *Elt : Elements)
102448675466SDimitry Andric Types.push_back(Elt->getType());
102548675466SDimitry Andric llvm::StructType *SType =
102648675466SDimitry Andric llvm::StructType::get(CGM.getLLVMContext(), Types, true);
102748675466SDimitry Andric return llvm::ConstantStruct::get(SType, Elements);
102848675466SDimitry Andric }
102948675466SDimitry Andric
103022989816SDimitry Andric // This class only needs to handle arrays, structs and unions. Outside C++11
103122989816SDimitry Andric // mode, we don't currently constant fold those types. All other types are
103222989816SDimitry Andric // handled by constant folding.
103322989816SDimitry Andric //
103422989816SDimitry Andric // Constant folding is currently missing support for a few features supported
103522989816SDimitry Andric // here: CK_ToUnion, CK_ReinterpretMemberPointer, and DesignatedInitUpdateExpr.
1036ac9a064cSDimitry Andric class ConstExprEmitter
1037ac9a064cSDimitry Andric : public ConstStmtVisitor<ConstExprEmitter, llvm::Constant *, QualType> {
1038ec2b103cSEd Schouten CodeGenModule &CGM;
1039461a67faSDimitry Andric ConstantEmitter &Emitter;
10404c8b2481SRoman Divacky llvm::LLVMContext &VMContext;
1041ec2b103cSEd Schouten public:
ConstExprEmitter(ConstantEmitter & emitter)1042461a67faSDimitry Andric ConstExprEmitter(ConstantEmitter &emitter)
1043461a67faSDimitry Andric : CGM(emitter.CGM), Emitter(emitter), VMContext(CGM.getLLVMContext()) {
1044ec2b103cSEd Schouten }
1045ec2b103cSEd Schouten
1046ec2b103cSEd Schouten //===--------------------------------------------------------------------===//
1047ec2b103cSEd Schouten // Visitor Methods
1048ec2b103cSEd Schouten //===--------------------------------------------------------------------===//
1049ec2b103cSEd Schouten
VisitStmt(const Stmt * S,QualType T)1050ac9a064cSDimitry Andric llvm::Constant *VisitStmt(const Stmt *S, QualType T) { return nullptr; }
1051ec2b103cSEd Schouten
VisitConstantExpr(const ConstantExpr * CE,QualType T)1052ac9a064cSDimitry Andric llvm::Constant *VisitConstantExpr(const ConstantExpr *CE, QualType T) {
1053cfca06d7SDimitry Andric if (llvm::Constant *Result = Emitter.tryEmitConstantExpr(CE))
1054cfca06d7SDimitry Andric return Result;
1055676fbe81SDimitry Andric return Visit(CE->getSubExpr(), T);
1056676fbe81SDimitry Andric }
1057676fbe81SDimitry Andric
VisitParenExpr(const ParenExpr * PE,QualType T)1058ac9a064cSDimitry Andric llvm::Constant *VisitParenExpr(const ParenExpr *PE, QualType T) {
1059461a67faSDimitry Andric return Visit(PE->getSubExpr(), T);
1060ec2b103cSEd Schouten }
1061ec2b103cSEd Schouten
1062180abc3dSDimitry Andric llvm::Constant *
VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr * PE,QualType T)1063ac9a064cSDimitry Andric VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr *PE,
1064461a67faSDimitry Andric QualType T) {
1065461a67faSDimitry Andric return Visit(PE->getReplacement(), T);
1066180abc3dSDimitry Andric }
1067180abc3dSDimitry Andric
VisitGenericSelectionExpr(const GenericSelectionExpr * GE,QualType T)1068ac9a064cSDimitry Andric llvm::Constant *VisitGenericSelectionExpr(const GenericSelectionExpr *GE,
1069461a67faSDimitry Andric QualType T) {
1070461a67faSDimitry Andric return Visit(GE->getResultExpr(), T);
107101af97d3SDimitry Andric }
107201af97d3SDimitry Andric
VisitChooseExpr(const ChooseExpr * CE,QualType T)1073ac9a064cSDimitry Andric llvm::Constant *VisitChooseExpr(const ChooseExpr *CE, QualType T) {
1074461a67faSDimitry Andric return Visit(CE->getChosenSubExpr(), T);
1075bfef3995SDimitry Andric }
1076bfef3995SDimitry Andric
VisitCompoundLiteralExpr(const CompoundLiteralExpr * E,QualType T)1077ac9a064cSDimitry Andric llvm::Constant *VisitCompoundLiteralExpr(const CompoundLiteralExpr *E,
1078ac9a064cSDimitry Andric QualType T) {
1079461a67faSDimitry Andric return Visit(E->getInitializer(), T);
1080ec2b103cSEd Schouten }
1081ec2b103cSEd Schouten
ProduceIntToIntCast(const Expr * E,QualType DestType)1082ac9a064cSDimitry Andric llvm::Constant *ProduceIntToIntCast(const Expr *E, QualType DestType) {
1083ac9a064cSDimitry Andric QualType FromType = E->getType();
1084ac9a064cSDimitry Andric // See also HandleIntToIntCast in ExprConstant.cpp
1085ac9a064cSDimitry Andric if (FromType->isIntegerType())
1086ac9a064cSDimitry Andric if (llvm::Constant *C = Visit(E, FromType))
1087ac9a064cSDimitry Andric if (auto *CI = dyn_cast<llvm::ConstantInt>(C)) {
1088ac9a064cSDimitry Andric unsigned SrcWidth = CGM.getContext().getIntWidth(FromType);
1089ac9a064cSDimitry Andric unsigned DstWidth = CGM.getContext().getIntWidth(DestType);
1090ac9a064cSDimitry Andric if (DstWidth == SrcWidth)
1091ac9a064cSDimitry Andric return CI;
1092ac9a064cSDimitry Andric llvm::APInt A = FromType->isSignedIntegerType()
1093ac9a064cSDimitry Andric ? CI->getValue().sextOrTrunc(DstWidth)
1094ac9a064cSDimitry Andric : CI->getValue().zextOrTrunc(DstWidth);
1095ac9a064cSDimitry Andric return llvm::ConstantInt::get(CGM.getLLVMContext(), A);
1096ac9a064cSDimitry Andric }
1097ac9a064cSDimitry Andric return nullptr;
1098ac9a064cSDimitry Andric }
1099ac9a064cSDimitry Andric
VisitCastExpr(const CastExpr * E,QualType destType)1100ac9a064cSDimitry Andric llvm::Constant *VisitCastExpr(const CastExpr *E, QualType destType) {
110145b53394SDimitry Andric if (const auto *ECE = dyn_cast<ExplicitCastExpr>(E))
1102461a67faSDimitry Andric CGM.EmitExplicitCastExprType(ECE, Emitter.CGF);
1103ac9a064cSDimitry Andric const Expr *subExpr = E->getSubExpr();
110401af97d3SDimitry Andric
11054c8b2481SRoman Divacky switch (E->getCastKind()) {
11063d1dcd9bSDimitry Andric case CK_ToUnion: {
1107ec2b103cSEd Schouten // GCC cast to union extension
11084c8b2481SRoman Divacky assert(E->getType()->isUnionType() &&
11094c8b2481SRoman Divacky "Destination type is not union type!");
11104c8b2481SRoman Divacky
1111461a67faSDimitry Andric auto field = E->getTargetUnionField();
1112461a67faSDimitry Andric
1113461a67faSDimitry Andric auto C = Emitter.tryEmitPrivateForMemory(subExpr, field->getType());
1114461a67faSDimitry Andric if (!C) return nullptr;
1115461a67faSDimitry Andric
1116461a67faSDimitry Andric auto destTy = ConvertType(destType);
1117461a67faSDimitry Andric if (C->getType() == destTy) return C;
1118461a67faSDimitry Andric
11194c8b2481SRoman Divacky // Build a struct with the union sub-element as the first member,
1120461a67faSDimitry Andric // and padded to the appropriate size.
1121dbe13110SDimitry Andric SmallVector<llvm::Constant*, 2> Elts;
1122dbe13110SDimitry Andric SmallVector<llvm::Type*, 2> Types;
11234c8b2481SRoman Divacky Elts.push_back(C);
11244c8b2481SRoman Divacky Types.push_back(C->getType());
112513cc256eSDimitry Andric unsigned CurSize = CGM.getDataLayout().getTypeAllocSize(C->getType());
1126461a67faSDimitry Andric unsigned TotalSize = CGM.getDataLayout().getTypeAllocSize(destTy);
11274c8b2481SRoman Divacky
11284c8b2481SRoman Divacky assert(CurSize <= TotalSize && "Union size mismatch!");
11294c8b2481SRoman Divacky if (unsigned NumPadBytes = TotalSize - CurSize) {
1130b60736ecSDimitry Andric llvm::Type *Ty = CGM.CharTy;
11314c8b2481SRoman Divacky if (NumPadBytes > 1)
11324c8b2481SRoman Divacky Ty = llvm::ArrayType::get(Ty, NumPadBytes);
11334c8b2481SRoman Divacky
113451fb8b01SRoman Divacky Elts.push_back(llvm::UndefValue::get(Ty));
11354c8b2481SRoman Divacky Types.push_back(Ty);
1136ec2b103cSEd Schouten }
11374c8b2481SRoman Divacky
1138461a67faSDimitry Andric llvm::StructType *STy = llvm::StructType::get(VMContext, Types, false);
11394c8b2481SRoman Divacky return llvm::ConstantStruct::get(STy, Elts);
11404c8b2481SRoman Divacky }
11414c8b2481SRoman Divacky
1142461a67faSDimitry Andric case CK_AddressSpaceConversion: {
1143461a67faSDimitry Andric auto C = Emitter.tryEmitPrivate(subExpr, subExpr->getType());
1144461a67faSDimitry Andric if (!C) return nullptr;
1145461a67faSDimitry Andric LangAS destAS = E->getType()->getPointeeType().getAddressSpace();
1146461a67faSDimitry Andric LangAS srcAS = subExpr->getType()->getPointeeType().getAddressSpace();
1147461a67faSDimitry Andric llvm::Type *destTy = ConvertType(E->getType());
1148461a67faSDimitry Andric return CGM.getTargetCodeGenInfo().performAddrSpaceCast(CGM, C, srcAS,
1149461a67faSDimitry Andric destAS, destTy);
1150461a67faSDimitry Andric }
11519f4dbff6SDimitry Andric
1152145449b1SDimitry Andric case CK_LValueToRValue: {
1153145449b1SDimitry Andric // We don't really support doing lvalue-to-rvalue conversions here; any
1154145449b1SDimitry Andric // interesting conversions should be done in Evaluate(). But as a
1155145449b1SDimitry Andric // special case, allow compound literals to support the gcc extension
1156145449b1SDimitry Andric // allowing "struct x {int x;} x = (struct x) {};".
1157ac9a064cSDimitry Andric if (const auto *E =
1158ac9a064cSDimitry Andric dyn_cast<CompoundLiteralExpr>(subExpr->IgnoreParens()))
1159145449b1SDimitry Andric return Visit(E->getInitializer(), destType);
1160145449b1SDimitry Andric return nullptr;
1161145449b1SDimitry Andric }
1162145449b1SDimitry Andric
1163dbe13110SDimitry Andric case CK_AtomicToNonAtomic:
1164dbe13110SDimitry Andric case CK_NonAtomicToAtomic:
116501af97d3SDimitry Andric case CK_NoOp:
1166bfef3995SDimitry Andric case CK_ConstructorConversion:
1167461a67faSDimitry Andric return Visit(subExpr, destType);
116801af97d3SDimitry Andric
1169b1c73532SDimitry Andric case CK_ArrayToPointerDecay:
1170b1c73532SDimitry Andric if (const auto *S = dyn_cast<StringLiteral>(subExpr))
1171b1c73532SDimitry Andric return CGM.GetAddrOfConstantStringFromLiteral(S).getPointer();
1172b1c73532SDimitry Andric return nullptr;
1173b1c73532SDimitry Andric case CK_NullToPointer:
1174b1c73532SDimitry Andric if (Visit(subExpr, destType))
1175b1c73532SDimitry Andric return CGM.EmitNullConstant(destType);
1176b1c73532SDimitry Andric return nullptr;
1177b1c73532SDimitry Andric
1178bab175ecSDimitry Andric case CK_IntToOCLSampler:
1179bab175ecSDimitry Andric llvm_unreachable("global sampler variables are not generated");
1180bab175ecSDimitry Andric
1181ac9a064cSDimitry Andric case CK_IntegralCast:
1182ac9a064cSDimitry Andric return ProduceIntToIntCast(subExpr, destType);
1183b1c73532SDimitry Andric
118401af97d3SDimitry Andric case CK_Dependent: llvm_unreachable("saw dependent cast!");
11854c8b2481SRoman Divacky
118613cc256eSDimitry Andric case CK_BuiltinFnToFnPtr:
118713cc256eSDimitry Andric llvm_unreachable("builtin functions are handled elsewhere");
118813cc256eSDimitry Andric
1189dbe13110SDimitry Andric case CK_ReinterpretMemberPointer:
1190dbe13110SDimitry Andric case CK_DerivedToBaseMemberPointer:
1191461a67faSDimitry Andric case CK_BaseToDerivedMemberPointer: {
1192461a67faSDimitry Andric auto C = Emitter.tryEmitPrivate(subExpr, subExpr->getType());
1193461a67faSDimitry Andric if (!C) return nullptr;
1194dbe13110SDimitry Andric return CGM.getCXXABI().EmitMemberPointerConversion(E, C);
1195461a67faSDimitry Andric }
1196dbe13110SDimitry Andric
119701af97d3SDimitry Andric // These will never be supported.
119801af97d3SDimitry Andric case CK_ObjCObjectLValueCast:
119936981b17SDimitry Andric case CK_ARCProduceObject:
120036981b17SDimitry Andric case CK_ARCConsumeObject:
120136981b17SDimitry Andric case CK_ARCReclaimReturnedObject:
120236981b17SDimitry Andric case CK_ARCExtendBlockObject:
1203dbe13110SDimitry Andric case CK_CopyAndAutoreleaseBlockObject:
12049f4dbff6SDimitry Andric return nullptr;
120501af97d3SDimitry Andric
1206dbe13110SDimitry Andric // These don't need to be handled here because Evaluate knows how to
1207dbe13110SDimitry Andric // evaluate them in the cases where they can be folded.
1208dbe13110SDimitry Andric case CK_BitCast:
1209dbe13110SDimitry Andric case CK_ToVoid:
1210dbe13110SDimitry Andric case CK_Dynamic:
1211dbe13110SDimitry Andric case CK_LValueBitCast:
121222989816SDimitry Andric case CK_LValueToRValueBitCast:
1213dbe13110SDimitry Andric case CK_NullToMemberPointer:
121401af97d3SDimitry Andric case CK_UserDefinedConversion:
1215dbe13110SDimitry Andric case CK_CPointerToObjCPointerCast:
1216dbe13110SDimitry Andric case CK_BlockPointerToObjCPointerCast:
1217dbe13110SDimitry Andric case CK_AnyPointerToBlockPointerCast:
121801af97d3SDimitry Andric case CK_FunctionToPointerDecay:
121901af97d3SDimitry Andric case CK_BaseToDerived:
122001af97d3SDimitry Andric case CK_DerivedToBase:
122101af97d3SDimitry Andric case CK_UncheckedDerivedToBase:
122201af97d3SDimitry Andric case CK_MemberPointerToBoolean:
122301af97d3SDimitry Andric case CK_VectorSplat:
122401af97d3SDimitry Andric case CK_FloatingRealToComplex:
122501af97d3SDimitry Andric case CK_FloatingComplexToReal:
122601af97d3SDimitry Andric case CK_FloatingComplexToBoolean:
122701af97d3SDimitry Andric case CK_FloatingComplexCast:
122801af97d3SDimitry Andric case CK_FloatingComplexToIntegralComplex:
122901af97d3SDimitry Andric case CK_IntegralRealToComplex:
123001af97d3SDimitry Andric case CK_IntegralComplexToReal:
123101af97d3SDimitry Andric case CK_IntegralComplexToBoolean:
123201af97d3SDimitry Andric case CK_IntegralComplexCast:
123301af97d3SDimitry Andric case CK_IntegralComplexToFloatingComplex:
123401af97d3SDimitry Andric case CK_PointerToIntegral:
123501af97d3SDimitry Andric case CK_PointerToBoolean:
12360414e226SDimitry Andric case CK_BooleanToSignedIntegral:
1237dbe13110SDimitry Andric case CK_IntegralToPointer:
123801af97d3SDimitry Andric case CK_IntegralToBoolean:
123901af97d3SDimitry Andric case CK_IntegralToFloating:
124001af97d3SDimitry Andric case CK_FloatingToIntegral:
124101af97d3SDimitry Andric case CK_FloatingToBoolean:
124201af97d3SDimitry Andric case CK_FloatingCast:
1243b60736ecSDimitry Andric case CK_FloatingToFixedPoint:
1244b60736ecSDimitry Andric case CK_FixedPointToFloating:
1245676fbe81SDimitry Andric case CK_FixedPointCast:
1246676fbe81SDimitry Andric case CK_FixedPointToBoolean:
124722989816SDimitry Andric case CK_FixedPointToIntegral:
124822989816SDimitry Andric case CK_IntegralToFixedPoint:
1249676fbe81SDimitry Andric case CK_ZeroToOCLOpaqueType:
1250344a3780SDimitry Andric case CK_MatrixCast:
1251ac9a064cSDimitry Andric case CK_HLSLVectorTruncation:
1252ac9a064cSDimitry Andric case CK_HLSLArrayRValue:
12539f4dbff6SDimitry Andric return nullptr;
125401af97d3SDimitry Andric }
125501af97d3SDimitry Andric llvm_unreachable("Invalid CastKind");
12564c8b2481SRoman Divacky }
1257ec2b103cSEd Schouten
VisitCXXDefaultInitExpr(const CXXDefaultInitExpr * DIE,QualType T)1258ac9a064cSDimitry Andric llvm::Constant *VisitCXXDefaultInitExpr(const CXXDefaultInitExpr *DIE,
1259ac9a064cSDimitry Andric QualType T) {
12606a037251SDimitry Andric // No need for a DefaultInitExprScope: we don't handle 'this' in a
12616a037251SDimitry Andric // constant expression.
1262461a67faSDimitry Andric return Visit(DIE->getExpr(), T);
12636a037251SDimitry Andric }
12646a037251SDimitry Andric
VisitExprWithCleanups(const ExprWithCleanups * E,QualType T)1265ac9a064cSDimitry Andric llvm::Constant *VisitExprWithCleanups(const ExprWithCleanups *E, QualType T) {
1266461a67faSDimitry Andric return Visit(E->getSubExpr(), T);
12672b6b257fSDimitry Andric }
12682b6b257fSDimitry Andric
VisitIntegerLiteral(const IntegerLiteral * I,QualType T)1269ac9a064cSDimitry Andric llvm::Constant *VisitIntegerLiteral(const IntegerLiteral *I, QualType T) {
1270b1c73532SDimitry Andric return llvm::ConstantInt::get(CGM.getLLVMContext(), I->getValue());
1271b1c73532SDimitry Andric }
1272b1c73532SDimitry Andric
withDestType(ASTContext & Ctx,const Expr * E,QualType SrcType,QualType DestType,const llvm::APSInt & Value)1273ac9a064cSDimitry Andric static APValue withDestType(ASTContext &Ctx, const Expr *E, QualType SrcType,
1274ac9a064cSDimitry Andric QualType DestType, const llvm::APSInt &Value) {
1275ac9a064cSDimitry Andric if (!Ctx.hasSameType(SrcType, DestType)) {
1276ac9a064cSDimitry Andric if (DestType->isFloatingType()) {
1277ac9a064cSDimitry Andric llvm::APFloat Result =
1278ac9a064cSDimitry Andric llvm::APFloat(Ctx.getFloatTypeSemantics(DestType), 1);
1279ac9a064cSDimitry Andric llvm::RoundingMode RM =
1280ac9a064cSDimitry Andric E->getFPFeaturesInEffect(Ctx.getLangOpts()).getRoundingMode();
1281ac9a064cSDimitry Andric if (RM == llvm::RoundingMode::Dynamic)
1282ac9a064cSDimitry Andric RM = llvm::RoundingMode::NearestTiesToEven;
1283ac9a064cSDimitry Andric Result.convertFromAPInt(Value, Value.isSigned(), RM);
1284ac9a064cSDimitry Andric return APValue(Result);
1285ac9a064cSDimitry Andric }
1286ac9a064cSDimitry Andric }
1287ac9a064cSDimitry Andric return APValue(Value);
1288ac9a064cSDimitry Andric }
1289ac9a064cSDimitry Andric
EmitArrayInitialization(const InitListExpr * ILE,QualType T)1290ac9a064cSDimitry Andric llvm::Constant *EmitArrayInitialization(const InitListExpr *ILE, QualType T) {
129148675466SDimitry Andric auto *CAT = CGM.getContext().getAsConstantArrayType(ILE->getType());
129248675466SDimitry Andric assert(CAT && "can't emit array init for non-constant-bound array");
1293ac9a064cSDimitry Andric uint64_t NumInitElements = ILE->getNumInits();
1294ac9a064cSDimitry Andric const uint64_t NumElements = CAT->getZExtSize();
1295ac9a064cSDimitry Andric for (const auto *Init : ILE->inits()) {
1296ac9a064cSDimitry Andric if (const auto *Embed =
1297ac9a064cSDimitry Andric dyn_cast<EmbedExpr>(Init->IgnoreParenImpCasts())) {
1298ac9a064cSDimitry Andric NumInitElements += Embed->getDataElementCount() - 1;
1299ac9a064cSDimitry Andric if (NumInitElements > NumElements) {
1300ac9a064cSDimitry Andric NumInitElements = NumElements;
1301ac9a064cSDimitry Andric break;
1302ac9a064cSDimitry Andric }
1303ac9a064cSDimitry Andric }
1304ac9a064cSDimitry Andric }
1305ec2b103cSEd Schouten
1306ec2b103cSEd Schouten // Initialising an array requires us to automatically
1307ec2b103cSEd Schouten // initialise any elements that have not been initialised explicitly
1308ac9a064cSDimitry Andric uint64_t NumInitableElts = std::min<uint64_t>(NumInitElements, NumElements);
1309ec2b103cSEd Schouten
131048675466SDimitry Andric QualType EltType = CAT->getElementType();
1311461a67faSDimitry Andric
131206d4ba38SDimitry Andric // Initialize remaining array elements.
131348675466SDimitry Andric llvm::Constant *fillC = nullptr;
1314ac9a064cSDimitry Andric if (const Expr *filler = ILE->getArrayFiller()) {
1315461a67faSDimitry Andric fillC = Emitter.tryEmitAbstractForMemory(filler, EltType);
131606d4ba38SDimitry Andric if (!fillC)
131706d4ba38SDimitry Andric return nullptr;
131848675466SDimitry Andric }
131906d4ba38SDimitry Andric
1320ec2b103cSEd Schouten // Copy initializer elements.
1321461a67faSDimitry Andric SmallVector<llvm::Constant *, 16> Elts;
132248675466SDimitry Andric if (fillC && fillC->isNullValue())
132348675466SDimitry Andric Elts.reserve(NumInitableElts + 1);
132448675466SDimitry Andric else
132548675466SDimitry Andric Elts.reserve(NumElements);
1326dbe13110SDimitry Andric
132748675466SDimitry Andric llvm::Type *CommonElementType = nullptr;
1328ac9a064cSDimitry Andric auto Emit = [&](const Expr *Init, unsigned ArrayIndex) {
1329ac9a064cSDimitry Andric llvm::Constant *C = nullptr;
1330ac9a064cSDimitry Andric C = Emitter.tryEmitPrivateForMemory(Init, EltType);
1331ec2b103cSEd Schouten if (!C)
1332ac9a064cSDimitry Andric return false;
1333ac9a064cSDimitry Andric if (ArrayIndex == 0)
133448675466SDimitry Andric CommonElementType = C->getType();
133548675466SDimitry Andric else if (C->getType() != CommonElementType)
133648675466SDimitry Andric CommonElementType = nullptr;
1337ec2b103cSEd Schouten Elts.push_back(C);
1338ac9a064cSDimitry Andric return true;
1339ac9a064cSDimitry Andric };
1340ac9a064cSDimitry Andric
1341ac9a064cSDimitry Andric unsigned ArrayIndex = 0;
1342ac9a064cSDimitry Andric QualType DestTy = CAT->getElementType();
1343ac9a064cSDimitry Andric for (unsigned i = 0; i < ILE->getNumInits(); ++i) {
1344ac9a064cSDimitry Andric const Expr *Init = ILE->getInit(i);
1345ac9a064cSDimitry Andric if (auto *EmbedS = dyn_cast<EmbedExpr>(Init->IgnoreParenImpCasts())) {
1346ac9a064cSDimitry Andric StringLiteral *SL = EmbedS->getDataStringLiteral();
1347ac9a064cSDimitry Andric llvm::APSInt Value(CGM.getContext().getTypeSize(DestTy),
1348ac9a064cSDimitry Andric DestTy->isUnsignedIntegerType());
1349ac9a064cSDimitry Andric llvm::Constant *C;
1350ac9a064cSDimitry Andric for (unsigned I = EmbedS->getStartingElementPos(),
1351ac9a064cSDimitry Andric N = EmbedS->getDataElementCount();
1352ac9a064cSDimitry Andric I != EmbedS->getStartingElementPos() + N; ++I) {
1353ac9a064cSDimitry Andric Value = SL->getCodeUnit(I);
1354ac9a064cSDimitry Andric if (DestTy->isIntegerType()) {
1355ac9a064cSDimitry Andric C = llvm::ConstantInt::get(CGM.getLLVMContext(), Value);
1356ac9a064cSDimitry Andric } else {
1357ac9a064cSDimitry Andric C = Emitter.tryEmitPrivateForMemory(
1358ac9a064cSDimitry Andric withDestType(CGM.getContext(), Init, EmbedS->getType(), DestTy,
1359ac9a064cSDimitry Andric Value),
1360ac9a064cSDimitry Andric EltType);
1361ac9a064cSDimitry Andric }
1362ac9a064cSDimitry Andric if (!C)
1363ac9a064cSDimitry Andric return nullptr;
1364ac9a064cSDimitry Andric Elts.push_back(C);
1365ac9a064cSDimitry Andric ArrayIndex++;
1366ac9a064cSDimitry Andric }
1367ac9a064cSDimitry Andric if ((ArrayIndex - EmbedS->getDataElementCount()) == 0)
1368ac9a064cSDimitry Andric CommonElementType = C->getType();
1369ac9a064cSDimitry Andric else if (C->getType() != CommonElementType)
1370ac9a064cSDimitry Andric CommonElementType = nullptr;
1371ac9a064cSDimitry Andric } else {
1372ac9a064cSDimitry Andric if (!Emit(Init, ArrayIndex))
1373ac9a064cSDimitry Andric return nullptr;
1374ac9a064cSDimitry Andric ArrayIndex++;
1375ac9a064cSDimitry Andric }
1376ec2b103cSEd Schouten }
1377ec2b103cSEd Schouten
137822989816SDimitry Andric llvm::ArrayType *Desired =
137922989816SDimitry Andric cast<llvm::ArrayType>(CGM.getTypes().ConvertType(ILE->getType()));
138022989816SDimitry Andric return EmitArrayConstant(CGM, Desired, CommonElementType, NumElements, Elts,
138148675466SDimitry Andric fillC);
1382ec2b103cSEd Schouten }
1383ec2b103cSEd Schouten
EmitRecordInitialization(const InitListExpr * ILE,QualType T)1384ac9a064cSDimitry Andric llvm::Constant *EmitRecordInitialization(const InitListExpr *ILE,
1385ac9a064cSDimitry Andric QualType T) {
1386461a67faSDimitry Andric return ConstStructBuilder::BuildStruct(Emitter, ILE, T);
1387ec2b103cSEd Schouten }
1388ec2b103cSEd Schouten
VisitImplicitValueInitExpr(const ImplicitValueInitExpr * E,QualType T)1389ac9a064cSDimitry Andric llvm::Constant *VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E,
1390461a67faSDimitry Andric QualType T) {
1391461a67faSDimitry Andric return CGM.EmitNullConstant(T);
1392ec2b103cSEd Schouten }
1393ec2b103cSEd Schouten
VisitInitListExpr(const InitListExpr * ILE,QualType T)1394ac9a064cSDimitry Andric llvm::Constant *VisitInitListExpr(const InitListExpr *ILE, QualType T) {
1395bab175ecSDimitry Andric if (ILE->isTransparent())
1396461a67faSDimitry Andric return Visit(ILE->getInit(0), T);
1397bab175ecSDimitry Andric
1398ec2b103cSEd Schouten if (ILE->getType()->isArrayType())
1399461a67faSDimitry Andric return EmitArrayInitialization(ILE, T);
1400ec2b103cSEd Schouten
14011569ce68SRoman Divacky if (ILE->getType()->isRecordType())
1402461a67faSDimitry Andric return EmitRecordInitialization(ILE, T);
1403ec2b103cSEd Schouten
14049f4dbff6SDimitry Andric return nullptr;
1405ec2b103cSEd Schouten }
1406ec2b103cSEd Schouten
1407ac9a064cSDimitry Andric llvm::Constant *
VisitDesignatedInitUpdateExpr(const DesignatedInitUpdateExpr * E,QualType destType)1408ac9a064cSDimitry Andric VisitDesignatedInitUpdateExpr(const DesignatedInitUpdateExpr *E,
1409461a67faSDimitry Andric QualType destType) {
1410461a67faSDimitry Andric auto C = Visit(E->getBase(), destType);
141122989816SDimitry Andric if (!C)
141222989816SDimitry Andric return nullptr;
141322989816SDimitry Andric
141422989816SDimitry Andric ConstantAggregateBuilder Const(CGM);
141522989816SDimitry Andric Const.add(C, CharUnits::Zero(), false);
141622989816SDimitry Andric
141722989816SDimitry Andric if (!EmitDesignatedInitUpdater(Emitter, Const, CharUnits::Zero(), destType,
141822989816SDimitry Andric E->getUpdater()))
141922989816SDimitry Andric return nullptr;
142022989816SDimitry Andric
142122989816SDimitry Andric llvm::Type *ValTy = CGM.getTypes().ConvertType(destType);
142222989816SDimitry Andric bool HasFlexibleArray = false;
1423ac9a064cSDimitry Andric if (const auto *RT = destType->getAs<RecordType>())
142422989816SDimitry Andric HasFlexibleArray = RT->getDecl()->hasFlexibleArrayMember();
142522989816SDimitry Andric return Const.build(ValTy, HasFlexibleArray);
14262e645aa5SDimitry Andric }
14272e645aa5SDimitry Andric
VisitCXXConstructExpr(const CXXConstructExpr * E,QualType Ty)1428ac9a064cSDimitry Andric llvm::Constant *VisitCXXConstructExpr(const CXXConstructExpr *E,
1429ac9a064cSDimitry Andric QualType Ty) {
1430ecb7e5c8SRoman Divacky if (!E->getConstructor()->isTrivial())
14319f4dbff6SDimitry Andric return nullptr;
1432ecb7e5c8SRoman Divacky
1433cfca06d7SDimitry Andric // Only default and copy/move constructors can be trivial.
1434ecb7e5c8SRoman Divacky if (E->getNumArgs()) {
1435ecb7e5c8SRoman Divacky assert(E->getNumArgs() == 1 && "trivial ctor with > 1 argument");
143636981b17SDimitry Andric assert(E->getConstructor()->isCopyOrMoveConstructor() &&
143736981b17SDimitry Andric "trivial ctor has argument but isn't a copy/move ctor");
1438ecb7e5c8SRoman Divacky
1439ac9a064cSDimitry Andric const Expr *Arg = E->getArg(0);
1440ecb7e5c8SRoman Divacky assert(CGM.getContext().hasSameUnqualifiedType(Ty, Arg->getType()) &&
1441ecb7e5c8SRoman Divacky "argument to copy ctor is of wrong type");
1442ecb7e5c8SRoman Divacky
14437fa27ce4SDimitry Andric // Look through the temporary; it's just converting the value to an
14447fa27ce4SDimitry Andric // lvalue to pass it to the constructor.
1445ac9a064cSDimitry Andric if (const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(Arg))
14467fa27ce4SDimitry Andric return Visit(MTE->getSubExpr(), Ty);
14477fa27ce4SDimitry Andric // Don't try to support arbitrary lvalue-to-rvalue conversions for now.
14487fa27ce4SDimitry Andric return nullptr;
1449ecb7e5c8SRoman Divacky }
1450ecb7e5c8SRoman Divacky
1451ecb7e5c8SRoman Divacky return CGM.EmitNullConstant(Ty);
1452ecb7e5c8SRoman Divacky }
1453ecb7e5c8SRoman Divacky
VisitStringLiteral(const StringLiteral * E,QualType T)1454ac9a064cSDimitry Andric llvm::Constant *VisitStringLiteral(const StringLiteral *E, QualType T) {
145522989816SDimitry Andric // This is a string literal initializing an array in an initializer.
1456dbe13110SDimitry Andric return CGM.GetConstantArrayFromStringLiteral(E);
1457ec2b103cSEd Schouten }
1458ec2b103cSEd Schouten
VisitObjCEncodeExpr(const ObjCEncodeExpr * E,QualType T)1459ac9a064cSDimitry Andric llvm::Constant *VisitObjCEncodeExpr(const ObjCEncodeExpr *E, QualType T) {
1460ec2b103cSEd Schouten // This must be an @encode initializing an array in a static initializer.
1461ec2b103cSEd Schouten // Don't emit it as the address of the string, emit the string data itself
1462ec2b103cSEd Schouten // as an inline array.
1463ec2b103cSEd Schouten std::string Str;
1464ec2b103cSEd Schouten CGM.getContext().getObjCEncodingForType(E->getEncodedType(), Str);
1465461a67faSDimitry Andric const ConstantArrayType *CAT = CGM.getContext().getAsConstantArrayType(T);
14667fa27ce4SDimitry Andric assert(CAT && "String data not of constant array type!");
1467ec2b103cSEd Schouten
1468ec2b103cSEd Schouten // Resize the string to the right size, adding zeros at the end, or
1469ec2b103cSEd Schouten // truncating as needed.
1470ac9a064cSDimitry Andric Str.resize(CAT->getZExtSize(), '\0');
1471dbe13110SDimitry Andric return llvm::ConstantDataArray::getString(VMContext, Str, false);
1472ec2b103cSEd Schouten }
1473ec2b103cSEd Schouten
VisitUnaryExtension(const UnaryOperator * E,QualType T)1474461a67faSDimitry Andric llvm::Constant *VisitUnaryExtension(const UnaryOperator *E, QualType T) {
1475461a67faSDimitry Andric return Visit(E->getSubExpr(), T);
1476ec2b103cSEd Schouten }
1477ec2b103cSEd Schouten
VisitUnaryMinus(const UnaryOperator * U,QualType T)1478ac9a064cSDimitry Andric llvm::Constant *VisitUnaryMinus(const UnaryOperator *U, QualType T) {
1479b1c73532SDimitry Andric if (llvm::Constant *C = Visit(U->getSubExpr(), T))
1480b1c73532SDimitry Andric if (auto *CI = dyn_cast<llvm::ConstantInt>(C))
1481b1c73532SDimitry Andric return llvm::ConstantInt::get(CGM.getLLVMContext(), -CI->getValue());
1482b1c73532SDimitry Andric return nullptr;
1483b1c73532SDimitry Andric }
1484b1c73532SDimitry Andric
VisitPackIndexingExpr(const PackIndexingExpr * E,QualType T)1485ac9a064cSDimitry Andric llvm::Constant *VisitPackIndexingExpr(const PackIndexingExpr *E, QualType T) {
1486ac9a064cSDimitry Andric return Visit(E->getSelectedExpr(), T);
1487ac9a064cSDimitry Andric }
1488ac9a064cSDimitry Andric
1489ec2b103cSEd Schouten // Utility methods
ConvertType(QualType T)149036981b17SDimitry Andric llvm::Type *ConvertType(QualType T) {
1491ec2b103cSEd Schouten return CGM.getTypes().ConvertType(T);
1492ec2b103cSEd Schouten }
1493ec2b103cSEd Schouten };
1494ec2b103cSEd Schouten
1495ec2b103cSEd Schouten } // end anonymous namespace.
1496ec2b103cSEd Schouten
validateAndPopAbstract(llvm::Constant * C,AbstractState saved)1497461a67faSDimitry Andric llvm::Constant *ConstantEmitter::validateAndPopAbstract(llvm::Constant *C,
1498461a67faSDimitry Andric AbstractState saved) {
1499461a67faSDimitry Andric Abstract = saved.OldValue;
1500461a67faSDimitry Andric
1501461a67faSDimitry Andric assert(saved.OldPlaceholdersSize == PlaceholderAddresses.size() &&
1502461a67faSDimitry Andric "created a placeholder while doing an abstract emission?");
1503461a67faSDimitry Andric
1504461a67faSDimitry Andric // No validation necessary for now.
1505461a67faSDimitry Andric // No cleanup to do for now.
1506461a67faSDimitry Andric return C;
1507461a67faSDimitry Andric }
1508461a67faSDimitry Andric
1509461a67faSDimitry Andric llvm::Constant *
tryEmitAbstractForInitializer(const VarDecl & D)1510461a67faSDimitry Andric ConstantEmitter::tryEmitAbstractForInitializer(const VarDecl &D) {
1511461a67faSDimitry Andric auto state = pushAbstract();
1512461a67faSDimitry Andric auto C = tryEmitPrivateForVarInit(D);
1513461a67faSDimitry Andric return validateAndPopAbstract(C, state);
1514461a67faSDimitry Andric }
1515461a67faSDimitry Andric
1516461a67faSDimitry Andric llvm::Constant *
tryEmitAbstract(const Expr * E,QualType destType)1517461a67faSDimitry Andric ConstantEmitter::tryEmitAbstract(const Expr *E, QualType destType) {
1518461a67faSDimitry Andric auto state = pushAbstract();
1519461a67faSDimitry Andric auto C = tryEmitPrivate(E, destType);
1520461a67faSDimitry Andric return validateAndPopAbstract(C, state);
1521461a67faSDimitry Andric }
1522461a67faSDimitry Andric
1523461a67faSDimitry Andric llvm::Constant *
tryEmitAbstract(const APValue & value,QualType destType)1524461a67faSDimitry Andric ConstantEmitter::tryEmitAbstract(const APValue &value, QualType destType) {
1525461a67faSDimitry Andric auto state = pushAbstract();
1526461a67faSDimitry Andric auto C = tryEmitPrivate(value, destType);
1527461a67faSDimitry Andric return validateAndPopAbstract(C, state);
1528461a67faSDimitry Andric }
1529461a67faSDimitry Andric
tryEmitConstantExpr(const ConstantExpr * CE)1530cfca06d7SDimitry Andric llvm::Constant *ConstantEmitter::tryEmitConstantExpr(const ConstantExpr *CE) {
1531cfca06d7SDimitry Andric if (!CE->hasAPValueResult())
1532cfca06d7SDimitry Andric return nullptr;
1533e3b55780SDimitry Andric
1534e3b55780SDimitry Andric QualType RetType = CE->getType();
1535e3b55780SDimitry Andric if (CE->isGLValue())
1536e3b55780SDimitry Andric RetType = CGM.getContext().getLValueReferenceType(RetType);
1537e3b55780SDimitry Andric
1538e3b55780SDimitry Andric return emitAbstract(CE->getBeginLoc(), CE->getAPValueResult(), RetType);
1539cfca06d7SDimitry Andric }
1540cfca06d7SDimitry Andric
1541461a67faSDimitry Andric llvm::Constant *
emitAbstract(const Expr * E,QualType destType)1542461a67faSDimitry Andric ConstantEmitter::emitAbstract(const Expr *E, QualType destType) {
1543461a67faSDimitry Andric auto state = pushAbstract();
1544461a67faSDimitry Andric auto C = tryEmitPrivate(E, destType);
1545461a67faSDimitry Andric C = validateAndPopAbstract(C, state);
1546461a67faSDimitry Andric if (!C) {
1547461a67faSDimitry Andric CGM.Error(E->getExprLoc(),
1548461a67faSDimitry Andric "internal error: could not emit constant value \"abstractly\"");
1549461a67faSDimitry Andric C = CGM.EmitNullConstant(destType);
1550461a67faSDimitry Andric }
1551461a67faSDimitry Andric return C;
1552461a67faSDimitry Andric }
1553461a67faSDimitry Andric
1554461a67faSDimitry Andric llvm::Constant *
emitAbstract(SourceLocation loc,const APValue & value,QualType destType,bool EnablePtrAuthFunctionTypeDiscrimination)1555461a67faSDimitry Andric ConstantEmitter::emitAbstract(SourceLocation loc, const APValue &value,
1556ac9a064cSDimitry Andric QualType destType,
1557ac9a064cSDimitry Andric bool EnablePtrAuthFunctionTypeDiscrimination) {
1558461a67faSDimitry Andric auto state = pushAbstract();
1559ac9a064cSDimitry Andric auto C =
1560ac9a064cSDimitry Andric tryEmitPrivate(value, destType, EnablePtrAuthFunctionTypeDiscrimination);
1561461a67faSDimitry Andric C = validateAndPopAbstract(C, state);
1562461a67faSDimitry Andric if (!C) {
1563461a67faSDimitry Andric CGM.Error(loc,
1564461a67faSDimitry Andric "internal error: could not emit constant value \"abstractly\"");
1565461a67faSDimitry Andric C = CGM.EmitNullConstant(destType);
1566461a67faSDimitry Andric }
1567461a67faSDimitry Andric return C;
1568461a67faSDimitry Andric }
1569461a67faSDimitry Andric
tryEmitForInitializer(const VarDecl & D)1570461a67faSDimitry Andric llvm::Constant *ConstantEmitter::tryEmitForInitializer(const VarDecl &D) {
1571461a67faSDimitry Andric initializeNonAbstract(D.getType().getAddressSpace());
1572461a67faSDimitry Andric return markIfFailed(tryEmitPrivateForVarInit(D));
1573461a67faSDimitry Andric }
1574461a67faSDimitry Andric
tryEmitForInitializer(const Expr * E,LangAS destAddrSpace,QualType destType)1575461a67faSDimitry Andric llvm::Constant *ConstantEmitter::tryEmitForInitializer(const Expr *E,
1576461a67faSDimitry Andric LangAS destAddrSpace,
1577461a67faSDimitry Andric QualType destType) {
1578461a67faSDimitry Andric initializeNonAbstract(destAddrSpace);
1579461a67faSDimitry Andric return markIfFailed(tryEmitPrivateForMemory(E, destType));
1580461a67faSDimitry Andric }
1581461a67faSDimitry Andric
emitForInitializer(const APValue & value,LangAS destAddrSpace,QualType destType)1582461a67faSDimitry Andric llvm::Constant *ConstantEmitter::emitForInitializer(const APValue &value,
1583461a67faSDimitry Andric LangAS destAddrSpace,
1584461a67faSDimitry Andric QualType destType) {
1585461a67faSDimitry Andric initializeNonAbstract(destAddrSpace);
1586461a67faSDimitry Andric auto C = tryEmitPrivateForMemory(value, destType);
1587461a67faSDimitry Andric assert(C && "couldn't emit constant value non-abstractly?");
1588461a67faSDimitry Andric return C;
1589461a67faSDimitry Andric }
1590461a67faSDimitry Andric
getCurrentAddrPrivate()1591461a67faSDimitry Andric llvm::GlobalValue *ConstantEmitter::getCurrentAddrPrivate() {
1592461a67faSDimitry Andric assert(!Abstract && "cannot get current address for abstract constant");
1593461a67faSDimitry Andric
1594461a67faSDimitry Andric
1595461a67faSDimitry Andric
1596461a67faSDimitry Andric // Make an obviously ill-formed global that should blow up compilation
1597461a67faSDimitry Andric // if it survives.
1598461a67faSDimitry Andric auto global = new llvm::GlobalVariable(CGM.getModule(), CGM.Int8Ty, true,
1599461a67faSDimitry Andric llvm::GlobalValue::PrivateLinkage,
1600461a67faSDimitry Andric /*init*/ nullptr,
1601461a67faSDimitry Andric /*name*/ "",
1602461a67faSDimitry Andric /*before*/ nullptr,
1603461a67faSDimitry Andric llvm::GlobalVariable::NotThreadLocal,
1604461a67faSDimitry Andric CGM.getContext().getTargetAddressSpace(DestAddressSpace));
1605461a67faSDimitry Andric
1606461a67faSDimitry Andric PlaceholderAddresses.push_back(std::make_pair(nullptr, global));
1607461a67faSDimitry Andric
1608461a67faSDimitry Andric return global;
1609461a67faSDimitry Andric }
1610461a67faSDimitry Andric
registerCurrentAddrPrivate(llvm::Constant * signal,llvm::GlobalValue * placeholder)1611461a67faSDimitry Andric void ConstantEmitter::registerCurrentAddrPrivate(llvm::Constant *signal,
1612461a67faSDimitry Andric llvm::GlobalValue *placeholder) {
1613461a67faSDimitry Andric assert(!PlaceholderAddresses.empty());
1614461a67faSDimitry Andric assert(PlaceholderAddresses.back().first == nullptr);
1615461a67faSDimitry Andric assert(PlaceholderAddresses.back().second == placeholder);
1616461a67faSDimitry Andric PlaceholderAddresses.back().first = signal;
1617461a67faSDimitry Andric }
1618461a67faSDimitry Andric
1619461a67faSDimitry Andric namespace {
1620461a67faSDimitry Andric struct ReplacePlaceholders {
1621461a67faSDimitry Andric CodeGenModule &CGM;
1622461a67faSDimitry Andric
1623461a67faSDimitry Andric /// The base address of the global.
1624461a67faSDimitry Andric llvm::Constant *Base;
1625461a67faSDimitry Andric llvm::Type *BaseValueTy = nullptr;
1626461a67faSDimitry Andric
1627461a67faSDimitry Andric /// The placeholder addresses that were registered during emission.
1628461a67faSDimitry Andric llvm::DenseMap<llvm::Constant*, llvm::GlobalVariable*> PlaceholderAddresses;
1629461a67faSDimitry Andric
1630461a67faSDimitry Andric /// The locations of the placeholder signals.
1631461a67faSDimitry Andric llvm::DenseMap<llvm::GlobalVariable*, llvm::Constant*> Locations;
1632461a67faSDimitry Andric
1633461a67faSDimitry Andric /// The current index stack. We use a simple unsigned stack because
1634461a67faSDimitry Andric /// we assume that placeholders will be relatively sparse in the
1635461a67faSDimitry Andric /// initializer, but we cache the index values we find just in case.
1636461a67faSDimitry Andric llvm::SmallVector<unsigned, 8> Indices;
1637461a67faSDimitry Andric llvm::SmallVector<llvm::Constant*, 8> IndexValues;
1638461a67faSDimitry Andric
ReplacePlaceholders__anon4cd729e60a11::ReplacePlaceholders1639461a67faSDimitry Andric ReplacePlaceholders(CodeGenModule &CGM, llvm::Constant *base,
1640461a67faSDimitry Andric ArrayRef<std::pair<llvm::Constant*,
1641461a67faSDimitry Andric llvm::GlobalVariable*>> addresses)
1642461a67faSDimitry Andric : CGM(CGM), Base(base),
1643461a67faSDimitry Andric PlaceholderAddresses(addresses.begin(), addresses.end()) {
1644461a67faSDimitry Andric }
1645461a67faSDimitry Andric
replaceInInitializer__anon4cd729e60a11::ReplacePlaceholders1646461a67faSDimitry Andric void replaceInInitializer(llvm::Constant *init) {
1647461a67faSDimitry Andric // Remember the type of the top-most initializer.
1648461a67faSDimitry Andric BaseValueTy = init->getType();
1649461a67faSDimitry Andric
1650461a67faSDimitry Andric // Initialize the stack.
1651461a67faSDimitry Andric Indices.push_back(0);
1652461a67faSDimitry Andric IndexValues.push_back(nullptr);
1653461a67faSDimitry Andric
1654461a67faSDimitry Andric // Recurse into the initializer.
1655461a67faSDimitry Andric findLocations(init);
1656461a67faSDimitry Andric
1657461a67faSDimitry Andric // Check invariants.
1658461a67faSDimitry Andric assert(IndexValues.size() == Indices.size() && "mismatch");
1659461a67faSDimitry Andric assert(Indices.size() == 1 && "didn't pop all indices");
1660461a67faSDimitry Andric
1661461a67faSDimitry Andric // Do the replacement; this basically invalidates 'init'.
1662461a67faSDimitry Andric assert(Locations.size() == PlaceholderAddresses.size() &&
1663461a67faSDimitry Andric "missed a placeholder?");
1664461a67faSDimitry Andric
1665461a67faSDimitry Andric // We're iterating over a hashtable, so this would be a source of
1666461a67faSDimitry Andric // non-determinism in compiler output *except* that we're just
1667461a67faSDimitry Andric // messing around with llvm::Constant structures, which never itself
1668461a67faSDimitry Andric // does anything that should be visible in compiler output.
1669461a67faSDimitry Andric for (auto &entry : Locations) {
1670ac9a064cSDimitry Andric assert(entry.first->getName() == "" && "not a placeholder!");
1671461a67faSDimitry Andric entry.first->replaceAllUsesWith(entry.second);
1672461a67faSDimitry Andric entry.first->eraseFromParent();
1673461a67faSDimitry Andric }
1674461a67faSDimitry Andric }
1675461a67faSDimitry Andric
1676461a67faSDimitry Andric private:
findLocations__anon4cd729e60a11::ReplacePlaceholders1677461a67faSDimitry Andric void findLocations(llvm::Constant *init) {
1678461a67faSDimitry Andric // Recurse into aggregates.
1679461a67faSDimitry Andric if (auto agg = dyn_cast<llvm::ConstantAggregate>(init)) {
1680461a67faSDimitry Andric for (unsigned i = 0, e = agg->getNumOperands(); i != e; ++i) {
1681461a67faSDimitry Andric Indices.push_back(i);
1682461a67faSDimitry Andric IndexValues.push_back(nullptr);
1683461a67faSDimitry Andric
1684461a67faSDimitry Andric findLocations(agg->getOperand(i));
1685461a67faSDimitry Andric
1686461a67faSDimitry Andric IndexValues.pop_back();
1687461a67faSDimitry Andric Indices.pop_back();
1688461a67faSDimitry Andric }
1689461a67faSDimitry Andric return;
1690461a67faSDimitry Andric }
1691461a67faSDimitry Andric
1692461a67faSDimitry Andric // Otherwise, check for registered constants.
1693461a67faSDimitry Andric while (true) {
1694461a67faSDimitry Andric auto it = PlaceholderAddresses.find(init);
1695461a67faSDimitry Andric if (it != PlaceholderAddresses.end()) {
1696461a67faSDimitry Andric setLocation(it->second);
1697461a67faSDimitry Andric break;
1698461a67faSDimitry Andric }
1699461a67faSDimitry Andric
1700461a67faSDimitry Andric // Look through bitcasts or other expressions.
1701461a67faSDimitry Andric if (auto expr = dyn_cast<llvm::ConstantExpr>(init)) {
1702461a67faSDimitry Andric init = expr->getOperand(0);
1703461a67faSDimitry Andric } else {
1704461a67faSDimitry Andric break;
1705461a67faSDimitry Andric }
1706461a67faSDimitry Andric }
1707461a67faSDimitry Andric }
1708461a67faSDimitry Andric
setLocation__anon4cd729e60a11::ReplacePlaceholders1709461a67faSDimitry Andric void setLocation(llvm::GlobalVariable *placeholder) {
17107fa27ce4SDimitry Andric assert(!Locations.contains(placeholder) &&
1711461a67faSDimitry Andric "already found location for placeholder!");
1712461a67faSDimitry Andric
1713461a67faSDimitry Andric // Lazily fill in IndexValues with the values from Indices.
1714461a67faSDimitry Andric // We do this in reverse because we should always have a strict
1715461a67faSDimitry Andric // prefix of indices from the start.
1716461a67faSDimitry Andric assert(Indices.size() == IndexValues.size());
1717461a67faSDimitry Andric for (size_t i = Indices.size() - 1; i != size_t(-1); --i) {
1718461a67faSDimitry Andric if (IndexValues[i]) {
1719461a67faSDimitry Andric #ifndef NDEBUG
1720461a67faSDimitry Andric for (size_t j = 0; j != i + 1; ++j) {
1721461a67faSDimitry Andric assert(IndexValues[j] &&
1722461a67faSDimitry Andric isa<llvm::ConstantInt>(IndexValues[j]) &&
1723461a67faSDimitry Andric cast<llvm::ConstantInt>(IndexValues[j])->getZExtValue()
1724461a67faSDimitry Andric == Indices[j]);
1725461a67faSDimitry Andric }
1726461a67faSDimitry Andric #endif
1727461a67faSDimitry Andric break;
1728461a67faSDimitry Andric }
1729461a67faSDimitry Andric
1730461a67faSDimitry Andric IndexValues[i] = llvm::ConstantInt::get(CGM.Int32Ty, Indices[i]);
1731461a67faSDimitry Andric }
1732461a67faSDimitry Andric
1733b1c73532SDimitry Andric llvm::Constant *location = llvm::ConstantExpr::getInBoundsGetElementPtr(
1734b1c73532SDimitry Andric BaseValueTy, Base, IndexValues);
1735461a67faSDimitry Andric
1736461a67faSDimitry Andric Locations.insert({placeholder, location});
1737461a67faSDimitry Andric }
1738461a67faSDimitry Andric };
1739461a67faSDimitry Andric }
1740461a67faSDimitry Andric
finalize(llvm::GlobalVariable * global)1741461a67faSDimitry Andric void ConstantEmitter::finalize(llvm::GlobalVariable *global) {
1742461a67faSDimitry Andric assert(InitializedNonAbstract &&
1743461a67faSDimitry Andric "finalizing emitter that was used for abstract emission?");
1744461a67faSDimitry Andric assert(!Finalized && "finalizing emitter multiple times");
1745461a67faSDimitry Andric assert(global->getInitializer());
1746461a67faSDimitry Andric
1747461a67faSDimitry Andric // Note that we might also be Failed.
1748461a67faSDimitry Andric Finalized = true;
1749461a67faSDimitry Andric
1750461a67faSDimitry Andric if (!PlaceholderAddresses.empty()) {
1751461a67faSDimitry Andric ReplacePlaceholders(CGM, global, PlaceholderAddresses)
1752461a67faSDimitry Andric .replaceInInitializer(global->getInitializer());
1753461a67faSDimitry Andric PlaceholderAddresses.clear(); // satisfy
1754461a67faSDimitry Andric }
1755461a67faSDimitry Andric }
1756461a67faSDimitry Andric
~ConstantEmitter()1757461a67faSDimitry Andric ConstantEmitter::~ConstantEmitter() {
1758461a67faSDimitry Andric assert((!InitializedNonAbstract || Finalized || Failed) &&
1759461a67faSDimitry Andric "not finalized after being initialized for non-abstract emission");
1760461a67faSDimitry Andric assert(PlaceholderAddresses.empty() && "unhandled placeholders");
1761461a67faSDimitry Andric }
1762461a67faSDimitry Andric
getNonMemoryType(CodeGenModule & CGM,QualType type)1763461a67faSDimitry Andric static QualType getNonMemoryType(CodeGenModule &CGM, QualType type) {
1764461a67faSDimitry Andric if (auto AT = type->getAs<AtomicType>()) {
1765461a67faSDimitry Andric return CGM.getContext().getQualifiedType(AT->getValueType(),
1766461a67faSDimitry Andric type.getQualifiers());
1767461a67faSDimitry Andric }
1768461a67faSDimitry Andric return type;
1769461a67faSDimitry Andric }
1770461a67faSDimitry Andric
tryEmitPrivateForVarInit(const VarDecl & D)1771461a67faSDimitry Andric llvm::Constant *ConstantEmitter::tryEmitPrivateForVarInit(const VarDecl &D) {
1772809500fcSDimitry Andric // Make a quick check if variable can be default NULL initialized
1773809500fcSDimitry Andric // and avoid going through rest of code which may do, for c++11,
1774809500fcSDimitry Andric // initialization of memory to all NULLs.
1775809500fcSDimitry Andric if (!D.hasLocalStorage()) {
1776461a67faSDimitry Andric QualType Ty = CGM.getContext().getBaseElementType(D.getType());
1777809500fcSDimitry Andric if (Ty->isRecordType())
1778809500fcSDimitry Andric if (const CXXConstructExpr *E =
1779809500fcSDimitry Andric dyn_cast_or_null<CXXConstructExpr>(D.getInit())) {
1780809500fcSDimitry Andric const CXXConstructorDecl *CD = E->getConstructor();
1781809500fcSDimitry Andric if (CD->isTrivial() && CD->isDefaultConstructor())
1782461a67faSDimitry Andric return CGM.EmitNullConstant(D.getType());
1783809500fcSDimitry Andric }
1784809500fcSDimitry Andric }
1785b60736ecSDimitry Andric InConstantContext = D.hasConstantInitialization();
1786809500fcSDimitry Andric
1787461a67faSDimitry Andric QualType destType = D.getType();
1788dbe13110SDimitry Andric const Expr *E = D.getInit();
1789dbe13110SDimitry Andric assert(E && "No initializer to emit");
1790dbe13110SDimitry Andric
17917fa27ce4SDimitry Andric if (!destType->isReferenceType()) {
17927fa27ce4SDimitry Andric QualType nonMemoryDestType = getNonMemoryType(CGM, destType);
1793ac9a064cSDimitry Andric if (llvm::Constant *C = ConstExprEmitter(*this).Visit(E, nonMemoryDestType))
17947fa27ce4SDimitry Andric return emitForMemory(C, destType);
17957fa27ce4SDimitry Andric }
17967fa27ce4SDimitry Andric
17977fa27ce4SDimitry Andric // Try to emit the initializer. Note that this can allow some things that
17987fa27ce4SDimitry Andric // are not allowed by tryEmitPrivateForMemory alone.
17997fa27ce4SDimitry Andric if (APValue *value = D.evaluateValue())
18007fa27ce4SDimitry Andric return tryEmitPrivateForMemory(*value, destType);
18017fa27ce4SDimitry Andric
18027fa27ce4SDimitry Andric return nullptr;
1803dbe13110SDimitry Andric }
1804461a67faSDimitry Andric
1805461a67faSDimitry Andric llvm::Constant *
tryEmitAbstractForMemory(const Expr * E,QualType destType)1806461a67faSDimitry Andric ConstantEmitter::tryEmitAbstractForMemory(const Expr *E, QualType destType) {
1807461a67faSDimitry Andric auto nonMemoryDestType = getNonMemoryType(CGM, destType);
1808461a67faSDimitry Andric auto C = tryEmitAbstract(E, nonMemoryDestType);
1809461a67faSDimitry Andric return (C ? emitForMemory(C, destType) : nullptr);
1810461a67faSDimitry Andric }
1811461a67faSDimitry Andric
1812461a67faSDimitry Andric llvm::Constant *
tryEmitAbstractForMemory(const APValue & value,QualType destType)1813461a67faSDimitry Andric ConstantEmitter::tryEmitAbstractForMemory(const APValue &value,
1814461a67faSDimitry Andric QualType destType) {
1815461a67faSDimitry Andric auto nonMemoryDestType = getNonMemoryType(CGM, destType);
1816461a67faSDimitry Andric auto C = tryEmitAbstract(value, nonMemoryDestType);
1817461a67faSDimitry Andric return (C ? emitForMemory(C, destType) : nullptr);
1818461a67faSDimitry Andric }
1819461a67faSDimitry Andric
tryEmitPrivateForMemory(const Expr * E,QualType destType)1820461a67faSDimitry Andric llvm::Constant *ConstantEmitter::tryEmitPrivateForMemory(const Expr *E,
1821461a67faSDimitry Andric QualType destType) {
1822461a67faSDimitry Andric auto nonMemoryDestType = getNonMemoryType(CGM, destType);
1823461a67faSDimitry Andric llvm::Constant *C = tryEmitPrivate(E, nonMemoryDestType);
1824461a67faSDimitry Andric return (C ? emitForMemory(C, destType) : nullptr);
1825461a67faSDimitry Andric }
1826461a67faSDimitry Andric
tryEmitPrivateForMemory(const APValue & value,QualType destType)1827461a67faSDimitry Andric llvm::Constant *ConstantEmitter::tryEmitPrivateForMemory(const APValue &value,
1828461a67faSDimitry Andric QualType destType) {
1829461a67faSDimitry Andric auto nonMemoryDestType = getNonMemoryType(CGM, destType);
1830461a67faSDimitry Andric auto C = tryEmitPrivate(value, nonMemoryDestType);
1831461a67faSDimitry Andric return (C ? emitForMemory(C, destType) : nullptr);
1832461a67faSDimitry Andric }
1833461a67faSDimitry Andric
1834ac9a064cSDimitry Andric /// Try to emit a constant signed pointer, given a raw pointer and the
1835ac9a064cSDimitry Andric /// destination ptrauth qualifier.
1836ac9a064cSDimitry Andric ///
1837ac9a064cSDimitry Andric /// This can fail if the qualifier needs address discrimination and the
1838ac9a064cSDimitry Andric /// emitter is in an abstract mode.
1839ac9a064cSDimitry Andric llvm::Constant *
tryEmitConstantSignedPointer(llvm::Constant * UnsignedPointer,PointerAuthQualifier Schema)1840ac9a064cSDimitry Andric ConstantEmitter::tryEmitConstantSignedPointer(llvm::Constant *UnsignedPointer,
1841ac9a064cSDimitry Andric PointerAuthQualifier Schema) {
1842ac9a064cSDimitry Andric assert(Schema && "applying trivial ptrauth schema");
1843ac9a064cSDimitry Andric
1844ac9a064cSDimitry Andric if (Schema.hasKeyNone())
1845ac9a064cSDimitry Andric return UnsignedPointer;
1846ac9a064cSDimitry Andric
1847ac9a064cSDimitry Andric unsigned Key = Schema.getKey();
1848ac9a064cSDimitry Andric
1849ac9a064cSDimitry Andric // Create an address placeholder if we're using address discrimination.
1850ac9a064cSDimitry Andric llvm::GlobalValue *StorageAddress = nullptr;
1851ac9a064cSDimitry Andric if (Schema.isAddressDiscriminated()) {
1852ac9a064cSDimitry Andric // We can't do this if the emitter is in an abstract state.
1853ac9a064cSDimitry Andric if (isAbstract())
1854ac9a064cSDimitry Andric return nullptr;
1855ac9a064cSDimitry Andric
1856ac9a064cSDimitry Andric StorageAddress = getCurrentAddrPrivate();
1857ac9a064cSDimitry Andric }
1858ac9a064cSDimitry Andric
1859ac9a064cSDimitry Andric llvm::ConstantInt *Discriminator =
1860ac9a064cSDimitry Andric llvm::ConstantInt::get(CGM.IntPtrTy, Schema.getExtraDiscriminator());
1861ac9a064cSDimitry Andric
1862ac9a064cSDimitry Andric llvm::Constant *SignedPointer = CGM.getConstantSignedPointer(
1863ac9a064cSDimitry Andric UnsignedPointer, Key, StorageAddress, Discriminator);
1864ac9a064cSDimitry Andric
1865ac9a064cSDimitry Andric if (Schema.isAddressDiscriminated())
1866ac9a064cSDimitry Andric registerCurrentAddrPrivate(SignedPointer, StorageAddress);
1867ac9a064cSDimitry Andric
1868ac9a064cSDimitry Andric return SignedPointer;
1869ac9a064cSDimitry Andric }
1870ac9a064cSDimitry Andric
emitForMemory(CodeGenModule & CGM,llvm::Constant * C,QualType destType)1871461a67faSDimitry Andric llvm::Constant *ConstantEmitter::emitForMemory(CodeGenModule &CGM,
1872461a67faSDimitry Andric llvm::Constant *C,
1873461a67faSDimitry Andric QualType destType) {
1874461a67faSDimitry Andric // For an _Atomic-qualified constant, we may need to add tail padding.
1875461a67faSDimitry Andric if (auto AT = destType->getAs<AtomicType>()) {
1876461a67faSDimitry Andric QualType destValueType = AT->getValueType();
1877461a67faSDimitry Andric C = emitForMemory(CGM, C, destValueType);
1878461a67faSDimitry Andric
1879461a67faSDimitry Andric uint64_t innerSize = CGM.getContext().getTypeSize(destValueType);
1880461a67faSDimitry Andric uint64_t outerSize = CGM.getContext().getTypeSize(destType);
1881461a67faSDimitry Andric if (innerSize == outerSize)
1882461a67faSDimitry Andric return C;
1883461a67faSDimitry Andric
1884461a67faSDimitry Andric assert(innerSize < outerSize && "emitted over-large constant for atomic");
1885461a67faSDimitry Andric llvm::Constant *elts[] = {
1886461a67faSDimitry Andric C,
1887461a67faSDimitry Andric llvm::ConstantAggregateZero::get(
1888461a67faSDimitry Andric llvm::ArrayType::get(CGM.Int8Ty, (outerSize - innerSize) / 8))
1889461a67faSDimitry Andric };
1890461a67faSDimitry Andric return llvm::ConstantStruct::getAnon(elts);
1891461a67faSDimitry Andric }
1892461a67faSDimitry Andric
1893461a67faSDimitry Andric // Zero-extend bool.
18947fa27ce4SDimitry Andric if (C->getType()->isIntegerTy(1) && !destType->isBitIntType()) {
1895461a67faSDimitry Andric llvm::Type *boolTy = CGM.getTypes().ConvertTypeForMem(destType);
1896b1c73532SDimitry Andric llvm::Constant *Res = llvm::ConstantFoldCastOperand(
1897b1c73532SDimitry Andric llvm::Instruction::ZExt, C, boolTy, CGM.getDataLayout());
1898b1c73532SDimitry Andric assert(Res && "Constant folding must succeed");
1899b1c73532SDimitry Andric return Res;
1900461a67faSDimitry Andric }
1901461a67faSDimitry Andric
1902ac9a064cSDimitry Andric if (destType->isBitIntType()) {
1903ac9a064cSDimitry Andric ConstantAggregateBuilder Builder(CGM);
1904ac9a064cSDimitry Andric llvm::Type *LoadStoreTy = CGM.getTypes().convertTypeForLoadStore(destType);
1905ac9a064cSDimitry Andric // ptrtoint/inttoptr should not involve _BitInt in constant expressions, so
1906ac9a064cSDimitry Andric // casting to ConstantInt is safe here.
1907ac9a064cSDimitry Andric auto *CI = cast<llvm::ConstantInt>(C);
1908ac9a064cSDimitry Andric llvm::Constant *Res = llvm::ConstantFoldCastOperand(
1909ac9a064cSDimitry Andric destType->isSignedIntegerOrEnumerationType() ? llvm::Instruction::SExt
1910ac9a064cSDimitry Andric : llvm::Instruction::ZExt,
1911ac9a064cSDimitry Andric CI, LoadStoreTy, CGM.getDataLayout());
1912ac9a064cSDimitry Andric if (CGM.getTypes().typeRequiresSplitIntoByteArray(destType, C->getType())) {
1913ac9a064cSDimitry Andric // Long _BitInt has array of bytes as in-memory type.
1914ac9a064cSDimitry Andric // So, split constant into individual bytes.
1915ac9a064cSDimitry Andric llvm::Type *DesiredTy = CGM.getTypes().ConvertTypeForMem(destType);
1916ac9a064cSDimitry Andric llvm::APInt Value = cast<llvm::ConstantInt>(Res)->getValue();
1917ac9a064cSDimitry Andric Builder.addBits(Value, /*OffsetInBits=*/0, /*AllowOverwrite=*/false);
1918ac9a064cSDimitry Andric return Builder.build(DesiredTy, /*AllowOversized*/ false);
1919ac9a064cSDimitry Andric }
1920ac9a064cSDimitry Andric return Res;
1921ac9a064cSDimitry Andric }
1922ac9a064cSDimitry Andric
1923dbe13110SDimitry Andric return C;
1924dbe13110SDimitry Andric }
1925dbe13110SDimitry Andric
tryEmitPrivate(const Expr * E,QualType destType)1926461a67faSDimitry Andric llvm::Constant *ConstantEmitter::tryEmitPrivate(const Expr *E,
1927461a67faSDimitry Andric QualType destType) {
1928c0981da4SDimitry Andric assert(!destType->isVoidType() && "can't emit a void constant");
1929c0981da4SDimitry Andric
1930b1c73532SDimitry Andric if (!destType->isReferenceType())
1931ac9a064cSDimitry Andric if (llvm::Constant *C = ConstExprEmitter(*this).Visit(E, destType))
19327fa27ce4SDimitry Andric return C;
19337fa27ce4SDimitry Andric
1934ec2b103cSEd Schouten Expr::EvalResult Result;
1935ec2b103cSEd Schouten
1936ec2b103cSEd Schouten bool Success = false;
1937ec2b103cSEd Schouten
1938461a67faSDimitry Andric if (destType->isReferenceType())
1939461a67faSDimitry Andric Success = E->EvaluateAsLValue(Result, CGM.getContext());
1940ec2b103cSEd Schouten else
1941676fbe81SDimitry Andric Success = E->EvaluateAsRValue(Result, CGM.getContext(), InConstantContext);
1942ec2b103cSEd Schouten
1943dbe13110SDimitry Andric if (Success && !Result.HasSideEffects)
19447fa27ce4SDimitry Andric return tryEmitPrivate(Result.Val, destType);
1945dbe13110SDimitry Andric
19467fa27ce4SDimitry Andric return nullptr;
1947dbe13110SDimitry Andric }
1948dbe13110SDimitry Andric
getNullPointer(llvm::PointerType * T,QualType QT)1949bab175ecSDimitry Andric llvm::Constant *CodeGenModule::getNullPointer(llvm::PointerType *T, QualType QT) {
1950bab175ecSDimitry Andric return getTargetCodeGenInfo().getNullPointer(*this, T, QT);
1951bab175ecSDimitry Andric }
1952bab175ecSDimitry Andric
1953461a67faSDimitry Andric namespace {
1954461a67faSDimitry Andric /// A struct which can be used to peephole certain kinds of finalization
1955461a67faSDimitry Andric /// that normally happen during l-value emission.
1956461a67faSDimitry Andric struct ConstantLValue {
1957461a67faSDimitry Andric llvm::Constant *Value;
1958461a67faSDimitry Andric bool HasOffsetApplied;
19599f4dbff6SDimitry Andric
ConstantLValue__anon4cd729e60b11::ConstantLValue1960461a67faSDimitry Andric /*implicit*/ ConstantLValue(llvm::Constant *value,
1961461a67faSDimitry Andric bool hasOffsetApplied = false)
1962706b4fc4SDimitry Andric : Value(value), HasOffsetApplied(hasOffsetApplied) {}
19639f4dbff6SDimitry Andric
ConstantLValue__anon4cd729e60b11::ConstantLValue1964461a67faSDimitry Andric /*implicit*/ ConstantLValue(ConstantAddress address)
1965461a67faSDimitry Andric : ConstantLValue(address.getPointer()) {}
19669f4dbff6SDimitry Andric };
1967461a67faSDimitry Andric
1968461a67faSDimitry Andric /// A helper class for emitting constant l-values.
1969461a67faSDimitry Andric class ConstantLValueEmitter : public ConstStmtVisitor<ConstantLValueEmitter,
1970461a67faSDimitry Andric ConstantLValue> {
1971461a67faSDimitry Andric CodeGenModule &CGM;
1972461a67faSDimitry Andric ConstantEmitter &Emitter;
1973461a67faSDimitry Andric const APValue &Value;
1974461a67faSDimitry Andric QualType DestType;
1975ac9a064cSDimitry Andric bool EnablePtrAuthFunctionTypeDiscrimination;
1976461a67faSDimitry Andric
1977461a67faSDimitry Andric // Befriend StmtVisitorBase so that we don't have to expose Visit*.
1978461a67faSDimitry Andric friend StmtVisitorBase;
1979461a67faSDimitry Andric
1980461a67faSDimitry Andric public:
ConstantLValueEmitter(ConstantEmitter & emitter,const APValue & value,QualType destType,bool EnablePtrAuthFunctionTypeDiscrimination=true)1981461a67faSDimitry Andric ConstantLValueEmitter(ConstantEmitter &emitter, const APValue &value,
1982ac9a064cSDimitry Andric QualType destType,
1983ac9a064cSDimitry Andric bool EnablePtrAuthFunctionTypeDiscrimination = true)
1984ac9a064cSDimitry Andric : CGM(emitter.CGM), Emitter(emitter), Value(value), DestType(destType),
1985ac9a064cSDimitry Andric EnablePtrAuthFunctionTypeDiscrimination(
1986ac9a064cSDimitry Andric EnablePtrAuthFunctionTypeDiscrimination) {}
1987461a67faSDimitry Andric
1988461a67faSDimitry Andric llvm::Constant *tryEmit();
1989461a67faSDimitry Andric
1990461a67faSDimitry Andric private:
1991461a67faSDimitry Andric llvm::Constant *tryEmitAbsolute(llvm::Type *destTy);
1992461a67faSDimitry Andric ConstantLValue tryEmitBase(const APValue::LValueBase &base);
1993461a67faSDimitry Andric
VisitStmt(const Stmt * S)1994461a67faSDimitry Andric ConstantLValue VisitStmt(const Stmt *S) { return nullptr; }
1995676fbe81SDimitry Andric ConstantLValue VisitConstantExpr(const ConstantExpr *E);
1996461a67faSDimitry Andric ConstantLValue VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
1997461a67faSDimitry Andric ConstantLValue VisitStringLiteral(const StringLiteral *E);
199822989816SDimitry Andric ConstantLValue VisitObjCBoxedExpr(const ObjCBoxedExpr *E);
1999461a67faSDimitry Andric ConstantLValue VisitObjCEncodeExpr(const ObjCEncodeExpr *E);
2000461a67faSDimitry Andric ConstantLValue VisitObjCStringLiteral(const ObjCStringLiteral *E);
2001461a67faSDimitry Andric ConstantLValue VisitPredefinedExpr(const PredefinedExpr *E);
2002461a67faSDimitry Andric ConstantLValue VisitAddrLabelExpr(const AddrLabelExpr *E);
2003461a67faSDimitry Andric ConstantLValue VisitCallExpr(const CallExpr *E);
2004461a67faSDimitry Andric ConstantLValue VisitBlockExpr(const BlockExpr *E);
2005461a67faSDimitry Andric ConstantLValue VisitCXXTypeidExpr(const CXXTypeidExpr *E);
2006461a67faSDimitry Andric ConstantLValue VisitMaterializeTemporaryExpr(
2007461a67faSDimitry Andric const MaterializeTemporaryExpr *E);
2008461a67faSDimitry Andric
2009ac9a064cSDimitry Andric ConstantLValue emitPointerAuthSignConstant(const CallExpr *E);
2010ac9a064cSDimitry Andric llvm::Constant *emitPointerAuthPointer(const Expr *E);
2011ac9a064cSDimitry Andric unsigned emitPointerAuthKey(const Expr *E);
2012ac9a064cSDimitry Andric std::pair<llvm::Constant *, llvm::ConstantInt *>
2013ac9a064cSDimitry Andric emitPointerAuthDiscriminator(const Expr *E);
2014ac9a064cSDimitry Andric
hasNonZeroOffset() const2015461a67faSDimitry Andric bool hasNonZeroOffset() const {
2016461a67faSDimitry Andric return !Value.getLValueOffset().isZero();
20179f4dbff6SDimitry Andric }
20189f4dbff6SDimitry Andric
2019461a67faSDimitry Andric /// Return the value offset.
getOffset()2020461a67faSDimitry Andric llvm::Constant *getOffset() {
2021461a67faSDimitry Andric return llvm::ConstantInt::get(CGM.Int64Ty,
2022461a67faSDimitry Andric Value.getLValueOffset().getQuantity());
2023461a67faSDimitry Andric }
2024461a67faSDimitry Andric
2025461a67faSDimitry Andric /// Apply the value offset to the given constant.
applyOffset(llvm::Constant * C)2026461a67faSDimitry Andric llvm::Constant *applyOffset(llvm::Constant *C) {
2027461a67faSDimitry Andric if (!hasNonZeroOffset())
2028461a67faSDimitry Andric return C;
2029461a67faSDimitry Andric
2030b1c73532SDimitry Andric return llvm::ConstantExpr::getGetElementPtr(CGM.Int8Ty, C, getOffset());
2031461a67faSDimitry Andric }
2032461a67faSDimitry Andric };
2033461a67faSDimitry Andric
2034461a67faSDimitry Andric }
2035461a67faSDimitry Andric
tryEmit()2036461a67faSDimitry Andric llvm::Constant *ConstantLValueEmitter::tryEmit() {
2037461a67faSDimitry Andric const APValue::LValueBase &base = Value.getLValueBase();
2038461a67faSDimitry Andric
203922989816SDimitry Andric // The destination type should be a pointer or reference
2040461a67faSDimitry Andric // type, but it might also be a cast thereof.
2041461a67faSDimitry Andric //
2042461a67faSDimitry Andric // FIXME: the chain of casts required should be reflected in the APValue.
2043461a67faSDimitry Andric // We need this in order to correctly handle things like a ptrtoint of a
2044461a67faSDimitry Andric // non-zero null pointer and addrspace casts that aren't trivially
2045461a67faSDimitry Andric // represented in LLVM IR.
2046461a67faSDimitry Andric auto destTy = CGM.getTypes().ConvertTypeForMem(DestType);
2047461a67faSDimitry Andric assert(isa<llvm::IntegerType>(destTy) || isa<llvm::PointerType>(destTy));
2048461a67faSDimitry Andric
2049461a67faSDimitry Andric // If there's no base at all, this is a null or absolute pointer,
2050461a67faSDimitry Andric // possibly cast back to an integer type.
2051461a67faSDimitry Andric if (!base) {
2052461a67faSDimitry Andric return tryEmitAbsolute(destTy);
2053461a67faSDimitry Andric }
2054461a67faSDimitry Andric
2055461a67faSDimitry Andric // Otherwise, try to emit the base.
2056461a67faSDimitry Andric ConstantLValue result = tryEmitBase(base);
2057461a67faSDimitry Andric
2058461a67faSDimitry Andric // If that failed, we're done.
2059461a67faSDimitry Andric llvm::Constant *value = result.Value;
2060461a67faSDimitry Andric if (!value) return nullptr;
2061461a67faSDimitry Andric
2062461a67faSDimitry Andric // Apply the offset if necessary and not already done.
2063461a67faSDimitry Andric if (!result.HasOffsetApplied) {
2064461a67faSDimitry Andric value = applyOffset(value);
2065461a67faSDimitry Andric }
2066461a67faSDimitry Andric
2067461a67faSDimitry Andric // Convert to the appropriate type; this could be an lvalue for
2068461a67faSDimitry Andric // an integer. FIXME: performAddrSpaceCast
2069461a67faSDimitry Andric if (isa<llvm::PointerType>(destTy))
2070461a67faSDimitry Andric return llvm::ConstantExpr::getPointerCast(value, destTy);
2071461a67faSDimitry Andric
2072461a67faSDimitry Andric return llvm::ConstantExpr::getPtrToInt(value, destTy);
2073461a67faSDimitry Andric }
2074461a67faSDimitry Andric
2075461a67faSDimitry Andric /// Try to emit an absolute l-value, such as a null pointer or an integer
2076461a67faSDimitry Andric /// bitcast to pointer type.
2077461a67faSDimitry Andric llvm::Constant *
tryEmitAbsolute(llvm::Type * destTy)2078461a67faSDimitry Andric ConstantLValueEmitter::tryEmitAbsolute(llvm::Type *destTy) {
2079461a67faSDimitry Andric // If we're producing a pointer, this is easy.
208022989816SDimitry Andric auto destPtrTy = cast<llvm::PointerType>(destTy);
2081461a67faSDimitry Andric if (Value.isNullPointer()) {
2082461a67faSDimitry Andric // FIXME: integer offsets from non-zero null pointers.
2083461a67faSDimitry Andric return CGM.getNullPointer(destPtrTy, DestType);
2084461a67faSDimitry Andric }
2085461a67faSDimitry Andric
2086461a67faSDimitry Andric // Convert the integer to a pointer-sized integer before converting it
2087461a67faSDimitry Andric // to a pointer.
2088461a67faSDimitry Andric // FIXME: signedness depends on the original integer type.
2089461a67faSDimitry Andric auto intptrTy = CGM.getDataLayout().getIntPtrType(destPtrTy);
209022989816SDimitry Andric llvm::Constant *C;
2091b1c73532SDimitry Andric C = llvm::ConstantFoldIntegerCast(getOffset(), intptrTy, /*isSigned*/ false,
2092b1c73532SDimitry Andric CGM.getDataLayout());
2093b1c73532SDimitry Andric assert(C && "Must have folded, as Offset is a ConstantInt");
2094461a67faSDimitry Andric C = llvm::ConstantExpr::getIntToPtr(C, destPtrTy);
2095461a67faSDimitry Andric return C;
2096461a67faSDimitry Andric }
2097461a67faSDimitry Andric
2098461a67faSDimitry Andric ConstantLValue
tryEmitBase(const APValue::LValueBase & base)2099461a67faSDimitry Andric ConstantLValueEmitter::tryEmitBase(const APValue::LValueBase &base) {
2100461a67faSDimitry Andric // Handle values.
2101461a67faSDimitry Andric if (const ValueDecl *D = base.dyn_cast<const ValueDecl*>()) {
2102b60736ecSDimitry Andric // The constant always points to the canonical declaration. We want to look
2103b60736ecSDimitry Andric // at properties of the most recent declaration at the point of emission.
2104b60736ecSDimitry Andric D = cast<ValueDecl>(D->getMostRecentDecl());
2105b60736ecSDimitry Andric
2106461a67faSDimitry Andric if (D->hasAttr<WeakRefAttr>())
2107461a67faSDimitry Andric return CGM.GetWeakRefReference(D).getPointer();
2108461a67faSDimitry Andric
2109ac9a064cSDimitry Andric auto PtrAuthSign = [&](llvm::Constant *C) {
2110ac9a064cSDimitry Andric CGPointerAuthInfo AuthInfo;
2111461a67faSDimitry Andric
2112ac9a064cSDimitry Andric if (EnablePtrAuthFunctionTypeDiscrimination)
2113ac9a064cSDimitry Andric AuthInfo = CGM.getFunctionPointerAuthInfo(DestType);
2114ac9a064cSDimitry Andric
2115ac9a064cSDimitry Andric if (AuthInfo) {
2116ac9a064cSDimitry Andric if (hasNonZeroOffset())
2117ac9a064cSDimitry Andric return ConstantLValue(nullptr);
2118ac9a064cSDimitry Andric
2119ac9a064cSDimitry Andric C = applyOffset(C);
2120ac9a064cSDimitry Andric C = CGM.getConstantSignedPointer(
2121ac9a064cSDimitry Andric C, AuthInfo.getKey(), nullptr,
2122ac9a064cSDimitry Andric cast_or_null<llvm::ConstantInt>(AuthInfo.getDiscriminator()));
2123ac9a064cSDimitry Andric return ConstantLValue(C, /*applied offset*/ true);
2124ac9a064cSDimitry Andric }
2125ac9a064cSDimitry Andric
2126ac9a064cSDimitry Andric return ConstantLValue(C);
2127ac9a064cSDimitry Andric };
2128ac9a064cSDimitry Andric
2129ac9a064cSDimitry Andric if (const auto *FD = dyn_cast<FunctionDecl>(D))
2130ac9a064cSDimitry Andric return PtrAuthSign(CGM.getRawFunctionPointer(FD));
2131ac9a064cSDimitry Andric
2132ac9a064cSDimitry Andric if (const auto *VD = dyn_cast<VarDecl>(D)) {
2133461a67faSDimitry Andric // We can never refer to a variable with local storage.
2134461a67faSDimitry Andric if (!VD->hasLocalStorage()) {
2135461a67faSDimitry Andric if (VD->isFileVarDecl() || VD->hasExternalStorage())
2136461a67faSDimitry Andric return CGM.GetAddrOfGlobalVar(VD);
2137461a67faSDimitry Andric
2138461a67faSDimitry Andric if (VD->isLocalVarDecl()) {
2139461a67faSDimitry Andric return CGM.getOrCreateStaticVarDecl(
2140b1c73532SDimitry Andric *VD, CGM.getLLVMLinkageVarDefinition(VD));
2141461a67faSDimitry Andric }
2142461a67faSDimitry Andric }
2143461a67faSDimitry Andric }
2144461a67faSDimitry Andric
2145ac9a064cSDimitry Andric if (const auto *GD = dyn_cast<MSGuidDecl>(D))
2146cfca06d7SDimitry Andric return CGM.GetAddrOfMSGuidDecl(GD);
2147cfca06d7SDimitry Andric
2148ac9a064cSDimitry Andric if (const auto *GCD = dyn_cast<UnnamedGlobalConstantDecl>(D))
2149145449b1SDimitry Andric return CGM.GetAddrOfUnnamedGlobalConstantDecl(GCD);
2150145449b1SDimitry Andric
2151ac9a064cSDimitry Andric if (const auto *TPO = dyn_cast<TemplateParamObjectDecl>(D))
2152b60736ecSDimitry Andric return CGM.GetAddrOfTemplateParamObject(TPO);
2153b60736ecSDimitry Andric
2154461a67faSDimitry Andric return nullptr;
2155461a67faSDimitry Andric }
2156461a67faSDimitry Andric
215722989816SDimitry Andric // Handle typeid(T).
21587fa27ce4SDimitry Andric if (TypeInfoLValue TI = base.dyn_cast<TypeInfoLValue>())
21597fa27ce4SDimitry Andric return CGM.GetAddrOfRTTIDescriptor(QualType(TI.getType(), 0));
216022989816SDimitry Andric
2161461a67faSDimitry Andric // Otherwise, it must be an expression.
2162461a67faSDimitry Andric return Visit(base.get<const Expr*>());
2163461a67faSDimitry Andric }
2164461a67faSDimitry Andric
2165461a67faSDimitry Andric ConstantLValue
VisitConstantExpr(const ConstantExpr * E)2166676fbe81SDimitry Andric ConstantLValueEmitter::VisitConstantExpr(const ConstantExpr *E) {
2167cfca06d7SDimitry Andric if (llvm::Constant *Result = Emitter.tryEmitConstantExpr(E))
2168cfca06d7SDimitry Andric return Result;
2169676fbe81SDimitry Andric return Visit(E->getSubExpr());
2170676fbe81SDimitry Andric }
2171676fbe81SDimitry Andric
2172676fbe81SDimitry Andric ConstantLValue
VisitCompoundLiteralExpr(const CompoundLiteralExpr * E)2173461a67faSDimitry Andric ConstantLValueEmitter::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
2174e3b55780SDimitry Andric ConstantEmitter CompoundLiteralEmitter(CGM, Emitter.CGF);
2175e3b55780SDimitry Andric CompoundLiteralEmitter.setInConstantContext(Emitter.isInConstantContext());
2176e3b55780SDimitry Andric return tryEmitGlobalCompoundLiteral(CompoundLiteralEmitter, E);
2177461a67faSDimitry Andric }
2178461a67faSDimitry Andric
2179461a67faSDimitry Andric ConstantLValue
VisitStringLiteral(const StringLiteral * E)2180461a67faSDimitry Andric ConstantLValueEmitter::VisitStringLiteral(const StringLiteral *E) {
2181461a67faSDimitry Andric return CGM.GetAddrOfConstantStringFromLiteral(E);
2182461a67faSDimitry Andric }
2183461a67faSDimitry Andric
2184461a67faSDimitry Andric ConstantLValue
VisitObjCEncodeExpr(const ObjCEncodeExpr * E)2185461a67faSDimitry Andric ConstantLValueEmitter::VisitObjCEncodeExpr(const ObjCEncodeExpr *E) {
2186461a67faSDimitry Andric return CGM.GetAddrOfConstantStringFromObjCEncode(E);
2187461a67faSDimitry Andric }
2188461a67faSDimitry Andric
emitConstantObjCStringLiteral(const StringLiteral * S,QualType T,CodeGenModule & CGM)218922989816SDimitry Andric static ConstantLValue emitConstantObjCStringLiteral(const StringLiteral *S,
219022989816SDimitry Andric QualType T,
219122989816SDimitry Andric CodeGenModule &CGM) {
219222989816SDimitry Andric auto C = CGM.getObjCRuntime().GenerateConstantString(S);
21937fa27ce4SDimitry Andric return C.withElementType(CGM.getTypes().ConvertTypeForMem(T));
219422989816SDimitry Andric }
219522989816SDimitry Andric
2196461a67faSDimitry Andric ConstantLValue
VisitObjCStringLiteral(const ObjCStringLiteral * E)2197461a67faSDimitry Andric ConstantLValueEmitter::VisitObjCStringLiteral(const ObjCStringLiteral *E) {
219822989816SDimitry Andric return emitConstantObjCStringLiteral(E->getString(), E->getType(), CGM);
219922989816SDimitry Andric }
220022989816SDimitry Andric
220122989816SDimitry Andric ConstantLValue
VisitObjCBoxedExpr(const ObjCBoxedExpr * E)220222989816SDimitry Andric ConstantLValueEmitter::VisitObjCBoxedExpr(const ObjCBoxedExpr *E) {
220322989816SDimitry Andric assert(E->isExpressibleAsConstantInitializer() &&
220422989816SDimitry Andric "this boxed expression can't be emitted as a compile-time constant");
2205ac9a064cSDimitry Andric const auto *SL = cast<StringLiteral>(E->getSubExpr()->IgnoreParenCasts());
220622989816SDimitry Andric return emitConstantObjCStringLiteral(SL, E->getType(), CGM);
2207461a67faSDimitry Andric }
2208461a67faSDimitry Andric
2209461a67faSDimitry Andric ConstantLValue
VisitPredefinedExpr(const PredefinedExpr * E)2210461a67faSDimitry Andric ConstantLValueEmitter::VisitPredefinedExpr(const PredefinedExpr *E) {
221122989816SDimitry Andric return CGM.GetAddrOfConstantStringFromLiteral(E->getFunctionName());
2212461a67faSDimitry Andric }
2213461a67faSDimitry Andric
2214461a67faSDimitry Andric ConstantLValue
VisitAddrLabelExpr(const AddrLabelExpr * E)2215461a67faSDimitry Andric ConstantLValueEmitter::VisitAddrLabelExpr(const AddrLabelExpr *E) {
2216461a67faSDimitry Andric assert(Emitter.CGF && "Invalid address of label expression outside function");
2217461a67faSDimitry Andric llvm::Constant *Ptr = Emitter.CGF->GetAddrOfLabel(E->getLabel());
2218461a67faSDimitry Andric return Ptr;
2219461a67faSDimitry Andric }
2220461a67faSDimitry Andric
2221461a67faSDimitry Andric ConstantLValue
VisitCallExpr(const CallExpr * E)2222461a67faSDimitry Andric ConstantLValueEmitter::VisitCallExpr(const CallExpr *E) {
2223461a67faSDimitry Andric unsigned builtin = E->getBuiltinCallee();
222477fc4c14SDimitry Andric if (builtin == Builtin::BI__builtin_function_start)
222577fc4c14SDimitry Andric return CGM.GetFunctionStart(
222677fc4c14SDimitry Andric E->getArg(0)->getAsBuiltinConstantDeclRef(CGM.getContext()));
2227ac9a064cSDimitry Andric
2228ac9a064cSDimitry Andric if (builtin == Builtin::BI__builtin_ptrauth_sign_constant)
2229ac9a064cSDimitry Andric return emitPointerAuthSignConstant(E);
2230ac9a064cSDimitry Andric
2231461a67faSDimitry Andric if (builtin != Builtin::BI__builtin___CFStringMakeConstantString &&
2232461a67faSDimitry Andric builtin != Builtin::BI__builtin___NSStringMakeConstantString)
2233461a67faSDimitry Andric return nullptr;
2234461a67faSDimitry Andric
2235ac9a064cSDimitry Andric const auto *Literal = cast<StringLiteral>(E->getArg(0)->IgnoreParenCasts());
2236461a67faSDimitry Andric if (builtin == Builtin::BI__builtin___NSStringMakeConstantString) {
2237ac9a064cSDimitry Andric return CGM.getObjCRuntime().GenerateConstantString(Literal);
2238461a67faSDimitry Andric } else {
2239461a67faSDimitry Andric // FIXME: need to deal with UCN conversion issues.
2240ac9a064cSDimitry Andric return CGM.GetAddrOfConstantCFString(Literal);
2241461a67faSDimitry Andric }
2242461a67faSDimitry Andric }
2243461a67faSDimitry Andric
2244461a67faSDimitry Andric ConstantLValue
emitPointerAuthSignConstant(const CallExpr * E)2245ac9a064cSDimitry Andric ConstantLValueEmitter::emitPointerAuthSignConstant(const CallExpr *E) {
2246ac9a064cSDimitry Andric llvm::Constant *UnsignedPointer = emitPointerAuthPointer(E->getArg(0));
2247ac9a064cSDimitry Andric unsigned Key = emitPointerAuthKey(E->getArg(1));
2248ac9a064cSDimitry Andric auto [StorageAddress, OtherDiscriminator] =
2249ac9a064cSDimitry Andric emitPointerAuthDiscriminator(E->getArg(2));
2250ac9a064cSDimitry Andric
2251ac9a064cSDimitry Andric llvm::Constant *SignedPointer = CGM.getConstantSignedPointer(
2252ac9a064cSDimitry Andric UnsignedPointer, Key, StorageAddress, OtherDiscriminator);
2253ac9a064cSDimitry Andric return SignedPointer;
2254ac9a064cSDimitry Andric }
2255ac9a064cSDimitry Andric
emitPointerAuthPointer(const Expr * E)2256ac9a064cSDimitry Andric llvm::Constant *ConstantLValueEmitter::emitPointerAuthPointer(const Expr *E) {
2257ac9a064cSDimitry Andric Expr::EvalResult Result;
2258ac9a064cSDimitry Andric bool Succeeded = E->EvaluateAsRValue(Result, CGM.getContext());
2259ac9a064cSDimitry Andric assert(Succeeded);
2260ac9a064cSDimitry Andric (void)Succeeded;
2261ac9a064cSDimitry Andric
2262ac9a064cSDimitry Andric // The assertions here are all checked by Sema.
2263ac9a064cSDimitry Andric assert(Result.Val.isLValue());
2264ac9a064cSDimitry Andric if (isa<FunctionDecl>(Result.Val.getLValueBase().get<const ValueDecl *>()))
2265ac9a064cSDimitry Andric assert(Result.Val.getLValueOffset().isZero());
2266ac9a064cSDimitry Andric return ConstantEmitter(CGM, Emitter.CGF)
2267ac9a064cSDimitry Andric .emitAbstract(E->getExprLoc(), Result.Val, E->getType(), false);
2268ac9a064cSDimitry Andric }
2269ac9a064cSDimitry Andric
emitPointerAuthKey(const Expr * E)2270ac9a064cSDimitry Andric unsigned ConstantLValueEmitter::emitPointerAuthKey(const Expr *E) {
2271ac9a064cSDimitry Andric return E->EvaluateKnownConstInt(CGM.getContext()).getZExtValue();
2272ac9a064cSDimitry Andric }
2273ac9a064cSDimitry Andric
2274ac9a064cSDimitry Andric std::pair<llvm::Constant *, llvm::ConstantInt *>
emitPointerAuthDiscriminator(const Expr * E)2275ac9a064cSDimitry Andric ConstantLValueEmitter::emitPointerAuthDiscriminator(const Expr *E) {
2276ac9a064cSDimitry Andric E = E->IgnoreParens();
2277ac9a064cSDimitry Andric
2278ac9a064cSDimitry Andric if (const auto *Call = dyn_cast<CallExpr>(E)) {
2279ac9a064cSDimitry Andric if (Call->getBuiltinCallee() ==
2280ac9a064cSDimitry Andric Builtin::BI__builtin_ptrauth_blend_discriminator) {
2281ac9a064cSDimitry Andric llvm::Constant *Pointer = ConstantEmitter(CGM).emitAbstract(
2282ac9a064cSDimitry Andric Call->getArg(0), Call->getArg(0)->getType());
2283ac9a064cSDimitry Andric auto *Extra = cast<llvm::ConstantInt>(ConstantEmitter(CGM).emitAbstract(
2284ac9a064cSDimitry Andric Call->getArg(1), Call->getArg(1)->getType()));
2285ac9a064cSDimitry Andric return {Pointer, Extra};
2286ac9a064cSDimitry Andric }
2287ac9a064cSDimitry Andric }
2288ac9a064cSDimitry Andric
2289ac9a064cSDimitry Andric llvm::Constant *Result = ConstantEmitter(CGM).emitAbstract(E, E->getType());
2290ac9a064cSDimitry Andric if (Result->getType()->isPointerTy())
2291ac9a064cSDimitry Andric return {Result, nullptr};
2292ac9a064cSDimitry Andric return {nullptr, cast<llvm::ConstantInt>(Result)};
2293ac9a064cSDimitry Andric }
2294ac9a064cSDimitry Andric
2295ac9a064cSDimitry Andric ConstantLValue
VisitBlockExpr(const BlockExpr * E)2296461a67faSDimitry Andric ConstantLValueEmitter::VisitBlockExpr(const BlockExpr *E) {
2297461a67faSDimitry Andric StringRef functionName;
2298461a67faSDimitry Andric if (auto CGF = Emitter.CGF)
2299461a67faSDimitry Andric functionName = CGF->CurFn->getName();
2300461a67faSDimitry Andric else
2301461a67faSDimitry Andric functionName = "global";
2302461a67faSDimitry Andric
2303461a67faSDimitry Andric return CGM.GetAddrOfGlobalBlock(E, functionName);
2304461a67faSDimitry Andric }
2305461a67faSDimitry Andric
2306461a67faSDimitry Andric ConstantLValue
VisitCXXTypeidExpr(const CXXTypeidExpr * E)2307461a67faSDimitry Andric ConstantLValueEmitter::VisitCXXTypeidExpr(const CXXTypeidExpr *E) {
2308461a67faSDimitry Andric QualType T;
2309461a67faSDimitry Andric if (E->isTypeOperand())
2310461a67faSDimitry Andric T = E->getTypeOperand(CGM.getContext());
2311461a67faSDimitry Andric else
2312461a67faSDimitry Andric T = E->getExprOperand()->getType();
2313461a67faSDimitry Andric return CGM.GetAddrOfRTTIDescriptor(T);
2314461a67faSDimitry Andric }
2315461a67faSDimitry Andric
2316461a67faSDimitry Andric ConstantLValue
VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr * E)2317461a67faSDimitry Andric ConstantLValueEmitter::VisitMaterializeTemporaryExpr(
2318461a67faSDimitry Andric const MaterializeTemporaryExpr *E) {
2319461a67faSDimitry Andric assert(E->getStorageDuration() == SD_Static);
2320ac9a064cSDimitry Andric const Expr *Inner = E->getSubExpr()->skipRValueSubobjectAdjustments();
2321461a67faSDimitry Andric return CGM.GetAddrOfGlobalTemporary(E, Inner);
2322461a67faSDimitry Andric }
2323461a67faSDimitry Andric
2324ac9a064cSDimitry Andric llvm::Constant *
tryEmitPrivate(const APValue & Value,QualType DestType,bool EnablePtrAuthFunctionTypeDiscrimination)2325ac9a064cSDimitry Andric ConstantEmitter::tryEmitPrivate(const APValue &Value, QualType DestType,
2326ac9a064cSDimitry Andric bool EnablePtrAuthFunctionTypeDiscrimination) {
2327dbe13110SDimitry Andric switch (Value.getKind()) {
232822989816SDimitry Andric case APValue::None:
232922989816SDimitry Andric case APValue::Indeterminate:
233022989816SDimitry Andric // Out-of-lifetime and indeterminate values can be modeled as 'undef'.
233122989816SDimitry Andric return llvm::UndefValue::get(CGM.getTypes().ConvertType(DestType));
2332461a67faSDimitry Andric case APValue::LValue:
2333ac9a064cSDimitry Andric return ConstantLValueEmitter(*this, Value, DestType,
2334ac9a064cSDimitry Andric EnablePtrAuthFunctionTypeDiscrimination)
2335ac9a064cSDimitry Andric .tryEmit();
2336dbe13110SDimitry Andric case APValue::Int:
2337461a67faSDimitry Andric return llvm::ConstantInt::get(CGM.getLLVMContext(), Value.getInt());
233822989816SDimitry Andric case APValue::FixedPoint:
233922989816SDimitry Andric return llvm::ConstantInt::get(CGM.getLLVMContext(),
234022989816SDimitry Andric Value.getFixedPoint().getValue());
2341ec2b103cSEd Schouten case APValue::ComplexInt: {
2342ec2b103cSEd Schouten llvm::Constant *Complex[2];
2343ec2b103cSEd Schouten
2344461a67faSDimitry Andric Complex[0] = llvm::ConstantInt::get(CGM.getLLVMContext(),
2345dbe13110SDimitry Andric Value.getComplexIntReal());
2346461a67faSDimitry Andric Complex[1] = llvm::ConstantInt::get(CGM.getLLVMContext(),
2347dbe13110SDimitry Andric Value.getComplexIntImag());
2348ec2b103cSEd Schouten
23494c8b2481SRoman Divacky // FIXME: the target may want to specify that this is packed.
23502410013dSDimitry Andric llvm::StructType *STy =
23512410013dSDimitry Andric llvm::StructType::get(Complex[0]->getType(), Complex[1]->getType());
2352180abc3dSDimitry Andric return llvm::ConstantStruct::get(STy, Complex);
2353ec2b103cSEd Schouten }
235436981b17SDimitry Andric case APValue::Float: {
2355dbe13110SDimitry Andric const llvm::APFloat &Init = Value.getFloat();
2356bab175ecSDimitry Andric if (&Init.getSemantics() == &llvm::APFloat::IEEEhalf() &&
2357461a67faSDimitry Andric !CGM.getContext().getLangOpts().NativeHalfType &&
2358461a67faSDimitry Andric CGM.getContext().getTargetInfo().useFP16ConversionIntrinsics())
2359461a67faSDimitry Andric return llvm::ConstantInt::get(CGM.getLLVMContext(),
2360461a67faSDimitry Andric Init.bitcastToAPInt());
236136981b17SDimitry Andric else
2362461a67faSDimitry Andric return llvm::ConstantFP::get(CGM.getLLVMContext(), Init);
236336981b17SDimitry Andric }
2364ec2b103cSEd Schouten case APValue::ComplexFloat: {
2365ec2b103cSEd Schouten llvm::Constant *Complex[2];
2366ec2b103cSEd Schouten
2367461a67faSDimitry Andric Complex[0] = llvm::ConstantFP::get(CGM.getLLVMContext(),
2368dbe13110SDimitry Andric Value.getComplexFloatReal());
2369461a67faSDimitry Andric Complex[1] = llvm::ConstantFP::get(CGM.getLLVMContext(),
2370dbe13110SDimitry Andric Value.getComplexFloatImag());
2371ec2b103cSEd Schouten
23724c8b2481SRoman Divacky // FIXME: the target may want to specify that this is packed.
23732410013dSDimitry Andric llvm::StructType *STy =
23742410013dSDimitry Andric llvm::StructType::get(Complex[0]->getType(), Complex[1]->getType());
2375180abc3dSDimitry Andric return llvm::ConstantStruct::get(STy, Complex);
2376ec2b103cSEd Schouten }
2377ec2b103cSEd Schouten case APValue::Vector: {
2378dbe13110SDimitry Andric unsigned NumElts = Value.getVectorLength();
237945b53394SDimitry Andric SmallVector<llvm::Constant *, 4> Inits(NumElts);
2380ec2b103cSEd Schouten
238145b53394SDimitry Andric for (unsigned I = 0; I != NumElts; ++I) {
238245b53394SDimitry Andric const APValue &Elt = Value.getVectorElt(I);
2383ec2b103cSEd Schouten if (Elt.isInt())
2384461a67faSDimitry Andric Inits[I] = llvm::ConstantInt::get(CGM.getLLVMContext(), Elt.getInt());
238545b53394SDimitry Andric else if (Elt.isFloat())
2386461a67faSDimitry Andric Inits[I] = llvm::ConstantFP::get(CGM.getLLVMContext(), Elt.getFloat());
2387b1c73532SDimitry Andric else if (Elt.isIndeterminate())
2388b1c73532SDimitry Andric Inits[I] = llvm::UndefValue::get(CGM.getTypes().ConvertType(
2389b1c73532SDimitry Andric DestType->castAs<VectorType>()->getElementType()));
2390ec2b103cSEd Schouten else
239145b53394SDimitry Andric llvm_unreachable("unsupported vector element type");
2392ec2b103cSEd Schouten }
2393bca07a45SDimitry Andric return llvm::ConstantVector::get(Inits);
2394ec2b103cSEd Schouten }
2395dbe13110SDimitry Andric case APValue::AddrLabelDiff: {
2396dbe13110SDimitry Andric const AddrLabelExpr *LHSExpr = Value.getAddrLabelDiffLHS();
2397dbe13110SDimitry Andric const AddrLabelExpr *RHSExpr = Value.getAddrLabelDiffRHS();
2398461a67faSDimitry Andric llvm::Constant *LHS = tryEmitPrivate(LHSExpr, LHSExpr->getType());
2399461a67faSDimitry Andric llvm::Constant *RHS = tryEmitPrivate(RHSExpr, RHSExpr->getType());
2400461a67faSDimitry Andric if (!LHS || !RHS) return nullptr;
2401dbe13110SDimitry Andric
2402dbe13110SDimitry Andric // Compute difference
2403461a67faSDimitry Andric llvm::Type *ResultType = CGM.getTypes().ConvertType(DestType);
2404461a67faSDimitry Andric LHS = llvm::ConstantExpr::getPtrToInt(LHS, CGM.IntPtrTy);
2405461a67faSDimitry Andric RHS = llvm::ConstantExpr::getPtrToInt(RHS, CGM.IntPtrTy);
2406dbe13110SDimitry Andric llvm::Constant *AddrLabelDiff = llvm::ConstantExpr::getSub(LHS, RHS);
2407dbe13110SDimitry Andric
2408dbe13110SDimitry Andric // LLVM is a bit sensitive about the exact format of the
2409dbe13110SDimitry Andric // address-of-label difference; make sure to truncate after
2410dbe13110SDimitry Andric // the subtraction.
2411dbe13110SDimitry Andric return llvm::ConstantExpr::getTruncOrBitCast(AddrLabelDiff, ResultType);
2412ec2b103cSEd Schouten }
2413dbe13110SDimitry Andric case APValue::Struct:
2414dbe13110SDimitry Andric case APValue::Union:
2415461a67faSDimitry Andric return ConstStructBuilder::BuildStruct(*this, Value, DestType);
2416dbe13110SDimitry Andric case APValue::Array: {
2417b60736ecSDimitry Andric const ArrayType *ArrayTy = CGM.getContext().getAsArrayType(DestType);
2418dbe13110SDimitry Andric unsigned NumElements = Value.getArraySize();
2419dbe13110SDimitry Andric unsigned NumInitElts = Value.getArrayInitializedElts();
2420dbe13110SDimitry Andric
2421dbe13110SDimitry Andric // Emit array filler, if there is one.
24229f4dbff6SDimitry Andric llvm::Constant *Filler = nullptr;
242348675466SDimitry Andric if (Value.hasArrayFiller()) {
2424461a67faSDimitry Andric Filler = tryEmitAbstractForMemory(Value.getArrayFiller(),
2425b60736ecSDimitry Andric ArrayTy->getElementType());
242648675466SDimitry Andric if (!Filler)
242748675466SDimitry Andric return nullptr;
242848675466SDimitry Andric }
2429dbe13110SDimitry Andric
2430dbe13110SDimitry Andric // Emit initializer elements.
2431461a67faSDimitry Andric SmallVector<llvm::Constant*, 16> Elts;
243248675466SDimitry Andric if (Filler && Filler->isNullValue())
243348675466SDimitry Andric Elts.reserve(NumInitElts + 1);
243448675466SDimitry Andric else
243506d4ba38SDimitry Andric Elts.reserve(NumElements);
243648675466SDimitry Andric
243748675466SDimitry Andric llvm::Type *CommonElementType = nullptr;
243848675466SDimitry Andric for (unsigned I = 0; I < NumInitElts; ++I) {
243948675466SDimitry Andric llvm::Constant *C = tryEmitPrivateForMemory(
2440b60736ecSDimitry Andric Value.getArrayInitializedElt(I), ArrayTy->getElementType());
2441461a67faSDimitry Andric if (!C) return nullptr;
2442461a67faSDimitry Andric
2443dbe13110SDimitry Andric if (I == 0)
2444dbe13110SDimitry Andric CommonElementType = C->getType();
2445dbe13110SDimitry Andric else if (C->getType() != CommonElementType)
24469f4dbff6SDimitry Andric CommonElementType = nullptr;
2447dbe13110SDimitry Andric Elts.push_back(C);
2448ec2b103cSEd Schouten }
2449ec2b103cSEd Schouten
245022989816SDimitry Andric llvm::ArrayType *Desired =
245122989816SDimitry Andric cast<llvm::ArrayType>(CGM.getTypes().ConvertType(DestType));
24527fa27ce4SDimitry Andric
24537fa27ce4SDimitry Andric // Fix the type of incomplete arrays if the initializer isn't empty.
24547fa27ce4SDimitry Andric if (DestType->isIncompleteArrayType() && !Elts.empty())
24557fa27ce4SDimitry Andric Desired = llvm::ArrayType::get(Desired->getElementType(), Elts.size());
24567fa27ce4SDimitry Andric
245722989816SDimitry Andric return EmitArrayConstant(CGM, Desired, CommonElementType, NumElements, Elts,
245848675466SDimitry Andric Filler);
2459dbe13110SDimitry Andric }
2460dbe13110SDimitry Andric case APValue::MemberPointer:
2461461a67faSDimitry Andric return CGM.getCXXABI().EmitMemberPointer(Value, DestType);
2462dbe13110SDimitry Andric }
2463dbe13110SDimitry Andric llvm_unreachable("Unknown APValue kind");
2464dbe13110SDimitry Andric }
2465dbe13110SDimitry Andric
getAddrOfConstantCompoundLiteralIfEmitted(const CompoundLiteralExpr * E)2466bab175ecSDimitry Andric llvm::GlobalVariable *CodeGenModule::getAddrOfConstantCompoundLiteralIfEmitted(
2467bab175ecSDimitry Andric const CompoundLiteralExpr *E) {
2468bab175ecSDimitry Andric return EmittedCompoundLiterals.lookup(E);
2469bab175ecSDimitry Andric }
2470bab175ecSDimitry Andric
setAddrOfConstantCompoundLiteral(const CompoundLiteralExpr * CLE,llvm::GlobalVariable * GV)2471bab175ecSDimitry Andric void CodeGenModule::setAddrOfConstantCompoundLiteral(
2472bab175ecSDimitry Andric const CompoundLiteralExpr *CLE, llvm::GlobalVariable *GV) {
2473bab175ecSDimitry Andric bool Ok = EmittedCompoundLiterals.insert(std::make_pair(CLE, GV)).second;
2474bab175ecSDimitry Andric (void)Ok;
2475bab175ecSDimitry Andric assert(Ok && "CLE has already been emitted!");
2476bab175ecSDimitry Andric }
2477bab175ecSDimitry Andric
247845b53394SDimitry Andric ConstantAddress
GetAddrOfConstantCompoundLiteral(const CompoundLiteralExpr * E)2479dbe13110SDimitry Andric CodeGenModule::GetAddrOfConstantCompoundLiteral(const CompoundLiteralExpr *E) {
2480dbe13110SDimitry Andric assert(E->isFileScope() && "not a file-scope compound literal expr");
2481e3b55780SDimitry Andric ConstantEmitter emitter(*this);
2482e3b55780SDimitry Andric return tryEmitGlobalCompoundLiteral(emitter, E);
2483bca07a45SDimitry Andric }
2484bca07a45SDimitry Andric
2485bca07a45SDimitry Andric llvm::Constant *
getMemberPointerConstant(const UnaryOperator * uo)2486bca07a45SDimitry Andric CodeGenModule::getMemberPointerConstant(const UnaryOperator *uo) {
2487bca07a45SDimitry Andric // Member pointer constants always have a very particular form.
2488bca07a45SDimitry Andric const MemberPointerType *type = cast<MemberPointerType>(uo->getType());
2489bca07a45SDimitry Andric const ValueDecl *decl = cast<DeclRefExpr>(uo->getSubExpr())->getDecl();
2490bca07a45SDimitry Andric
2491bca07a45SDimitry Andric // A member function pointer.
2492bca07a45SDimitry Andric if (const CXXMethodDecl *method = dyn_cast<CXXMethodDecl>(decl))
2493c192b3dcSDimitry Andric return getCXXABI().EmitMemberFunctionPointer(method);
2494bca07a45SDimitry Andric
2495bca07a45SDimitry Andric // Otherwise, a member data pointer.
2496dbe13110SDimitry Andric uint64_t fieldOffset = getContext().getFieldOffset(decl);
2497bca07a45SDimitry Andric CharUnits chars = getContext().toCharUnitsFromBits((int64_t) fieldOffset);
2498bca07a45SDimitry Andric return getCXXABI().EmitMemberDataPointer(type, chars);
2499bca07a45SDimitry Andric }
2500bca07a45SDimitry Andric
2501bca07a45SDimitry Andric static llvm::Constant *EmitNullConstantForBase(CodeGenModule &CGM,
250236981b17SDimitry Andric llvm::Type *baseType,
2503bca07a45SDimitry Andric const CXXRecordDecl *base);
2504bca07a45SDimitry Andric
EmitNullConstant(CodeGenModule & CGM,const RecordDecl * record,bool asCompleteObject)2505bca07a45SDimitry Andric static llvm::Constant *EmitNullConstant(CodeGenModule &CGM,
2506bab175ecSDimitry Andric const RecordDecl *record,
2507bca07a45SDimitry Andric bool asCompleteObject) {
2508bca07a45SDimitry Andric const CGRecordLayout &layout = CGM.getTypes().getCGRecordLayout(record);
250936981b17SDimitry Andric llvm::StructType *structure =
2510bca07a45SDimitry Andric (asCompleteObject ? layout.getLLVMType()
2511bca07a45SDimitry Andric : layout.getBaseSubobjectLLVMType());
2512bca07a45SDimitry Andric
2513bca07a45SDimitry Andric unsigned numElements = structure->getNumElements();
2514bca07a45SDimitry Andric std::vector<llvm::Constant *> elements(numElements);
2515bca07a45SDimitry Andric
2516bab175ecSDimitry Andric auto CXXR = dyn_cast<CXXRecordDecl>(record);
2517bca07a45SDimitry Andric // Fill in all the bases.
2518bab175ecSDimitry Andric if (CXXR) {
2519bab175ecSDimitry Andric for (const auto &I : CXXR->bases()) {
25209f4dbff6SDimitry Andric if (I.isVirtual()) {
2521bca07a45SDimitry Andric // Ignore virtual bases; if we're laying out for a complete
2522bca07a45SDimitry Andric // object, we'll lay these out later.
2523bca07a45SDimitry Andric continue;
2524bca07a45SDimitry Andric }
2525bca07a45SDimitry Andric
2526bca07a45SDimitry Andric const CXXRecordDecl *base =
25279f4dbff6SDimitry Andric cast<CXXRecordDecl>(I.getType()->castAs<RecordType>()->getDecl());
2528bca07a45SDimitry Andric
2529bca07a45SDimitry Andric // Ignore empty bases.
2530ac9a064cSDimitry Andric if (isEmptyRecordForLayout(CGM.getContext(), I.getType()) ||
2531ac9a064cSDimitry Andric CGM.getContext()
2532ac9a064cSDimitry Andric .getASTRecordLayout(base)
2533ac9a064cSDimitry Andric .getNonVirtualSize()
2534bab175ecSDimitry Andric .isZero())
2535bca07a45SDimitry Andric continue;
2536bca07a45SDimitry Andric
2537bca07a45SDimitry Andric unsigned fieldIndex = layout.getNonVirtualBaseLLVMFieldNo(base);
253836981b17SDimitry Andric llvm::Type *baseType = structure->getElementType(fieldIndex);
2539bca07a45SDimitry Andric elements[fieldIndex] = EmitNullConstantForBase(CGM, baseType, base);
2540bca07a45SDimitry Andric }
2541bab175ecSDimitry Andric }
2542bca07a45SDimitry Andric
2543bca07a45SDimitry Andric // Fill in all the fields.
25449f4dbff6SDimitry Andric for (const auto *Field : record->fields()) {
2545dbe13110SDimitry Andric // Fill in non-bitfields. (Bitfields always use a zero pattern, which we
2546dbe13110SDimitry Andric // will fill in later.)
2547ac9a064cSDimitry Andric if (!Field->isBitField() &&
2548ac9a064cSDimitry Andric !isEmptyFieldForLayout(CGM.getContext(), Field)) {
25499f4dbff6SDimitry Andric unsigned fieldIndex = layout.getLLVMFieldNo(Field);
25509f4dbff6SDimitry Andric elements[fieldIndex] = CGM.EmitNullConstant(Field->getType());
2551bca07a45SDimitry Andric }
2552bca07a45SDimitry Andric
2553dbe13110SDimitry Andric // For unions, stop after the first named field.
2554798321d8SDimitry Andric if (record->isUnion()) {
2555798321d8SDimitry Andric if (Field->getIdentifier())
2556dbe13110SDimitry Andric break;
2557c7e70c43SDimitry Andric if (const auto *FieldRD = Field->getType()->getAsRecordDecl())
2558798321d8SDimitry Andric if (FieldRD->findFirstNamedDataMember())
2559798321d8SDimitry Andric break;
2560798321d8SDimitry Andric }
2561dbe13110SDimitry Andric }
2562dbe13110SDimitry Andric
2563bca07a45SDimitry Andric // Fill in the virtual bases, if we're working with the complete object.
2564bab175ecSDimitry Andric if (CXXR && asCompleteObject) {
2565bab175ecSDimitry Andric for (const auto &I : CXXR->vbases()) {
2566bca07a45SDimitry Andric const CXXRecordDecl *base =
25679f4dbff6SDimitry Andric cast<CXXRecordDecl>(I.getType()->castAs<RecordType>()->getDecl());
2568bca07a45SDimitry Andric
2569bca07a45SDimitry Andric // Ignore empty bases.
2570ac9a064cSDimitry Andric if (isEmptyRecordForLayout(CGM.getContext(), I.getType()))
2571bca07a45SDimitry Andric continue;
2572bca07a45SDimitry Andric
2573bca07a45SDimitry Andric unsigned fieldIndex = layout.getVirtualBaseIndex(base);
2574bca07a45SDimitry Andric
2575bca07a45SDimitry Andric // We might have already laid this field out.
2576bca07a45SDimitry Andric if (elements[fieldIndex]) continue;
2577bca07a45SDimitry Andric
257836981b17SDimitry Andric llvm::Type *baseType = structure->getElementType(fieldIndex);
2579bca07a45SDimitry Andric elements[fieldIndex] = EmitNullConstantForBase(CGM, baseType, base);
2580bca07a45SDimitry Andric }
2581bca07a45SDimitry Andric }
2582bca07a45SDimitry Andric
2583bca07a45SDimitry Andric // Now go through all other fields and zero them out.
2584bca07a45SDimitry Andric for (unsigned i = 0; i != numElements; ++i) {
2585bca07a45SDimitry Andric if (!elements[i])
2586bca07a45SDimitry Andric elements[i] = llvm::Constant::getNullValue(structure->getElementType(i));
2587bca07a45SDimitry Andric }
2588bca07a45SDimitry Andric
2589bca07a45SDimitry Andric return llvm::ConstantStruct::get(structure, elements);
2590bca07a45SDimitry Andric }
2591bca07a45SDimitry Andric
2592bca07a45SDimitry Andric /// Emit the null constant for a base subobject.
EmitNullConstantForBase(CodeGenModule & CGM,llvm::Type * baseType,const CXXRecordDecl * base)2593bca07a45SDimitry Andric static llvm::Constant *EmitNullConstantForBase(CodeGenModule &CGM,
259436981b17SDimitry Andric llvm::Type *baseType,
2595bca07a45SDimitry Andric const CXXRecordDecl *base) {
2596bca07a45SDimitry Andric const CGRecordLayout &baseLayout = CGM.getTypes().getCGRecordLayout(base);
2597bca07a45SDimitry Andric
2598bca07a45SDimitry Andric // Just zero out bases that don't have any pointer to data members.
2599bca07a45SDimitry Andric if (baseLayout.isZeroInitializableAsBase())
2600bca07a45SDimitry Andric return llvm::Constant::getNullValue(baseType);
2601bca07a45SDimitry Andric
260206d4ba38SDimitry Andric // Otherwise, we can just use its null constant.
260306d4ba38SDimitry Andric return EmitNullConstant(CGM, base, /*asCompleteObject=*/false);
2604bca07a45SDimitry Andric }
2605bca07a45SDimitry Andric
emitNullForMemory(CodeGenModule & CGM,QualType T)2606461a67faSDimitry Andric llvm::Constant *ConstantEmitter::emitNullForMemory(CodeGenModule &CGM,
2607461a67faSDimitry Andric QualType T) {
2608461a67faSDimitry Andric return emitForMemory(CGM, CGM.EmitNullConstant(T), T);
2609461a67faSDimitry Andric }
2610461a67faSDimitry Andric
EmitNullConstant(QualType T)2611ec2b103cSEd Schouten llvm::Constant *CodeGenModule::EmitNullConstant(QualType T) {
2612bab175ecSDimitry Andric if (T->getAs<PointerType>())
2613bab175ecSDimitry Andric return getNullPointer(
2614bab175ecSDimitry Andric cast<llvm::PointerType>(getTypes().ConvertTypeForMem(T)), T);
2615bab175ecSDimitry Andric
26163d1dcd9bSDimitry Andric if (getTypes().isZeroInitializable(T))
26174c8b2481SRoman Divacky return llvm::Constant::getNullValue(getTypes().ConvertTypeForMem(T));
26184c8b2481SRoman Divacky
26194c8b2481SRoman Divacky if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(T)) {
2620dbe13110SDimitry Andric llvm::ArrayType *ATy =
2621dbe13110SDimitry Andric cast<llvm::ArrayType>(getTypes().ConvertTypeForMem(T));
26224c8b2481SRoman Divacky
26234c8b2481SRoman Divacky QualType ElementTy = CAT->getElementType();
26244c8b2481SRoman Divacky
2625461a67faSDimitry Andric llvm::Constant *Element =
2626461a67faSDimitry Andric ConstantEmitter::emitNullForMemory(*this, ElementTy);
2627ac9a064cSDimitry Andric unsigned NumElements = CAT->getZExtSize();
2628dbe13110SDimitry Andric SmallVector<llvm::Constant *, 8> Array(NumElements, Element);
26294c8b2481SRoman Divacky return llvm::ConstantArray::get(ATy, Array);
26304c8b2481SRoman Divacky }
26314c8b2481SRoman Divacky
2632bab175ecSDimitry Andric if (const RecordType *RT = T->getAs<RecordType>())
2633bab175ecSDimitry Andric return ::EmitNullConstant(*this, RT->getDecl(), /*complete object*/ true);
2634ecb7e5c8SRoman Divacky
26355e20cdd8SDimitry Andric assert(T->isMemberDataPointerType() &&
2636ecb7e5c8SRoman Divacky "Should only see pointers to data members here!");
2637ecb7e5c8SRoman Divacky
2638bca07a45SDimitry Andric return getCXXABI().EmitNullMemberPointer(T->castAs<MemberPointerType>());
2639ecb7e5c8SRoman Divacky }
264036981b17SDimitry Andric
264136981b17SDimitry Andric llvm::Constant *
EmitNullConstantForBase(const CXXRecordDecl * Record)264236981b17SDimitry Andric CodeGenModule::EmitNullConstantForBase(const CXXRecordDecl *Record) {
264336981b17SDimitry Andric return ::EmitNullConstant(*this, Record, false);
264436981b17SDimitry Andric }
2645