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