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