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