Home | History | Annotate | Download | only in CodeGen
      1 //===--- CGDecl.cpp - Emit LLVM Code for declarations ---------------------===//
      2 //
      3 //                     The LLVM Compiler Infrastructure
      4 //
      5 // This file is distributed under the University of Illinois Open Source
      6 // License. See LICENSE.TXT for details.
      7 //
      8 //===----------------------------------------------------------------------===//
      9 //
     10 // This contains code to emit Decl nodes as LLVM code.
     11 //
     12 //===----------------------------------------------------------------------===//
     13 
     14 #include "CodeGenFunction.h"
     15 #include "CGDebugInfo.h"
     16 #include "CGOpenCLRuntime.h"
     17 #include "CodeGenModule.h"
     18 #include "clang/AST/ASTContext.h"
     19 #include "clang/AST/CharUnits.h"
     20 #include "clang/AST/Decl.h"
     21 #include "clang/AST/DeclObjC.h"
     22 #include "clang/Basic/SourceManager.h"
     23 #include "clang/Basic/TargetInfo.h"
     24 #include "clang/CodeGen/CGFunctionInfo.h"
     25 #include "clang/Frontend/CodeGenOptions.h"
     26 #include "llvm/IR/DataLayout.h"
     27 #include "llvm/IR/GlobalVariable.h"
     28 #include "llvm/IR/Intrinsics.h"
     29 #include "llvm/IR/Type.h"
     30 using namespace clang;
     31 using namespace CodeGen;
     32 
     33 
     34 void CodeGenFunction::EmitDecl(const Decl &D) {
     35   switch (D.getKind()) {
     36   case Decl::TranslationUnit:
     37   case Decl::Namespace:
     38   case Decl::UnresolvedUsingTypename:
     39   case Decl::ClassTemplateSpecialization:
     40   case Decl::ClassTemplatePartialSpecialization:
     41   case Decl::VarTemplateSpecialization:
     42   case Decl::VarTemplatePartialSpecialization:
     43   case Decl::TemplateTypeParm:
     44   case Decl::UnresolvedUsingValue:
     45   case Decl::NonTypeTemplateParm:
     46   case Decl::CXXMethod:
     47   case Decl::CXXConstructor:
     48   case Decl::CXXDestructor:
     49   case Decl::CXXConversion:
     50   case Decl::Field:
     51   case Decl::MSProperty:
     52   case Decl::IndirectField:
     53   case Decl::ObjCIvar:
     54   case Decl::ObjCAtDefsField:
     55   case Decl::ParmVar:
     56   case Decl::ImplicitParam:
     57   case Decl::ClassTemplate:
     58   case Decl::VarTemplate:
     59   case Decl::FunctionTemplate:
     60   case Decl::TypeAliasTemplate:
     61   case Decl::TemplateTemplateParm:
     62   case Decl::ObjCMethod:
     63   case Decl::ObjCCategory:
     64   case Decl::ObjCProtocol:
     65   case Decl::ObjCInterface:
     66   case Decl::ObjCCategoryImpl:
     67   case Decl::ObjCImplementation:
     68   case Decl::ObjCProperty:
     69   case Decl::ObjCCompatibleAlias:
     70   case Decl::AccessSpec:
     71   case Decl::LinkageSpec:
     72   case Decl::ObjCPropertyImpl:
     73   case Decl::FileScopeAsm:
     74   case Decl::Friend:
     75   case Decl::FriendTemplate:
     76   case Decl::Block:
     77   case Decl::Captured:
     78   case Decl::ClassScopeFunctionSpecialization:
     79   case Decl::UsingShadow:
     80     llvm_unreachable("Declaration should not be in declstmts!");
     81   case Decl::Function:  // void X();
     82   case Decl::Record:    // struct/union/class X;
     83   case Decl::Enum:      // enum X;
     84   case Decl::EnumConstant: // enum ? { X = ? }
     85   case Decl::CXXRecord: // struct/union/class X; [C++]
     86   case Decl::StaticAssert: // static_assert(X, ""); [C++0x]
     87   case Decl::Label:        // __label__ x;
     88   case Decl::Import:
     89   case Decl::OMPThreadPrivate:
     90   case Decl::Empty:
     91     // None of these decls require codegen support.
     92     return;
     93 
     94   case Decl::NamespaceAlias:
     95     if (CGDebugInfo *DI = getDebugInfo())
     96         DI->EmitNamespaceAlias(cast<NamespaceAliasDecl>(D));
     97     return;
     98   case Decl::Using:          // using X; [C++]
     99     if (CGDebugInfo *DI = getDebugInfo())
    100         DI->EmitUsingDecl(cast<UsingDecl>(D));
    101     return;
    102   case Decl::UsingDirective: // using namespace X; [C++]
    103     if (CGDebugInfo *DI = getDebugInfo())
    104       DI->EmitUsingDirective(cast<UsingDirectiveDecl>(D));
    105     return;
    106   case Decl::Var: {
    107     const VarDecl &VD = cast<VarDecl>(D);
    108     assert(VD.isLocalVarDecl() &&
    109            "Should not see file-scope variables inside a function!");
    110     return EmitVarDecl(VD);
    111   }
    112 
    113   case Decl::Typedef:      // typedef int X;
    114   case Decl::TypeAlias: {  // using X = int; [C++0x]
    115     const TypedefNameDecl &TD = cast<TypedefNameDecl>(D);
    116     QualType Ty = TD.getUnderlyingType();
    117 
    118     if (Ty->isVariablyModifiedType())
    119       EmitVariablyModifiedType(Ty);
    120   }
    121   }
    122 }
    123 
    124 /// EmitVarDecl - This method handles emission of any variable declaration
    125 /// inside a function, including static vars etc.
    126 void CodeGenFunction::EmitVarDecl(const VarDecl &D) {
    127   if (D.isStaticLocal()) {
    128     llvm::GlobalValue::LinkageTypes Linkage =
    129         CGM.getLLVMLinkageVarDefinition(&D, /*isConstant=*/false);
    130 
    131     // FIXME: We need to force the emission/use of a guard variable for
    132     // some variables even if we can constant-evaluate them because
    133     // we can't guarantee every translation unit will constant-evaluate them.
    134 
    135     return EmitStaticVarDecl(D, Linkage);
    136   }
    137 
    138   if (D.hasExternalStorage())
    139     // Don't emit it now, allow it to be emitted lazily on its first use.
    140     return;
    141 
    142   if (D.getStorageClass() == SC_OpenCLWorkGroupLocal)
    143     return CGM.getOpenCLRuntime().EmitWorkGroupLocalVarDecl(*this, D);
    144 
    145   assert(D.hasLocalStorage());
    146   return EmitAutoVarDecl(D);
    147 }
    148 
    149 static std::string GetStaticDeclName(CodeGenFunction &CGF, const VarDecl &D,
    150                                      const char *Separator) {
    151   CodeGenModule &CGM = CGF.CGM;
    152 
    153   if (CGF.getLangOpts().CPlusPlus)
    154     return CGM.getMangledName(&D).str();
    155 
    156   StringRef ContextName;
    157   if (!CGF.CurFuncDecl) {
    158     // Better be in a block declared in global scope.
    159     const NamedDecl *ND = cast<NamedDecl>(&D);
    160     const DeclContext *DC = ND->getDeclContext();
    161     if (const BlockDecl *BD = dyn_cast<BlockDecl>(DC))
    162       ContextName = CGM.getBlockMangledName(GlobalDecl(), BD);
    163     else
    164       llvm_unreachable("Unknown context for block static var decl");
    165   } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(CGF.CurFuncDecl))
    166     ContextName = CGM.getMangledName(FD);
    167   else if (isa<ObjCMethodDecl>(CGF.CurFuncDecl))
    168     ContextName = CGF.CurFn->getName();
    169   else
    170     llvm_unreachable("Unknown context for static var decl");
    171 
    172   return ContextName.str() + Separator + D.getNameAsString();
    173 }
    174 
    175 llvm::Constant *
    176 CodeGenFunction::CreateStaticVarDecl(const VarDecl &D,
    177                                      const char *Separator,
    178                                      llvm::GlobalValue::LinkageTypes Linkage) {
    179   QualType Ty = D.getType();
    180   assert(Ty->isConstantSizeType() && "VLAs can't be static");
    181 
    182   // Use the label if the variable is renamed with the asm-label extension.
    183   std::string Name;
    184   if (D.hasAttr<AsmLabelAttr>())
    185     Name = CGM.getMangledName(&D);
    186   else
    187     Name = GetStaticDeclName(*this, D, Separator);
    188 
    189   llvm::Type *LTy = CGM.getTypes().ConvertTypeForMem(Ty);
    190   unsigned AddrSpace =
    191    CGM.GetGlobalVarAddressSpace(&D, CGM.getContext().getTargetAddressSpace(Ty));
    192   llvm::GlobalVariable *GV =
    193     new llvm::GlobalVariable(CGM.getModule(), LTy,
    194                              Ty.isConstant(getContext()), Linkage,
    195                              CGM.EmitNullConstant(D.getType()), Name, nullptr,
    196                              llvm::GlobalVariable::NotThreadLocal,
    197                              AddrSpace);
    198   GV->setAlignment(getContext().getDeclAlign(&D).getQuantity());
    199   CGM.setGlobalVisibility(GV, &D);
    200 
    201   if (D.getTLSKind())
    202     CGM.setTLSMode(GV, D);
    203 
    204   if (D.isExternallyVisible()) {
    205     if (D.hasAttr<DLLImportAttr>())
    206       GV->setDLLStorageClass(llvm::GlobalVariable::DLLImportStorageClass);
    207     else if (D.hasAttr<DLLExportAttr>())
    208       GV->setDLLStorageClass(llvm::GlobalVariable::DLLExportStorageClass);
    209   }
    210 
    211   // Make sure the result is of the correct type.
    212   unsigned ExpectedAddrSpace = CGM.getContext().getTargetAddressSpace(Ty);
    213   if (AddrSpace != ExpectedAddrSpace) {
    214     llvm::PointerType *PTy = llvm::PointerType::get(LTy, ExpectedAddrSpace);
    215     return llvm::ConstantExpr::getAddrSpaceCast(GV, PTy);
    216   }
    217 
    218   return GV;
    219 }
    220 
    221 /// hasNontrivialDestruction - Determine whether a type's destruction is
    222 /// non-trivial. If so, and the variable uses static initialization, we must
    223 /// register its destructor to run on exit.
    224 static bool hasNontrivialDestruction(QualType T) {
    225   CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
    226   return RD && !RD->hasTrivialDestructor();
    227 }
    228 
    229 /// AddInitializerToStaticVarDecl - Add the initializer for 'D' to the
    230 /// global variable that has already been created for it.  If the initializer
    231 /// has a different type than GV does, this may free GV and return a different
    232 /// one.  Otherwise it just returns GV.
    233 llvm::GlobalVariable *
    234 CodeGenFunction::AddInitializerToStaticVarDecl(const VarDecl &D,
    235                                                llvm::GlobalVariable *GV) {
    236   llvm::Constant *Init = CGM.EmitConstantInit(D, this);
    237 
    238   // If constant emission failed, then this should be a C++ static
    239   // initializer.
    240   if (!Init) {
    241     if (!getLangOpts().CPlusPlus)
    242       CGM.ErrorUnsupported(D.getInit(), "constant l-value expression");
    243     else if (Builder.GetInsertBlock()) {
    244       // Since we have a static initializer, this global variable can't
    245       // be constant.
    246       GV->setConstant(false);
    247 
    248       EmitCXXGuardedInit(D, GV, /*PerformInit*/true);
    249     }
    250     return GV;
    251   }
    252 
    253   // The initializer may differ in type from the global. Rewrite
    254   // the global to match the initializer.  (We have to do this
    255   // because some types, like unions, can't be completely represented
    256   // in the LLVM type system.)
    257   if (GV->getType()->getElementType() != Init->getType()) {
    258     llvm::GlobalVariable *OldGV = GV;
    259 
    260     GV = new llvm::GlobalVariable(CGM.getModule(), Init->getType(),
    261                                   OldGV->isConstant(),
    262                                   OldGV->getLinkage(), Init, "",
    263                                   /*InsertBefore*/ OldGV,
    264                                   OldGV->getThreadLocalMode(),
    265                            CGM.getContext().getTargetAddressSpace(D.getType()));
    266     GV->setVisibility(OldGV->getVisibility());
    267 
    268     // Steal the name of the old global
    269     GV->takeName(OldGV);
    270 
    271     // Replace all uses of the old global with the new global
    272     llvm::Constant *NewPtrForOldDecl =
    273     llvm::ConstantExpr::getBitCast(GV, OldGV->getType());
    274     OldGV->replaceAllUsesWith(NewPtrForOldDecl);
    275 
    276     // Erase the old global, since it is no longer used.
    277     OldGV->eraseFromParent();
    278   }
    279 
    280   GV->setConstant(CGM.isTypeConstant(D.getType(), true));
    281   GV->setInitializer(Init);
    282 
    283   if (hasNontrivialDestruction(D.getType())) {
    284     // We have a constant initializer, but a nontrivial destructor. We still
    285     // need to perform a guarded "initialization" in order to register the
    286     // destructor.
    287     EmitCXXGuardedInit(D, GV, /*PerformInit*/false);
    288   }
    289 
    290   return GV;
    291 }
    292 
    293 void CodeGenFunction::EmitStaticVarDecl(const VarDecl &D,
    294                                       llvm::GlobalValue::LinkageTypes Linkage) {
    295   llvm::Value *&DMEntry = LocalDeclMap[&D];
    296   assert(!DMEntry && "Decl already exists in localdeclmap!");
    297 
    298   // Check to see if we already have a global variable for this
    299   // declaration.  This can happen when double-emitting function
    300   // bodies, e.g. with complete and base constructors.
    301   llvm::Constant *addr =
    302     CGM.getStaticLocalDeclAddress(&D);
    303 
    304   if (!addr)
    305     addr = CreateStaticVarDecl(D, ".", Linkage);
    306 
    307   // Store into LocalDeclMap before generating initializer to handle
    308   // circular references.
    309   DMEntry = addr;
    310   CGM.setStaticLocalDeclAddress(&D, addr);
    311 
    312   // We can't have a VLA here, but we can have a pointer to a VLA,
    313   // even though that doesn't really make any sense.
    314   // Make sure to evaluate VLA bounds now so that we have them for later.
    315   if (D.getType()->isVariablyModifiedType())
    316     EmitVariablyModifiedType(D.getType());
    317 
    318   // Save the type in case adding the initializer forces a type change.
    319   llvm::Type *expectedType = addr->getType();
    320 
    321   llvm::GlobalVariable *var =
    322     cast<llvm::GlobalVariable>(addr->stripPointerCasts());
    323   // If this value has an initializer, emit it.
    324   if (D.getInit())
    325     var = AddInitializerToStaticVarDecl(D, var);
    326 
    327   var->setAlignment(getContext().getDeclAlign(&D).getQuantity());
    328 
    329   if (D.hasAttr<AnnotateAttr>())
    330     CGM.AddGlobalAnnotations(&D, var);
    331 
    332   if (const SectionAttr *SA = D.getAttr<SectionAttr>())
    333     var->setSection(SA->getName());
    334 
    335   if (D.hasAttr<UsedAttr>())
    336     CGM.addUsedGlobal(var);
    337 
    338   // We may have to cast the constant because of the initializer
    339   // mismatch above.
    340   //
    341   // FIXME: It is really dangerous to store this in the map; if anyone
    342   // RAUW's the GV uses of this constant will be invalid.
    343   llvm::Constant *castedAddr =
    344     llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(var, expectedType);
    345   DMEntry = castedAddr;
    346   CGM.setStaticLocalDeclAddress(&D, castedAddr);
    347 
    348   CGM.reportGlobalToASan(var, D.getLocation());
    349 
    350   // Emit global variable debug descriptor for static vars.
    351   CGDebugInfo *DI = getDebugInfo();
    352   if (DI &&
    353       CGM.getCodeGenOpts().getDebugInfo() >= CodeGenOptions::LimitedDebugInfo) {
    354     DI->setLocation(D.getLocation());
    355     DI->EmitGlobalVariable(var, &D);
    356   }
    357 }
    358 
    359 namespace {
    360   struct DestroyObject : EHScopeStack::Cleanup {
    361     DestroyObject(llvm::Value *addr, QualType type,
    362                   CodeGenFunction::Destroyer *destroyer,
    363                   bool useEHCleanupForArray)
    364       : addr(addr), type(type), destroyer(destroyer),
    365         useEHCleanupForArray(useEHCleanupForArray) {}
    366 
    367     llvm::Value *addr;
    368     QualType type;
    369     CodeGenFunction::Destroyer *destroyer;
    370     bool useEHCleanupForArray;
    371 
    372     void Emit(CodeGenFunction &CGF, Flags flags) override {
    373       // Don't use an EH cleanup recursively from an EH cleanup.
    374       bool useEHCleanupForArray =
    375         flags.isForNormalCleanup() && this->useEHCleanupForArray;
    376 
    377       CGF.emitDestroy(addr, type, destroyer, useEHCleanupForArray);
    378     }
    379   };
    380 
    381   struct DestroyNRVOVariable : EHScopeStack::Cleanup {
    382     DestroyNRVOVariable(llvm::Value *addr,
    383                         const CXXDestructorDecl *Dtor,
    384                         llvm::Value *NRVOFlag)
    385       : Dtor(Dtor), NRVOFlag(NRVOFlag), Loc(addr) {}
    386 
    387     const CXXDestructorDecl *Dtor;
    388     llvm::Value *NRVOFlag;
    389     llvm::Value *Loc;
    390 
    391     void Emit(CodeGenFunction &CGF, Flags flags) override {
    392       // Along the exceptions path we always execute the dtor.
    393       bool NRVO = flags.isForNormalCleanup() && NRVOFlag;
    394 
    395       llvm::BasicBlock *SkipDtorBB = nullptr;
    396       if (NRVO) {
    397         // If we exited via NRVO, we skip the destructor call.
    398         llvm::BasicBlock *RunDtorBB = CGF.createBasicBlock("nrvo.unused");
    399         SkipDtorBB = CGF.createBasicBlock("nrvo.skipdtor");
    400         llvm::Value *DidNRVO = CGF.Builder.CreateLoad(NRVOFlag, "nrvo.val");
    401         CGF.Builder.CreateCondBr(DidNRVO, SkipDtorBB, RunDtorBB);
    402         CGF.EmitBlock(RunDtorBB);
    403       }
    404 
    405       CGF.EmitCXXDestructorCall(Dtor, Dtor_Complete,
    406                                 /*ForVirtualBase=*/false,
    407                                 /*Delegating=*/false,
    408                                 Loc);
    409 
    410       if (NRVO) CGF.EmitBlock(SkipDtorBB);
    411     }
    412   };
    413 
    414   struct CallStackRestore : EHScopeStack::Cleanup {
    415     llvm::Value *Stack;
    416     CallStackRestore(llvm::Value *Stack) : Stack(Stack) {}
    417     void Emit(CodeGenFunction &CGF, Flags flags) override {
    418       llvm::Value *V = CGF.Builder.CreateLoad(Stack);
    419       llvm::Value *F = CGF.CGM.getIntrinsic(llvm::Intrinsic::stackrestore);
    420       CGF.Builder.CreateCall(F, V);
    421     }
    422   };
    423 
    424   struct ExtendGCLifetime : EHScopeStack::Cleanup {
    425     const VarDecl &Var;
    426     ExtendGCLifetime(const VarDecl *var) : Var(*var) {}
    427 
    428     void Emit(CodeGenFunction &CGF, Flags flags) override {
    429       // Compute the address of the local variable, in case it's a
    430       // byref or something.
    431       DeclRefExpr DRE(const_cast<VarDecl*>(&Var), false,
    432                       Var.getType(), VK_LValue, SourceLocation());
    433       llvm::Value *value = CGF.EmitLoadOfScalar(CGF.EmitDeclRefLValue(&DRE),
    434                                                 SourceLocation());
    435       CGF.EmitExtendGCLifetime(value);
    436     }
    437   };
    438 
    439   struct CallCleanupFunction : EHScopeStack::Cleanup {
    440     llvm::Constant *CleanupFn;
    441     const CGFunctionInfo &FnInfo;
    442     const VarDecl &Var;
    443 
    444     CallCleanupFunction(llvm::Constant *CleanupFn, const CGFunctionInfo *Info,
    445                         const VarDecl *Var)
    446       : CleanupFn(CleanupFn), FnInfo(*Info), Var(*Var) {}
    447 
    448     void Emit(CodeGenFunction &CGF, Flags flags) override {
    449       DeclRefExpr DRE(const_cast<VarDecl*>(&Var), false,
    450                       Var.getType(), VK_LValue, SourceLocation());
    451       // Compute the address of the local variable, in case it's a byref
    452       // or something.
    453       llvm::Value *Addr = CGF.EmitDeclRefLValue(&DRE).getAddress();
    454 
    455       // In some cases, the type of the function argument will be different from
    456       // the type of the pointer. An example of this is
    457       // void f(void* arg);
    458       // __attribute__((cleanup(f))) void *g;
    459       //
    460       // To fix this we insert a bitcast here.
    461       QualType ArgTy = FnInfo.arg_begin()->type;
    462       llvm::Value *Arg =
    463         CGF.Builder.CreateBitCast(Addr, CGF.ConvertType(ArgTy));
    464 
    465       CallArgList Args;
    466       Args.add(RValue::get(Arg),
    467                CGF.getContext().getPointerType(Var.getType()));
    468       CGF.EmitCall(FnInfo, CleanupFn, ReturnValueSlot(), Args);
    469     }
    470   };
    471 
    472   /// A cleanup to call @llvm.lifetime.end.
    473   class CallLifetimeEnd : public EHScopeStack::Cleanup {
    474     llvm::Value *Addr;
    475     llvm::Value *Size;
    476   public:
    477     CallLifetimeEnd(llvm::Value *addr, llvm::Value *size)
    478       : Addr(addr), Size(size) {}
    479 
    480     void Emit(CodeGenFunction &CGF, Flags flags) override {
    481       llvm::Value *castAddr = CGF.Builder.CreateBitCast(Addr, CGF.Int8PtrTy);
    482       CGF.Builder.CreateCall2(CGF.CGM.getLLVMLifetimeEndFn(),
    483                               Size, castAddr)
    484         ->setDoesNotThrow();
    485     }
    486   };
    487 }
    488 
    489 /// EmitAutoVarWithLifetime - Does the setup required for an automatic
    490 /// variable with lifetime.
    491 static void EmitAutoVarWithLifetime(CodeGenFunction &CGF, const VarDecl &var,
    492                                     llvm::Value *addr,
    493                                     Qualifiers::ObjCLifetime lifetime) {
    494   switch (lifetime) {
    495   case Qualifiers::OCL_None:
    496     llvm_unreachable("present but none");
    497 
    498   case Qualifiers::OCL_ExplicitNone:
    499     // nothing to do
    500     break;
    501 
    502   case Qualifiers::OCL_Strong: {
    503     CodeGenFunction::Destroyer *destroyer =
    504       (var.hasAttr<ObjCPreciseLifetimeAttr>()
    505        ? CodeGenFunction::destroyARCStrongPrecise
    506        : CodeGenFunction::destroyARCStrongImprecise);
    507 
    508     CleanupKind cleanupKind = CGF.getARCCleanupKind();
    509     CGF.pushDestroy(cleanupKind, addr, var.getType(), destroyer,
    510                     cleanupKind & EHCleanup);
    511     break;
    512   }
    513   case Qualifiers::OCL_Autoreleasing:
    514     // nothing to do
    515     break;
    516 
    517   case Qualifiers::OCL_Weak:
    518     // __weak objects always get EH cleanups; otherwise, exceptions
    519     // could cause really nasty crashes instead of mere leaks.
    520     CGF.pushDestroy(NormalAndEHCleanup, addr, var.getType(),
    521                     CodeGenFunction::destroyARCWeak,
    522                     /*useEHCleanup*/ true);
    523     break;
    524   }
    525 }
    526 
    527 static bool isAccessedBy(const VarDecl &var, const Stmt *s) {
    528   if (const Expr *e = dyn_cast<Expr>(s)) {
    529     // Skip the most common kinds of expressions that make
    530     // hierarchy-walking expensive.
    531     s = e = e->IgnoreParenCasts();
    532 
    533     if (const DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e))
    534       return (ref->getDecl() == &var);
    535     if (const BlockExpr *be = dyn_cast<BlockExpr>(e)) {
    536       const BlockDecl *block = be->getBlockDecl();
    537       for (const auto &I : block->captures()) {
    538         if (I.getVariable() == &var)
    539           return true;
    540       }
    541     }
    542   }
    543 
    544   for (Stmt::const_child_range children = s->children(); children; ++children)
    545     // children might be null; as in missing decl or conditional of an if-stmt.
    546     if ((*children) && isAccessedBy(var, *children))
    547       return true;
    548 
    549   return false;
    550 }
    551 
    552 static bool isAccessedBy(const ValueDecl *decl, const Expr *e) {
    553   if (!decl) return false;
    554   if (!isa<VarDecl>(decl)) return false;
    555   const VarDecl *var = cast<VarDecl>(decl);
    556   return isAccessedBy(*var, e);
    557 }
    558 
    559 static void drillIntoBlockVariable(CodeGenFunction &CGF,
    560                                    LValue &lvalue,
    561                                    const VarDecl *var) {
    562   lvalue.setAddress(CGF.BuildBlockByrefAddress(lvalue.getAddress(), var));
    563 }
    564 
    565 void CodeGenFunction::EmitScalarInit(const Expr *init,
    566                                      const ValueDecl *D,
    567                                      LValue lvalue,
    568                                      bool capturedByInit) {
    569   Qualifiers::ObjCLifetime lifetime = lvalue.getObjCLifetime();
    570   if (!lifetime) {
    571     llvm::Value *value = EmitScalarExpr(init);
    572     if (capturedByInit)
    573       drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D));
    574     EmitStoreThroughLValue(RValue::get(value), lvalue, true);
    575     return;
    576   }
    577 
    578   if (const CXXDefaultInitExpr *DIE = dyn_cast<CXXDefaultInitExpr>(init))
    579     init = DIE->getExpr();
    580 
    581   // If we're emitting a value with lifetime, we have to do the
    582   // initialization *before* we leave the cleanup scopes.
    583   if (const ExprWithCleanups *ewc = dyn_cast<ExprWithCleanups>(init)) {
    584     enterFullExpression(ewc);
    585     init = ewc->getSubExpr();
    586   }
    587   CodeGenFunction::RunCleanupsScope Scope(*this);
    588 
    589   // We have to maintain the illusion that the variable is
    590   // zero-initialized.  If the variable might be accessed in its
    591   // initializer, zero-initialize before running the initializer, then
    592   // actually perform the initialization with an assign.
    593   bool accessedByInit = false;
    594   if (lifetime != Qualifiers::OCL_ExplicitNone)
    595     accessedByInit = (capturedByInit || isAccessedBy(D, init));
    596   if (accessedByInit) {
    597     LValue tempLV = lvalue;
    598     // Drill down to the __block object if necessary.
    599     if (capturedByInit) {
    600       // We can use a simple GEP for this because it can't have been
    601       // moved yet.
    602       tempLV.setAddress(Builder.CreateStructGEP(tempLV.getAddress(),
    603                                    getByRefValueLLVMField(cast<VarDecl>(D))));
    604     }
    605 
    606     llvm::PointerType *ty
    607       = cast<llvm::PointerType>(tempLV.getAddress()->getType());
    608     ty = cast<llvm::PointerType>(ty->getElementType());
    609 
    610     llvm::Value *zero = llvm::ConstantPointerNull::get(ty);
    611 
    612     // If __weak, we want to use a barrier under certain conditions.
    613     if (lifetime == Qualifiers::OCL_Weak)
    614       EmitARCInitWeak(tempLV.getAddress(), zero);
    615 
    616     // Otherwise just do a simple store.
    617     else
    618       EmitStoreOfScalar(zero, tempLV, /* isInitialization */ true);
    619   }
    620 
    621   // Emit the initializer.
    622   llvm::Value *value = nullptr;
    623 
    624   switch (lifetime) {
    625   case Qualifiers::OCL_None:
    626     llvm_unreachable("present but none");
    627 
    628   case Qualifiers::OCL_ExplicitNone:
    629     // nothing to do
    630     value = EmitScalarExpr(init);
    631     break;
    632 
    633   case Qualifiers::OCL_Strong: {
    634     value = EmitARCRetainScalarExpr(init);
    635     break;
    636   }
    637 
    638   case Qualifiers::OCL_Weak: {
    639     // No way to optimize a producing initializer into this.  It's not
    640     // worth optimizing for, because the value will immediately
    641     // disappear in the common case.
    642     value = EmitScalarExpr(init);
    643 
    644     if (capturedByInit) drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D));
    645     if (accessedByInit)
    646       EmitARCStoreWeak(lvalue.getAddress(), value, /*ignored*/ true);
    647     else
    648       EmitARCInitWeak(lvalue.getAddress(), value);
    649     return;
    650   }
    651 
    652   case Qualifiers::OCL_Autoreleasing:
    653     value = EmitARCRetainAutoreleaseScalarExpr(init);
    654     break;
    655   }
    656 
    657   if (capturedByInit) drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D));
    658 
    659   // If the variable might have been accessed by its initializer, we
    660   // might have to initialize with a barrier.  We have to do this for
    661   // both __weak and __strong, but __weak got filtered out above.
    662   if (accessedByInit && lifetime == Qualifiers::OCL_Strong) {
    663     llvm::Value *oldValue = EmitLoadOfScalar(lvalue, init->getExprLoc());
    664     EmitStoreOfScalar(value, lvalue, /* isInitialization */ true);
    665     EmitARCRelease(oldValue, ARCImpreciseLifetime);
    666     return;
    667   }
    668 
    669   EmitStoreOfScalar(value, lvalue, /* isInitialization */ true);
    670 }
    671 
    672 /// EmitScalarInit - Initialize the given lvalue with the given object.
    673 void CodeGenFunction::EmitScalarInit(llvm::Value *init, LValue lvalue) {
    674   Qualifiers::ObjCLifetime lifetime = lvalue.getObjCLifetime();
    675   if (!lifetime)
    676     return EmitStoreThroughLValue(RValue::get(init), lvalue, true);
    677 
    678   switch (lifetime) {
    679   case Qualifiers::OCL_None:
    680     llvm_unreachable("present but none");
    681 
    682   case Qualifiers::OCL_ExplicitNone:
    683     // nothing to do
    684     break;
    685 
    686   case Qualifiers::OCL_Strong:
    687     init = EmitARCRetain(lvalue.getType(), init);
    688     break;
    689 
    690   case Qualifiers::OCL_Weak:
    691     // Initialize and then skip the primitive store.
    692     EmitARCInitWeak(lvalue.getAddress(), init);
    693     return;
    694 
    695   case Qualifiers::OCL_Autoreleasing:
    696     init = EmitARCRetainAutorelease(lvalue.getType(), init);
    697     break;
    698   }
    699 
    700   EmitStoreOfScalar(init, lvalue, /* isInitialization */ true);
    701 }
    702 
    703 /// canEmitInitWithFewStoresAfterMemset - Decide whether we can emit the
    704 /// non-zero parts of the specified initializer with equal or fewer than
    705 /// NumStores scalar stores.
    706 static bool canEmitInitWithFewStoresAfterMemset(llvm::Constant *Init,
    707                                                 unsigned &NumStores) {
    708   // Zero and Undef never requires any extra stores.
    709   if (isa<llvm::ConstantAggregateZero>(Init) ||
    710       isa<llvm::ConstantPointerNull>(Init) ||
    711       isa<llvm::UndefValue>(Init))
    712     return true;
    713   if (isa<llvm::ConstantInt>(Init) || isa<llvm::ConstantFP>(Init) ||
    714       isa<llvm::ConstantVector>(Init) || isa<llvm::BlockAddress>(Init) ||
    715       isa<llvm::ConstantExpr>(Init))
    716     return Init->isNullValue() || NumStores--;
    717 
    718   // See if we can emit each element.
    719   if (isa<llvm::ConstantArray>(Init) || isa<llvm::ConstantStruct>(Init)) {
    720     for (unsigned i = 0, e = Init->getNumOperands(); i != e; ++i) {
    721       llvm::Constant *Elt = cast<llvm::Constant>(Init->getOperand(i));
    722       if (!canEmitInitWithFewStoresAfterMemset(Elt, NumStores))
    723         return false;
    724     }
    725     return true;
    726   }
    727 
    728   if (llvm::ConstantDataSequential *CDS =
    729         dyn_cast<llvm::ConstantDataSequential>(Init)) {
    730     for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
    731       llvm::Constant *Elt = CDS->getElementAsConstant(i);
    732       if (!canEmitInitWithFewStoresAfterMemset(Elt, NumStores))
    733         return false;
    734     }
    735     return true;
    736   }
    737 
    738   // Anything else is hard and scary.
    739   return false;
    740 }
    741 
    742 /// emitStoresForInitAfterMemset - For inits that
    743 /// canEmitInitWithFewStoresAfterMemset returned true for, emit the scalar
    744 /// stores that would be required.
    745 static void emitStoresForInitAfterMemset(llvm::Constant *Init, llvm::Value *Loc,
    746                                          bool isVolatile, CGBuilderTy &Builder) {
    747   assert(!Init->isNullValue() && !isa<llvm::UndefValue>(Init) &&
    748          "called emitStoresForInitAfterMemset for zero or undef value.");
    749 
    750   if (isa<llvm::ConstantInt>(Init) || isa<llvm::ConstantFP>(Init) ||
    751       isa<llvm::ConstantVector>(Init) || isa<llvm::BlockAddress>(Init) ||
    752       isa<llvm::ConstantExpr>(Init)) {
    753     Builder.CreateStore(Init, Loc, isVolatile);
    754     return;
    755   }
    756 
    757   if (llvm::ConstantDataSequential *CDS =
    758         dyn_cast<llvm::ConstantDataSequential>(Init)) {
    759     for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
    760       llvm::Constant *Elt = CDS->getElementAsConstant(i);
    761 
    762       // If necessary, get a pointer to the element and emit it.
    763       if (!Elt->isNullValue() && !isa<llvm::UndefValue>(Elt))
    764         emitStoresForInitAfterMemset(Elt, Builder.CreateConstGEP2_32(Loc, 0, i),
    765                                      isVolatile, Builder);
    766     }
    767     return;
    768   }
    769 
    770   assert((isa<llvm::ConstantStruct>(Init) || isa<llvm::ConstantArray>(Init)) &&
    771          "Unknown value type!");
    772 
    773   for (unsigned i = 0, e = Init->getNumOperands(); i != e; ++i) {
    774     llvm::Constant *Elt = cast<llvm::Constant>(Init->getOperand(i));
    775 
    776     // If necessary, get a pointer to the element and emit it.
    777     if (!Elt->isNullValue() && !isa<llvm::UndefValue>(Elt))
    778       emitStoresForInitAfterMemset(Elt, Builder.CreateConstGEP2_32(Loc, 0, i),
    779                                    isVolatile, Builder);
    780   }
    781 }
    782 
    783 
    784 /// shouldUseMemSetPlusStoresToInitialize - Decide whether we should use memset
    785 /// plus some stores to initialize a local variable instead of using a memcpy
    786 /// from a constant global.  It is beneficial to use memset if the global is all
    787 /// zeros, or mostly zeros and large.
    788 static bool shouldUseMemSetPlusStoresToInitialize(llvm::Constant *Init,
    789                                                   uint64_t GlobalSize) {
    790   // If a global is all zeros, always use a memset.
    791   if (isa<llvm::ConstantAggregateZero>(Init)) return true;
    792 
    793   // If a non-zero global is <= 32 bytes, always use a memcpy.  If it is large,
    794   // do it if it will require 6 or fewer scalar stores.
    795   // TODO: Should budget depends on the size?  Avoiding a large global warrants
    796   // plopping in more stores.
    797   unsigned StoreBudget = 6;
    798   uint64_t SizeLimit = 32;
    799 
    800   return GlobalSize > SizeLimit &&
    801          canEmitInitWithFewStoresAfterMemset(Init, StoreBudget);
    802 }
    803 
    804 /// Should we use the LLVM lifetime intrinsics for the given local variable?
    805 static bool shouldUseLifetimeMarkers(CodeGenFunction &CGF, const VarDecl &D,
    806                                      unsigned Size) {
    807   // For now, only in optimized builds.
    808   if (CGF.CGM.getCodeGenOpts().OptimizationLevel == 0)
    809     return false;
    810 
    811   // Limit the size of marked objects to 32 bytes. We don't want to increase
    812   // compile time by marking tiny objects.
    813   unsigned SizeThreshold = 32;
    814 
    815   return Size > SizeThreshold;
    816 }
    817 
    818 
    819 /// EmitAutoVarDecl - Emit code and set up an entry in LocalDeclMap for a
    820 /// variable declaration with auto, register, or no storage class specifier.
    821 /// These turn into simple stack objects, or GlobalValues depending on target.
    822 void CodeGenFunction::EmitAutoVarDecl(const VarDecl &D) {
    823   AutoVarEmission emission = EmitAutoVarAlloca(D);
    824   EmitAutoVarInit(emission);
    825   EmitAutoVarCleanups(emission);
    826 }
    827 
    828 /// EmitAutoVarAlloca - Emit the alloca and debug information for a
    829 /// local variable.  Does not emit initialization or destruction.
    830 CodeGenFunction::AutoVarEmission
    831 CodeGenFunction::EmitAutoVarAlloca(const VarDecl &D) {
    832   QualType Ty = D.getType();
    833 
    834   AutoVarEmission emission(D);
    835 
    836   bool isByRef = D.hasAttr<BlocksAttr>();
    837   emission.IsByRef = isByRef;
    838 
    839   CharUnits alignment = getContext().getDeclAlign(&D);
    840   emission.Alignment = alignment;
    841 
    842   // If the type is variably-modified, emit all the VLA sizes for it.
    843   if (Ty->isVariablyModifiedType())
    844     EmitVariablyModifiedType(Ty);
    845 
    846   llvm::Value *DeclPtr;
    847   if (Ty->isConstantSizeType()) {
    848     bool NRVO = getLangOpts().ElideConstructors &&
    849       D.isNRVOVariable();
    850 
    851     // If this value is an array or struct with a statically determinable
    852     // constant initializer, there are optimizations we can do.
    853     //
    854     // TODO: We should constant-evaluate the initializer of any variable,
    855     // as long as it is initialized by a constant expression. Currently,
    856     // isConstantInitializer produces wrong answers for structs with
    857     // reference or bitfield members, and a few other cases, and checking
    858     // for POD-ness protects us from some of these.
    859     if (D.getInit() && (Ty->isArrayType() || Ty->isRecordType()) &&
    860         (D.isConstexpr() ||
    861          ((Ty.isPODType(getContext()) ||
    862            getContext().getBaseElementType(Ty)->isObjCObjectPointerType()) &&
    863           D.getInit()->isConstantInitializer(getContext(), false)))) {
    864 
    865       // If the variable's a const type, and it's neither an NRVO
    866       // candidate nor a __block variable and has no mutable members,
    867       // emit it as a global instead.
    868       if (CGM.getCodeGenOpts().MergeAllConstants && !NRVO && !isByRef &&
    869           CGM.isTypeConstant(Ty, true)) {
    870         EmitStaticVarDecl(D, llvm::GlobalValue::InternalLinkage);
    871 
    872         emission.Address = nullptr; // signal this condition to later callbacks
    873         assert(emission.wasEmittedAsGlobal());
    874         return emission;
    875       }
    876 
    877       // Otherwise, tell the initialization code that we're in this case.
    878       emission.IsConstantAggregate = true;
    879     }
    880 
    881     // A normal fixed sized variable becomes an alloca in the entry block,
    882     // unless it's an NRVO variable.
    883     llvm::Type *LTy = ConvertTypeForMem(Ty);
    884 
    885     if (NRVO) {
    886       // The named return value optimization: allocate this variable in the
    887       // return slot, so that we can elide the copy when returning this
    888       // variable (C++0x [class.copy]p34).
    889       DeclPtr = ReturnValue;
    890 
    891       if (const RecordType *RecordTy = Ty->getAs<RecordType>()) {
    892         if (!cast<CXXRecordDecl>(RecordTy->getDecl())->hasTrivialDestructor()) {
    893           // Create a flag that is used to indicate when the NRVO was applied
    894           // to this variable. Set it to zero to indicate that NRVO was not
    895           // applied.
    896           llvm::Value *Zero = Builder.getFalse();
    897           llvm::Value *NRVOFlag = CreateTempAlloca(Zero->getType(), "nrvo");
    898           EnsureInsertPoint();
    899           Builder.CreateStore(Zero, NRVOFlag);
    900 
    901           // Record the NRVO flag for this variable.
    902           NRVOFlags[&D] = NRVOFlag;
    903           emission.NRVOFlag = NRVOFlag;
    904         }
    905       }
    906     } else {
    907       if (isByRef)
    908         LTy = BuildByRefType(&D);
    909 
    910       llvm::AllocaInst *Alloc = CreateTempAlloca(LTy);
    911       Alloc->setName(D.getName());
    912 
    913       CharUnits allocaAlignment = alignment;
    914       if (isByRef)
    915         allocaAlignment = std::max(allocaAlignment,
    916             getContext().toCharUnitsFromBits(getTarget().getPointerAlign(0)));
    917       Alloc->setAlignment(allocaAlignment.getQuantity());
    918       DeclPtr = Alloc;
    919 
    920       // Emit a lifetime intrinsic if meaningful.  There's no point
    921       // in doing this if we don't have a valid insertion point (?).
    922       uint64_t size = CGM.getDataLayout().getTypeAllocSize(LTy);
    923       if (HaveInsertPoint() && shouldUseLifetimeMarkers(*this, D, size)) {
    924         llvm::Value *sizeV = llvm::ConstantInt::get(Int64Ty, size);
    925 
    926         emission.SizeForLifetimeMarkers = sizeV;
    927         llvm::Value *castAddr = Builder.CreateBitCast(Alloc, Int8PtrTy);
    928         Builder.CreateCall2(CGM.getLLVMLifetimeStartFn(), sizeV, castAddr)
    929           ->setDoesNotThrow();
    930       } else {
    931         assert(!emission.useLifetimeMarkers());
    932       }
    933     }
    934   } else {
    935     EnsureInsertPoint();
    936 
    937     if (!DidCallStackSave) {
    938       // Save the stack.
    939       llvm::Value *Stack = CreateTempAlloca(Int8PtrTy, "saved_stack");
    940 
    941       llvm::Value *F = CGM.getIntrinsic(llvm::Intrinsic::stacksave);
    942       llvm::Value *V = Builder.CreateCall(F);
    943 
    944       Builder.CreateStore(V, Stack);
    945 
    946       DidCallStackSave = true;
    947 
    948       // Push a cleanup block and restore the stack there.
    949       // FIXME: in general circumstances, this should be an EH cleanup.
    950       pushStackRestore(NormalCleanup, Stack);
    951     }
    952 
    953     llvm::Value *elementCount;
    954     QualType elementType;
    955     std::tie(elementCount, elementType) = getVLASize(Ty);
    956 
    957     llvm::Type *llvmTy = ConvertTypeForMem(elementType);
    958 
    959     // Allocate memory for the array.
    960     llvm::AllocaInst *vla = Builder.CreateAlloca(llvmTy, elementCount, "vla");
    961     vla->setAlignment(alignment.getQuantity());
    962 
    963     DeclPtr = vla;
    964   }
    965 
    966   llvm::Value *&DMEntry = LocalDeclMap[&D];
    967   assert(!DMEntry && "Decl already exists in localdeclmap!");
    968   DMEntry = DeclPtr;
    969   emission.Address = DeclPtr;
    970 
    971   // Emit debug info for local var declaration.
    972   if (HaveInsertPoint())
    973     if (CGDebugInfo *DI = getDebugInfo()) {
    974       if (CGM.getCodeGenOpts().getDebugInfo()
    975             >= CodeGenOptions::LimitedDebugInfo) {
    976         DI->setLocation(D.getLocation());
    977         DI->EmitDeclareOfAutoVariable(&D, DeclPtr, Builder);
    978       }
    979     }
    980 
    981   if (D.hasAttr<AnnotateAttr>())
    982       EmitVarAnnotations(&D, emission.Address);
    983 
    984   return emission;
    985 }
    986 
    987 /// Determines whether the given __block variable is potentially
    988 /// captured by the given expression.
    989 static bool isCapturedBy(const VarDecl &var, const Expr *e) {
    990   // Skip the most common kinds of expressions that make
    991   // hierarchy-walking expensive.
    992   e = e->IgnoreParenCasts();
    993 
    994   if (const BlockExpr *be = dyn_cast<BlockExpr>(e)) {
    995     const BlockDecl *block = be->getBlockDecl();
    996     for (const auto &I : block->captures()) {
    997       if (I.getVariable() == &var)
    998         return true;
    999     }
   1000 
   1001     // No need to walk into the subexpressions.
   1002     return false;
   1003   }
   1004 
   1005   if (const StmtExpr *SE = dyn_cast<StmtExpr>(e)) {
   1006     const CompoundStmt *CS = SE->getSubStmt();
   1007     for (const auto *BI : CS->body())
   1008       if (const auto *E = dyn_cast<Expr>(BI)) {
   1009         if (isCapturedBy(var, E))
   1010             return true;
   1011       }
   1012       else if (const auto *DS = dyn_cast<DeclStmt>(BI)) {
   1013           // special case declarations
   1014           for (const auto *I : DS->decls()) {
   1015               if (const auto *VD = dyn_cast<VarDecl>((I))) {
   1016                 const Expr *Init = VD->getInit();
   1017                 if (Init && isCapturedBy(var, Init))
   1018                   return true;
   1019               }
   1020           }
   1021       }
   1022       else
   1023         // FIXME. Make safe assumption assuming arbitrary statements cause capturing.
   1024         // Later, provide code to poke into statements for capture analysis.
   1025         return true;
   1026     return false;
   1027   }
   1028 
   1029   for (Stmt::const_child_range children = e->children(); children; ++children)
   1030     if (isCapturedBy(var, cast<Expr>(*children)))
   1031       return true;
   1032 
   1033   return false;
   1034 }
   1035 
   1036 /// \brief Determine whether the given initializer is trivial in the sense
   1037 /// that it requires no code to be generated.
   1038 static bool isTrivialInitializer(const Expr *Init) {
   1039   if (!Init)
   1040     return true;
   1041 
   1042   if (const CXXConstructExpr *Construct = dyn_cast<CXXConstructExpr>(Init))
   1043     if (CXXConstructorDecl *Constructor = Construct->getConstructor())
   1044       if (Constructor->isTrivial() &&
   1045           Constructor->isDefaultConstructor() &&
   1046           !Construct->requiresZeroInitialization())
   1047         return true;
   1048 
   1049   return false;
   1050 }
   1051 void CodeGenFunction::EmitAutoVarInit(const AutoVarEmission &emission) {
   1052   assert(emission.Variable && "emission was not valid!");
   1053 
   1054   // If this was emitted as a global constant, we're done.
   1055   if (emission.wasEmittedAsGlobal()) return;
   1056 
   1057   const VarDecl &D = *emission.Variable;
   1058   QualType type = D.getType();
   1059 
   1060   // If this local has an initializer, emit it now.
   1061   const Expr *Init = D.getInit();
   1062 
   1063   // If we are at an unreachable point, we don't need to emit the initializer
   1064   // unless it contains a label.
   1065   if (!HaveInsertPoint()) {
   1066     if (!Init || !ContainsLabel(Init)) return;
   1067     EnsureInsertPoint();
   1068   }
   1069 
   1070   // Initialize the structure of a __block variable.
   1071   if (emission.IsByRef)
   1072     emitByrefStructureInit(emission);
   1073 
   1074   if (isTrivialInitializer(Init))
   1075     return;
   1076 
   1077   CharUnits alignment = emission.Alignment;
   1078 
   1079   // Check whether this is a byref variable that's potentially
   1080   // captured and moved by its own initializer.  If so, we'll need to
   1081   // emit the initializer first, then copy into the variable.
   1082   bool capturedByInit = emission.IsByRef && isCapturedBy(D, Init);
   1083 
   1084   llvm::Value *Loc =
   1085     capturedByInit ? emission.Address : emission.getObjectAddress(*this);
   1086 
   1087   llvm::Constant *constant = nullptr;
   1088   if (emission.IsConstantAggregate || D.isConstexpr()) {
   1089     assert(!capturedByInit && "constant init contains a capturing block?");
   1090     constant = CGM.EmitConstantInit(D, this);
   1091   }
   1092 
   1093   if (!constant) {
   1094     LValue lv = MakeAddrLValue(Loc, type, alignment);
   1095     lv.setNonGC(true);
   1096     return EmitExprAsInit(Init, &D, lv, capturedByInit);
   1097   }
   1098 
   1099   if (!emission.IsConstantAggregate) {
   1100     // For simple scalar/complex initialization, store the value directly.
   1101     LValue lv = MakeAddrLValue(Loc, type, alignment);
   1102     lv.setNonGC(true);
   1103     return EmitStoreThroughLValue(RValue::get(constant), lv, true);
   1104   }
   1105 
   1106   // If this is a simple aggregate initialization, we can optimize it
   1107   // in various ways.
   1108   bool isVolatile = type.isVolatileQualified();
   1109 
   1110   llvm::Value *SizeVal =
   1111     llvm::ConstantInt::get(IntPtrTy,
   1112                            getContext().getTypeSizeInChars(type).getQuantity());
   1113 
   1114   llvm::Type *BP = Int8PtrTy;
   1115   if (Loc->getType() != BP)
   1116     Loc = Builder.CreateBitCast(Loc, BP);
   1117 
   1118   // If the initializer is all or mostly zeros, codegen with memset then do
   1119   // a few stores afterward.
   1120   if (shouldUseMemSetPlusStoresToInitialize(constant,
   1121                 CGM.getDataLayout().getTypeAllocSize(constant->getType()))) {
   1122     Builder.CreateMemSet(Loc, llvm::ConstantInt::get(Int8Ty, 0), SizeVal,
   1123                          alignment.getQuantity(), isVolatile);
   1124     // Zero and undef don't require a stores.
   1125     if (!constant->isNullValue() && !isa<llvm::UndefValue>(constant)) {
   1126       Loc = Builder.CreateBitCast(Loc, constant->getType()->getPointerTo());
   1127       emitStoresForInitAfterMemset(constant, Loc, isVolatile, Builder);
   1128     }
   1129   } else {
   1130     // Otherwise, create a temporary global with the initializer then
   1131     // memcpy from the global to the alloca.
   1132     std::string Name = GetStaticDeclName(*this, D, ".");
   1133     llvm::GlobalVariable *GV =
   1134       new llvm::GlobalVariable(CGM.getModule(), constant->getType(), true,
   1135                                llvm::GlobalValue::PrivateLinkage,
   1136                                constant, Name);
   1137     GV->setAlignment(alignment.getQuantity());
   1138     GV->setUnnamedAddr(true);
   1139 
   1140     llvm::Value *SrcPtr = GV;
   1141     if (SrcPtr->getType() != BP)
   1142       SrcPtr = Builder.CreateBitCast(SrcPtr, BP);
   1143 
   1144     Builder.CreateMemCpy(Loc, SrcPtr, SizeVal, alignment.getQuantity(),
   1145                          isVolatile);
   1146   }
   1147 }
   1148 
   1149 /// Emit an expression as an initializer for a variable at the given
   1150 /// location.  The expression is not necessarily the normal
   1151 /// initializer for the variable, and the address is not necessarily
   1152 /// its normal location.
   1153 ///
   1154 /// \param init the initializing expression
   1155 /// \param var the variable to act as if we're initializing
   1156 /// \param loc the address to initialize; its type is a pointer
   1157 ///   to the LLVM mapping of the variable's type
   1158 /// \param alignment the alignment of the address
   1159 /// \param capturedByInit true if the variable is a __block variable
   1160 ///   whose address is potentially changed by the initializer
   1161 void CodeGenFunction::EmitExprAsInit(const Expr *init,
   1162                                      const ValueDecl *D,
   1163                                      LValue lvalue,
   1164                                      bool capturedByInit) {
   1165   QualType type = D->getType();
   1166 
   1167   if (type->isReferenceType()) {
   1168     RValue rvalue = EmitReferenceBindingToExpr(init);
   1169     if (capturedByInit)
   1170       drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D));
   1171     EmitStoreThroughLValue(rvalue, lvalue, true);
   1172     return;
   1173   }
   1174   switch (getEvaluationKind(type)) {
   1175   case TEK_Scalar:
   1176     EmitScalarInit(init, D, lvalue, capturedByInit);
   1177     return;
   1178   case TEK_Complex: {
   1179     ComplexPairTy complex = EmitComplexExpr(init);
   1180     if (capturedByInit)
   1181       drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D));
   1182     EmitStoreOfComplex(complex, lvalue, /*init*/ true);
   1183     return;
   1184   }
   1185   case TEK_Aggregate:
   1186     if (type->isAtomicType()) {
   1187       EmitAtomicInit(const_cast<Expr*>(init), lvalue);
   1188     } else {
   1189       // TODO: how can we delay here if D is captured by its initializer?
   1190       EmitAggExpr(init, AggValueSlot::forLValue(lvalue,
   1191                                               AggValueSlot::IsDestructed,
   1192                                          AggValueSlot::DoesNotNeedGCBarriers,
   1193                                               AggValueSlot::IsNotAliased));
   1194     }
   1195     return;
   1196   }
   1197   llvm_unreachable("bad evaluation kind");
   1198 }
   1199 
   1200 /// Enter a destroy cleanup for the given local variable.
   1201 void CodeGenFunction::emitAutoVarTypeCleanup(
   1202                             const CodeGenFunction::AutoVarEmission &emission,
   1203                             QualType::DestructionKind dtorKind) {
   1204   assert(dtorKind != QualType::DK_none);
   1205 
   1206   // Note that for __block variables, we want to destroy the
   1207   // original stack object, not the possibly forwarded object.
   1208   llvm::Value *addr = emission.getObjectAddress(*this);
   1209 
   1210   const VarDecl *var = emission.Variable;
   1211   QualType type = var->getType();
   1212 
   1213   CleanupKind cleanupKind = NormalAndEHCleanup;
   1214   CodeGenFunction::Destroyer *destroyer = nullptr;
   1215 
   1216   switch (dtorKind) {
   1217   case QualType::DK_none:
   1218     llvm_unreachable("no cleanup for trivially-destructible variable");
   1219 
   1220   case QualType::DK_cxx_destructor:
   1221     // If there's an NRVO flag on the emission, we need a different
   1222     // cleanup.
   1223     if (emission.NRVOFlag) {
   1224       assert(!type->isArrayType());
   1225       CXXDestructorDecl *dtor = type->getAsCXXRecordDecl()->getDestructor();
   1226       EHStack.pushCleanup<DestroyNRVOVariable>(cleanupKind, addr, dtor,
   1227                                                emission.NRVOFlag);
   1228       return;
   1229     }
   1230     break;
   1231 
   1232   case QualType::DK_objc_strong_lifetime:
   1233     // Suppress cleanups for pseudo-strong variables.
   1234     if (var->isARCPseudoStrong()) return;
   1235 
   1236     // Otherwise, consider whether to use an EH cleanup or not.
   1237     cleanupKind = getARCCleanupKind();
   1238 
   1239     // Use the imprecise destroyer by default.
   1240     if (!var->hasAttr<ObjCPreciseLifetimeAttr>())
   1241       destroyer = CodeGenFunction::destroyARCStrongImprecise;
   1242     break;
   1243 
   1244   case QualType::DK_objc_weak_lifetime:
   1245     break;
   1246   }
   1247 
   1248   // If we haven't chosen a more specific destroyer, use the default.
   1249   if (!destroyer) destroyer = getDestroyer(dtorKind);
   1250 
   1251   // Use an EH cleanup in array destructors iff the destructor itself
   1252   // is being pushed as an EH cleanup.
   1253   bool useEHCleanup = (cleanupKind & EHCleanup);
   1254   EHStack.pushCleanup<DestroyObject>(cleanupKind, addr, type, destroyer,
   1255                                      useEHCleanup);
   1256 }
   1257 
   1258 void CodeGenFunction::EmitAutoVarCleanups(const AutoVarEmission &emission) {
   1259   assert(emission.Variable && "emission was not valid!");
   1260 
   1261   // If this was emitted as a global constant, we're done.
   1262   if (emission.wasEmittedAsGlobal()) return;
   1263 
   1264   // If we don't have an insertion point, we're done.  Sema prevents
   1265   // us from jumping into any of these scopes anyway.
   1266   if (!HaveInsertPoint()) return;
   1267 
   1268   const VarDecl &D = *emission.Variable;
   1269 
   1270   // Make sure we call @llvm.lifetime.end.  This needs to happen
   1271   // *last*, so the cleanup needs to be pushed *first*.
   1272   if (emission.useLifetimeMarkers()) {
   1273     EHStack.pushCleanup<CallLifetimeEnd>(NormalCleanup,
   1274                                          emission.getAllocatedAddress(),
   1275                                          emission.getSizeForLifetimeMarkers());
   1276   }
   1277 
   1278   // Check the type for a cleanup.
   1279   if (QualType::DestructionKind dtorKind = D.getType().isDestructedType())
   1280     emitAutoVarTypeCleanup(emission, dtorKind);
   1281 
   1282   // In GC mode, honor objc_precise_lifetime.
   1283   if (getLangOpts().getGC() != LangOptions::NonGC &&
   1284       D.hasAttr<ObjCPreciseLifetimeAttr>()) {
   1285     EHStack.pushCleanup<ExtendGCLifetime>(NormalCleanup, &D);
   1286   }
   1287 
   1288   // Handle the cleanup attribute.
   1289   if (const CleanupAttr *CA = D.getAttr<CleanupAttr>()) {
   1290     const FunctionDecl *FD = CA->getFunctionDecl();
   1291 
   1292     llvm::Constant *F = CGM.GetAddrOfFunction(FD);
   1293     assert(F && "Could not find function!");
   1294 
   1295     const CGFunctionInfo &Info = CGM.getTypes().arrangeFunctionDeclaration(FD);
   1296     EHStack.pushCleanup<CallCleanupFunction>(NormalAndEHCleanup, F, &Info, &D);
   1297   }
   1298 
   1299   // If this is a block variable, call _Block_object_destroy
   1300   // (on the unforwarded address).
   1301   if (emission.IsByRef)
   1302     enterByrefCleanup(emission);
   1303 }
   1304 
   1305 CodeGenFunction::Destroyer *
   1306 CodeGenFunction::getDestroyer(QualType::DestructionKind kind) {
   1307   switch (kind) {
   1308   case QualType::DK_none: llvm_unreachable("no destroyer for trivial dtor");
   1309   case QualType::DK_cxx_destructor:
   1310     return destroyCXXObject;
   1311   case QualType::DK_objc_strong_lifetime:
   1312     return destroyARCStrongPrecise;
   1313   case QualType::DK_objc_weak_lifetime:
   1314     return destroyARCWeak;
   1315   }
   1316   llvm_unreachable("Unknown DestructionKind");
   1317 }
   1318 
   1319 /// pushEHDestroy - Push the standard destructor for the given type as
   1320 /// an EH-only cleanup.
   1321 void CodeGenFunction::pushEHDestroy(QualType::DestructionKind dtorKind,
   1322                                   llvm::Value *addr, QualType type) {
   1323   assert(dtorKind && "cannot push destructor for trivial type");
   1324   assert(needsEHCleanup(dtorKind));
   1325 
   1326   pushDestroy(EHCleanup, addr, type, getDestroyer(dtorKind), true);
   1327 }
   1328 
   1329 /// pushDestroy - Push the standard destructor for the given type as
   1330 /// at least a normal cleanup.
   1331 void CodeGenFunction::pushDestroy(QualType::DestructionKind dtorKind,
   1332                                   llvm::Value *addr, QualType type) {
   1333   assert(dtorKind && "cannot push destructor for trivial type");
   1334 
   1335   CleanupKind cleanupKind = getCleanupKind(dtorKind);
   1336   pushDestroy(cleanupKind, addr, type, getDestroyer(dtorKind),
   1337               cleanupKind & EHCleanup);
   1338 }
   1339 
   1340 void CodeGenFunction::pushDestroy(CleanupKind cleanupKind, llvm::Value *addr,
   1341                                   QualType type, Destroyer *destroyer,
   1342                                   bool useEHCleanupForArray) {
   1343   pushFullExprCleanup<DestroyObject>(cleanupKind, addr, type,
   1344                                      destroyer, useEHCleanupForArray);
   1345 }
   1346 
   1347 void CodeGenFunction::pushStackRestore(CleanupKind Kind, llvm::Value *SPMem) {
   1348   EHStack.pushCleanup<CallStackRestore>(Kind, SPMem);
   1349 }
   1350 
   1351 void CodeGenFunction::pushLifetimeExtendedDestroy(
   1352     CleanupKind cleanupKind, llvm::Value *addr, QualType type,
   1353     Destroyer *destroyer, bool useEHCleanupForArray) {
   1354   assert(!isInConditionalBranch() &&
   1355          "performing lifetime extension from within conditional");
   1356 
   1357   // Push an EH-only cleanup for the object now.
   1358   // FIXME: When popping normal cleanups, we need to keep this EH cleanup
   1359   // around in case a temporary's destructor throws an exception.
   1360   if (cleanupKind & EHCleanup)
   1361     EHStack.pushCleanup<DestroyObject>(
   1362         static_cast<CleanupKind>(cleanupKind & ~NormalCleanup), addr, type,
   1363         destroyer, useEHCleanupForArray);
   1364 
   1365   // Remember that we need to push a full cleanup for the object at the
   1366   // end of the full-expression.
   1367   pushCleanupAfterFullExpr<DestroyObject>(
   1368       cleanupKind, addr, type, destroyer, useEHCleanupForArray);
   1369 }
   1370 
   1371 /// emitDestroy - Immediately perform the destruction of the given
   1372 /// object.
   1373 ///
   1374 /// \param addr - the address of the object; a type*
   1375 /// \param type - the type of the object; if an array type, all
   1376 ///   objects are destroyed in reverse order
   1377 /// \param destroyer - the function to call to destroy individual
   1378 ///   elements
   1379 /// \param useEHCleanupForArray - whether an EH cleanup should be
   1380 ///   used when destroying array elements, in case one of the
   1381 ///   destructions throws an exception
   1382 void CodeGenFunction::emitDestroy(llvm::Value *addr, QualType type,
   1383                                   Destroyer *destroyer,
   1384                                   bool useEHCleanupForArray) {
   1385   const ArrayType *arrayType = getContext().getAsArrayType(type);
   1386   if (!arrayType)
   1387     return destroyer(*this, addr, type);
   1388 
   1389   llvm::Value *begin = addr;
   1390   llvm::Value *length = emitArrayLength(arrayType, type, begin);
   1391 
   1392   // Normally we have to check whether the array is zero-length.
   1393   bool checkZeroLength = true;
   1394 
   1395   // But if the array length is constant, we can suppress that.
   1396   if (llvm::ConstantInt *constLength = dyn_cast<llvm::ConstantInt>(length)) {
   1397     // ...and if it's constant zero, we can just skip the entire thing.
   1398     if (constLength->isZero()) return;
   1399     checkZeroLength = false;
   1400   }
   1401 
   1402   llvm::Value *end = Builder.CreateInBoundsGEP(begin, length);
   1403   emitArrayDestroy(begin, end, type, destroyer,
   1404                    checkZeroLength, useEHCleanupForArray);
   1405 }
   1406 
   1407 /// emitArrayDestroy - Destroys all the elements of the given array,
   1408 /// beginning from last to first.  The array cannot be zero-length.
   1409 ///
   1410 /// \param begin - a type* denoting the first element of the array
   1411 /// \param end - a type* denoting one past the end of the array
   1412 /// \param type - the element type of the array
   1413 /// \param destroyer - the function to call to destroy elements
   1414 /// \param useEHCleanup - whether to push an EH cleanup to destroy
   1415 ///   the remaining elements in case the destruction of a single
   1416 ///   element throws
   1417 void CodeGenFunction::emitArrayDestroy(llvm::Value *begin,
   1418                                        llvm::Value *end,
   1419                                        QualType type,
   1420                                        Destroyer *destroyer,
   1421                                        bool checkZeroLength,
   1422                                        bool useEHCleanup) {
   1423   assert(!type->isArrayType());
   1424 
   1425   // The basic structure here is a do-while loop, because we don't
   1426   // need to check for the zero-element case.
   1427   llvm::BasicBlock *bodyBB = createBasicBlock("arraydestroy.body");
   1428   llvm::BasicBlock *doneBB = createBasicBlock("arraydestroy.done");
   1429 
   1430   if (checkZeroLength) {
   1431     llvm::Value *isEmpty = Builder.CreateICmpEQ(begin, end,
   1432                                                 "arraydestroy.isempty");
   1433     Builder.CreateCondBr(isEmpty, doneBB, bodyBB);
   1434   }
   1435 
   1436   // Enter the loop body, making that address the current address.
   1437   llvm::BasicBlock *entryBB = Builder.GetInsertBlock();
   1438   EmitBlock(bodyBB);
   1439   llvm::PHINode *elementPast =
   1440     Builder.CreatePHI(begin->getType(), 2, "arraydestroy.elementPast");
   1441   elementPast->addIncoming(end, entryBB);
   1442 
   1443   // Shift the address back by one element.
   1444   llvm::Value *negativeOne = llvm::ConstantInt::get(SizeTy, -1, true);
   1445   llvm::Value *element = Builder.CreateInBoundsGEP(elementPast, negativeOne,
   1446                                                    "arraydestroy.element");
   1447 
   1448   if (useEHCleanup)
   1449     pushRegularPartialArrayCleanup(begin, element, type, destroyer);
   1450 
   1451   // Perform the actual destruction there.
   1452   destroyer(*this, element, type);
   1453 
   1454   if (useEHCleanup)
   1455     PopCleanupBlock();
   1456 
   1457   // Check whether we've reached the end.
   1458   llvm::Value *done = Builder.CreateICmpEQ(element, begin, "arraydestroy.done");
   1459   Builder.CreateCondBr(done, doneBB, bodyBB);
   1460   elementPast->addIncoming(element, Builder.GetInsertBlock());
   1461 
   1462   // Done.
   1463   EmitBlock(doneBB);
   1464 }
   1465 
   1466 /// Perform partial array destruction as if in an EH cleanup.  Unlike
   1467 /// emitArrayDestroy, the element type here may still be an array type.
   1468 static void emitPartialArrayDestroy(CodeGenFunction &CGF,
   1469                                     llvm::Value *begin, llvm::Value *end,
   1470                                     QualType type,
   1471                                     CodeGenFunction::Destroyer *destroyer) {
   1472   // If the element type is itself an array, drill down.
   1473   unsigned arrayDepth = 0;
   1474   while (const ArrayType *arrayType = CGF.getContext().getAsArrayType(type)) {
   1475     // VLAs don't require a GEP index to walk into.
   1476     if (!isa<VariableArrayType>(arrayType))
   1477       arrayDepth++;
   1478     type = arrayType->getElementType();
   1479   }
   1480 
   1481   if (arrayDepth) {
   1482     llvm::Value *zero = llvm::ConstantInt::get(CGF.SizeTy, arrayDepth+1);
   1483 
   1484     SmallVector<llvm::Value*,4> gepIndices(arrayDepth, zero);
   1485     begin = CGF.Builder.CreateInBoundsGEP(begin, gepIndices, "pad.arraybegin");
   1486     end = CGF.Builder.CreateInBoundsGEP(end, gepIndices, "pad.arrayend");
   1487   }
   1488 
   1489   // Destroy the array.  We don't ever need an EH cleanup because we
   1490   // assume that we're in an EH cleanup ourselves, so a throwing
   1491   // destructor causes an immediate terminate.
   1492   CGF.emitArrayDestroy(begin, end, type, destroyer,
   1493                        /*checkZeroLength*/ true, /*useEHCleanup*/ false);
   1494 }
   1495 
   1496 namespace {
   1497   /// RegularPartialArrayDestroy - a cleanup which performs a partial
   1498   /// array destroy where the end pointer is regularly determined and
   1499   /// does not need to be loaded from a local.
   1500   class RegularPartialArrayDestroy : public EHScopeStack::Cleanup {
   1501     llvm::Value *ArrayBegin;
   1502     llvm::Value *ArrayEnd;
   1503     QualType ElementType;
   1504     CodeGenFunction::Destroyer *Destroyer;
   1505   public:
   1506     RegularPartialArrayDestroy(llvm::Value *arrayBegin, llvm::Value *arrayEnd,
   1507                                QualType elementType,
   1508                                CodeGenFunction::Destroyer *destroyer)
   1509       : ArrayBegin(arrayBegin), ArrayEnd(arrayEnd),
   1510         ElementType(elementType), Destroyer(destroyer) {}
   1511 
   1512     void Emit(CodeGenFunction &CGF, Flags flags) override {
   1513       emitPartialArrayDestroy(CGF, ArrayBegin, ArrayEnd,
   1514                               ElementType, Destroyer);
   1515     }
   1516   };
   1517 
   1518   /// IrregularPartialArrayDestroy - a cleanup which performs a
   1519   /// partial array destroy where the end pointer is irregularly
   1520   /// determined and must be loaded from a local.
   1521   class IrregularPartialArrayDestroy : public EHScopeStack::Cleanup {
   1522     llvm::Value *ArrayBegin;
   1523     llvm::Value *ArrayEndPointer;
   1524     QualType ElementType;
   1525     CodeGenFunction::Destroyer *Destroyer;
   1526   public:
   1527     IrregularPartialArrayDestroy(llvm::Value *arrayBegin,
   1528                                  llvm::Value *arrayEndPointer,
   1529                                  QualType elementType,
   1530                                  CodeGenFunction::Destroyer *destroyer)
   1531       : ArrayBegin(arrayBegin), ArrayEndPointer(arrayEndPointer),
   1532         ElementType(elementType), Destroyer(destroyer) {}
   1533 
   1534     void Emit(CodeGenFunction &CGF, Flags flags) override {
   1535       llvm::Value *arrayEnd = CGF.Builder.CreateLoad(ArrayEndPointer);
   1536       emitPartialArrayDestroy(CGF, ArrayBegin, arrayEnd,
   1537                               ElementType, Destroyer);
   1538     }
   1539   };
   1540 }
   1541 
   1542 /// pushIrregularPartialArrayCleanup - Push an EH cleanup to destroy
   1543 /// already-constructed elements of the given array.  The cleanup
   1544 /// may be popped with DeactivateCleanupBlock or PopCleanupBlock.
   1545 ///
   1546 /// \param elementType - the immediate element type of the array;
   1547 ///   possibly still an array type
   1548 void CodeGenFunction::pushIrregularPartialArrayCleanup(llvm::Value *arrayBegin,
   1549                                                  llvm::Value *arrayEndPointer,
   1550                                                        QualType elementType,
   1551                                                        Destroyer *destroyer) {
   1552   pushFullExprCleanup<IrregularPartialArrayDestroy>(EHCleanup,
   1553                                                     arrayBegin, arrayEndPointer,
   1554                                                     elementType, destroyer);
   1555 }
   1556 
   1557 /// pushRegularPartialArrayCleanup - Push an EH cleanup to destroy
   1558 /// already-constructed elements of the given array.  The cleanup
   1559 /// may be popped with DeactivateCleanupBlock or PopCleanupBlock.
   1560 ///
   1561 /// \param elementType - the immediate element type of the array;
   1562 ///   possibly still an array type
   1563 void CodeGenFunction::pushRegularPartialArrayCleanup(llvm::Value *arrayBegin,
   1564                                                      llvm::Value *arrayEnd,
   1565                                                      QualType elementType,
   1566                                                      Destroyer *destroyer) {
   1567   pushFullExprCleanup<RegularPartialArrayDestroy>(EHCleanup,
   1568                                                   arrayBegin, arrayEnd,
   1569                                                   elementType, destroyer);
   1570 }
   1571 
   1572 /// Lazily declare the @llvm.lifetime.start intrinsic.
   1573 llvm::Constant *CodeGenModule::getLLVMLifetimeStartFn() {
   1574   if (LifetimeStartFn) return LifetimeStartFn;
   1575   LifetimeStartFn = llvm::Intrinsic::getDeclaration(&getModule(),
   1576                                             llvm::Intrinsic::lifetime_start);
   1577   return LifetimeStartFn;
   1578 }
   1579 
   1580 /// Lazily declare the @llvm.lifetime.end intrinsic.
   1581 llvm::Constant *CodeGenModule::getLLVMLifetimeEndFn() {
   1582   if (LifetimeEndFn) return LifetimeEndFn;
   1583   LifetimeEndFn = llvm::Intrinsic::getDeclaration(&getModule(),
   1584                                               llvm::Intrinsic::lifetime_end);
   1585   return LifetimeEndFn;
   1586 }
   1587 
   1588 namespace {
   1589   /// A cleanup to perform a release of an object at the end of a
   1590   /// function.  This is used to balance out the incoming +1 of a
   1591   /// ns_consumed argument when we can't reasonably do that just by
   1592   /// not doing the initial retain for a __block argument.
   1593   struct ConsumeARCParameter : EHScopeStack::Cleanup {
   1594     ConsumeARCParameter(llvm::Value *param,
   1595                         ARCPreciseLifetime_t precise)
   1596       : Param(param), Precise(precise) {}
   1597 
   1598     llvm::Value *Param;
   1599     ARCPreciseLifetime_t Precise;
   1600 
   1601     void Emit(CodeGenFunction &CGF, Flags flags) override {
   1602       CGF.EmitARCRelease(Param, Precise);
   1603     }
   1604   };
   1605 }
   1606 
   1607 /// Emit an alloca (or GlobalValue depending on target)
   1608 /// for the specified parameter and set up LocalDeclMap.
   1609 void CodeGenFunction::EmitParmDecl(const VarDecl &D, llvm::Value *Arg,
   1610                                    bool ArgIsPointer, unsigned ArgNo) {
   1611   // FIXME: Why isn't ImplicitParamDecl a ParmVarDecl?
   1612   assert((isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D)) &&
   1613          "Invalid argument to EmitParmDecl");
   1614 
   1615   Arg->setName(D.getName());
   1616 
   1617   QualType Ty = D.getType();
   1618 
   1619   // Use better IR generation for certain implicit parameters.
   1620   if (isa<ImplicitParamDecl>(D)) {
   1621     // The only implicit argument a block has is its literal.
   1622     if (BlockInfo) {
   1623       LocalDeclMap[&D] = Arg;
   1624       llvm::Value *LocalAddr = nullptr;
   1625       if (CGM.getCodeGenOpts().OptimizationLevel == 0) {
   1626         // Allocate a stack slot to let the debug info survive the RA.
   1627         llvm::AllocaInst *Alloc = CreateTempAlloca(ConvertTypeForMem(Ty),
   1628                                                    D.getName() + ".addr");
   1629         Alloc->setAlignment(getContext().getDeclAlign(&D).getQuantity());
   1630         LValue lv = MakeAddrLValue(Alloc, Ty, getContext().getDeclAlign(&D));
   1631         EmitStoreOfScalar(Arg, lv, /* isInitialization */ true);
   1632         LocalAddr = Builder.CreateLoad(Alloc);
   1633       }
   1634 
   1635       if (CGDebugInfo *DI = getDebugInfo()) {
   1636         if (CGM.getCodeGenOpts().getDebugInfo()
   1637               >= CodeGenOptions::LimitedDebugInfo) {
   1638           DI->setLocation(D.getLocation());
   1639           DI->EmitDeclareOfBlockLiteralArgVariable(*BlockInfo, Arg, LocalAddr, Builder);
   1640         }
   1641       }
   1642 
   1643       return;
   1644     }
   1645   }
   1646 
   1647   llvm::Value *DeclPtr;
   1648   bool DoStore = false;
   1649   bool IsScalar = hasScalarEvaluationKind(Ty);
   1650   CharUnits Align = getContext().getDeclAlign(&D);
   1651   // If we already have a pointer to the argument, reuse the input pointer.
   1652   if (ArgIsPointer) {
   1653     // If we have a prettier pointer type at this point, bitcast to that.
   1654     unsigned AS = cast<llvm::PointerType>(Arg->getType())->getAddressSpace();
   1655     llvm::Type *IRTy = ConvertTypeForMem(Ty)->getPointerTo(AS);
   1656     DeclPtr = Arg->getType() == IRTy ? Arg : Builder.CreateBitCast(Arg, IRTy,
   1657                                                                    D.getName());
   1658     // Push a destructor cleanup for this parameter if the ABI requires it.
   1659     if (!IsScalar &&
   1660         getTarget().getCXXABI().areArgsDestroyedLeftToRightInCallee()) {
   1661       const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
   1662       if (RD && RD->hasNonTrivialDestructor())
   1663         pushDestroy(QualType::DK_cxx_destructor, DeclPtr, Ty);
   1664     }
   1665   } else {
   1666     // Otherwise, create a temporary to hold the value.
   1667     llvm::AllocaInst *Alloc = CreateTempAlloca(ConvertTypeForMem(Ty),
   1668                                                D.getName() + ".addr");
   1669     Alloc->setAlignment(Align.getQuantity());
   1670     DeclPtr = Alloc;
   1671     DoStore = true;
   1672   }
   1673 
   1674   LValue lv = MakeAddrLValue(DeclPtr, Ty, Align);
   1675   if (IsScalar) {
   1676     Qualifiers qs = Ty.getQualifiers();
   1677     if (Qualifiers::ObjCLifetime lt = qs.getObjCLifetime()) {
   1678       // We honor __attribute__((ns_consumed)) for types with lifetime.
   1679       // For __strong, it's handled by just skipping the initial retain;
   1680       // otherwise we have to balance out the initial +1 with an extra
   1681       // cleanup to do the release at the end of the function.
   1682       bool isConsumed = D.hasAttr<NSConsumedAttr>();
   1683 
   1684       // 'self' is always formally __strong, but if this is not an
   1685       // init method then we don't want to retain it.
   1686       if (D.isARCPseudoStrong()) {
   1687         const ObjCMethodDecl *method = cast<ObjCMethodDecl>(CurCodeDecl);
   1688         assert(&D == method->getSelfDecl());
   1689         assert(lt == Qualifiers::OCL_Strong);
   1690         assert(qs.hasConst());
   1691         assert(method->getMethodFamily() != OMF_init);
   1692         (void) method;
   1693         lt = Qualifiers::OCL_ExplicitNone;
   1694       }
   1695 
   1696       if (lt == Qualifiers::OCL_Strong) {
   1697         if (!isConsumed) {
   1698           if (CGM.getCodeGenOpts().OptimizationLevel == 0) {
   1699             // use objc_storeStrong(&dest, value) for retaining the
   1700             // object. But first, store a null into 'dest' because
   1701             // objc_storeStrong attempts to release its old value.
   1702             llvm::Value *Null = CGM.EmitNullConstant(D.getType());
   1703             EmitStoreOfScalar(Null, lv, /* isInitialization */ true);
   1704             EmitARCStoreStrongCall(lv.getAddress(), Arg, true);
   1705             DoStore = false;
   1706           }
   1707           else
   1708           // Don't use objc_retainBlock for block pointers, because we
   1709           // don't want to Block_copy something just because we got it
   1710           // as a parameter.
   1711             Arg = EmitARCRetainNonBlock(Arg);
   1712         }
   1713       } else {
   1714         // Push the cleanup for a consumed parameter.
   1715         if (isConsumed) {
   1716           ARCPreciseLifetime_t precise = (D.hasAttr<ObjCPreciseLifetimeAttr>()
   1717                                 ? ARCPreciseLifetime : ARCImpreciseLifetime);
   1718           EHStack.pushCleanup<ConsumeARCParameter>(getARCCleanupKind(), Arg,
   1719                                                    precise);
   1720         }
   1721 
   1722         if (lt == Qualifiers::OCL_Weak) {
   1723           EmitARCInitWeak(DeclPtr, Arg);
   1724           DoStore = false; // The weak init is a store, no need to do two.
   1725         }
   1726       }
   1727 
   1728       // Enter the cleanup scope.
   1729       EmitAutoVarWithLifetime(*this, D, DeclPtr, lt);
   1730     }
   1731   }
   1732 
   1733   // Store the initial value into the alloca.
   1734   if (DoStore)
   1735     EmitStoreOfScalar(Arg, lv, /* isInitialization */ true);
   1736 
   1737   llvm::Value *&DMEntry = LocalDeclMap[&D];
   1738   assert(!DMEntry && "Decl already exists in localdeclmap!");
   1739   DMEntry = DeclPtr;
   1740 
   1741   // Emit debug info for param declaration.
   1742   if (CGDebugInfo *DI = getDebugInfo()) {
   1743     if (CGM.getCodeGenOpts().getDebugInfo()
   1744           >= CodeGenOptions::LimitedDebugInfo) {
   1745       DI->EmitDeclareOfArgVariable(&D, DeclPtr, ArgNo, Builder);
   1746     }
   1747   }
   1748 
   1749   if (D.hasAttr<AnnotateAttr>())
   1750       EmitVarAnnotations(&D, DeclPtr);
   1751 }
   1752