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