clang API Documentation

CGExprConstant.cpp
Go to the documentation of this file.
00001 //===--- CGExprConstant.cpp - Emit LLVM Code from Constant Expressions ----===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 // This contains code to emit Constant Expr nodes as LLVM code.
00011 //
00012 //===----------------------------------------------------------------------===//
00013 
00014 #include "CodeGenFunction.h"
00015 #include "CGCXXABI.h"
00016 #include "CGObjCRuntime.h"
00017 #include "CGRecordLayout.h"
00018 #include "CodeGenModule.h"
00019 #include "clang/AST/APValue.h"
00020 #include "clang/AST/ASTContext.h"
00021 #include "clang/AST/RecordLayout.h"
00022 #include "clang/AST/StmtVisitor.h"
00023 #include "clang/Basic/Builtins.h"
00024 #include "llvm/IR/Constants.h"
00025 #include "llvm/IR/DataLayout.h"
00026 #include "llvm/IR/Function.h"
00027 #include "llvm/IR/GlobalVariable.h"
00028 using namespace clang;
00029 using namespace CodeGen;
00030 
00031 //===----------------------------------------------------------------------===//
00032 //                            ConstStructBuilder
00033 //===----------------------------------------------------------------------===//
00034 
00035 namespace {
00036 class ConstStructBuilder {
00037   CodeGenModule &CGM;
00038   CodeGenFunction *CGF;
00039 
00040   bool Packed;
00041   CharUnits NextFieldOffsetInChars;
00042   CharUnits LLVMStructAlignment;
00043   SmallVector<llvm::Constant *, 32> Elements;
00044 public:
00045   static llvm::Constant *BuildStruct(CodeGenModule &CGM, CodeGenFunction *CGF,
00046                                      InitListExpr *ILE);
00047   static llvm::Constant *BuildStruct(CodeGenModule &CGM, CodeGenFunction *CGF,
00048                                      const APValue &Value, QualType ValTy);
00049 
00050 private:
00051   ConstStructBuilder(CodeGenModule &CGM, CodeGenFunction *CGF)
00052     : CGM(CGM), CGF(CGF), Packed(false), 
00053     NextFieldOffsetInChars(CharUnits::Zero()),
00054     LLVMStructAlignment(CharUnits::One()) { }
00055 
00056   void AppendField(const FieldDecl *Field, uint64_t FieldOffset,
00057                    llvm::Constant *InitExpr);
00058 
00059   void AppendBytes(CharUnits FieldOffsetInChars, llvm::Constant *InitCst);
00060 
00061   void AppendBitField(const FieldDecl *Field, uint64_t FieldOffset,
00062                       llvm::ConstantInt *InitExpr);
00063 
00064   void AppendPadding(CharUnits PadSize);
00065 
00066   void AppendTailPadding(CharUnits RecordSize);
00067 
00068   void ConvertStructToPacked();
00069 
00070   bool Build(InitListExpr *ILE);
00071   void Build(const APValue &Val, const RecordDecl *RD, bool IsPrimaryBase,
00072              const CXXRecordDecl *VTableClass, CharUnits BaseOffset);
00073   llvm::Constant *Finalize(QualType Ty);
00074 
00075   CharUnits getAlignment(const llvm::Constant *C) const {
00076     if (Packed)  return CharUnits::One();
00077     return CharUnits::fromQuantity(
00078         CGM.getDataLayout().getABITypeAlignment(C->getType()));
00079   }
00080 
00081   CharUnits getSizeInChars(const llvm::Constant *C) const {
00082     return CharUnits::fromQuantity(
00083         CGM.getDataLayout().getTypeAllocSize(C->getType()));
00084   }
00085 };
00086 
00087 void ConstStructBuilder::
00088 AppendField(const FieldDecl *Field, uint64_t FieldOffset,
00089             llvm::Constant *InitCst) {
00090   const ASTContext &Context = CGM.getContext();
00091 
00092   CharUnits FieldOffsetInChars = Context.toCharUnitsFromBits(FieldOffset);
00093 
00094   AppendBytes(FieldOffsetInChars, InitCst);
00095 }
00096 
00097 void ConstStructBuilder::
00098 AppendBytes(CharUnits FieldOffsetInChars, llvm::Constant *InitCst) {
00099 
00100   assert(NextFieldOffsetInChars <= FieldOffsetInChars
00101          && "Field offset mismatch!");
00102 
00103   CharUnits FieldAlignment = getAlignment(InitCst);
00104 
00105   // Round up the field offset to the alignment of the field type.
00106   CharUnits AlignedNextFieldOffsetInChars =
00107       NextFieldOffsetInChars.RoundUpToAlignment(FieldAlignment);
00108 
00109   if (AlignedNextFieldOffsetInChars < FieldOffsetInChars) {
00110     // We need to append padding.
00111     AppendPadding(FieldOffsetInChars - NextFieldOffsetInChars);
00112 
00113     assert(NextFieldOffsetInChars == FieldOffsetInChars &&
00114            "Did not add enough padding!");
00115 
00116     AlignedNextFieldOffsetInChars =
00117         NextFieldOffsetInChars.RoundUpToAlignment(FieldAlignment);
00118   }
00119 
00120   if (AlignedNextFieldOffsetInChars > FieldOffsetInChars) {
00121     assert(!Packed && "Alignment is wrong even with a packed struct!");
00122 
00123     // Convert the struct to a packed struct.
00124     ConvertStructToPacked();
00125 
00126     // After we pack the struct, we may need to insert padding.
00127     if (NextFieldOffsetInChars < FieldOffsetInChars) {
00128       // We need to append padding.
00129       AppendPadding(FieldOffsetInChars - NextFieldOffsetInChars);
00130 
00131       assert(NextFieldOffsetInChars == FieldOffsetInChars &&
00132              "Did not add enough padding!");
00133     }
00134     AlignedNextFieldOffsetInChars = NextFieldOffsetInChars;
00135   }
00136 
00137   // Add the field.
00138   Elements.push_back(InitCst);
00139   NextFieldOffsetInChars = AlignedNextFieldOffsetInChars +
00140                            getSizeInChars(InitCst);
00141 
00142   if (Packed)
00143     assert(LLVMStructAlignment == CharUnits::One() &&
00144            "Packed struct not byte-aligned!");
00145   else
00146     LLVMStructAlignment = std::max(LLVMStructAlignment, FieldAlignment);
00147 }
00148 
00149 void ConstStructBuilder::AppendBitField(const FieldDecl *Field,
00150                                         uint64_t FieldOffset,
00151                                         llvm::ConstantInt *CI) {
00152   const ASTContext &Context = CGM.getContext();
00153   const uint64_t CharWidth = Context.getCharWidth();
00154   uint64_t NextFieldOffsetInBits = Context.toBits(NextFieldOffsetInChars);
00155   if (FieldOffset > NextFieldOffsetInBits) {
00156     // We need to add padding.
00157     CharUnits PadSize = Context.toCharUnitsFromBits(
00158       llvm::RoundUpToAlignment(FieldOffset - NextFieldOffsetInBits, 
00159                                Context.getTargetInfo().getCharAlign()));
00160 
00161     AppendPadding(PadSize);
00162   }
00163 
00164   uint64_t FieldSize = Field->getBitWidthValue(Context);
00165 
00166   llvm::APInt FieldValue = CI->getValue();
00167 
00168   // Promote the size of FieldValue if necessary
00169   // FIXME: This should never occur, but currently it can because initializer
00170   // constants are cast to bool, and because clang is not enforcing bitfield
00171   // width limits.
00172   if (FieldSize > FieldValue.getBitWidth())
00173     FieldValue = FieldValue.zext(FieldSize);
00174 
00175   // Truncate the size of FieldValue to the bit field size.
00176   if (FieldSize < FieldValue.getBitWidth())
00177     FieldValue = FieldValue.trunc(FieldSize);
00178 
00179   NextFieldOffsetInBits = Context.toBits(NextFieldOffsetInChars);
00180   if (FieldOffset < NextFieldOffsetInBits) {
00181     // Either part of the field or the entire field can go into the previous
00182     // byte.
00183     assert(!Elements.empty() && "Elements can't be empty!");
00184 
00185     unsigned BitsInPreviousByte = NextFieldOffsetInBits - FieldOffset;
00186 
00187     bool FitsCompletelyInPreviousByte =
00188       BitsInPreviousByte >= FieldValue.getBitWidth();
00189 
00190     llvm::APInt Tmp = FieldValue;
00191 
00192     if (!FitsCompletelyInPreviousByte) {
00193       unsigned NewFieldWidth = FieldSize - BitsInPreviousByte;
00194 
00195       if (CGM.getDataLayout().isBigEndian()) {
00196         Tmp = Tmp.lshr(NewFieldWidth);
00197         Tmp = Tmp.trunc(BitsInPreviousByte);
00198 
00199         // We want the remaining high bits.
00200         FieldValue = FieldValue.trunc(NewFieldWidth);
00201       } else {
00202         Tmp = Tmp.trunc(BitsInPreviousByte);
00203 
00204         // We want the remaining low bits.
00205         FieldValue = FieldValue.lshr(BitsInPreviousByte);
00206         FieldValue = FieldValue.trunc(NewFieldWidth);
00207       }
00208     }
00209 
00210     Tmp = Tmp.zext(CharWidth);
00211     if (CGM.getDataLayout().isBigEndian()) {
00212       if (FitsCompletelyInPreviousByte)
00213         Tmp = Tmp.shl(BitsInPreviousByte - FieldValue.getBitWidth());
00214     } else {
00215       Tmp = Tmp.shl(CharWidth - BitsInPreviousByte);
00216     }
00217 
00218     // 'or' in the bits that go into the previous byte.
00219     llvm::Value *LastElt = Elements.back();
00220     if (llvm::ConstantInt *Val = dyn_cast<llvm::ConstantInt>(LastElt))
00221       Tmp |= Val->getValue();
00222     else {
00223       assert(isa<llvm::UndefValue>(LastElt));
00224       // If there is an undef field that we're adding to, it can either be a
00225       // scalar undef (in which case, we just replace it with our field) or it
00226       // is an array.  If it is an array, we have to pull one byte off the
00227       // array so that the other undef bytes stay around.
00228       if (!isa<llvm::IntegerType>(LastElt->getType())) {
00229         // The undef padding will be a multibyte array, create a new smaller
00230         // padding and then an hole for our i8 to get plopped into.
00231         assert(isa<llvm::ArrayType>(LastElt->getType()) &&
00232                "Expected array padding of undefs");
00233         llvm::ArrayType *AT = cast<llvm::ArrayType>(LastElt->getType());
00234         assert(AT->getElementType()->isIntegerTy(CharWidth) &&
00235                AT->getNumElements() != 0 &&
00236                "Expected non-empty array padding of undefs");
00237         
00238         // Remove the padding array.
00239         NextFieldOffsetInChars -= CharUnits::fromQuantity(AT->getNumElements());
00240         Elements.pop_back();
00241         
00242         // Add the padding back in two chunks.
00243         AppendPadding(CharUnits::fromQuantity(AT->getNumElements()-1));
00244         AppendPadding(CharUnits::One());
00245         assert(isa<llvm::UndefValue>(Elements.back()) &&
00246                Elements.back()->getType()->isIntegerTy(CharWidth) &&
00247                "Padding addition didn't work right");
00248       }
00249     }
00250 
00251     Elements.back() = llvm::ConstantInt::get(CGM.getLLVMContext(), Tmp);
00252 
00253     if (FitsCompletelyInPreviousByte)
00254       return;
00255   }
00256 
00257   while (FieldValue.getBitWidth() > CharWidth) {
00258     llvm::APInt Tmp;
00259 
00260     if (CGM.getDataLayout().isBigEndian()) {
00261       // We want the high bits.
00262       Tmp = 
00263         FieldValue.lshr(FieldValue.getBitWidth() - CharWidth).trunc(CharWidth);
00264     } else {
00265       // We want the low bits.
00266       Tmp = FieldValue.trunc(CharWidth);
00267 
00268       FieldValue = FieldValue.lshr(CharWidth);
00269     }
00270 
00271     Elements.push_back(llvm::ConstantInt::get(CGM.getLLVMContext(), Tmp));
00272     ++NextFieldOffsetInChars;
00273 
00274     FieldValue = FieldValue.trunc(FieldValue.getBitWidth() - CharWidth);
00275   }
00276 
00277   assert(FieldValue.getBitWidth() > 0 &&
00278          "Should have at least one bit left!");
00279   assert(FieldValue.getBitWidth() <= CharWidth &&
00280          "Should not have more than a byte left!");
00281 
00282   if (FieldValue.getBitWidth() < CharWidth) {
00283     if (CGM.getDataLayout().isBigEndian()) {
00284       unsigned BitWidth = FieldValue.getBitWidth();
00285 
00286       FieldValue = FieldValue.zext(CharWidth) << (CharWidth - BitWidth);
00287     } else
00288       FieldValue = FieldValue.zext(CharWidth);
00289   }
00290 
00291   // Append the last element.
00292   Elements.push_back(llvm::ConstantInt::get(CGM.getLLVMContext(),
00293                                             FieldValue));
00294   ++NextFieldOffsetInChars;
00295 }
00296 
00297 void ConstStructBuilder::AppendPadding(CharUnits PadSize) {
00298   if (PadSize.isZero())
00299     return;
00300 
00301   llvm::Type *Ty = CGM.Int8Ty;
00302   if (PadSize > CharUnits::One())
00303     Ty = llvm::ArrayType::get(Ty, PadSize.getQuantity());
00304 
00305   llvm::Constant *C = llvm::UndefValue::get(Ty);
00306   Elements.push_back(C);
00307   assert(getAlignment(C) == CharUnits::One() && 
00308          "Padding must have 1 byte alignment!");
00309 
00310   NextFieldOffsetInChars += getSizeInChars(C);
00311 }
00312 
00313 void ConstStructBuilder::AppendTailPadding(CharUnits RecordSize) {
00314   assert(NextFieldOffsetInChars <= RecordSize && 
00315          "Size mismatch!");
00316 
00317   AppendPadding(RecordSize - NextFieldOffsetInChars);
00318 }
00319 
00320 void ConstStructBuilder::ConvertStructToPacked() {
00321   SmallVector<llvm::Constant *, 16> PackedElements;
00322   CharUnits ElementOffsetInChars = CharUnits::Zero();
00323 
00324   for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
00325     llvm::Constant *C = Elements[i];
00326 
00327     CharUnits ElementAlign = CharUnits::fromQuantity(
00328       CGM.getDataLayout().getABITypeAlignment(C->getType()));
00329     CharUnits AlignedElementOffsetInChars =
00330       ElementOffsetInChars.RoundUpToAlignment(ElementAlign);
00331 
00332     if (AlignedElementOffsetInChars > ElementOffsetInChars) {
00333       // We need some padding.
00334       CharUnits NumChars =
00335         AlignedElementOffsetInChars - ElementOffsetInChars;
00336 
00337       llvm::Type *Ty = CGM.Int8Ty;
00338       if (NumChars > CharUnits::One())
00339         Ty = llvm::ArrayType::get(Ty, NumChars.getQuantity());
00340 
00341       llvm::Constant *Padding = llvm::UndefValue::get(Ty);
00342       PackedElements.push_back(Padding);
00343       ElementOffsetInChars += getSizeInChars(Padding);
00344     }
00345 
00346     PackedElements.push_back(C);
00347     ElementOffsetInChars += getSizeInChars(C);
00348   }
00349 
00350   assert(ElementOffsetInChars == NextFieldOffsetInChars &&
00351          "Packing the struct changed its size!");
00352 
00353   Elements.swap(PackedElements);
00354   LLVMStructAlignment = CharUnits::One();
00355   Packed = true;
00356 }
00357                             
00358 bool ConstStructBuilder::Build(InitListExpr *ILE) {
00359   RecordDecl *RD = ILE->getType()->getAs<RecordType>()->getDecl();
00360   const ASTRecordLayout &Layout = CGM.getContext().getASTRecordLayout(RD);
00361 
00362   unsigned FieldNo = 0;
00363   unsigned ElementNo = 0;
00364   
00365   for (RecordDecl::field_iterator Field = RD->field_begin(),
00366        FieldEnd = RD->field_end(); Field != FieldEnd; ++Field, ++FieldNo) {
00367     // If this is a union, skip all the fields that aren't being initialized.
00368     if (RD->isUnion() && ILE->getInitializedFieldInUnion() != *Field)
00369       continue;
00370 
00371     // Don't emit anonymous bitfields, they just affect layout.
00372     if (Field->isUnnamedBitfield())
00373       continue;
00374 
00375     // Get the initializer.  A struct can include fields without initializers,
00376     // we just use explicit null values for them.
00377     llvm::Constant *EltInit;
00378     if (ElementNo < ILE->getNumInits())
00379       EltInit = CGM.EmitConstantExpr(ILE->getInit(ElementNo++),
00380                                      Field->getType(), CGF);
00381     else
00382       EltInit = CGM.EmitNullConstant(Field->getType());
00383 
00384     if (!EltInit)
00385       return false;
00386     
00387     if (!Field->isBitField()) {
00388       // Handle non-bitfield members.
00389       AppendField(*Field, Layout.getFieldOffset(FieldNo), EltInit);
00390     } else {
00391       // Otherwise we have a bitfield.
00392       AppendBitField(*Field, Layout.getFieldOffset(FieldNo),
00393                      cast<llvm::ConstantInt>(EltInit));
00394     }
00395   }
00396 
00397   return true;
00398 }
00399 
00400 namespace {
00401 struct BaseInfo {
00402   BaseInfo(const CXXRecordDecl *Decl, CharUnits Offset, unsigned Index)
00403     : Decl(Decl), Offset(Offset), Index(Index) {
00404   }
00405 
00406   const CXXRecordDecl *Decl;
00407   CharUnits Offset;
00408   unsigned Index;
00409 
00410   bool operator<(const BaseInfo &O) const { return Offset < O.Offset; }
00411 };
00412 }
00413 
00414 void ConstStructBuilder::Build(const APValue &Val, const RecordDecl *RD,
00415                                bool IsPrimaryBase,
00416                                const CXXRecordDecl *VTableClass,
00417                                CharUnits Offset) {
00418   const ASTRecordLayout &Layout = CGM.getContext().getASTRecordLayout(RD);
00419 
00420   if (const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD)) {
00421     // Add a vtable pointer, if we need one and it hasn't already been added.
00422     if (CD->isDynamicClass() && !IsPrimaryBase) {
00423       llvm::Constant *VTableAddressPoint =
00424           CGM.getCXXABI().getVTableAddressPointForConstExpr(
00425               BaseSubobject(CD, Offset), VTableClass);
00426       AppendBytes(Offset, VTableAddressPoint);
00427     }
00428 
00429     // Accumulate and sort bases, in order to visit them in address order, which
00430     // may not be the same as declaration order.
00431     SmallVector<BaseInfo, 8> Bases;
00432     Bases.reserve(CD->getNumBases());
00433     unsigned BaseNo = 0;
00434     for (CXXRecordDecl::base_class_const_iterator Base = CD->bases_begin(),
00435          BaseEnd = CD->bases_end(); Base != BaseEnd; ++Base, ++BaseNo) {
00436       assert(!Base->isVirtual() && "should not have virtual bases here");
00437       const CXXRecordDecl *BD = Base->getType()->getAsCXXRecordDecl();
00438       CharUnits BaseOffset = Layout.getBaseClassOffset(BD);
00439       Bases.push_back(BaseInfo(BD, BaseOffset, BaseNo));
00440     }
00441     std::stable_sort(Bases.begin(), Bases.end());
00442 
00443     for (unsigned I = 0, N = Bases.size(); I != N; ++I) {
00444       BaseInfo &Base = Bases[I];
00445 
00446       bool IsPrimaryBase = Layout.getPrimaryBase() == Base.Decl;
00447       Build(Val.getStructBase(Base.Index), Base.Decl, IsPrimaryBase,
00448             VTableClass, Offset + Base.Offset);
00449     }
00450   }
00451 
00452   unsigned FieldNo = 0;
00453   uint64_t OffsetBits = CGM.getContext().toBits(Offset);
00454 
00455   for (RecordDecl::field_iterator Field = RD->field_begin(),
00456        FieldEnd = RD->field_end(); Field != FieldEnd; ++Field, ++FieldNo) {
00457     // If this is a union, skip all the fields that aren't being initialized.
00458     if (RD->isUnion() && Val.getUnionField() != *Field)
00459       continue;
00460 
00461     // Don't emit anonymous bitfields, they just affect layout.
00462     if (Field->isUnnamedBitfield())
00463       continue;
00464 
00465     // Emit the value of the initializer.
00466     const APValue &FieldValue =
00467       RD->isUnion() ? Val.getUnionValue() : Val.getStructField(FieldNo);
00468     llvm::Constant *EltInit =
00469       CGM.EmitConstantValueForMemory(FieldValue, Field->getType(), CGF);
00470     assert(EltInit && "EmitConstantValue can't fail");
00471 
00472     if (!Field->isBitField()) {
00473       // Handle non-bitfield members.
00474       AppendField(*Field, Layout.getFieldOffset(FieldNo) + OffsetBits, EltInit);
00475     } else {
00476       // Otherwise we have a bitfield.
00477       AppendBitField(*Field, Layout.getFieldOffset(FieldNo) + OffsetBits,
00478                      cast<llvm::ConstantInt>(EltInit));
00479     }
00480   }
00481 }
00482 
00483 llvm::Constant *ConstStructBuilder::Finalize(QualType Ty) {
00484   RecordDecl *RD = Ty->getAs<RecordType>()->getDecl();
00485   const ASTRecordLayout &Layout = CGM.getContext().getASTRecordLayout(RD);
00486 
00487   CharUnits LayoutSizeInChars = Layout.getSize();
00488 
00489   if (NextFieldOffsetInChars > LayoutSizeInChars) {
00490     // If the struct is bigger than the size of the record type,
00491     // we must have a flexible array member at the end.
00492     assert(RD->hasFlexibleArrayMember() &&
00493            "Must have flexible array member if struct is bigger than type!");
00494 
00495     // No tail padding is necessary.
00496   } else {
00497     // Append tail padding if necessary.
00498     CharUnits LLVMSizeInChars =
00499         NextFieldOffsetInChars.RoundUpToAlignment(LLVMStructAlignment);
00500 
00501     if (LLVMSizeInChars != LayoutSizeInChars)
00502       AppendTailPadding(LayoutSizeInChars);
00503 
00504     LLVMSizeInChars =
00505         NextFieldOffsetInChars.RoundUpToAlignment(LLVMStructAlignment);
00506 
00507     // Check if we need to convert the struct to a packed struct.
00508     if (NextFieldOffsetInChars <= LayoutSizeInChars &&
00509         LLVMSizeInChars > LayoutSizeInChars) {
00510       assert(!Packed && "Size mismatch!");
00511 
00512       ConvertStructToPacked();
00513       assert(NextFieldOffsetInChars <= LayoutSizeInChars &&
00514              "Converting to packed did not help!");
00515     }
00516 
00517     LLVMSizeInChars =
00518         NextFieldOffsetInChars.RoundUpToAlignment(LLVMStructAlignment);
00519 
00520     assert(LayoutSizeInChars == LLVMSizeInChars &&
00521            "Tail padding mismatch!");
00522   }
00523 
00524   // Pick the type to use.  If the type is layout identical to the ConvertType
00525   // type then use it, otherwise use whatever the builder produced for us.
00526   llvm::StructType *STy =
00527       llvm::ConstantStruct::getTypeForElements(CGM.getLLVMContext(),
00528                                                Elements, Packed);
00529   llvm::Type *ValTy = CGM.getTypes().ConvertType(Ty);
00530   if (llvm::StructType *ValSTy = dyn_cast<llvm::StructType>(ValTy)) {
00531     if (ValSTy->isLayoutIdentical(STy))
00532       STy = ValSTy;
00533   }
00534 
00535   llvm::Constant *Result = llvm::ConstantStruct::get(STy, Elements);
00536 
00537   assert(NextFieldOffsetInChars.RoundUpToAlignment(getAlignment(Result)) ==
00538          getSizeInChars(Result) && "Size mismatch!");
00539 
00540   return Result;
00541 }
00542 
00543 llvm::Constant *ConstStructBuilder::BuildStruct(CodeGenModule &CGM,
00544                                                 CodeGenFunction *CGF,
00545                                                 InitListExpr *ILE) {
00546   ConstStructBuilder Builder(CGM, CGF);
00547 
00548   if (!Builder.Build(ILE))
00549     return nullptr;
00550 
00551   return Builder.Finalize(ILE->getType());
00552 }
00553 
00554 llvm::Constant *ConstStructBuilder::BuildStruct(CodeGenModule &CGM,
00555                                                 CodeGenFunction *CGF,
00556                                                 const APValue &Val,
00557                                                 QualType ValTy) {
00558   ConstStructBuilder Builder(CGM, CGF);
00559 
00560   const RecordDecl *RD = ValTy->castAs<RecordType>()->getDecl();
00561   const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD);
00562   Builder.Build(Val, RD, false, CD, CharUnits::Zero());
00563 
00564   return Builder.Finalize(ValTy);
00565 }
00566 
00567 
00568 //===----------------------------------------------------------------------===//
00569 //                             ConstExprEmitter
00570 //===----------------------------------------------------------------------===//
00571 
00572 /// This class only needs to handle two cases:
00573 /// 1) Literals (this is used by APValue emission to emit literals).
00574 /// 2) Arrays, structs and unions (outside C++11 mode, we don't currently
00575 ///    constant fold these types).
00576 class ConstExprEmitter :
00577   public StmtVisitor<ConstExprEmitter, llvm::Constant*> {
00578   CodeGenModule &CGM;
00579   CodeGenFunction *CGF;
00580   llvm::LLVMContext &VMContext;
00581 public:
00582   ConstExprEmitter(CodeGenModule &cgm, CodeGenFunction *cgf)
00583     : CGM(cgm), CGF(cgf), VMContext(cgm.getLLVMContext()) {
00584   }
00585 
00586   //===--------------------------------------------------------------------===//
00587   //                            Visitor Methods
00588   //===--------------------------------------------------------------------===//
00589 
00590   llvm::Constant *VisitStmt(Stmt *S) {
00591     return nullptr;
00592   }
00593 
00594   llvm::Constant *VisitParenExpr(ParenExpr *PE) {
00595     return Visit(PE->getSubExpr());
00596   }
00597 
00598   llvm::Constant *
00599   VisitSubstNonTypeTemplateParmExpr(SubstNonTypeTemplateParmExpr *PE) {
00600     return Visit(PE->getReplacement());
00601   }
00602 
00603   llvm::Constant *VisitGenericSelectionExpr(GenericSelectionExpr *GE) {
00604     return Visit(GE->getResultExpr());
00605   }
00606 
00607   llvm::Constant *VisitChooseExpr(ChooseExpr *CE) {
00608     return Visit(CE->getChosenSubExpr());
00609   }
00610 
00611   llvm::Constant *VisitCompoundLiteralExpr(CompoundLiteralExpr *E) {
00612     return Visit(E->getInitializer());
00613   }
00614 
00615   llvm::Constant *VisitCastExpr(CastExpr* E) {
00616     Expr *subExpr = E->getSubExpr();
00617     llvm::Constant *C = CGM.EmitConstantExpr(subExpr, subExpr->getType(), CGF);
00618     if (!C) return nullptr;
00619 
00620     llvm::Type *destType = ConvertType(E->getType());
00621 
00622     switch (E->getCastKind()) {
00623     case CK_ToUnion: {
00624       // GCC cast to union extension
00625       assert(E->getType()->isUnionType() &&
00626              "Destination type is not union type!");
00627 
00628       // Build a struct with the union sub-element as the first member,
00629       // and padded to the appropriate size
00630       SmallVector<llvm::Constant*, 2> Elts;
00631       SmallVector<llvm::Type*, 2> Types;
00632       Elts.push_back(C);
00633       Types.push_back(C->getType());
00634       unsigned CurSize = CGM.getDataLayout().getTypeAllocSize(C->getType());
00635       unsigned TotalSize = CGM.getDataLayout().getTypeAllocSize(destType);
00636 
00637       assert(CurSize <= TotalSize && "Union size mismatch!");
00638       if (unsigned NumPadBytes = TotalSize - CurSize) {
00639         llvm::Type *Ty = CGM.Int8Ty;
00640         if (NumPadBytes > 1)
00641           Ty = llvm::ArrayType::get(Ty, NumPadBytes);
00642 
00643         Elts.push_back(llvm::UndefValue::get(Ty));
00644         Types.push_back(Ty);
00645       }
00646 
00647       llvm::StructType* STy =
00648         llvm::StructType::get(C->getType()->getContext(), Types, false);
00649       return llvm::ConstantStruct::get(STy, Elts);
00650     }
00651 
00652     case CK_AddressSpaceConversion:
00653       return llvm::ConstantExpr::getAddrSpaceCast(C, destType);
00654 
00655     case CK_LValueToRValue:
00656     case CK_AtomicToNonAtomic:
00657     case CK_NonAtomicToAtomic:
00658     case CK_NoOp:
00659     case CK_ConstructorConversion:
00660       return C;
00661 
00662     case CK_Dependent: llvm_unreachable("saw dependent cast!");
00663 
00664     case CK_BuiltinFnToFnPtr:
00665       llvm_unreachable("builtin functions are handled elsewhere");
00666 
00667     case CK_ReinterpretMemberPointer:
00668     case CK_DerivedToBaseMemberPointer:
00669     case CK_BaseToDerivedMemberPointer:
00670       return CGM.getCXXABI().EmitMemberPointerConversion(E, C);
00671 
00672     // These will never be supported.
00673     case CK_ObjCObjectLValueCast:
00674     case CK_ARCProduceObject:
00675     case CK_ARCConsumeObject:
00676     case CK_ARCReclaimReturnedObject:
00677     case CK_ARCExtendBlockObject:
00678     case CK_CopyAndAutoreleaseBlockObject:
00679       return nullptr;
00680 
00681     // These don't need to be handled here because Evaluate knows how to
00682     // evaluate them in the cases where they can be folded.
00683     case CK_BitCast:
00684     case CK_ToVoid:
00685     case CK_Dynamic:
00686     case CK_LValueBitCast:
00687     case CK_NullToMemberPointer:
00688     case CK_UserDefinedConversion:
00689     case CK_CPointerToObjCPointerCast:
00690     case CK_BlockPointerToObjCPointerCast:
00691     case CK_AnyPointerToBlockPointerCast:
00692     case CK_ArrayToPointerDecay:
00693     case CK_FunctionToPointerDecay:
00694     case CK_BaseToDerived:
00695     case CK_DerivedToBase:
00696     case CK_UncheckedDerivedToBase:
00697     case CK_MemberPointerToBoolean:
00698     case CK_VectorSplat:
00699     case CK_FloatingRealToComplex:
00700     case CK_FloatingComplexToReal:
00701     case CK_FloatingComplexToBoolean:
00702     case CK_FloatingComplexCast:
00703     case CK_FloatingComplexToIntegralComplex:
00704     case CK_IntegralRealToComplex:
00705     case CK_IntegralComplexToReal:
00706     case CK_IntegralComplexToBoolean:
00707     case CK_IntegralComplexCast:
00708     case CK_IntegralComplexToFloatingComplex:
00709     case CK_PointerToIntegral:
00710     case CK_PointerToBoolean:
00711     case CK_NullToPointer:
00712     case CK_IntegralCast:
00713     case CK_IntegralToPointer:
00714     case CK_IntegralToBoolean:
00715     case CK_IntegralToFloating:
00716     case CK_FloatingToIntegral:
00717     case CK_FloatingToBoolean:
00718     case CK_FloatingCast:
00719     case CK_ZeroToOCLEvent:
00720       return nullptr;
00721     }
00722     llvm_unreachable("Invalid CastKind");
00723   }
00724 
00725   llvm::Constant *VisitCXXDefaultArgExpr(CXXDefaultArgExpr *DAE) {
00726     return Visit(DAE->getExpr());
00727   }
00728 
00729   llvm::Constant *VisitCXXDefaultInitExpr(CXXDefaultInitExpr *DIE) {
00730     // No need for a DefaultInitExprScope: we don't handle 'this' in a
00731     // constant expression.
00732     return Visit(DIE->getExpr());
00733   }
00734 
00735   llvm::Constant *VisitMaterializeTemporaryExpr(MaterializeTemporaryExpr *E) {
00736     return Visit(E->GetTemporaryExpr());
00737   }
00738 
00739   llvm::Constant *EmitArrayInitialization(InitListExpr *ILE) {
00740     if (ILE->isStringLiteralInit())
00741       return Visit(ILE->getInit(0));
00742 
00743     llvm::ArrayType *AType =
00744         cast<llvm::ArrayType>(ConvertType(ILE->getType()));
00745     llvm::Type *ElemTy = AType->getElementType();
00746     unsigned NumInitElements = ILE->getNumInits();
00747     unsigned NumElements = AType->getNumElements();
00748 
00749     // Initialising an array requires us to automatically
00750     // initialise any elements that have not been initialised explicitly
00751     unsigned NumInitableElts = std::min(NumInitElements, NumElements);
00752 
00753     // Copy initializer elements.
00754     std::vector<llvm::Constant*> Elts;
00755     Elts.reserve(NumInitableElts + NumElements);
00756 
00757     bool RewriteType = false;
00758     for (unsigned i = 0; i < NumInitableElts; ++i) {
00759       Expr *Init = ILE->getInit(i);
00760       llvm::Constant *C = CGM.EmitConstantExpr(Init, Init->getType(), CGF);
00761       if (!C)
00762         return nullptr;
00763       RewriteType |= (C->getType() != ElemTy);
00764       Elts.push_back(C);
00765     }
00766 
00767     // Initialize remaining array elements.
00768     // FIXME: This doesn't handle member pointers correctly!
00769     llvm::Constant *fillC;
00770     if (Expr *filler = ILE->getArrayFiller())
00771       fillC = CGM.EmitConstantExpr(filler, filler->getType(), CGF);
00772     else
00773       fillC = llvm::Constant::getNullValue(ElemTy);
00774     if (!fillC)
00775       return nullptr;
00776     RewriteType |= (fillC->getType() != ElemTy);
00777     Elts.resize(NumElements, fillC);
00778 
00779     if (RewriteType) {
00780       // FIXME: Try to avoid packing the array
00781       std::vector<llvm::Type*> Types;
00782       Types.reserve(NumInitableElts + NumElements);
00783       for (unsigned i = 0, e = Elts.size(); i < e; ++i)
00784         Types.push_back(Elts[i]->getType());
00785       llvm::StructType *SType = llvm::StructType::get(AType->getContext(),
00786                                                             Types, true);
00787       return llvm::ConstantStruct::get(SType, Elts);
00788     }
00789 
00790     return llvm::ConstantArray::get(AType, Elts);
00791   }
00792 
00793   llvm::Constant *EmitRecordInitialization(InitListExpr *ILE) {
00794     return ConstStructBuilder::BuildStruct(CGM, CGF, ILE);
00795   }
00796 
00797   llvm::Constant *VisitImplicitValueInitExpr(ImplicitValueInitExpr* E) {
00798     return CGM.EmitNullConstant(E->getType());
00799   }
00800 
00801   llvm::Constant *VisitInitListExpr(InitListExpr *ILE) {
00802     if (ILE->getType()->isArrayType())
00803       return EmitArrayInitialization(ILE);
00804 
00805     if (ILE->getType()->isRecordType())
00806       return EmitRecordInitialization(ILE);
00807 
00808     return nullptr;
00809   }
00810 
00811   llvm::Constant *VisitCXXConstructExpr(CXXConstructExpr *E) {
00812     if (!E->getConstructor()->isTrivial())
00813       return nullptr;
00814 
00815     QualType Ty = E->getType();
00816 
00817     // FIXME: We should not have to call getBaseElementType here.
00818     const RecordType *RT = 
00819       CGM.getContext().getBaseElementType(Ty)->getAs<RecordType>();
00820     const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
00821     
00822     // If the class doesn't have a trivial destructor, we can't emit it as a
00823     // constant expr.
00824     if (!RD->hasTrivialDestructor())
00825       return nullptr;
00826 
00827     // Only copy and default constructors can be trivial.
00828 
00829 
00830     if (E->getNumArgs()) {
00831       assert(E->getNumArgs() == 1 && "trivial ctor with > 1 argument");
00832       assert(E->getConstructor()->isCopyOrMoveConstructor() &&
00833              "trivial ctor has argument but isn't a copy/move ctor");
00834 
00835       Expr *Arg = E->getArg(0);
00836       assert(CGM.getContext().hasSameUnqualifiedType(Ty, Arg->getType()) &&
00837              "argument to copy ctor is of wrong type");
00838 
00839       return Visit(Arg);
00840     }
00841 
00842     return CGM.EmitNullConstant(Ty);
00843   }
00844 
00845   llvm::Constant *VisitStringLiteral(StringLiteral *E) {
00846     return CGM.GetConstantArrayFromStringLiteral(E);
00847   }
00848 
00849   llvm::Constant *VisitObjCEncodeExpr(ObjCEncodeExpr *E) {
00850     // This must be an @encode initializing an array in a static initializer.
00851     // Don't emit it as the address of the string, emit the string data itself
00852     // as an inline array.
00853     std::string Str;
00854     CGM.getContext().getObjCEncodingForType(E->getEncodedType(), Str);
00855     QualType T = E->getType();
00856     if (T->getTypeClass() == Type::TypeOfExpr)
00857       T = cast<TypeOfExprType>(T)->getUnderlyingExpr()->getType();
00858     const ConstantArrayType *CAT = cast<ConstantArrayType>(T);
00859 
00860     // Resize the string to the right size, adding zeros at the end, or
00861     // truncating as needed.
00862     Str.resize(CAT->getSize().getZExtValue(), '\0');
00863     return llvm::ConstantDataArray::getString(VMContext, Str, false);
00864   }
00865 
00866   llvm::Constant *VisitUnaryExtension(const UnaryOperator *E) {
00867     return Visit(E->getSubExpr());
00868   }
00869 
00870   // Utility methods
00871   llvm::Type *ConvertType(QualType T) {
00872     return CGM.getTypes().ConvertType(T);
00873   }
00874 
00875 public:
00876   llvm::Constant *EmitLValue(APValue::LValueBase LVBase) {
00877     if (const ValueDecl *Decl = LVBase.dyn_cast<const ValueDecl*>()) {
00878       if (Decl->hasAttr<WeakRefAttr>())
00879         return CGM.GetWeakRefReference(Decl);
00880       if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(Decl))
00881         return CGM.GetAddrOfFunction(FD);
00882       if (const VarDecl* VD = dyn_cast<VarDecl>(Decl)) {
00883         // We can never refer to a variable with local storage.
00884         if (!VD->hasLocalStorage()) {
00885           if (VD->isFileVarDecl() || VD->hasExternalStorage())
00886             return CGM.GetAddrOfGlobalVar(VD);
00887           else if (VD->isLocalVarDecl())
00888             return CGM.getOrCreateStaticVarDecl(
00889                 *VD, CGM.getLLVMLinkageVarDefinition(VD, /*isConstant=*/false));
00890         }
00891       }
00892       return nullptr;
00893     }
00894 
00895     Expr *E = const_cast<Expr*>(LVBase.get<const Expr*>());
00896     switch (E->getStmtClass()) {
00897     default: break;
00898     case Expr::CompoundLiteralExprClass: {
00899       // Note that due to the nature of compound literals, this is guaranteed
00900       // to be the only use of the variable, so we just generate it here.
00901       CompoundLiteralExpr *CLE = cast<CompoundLiteralExpr>(E);
00902       llvm::Constant* C = CGM.EmitConstantExpr(CLE->getInitializer(),
00903                                                CLE->getType(), CGF);
00904       // FIXME: "Leaked" on failure.
00905       if (C)
00906         C = new llvm::GlobalVariable(CGM.getModule(), C->getType(),
00907                                      E->getType().isConstant(CGM.getContext()),
00908                                      llvm::GlobalValue::InternalLinkage,
00909                                      C, ".compoundliteral", nullptr,
00910                                      llvm::GlobalVariable::NotThreadLocal,
00911                           CGM.getContext().getTargetAddressSpace(E->getType()));
00912       return C;
00913     }
00914     case Expr::StringLiteralClass:
00915       return CGM.GetAddrOfConstantStringFromLiteral(cast<StringLiteral>(E));
00916     case Expr::ObjCEncodeExprClass:
00917       return CGM.GetAddrOfConstantStringFromObjCEncode(cast<ObjCEncodeExpr>(E));
00918     case Expr::ObjCStringLiteralClass: {
00919       ObjCStringLiteral* SL = cast<ObjCStringLiteral>(E);
00920       llvm::Constant *C =
00921           CGM.getObjCRuntime().GenerateConstantString(SL->getString());
00922       return llvm::ConstantExpr::getBitCast(C, ConvertType(E->getType()));
00923     }
00924     case Expr::PredefinedExprClass: {
00925       unsigned Type = cast<PredefinedExpr>(E)->getIdentType();
00926       if (CGF) {
00927         LValue Res = CGF->EmitPredefinedLValue(cast<PredefinedExpr>(E));
00928         return cast<llvm::Constant>(Res.getAddress());
00929       } else if (Type == PredefinedExpr::PrettyFunction) {
00930         return CGM.GetAddrOfConstantCString("top level", ".tmp");
00931       }
00932 
00933       return CGM.GetAddrOfConstantCString("", ".tmp");
00934     }
00935     case Expr::AddrLabelExprClass: {
00936       assert(CGF && "Invalid address of label expression outside function.");
00937       llvm::Constant *Ptr =
00938         CGF->GetAddrOfLabel(cast<AddrLabelExpr>(E)->getLabel());
00939       return llvm::ConstantExpr::getBitCast(Ptr, ConvertType(E->getType()));
00940     }
00941     case Expr::CallExprClass: {
00942       CallExpr* CE = cast<CallExpr>(E);
00943       unsigned builtin = CE->getBuiltinCallee();
00944       if (builtin !=
00945             Builtin::BI__builtin___CFStringMakeConstantString &&
00946           builtin !=
00947             Builtin::BI__builtin___NSStringMakeConstantString)
00948         break;
00949       const Expr *Arg = CE->getArg(0)->IgnoreParenCasts();
00950       const StringLiteral *Literal = cast<StringLiteral>(Arg);
00951       if (builtin ==
00952             Builtin::BI__builtin___NSStringMakeConstantString) {
00953         return CGM.getObjCRuntime().GenerateConstantString(Literal);
00954       }
00955       // FIXME: need to deal with UCN conversion issues.
00956       return CGM.GetAddrOfConstantCFString(Literal);
00957     }
00958     case Expr::BlockExprClass: {
00959       std::string FunctionName;
00960       if (CGF)
00961         FunctionName = CGF->CurFn->getName();
00962       else
00963         FunctionName = "global";
00964 
00965       return CGM.GetAddrOfGlobalBlock(cast<BlockExpr>(E), FunctionName.c_str());
00966     }
00967     case Expr::CXXTypeidExprClass: {
00968       CXXTypeidExpr *Typeid = cast<CXXTypeidExpr>(E);
00969       QualType T;
00970       if (Typeid->isTypeOperand())
00971         T = Typeid->getTypeOperand(CGM.getContext());
00972       else
00973         T = Typeid->getExprOperand()->getType();
00974       return CGM.GetAddrOfRTTIDescriptor(T);
00975     }
00976     case Expr::CXXUuidofExprClass: {
00977       return CGM.GetAddrOfUuidDescriptor(cast<CXXUuidofExpr>(E));
00978     }
00979     case Expr::MaterializeTemporaryExprClass: {
00980       MaterializeTemporaryExpr *MTE = cast<MaterializeTemporaryExpr>(E);
00981       assert(MTE->getStorageDuration() == SD_Static);
00982       SmallVector<const Expr *, 2> CommaLHSs;
00983       SmallVector<SubobjectAdjustment, 2> Adjustments;
00984       const Expr *Inner = MTE->GetTemporaryExpr()
00985           ->skipRValueSubobjectAdjustments(CommaLHSs, Adjustments);
00986       return CGM.GetAddrOfGlobalTemporary(MTE, Inner);
00987     }
00988     }
00989 
00990     return nullptr;
00991   }
00992 };
00993 
00994 }  // end anonymous namespace.
00995 
00996 llvm::Constant *CodeGenModule::EmitConstantInit(const VarDecl &D,
00997                                                 CodeGenFunction *CGF) {
00998   // Make a quick check if variable can be default NULL initialized
00999   // and avoid going through rest of code which may do, for c++11,
01000   // initialization of memory to all NULLs.
01001   if (!D.hasLocalStorage()) {
01002     QualType Ty = D.getType();
01003     if (Ty->isArrayType())
01004       Ty = Context.getBaseElementType(Ty);
01005     if (Ty->isRecordType())
01006       if (const CXXConstructExpr *E =
01007           dyn_cast_or_null<CXXConstructExpr>(D.getInit())) {
01008         const CXXConstructorDecl *CD = E->getConstructor();
01009         if (CD->isTrivial() && CD->isDefaultConstructor())
01010           return EmitNullConstant(D.getType());
01011       }
01012   }
01013   
01014   if (const APValue *Value = D.evaluateValue())
01015     return EmitConstantValueForMemory(*Value, D.getType(), CGF);
01016 
01017   // FIXME: Implement C++11 [basic.start.init]p2: if the initializer of a
01018   // reference is a constant expression, and the reference binds to a temporary,
01019   // then constant initialization is performed. ConstExprEmitter will
01020   // incorrectly emit a prvalue constant in this case, and the calling code
01021   // interprets that as the (pointer) value of the reference, rather than the
01022   // desired value of the referee.
01023   if (D.getType()->isReferenceType())
01024     return nullptr;
01025 
01026   const Expr *E = D.getInit();
01027   assert(E && "No initializer to emit");
01028 
01029   llvm::Constant* C = ConstExprEmitter(*this, CGF).Visit(const_cast<Expr*>(E));
01030   if (C && C->getType()->isIntegerTy(1)) {
01031     llvm::Type *BoolTy = getTypes().ConvertTypeForMem(E->getType());
01032     C = llvm::ConstantExpr::getZExt(C, BoolTy);
01033   }
01034   return C;
01035 }
01036 
01037 llvm::Constant *CodeGenModule::EmitConstantExpr(const Expr *E,
01038                                                 QualType DestType,
01039                                                 CodeGenFunction *CGF) {
01040   Expr::EvalResult Result;
01041 
01042   bool Success = false;
01043 
01044   if (DestType->isReferenceType())
01045     Success = E->EvaluateAsLValue(Result, Context);
01046   else
01047     Success = E->EvaluateAsRValue(Result, Context);
01048 
01049   llvm::Constant *C = nullptr;
01050   if (Success && !Result.HasSideEffects)
01051     C = EmitConstantValue(Result.Val, DestType, CGF);
01052   else
01053     C = ConstExprEmitter(*this, CGF).Visit(const_cast<Expr*>(E));
01054 
01055   if (C && C->getType()->isIntegerTy(1)) {
01056     llvm::Type *BoolTy = getTypes().ConvertTypeForMem(E->getType());
01057     C = llvm::ConstantExpr::getZExt(C, BoolTy);
01058   }
01059   return C;
01060 }
01061 
01062 llvm::Constant *CodeGenModule::EmitConstantValue(const APValue &Value,
01063                                                  QualType DestType,
01064                                                  CodeGenFunction *CGF) {
01065   // For an _Atomic-qualified constant, we may need to add tail padding.
01066   if (auto *AT = DestType->getAs<AtomicType>()) {
01067     QualType InnerType = AT->getValueType();
01068     auto *Inner = EmitConstantValue(Value, InnerType, CGF);
01069 
01070     uint64_t InnerSize = Context.getTypeSize(InnerType);
01071     uint64_t OuterSize = Context.getTypeSize(DestType);
01072     if (InnerSize == OuterSize)
01073       return Inner;
01074 
01075     assert(InnerSize < OuterSize && "emitted over-large constant for atomic");
01076     llvm::Constant *Elts[] = {
01077       Inner,
01078       llvm::ConstantAggregateZero::get(
01079           llvm::ArrayType::get(Int8Ty, (OuterSize - InnerSize) / 8))
01080     };
01081     return llvm::ConstantStruct::getAnon(Elts);
01082   }
01083 
01084   switch (Value.getKind()) {
01085   case APValue::Uninitialized:
01086     llvm_unreachable("Constant expressions should be initialized.");
01087   case APValue::LValue: {
01088     llvm::Type *DestTy = getTypes().ConvertTypeForMem(DestType);
01089     llvm::Constant *Offset =
01090       llvm::ConstantInt::get(Int64Ty, Value.getLValueOffset().getQuantity());
01091 
01092     llvm::Constant *C;
01093     if (APValue::LValueBase LVBase = Value.getLValueBase()) {
01094       // An array can be represented as an lvalue referring to the base.
01095       if (isa<llvm::ArrayType>(DestTy)) {
01096         assert(Offset->isNullValue() && "offset on array initializer");
01097         return ConstExprEmitter(*this, CGF).Visit(
01098           const_cast<Expr*>(LVBase.get<const Expr*>()));
01099       }
01100 
01101       C = ConstExprEmitter(*this, CGF).EmitLValue(LVBase);
01102 
01103       // Apply offset if necessary.
01104       if (!Offset->isNullValue()) {
01105         unsigned AS = C->getType()->getPointerAddressSpace();
01106         llvm::Type *CharPtrTy = Int8Ty->getPointerTo(AS);
01107         llvm::Constant *Casted = llvm::ConstantExpr::getBitCast(C, CharPtrTy);
01108         Casted = llvm::ConstantExpr::getGetElementPtr(Casted, Offset);
01109         C = llvm::ConstantExpr::getPointerCast(Casted, C->getType());
01110       }
01111 
01112       // Convert to the appropriate type; this could be an lvalue for
01113       // an integer.
01114       if (isa<llvm::PointerType>(DestTy))
01115         return llvm::ConstantExpr::getPointerCast(C, DestTy);
01116 
01117       return llvm::ConstantExpr::getPtrToInt(C, DestTy);
01118     } else {
01119       C = Offset;
01120 
01121       // Convert to the appropriate type; this could be an lvalue for
01122       // an integer.
01123       if (isa<llvm::PointerType>(DestTy))
01124         return llvm::ConstantExpr::getIntToPtr(C, DestTy);
01125 
01126       // If the types don't match this should only be a truncate.
01127       if (C->getType() != DestTy)
01128         return llvm::ConstantExpr::getTrunc(C, DestTy);
01129 
01130       return C;
01131     }
01132   }
01133   case APValue::Int:
01134     return llvm::ConstantInt::get(VMContext, Value.getInt());
01135   case APValue::ComplexInt: {
01136     llvm::Constant *Complex[2];
01137 
01138     Complex[0] = llvm::ConstantInt::get(VMContext,
01139                                         Value.getComplexIntReal());
01140     Complex[1] = llvm::ConstantInt::get(VMContext,
01141                                         Value.getComplexIntImag());
01142 
01143     // FIXME: the target may want to specify that this is packed.
01144     llvm::StructType *STy = llvm::StructType::get(Complex[0]->getType(),
01145                                                   Complex[1]->getType(),
01146                                                   NULL);
01147     return llvm::ConstantStruct::get(STy, Complex);
01148   }
01149   case APValue::Float: {
01150     const llvm::APFloat &Init = Value.getFloat();
01151     if (&Init.getSemantics() == &llvm::APFloat::IEEEhalf &&
01152         !Context.getLangOpts().NativeHalfType &&
01153         !Context.getLangOpts().HalfArgsAndReturns)
01154       return llvm::ConstantInt::get(VMContext, Init.bitcastToAPInt());
01155     else
01156       return llvm::ConstantFP::get(VMContext, Init);
01157   }
01158   case APValue::ComplexFloat: {
01159     llvm::Constant *Complex[2];
01160 
01161     Complex[0] = llvm::ConstantFP::get(VMContext,
01162                                        Value.getComplexFloatReal());
01163     Complex[1] = llvm::ConstantFP::get(VMContext,
01164                                        Value.getComplexFloatImag());
01165 
01166     // FIXME: the target may want to specify that this is packed.
01167     llvm::StructType *STy = llvm::StructType::get(Complex[0]->getType(),
01168                                                   Complex[1]->getType(),
01169                                                   NULL);
01170     return llvm::ConstantStruct::get(STy, Complex);
01171   }
01172   case APValue::Vector: {
01173     SmallVector<llvm::Constant *, 4> Inits;
01174     unsigned NumElts = Value.getVectorLength();
01175 
01176     for (unsigned i = 0; i != NumElts; ++i) {
01177       const APValue &Elt = Value.getVectorElt(i);
01178       if (Elt.isInt())
01179         Inits.push_back(llvm::ConstantInt::get(VMContext, Elt.getInt()));
01180       else
01181         Inits.push_back(llvm::ConstantFP::get(VMContext, Elt.getFloat()));
01182     }
01183     return llvm::ConstantVector::get(Inits);
01184   }
01185   case APValue::AddrLabelDiff: {
01186     const AddrLabelExpr *LHSExpr = Value.getAddrLabelDiffLHS();
01187     const AddrLabelExpr *RHSExpr = Value.getAddrLabelDiffRHS();
01188     llvm::Constant *LHS = EmitConstantExpr(LHSExpr, LHSExpr->getType(), CGF);
01189     llvm::Constant *RHS = EmitConstantExpr(RHSExpr, RHSExpr->getType(), CGF);
01190 
01191     // Compute difference
01192     llvm::Type *ResultType = getTypes().ConvertType(DestType);
01193     LHS = llvm::ConstantExpr::getPtrToInt(LHS, IntPtrTy);
01194     RHS = llvm::ConstantExpr::getPtrToInt(RHS, IntPtrTy);
01195     llvm::Constant *AddrLabelDiff = llvm::ConstantExpr::getSub(LHS, RHS);
01196 
01197     // LLVM is a bit sensitive about the exact format of the
01198     // address-of-label difference; make sure to truncate after
01199     // the subtraction.
01200     return llvm::ConstantExpr::getTruncOrBitCast(AddrLabelDiff, ResultType);
01201   }
01202   case APValue::Struct:
01203   case APValue::Union:
01204     return ConstStructBuilder::BuildStruct(*this, CGF, Value, DestType);
01205   case APValue::Array: {
01206     const ArrayType *CAT = Context.getAsArrayType(DestType);
01207     unsigned NumElements = Value.getArraySize();
01208     unsigned NumInitElts = Value.getArrayInitializedElts();
01209 
01210     std::vector<llvm::Constant*> Elts;
01211     Elts.reserve(NumElements);
01212 
01213     // Emit array filler, if there is one.
01214     llvm::Constant *Filler = nullptr;
01215     if (Value.hasArrayFiller())
01216       Filler = EmitConstantValueForMemory(Value.getArrayFiller(),
01217                                           CAT->getElementType(), CGF);
01218 
01219     // Emit initializer elements.
01220     llvm::Type *CommonElementType = nullptr;
01221     for (unsigned I = 0; I < NumElements; ++I) {
01222       llvm::Constant *C = Filler;
01223       if (I < NumInitElts)
01224         C = EmitConstantValueForMemory(Value.getArrayInitializedElt(I),
01225                                        CAT->getElementType(), CGF);
01226       else
01227         assert(Filler && "Missing filler for implicit elements of initializer");
01228       if (I == 0)
01229         CommonElementType = C->getType();
01230       else if (C->getType() != CommonElementType)
01231         CommonElementType = nullptr;
01232       Elts.push_back(C);
01233     }
01234 
01235     if (!CommonElementType) {
01236       // FIXME: Try to avoid packing the array
01237       std::vector<llvm::Type*> Types;
01238       Types.reserve(NumElements);
01239       for (unsigned i = 0, e = Elts.size(); i < e; ++i)
01240         Types.push_back(Elts[i]->getType());
01241       llvm::StructType *SType = llvm::StructType::get(VMContext, Types, true);
01242       return llvm::ConstantStruct::get(SType, Elts);
01243     }
01244 
01245     llvm::ArrayType *AType =
01246       llvm::ArrayType::get(CommonElementType, NumElements);
01247     return llvm::ConstantArray::get(AType, Elts);
01248   }
01249   case APValue::MemberPointer:
01250     return getCXXABI().EmitMemberPointer(Value, DestType);
01251   }
01252   llvm_unreachable("Unknown APValue kind");
01253 }
01254 
01255 llvm::Constant *
01256 CodeGenModule::EmitConstantValueForMemory(const APValue &Value,
01257                                           QualType DestType,
01258                                           CodeGenFunction *CGF) {
01259   llvm::Constant *C = EmitConstantValue(Value, DestType, CGF);
01260   if (C->getType()->isIntegerTy(1)) {
01261     llvm::Type *BoolTy = getTypes().ConvertTypeForMem(DestType);
01262     C = llvm::ConstantExpr::getZExt(C, BoolTy);
01263   }
01264   return C;
01265 }
01266 
01267 llvm::Constant *
01268 CodeGenModule::GetAddrOfConstantCompoundLiteral(const CompoundLiteralExpr *E) {
01269   assert(E->isFileScope() && "not a file-scope compound literal expr");
01270   return ConstExprEmitter(*this, nullptr).EmitLValue(E);
01271 }
01272 
01273 llvm::Constant *
01274 CodeGenModule::getMemberPointerConstant(const UnaryOperator *uo) {
01275   // Member pointer constants always have a very particular form.
01276   const MemberPointerType *type = cast<MemberPointerType>(uo->getType());
01277   const ValueDecl *decl = cast<DeclRefExpr>(uo->getSubExpr())->getDecl();
01278 
01279   // A member function pointer.
01280   if (const CXXMethodDecl *method = dyn_cast<CXXMethodDecl>(decl))
01281     return getCXXABI().EmitMemberPointer(method);
01282 
01283   // Otherwise, a member data pointer.
01284   uint64_t fieldOffset = getContext().getFieldOffset(decl);
01285   CharUnits chars = getContext().toCharUnitsFromBits((int64_t) fieldOffset);
01286   return getCXXABI().EmitMemberDataPointer(type, chars);
01287 }
01288 
01289 static llvm::Constant *EmitNullConstantForBase(CodeGenModule &CGM,
01290                                                llvm::Type *baseType,
01291                                                const CXXRecordDecl *base);
01292 
01293 static llvm::Constant *EmitNullConstant(CodeGenModule &CGM,
01294                                         const CXXRecordDecl *record,
01295                                         bool asCompleteObject) {
01296   const CGRecordLayout &layout = CGM.getTypes().getCGRecordLayout(record);
01297   llvm::StructType *structure =
01298     (asCompleteObject ? layout.getLLVMType()
01299                       : layout.getBaseSubobjectLLVMType());
01300 
01301   unsigned numElements = structure->getNumElements();
01302   std::vector<llvm::Constant *> elements(numElements);
01303 
01304   // Fill in all the bases.
01305   for (const auto &I : record->bases()) {
01306     if (I.isVirtual()) {
01307       // Ignore virtual bases; if we're laying out for a complete
01308       // object, we'll lay these out later.
01309       continue;
01310     }
01311 
01312     const CXXRecordDecl *base = 
01313       cast<CXXRecordDecl>(I.getType()->castAs<RecordType>()->getDecl());
01314 
01315     // Ignore empty bases.
01316     if (base->isEmpty())
01317       continue;
01318     
01319     unsigned fieldIndex = layout.getNonVirtualBaseLLVMFieldNo(base);
01320     llvm::Type *baseType = structure->getElementType(fieldIndex);
01321     elements[fieldIndex] = EmitNullConstantForBase(CGM, baseType, base);
01322   }
01323 
01324   // Fill in all the fields.
01325   for (const auto *Field : record->fields()) {
01326     // Fill in non-bitfields. (Bitfields always use a zero pattern, which we
01327     // will fill in later.)
01328     if (!Field->isBitField()) {
01329       unsigned fieldIndex = layout.getLLVMFieldNo(Field);
01330       elements[fieldIndex] = CGM.EmitNullConstant(Field->getType());
01331     }
01332 
01333     // For unions, stop after the first named field.
01334     if (record->isUnion() && Field->getDeclName())
01335       break;
01336   }
01337 
01338   // Fill in the virtual bases, if we're working with the complete object.
01339   if (asCompleteObject) {
01340     for (const auto &I : record->vbases()) {
01341       const CXXRecordDecl *base = 
01342         cast<CXXRecordDecl>(I.getType()->castAs<RecordType>()->getDecl());
01343 
01344       // Ignore empty bases.
01345       if (base->isEmpty())
01346         continue;
01347 
01348       unsigned fieldIndex = layout.getVirtualBaseIndex(base);
01349 
01350       // We might have already laid this field out.
01351       if (elements[fieldIndex]) continue;
01352 
01353       llvm::Type *baseType = structure->getElementType(fieldIndex);
01354       elements[fieldIndex] = EmitNullConstantForBase(CGM, baseType, base);
01355     }
01356   }
01357 
01358   // Now go through all other fields and zero them out.
01359   for (unsigned i = 0; i != numElements; ++i) {
01360     if (!elements[i])
01361       elements[i] = llvm::Constant::getNullValue(structure->getElementType(i));
01362   }
01363   
01364   return llvm::ConstantStruct::get(structure, elements);
01365 }
01366 
01367 /// Emit the null constant for a base subobject.
01368 static llvm::Constant *EmitNullConstantForBase(CodeGenModule &CGM,
01369                                                llvm::Type *baseType,
01370                                                const CXXRecordDecl *base) {
01371   const CGRecordLayout &baseLayout = CGM.getTypes().getCGRecordLayout(base);
01372 
01373   // Just zero out bases that don't have any pointer to data members.
01374   if (baseLayout.isZeroInitializableAsBase())
01375     return llvm::Constant::getNullValue(baseType);
01376 
01377   // Otherwise, we can just use its null constant.
01378   return EmitNullConstant(CGM, base, /*asCompleteObject=*/false);
01379 }
01380 
01381 llvm::Constant *CodeGenModule::EmitNullConstant(QualType T) {
01382   if (getTypes().isZeroInitializable(T))
01383     return llvm::Constant::getNullValue(getTypes().ConvertTypeForMem(T));
01384     
01385   if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(T)) {
01386     llvm::ArrayType *ATy =
01387       cast<llvm::ArrayType>(getTypes().ConvertTypeForMem(T));
01388 
01389     QualType ElementTy = CAT->getElementType();
01390 
01391     llvm::Constant *Element = EmitNullConstant(ElementTy);
01392     unsigned NumElements = CAT->getSize().getZExtValue();
01393     
01394     if (Element->isNullValue())
01395       return llvm::ConstantAggregateZero::get(ATy);
01396     
01397     SmallVector<llvm::Constant *, 8> Array(NumElements, Element);
01398     return llvm::ConstantArray::get(ATy, Array);
01399   }
01400 
01401   if (const RecordType *RT = T->getAs<RecordType>()) {
01402     const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
01403     return ::EmitNullConstant(*this, RD, /*complete object*/ true);
01404   }
01405 
01406   assert(T->isMemberPointerType() && "Should only see member pointers here!");
01407   assert(!T->getAs<MemberPointerType>()->getPointeeType()->isFunctionType() &&
01408          "Should only see pointers to data members here!");
01409 
01410   return getCXXABI().EmitNullMemberPointer(T->castAs<MemberPointerType>());
01411 }
01412 
01413 llvm::Constant *
01414 CodeGenModule::EmitNullConstantForBase(const CXXRecordDecl *Record) {
01415   return ::EmitNullConstant(*this, Record, false);
01416 }