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 llvm::GlobalVariable *GV = 193 new llvm::GlobalVariable(getModule(), LTy, 194 Ty.isConstant(getContext()), Linkage, 195 EmitNullConstant(D.getType()), Name, nullptr, 196 llvm::GlobalVariable::NotThreadLocal, 197 AddrSpace); 198 GV->setAlignment(getContext().getDeclAlign(&D).getQuantity()); 199 setGlobalVisibility(GV, &D); 200 201 if (D.getTLSKind()) 202 setTLSMode(GV, D); 203 204 if (D.isExternallyVisible()) { 205 if (D.hasAttr<DLLImportAttr>()) 206 GV->setDLLStorageClass(llvm::GlobalVariable::DLLImportStorageClass); 207 else if (D.hasAttr<DLLExportAttr>()) 208 GV->setDLLStorageClass(llvm::GlobalVariable::DLLExportStorageClass); 209 } 210 211 // Make sure the result is of the correct type. 212 unsigned ExpectedAddrSpace = getContext().getTargetAddressSpace(Ty); 213 llvm::Constant *Addr = GV; 214 if (AddrSpace != ExpectedAddrSpace) { 215 llvm::PointerType *PTy = llvm::PointerType::get(LTy, ExpectedAddrSpace); 216 Addr = llvm::ConstantExpr::getAddrSpaceCast(GV, PTy); 217 } 218 219 setStaticLocalDeclAddress(&D, Addr); 220 221 // Ensure that the static local gets initialized by making sure the parent 222 // function gets emitted eventually. 223 const Decl *DC = cast<Decl>(D.getDeclContext()); 224 225 // We can't name blocks or captured statements directly, so try to emit their 226 // parents. 227 if (isa<BlockDecl>(DC) || isa<CapturedDecl>(DC)) { 228 DC = DC->getNonClosureContext(); 229 // FIXME: Ensure that global blocks get emitted. 230 if (!DC) 231 return Addr; 232 } 233 234 GlobalDecl GD; 235 if (const auto *CD = dyn_cast<CXXConstructorDecl>(DC)) 236 GD = GlobalDecl(CD, Ctor_Base); 237 else if (const auto *DD = dyn_cast<CXXDestructorDecl>(DC)) 238 GD = GlobalDecl(DD, Dtor_Base); 239 else if (const auto *FD = dyn_cast<FunctionDecl>(DC)) 240 GD = GlobalDecl(FD); 241 else { 242 // Don't do anything for Obj-C method decls or global closures. We should 243 // never defer them. 244 assert(isa<ObjCMethodDecl>(DC) && "unexpected parent code decl"); 245 } 246 if (GD.getDecl()) 247 (void)GetAddrOfGlobal(GD); 248 249 return Addr; 250 } 251 252 /// hasNontrivialDestruction - Determine whether a type's destruction is 253 /// non-trivial. If so, and the variable uses static initialization, we must 254 /// register its destructor to run on exit. 255 static bool hasNontrivialDestruction(QualType T) { 256 CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl(); 257 return RD && !RD->hasTrivialDestructor(); 258 } 259 260 /// AddInitializerToStaticVarDecl - Add the initializer for 'D' to the 261 /// global variable that has already been created for it. If the initializer 262 /// has a different type than GV does, this may free GV and return a different 263 /// one. Otherwise it just returns GV. 264 llvm::GlobalVariable * 265 CodeGenFunction::AddInitializerToStaticVarDecl(const VarDecl &D, 266 llvm::GlobalVariable *GV) { 267 llvm::Constant *Init = CGM.EmitConstantInit(D, this); 268 269 // If constant emission failed, then this should be a C++ static 270 // initializer. 271 if (!Init) { 272 if (!getLangOpts().CPlusPlus) 273 CGM.ErrorUnsupported(D.getInit(), "constant l-value expression"); 274 else if (Builder.GetInsertBlock()) { 275 // Since we have a static initializer, this global variable can't 276 // be constant. 277 GV->setConstant(false); 278 279 EmitCXXGuardedInit(D, GV, /*PerformInit*/true); 280 } 281 return GV; 282 } 283 284 // The initializer may differ in type from the global. Rewrite 285 // the global to match the initializer. (We have to do this 286 // because some types, like unions, can't be completely represented 287 // in the LLVM type system.) 288 if (GV->getType()->getElementType() != Init->getType()) { 289 llvm::GlobalVariable *OldGV = GV; 290 291 GV = new llvm::GlobalVariable(CGM.getModule(), Init->getType(), 292 OldGV->isConstant(), 293 OldGV->getLinkage(), Init, "", 294 /*InsertBefore*/ OldGV, 295 OldGV->getThreadLocalMode(), 296 CGM.getContext().getTargetAddressSpace(D.getType())); 297 GV->setVisibility(OldGV->getVisibility()); 298 299 // Steal the name of the old global 300 GV->takeName(OldGV); 301 302 // Replace all uses of the old global with the new global 303 llvm::Constant *NewPtrForOldDecl = 304 llvm::ConstantExpr::getBitCast(GV, OldGV->getType()); 305 OldGV->replaceAllUsesWith(NewPtrForOldDecl); 306 307 // Erase the old global, since it is no longer used. 308 OldGV->eraseFromParent(); 309 } 310 311 GV->setConstant(CGM.isTypeConstant(D.getType(), true)); 312 GV->setInitializer(Init); 313 314 if (hasNontrivialDestruction(D.getType())) { 315 // We have a constant initializer, but a nontrivial destructor. We still 316 // need to perform a guarded "initialization" in order to register the 317 // destructor. 318 EmitCXXGuardedInit(D, GV, /*PerformInit*/false); 319 } 320 321 return GV; 322 } 323 324 void CodeGenFunction::EmitStaticVarDecl(const VarDecl &D, 325 llvm::GlobalValue::LinkageTypes Linkage) { 326 llvm::Value *&DMEntry = LocalDeclMap[&D]; 327 assert(!DMEntry && "Decl already exists in localdeclmap!"); 328 329 // Check to see if we already have a global variable for this 330 // declaration. This can happen when double-emitting function 331 // bodies, e.g. with complete and base constructors. 332 llvm::Constant *addr = CGM.getOrCreateStaticVarDecl(D, Linkage); 333 334 // Store into LocalDeclMap before generating initializer to handle 335 // circular references. 336 DMEntry = addr; 337 338 // We can't have a VLA here, but we can have a pointer to a VLA, 339 // even though that doesn't really make any sense. 340 // Make sure to evaluate VLA bounds now so that we have them for later. 341 if (D.getType()->isVariablyModifiedType()) 342 EmitVariablyModifiedType(D.getType()); 343 344 // Save the type in case adding the initializer forces a type change. 345 llvm::Type *expectedType = addr->getType(); 346 347 llvm::GlobalVariable *var = 348 cast<llvm::GlobalVariable>(addr->stripPointerCasts()); 349 // If this value has an initializer, emit it. 350 if (D.getInit()) 351 var = AddInitializerToStaticVarDecl(D, var); 352 353 var->setAlignment(getContext().getDeclAlign(&D).getQuantity()); 354 355 if (D.hasAttr<AnnotateAttr>()) 356 CGM.AddGlobalAnnotations(&D, var); 357 358 if (const SectionAttr *SA = D.getAttr<SectionAttr>()) 359 var->setSection(SA->getName()); 360 361 if (D.hasAttr<UsedAttr>()) 362 CGM.addUsedGlobal(var); 363 364 // We may have to cast the constant because of the initializer 365 // mismatch above. 366 // 367 // FIXME: It is really dangerous to store this in the map; if anyone 368 // RAUW's the GV uses of this constant will be invalid. 369 llvm::Constant *castedAddr = 370 llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(var, expectedType); 371 DMEntry = castedAddr; 372 CGM.setStaticLocalDeclAddress(&D, castedAddr); 373 374 CGM.getSanitizerMetadata()->reportGlobalToASan(var, D); 375 376 // Emit global variable debug descriptor for static vars. 377 CGDebugInfo *DI = getDebugInfo(); 378 if (DI && 379 CGM.getCodeGenOpts().getDebugInfo() >= CodeGenOptions::LimitedDebugInfo) { 380 DI->setLocation(D.getLocation()); 381 DI->EmitGlobalVariable(var, &D); 382 } 383 } 384 385 namespace { 386 struct DestroyObject : EHScopeStack::Cleanup { 387 DestroyObject(llvm::Value *addr, QualType type, 388 CodeGenFunction::Destroyer *destroyer, 389 bool useEHCleanupForArray) 390 : addr(addr), type(type), destroyer(destroyer), 391 useEHCleanupForArray(useEHCleanupForArray) {} 392 393 llvm::Value *addr; 394 QualType type; 395 CodeGenFunction::Destroyer *destroyer; 396 bool useEHCleanupForArray; 397 398 void Emit(CodeGenFunction &CGF, Flags flags) override { 399 // Don't use an EH cleanup recursively from an EH cleanup. 400 bool useEHCleanupForArray = 401 flags.isForNormalCleanup() && this->useEHCleanupForArray; 402 403 CGF.emitDestroy(addr, type, destroyer, useEHCleanupForArray); 404 } 405 }; 406 407 struct DestroyNRVOVariable : EHScopeStack::Cleanup { 408 DestroyNRVOVariable(llvm::Value *addr, 409 const CXXDestructorDecl *Dtor, 410 llvm::Value *NRVOFlag) 411 : Dtor(Dtor), NRVOFlag(NRVOFlag), Loc(addr) {} 412 413 const CXXDestructorDecl *Dtor; 414 llvm::Value *NRVOFlag; 415 llvm::Value *Loc; 416 417 void Emit(CodeGenFunction &CGF, Flags flags) override { 418 // Along the exceptions path we always execute the dtor. 419 bool NRVO = flags.isForNormalCleanup() && NRVOFlag; 420 421 llvm::BasicBlock *SkipDtorBB = nullptr; 422 if (NRVO) { 423 // If we exited via NRVO, we skip the destructor call. 424 llvm::BasicBlock *RunDtorBB = CGF.createBasicBlock("nrvo.unused"); 425 SkipDtorBB = CGF.createBasicBlock("nrvo.skipdtor"); 426 llvm::Value *DidNRVO = CGF.Builder.CreateLoad(NRVOFlag, "nrvo.val"); 427 CGF.Builder.CreateCondBr(DidNRVO, SkipDtorBB, RunDtorBB); 428 CGF.EmitBlock(RunDtorBB); 429 } 430 431 CGF.EmitCXXDestructorCall(Dtor, Dtor_Complete, 432 /*ForVirtualBase=*/false, 433 /*Delegating=*/false, 434 Loc); 435 436 if (NRVO) CGF.EmitBlock(SkipDtorBB); 437 } 438 }; 439 440 struct CallStackRestore : EHScopeStack::Cleanup { 441 llvm::Value *Stack; 442 CallStackRestore(llvm::Value *Stack) : Stack(Stack) {} 443 void Emit(CodeGenFunction &CGF, Flags flags) override { 444 llvm::Value *V = CGF.Builder.CreateLoad(Stack); 445 llvm::Value *F = CGF.CGM.getIntrinsic(llvm::Intrinsic::stackrestore); 446 CGF.Builder.CreateCall(F, V); 447 } 448 }; 449 450 struct ExtendGCLifetime : EHScopeStack::Cleanup { 451 const VarDecl &Var; 452 ExtendGCLifetime(const VarDecl *var) : Var(*var) {} 453 454 void Emit(CodeGenFunction &CGF, Flags flags) override { 455 // Compute the address of the local variable, in case it's a 456 // byref or something. 457 DeclRefExpr DRE(const_cast<VarDecl*>(&Var), false, 458 Var.getType(), VK_LValue, SourceLocation()); 459 llvm::Value *value = CGF.EmitLoadOfScalar(CGF.EmitDeclRefLValue(&DRE), 460 SourceLocation()); 461 CGF.EmitExtendGCLifetime(value); 462 } 463 }; 464 465 struct CallCleanupFunction : EHScopeStack::Cleanup { 466 llvm::Constant *CleanupFn; 467 const CGFunctionInfo &FnInfo; 468 const VarDecl &Var; 469 470 CallCleanupFunction(llvm::Constant *CleanupFn, const CGFunctionInfo *Info, 471 const VarDecl *Var) 472 : CleanupFn(CleanupFn), FnInfo(*Info), Var(*Var) {} 473 474 void Emit(CodeGenFunction &CGF, Flags flags) override { 475 DeclRefExpr DRE(const_cast<VarDecl*>(&Var), false, 476 Var.getType(), VK_LValue, SourceLocation()); 477 // Compute the address of the local variable, in case it's a byref 478 // or something. 479 llvm::Value *Addr = CGF.EmitDeclRefLValue(&DRE).getAddress(); 480 481 // In some cases, the type of the function argument will be different from 482 // the type of the pointer. An example of this is 483 // void f(void* arg); 484 // __attribute__((cleanup(f))) void *g; 485 // 486 // To fix this we insert a bitcast here. 487 QualType ArgTy = FnInfo.arg_begin()->type; 488 llvm::Value *Arg = 489 CGF.Builder.CreateBitCast(Addr, CGF.ConvertType(ArgTy)); 490 491 CallArgList Args; 492 Args.add(RValue::get(Arg), 493 CGF.getContext().getPointerType(Var.getType())); 494 CGF.EmitCall(FnInfo, CleanupFn, ReturnValueSlot(), Args); 495 } 496 }; 497 498 /// A cleanup to call @llvm.lifetime.end. 499 class CallLifetimeEnd : public EHScopeStack::Cleanup { 500 llvm::Value *Addr; 501 llvm::Value *Size; 502 public: 503 CallLifetimeEnd(llvm::Value *addr, llvm::Value *size) 504 : Addr(addr), Size(size) {} 505 506 void Emit(CodeGenFunction &CGF, Flags flags) override { 507 CGF.EmitLifetimeEnd(Size, Addr); 508 } 509 }; 510 511 } 512 513 /// EmitAutoVarWithLifetime - Does the setup required for an automatic 514 /// variable with lifetime. 515 static void EmitAutoVarWithLifetime(CodeGenFunction &CGF, const VarDecl &var, 516 llvm::Value *addr, 517 Qualifiers::ObjCLifetime lifetime) { 518 switch (lifetime) { 519 case Qualifiers::OCL_None: 520 llvm_unreachable("present but none"); 521 522 case Qualifiers::OCL_ExplicitNone: 523 // nothing to do 524 break; 525 526 case Qualifiers::OCL_Strong: { 527 CodeGenFunction::Destroyer *destroyer = 528 (var.hasAttr<ObjCPreciseLifetimeAttr>() 529 ? CodeGenFunction::destroyARCStrongPrecise 530 : CodeGenFunction::destroyARCStrongImprecise); 531 532 CleanupKind cleanupKind = CGF.getARCCleanupKind(); 533 CGF.pushDestroy(cleanupKind, addr, var.getType(), destroyer, 534 cleanupKind & EHCleanup); 535 break; 536 } 537 case Qualifiers::OCL_Autoreleasing: 538 // nothing to do 539 break; 540 541 case Qualifiers::OCL_Weak: 542 // __weak objects always get EH cleanups; otherwise, exceptions 543 // could cause really nasty crashes instead of mere leaks. 544 CGF.pushDestroy(NormalAndEHCleanup, addr, var.getType(), 545 CodeGenFunction::destroyARCWeak, 546 /*useEHCleanup*/ true); 547 break; 548 } 549 } 550 551 static bool isAccessedBy(const VarDecl &var, const Stmt *s) { 552 if (const Expr *e = dyn_cast<Expr>(s)) { 553 // Skip the most common kinds of expressions that make 554 // hierarchy-walking expensive. 555 s = e = e->IgnoreParenCasts(); 556 557 if (const DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) 558 return (ref->getDecl() == &var); 559 if (const BlockExpr *be = dyn_cast<BlockExpr>(e)) { 560 const BlockDecl *block = be->getBlockDecl(); 561 for (const auto &I : block->captures()) { 562 if (I.getVariable() == &var) 563 return true; 564 } 565 } 566 } 567 568 for (Stmt::const_child_range children = s->children(); children; ++children) 569 // children might be null; as in missing decl or conditional of an if-stmt. 570 if ((*children) && isAccessedBy(var, *children)) 571 return true; 572 573 return false; 574 } 575 576 static bool isAccessedBy(const ValueDecl *decl, const Expr *e) { 577 if (!decl) return false; 578 if (!isa<VarDecl>(decl)) return false; 579 const VarDecl *var = cast<VarDecl>(decl); 580 return isAccessedBy(*var, e); 581 } 582 583 static void drillIntoBlockVariable(CodeGenFunction &CGF, 584 LValue &lvalue, 585 const VarDecl *var) { 586 lvalue.setAddress(CGF.BuildBlockByrefAddress(lvalue.getAddress(), var)); 587 } 588 589 void CodeGenFunction::EmitScalarInit(const Expr *init, 590 const ValueDecl *D, 591 LValue lvalue, 592 bool capturedByInit) { 593 Qualifiers::ObjCLifetime lifetime = lvalue.getObjCLifetime(); 594 if (!lifetime) { 595 llvm::Value *value = EmitScalarExpr(init); 596 if (capturedByInit) 597 drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D)); 598 EmitStoreThroughLValue(RValue::get(value), lvalue, true); 599 return; 600 } 601 602 if (const CXXDefaultInitExpr *DIE = dyn_cast<CXXDefaultInitExpr>(init)) 603 init = DIE->getExpr(); 604 605 // If we're emitting a value with lifetime, we have to do the 606 // initialization *before* we leave the cleanup scopes. 607 if (const ExprWithCleanups *ewc = dyn_cast<ExprWithCleanups>(init)) { 608 enterFullExpression(ewc); 609 init = ewc->getSubExpr(); 610 } 611 CodeGenFunction::RunCleanupsScope Scope(*this); 612 613 // We have to maintain the illusion that the variable is 614 // zero-initialized. If the variable might be accessed in its 615 // initializer, zero-initialize before running the initializer, then 616 // actually perform the initialization with an assign. 617 bool accessedByInit = false; 618 if (lifetime != Qualifiers::OCL_ExplicitNone) 619 accessedByInit = (capturedByInit || isAccessedBy(D, init)); 620 if (accessedByInit) { 621 LValue tempLV = lvalue; 622 // Drill down to the __block object if necessary. 623 if (capturedByInit) { 624 // We can use a simple GEP for this because it can't have been 625 // moved yet. 626 tempLV.setAddress(Builder.CreateStructGEP(tempLV.getAddress(), 627 getByRefValueLLVMField(cast<VarDecl>(D)))); 628 } 629 630 llvm::PointerType *ty 631 = cast<llvm::PointerType>(tempLV.getAddress()->getType()); 632 ty = cast<llvm::PointerType>(ty->getElementType()); 633 634 llvm::Value *zero = llvm::ConstantPointerNull::get(ty); 635 636 // If __weak, we want to use a barrier under certain conditions. 637 if (lifetime == Qualifiers::OCL_Weak) 638 EmitARCInitWeak(tempLV.getAddress(), zero); 639 640 // Otherwise just do a simple store. 641 else 642 EmitStoreOfScalar(zero, tempLV, /* isInitialization */ true); 643 } 644 645 // Emit the initializer. 646 llvm::Value *value = nullptr; 647 648 switch (lifetime) { 649 case Qualifiers::OCL_None: 650 llvm_unreachable("present but none"); 651 652 case Qualifiers::OCL_ExplicitNone: 653 // nothing to do 654 value = EmitScalarExpr(init); 655 break; 656 657 case Qualifiers::OCL_Strong: { 658 value = EmitARCRetainScalarExpr(init); 659 break; 660 } 661 662 case Qualifiers::OCL_Weak: { 663 // No way to optimize a producing initializer into this. It's not 664 // worth optimizing for, because the value will immediately 665 // disappear in the common case. 666 value = EmitScalarExpr(init); 667 668 if (capturedByInit) drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D)); 669 if (accessedByInit) 670 EmitARCStoreWeak(lvalue.getAddress(), value, /*ignored*/ true); 671 else 672 EmitARCInitWeak(lvalue.getAddress(), value); 673 return; 674 } 675 676 case Qualifiers::OCL_Autoreleasing: 677 value = EmitARCRetainAutoreleaseScalarExpr(init); 678 break; 679 } 680 681 if (capturedByInit) drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D)); 682 683 // If the variable might have been accessed by its initializer, we 684 // might have to initialize with a barrier. We have to do this for 685 // both __weak and __strong, but __weak got filtered out above. 686 if (accessedByInit && lifetime == Qualifiers::OCL_Strong) { 687 llvm::Value *oldValue = EmitLoadOfScalar(lvalue, init->getExprLoc()); 688 EmitStoreOfScalar(value, lvalue, /* isInitialization */ true); 689 EmitARCRelease(oldValue, ARCImpreciseLifetime); 690 return; 691 } 692 693 EmitStoreOfScalar(value, lvalue, /* isInitialization */ true); 694 } 695 696 /// EmitScalarInit - Initialize the given lvalue with the given object. 697 void CodeGenFunction::EmitScalarInit(llvm::Value *init, LValue lvalue) { 698 Qualifiers::ObjCLifetime lifetime = lvalue.getObjCLifetime(); 699 if (!lifetime) 700 return EmitStoreThroughLValue(RValue::get(init), lvalue, true); 701 702 switch (lifetime) { 703 case Qualifiers::OCL_None: 704 llvm_unreachable("present but none"); 705 706 case Qualifiers::OCL_ExplicitNone: 707 // nothing to do 708 break; 709 710 case Qualifiers::OCL_Strong: 711 init = EmitARCRetain(lvalue.getType(), init); 712 break; 713 714 case Qualifiers::OCL_Weak: 715 // Initialize and then skip the primitive store. 716 EmitARCInitWeak(lvalue.getAddress(), init); 717 return; 718 719 case Qualifiers::OCL_Autoreleasing: 720 init = EmitARCRetainAutorelease(lvalue.getType(), init); 721 break; 722 } 723 724 EmitStoreOfScalar(init, lvalue, /* isInitialization */ true); 725 } 726 727 /// canEmitInitWithFewStoresAfterMemset - Decide whether we can emit the 728 /// non-zero parts of the specified initializer with equal or fewer than 729 /// NumStores scalar stores. 730 static bool canEmitInitWithFewStoresAfterMemset(llvm::Constant *Init, 731 unsigned &NumStores) { 732 // Zero and Undef never requires any extra stores. 733 if (isa<llvm::ConstantAggregateZero>(Init) || 734 isa<llvm::ConstantPointerNull>(Init) || 735 isa<llvm::UndefValue>(Init)) 736 return true; 737 if (isa<llvm::ConstantInt>(Init) || isa<llvm::ConstantFP>(Init) || 738 isa<llvm::ConstantVector>(Init) || isa<llvm::BlockAddress>(Init) || 739 isa<llvm::ConstantExpr>(Init)) 740 return Init->isNullValue() || NumStores--; 741 742 // See if we can emit each element. 743 if (isa<llvm::ConstantArray>(Init) || isa<llvm::ConstantStruct>(Init)) { 744 for (unsigned i = 0, e = Init->getNumOperands(); i != e; ++i) { 745 llvm::Constant *Elt = cast<llvm::Constant>(Init->getOperand(i)); 746 if (!canEmitInitWithFewStoresAfterMemset(Elt, NumStores)) 747 return false; 748 } 749 return true; 750 } 751 752 if (llvm::ConstantDataSequential *CDS = 753 dyn_cast<llvm::ConstantDataSequential>(Init)) { 754 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) { 755 llvm::Constant *Elt = CDS->getElementAsConstant(i); 756 if (!canEmitInitWithFewStoresAfterMemset(Elt, NumStores)) 757 return false; 758 } 759 return true; 760 } 761 762 // Anything else is hard and scary. 763 return false; 764 } 765 766 /// emitStoresForInitAfterMemset - For inits that 767 /// canEmitInitWithFewStoresAfterMemset returned true for, emit the scalar 768 /// stores that would be required. 769 static void emitStoresForInitAfterMemset(llvm::Constant *Init, llvm::Value *Loc, 770 bool isVolatile, CGBuilderTy &Builder) { 771 assert(!Init->isNullValue() && !isa<llvm::UndefValue>(Init) && 772 "called emitStoresForInitAfterMemset for zero or undef value."); 773 774 if (isa<llvm::ConstantInt>(Init) || isa<llvm::ConstantFP>(Init) || 775 isa<llvm::ConstantVector>(Init) || isa<llvm::BlockAddress>(Init) || 776 isa<llvm::ConstantExpr>(Init)) { 777 Builder.CreateStore(Init, Loc, isVolatile); 778 return; 779 } 780 781 if (llvm::ConstantDataSequential *CDS = 782 dyn_cast<llvm::ConstantDataSequential>(Init)) { 783 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) { 784 llvm::Constant *Elt = CDS->getElementAsConstant(i); 785 786 // If necessary, get a pointer to the element and emit it. 787 if (!Elt->isNullValue() && !isa<llvm::UndefValue>(Elt)) 788 emitStoresForInitAfterMemset(Elt, Builder.CreateConstGEP2_32(Loc, 0, i), 789 isVolatile, Builder); 790 } 791 return; 792 } 793 794 assert((isa<llvm::ConstantStruct>(Init) || isa<llvm::ConstantArray>(Init)) && 795 "Unknown value type!"); 796 797 for (unsigned i = 0, e = Init->getNumOperands(); i != e; ++i) { 798 llvm::Constant *Elt = cast<llvm::Constant>(Init->getOperand(i)); 799 800 // If necessary, get a pointer to the element and emit it. 801 if (!Elt->isNullValue() && !isa<llvm::UndefValue>(Elt)) 802 emitStoresForInitAfterMemset(Elt, Builder.CreateConstGEP2_32(Loc, 0, i), 803 isVolatile, Builder); 804 } 805 } 806 807 808 /// shouldUseMemSetPlusStoresToInitialize - Decide whether we should use memset 809 /// plus some stores to initialize a local variable instead of using a memcpy 810 /// from a constant global. It is beneficial to use memset if the global is all 811 /// zeros, or mostly zeros and large. 812 static bool shouldUseMemSetPlusStoresToInitialize(llvm::Constant *Init, 813 uint64_t GlobalSize) { 814 // If a global is all zeros, always use a memset. 815 if (isa<llvm::ConstantAggregateZero>(Init)) return true; 816 817 // If a non-zero global is <= 32 bytes, always use a memcpy. If it is large, 818 // do it if it will require 6 or fewer scalar stores. 819 // TODO: Should budget depends on the size? Avoiding a large global warrants 820 // plopping in more stores. 821 unsigned StoreBudget = 6; 822 uint64_t SizeLimit = 32; 823 824 return GlobalSize > SizeLimit && 825 canEmitInitWithFewStoresAfterMemset(Init, StoreBudget); 826 } 827 828 /// Should we use the LLVM lifetime intrinsics for the given local variable? 829 static bool shouldUseLifetimeMarkers(CodeGenFunction &CGF, uint64_t Size) { 830 // For now, only in optimized builds. 831 if (CGF.CGM.getCodeGenOpts().OptimizationLevel == 0) 832 return false; 833 834 // Limit the size of marked objects to 32 bytes. We don't want to increase 835 // compile time by marking tiny objects. 836 unsigned SizeThreshold = 32; 837 838 return Size > SizeThreshold; 839 } 840 841 /// EmitAutoVarDecl - Emit code and set up an entry in LocalDeclMap for a 842 /// variable declaration with auto, register, or no storage class specifier. 843 /// These turn into simple stack objects, or GlobalValues depending on target. 844 void CodeGenFunction::EmitAutoVarDecl(const VarDecl &D) { 845 AutoVarEmission emission = EmitAutoVarAlloca(D); 846 EmitAutoVarInit(emission); 847 EmitAutoVarCleanups(emission); 848 } 849 850 /// Emit a lifetime.begin marker if some criteria are satisfied. 851 /// \return a pointer to the temporary size Value if a marker was emitted, null 852 /// otherwise 853 llvm::Value *CodeGenFunction::EmitLifetimeStart(uint64_t Size, 854 llvm::Value *Addr) { 855 if (!shouldUseLifetimeMarkers(*this, Size)) 856 return nullptr; 857 858 llvm::Value *SizeV = llvm::ConstantInt::get(Int64Ty, Size); 859 llvm::Value *CastAddr = Builder.CreateBitCast(Addr, Int8PtrTy); 860 Builder.CreateCall2(CGM.getLLVMLifetimeStartFn(), SizeV, CastAddr) 861 ->setDoesNotThrow(); 862 return SizeV; 863 } 864 865 void CodeGenFunction::EmitLifetimeEnd(llvm::Value *Size, llvm::Value *Addr) { 866 llvm::Value *CastAddr = Builder.CreateBitCast(Addr, Int8PtrTy); 867 Builder.CreateCall2(CGM.getLLVMLifetimeEndFn(), Size, CastAddr) 868 ->setDoesNotThrow(); 869 } 870 871 /// EmitAutoVarAlloca - Emit the alloca and debug information for a 872 /// local variable. Does not emit initialization or destruction. 873 CodeGenFunction::AutoVarEmission 874 CodeGenFunction::EmitAutoVarAlloca(const VarDecl &D) { 875 QualType Ty = D.getType(); 876 877 AutoVarEmission emission(D); 878 879 bool isByRef = D.hasAttr<BlocksAttr>(); 880 emission.IsByRef = isByRef; 881 882 CharUnits alignment = getContext().getDeclAlign(&D); 883 emission.Alignment = alignment; 884 885 // If the type is variably-modified, emit all the VLA sizes for it. 886 if (Ty->isVariablyModifiedType()) 887 EmitVariablyModifiedType(Ty); 888 889 llvm::Value *DeclPtr; 890 if (Ty->isConstantSizeType()) { 891 bool NRVO = getLangOpts().ElideConstructors && 892 D.isNRVOVariable(); 893 894 // If this value is an array or struct with a statically determinable 895 // constant initializer, there are optimizations we can do. 896 // 897 // TODO: We should constant-evaluate the initializer of any variable, 898 // as long as it is initialized by a constant expression. Currently, 899 // isConstantInitializer produces wrong answers for structs with 900 // reference or bitfield members, and a few other cases, and checking 901 // for POD-ness protects us from some of these. 902 if (D.getInit() && (Ty->isArrayType() || Ty->isRecordType()) && 903 (D.isConstexpr() || 904 ((Ty.isPODType(getContext()) || 905 getContext().getBaseElementType(Ty)->isObjCObjectPointerType()) && 906 D.getInit()->isConstantInitializer(getContext(), false)))) { 907 908 // If the variable's a const type, and it's neither an NRVO 909 // candidate nor a __block variable and has no mutable members, 910 // emit it as a global instead. 911 if (CGM.getCodeGenOpts().MergeAllConstants && !NRVO && !isByRef && 912 CGM.isTypeConstant(Ty, true)) { 913 EmitStaticVarDecl(D, llvm::GlobalValue::InternalLinkage); 914 915 emission.Address = nullptr; // signal this condition to later callbacks 916 assert(emission.wasEmittedAsGlobal()); 917 return emission; 918 } 919 920 // Otherwise, tell the initialization code that we're in this case. 921 emission.IsConstantAggregate = true; 922 } 923 924 // A normal fixed sized variable becomes an alloca in the entry block, 925 // unless it's an NRVO variable. 926 llvm::Type *LTy = ConvertTypeForMem(Ty); 927 928 if (NRVO) { 929 // The named return value optimization: allocate this variable in the 930 // return slot, so that we can elide the copy when returning this 931 // variable (C++0x [class.copy]p34). 932 DeclPtr = ReturnValue; 933 934 if (const RecordType *RecordTy = Ty->getAs<RecordType>()) { 935 if (!cast<CXXRecordDecl>(RecordTy->getDecl())->hasTrivialDestructor()) { 936 // Create a flag that is used to indicate when the NRVO was applied 937 // to this variable. Set it to zero to indicate that NRVO was not 938 // applied. 939 llvm::Value *Zero = Builder.getFalse(); 940 llvm::Value *NRVOFlag = CreateTempAlloca(Zero->getType(), "nrvo"); 941 EnsureInsertPoint(); 942 Builder.CreateStore(Zero, NRVOFlag); 943 944 // Record the NRVO flag for this variable. 945 NRVOFlags[&D] = NRVOFlag; 946 emission.NRVOFlag = NRVOFlag; 947 } 948 } 949 } else { 950 if (isByRef) 951 LTy = BuildByRefType(&D); 952 953 llvm::AllocaInst *Alloc = CreateTempAlloca(LTy); 954 Alloc->setName(D.getName()); 955 956 CharUnits allocaAlignment = alignment; 957 if (isByRef) 958 allocaAlignment = std::max(allocaAlignment, 959 getContext().toCharUnitsFromBits(getTarget().getPointerAlign(0))); 960 Alloc->setAlignment(allocaAlignment.getQuantity()); 961 DeclPtr = Alloc; 962 963 // Emit a lifetime intrinsic if meaningful. There's no point 964 // in doing this if we don't have a valid insertion point (?). 965 uint64_t size = CGM.getDataLayout().getTypeAllocSize(LTy); 966 if (HaveInsertPoint() && EmitLifetimeStart(size, Alloc)) { 967 emission.SizeForLifetimeMarkers = llvm::ConstantInt::get(Int64Ty, size); 968 } else { 969 assert(!emission.useLifetimeMarkers()); 970 } 971 } 972 } else { 973 EnsureInsertPoint(); 974 975 if (!DidCallStackSave) { 976 // Save the stack. 977 llvm::Value *Stack = CreateTempAlloca(Int8PtrTy, "saved_stack"); 978 979 llvm::Value *F = CGM.getIntrinsic(llvm::Intrinsic::stacksave); 980 llvm::Value *V = Builder.CreateCall(F); 981 982 Builder.CreateStore(V, Stack); 983 984 DidCallStackSave = true; 985 986 // Push a cleanup block and restore the stack there. 987 // FIXME: in general circumstances, this should be an EH cleanup. 988 pushStackRestore(NormalCleanup, Stack); 989 } 990 991 llvm::Value *elementCount; 992 QualType elementType; 993 std::tie(elementCount, elementType) = getVLASize(Ty); 994 995 llvm::Type *llvmTy = ConvertTypeForMem(elementType); 996 997 // Allocate memory for the array. 998 llvm::AllocaInst *vla = Builder.CreateAlloca(llvmTy, elementCount, "vla"); 999 vla->setAlignment(alignment.getQuantity()); 1000 1001 DeclPtr = vla; 1002 } 1003 1004 llvm::Value *&DMEntry = LocalDeclMap[&D]; 1005 assert(!DMEntry && "Decl already exists in localdeclmap!"); 1006 DMEntry = DeclPtr; 1007 emission.Address = DeclPtr; 1008 1009 // Emit debug info for local var declaration. 1010 if (HaveInsertPoint()) 1011 if (CGDebugInfo *DI = getDebugInfo()) { 1012 if (CGM.getCodeGenOpts().getDebugInfo() 1013 >= CodeGenOptions::LimitedDebugInfo) { 1014 DI->setLocation(D.getLocation()); 1015 DI->EmitDeclareOfAutoVariable(&D, DeclPtr, Builder); 1016 } 1017 } 1018 1019 if (D.hasAttr<AnnotateAttr>()) 1020 EmitVarAnnotations(&D, emission.Address); 1021 1022 return emission; 1023 } 1024 1025 /// Determines whether the given __block variable is potentially 1026 /// captured by the given expression. 1027 static bool isCapturedBy(const VarDecl &var, const Expr *e) { 1028 // Skip the most common kinds of expressions that make 1029 // hierarchy-walking expensive. 1030 e = e->IgnoreParenCasts(); 1031 1032 if (const BlockExpr *be = dyn_cast<BlockExpr>(e)) { 1033 const BlockDecl *block = be->getBlockDecl(); 1034 for (const auto &I : block->captures()) { 1035 if (I.getVariable() == &var) 1036 return true; 1037 } 1038 1039 // No need to walk into the subexpressions. 1040 return false; 1041 } 1042 1043 if (const StmtExpr *SE = dyn_cast<StmtExpr>(e)) { 1044 const CompoundStmt *CS = SE->getSubStmt(); 1045 for (const auto *BI : CS->body()) 1046 if (const auto *E = dyn_cast<Expr>(BI)) { 1047 if (isCapturedBy(var, E)) 1048 return true; 1049 } 1050 else if (const auto *DS = dyn_cast<DeclStmt>(BI)) { 1051 // special case declarations 1052 for (const auto *I : DS->decls()) { 1053 if (const auto *VD = dyn_cast<VarDecl>((I))) { 1054 const Expr *Init = VD->getInit(); 1055 if (Init && isCapturedBy(var, Init)) 1056 return true; 1057 } 1058 } 1059 } 1060 else 1061 // FIXME. Make safe assumption assuming arbitrary statements cause capturing. 1062 // Later, provide code to poke into statements for capture analysis. 1063 return true; 1064 return false; 1065 } 1066 1067 for (Stmt::const_child_range children = e->children(); children; ++children) 1068 if (isCapturedBy(var, cast<Expr>(*children))) 1069 return true; 1070 1071 return false; 1072 } 1073 1074 /// \brief Determine whether the given initializer is trivial in the sense 1075 /// that it requires no code to be generated. 1076 bool CodeGenFunction::isTrivialInitializer(const Expr *Init) { 1077 if (!Init) 1078 return true; 1079 1080 if (const CXXConstructExpr *Construct = dyn_cast<CXXConstructExpr>(Init)) 1081 if (CXXConstructorDecl *Constructor = Construct->getConstructor()) 1082 if (Constructor->isTrivial() && 1083 Constructor->isDefaultConstructor() && 1084 !Construct->requiresZeroInitialization()) 1085 return true; 1086 1087 return false; 1088 } 1089 void CodeGenFunction::EmitAutoVarInit(const AutoVarEmission &emission) { 1090 assert(emission.Variable && "emission was not valid!"); 1091 1092 // If this was emitted as a global constant, we're done. 1093 if (emission.wasEmittedAsGlobal()) return; 1094 1095 const VarDecl &D = *emission.Variable; 1096 QualType type = D.getType(); 1097 1098 // If this local has an initializer, emit it now. 1099 const Expr *Init = D.getInit(); 1100 1101 // If we are at an unreachable point, we don't need to emit the initializer 1102 // unless it contains a label. 1103 if (!HaveInsertPoint()) { 1104 if (!Init || !ContainsLabel(Init)) return; 1105 EnsureInsertPoint(); 1106 } 1107 1108 // Initialize the structure of a __block variable. 1109 if (emission.IsByRef) 1110 emitByrefStructureInit(emission); 1111 1112 if (isTrivialInitializer(Init)) 1113 return; 1114 1115 CharUnits alignment = emission.Alignment; 1116 1117 // Check whether this is a byref variable that's potentially 1118 // captured and moved by its own initializer. If so, we'll need to 1119 // emit the initializer first, then copy into the variable. 1120 bool capturedByInit = emission.IsByRef && isCapturedBy(D, Init); 1121 1122 llvm::Value *Loc = 1123 capturedByInit ? emission.Address : emission.getObjectAddress(*this); 1124 1125 llvm::Constant *constant = nullptr; 1126 if (emission.IsConstantAggregate || D.isConstexpr()) { 1127 assert(!capturedByInit && "constant init contains a capturing block?"); 1128 constant = CGM.EmitConstantInit(D, this); 1129 } 1130 1131 if (!constant) { 1132 LValue lv = MakeAddrLValue(Loc, type, alignment); 1133 lv.setNonGC(true); 1134 return EmitExprAsInit(Init, &D, lv, capturedByInit); 1135 } 1136 1137 if (!emission.IsConstantAggregate) { 1138 // For simple scalar/complex initialization, store the value directly. 1139 LValue lv = MakeAddrLValue(Loc, type, alignment); 1140 lv.setNonGC(true); 1141 return EmitStoreThroughLValue(RValue::get(constant), lv, true); 1142 } 1143 1144 // If this is a simple aggregate initialization, we can optimize it 1145 // in various ways. 1146 bool isVolatile = type.isVolatileQualified(); 1147 1148 llvm::Value *SizeVal = 1149 llvm::ConstantInt::get(IntPtrTy, 1150 getContext().getTypeSizeInChars(type).getQuantity()); 1151 1152 llvm::Type *BP = Int8PtrTy; 1153 if (Loc->getType() != BP) 1154 Loc = Builder.CreateBitCast(Loc, BP); 1155 1156 // If the initializer is all or mostly zeros, codegen with memset then do 1157 // a few stores afterward. 1158 if (shouldUseMemSetPlusStoresToInitialize(constant, 1159 CGM.getDataLayout().getTypeAllocSize(constant->getType()))) { 1160 Builder.CreateMemSet(Loc, llvm::ConstantInt::get(Int8Ty, 0), SizeVal, 1161 alignment.getQuantity(), isVolatile); 1162 // Zero and undef don't require a stores. 1163 if (!constant->isNullValue() && !isa<llvm::UndefValue>(constant)) { 1164 Loc = Builder.CreateBitCast(Loc, constant->getType()->getPointerTo()); 1165 emitStoresForInitAfterMemset(constant, Loc, isVolatile, Builder); 1166 } 1167 } else { 1168 // Otherwise, create a temporary global with the initializer then 1169 // memcpy from the global to the alloca. 1170 std::string Name = getStaticDeclName(CGM, D); 1171 llvm::GlobalVariable *GV = 1172 new llvm::GlobalVariable(CGM.getModule(), constant->getType(), true, 1173 llvm::GlobalValue::PrivateLinkage, 1174 constant, Name); 1175 GV->setAlignment(alignment.getQuantity()); 1176 GV->setUnnamedAddr(true); 1177 1178 llvm::Value *SrcPtr = GV; 1179 if (SrcPtr->getType() != BP) 1180 SrcPtr = Builder.CreateBitCast(SrcPtr, BP); 1181 1182 Builder.CreateMemCpy(Loc, SrcPtr, SizeVal, alignment.getQuantity(), 1183 isVolatile); 1184 } 1185 } 1186 1187 /// Emit an expression as an initializer for a variable at the given 1188 /// location. The expression is not necessarily the normal 1189 /// initializer for the variable, and the address is not necessarily 1190 /// its normal location. 1191 /// 1192 /// \param init the initializing expression 1193 /// \param var the variable to act as if we're initializing 1194 /// \param loc the address to initialize; its type is a pointer 1195 /// to the LLVM mapping of the variable's type 1196 /// \param alignment the alignment of the address 1197 /// \param capturedByInit true if the variable is a __block variable 1198 /// whose address is potentially changed by the initializer 1199 void CodeGenFunction::EmitExprAsInit(const Expr *init, 1200 const ValueDecl *D, 1201 LValue lvalue, 1202 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. 1239 void 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 1296 void 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 1343 CodeGenFunction::Destroyer * 1344 CodeGenFunction::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. 1359 void 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. 1369 void 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 1378 void 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 1385 void CodeGenFunction::pushStackRestore(CleanupKind Kind, llvm::Value *SPMem) { 1386 EHStack.pushCleanup<CallStackRestore>(Kind, SPMem); 1387 } 1388 1389 void 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 void 1410 CodeGenFunction::pushLifetimeEndMarker(StorageDuration SD, 1411 llvm::Value *ReferenceTemporary, 1412 llvm::Value *SizeForLifeTimeMarkers) { 1413 // SizeForLifeTimeMarkers is null in case no corresponding 1414 // @llvm.lifetime.start was emitted: there is nothing to do then. 1415 if (!SizeForLifeTimeMarkers) 1416 return; 1417 1418 switch (SD) { 1419 case SD_FullExpression: 1420 pushFullExprCleanup<CallLifetimeEnd>(NormalAndEHCleanup, ReferenceTemporary, 1421 SizeForLifeTimeMarkers); 1422 return; 1423 case SD_Automatic: 1424 EHStack.pushCleanup<CallLifetimeEnd>(static_cast<CleanupKind>(EHCleanup), 1425 ReferenceTemporary, 1426 SizeForLifeTimeMarkers); 1427 pushCleanupAfterFullExpr<CallLifetimeEnd>( 1428 NormalAndEHCleanup, ReferenceTemporary, SizeForLifeTimeMarkers); 1429 return; 1430 default: 1431 llvm_unreachable("unexpected storage duration for Lifetime markers"); 1432 } 1433 } 1434 1435 /// emitDestroy - Immediately perform the destruction of the given 1436 /// object. 1437 /// 1438 /// \param addr - the address of the object; a type* 1439 /// \param type - the type of the object; if an array type, all 1440 /// objects are destroyed in reverse order 1441 /// \param destroyer - the function to call to destroy individual 1442 /// elements 1443 /// \param useEHCleanupForArray - whether an EH cleanup should be 1444 /// used when destroying array elements, in case one of the 1445 /// destructions throws an exception 1446 void CodeGenFunction::emitDestroy(llvm::Value *addr, QualType type, 1447 Destroyer *destroyer, 1448 bool useEHCleanupForArray) { 1449 const ArrayType *arrayType = getContext().getAsArrayType(type); 1450 if (!arrayType) 1451 return destroyer(*this, addr, type); 1452 1453 llvm::Value *begin = addr; 1454 llvm::Value *length = emitArrayLength(arrayType, type, begin); 1455 1456 // Normally we have to check whether the array is zero-length. 1457 bool checkZeroLength = true; 1458 1459 // But if the array length is constant, we can suppress that. 1460 if (llvm::ConstantInt *constLength = dyn_cast<llvm::ConstantInt>(length)) { 1461 // ...and if it's constant zero, we can just skip the entire thing. 1462 if (constLength->isZero()) return; 1463 checkZeroLength = false; 1464 } 1465 1466 llvm::Value *end = Builder.CreateInBoundsGEP(begin, length); 1467 emitArrayDestroy(begin, end, type, destroyer, 1468 checkZeroLength, useEHCleanupForArray); 1469 } 1470 1471 /// emitArrayDestroy - Destroys all the elements of the given array, 1472 /// beginning from last to first. The array cannot be zero-length. 1473 /// 1474 /// \param begin - a type* denoting the first element of the array 1475 /// \param end - a type* denoting one past the end of the array 1476 /// \param type - the element type of the array 1477 /// \param destroyer - the function to call to destroy elements 1478 /// \param useEHCleanup - whether to push an EH cleanup to destroy 1479 /// the remaining elements in case the destruction of a single 1480 /// element throws 1481 void CodeGenFunction::emitArrayDestroy(llvm::Value *begin, 1482 llvm::Value *end, 1483 QualType type, 1484 Destroyer *destroyer, 1485 bool checkZeroLength, 1486 bool useEHCleanup) { 1487 assert(!type->isArrayType()); 1488 1489 // The basic structure here is a do-while loop, because we don't 1490 // need to check for the zero-element case. 1491 llvm::BasicBlock *bodyBB = createBasicBlock("arraydestroy.body"); 1492 llvm::BasicBlock *doneBB = createBasicBlock("arraydestroy.done"); 1493 1494 if (checkZeroLength) { 1495 llvm::Value *isEmpty = Builder.CreateICmpEQ(begin, end, 1496 "arraydestroy.isempty"); 1497 Builder.CreateCondBr(isEmpty, doneBB, bodyBB); 1498 } 1499 1500 // Enter the loop body, making that address the current address. 1501 llvm::BasicBlock *entryBB = Builder.GetInsertBlock(); 1502 EmitBlock(bodyBB); 1503 llvm::PHINode *elementPast = 1504 Builder.CreatePHI(begin->getType(), 2, "arraydestroy.elementPast"); 1505 elementPast->addIncoming(end, entryBB); 1506 1507 // Shift the address back by one element. 1508 llvm::Value *negativeOne = llvm::ConstantInt::get(SizeTy, -1, true); 1509 llvm::Value *element = Builder.CreateInBoundsGEP(elementPast, negativeOne, 1510 "arraydestroy.element"); 1511 1512 if (useEHCleanup) 1513 pushRegularPartialArrayCleanup(begin, element, type, destroyer); 1514 1515 // Perform the actual destruction there. 1516 destroyer(*this, element, type); 1517 1518 if (useEHCleanup) 1519 PopCleanupBlock(); 1520 1521 // Check whether we've reached the end. 1522 llvm::Value *done = Builder.CreateICmpEQ(element, begin, "arraydestroy.done"); 1523 Builder.CreateCondBr(done, doneBB, bodyBB); 1524 elementPast->addIncoming(element, Builder.GetInsertBlock()); 1525 1526 // Done. 1527 EmitBlock(doneBB); 1528 } 1529 1530 /// Perform partial array destruction as if in an EH cleanup. Unlike 1531 /// emitArrayDestroy, the element type here may still be an array type. 1532 static void emitPartialArrayDestroy(CodeGenFunction &CGF, 1533 llvm::Value *begin, llvm::Value *end, 1534 QualType type, 1535 CodeGenFunction::Destroyer *destroyer) { 1536 // If the element type is itself an array, drill down. 1537 unsigned arrayDepth = 0; 1538 while (const ArrayType *arrayType = CGF.getContext().getAsArrayType(type)) { 1539 // VLAs don't require a GEP index to walk into. 1540 if (!isa<VariableArrayType>(arrayType)) 1541 arrayDepth++; 1542 type = arrayType->getElementType(); 1543 } 1544 1545 if (arrayDepth) { 1546 llvm::Value *zero = llvm::ConstantInt::get(CGF.SizeTy, arrayDepth+1); 1547 1548 SmallVector<llvm::Value*,4> gepIndices(arrayDepth, zero); 1549 begin = CGF.Builder.CreateInBoundsGEP(begin, gepIndices, "pad.arraybegin"); 1550 end = CGF.Builder.CreateInBoundsGEP(end, gepIndices, "pad.arrayend"); 1551 } 1552 1553 // Destroy the array. We don't ever need an EH cleanup because we 1554 // assume that we're in an EH cleanup ourselves, so a throwing 1555 // destructor causes an immediate terminate. 1556 CGF.emitArrayDestroy(begin, end, type, destroyer, 1557 /*checkZeroLength*/ true, /*useEHCleanup*/ false); 1558 } 1559 1560 namespace { 1561 /// RegularPartialArrayDestroy - a cleanup which performs a partial 1562 /// array destroy where the end pointer is regularly determined and 1563 /// does not need to be loaded from a local. 1564 class RegularPartialArrayDestroy : public EHScopeStack::Cleanup { 1565 llvm::Value *ArrayBegin; 1566 llvm::Value *ArrayEnd; 1567 QualType ElementType; 1568 CodeGenFunction::Destroyer *Destroyer; 1569 public: 1570 RegularPartialArrayDestroy(llvm::Value *arrayBegin, llvm::Value *arrayEnd, 1571 QualType elementType, 1572 CodeGenFunction::Destroyer *destroyer) 1573 : ArrayBegin(arrayBegin), ArrayEnd(arrayEnd), 1574 ElementType(elementType), Destroyer(destroyer) {} 1575 1576 void Emit(CodeGenFunction &CGF, Flags flags) override { 1577 emitPartialArrayDestroy(CGF, ArrayBegin, ArrayEnd, 1578 ElementType, Destroyer); 1579 } 1580 }; 1581 1582 /// IrregularPartialArrayDestroy - a cleanup which performs a 1583 /// partial array destroy where the end pointer is irregularly 1584 /// determined and must be loaded from a local. 1585 class IrregularPartialArrayDestroy : public EHScopeStack::Cleanup { 1586 llvm::Value *ArrayBegin; 1587 llvm::Value *ArrayEndPointer; 1588 QualType ElementType; 1589 CodeGenFunction::Destroyer *Destroyer; 1590 public: 1591 IrregularPartialArrayDestroy(llvm::Value *arrayBegin, 1592 llvm::Value *arrayEndPointer, 1593 QualType elementType, 1594 CodeGenFunction::Destroyer *destroyer) 1595 : ArrayBegin(arrayBegin), ArrayEndPointer(arrayEndPointer), 1596 ElementType(elementType), Destroyer(destroyer) {} 1597 1598 void Emit(CodeGenFunction &CGF, Flags flags) override { 1599 llvm::Value *arrayEnd = CGF.Builder.CreateLoad(ArrayEndPointer); 1600 emitPartialArrayDestroy(CGF, ArrayBegin, arrayEnd, 1601 ElementType, Destroyer); 1602 } 1603 }; 1604 } 1605 1606 /// pushIrregularPartialArrayCleanup - Push an EH cleanup to destroy 1607 /// already-constructed elements of the given array. The cleanup 1608 /// may be popped with DeactivateCleanupBlock or PopCleanupBlock. 1609 /// 1610 /// \param elementType - the immediate element type of the array; 1611 /// possibly still an array type 1612 void CodeGenFunction::pushIrregularPartialArrayCleanup(llvm::Value *arrayBegin, 1613 llvm::Value *arrayEndPointer, 1614 QualType elementType, 1615 Destroyer *destroyer) { 1616 pushFullExprCleanup<IrregularPartialArrayDestroy>(EHCleanup, 1617 arrayBegin, arrayEndPointer, 1618 elementType, destroyer); 1619 } 1620 1621 /// pushRegularPartialArrayCleanup - Push an EH cleanup to destroy 1622 /// already-constructed elements of the given array. The cleanup 1623 /// may be popped with DeactivateCleanupBlock or PopCleanupBlock. 1624 /// 1625 /// \param elementType - the immediate element type of the array; 1626 /// possibly still an array type 1627 void CodeGenFunction::pushRegularPartialArrayCleanup(llvm::Value *arrayBegin, 1628 llvm::Value *arrayEnd, 1629 QualType elementType, 1630 Destroyer *destroyer) { 1631 pushFullExprCleanup<RegularPartialArrayDestroy>(EHCleanup, 1632 arrayBegin, arrayEnd, 1633 elementType, destroyer); 1634 } 1635 1636 /// Lazily declare the @llvm.lifetime.start intrinsic. 1637 llvm::Constant *CodeGenModule::getLLVMLifetimeStartFn() { 1638 if (LifetimeStartFn) return LifetimeStartFn; 1639 LifetimeStartFn = llvm::Intrinsic::getDeclaration(&getModule(), 1640 llvm::Intrinsic::lifetime_start); 1641 return LifetimeStartFn; 1642 } 1643 1644 /// Lazily declare the @llvm.lifetime.end intrinsic. 1645 llvm::Constant *CodeGenModule::getLLVMLifetimeEndFn() { 1646 if (LifetimeEndFn) return LifetimeEndFn; 1647 LifetimeEndFn = llvm::Intrinsic::getDeclaration(&getModule(), 1648 llvm::Intrinsic::lifetime_end); 1649 return LifetimeEndFn; 1650 } 1651 1652 namespace { 1653 /// A cleanup to perform a release of an object at the end of a 1654 /// function. This is used to balance out the incoming +1 of a 1655 /// ns_consumed argument when we can't reasonably do that just by 1656 /// not doing the initial retain for a __block argument. 1657 struct ConsumeARCParameter : EHScopeStack::Cleanup { 1658 ConsumeARCParameter(llvm::Value *param, 1659 ARCPreciseLifetime_t precise) 1660 : Param(param), Precise(precise) {} 1661 1662 llvm::Value *Param; 1663 ARCPreciseLifetime_t Precise; 1664 1665 void Emit(CodeGenFunction &CGF, Flags flags) override { 1666 CGF.EmitARCRelease(Param, Precise); 1667 } 1668 }; 1669 } 1670 1671 /// Emit an alloca (or GlobalValue depending on target) 1672 /// for the specified parameter and set up LocalDeclMap. 1673 void CodeGenFunction::EmitParmDecl(const VarDecl &D, llvm::Value *Arg, 1674 bool ArgIsPointer, unsigned ArgNo) { 1675 // FIXME: Why isn't ImplicitParamDecl a ParmVarDecl? 1676 assert((isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D)) && 1677 "Invalid argument to EmitParmDecl"); 1678 1679 Arg->setName(D.getName()); 1680 1681 QualType Ty = D.getType(); 1682 1683 // Use better IR generation for certain implicit parameters. 1684 if (isa<ImplicitParamDecl>(D)) { 1685 // The only implicit argument a block has is its literal. 1686 if (BlockInfo) { 1687 LocalDeclMap[&D] = Arg; 1688 llvm::Value *LocalAddr = nullptr; 1689 if (CGM.getCodeGenOpts().OptimizationLevel == 0) { 1690 // Allocate a stack slot to let the debug info survive the RA. 1691 llvm::AllocaInst *Alloc = CreateTempAlloca(ConvertTypeForMem(Ty), 1692 D.getName() + ".addr"); 1693 Alloc->setAlignment(getContext().getDeclAlign(&D).getQuantity()); 1694 LValue lv = MakeAddrLValue(Alloc, Ty, getContext().getDeclAlign(&D)); 1695 EmitStoreOfScalar(Arg, lv, /* isInitialization */ true); 1696 LocalAddr = Builder.CreateLoad(Alloc); 1697 } 1698 1699 if (CGDebugInfo *DI = getDebugInfo()) { 1700 if (CGM.getCodeGenOpts().getDebugInfo() 1701 >= CodeGenOptions::LimitedDebugInfo) { 1702 DI->setLocation(D.getLocation()); 1703 DI->EmitDeclareOfBlockLiteralArgVariable(*BlockInfo, Arg, ArgNo, 1704 LocalAddr, Builder); 1705 } 1706 } 1707 1708 return; 1709 } 1710 } 1711 1712 llvm::Value *DeclPtr; 1713 bool DoStore = false; 1714 bool IsScalar = hasScalarEvaluationKind(Ty); 1715 CharUnits Align = getContext().getDeclAlign(&D); 1716 // If we already have a pointer to the argument, reuse the input pointer. 1717 if (ArgIsPointer) { 1718 // If we have a prettier pointer type at this point, bitcast to that. 1719 unsigned AS = cast<llvm::PointerType>(Arg->getType())->getAddressSpace(); 1720 llvm::Type *IRTy = ConvertTypeForMem(Ty)->getPointerTo(AS); 1721 DeclPtr = Arg->getType() == IRTy ? Arg : Builder.CreateBitCast(Arg, IRTy, 1722 D.getName()); 1723 // Push a destructor cleanup for this parameter if the ABI requires it. 1724 // Don't push a cleanup in a thunk for a method that will also emit a 1725 // cleanup. 1726 if (!IsScalar && !CurFuncIsThunk && 1727 getTarget().getCXXABI().areArgsDestroyedLeftToRightInCallee()) { 1728 const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl(); 1729 if (RD && RD->hasNonTrivialDestructor()) 1730 pushDestroy(QualType::DK_cxx_destructor, DeclPtr, Ty); 1731 } 1732 } else { 1733 // Otherwise, create a temporary to hold the value. 1734 llvm::AllocaInst *Alloc = CreateTempAlloca(ConvertTypeForMem(Ty), 1735 D.getName() + ".addr"); 1736 Alloc->setAlignment(Align.getQuantity()); 1737 DeclPtr = Alloc; 1738 DoStore = true; 1739 } 1740 1741 LValue lv = MakeAddrLValue(DeclPtr, Ty, Align); 1742 if (IsScalar) { 1743 Qualifiers qs = Ty.getQualifiers(); 1744 if (Qualifiers::ObjCLifetime lt = qs.getObjCLifetime()) { 1745 // We honor __attribute__((ns_consumed)) for types with lifetime. 1746 // For __strong, it's handled by just skipping the initial retain; 1747 // otherwise we have to balance out the initial +1 with an extra 1748 // cleanup to do the release at the end of the function. 1749 bool isConsumed = D.hasAttr<NSConsumedAttr>(); 1750 1751 // 'self' is always formally __strong, but if this is not an 1752 // init method then we don't want to retain it. 1753 if (D.isARCPseudoStrong()) { 1754 const ObjCMethodDecl *method = cast<ObjCMethodDecl>(CurCodeDecl); 1755 assert(&D == method->getSelfDecl()); 1756 assert(lt == Qualifiers::OCL_Strong); 1757 assert(qs.hasConst()); 1758 assert(method->getMethodFamily() != OMF_init); 1759 (void) method; 1760 lt = Qualifiers::OCL_ExplicitNone; 1761 } 1762 1763 if (lt == Qualifiers::OCL_Strong) { 1764 if (!isConsumed) { 1765 if (CGM.getCodeGenOpts().OptimizationLevel == 0) { 1766 // use objc_storeStrong(&dest, value) for retaining the 1767 // object. But first, store a null into 'dest' because 1768 // objc_storeStrong attempts to release its old value. 1769 llvm::Value *Null = CGM.EmitNullConstant(D.getType()); 1770 EmitStoreOfScalar(Null, lv, /* isInitialization */ true); 1771 EmitARCStoreStrongCall(lv.getAddress(), Arg, true); 1772 DoStore = false; 1773 } 1774 else 1775 // Don't use objc_retainBlock for block pointers, because we 1776 // don't want to Block_copy something just because we got it 1777 // as a parameter. 1778 Arg = EmitARCRetainNonBlock(Arg); 1779 } 1780 } else { 1781 // Push the cleanup for a consumed parameter. 1782 if (isConsumed) { 1783 ARCPreciseLifetime_t precise = (D.hasAttr<ObjCPreciseLifetimeAttr>() 1784 ? ARCPreciseLifetime : ARCImpreciseLifetime); 1785 EHStack.pushCleanup<ConsumeARCParameter>(getARCCleanupKind(), Arg, 1786 precise); 1787 } 1788 1789 if (lt == Qualifiers::OCL_Weak) { 1790 EmitARCInitWeak(DeclPtr, Arg); 1791 DoStore = false; // The weak init is a store, no need to do two. 1792 } 1793 } 1794 1795 // Enter the cleanup scope. 1796 EmitAutoVarWithLifetime(*this, D, DeclPtr, lt); 1797 } 1798 } 1799 1800 // Store the initial value into the alloca. 1801 if (DoStore) 1802 EmitStoreOfScalar(Arg, lv, /* isInitialization */ true); 1803 1804 llvm::Value *&DMEntry = LocalDeclMap[&D]; 1805 assert(!DMEntry && "Decl already exists in localdeclmap!"); 1806 DMEntry = DeclPtr; 1807 1808 // Emit debug info for param declaration. 1809 if (CGDebugInfo *DI = getDebugInfo()) { 1810 if (CGM.getCodeGenOpts().getDebugInfo() 1811 >= CodeGenOptions::LimitedDebugInfo) { 1812 DI->EmitDeclareOfArgVariable(&D, DeclPtr, ArgNo, Builder); 1813 } 1814 } 1815 1816 if (D.hasAttr<AnnotateAttr>()) 1817 EmitVarAnnotations(&D, DeclPtr); 1818 } 1819