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