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