clang API Documentation

CGDecl.cpp
Go to the documentation of this file.
00001 //===--- CGDecl.cpp - Emit LLVM Code for declarations ---------------------===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 // This contains code to emit Decl nodes as LLVM code.
00011 //
00012 //===----------------------------------------------------------------------===//
00013 
00014 #include "CodeGenFunction.h"
00015 #include "CGDebugInfo.h"
00016 #include "CGOpenCLRuntime.h"
00017 #include "CodeGenModule.h"
00018 #include "clang/AST/ASTContext.h"
00019 #include "clang/AST/CharUnits.h"
00020 #include "clang/AST/Decl.h"
00021 #include "clang/AST/DeclObjC.h"
00022 #include "clang/Basic/SourceManager.h"
00023 #include "clang/Basic/TargetInfo.h"
00024 #include "clang/CodeGen/CGFunctionInfo.h"
00025 #include "clang/Frontend/CodeGenOptions.h"
00026 #include "llvm/IR/DataLayout.h"
00027 #include "llvm/IR/GlobalVariable.h"
00028 #include "llvm/IR/Intrinsics.h"
00029 #include "llvm/IR/Type.h"
00030 using namespace clang;
00031 using namespace CodeGen;
00032 
00033 
00034 void CodeGenFunction::EmitDecl(const Decl &D) {
00035   switch (D.getKind()) {
00036   case Decl::TranslationUnit:
00037   case Decl::Namespace:
00038   case Decl::UnresolvedUsingTypename:
00039   case Decl::ClassTemplateSpecialization:
00040   case Decl::ClassTemplatePartialSpecialization:
00041   case Decl::VarTemplateSpecialization:
00042   case Decl::VarTemplatePartialSpecialization:
00043   case Decl::TemplateTypeParm:
00044   case Decl::UnresolvedUsingValue:
00045   case Decl::NonTypeTemplateParm:
00046   case Decl::CXXMethod:
00047   case Decl::CXXConstructor:
00048   case Decl::CXXDestructor:
00049   case Decl::CXXConversion:
00050   case Decl::Field:
00051   case Decl::MSProperty:
00052   case Decl::IndirectField:
00053   case Decl::ObjCIvar:
00054   case Decl::ObjCAtDefsField:
00055   case Decl::ParmVar:
00056   case Decl::ImplicitParam:
00057   case Decl::ClassTemplate:
00058   case Decl::VarTemplate:
00059   case Decl::FunctionTemplate:
00060   case Decl::TypeAliasTemplate:
00061   case Decl::TemplateTemplateParm:
00062   case Decl::ObjCMethod:
00063   case Decl::ObjCCategory:
00064   case Decl::ObjCProtocol:
00065   case Decl::ObjCInterface:
00066   case Decl::ObjCCategoryImpl:
00067   case Decl::ObjCImplementation:
00068   case Decl::ObjCProperty:
00069   case Decl::ObjCCompatibleAlias:
00070   case Decl::AccessSpec:
00071   case Decl::LinkageSpec:
00072   case Decl::ObjCPropertyImpl:
00073   case Decl::FileScopeAsm:
00074   case Decl::Friend:
00075   case Decl::FriendTemplate:
00076   case Decl::Block:
00077   case Decl::Captured:
00078   case Decl::ClassScopeFunctionSpecialization:
00079   case Decl::UsingShadow:
00080     llvm_unreachable("Declaration should not be in declstmts!");
00081   case Decl::Function:  // void X();
00082   case Decl::Record:    // struct/union/class X;
00083   case Decl::Enum:      // enum X;
00084   case Decl::EnumConstant: // enum ? { X = ? }
00085   case Decl::CXXRecord: // struct/union/class X; [C++]
00086   case Decl::StaticAssert: // static_assert(X, ""); [C++0x]
00087   case Decl::Label:        // __label__ x;
00088   case Decl::Import:
00089   case Decl::OMPThreadPrivate:
00090   case Decl::Empty:
00091     // None of these decls require codegen support.
00092     return;
00093 
00094   case Decl::NamespaceAlias:
00095     if (CGDebugInfo *DI = getDebugInfo())
00096         DI->EmitNamespaceAlias(cast<NamespaceAliasDecl>(D));
00097     return;
00098   case Decl::Using:          // using X; [C++]
00099     if (CGDebugInfo *DI = getDebugInfo())
00100         DI->EmitUsingDecl(cast<UsingDecl>(D));
00101     return;
00102   case Decl::UsingDirective: // using namespace X; [C++]
00103     if (CGDebugInfo *DI = getDebugInfo())
00104       DI->EmitUsingDirective(cast<UsingDirectiveDecl>(D));
00105     return;
00106   case Decl::Var: {
00107     const VarDecl &VD = cast<VarDecl>(D);
00108     assert(VD.isLocalVarDecl() &&
00109            "Should not see file-scope variables inside a function!");
00110     return EmitVarDecl(VD);
00111   }
00112 
00113   case Decl::Typedef:      // typedef int X;
00114   case Decl::TypeAlias: {  // using X = int; [C++0x]
00115     const TypedefNameDecl &TD = cast<TypedefNameDecl>(D);
00116     QualType Ty = TD.getUnderlyingType();
00117 
00118     if (Ty->isVariablyModifiedType())
00119       EmitVariablyModifiedType(Ty);
00120   }
00121   }
00122 }
00123 
00124 /// EmitVarDecl - This method handles emission of any variable declaration
00125 /// inside a function, including static vars etc.
00126 void CodeGenFunction::EmitVarDecl(const VarDecl &D) {
00127   if (D.isStaticLocal()) {
00128     llvm::GlobalValue::LinkageTypes Linkage =
00129         CGM.getLLVMLinkageVarDefinition(&D, /*isConstant=*/false);
00130 
00131     // FIXME: We need to force the emission/use of a guard variable for
00132     // some variables even if we can constant-evaluate them because
00133     // we can't guarantee every translation unit will constant-evaluate them.
00134 
00135     return EmitStaticVarDecl(D, Linkage);
00136   }
00137 
00138   if (D.hasExternalStorage())
00139     // Don't emit it now, allow it to be emitted lazily on its first use.
00140     return;
00141 
00142   if (D.getStorageClass() == SC_OpenCLWorkGroupLocal)
00143     return CGM.getOpenCLRuntime().EmitWorkGroupLocalVarDecl(*this, D);
00144 
00145   assert(D.hasLocalStorage());
00146   return EmitAutoVarDecl(D);
00147 }
00148 
00149 static std::string getStaticDeclName(CodeGenModule &CGM, const VarDecl &D) {
00150   if (CGM.getLangOpts().CPlusPlus)
00151     return CGM.getMangledName(&D).str();
00152 
00153   // If this isn't C++, we don't need a mangled name, just a pretty one.
00154   assert(!D.isExternallyVisible() && "name shouldn't matter");
00155   std::string ContextName;
00156   const DeclContext *DC = D.getDeclContext();
00157   if (const auto *FD = dyn_cast<FunctionDecl>(DC))
00158     ContextName = CGM.getMangledName(FD);
00159   else if (const auto *BD = dyn_cast<BlockDecl>(DC))
00160     ContextName = CGM.getBlockMangledName(GlobalDecl(), BD);
00161   else if (const auto *OMD = dyn_cast<ObjCMethodDecl>(DC))
00162     ContextName = OMD->getSelector().getAsString();
00163   else
00164     llvm_unreachable("Unknown context for static var decl");
00165 
00166   ContextName += "." + D.getNameAsString();
00167   return ContextName;
00168 }
00169 
00170 llvm::Constant *CodeGenModule::getOrCreateStaticVarDecl(
00171     const VarDecl &D, llvm::GlobalValue::LinkageTypes Linkage) {
00172   // In general, we don't always emit static var decls once before we reference
00173   // them. It is possible to reference them before emitting the function that
00174   // contains them, and it is possible to emit the containing function multiple
00175   // times.
00176   if (llvm::Constant *ExistingGV = StaticLocalDeclMap[&D])
00177     return ExistingGV;
00178 
00179   QualType Ty = D.getType();
00180   assert(Ty->isConstantSizeType() && "VLAs can't be static");
00181 
00182   // Use the label if the variable is renamed with the asm-label extension.
00183   std::string Name;
00184   if (D.hasAttr<AsmLabelAttr>())
00185     Name = getMangledName(&D);
00186   else
00187     Name = getStaticDeclName(*this, D);
00188 
00189   llvm::Type *LTy = getTypes().ConvertTypeForMem(Ty);
00190   unsigned AddrSpace =
00191       GetGlobalVarAddressSpace(&D, getContext().getTargetAddressSpace(Ty));
00192 
00193   // Local address space cannot have an initializer.
00194   llvm::Constant *Init = nullptr;
00195   if (Ty.getAddressSpace() != LangAS::opencl_local)
00196     Init = EmitNullConstant(Ty);
00197   else
00198     Init = llvm::UndefValue::get(LTy);
00199 
00200   llvm::GlobalVariable *GV =
00201     new llvm::GlobalVariable(getModule(), LTy,
00202                              Ty.isConstant(getContext()), Linkage,
00203                              Init, Name, nullptr,
00204                              llvm::GlobalVariable::NotThreadLocal,
00205                              AddrSpace);
00206   GV->setAlignment(getContext().getDeclAlign(&D).getQuantity());
00207   setGlobalVisibility(GV, &D);
00208 
00209   if (D.getTLSKind())
00210     setTLSMode(GV, D);
00211 
00212   if (D.isExternallyVisible()) {
00213     if (D.hasAttr<DLLImportAttr>())
00214       GV->setDLLStorageClass(llvm::GlobalVariable::DLLImportStorageClass);
00215     else if (D.hasAttr<DLLExportAttr>())
00216       GV->setDLLStorageClass(llvm::GlobalVariable::DLLExportStorageClass);
00217   }
00218 
00219   // Make sure the result is of the correct type.
00220   unsigned ExpectedAddrSpace = getContext().getTargetAddressSpace(Ty);
00221   llvm::Constant *Addr = GV;
00222   if (AddrSpace != ExpectedAddrSpace) {
00223     llvm::PointerType *PTy = llvm::PointerType::get(LTy, ExpectedAddrSpace);
00224     Addr = llvm::ConstantExpr::getAddrSpaceCast(GV, PTy);
00225   }
00226 
00227   setStaticLocalDeclAddress(&D, Addr);
00228 
00229   // Ensure that the static local gets initialized by making sure the parent
00230   // function gets emitted eventually.
00231   const Decl *DC = cast<Decl>(D.getDeclContext());
00232 
00233   // We can't name blocks or captured statements directly, so try to emit their
00234   // parents.
00235   if (isa<BlockDecl>(DC) || isa<CapturedDecl>(DC)) {
00236     DC = DC->getNonClosureContext();
00237     // FIXME: Ensure that global blocks get emitted.
00238     if (!DC)
00239       return Addr;
00240   }
00241 
00242   GlobalDecl GD;
00243   if (const auto *CD = dyn_cast<CXXConstructorDecl>(DC))
00244     GD = GlobalDecl(CD, Ctor_Base);
00245   else if (const auto *DD = dyn_cast<CXXDestructorDecl>(DC))
00246     GD = GlobalDecl(DD, Dtor_Base);
00247   else if (const auto *FD = dyn_cast<FunctionDecl>(DC))
00248     GD = GlobalDecl(FD);
00249   else {
00250     // Don't do anything for Obj-C method decls or global closures. We should
00251     // never defer them.
00252     assert(isa<ObjCMethodDecl>(DC) && "unexpected parent code decl");
00253   }
00254   if (GD.getDecl())
00255     (void)GetAddrOfGlobal(GD);
00256 
00257   return Addr;
00258 }
00259 
00260 /// hasNontrivialDestruction - Determine whether a type's destruction is
00261 /// non-trivial. If so, and the variable uses static initialization, we must
00262 /// register its destructor to run on exit.
00263 static bool hasNontrivialDestruction(QualType T) {
00264   CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
00265   return RD && !RD->hasTrivialDestructor();
00266 }
00267 
00268 /// AddInitializerToStaticVarDecl - Add the initializer for 'D' to the
00269 /// global variable that has already been created for it.  If the initializer
00270 /// has a different type than GV does, this may free GV and return a different
00271 /// one.  Otherwise it just returns GV.
00272 llvm::GlobalVariable *
00273 CodeGenFunction::AddInitializerToStaticVarDecl(const VarDecl &D,
00274                                                llvm::GlobalVariable *GV) {
00275   llvm::Constant *Init = CGM.EmitConstantInit(D, this);
00276 
00277   // If constant emission failed, then this should be a C++ static
00278   // initializer.
00279   if (!Init) {
00280     if (!getLangOpts().CPlusPlus)
00281       CGM.ErrorUnsupported(D.getInit(), "constant l-value expression");
00282     else if (Builder.GetInsertBlock()) {
00283       // Since we have a static initializer, this global variable can't
00284       // be constant.
00285       GV->setConstant(false);
00286 
00287       EmitCXXGuardedInit(D, GV, /*PerformInit*/true);
00288     }
00289     return GV;
00290   }
00291 
00292   // The initializer may differ in type from the global. Rewrite
00293   // the global to match the initializer.  (We have to do this
00294   // because some types, like unions, can't be completely represented
00295   // in the LLVM type system.)
00296   if (GV->getType()->getElementType() != Init->getType()) {
00297     llvm::GlobalVariable *OldGV = GV;
00298 
00299     GV = new llvm::GlobalVariable(CGM.getModule(), Init->getType(),
00300                                   OldGV->isConstant(),
00301                                   OldGV->getLinkage(), Init, "",
00302                                   /*InsertBefore*/ OldGV,
00303                                   OldGV->getThreadLocalMode(),
00304                            CGM.getContext().getTargetAddressSpace(D.getType()));
00305     GV->setVisibility(OldGV->getVisibility());
00306 
00307     // Steal the name of the old global
00308     GV->takeName(OldGV);
00309 
00310     // Replace all uses of the old global with the new global
00311     llvm::Constant *NewPtrForOldDecl =
00312     llvm::ConstantExpr::getBitCast(GV, OldGV->getType());
00313     OldGV->replaceAllUsesWith(NewPtrForOldDecl);
00314 
00315     // Erase the old global, since it is no longer used.
00316     OldGV->eraseFromParent();
00317   }
00318 
00319   GV->setConstant(CGM.isTypeConstant(D.getType(), true));
00320   GV->setInitializer(Init);
00321 
00322   if (hasNontrivialDestruction(D.getType())) {
00323     // We have a constant initializer, but a nontrivial destructor. We still
00324     // need to perform a guarded "initialization" in order to register the
00325     // destructor.
00326     EmitCXXGuardedInit(D, GV, /*PerformInit*/false);
00327   }
00328 
00329   return GV;
00330 }
00331 
00332 void CodeGenFunction::EmitStaticVarDecl(const VarDecl &D,
00333                                       llvm::GlobalValue::LinkageTypes Linkage) {
00334   llvm::Value *&DMEntry = LocalDeclMap[&D];
00335   assert(!DMEntry && "Decl already exists in localdeclmap!");
00336 
00337   // Check to see if we already have a global variable for this
00338   // declaration.  This can happen when double-emitting function
00339   // bodies, e.g. with complete and base constructors.
00340   llvm::Constant *addr = CGM.getOrCreateStaticVarDecl(D, Linkage);
00341 
00342   // Store into LocalDeclMap before generating initializer to handle
00343   // circular references.
00344   DMEntry = addr;
00345 
00346   // We can't have a VLA here, but we can have a pointer to a VLA,
00347   // even though that doesn't really make any sense.
00348   // Make sure to evaluate VLA bounds now so that we have them for later.
00349   if (D.getType()->isVariablyModifiedType())
00350     EmitVariablyModifiedType(D.getType());
00351 
00352   // Save the type in case adding the initializer forces a type change.
00353   llvm::Type *expectedType = addr->getType();
00354 
00355   llvm::GlobalVariable *var =
00356     cast<llvm::GlobalVariable>(addr->stripPointerCasts());
00357   // If this value has an initializer, emit it.
00358   if (D.getInit())
00359     var = AddInitializerToStaticVarDecl(D, var);
00360 
00361   var->setAlignment(getContext().getDeclAlign(&D).getQuantity());
00362 
00363   if (D.hasAttr<AnnotateAttr>())
00364     CGM.AddGlobalAnnotations(&D, var);
00365 
00366   if (const SectionAttr *SA = D.getAttr<SectionAttr>())
00367     var->setSection(SA->getName());
00368 
00369   if (D.hasAttr<UsedAttr>())
00370     CGM.addUsedGlobal(var);
00371 
00372   // We may have to cast the constant because of the initializer
00373   // mismatch above.
00374   //
00375   // FIXME: It is really dangerous to store this in the map; if anyone
00376   // RAUW's the GV uses of this constant will be invalid.
00377   llvm::Constant *castedAddr =
00378     llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(var, expectedType);
00379   DMEntry = castedAddr;
00380   CGM.setStaticLocalDeclAddress(&D, castedAddr);
00381 
00382   CGM.getSanitizerMetadata()->reportGlobalToASan(var, D);
00383 
00384   // Emit global variable debug descriptor for static vars.
00385   CGDebugInfo *DI = getDebugInfo();
00386   if (DI &&
00387       CGM.getCodeGenOpts().getDebugInfo() >= CodeGenOptions::LimitedDebugInfo) {
00388     DI->setLocation(D.getLocation());
00389     DI->EmitGlobalVariable(var, &D);
00390   }
00391 }
00392 
00393 namespace {
00394   struct DestroyObject : EHScopeStack::Cleanup {
00395     DestroyObject(llvm::Value *addr, QualType type,
00396                   CodeGenFunction::Destroyer *destroyer,
00397                   bool useEHCleanupForArray)
00398       : addr(addr), type(type), destroyer(destroyer),
00399         useEHCleanupForArray(useEHCleanupForArray) {}
00400 
00401     llvm::Value *addr;
00402     QualType type;
00403     CodeGenFunction::Destroyer *destroyer;
00404     bool useEHCleanupForArray;
00405 
00406     void Emit(CodeGenFunction &CGF, Flags flags) override {
00407       // Don't use an EH cleanup recursively from an EH cleanup.
00408       bool useEHCleanupForArray =
00409         flags.isForNormalCleanup() && this->useEHCleanupForArray;
00410 
00411       CGF.emitDestroy(addr, type, destroyer, useEHCleanupForArray);
00412     }
00413   };
00414 
00415   struct DestroyNRVOVariable : EHScopeStack::Cleanup {
00416     DestroyNRVOVariable(llvm::Value *addr,
00417                         const CXXDestructorDecl *Dtor,
00418                         llvm::Value *NRVOFlag)
00419       : Dtor(Dtor), NRVOFlag(NRVOFlag), Loc(addr) {}
00420 
00421     const CXXDestructorDecl *Dtor;
00422     llvm::Value *NRVOFlag;
00423     llvm::Value *Loc;
00424 
00425     void Emit(CodeGenFunction &CGF, Flags flags) override {
00426       // Along the exceptions path we always execute the dtor.
00427       bool NRVO = flags.isForNormalCleanup() && NRVOFlag;
00428 
00429       llvm::BasicBlock *SkipDtorBB = nullptr;
00430       if (NRVO) {
00431         // If we exited via NRVO, we skip the destructor call.
00432         llvm::BasicBlock *RunDtorBB = CGF.createBasicBlock("nrvo.unused");
00433         SkipDtorBB = CGF.createBasicBlock("nrvo.skipdtor");
00434         llvm::Value *DidNRVO = CGF.Builder.CreateLoad(NRVOFlag, "nrvo.val");
00435         CGF.Builder.CreateCondBr(DidNRVO, SkipDtorBB, RunDtorBB);
00436         CGF.EmitBlock(RunDtorBB);
00437       }
00438 
00439       CGF.EmitCXXDestructorCall(Dtor, Dtor_Complete,
00440                                 /*ForVirtualBase=*/false,
00441                                 /*Delegating=*/false,
00442                                 Loc);
00443 
00444       if (NRVO) CGF.EmitBlock(SkipDtorBB);
00445     }
00446   };
00447 
00448   struct CallStackRestore : EHScopeStack::Cleanup {
00449     llvm::Value *Stack;
00450     CallStackRestore(llvm::Value *Stack) : Stack(Stack) {}
00451     void Emit(CodeGenFunction &CGF, Flags flags) override {
00452       llvm::Value *V = CGF.Builder.CreateLoad(Stack);
00453       llvm::Value *F = CGF.CGM.getIntrinsic(llvm::Intrinsic::stackrestore);
00454       CGF.Builder.CreateCall(F, V);
00455     }
00456   };
00457 
00458   struct ExtendGCLifetime : EHScopeStack::Cleanup {
00459     const VarDecl &Var;
00460     ExtendGCLifetime(const VarDecl *var) : Var(*var) {}
00461 
00462     void Emit(CodeGenFunction &CGF, Flags flags) override {
00463       // Compute the address of the local variable, in case it's a
00464       // byref or something.
00465       DeclRefExpr DRE(const_cast<VarDecl*>(&Var), false,
00466                       Var.getType(), VK_LValue, SourceLocation());
00467       llvm::Value *value = CGF.EmitLoadOfScalar(CGF.EmitDeclRefLValue(&DRE),
00468                                                 SourceLocation());
00469       CGF.EmitExtendGCLifetime(value);
00470     }
00471   };
00472 
00473   struct CallCleanupFunction : EHScopeStack::Cleanup {
00474     llvm::Constant *CleanupFn;
00475     const CGFunctionInfo &FnInfo;
00476     const VarDecl &Var;
00477 
00478     CallCleanupFunction(llvm::Constant *CleanupFn, const CGFunctionInfo *Info,
00479                         const VarDecl *Var)
00480       : CleanupFn(CleanupFn), FnInfo(*Info), Var(*Var) {}
00481 
00482     void Emit(CodeGenFunction &CGF, Flags flags) override {
00483       DeclRefExpr DRE(const_cast<VarDecl*>(&Var), false,
00484                       Var.getType(), VK_LValue, SourceLocation());
00485       // Compute the address of the local variable, in case it's a byref
00486       // or something.
00487       llvm::Value *Addr = CGF.EmitDeclRefLValue(&DRE).getAddress();
00488 
00489       // In some cases, the type of the function argument will be different from
00490       // the type of the pointer. An example of this is
00491       // void f(void* arg);
00492       // __attribute__((cleanup(f))) void *g;
00493       //
00494       // To fix this we insert a bitcast here.
00495       QualType ArgTy = FnInfo.arg_begin()->type;
00496       llvm::Value *Arg =
00497         CGF.Builder.CreateBitCast(Addr, CGF.ConvertType(ArgTy));
00498 
00499       CallArgList Args;
00500       Args.add(RValue::get(Arg),
00501                CGF.getContext().getPointerType(Var.getType()));
00502       CGF.EmitCall(FnInfo, CleanupFn, ReturnValueSlot(), Args);
00503     }
00504   };
00505 
00506   /// A cleanup to call @llvm.lifetime.end.
00507   class CallLifetimeEnd : public EHScopeStack::Cleanup {
00508     llvm::Value *Addr;
00509     llvm::Value *Size;
00510   public:
00511     CallLifetimeEnd(llvm::Value *addr, llvm::Value *size)
00512       : Addr(addr), Size(size) {}
00513 
00514     void Emit(CodeGenFunction &CGF, Flags flags) override {
00515       llvm::Value *castAddr = CGF.Builder.CreateBitCast(Addr, CGF.Int8PtrTy);
00516       CGF.Builder.CreateCall2(CGF.CGM.getLLVMLifetimeEndFn(),
00517                               Size, castAddr)
00518         ->setDoesNotThrow();
00519     }
00520   };
00521 }
00522 
00523 /// EmitAutoVarWithLifetime - Does the setup required for an automatic
00524 /// variable with lifetime.
00525 static void EmitAutoVarWithLifetime(CodeGenFunction &CGF, const VarDecl &var,
00526                                     llvm::Value *addr,
00527                                     Qualifiers::ObjCLifetime lifetime) {
00528   switch (lifetime) {
00529   case Qualifiers::OCL_None:
00530     llvm_unreachable("present but none");
00531 
00532   case Qualifiers::OCL_ExplicitNone:
00533     // nothing to do
00534     break;
00535 
00536   case Qualifiers::OCL_Strong: {
00537     CodeGenFunction::Destroyer *destroyer =
00538       (var.hasAttr<ObjCPreciseLifetimeAttr>()
00539        ? CodeGenFunction::destroyARCStrongPrecise
00540        : CodeGenFunction::destroyARCStrongImprecise);
00541 
00542     CleanupKind cleanupKind = CGF.getARCCleanupKind();
00543     CGF.pushDestroy(cleanupKind, addr, var.getType(), destroyer,
00544                     cleanupKind & EHCleanup);
00545     break;
00546   }
00547   case Qualifiers::OCL_Autoreleasing:
00548     // nothing to do
00549     break;
00550 
00551   case Qualifiers::OCL_Weak:
00552     // __weak objects always get EH cleanups; otherwise, exceptions
00553     // could cause really nasty crashes instead of mere leaks.
00554     CGF.pushDestroy(NormalAndEHCleanup, addr, var.getType(),
00555                     CodeGenFunction::destroyARCWeak,
00556                     /*useEHCleanup*/ true);
00557     break;
00558   }
00559 }
00560 
00561 static bool isAccessedBy(const VarDecl &var, const Stmt *s) {
00562   if (const Expr *e = dyn_cast<Expr>(s)) {
00563     // Skip the most common kinds of expressions that make
00564     // hierarchy-walking expensive.
00565     s = e = e->IgnoreParenCasts();
00566 
00567     if (const DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e))
00568       return (ref->getDecl() == &var);
00569     if (const BlockExpr *be = dyn_cast<BlockExpr>(e)) {
00570       const BlockDecl *block = be->getBlockDecl();
00571       for (const auto &I : block->captures()) {
00572         if (I.getVariable() == &var)
00573           return true;
00574       }
00575     }
00576   }
00577 
00578   for (Stmt::const_child_range children = s->children(); children; ++children)
00579     // children might be null; as in missing decl or conditional of an if-stmt.
00580     if ((*children) && isAccessedBy(var, *children))
00581       return true;
00582 
00583   return false;
00584 }
00585 
00586 static bool isAccessedBy(const ValueDecl *decl, const Expr *e) {
00587   if (!decl) return false;
00588   if (!isa<VarDecl>(decl)) return false;
00589   const VarDecl *var = cast<VarDecl>(decl);
00590   return isAccessedBy(*var, e);
00591 }
00592 
00593 static void drillIntoBlockVariable(CodeGenFunction &CGF,
00594                                    LValue &lvalue,
00595                                    const VarDecl *var) {
00596   lvalue.setAddress(CGF.BuildBlockByrefAddress(lvalue.getAddress(), var));
00597 }
00598 
00599 void CodeGenFunction::EmitScalarInit(const Expr *init,
00600                                      const ValueDecl *D,
00601                                      LValue lvalue,
00602                                      bool capturedByInit) {
00603   Qualifiers::ObjCLifetime lifetime = lvalue.getObjCLifetime();
00604   if (!lifetime) {
00605     llvm::Value *value = EmitScalarExpr(init);
00606     if (capturedByInit)
00607       drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D));
00608     EmitStoreThroughLValue(RValue::get(value), lvalue, true);
00609     return;
00610   }
00611   
00612   if (const CXXDefaultInitExpr *DIE = dyn_cast<CXXDefaultInitExpr>(init))
00613     init = DIE->getExpr();
00614     
00615   // If we're emitting a value with lifetime, we have to do the
00616   // initialization *before* we leave the cleanup scopes.
00617   if (const ExprWithCleanups *ewc = dyn_cast<ExprWithCleanups>(init)) {
00618     enterFullExpression(ewc);
00619     init = ewc->getSubExpr();
00620   }
00621   CodeGenFunction::RunCleanupsScope Scope(*this);
00622 
00623   // We have to maintain the illusion that the variable is
00624   // zero-initialized.  If the variable might be accessed in its
00625   // initializer, zero-initialize before running the initializer, then
00626   // actually perform the initialization with an assign.
00627   bool accessedByInit = false;
00628   if (lifetime != Qualifiers::OCL_ExplicitNone)
00629     accessedByInit = (capturedByInit || isAccessedBy(D, init));
00630   if (accessedByInit) {
00631     LValue tempLV = lvalue;
00632     // Drill down to the __block object if necessary.
00633     if (capturedByInit) {
00634       // We can use a simple GEP for this because it can't have been
00635       // moved yet.
00636       tempLV.setAddress(Builder.CreateStructGEP(tempLV.getAddress(),
00637                                    getByRefValueLLVMField(cast<VarDecl>(D))));
00638     }
00639 
00640     llvm::PointerType *ty
00641       = cast<llvm::PointerType>(tempLV.getAddress()->getType());
00642     ty = cast<llvm::PointerType>(ty->getElementType());
00643 
00644     llvm::Value *zero = llvm::ConstantPointerNull::get(ty);
00645 
00646     // If __weak, we want to use a barrier under certain conditions.
00647     if (lifetime == Qualifiers::OCL_Weak)
00648       EmitARCInitWeak(tempLV.getAddress(), zero);
00649 
00650     // Otherwise just do a simple store.
00651     else
00652       EmitStoreOfScalar(zero, tempLV, /* isInitialization */ true);
00653   }
00654 
00655   // Emit the initializer.
00656   llvm::Value *value = nullptr;
00657 
00658   switch (lifetime) {
00659   case Qualifiers::OCL_None:
00660     llvm_unreachable("present but none");
00661 
00662   case Qualifiers::OCL_ExplicitNone:
00663     // nothing to do
00664     value = EmitScalarExpr(init);
00665     break;
00666 
00667   case Qualifiers::OCL_Strong: {
00668     value = EmitARCRetainScalarExpr(init);
00669     break;
00670   }
00671 
00672   case Qualifiers::OCL_Weak: {
00673     // No way to optimize a producing initializer into this.  It's not
00674     // worth optimizing for, because the value will immediately
00675     // disappear in the common case.
00676     value = EmitScalarExpr(init);
00677 
00678     if (capturedByInit) drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D));
00679     if (accessedByInit)
00680       EmitARCStoreWeak(lvalue.getAddress(), value, /*ignored*/ true);
00681     else
00682       EmitARCInitWeak(lvalue.getAddress(), value);
00683     return;
00684   }
00685 
00686   case Qualifiers::OCL_Autoreleasing:
00687     value = EmitARCRetainAutoreleaseScalarExpr(init);
00688     break;
00689   }
00690 
00691   if (capturedByInit) drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D));
00692 
00693   // If the variable might have been accessed by its initializer, we
00694   // might have to initialize with a barrier.  We have to do this for
00695   // both __weak and __strong, but __weak got filtered out above.
00696   if (accessedByInit && lifetime == Qualifiers::OCL_Strong) {
00697     llvm::Value *oldValue = EmitLoadOfScalar(lvalue, init->getExprLoc());
00698     EmitStoreOfScalar(value, lvalue, /* isInitialization */ true);
00699     EmitARCRelease(oldValue, ARCImpreciseLifetime);
00700     return;
00701   }
00702 
00703   EmitStoreOfScalar(value, lvalue, /* isInitialization */ true);
00704 }
00705 
00706 /// EmitScalarInit - Initialize the given lvalue with the given object.
00707 void CodeGenFunction::EmitScalarInit(llvm::Value *init, LValue lvalue) {
00708   Qualifiers::ObjCLifetime lifetime = lvalue.getObjCLifetime();
00709   if (!lifetime)
00710     return EmitStoreThroughLValue(RValue::get(init), lvalue, true);
00711 
00712   switch (lifetime) {
00713   case Qualifiers::OCL_None:
00714     llvm_unreachable("present but none");
00715 
00716   case Qualifiers::OCL_ExplicitNone:
00717     // nothing to do
00718     break;
00719 
00720   case Qualifiers::OCL_Strong:
00721     init = EmitARCRetain(lvalue.getType(), init);
00722     break;
00723 
00724   case Qualifiers::OCL_Weak:
00725     // Initialize and then skip the primitive store.
00726     EmitARCInitWeak(lvalue.getAddress(), init);
00727     return;
00728 
00729   case Qualifiers::OCL_Autoreleasing:
00730     init = EmitARCRetainAutorelease(lvalue.getType(), init);
00731     break;
00732   }
00733 
00734   EmitStoreOfScalar(init, lvalue, /* isInitialization */ true);
00735 }
00736 
00737 /// canEmitInitWithFewStoresAfterMemset - Decide whether we can emit the
00738 /// non-zero parts of the specified initializer with equal or fewer than
00739 /// NumStores scalar stores.
00740 static bool canEmitInitWithFewStoresAfterMemset(llvm::Constant *Init,
00741                                                 unsigned &NumStores) {
00742   // Zero and Undef never requires any extra stores.
00743   if (isa<llvm::ConstantAggregateZero>(Init) ||
00744       isa<llvm::ConstantPointerNull>(Init) ||
00745       isa<llvm::UndefValue>(Init))
00746     return true;
00747   if (isa<llvm::ConstantInt>(Init) || isa<llvm::ConstantFP>(Init) ||
00748       isa<llvm::ConstantVector>(Init) || isa<llvm::BlockAddress>(Init) ||
00749       isa<llvm::ConstantExpr>(Init))
00750     return Init->isNullValue() || NumStores--;
00751 
00752   // See if we can emit each element.
00753   if (isa<llvm::ConstantArray>(Init) || isa<llvm::ConstantStruct>(Init)) {
00754     for (unsigned i = 0, e = Init->getNumOperands(); i != e; ++i) {
00755       llvm::Constant *Elt = cast<llvm::Constant>(Init->getOperand(i));
00756       if (!canEmitInitWithFewStoresAfterMemset(Elt, NumStores))
00757         return false;
00758     }
00759     return true;
00760   }
00761   
00762   if (llvm::ConstantDataSequential *CDS =
00763         dyn_cast<llvm::ConstantDataSequential>(Init)) {
00764     for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
00765       llvm::Constant *Elt = CDS->getElementAsConstant(i);
00766       if (!canEmitInitWithFewStoresAfterMemset(Elt, NumStores))
00767         return false;
00768     }
00769     return true;
00770   }
00771 
00772   // Anything else is hard and scary.
00773   return false;
00774 }
00775 
00776 /// emitStoresForInitAfterMemset - For inits that
00777 /// canEmitInitWithFewStoresAfterMemset returned true for, emit the scalar
00778 /// stores that would be required.
00779 static void emitStoresForInitAfterMemset(llvm::Constant *Init, llvm::Value *Loc,
00780                                          bool isVolatile, CGBuilderTy &Builder) {
00781   assert(!Init->isNullValue() && !isa<llvm::UndefValue>(Init) &&
00782          "called emitStoresForInitAfterMemset for zero or undef value.");
00783 
00784   if (isa<llvm::ConstantInt>(Init) || isa<llvm::ConstantFP>(Init) ||
00785       isa<llvm::ConstantVector>(Init) || isa<llvm::BlockAddress>(Init) ||
00786       isa<llvm::ConstantExpr>(Init)) {
00787     Builder.CreateStore(Init, Loc, isVolatile);
00788     return;
00789   }
00790   
00791   if (llvm::ConstantDataSequential *CDS = 
00792         dyn_cast<llvm::ConstantDataSequential>(Init)) {
00793     for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
00794       llvm::Constant *Elt = CDS->getElementAsConstant(i);
00795 
00796       // If necessary, get a pointer to the element and emit it.
00797       if (!Elt->isNullValue() && !isa<llvm::UndefValue>(Elt))
00798         emitStoresForInitAfterMemset(Elt, Builder.CreateConstGEP2_32(Loc, 0, i),
00799                                      isVolatile, Builder);
00800     }
00801     return;
00802   }
00803 
00804   assert((isa<llvm::ConstantStruct>(Init) || isa<llvm::ConstantArray>(Init)) &&
00805          "Unknown value type!");
00806 
00807   for (unsigned i = 0, e = Init->getNumOperands(); i != e; ++i) {
00808     llvm::Constant *Elt = cast<llvm::Constant>(Init->getOperand(i));
00809 
00810     // If necessary, get a pointer to the element and emit it.
00811     if (!Elt->isNullValue() && !isa<llvm::UndefValue>(Elt))
00812       emitStoresForInitAfterMemset(Elt, Builder.CreateConstGEP2_32(Loc, 0, i),
00813                                    isVolatile, Builder);
00814   }
00815 }
00816 
00817 
00818 /// shouldUseMemSetPlusStoresToInitialize - Decide whether we should use memset
00819 /// plus some stores to initialize a local variable instead of using a memcpy
00820 /// from a constant global.  It is beneficial to use memset if the global is all
00821 /// zeros, or mostly zeros and large.
00822 static bool shouldUseMemSetPlusStoresToInitialize(llvm::Constant *Init,
00823                                                   uint64_t GlobalSize) {
00824   // If a global is all zeros, always use a memset.
00825   if (isa<llvm::ConstantAggregateZero>(Init)) return true;
00826 
00827   // If a non-zero global is <= 32 bytes, always use a memcpy.  If it is large,
00828   // do it if it will require 6 or fewer scalar stores.
00829   // TODO: Should budget depends on the size?  Avoiding a large global warrants
00830   // plopping in more stores.
00831   unsigned StoreBudget = 6;
00832   uint64_t SizeLimit = 32;
00833 
00834   return GlobalSize > SizeLimit &&
00835          canEmitInitWithFewStoresAfterMemset(Init, StoreBudget);
00836 }
00837 
00838 /// Should we use the LLVM lifetime intrinsics for the given local variable?
00839 static bool shouldUseLifetimeMarkers(CodeGenFunction &CGF, const VarDecl &D,
00840                                      unsigned Size) {
00841   // For now, only in optimized builds.
00842   if (CGF.CGM.getCodeGenOpts().OptimizationLevel == 0)
00843     return false;
00844 
00845   // Limit the size of marked objects to 32 bytes. We don't want to increase
00846   // compile time by marking tiny objects.
00847   unsigned SizeThreshold = 32;
00848 
00849   return Size > SizeThreshold;
00850 }
00851 
00852 
00853 /// EmitAutoVarDecl - Emit code and set up an entry in LocalDeclMap for a
00854 /// variable declaration with auto, register, or no storage class specifier.
00855 /// These turn into simple stack objects, or GlobalValues depending on target.
00856 void CodeGenFunction::EmitAutoVarDecl(const VarDecl &D) {
00857   AutoVarEmission emission = EmitAutoVarAlloca(D);
00858   EmitAutoVarInit(emission);
00859   EmitAutoVarCleanups(emission);
00860 }
00861 
00862 /// EmitAutoVarAlloca - Emit the alloca and debug information for a
00863 /// local variable.  Does not emit initialization or destruction.
00864 CodeGenFunction::AutoVarEmission
00865 CodeGenFunction::EmitAutoVarAlloca(const VarDecl &D) {
00866   QualType Ty = D.getType();
00867 
00868   AutoVarEmission emission(D);
00869 
00870   bool isByRef = D.hasAttr<BlocksAttr>();
00871   emission.IsByRef = isByRef;
00872 
00873   CharUnits alignment = getContext().getDeclAlign(&D);
00874   emission.Alignment = alignment;
00875 
00876   // If the type is variably-modified, emit all the VLA sizes for it.
00877   if (Ty->isVariablyModifiedType())
00878     EmitVariablyModifiedType(Ty);
00879 
00880   llvm::Value *DeclPtr;
00881   if (Ty->isConstantSizeType()) {
00882     bool NRVO = getLangOpts().ElideConstructors &&
00883       D.isNRVOVariable();
00884 
00885     // If this value is an array or struct with a statically determinable
00886     // constant initializer, there are optimizations we can do.
00887     //
00888     // TODO: We should constant-evaluate the initializer of any variable,
00889     // as long as it is initialized by a constant expression. Currently,
00890     // isConstantInitializer produces wrong answers for structs with
00891     // reference or bitfield members, and a few other cases, and checking
00892     // for POD-ness protects us from some of these.
00893     if (D.getInit() && (Ty->isArrayType() || Ty->isRecordType()) &&
00894         (D.isConstexpr() ||
00895          ((Ty.isPODType(getContext()) ||
00896            getContext().getBaseElementType(Ty)->isObjCObjectPointerType()) &&
00897           D.getInit()->isConstantInitializer(getContext(), false)))) {
00898 
00899       // If the variable's a const type, and it's neither an NRVO
00900       // candidate nor a __block variable and has no mutable members,
00901       // emit it as a global instead.
00902       if (CGM.getCodeGenOpts().MergeAllConstants && !NRVO && !isByRef &&
00903           CGM.isTypeConstant(Ty, true)) {
00904         EmitStaticVarDecl(D, llvm::GlobalValue::InternalLinkage);
00905 
00906         emission.Address = nullptr; // signal this condition to later callbacks
00907         assert(emission.wasEmittedAsGlobal());
00908         return emission;
00909       }
00910 
00911       // Otherwise, tell the initialization code that we're in this case.
00912       emission.IsConstantAggregate = true;
00913     }
00914 
00915     // A normal fixed sized variable becomes an alloca in the entry block,
00916     // unless it's an NRVO variable.
00917     llvm::Type *LTy = ConvertTypeForMem(Ty);
00918 
00919     if (NRVO) {
00920       // The named return value optimization: allocate this variable in the
00921       // return slot, so that we can elide the copy when returning this
00922       // variable (C++0x [class.copy]p34).
00923       DeclPtr = ReturnValue;
00924 
00925       if (const RecordType *RecordTy = Ty->getAs<RecordType>()) {
00926         if (!cast<CXXRecordDecl>(RecordTy->getDecl())->hasTrivialDestructor()) {
00927           // Create a flag that is used to indicate when the NRVO was applied
00928           // to this variable. Set it to zero to indicate that NRVO was not
00929           // applied.
00930           llvm::Value *Zero = Builder.getFalse();
00931           llvm::Value *NRVOFlag = CreateTempAlloca(Zero->getType(), "nrvo");
00932           EnsureInsertPoint();
00933           Builder.CreateStore(Zero, NRVOFlag);
00934 
00935           // Record the NRVO flag for this variable.
00936           NRVOFlags[&D] = NRVOFlag;
00937           emission.NRVOFlag = NRVOFlag;
00938         }
00939       }
00940     } else {
00941       if (isByRef)
00942         LTy = BuildByRefType(&D);
00943 
00944       llvm::AllocaInst *Alloc = CreateTempAlloca(LTy);
00945       Alloc->setName(D.getName());
00946 
00947       CharUnits allocaAlignment = alignment;
00948       if (isByRef)
00949         allocaAlignment = std::max(allocaAlignment,
00950             getContext().toCharUnitsFromBits(getTarget().getPointerAlign(0)));
00951       Alloc->setAlignment(allocaAlignment.getQuantity());
00952       DeclPtr = Alloc;
00953 
00954       // Emit a lifetime intrinsic if meaningful.  There's no point
00955       // in doing this if we don't have a valid insertion point (?).
00956       uint64_t size = CGM.getDataLayout().getTypeAllocSize(LTy);
00957       if (HaveInsertPoint() && shouldUseLifetimeMarkers(*this, D, size)) {
00958         llvm::Value *sizeV = llvm::ConstantInt::get(Int64Ty, size);
00959 
00960         emission.SizeForLifetimeMarkers = sizeV;
00961         llvm::Value *castAddr = Builder.CreateBitCast(Alloc, Int8PtrTy);
00962         Builder.CreateCall2(CGM.getLLVMLifetimeStartFn(), sizeV, castAddr)
00963           ->setDoesNotThrow();
00964       } else {
00965         assert(!emission.useLifetimeMarkers());
00966       }
00967     }
00968   } else {
00969     EnsureInsertPoint();
00970 
00971     if (!DidCallStackSave) {
00972       // Save the stack.
00973       llvm::Value *Stack = CreateTempAlloca(Int8PtrTy, "saved_stack");
00974 
00975       llvm::Value *F = CGM.getIntrinsic(llvm::Intrinsic::stacksave);
00976       llvm::Value *V = Builder.CreateCall(F);
00977 
00978       Builder.CreateStore(V, Stack);
00979 
00980       DidCallStackSave = true;
00981 
00982       // Push a cleanup block and restore the stack there.
00983       // FIXME: in general circumstances, this should be an EH cleanup.
00984       pushStackRestore(NormalCleanup, Stack);
00985     }
00986 
00987     llvm::Value *elementCount;
00988     QualType elementType;
00989     std::tie(elementCount, elementType) = getVLASize(Ty);
00990 
00991     llvm::Type *llvmTy = ConvertTypeForMem(elementType);
00992 
00993     // Allocate memory for the array.
00994     llvm::AllocaInst *vla = Builder.CreateAlloca(llvmTy, elementCount, "vla");
00995     vla->setAlignment(alignment.getQuantity());
00996 
00997     DeclPtr = vla;
00998   }
00999 
01000   llvm::Value *&DMEntry = LocalDeclMap[&D];
01001   assert(!DMEntry && "Decl already exists in localdeclmap!");
01002   DMEntry = DeclPtr;
01003   emission.Address = DeclPtr;
01004 
01005   // Emit debug info for local var declaration.
01006   if (HaveInsertPoint())
01007     if (CGDebugInfo *DI = getDebugInfo()) {
01008       if (CGM.getCodeGenOpts().getDebugInfo()
01009             >= CodeGenOptions::LimitedDebugInfo) {
01010         DI->setLocation(D.getLocation());
01011         DI->EmitDeclareOfAutoVariable(&D, DeclPtr, Builder);
01012       }
01013     }
01014 
01015   if (D.hasAttr<AnnotateAttr>())
01016       EmitVarAnnotations(&D, emission.Address);
01017 
01018   return emission;
01019 }
01020 
01021 /// Determines whether the given __block variable is potentially
01022 /// captured by the given expression.
01023 static bool isCapturedBy(const VarDecl &var, const Expr *e) {
01024   // Skip the most common kinds of expressions that make
01025   // hierarchy-walking expensive.
01026   e = e->IgnoreParenCasts();
01027 
01028   if (const BlockExpr *be = dyn_cast<BlockExpr>(e)) {
01029     const BlockDecl *block = be->getBlockDecl();
01030     for (const auto &I : block->captures()) {
01031       if (I.getVariable() == &var)
01032         return true;
01033     }
01034 
01035     // No need to walk into the subexpressions.
01036     return false;
01037   }
01038 
01039   if (const StmtExpr *SE = dyn_cast<StmtExpr>(e)) {
01040     const CompoundStmt *CS = SE->getSubStmt();
01041     for (const auto *BI : CS->body())
01042       if (const auto *E = dyn_cast<Expr>(BI)) {
01043         if (isCapturedBy(var, E))
01044             return true;
01045       }
01046       else if (const auto *DS = dyn_cast<DeclStmt>(BI)) {
01047           // special case declarations
01048           for (const auto *I : DS->decls()) {
01049               if (const auto *VD = dyn_cast<VarDecl>((I))) {
01050                 const Expr *Init = VD->getInit();
01051                 if (Init && isCapturedBy(var, Init))
01052                   return true;
01053               }
01054           }
01055       }
01056       else
01057         // FIXME. Make safe assumption assuming arbitrary statements cause capturing.
01058         // Later, provide code to poke into statements for capture analysis.
01059         return true;
01060     return false;
01061   }
01062 
01063   for (Stmt::const_child_range children = e->children(); children; ++children)
01064     if (isCapturedBy(var, cast<Expr>(*children)))
01065       return true;
01066 
01067   return false;
01068 }
01069 
01070 /// \brief Determine whether the given initializer is trivial in the sense
01071 /// that it requires no code to be generated.
01072 bool CodeGenFunction::isTrivialInitializer(const Expr *Init) {
01073   if (!Init)
01074     return true;
01075 
01076   if (const CXXConstructExpr *Construct = dyn_cast<CXXConstructExpr>(Init))
01077     if (CXXConstructorDecl *Constructor = Construct->getConstructor())
01078       if (Constructor->isTrivial() &&
01079           Constructor->isDefaultConstructor() &&
01080           !Construct->requiresZeroInitialization())
01081         return true;
01082 
01083   return false;
01084 }
01085 void CodeGenFunction::EmitAutoVarInit(const AutoVarEmission &emission) {
01086   assert(emission.Variable && "emission was not valid!");
01087 
01088   // If this was emitted as a global constant, we're done.
01089   if (emission.wasEmittedAsGlobal()) return;
01090 
01091   const VarDecl &D = *emission.Variable;
01092   QualType type = D.getType();
01093 
01094   // If this local has an initializer, emit it now.
01095   const Expr *Init = D.getInit();
01096 
01097   // If we are at an unreachable point, we don't need to emit the initializer
01098   // unless it contains a label.
01099   if (!HaveInsertPoint()) {
01100     if (!Init || !ContainsLabel(Init)) return;
01101     EnsureInsertPoint();
01102   }
01103 
01104   // Initialize the structure of a __block variable.
01105   if (emission.IsByRef)
01106     emitByrefStructureInit(emission);
01107 
01108   if (isTrivialInitializer(Init))
01109     return;
01110 
01111   CharUnits alignment = emission.Alignment;
01112 
01113   // Check whether this is a byref variable that's potentially
01114   // captured and moved by its own initializer.  If so, we'll need to
01115   // emit the initializer first, then copy into the variable.
01116   bool capturedByInit = emission.IsByRef && isCapturedBy(D, Init);
01117 
01118   llvm::Value *Loc =
01119     capturedByInit ? emission.Address : emission.getObjectAddress(*this);
01120 
01121   llvm::Constant *constant = nullptr;
01122   if (emission.IsConstantAggregate || D.isConstexpr()) {
01123     assert(!capturedByInit && "constant init contains a capturing block?");
01124     constant = CGM.EmitConstantInit(D, this);
01125   }
01126 
01127   if (!constant) {
01128     LValue lv = MakeAddrLValue(Loc, type, alignment);
01129     lv.setNonGC(true);
01130     return EmitExprAsInit(Init, &D, lv, capturedByInit);
01131   }
01132 
01133   if (!emission.IsConstantAggregate) {
01134     // For simple scalar/complex initialization, store the value directly.
01135     LValue lv = MakeAddrLValue(Loc, type, alignment);
01136     lv.setNonGC(true);
01137     return EmitStoreThroughLValue(RValue::get(constant), lv, true);
01138   }
01139 
01140   // If this is a simple aggregate initialization, we can optimize it
01141   // in various ways.
01142   bool isVolatile = type.isVolatileQualified();
01143 
01144   llvm::Value *SizeVal =
01145     llvm::ConstantInt::get(IntPtrTy,
01146                            getContext().getTypeSizeInChars(type).getQuantity());
01147 
01148   llvm::Type *BP = Int8PtrTy;
01149   if (Loc->getType() != BP)
01150     Loc = Builder.CreateBitCast(Loc, BP);
01151 
01152   // If the initializer is all or mostly zeros, codegen with memset then do
01153   // a few stores afterward.
01154   if (shouldUseMemSetPlusStoresToInitialize(constant,
01155                 CGM.getDataLayout().getTypeAllocSize(constant->getType()))) {
01156     Builder.CreateMemSet(Loc, llvm::ConstantInt::get(Int8Ty, 0), SizeVal,
01157                          alignment.getQuantity(), isVolatile);
01158     // Zero and undef don't require a stores.
01159     if (!constant->isNullValue() && !isa<llvm::UndefValue>(constant)) {
01160       Loc = Builder.CreateBitCast(Loc, constant->getType()->getPointerTo());
01161       emitStoresForInitAfterMemset(constant, Loc, isVolatile, Builder);
01162     }
01163   } else {
01164     // Otherwise, create a temporary global with the initializer then
01165     // memcpy from the global to the alloca.
01166     std::string Name = getStaticDeclName(CGM, D);
01167     llvm::GlobalVariable *GV =
01168       new llvm::GlobalVariable(CGM.getModule(), constant->getType(), true,
01169                                llvm::GlobalValue::PrivateLinkage,
01170                                constant, Name);
01171     GV->setAlignment(alignment.getQuantity());
01172     GV->setUnnamedAddr(true);
01173 
01174     llvm::Value *SrcPtr = GV;
01175     if (SrcPtr->getType() != BP)
01176       SrcPtr = Builder.CreateBitCast(SrcPtr, BP);
01177 
01178     Builder.CreateMemCpy(Loc, SrcPtr, SizeVal, alignment.getQuantity(),
01179                          isVolatile);
01180   }
01181 }
01182 
01183 /// Emit an expression as an initializer for a variable at the given
01184 /// location.  The expression is not necessarily the normal
01185 /// initializer for the variable, and the address is not necessarily
01186 /// its normal location.
01187 ///
01188 /// \param init the initializing expression
01189 /// \param var the variable to act as if we're initializing
01190 /// \param loc the address to initialize; its type is a pointer
01191 ///   to the LLVM mapping of the variable's type
01192 /// \param alignment the alignment of the address
01193 /// \param capturedByInit true if the variable is a __block variable
01194 ///   whose address is potentially changed by the initializer
01195 void CodeGenFunction::EmitExprAsInit(const Expr *init,
01196                                      const ValueDecl *D,
01197                                      LValue lvalue,
01198                                      bool capturedByInit) {
01199   QualType type = D->getType();
01200 
01201   if (type->isReferenceType()) {
01202     RValue rvalue = EmitReferenceBindingToExpr(init);
01203     if (capturedByInit)
01204       drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D));
01205     EmitStoreThroughLValue(rvalue, lvalue, true);
01206     return;
01207   }
01208   switch (getEvaluationKind(type)) {
01209   case TEK_Scalar:
01210     EmitScalarInit(init, D, lvalue, capturedByInit);
01211     return;
01212   case TEK_Complex: {
01213     ComplexPairTy complex = EmitComplexExpr(init);
01214     if (capturedByInit)
01215       drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D));
01216     EmitStoreOfComplex(complex, lvalue, /*init*/ true);
01217     return;
01218   }
01219   case TEK_Aggregate:
01220     if (type->isAtomicType()) {
01221       EmitAtomicInit(const_cast<Expr*>(init), lvalue);
01222     } else {
01223       // TODO: how can we delay here if D is captured by its initializer?
01224       EmitAggExpr(init, AggValueSlot::forLValue(lvalue,
01225                                               AggValueSlot::IsDestructed,
01226                                          AggValueSlot::DoesNotNeedGCBarriers,
01227                                               AggValueSlot::IsNotAliased));
01228     }
01229     return;
01230   }
01231   llvm_unreachable("bad evaluation kind");
01232 }
01233 
01234 /// Enter a destroy cleanup for the given local variable.
01235 void CodeGenFunction::emitAutoVarTypeCleanup(
01236                             const CodeGenFunction::AutoVarEmission &emission,
01237                             QualType::DestructionKind dtorKind) {
01238   assert(dtorKind != QualType::DK_none);
01239 
01240   // Note that for __block variables, we want to destroy the
01241   // original stack object, not the possibly forwarded object.
01242   llvm::Value *addr = emission.getObjectAddress(*this);
01243 
01244   const VarDecl *var = emission.Variable;
01245   QualType type = var->getType();
01246 
01247   CleanupKind cleanupKind = NormalAndEHCleanup;
01248   CodeGenFunction::Destroyer *destroyer = nullptr;
01249 
01250   switch (dtorKind) {
01251   case QualType::DK_none:
01252     llvm_unreachable("no cleanup for trivially-destructible variable");
01253 
01254   case QualType::DK_cxx_destructor:
01255     // If there's an NRVO flag on the emission, we need a different
01256     // cleanup.
01257     if (emission.NRVOFlag) {
01258       assert(!type->isArrayType());
01259       CXXDestructorDecl *dtor = type->getAsCXXRecordDecl()->getDestructor();
01260       EHStack.pushCleanup<DestroyNRVOVariable>(cleanupKind, addr, dtor,
01261                                                emission.NRVOFlag);
01262       return;
01263     }
01264     break;
01265 
01266   case QualType::DK_objc_strong_lifetime:
01267     // Suppress cleanups for pseudo-strong variables.
01268     if (var->isARCPseudoStrong()) return;
01269 
01270     // Otherwise, consider whether to use an EH cleanup or not.
01271     cleanupKind = getARCCleanupKind();
01272 
01273     // Use the imprecise destroyer by default.
01274     if (!var->hasAttr<ObjCPreciseLifetimeAttr>())
01275       destroyer = CodeGenFunction::destroyARCStrongImprecise;
01276     break;
01277 
01278   case QualType::DK_objc_weak_lifetime:
01279     break;
01280   }
01281 
01282   // If we haven't chosen a more specific destroyer, use the default.
01283   if (!destroyer) destroyer = getDestroyer(dtorKind);
01284 
01285   // Use an EH cleanup in array destructors iff the destructor itself
01286   // is being pushed as an EH cleanup.
01287   bool useEHCleanup = (cleanupKind & EHCleanup);
01288   EHStack.pushCleanup<DestroyObject>(cleanupKind, addr, type, destroyer,
01289                                      useEHCleanup);
01290 }
01291 
01292 void CodeGenFunction::EmitAutoVarCleanups(const AutoVarEmission &emission) {
01293   assert(emission.Variable && "emission was not valid!");
01294 
01295   // If this was emitted as a global constant, we're done.
01296   if (emission.wasEmittedAsGlobal()) return;
01297 
01298   // If we don't have an insertion point, we're done.  Sema prevents
01299   // us from jumping into any of these scopes anyway.
01300   if (!HaveInsertPoint()) return;
01301 
01302   const VarDecl &D = *emission.Variable;
01303 
01304   // Make sure we call @llvm.lifetime.end.  This needs to happen
01305   // *last*, so the cleanup needs to be pushed *first*.
01306   if (emission.useLifetimeMarkers()) {
01307     EHStack.pushCleanup<CallLifetimeEnd>(NormalCleanup,
01308                                          emission.getAllocatedAddress(),
01309                                          emission.getSizeForLifetimeMarkers());
01310   }
01311 
01312   // Check the type for a cleanup.
01313   if (QualType::DestructionKind dtorKind = D.getType().isDestructedType())
01314     emitAutoVarTypeCleanup(emission, dtorKind);
01315 
01316   // In GC mode, honor objc_precise_lifetime.
01317   if (getLangOpts().getGC() != LangOptions::NonGC &&
01318       D.hasAttr<ObjCPreciseLifetimeAttr>()) {
01319     EHStack.pushCleanup<ExtendGCLifetime>(NormalCleanup, &D);
01320   }
01321 
01322   // Handle the cleanup attribute.
01323   if (const CleanupAttr *CA = D.getAttr<CleanupAttr>()) {
01324     const FunctionDecl *FD = CA->getFunctionDecl();
01325 
01326     llvm::Constant *F = CGM.GetAddrOfFunction(FD);
01327     assert(F && "Could not find function!");
01328 
01329     const CGFunctionInfo &Info = CGM.getTypes().arrangeFunctionDeclaration(FD);
01330     EHStack.pushCleanup<CallCleanupFunction>(NormalAndEHCleanup, F, &Info, &D);
01331   }
01332 
01333   // If this is a block variable, call _Block_object_destroy
01334   // (on the unforwarded address).
01335   if (emission.IsByRef)
01336     enterByrefCleanup(emission);
01337 }
01338 
01339 CodeGenFunction::Destroyer *
01340 CodeGenFunction::getDestroyer(QualType::DestructionKind kind) {
01341   switch (kind) {
01342   case QualType::DK_none: llvm_unreachable("no destroyer for trivial dtor");
01343   case QualType::DK_cxx_destructor:
01344     return destroyCXXObject;
01345   case QualType::DK_objc_strong_lifetime:
01346     return destroyARCStrongPrecise;
01347   case QualType::DK_objc_weak_lifetime:
01348     return destroyARCWeak;
01349   }
01350   llvm_unreachable("Unknown DestructionKind");
01351 }
01352 
01353 /// pushEHDestroy - Push the standard destructor for the given type as
01354 /// an EH-only cleanup.
01355 void CodeGenFunction::pushEHDestroy(QualType::DestructionKind dtorKind,
01356                                   llvm::Value *addr, QualType type) {
01357   assert(dtorKind && "cannot push destructor for trivial type");
01358   assert(needsEHCleanup(dtorKind));
01359 
01360   pushDestroy(EHCleanup, addr, type, getDestroyer(dtorKind), true);
01361 }
01362 
01363 /// pushDestroy - Push the standard destructor for the given type as
01364 /// at least a normal cleanup.
01365 void CodeGenFunction::pushDestroy(QualType::DestructionKind dtorKind,
01366                                   llvm::Value *addr, QualType type) {
01367   assert(dtorKind && "cannot push destructor for trivial type");
01368 
01369   CleanupKind cleanupKind = getCleanupKind(dtorKind);
01370   pushDestroy(cleanupKind, addr, type, getDestroyer(dtorKind),
01371               cleanupKind & EHCleanup);
01372 }
01373 
01374 void CodeGenFunction::pushDestroy(CleanupKind cleanupKind, llvm::Value *addr,
01375                                   QualType type, Destroyer *destroyer,
01376                                   bool useEHCleanupForArray) {
01377   pushFullExprCleanup<DestroyObject>(cleanupKind, addr, type,
01378                                      destroyer, useEHCleanupForArray);
01379 }
01380 
01381 void CodeGenFunction::pushStackRestore(CleanupKind Kind, llvm::Value *SPMem) {
01382   EHStack.pushCleanup<CallStackRestore>(Kind, SPMem);
01383 }
01384 
01385 void CodeGenFunction::pushLifetimeExtendedDestroy(
01386     CleanupKind cleanupKind, llvm::Value *addr, QualType type,
01387     Destroyer *destroyer, bool useEHCleanupForArray) {
01388   assert(!isInConditionalBranch() &&
01389          "performing lifetime extension from within conditional");
01390 
01391   // Push an EH-only cleanup for the object now.
01392   // FIXME: When popping normal cleanups, we need to keep this EH cleanup
01393   // around in case a temporary's destructor throws an exception.
01394   if (cleanupKind & EHCleanup)
01395     EHStack.pushCleanup<DestroyObject>(
01396         static_cast<CleanupKind>(cleanupKind & ~NormalCleanup), addr, type,
01397         destroyer, useEHCleanupForArray);
01398 
01399   // Remember that we need to push a full cleanup for the object at the
01400   // end of the full-expression.
01401   pushCleanupAfterFullExpr<DestroyObject>(
01402       cleanupKind, addr, type, destroyer, useEHCleanupForArray);
01403 }
01404 
01405 /// emitDestroy - Immediately perform the destruction of the given
01406 /// object.
01407 ///
01408 /// \param addr - the address of the object; a type*
01409 /// \param type - the type of the object; if an array type, all
01410 ///   objects are destroyed in reverse order
01411 /// \param destroyer - the function to call to destroy individual
01412 ///   elements
01413 /// \param useEHCleanupForArray - whether an EH cleanup should be
01414 ///   used when destroying array elements, in case one of the
01415 ///   destructions throws an exception
01416 void CodeGenFunction::emitDestroy(llvm::Value *addr, QualType type,
01417                                   Destroyer *destroyer,
01418                                   bool useEHCleanupForArray) {
01419   const ArrayType *arrayType = getContext().getAsArrayType(type);
01420   if (!arrayType)
01421     return destroyer(*this, addr, type);
01422 
01423   llvm::Value *begin = addr;
01424   llvm::Value *length = emitArrayLength(arrayType, type, begin);
01425 
01426   // Normally we have to check whether the array is zero-length.
01427   bool checkZeroLength = true;
01428 
01429   // But if the array length is constant, we can suppress that.
01430   if (llvm::ConstantInt *constLength = dyn_cast<llvm::ConstantInt>(length)) {
01431     // ...and if it's constant zero, we can just skip the entire thing.
01432     if (constLength->isZero()) return;
01433     checkZeroLength = false;
01434   }
01435 
01436   llvm::Value *end = Builder.CreateInBoundsGEP(begin, length);
01437   emitArrayDestroy(begin, end, type, destroyer,
01438                    checkZeroLength, useEHCleanupForArray);
01439 }
01440 
01441 /// emitArrayDestroy - Destroys all the elements of the given array,
01442 /// beginning from last to first.  The array cannot be zero-length.
01443 ///
01444 /// \param begin - a type* denoting the first element of the array
01445 /// \param end - a type* denoting one past the end of the array
01446 /// \param type - the element type of the array
01447 /// \param destroyer - the function to call to destroy elements
01448 /// \param useEHCleanup - whether to push an EH cleanup to destroy
01449 ///   the remaining elements in case the destruction of a single
01450 ///   element throws
01451 void CodeGenFunction::emitArrayDestroy(llvm::Value *begin,
01452                                        llvm::Value *end,
01453                                        QualType type,
01454                                        Destroyer *destroyer,
01455                                        bool checkZeroLength,
01456                                        bool useEHCleanup) {
01457   assert(!type->isArrayType());
01458 
01459   // The basic structure here is a do-while loop, because we don't
01460   // need to check for the zero-element case.
01461   llvm::BasicBlock *bodyBB = createBasicBlock("arraydestroy.body");
01462   llvm::BasicBlock *doneBB = createBasicBlock("arraydestroy.done");
01463 
01464   if (checkZeroLength) {
01465     llvm::Value *isEmpty = Builder.CreateICmpEQ(begin, end,
01466                                                 "arraydestroy.isempty");
01467     Builder.CreateCondBr(isEmpty, doneBB, bodyBB);
01468   }
01469 
01470   // Enter the loop body, making that address the current address.
01471   llvm::BasicBlock *entryBB = Builder.GetInsertBlock();
01472   EmitBlock(bodyBB);
01473   llvm::PHINode *elementPast =
01474     Builder.CreatePHI(begin->getType(), 2, "arraydestroy.elementPast");
01475   elementPast->addIncoming(end, entryBB);
01476 
01477   // Shift the address back by one element.
01478   llvm::Value *negativeOne = llvm::ConstantInt::get(SizeTy, -1, true);
01479   llvm::Value *element = Builder.CreateInBoundsGEP(elementPast, negativeOne,
01480                                                    "arraydestroy.element");
01481 
01482   if (useEHCleanup)
01483     pushRegularPartialArrayCleanup(begin, element, type, destroyer);
01484 
01485   // Perform the actual destruction there.
01486   destroyer(*this, element, type);
01487 
01488   if (useEHCleanup)
01489     PopCleanupBlock();
01490 
01491   // Check whether we've reached the end.
01492   llvm::Value *done = Builder.CreateICmpEQ(element, begin, "arraydestroy.done");
01493   Builder.CreateCondBr(done, doneBB, bodyBB);
01494   elementPast->addIncoming(element, Builder.GetInsertBlock());
01495 
01496   // Done.
01497   EmitBlock(doneBB);
01498 }
01499 
01500 /// Perform partial array destruction as if in an EH cleanup.  Unlike
01501 /// emitArrayDestroy, the element type here may still be an array type.
01502 static void emitPartialArrayDestroy(CodeGenFunction &CGF,
01503                                     llvm::Value *begin, llvm::Value *end,
01504                                     QualType type,
01505                                     CodeGenFunction::Destroyer *destroyer) {
01506   // If the element type is itself an array, drill down.
01507   unsigned arrayDepth = 0;
01508   while (const ArrayType *arrayType = CGF.getContext().getAsArrayType(type)) {
01509     // VLAs don't require a GEP index to walk into.
01510     if (!isa<VariableArrayType>(arrayType))
01511       arrayDepth++;
01512     type = arrayType->getElementType();
01513   }
01514 
01515   if (arrayDepth) {
01516     llvm::Value *zero = llvm::ConstantInt::get(CGF.SizeTy, arrayDepth+1);
01517 
01518     SmallVector<llvm::Value*,4> gepIndices(arrayDepth, zero);
01519     begin = CGF.Builder.CreateInBoundsGEP(begin, gepIndices, "pad.arraybegin");
01520     end = CGF.Builder.CreateInBoundsGEP(end, gepIndices, "pad.arrayend");
01521   }
01522 
01523   // Destroy the array.  We don't ever need an EH cleanup because we
01524   // assume that we're in an EH cleanup ourselves, so a throwing
01525   // destructor causes an immediate terminate.
01526   CGF.emitArrayDestroy(begin, end, type, destroyer,
01527                        /*checkZeroLength*/ true, /*useEHCleanup*/ false);
01528 }
01529 
01530 namespace {
01531   /// RegularPartialArrayDestroy - a cleanup which performs a partial
01532   /// array destroy where the end pointer is regularly determined and
01533   /// does not need to be loaded from a local.
01534   class RegularPartialArrayDestroy : public EHScopeStack::Cleanup {
01535     llvm::Value *ArrayBegin;
01536     llvm::Value *ArrayEnd;
01537     QualType ElementType;
01538     CodeGenFunction::Destroyer *Destroyer;
01539   public:
01540     RegularPartialArrayDestroy(llvm::Value *arrayBegin, llvm::Value *arrayEnd,
01541                                QualType elementType,
01542                                CodeGenFunction::Destroyer *destroyer)
01543       : ArrayBegin(arrayBegin), ArrayEnd(arrayEnd),
01544         ElementType(elementType), Destroyer(destroyer) {}
01545 
01546     void Emit(CodeGenFunction &CGF, Flags flags) override {
01547       emitPartialArrayDestroy(CGF, ArrayBegin, ArrayEnd,
01548                               ElementType, Destroyer);
01549     }
01550   };
01551 
01552   /// IrregularPartialArrayDestroy - a cleanup which performs a
01553   /// partial array destroy where the end pointer is irregularly
01554   /// determined and must be loaded from a local.
01555   class IrregularPartialArrayDestroy : public EHScopeStack::Cleanup {
01556     llvm::Value *ArrayBegin;
01557     llvm::Value *ArrayEndPointer;
01558     QualType ElementType;
01559     CodeGenFunction::Destroyer *Destroyer;
01560   public:
01561     IrregularPartialArrayDestroy(llvm::Value *arrayBegin,
01562                                  llvm::Value *arrayEndPointer,
01563                                  QualType elementType,
01564                                  CodeGenFunction::Destroyer *destroyer)
01565       : ArrayBegin(arrayBegin), ArrayEndPointer(arrayEndPointer),
01566         ElementType(elementType), Destroyer(destroyer) {}
01567 
01568     void Emit(CodeGenFunction &CGF, Flags flags) override {
01569       llvm::Value *arrayEnd = CGF.Builder.CreateLoad(ArrayEndPointer);
01570       emitPartialArrayDestroy(CGF, ArrayBegin, arrayEnd,
01571                               ElementType, Destroyer);
01572     }
01573   };
01574 }
01575 
01576 /// pushIrregularPartialArrayCleanup - Push an EH cleanup to destroy
01577 /// already-constructed elements of the given array.  The cleanup
01578 /// may be popped with DeactivateCleanupBlock or PopCleanupBlock.
01579 ///
01580 /// \param elementType - the immediate element type of the array;
01581 ///   possibly still an array type
01582 void CodeGenFunction::pushIrregularPartialArrayCleanup(llvm::Value *arrayBegin,
01583                                                  llvm::Value *arrayEndPointer,
01584                                                        QualType elementType,
01585                                                        Destroyer *destroyer) {
01586   pushFullExprCleanup<IrregularPartialArrayDestroy>(EHCleanup,
01587                                                     arrayBegin, arrayEndPointer,
01588                                                     elementType, destroyer);
01589 }
01590 
01591 /// pushRegularPartialArrayCleanup - Push an EH cleanup to destroy
01592 /// already-constructed elements of the given array.  The cleanup
01593 /// may be popped with DeactivateCleanupBlock or PopCleanupBlock.
01594 ///
01595 /// \param elementType - the immediate element type of the array;
01596 ///   possibly still an array type
01597 void CodeGenFunction::pushRegularPartialArrayCleanup(llvm::Value *arrayBegin,
01598                                                      llvm::Value *arrayEnd,
01599                                                      QualType elementType,
01600                                                      Destroyer *destroyer) {
01601   pushFullExprCleanup<RegularPartialArrayDestroy>(EHCleanup,
01602                                                   arrayBegin, arrayEnd,
01603                                                   elementType, destroyer);
01604 }
01605 
01606 /// Lazily declare the @llvm.lifetime.start intrinsic.
01607 llvm::Constant *CodeGenModule::getLLVMLifetimeStartFn() {
01608   if (LifetimeStartFn) return LifetimeStartFn;
01609   LifetimeStartFn = llvm::Intrinsic::getDeclaration(&getModule(),
01610                                             llvm::Intrinsic::lifetime_start);
01611   return LifetimeStartFn;
01612 }
01613 
01614 /// Lazily declare the @llvm.lifetime.end intrinsic.
01615 llvm::Constant *CodeGenModule::getLLVMLifetimeEndFn() {
01616   if (LifetimeEndFn) return LifetimeEndFn;
01617   LifetimeEndFn = llvm::Intrinsic::getDeclaration(&getModule(),
01618                                               llvm::Intrinsic::lifetime_end);
01619   return LifetimeEndFn;
01620 }
01621 
01622 namespace {
01623   /// A cleanup to perform a release of an object at the end of a
01624   /// function.  This is used to balance out the incoming +1 of a
01625   /// ns_consumed argument when we can't reasonably do that just by
01626   /// not doing the initial retain for a __block argument.
01627   struct ConsumeARCParameter : EHScopeStack::Cleanup {
01628     ConsumeARCParameter(llvm::Value *param,
01629                         ARCPreciseLifetime_t precise)
01630       : Param(param), Precise(precise) {}
01631 
01632     llvm::Value *Param;
01633     ARCPreciseLifetime_t Precise;
01634 
01635     void Emit(CodeGenFunction &CGF, Flags flags) override {
01636       CGF.EmitARCRelease(Param, Precise);
01637     }
01638   };
01639 }
01640 
01641 /// Emit an alloca (or GlobalValue depending on target)
01642 /// for the specified parameter and set up LocalDeclMap.
01643 void CodeGenFunction::EmitParmDecl(const VarDecl &D, llvm::Value *Arg,
01644                                    bool ArgIsPointer, unsigned ArgNo) {
01645   // FIXME: Why isn't ImplicitParamDecl a ParmVarDecl?
01646   assert((isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D)) &&
01647          "Invalid argument to EmitParmDecl");
01648 
01649   Arg->setName(D.getName());
01650 
01651   QualType Ty = D.getType();
01652 
01653   // Use better IR generation for certain implicit parameters.
01654   if (isa<ImplicitParamDecl>(D)) {
01655     // The only implicit argument a block has is its literal.
01656     if (BlockInfo) {
01657       LocalDeclMap[&D] = Arg;
01658       llvm::Value *LocalAddr = nullptr;
01659       if (CGM.getCodeGenOpts().OptimizationLevel == 0) {
01660         // Allocate a stack slot to let the debug info survive the RA.
01661         llvm::AllocaInst *Alloc = CreateTempAlloca(ConvertTypeForMem(Ty),
01662                                                    D.getName() + ".addr");
01663         Alloc->setAlignment(getContext().getDeclAlign(&D).getQuantity());
01664         LValue lv = MakeAddrLValue(Alloc, Ty, getContext().getDeclAlign(&D));
01665         EmitStoreOfScalar(Arg, lv, /* isInitialization */ true);
01666         LocalAddr = Builder.CreateLoad(Alloc);
01667       }
01668 
01669       if (CGDebugInfo *DI = getDebugInfo()) {
01670         if (CGM.getCodeGenOpts().getDebugInfo()
01671               >= CodeGenOptions::LimitedDebugInfo) {
01672           DI->setLocation(D.getLocation());
01673           DI->EmitDeclareOfBlockLiteralArgVariable(*BlockInfo, Arg, ArgNo,
01674                                                    LocalAddr, Builder);
01675         }
01676       }
01677 
01678       return;
01679     }
01680   }
01681 
01682   llvm::Value *DeclPtr;
01683   bool DoStore = false;
01684   bool IsScalar = hasScalarEvaluationKind(Ty);
01685   CharUnits Align = getContext().getDeclAlign(&D);
01686   // If we already have a pointer to the argument, reuse the input pointer.
01687   if (ArgIsPointer) {
01688     // If we have a prettier pointer type at this point, bitcast to that.
01689     unsigned AS = cast<llvm::PointerType>(Arg->getType())->getAddressSpace();
01690     llvm::Type *IRTy = ConvertTypeForMem(Ty)->getPointerTo(AS);
01691     DeclPtr = Arg->getType() == IRTy ? Arg : Builder.CreateBitCast(Arg, IRTy,
01692                                                                    D.getName());
01693     // Push a destructor cleanup for this parameter if the ABI requires it.
01694     // Don't push a cleanup in a thunk for a method that will also emit a
01695     // cleanup.
01696     if (!IsScalar && !CurFuncIsThunk &&
01697         getTarget().getCXXABI().areArgsDestroyedLeftToRightInCallee()) {
01698       const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
01699       if (RD && RD->hasNonTrivialDestructor())
01700         pushDestroy(QualType::DK_cxx_destructor, DeclPtr, Ty);
01701     }
01702   } else {
01703     // Otherwise, create a temporary to hold the value.
01704     llvm::AllocaInst *Alloc = CreateTempAlloca(ConvertTypeForMem(Ty),
01705                                                D.getName() + ".addr");
01706     Alloc->setAlignment(Align.getQuantity());
01707     DeclPtr = Alloc;
01708     DoStore = true;
01709   }
01710 
01711   LValue lv = MakeAddrLValue(DeclPtr, Ty, Align);
01712   if (IsScalar) {
01713     Qualifiers qs = Ty.getQualifiers();
01714     if (Qualifiers::ObjCLifetime lt = qs.getObjCLifetime()) {
01715       // We honor __attribute__((ns_consumed)) for types with lifetime.
01716       // For __strong, it's handled by just skipping the initial retain;
01717       // otherwise we have to balance out the initial +1 with an extra
01718       // cleanup to do the release at the end of the function.
01719       bool isConsumed = D.hasAttr<NSConsumedAttr>();
01720 
01721       // 'self' is always formally __strong, but if this is not an
01722       // init method then we don't want to retain it.
01723       if (D.isARCPseudoStrong()) {
01724         const ObjCMethodDecl *method = cast<ObjCMethodDecl>(CurCodeDecl);
01725         assert(&D == method->getSelfDecl());
01726         assert(lt == Qualifiers::OCL_Strong);
01727         assert(qs.hasConst());
01728         assert(method->getMethodFamily() != OMF_init);
01729         (void) method;
01730         lt = Qualifiers::OCL_ExplicitNone;
01731       }
01732 
01733       if (lt == Qualifiers::OCL_Strong) {
01734         if (!isConsumed) {
01735           if (CGM.getCodeGenOpts().OptimizationLevel == 0) {
01736             // use objc_storeStrong(&dest, value) for retaining the
01737             // object. But first, store a null into 'dest' because
01738             // objc_storeStrong attempts to release its old value.
01739             llvm::Value *Null = CGM.EmitNullConstant(D.getType());
01740             EmitStoreOfScalar(Null, lv, /* isInitialization */ true);
01741             EmitARCStoreStrongCall(lv.getAddress(), Arg, true);
01742             DoStore = false;
01743           }
01744           else
01745           // Don't use objc_retainBlock for block pointers, because we
01746           // don't want to Block_copy something just because we got it
01747           // as a parameter.
01748             Arg = EmitARCRetainNonBlock(Arg);
01749         }
01750       } else {
01751         // Push the cleanup for a consumed parameter.
01752         if (isConsumed) {
01753           ARCPreciseLifetime_t precise = (D.hasAttr<ObjCPreciseLifetimeAttr>()
01754                                 ? ARCPreciseLifetime : ARCImpreciseLifetime);
01755           EHStack.pushCleanup<ConsumeARCParameter>(getARCCleanupKind(), Arg,
01756                                                    precise);
01757         }
01758 
01759         if (lt == Qualifiers::OCL_Weak) {
01760           EmitARCInitWeak(DeclPtr, Arg);
01761           DoStore = false; // The weak init is a store, no need to do two.
01762         }
01763       }
01764 
01765       // Enter the cleanup scope.
01766       EmitAutoVarWithLifetime(*this, D, DeclPtr, lt);
01767     }
01768   }
01769 
01770   // Store the initial value into the alloca.
01771   if (DoStore)
01772     EmitStoreOfScalar(Arg, lv, /* isInitialization */ true);
01773 
01774   llvm::Value *&DMEntry = LocalDeclMap[&D];
01775   assert(!DMEntry && "Decl already exists in localdeclmap!");
01776   DMEntry = DeclPtr;
01777 
01778   // Emit debug info for param declaration.
01779   if (CGDebugInfo *DI = getDebugInfo()) {
01780     if (CGM.getCodeGenOpts().getDebugInfo()
01781           >= CodeGenOptions::LimitedDebugInfo) {
01782       DI->EmitDeclareOfArgVariable(&D, DeclPtr, ArgNo, Builder);
01783     }
01784   }
01785 
01786   if (D.hasAttr<AnnotateAttr>())
01787       EmitVarAnnotations(&D, DeclPtr);
01788 }