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