1 //===--- CGExprConstant.cpp - Emit LLVM Code from Constant Expressions ----===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This contains code to emit Constant Expr nodes as LLVM code.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "CodeGenFunction.h"
14 #include "CGCXXABI.h"
15 #include "CGObjCRuntime.h"
16 #include "CGRecordLayout.h"
17 #include "CodeGenModule.h"
18 #include "ConstantEmitter.h"
19 #include "TargetInfo.h"
20 #include "clang/AST/APValue.h"
21 #include "clang/AST/ASTContext.h"
22 #include "clang/AST/RecordLayout.h"
23 #include "clang/AST/StmtVisitor.h"
24 #include "clang/Basic/Builtins.h"
25 #include "llvm/ADT/Sequence.h"
26 #include "llvm/ADT/STLExtras.h"
27 #include "llvm/IR/Constants.h"
28 #include "llvm/IR/DataLayout.h"
29 #include "llvm/IR/Function.h"
30 #include "llvm/IR/GlobalVariable.h"
31 using namespace clang;
32 using namespace CodeGen;
33 
34 //===----------------------------------------------------------------------===//
35 //                            ConstantAggregateBuilder
36 //===----------------------------------------------------------------------===//
37 
38 namespace {
39 class ConstExprEmitter;
40 
41 struct ConstantAggregateBuilderUtils {
42   CodeGenModule &CGM;
43 
44   ConstantAggregateBuilderUtils(CodeGenModule &CGM) : CGM(CGM) {}
45 
46   CharUnits getAlignment(const llvm::Constant *C) const {
47     return CharUnits::fromQuantity(
48         CGM.getDataLayout().getABITypeAlignment(C->getType()));
49   }
50 
51   CharUnits getSize(llvm::Type *Ty) const {
52     return CharUnits::fromQuantity(CGM.getDataLayout().getTypeAllocSize(Ty));
53   }
54 
55   CharUnits getSize(const llvm::Constant *C) const {
56     return getSize(C->getType());
57   }
58 
59   llvm::Constant *getPadding(CharUnits PadSize) const {
60     llvm::Type *Ty = CGM.Int8Ty;
61     if (PadSize > CharUnits::One())
62       Ty = llvm::ArrayType::get(Ty, PadSize.getQuantity());
63     return llvm::UndefValue::get(Ty);
64   }
65 
66   llvm::Constant *getZeroes(CharUnits ZeroSize) const {
67     llvm::Type *Ty = llvm::ArrayType::get(CGM.Int8Ty, ZeroSize.getQuantity());
68     return llvm::ConstantAggregateZero::get(Ty);
69   }
70 };
71 
72 /// Incremental builder for an llvm::Constant* holding a struct or array
73 /// constant.
74 class ConstantAggregateBuilder : private ConstantAggregateBuilderUtils {
75   /// The elements of the constant. These two arrays must have the same size;
76   /// Offsets[i] describes the offset of Elems[i] within the constant. The
77   /// elements are kept in increasing offset order, and we ensure that there
78   /// is no overlap: Offsets[i+1] >= Offsets[i] + getSize(Elemes[i]).
79   ///
80   /// This may contain explicit padding elements (in order to create a
81   /// natural layout), but need not. Gaps between elements are implicitly
82   /// considered to be filled with undef.
83   llvm::SmallVector<llvm::Constant*, 32> Elems;
84   llvm::SmallVector<CharUnits, 32> Offsets;
85 
86   /// The size of the constant (the maximum end offset of any added element).
87   /// May be larger than the end of Elems.back() if we split the last element
88   /// and removed some trailing undefs.
89   CharUnits Size = CharUnits::Zero();
90 
91   /// This is true only if laying out Elems in order as the elements of a
92   /// non-packed LLVM struct will give the correct layout.
93   bool NaturalLayout = true;
94 
95   bool split(size_t Index, CharUnits Hint);
96   Optional<size_t> splitAt(CharUnits Pos);
97 
98   static llvm::Constant *buildFrom(CodeGenModule &CGM,
99                                    ArrayRef<llvm::Constant *> Elems,
100                                    ArrayRef<CharUnits> Offsets,
101                                    CharUnits StartOffset, CharUnits Size,
102                                    bool NaturalLayout, llvm::Type *DesiredTy,
103                                    bool AllowOversized);
104 
105 public:
106   ConstantAggregateBuilder(CodeGenModule &CGM)
107       : ConstantAggregateBuilderUtils(CGM) {}
108 
109   /// Update or overwrite the value starting at \p Offset with \c C.
110   ///
111   /// \param AllowOverwrite If \c true, this constant might overwrite (part of)
112   ///        a constant that has already been added. This flag is only used to
113   ///        detect bugs.
114   bool add(llvm::Constant *C, CharUnits Offset, bool AllowOverwrite);
115 
116   /// Update or overwrite the bits starting at \p OffsetInBits with \p Bits.
117   bool addBits(llvm::APInt Bits, uint64_t OffsetInBits, bool AllowOverwrite);
118 
119   /// Attempt to condense the value starting at \p Offset to a constant of type
120   /// \p DesiredTy.
121   void condense(CharUnits Offset, llvm::Type *DesiredTy);
122 
123   /// Produce a constant representing the entire accumulated value, ideally of
124   /// the specified type. If \p AllowOversized, the constant might be larger
125   /// than implied by \p DesiredTy (eg, if there is a flexible array member).
126   /// Otherwise, the constant will be of exactly the same size as \p DesiredTy
127   /// even if we can't represent it as that type.
128   llvm::Constant *build(llvm::Type *DesiredTy, bool AllowOversized) const {
129     return buildFrom(CGM, Elems, Offsets, CharUnits::Zero(), Size,
130                      NaturalLayout, DesiredTy, AllowOversized);
131   }
132 };
133 
134 template<typename Container, typename Range = std::initializer_list<
135                                  typename Container::value_type>>
136 static void replace(Container &C, size_t BeginOff, size_t EndOff, Range Vals) {
137   assert(BeginOff <= EndOff && "invalid replacement range");
138   llvm::replace(C, C.begin() + BeginOff, C.begin() + EndOff, Vals);
139 }
140 
141 bool ConstantAggregateBuilder::add(llvm::Constant *C, CharUnits Offset,
142                           bool AllowOverwrite) {
143   // Common case: appending to a layout.
144   if (Offset >= Size) {
145     CharUnits Align = getAlignment(C);
146     CharUnits AlignedSize = Size.alignTo(Align);
147     if (AlignedSize > Offset || Offset.alignTo(Align) != Offset)
148       NaturalLayout = false;
149     else if (AlignedSize < Offset) {
150       Elems.push_back(getPadding(Offset - Size));
151       Offsets.push_back(Size);
152     }
153     Elems.push_back(C);
154     Offsets.push_back(Offset);
155     Size = Offset + getSize(C);
156     return true;
157   }
158 
159   // Uncommon case: constant overlaps what we've already created.
160   llvm::Optional<size_t> FirstElemToReplace = splitAt(Offset);
161   if (!FirstElemToReplace)
162     return false;
163 
164   CharUnits CSize = getSize(C);
165   llvm::Optional<size_t> LastElemToReplace = splitAt(Offset + CSize);
166   if (!LastElemToReplace)
167     return false;
168 
169   assert((FirstElemToReplace == LastElemToReplace || AllowOverwrite) &&
170          "unexpectedly overwriting field");
171 
172   replace(Elems, *FirstElemToReplace, *LastElemToReplace, {C});
173   replace(Offsets, *FirstElemToReplace, *LastElemToReplace, {Offset});
174   Size = std::max(Size, Offset + CSize);
175   NaturalLayout = false;
176   return true;
177 }
178 
179 bool ConstantAggregateBuilder::addBits(llvm::APInt Bits, uint64_t OffsetInBits,
180                               bool AllowOverwrite) {
181   const ASTContext &Context = CGM.getContext();
182   const uint64_t CharWidth = CGM.getContext().getCharWidth();
183 
184   // Offset of where we want the first bit to go within the bits of the
185   // current char.
186   unsigned OffsetWithinChar = OffsetInBits % CharWidth;
187 
188   // We split bit-fields up into individual bytes. Walk over the bytes and
189   // update them.
190   for (CharUnits OffsetInChars = Context.toCharUnitsFromBits(OffsetInBits);
191        /**/; ++OffsetInChars) {
192     // Number of bits we want to fill in this char.
193     unsigned WantedBits =
194         std::min((uint64_t)Bits.getBitWidth(), CharWidth - OffsetWithinChar);
195 
196     // Get a char containing the bits we want in the right places. The other
197     // bits have unspecified values.
198     llvm::APInt BitsThisChar = Bits;
199     if (BitsThisChar.getBitWidth() < CharWidth)
200       BitsThisChar = BitsThisChar.zext(CharWidth);
201     if (CGM.getDataLayout().isBigEndian()) {
202       // Figure out how much to shift by. We may need to left-shift if we have
203       // less than one byte of Bits left.
204       int Shift = Bits.getBitWidth() - CharWidth + OffsetWithinChar;
205       if (Shift > 0)
206         BitsThisChar.lshrInPlace(Shift);
207       else if (Shift < 0)
208         BitsThisChar = BitsThisChar.shl(-Shift);
209     } else {
210       BitsThisChar = BitsThisChar.shl(OffsetWithinChar);
211     }
212     if (BitsThisChar.getBitWidth() > CharWidth)
213       BitsThisChar = BitsThisChar.trunc(CharWidth);
214 
215     if (WantedBits == CharWidth) {
216       // Got a full byte: just add it directly.
217       add(llvm::ConstantInt::get(CGM.getLLVMContext(), BitsThisChar),
218           OffsetInChars, AllowOverwrite);
219     } else {
220       // Partial byte: update the existing integer if there is one. If we
221       // can't split out a 1-CharUnit range to update, then we can't add
222       // these bits and fail the entire constant emission.
223       llvm::Optional<size_t> FirstElemToUpdate = splitAt(OffsetInChars);
224       if (!FirstElemToUpdate)
225         return false;
226       llvm::Optional<size_t> LastElemToUpdate =
227           splitAt(OffsetInChars + CharUnits::One());
228       if (!LastElemToUpdate)
229         return false;
230       assert(*LastElemToUpdate - *FirstElemToUpdate < 2 &&
231              "should have at most one element covering one byte");
232 
233       // Figure out which bits we want and discard the rest.
234       llvm::APInt UpdateMask(CharWidth, 0);
235       if (CGM.getDataLayout().isBigEndian())
236         UpdateMask.setBits(CharWidth - OffsetWithinChar - WantedBits,
237                            CharWidth - OffsetWithinChar);
238       else
239         UpdateMask.setBits(OffsetWithinChar, OffsetWithinChar + WantedBits);
240       BitsThisChar &= UpdateMask;
241 
242       if (*FirstElemToUpdate == *LastElemToUpdate ||
243           Elems[*FirstElemToUpdate]->isNullValue() ||
244           isa<llvm::UndefValue>(Elems[*FirstElemToUpdate])) {
245         // All existing bits are either zero or undef.
246         add(llvm::ConstantInt::get(CGM.getLLVMContext(), BitsThisChar),
247             OffsetInChars, /*AllowOverwrite*/ true);
248       } else {
249         llvm::Constant *&ToUpdate = Elems[*FirstElemToUpdate];
250         // In order to perform a partial update, we need the existing bitwise
251         // value, which we can only extract for a constant int.
252         auto *CI = dyn_cast<llvm::ConstantInt>(ToUpdate);
253         if (!CI)
254           return false;
255         // Because this is a 1-CharUnit range, the constant occupying it must
256         // be exactly one CharUnit wide.
257         assert(CI->getBitWidth() == CharWidth && "splitAt failed");
258         assert((!(CI->getValue() & UpdateMask) || AllowOverwrite) &&
259                "unexpectedly overwriting bitfield");
260         BitsThisChar |= (CI->getValue() & ~UpdateMask);
261         ToUpdate = llvm::ConstantInt::get(CGM.getLLVMContext(), BitsThisChar);
262       }
263     }
264 
265     // Stop if we've added all the bits.
266     if (WantedBits == Bits.getBitWidth())
267       break;
268 
269     // Remove the consumed bits from Bits.
270     if (!CGM.getDataLayout().isBigEndian())
271       Bits.lshrInPlace(WantedBits);
272     Bits = Bits.trunc(Bits.getBitWidth() - WantedBits);
273 
274     // The remanining bits go at the start of the following bytes.
275     OffsetWithinChar = 0;
276   }
277 
278   return true;
279 }
280 
281 /// Returns a position within Elems and Offsets such that all elements
282 /// before the returned index end before Pos and all elements at or after
283 /// the returned index begin at or after Pos. Splits elements as necessary
284 /// to ensure this. Returns None if we find something we can't split.
285 Optional<size_t> ConstantAggregateBuilder::splitAt(CharUnits Pos) {
286   if (Pos >= Size)
287     return Offsets.size();
288 
289   while (true) {
290     auto FirstAfterPos = std::upper_bound(Offsets.begin(), Offsets.end(), Pos);
291     if (FirstAfterPos == Offsets.begin())
292       return 0;
293 
294     // If we already have an element starting at Pos, we're done.
295     size_t LastAtOrBeforePosIndex = FirstAfterPos - Offsets.begin() - 1;
296     if (Offsets[LastAtOrBeforePosIndex] == Pos)
297       return LastAtOrBeforePosIndex;
298 
299     // We found an element starting before Pos. Check for overlap.
300     if (Offsets[LastAtOrBeforePosIndex] +
301         getSize(Elems[LastAtOrBeforePosIndex]) <= Pos)
302       return LastAtOrBeforePosIndex + 1;
303 
304     // Try to decompose it into smaller constants.
305     if (!split(LastAtOrBeforePosIndex, Pos))
306       return None;
307   }
308 }
309 
310 /// Split the constant at index Index, if possible. Return true if we did.
311 /// Hint indicates the location at which we'd like to split, but may be
312 /// ignored.
313 bool ConstantAggregateBuilder::split(size_t Index, CharUnits Hint) {
314   NaturalLayout = false;
315   llvm::Constant *C = Elems[Index];
316   CharUnits Offset = Offsets[Index];
317 
318   if (auto *CA = dyn_cast<llvm::ConstantAggregate>(C)) {
319     replace(Elems, Index, Index + 1,
320             llvm::map_range(llvm::seq(0u, CA->getNumOperands()),
321                             [&](unsigned Op) { return CA->getOperand(Op); }));
322     if (auto *Seq = dyn_cast<llvm::SequentialType>(CA->getType())) {
323       // Array or vector.
324       CharUnits ElemSize = getSize(Seq->getElementType());
325       replace(
326           Offsets, Index, Index + 1,
327           llvm::map_range(llvm::seq(0u, CA->getNumOperands()),
328                           [&](unsigned Op) { return Offset + Op * ElemSize; }));
329     } else {
330       // Must be a struct.
331       auto *ST = cast<llvm::StructType>(CA->getType());
332       const llvm::StructLayout *Layout =
333           CGM.getDataLayout().getStructLayout(ST);
334       replace(Offsets, Index, Index + 1,
335               llvm::map_range(
336                   llvm::seq(0u, CA->getNumOperands()), [&](unsigned Op) {
337                     return Offset + CharUnits::fromQuantity(
338                                         Layout->getElementOffset(Op));
339                   }));
340     }
341     return true;
342   }
343 
344   if (auto *CDS = dyn_cast<llvm::ConstantDataSequential>(C)) {
345     // FIXME: If possible, split into two ConstantDataSequentials at Hint.
346     CharUnits ElemSize = getSize(CDS->getElementType());
347     replace(Elems, Index, Index + 1,
348             llvm::map_range(llvm::seq(0u, CDS->getNumElements()),
349                             [&](unsigned Elem) {
350                               return CDS->getElementAsConstant(Elem);
351                             }));
352     replace(Offsets, Index, Index + 1,
353             llvm::map_range(
354                 llvm::seq(0u, CDS->getNumElements()),
355                 [&](unsigned Elem) { return Offset + Elem * ElemSize; }));
356     return true;
357   }
358 
359   if (isa<llvm::ConstantAggregateZero>(C)) {
360     CharUnits ElemSize = getSize(C);
361     assert(Hint > Offset && Hint < Offset + ElemSize && "nothing to split");
362     replace(Elems, Index, Index + 1,
363             {getZeroes(Hint - Offset), getZeroes(Offset + ElemSize - Hint)});
364     replace(Offsets, Index, Index + 1, {Offset, Hint});
365     return true;
366   }
367 
368   if (isa<llvm::UndefValue>(C)) {
369     replace(Elems, Index, Index + 1, {});
370     replace(Offsets, Index, Index + 1, {});
371     return true;
372   }
373 
374   // FIXME: We could split a ConstantInt if the need ever arose.
375   // We don't need to do this to handle bit-fields because we always eagerly
376   // split them into 1-byte chunks.
377 
378   return false;
379 }
380 
381 static llvm::Constant *
382 EmitArrayConstant(CodeGenModule &CGM, llvm::ArrayType *DesiredType,
383                   llvm::Type *CommonElementType, unsigned ArrayBound,
384                   SmallVectorImpl<llvm::Constant *> &Elements,
385                   llvm::Constant *Filler);
386 
387 llvm::Constant *ConstantAggregateBuilder::buildFrom(
388     CodeGenModule &CGM, ArrayRef<llvm::Constant *> Elems,
389     ArrayRef<CharUnits> Offsets, CharUnits StartOffset, CharUnits Size,
390     bool NaturalLayout, llvm::Type *DesiredTy, bool AllowOversized) {
391   ConstantAggregateBuilderUtils Utils(CGM);
392 
393   if (Elems.empty())
394     return llvm::UndefValue::get(DesiredTy);
395 
396   auto Offset = [&](size_t I) { return Offsets[I] - StartOffset; };
397 
398   // If we want an array type, see if all the elements are the same type and
399   // appropriately spaced.
400   if (llvm::ArrayType *ATy = dyn_cast<llvm::ArrayType>(DesiredTy)) {
401     assert(!AllowOversized && "oversized array emission not supported");
402 
403     bool CanEmitArray = true;
404     llvm::Type *CommonType = Elems[0]->getType();
405     llvm::Constant *Filler = llvm::Constant::getNullValue(CommonType);
406     CharUnits ElemSize = Utils.getSize(ATy->getElementType());
407     SmallVector<llvm::Constant*, 32> ArrayElements;
408     for (size_t I = 0; I != Elems.size(); ++I) {
409       // Skip zeroes; we'll use a zero value as our array filler.
410       if (Elems[I]->isNullValue())
411         continue;
412 
413       // All remaining elements must be the same type.
414       if (Elems[I]->getType() != CommonType ||
415           Offset(I) % ElemSize != 0) {
416         CanEmitArray = false;
417         break;
418       }
419       ArrayElements.resize(Offset(I) / ElemSize + 1, Filler);
420       ArrayElements.back() = Elems[I];
421     }
422 
423     if (CanEmitArray) {
424       return EmitArrayConstant(CGM, ATy, CommonType, ATy->getNumElements(),
425                                ArrayElements, Filler);
426     }
427 
428     // Can't emit as an array, carry on to emit as a struct.
429   }
430 
431   CharUnits DesiredSize = Utils.getSize(DesiredTy);
432   CharUnits Align = CharUnits::One();
433   for (llvm::Constant *C : Elems)
434     Align = std::max(Align, Utils.getAlignment(C));
435   CharUnits AlignedSize = Size.alignTo(Align);
436 
437   bool Packed = false;
438   ArrayRef<llvm::Constant*> UnpackedElems = Elems;
439   llvm::SmallVector<llvm::Constant*, 32> UnpackedElemStorage;
440   if ((DesiredSize < AlignedSize && !AllowOversized) ||
441       DesiredSize.alignTo(Align) != DesiredSize) {
442     // The natural layout would be the wrong size; force use of a packed layout.
443     NaturalLayout = false;
444     Packed = true;
445   } else if (DesiredSize > AlignedSize) {
446     // The constant would be too small. Add padding to fix it.
447     UnpackedElemStorage.assign(Elems.begin(), Elems.end());
448     UnpackedElemStorage.push_back(Utils.getPadding(DesiredSize - Size));
449     UnpackedElems = UnpackedElemStorage;
450   }
451 
452   // If we don't have a natural layout, insert padding as necessary.
453   // As we go, double-check to see if we can actually just emit Elems
454   // as a non-packed struct and do so opportunistically if possible.
455   llvm::SmallVector<llvm::Constant*, 32> PackedElems;
456   if (!NaturalLayout) {
457     CharUnits SizeSoFar = CharUnits::Zero();
458     for (size_t I = 0; I != Elems.size(); ++I) {
459       CharUnits Align = Utils.getAlignment(Elems[I]);
460       CharUnits NaturalOffset = SizeSoFar.alignTo(Align);
461       CharUnits DesiredOffset = Offset(I);
462       assert(DesiredOffset >= SizeSoFar && "elements out of order");
463 
464       if (DesiredOffset != NaturalOffset)
465         Packed = true;
466       if (DesiredOffset != SizeSoFar)
467         PackedElems.push_back(Utils.getPadding(DesiredOffset - SizeSoFar));
468       PackedElems.push_back(Elems[I]);
469       SizeSoFar = DesiredOffset + Utils.getSize(Elems[I]);
470     }
471     // If we're using the packed layout, pad it out to the desired size if
472     // necessary.
473     if (Packed) {
474       assert((SizeSoFar <= DesiredSize || AllowOversized) &&
475              "requested size is too small for contents");
476       if (SizeSoFar < DesiredSize)
477         PackedElems.push_back(Utils.getPadding(DesiredSize - SizeSoFar));
478     }
479   }
480 
481   llvm::StructType *STy = llvm::ConstantStruct::getTypeForElements(
482       CGM.getLLVMContext(), Packed ? PackedElems : UnpackedElems, Packed);
483 
484   // Pick the type to use.  If the type is layout identical to the desired
485   // type then use it, otherwise use whatever the builder produced for us.
486   if (llvm::StructType *DesiredSTy = dyn_cast<llvm::StructType>(DesiredTy)) {
487     if (DesiredSTy->isLayoutIdentical(STy))
488       STy = DesiredSTy;
489   }
490 
491   return llvm::ConstantStruct::get(STy, Packed ? PackedElems : UnpackedElems);
492 }
493 
494 void ConstantAggregateBuilder::condense(CharUnits Offset,
495                                         llvm::Type *DesiredTy) {
496   CharUnits Size = getSize(DesiredTy);
497 
498   llvm::Optional<size_t> FirstElemToReplace = splitAt(Offset);
499   if (!FirstElemToReplace)
500     return;
501   size_t First = *FirstElemToReplace;
502 
503   llvm::Optional<size_t> LastElemToReplace = splitAt(Offset + Size);
504   if (!LastElemToReplace)
505     return;
506   size_t Last = *LastElemToReplace;
507 
508   size_t Length = Last - First;
509   if (Length == 0)
510     return;
511 
512   if (Length == 1 && Offsets[First] == Offset &&
513       getSize(Elems[First]) == Size) {
514     // Re-wrap single element structs if necessary. Otherwise, leave any single
515     // element constant of the right size alone even if it has the wrong type.
516     auto *STy = dyn_cast<llvm::StructType>(DesiredTy);
517     if (STy && STy->getNumElements() == 1 &&
518         STy->getElementType(0) == Elems[First]->getType())
519       Elems[First] = llvm::ConstantStruct::get(STy, Elems[First]);
520     return;
521   }
522 
523   llvm::Constant *Replacement = buildFrom(
524       CGM, makeArrayRef(Elems).slice(First, Length),
525       makeArrayRef(Offsets).slice(First, Length), Offset, getSize(DesiredTy),
526       /*known to have natural layout=*/false, DesiredTy, false);
527   replace(Elems, First, Last, {Replacement});
528   replace(Offsets, First, Last, {Offset});
529 }
530 
531 //===----------------------------------------------------------------------===//
532 //                            ConstStructBuilder
533 //===----------------------------------------------------------------------===//
534 
535 class ConstStructBuilder {
536   CodeGenModule &CGM;
537   ConstantEmitter &Emitter;
538   ConstantAggregateBuilder &Builder;
539   CharUnits StartOffset;
540 
541 public:
542   static llvm::Constant *BuildStruct(ConstantEmitter &Emitter,
543                                      InitListExpr *ILE, QualType StructTy);
544   static llvm::Constant *BuildStruct(ConstantEmitter &Emitter,
545                                      const APValue &Value, QualType ValTy);
546   static bool UpdateStruct(ConstantEmitter &Emitter,
547                            ConstantAggregateBuilder &Const, CharUnits Offset,
548                            InitListExpr *Updater);
549 
550 private:
551   ConstStructBuilder(ConstantEmitter &Emitter,
552                      ConstantAggregateBuilder &Builder, CharUnits StartOffset)
553       : CGM(Emitter.CGM), Emitter(Emitter), Builder(Builder),
554         StartOffset(StartOffset) {}
555 
556   bool AppendField(const FieldDecl *Field, uint64_t FieldOffset,
557                    llvm::Constant *InitExpr, bool AllowOverwrite = false);
558 
559   bool AppendBytes(CharUnits FieldOffsetInChars, llvm::Constant *InitCst,
560                    bool AllowOverwrite = false);
561 
562   bool AppendBitField(const FieldDecl *Field, uint64_t FieldOffset,
563                       llvm::ConstantInt *InitExpr, bool AllowOverwrite = false);
564 
565   bool Build(InitListExpr *ILE, bool AllowOverwrite);
566   bool Build(const APValue &Val, const RecordDecl *RD, bool IsPrimaryBase,
567              const CXXRecordDecl *VTableClass, CharUnits BaseOffset);
568   llvm::Constant *Finalize(QualType Ty);
569 };
570 
571 bool ConstStructBuilder::AppendField(
572     const FieldDecl *Field, uint64_t FieldOffset, llvm::Constant *InitCst,
573     bool AllowOverwrite) {
574   const ASTContext &Context = CGM.getContext();
575 
576   CharUnits FieldOffsetInChars = Context.toCharUnitsFromBits(FieldOffset);
577 
578   return AppendBytes(FieldOffsetInChars, InitCst, AllowOverwrite);
579 }
580 
581 bool ConstStructBuilder::AppendBytes(CharUnits FieldOffsetInChars,
582                                      llvm::Constant *InitCst,
583                                      bool AllowOverwrite) {
584   return Builder.add(InitCst, StartOffset + FieldOffsetInChars, AllowOverwrite);
585 }
586 
587 bool ConstStructBuilder::AppendBitField(
588     const FieldDecl *Field, uint64_t FieldOffset, llvm::ConstantInt *CI,
589     bool AllowOverwrite) {
590   uint64_t FieldSize = Field->getBitWidthValue(CGM.getContext());
591   llvm::APInt FieldValue = CI->getValue();
592 
593   // Promote the size of FieldValue if necessary
594   // FIXME: This should never occur, but currently it can because initializer
595   // constants are cast to bool, and because clang is not enforcing bitfield
596   // width limits.
597   if (FieldSize > FieldValue.getBitWidth())
598     FieldValue = FieldValue.zext(FieldSize);
599 
600   // Truncate the size of FieldValue to the bit field size.
601   if (FieldSize < FieldValue.getBitWidth())
602     FieldValue = FieldValue.trunc(FieldSize);
603 
604   return Builder.addBits(FieldValue,
605                          CGM.getContext().toBits(StartOffset) + FieldOffset,
606                          AllowOverwrite);
607 }
608 
609 static bool EmitDesignatedInitUpdater(ConstantEmitter &Emitter,
610                                       ConstantAggregateBuilder &Const,
611                                       CharUnits Offset, QualType Type,
612                                       InitListExpr *Updater) {
613   if (Type->isRecordType())
614     return ConstStructBuilder::UpdateStruct(Emitter, Const, Offset, Updater);
615 
616   auto CAT = Emitter.CGM.getContext().getAsConstantArrayType(Type);
617   if (!CAT)
618     return false;
619   QualType ElemType = CAT->getElementType();
620   CharUnits ElemSize = Emitter.CGM.getContext().getTypeSizeInChars(ElemType);
621   llvm::Type *ElemTy = Emitter.CGM.getTypes().ConvertTypeForMem(ElemType);
622 
623   llvm::Constant *FillC = nullptr;
624   if (Expr *Filler = Updater->getArrayFiller()) {
625     if (!isa<NoInitExpr>(Filler)) {
626       FillC = Emitter.tryEmitAbstractForMemory(Filler, ElemType);
627       if (!FillC)
628         return false;
629     }
630   }
631 
632   unsigned NumElementsToUpdate =
633       FillC ? CAT->getSize().getZExtValue() : Updater->getNumInits();
634   for (unsigned I = 0; I != NumElementsToUpdate; ++I, Offset += ElemSize) {
635     Expr *Init = nullptr;
636     if (I < Updater->getNumInits())
637       Init = Updater->getInit(I);
638 
639     if (!Init && FillC) {
640       if (!Const.add(FillC, Offset, true))
641         return false;
642     } else if (!Init || isa<NoInitExpr>(Init)) {
643       continue;
644     } else if (InitListExpr *ChildILE = dyn_cast<InitListExpr>(Init)) {
645       if (!EmitDesignatedInitUpdater(Emitter, Const, Offset, ElemType,
646                                      ChildILE))
647         return false;
648       // Attempt to reduce the array element to a single constant if necessary.
649       Const.condense(Offset, ElemTy);
650     } else {
651       llvm::Constant *Val = Emitter.tryEmitPrivateForMemory(Init, ElemType);
652       if (!Const.add(Val, Offset, true))
653         return false;
654     }
655   }
656 
657   return true;
658 }
659 
660 bool ConstStructBuilder::Build(InitListExpr *ILE, bool AllowOverwrite) {
661   RecordDecl *RD = ILE->getType()->getAs<RecordType>()->getDecl();
662   const ASTRecordLayout &Layout = CGM.getContext().getASTRecordLayout(RD);
663 
664   unsigned FieldNo = -1;
665   unsigned ElementNo = 0;
666 
667   // Bail out if we have base classes. We could support these, but they only
668   // arise in C++1z where we will have already constant folded most interesting
669   // cases. FIXME: There are still a few more cases we can handle this way.
670   if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD))
671     if (CXXRD->getNumBases())
672       return false;
673 
674   for (FieldDecl *Field : RD->fields()) {
675     ++FieldNo;
676 
677     // If this is a union, skip all the fields that aren't being initialized.
678     if (RD->isUnion() && ILE->getInitializedFieldInUnion() != Field)
679       continue;
680 
681     // Don't emit anonymous bitfields, they just affect layout.
682     if (Field->isUnnamedBitfield())
683       continue;
684 
685     // Get the initializer.  A struct can include fields without initializers,
686     // we just use explicit null values for them.
687     Expr *Init = nullptr;
688     if (ElementNo < ILE->getNumInits())
689       Init = ILE->getInit(ElementNo++);
690     if (Init && isa<NoInitExpr>(Init))
691       continue;
692 
693     // When emitting a DesignatedInitUpdateExpr, a nested InitListExpr
694     // represents additional overwriting of our current constant value, and not
695     // a new constant to emit independently.
696     if (AllowOverwrite &&
697         (Field->getType()->isArrayType() || Field->getType()->isRecordType())) {
698       if (auto *SubILE = dyn_cast<InitListExpr>(Init)) {
699         CharUnits Offset = CGM.getContext().toCharUnitsFromBits(
700             Layout.getFieldOffset(FieldNo));
701         if (!EmitDesignatedInitUpdater(Emitter, Builder, StartOffset + Offset,
702                                        Field->getType(), SubILE))
703           return false;
704         // If we split apart the field's value, try to collapse it down to a
705         // single value now.
706         Builder.condense(StartOffset + Offset,
707                          CGM.getTypes().ConvertTypeForMem(Field->getType()));
708         continue;
709       }
710     }
711 
712     llvm::Constant *EltInit =
713         Init ? Emitter.tryEmitPrivateForMemory(Init, Field->getType())
714              : Emitter.emitNullForMemory(Field->getType());
715     if (!EltInit)
716       return false;
717 
718     if (!Field->isBitField()) {
719       // Handle non-bitfield members.
720       if (!AppendField(Field, Layout.getFieldOffset(FieldNo), EltInit,
721                        AllowOverwrite))
722         return false;
723     } else {
724       // Otherwise we have a bitfield.
725       if (auto *CI = dyn_cast<llvm::ConstantInt>(EltInit)) {
726         if (!AppendBitField(Field, Layout.getFieldOffset(FieldNo), CI,
727                             AllowOverwrite))
728           return false;
729       } else {
730         // We are trying to initialize a bitfield with a non-trivial constant,
731         // this must require run-time code.
732         return false;
733       }
734     }
735   }
736 
737   return true;
738 }
739 
740 namespace {
741 struct BaseInfo {
742   BaseInfo(const CXXRecordDecl *Decl, CharUnits Offset, unsigned Index)
743     : Decl(Decl), Offset(Offset), Index(Index) {
744   }
745 
746   const CXXRecordDecl *Decl;
747   CharUnits Offset;
748   unsigned Index;
749 
750   bool operator<(const BaseInfo &O) const { return Offset < O.Offset; }
751 };
752 }
753 
754 bool ConstStructBuilder::Build(const APValue &Val, const RecordDecl *RD,
755                                bool IsPrimaryBase,
756                                const CXXRecordDecl *VTableClass,
757                                CharUnits Offset) {
758   const ASTRecordLayout &Layout = CGM.getContext().getASTRecordLayout(RD);
759 
760   if (const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD)) {
761     // Add a vtable pointer, if we need one and it hasn't already been added.
762     if (CD->isDynamicClass() && !IsPrimaryBase) {
763       llvm::Constant *VTableAddressPoint =
764           CGM.getCXXABI().getVTableAddressPointForConstExpr(
765               BaseSubobject(CD, Offset), VTableClass);
766       if (!AppendBytes(Offset, VTableAddressPoint))
767         return false;
768     }
769 
770     // Accumulate and sort bases, in order to visit them in address order, which
771     // may not be the same as declaration order.
772     SmallVector<BaseInfo, 8> Bases;
773     Bases.reserve(CD->getNumBases());
774     unsigned BaseNo = 0;
775     for (CXXRecordDecl::base_class_const_iterator Base = CD->bases_begin(),
776          BaseEnd = CD->bases_end(); Base != BaseEnd; ++Base, ++BaseNo) {
777       assert(!Base->isVirtual() && "should not have virtual bases here");
778       const CXXRecordDecl *BD = Base->getType()->getAsCXXRecordDecl();
779       CharUnits BaseOffset = Layout.getBaseClassOffset(BD);
780       Bases.push_back(BaseInfo(BD, BaseOffset, BaseNo));
781     }
782     llvm::stable_sort(Bases);
783 
784     for (unsigned I = 0, N = Bases.size(); I != N; ++I) {
785       BaseInfo &Base = Bases[I];
786 
787       bool IsPrimaryBase = Layout.getPrimaryBase() == Base.Decl;
788       Build(Val.getStructBase(Base.Index), Base.Decl, IsPrimaryBase,
789             VTableClass, Offset + Base.Offset);
790     }
791   }
792 
793   unsigned FieldNo = 0;
794   uint64_t OffsetBits = CGM.getContext().toBits(Offset);
795 
796   for (RecordDecl::field_iterator Field = RD->field_begin(),
797        FieldEnd = RD->field_end(); Field != FieldEnd; ++Field, ++FieldNo) {
798     // If this is a union, skip all the fields that aren't being initialized.
799     if (RD->isUnion() && !declaresSameEntity(Val.getUnionField(), *Field))
800       continue;
801 
802     // Don't emit anonymous bitfields, they just affect layout.
803     if (Field->isUnnamedBitfield())
804       continue;
805 
806     // Emit the value of the initializer.
807     const APValue &FieldValue =
808       RD->isUnion() ? Val.getUnionValue() : Val.getStructField(FieldNo);
809     llvm::Constant *EltInit =
810       Emitter.tryEmitPrivateForMemory(FieldValue, Field->getType());
811     if (!EltInit)
812       return false;
813 
814     if (!Field->isBitField()) {
815       // Handle non-bitfield members.
816       if (!AppendField(*Field, Layout.getFieldOffset(FieldNo) + OffsetBits,
817                        EltInit))
818         return false;
819     } else {
820       // Otherwise we have a bitfield.
821       if (!AppendBitField(*Field, Layout.getFieldOffset(FieldNo) + OffsetBits,
822                           cast<llvm::ConstantInt>(EltInit)))
823         return false;
824     }
825   }
826 
827   return true;
828 }
829 
830 llvm::Constant *ConstStructBuilder::Finalize(QualType Type) {
831   RecordDecl *RD = Type->getAs<RecordType>()->getDecl();
832   llvm::Type *ValTy = CGM.getTypes().ConvertType(Type);
833   return Builder.build(ValTy, RD->hasFlexibleArrayMember());
834 }
835 
836 llvm::Constant *ConstStructBuilder::BuildStruct(ConstantEmitter &Emitter,
837                                                 InitListExpr *ILE,
838                                                 QualType ValTy) {
839   ConstantAggregateBuilder Const(Emitter.CGM);
840   ConstStructBuilder Builder(Emitter, Const, CharUnits::Zero());
841 
842   if (!Builder.Build(ILE, /*AllowOverwrite*/false))
843     return nullptr;
844 
845   return Builder.Finalize(ValTy);
846 }
847 
848 llvm::Constant *ConstStructBuilder::BuildStruct(ConstantEmitter &Emitter,
849                                                 const APValue &Val,
850                                                 QualType ValTy) {
851   ConstantAggregateBuilder Const(Emitter.CGM);
852   ConstStructBuilder Builder(Emitter, Const, CharUnits::Zero());
853 
854   const RecordDecl *RD = ValTy->castAs<RecordType>()->getDecl();
855   const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD);
856   if (!Builder.Build(Val, RD, false, CD, CharUnits::Zero()))
857     return nullptr;
858 
859   return Builder.Finalize(ValTy);
860 }
861 
862 bool ConstStructBuilder::UpdateStruct(ConstantEmitter &Emitter,
863                                       ConstantAggregateBuilder &Const,
864                                       CharUnits Offset, InitListExpr *Updater) {
865   return ConstStructBuilder(Emitter, Const, Offset)
866       .Build(Updater, /*AllowOverwrite*/ true);
867 }
868 
869 //===----------------------------------------------------------------------===//
870 //                             ConstExprEmitter
871 //===----------------------------------------------------------------------===//
872 
873 static ConstantAddress tryEmitGlobalCompoundLiteral(CodeGenModule &CGM,
874                                                     CodeGenFunction *CGF,
875                                               const CompoundLiteralExpr *E) {
876   CharUnits Align = CGM.getContext().getTypeAlignInChars(E->getType());
877   if (llvm::GlobalVariable *Addr =
878           CGM.getAddrOfConstantCompoundLiteralIfEmitted(E))
879     return ConstantAddress(Addr, Align);
880 
881   LangAS addressSpace = E->getType().getAddressSpace();
882 
883   ConstantEmitter emitter(CGM, CGF);
884   llvm::Constant *C = emitter.tryEmitForInitializer(E->getInitializer(),
885                                                     addressSpace, E->getType());
886   if (!C) {
887     assert(!E->isFileScope() &&
888            "file-scope compound literal did not have constant initializer!");
889     return ConstantAddress::invalid();
890   }
891 
892   auto GV = new llvm::GlobalVariable(CGM.getModule(), C->getType(),
893                                      CGM.isTypeConstant(E->getType(), true),
894                                      llvm::GlobalValue::InternalLinkage,
895                                      C, ".compoundliteral", nullptr,
896                                      llvm::GlobalVariable::NotThreadLocal,
897                     CGM.getContext().getTargetAddressSpace(addressSpace));
898   emitter.finalize(GV);
899   GV->setAlignment(Align.getQuantity());
900   CGM.setAddrOfConstantCompoundLiteral(E, GV);
901   return ConstantAddress(GV, Align);
902 }
903 
904 static llvm::Constant *
905 EmitArrayConstant(CodeGenModule &CGM, llvm::ArrayType *DesiredType,
906                   llvm::Type *CommonElementType, unsigned ArrayBound,
907                   SmallVectorImpl<llvm::Constant *> &Elements,
908                   llvm::Constant *Filler) {
909   // Figure out how long the initial prefix of non-zero elements is.
910   unsigned NonzeroLength = ArrayBound;
911   if (Elements.size() < NonzeroLength && Filler->isNullValue())
912     NonzeroLength = Elements.size();
913   if (NonzeroLength == Elements.size()) {
914     while (NonzeroLength > 0 && Elements[NonzeroLength - 1]->isNullValue())
915       --NonzeroLength;
916   }
917 
918   if (NonzeroLength == 0)
919     return llvm::ConstantAggregateZero::get(DesiredType);
920 
921   // Add a zeroinitializer array filler if we have lots of trailing zeroes.
922   unsigned TrailingZeroes = ArrayBound - NonzeroLength;
923   if (TrailingZeroes >= 8) {
924     assert(Elements.size() >= NonzeroLength &&
925            "missing initializer for non-zero element");
926 
927     // If all the elements had the same type up to the trailing zeroes, emit a
928     // struct of two arrays (the nonzero data and the zeroinitializer).
929     if (CommonElementType && NonzeroLength >= 8) {
930       llvm::Constant *Initial = llvm::ConstantArray::get(
931           llvm::ArrayType::get(CommonElementType, NonzeroLength),
932           makeArrayRef(Elements).take_front(NonzeroLength));
933       Elements.resize(2);
934       Elements[0] = Initial;
935     } else {
936       Elements.resize(NonzeroLength + 1);
937     }
938 
939     auto *FillerType =
940         CommonElementType ? CommonElementType : DesiredType->getElementType();
941     FillerType = llvm::ArrayType::get(FillerType, TrailingZeroes);
942     Elements.back() = llvm::ConstantAggregateZero::get(FillerType);
943     CommonElementType = nullptr;
944   } else if (Elements.size() != ArrayBound) {
945     // Otherwise pad to the right size with the filler if necessary.
946     Elements.resize(ArrayBound, Filler);
947     if (Filler->getType() != CommonElementType)
948       CommonElementType = nullptr;
949   }
950 
951   // If all elements have the same type, just emit an array constant.
952   if (CommonElementType)
953     return llvm::ConstantArray::get(
954         llvm::ArrayType::get(CommonElementType, ArrayBound), Elements);
955 
956   // We have mixed types. Use a packed struct.
957   llvm::SmallVector<llvm::Type *, 16> Types;
958   Types.reserve(Elements.size());
959   for (llvm::Constant *Elt : Elements)
960     Types.push_back(Elt->getType());
961   llvm::StructType *SType =
962       llvm::StructType::get(CGM.getLLVMContext(), Types, true);
963   return llvm::ConstantStruct::get(SType, Elements);
964 }
965 
966 // This class only needs to handle arrays, structs and unions. Outside C++11
967 // mode, we don't currently constant fold those types.  All other types are
968 // handled by constant folding.
969 //
970 // Constant folding is currently missing support for a few features supported
971 // here: CK_ToUnion, CK_ReinterpretMemberPointer, and DesignatedInitUpdateExpr.
972 class ConstExprEmitter :
973   public StmtVisitor<ConstExprEmitter, llvm::Constant*, QualType> {
974   CodeGenModule &CGM;
975   ConstantEmitter &Emitter;
976   llvm::LLVMContext &VMContext;
977 public:
978   ConstExprEmitter(ConstantEmitter &emitter)
979     : CGM(emitter.CGM), Emitter(emitter), VMContext(CGM.getLLVMContext()) {
980   }
981 
982   //===--------------------------------------------------------------------===//
983   //                            Visitor Methods
984   //===--------------------------------------------------------------------===//
985 
986   llvm::Constant *VisitStmt(Stmt *S, QualType T) {
987     return nullptr;
988   }
989 
990   llvm::Constant *VisitConstantExpr(ConstantExpr *CE, QualType T) {
991     return Visit(CE->getSubExpr(), T);
992   }
993 
994   llvm::Constant *VisitParenExpr(ParenExpr *PE, QualType T) {
995     return Visit(PE->getSubExpr(), T);
996   }
997 
998   llvm::Constant *
999   VisitSubstNonTypeTemplateParmExpr(SubstNonTypeTemplateParmExpr *PE,
1000                                     QualType T) {
1001     return Visit(PE->getReplacement(), T);
1002   }
1003 
1004   llvm::Constant *VisitGenericSelectionExpr(GenericSelectionExpr *GE,
1005                                             QualType T) {
1006     return Visit(GE->getResultExpr(), T);
1007   }
1008 
1009   llvm::Constant *VisitChooseExpr(ChooseExpr *CE, QualType T) {
1010     return Visit(CE->getChosenSubExpr(), T);
1011   }
1012 
1013   llvm::Constant *VisitCompoundLiteralExpr(CompoundLiteralExpr *E, QualType T) {
1014     return Visit(E->getInitializer(), T);
1015   }
1016 
1017   llvm::Constant *VisitCastExpr(CastExpr *E, QualType destType) {
1018     if (const auto *ECE = dyn_cast<ExplicitCastExpr>(E))
1019       CGM.EmitExplicitCastExprType(ECE, Emitter.CGF);
1020     Expr *subExpr = E->getSubExpr();
1021 
1022     switch (E->getCastKind()) {
1023     case CK_ToUnion: {
1024       // GCC cast to union extension
1025       assert(E->getType()->isUnionType() &&
1026              "Destination type is not union type!");
1027 
1028       auto field = E->getTargetUnionField();
1029 
1030       auto C = Emitter.tryEmitPrivateForMemory(subExpr, field->getType());
1031       if (!C) return nullptr;
1032 
1033       auto destTy = ConvertType(destType);
1034       if (C->getType() == destTy) return C;
1035 
1036       // Build a struct with the union sub-element as the first member,
1037       // and padded to the appropriate size.
1038       SmallVector<llvm::Constant*, 2> Elts;
1039       SmallVector<llvm::Type*, 2> Types;
1040       Elts.push_back(C);
1041       Types.push_back(C->getType());
1042       unsigned CurSize = CGM.getDataLayout().getTypeAllocSize(C->getType());
1043       unsigned TotalSize = CGM.getDataLayout().getTypeAllocSize(destTy);
1044 
1045       assert(CurSize <= TotalSize && "Union size mismatch!");
1046       if (unsigned NumPadBytes = TotalSize - CurSize) {
1047         llvm::Type *Ty = CGM.Int8Ty;
1048         if (NumPadBytes > 1)
1049           Ty = llvm::ArrayType::get(Ty, NumPadBytes);
1050 
1051         Elts.push_back(llvm::UndefValue::get(Ty));
1052         Types.push_back(Ty);
1053       }
1054 
1055       llvm::StructType *STy = llvm::StructType::get(VMContext, Types, false);
1056       return llvm::ConstantStruct::get(STy, Elts);
1057     }
1058 
1059     case CK_AddressSpaceConversion: {
1060       auto C = Emitter.tryEmitPrivate(subExpr, subExpr->getType());
1061       if (!C) return nullptr;
1062       LangAS destAS = E->getType()->getPointeeType().getAddressSpace();
1063       LangAS srcAS = subExpr->getType()->getPointeeType().getAddressSpace();
1064       llvm::Type *destTy = ConvertType(E->getType());
1065       return CGM.getTargetCodeGenInfo().performAddrSpaceCast(CGM, C, srcAS,
1066                                                              destAS, destTy);
1067     }
1068 
1069     case CK_LValueToRValue:
1070     case CK_AtomicToNonAtomic:
1071     case CK_NonAtomicToAtomic:
1072     case CK_NoOp:
1073     case CK_ConstructorConversion:
1074       return Visit(subExpr, destType);
1075 
1076     case CK_IntToOCLSampler:
1077       llvm_unreachable("global sampler variables are not generated");
1078 
1079     case CK_Dependent: llvm_unreachable("saw dependent cast!");
1080 
1081     case CK_BuiltinFnToFnPtr:
1082       llvm_unreachable("builtin functions are handled elsewhere");
1083 
1084     case CK_ReinterpretMemberPointer:
1085     case CK_DerivedToBaseMemberPointer:
1086     case CK_BaseToDerivedMemberPointer: {
1087       auto C = Emitter.tryEmitPrivate(subExpr, subExpr->getType());
1088       if (!C) return nullptr;
1089       return CGM.getCXXABI().EmitMemberPointerConversion(E, C);
1090     }
1091 
1092     // These will never be supported.
1093     case CK_ObjCObjectLValueCast:
1094     case CK_ARCProduceObject:
1095     case CK_ARCConsumeObject:
1096     case CK_ARCReclaimReturnedObject:
1097     case CK_ARCExtendBlockObject:
1098     case CK_CopyAndAutoreleaseBlockObject:
1099       return nullptr;
1100 
1101     // These don't need to be handled here because Evaluate knows how to
1102     // evaluate them in the cases where they can be folded.
1103     case CK_BitCast:
1104     case CK_ToVoid:
1105     case CK_Dynamic:
1106     case CK_LValueBitCast:
1107     case CK_NullToMemberPointer:
1108     case CK_UserDefinedConversion:
1109     case CK_CPointerToObjCPointerCast:
1110     case CK_BlockPointerToObjCPointerCast:
1111     case CK_AnyPointerToBlockPointerCast:
1112     case CK_ArrayToPointerDecay:
1113     case CK_FunctionToPointerDecay:
1114     case CK_BaseToDerived:
1115     case CK_DerivedToBase:
1116     case CK_UncheckedDerivedToBase:
1117     case CK_MemberPointerToBoolean:
1118     case CK_VectorSplat:
1119     case CK_FloatingRealToComplex:
1120     case CK_FloatingComplexToReal:
1121     case CK_FloatingComplexToBoolean:
1122     case CK_FloatingComplexCast:
1123     case CK_FloatingComplexToIntegralComplex:
1124     case CK_IntegralRealToComplex:
1125     case CK_IntegralComplexToReal:
1126     case CK_IntegralComplexToBoolean:
1127     case CK_IntegralComplexCast:
1128     case CK_IntegralComplexToFloatingComplex:
1129     case CK_PointerToIntegral:
1130     case CK_PointerToBoolean:
1131     case CK_NullToPointer:
1132     case CK_IntegralCast:
1133     case CK_BooleanToSignedIntegral:
1134     case CK_IntegralToPointer:
1135     case CK_IntegralToBoolean:
1136     case CK_IntegralToFloating:
1137     case CK_FloatingToIntegral:
1138     case CK_FloatingToBoolean:
1139     case CK_FloatingCast:
1140     case CK_FixedPointCast:
1141     case CK_FixedPointToBoolean:
1142     case CK_FixedPointToIntegral:
1143     case CK_IntegralToFixedPoint:
1144     case CK_ZeroToOCLOpaqueType:
1145       return nullptr;
1146     }
1147     llvm_unreachable("Invalid CastKind");
1148   }
1149 
1150   llvm::Constant *VisitCXXDefaultInitExpr(CXXDefaultInitExpr *DIE, QualType T) {
1151     // No need for a DefaultInitExprScope: we don't handle 'this' in a
1152     // constant expression.
1153     return Visit(DIE->getExpr(), T);
1154   }
1155 
1156   llvm::Constant *VisitExprWithCleanups(ExprWithCleanups *E, QualType T) {
1157     if (!E->cleanupsHaveSideEffects())
1158       return Visit(E->getSubExpr(), T);
1159     return nullptr;
1160   }
1161 
1162   llvm::Constant *VisitMaterializeTemporaryExpr(MaterializeTemporaryExpr *E,
1163                                                 QualType T) {
1164     return Visit(E->GetTemporaryExpr(), T);
1165   }
1166 
1167   llvm::Constant *EmitArrayInitialization(InitListExpr *ILE, QualType T) {
1168     auto *CAT = CGM.getContext().getAsConstantArrayType(ILE->getType());
1169     assert(CAT && "can't emit array init for non-constant-bound array");
1170     unsigned NumInitElements = ILE->getNumInits();
1171     unsigned NumElements = CAT->getSize().getZExtValue();
1172 
1173     // Initialising an array requires us to automatically
1174     // initialise any elements that have not been initialised explicitly
1175     unsigned NumInitableElts = std::min(NumInitElements, NumElements);
1176 
1177     QualType EltType = CAT->getElementType();
1178 
1179     // Initialize remaining array elements.
1180     llvm::Constant *fillC = nullptr;
1181     if (Expr *filler = ILE->getArrayFiller()) {
1182       fillC = Emitter.tryEmitAbstractForMemory(filler, EltType);
1183       if (!fillC)
1184         return nullptr;
1185     }
1186 
1187     // Copy initializer elements.
1188     SmallVector<llvm::Constant*, 16> Elts;
1189     if (fillC && fillC->isNullValue())
1190       Elts.reserve(NumInitableElts + 1);
1191     else
1192       Elts.reserve(NumElements);
1193 
1194     llvm::Type *CommonElementType = nullptr;
1195     for (unsigned i = 0; i < NumInitableElts; ++i) {
1196       Expr *Init = ILE->getInit(i);
1197       llvm::Constant *C = Emitter.tryEmitPrivateForMemory(Init, EltType);
1198       if (!C)
1199         return nullptr;
1200       if (i == 0)
1201         CommonElementType = C->getType();
1202       else if (C->getType() != CommonElementType)
1203         CommonElementType = nullptr;
1204       Elts.push_back(C);
1205     }
1206 
1207     llvm::ArrayType *Desired =
1208         cast<llvm::ArrayType>(CGM.getTypes().ConvertType(ILE->getType()));
1209     return EmitArrayConstant(CGM, Desired, CommonElementType, NumElements, Elts,
1210                              fillC);
1211   }
1212 
1213   llvm::Constant *EmitRecordInitialization(InitListExpr *ILE, QualType T) {
1214     return ConstStructBuilder::BuildStruct(Emitter, ILE, T);
1215   }
1216 
1217   llvm::Constant *VisitImplicitValueInitExpr(ImplicitValueInitExpr* E,
1218                                              QualType T) {
1219     return CGM.EmitNullConstant(T);
1220   }
1221 
1222   llvm::Constant *VisitInitListExpr(InitListExpr *ILE, QualType T) {
1223     if (ILE->isTransparent())
1224       return Visit(ILE->getInit(0), T);
1225 
1226     if (ILE->getType()->isArrayType())
1227       return EmitArrayInitialization(ILE, T);
1228 
1229     if (ILE->getType()->isRecordType())
1230       return EmitRecordInitialization(ILE, T);
1231 
1232     return nullptr;
1233   }
1234 
1235   llvm::Constant *VisitDesignatedInitUpdateExpr(DesignatedInitUpdateExpr *E,
1236                                                 QualType destType) {
1237     auto C = Visit(E->getBase(), destType);
1238     if (!C)
1239       return nullptr;
1240 
1241     ConstantAggregateBuilder Const(CGM);
1242     Const.add(C, CharUnits::Zero(), false);
1243 
1244     if (!EmitDesignatedInitUpdater(Emitter, Const, CharUnits::Zero(), destType,
1245                                    E->getUpdater()))
1246       return nullptr;
1247 
1248     llvm::Type *ValTy = CGM.getTypes().ConvertType(destType);
1249     bool HasFlexibleArray = false;
1250     if (auto *RT = destType->getAs<RecordType>())
1251       HasFlexibleArray = RT->getDecl()->hasFlexibleArrayMember();
1252     return Const.build(ValTy, HasFlexibleArray);
1253   }
1254 
1255   llvm::Constant *VisitCXXConstructExpr(CXXConstructExpr *E, QualType Ty) {
1256     if (!E->getConstructor()->isTrivial())
1257       return nullptr;
1258 
1259     // FIXME: We should not have to call getBaseElementType here.
1260     const RecordType *RT =
1261       CGM.getContext().getBaseElementType(Ty)->getAs<RecordType>();
1262     const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
1263 
1264     // If the class doesn't have a trivial destructor, we can't emit it as a
1265     // constant expr.
1266     if (!RD->hasTrivialDestructor())
1267       return nullptr;
1268 
1269     // Only copy and default constructors can be trivial.
1270 
1271 
1272     if (E->getNumArgs()) {
1273       assert(E->getNumArgs() == 1 && "trivial ctor with > 1 argument");
1274       assert(E->getConstructor()->isCopyOrMoveConstructor() &&
1275              "trivial ctor has argument but isn't a copy/move ctor");
1276 
1277       Expr *Arg = E->getArg(0);
1278       assert(CGM.getContext().hasSameUnqualifiedType(Ty, Arg->getType()) &&
1279              "argument to copy ctor is of wrong type");
1280 
1281       return Visit(Arg, Ty);
1282     }
1283 
1284     return CGM.EmitNullConstant(Ty);
1285   }
1286 
1287   llvm::Constant *VisitStringLiteral(StringLiteral *E, QualType T) {
1288     // This is a string literal initializing an array in an initializer.
1289     return CGM.GetConstantArrayFromStringLiteral(E);
1290   }
1291 
1292   llvm::Constant *VisitObjCEncodeExpr(ObjCEncodeExpr *E, QualType T) {
1293     // This must be an @encode initializing an array in a static initializer.
1294     // Don't emit it as the address of the string, emit the string data itself
1295     // as an inline array.
1296     std::string Str;
1297     CGM.getContext().getObjCEncodingForType(E->getEncodedType(), Str);
1298     const ConstantArrayType *CAT = CGM.getContext().getAsConstantArrayType(T);
1299 
1300     // Resize the string to the right size, adding zeros at the end, or
1301     // truncating as needed.
1302     Str.resize(CAT->getSize().getZExtValue(), '\0');
1303     return llvm::ConstantDataArray::getString(VMContext, Str, false);
1304   }
1305 
1306   llvm::Constant *VisitUnaryExtension(const UnaryOperator *E, QualType T) {
1307     return Visit(E->getSubExpr(), T);
1308   }
1309 
1310   // Utility methods
1311   llvm::Type *ConvertType(QualType T) {
1312     return CGM.getTypes().ConvertType(T);
1313   }
1314 };
1315 
1316 }  // end anonymous namespace.
1317 
1318 llvm::Constant *ConstantEmitter::validateAndPopAbstract(llvm::Constant *C,
1319                                                         AbstractState saved) {
1320   Abstract = saved.OldValue;
1321 
1322   assert(saved.OldPlaceholdersSize == PlaceholderAddresses.size() &&
1323          "created a placeholder while doing an abstract emission?");
1324 
1325   // No validation necessary for now.
1326   // No cleanup to do for now.
1327   return C;
1328 }
1329 
1330 llvm::Constant *
1331 ConstantEmitter::tryEmitAbstractForInitializer(const VarDecl &D) {
1332   auto state = pushAbstract();
1333   auto C = tryEmitPrivateForVarInit(D);
1334   return validateAndPopAbstract(C, state);
1335 }
1336 
1337 llvm::Constant *
1338 ConstantEmitter::tryEmitAbstract(const Expr *E, QualType destType) {
1339   auto state = pushAbstract();
1340   auto C = tryEmitPrivate(E, destType);
1341   return validateAndPopAbstract(C, state);
1342 }
1343 
1344 llvm::Constant *
1345 ConstantEmitter::tryEmitAbstract(const APValue &value, QualType destType) {
1346   auto state = pushAbstract();
1347   auto C = tryEmitPrivate(value, destType);
1348   return validateAndPopAbstract(C, state);
1349 }
1350 
1351 llvm::Constant *
1352 ConstantEmitter::emitAbstract(const Expr *E, QualType destType) {
1353   auto state = pushAbstract();
1354   auto C = tryEmitPrivate(E, destType);
1355   C = validateAndPopAbstract(C, state);
1356   if (!C) {
1357     CGM.Error(E->getExprLoc(),
1358               "internal error: could not emit constant value \"abstractly\"");
1359     C = CGM.EmitNullConstant(destType);
1360   }
1361   return C;
1362 }
1363 
1364 llvm::Constant *
1365 ConstantEmitter::emitAbstract(SourceLocation loc, const APValue &value,
1366                               QualType destType) {
1367   auto state = pushAbstract();
1368   auto C = tryEmitPrivate(value, destType);
1369   C = validateAndPopAbstract(C, state);
1370   if (!C) {
1371     CGM.Error(loc,
1372               "internal error: could not emit constant value \"abstractly\"");
1373     C = CGM.EmitNullConstant(destType);
1374   }
1375   return C;
1376 }
1377 
1378 llvm::Constant *ConstantEmitter::tryEmitForInitializer(const VarDecl &D) {
1379   initializeNonAbstract(D.getType().getAddressSpace());
1380   return markIfFailed(tryEmitPrivateForVarInit(D));
1381 }
1382 
1383 llvm::Constant *ConstantEmitter::tryEmitForInitializer(const Expr *E,
1384                                                        LangAS destAddrSpace,
1385                                                        QualType destType) {
1386   initializeNonAbstract(destAddrSpace);
1387   return markIfFailed(tryEmitPrivateForMemory(E, destType));
1388 }
1389 
1390 llvm::Constant *ConstantEmitter::emitForInitializer(const APValue &value,
1391                                                     LangAS destAddrSpace,
1392                                                     QualType destType) {
1393   initializeNonAbstract(destAddrSpace);
1394   auto C = tryEmitPrivateForMemory(value, destType);
1395   assert(C && "couldn't emit constant value non-abstractly?");
1396   return C;
1397 }
1398 
1399 llvm::GlobalValue *ConstantEmitter::getCurrentAddrPrivate() {
1400   assert(!Abstract && "cannot get current address for abstract constant");
1401 
1402 
1403 
1404   // Make an obviously ill-formed global that should blow up compilation
1405   // if it survives.
1406   auto global = new llvm::GlobalVariable(CGM.getModule(), CGM.Int8Ty, true,
1407                                          llvm::GlobalValue::PrivateLinkage,
1408                                          /*init*/ nullptr,
1409                                          /*name*/ "",
1410                                          /*before*/ nullptr,
1411                                          llvm::GlobalVariable::NotThreadLocal,
1412                                          CGM.getContext().getTargetAddressSpace(DestAddressSpace));
1413 
1414   PlaceholderAddresses.push_back(std::make_pair(nullptr, global));
1415 
1416   return global;
1417 }
1418 
1419 void ConstantEmitter::registerCurrentAddrPrivate(llvm::Constant *signal,
1420                                            llvm::GlobalValue *placeholder) {
1421   assert(!PlaceholderAddresses.empty());
1422   assert(PlaceholderAddresses.back().first == nullptr);
1423   assert(PlaceholderAddresses.back().second == placeholder);
1424   PlaceholderAddresses.back().first = signal;
1425 }
1426 
1427 namespace {
1428   struct ReplacePlaceholders {
1429     CodeGenModule &CGM;
1430 
1431     /// The base address of the global.
1432     llvm::Constant *Base;
1433     llvm::Type *BaseValueTy = nullptr;
1434 
1435     /// The placeholder addresses that were registered during emission.
1436     llvm::DenseMap<llvm::Constant*, llvm::GlobalVariable*> PlaceholderAddresses;
1437 
1438     /// The locations of the placeholder signals.
1439     llvm::DenseMap<llvm::GlobalVariable*, llvm::Constant*> Locations;
1440 
1441     /// The current index stack.  We use a simple unsigned stack because
1442     /// we assume that placeholders will be relatively sparse in the
1443     /// initializer, but we cache the index values we find just in case.
1444     llvm::SmallVector<unsigned, 8> Indices;
1445     llvm::SmallVector<llvm::Constant*, 8> IndexValues;
1446 
1447     ReplacePlaceholders(CodeGenModule &CGM, llvm::Constant *base,
1448                         ArrayRef<std::pair<llvm::Constant*,
1449                                            llvm::GlobalVariable*>> addresses)
1450         : CGM(CGM), Base(base),
1451           PlaceholderAddresses(addresses.begin(), addresses.end()) {
1452     }
1453 
1454     void replaceInInitializer(llvm::Constant *init) {
1455       // Remember the type of the top-most initializer.
1456       BaseValueTy = init->getType();
1457 
1458       // Initialize the stack.
1459       Indices.push_back(0);
1460       IndexValues.push_back(nullptr);
1461 
1462       // Recurse into the initializer.
1463       findLocations(init);
1464 
1465       // Check invariants.
1466       assert(IndexValues.size() == Indices.size() && "mismatch");
1467       assert(Indices.size() == 1 && "didn't pop all indices");
1468 
1469       // Do the replacement; this basically invalidates 'init'.
1470       assert(Locations.size() == PlaceholderAddresses.size() &&
1471              "missed a placeholder?");
1472 
1473       // We're iterating over a hashtable, so this would be a source of
1474       // non-determinism in compiler output *except* that we're just
1475       // messing around with llvm::Constant structures, which never itself
1476       // does anything that should be visible in compiler output.
1477       for (auto &entry : Locations) {
1478         assert(entry.first->getParent() == nullptr && "not a placeholder!");
1479         entry.first->replaceAllUsesWith(entry.second);
1480         entry.first->eraseFromParent();
1481       }
1482     }
1483 
1484   private:
1485     void findLocations(llvm::Constant *init) {
1486       // Recurse into aggregates.
1487       if (auto agg = dyn_cast<llvm::ConstantAggregate>(init)) {
1488         for (unsigned i = 0, e = agg->getNumOperands(); i != e; ++i) {
1489           Indices.push_back(i);
1490           IndexValues.push_back(nullptr);
1491 
1492           findLocations(agg->getOperand(i));
1493 
1494           IndexValues.pop_back();
1495           Indices.pop_back();
1496         }
1497         return;
1498       }
1499 
1500       // Otherwise, check for registered constants.
1501       while (true) {
1502         auto it = PlaceholderAddresses.find(init);
1503         if (it != PlaceholderAddresses.end()) {
1504           setLocation(it->second);
1505           break;
1506         }
1507 
1508         // Look through bitcasts or other expressions.
1509         if (auto expr = dyn_cast<llvm::ConstantExpr>(init)) {
1510           init = expr->getOperand(0);
1511         } else {
1512           break;
1513         }
1514       }
1515     }
1516 
1517     void setLocation(llvm::GlobalVariable *placeholder) {
1518       assert(Locations.find(placeholder) == Locations.end() &&
1519              "already found location for placeholder!");
1520 
1521       // Lazily fill in IndexValues with the values from Indices.
1522       // We do this in reverse because we should always have a strict
1523       // prefix of indices from the start.
1524       assert(Indices.size() == IndexValues.size());
1525       for (size_t i = Indices.size() - 1; i != size_t(-1); --i) {
1526         if (IndexValues[i]) {
1527 #ifndef NDEBUG
1528           for (size_t j = 0; j != i + 1; ++j) {
1529             assert(IndexValues[j] &&
1530                    isa<llvm::ConstantInt>(IndexValues[j]) &&
1531                    cast<llvm::ConstantInt>(IndexValues[j])->getZExtValue()
1532                      == Indices[j]);
1533           }
1534 #endif
1535           break;
1536         }
1537 
1538         IndexValues[i] = llvm::ConstantInt::get(CGM.Int32Ty, Indices[i]);
1539       }
1540 
1541       // Form a GEP and then bitcast to the placeholder type so that the
1542       // replacement will succeed.
1543       llvm::Constant *location =
1544         llvm::ConstantExpr::getInBoundsGetElementPtr(BaseValueTy,
1545                                                      Base, IndexValues);
1546       location = llvm::ConstantExpr::getBitCast(location,
1547                                                 placeholder->getType());
1548 
1549       Locations.insert({placeholder, location});
1550     }
1551   };
1552 }
1553 
1554 void ConstantEmitter::finalize(llvm::GlobalVariable *global) {
1555   assert(InitializedNonAbstract &&
1556          "finalizing emitter that was used for abstract emission?");
1557   assert(!Finalized && "finalizing emitter multiple times");
1558   assert(global->getInitializer());
1559 
1560   // Note that we might also be Failed.
1561   Finalized = true;
1562 
1563   if (!PlaceholderAddresses.empty()) {
1564     ReplacePlaceholders(CGM, global, PlaceholderAddresses)
1565       .replaceInInitializer(global->getInitializer());
1566     PlaceholderAddresses.clear(); // satisfy
1567   }
1568 }
1569 
1570 ConstantEmitter::~ConstantEmitter() {
1571   assert((!InitializedNonAbstract || Finalized || Failed) &&
1572          "not finalized after being initialized for non-abstract emission");
1573   assert(PlaceholderAddresses.empty() && "unhandled placeholders");
1574 }
1575 
1576 static QualType getNonMemoryType(CodeGenModule &CGM, QualType type) {
1577   if (auto AT = type->getAs<AtomicType>()) {
1578     return CGM.getContext().getQualifiedType(AT->getValueType(),
1579                                              type.getQualifiers());
1580   }
1581   return type;
1582 }
1583 
1584 llvm::Constant *ConstantEmitter::tryEmitPrivateForVarInit(const VarDecl &D) {
1585   // Make a quick check if variable can be default NULL initialized
1586   // and avoid going through rest of code which may do, for c++11,
1587   // initialization of memory to all NULLs.
1588   if (!D.hasLocalStorage()) {
1589     QualType Ty = CGM.getContext().getBaseElementType(D.getType());
1590     if (Ty->isRecordType())
1591       if (const CXXConstructExpr *E =
1592           dyn_cast_or_null<CXXConstructExpr>(D.getInit())) {
1593         const CXXConstructorDecl *CD = E->getConstructor();
1594         if (CD->isTrivial() && CD->isDefaultConstructor())
1595           return CGM.EmitNullConstant(D.getType());
1596       }
1597     InConstantContext = true;
1598   }
1599 
1600   QualType destType = D.getType();
1601 
1602   // Try to emit the initializer.  Note that this can allow some things that
1603   // are not allowed by tryEmitPrivateForMemory alone.
1604   if (auto value = D.evaluateValue()) {
1605     return tryEmitPrivateForMemory(*value, destType);
1606   }
1607 
1608   // FIXME: Implement C++11 [basic.start.init]p2: if the initializer of a
1609   // reference is a constant expression, and the reference binds to a temporary,
1610   // then constant initialization is performed. ConstExprEmitter will
1611   // incorrectly emit a prvalue constant in this case, and the calling code
1612   // interprets that as the (pointer) value of the reference, rather than the
1613   // desired value of the referee.
1614   if (destType->isReferenceType())
1615     return nullptr;
1616 
1617   const Expr *E = D.getInit();
1618   assert(E && "No initializer to emit");
1619 
1620   auto nonMemoryDestType = getNonMemoryType(CGM, destType);
1621   auto C =
1622     ConstExprEmitter(*this).Visit(const_cast<Expr*>(E), nonMemoryDestType);
1623   return (C ? emitForMemory(C, destType) : nullptr);
1624 }
1625 
1626 llvm::Constant *
1627 ConstantEmitter::tryEmitAbstractForMemory(const Expr *E, QualType destType) {
1628   auto nonMemoryDestType = getNonMemoryType(CGM, destType);
1629   auto C = tryEmitAbstract(E, nonMemoryDestType);
1630   return (C ? emitForMemory(C, destType) : nullptr);
1631 }
1632 
1633 llvm::Constant *
1634 ConstantEmitter::tryEmitAbstractForMemory(const APValue &value,
1635                                           QualType destType) {
1636   auto nonMemoryDestType = getNonMemoryType(CGM, destType);
1637   auto C = tryEmitAbstract(value, nonMemoryDestType);
1638   return (C ? emitForMemory(C, destType) : nullptr);
1639 }
1640 
1641 llvm::Constant *ConstantEmitter::tryEmitPrivateForMemory(const Expr *E,
1642                                                          QualType destType) {
1643   auto nonMemoryDestType = getNonMemoryType(CGM, destType);
1644   llvm::Constant *C = tryEmitPrivate(E, nonMemoryDestType);
1645   return (C ? emitForMemory(C, destType) : nullptr);
1646 }
1647 
1648 llvm::Constant *ConstantEmitter::tryEmitPrivateForMemory(const APValue &value,
1649                                                          QualType destType) {
1650   auto nonMemoryDestType = getNonMemoryType(CGM, destType);
1651   auto C = tryEmitPrivate(value, nonMemoryDestType);
1652   return (C ? emitForMemory(C, destType) : nullptr);
1653 }
1654 
1655 llvm::Constant *ConstantEmitter::emitForMemory(CodeGenModule &CGM,
1656                                                llvm::Constant *C,
1657                                                QualType destType) {
1658   // For an _Atomic-qualified constant, we may need to add tail padding.
1659   if (auto AT = destType->getAs<AtomicType>()) {
1660     QualType destValueType = AT->getValueType();
1661     C = emitForMemory(CGM, C, destValueType);
1662 
1663     uint64_t innerSize = CGM.getContext().getTypeSize(destValueType);
1664     uint64_t outerSize = CGM.getContext().getTypeSize(destType);
1665     if (innerSize == outerSize)
1666       return C;
1667 
1668     assert(innerSize < outerSize && "emitted over-large constant for atomic");
1669     llvm::Constant *elts[] = {
1670       C,
1671       llvm::ConstantAggregateZero::get(
1672           llvm::ArrayType::get(CGM.Int8Ty, (outerSize - innerSize) / 8))
1673     };
1674     return llvm::ConstantStruct::getAnon(elts);
1675   }
1676 
1677   // Zero-extend bool.
1678   if (C->getType()->isIntegerTy(1)) {
1679     llvm::Type *boolTy = CGM.getTypes().ConvertTypeForMem(destType);
1680     return llvm::ConstantExpr::getZExt(C, boolTy);
1681   }
1682 
1683   return C;
1684 }
1685 
1686 llvm::Constant *ConstantEmitter::tryEmitPrivate(const Expr *E,
1687                                                 QualType destType) {
1688   Expr::EvalResult Result;
1689 
1690   bool Success = false;
1691 
1692   if (destType->isReferenceType())
1693     Success = E->EvaluateAsLValue(Result, CGM.getContext());
1694   else
1695     Success = E->EvaluateAsRValue(Result, CGM.getContext(), InConstantContext);
1696 
1697   llvm::Constant *C;
1698   if (Success && !Result.HasSideEffects)
1699     C = tryEmitPrivate(Result.Val, destType);
1700   else
1701     C = ConstExprEmitter(*this).Visit(const_cast<Expr*>(E), destType);
1702 
1703   return C;
1704 }
1705 
1706 llvm::Constant *CodeGenModule::getNullPointer(llvm::PointerType *T, QualType QT) {
1707   return getTargetCodeGenInfo().getNullPointer(*this, T, QT);
1708 }
1709 
1710 namespace {
1711 /// A struct which can be used to peephole certain kinds of finalization
1712 /// that normally happen during l-value emission.
1713 struct ConstantLValue {
1714   llvm::Constant *Value;
1715   bool HasOffsetApplied;
1716 
1717   /*implicit*/ ConstantLValue(llvm::Constant *value,
1718                               bool hasOffsetApplied = false)
1719     : Value(value), HasOffsetApplied(false) {}
1720 
1721   /*implicit*/ ConstantLValue(ConstantAddress address)
1722     : ConstantLValue(address.getPointer()) {}
1723 };
1724 
1725 /// A helper class for emitting constant l-values.
1726 class ConstantLValueEmitter : public ConstStmtVisitor<ConstantLValueEmitter,
1727                                                       ConstantLValue> {
1728   CodeGenModule &CGM;
1729   ConstantEmitter &Emitter;
1730   const APValue &Value;
1731   QualType DestType;
1732 
1733   // Befriend StmtVisitorBase so that we don't have to expose Visit*.
1734   friend StmtVisitorBase;
1735 
1736 public:
1737   ConstantLValueEmitter(ConstantEmitter &emitter, const APValue &value,
1738                         QualType destType)
1739     : CGM(emitter.CGM), Emitter(emitter), Value(value), DestType(destType) {}
1740 
1741   llvm::Constant *tryEmit();
1742 
1743 private:
1744   llvm::Constant *tryEmitAbsolute(llvm::Type *destTy);
1745   ConstantLValue tryEmitBase(const APValue::LValueBase &base);
1746 
1747   ConstantLValue VisitStmt(const Stmt *S) { return nullptr; }
1748   ConstantLValue VisitConstantExpr(const ConstantExpr *E);
1749   ConstantLValue VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
1750   ConstantLValue VisitStringLiteral(const StringLiteral *E);
1751   ConstantLValue VisitObjCBoxedExpr(const ObjCBoxedExpr *E);
1752   ConstantLValue VisitObjCEncodeExpr(const ObjCEncodeExpr *E);
1753   ConstantLValue VisitObjCStringLiteral(const ObjCStringLiteral *E);
1754   ConstantLValue VisitPredefinedExpr(const PredefinedExpr *E);
1755   ConstantLValue VisitAddrLabelExpr(const AddrLabelExpr *E);
1756   ConstantLValue VisitCallExpr(const CallExpr *E);
1757   ConstantLValue VisitBlockExpr(const BlockExpr *E);
1758   ConstantLValue VisitCXXTypeidExpr(const CXXTypeidExpr *E);
1759   ConstantLValue VisitCXXUuidofExpr(const CXXUuidofExpr *E);
1760   ConstantLValue VisitMaterializeTemporaryExpr(
1761                                          const MaterializeTemporaryExpr *E);
1762 
1763   bool hasNonZeroOffset() const {
1764     return !Value.getLValueOffset().isZero();
1765   }
1766 
1767   /// Return the value offset.
1768   llvm::Constant *getOffset() {
1769     return llvm::ConstantInt::get(CGM.Int64Ty,
1770                                   Value.getLValueOffset().getQuantity());
1771   }
1772 
1773   /// Apply the value offset to the given constant.
1774   llvm::Constant *applyOffset(llvm::Constant *C) {
1775     if (!hasNonZeroOffset())
1776       return C;
1777 
1778     llvm::Type *origPtrTy = C->getType();
1779     unsigned AS = origPtrTy->getPointerAddressSpace();
1780     llvm::Type *charPtrTy = CGM.Int8Ty->getPointerTo(AS);
1781     C = llvm::ConstantExpr::getBitCast(C, charPtrTy);
1782     C = llvm::ConstantExpr::getGetElementPtr(CGM.Int8Ty, C, getOffset());
1783     C = llvm::ConstantExpr::getPointerCast(C, origPtrTy);
1784     return C;
1785   }
1786 };
1787 
1788 }
1789 
1790 llvm::Constant *ConstantLValueEmitter::tryEmit() {
1791   const APValue::LValueBase &base = Value.getLValueBase();
1792 
1793   // The destination type should be a pointer or reference
1794   // type, but it might also be a cast thereof.
1795   //
1796   // FIXME: the chain of casts required should be reflected in the APValue.
1797   // We need this in order to correctly handle things like a ptrtoint of a
1798   // non-zero null pointer and addrspace casts that aren't trivially
1799   // represented in LLVM IR.
1800   auto destTy = CGM.getTypes().ConvertTypeForMem(DestType);
1801   assert(isa<llvm::IntegerType>(destTy) || isa<llvm::PointerType>(destTy));
1802 
1803   // If there's no base at all, this is a null or absolute pointer,
1804   // possibly cast back to an integer type.
1805   if (!base) {
1806     return tryEmitAbsolute(destTy);
1807   }
1808 
1809   // Otherwise, try to emit the base.
1810   ConstantLValue result = tryEmitBase(base);
1811 
1812   // If that failed, we're done.
1813   llvm::Constant *value = result.Value;
1814   if (!value) return nullptr;
1815 
1816   // Apply the offset if necessary and not already done.
1817   if (!result.HasOffsetApplied) {
1818     value = applyOffset(value);
1819   }
1820 
1821   // Convert to the appropriate type; this could be an lvalue for
1822   // an integer.  FIXME: performAddrSpaceCast
1823   if (isa<llvm::PointerType>(destTy))
1824     return llvm::ConstantExpr::getPointerCast(value, destTy);
1825 
1826   return llvm::ConstantExpr::getPtrToInt(value, destTy);
1827 }
1828 
1829 /// Try to emit an absolute l-value, such as a null pointer or an integer
1830 /// bitcast to pointer type.
1831 llvm::Constant *
1832 ConstantLValueEmitter::tryEmitAbsolute(llvm::Type *destTy) {
1833   // If we're producing a pointer, this is easy.
1834   auto destPtrTy = cast<llvm::PointerType>(destTy);
1835   if (Value.isNullPointer()) {
1836     // FIXME: integer offsets from non-zero null pointers.
1837     return CGM.getNullPointer(destPtrTy, DestType);
1838   }
1839 
1840   // Convert the integer to a pointer-sized integer before converting it
1841   // to a pointer.
1842   // FIXME: signedness depends on the original integer type.
1843   auto intptrTy = CGM.getDataLayout().getIntPtrType(destPtrTy);
1844   llvm::Constant *C;
1845   C = llvm::ConstantExpr::getIntegerCast(getOffset(), intptrTy,
1846                                          /*isSigned*/ false);
1847   C = llvm::ConstantExpr::getIntToPtr(C, destPtrTy);
1848   return C;
1849 }
1850 
1851 ConstantLValue
1852 ConstantLValueEmitter::tryEmitBase(const APValue::LValueBase &base) {
1853   // Handle values.
1854   if (const ValueDecl *D = base.dyn_cast<const ValueDecl*>()) {
1855     if (D->hasAttr<WeakRefAttr>())
1856       return CGM.GetWeakRefReference(D).getPointer();
1857 
1858     if (auto FD = dyn_cast<FunctionDecl>(D))
1859       return CGM.GetAddrOfFunction(FD);
1860 
1861     if (auto VD = dyn_cast<VarDecl>(D)) {
1862       // We can never refer to a variable with local storage.
1863       if (!VD->hasLocalStorage()) {
1864         if (VD->isFileVarDecl() || VD->hasExternalStorage())
1865           return CGM.GetAddrOfGlobalVar(VD);
1866 
1867         if (VD->isLocalVarDecl()) {
1868           return CGM.getOrCreateStaticVarDecl(
1869               *VD, CGM.getLLVMLinkageVarDefinition(VD, /*isConstant=*/false));
1870         }
1871       }
1872     }
1873 
1874     return nullptr;
1875   }
1876 
1877   // Handle typeid(T).
1878   if (TypeInfoLValue TI = base.dyn_cast<TypeInfoLValue>()) {
1879     llvm::Type *StdTypeInfoPtrTy =
1880         CGM.getTypes().ConvertType(base.getTypeInfoType())->getPointerTo();
1881     llvm::Constant *TypeInfo =
1882         CGM.GetAddrOfRTTIDescriptor(QualType(TI.getType(), 0));
1883     if (TypeInfo->getType() != StdTypeInfoPtrTy)
1884       TypeInfo = llvm::ConstantExpr::getBitCast(TypeInfo, StdTypeInfoPtrTy);
1885     return TypeInfo;
1886   }
1887 
1888   // Otherwise, it must be an expression.
1889   return Visit(base.get<const Expr*>());
1890 }
1891 
1892 ConstantLValue
1893 ConstantLValueEmitter::VisitConstantExpr(const ConstantExpr *E) {
1894   return Visit(E->getSubExpr());
1895 }
1896 
1897 ConstantLValue
1898 ConstantLValueEmitter::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
1899   return tryEmitGlobalCompoundLiteral(CGM, Emitter.CGF, E);
1900 }
1901 
1902 ConstantLValue
1903 ConstantLValueEmitter::VisitStringLiteral(const StringLiteral *E) {
1904   return CGM.GetAddrOfConstantStringFromLiteral(E);
1905 }
1906 
1907 ConstantLValue
1908 ConstantLValueEmitter::VisitObjCEncodeExpr(const ObjCEncodeExpr *E) {
1909   return CGM.GetAddrOfConstantStringFromObjCEncode(E);
1910 }
1911 
1912 static ConstantLValue emitConstantObjCStringLiteral(const StringLiteral *S,
1913                                                     QualType T,
1914                                                     CodeGenModule &CGM) {
1915   auto C = CGM.getObjCRuntime().GenerateConstantString(S);
1916   return C.getElementBitCast(CGM.getTypes().ConvertTypeForMem(T));
1917 }
1918 
1919 ConstantLValue
1920 ConstantLValueEmitter::VisitObjCStringLiteral(const ObjCStringLiteral *E) {
1921   return emitConstantObjCStringLiteral(E->getString(), E->getType(), CGM);
1922 }
1923 
1924 ConstantLValue
1925 ConstantLValueEmitter::VisitObjCBoxedExpr(const ObjCBoxedExpr *E) {
1926   assert(E->isExpressibleAsConstantInitializer() &&
1927          "this boxed expression can't be emitted as a compile-time constant");
1928   auto *SL = cast<StringLiteral>(E->getSubExpr()->IgnoreParenCasts());
1929   return emitConstantObjCStringLiteral(SL, E->getType(), CGM);
1930 }
1931 
1932 ConstantLValue
1933 ConstantLValueEmitter::VisitPredefinedExpr(const PredefinedExpr *E) {
1934   return CGM.GetAddrOfConstantStringFromLiteral(E->getFunctionName());
1935 }
1936 
1937 ConstantLValue
1938 ConstantLValueEmitter::VisitAddrLabelExpr(const AddrLabelExpr *E) {
1939   assert(Emitter.CGF && "Invalid address of label expression outside function");
1940   llvm::Constant *Ptr = Emitter.CGF->GetAddrOfLabel(E->getLabel());
1941   Ptr = llvm::ConstantExpr::getBitCast(Ptr,
1942                                    CGM.getTypes().ConvertType(E->getType()));
1943   return Ptr;
1944 }
1945 
1946 ConstantLValue
1947 ConstantLValueEmitter::VisitCallExpr(const CallExpr *E) {
1948   unsigned builtin = E->getBuiltinCallee();
1949   if (builtin != Builtin::BI__builtin___CFStringMakeConstantString &&
1950       builtin != Builtin::BI__builtin___NSStringMakeConstantString)
1951     return nullptr;
1952 
1953   auto literal = cast<StringLiteral>(E->getArg(0)->IgnoreParenCasts());
1954   if (builtin == Builtin::BI__builtin___NSStringMakeConstantString) {
1955     return CGM.getObjCRuntime().GenerateConstantString(literal);
1956   } else {
1957     // FIXME: need to deal with UCN conversion issues.
1958     return CGM.GetAddrOfConstantCFString(literal);
1959   }
1960 }
1961 
1962 ConstantLValue
1963 ConstantLValueEmitter::VisitBlockExpr(const BlockExpr *E) {
1964   StringRef functionName;
1965   if (auto CGF = Emitter.CGF)
1966     functionName = CGF->CurFn->getName();
1967   else
1968     functionName = "global";
1969 
1970   return CGM.GetAddrOfGlobalBlock(E, functionName);
1971 }
1972 
1973 ConstantLValue
1974 ConstantLValueEmitter::VisitCXXTypeidExpr(const CXXTypeidExpr *E) {
1975   QualType T;
1976   if (E->isTypeOperand())
1977     T = E->getTypeOperand(CGM.getContext());
1978   else
1979     T = E->getExprOperand()->getType();
1980   return CGM.GetAddrOfRTTIDescriptor(T);
1981 }
1982 
1983 ConstantLValue
1984 ConstantLValueEmitter::VisitCXXUuidofExpr(const CXXUuidofExpr *E) {
1985   return CGM.GetAddrOfUuidDescriptor(E);
1986 }
1987 
1988 ConstantLValue
1989 ConstantLValueEmitter::VisitMaterializeTemporaryExpr(
1990                                             const MaterializeTemporaryExpr *E) {
1991   assert(E->getStorageDuration() == SD_Static);
1992   SmallVector<const Expr *, 2> CommaLHSs;
1993   SmallVector<SubobjectAdjustment, 2> Adjustments;
1994   const Expr *Inner = E->GetTemporaryExpr()
1995       ->skipRValueSubobjectAdjustments(CommaLHSs, Adjustments);
1996   return CGM.GetAddrOfGlobalTemporary(E, Inner);
1997 }
1998 
1999 llvm::Constant *ConstantEmitter::tryEmitPrivate(const APValue &Value,
2000                                                 QualType DestType) {
2001   switch (Value.getKind()) {
2002   case APValue::None:
2003   case APValue::Indeterminate:
2004     // Out-of-lifetime and indeterminate values can be modeled as 'undef'.
2005     return llvm::UndefValue::get(CGM.getTypes().ConvertType(DestType));
2006   case APValue::LValue:
2007     return ConstantLValueEmitter(*this, Value, DestType).tryEmit();
2008   case APValue::Int:
2009     return llvm::ConstantInt::get(CGM.getLLVMContext(), Value.getInt());
2010   case APValue::FixedPoint:
2011     return llvm::ConstantInt::get(CGM.getLLVMContext(),
2012                                   Value.getFixedPoint().getValue());
2013   case APValue::ComplexInt: {
2014     llvm::Constant *Complex[2];
2015 
2016     Complex[0] = llvm::ConstantInt::get(CGM.getLLVMContext(),
2017                                         Value.getComplexIntReal());
2018     Complex[1] = llvm::ConstantInt::get(CGM.getLLVMContext(),
2019                                         Value.getComplexIntImag());
2020 
2021     // FIXME: the target may want to specify that this is packed.
2022     llvm::StructType *STy =
2023         llvm::StructType::get(Complex[0]->getType(), Complex[1]->getType());
2024     return llvm::ConstantStruct::get(STy, Complex);
2025   }
2026   case APValue::Float: {
2027     const llvm::APFloat &Init = Value.getFloat();
2028     if (&Init.getSemantics() == &llvm::APFloat::IEEEhalf() &&
2029         !CGM.getContext().getLangOpts().NativeHalfType &&
2030         CGM.getContext().getTargetInfo().useFP16ConversionIntrinsics())
2031       return llvm::ConstantInt::get(CGM.getLLVMContext(),
2032                                     Init.bitcastToAPInt());
2033     else
2034       return llvm::ConstantFP::get(CGM.getLLVMContext(), Init);
2035   }
2036   case APValue::ComplexFloat: {
2037     llvm::Constant *Complex[2];
2038 
2039     Complex[0] = llvm::ConstantFP::get(CGM.getLLVMContext(),
2040                                        Value.getComplexFloatReal());
2041     Complex[1] = llvm::ConstantFP::get(CGM.getLLVMContext(),
2042                                        Value.getComplexFloatImag());
2043 
2044     // FIXME: the target may want to specify that this is packed.
2045     llvm::StructType *STy =
2046         llvm::StructType::get(Complex[0]->getType(), Complex[1]->getType());
2047     return llvm::ConstantStruct::get(STy, Complex);
2048   }
2049   case APValue::Vector: {
2050     unsigned NumElts = Value.getVectorLength();
2051     SmallVector<llvm::Constant *, 4> Inits(NumElts);
2052 
2053     for (unsigned I = 0; I != NumElts; ++I) {
2054       const APValue &Elt = Value.getVectorElt(I);
2055       if (Elt.isInt())
2056         Inits[I] = llvm::ConstantInt::get(CGM.getLLVMContext(), Elt.getInt());
2057       else if (Elt.isFloat())
2058         Inits[I] = llvm::ConstantFP::get(CGM.getLLVMContext(), Elt.getFloat());
2059       else
2060         llvm_unreachable("unsupported vector element type");
2061     }
2062     return llvm::ConstantVector::get(Inits);
2063   }
2064   case APValue::AddrLabelDiff: {
2065     const AddrLabelExpr *LHSExpr = Value.getAddrLabelDiffLHS();
2066     const AddrLabelExpr *RHSExpr = Value.getAddrLabelDiffRHS();
2067     llvm::Constant *LHS = tryEmitPrivate(LHSExpr, LHSExpr->getType());
2068     llvm::Constant *RHS = tryEmitPrivate(RHSExpr, RHSExpr->getType());
2069     if (!LHS || !RHS) return nullptr;
2070 
2071     // Compute difference
2072     llvm::Type *ResultType = CGM.getTypes().ConvertType(DestType);
2073     LHS = llvm::ConstantExpr::getPtrToInt(LHS, CGM.IntPtrTy);
2074     RHS = llvm::ConstantExpr::getPtrToInt(RHS, CGM.IntPtrTy);
2075     llvm::Constant *AddrLabelDiff = llvm::ConstantExpr::getSub(LHS, RHS);
2076 
2077     // LLVM is a bit sensitive about the exact format of the
2078     // address-of-label difference; make sure to truncate after
2079     // the subtraction.
2080     return llvm::ConstantExpr::getTruncOrBitCast(AddrLabelDiff, ResultType);
2081   }
2082   case APValue::Struct:
2083   case APValue::Union:
2084     return ConstStructBuilder::BuildStruct(*this, Value, DestType);
2085   case APValue::Array: {
2086     const ConstantArrayType *CAT =
2087         CGM.getContext().getAsConstantArrayType(DestType);
2088     unsigned NumElements = Value.getArraySize();
2089     unsigned NumInitElts = Value.getArrayInitializedElts();
2090 
2091     // Emit array filler, if there is one.
2092     llvm::Constant *Filler = nullptr;
2093     if (Value.hasArrayFiller()) {
2094       Filler = tryEmitAbstractForMemory(Value.getArrayFiller(),
2095                                         CAT->getElementType());
2096       if (!Filler)
2097         return nullptr;
2098     }
2099 
2100     // Emit initializer elements.
2101     SmallVector<llvm::Constant*, 16> Elts;
2102     if (Filler && Filler->isNullValue())
2103       Elts.reserve(NumInitElts + 1);
2104     else
2105       Elts.reserve(NumElements);
2106 
2107     llvm::Type *CommonElementType = nullptr;
2108     for (unsigned I = 0; I < NumInitElts; ++I) {
2109       llvm::Constant *C = tryEmitPrivateForMemory(
2110           Value.getArrayInitializedElt(I), CAT->getElementType());
2111       if (!C) return nullptr;
2112 
2113       if (I == 0)
2114         CommonElementType = C->getType();
2115       else if (C->getType() != CommonElementType)
2116         CommonElementType = nullptr;
2117       Elts.push_back(C);
2118     }
2119 
2120     // This means that the array type is probably "IncompleteType" or some
2121     // type that is not ConstantArray.
2122     if (CAT == nullptr && CommonElementType == nullptr && !NumInitElts) {
2123       const ArrayType *AT = CGM.getContext().getAsArrayType(DestType);
2124       CommonElementType = CGM.getTypes().ConvertType(AT->getElementType());
2125       llvm::ArrayType *AType = llvm::ArrayType::get(CommonElementType,
2126                                                     NumElements);
2127       return llvm::ConstantAggregateZero::get(AType);
2128     }
2129 
2130     llvm::ArrayType *Desired =
2131         cast<llvm::ArrayType>(CGM.getTypes().ConvertType(DestType));
2132     return EmitArrayConstant(CGM, Desired, CommonElementType, NumElements, Elts,
2133                              Filler);
2134   }
2135   case APValue::MemberPointer:
2136     return CGM.getCXXABI().EmitMemberPointer(Value, DestType);
2137   }
2138   llvm_unreachable("Unknown APValue kind");
2139 }
2140 
2141 llvm::GlobalVariable *CodeGenModule::getAddrOfConstantCompoundLiteralIfEmitted(
2142     const CompoundLiteralExpr *E) {
2143   return EmittedCompoundLiterals.lookup(E);
2144 }
2145 
2146 void CodeGenModule::setAddrOfConstantCompoundLiteral(
2147     const CompoundLiteralExpr *CLE, llvm::GlobalVariable *GV) {
2148   bool Ok = EmittedCompoundLiterals.insert(std::make_pair(CLE, GV)).second;
2149   (void)Ok;
2150   assert(Ok && "CLE has already been emitted!");
2151 }
2152 
2153 ConstantAddress
2154 CodeGenModule::GetAddrOfConstantCompoundLiteral(const CompoundLiteralExpr *E) {
2155   assert(E->isFileScope() && "not a file-scope compound literal expr");
2156   return tryEmitGlobalCompoundLiteral(*this, nullptr, E);
2157 }
2158 
2159 llvm::Constant *
2160 CodeGenModule::getMemberPointerConstant(const UnaryOperator *uo) {
2161   // Member pointer constants always have a very particular form.
2162   const MemberPointerType *type = cast<MemberPointerType>(uo->getType());
2163   const ValueDecl *decl = cast<DeclRefExpr>(uo->getSubExpr())->getDecl();
2164 
2165   // A member function pointer.
2166   if (const CXXMethodDecl *method = dyn_cast<CXXMethodDecl>(decl))
2167     return getCXXABI().EmitMemberFunctionPointer(method);
2168 
2169   // Otherwise, a member data pointer.
2170   uint64_t fieldOffset = getContext().getFieldOffset(decl);
2171   CharUnits chars = getContext().toCharUnitsFromBits((int64_t) fieldOffset);
2172   return getCXXABI().EmitMemberDataPointer(type, chars);
2173 }
2174 
2175 static llvm::Constant *EmitNullConstantForBase(CodeGenModule &CGM,
2176                                                llvm::Type *baseType,
2177                                                const CXXRecordDecl *base);
2178 
2179 static llvm::Constant *EmitNullConstant(CodeGenModule &CGM,
2180                                         const RecordDecl *record,
2181                                         bool asCompleteObject) {
2182   const CGRecordLayout &layout = CGM.getTypes().getCGRecordLayout(record);
2183   llvm::StructType *structure =
2184     (asCompleteObject ? layout.getLLVMType()
2185                       : layout.getBaseSubobjectLLVMType());
2186 
2187   unsigned numElements = structure->getNumElements();
2188   std::vector<llvm::Constant *> elements(numElements);
2189 
2190   auto CXXR = dyn_cast<CXXRecordDecl>(record);
2191   // Fill in all the bases.
2192   if (CXXR) {
2193     for (const auto &I : CXXR->bases()) {
2194       if (I.isVirtual()) {
2195         // Ignore virtual bases; if we're laying out for a complete
2196         // object, we'll lay these out later.
2197         continue;
2198       }
2199 
2200       const CXXRecordDecl *base =
2201         cast<CXXRecordDecl>(I.getType()->castAs<RecordType>()->getDecl());
2202 
2203       // Ignore empty bases.
2204       if (base->isEmpty() ||
2205           CGM.getContext().getASTRecordLayout(base).getNonVirtualSize()
2206               .isZero())
2207         continue;
2208 
2209       unsigned fieldIndex = layout.getNonVirtualBaseLLVMFieldNo(base);
2210       llvm::Type *baseType = structure->getElementType(fieldIndex);
2211       elements[fieldIndex] = EmitNullConstantForBase(CGM, baseType, base);
2212     }
2213   }
2214 
2215   // Fill in all the fields.
2216   for (const auto *Field : record->fields()) {
2217     // Fill in non-bitfields. (Bitfields always use a zero pattern, which we
2218     // will fill in later.)
2219     if (!Field->isBitField()) {
2220       unsigned fieldIndex = layout.getLLVMFieldNo(Field);
2221       elements[fieldIndex] = CGM.EmitNullConstant(Field->getType());
2222     }
2223 
2224     // For unions, stop after the first named field.
2225     if (record->isUnion()) {
2226       if (Field->getIdentifier())
2227         break;
2228       if (const auto *FieldRD = Field->getType()->getAsRecordDecl())
2229         if (FieldRD->findFirstNamedDataMember())
2230           break;
2231     }
2232   }
2233 
2234   // Fill in the virtual bases, if we're working with the complete object.
2235   if (CXXR && asCompleteObject) {
2236     for (const auto &I : CXXR->vbases()) {
2237       const CXXRecordDecl *base =
2238         cast<CXXRecordDecl>(I.getType()->castAs<RecordType>()->getDecl());
2239 
2240       // Ignore empty bases.
2241       if (base->isEmpty())
2242         continue;
2243 
2244       unsigned fieldIndex = layout.getVirtualBaseIndex(base);
2245 
2246       // We might have already laid this field out.
2247       if (elements[fieldIndex]) continue;
2248 
2249       llvm::Type *baseType = structure->getElementType(fieldIndex);
2250       elements[fieldIndex] = EmitNullConstantForBase(CGM, baseType, base);
2251     }
2252   }
2253 
2254   // Now go through all other fields and zero them out.
2255   for (unsigned i = 0; i != numElements; ++i) {
2256     if (!elements[i])
2257       elements[i] = llvm::Constant::getNullValue(structure->getElementType(i));
2258   }
2259 
2260   return llvm::ConstantStruct::get(structure, elements);
2261 }
2262 
2263 /// Emit the null constant for a base subobject.
2264 static llvm::Constant *EmitNullConstantForBase(CodeGenModule &CGM,
2265                                                llvm::Type *baseType,
2266                                                const CXXRecordDecl *base) {
2267   const CGRecordLayout &baseLayout = CGM.getTypes().getCGRecordLayout(base);
2268 
2269   // Just zero out bases that don't have any pointer to data members.
2270   if (baseLayout.isZeroInitializableAsBase())
2271     return llvm::Constant::getNullValue(baseType);
2272 
2273   // Otherwise, we can just use its null constant.
2274   return EmitNullConstant(CGM, base, /*asCompleteObject=*/false);
2275 }
2276 
2277 llvm::Constant *ConstantEmitter::emitNullForMemory(CodeGenModule &CGM,
2278                                                    QualType T) {
2279   return emitForMemory(CGM, CGM.EmitNullConstant(T), T);
2280 }
2281 
2282 llvm::Constant *CodeGenModule::EmitNullConstant(QualType T) {
2283   if (T->getAs<PointerType>())
2284     return getNullPointer(
2285         cast<llvm::PointerType>(getTypes().ConvertTypeForMem(T)), T);
2286 
2287   if (getTypes().isZeroInitializable(T))
2288     return llvm::Constant::getNullValue(getTypes().ConvertTypeForMem(T));
2289 
2290   if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(T)) {
2291     llvm::ArrayType *ATy =
2292       cast<llvm::ArrayType>(getTypes().ConvertTypeForMem(T));
2293 
2294     QualType ElementTy = CAT->getElementType();
2295 
2296     llvm::Constant *Element =
2297       ConstantEmitter::emitNullForMemory(*this, ElementTy);
2298     unsigned NumElements = CAT->getSize().getZExtValue();
2299     SmallVector<llvm::Constant *, 8> Array(NumElements, Element);
2300     return llvm::ConstantArray::get(ATy, Array);
2301   }
2302 
2303   if (const RecordType *RT = T->getAs<RecordType>())
2304     return ::EmitNullConstant(*this, RT->getDecl(), /*complete object*/ true);
2305 
2306   assert(T->isMemberDataPointerType() &&
2307          "Should only see pointers to data members here!");
2308 
2309   return getCXXABI().EmitNullMemberPointer(T->castAs<MemberPointerType>());
2310 }
2311 
2312 llvm::Constant *
2313 CodeGenModule::EmitNullConstantForBase(const CXXRecordDecl *Record) {
2314   return ::EmitNullConstant(*this, Record, false);
2315 }
2316