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() &&
679         !declaresSameEntity(ILE->getInitializedFieldInUnion(), Field))
680       continue;
681 
682     // Don't emit anonymous bitfields or zero-sized fields.
683     if (Field->isUnnamedBitfield() || Field->isZeroSize(CGM.getContext()))
684       continue;
685 
686     // Get the initializer.  A struct can include fields without initializers,
687     // we just use explicit null values for them.
688     Expr *Init = nullptr;
689     if (ElementNo < ILE->getNumInits())
690       Init = ILE->getInit(ElementNo++);
691     if (Init && isa<NoInitExpr>(Init))
692       continue;
693 
694     // When emitting a DesignatedInitUpdateExpr, a nested InitListExpr
695     // represents additional overwriting of our current constant value, and not
696     // a new constant to emit independently.
697     if (AllowOverwrite &&
698         (Field->getType()->isArrayType() || Field->getType()->isRecordType())) {
699       if (auto *SubILE = dyn_cast<InitListExpr>(Init)) {
700         CharUnits Offset = CGM.getContext().toCharUnitsFromBits(
701             Layout.getFieldOffset(FieldNo));
702         if (!EmitDesignatedInitUpdater(Emitter, Builder, StartOffset + Offset,
703                                        Field->getType(), SubILE))
704           return false;
705         // If we split apart the field's value, try to collapse it down to a
706         // single value now.
707         Builder.condense(StartOffset + Offset,
708                          CGM.getTypes().ConvertTypeForMem(Field->getType()));
709         continue;
710       }
711     }
712 
713     llvm::Constant *EltInit =
714         Init ? Emitter.tryEmitPrivateForMemory(Init, Field->getType())
715              : Emitter.emitNullForMemory(Field->getType());
716     if (!EltInit)
717       return false;
718 
719     if (!Field->isBitField()) {
720       // Handle non-bitfield members.
721       if (!AppendField(Field, Layout.getFieldOffset(FieldNo), EltInit,
722                        AllowOverwrite))
723         return false;
724       // After emitting a non-empty field with [[no_unique_address]], we may
725       // need to overwrite its tail padding.
726       if (Field->hasAttr<NoUniqueAddressAttr>())
727         AllowOverwrite = true;
728     } else {
729       // Otherwise we have a bitfield.
730       if (auto *CI = dyn_cast<llvm::ConstantInt>(EltInit)) {
731         if (!AppendBitField(Field, Layout.getFieldOffset(FieldNo), CI,
732                             AllowOverwrite))
733           return false;
734       } else {
735         // We are trying to initialize a bitfield with a non-trivial constant,
736         // this must require run-time code.
737         return false;
738       }
739     }
740   }
741 
742   return true;
743 }
744 
745 namespace {
746 struct BaseInfo {
747   BaseInfo(const CXXRecordDecl *Decl, CharUnits Offset, unsigned Index)
748     : Decl(Decl), Offset(Offset), Index(Index) {
749   }
750 
751   const CXXRecordDecl *Decl;
752   CharUnits Offset;
753   unsigned Index;
754 
755   bool operator<(const BaseInfo &O) const { return Offset < O.Offset; }
756 };
757 }
758 
759 bool ConstStructBuilder::Build(const APValue &Val, const RecordDecl *RD,
760                                bool IsPrimaryBase,
761                                const CXXRecordDecl *VTableClass,
762                                CharUnits Offset) {
763   const ASTRecordLayout &Layout = CGM.getContext().getASTRecordLayout(RD);
764 
765   if (const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD)) {
766     // Add a vtable pointer, if we need one and it hasn't already been added.
767     if (CD->isDynamicClass() && !IsPrimaryBase) {
768       llvm::Constant *VTableAddressPoint =
769           CGM.getCXXABI().getVTableAddressPointForConstExpr(
770               BaseSubobject(CD, Offset), VTableClass);
771       if (!AppendBytes(Offset, VTableAddressPoint))
772         return false;
773     }
774 
775     // Accumulate and sort bases, in order to visit them in address order, which
776     // may not be the same as declaration order.
777     SmallVector<BaseInfo, 8> Bases;
778     Bases.reserve(CD->getNumBases());
779     unsigned BaseNo = 0;
780     for (CXXRecordDecl::base_class_const_iterator Base = CD->bases_begin(),
781          BaseEnd = CD->bases_end(); Base != BaseEnd; ++Base, ++BaseNo) {
782       assert(!Base->isVirtual() && "should not have virtual bases here");
783       const CXXRecordDecl *BD = Base->getType()->getAsCXXRecordDecl();
784       CharUnits BaseOffset = Layout.getBaseClassOffset(BD);
785       Bases.push_back(BaseInfo(BD, BaseOffset, BaseNo));
786     }
787     llvm::stable_sort(Bases);
788 
789     for (unsigned I = 0, N = Bases.size(); I != N; ++I) {
790       BaseInfo &Base = Bases[I];
791 
792       bool IsPrimaryBase = Layout.getPrimaryBase() == Base.Decl;
793       Build(Val.getStructBase(Base.Index), Base.Decl, IsPrimaryBase,
794             VTableClass, Offset + Base.Offset);
795     }
796   }
797 
798   unsigned FieldNo = 0;
799   uint64_t OffsetBits = CGM.getContext().toBits(Offset);
800 
801   bool AllowOverwrite = false;
802   for (RecordDecl::field_iterator Field = RD->field_begin(),
803        FieldEnd = RD->field_end(); Field != FieldEnd; ++Field, ++FieldNo) {
804     // If this is a union, skip all the fields that aren't being initialized.
805     if (RD->isUnion() && !declaresSameEntity(Val.getUnionField(), *Field))
806       continue;
807 
808     // Don't emit anonymous bitfields or zero-sized fields.
809     if (Field->isUnnamedBitfield() || Field->isZeroSize(CGM.getContext()))
810       continue;
811 
812     // Emit the value of the initializer.
813     const APValue &FieldValue =
814       RD->isUnion() ? Val.getUnionValue() : Val.getStructField(FieldNo);
815     llvm::Constant *EltInit =
816       Emitter.tryEmitPrivateForMemory(FieldValue, Field->getType());
817     if (!EltInit)
818       return false;
819 
820     if (!Field->isBitField()) {
821       // Handle non-bitfield members.
822       if (!AppendField(*Field, Layout.getFieldOffset(FieldNo) + OffsetBits,
823                        EltInit, AllowOverwrite))
824         return false;
825       // After emitting a non-empty field with [[no_unique_address]], we may
826       // need to overwrite its tail padding.
827       if (Field->hasAttr<NoUniqueAddressAttr>())
828         AllowOverwrite = true;
829     } else {
830       // Otherwise we have a bitfield.
831       if (!AppendBitField(*Field, Layout.getFieldOffset(FieldNo) + OffsetBits,
832                           cast<llvm::ConstantInt>(EltInit), AllowOverwrite))
833         return false;
834     }
835   }
836 
837   return true;
838 }
839 
840 llvm::Constant *ConstStructBuilder::Finalize(QualType Type) {
841   RecordDecl *RD = Type->getAs<RecordType>()->getDecl();
842   llvm::Type *ValTy = CGM.getTypes().ConvertType(Type);
843   return Builder.build(ValTy, RD->hasFlexibleArrayMember());
844 }
845 
846 llvm::Constant *ConstStructBuilder::BuildStruct(ConstantEmitter &Emitter,
847                                                 InitListExpr *ILE,
848                                                 QualType ValTy) {
849   ConstantAggregateBuilder Const(Emitter.CGM);
850   ConstStructBuilder Builder(Emitter, Const, CharUnits::Zero());
851 
852   if (!Builder.Build(ILE, /*AllowOverwrite*/false))
853     return nullptr;
854 
855   return Builder.Finalize(ValTy);
856 }
857 
858 llvm::Constant *ConstStructBuilder::BuildStruct(ConstantEmitter &Emitter,
859                                                 const APValue &Val,
860                                                 QualType ValTy) {
861   ConstantAggregateBuilder Const(Emitter.CGM);
862   ConstStructBuilder Builder(Emitter, Const, CharUnits::Zero());
863 
864   const RecordDecl *RD = ValTy->castAs<RecordType>()->getDecl();
865   const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD);
866   if (!Builder.Build(Val, RD, false, CD, CharUnits::Zero()))
867     return nullptr;
868 
869   return Builder.Finalize(ValTy);
870 }
871 
872 bool ConstStructBuilder::UpdateStruct(ConstantEmitter &Emitter,
873                                       ConstantAggregateBuilder &Const,
874                                       CharUnits Offset, InitListExpr *Updater) {
875   return ConstStructBuilder(Emitter, Const, Offset)
876       .Build(Updater, /*AllowOverwrite*/ true);
877 }
878 
879 //===----------------------------------------------------------------------===//
880 //                             ConstExprEmitter
881 //===----------------------------------------------------------------------===//
882 
883 static ConstantAddress tryEmitGlobalCompoundLiteral(CodeGenModule &CGM,
884                                                     CodeGenFunction *CGF,
885                                               const CompoundLiteralExpr *E) {
886   CharUnits Align = CGM.getContext().getTypeAlignInChars(E->getType());
887   if (llvm::GlobalVariable *Addr =
888           CGM.getAddrOfConstantCompoundLiteralIfEmitted(E))
889     return ConstantAddress(Addr, Align);
890 
891   LangAS addressSpace = E->getType().getAddressSpace();
892 
893   ConstantEmitter emitter(CGM, CGF);
894   llvm::Constant *C = emitter.tryEmitForInitializer(E->getInitializer(),
895                                                     addressSpace, E->getType());
896   if (!C) {
897     assert(!E->isFileScope() &&
898            "file-scope compound literal did not have constant initializer!");
899     return ConstantAddress::invalid();
900   }
901 
902   auto GV = new llvm::GlobalVariable(CGM.getModule(), C->getType(),
903                                      CGM.isTypeConstant(E->getType(), true),
904                                      llvm::GlobalValue::InternalLinkage,
905                                      C, ".compoundliteral", nullptr,
906                                      llvm::GlobalVariable::NotThreadLocal,
907                     CGM.getContext().getTargetAddressSpace(addressSpace));
908   emitter.finalize(GV);
909   GV->setAlignment(Align.getQuantity());
910   CGM.setAddrOfConstantCompoundLiteral(E, GV);
911   return ConstantAddress(GV, Align);
912 }
913 
914 static llvm::Constant *
915 EmitArrayConstant(CodeGenModule &CGM, llvm::ArrayType *DesiredType,
916                   llvm::Type *CommonElementType, unsigned ArrayBound,
917                   SmallVectorImpl<llvm::Constant *> &Elements,
918                   llvm::Constant *Filler) {
919   // Figure out how long the initial prefix of non-zero elements is.
920   unsigned NonzeroLength = ArrayBound;
921   if (Elements.size() < NonzeroLength && Filler->isNullValue())
922     NonzeroLength = Elements.size();
923   if (NonzeroLength == Elements.size()) {
924     while (NonzeroLength > 0 && Elements[NonzeroLength - 1]->isNullValue())
925       --NonzeroLength;
926   }
927 
928   if (NonzeroLength == 0)
929     return llvm::ConstantAggregateZero::get(DesiredType);
930 
931   // Add a zeroinitializer array filler if we have lots of trailing zeroes.
932   unsigned TrailingZeroes = ArrayBound - NonzeroLength;
933   if (TrailingZeroes >= 8) {
934     assert(Elements.size() >= NonzeroLength &&
935            "missing initializer for non-zero element");
936 
937     // If all the elements had the same type up to the trailing zeroes, emit a
938     // struct of two arrays (the nonzero data and the zeroinitializer).
939     if (CommonElementType && NonzeroLength >= 8) {
940       llvm::Constant *Initial = llvm::ConstantArray::get(
941           llvm::ArrayType::get(CommonElementType, NonzeroLength),
942           makeArrayRef(Elements).take_front(NonzeroLength));
943       Elements.resize(2);
944       Elements[0] = Initial;
945     } else {
946       Elements.resize(NonzeroLength + 1);
947     }
948 
949     auto *FillerType =
950         CommonElementType ? CommonElementType : DesiredType->getElementType();
951     FillerType = llvm::ArrayType::get(FillerType, TrailingZeroes);
952     Elements.back() = llvm::ConstantAggregateZero::get(FillerType);
953     CommonElementType = nullptr;
954   } else if (Elements.size() != ArrayBound) {
955     // Otherwise pad to the right size with the filler if necessary.
956     Elements.resize(ArrayBound, Filler);
957     if (Filler->getType() != CommonElementType)
958       CommonElementType = nullptr;
959   }
960 
961   // If all elements have the same type, just emit an array constant.
962   if (CommonElementType)
963     return llvm::ConstantArray::get(
964         llvm::ArrayType::get(CommonElementType, ArrayBound), Elements);
965 
966   // We have mixed types. Use a packed struct.
967   llvm::SmallVector<llvm::Type *, 16> Types;
968   Types.reserve(Elements.size());
969   for (llvm::Constant *Elt : Elements)
970     Types.push_back(Elt->getType());
971   llvm::StructType *SType =
972       llvm::StructType::get(CGM.getLLVMContext(), Types, true);
973   return llvm::ConstantStruct::get(SType, Elements);
974 }
975 
976 // This class only needs to handle arrays, structs and unions. Outside C++11
977 // mode, we don't currently constant fold those types.  All other types are
978 // handled by constant folding.
979 //
980 // Constant folding is currently missing support for a few features supported
981 // here: CK_ToUnion, CK_ReinterpretMemberPointer, and DesignatedInitUpdateExpr.
982 class ConstExprEmitter :
983   public StmtVisitor<ConstExprEmitter, llvm::Constant*, QualType> {
984   CodeGenModule &CGM;
985   ConstantEmitter &Emitter;
986   llvm::LLVMContext &VMContext;
987 public:
988   ConstExprEmitter(ConstantEmitter &emitter)
989     : CGM(emitter.CGM), Emitter(emitter), VMContext(CGM.getLLVMContext()) {
990   }
991 
992   //===--------------------------------------------------------------------===//
993   //                            Visitor Methods
994   //===--------------------------------------------------------------------===//
995 
996   llvm::Constant *VisitStmt(Stmt *S, QualType T) {
997     return nullptr;
998   }
999 
1000   llvm::Constant *VisitConstantExpr(ConstantExpr *CE, QualType T) {
1001     return Visit(CE->getSubExpr(), T);
1002   }
1003 
1004   llvm::Constant *VisitParenExpr(ParenExpr *PE, QualType T) {
1005     return Visit(PE->getSubExpr(), T);
1006   }
1007 
1008   llvm::Constant *
1009   VisitSubstNonTypeTemplateParmExpr(SubstNonTypeTemplateParmExpr *PE,
1010                                     QualType T) {
1011     return Visit(PE->getReplacement(), T);
1012   }
1013 
1014   llvm::Constant *VisitGenericSelectionExpr(GenericSelectionExpr *GE,
1015                                             QualType T) {
1016     return Visit(GE->getResultExpr(), T);
1017   }
1018 
1019   llvm::Constant *VisitChooseExpr(ChooseExpr *CE, QualType T) {
1020     return Visit(CE->getChosenSubExpr(), T);
1021   }
1022 
1023   llvm::Constant *VisitCompoundLiteralExpr(CompoundLiteralExpr *E, QualType T) {
1024     return Visit(E->getInitializer(), T);
1025   }
1026 
1027   llvm::Constant *VisitCastExpr(CastExpr *E, QualType destType) {
1028     if (const auto *ECE = dyn_cast<ExplicitCastExpr>(E))
1029       CGM.EmitExplicitCastExprType(ECE, Emitter.CGF);
1030     Expr *subExpr = E->getSubExpr();
1031 
1032     switch (E->getCastKind()) {
1033     case CK_ToUnion: {
1034       // GCC cast to union extension
1035       assert(E->getType()->isUnionType() &&
1036              "Destination type is not union type!");
1037 
1038       auto field = E->getTargetUnionField();
1039 
1040       auto C = Emitter.tryEmitPrivateForMemory(subExpr, field->getType());
1041       if (!C) return nullptr;
1042 
1043       auto destTy = ConvertType(destType);
1044       if (C->getType() == destTy) return C;
1045 
1046       // Build a struct with the union sub-element as the first member,
1047       // and padded to the appropriate size.
1048       SmallVector<llvm::Constant*, 2> Elts;
1049       SmallVector<llvm::Type*, 2> Types;
1050       Elts.push_back(C);
1051       Types.push_back(C->getType());
1052       unsigned CurSize = CGM.getDataLayout().getTypeAllocSize(C->getType());
1053       unsigned TotalSize = CGM.getDataLayout().getTypeAllocSize(destTy);
1054 
1055       assert(CurSize <= TotalSize && "Union size mismatch!");
1056       if (unsigned NumPadBytes = TotalSize - CurSize) {
1057         llvm::Type *Ty = CGM.Int8Ty;
1058         if (NumPadBytes > 1)
1059           Ty = llvm::ArrayType::get(Ty, NumPadBytes);
1060 
1061         Elts.push_back(llvm::UndefValue::get(Ty));
1062         Types.push_back(Ty);
1063       }
1064 
1065       llvm::StructType *STy = llvm::StructType::get(VMContext, Types, false);
1066       return llvm::ConstantStruct::get(STy, Elts);
1067     }
1068 
1069     case CK_AddressSpaceConversion: {
1070       auto C = Emitter.tryEmitPrivate(subExpr, subExpr->getType());
1071       if (!C) return nullptr;
1072       LangAS destAS = E->getType()->getPointeeType().getAddressSpace();
1073       LangAS srcAS = subExpr->getType()->getPointeeType().getAddressSpace();
1074       llvm::Type *destTy = ConvertType(E->getType());
1075       return CGM.getTargetCodeGenInfo().performAddrSpaceCast(CGM, C, srcAS,
1076                                                              destAS, destTy);
1077     }
1078 
1079     case CK_LValueToRValue:
1080     case CK_AtomicToNonAtomic:
1081     case CK_NonAtomicToAtomic:
1082     case CK_NoOp:
1083     case CK_ConstructorConversion:
1084       return Visit(subExpr, destType);
1085 
1086     case CK_IntToOCLSampler:
1087       llvm_unreachable("global sampler variables are not generated");
1088 
1089     case CK_Dependent: llvm_unreachable("saw dependent cast!");
1090 
1091     case CK_BuiltinFnToFnPtr:
1092       llvm_unreachable("builtin functions are handled elsewhere");
1093 
1094     case CK_ReinterpretMemberPointer:
1095     case CK_DerivedToBaseMemberPointer:
1096     case CK_BaseToDerivedMemberPointer: {
1097       auto C = Emitter.tryEmitPrivate(subExpr, subExpr->getType());
1098       if (!C) return nullptr;
1099       return CGM.getCXXABI().EmitMemberPointerConversion(E, C);
1100     }
1101 
1102     // These will never be supported.
1103     case CK_ObjCObjectLValueCast:
1104     case CK_ARCProduceObject:
1105     case CK_ARCConsumeObject:
1106     case CK_ARCReclaimReturnedObject:
1107     case CK_ARCExtendBlockObject:
1108     case CK_CopyAndAutoreleaseBlockObject:
1109       return nullptr;
1110 
1111     // These don't need to be handled here because Evaluate knows how to
1112     // evaluate them in the cases where they can be folded.
1113     case CK_BitCast:
1114     case CK_ToVoid:
1115     case CK_Dynamic:
1116     case CK_LValueBitCast:
1117     case CK_NullToMemberPointer:
1118     case CK_UserDefinedConversion:
1119     case CK_CPointerToObjCPointerCast:
1120     case CK_BlockPointerToObjCPointerCast:
1121     case CK_AnyPointerToBlockPointerCast:
1122     case CK_ArrayToPointerDecay:
1123     case CK_FunctionToPointerDecay:
1124     case CK_BaseToDerived:
1125     case CK_DerivedToBase:
1126     case CK_UncheckedDerivedToBase:
1127     case CK_MemberPointerToBoolean:
1128     case CK_VectorSplat:
1129     case CK_FloatingRealToComplex:
1130     case CK_FloatingComplexToReal:
1131     case CK_FloatingComplexToBoolean:
1132     case CK_FloatingComplexCast:
1133     case CK_FloatingComplexToIntegralComplex:
1134     case CK_IntegralRealToComplex:
1135     case CK_IntegralComplexToReal:
1136     case CK_IntegralComplexToBoolean:
1137     case CK_IntegralComplexCast:
1138     case CK_IntegralComplexToFloatingComplex:
1139     case CK_PointerToIntegral:
1140     case CK_PointerToBoolean:
1141     case CK_NullToPointer:
1142     case CK_IntegralCast:
1143     case CK_BooleanToSignedIntegral:
1144     case CK_IntegralToPointer:
1145     case CK_IntegralToBoolean:
1146     case CK_IntegralToFloating:
1147     case CK_FloatingToIntegral:
1148     case CK_FloatingToBoolean:
1149     case CK_FloatingCast:
1150     case CK_FixedPointCast:
1151     case CK_FixedPointToBoolean:
1152     case CK_FixedPointToIntegral:
1153     case CK_IntegralToFixedPoint:
1154     case CK_ZeroToOCLOpaqueType:
1155       return nullptr;
1156     }
1157     llvm_unreachable("Invalid CastKind");
1158   }
1159 
1160   llvm::Constant *VisitCXXDefaultInitExpr(CXXDefaultInitExpr *DIE, QualType T) {
1161     // No need for a DefaultInitExprScope: we don't handle 'this' in a
1162     // constant expression.
1163     return Visit(DIE->getExpr(), T);
1164   }
1165 
1166   llvm::Constant *VisitExprWithCleanups(ExprWithCleanups *E, QualType T) {
1167     if (!E->cleanupsHaveSideEffects())
1168       return Visit(E->getSubExpr(), T);
1169     return nullptr;
1170   }
1171 
1172   llvm::Constant *VisitMaterializeTemporaryExpr(MaterializeTemporaryExpr *E,
1173                                                 QualType T) {
1174     return Visit(E->GetTemporaryExpr(), T);
1175   }
1176 
1177   llvm::Constant *EmitArrayInitialization(InitListExpr *ILE, QualType T) {
1178     auto *CAT = CGM.getContext().getAsConstantArrayType(ILE->getType());
1179     assert(CAT && "can't emit array init for non-constant-bound array");
1180     unsigned NumInitElements = ILE->getNumInits();
1181     unsigned NumElements = CAT->getSize().getZExtValue();
1182 
1183     // Initialising an array requires us to automatically
1184     // initialise any elements that have not been initialised explicitly
1185     unsigned NumInitableElts = std::min(NumInitElements, NumElements);
1186 
1187     QualType EltType = CAT->getElementType();
1188 
1189     // Initialize remaining array elements.
1190     llvm::Constant *fillC = nullptr;
1191     if (Expr *filler = ILE->getArrayFiller()) {
1192       fillC = Emitter.tryEmitAbstractForMemory(filler, EltType);
1193       if (!fillC)
1194         return nullptr;
1195     }
1196 
1197     // Copy initializer elements.
1198     SmallVector<llvm::Constant*, 16> Elts;
1199     if (fillC && fillC->isNullValue())
1200       Elts.reserve(NumInitableElts + 1);
1201     else
1202       Elts.reserve(NumElements);
1203 
1204     llvm::Type *CommonElementType = nullptr;
1205     for (unsigned i = 0; i < NumInitableElts; ++i) {
1206       Expr *Init = ILE->getInit(i);
1207       llvm::Constant *C = Emitter.tryEmitPrivateForMemory(Init, EltType);
1208       if (!C)
1209         return nullptr;
1210       if (i == 0)
1211         CommonElementType = C->getType();
1212       else if (C->getType() != CommonElementType)
1213         CommonElementType = nullptr;
1214       Elts.push_back(C);
1215     }
1216 
1217     llvm::ArrayType *Desired =
1218         cast<llvm::ArrayType>(CGM.getTypes().ConvertType(ILE->getType()));
1219     return EmitArrayConstant(CGM, Desired, CommonElementType, NumElements, Elts,
1220                              fillC);
1221   }
1222 
1223   llvm::Constant *EmitRecordInitialization(InitListExpr *ILE, QualType T) {
1224     return ConstStructBuilder::BuildStruct(Emitter, ILE, T);
1225   }
1226 
1227   llvm::Constant *VisitImplicitValueInitExpr(ImplicitValueInitExpr* E,
1228                                              QualType T) {
1229     return CGM.EmitNullConstant(T);
1230   }
1231 
1232   llvm::Constant *VisitInitListExpr(InitListExpr *ILE, QualType T) {
1233     if (ILE->isTransparent())
1234       return Visit(ILE->getInit(0), T);
1235 
1236     if (ILE->getType()->isArrayType())
1237       return EmitArrayInitialization(ILE, T);
1238 
1239     if (ILE->getType()->isRecordType())
1240       return EmitRecordInitialization(ILE, T);
1241 
1242     return nullptr;
1243   }
1244 
1245   llvm::Constant *VisitDesignatedInitUpdateExpr(DesignatedInitUpdateExpr *E,
1246                                                 QualType destType) {
1247     auto C = Visit(E->getBase(), destType);
1248     if (!C)
1249       return nullptr;
1250 
1251     ConstantAggregateBuilder Const(CGM);
1252     Const.add(C, CharUnits::Zero(), false);
1253 
1254     if (!EmitDesignatedInitUpdater(Emitter, Const, CharUnits::Zero(), destType,
1255                                    E->getUpdater()))
1256       return nullptr;
1257 
1258     llvm::Type *ValTy = CGM.getTypes().ConvertType(destType);
1259     bool HasFlexibleArray = false;
1260     if (auto *RT = destType->getAs<RecordType>())
1261       HasFlexibleArray = RT->getDecl()->hasFlexibleArrayMember();
1262     return Const.build(ValTy, HasFlexibleArray);
1263   }
1264 
1265   llvm::Constant *VisitCXXConstructExpr(CXXConstructExpr *E, QualType Ty) {
1266     if (!E->getConstructor()->isTrivial())
1267       return nullptr;
1268 
1269     // FIXME: We should not have to call getBaseElementType here.
1270     const RecordType *RT =
1271       CGM.getContext().getBaseElementType(Ty)->getAs<RecordType>();
1272     const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
1273 
1274     // If the class doesn't have a trivial destructor, we can't emit it as a
1275     // constant expr.
1276     if (!RD->hasTrivialDestructor())
1277       return nullptr;
1278 
1279     // Only copy and default constructors can be trivial.
1280 
1281 
1282     if (E->getNumArgs()) {
1283       assert(E->getNumArgs() == 1 && "trivial ctor with > 1 argument");
1284       assert(E->getConstructor()->isCopyOrMoveConstructor() &&
1285              "trivial ctor has argument but isn't a copy/move ctor");
1286 
1287       Expr *Arg = E->getArg(0);
1288       assert(CGM.getContext().hasSameUnqualifiedType(Ty, Arg->getType()) &&
1289              "argument to copy ctor is of wrong type");
1290 
1291       return Visit(Arg, Ty);
1292     }
1293 
1294     return CGM.EmitNullConstant(Ty);
1295   }
1296 
1297   llvm::Constant *VisitStringLiteral(StringLiteral *E, QualType T) {
1298     // This is a string literal initializing an array in an initializer.
1299     return CGM.GetConstantArrayFromStringLiteral(E);
1300   }
1301 
1302   llvm::Constant *VisitObjCEncodeExpr(ObjCEncodeExpr *E, QualType T) {
1303     // This must be an @encode initializing an array in a static initializer.
1304     // Don't emit it as the address of the string, emit the string data itself
1305     // as an inline array.
1306     std::string Str;
1307     CGM.getContext().getObjCEncodingForType(E->getEncodedType(), Str);
1308     const ConstantArrayType *CAT = CGM.getContext().getAsConstantArrayType(T);
1309 
1310     // Resize the string to the right size, adding zeros at the end, or
1311     // truncating as needed.
1312     Str.resize(CAT->getSize().getZExtValue(), '\0');
1313     return llvm::ConstantDataArray::getString(VMContext, Str, false);
1314   }
1315 
1316   llvm::Constant *VisitUnaryExtension(const UnaryOperator *E, QualType T) {
1317     return Visit(E->getSubExpr(), T);
1318   }
1319 
1320   // Utility methods
1321   llvm::Type *ConvertType(QualType T) {
1322     return CGM.getTypes().ConvertType(T);
1323   }
1324 };
1325 
1326 }  // end anonymous namespace.
1327 
1328 llvm::Constant *ConstantEmitter::validateAndPopAbstract(llvm::Constant *C,
1329                                                         AbstractState saved) {
1330   Abstract = saved.OldValue;
1331 
1332   assert(saved.OldPlaceholdersSize == PlaceholderAddresses.size() &&
1333          "created a placeholder while doing an abstract emission?");
1334 
1335   // No validation necessary for now.
1336   // No cleanup to do for now.
1337   return C;
1338 }
1339 
1340 llvm::Constant *
1341 ConstantEmitter::tryEmitAbstractForInitializer(const VarDecl &D) {
1342   auto state = pushAbstract();
1343   auto C = tryEmitPrivateForVarInit(D);
1344   return validateAndPopAbstract(C, state);
1345 }
1346 
1347 llvm::Constant *
1348 ConstantEmitter::tryEmitAbstract(const Expr *E, QualType destType) {
1349   auto state = pushAbstract();
1350   auto C = tryEmitPrivate(E, destType);
1351   return validateAndPopAbstract(C, state);
1352 }
1353 
1354 llvm::Constant *
1355 ConstantEmitter::tryEmitAbstract(const APValue &value, QualType destType) {
1356   auto state = pushAbstract();
1357   auto C = tryEmitPrivate(value, destType);
1358   return validateAndPopAbstract(C, state);
1359 }
1360 
1361 llvm::Constant *
1362 ConstantEmitter::emitAbstract(const Expr *E, QualType destType) {
1363   auto state = pushAbstract();
1364   auto C = tryEmitPrivate(E, destType);
1365   C = validateAndPopAbstract(C, state);
1366   if (!C) {
1367     CGM.Error(E->getExprLoc(),
1368               "internal error: could not emit constant value \"abstractly\"");
1369     C = CGM.EmitNullConstant(destType);
1370   }
1371   return C;
1372 }
1373 
1374 llvm::Constant *
1375 ConstantEmitter::emitAbstract(SourceLocation loc, const APValue &value,
1376                               QualType destType) {
1377   auto state = pushAbstract();
1378   auto C = tryEmitPrivate(value, destType);
1379   C = validateAndPopAbstract(C, state);
1380   if (!C) {
1381     CGM.Error(loc,
1382               "internal error: could not emit constant value \"abstractly\"");
1383     C = CGM.EmitNullConstant(destType);
1384   }
1385   return C;
1386 }
1387 
1388 llvm::Constant *ConstantEmitter::tryEmitForInitializer(const VarDecl &D) {
1389   initializeNonAbstract(D.getType().getAddressSpace());
1390   return markIfFailed(tryEmitPrivateForVarInit(D));
1391 }
1392 
1393 llvm::Constant *ConstantEmitter::tryEmitForInitializer(const Expr *E,
1394                                                        LangAS destAddrSpace,
1395                                                        QualType destType) {
1396   initializeNonAbstract(destAddrSpace);
1397   return markIfFailed(tryEmitPrivateForMemory(E, destType));
1398 }
1399 
1400 llvm::Constant *ConstantEmitter::emitForInitializer(const APValue &value,
1401                                                     LangAS destAddrSpace,
1402                                                     QualType destType) {
1403   initializeNonAbstract(destAddrSpace);
1404   auto C = tryEmitPrivateForMemory(value, destType);
1405   assert(C && "couldn't emit constant value non-abstractly?");
1406   return C;
1407 }
1408 
1409 llvm::GlobalValue *ConstantEmitter::getCurrentAddrPrivate() {
1410   assert(!Abstract && "cannot get current address for abstract constant");
1411 
1412 
1413 
1414   // Make an obviously ill-formed global that should blow up compilation
1415   // if it survives.
1416   auto global = new llvm::GlobalVariable(CGM.getModule(), CGM.Int8Ty, true,
1417                                          llvm::GlobalValue::PrivateLinkage,
1418                                          /*init*/ nullptr,
1419                                          /*name*/ "",
1420                                          /*before*/ nullptr,
1421                                          llvm::GlobalVariable::NotThreadLocal,
1422                                          CGM.getContext().getTargetAddressSpace(DestAddressSpace));
1423 
1424   PlaceholderAddresses.push_back(std::make_pair(nullptr, global));
1425 
1426   return global;
1427 }
1428 
1429 void ConstantEmitter::registerCurrentAddrPrivate(llvm::Constant *signal,
1430                                            llvm::GlobalValue *placeholder) {
1431   assert(!PlaceholderAddresses.empty());
1432   assert(PlaceholderAddresses.back().first == nullptr);
1433   assert(PlaceholderAddresses.back().second == placeholder);
1434   PlaceholderAddresses.back().first = signal;
1435 }
1436 
1437 namespace {
1438   struct ReplacePlaceholders {
1439     CodeGenModule &CGM;
1440 
1441     /// The base address of the global.
1442     llvm::Constant *Base;
1443     llvm::Type *BaseValueTy = nullptr;
1444 
1445     /// The placeholder addresses that were registered during emission.
1446     llvm::DenseMap<llvm::Constant*, llvm::GlobalVariable*> PlaceholderAddresses;
1447 
1448     /// The locations of the placeholder signals.
1449     llvm::DenseMap<llvm::GlobalVariable*, llvm::Constant*> Locations;
1450 
1451     /// The current index stack.  We use a simple unsigned stack because
1452     /// we assume that placeholders will be relatively sparse in the
1453     /// initializer, but we cache the index values we find just in case.
1454     llvm::SmallVector<unsigned, 8> Indices;
1455     llvm::SmallVector<llvm::Constant*, 8> IndexValues;
1456 
1457     ReplacePlaceholders(CodeGenModule &CGM, llvm::Constant *base,
1458                         ArrayRef<std::pair<llvm::Constant*,
1459                                            llvm::GlobalVariable*>> addresses)
1460         : CGM(CGM), Base(base),
1461           PlaceholderAddresses(addresses.begin(), addresses.end()) {
1462     }
1463 
1464     void replaceInInitializer(llvm::Constant *init) {
1465       // Remember the type of the top-most initializer.
1466       BaseValueTy = init->getType();
1467 
1468       // Initialize the stack.
1469       Indices.push_back(0);
1470       IndexValues.push_back(nullptr);
1471 
1472       // Recurse into the initializer.
1473       findLocations(init);
1474 
1475       // Check invariants.
1476       assert(IndexValues.size() == Indices.size() && "mismatch");
1477       assert(Indices.size() == 1 && "didn't pop all indices");
1478 
1479       // Do the replacement; this basically invalidates 'init'.
1480       assert(Locations.size() == PlaceholderAddresses.size() &&
1481              "missed a placeholder?");
1482 
1483       // We're iterating over a hashtable, so this would be a source of
1484       // non-determinism in compiler output *except* that we're just
1485       // messing around with llvm::Constant structures, which never itself
1486       // does anything that should be visible in compiler output.
1487       for (auto &entry : Locations) {
1488         assert(entry.first->getParent() == nullptr && "not a placeholder!");
1489         entry.first->replaceAllUsesWith(entry.second);
1490         entry.first->eraseFromParent();
1491       }
1492     }
1493 
1494   private:
1495     void findLocations(llvm::Constant *init) {
1496       // Recurse into aggregates.
1497       if (auto agg = dyn_cast<llvm::ConstantAggregate>(init)) {
1498         for (unsigned i = 0, e = agg->getNumOperands(); i != e; ++i) {
1499           Indices.push_back(i);
1500           IndexValues.push_back(nullptr);
1501 
1502           findLocations(agg->getOperand(i));
1503 
1504           IndexValues.pop_back();
1505           Indices.pop_back();
1506         }
1507         return;
1508       }
1509 
1510       // Otherwise, check for registered constants.
1511       while (true) {
1512         auto it = PlaceholderAddresses.find(init);
1513         if (it != PlaceholderAddresses.end()) {
1514           setLocation(it->second);
1515           break;
1516         }
1517 
1518         // Look through bitcasts or other expressions.
1519         if (auto expr = dyn_cast<llvm::ConstantExpr>(init)) {
1520           init = expr->getOperand(0);
1521         } else {
1522           break;
1523         }
1524       }
1525     }
1526 
1527     void setLocation(llvm::GlobalVariable *placeholder) {
1528       assert(Locations.find(placeholder) == Locations.end() &&
1529              "already found location for placeholder!");
1530 
1531       // Lazily fill in IndexValues with the values from Indices.
1532       // We do this in reverse because we should always have a strict
1533       // prefix of indices from the start.
1534       assert(Indices.size() == IndexValues.size());
1535       for (size_t i = Indices.size() - 1; i != size_t(-1); --i) {
1536         if (IndexValues[i]) {
1537 #ifndef NDEBUG
1538           for (size_t j = 0; j != i + 1; ++j) {
1539             assert(IndexValues[j] &&
1540                    isa<llvm::ConstantInt>(IndexValues[j]) &&
1541                    cast<llvm::ConstantInt>(IndexValues[j])->getZExtValue()
1542                      == Indices[j]);
1543           }
1544 #endif
1545           break;
1546         }
1547 
1548         IndexValues[i] = llvm::ConstantInt::get(CGM.Int32Ty, Indices[i]);
1549       }
1550 
1551       // Form a GEP and then bitcast to the placeholder type so that the
1552       // replacement will succeed.
1553       llvm::Constant *location =
1554         llvm::ConstantExpr::getInBoundsGetElementPtr(BaseValueTy,
1555                                                      Base, IndexValues);
1556       location = llvm::ConstantExpr::getBitCast(location,
1557                                                 placeholder->getType());
1558 
1559       Locations.insert({placeholder, location});
1560     }
1561   };
1562 }
1563 
1564 void ConstantEmitter::finalize(llvm::GlobalVariable *global) {
1565   assert(InitializedNonAbstract &&
1566          "finalizing emitter that was used for abstract emission?");
1567   assert(!Finalized && "finalizing emitter multiple times");
1568   assert(global->getInitializer());
1569 
1570   // Note that we might also be Failed.
1571   Finalized = true;
1572 
1573   if (!PlaceholderAddresses.empty()) {
1574     ReplacePlaceholders(CGM, global, PlaceholderAddresses)
1575       .replaceInInitializer(global->getInitializer());
1576     PlaceholderAddresses.clear(); // satisfy
1577   }
1578 }
1579 
1580 ConstantEmitter::~ConstantEmitter() {
1581   assert((!InitializedNonAbstract || Finalized || Failed) &&
1582          "not finalized after being initialized for non-abstract emission");
1583   assert(PlaceholderAddresses.empty() && "unhandled placeholders");
1584 }
1585 
1586 static QualType getNonMemoryType(CodeGenModule &CGM, QualType type) {
1587   if (auto AT = type->getAs<AtomicType>()) {
1588     return CGM.getContext().getQualifiedType(AT->getValueType(),
1589                                              type.getQualifiers());
1590   }
1591   return type;
1592 }
1593 
1594 llvm::Constant *ConstantEmitter::tryEmitPrivateForVarInit(const VarDecl &D) {
1595   // Make a quick check if variable can be default NULL initialized
1596   // and avoid going through rest of code which may do, for c++11,
1597   // initialization of memory to all NULLs.
1598   if (!D.hasLocalStorage()) {
1599     QualType Ty = CGM.getContext().getBaseElementType(D.getType());
1600     if (Ty->isRecordType())
1601       if (const CXXConstructExpr *E =
1602           dyn_cast_or_null<CXXConstructExpr>(D.getInit())) {
1603         const CXXConstructorDecl *CD = E->getConstructor();
1604         if (CD->isTrivial() && CD->isDefaultConstructor())
1605           return CGM.EmitNullConstant(D.getType());
1606       }
1607     InConstantContext = true;
1608   }
1609 
1610   QualType destType = D.getType();
1611 
1612   // Try to emit the initializer.  Note that this can allow some things that
1613   // are not allowed by tryEmitPrivateForMemory alone.
1614   if (auto value = D.evaluateValue()) {
1615     return tryEmitPrivateForMemory(*value, destType);
1616   }
1617 
1618   // FIXME: Implement C++11 [basic.start.init]p2: if the initializer of a
1619   // reference is a constant expression, and the reference binds to a temporary,
1620   // then constant initialization is performed. ConstExprEmitter will
1621   // incorrectly emit a prvalue constant in this case, and the calling code
1622   // interprets that as the (pointer) value of the reference, rather than the
1623   // desired value of the referee.
1624   if (destType->isReferenceType())
1625     return nullptr;
1626 
1627   const Expr *E = D.getInit();
1628   assert(E && "No initializer to emit");
1629 
1630   auto nonMemoryDestType = getNonMemoryType(CGM, destType);
1631   auto C =
1632     ConstExprEmitter(*this).Visit(const_cast<Expr*>(E), nonMemoryDestType);
1633   return (C ? emitForMemory(C, destType) : nullptr);
1634 }
1635 
1636 llvm::Constant *
1637 ConstantEmitter::tryEmitAbstractForMemory(const Expr *E, QualType destType) {
1638   auto nonMemoryDestType = getNonMemoryType(CGM, destType);
1639   auto C = tryEmitAbstract(E, nonMemoryDestType);
1640   return (C ? emitForMemory(C, destType) : nullptr);
1641 }
1642 
1643 llvm::Constant *
1644 ConstantEmitter::tryEmitAbstractForMemory(const APValue &value,
1645                                           QualType destType) {
1646   auto nonMemoryDestType = getNonMemoryType(CGM, destType);
1647   auto C = tryEmitAbstract(value, nonMemoryDestType);
1648   return (C ? emitForMemory(C, destType) : nullptr);
1649 }
1650 
1651 llvm::Constant *ConstantEmitter::tryEmitPrivateForMemory(const Expr *E,
1652                                                          QualType destType) {
1653   auto nonMemoryDestType = getNonMemoryType(CGM, destType);
1654   llvm::Constant *C = tryEmitPrivate(E, nonMemoryDestType);
1655   return (C ? emitForMemory(C, destType) : nullptr);
1656 }
1657 
1658 llvm::Constant *ConstantEmitter::tryEmitPrivateForMemory(const APValue &value,
1659                                                          QualType destType) {
1660   auto nonMemoryDestType = getNonMemoryType(CGM, destType);
1661   auto C = tryEmitPrivate(value, nonMemoryDestType);
1662   return (C ? emitForMemory(C, destType) : nullptr);
1663 }
1664 
1665 llvm::Constant *ConstantEmitter::emitForMemory(CodeGenModule &CGM,
1666                                                llvm::Constant *C,
1667                                                QualType destType) {
1668   // For an _Atomic-qualified constant, we may need to add tail padding.
1669   if (auto AT = destType->getAs<AtomicType>()) {
1670     QualType destValueType = AT->getValueType();
1671     C = emitForMemory(CGM, C, destValueType);
1672 
1673     uint64_t innerSize = CGM.getContext().getTypeSize(destValueType);
1674     uint64_t outerSize = CGM.getContext().getTypeSize(destType);
1675     if (innerSize == outerSize)
1676       return C;
1677 
1678     assert(innerSize < outerSize && "emitted over-large constant for atomic");
1679     llvm::Constant *elts[] = {
1680       C,
1681       llvm::ConstantAggregateZero::get(
1682           llvm::ArrayType::get(CGM.Int8Ty, (outerSize - innerSize) / 8))
1683     };
1684     return llvm::ConstantStruct::getAnon(elts);
1685   }
1686 
1687   // Zero-extend bool.
1688   if (C->getType()->isIntegerTy(1)) {
1689     llvm::Type *boolTy = CGM.getTypes().ConvertTypeForMem(destType);
1690     return llvm::ConstantExpr::getZExt(C, boolTy);
1691   }
1692 
1693   return C;
1694 }
1695 
1696 llvm::Constant *ConstantEmitter::tryEmitPrivate(const Expr *E,
1697                                                 QualType destType) {
1698   Expr::EvalResult Result;
1699 
1700   bool Success = false;
1701 
1702   if (destType->isReferenceType())
1703     Success = E->EvaluateAsLValue(Result, CGM.getContext());
1704   else
1705     Success = E->EvaluateAsRValue(Result, CGM.getContext(), InConstantContext);
1706 
1707   llvm::Constant *C;
1708   if (Success && !Result.HasSideEffects)
1709     C = tryEmitPrivate(Result.Val, destType);
1710   else
1711     C = ConstExprEmitter(*this).Visit(const_cast<Expr*>(E), destType);
1712 
1713   return C;
1714 }
1715 
1716 llvm::Constant *CodeGenModule::getNullPointer(llvm::PointerType *T, QualType QT) {
1717   return getTargetCodeGenInfo().getNullPointer(*this, T, QT);
1718 }
1719 
1720 namespace {
1721 /// A struct which can be used to peephole certain kinds of finalization
1722 /// that normally happen during l-value emission.
1723 struct ConstantLValue {
1724   llvm::Constant *Value;
1725   bool HasOffsetApplied;
1726 
1727   /*implicit*/ ConstantLValue(llvm::Constant *value,
1728                               bool hasOffsetApplied = false)
1729     : Value(value), HasOffsetApplied(false) {}
1730 
1731   /*implicit*/ ConstantLValue(ConstantAddress address)
1732     : ConstantLValue(address.getPointer()) {}
1733 };
1734 
1735 /// A helper class for emitting constant l-values.
1736 class ConstantLValueEmitter : public ConstStmtVisitor<ConstantLValueEmitter,
1737                                                       ConstantLValue> {
1738   CodeGenModule &CGM;
1739   ConstantEmitter &Emitter;
1740   const APValue &Value;
1741   QualType DestType;
1742 
1743   // Befriend StmtVisitorBase so that we don't have to expose Visit*.
1744   friend StmtVisitorBase;
1745 
1746 public:
1747   ConstantLValueEmitter(ConstantEmitter &emitter, const APValue &value,
1748                         QualType destType)
1749     : CGM(emitter.CGM), Emitter(emitter), Value(value), DestType(destType) {}
1750 
1751   llvm::Constant *tryEmit();
1752 
1753 private:
1754   llvm::Constant *tryEmitAbsolute(llvm::Type *destTy);
1755   ConstantLValue tryEmitBase(const APValue::LValueBase &base);
1756 
1757   ConstantLValue VisitStmt(const Stmt *S) { return nullptr; }
1758   ConstantLValue VisitConstantExpr(const ConstantExpr *E);
1759   ConstantLValue VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
1760   ConstantLValue VisitStringLiteral(const StringLiteral *E);
1761   ConstantLValue VisitObjCBoxedExpr(const ObjCBoxedExpr *E);
1762   ConstantLValue VisitObjCEncodeExpr(const ObjCEncodeExpr *E);
1763   ConstantLValue VisitObjCStringLiteral(const ObjCStringLiteral *E);
1764   ConstantLValue VisitPredefinedExpr(const PredefinedExpr *E);
1765   ConstantLValue VisitAddrLabelExpr(const AddrLabelExpr *E);
1766   ConstantLValue VisitCallExpr(const CallExpr *E);
1767   ConstantLValue VisitBlockExpr(const BlockExpr *E);
1768   ConstantLValue VisitCXXTypeidExpr(const CXXTypeidExpr *E);
1769   ConstantLValue VisitCXXUuidofExpr(const CXXUuidofExpr *E);
1770   ConstantLValue VisitMaterializeTemporaryExpr(
1771                                          const MaterializeTemporaryExpr *E);
1772 
1773   bool hasNonZeroOffset() const {
1774     return !Value.getLValueOffset().isZero();
1775   }
1776 
1777   /// Return the value offset.
1778   llvm::Constant *getOffset() {
1779     return llvm::ConstantInt::get(CGM.Int64Ty,
1780                                   Value.getLValueOffset().getQuantity());
1781   }
1782 
1783   /// Apply the value offset to the given constant.
1784   llvm::Constant *applyOffset(llvm::Constant *C) {
1785     if (!hasNonZeroOffset())
1786       return C;
1787 
1788     llvm::Type *origPtrTy = C->getType();
1789     unsigned AS = origPtrTy->getPointerAddressSpace();
1790     llvm::Type *charPtrTy = CGM.Int8Ty->getPointerTo(AS);
1791     C = llvm::ConstantExpr::getBitCast(C, charPtrTy);
1792     C = llvm::ConstantExpr::getGetElementPtr(CGM.Int8Ty, C, getOffset());
1793     C = llvm::ConstantExpr::getPointerCast(C, origPtrTy);
1794     return C;
1795   }
1796 };
1797 
1798 }
1799 
1800 llvm::Constant *ConstantLValueEmitter::tryEmit() {
1801   const APValue::LValueBase &base = Value.getLValueBase();
1802 
1803   // The destination type should be a pointer or reference
1804   // type, but it might also be a cast thereof.
1805   //
1806   // FIXME: the chain of casts required should be reflected in the APValue.
1807   // We need this in order to correctly handle things like a ptrtoint of a
1808   // non-zero null pointer and addrspace casts that aren't trivially
1809   // represented in LLVM IR.
1810   auto destTy = CGM.getTypes().ConvertTypeForMem(DestType);
1811   assert(isa<llvm::IntegerType>(destTy) || isa<llvm::PointerType>(destTy));
1812 
1813   // If there's no base at all, this is a null or absolute pointer,
1814   // possibly cast back to an integer type.
1815   if (!base) {
1816     return tryEmitAbsolute(destTy);
1817   }
1818 
1819   // Otherwise, try to emit the base.
1820   ConstantLValue result = tryEmitBase(base);
1821 
1822   // If that failed, we're done.
1823   llvm::Constant *value = result.Value;
1824   if (!value) return nullptr;
1825 
1826   // Apply the offset if necessary and not already done.
1827   if (!result.HasOffsetApplied) {
1828     value = applyOffset(value);
1829   }
1830 
1831   // Convert to the appropriate type; this could be an lvalue for
1832   // an integer.  FIXME: performAddrSpaceCast
1833   if (isa<llvm::PointerType>(destTy))
1834     return llvm::ConstantExpr::getPointerCast(value, destTy);
1835 
1836   return llvm::ConstantExpr::getPtrToInt(value, destTy);
1837 }
1838 
1839 /// Try to emit an absolute l-value, such as a null pointer or an integer
1840 /// bitcast to pointer type.
1841 llvm::Constant *
1842 ConstantLValueEmitter::tryEmitAbsolute(llvm::Type *destTy) {
1843   // If we're producing a pointer, this is easy.
1844   auto destPtrTy = cast<llvm::PointerType>(destTy);
1845   if (Value.isNullPointer()) {
1846     // FIXME: integer offsets from non-zero null pointers.
1847     return CGM.getNullPointer(destPtrTy, DestType);
1848   }
1849 
1850   // Convert the integer to a pointer-sized integer before converting it
1851   // to a pointer.
1852   // FIXME: signedness depends on the original integer type.
1853   auto intptrTy = CGM.getDataLayout().getIntPtrType(destPtrTy);
1854   llvm::Constant *C;
1855   C = llvm::ConstantExpr::getIntegerCast(getOffset(), intptrTy,
1856                                          /*isSigned*/ false);
1857   C = llvm::ConstantExpr::getIntToPtr(C, destPtrTy);
1858   return C;
1859 }
1860 
1861 ConstantLValue
1862 ConstantLValueEmitter::tryEmitBase(const APValue::LValueBase &base) {
1863   // Handle values.
1864   if (const ValueDecl *D = base.dyn_cast<const ValueDecl*>()) {
1865     if (D->hasAttr<WeakRefAttr>())
1866       return CGM.GetWeakRefReference(D).getPointer();
1867 
1868     if (auto FD = dyn_cast<FunctionDecl>(D))
1869       return CGM.GetAddrOfFunction(FD);
1870 
1871     if (auto VD = dyn_cast<VarDecl>(D)) {
1872       // We can never refer to a variable with local storage.
1873       if (!VD->hasLocalStorage()) {
1874         if (VD->isFileVarDecl() || VD->hasExternalStorage())
1875           return CGM.GetAddrOfGlobalVar(VD);
1876 
1877         if (VD->isLocalVarDecl()) {
1878           return CGM.getOrCreateStaticVarDecl(
1879               *VD, CGM.getLLVMLinkageVarDefinition(VD, /*isConstant=*/false));
1880         }
1881       }
1882     }
1883 
1884     return nullptr;
1885   }
1886 
1887   // Handle typeid(T).
1888   if (TypeInfoLValue TI = base.dyn_cast<TypeInfoLValue>()) {
1889     llvm::Type *StdTypeInfoPtrTy =
1890         CGM.getTypes().ConvertType(base.getTypeInfoType())->getPointerTo();
1891     llvm::Constant *TypeInfo =
1892         CGM.GetAddrOfRTTIDescriptor(QualType(TI.getType(), 0));
1893     if (TypeInfo->getType() != StdTypeInfoPtrTy)
1894       TypeInfo = llvm::ConstantExpr::getBitCast(TypeInfo, StdTypeInfoPtrTy);
1895     return TypeInfo;
1896   }
1897 
1898   // Otherwise, it must be an expression.
1899   return Visit(base.get<const Expr*>());
1900 }
1901 
1902 ConstantLValue
1903 ConstantLValueEmitter::VisitConstantExpr(const ConstantExpr *E) {
1904   return Visit(E->getSubExpr());
1905 }
1906 
1907 ConstantLValue
1908 ConstantLValueEmitter::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
1909   return tryEmitGlobalCompoundLiteral(CGM, Emitter.CGF, E);
1910 }
1911 
1912 ConstantLValue
1913 ConstantLValueEmitter::VisitStringLiteral(const StringLiteral *E) {
1914   return CGM.GetAddrOfConstantStringFromLiteral(E);
1915 }
1916 
1917 ConstantLValue
1918 ConstantLValueEmitter::VisitObjCEncodeExpr(const ObjCEncodeExpr *E) {
1919   return CGM.GetAddrOfConstantStringFromObjCEncode(E);
1920 }
1921 
1922 static ConstantLValue emitConstantObjCStringLiteral(const StringLiteral *S,
1923                                                     QualType T,
1924                                                     CodeGenModule &CGM) {
1925   auto C = CGM.getObjCRuntime().GenerateConstantString(S);
1926   return C.getElementBitCast(CGM.getTypes().ConvertTypeForMem(T));
1927 }
1928 
1929 ConstantLValue
1930 ConstantLValueEmitter::VisitObjCStringLiteral(const ObjCStringLiteral *E) {
1931   return emitConstantObjCStringLiteral(E->getString(), E->getType(), CGM);
1932 }
1933 
1934 ConstantLValue
1935 ConstantLValueEmitter::VisitObjCBoxedExpr(const ObjCBoxedExpr *E) {
1936   assert(E->isExpressibleAsConstantInitializer() &&
1937          "this boxed expression can't be emitted as a compile-time constant");
1938   auto *SL = cast<StringLiteral>(E->getSubExpr()->IgnoreParenCasts());
1939   return emitConstantObjCStringLiteral(SL, E->getType(), CGM);
1940 }
1941 
1942 ConstantLValue
1943 ConstantLValueEmitter::VisitPredefinedExpr(const PredefinedExpr *E) {
1944   return CGM.GetAddrOfConstantStringFromLiteral(E->getFunctionName());
1945 }
1946 
1947 ConstantLValue
1948 ConstantLValueEmitter::VisitAddrLabelExpr(const AddrLabelExpr *E) {
1949   assert(Emitter.CGF && "Invalid address of label expression outside function");
1950   llvm::Constant *Ptr = Emitter.CGF->GetAddrOfLabel(E->getLabel());
1951   Ptr = llvm::ConstantExpr::getBitCast(Ptr,
1952                                    CGM.getTypes().ConvertType(E->getType()));
1953   return Ptr;
1954 }
1955 
1956 ConstantLValue
1957 ConstantLValueEmitter::VisitCallExpr(const CallExpr *E) {
1958   unsigned builtin = E->getBuiltinCallee();
1959   if (builtin != Builtin::BI__builtin___CFStringMakeConstantString &&
1960       builtin != Builtin::BI__builtin___NSStringMakeConstantString)
1961     return nullptr;
1962 
1963   auto literal = cast<StringLiteral>(E->getArg(0)->IgnoreParenCasts());
1964   if (builtin == Builtin::BI__builtin___NSStringMakeConstantString) {
1965     return CGM.getObjCRuntime().GenerateConstantString(literal);
1966   } else {
1967     // FIXME: need to deal with UCN conversion issues.
1968     return CGM.GetAddrOfConstantCFString(literal);
1969   }
1970 }
1971 
1972 ConstantLValue
1973 ConstantLValueEmitter::VisitBlockExpr(const BlockExpr *E) {
1974   StringRef functionName;
1975   if (auto CGF = Emitter.CGF)
1976     functionName = CGF->CurFn->getName();
1977   else
1978     functionName = "global";
1979 
1980   return CGM.GetAddrOfGlobalBlock(E, functionName);
1981 }
1982 
1983 ConstantLValue
1984 ConstantLValueEmitter::VisitCXXTypeidExpr(const CXXTypeidExpr *E) {
1985   QualType T;
1986   if (E->isTypeOperand())
1987     T = E->getTypeOperand(CGM.getContext());
1988   else
1989     T = E->getExprOperand()->getType();
1990   return CGM.GetAddrOfRTTIDescriptor(T);
1991 }
1992 
1993 ConstantLValue
1994 ConstantLValueEmitter::VisitCXXUuidofExpr(const CXXUuidofExpr *E) {
1995   return CGM.GetAddrOfUuidDescriptor(E);
1996 }
1997 
1998 ConstantLValue
1999 ConstantLValueEmitter::VisitMaterializeTemporaryExpr(
2000                                             const MaterializeTemporaryExpr *E) {
2001   assert(E->getStorageDuration() == SD_Static);
2002   SmallVector<const Expr *, 2> CommaLHSs;
2003   SmallVector<SubobjectAdjustment, 2> Adjustments;
2004   const Expr *Inner = E->GetTemporaryExpr()
2005       ->skipRValueSubobjectAdjustments(CommaLHSs, Adjustments);
2006   return CGM.GetAddrOfGlobalTemporary(E, Inner);
2007 }
2008 
2009 llvm::Constant *ConstantEmitter::tryEmitPrivate(const APValue &Value,
2010                                                 QualType DestType) {
2011   switch (Value.getKind()) {
2012   case APValue::None:
2013   case APValue::Indeterminate:
2014     // Out-of-lifetime and indeterminate values can be modeled as 'undef'.
2015     return llvm::UndefValue::get(CGM.getTypes().ConvertType(DestType));
2016   case APValue::LValue:
2017     return ConstantLValueEmitter(*this, Value, DestType).tryEmit();
2018   case APValue::Int:
2019     return llvm::ConstantInt::get(CGM.getLLVMContext(), Value.getInt());
2020   case APValue::FixedPoint:
2021     return llvm::ConstantInt::get(CGM.getLLVMContext(),
2022                                   Value.getFixedPoint().getValue());
2023   case APValue::ComplexInt: {
2024     llvm::Constant *Complex[2];
2025 
2026     Complex[0] = llvm::ConstantInt::get(CGM.getLLVMContext(),
2027                                         Value.getComplexIntReal());
2028     Complex[1] = llvm::ConstantInt::get(CGM.getLLVMContext(),
2029                                         Value.getComplexIntImag());
2030 
2031     // FIXME: the target may want to specify that this is packed.
2032     llvm::StructType *STy =
2033         llvm::StructType::get(Complex[0]->getType(), Complex[1]->getType());
2034     return llvm::ConstantStruct::get(STy, Complex);
2035   }
2036   case APValue::Float: {
2037     const llvm::APFloat &Init = Value.getFloat();
2038     if (&Init.getSemantics() == &llvm::APFloat::IEEEhalf() &&
2039         !CGM.getContext().getLangOpts().NativeHalfType &&
2040         CGM.getContext().getTargetInfo().useFP16ConversionIntrinsics())
2041       return llvm::ConstantInt::get(CGM.getLLVMContext(),
2042                                     Init.bitcastToAPInt());
2043     else
2044       return llvm::ConstantFP::get(CGM.getLLVMContext(), Init);
2045   }
2046   case APValue::ComplexFloat: {
2047     llvm::Constant *Complex[2];
2048 
2049     Complex[0] = llvm::ConstantFP::get(CGM.getLLVMContext(),
2050                                        Value.getComplexFloatReal());
2051     Complex[1] = llvm::ConstantFP::get(CGM.getLLVMContext(),
2052                                        Value.getComplexFloatImag());
2053 
2054     // FIXME: the target may want to specify that this is packed.
2055     llvm::StructType *STy =
2056         llvm::StructType::get(Complex[0]->getType(), Complex[1]->getType());
2057     return llvm::ConstantStruct::get(STy, Complex);
2058   }
2059   case APValue::Vector: {
2060     unsigned NumElts = Value.getVectorLength();
2061     SmallVector<llvm::Constant *, 4> Inits(NumElts);
2062 
2063     for (unsigned I = 0; I != NumElts; ++I) {
2064       const APValue &Elt = Value.getVectorElt(I);
2065       if (Elt.isInt())
2066         Inits[I] = llvm::ConstantInt::get(CGM.getLLVMContext(), Elt.getInt());
2067       else if (Elt.isFloat())
2068         Inits[I] = llvm::ConstantFP::get(CGM.getLLVMContext(), Elt.getFloat());
2069       else
2070         llvm_unreachable("unsupported vector element type");
2071     }
2072     return llvm::ConstantVector::get(Inits);
2073   }
2074   case APValue::AddrLabelDiff: {
2075     const AddrLabelExpr *LHSExpr = Value.getAddrLabelDiffLHS();
2076     const AddrLabelExpr *RHSExpr = Value.getAddrLabelDiffRHS();
2077     llvm::Constant *LHS = tryEmitPrivate(LHSExpr, LHSExpr->getType());
2078     llvm::Constant *RHS = tryEmitPrivate(RHSExpr, RHSExpr->getType());
2079     if (!LHS || !RHS) return nullptr;
2080 
2081     // Compute difference
2082     llvm::Type *ResultType = CGM.getTypes().ConvertType(DestType);
2083     LHS = llvm::ConstantExpr::getPtrToInt(LHS, CGM.IntPtrTy);
2084     RHS = llvm::ConstantExpr::getPtrToInt(RHS, CGM.IntPtrTy);
2085     llvm::Constant *AddrLabelDiff = llvm::ConstantExpr::getSub(LHS, RHS);
2086 
2087     // LLVM is a bit sensitive about the exact format of the
2088     // address-of-label difference; make sure to truncate after
2089     // the subtraction.
2090     return llvm::ConstantExpr::getTruncOrBitCast(AddrLabelDiff, ResultType);
2091   }
2092   case APValue::Struct:
2093   case APValue::Union:
2094     return ConstStructBuilder::BuildStruct(*this, Value, DestType);
2095   case APValue::Array: {
2096     const ConstantArrayType *CAT =
2097         CGM.getContext().getAsConstantArrayType(DestType);
2098     unsigned NumElements = Value.getArraySize();
2099     unsigned NumInitElts = Value.getArrayInitializedElts();
2100 
2101     // Emit array filler, if there is one.
2102     llvm::Constant *Filler = nullptr;
2103     if (Value.hasArrayFiller()) {
2104       Filler = tryEmitAbstractForMemory(Value.getArrayFiller(),
2105                                         CAT->getElementType());
2106       if (!Filler)
2107         return nullptr;
2108     }
2109 
2110     // Emit initializer elements.
2111     SmallVector<llvm::Constant*, 16> Elts;
2112     if (Filler && Filler->isNullValue())
2113       Elts.reserve(NumInitElts + 1);
2114     else
2115       Elts.reserve(NumElements);
2116 
2117     llvm::Type *CommonElementType = nullptr;
2118     for (unsigned I = 0; I < NumInitElts; ++I) {
2119       llvm::Constant *C = tryEmitPrivateForMemory(
2120           Value.getArrayInitializedElt(I), CAT->getElementType());
2121       if (!C) return nullptr;
2122 
2123       if (I == 0)
2124         CommonElementType = C->getType();
2125       else if (C->getType() != CommonElementType)
2126         CommonElementType = nullptr;
2127       Elts.push_back(C);
2128     }
2129 
2130     // This means that the array type is probably "IncompleteType" or some
2131     // type that is not ConstantArray.
2132     if (CAT == nullptr && CommonElementType == nullptr && !NumInitElts) {
2133       const ArrayType *AT = CGM.getContext().getAsArrayType(DestType);
2134       CommonElementType = CGM.getTypes().ConvertType(AT->getElementType());
2135       llvm::ArrayType *AType = llvm::ArrayType::get(CommonElementType,
2136                                                     NumElements);
2137       return llvm::ConstantAggregateZero::get(AType);
2138     }
2139 
2140     llvm::ArrayType *Desired =
2141         cast<llvm::ArrayType>(CGM.getTypes().ConvertType(DestType));
2142     return EmitArrayConstant(CGM, Desired, CommonElementType, NumElements, Elts,
2143                              Filler);
2144   }
2145   case APValue::MemberPointer:
2146     return CGM.getCXXABI().EmitMemberPointer(Value, DestType);
2147   }
2148   llvm_unreachable("Unknown APValue kind");
2149 }
2150 
2151 llvm::GlobalVariable *CodeGenModule::getAddrOfConstantCompoundLiteralIfEmitted(
2152     const CompoundLiteralExpr *E) {
2153   return EmittedCompoundLiterals.lookup(E);
2154 }
2155 
2156 void CodeGenModule::setAddrOfConstantCompoundLiteral(
2157     const CompoundLiteralExpr *CLE, llvm::GlobalVariable *GV) {
2158   bool Ok = EmittedCompoundLiterals.insert(std::make_pair(CLE, GV)).second;
2159   (void)Ok;
2160   assert(Ok && "CLE has already been emitted!");
2161 }
2162 
2163 ConstantAddress
2164 CodeGenModule::GetAddrOfConstantCompoundLiteral(const CompoundLiteralExpr *E) {
2165   assert(E->isFileScope() && "not a file-scope compound literal expr");
2166   return tryEmitGlobalCompoundLiteral(*this, nullptr, E);
2167 }
2168 
2169 llvm::Constant *
2170 CodeGenModule::getMemberPointerConstant(const UnaryOperator *uo) {
2171   // Member pointer constants always have a very particular form.
2172   const MemberPointerType *type = cast<MemberPointerType>(uo->getType());
2173   const ValueDecl *decl = cast<DeclRefExpr>(uo->getSubExpr())->getDecl();
2174 
2175   // A member function pointer.
2176   if (const CXXMethodDecl *method = dyn_cast<CXXMethodDecl>(decl))
2177     return getCXXABI().EmitMemberFunctionPointer(method);
2178 
2179   // Otherwise, a member data pointer.
2180   uint64_t fieldOffset = getContext().getFieldOffset(decl);
2181   CharUnits chars = getContext().toCharUnitsFromBits((int64_t) fieldOffset);
2182   return getCXXABI().EmitMemberDataPointer(type, chars);
2183 }
2184 
2185 static llvm::Constant *EmitNullConstantForBase(CodeGenModule &CGM,
2186                                                llvm::Type *baseType,
2187                                                const CXXRecordDecl *base);
2188 
2189 static llvm::Constant *EmitNullConstant(CodeGenModule &CGM,
2190                                         const RecordDecl *record,
2191                                         bool asCompleteObject) {
2192   const CGRecordLayout &layout = CGM.getTypes().getCGRecordLayout(record);
2193   llvm::StructType *structure =
2194     (asCompleteObject ? layout.getLLVMType()
2195                       : layout.getBaseSubobjectLLVMType());
2196 
2197   unsigned numElements = structure->getNumElements();
2198   std::vector<llvm::Constant *> elements(numElements);
2199 
2200   auto CXXR = dyn_cast<CXXRecordDecl>(record);
2201   // Fill in all the bases.
2202   if (CXXR) {
2203     for (const auto &I : CXXR->bases()) {
2204       if (I.isVirtual()) {
2205         // Ignore virtual bases; if we're laying out for a complete
2206         // object, we'll lay these out later.
2207         continue;
2208       }
2209 
2210       const CXXRecordDecl *base =
2211         cast<CXXRecordDecl>(I.getType()->castAs<RecordType>()->getDecl());
2212 
2213       // Ignore empty bases.
2214       if (base->isEmpty() ||
2215           CGM.getContext().getASTRecordLayout(base).getNonVirtualSize()
2216               .isZero())
2217         continue;
2218 
2219       unsigned fieldIndex = layout.getNonVirtualBaseLLVMFieldNo(base);
2220       llvm::Type *baseType = structure->getElementType(fieldIndex);
2221       elements[fieldIndex] = EmitNullConstantForBase(CGM, baseType, base);
2222     }
2223   }
2224 
2225   // Fill in all the fields.
2226   for (const auto *Field : record->fields()) {
2227     // Fill in non-bitfields. (Bitfields always use a zero pattern, which we
2228     // will fill in later.)
2229     if (!Field->isBitField() && !Field->isZeroSize(CGM.getContext())) {
2230       unsigned fieldIndex = layout.getLLVMFieldNo(Field);
2231       elements[fieldIndex] = CGM.EmitNullConstant(Field->getType());
2232     }
2233 
2234     // For unions, stop after the first named field.
2235     if (record->isUnion()) {
2236       if (Field->getIdentifier())
2237         break;
2238       if (const auto *FieldRD = Field->getType()->getAsRecordDecl())
2239         if (FieldRD->findFirstNamedDataMember())
2240           break;
2241     }
2242   }
2243 
2244   // Fill in the virtual bases, if we're working with the complete object.
2245   if (CXXR && asCompleteObject) {
2246     for (const auto &I : CXXR->vbases()) {
2247       const CXXRecordDecl *base =
2248         cast<CXXRecordDecl>(I.getType()->castAs<RecordType>()->getDecl());
2249 
2250       // Ignore empty bases.
2251       if (base->isEmpty())
2252         continue;
2253 
2254       unsigned fieldIndex = layout.getVirtualBaseIndex(base);
2255 
2256       // We might have already laid this field out.
2257       if (elements[fieldIndex]) continue;
2258 
2259       llvm::Type *baseType = structure->getElementType(fieldIndex);
2260       elements[fieldIndex] = EmitNullConstantForBase(CGM, baseType, base);
2261     }
2262   }
2263 
2264   // Now go through all other fields and zero them out.
2265   for (unsigned i = 0; i != numElements; ++i) {
2266     if (!elements[i])
2267       elements[i] = llvm::Constant::getNullValue(structure->getElementType(i));
2268   }
2269 
2270   return llvm::ConstantStruct::get(structure, elements);
2271 }
2272 
2273 /// Emit the null constant for a base subobject.
2274 static llvm::Constant *EmitNullConstantForBase(CodeGenModule &CGM,
2275                                                llvm::Type *baseType,
2276                                                const CXXRecordDecl *base) {
2277   const CGRecordLayout &baseLayout = CGM.getTypes().getCGRecordLayout(base);
2278 
2279   // Just zero out bases that don't have any pointer to data members.
2280   if (baseLayout.isZeroInitializableAsBase())
2281     return llvm::Constant::getNullValue(baseType);
2282 
2283   // Otherwise, we can just use its null constant.
2284   return EmitNullConstant(CGM, base, /*asCompleteObject=*/false);
2285 }
2286 
2287 llvm::Constant *ConstantEmitter::emitNullForMemory(CodeGenModule &CGM,
2288                                                    QualType T) {
2289   return emitForMemory(CGM, CGM.EmitNullConstant(T), T);
2290 }
2291 
2292 llvm::Constant *CodeGenModule::EmitNullConstant(QualType T) {
2293   if (T->getAs<PointerType>())
2294     return getNullPointer(
2295         cast<llvm::PointerType>(getTypes().ConvertTypeForMem(T)), T);
2296 
2297   if (getTypes().isZeroInitializable(T))
2298     return llvm::Constant::getNullValue(getTypes().ConvertTypeForMem(T));
2299 
2300   if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(T)) {
2301     llvm::ArrayType *ATy =
2302       cast<llvm::ArrayType>(getTypes().ConvertTypeForMem(T));
2303 
2304     QualType ElementTy = CAT->getElementType();
2305 
2306     llvm::Constant *Element =
2307       ConstantEmitter::emitNullForMemory(*this, ElementTy);
2308     unsigned NumElements = CAT->getSize().getZExtValue();
2309     SmallVector<llvm::Constant *, 8> Array(NumElements, Element);
2310     return llvm::ConstantArray::get(ATy, Array);
2311   }
2312 
2313   if (const RecordType *RT = T->getAs<RecordType>())
2314     return ::EmitNullConstant(*this, RT->getDecl(), /*complete object*/ true);
2315 
2316   assert(T->isMemberDataPointerType() &&
2317          "Should only see pointers to data members here!");
2318 
2319   return getCXXABI().EmitNullMemberPointer(T->castAs<MemberPointerType>());
2320 }
2321 
2322 llvm::Constant *
2323 CodeGenModule::EmitNullConstantForBase(const CXXRecordDecl *Record) {
2324   return ::EmitNullConstant(*this, Record, false);
2325 }
2326