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