1 //===--- CGExprConstant.cpp - Emit LLVM Code from Constant Expressions ----===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This contains code to emit Constant Expr nodes as LLVM code.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "CodeGenFunction.h"
15 #include "CGCXXABI.h"
16 #include "CGObjCRuntime.h"
17 #include "CGRecordLayout.h"
18 #include "CodeGenModule.h"
19 #include "clang/AST/APValue.h"
20 #include "clang/AST/ASTContext.h"
21 #include "clang/AST/RecordLayout.h"
22 #include "clang/AST/StmtVisitor.h"
23 #include "clang/Basic/Builtins.h"
24 #include "llvm/IR/Constants.h"
25 #include "llvm/IR/DataLayout.h"
26 #include "llvm/IR/Function.h"
27 #include "llvm/IR/GlobalVariable.h"
28 using namespace clang;
29 using namespace CodeGen;
30 
31 //===----------------------------------------------------------------------===//
32 //                            ConstStructBuilder
33 //===----------------------------------------------------------------------===//
34 
35 namespace {
36 class ConstExprEmitter;
37 class ConstStructBuilder {
38   CodeGenModule &CGM;
39   CodeGenFunction *CGF;
40 
41   bool Packed;
42   CharUnits NextFieldOffsetInChars;
43   CharUnits LLVMStructAlignment;
44   SmallVector<llvm::Constant *, 32> Elements;
45 public:
46   static llvm::Constant *BuildStruct(CodeGenModule &CGM, CodeGenFunction *CFG,
47                                      ConstExprEmitter *Emitter,
48                                      llvm::ConstantStruct *Base,
49                                      InitListExpr *Updater);
50   static llvm::Constant *BuildStruct(CodeGenModule &CGM, CodeGenFunction *CGF,
51                                      InitListExpr *ILE);
52   static llvm::Constant *BuildStruct(CodeGenModule &CGM, CodeGenFunction *CGF,
53                                      const APValue &Value, QualType ValTy);
54 
55 private:
56   ConstStructBuilder(CodeGenModule &CGM, CodeGenFunction *CGF)
57     : CGM(CGM), CGF(CGF), Packed(false),
58     NextFieldOffsetInChars(CharUnits::Zero()),
59     LLVMStructAlignment(CharUnits::One()) { }
60 
61   void AppendField(const FieldDecl *Field, uint64_t FieldOffset,
62                    llvm::Constant *InitExpr);
63 
64   void AppendBytes(CharUnits FieldOffsetInChars, llvm::Constant *InitCst);
65 
66   void AppendBitField(const FieldDecl *Field, uint64_t FieldOffset,
67                       llvm::ConstantInt *InitExpr);
68 
69   void AppendPadding(CharUnits PadSize);
70 
71   void AppendTailPadding(CharUnits RecordSize);
72 
73   void ConvertStructToPacked();
74 
75   bool Build(InitListExpr *ILE);
76   bool Build(ConstExprEmitter *Emitter, llvm::ConstantStruct *Base,
77              InitListExpr *Updater);
78   void Build(const APValue &Val, const RecordDecl *RD, bool IsPrimaryBase,
79              const CXXRecordDecl *VTableClass, CharUnits BaseOffset);
80   llvm::Constant *Finalize(QualType Ty);
81 
82   CharUnits getAlignment(const llvm::Constant *C) const {
83     if (Packed)  return CharUnits::One();
84     return CharUnits::fromQuantity(
85         CGM.getDataLayout().getABITypeAlignment(C->getType()));
86   }
87 
88   CharUnits getSizeInChars(const llvm::Constant *C) const {
89     return CharUnits::fromQuantity(
90         CGM.getDataLayout().getTypeAllocSize(C->getType()));
91   }
92 };
93 
94 void ConstStructBuilder::
95 AppendField(const FieldDecl *Field, uint64_t FieldOffset,
96             llvm::Constant *InitCst) {
97   const ASTContext &Context = CGM.getContext();
98 
99   CharUnits FieldOffsetInChars = Context.toCharUnitsFromBits(FieldOffset);
100 
101   AppendBytes(FieldOffsetInChars, InitCst);
102 }
103 
104 void ConstStructBuilder::
105 AppendBytes(CharUnits FieldOffsetInChars, llvm::Constant *InitCst) {
106 
107   assert(NextFieldOffsetInChars <= FieldOffsetInChars
108          && "Field offset mismatch!");
109 
110   CharUnits FieldAlignment = getAlignment(InitCst);
111 
112   // Round up the field offset to the alignment of the field type.
113   CharUnits AlignedNextFieldOffsetInChars =
114       NextFieldOffsetInChars.alignTo(FieldAlignment);
115 
116   if (AlignedNextFieldOffsetInChars < FieldOffsetInChars) {
117     // We need to append padding.
118     AppendPadding(FieldOffsetInChars - NextFieldOffsetInChars);
119 
120     assert(NextFieldOffsetInChars == FieldOffsetInChars &&
121            "Did not add enough padding!");
122 
123     AlignedNextFieldOffsetInChars =
124         NextFieldOffsetInChars.alignTo(FieldAlignment);
125   }
126 
127   if (AlignedNextFieldOffsetInChars > FieldOffsetInChars) {
128     assert(!Packed && "Alignment is wrong even with a packed struct!");
129 
130     // Convert the struct to a packed struct.
131     ConvertStructToPacked();
132 
133     // After we pack the struct, we may need to insert padding.
134     if (NextFieldOffsetInChars < FieldOffsetInChars) {
135       // We need to append padding.
136       AppendPadding(FieldOffsetInChars - NextFieldOffsetInChars);
137 
138       assert(NextFieldOffsetInChars == FieldOffsetInChars &&
139              "Did not add enough padding!");
140     }
141     AlignedNextFieldOffsetInChars = NextFieldOffsetInChars;
142   }
143 
144   // Add the field.
145   Elements.push_back(InitCst);
146   NextFieldOffsetInChars = AlignedNextFieldOffsetInChars +
147                            getSizeInChars(InitCst);
148 
149   if (Packed)
150     assert(LLVMStructAlignment == CharUnits::One() &&
151            "Packed struct not byte-aligned!");
152   else
153     LLVMStructAlignment = std::max(LLVMStructAlignment, FieldAlignment);
154 }
155 
156 void ConstStructBuilder::AppendBitField(const FieldDecl *Field,
157                                         uint64_t FieldOffset,
158                                         llvm::ConstantInt *CI) {
159   const ASTContext &Context = CGM.getContext();
160   const uint64_t CharWidth = Context.getCharWidth();
161   uint64_t NextFieldOffsetInBits = Context.toBits(NextFieldOffsetInChars);
162   if (FieldOffset > NextFieldOffsetInBits) {
163     // We need to add padding.
164     CharUnits PadSize = Context.toCharUnitsFromBits(
165         llvm::alignTo(FieldOffset - NextFieldOffsetInBits,
166                       Context.getTargetInfo().getCharAlign()));
167 
168     AppendPadding(PadSize);
169   }
170 
171   uint64_t FieldSize = Field->getBitWidthValue(Context);
172 
173   llvm::APInt FieldValue = CI->getValue();
174 
175   // Promote the size of FieldValue if necessary
176   // FIXME: This should never occur, but currently it can because initializer
177   // constants are cast to bool, and because clang is not enforcing bitfield
178   // width limits.
179   if (FieldSize > FieldValue.getBitWidth())
180     FieldValue = FieldValue.zext(FieldSize);
181 
182   // Truncate the size of FieldValue to the bit field size.
183   if (FieldSize < FieldValue.getBitWidth())
184     FieldValue = FieldValue.trunc(FieldSize);
185 
186   NextFieldOffsetInBits = Context.toBits(NextFieldOffsetInChars);
187   if (FieldOffset < NextFieldOffsetInBits) {
188     // Either part of the field or the entire field can go into the previous
189     // byte.
190     assert(!Elements.empty() && "Elements can't be empty!");
191 
192     unsigned BitsInPreviousByte = NextFieldOffsetInBits - FieldOffset;
193 
194     bool FitsCompletelyInPreviousByte =
195       BitsInPreviousByte >= FieldValue.getBitWidth();
196 
197     llvm::APInt Tmp = FieldValue;
198 
199     if (!FitsCompletelyInPreviousByte) {
200       unsigned NewFieldWidth = FieldSize - BitsInPreviousByte;
201 
202       if (CGM.getDataLayout().isBigEndian()) {
203         Tmp = Tmp.lshr(NewFieldWidth);
204         Tmp = Tmp.trunc(BitsInPreviousByte);
205 
206         // We want the remaining high bits.
207         FieldValue = FieldValue.trunc(NewFieldWidth);
208       } else {
209         Tmp = Tmp.trunc(BitsInPreviousByte);
210 
211         // We want the remaining low bits.
212         FieldValue = FieldValue.lshr(BitsInPreviousByte);
213         FieldValue = FieldValue.trunc(NewFieldWidth);
214       }
215     }
216 
217     Tmp = Tmp.zext(CharWidth);
218     if (CGM.getDataLayout().isBigEndian()) {
219       if (FitsCompletelyInPreviousByte)
220         Tmp = Tmp.shl(BitsInPreviousByte - FieldValue.getBitWidth());
221     } else {
222       Tmp = Tmp.shl(CharWidth - BitsInPreviousByte);
223     }
224 
225     // 'or' in the bits that go into the previous byte.
226     llvm::Value *LastElt = Elements.back();
227     if (llvm::ConstantInt *Val = dyn_cast<llvm::ConstantInt>(LastElt))
228       Tmp |= Val->getValue();
229     else {
230       assert(isa<llvm::UndefValue>(LastElt));
231       // If there is an undef field that we're adding to, it can either be a
232       // scalar undef (in which case, we just replace it with our field) or it
233       // is an array.  If it is an array, we have to pull one byte off the
234       // array so that the other undef bytes stay around.
235       if (!isa<llvm::IntegerType>(LastElt->getType())) {
236         // The undef padding will be a multibyte array, create a new smaller
237         // padding and then an hole for our i8 to get plopped into.
238         assert(isa<llvm::ArrayType>(LastElt->getType()) &&
239                "Expected array padding of undefs");
240         llvm::ArrayType *AT = cast<llvm::ArrayType>(LastElt->getType());
241         assert(AT->getElementType()->isIntegerTy(CharWidth) &&
242                AT->getNumElements() != 0 &&
243                "Expected non-empty array padding of undefs");
244 
245         // Remove the padding array.
246         NextFieldOffsetInChars -= CharUnits::fromQuantity(AT->getNumElements());
247         Elements.pop_back();
248 
249         // Add the padding back in two chunks.
250         AppendPadding(CharUnits::fromQuantity(AT->getNumElements()-1));
251         AppendPadding(CharUnits::One());
252         assert(isa<llvm::UndefValue>(Elements.back()) &&
253                Elements.back()->getType()->isIntegerTy(CharWidth) &&
254                "Padding addition didn't work right");
255       }
256     }
257 
258     Elements.back() = llvm::ConstantInt::get(CGM.getLLVMContext(), Tmp);
259 
260     if (FitsCompletelyInPreviousByte)
261       return;
262   }
263 
264   while (FieldValue.getBitWidth() > CharWidth) {
265     llvm::APInt Tmp;
266 
267     if (CGM.getDataLayout().isBigEndian()) {
268       // We want the high bits.
269       Tmp =
270         FieldValue.lshr(FieldValue.getBitWidth() - CharWidth).trunc(CharWidth);
271     } else {
272       // We want the low bits.
273       Tmp = FieldValue.trunc(CharWidth);
274 
275       FieldValue = FieldValue.lshr(CharWidth);
276     }
277 
278     Elements.push_back(llvm::ConstantInt::get(CGM.getLLVMContext(), Tmp));
279     ++NextFieldOffsetInChars;
280 
281     FieldValue = FieldValue.trunc(FieldValue.getBitWidth() - CharWidth);
282   }
283 
284   assert(FieldValue.getBitWidth() > 0 &&
285          "Should have at least one bit left!");
286   assert(FieldValue.getBitWidth() <= CharWidth &&
287          "Should not have more than a byte left!");
288 
289   if (FieldValue.getBitWidth() < CharWidth) {
290     if (CGM.getDataLayout().isBigEndian()) {
291       unsigned BitWidth = FieldValue.getBitWidth();
292 
293       FieldValue = FieldValue.zext(CharWidth) << (CharWidth - BitWidth);
294     } else
295       FieldValue = FieldValue.zext(CharWidth);
296   }
297 
298   // Append the last element.
299   Elements.push_back(llvm::ConstantInt::get(CGM.getLLVMContext(),
300                                             FieldValue));
301   ++NextFieldOffsetInChars;
302 }
303 
304 void ConstStructBuilder::AppendPadding(CharUnits PadSize) {
305   if (PadSize.isZero())
306     return;
307 
308   llvm::Type *Ty = CGM.Int8Ty;
309   if (PadSize > CharUnits::One())
310     Ty = llvm::ArrayType::get(Ty, PadSize.getQuantity());
311 
312   llvm::Constant *C = llvm::UndefValue::get(Ty);
313   Elements.push_back(C);
314   assert(getAlignment(C) == CharUnits::One() &&
315          "Padding must have 1 byte alignment!");
316 
317   NextFieldOffsetInChars += getSizeInChars(C);
318 }
319 
320 void ConstStructBuilder::AppendTailPadding(CharUnits RecordSize) {
321   assert(NextFieldOffsetInChars <= RecordSize &&
322          "Size mismatch!");
323 
324   AppendPadding(RecordSize - NextFieldOffsetInChars);
325 }
326 
327 void ConstStructBuilder::ConvertStructToPacked() {
328   SmallVector<llvm::Constant *, 16> PackedElements;
329   CharUnits ElementOffsetInChars = CharUnits::Zero();
330 
331   for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
332     llvm::Constant *C = Elements[i];
333 
334     CharUnits ElementAlign = CharUnits::fromQuantity(
335       CGM.getDataLayout().getABITypeAlignment(C->getType()));
336     CharUnits AlignedElementOffsetInChars =
337         ElementOffsetInChars.alignTo(ElementAlign);
338 
339     if (AlignedElementOffsetInChars > ElementOffsetInChars) {
340       // We need some padding.
341       CharUnits NumChars =
342         AlignedElementOffsetInChars - ElementOffsetInChars;
343 
344       llvm::Type *Ty = CGM.Int8Ty;
345       if (NumChars > CharUnits::One())
346         Ty = llvm::ArrayType::get(Ty, NumChars.getQuantity());
347 
348       llvm::Constant *Padding = llvm::UndefValue::get(Ty);
349       PackedElements.push_back(Padding);
350       ElementOffsetInChars += getSizeInChars(Padding);
351     }
352 
353     PackedElements.push_back(C);
354     ElementOffsetInChars += getSizeInChars(C);
355   }
356 
357   assert(ElementOffsetInChars == NextFieldOffsetInChars &&
358          "Packing the struct changed its size!");
359 
360   Elements.swap(PackedElements);
361   LLVMStructAlignment = CharUnits::One();
362   Packed = true;
363 }
364 
365 bool ConstStructBuilder::Build(InitListExpr *ILE) {
366   RecordDecl *RD = ILE->getType()->getAs<RecordType>()->getDecl();
367   const ASTRecordLayout &Layout = CGM.getContext().getASTRecordLayout(RD);
368 
369   unsigned FieldNo = 0;
370   unsigned ElementNo = 0;
371 
372   // Bail out if we have base classes. We could support these, but they only
373   // arise in C++1z where we will have already constant folded most interesting
374   // cases. FIXME: There are still a few more cases we can handle this way.
375   if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD))
376     if (CXXRD->getNumBases())
377       return false;
378 
379   for (RecordDecl::field_iterator Field = RD->field_begin(),
380        FieldEnd = RD->field_end(); Field != FieldEnd; ++Field, ++FieldNo) {
381     // If this is a union, skip all the fields that aren't being initialized.
382     if (RD->isUnion() && ILE->getInitializedFieldInUnion() != *Field)
383       continue;
384 
385     // Don't emit anonymous bitfields, they just affect layout.
386     if (Field->isUnnamedBitfield())
387       continue;
388 
389     // Get the initializer.  A struct can include fields without initializers,
390     // we just use explicit null values for them.
391     llvm::Constant *EltInit;
392     if (ElementNo < ILE->getNumInits())
393       EltInit = CGM.EmitConstantExpr(ILE->getInit(ElementNo++),
394                                      Field->getType(), CGF);
395     else
396       EltInit = CGM.EmitNullConstant(Field->getType());
397 
398     if (!EltInit)
399       return false;
400 
401     if (!Field->isBitField()) {
402       // Handle non-bitfield members.
403       AppendField(*Field, Layout.getFieldOffset(FieldNo), EltInit);
404     } else {
405       // Otherwise we have a bitfield.
406       if (auto *CI = dyn_cast<llvm::ConstantInt>(EltInit)) {
407         AppendBitField(*Field, Layout.getFieldOffset(FieldNo), CI);
408       } else {
409         // We are trying to initialize a bitfield with a non-trivial constant,
410         // this must require run-time code.
411         return false;
412       }
413     }
414   }
415 
416   return true;
417 }
418 
419 namespace {
420 struct BaseInfo {
421   BaseInfo(const CXXRecordDecl *Decl, CharUnits Offset, unsigned Index)
422     : Decl(Decl), Offset(Offset), Index(Index) {
423   }
424 
425   const CXXRecordDecl *Decl;
426   CharUnits Offset;
427   unsigned Index;
428 
429   bool operator<(const BaseInfo &O) const { return Offset < O.Offset; }
430 };
431 }
432 
433 void ConstStructBuilder::Build(const APValue &Val, const RecordDecl *RD,
434                                bool IsPrimaryBase,
435                                const CXXRecordDecl *VTableClass,
436                                CharUnits Offset) {
437   const ASTRecordLayout &Layout = CGM.getContext().getASTRecordLayout(RD);
438 
439   if (const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD)) {
440     // Add a vtable pointer, if we need one and it hasn't already been added.
441     if (CD->isDynamicClass() && !IsPrimaryBase) {
442       llvm::Constant *VTableAddressPoint =
443           CGM.getCXXABI().getVTableAddressPointForConstExpr(
444               BaseSubobject(CD, Offset), VTableClass);
445       AppendBytes(Offset, VTableAddressPoint);
446     }
447 
448     // Accumulate and sort bases, in order to visit them in address order, which
449     // may not be the same as declaration order.
450     SmallVector<BaseInfo, 8> Bases;
451     Bases.reserve(CD->getNumBases());
452     unsigned BaseNo = 0;
453     for (CXXRecordDecl::base_class_const_iterator Base = CD->bases_begin(),
454          BaseEnd = CD->bases_end(); Base != BaseEnd; ++Base, ++BaseNo) {
455       assert(!Base->isVirtual() && "should not have virtual bases here");
456       const CXXRecordDecl *BD = Base->getType()->getAsCXXRecordDecl();
457       CharUnits BaseOffset = Layout.getBaseClassOffset(BD);
458       Bases.push_back(BaseInfo(BD, BaseOffset, BaseNo));
459     }
460     std::stable_sort(Bases.begin(), Bases.end());
461 
462     for (unsigned I = 0, N = Bases.size(); I != N; ++I) {
463       BaseInfo &Base = Bases[I];
464 
465       bool IsPrimaryBase = Layout.getPrimaryBase() == Base.Decl;
466       Build(Val.getStructBase(Base.Index), Base.Decl, IsPrimaryBase,
467             VTableClass, Offset + Base.Offset);
468     }
469   }
470 
471   unsigned FieldNo = 0;
472   uint64_t OffsetBits = CGM.getContext().toBits(Offset);
473 
474   for (RecordDecl::field_iterator Field = RD->field_begin(),
475        FieldEnd = RD->field_end(); Field != FieldEnd; ++Field, ++FieldNo) {
476     // If this is a union, skip all the fields that aren't being initialized.
477     if (RD->isUnion() && Val.getUnionField() != *Field)
478       continue;
479 
480     // Don't emit anonymous bitfields, they just affect layout.
481     if (Field->isUnnamedBitfield())
482       continue;
483 
484     // Emit the value of the initializer.
485     const APValue &FieldValue =
486       RD->isUnion() ? Val.getUnionValue() : Val.getStructField(FieldNo);
487     llvm::Constant *EltInit =
488       CGM.EmitConstantValueForMemory(FieldValue, Field->getType(), CGF);
489     assert(EltInit && "EmitConstantValue can't fail");
490 
491     if (!Field->isBitField()) {
492       // Handle non-bitfield members.
493       AppendField(*Field, Layout.getFieldOffset(FieldNo) + OffsetBits, EltInit);
494     } else {
495       // Otherwise we have a bitfield.
496       AppendBitField(*Field, Layout.getFieldOffset(FieldNo) + OffsetBits,
497                      cast<llvm::ConstantInt>(EltInit));
498     }
499   }
500 }
501 
502 llvm::Constant *ConstStructBuilder::Finalize(QualType Ty) {
503   RecordDecl *RD = Ty->getAs<RecordType>()->getDecl();
504   const ASTRecordLayout &Layout = CGM.getContext().getASTRecordLayout(RD);
505 
506   CharUnits LayoutSizeInChars = Layout.getSize();
507 
508   if (NextFieldOffsetInChars > LayoutSizeInChars) {
509     // If the struct is bigger than the size of the record type,
510     // we must have a flexible array member at the end.
511     assert(RD->hasFlexibleArrayMember() &&
512            "Must have flexible array member if struct is bigger than type!");
513 
514     // No tail padding is necessary.
515   } else {
516     // Append tail padding if necessary.
517     CharUnits LLVMSizeInChars =
518         NextFieldOffsetInChars.alignTo(LLVMStructAlignment);
519 
520     if (LLVMSizeInChars != LayoutSizeInChars)
521       AppendTailPadding(LayoutSizeInChars);
522 
523     LLVMSizeInChars = NextFieldOffsetInChars.alignTo(LLVMStructAlignment);
524 
525     // Check if we need to convert the struct to a packed struct.
526     if (NextFieldOffsetInChars <= LayoutSizeInChars &&
527         LLVMSizeInChars > LayoutSizeInChars) {
528       assert(!Packed && "Size mismatch!");
529 
530       ConvertStructToPacked();
531       assert(NextFieldOffsetInChars <= LayoutSizeInChars &&
532              "Converting to packed did not help!");
533     }
534 
535     LLVMSizeInChars = NextFieldOffsetInChars.alignTo(LLVMStructAlignment);
536 
537     assert(LayoutSizeInChars == LLVMSizeInChars &&
538            "Tail padding mismatch!");
539   }
540 
541   // Pick the type to use.  If the type is layout identical to the ConvertType
542   // type then use it, otherwise use whatever the builder produced for us.
543   llvm::StructType *STy =
544       llvm::ConstantStruct::getTypeForElements(CGM.getLLVMContext(),
545                                                Elements, Packed);
546   llvm::Type *ValTy = CGM.getTypes().ConvertType(Ty);
547   if (llvm::StructType *ValSTy = dyn_cast<llvm::StructType>(ValTy)) {
548     if (ValSTy->isLayoutIdentical(STy))
549       STy = ValSTy;
550   }
551 
552   llvm::Constant *Result = llvm::ConstantStruct::get(STy, Elements);
553 
554   assert(NextFieldOffsetInChars.alignTo(getAlignment(Result)) ==
555              getSizeInChars(Result) &&
556          "Size mismatch!");
557 
558   return Result;
559 }
560 
561 llvm::Constant *ConstStructBuilder::BuildStruct(CodeGenModule &CGM,
562                                                 CodeGenFunction *CGF,
563                                                 ConstExprEmitter *Emitter,
564                                                 llvm::ConstantStruct *Base,
565                                                 InitListExpr *Updater) {
566   ConstStructBuilder Builder(CGM, CGF);
567   if (!Builder.Build(Emitter, Base, Updater))
568     return nullptr;
569   return Builder.Finalize(Updater->getType());
570 }
571 
572 llvm::Constant *ConstStructBuilder::BuildStruct(CodeGenModule &CGM,
573                                                 CodeGenFunction *CGF,
574                                                 InitListExpr *ILE) {
575   ConstStructBuilder Builder(CGM, CGF);
576 
577   if (!Builder.Build(ILE))
578     return nullptr;
579 
580   return Builder.Finalize(ILE->getType());
581 }
582 
583 llvm::Constant *ConstStructBuilder::BuildStruct(CodeGenModule &CGM,
584                                                 CodeGenFunction *CGF,
585                                                 const APValue &Val,
586                                                 QualType ValTy) {
587   ConstStructBuilder Builder(CGM, CGF);
588 
589   const RecordDecl *RD = ValTy->castAs<RecordType>()->getDecl();
590   const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD);
591   Builder.Build(Val, RD, false, CD, CharUnits::Zero());
592 
593   return Builder.Finalize(ValTy);
594 }
595 
596 
597 //===----------------------------------------------------------------------===//
598 //                             ConstExprEmitter
599 //===----------------------------------------------------------------------===//
600 
601 /// This class only needs to handle two cases:
602 /// 1) Literals (this is used by APValue emission to emit literals).
603 /// 2) Arrays, structs and unions (outside C++11 mode, we don't currently
604 ///    constant fold these types).
605 class ConstExprEmitter :
606   public StmtVisitor<ConstExprEmitter, llvm::Constant*> {
607   CodeGenModule &CGM;
608   CodeGenFunction *CGF;
609   llvm::LLVMContext &VMContext;
610 public:
611   ConstExprEmitter(CodeGenModule &cgm, CodeGenFunction *cgf)
612     : CGM(cgm), CGF(cgf), VMContext(cgm.getLLVMContext()) {
613   }
614 
615   //===--------------------------------------------------------------------===//
616   //                            Visitor Methods
617   //===--------------------------------------------------------------------===//
618 
619   llvm::Constant *VisitStmt(Stmt *S) {
620     return nullptr;
621   }
622 
623   llvm::Constant *VisitParenExpr(ParenExpr *PE) {
624     return Visit(PE->getSubExpr());
625   }
626 
627   llvm::Constant *
628   VisitSubstNonTypeTemplateParmExpr(SubstNonTypeTemplateParmExpr *PE) {
629     return Visit(PE->getReplacement());
630   }
631 
632   llvm::Constant *VisitGenericSelectionExpr(GenericSelectionExpr *GE) {
633     return Visit(GE->getResultExpr());
634   }
635 
636   llvm::Constant *VisitChooseExpr(ChooseExpr *CE) {
637     return Visit(CE->getChosenSubExpr());
638   }
639 
640   llvm::Constant *VisitCompoundLiteralExpr(CompoundLiteralExpr *E) {
641     return Visit(E->getInitializer());
642   }
643 
644   llvm::Constant *VisitCastExpr(CastExpr* E) {
645     if (const auto *ECE = dyn_cast<ExplicitCastExpr>(E))
646       CGM.EmitExplicitCastExprType(ECE, CGF);
647     Expr *subExpr = E->getSubExpr();
648     llvm::Constant *C = CGM.EmitConstantExpr(subExpr, subExpr->getType(), CGF);
649     if (!C) return nullptr;
650 
651     llvm::Type *destType = ConvertType(E->getType());
652 
653     switch (E->getCastKind()) {
654     case CK_ToUnion: {
655       // GCC cast to union extension
656       assert(E->getType()->isUnionType() &&
657              "Destination type is not union type!");
658 
659       // Build a struct with the union sub-element as the first member,
660       // and padded to the appropriate size
661       SmallVector<llvm::Constant*, 2> Elts;
662       SmallVector<llvm::Type*, 2> Types;
663       Elts.push_back(C);
664       Types.push_back(C->getType());
665       unsigned CurSize = CGM.getDataLayout().getTypeAllocSize(C->getType());
666       unsigned TotalSize = CGM.getDataLayout().getTypeAllocSize(destType);
667 
668       assert(CurSize <= TotalSize && "Union size mismatch!");
669       if (unsigned NumPadBytes = TotalSize - CurSize) {
670         llvm::Type *Ty = CGM.Int8Ty;
671         if (NumPadBytes > 1)
672           Ty = llvm::ArrayType::get(Ty, NumPadBytes);
673 
674         Elts.push_back(llvm::UndefValue::get(Ty));
675         Types.push_back(Ty);
676       }
677 
678       llvm::StructType* STy =
679         llvm::StructType::get(C->getType()->getContext(), Types, false);
680       return llvm::ConstantStruct::get(STy, Elts);
681     }
682 
683     case CK_AddressSpaceConversion:
684       return llvm::ConstantExpr::getAddrSpaceCast(C, destType);
685 
686     case CK_LValueToRValue:
687     case CK_AtomicToNonAtomic:
688     case CK_NonAtomicToAtomic:
689     case CK_NoOp:
690     case CK_ConstructorConversion:
691       return C;
692 
693     case CK_IntToOCLSampler:
694       llvm_unreachable("global sampler variables are not generated");
695 
696     case CK_Dependent: llvm_unreachable("saw dependent cast!");
697 
698     case CK_BuiltinFnToFnPtr:
699       llvm_unreachable("builtin functions are handled elsewhere");
700 
701     case CK_ReinterpretMemberPointer:
702     case CK_DerivedToBaseMemberPointer:
703     case CK_BaseToDerivedMemberPointer:
704       return CGM.getCXXABI().EmitMemberPointerConversion(E, C);
705 
706     // These will never be supported.
707     case CK_ObjCObjectLValueCast:
708     case CK_ARCProduceObject:
709     case CK_ARCConsumeObject:
710     case CK_ARCReclaimReturnedObject:
711     case CK_ARCExtendBlockObject:
712     case CK_CopyAndAutoreleaseBlockObject:
713       return nullptr;
714 
715     // These don't need to be handled here because Evaluate knows how to
716     // evaluate them in the cases where they can be folded.
717     case CK_BitCast:
718     case CK_ToVoid:
719     case CK_Dynamic:
720     case CK_LValueBitCast:
721     case CK_NullToMemberPointer:
722     case CK_UserDefinedConversion:
723     case CK_CPointerToObjCPointerCast:
724     case CK_BlockPointerToObjCPointerCast:
725     case CK_AnyPointerToBlockPointerCast:
726     case CK_ArrayToPointerDecay:
727     case CK_FunctionToPointerDecay:
728     case CK_BaseToDerived:
729     case CK_DerivedToBase:
730     case CK_UncheckedDerivedToBase:
731     case CK_MemberPointerToBoolean:
732     case CK_VectorSplat:
733     case CK_FloatingRealToComplex:
734     case CK_FloatingComplexToReal:
735     case CK_FloatingComplexToBoolean:
736     case CK_FloatingComplexCast:
737     case CK_FloatingComplexToIntegralComplex:
738     case CK_IntegralRealToComplex:
739     case CK_IntegralComplexToReal:
740     case CK_IntegralComplexToBoolean:
741     case CK_IntegralComplexCast:
742     case CK_IntegralComplexToFloatingComplex:
743     case CK_PointerToIntegral:
744     case CK_PointerToBoolean:
745     case CK_NullToPointer:
746     case CK_IntegralCast:
747     case CK_BooleanToSignedIntegral:
748     case CK_IntegralToPointer:
749     case CK_IntegralToBoolean:
750     case CK_IntegralToFloating:
751     case CK_FloatingToIntegral:
752     case CK_FloatingToBoolean:
753     case CK_FloatingCast:
754     case CK_ZeroToOCLEvent:
755       return nullptr;
756     }
757     llvm_unreachable("Invalid CastKind");
758   }
759 
760   llvm::Constant *VisitCXXDefaultArgExpr(CXXDefaultArgExpr *DAE) {
761     return Visit(DAE->getExpr());
762   }
763 
764   llvm::Constant *VisitCXXDefaultInitExpr(CXXDefaultInitExpr *DIE) {
765     // No need for a DefaultInitExprScope: we don't handle 'this' in a
766     // constant expression.
767     return Visit(DIE->getExpr());
768   }
769 
770   llvm::Constant *VisitExprWithCleanups(ExprWithCleanups *E) {
771     if (!E->cleanupsHaveSideEffects())
772       return Visit(E->getSubExpr());
773     return nullptr;
774   }
775 
776   llvm::Constant *VisitMaterializeTemporaryExpr(MaterializeTemporaryExpr *E) {
777     return Visit(E->GetTemporaryExpr());
778   }
779 
780   llvm::Constant *EmitArrayInitialization(InitListExpr *ILE) {
781     llvm::ArrayType *AType =
782         cast<llvm::ArrayType>(ConvertType(ILE->getType()));
783     llvm::Type *ElemTy = AType->getElementType();
784     unsigned NumInitElements = ILE->getNumInits();
785     unsigned NumElements = AType->getNumElements();
786 
787     // Initialising an array requires us to automatically
788     // initialise any elements that have not been initialised explicitly
789     unsigned NumInitableElts = std::min(NumInitElements, NumElements);
790 
791     // Initialize remaining array elements.
792     // FIXME: This doesn't handle member pointers correctly!
793     llvm::Constant *fillC;
794     if (Expr *filler = ILE->getArrayFiller())
795       fillC = CGM.EmitConstantExpr(filler, filler->getType(), CGF);
796     else
797       fillC = llvm::Constant::getNullValue(ElemTy);
798     if (!fillC)
799       return nullptr;
800 
801     // Try to use a ConstantAggregateZero if we can.
802     if (fillC->isNullValue() && !NumInitableElts)
803       return llvm::ConstantAggregateZero::get(AType);
804 
805     // Copy initializer elements.
806     std::vector<llvm::Constant*> Elts;
807     Elts.reserve(NumInitableElts + NumElements);
808 
809     bool RewriteType = false;
810     for (unsigned i = 0; i < NumInitableElts; ++i) {
811       Expr *Init = ILE->getInit(i);
812       llvm::Constant *C = CGM.EmitConstantExpr(Init, Init->getType(), CGF);
813       if (!C)
814         return nullptr;
815       RewriteType |= (C->getType() != ElemTy);
816       Elts.push_back(C);
817     }
818 
819     RewriteType |= (fillC->getType() != ElemTy);
820     Elts.resize(NumElements, fillC);
821 
822     if (RewriteType) {
823       // FIXME: Try to avoid packing the array
824       std::vector<llvm::Type*> Types;
825       Types.reserve(NumInitableElts + NumElements);
826       for (unsigned i = 0, e = Elts.size(); i < e; ++i)
827         Types.push_back(Elts[i]->getType());
828       llvm::StructType *SType = llvm::StructType::get(AType->getContext(),
829                                                             Types, true);
830       return llvm::ConstantStruct::get(SType, Elts);
831     }
832 
833     return llvm::ConstantArray::get(AType, Elts);
834   }
835 
836   llvm::Constant *EmitRecordInitialization(InitListExpr *ILE) {
837     return ConstStructBuilder::BuildStruct(CGM, CGF, ILE);
838   }
839 
840   llvm::Constant *VisitImplicitValueInitExpr(ImplicitValueInitExpr* E) {
841     return CGM.EmitNullConstant(E->getType());
842   }
843 
844   llvm::Constant *VisitInitListExpr(InitListExpr *ILE) {
845     if (ILE->isTransparent())
846       return Visit(ILE->getInit(0));
847 
848     if (ILE->getType()->isArrayType())
849       return EmitArrayInitialization(ILE);
850 
851     if (ILE->getType()->isRecordType())
852       return EmitRecordInitialization(ILE);
853 
854     return nullptr;
855   }
856 
857   llvm::Constant *EmitDesignatedInitUpdater(llvm::Constant *Base,
858                                             InitListExpr *Updater) {
859     QualType ExprType = Updater->getType();
860 
861     if (ExprType->isArrayType()) {
862       llvm::ArrayType *AType = cast<llvm::ArrayType>(ConvertType(ExprType));
863       llvm::Type *ElemType = AType->getElementType();
864 
865       unsigned NumInitElements = Updater->getNumInits();
866       unsigned NumElements = AType->getNumElements();
867 
868       std::vector<llvm::Constant *> Elts;
869       Elts.reserve(NumElements);
870 
871       if (llvm::ConstantDataArray *DataArray =
872             dyn_cast<llvm::ConstantDataArray>(Base))
873         for (unsigned i = 0; i != NumElements; ++i)
874           Elts.push_back(DataArray->getElementAsConstant(i));
875       else if (llvm::ConstantArray *Array =
876                  dyn_cast<llvm::ConstantArray>(Base))
877         for (unsigned i = 0; i != NumElements; ++i)
878           Elts.push_back(Array->getOperand(i));
879       else
880         return nullptr; // FIXME: other array types not implemented
881 
882       llvm::Constant *fillC = nullptr;
883       if (Expr *filler = Updater->getArrayFiller())
884         if (!isa<NoInitExpr>(filler))
885           fillC = CGM.EmitConstantExpr(filler, filler->getType(), CGF);
886       bool RewriteType = (fillC && fillC->getType() != ElemType);
887 
888       for (unsigned i = 0; i != NumElements; ++i) {
889         Expr *Init = nullptr;
890         if (i < NumInitElements)
891           Init = Updater->getInit(i);
892 
893         if (!Init && fillC)
894           Elts[i] = fillC;
895         else if (!Init || isa<NoInitExpr>(Init))
896           ; // Do nothing.
897         else if (InitListExpr *ChildILE = dyn_cast<InitListExpr>(Init))
898           Elts[i] = EmitDesignatedInitUpdater(Elts[i], ChildILE);
899         else
900           Elts[i] = CGM.EmitConstantExpr(Init, Init->getType(), CGF);
901 
902        if (!Elts[i])
903           return nullptr;
904         RewriteType |= (Elts[i]->getType() != ElemType);
905       }
906 
907       if (RewriteType) {
908         std::vector<llvm::Type *> Types;
909         Types.reserve(NumElements);
910         for (unsigned i = 0; i != NumElements; ++i)
911           Types.push_back(Elts[i]->getType());
912         llvm::StructType *SType = llvm::StructType::get(AType->getContext(),
913                                                         Types, true);
914         return llvm::ConstantStruct::get(SType, Elts);
915       }
916 
917       return llvm::ConstantArray::get(AType, Elts);
918     }
919 
920     if (ExprType->isRecordType())
921       return ConstStructBuilder::BuildStruct(CGM, CGF, this,
922                  dyn_cast<llvm::ConstantStruct>(Base), Updater);
923 
924     return nullptr;
925   }
926 
927   llvm::Constant *VisitDesignatedInitUpdateExpr(DesignatedInitUpdateExpr *E) {
928     return EmitDesignatedInitUpdater(
929                CGM.EmitConstantExpr(E->getBase(), E->getType(), CGF),
930                E->getUpdater());
931   }
932 
933   llvm::Constant *VisitCXXConstructExpr(CXXConstructExpr *E) {
934     if (!E->getConstructor()->isTrivial())
935       return nullptr;
936 
937     QualType Ty = E->getType();
938 
939     // FIXME: We should not have to call getBaseElementType here.
940     const RecordType *RT =
941       CGM.getContext().getBaseElementType(Ty)->getAs<RecordType>();
942     const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
943 
944     // If the class doesn't have a trivial destructor, we can't emit it as a
945     // constant expr.
946     if (!RD->hasTrivialDestructor())
947       return nullptr;
948 
949     // Only copy and default constructors can be trivial.
950 
951 
952     if (E->getNumArgs()) {
953       assert(E->getNumArgs() == 1 && "trivial ctor with > 1 argument");
954       assert(E->getConstructor()->isCopyOrMoveConstructor() &&
955              "trivial ctor has argument but isn't a copy/move ctor");
956 
957       Expr *Arg = E->getArg(0);
958       assert(CGM.getContext().hasSameUnqualifiedType(Ty, Arg->getType()) &&
959              "argument to copy ctor is of wrong type");
960 
961       return Visit(Arg);
962     }
963 
964     return CGM.EmitNullConstant(Ty);
965   }
966 
967   llvm::Constant *VisitStringLiteral(StringLiteral *E) {
968     return CGM.GetConstantArrayFromStringLiteral(E);
969   }
970 
971   llvm::Constant *VisitObjCEncodeExpr(ObjCEncodeExpr *E) {
972     // This must be an @encode initializing an array in a static initializer.
973     // Don't emit it as the address of the string, emit the string data itself
974     // as an inline array.
975     std::string Str;
976     CGM.getContext().getObjCEncodingForType(E->getEncodedType(), Str);
977     QualType T = E->getType();
978     if (T->getTypeClass() == Type::TypeOfExpr)
979       T = cast<TypeOfExprType>(T)->getUnderlyingExpr()->getType();
980     const ConstantArrayType *CAT = cast<ConstantArrayType>(T);
981 
982     // Resize the string to the right size, adding zeros at the end, or
983     // truncating as needed.
984     Str.resize(CAT->getSize().getZExtValue(), '\0');
985     return llvm::ConstantDataArray::getString(VMContext, Str, false);
986   }
987 
988   llvm::Constant *VisitUnaryExtension(const UnaryOperator *E) {
989     return Visit(E->getSubExpr());
990   }
991 
992   // Utility methods
993   llvm::Type *ConvertType(QualType T) {
994     return CGM.getTypes().ConvertType(T);
995   }
996 
997 public:
998   ConstantAddress EmitLValue(APValue::LValueBase LVBase) {
999     if (const ValueDecl *Decl = LVBase.dyn_cast<const ValueDecl*>()) {
1000       if (Decl->hasAttr<WeakRefAttr>())
1001         return CGM.GetWeakRefReference(Decl);
1002       if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(Decl))
1003         return ConstantAddress(CGM.GetAddrOfFunction(FD), CharUnits::One());
1004       if (const VarDecl* VD = dyn_cast<VarDecl>(Decl)) {
1005         // We can never refer to a variable with local storage.
1006         if (!VD->hasLocalStorage()) {
1007           CharUnits Align = CGM.getContext().getDeclAlign(VD);
1008           if (VD->isFileVarDecl() || VD->hasExternalStorage())
1009             return ConstantAddress(CGM.GetAddrOfGlobalVar(VD), Align);
1010           else if (VD->isLocalVarDecl()) {
1011             auto Ptr = CGM.getOrCreateStaticVarDecl(
1012                 *VD, CGM.getLLVMLinkageVarDefinition(VD, /*isConstant=*/false));
1013             return ConstantAddress(Ptr, Align);
1014           }
1015         }
1016       }
1017       return ConstantAddress::invalid();
1018     }
1019 
1020     Expr *E = const_cast<Expr*>(LVBase.get<const Expr*>());
1021     switch (E->getStmtClass()) {
1022     default: break;
1023     case Expr::CompoundLiteralExprClass: {
1024       // Note that due to the nature of compound literals, this is guaranteed
1025       // to be the only use of the variable, so we just generate it here.
1026       CompoundLiteralExpr *CLE = cast<CompoundLiteralExpr>(E);
1027       llvm::Constant* C = CGM.EmitConstantExpr(CLE->getInitializer(),
1028                                                CLE->getType(), CGF);
1029       // FIXME: "Leaked" on failure.
1030       if (!C) return ConstantAddress::invalid();
1031 
1032       CharUnits Align = CGM.getContext().getTypeAlignInChars(E->getType());
1033 
1034       auto GV = new llvm::GlobalVariable(CGM.getModule(), C->getType(),
1035                                      E->getType().isConstant(CGM.getContext()),
1036                                      llvm::GlobalValue::InternalLinkage,
1037                                      C, ".compoundliteral", nullptr,
1038                                      llvm::GlobalVariable::NotThreadLocal,
1039                           CGM.getContext().getTargetAddressSpace(E->getType()));
1040       GV->setAlignment(Align.getQuantity());
1041       return ConstantAddress(GV, Align);
1042     }
1043     case Expr::StringLiteralClass:
1044       return CGM.GetAddrOfConstantStringFromLiteral(cast<StringLiteral>(E));
1045     case Expr::ObjCEncodeExprClass:
1046       return CGM.GetAddrOfConstantStringFromObjCEncode(cast<ObjCEncodeExpr>(E));
1047     case Expr::ObjCStringLiteralClass: {
1048       ObjCStringLiteral* SL = cast<ObjCStringLiteral>(E);
1049       ConstantAddress C =
1050           CGM.getObjCRuntime().GenerateConstantString(SL->getString());
1051       return C.getElementBitCast(ConvertType(E->getType()));
1052     }
1053     case Expr::PredefinedExprClass: {
1054       unsigned Type = cast<PredefinedExpr>(E)->getIdentType();
1055       if (CGF) {
1056         LValue Res = CGF->EmitPredefinedLValue(cast<PredefinedExpr>(E));
1057         return cast<ConstantAddress>(Res.getAddress());
1058       } else if (Type == PredefinedExpr::PrettyFunction) {
1059         return CGM.GetAddrOfConstantCString("top level", ".tmp");
1060       }
1061 
1062       return CGM.GetAddrOfConstantCString("", ".tmp");
1063     }
1064     case Expr::AddrLabelExprClass: {
1065       assert(CGF && "Invalid address of label expression outside function.");
1066       llvm::Constant *Ptr =
1067         CGF->GetAddrOfLabel(cast<AddrLabelExpr>(E)->getLabel());
1068       Ptr = llvm::ConstantExpr::getBitCast(Ptr, ConvertType(E->getType()));
1069       return ConstantAddress(Ptr, CharUnits::One());
1070     }
1071     case Expr::CallExprClass: {
1072       CallExpr* CE = cast<CallExpr>(E);
1073       unsigned builtin = CE->getBuiltinCallee();
1074       if (builtin !=
1075             Builtin::BI__builtin___CFStringMakeConstantString &&
1076           builtin !=
1077             Builtin::BI__builtin___NSStringMakeConstantString)
1078         break;
1079       const Expr *Arg = CE->getArg(0)->IgnoreParenCasts();
1080       const StringLiteral *Literal = cast<StringLiteral>(Arg);
1081       if (builtin ==
1082             Builtin::BI__builtin___NSStringMakeConstantString) {
1083         return CGM.getObjCRuntime().GenerateConstantString(Literal);
1084       }
1085       // FIXME: need to deal with UCN conversion issues.
1086       return CGM.GetAddrOfConstantCFString(Literal);
1087     }
1088     case Expr::BlockExprClass: {
1089       StringRef FunctionName;
1090       if (CGF)
1091         FunctionName = CGF->CurFn->getName();
1092       else
1093         FunctionName = "global";
1094 
1095       // This is not really an l-value.
1096       llvm::Constant *Ptr =
1097         CGM.GetAddrOfGlobalBlock(cast<BlockExpr>(E), FunctionName);
1098       return ConstantAddress(Ptr, CGM.getPointerAlign());
1099     }
1100     case Expr::CXXTypeidExprClass: {
1101       CXXTypeidExpr *Typeid = cast<CXXTypeidExpr>(E);
1102       QualType T;
1103       if (Typeid->isTypeOperand())
1104         T = Typeid->getTypeOperand(CGM.getContext());
1105       else
1106         T = Typeid->getExprOperand()->getType();
1107       return ConstantAddress(CGM.GetAddrOfRTTIDescriptor(T),
1108                              CGM.getPointerAlign());
1109     }
1110     case Expr::CXXUuidofExprClass: {
1111       return CGM.GetAddrOfUuidDescriptor(cast<CXXUuidofExpr>(E));
1112     }
1113     case Expr::MaterializeTemporaryExprClass: {
1114       MaterializeTemporaryExpr *MTE = cast<MaterializeTemporaryExpr>(E);
1115       assert(MTE->getStorageDuration() == SD_Static);
1116       SmallVector<const Expr *, 2> CommaLHSs;
1117       SmallVector<SubobjectAdjustment, 2> Adjustments;
1118       const Expr *Inner = MTE->GetTemporaryExpr()
1119           ->skipRValueSubobjectAdjustments(CommaLHSs, Adjustments);
1120       return CGM.GetAddrOfGlobalTemporary(MTE, Inner);
1121     }
1122     }
1123 
1124     return ConstantAddress::invalid();
1125   }
1126 };
1127 
1128 }  // end anonymous namespace.
1129 
1130 bool ConstStructBuilder::Build(ConstExprEmitter *Emitter,
1131                                llvm::ConstantStruct *Base,
1132                                InitListExpr *Updater) {
1133   assert(Base && "base expression should not be empty");
1134 
1135   QualType ExprType = Updater->getType();
1136   RecordDecl *RD = ExprType->getAs<RecordType>()->getDecl();
1137   const ASTRecordLayout &Layout = CGM.getContext().getASTRecordLayout(RD);
1138   const llvm::StructLayout *BaseLayout = CGM.getDataLayout().getStructLayout(
1139                                            Base->getType());
1140   unsigned FieldNo = -1;
1141   unsigned ElementNo = 0;
1142 
1143   // Bail out if we have base classes. We could support these, but they only
1144   // arise in C++1z where we will have already constant folded most interesting
1145   // cases. FIXME: There are still a few more cases we can handle this way.
1146   if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD))
1147     if (CXXRD->getNumBases())
1148       return false;
1149 
1150   for (FieldDecl *Field : RD->fields()) {
1151     ++FieldNo;
1152 
1153     if (RD->isUnion() && Updater->getInitializedFieldInUnion() != Field)
1154       continue;
1155 
1156     // Skip anonymous bitfields.
1157     if (Field->isUnnamedBitfield())
1158       continue;
1159 
1160     llvm::Constant *EltInit = Base->getOperand(ElementNo);
1161 
1162     // Bail out if the type of the ConstantStruct does not have the same layout
1163     // as the type of the InitListExpr.
1164     if (CGM.getTypes().ConvertType(Field->getType()) != EltInit->getType() ||
1165         Layout.getFieldOffset(ElementNo) !=
1166           BaseLayout->getElementOffsetInBits(ElementNo))
1167       return false;
1168 
1169     // Get the initializer. If we encounter an empty field or a NoInitExpr,
1170     // we use values from the base expression.
1171     Expr *Init = nullptr;
1172     if (ElementNo < Updater->getNumInits())
1173       Init = Updater->getInit(ElementNo);
1174 
1175     if (!Init || isa<NoInitExpr>(Init))
1176       ; // Do nothing.
1177     else if (InitListExpr *ChildILE = dyn_cast<InitListExpr>(Init))
1178       EltInit = Emitter->EmitDesignatedInitUpdater(EltInit, ChildILE);
1179     else
1180       EltInit = CGM.EmitConstantExpr(Init, Field->getType(), CGF);
1181 
1182     ++ElementNo;
1183 
1184     if (!EltInit)
1185       return false;
1186 
1187     if (!Field->isBitField())
1188       AppendField(Field, Layout.getFieldOffset(FieldNo), EltInit);
1189     else if (llvm::ConstantInt *CI = dyn_cast<llvm::ConstantInt>(EltInit))
1190       AppendBitField(Field, Layout.getFieldOffset(FieldNo), CI);
1191     else
1192       // Initializing a bitfield with a non-trivial constant?
1193       return false;
1194   }
1195 
1196   return true;
1197 }
1198 
1199 llvm::Constant *CodeGenModule::EmitConstantInit(const VarDecl &D,
1200                                                 CodeGenFunction *CGF) {
1201   // Make a quick check if variable can be default NULL initialized
1202   // and avoid going through rest of code which may do, for c++11,
1203   // initialization of memory to all NULLs.
1204   if (!D.hasLocalStorage()) {
1205     QualType Ty = D.getType();
1206     if (Ty->isArrayType())
1207       Ty = Context.getBaseElementType(Ty);
1208     if (Ty->isRecordType())
1209       if (const CXXConstructExpr *E =
1210           dyn_cast_or_null<CXXConstructExpr>(D.getInit())) {
1211         const CXXConstructorDecl *CD = E->getConstructor();
1212         if (CD->isTrivial() && CD->isDefaultConstructor())
1213           return EmitNullConstant(D.getType());
1214       }
1215   }
1216 
1217   if (const APValue *Value = D.evaluateValue())
1218     return EmitConstantValueForMemory(*Value, D.getType(), CGF);
1219 
1220   // FIXME: Implement C++11 [basic.start.init]p2: if the initializer of a
1221   // reference is a constant expression, and the reference binds to a temporary,
1222   // then constant initialization is performed. ConstExprEmitter will
1223   // incorrectly emit a prvalue constant in this case, and the calling code
1224   // interprets that as the (pointer) value of the reference, rather than the
1225   // desired value of the referee.
1226   if (D.getType()->isReferenceType())
1227     return nullptr;
1228 
1229   const Expr *E = D.getInit();
1230   assert(E && "No initializer to emit");
1231 
1232   llvm::Constant* C = ConstExprEmitter(*this, CGF).Visit(const_cast<Expr*>(E));
1233   if (C && C->getType()->isIntegerTy(1)) {
1234     llvm::Type *BoolTy = getTypes().ConvertTypeForMem(E->getType());
1235     C = llvm::ConstantExpr::getZExt(C, BoolTy);
1236   }
1237   return C;
1238 }
1239 
1240 llvm::Constant *CodeGenModule::EmitConstantExpr(const Expr *E,
1241                                                 QualType DestType,
1242                                                 CodeGenFunction *CGF) {
1243   Expr::EvalResult Result;
1244 
1245   bool Success = false;
1246 
1247   if (DestType->isReferenceType())
1248     Success = E->EvaluateAsLValue(Result, Context);
1249   else
1250     Success = E->EvaluateAsRValue(Result, Context);
1251 
1252   llvm::Constant *C = nullptr;
1253   if (Success && !Result.HasSideEffects)
1254     C = EmitConstantValue(Result.Val, DestType, CGF);
1255   else
1256     C = ConstExprEmitter(*this, CGF).Visit(const_cast<Expr*>(E));
1257 
1258   if (C && C->getType()->isIntegerTy(1)) {
1259     llvm::Type *BoolTy = getTypes().ConvertTypeForMem(E->getType());
1260     C = llvm::ConstantExpr::getZExt(C, BoolTy);
1261   }
1262   return C;
1263 }
1264 
1265 llvm::Constant *CodeGenModule::EmitConstantValue(const APValue &Value,
1266                                                  QualType DestType,
1267                                                  CodeGenFunction *CGF) {
1268   // For an _Atomic-qualified constant, we may need to add tail padding.
1269   if (auto *AT = DestType->getAs<AtomicType>()) {
1270     QualType InnerType = AT->getValueType();
1271     auto *Inner = EmitConstantValue(Value, InnerType, CGF);
1272 
1273     uint64_t InnerSize = Context.getTypeSize(InnerType);
1274     uint64_t OuterSize = Context.getTypeSize(DestType);
1275     if (InnerSize == OuterSize)
1276       return Inner;
1277 
1278     assert(InnerSize < OuterSize && "emitted over-large constant for atomic");
1279     llvm::Constant *Elts[] = {
1280       Inner,
1281       llvm::ConstantAggregateZero::get(
1282           llvm::ArrayType::get(Int8Ty, (OuterSize - InnerSize) / 8))
1283     };
1284     return llvm::ConstantStruct::getAnon(Elts);
1285   }
1286 
1287   switch (Value.getKind()) {
1288   case APValue::Uninitialized:
1289     llvm_unreachable("Constant expressions should be initialized.");
1290   case APValue::LValue: {
1291     llvm::Type *DestTy = getTypes().ConvertTypeForMem(DestType);
1292     llvm::Constant *Offset =
1293       llvm::ConstantInt::get(Int64Ty, Value.getLValueOffset().getQuantity());
1294 
1295     llvm::Constant *C = nullptr;
1296     if (APValue::LValueBase LVBase = Value.getLValueBase()) {
1297       // An array can be represented as an lvalue referring to the base.
1298       if (isa<llvm::ArrayType>(DestTy)) {
1299         assert(Offset->isNullValue() && "offset on array initializer");
1300         return ConstExprEmitter(*this, CGF).Visit(
1301           const_cast<Expr*>(LVBase.get<const Expr*>()));
1302       }
1303 
1304       C = ConstExprEmitter(*this, CGF).EmitLValue(LVBase).getPointer();
1305 
1306       // Apply offset if necessary.
1307       if (!Offset->isNullValue()) {
1308         unsigned AS = C->getType()->getPointerAddressSpace();
1309         llvm::Type *CharPtrTy = Int8Ty->getPointerTo(AS);
1310         llvm::Constant *Casted = llvm::ConstantExpr::getBitCast(C, CharPtrTy);
1311         Casted = llvm::ConstantExpr::getGetElementPtr(Int8Ty, Casted, Offset);
1312         C = llvm::ConstantExpr::getPointerCast(Casted, C->getType());
1313       }
1314 
1315       // Convert to the appropriate type; this could be an lvalue for
1316       // an integer.
1317       if (isa<llvm::PointerType>(DestTy))
1318         return llvm::ConstantExpr::getPointerCast(C, DestTy);
1319 
1320       return llvm::ConstantExpr::getPtrToInt(C, DestTy);
1321     } else {
1322       C = Offset;
1323 
1324       // Convert to the appropriate type; this could be an lvalue for
1325       // an integer.
1326       if (isa<llvm::PointerType>(DestTy)) {
1327         // Convert the integer to a pointer-sized integer before converting it
1328         // to a pointer.
1329         C = llvm::ConstantExpr::getIntegerCast(
1330             C, getDataLayout().getIntPtrType(DestTy),
1331             /*isSigned=*/false);
1332         return llvm::ConstantExpr::getIntToPtr(C, DestTy);
1333       }
1334 
1335       // If the types don't match this should only be a truncate.
1336       if (C->getType() != DestTy)
1337         return llvm::ConstantExpr::getTrunc(C, DestTy);
1338 
1339       return C;
1340     }
1341   }
1342   case APValue::Int:
1343     return llvm::ConstantInt::get(VMContext, Value.getInt());
1344   case APValue::ComplexInt: {
1345     llvm::Constant *Complex[2];
1346 
1347     Complex[0] = llvm::ConstantInt::get(VMContext,
1348                                         Value.getComplexIntReal());
1349     Complex[1] = llvm::ConstantInt::get(VMContext,
1350                                         Value.getComplexIntImag());
1351 
1352     // FIXME: the target may want to specify that this is packed.
1353     llvm::StructType *STy = llvm::StructType::get(Complex[0]->getType(),
1354                                                   Complex[1]->getType(),
1355                                                   nullptr);
1356     return llvm::ConstantStruct::get(STy, Complex);
1357   }
1358   case APValue::Float: {
1359     const llvm::APFloat &Init = Value.getFloat();
1360     if (&Init.getSemantics() == &llvm::APFloat::IEEEhalf() &&
1361         !Context.getLangOpts().NativeHalfType &&
1362         !Context.getLangOpts().HalfArgsAndReturns)
1363       return llvm::ConstantInt::get(VMContext, Init.bitcastToAPInt());
1364     else
1365       return llvm::ConstantFP::get(VMContext, Init);
1366   }
1367   case APValue::ComplexFloat: {
1368     llvm::Constant *Complex[2];
1369 
1370     Complex[0] = llvm::ConstantFP::get(VMContext,
1371                                        Value.getComplexFloatReal());
1372     Complex[1] = llvm::ConstantFP::get(VMContext,
1373                                        Value.getComplexFloatImag());
1374 
1375     // FIXME: the target may want to specify that this is packed.
1376     llvm::StructType *STy = llvm::StructType::get(Complex[0]->getType(),
1377                                                   Complex[1]->getType(),
1378                                                   nullptr);
1379     return llvm::ConstantStruct::get(STy, Complex);
1380   }
1381   case APValue::Vector: {
1382     unsigned NumElts = Value.getVectorLength();
1383     SmallVector<llvm::Constant *, 4> Inits(NumElts);
1384 
1385     for (unsigned I = 0; I != NumElts; ++I) {
1386       const APValue &Elt = Value.getVectorElt(I);
1387       if (Elt.isInt())
1388         Inits[I] = llvm::ConstantInt::get(VMContext, Elt.getInt());
1389       else if (Elt.isFloat())
1390         Inits[I] = llvm::ConstantFP::get(VMContext, Elt.getFloat());
1391       else
1392         llvm_unreachable("unsupported vector element type");
1393     }
1394     return llvm::ConstantVector::get(Inits);
1395   }
1396   case APValue::AddrLabelDiff: {
1397     const AddrLabelExpr *LHSExpr = Value.getAddrLabelDiffLHS();
1398     const AddrLabelExpr *RHSExpr = Value.getAddrLabelDiffRHS();
1399     llvm::Constant *LHS = EmitConstantExpr(LHSExpr, LHSExpr->getType(), CGF);
1400     llvm::Constant *RHS = EmitConstantExpr(RHSExpr, RHSExpr->getType(), CGF);
1401 
1402     // Compute difference
1403     llvm::Type *ResultType = getTypes().ConvertType(DestType);
1404     LHS = llvm::ConstantExpr::getPtrToInt(LHS, IntPtrTy);
1405     RHS = llvm::ConstantExpr::getPtrToInt(RHS, IntPtrTy);
1406     llvm::Constant *AddrLabelDiff = llvm::ConstantExpr::getSub(LHS, RHS);
1407 
1408     // LLVM is a bit sensitive about the exact format of the
1409     // address-of-label difference; make sure to truncate after
1410     // the subtraction.
1411     return llvm::ConstantExpr::getTruncOrBitCast(AddrLabelDiff, ResultType);
1412   }
1413   case APValue::Struct:
1414   case APValue::Union:
1415     return ConstStructBuilder::BuildStruct(*this, CGF, Value, DestType);
1416   case APValue::Array: {
1417     const ArrayType *CAT = Context.getAsArrayType(DestType);
1418     unsigned NumElements = Value.getArraySize();
1419     unsigned NumInitElts = Value.getArrayInitializedElts();
1420 
1421     // Emit array filler, if there is one.
1422     llvm::Constant *Filler = nullptr;
1423     if (Value.hasArrayFiller())
1424       Filler = EmitConstantValueForMemory(Value.getArrayFiller(),
1425                                           CAT->getElementType(), CGF);
1426 
1427     // Emit initializer elements.
1428     llvm::Type *CommonElementType =
1429         getTypes().ConvertType(CAT->getElementType());
1430 
1431     // Try to use a ConstantAggregateZero if we can.
1432     if (Filler && Filler->isNullValue() && !NumInitElts) {
1433       llvm::ArrayType *AType =
1434           llvm::ArrayType::get(CommonElementType, NumElements);
1435       return llvm::ConstantAggregateZero::get(AType);
1436     }
1437 
1438     std::vector<llvm::Constant*> Elts;
1439     Elts.reserve(NumElements);
1440     for (unsigned I = 0; I < NumElements; ++I) {
1441       llvm::Constant *C = Filler;
1442       if (I < NumInitElts)
1443         C = EmitConstantValueForMemory(Value.getArrayInitializedElt(I),
1444                                        CAT->getElementType(), CGF);
1445       else
1446         assert(Filler && "Missing filler for implicit elements of initializer");
1447       if (I == 0)
1448         CommonElementType = C->getType();
1449       else if (C->getType() != CommonElementType)
1450         CommonElementType = nullptr;
1451       Elts.push_back(C);
1452     }
1453 
1454     if (!CommonElementType) {
1455       // FIXME: Try to avoid packing the array
1456       std::vector<llvm::Type*> Types;
1457       Types.reserve(NumElements);
1458       for (unsigned i = 0, e = Elts.size(); i < e; ++i)
1459         Types.push_back(Elts[i]->getType());
1460       llvm::StructType *SType = llvm::StructType::get(VMContext, Types, true);
1461       return llvm::ConstantStruct::get(SType, Elts);
1462     }
1463 
1464     llvm::ArrayType *AType =
1465       llvm::ArrayType::get(CommonElementType, NumElements);
1466     return llvm::ConstantArray::get(AType, Elts);
1467   }
1468   case APValue::MemberPointer:
1469     return getCXXABI().EmitMemberPointer(Value, DestType);
1470   }
1471   llvm_unreachable("Unknown APValue kind");
1472 }
1473 
1474 llvm::Constant *
1475 CodeGenModule::EmitConstantValueForMemory(const APValue &Value,
1476                                           QualType DestType,
1477                                           CodeGenFunction *CGF) {
1478   llvm::Constant *C = EmitConstantValue(Value, DestType, CGF);
1479   if (C->getType()->isIntegerTy(1)) {
1480     llvm::Type *BoolTy = getTypes().ConvertTypeForMem(DestType);
1481     C = llvm::ConstantExpr::getZExt(C, BoolTy);
1482   }
1483   return C;
1484 }
1485 
1486 ConstantAddress
1487 CodeGenModule::GetAddrOfConstantCompoundLiteral(const CompoundLiteralExpr *E) {
1488   assert(E->isFileScope() && "not a file-scope compound literal expr");
1489   return ConstExprEmitter(*this, nullptr).EmitLValue(E);
1490 }
1491 
1492 llvm::Constant *
1493 CodeGenModule::getMemberPointerConstant(const UnaryOperator *uo) {
1494   // Member pointer constants always have a very particular form.
1495   const MemberPointerType *type = cast<MemberPointerType>(uo->getType());
1496   const ValueDecl *decl = cast<DeclRefExpr>(uo->getSubExpr())->getDecl();
1497 
1498   // A member function pointer.
1499   if (const CXXMethodDecl *method = dyn_cast<CXXMethodDecl>(decl))
1500     return getCXXABI().EmitMemberFunctionPointer(method);
1501 
1502   // Otherwise, a member data pointer.
1503   uint64_t fieldOffset = getContext().getFieldOffset(decl);
1504   CharUnits chars = getContext().toCharUnitsFromBits((int64_t) fieldOffset);
1505   return getCXXABI().EmitMemberDataPointer(type, chars);
1506 }
1507 
1508 static llvm::Constant *EmitNullConstantForBase(CodeGenModule &CGM,
1509                                                llvm::Type *baseType,
1510                                                const CXXRecordDecl *base);
1511 
1512 static llvm::Constant *EmitNullConstant(CodeGenModule &CGM,
1513                                         const CXXRecordDecl *record,
1514                                         bool asCompleteObject) {
1515   const CGRecordLayout &layout = CGM.getTypes().getCGRecordLayout(record);
1516   llvm::StructType *structure =
1517     (asCompleteObject ? layout.getLLVMType()
1518                       : layout.getBaseSubobjectLLVMType());
1519 
1520   unsigned numElements = structure->getNumElements();
1521   std::vector<llvm::Constant *> elements(numElements);
1522 
1523   // Fill in all the bases.
1524   for (const auto &I : record->bases()) {
1525     if (I.isVirtual()) {
1526       // Ignore virtual bases; if we're laying out for a complete
1527       // object, we'll lay these out later.
1528       continue;
1529     }
1530 
1531     const CXXRecordDecl *base =
1532       cast<CXXRecordDecl>(I.getType()->castAs<RecordType>()->getDecl());
1533 
1534     // Ignore empty bases.
1535     if (base->isEmpty() ||
1536         CGM.getContext().getASTRecordLayout(base).getNonVirtualSize().isZero())
1537       continue;
1538 
1539     unsigned fieldIndex = layout.getNonVirtualBaseLLVMFieldNo(base);
1540     llvm::Type *baseType = structure->getElementType(fieldIndex);
1541     elements[fieldIndex] = EmitNullConstantForBase(CGM, baseType, base);
1542   }
1543 
1544   // Fill in all the fields.
1545   for (const auto *Field : record->fields()) {
1546     // Fill in non-bitfields. (Bitfields always use a zero pattern, which we
1547     // will fill in later.)
1548     if (!Field->isBitField()) {
1549       unsigned fieldIndex = layout.getLLVMFieldNo(Field);
1550       elements[fieldIndex] = CGM.EmitNullConstant(Field->getType());
1551     }
1552 
1553     // For unions, stop after the first named field.
1554     if (record->isUnion()) {
1555       if (Field->getIdentifier())
1556         break;
1557       if (const auto *FieldRD =
1558               dyn_cast_or_null<RecordDecl>(Field->getType()->getAsTagDecl()))
1559         if (FieldRD->findFirstNamedDataMember())
1560           break;
1561     }
1562   }
1563 
1564   // Fill in the virtual bases, if we're working with the complete object.
1565   if (asCompleteObject) {
1566     for (const auto &I : record->vbases()) {
1567       const CXXRecordDecl *base =
1568         cast<CXXRecordDecl>(I.getType()->castAs<RecordType>()->getDecl());
1569 
1570       // Ignore empty bases.
1571       if (base->isEmpty())
1572         continue;
1573 
1574       unsigned fieldIndex = layout.getVirtualBaseIndex(base);
1575 
1576       // We might have already laid this field out.
1577       if (elements[fieldIndex]) continue;
1578 
1579       llvm::Type *baseType = structure->getElementType(fieldIndex);
1580       elements[fieldIndex] = EmitNullConstantForBase(CGM, baseType, base);
1581     }
1582   }
1583 
1584   // Now go through all other fields and zero them out.
1585   for (unsigned i = 0; i != numElements; ++i) {
1586     if (!elements[i])
1587       elements[i] = llvm::Constant::getNullValue(structure->getElementType(i));
1588   }
1589 
1590   return llvm::ConstantStruct::get(structure, elements);
1591 }
1592 
1593 /// Emit the null constant for a base subobject.
1594 static llvm::Constant *EmitNullConstantForBase(CodeGenModule &CGM,
1595                                                llvm::Type *baseType,
1596                                                const CXXRecordDecl *base) {
1597   const CGRecordLayout &baseLayout = CGM.getTypes().getCGRecordLayout(base);
1598 
1599   // Just zero out bases that don't have any pointer to data members.
1600   if (baseLayout.isZeroInitializableAsBase())
1601     return llvm::Constant::getNullValue(baseType);
1602 
1603   // Otherwise, we can just use its null constant.
1604   return EmitNullConstant(CGM, base, /*asCompleteObject=*/false);
1605 }
1606 
1607 llvm::Constant *CodeGenModule::EmitNullConstant(QualType T) {
1608   if (getTypes().isZeroInitializable(T))
1609     return llvm::Constant::getNullValue(getTypes().ConvertTypeForMem(T));
1610 
1611   if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(T)) {
1612     llvm::ArrayType *ATy =
1613       cast<llvm::ArrayType>(getTypes().ConvertTypeForMem(T));
1614 
1615     QualType ElementTy = CAT->getElementType();
1616 
1617     llvm::Constant *Element = EmitNullConstant(ElementTy);
1618     unsigned NumElements = CAT->getSize().getZExtValue();
1619     SmallVector<llvm::Constant *, 8> Array(NumElements, Element);
1620     return llvm::ConstantArray::get(ATy, Array);
1621   }
1622 
1623   if (const RecordType *RT = T->getAs<RecordType>()) {
1624     const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
1625     return ::EmitNullConstant(*this, RD, /*complete object*/ true);
1626   }
1627 
1628   assert(T->isMemberDataPointerType() &&
1629          "Should only see pointers to data members here!");
1630 
1631   return getCXXABI().EmitNullMemberPointer(T->castAs<MemberPointerType>());
1632 }
1633 
1634 llvm::Constant *
1635 CodeGenModule::EmitNullConstantForBase(const CXXRecordDecl *Record) {
1636   return ::EmitNullConstant(*this, Record, false);
1637 }
1638