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