1 //===--- CGDecl.cpp - Emit LLVM Code for declarations ---------------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This contains code to emit Decl nodes as LLVM code. 10 // 11 //===----------------------------------------------------------------------===// 12 13 #include "CGBlocks.h" 14 #include "CGCXXABI.h" 15 #include "CGCleanup.h" 16 #include "CGDebugInfo.h" 17 #include "CGOpenCLRuntime.h" 18 #include "CGOpenMPRuntime.h" 19 #include "CodeGenFunction.h" 20 #include "CodeGenModule.h" 21 #include "ConstantEmitter.h" 22 #include "PatternInit.h" 23 #include "TargetInfo.h" 24 #include "clang/AST/ASTContext.h" 25 #include "clang/AST/CharUnits.h" 26 #include "clang/AST/Decl.h" 27 #include "clang/AST/DeclObjC.h" 28 #include "clang/AST/DeclOpenMP.h" 29 #include "clang/Basic/CodeGenOptions.h" 30 #include "clang/Basic/SourceManager.h" 31 #include "clang/Basic/TargetInfo.h" 32 #include "clang/CodeGen/CGFunctionInfo.h" 33 #include "llvm/Analysis/ValueTracking.h" 34 #include "llvm/IR/DataLayout.h" 35 #include "llvm/IR/GlobalVariable.h" 36 #include "llvm/IR/Intrinsics.h" 37 #include "llvm/IR/Type.h" 38 39 using namespace clang; 40 using namespace CodeGen; 41 42 void CodeGenFunction::EmitDecl(const Decl &D) { 43 switch (D.getKind()) { 44 case Decl::BuiltinTemplate: 45 case Decl::TranslationUnit: 46 case Decl::ExternCContext: 47 case Decl::Namespace: 48 case Decl::UnresolvedUsingTypename: 49 case Decl::ClassTemplateSpecialization: 50 case Decl::ClassTemplatePartialSpecialization: 51 case Decl::VarTemplateSpecialization: 52 case Decl::VarTemplatePartialSpecialization: 53 case Decl::TemplateTypeParm: 54 case Decl::UnresolvedUsingValue: 55 case Decl::NonTypeTemplateParm: 56 case Decl::CXXDeductionGuide: 57 case Decl::CXXMethod: 58 case Decl::CXXConstructor: 59 case Decl::CXXDestructor: 60 case Decl::CXXConversion: 61 case Decl::Field: 62 case Decl::MSProperty: 63 case Decl::IndirectField: 64 case Decl::ObjCIvar: 65 case Decl::ObjCAtDefsField: 66 case Decl::ParmVar: 67 case Decl::ImplicitParam: 68 case Decl::ClassTemplate: 69 case Decl::VarTemplate: 70 case Decl::FunctionTemplate: 71 case Decl::TypeAliasTemplate: 72 case Decl::TemplateTemplateParm: 73 case Decl::ObjCMethod: 74 case Decl::ObjCCategory: 75 case Decl::ObjCProtocol: 76 case Decl::ObjCInterface: 77 case Decl::ObjCCategoryImpl: 78 case Decl::ObjCImplementation: 79 case Decl::ObjCProperty: 80 case Decl::ObjCCompatibleAlias: 81 case Decl::PragmaComment: 82 case Decl::PragmaDetectMismatch: 83 case Decl::AccessSpec: 84 case Decl::LinkageSpec: 85 case Decl::Export: 86 case Decl::ObjCPropertyImpl: 87 case Decl::FileScopeAsm: 88 case Decl::Friend: 89 case Decl::FriendTemplate: 90 case Decl::Block: 91 case Decl::Captured: 92 case Decl::ClassScopeFunctionSpecialization: 93 case Decl::UsingShadow: 94 case Decl::ConstructorUsingShadow: 95 case Decl::ObjCTypeParam: 96 case Decl::Binding: 97 llvm_unreachable("Declaration should not be in declstmts!"); 98 case Decl::Function: // void X(); 99 case Decl::Record: // struct/union/class X; 100 case Decl::Enum: // enum X; 101 case Decl::EnumConstant: // enum ? { X = ? } 102 case Decl::CXXRecord: // struct/union/class X; [C++] 103 case Decl::StaticAssert: // static_assert(X, ""); [C++0x] 104 case Decl::Label: // __label__ x; 105 case Decl::Import: 106 case Decl::OMPThreadPrivate: 107 case Decl::OMPAllocate: 108 case Decl::OMPCapturedExpr: 109 case Decl::OMPRequires: 110 case Decl::Empty: 111 // None of these decls require codegen support. 112 return; 113 114 case Decl::NamespaceAlias: 115 if (CGDebugInfo *DI = getDebugInfo()) 116 DI->EmitNamespaceAlias(cast<NamespaceAliasDecl>(D)); 117 return; 118 case Decl::Using: // using X; [C++] 119 if (CGDebugInfo *DI = getDebugInfo()) 120 DI->EmitUsingDecl(cast<UsingDecl>(D)); 121 return; 122 case Decl::UsingPack: 123 for (auto *Using : cast<UsingPackDecl>(D).expansions()) 124 EmitDecl(*Using); 125 return; 126 case Decl::UsingDirective: // using namespace X; [C++] 127 if (CGDebugInfo *DI = getDebugInfo()) 128 DI->EmitUsingDirective(cast<UsingDirectiveDecl>(D)); 129 return; 130 case Decl::Var: 131 case Decl::Decomposition: { 132 const VarDecl &VD = cast<VarDecl>(D); 133 assert(VD.isLocalVarDecl() && 134 "Should not see file-scope variables inside a function!"); 135 EmitVarDecl(VD); 136 if (auto *DD = dyn_cast<DecompositionDecl>(&VD)) 137 for (auto *B : DD->bindings()) 138 if (auto *HD = B->getHoldingVar()) 139 EmitVarDecl(*HD); 140 return; 141 } 142 143 case Decl::OMPDeclareReduction: 144 return CGM.EmitOMPDeclareReduction(cast<OMPDeclareReductionDecl>(&D), this); 145 146 case Decl::OMPDeclareMapper: 147 return CGM.EmitOMPDeclareMapper(cast<OMPDeclareMapperDecl>(&D), this); 148 149 case Decl::Typedef: // typedef int X; 150 case Decl::TypeAlias: { // using X = int; [C++0x] 151 const TypedefNameDecl &TD = cast<TypedefNameDecl>(D); 152 QualType Ty = TD.getUnderlyingType(); 153 154 if (Ty->isVariablyModifiedType()) 155 EmitVariablyModifiedType(Ty); 156 157 return; 158 } 159 } 160 } 161 162 /// EmitVarDecl - This method handles emission of any variable declaration 163 /// inside a function, including static vars etc. 164 void CodeGenFunction::EmitVarDecl(const VarDecl &D) { 165 if (D.hasExternalStorage()) 166 // Don't emit it now, allow it to be emitted lazily on its first use. 167 return; 168 169 // Some function-scope variable does not have static storage but still 170 // needs to be emitted like a static variable, e.g. a function-scope 171 // variable in constant address space in OpenCL. 172 if (D.getStorageDuration() != SD_Automatic) { 173 // Static sampler variables translated to function calls. 174 if (D.getType()->isSamplerT()) 175 return; 176 177 llvm::GlobalValue::LinkageTypes Linkage = 178 CGM.getLLVMLinkageVarDefinition(&D, /*isConstant=*/false); 179 180 // FIXME: We need to force the emission/use of a guard variable for 181 // some variables even if we can constant-evaluate them because 182 // we can't guarantee every translation unit will constant-evaluate them. 183 184 return EmitStaticVarDecl(D, Linkage); 185 } 186 187 if (D.getType().getAddressSpace() == LangAS::opencl_local) 188 return CGM.getOpenCLRuntime().EmitWorkGroupLocalVarDecl(*this, D); 189 190 assert(D.hasLocalStorage()); 191 return EmitAutoVarDecl(D); 192 } 193 194 static std::string getStaticDeclName(CodeGenModule &CGM, const VarDecl &D) { 195 if (CGM.getLangOpts().CPlusPlus) 196 return CGM.getMangledName(&D).str(); 197 198 // If this isn't C++, we don't need a mangled name, just a pretty one. 199 assert(!D.isExternallyVisible() && "name shouldn't matter"); 200 std::string ContextName; 201 const DeclContext *DC = D.getDeclContext(); 202 if (auto *CD = dyn_cast<CapturedDecl>(DC)) 203 DC = cast<DeclContext>(CD->getNonClosureContext()); 204 if (const auto *FD = dyn_cast<FunctionDecl>(DC)) 205 ContextName = CGM.getMangledName(FD); 206 else if (const auto *BD = dyn_cast<BlockDecl>(DC)) 207 ContextName = CGM.getBlockMangledName(GlobalDecl(), BD); 208 else if (const auto *OMD = dyn_cast<ObjCMethodDecl>(DC)) 209 ContextName = OMD->getSelector().getAsString(); 210 else 211 llvm_unreachable("Unknown context for static var decl"); 212 213 ContextName += "." + D.getNameAsString(); 214 return ContextName; 215 } 216 217 llvm::Constant *CodeGenModule::getOrCreateStaticVarDecl( 218 const VarDecl &D, llvm::GlobalValue::LinkageTypes Linkage) { 219 // In general, we don't always emit static var decls once before we reference 220 // them. It is possible to reference them before emitting the function that 221 // contains them, and it is possible to emit the containing function multiple 222 // times. 223 if (llvm::Constant *ExistingGV = StaticLocalDeclMap[&D]) 224 return ExistingGV; 225 226 QualType Ty = D.getType(); 227 assert(Ty->isConstantSizeType() && "VLAs can't be static"); 228 229 // Use the label if the variable is renamed with the asm-label extension. 230 std::string Name; 231 if (D.hasAttr<AsmLabelAttr>()) 232 Name = getMangledName(&D); 233 else 234 Name = getStaticDeclName(*this, D); 235 236 llvm::Type *LTy = getTypes().ConvertTypeForMem(Ty); 237 LangAS AS = GetGlobalVarAddressSpace(&D); 238 unsigned TargetAS = getContext().getTargetAddressSpace(AS); 239 240 // OpenCL variables in local address space and CUDA shared 241 // variables cannot have an initializer. 242 llvm::Constant *Init = nullptr; 243 if (Ty.getAddressSpace() == LangAS::opencl_local || 244 D.hasAttr<CUDASharedAttr>()) 245 Init = llvm::UndefValue::get(LTy); 246 else 247 Init = EmitNullConstant(Ty); 248 249 llvm::GlobalVariable *GV = new llvm::GlobalVariable( 250 getModule(), LTy, Ty.isConstant(getContext()), Linkage, Init, Name, 251 nullptr, llvm::GlobalVariable::NotThreadLocal, TargetAS); 252 GV->setAlignment(getContext().getDeclAlign(&D).getQuantity()); 253 254 if (supportsCOMDAT() && GV->isWeakForLinker()) 255 GV->setComdat(TheModule.getOrInsertComdat(GV->getName())); 256 257 if (D.getTLSKind()) 258 setTLSMode(GV, D); 259 260 setGVProperties(GV, &D); 261 262 // Make sure the result is of the correct type. 263 LangAS ExpectedAS = Ty.getAddressSpace(); 264 llvm::Constant *Addr = GV; 265 if (AS != ExpectedAS) { 266 Addr = getTargetCodeGenInfo().performAddrSpaceCast( 267 *this, GV, AS, ExpectedAS, 268 LTy->getPointerTo(getContext().getTargetAddressSpace(ExpectedAS))); 269 } 270 271 setStaticLocalDeclAddress(&D, Addr); 272 273 // Ensure that the static local gets initialized by making sure the parent 274 // function gets emitted eventually. 275 const Decl *DC = cast<Decl>(D.getDeclContext()); 276 277 // We can't name blocks or captured statements directly, so try to emit their 278 // parents. 279 if (isa<BlockDecl>(DC) || isa<CapturedDecl>(DC)) { 280 DC = DC->getNonClosureContext(); 281 // FIXME: Ensure that global blocks get emitted. 282 if (!DC) 283 return Addr; 284 } 285 286 GlobalDecl GD; 287 if (const auto *CD = dyn_cast<CXXConstructorDecl>(DC)) 288 GD = GlobalDecl(CD, Ctor_Base); 289 else if (const auto *DD = dyn_cast<CXXDestructorDecl>(DC)) 290 GD = GlobalDecl(DD, Dtor_Base); 291 else if (const auto *FD = dyn_cast<FunctionDecl>(DC)) 292 GD = GlobalDecl(FD); 293 else { 294 // Don't do anything for Obj-C method decls or global closures. We should 295 // never defer them. 296 assert(isa<ObjCMethodDecl>(DC) && "unexpected parent code decl"); 297 } 298 if (GD.getDecl()) { 299 // Disable emission of the parent function for the OpenMP device codegen. 300 CGOpenMPRuntime::DisableAutoDeclareTargetRAII NoDeclTarget(*this); 301 (void)GetAddrOfGlobal(GD); 302 } 303 304 return Addr; 305 } 306 307 /// hasNontrivialDestruction - Determine whether a type's destruction is 308 /// non-trivial. If so, and the variable uses static initialization, we must 309 /// register its destructor to run on exit. 310 static bool hasNontrivialDestruction(QualType T) { 311 CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl(); 312 return RD && !RD->hasTrivialDestructor(); 313 } 314 315 /// AddInitializerToStaticVarDecl - Add the initializer for 'D' to the 316 /// global variable that has already been created for it. If the initializer 317 /// has a different type than GV does, this may free GV and return a different 318 /// one. Otherwise it just returns GV. 319 llvm::GlobalVariable * 320 CodeGenFunction::AddInitializerToStaticVarDecl(const VarDecl &D, 321 llvm::GlobalVariable *GV) { 322 ConstantEmitter emitter(*this); 323 llvm::Constant *Init = emitter.tryEmitForInitializer(D); 324 325 // If constant emission failed, then this should be a C++ static 326 // initializer. 327 if (!Init) { 328 if (!getLangOpts().CPlusPlus) 329 CGM.ErrorUnsupported(D.getInit(), "constant l-value expression"); 330 else if (HaveInsertPoint()) { 331 // Since we have a static initializer, this global variable can't 332 // be constant. 333 GV->setConstant(false); 334 335 EmitCXXGuardedInit(D, GV, /*PerformInit*/true); 336 } 337 return GV; 338 } 339 340 // The initializer may differ in type from the global. Rewrite 341 // the global to match the initializer. (We have to do this 342 // because some types, like unions, can't be completely represented 343 // in the LLVM type system.) 344 if (GV->getType()->getElementType() != Init->getType()) { 345 llvm::GlobalVariable *OldGV = GV; 346 347 GV = new llvm::GlobalVariable(CGM.getModule(), Init->getType(), 348 OldGV->isConstant(), 349 OldGV->getLinkage(), Init, "", 350 /*InsertBefore*/ OldGV, 351 OldGV->getThreadLocalMode(), 352 CGM.getContext().getTargetAddressSpace(D.getType())); 353 GV->setVisibility(OldGV->getVisibility()); 354 GV->setDSOLocal(OldGV->isDSOLocal()); 355 GV->setComdat(OldGV->getComdat()); 356 357 // Steal the name of the old global 358 GV->takeName(OldGV); 359 360 // Replace all uses of the old global with the new global 361 llvm::Constant *NewPtrForOldDecl = 362 llvm::ConstantExpr::getBitCast(GV, OldGV->getType()); 363 OldGV->replaceAllUsesWith(NewPtrForOldDecl); 364 365 // Erase the old global, since it is no longer used. 366 OldGV->eraseFromParent(); 367 } 368 369 GV->setConstant(CGM.isTypeConstant(D.getType(), true)); 370 GV->setInitializer(Init); 371 372 emitter.finalize(GV); 373 374 if (hasNontrivialDestruction(D.getType()) && HaveInsertPoint()) { 375 // We have a constant initializer, but a nontrivial destructor. We still 376 // need to perform a guarded "initialization" in order to register the 377 // destructor. 378 EmitCXXGuardedInit(D, GV, /*PerformInit*/false); 379 } 380 381 return GV; 382 } 383 384 void CodeGenFunction::EmitStaticVarDecl(const VarDecl &D, 385 llvm::GlobalValue::LinkageTypes Linkage) { 386 // Check to see if we already have a global variable for this 387 // declaration. This can happen when double-emitting function 388 // bodies, e.g. with complete and base constructors. 389 llvm::Constant *addr = CGM.getOrCreateStaticVarDecl(D, Linkage); 390 CharUnits alignment = getContext().getDeclAlign(&D); 391 392 // Store into LocalDeclMap before generating initializer to handle 393 // circular references. 394 setAddrOfLocalVar(&D, Address(addr, alignment)); 395 396 // We can't have a VLA here, but we can have a pointer to a VLA, 397 // even though that doesn't really make any sense. 398 // Make sure to evaluate VLA bounds now so that we have them for later. 399 if (D.getType()->isVariablyModifiedType()) 400 EmitVariablyModifiedType(D.getType()); 401 402 // Save the type in case adding the initializer forces a type change. 403 llvm::Type *expectedType = addr->getType(); 404 405 llvm::GlobalVariable *var = 406 cast<llvm::GlobalVariable>(addr->stripPointerCasts()); 407 408 // CUDA's local and local static __shared__ variables should not 409 // have any non-empty initializers. This is ensured by Sema. 410 // Whatever initializer such variable may have when it gets here is 411 // a no-op and should not be emitted. 412 bool isCudaSharedVar = getLangOpts().CUDA && getLangOpts().CUDAIsDevice && 413 D.hasAttr<CUDASharedAttr>(); 414 // If this value has an initializer, emit it. 415 if (D.getInit() && !isCudaSharedVar) 416 var = AddInitializerToStaticVarDecl(D, var); 417 418 var->setAlignment(alignment.getQuantity()); 419 420 if (D.hasAttr<AnnotateAttr>()) 421 CGM.AddGlobalAnnotations(&D, var); 422 423 if (auto *SA = D.getAttr<PragmaClangBSSSectionAttr>()) 424 var->addAttribute("bss-section", SA->getName()); 425 if (auto *SA = D.getAttr<PragmaClangDataSectionAttr>()) 426 var->addAttribute("data-section", SA->getName()); 427 if (auto *SA = D.getAttr<PragmaClangRodataSectionAttr>()) 428 var->addAttribute("rodata-section", SA->getName()); 429 430 if (const SectionAttr *SA = D.getAttr<SectionAttr>()) 431 var->setSection(SA->getName()); 432 433 if (D.hasAttr<UsedAttr>()) 434 CGM.addUsedGlobal(var); 435 436 // We may have to cast the constant because of the initializer 437 // mismatch above. 438 // 439 // FIXME: It is really dangerous to store this in the map; if anyone 440 // RAUW's the GV uses of this constant will be invalid. 441 llvm::Constant *castedAddr = 442 llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(var, expectedType); 443 if (var != castedAddr) 444 LocalDeclMap.find(&D)->second = Address(castedAddr, alignment); 445 CGM.setStaticLocalDeclAddress(&D, castedAddr); 446 447 CGM.getSanitizerMetadata()->reportGlobalToASan(var, D); 448 449 // Emit global variable debug descriptor for static vars. 450 CGDebugInfo *DI = getDebugInfo(); 451 if (DI && 452 CGM.getCodeGenOpts().getDebugInfo() >= codegenoptions::LimitedDebugInfo) { 453 DI->setLocation(D.getLocation()); 454 DI->EmitGlobalVariable(var, &D); 455 } 456 } 457 458 namespace { 459 struct DestroyObject final : EHScopeStack::Cleanup { 460 DestroyObject(Address addr, QualType type, 461 CodeGenFunction::Destroyer *destroyer, 462 bool useEHCleanupForArray) 463 : addr(addr), type(type), destroyer(destroyer), 464 useEHCleanupForArray(useEHCleanupForArray) {} 465 466 Address addr; 467 QualType type; 468 CodeGenFunction::Destroyer *destroyer; 469 bool useEHCleanupForArray; 470 471 void Emit(CodeGenFunction &CGF, Flags flags) override { 472 // Don't use an EH cleanup recursively from an EH cleanup. 473 bool useEHCleanupForArray = 474 flags.isForNormalCleanup() && this->useEHCleanupForArray; 475 476 CGF.emitDestroy(addr, type, destroyer, useEHCleanupForArray); 477 } 478 }; 479 480 template <class Derived> 481 struct DestroyNRVOVariable : EHScopeStack::Cleanup { 482 DestroyNRVOVariable(Address addr, llvm::Value *NRVOFlag) 483 : NRVOFlag(NRVOFlag), Loc(addr) {} 484 485 llvm::Value *NRVOFlag; 486 Address Loc; 487 488 void Emit(CodeGenFunction &CGF, Flags flags) override { 489 // Along the exceptions path we always execute the dtor. 490 bool NRVO = flags.isForNormalCleanup() && NRVOFlag; 491 492 llvm::BasicBlock *SkipDtorBB = nullptr; 493 if (NRVO) { 494 // If we exited via NRVO, we skip the destructor call. 495 llvm::BasicBlock *RunDtorBB = CGF.createBasicBlock("nrvo.unused"); 496 SkipDtorBB = CGF.createBasicBlock("nrvo.skipdtor"); 497 llvm::Value *DidNRVO = 498 CGF.Builder.CreateFlagLoad(NRVOFlag, "nrvo.val"); 499 CGF.Builder.CreateCondBr(DidNRVO, SkipDtorBB, RunDtorBB); 500 CGF.EmitBlock(RunDtorBB); 501 } 502 503 static_cast<Derived *>(this)->emitDestructorCall(CGF); 504 505 if (NRVO) CGF.EmitBlock(SkipDtorBB); 506 } 507 508 virtual ~DestroyNRVOVariable() = default; 509 }; 510 511 struct DestroyNRVOVariableCXX final 512 : DestroyNRVOVariable<DestroyNRVOVariableCXX> { 513 DestroyNRVOVariableCXX(Address addr, const CXXDestructorDecl *Dtor, 514 llvm::Value *NRVOFlag) 515 : DestroyNRVOVariable<DestroyNRVOVariableCXX>(addr, NRVOFlag), 516 Dtor(Dtor) {} 517 518 const CXXDestructorDecl *Dtor; 519 520 void emitDestructorCall(CodeGenFunction &CGF) { 521 CGF.EmitCXXDestructorCall(Dtor, Dtor_Complete, 522 /*ForVirtualBase=*/false, 523 /*Delegating=*/false, Loc); 524 } 525 }; 526 527 struct DestroyNRVOVariableC final 528 : DestroyNRVOVariable<DestroyNRVOVariableC> { 529 DestroyNRVOVariableC(Address addr, llvm::Value *NRVOFlag, QualType Ty) 530 : DestroyNRVOVariable<DestroyNRVOVariableC>(addr, NRVOFlag), Ty(Ty) {} 531 532 QualType Ty; 533 534 void emitDestructorCall(CodeGenFunction &CGF) { 535 CGF.destroyNonTrivialCStruct(CGF, Loc, Ty); 536 } 537 }; 538 539 struct CallStackRestore final : EHScopeStack::Cleanup { 540 Address Stack; 541 CallStackRestore(Address Stack) : Stack(Stack) {} 542 void Emit(CodeGenFunction &CGF, Flags flags) override { 543 llvm::Value *V = CGF.Builder.CreateLoad(Stack); 544 llvm::Function *F = CGF.CGM.getIntrinsic(llvm::Intrinsic::stackrestore); 545 CGF.Builder.CreateCall(F, V); 546 } 547 }; 548 549 struct ExtendGCLifetime final : EHScopeStack::Cleanup { 550 const VarDecl &Var; 551 ExtendGCLifetime(const VarDecl *var) : Var(*var) {} 552 553 void Emit(CodeGenFunction &CGF, Flags flags) override { 554 // Compute the address of the local variable, in case it's a 555 // byref or something. 556 DeclRefExpr DRE(CGF.getContext(), const_cast<VarDecl *>(&Var), false, 557 Var.getType(), VK_LValue, SourceLocation()); 558 llvm::Value *value = CGF.EmitLoadOfScalar(CGF.EmitDeclRefLValue(&DRE), 559 SourceLocation()); 560 CGF.EmitExtendGCLifetime(value); 561 } 562 }; 563 564 struct CallCleanupFunction final : EHScopeStack::Cleanup { 565 llvm::Constant *CleanupFn; 566 const CGFunctionInfo &FnInfo; 567 const VarDecl &Var; 568 569 CallCleanupFunction(llvm::Constant *CleanupFn, const CGFunctionInfo *Info, 570 const VarDecl *Var) 571 : CleanupFn(CleanupFn), FnInfo(*Info), Var(*Var) {} 572 573 void Emit(CodeGenFunction &CGF, Flags flags) override { 574 DeclRefExpr DRE(CGF.getContext(), const_cast<VarDecl *>(&Var), false, 575 Var.getType(), VK_LValue, SourceLocation()); 576 // Compute the address of the local variable, in case it's a byref 577 // or something. 578 llvm::Value *Addr = CGF.EmitDeclRefLValue(&DRE).getPointer(); 579 580 // In some cases, the type of the function argument will be different from 581 // the type of the pointer. An example of this is 582 // void f(void* arg); 583 // __attribute__((cleanup(f))) void *g; 584 // 585 // To fix this we insert a bitcast here. 586 QualType ArgTy = FnInfo.arg_begin()->type; 587 llvm::Value *Arg = 588 CGF.Builder.CreateBitCast(Addr, CGF.ConvertType(ArgTy)); 589 590 CallArgList Args; 591 Args.add(RValue::get(Arg), 592 CGF.getContext().getPointerType(Var.getType())); 593 auto Callee = CGCallee::forDirect(CleanupFn); 594 CGF.EmitCall(FnInfo, Callee, ReturnValueSlot(), Args); 595 } 596 }; 597 } // end anonymous namespace 598 599 /// EmitAutoVarWithLifetime - Does the setup required for an automatic 600 /// variable with lifetime. 601 static void EmitAutoVarWithLifetime(CodeGenFunction &CGF, const VarDecl &var, 602 Address addr, 603 Qualifiers::ObjCLifetime lifetime) { 604 switch (lifetime) { 605 case Qualifiers::OCL_None: 606 llvm_unreachable("present but none"); 607 608 case Qualifiers::OCL_ExplicitNone: 609 // nothing to do 610 break; 611 612 case Qualifiers::OCL_Strong: { 613 CodeGenFunction::Destroyer *destroyer = 614 (var.hasAttr<ObjCPreciseLifetimeAttr>() 615 ? CodeGenFunction::destroyARCStrongPrecise 616 : CodeGenFunction::destroyARCStrongImprecise); 617 618 CleanupKind cleanupKind = CGF.getARCCleanupKind(); 619 CGF.pushDestroy(cleanupKind, addr, var.getType(), destroyer, 620 cleanupKind & EHCleanup); 621 break; 622 } 623 case Qualifiers::OCL_Autoreleasing: 624 // nothing to do 625 break; 626 627 case Qualifiers::OCL_Weak: 628 // __weak objects always get EH cleanups; otherwise, exceptions 629 // could cause really nasty crashes instead of mere leaks. 630 CGF.pushDestroy(NormalAndEHCleanup, addr, var.getType(), 631 CodeGenFunction::destroyARCWeak, 632 /*useEHCleanup*/ true); 633 break; 634 } 635 } 636 637 static bool isAccessedBy(const VarDecl &var, const Stmt *s) { 638 if (const Expr *e = dyn_cast<Expr>(s)) { 639 // Skip the most common kinds of expressions that make 640 // hierarchy-walking expensive. 641 s = e = e->IgnoreParenCasts(); 642 643 if (const DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) 644 return (ref->getDecl() == &var); 645 if (const BlockExpr *be = dyn_cast<BlockExpr>(e)) { 646 const BlockDecl *block = be->getBlockDecl(); 647 for (const auto &I : block->captures()) { 648 if (I.getVariable() == &var) 649 return true; 650 } 651 } 652 } 653 654 for (const Stmt *SubStmt : s->children()) 655 // SubStmt might be null; as in missing decl or conditional of an if-stmt. 656 if (SubStmt && isAccessedBy(var, SubStmt)) 657 return true; 658 659 return false; 660 } 661 662 static bool isAccessedBy(const ValueDecl *decl, const Expr *e) { 663 if (!decl) return false; 664 if (!isa<VarDecl>(decl)) return false; 665 const VarDecl *var = cast<VarDecl>(decl); 666 return isAccessedBy(*var, e); 667 } 668 669 static bool tryEmitARCCopyWeakInit(CodeGenFunction &CGF, 670 const LValue &destLV, const Expr *init) { 671 bool needsCast = false; 672 673 while (auto castExpr = dyn_cast<CastExpr>(init->IgnoreParens())) { 674 switch (castExpr->getCastKind()) { 675 // Look through casts that don't require representation changes. 676 case CK_NoOp: 677 case CK_BitCast: 678 case CK_BlockPointerToObjCPointerCast: 679 needsCast = true; 680 break; 681 682 // If we find an l-value to r-value cast from a __weak variable, 683 // emit this operation as a copy or move. 684 case CK_LValueToRValue: { 685 const Expr *srcExpr = castExpr->getSubExpr(); 686 if (srcExpr->getType().getObjCLifetime() != Qualifiers::OCL_Weak) 687 return false; 688 689 // Emit the source l-value. 690 LValue srcLV = CGF.EmitLValue(srcExpr); 691 692 // Handle a formal type change to avoid asserting. 693 auto srcAddr = srcLV.getAddress(); 694 if (needsCast) { 695 srcAddr = CGF.Builder.CreateElementBitCast(srcAddr, 696 destLV.getAddress().getElementType()); 697 } 698 699 // If it was an l-value, use objc_copyWeak. 700 if (srcExpr->getValueKind() == VK_LValue) { 701 CGF.EmitARCCopyWeak(destLV.getAddress(), srcAddr); 702 } else { 703 assert(srcExpr->getValueKind() == VK_XValue); 704 CGF.EmitARCMoveWeak(destLV.getAddress(), srcAddr); 705 } 706 return true; 707 } 708 709 // Stop at anything else. 710 default: 711 return false; 712 } 713 714 init = castExpr->getSubExpr(); 715 } 716 return false; 717 } 718 719 static void drillIntoBlockVariable(CodeGenFunction &CGF, 720 LValue &lvalue, 721 const VarDecl *var) { 722 lvalue.setAddress(CGF.emitBlockByrefAddress(lvalue.getAddress(), var)); 723 } 724 725 void CodeGenFunction::EmitNullabilityCheck(LValue LHS, llvm::Value *RHS, 726 SourceLocation Loc) { 727 if (!SanOpts.has(SanitizerKind::NullabilityAssign)) 728 return; 729 730 auto Nullability = LHS.getType()->getNullability(getContext()); 731 if (!Nullability || *Nullability != NullabilityKind::NonNull) 732 return; 733 734 // Check if the right hand side of the assignment is nonnull, if the left 735 // hand side must be nonnull. 736 SanitizerScope SanScope(this); 737 llvm::Value *IsNotNull = Builder.CreateIsNotNull(RHS); 738 llvm::Constant *StaticData[] = { 739 EmitCheckSourceLocation(Loc), EmitCheckTypeDescriptor(LHS.getType()), 740 llvm::ConstantInt::get(Int8Ty, 0), // The LogAlignment info is unused. 741 llvm::ConstantInt::get(Int8Ty, TCK_NonnullAssign)}; 742 EmitCheck({{IsNotNull, SanitizerKind::NullabilityAssign}}, 743 SanitizerHandler::TypeMismatch, StaticData, RHS); 744 } 745 746 void CodeGenFunction::EmitScalarInit(const Expr *init, const ValueDecl *D, 747 LValue lvalue, bool capturedByInit) { 748 Qualifiers::ObjCLifetime lifetime = lvalue.getObjCLifetime(); 749 if (!lifetime) { 750 llvm::Value *value = EmitScalarExpr(init); 751 if (capturedByInit) 752 drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D)); 753 EmitNullabilityCheck(lvalue, value, init->getExprLoc()); 754 EmitStoreThroughLValue(RValue::get(value), lvalue, true); 755 return; 756 } 757 758 if (const CXXDefaultInitExpr *DIE = dyn_cast<CXXDefaultInitExpr>(init)) 759 init = DIE->getExpr(); 760 761 // If we're emitting a value with lifetime, we have to do the 762 // initialization *before* we leave the cleanup scopes. 763 if (const FullExpr *fe = dyn_cast<FullExpr>(init)) { 764 enterFullExpression(fe); 765 init = fe->getSubExpr(); 766 } 767 CodeGenFunction::RunCleanupsScope Scope(*this); 768 769 // We have to maintain the illusion that the variable is 770 // zero-initialized. If the variable might be accessed in its 771 // initializer, zero-initialize before running the initializer, then 772 // actually perform the initialization with an assign. 773 bool accessedByInit = false; 774 if (lifetime != Qualifiers::OCL_ExplicitNone) 775 accessedByInit = (capturedByInit || isAccessedBy(D, init)); 776 if (accessedByInit) { 777 LValue tempLV = lvalue; 778 // Drill down to the __block object if necessary. 779 if (capturedByInit) { 780 // We can use a simple GEP for this because it can't have been 781 // moved yet. 782 tempLV.setAddress(emitBlockByrefAddress(tempLV.getAddress(), 783 cast<VarDecl>(D), 784 /*follow*/ false)); 785 } 786 787 auto ty = cast<llvm::PointerType>(tempLV.getAddress().getElementType()); 788 llvm::Value *zero = CGM.getNullPointer(ty, tempLV.getType()); 789 790 // If __weak, we want to use a barrier under certain conditions. 791 if (lifetime == Qualifiers::OCL_Weak) 792 EmitARCInitWeak(tempLV.getAddress(), zero); 793 794 // Otherwise just do a simple store. 795 else 796 EmitStoreOfScalar(zero, tempLV, /* isInitialization */ true); 797 } 798 799 // Emit the initializer. 800 llvm::Value *value = nullptr; 801 802 switch (lifetime) { 803 case Qualifiers::OCL_None: 804 llvm_unreachable("present but none"); 805 806 case Qualifiers::OCL_Strong: { 807 if (!D || !isa<VarDecl>(D) || !cast<VarDecl>(D)->isARCPseudoStrong()) { 808 value = EmitARCRetainScalarExpr(init); 809 break; 810 } 811 // If D is pseudo-strong, treat it like __unsafe_unretained here. This means 812 // that we omit the retain, and causes non-autoreleased return values to be 813 // immediately released. 814 LLVM_FALLTHROUGH; 815 } 816 817 case Qualifiers::OCL_ExplicitNone: 818 value = EmitARCUnsafeUnretainedScalarExpr(init); 819 break; 820 821 case Qualifiers::OCL_Weak: { 822 // If it's not accessed by the initializer, try to emit the 823 // initialization with a copy or move. 824 if (!accessedByInit && tryEmitARCCopyWeakInit(*this, lvalue, init)) { 825 return; 826 } 827 828 // No way to optimize a producing initializer into this. It's not 829 // worth optimizing for, because the value will immediately 830 // disappear in the common case. 831 value = EmitScalarExpr(init); 832 833 if (capturedByInit) drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D)); 834 if (accessedByInit) 835 EmitARCStoreWeak(lvalue.getAddress(), value, /*ignored*/ true); 836 else 837 EmitARCInitWeak(lvalue.getAddress(), value); 838 return; 839 } 840 841 case Qualifiers::OCL_Autoreleasing: 842 value = EmitARCRetainAutoreleaseScalarExpr(init); 843 break; 844 } 845 846 if (capturedByInit) drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D)); 847 848 EmitNullabilityCheck(lvalue, value, init->getExprLoc()); 849 850 // If the variable might have been accessed by its initializer, we 851 // might have to initialize with a barrier. We have to do this for 852 // both __weak and __strong, but __weak got filtered out above. 853 if (accessedByInit && lifetime == Qualifiers::OCL_Strong) { 854 llvm::Value *oldValue = EmitLoadOfScalar(lvalue, init->getExprLoc()); 855 EmitStoreOfScalar(value, lvalue, /* isInitialization */ true); 856 EmitARCRelease(oldValue, ARCImpreciseLifetime); 857 return; 858 } 859 860 EmitStoreOfScalar(value, lvalue, /* isInitialization */ true); 861 } 862 863 /// Decide whether we can emit the non-zero parts of the specified initializer 864 /// with equal or fewer than NumStores scalar stores. 865 static bool canEmitInitWithFewStoresAfterBZero(llvm::Constant *Init, 866 unsigned &NumStores) { 867 // Zero and Undef never requires any extra stores. 868 if (isa<llvm::ConstantAggregateZero>(Init) || 869 isa<llvm::ConstantPointerNull>(Init) || 870 isa<llvm::UndefValue>(Init)) 871 return true; 872 if (isa<llvm::ConstantInt>(Init) || isa<llvm::ConstantFP>(Init) || 873 isa<llvm::ConstantVector>(Init) || isa<llvm::BlockAddress>(Init) || 874 isa<llvm::ConstantExpr>(Init)) 875 return Init->isNullValue() || NumStores--; 876 877 // See if we can emit each element. 878 if (isa<llvm::ConstantArray>(Init) || isa<llvm::ConstantStruct>(Init)) { 879 for (unsigned i = 0, e = Init->getNumOperands(); i != e; ++i) { 880 llvm::Constant *Elt = cast<llvm::Constant>(Init->getOperand(i)); 881 if (!canEmitInitWithFewStoresAfterBZero(Elt, NumStores)) 882 return false; 883 } 884 return true; 885 } 886 887 if (llvm::ConstantDataSequential *CDS = 888 dyn_cast<llvm::ConstantDataSequential>(Init)) { 889 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) { 890 llvm::Constant *Elt = CDS->getElementAsConstant(i); 891 if (!canEmitInitWithFewStoresAfterBZero(Elt, NumStores)) 892 return false; 893 } 894 return true; 895 } 896 897 // Anything else is hard and scary. 898 return false; 899 } 900 901 /// For inits that canEmitInitWithFewStoresAfterBZero returned true for, emit 902 /// the scalar stores that would be required. 903 static void emitStoresForInitAfterBZero(CodeGenModule &CGM, 904 llvm::Constant *Init, Address Loc, 905 bool isVolatile, CGBuilderTy &Builder) { 906 assert(!Init->isNullValue() && !isa<llvm::UndefValue>(Init) && 907 "called emitStoresForInitAfterBZero for zero or undef value."); 908 909 if (isa<llvm::ConstantInt>(Init) || isa<llvm::ConstantFP>(Init) || 910 isa<llvm::ConstantVector>(Init) || isa<llvm::BlockAddress>(Init) || 911 isa<llvm::ConstantExpr>(Init)) { 912 Builder.CreateStore(Init, Loc, isVolatile); 913 return; 914 } 915 916 if (llvm::ConstantDataSequential *CDS = 917 dyn_cast<llvm::ConstantDataSequential>(Init)) { 918 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) { 919 llvm::Constant *Elt = CDS->getElementAsConstant(i); 920 921 // If necessary, get a pointer to the element and emit it. 922 if (!Elt->isNullValue() && !isa<llvm::UndefValue>(Elt)) 923 emitStoresForInitAfterBZero( 924 CGM, Elt, Builder.CreateConstInBoundsGEP2_32(Loc, 0, i), isVolatile, 925 Builder); 926 } 927 return; 928 } 929 930 assert((isa<llvm::ConstantStruct>(Init) || isa<llvm::ConstantArray>(Init)) && 931 "Unknown value type!"); 932 933 for (unsigned i = 0, e = Init->getNumOperands(); i != e; ++i) { 934 llvm::Constant *Elt = cast<llvm::Constant>(Init->getOperand(i)); 935 936 // If necessary, get a pointer to the element and emit it. 937 if (!Elt->isNullValue() && !isa<llvm::UndefValue>(Elt)) 938 emitStoresForInitAfterBZero(CGM, Elt, 939 Builder.CreateConstInBoundsGEP2_32(Loc, 0, i), 940 isVolatile, Builder); 941 } 942 } 943 944 /// Decide whether we should use bzero plus some stores to initialize a local 945 /// variable instead of using a memcpy from a constant global. It is beneficial 946 /// to use bzero if the global is all zeros, or mostly zeros and large. 947 static bool shouldUseBZeroPlusStoresToInitialize(llvm::Constant *Init, 948 uint64_t GlobalSize) { 949 // If a global is all zeros, always use a bzero. 950 if (isa<llvm::ConstantAggregateZero>(Init)) return true; 951 952 // If a non-zero global is <= 32 bytes, always use a memcpy. If it is large, 953 // do it if it will require 6 or fewer scalar stores. 954 // TODO: Should budget depends on the size? Avoiding a large global warrants 955 // plopping in more stores. 956 unsigned StoreBudget = 6; 957 uint64_t SizeLimit = 32; 958 959 return GlobalSize > SizeLimit && 960 canEmitInitWithFewStoresAfterBZero(Init, StoreBudget); 961 } 962 963 /// Decide whether we should use memset to initialize a local variable instead 964 /// of using a memcpy from a constant global. Assumes we've already decided to 965 /// not user bzero. 966 /// FIXME We could be more clever, as we are for bzero above, and generate 967 /// memset followed by stores. It's unclear that's worth the effort. 968 static llvm::Value *shouldUseMemSetToInitialize(llvm::Constant *Init, 969 uint64_t GlobalSize) { 970 uint64_t SizeLimit = 32; 971 if (GlobalSize <= SizeLimit) 972 return nullptr; 973 return llvm::isBytewiseValue(Init); 974 } 975 976 /// Decide whether we want to split a constant structure or array store into a 977 /// sequence of its fields' stores. This may cost us code size and compilation 978 /// speed, but plays better with store optimizations. 979 static bool shouldSplitConstantStore(CodeGenModule &CGM, 980 uint64_t GlobalByteSize) { 981 // Don't break things that occupy more than one cacheline. 982 uint64_t ByteSizeLimit = 64; 983 if (CGM.getCodeGenOpts().OptimizationLevel == 0) 984 return false; 985 if (GlobalByteSize <= ByteSizeLimit) 986 return true; 987 return false; 988 } 989 990 enum class IsPattern { No, Yes }; 991 992 /// Generate a constant filled with either a pattern or zeroes. 993 static llvm::Constant *patternOrZeroFor(CodeGenModule &CGM, IsPattern isPattern, 994 llvm::Type *Ty) { 995 if (isPattern == IsPattern::Yes) 996 return initializationPatternFor(CGM, Ty); 997 else 998 return llvm::Constant::getNullValue(Ty); 999 } 1000 1001 static llvm::Constant *constWithPadding(CodeGenModule &CGM, IsPattern isPattern, 1002 llvm::Constant *constant); 1003 1004 /// Helper function for constWithPadding() to deal with padding in structures. 1005 static llvm::Constant *constStructWithPadding(CodeGenModule &CGM, 1006 IsPattern isPattern, 1007 llvm::StructType *STy, 1008 llvm::Constant *constant) { 1009 const llvm::DataLayout &DL = CGM.getDataLayout(); 1010 const llvm::StructLayout *Layout = DL.getStructLayout(STy); 1011 llvm::Type *Int8Ty = llvm::IntegerType::getInt8Ty(CGM.getLLVMContext()); 1012 unsigned SizeSoFar = 0; 1013 SmallVector<llvm::Constant *, 8> Values; 1014 bool NestedIntact = true; 1015 for (unsigned i = 0, e = STy->getNumElements(); i != e; i++) { 1016 unsigned CurOff = Layout->getElementOffset(i); 1017 if (SizeSoFar < CurOff) { 1018 assert(!STy->isPacked()); 1019 auto *PadTy = llvm::ArrayType::get(Int8Ty, CurOff - SizeSoFar); 1020 Values.push_back(patternOrZeroFor(CGM, isPattern, PadTy)); 1021 } 1022 llvm::Constant *CurOp; 1023 if (constant->isZeroValue()) 1024 CurOp = llvm::Constant::getNullValue(STy->getElementType(i)); 1025 else 1026 CurOp = cast<llvm::Constant>(constant->getAggregateElement(i)); 1027 auto *NewOp = constWithPadding(CGM, isPattern, CurOp); 1028 if (CurOp != NewOp) 1029 NestedIntact = false; 1030 Values.push_back(NewOp); 1031 SizeSoFar = CurOff + DL.getTypeAllocSize(CurOp->getType()); 1032 } 1033 unsigned TotalSize = Layout->getSizeInBytes(); 1034 if (SizeSoFar < TotalSize) { 1035 auto *PadTy = llvm::ArrayType::get(Int8Ty, TotalSize - SizeSoFar); 1036 Values.push_back(patternOrZeroFor(CGM, isPattern, PadTy)); 1037 } 1038 if (NestedIntact && Values.size() == STy->getNumElements()) 1039 return constant; 1040 return llvm::ConstantStruct::getAnon(Values, STy->isPacked()); 1041 } 1042 1043 /// Replace all padding bytes in a given constant with either a pattern byte or 1044 /// 0x00. 1045 static llvm::Constant *constWithPadding(CodeGenModule &CGM, IsPattern isPattern, 1046 llvm::Constant *constant) { 1047 llvm::Type *OrigTy = constant->getType(); 1048 if (const auto STy = dyn_cast<llvm::StructType>(OrigTy)) 1049 return constStructWithPadding(CGM, isPattern, STy, constant); 1050 if (auto *STy = dyn_cast<llvm::SequentialType>(OrigTy)) { 1051 llvm::SmallVector<llvm::Constant *, 8> Values; 1052 unsigned Size = STy->getNumElements(); 1053 if (!Size) 1054 return constant; 1055 llvm::Type *ElemTy = STy->getElementType(); 1056 bool ZeroInitializer = constant->isZeroValue(); 1057 llvm::Constant *OpValue, *PaddedOp; 1058 if (ZeroInitializer) { 1059 OpValue = llvm::Constant::getNullValue(ElemTy); 1060 PaddedOp = constWithPadding(CGM, isPattern, OpValue); 1061 } 1062 for (unsigned Op = 0; Op != Size; ++Op) { 1063 if (!ZeroInitializer) { 1064 OpValue = constant->getAggregateElement(Op); 1065 PaddedOp = constWithPadding(CGM, isPattern, OpValue); 1066 } 1067 Values.push_back(PaddedOp); 1068 } 1069 auto *NewElemTy = Values[0]->getType(); 1070 if (NewElemTy == ElemTy) 1071 return constant; 1072 if (OrigTy->isArrayTy()) { 1073 auto *ArrayTy = llvm::ArrayType::get(NewElemTy, Size); 1074 return llvm::ConstantArray::get(ArrayTy, Values); 1075 } else { 1076 return llvm::ConstantVector::get(Values); 1077 } 1078 } 1079 return constant; 1080 } 1081 1082 Address CodeGenModule::createUnnamedGlobalFrom(const VarDecl &D, 1083 llvm::Constant *Constant, 1084 CharUnits Align) { 1085 auto FunctionName = [&](const DeclContext *DC) -> std::string { 1086 if (const auto *FD = dyn_cast<FunctionDecl>(DC)) { 1087 if (const auto *CC = dyn_cast<CXXConstructorDecl>(FD)) 1088 return CC->getNameAsString(); 1089 if (const auto *CD = dyn_cast<CXXDestructorDecl>(FD)) 1090 return CD->getNameAsString(); 1091 return getMangledName(FD); 1092 } else if (const auto *OM = dyn_cast<ObjCMethodDecl>(DC)) { 1093 return OM->getNameAsString(); 1094 } else if (isa<BlockDecl>(DC)) { 1095 return "<block>"; 1096 } else if (isa<CapturedDecl>(DC)) { 1097 return "<captured>"; 1098 } else { 1099 llvm_unreachable("expected a function or method"); 1100 } 1101 }; 1102 1103 // Form a simple per-variable cache of these values in case we find we 1104 // want to reuse them. 1105 llvm::GlobalVariable *&CacheEntry = InitializerConstants[&D]; 1106 if (!CacheEntry || CacheEntry->getInitializer() != Constant) { 1107 auto *Ty = Constant->getType(); 1108 bool isConstant = true; 1109 llvm::GlobalVariable *InsertBefore = nullptr; 1110 unsigned AS = 1111 getContext().getTargetAddressSpace(getStringLiteralAddressSpace()); 1112 std::string Name; 1113 if (D.hasGlobalStorage()) 1114 Name = getMangledName(&D).str() + ".const"; 1115 else if (const DeclContext *DC = D.getParentFunctionOrMethod()) 1116 Name = ("__const." + FunctionName(DC) + "." + D.getName()).str(); 1117 else 1118 llvm_unreachable("local variable has no parent function or method"); 1119 llvm::GlobalVariable *GV = new llvm::GlobalVariable( 1120 getModule(), Ty, isConstant, llvm::GlobalValue::PrivateLinkage, 1121 Constant, Name, InsertBefore, llvm::GlobalValue::NotThreadLocal, AS); 1122 GV->setAlignment(Align.getQuantity()); 1123 GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global); 1124 CacheEntry = GV; 1125 } else if (CacheEntry->getAlignment() < Align.getQuantity()) { 1126 CacheEntry->setAlignment(Align.getQuantity()); 1127 } 1128 1129 return Address(CacheEntry, Align); 1130 } 1131 1132 static Address createUnnamedGlobalForMemcpyFrom(CodeGenModule &CGM, 1133 const VarDecl &D, 1134 CGBuilderTy &Builder, 1135 llvm::Constant *Constant, 1136 CharUnits Align) { 1137 Address SrcPtr = CGM.createUnnamedGlobalFrom(D, Constant, Align); 1138 llvm::Type *BP = llvm::PointerType::getInt8PtrTy(CGM.getLLVMContext(), 1139 SrcPtr.getAddressSpace()); 1140 if (SrcPtr.getType() != BP) 1141 SrcPtr = Builder.CreateBitCast(SrcPtr, BP); 1142 return SrcPtr; 1143 } 1144 1145 static void emitStoresForConstant(CodeGenModule &CGM, const VarDecl &D, 1146 Address Loc, bool isVolatile, 1147 CGBuilderTy &Builder, 1148 llvm::Constant *constant) { 1149 auto *Ty = constant->getType(); 1150 uint64_t ConstantSize = CGM.getDataLayout().getTypeAllocSize(Ty); 1151 if (!ConstantSize) 1152 return; 1153 1154 bool canDoSingleStore = Ty->isIntOrIntVectorTy() || 1155 Ty->isPtrOrPtrVectorTy() || Ty->isFPOrFPVectorTy(); 1156 if (canDoSingleStore) { 1157 Builder.CreateStore(constant, Loc, isVolatile); 1158 return; 1159 } 1160 1161 auto *SizeVal = llvm::ConstantInt::get(CGM.IntPtrTy, ConstantSize); 1162 1163 // If the initializer is all or mostly the same, codegen with bzero / memset 1164 // then do a few stores afterward. 1165 if (shouldUseBZeroPlusStoresToInitialize(constant, ConstantSize)) { 1166 Builder.CreateMemSet(Loc, llvm::ConstantInt::get(CGM.Int8Ty, 0), SizeVal, 1167 isVolatile); 1168 1169 bool valueAlreadyCorrect = 1170 constant->isNullValue() || isa<llvm::UndefValue>(constant); 1171 if (!valueAlreadyCorrect) { 1172 Loc = Builder.CreateBitCast(Loc, Ty->getPointerTo(Loc.getAddressSpace())); 1173 emitStoresForInitAfterBZero(CGM, constant, Loc, isVolatile, Builder); 1174 } 1175 return; 1176 } 1177 1178 // If the initializer is a repeated byte pattern, use memset. 1179 llvm::Value *Pattern = shouldUseMemSetToInitialize(constant, ConstantSize); 1180 if (Pattern) { 1181 uint64_t Value = 0x00; 1182 if (!isa<llvm::UndefValue>(Pattern)) { 1183 const llvm::APInt &AP = cast<llvm::ConstantInt>(Pattern)->getValue(); 1184 assert(AP.getBitWidth() <= 8); 1185 Value = AP.getLimitedValue(); 1186 } 1187 Builder.CreateMemSet(Loc, llvm::ConstantInt::get(CGM.Int8Ty, Value), SizeVal, 1188 isVolatile); 1189 return; 1190 } 1191 1192 // If the initializer is small, use a handful of stores. 1193 if (shouldSplitConstantStore(CGM, ConstantSize)) { 1194 if (auto *STy = dyn_cast<llvm::StructType>(Ty)) { 1195 // FIXME: handle the case when STy != Loc.getElementType(). 1196 if (STy == Loc.getElementType()) { 1197 for (unsigned i = 0; i != constant->getNumOperands(); i++) { 1198 Address EltPtr = Builder.CreateStructGEP(Loc, i); 1199 emitStoresForConstant( 1200 CGM, D, EltPtr, isVolatile, Builder, 1201 cast<llvm::Constant>(Builder.CreateExtractValue(constant, i))); 1202 } 1203 return; 1204 } 1205 } else if (auto *ATy = dyn_cast<llvm::ArrayType>(Ty)) { 1206 // FIXME: handle the case when ATy != Loc.getElementType(). 1207 if (ATy == Loc.getElementType()) { 1208 for (unsigned i = 0; i != ATy->getNumElements(); i++) { 1209 Address EltPtr = Builder.CreateConstArrayGEP(Loc, i); 1210 emitStoresForConstant( 1211 CGM, D, EltPtr, isVolatile, Builder, 1212 cast<llvm::Constant>(Builder.CreateExtractValue(constant, i))); 1213 } 1214 return; 1215 } 1216 } 1217 } 1218 1219 // Copy from a global. 1220 Builder.CreateMemCpy(Loc, 1221 createUnnamedGlobalForMemcpyFrom( 1222 CGM, D, Builder, constant, Loc.getAlignment()), 1223 SizeVal, isVolatile); 1224 } 1225 1226 static void emitStoresForZeroInit(CodeGenModule &CGM, const VarDecl &D, 1227 Address Loc, bool isVolatile, 1228 CGBuilderTy &Builder) { 1229 llvm::Type *ElTy = Loc.getElementType(); 1230 llvm::Constant *constant = 1231 constWithPadding(CGM, IsPattern::No, llvm::Constant::getNullValue(ElTy)); 1232 emitStoresForConstant(CGM, D, Loc, isVolatile, Builder, constant); 1233 } 1234 1235 static void emitStoresForPatternInit(CodeGenModule &CGM, const VarDecl &D, 1236 Address Loc, bool isVolatile, 1237 CGBuilderTy &Builder) { 1238 llvm::Type *ElTy = Loc.getElementType(); 1239 llvm::Constant *constant = constWithPadding( 1240 CGM, IsPattern::Yes, initializationPatternFor(CGM, ElTy)); 1241 assert(!isa<llvm::UndefValue>(constant)); 1242 emitStoresForConstant(CGM, D, Loc, isVolatile, Builder, constant); 1243 } 1244 1245 static bool containsUndef(llvm::Constant *constant) { 1246 auto *Ty = constant->getType(); 1247 if (isa<llvm::UndefValue>(constant)) 1248 return true; 1249 if (Ty->isStructTy() || Ty->isArrayTy() || Ty->isVectorTy()) 1250 for (llvm::Use &Op : constant->operands()) 1251 if (containsUndef(cast<llvm::Constant>(Op))) 1252 return true; 1253 return false; 1254 } 1255 1256 static llvm::Constant *replaceUndef(CodeGenModule &CGM, IsPattern isPattern, 1257 llvm::Constant *constant) { 1258 auto *Ty = constant->getType(); 1259 if (isa<llvm::UndefValue>(constant)) 1260 return patternOrZeroFor(CGM, isPattern, Ty); 1261 if (!(Ty->isStructTy() || Ty->isArrayTy() || Ty->isVectorTy())) 1262 return constant; 1263 if (!containsUndef(constant)) 1264 return constant; 1265 llvm::SmallVector<llvm::Constant *, 8> Values(constant->getNumOperands()); 1266 for (unsigned Op = 0, NumOp = constant->getNumOperands(); Op != NumOp; ++Op) { 1267 auto *OpValue = cast<llvm::Constant>(constant->getOperand(Op)); 1268 Values[Op] = replaceUndef(CGM, isPattern, OpValue); 1269 } 1270 if (Ty->isStructTy()) 1271 return llvm::ConstantStruct::get(cast<llvm::StructType>(Ty), Values); 1272 if (Ty->isArrayTy()) 1273 return llvm::ConstantArray::get(cast<llvm::ArrayType>(Ty), Values); 1274 assert(Ty->isVectorTy()); 1275 return llvm::ConstantVector::get(Values); 1276 } 1277 1278 /// EmitAutoVarDecl - Emit code and set up an entry in LocalDeclMap for a 1279 /// variable declaration with auto, register, or no storage class specifier. 1280 /// These turn into simple stack objects, or GlobalValues depending on target. 1281 void CodeGenFunction::EmitAutoVarDecl(const VarDecl &D) { 1282 AutoVarEmission emission = EmitAutoVarAlloca(D); 1283 EmitAutoVarInit(emission); 1284 EmitAutoVarCleanups(emission); 1285 } 1286 1287 /// Emit a lifetime.begin marker if some criteria are satisfied. 1288 /// \return a pointer to the temporary size Value if a marker was emitted, null 1289 /// otherwise 1290 llvm::Value *CodeGenFunction::EmitLifetimeStart(uint64_t Size, 1291 llvm::Value *Addr) { 1292 if (!ShouldEmitLifetimeMarkers) 1293 return nullptr; 1294 1295 assert(Addr->getType()->getPointerAddressSpace() == 1296 CGM.getDataLayout().getAllocaAddrSpace() && 1297 "Pointer should be in alloca address space"); 1298 llvm::Value *SizeV = llvm::ConstantInt::get(Int64Ty, Size); 1299 Addr = Builder.CreateBitCast(Addr, AllocaInt8PtrTy); 1300 llvm::CallInst *C = 1301 Builder.CreateCall(CGM.getLLVMLifetimeStartFn(), {SizeV, Addr}); 1302 C->setDoesNotThrow(); 1303 return SizeV; 1304 } 1305 1306 void CodeGenFunction::EmitLifetimeEnd(llvm::Value *Size, llvm::Value *Addr) { 1307 assert(Addr->getType()->getPointerAddressSpace() == 1308 CGM.getDataLayout().getAllocaAddrSpace() && 1309 "Pointer should be in alloca address space"); 1310 Addr = Builder.CreateBitCast(Addr, AllocaInt8PtrTy); 1311 llvm::CallInst *C = 1312 Builder.CreateCall(CGM.getLLVMLifetimeEndFn(), {Size, Addr}); 1313 C->setDoesNotThrow(); 1314 } 1315 1316 void CodeGenFunction::EmitAndRegisterVariableArrayDimensions( 1317 CGDebugInfo *DI, const VarDecl &D, bool EmitDebugInfo) { 1318 // For each dimension stores its QualType and corresponding 1319 // size-expression Value. 1320 SmallVector<CodeGenFunction::VlaSizePair, 4> Dimensions; 1321 SmallVector<IdentifierInfo *, 4> VLAExprNames; 1322 1323 // Break down the array into individual dimensions. 1324 QualType Type1D = D.getType(); 1325 while (getContext().getAsVariableArrayType(Type1D)) { 1326 auto VlaSize = getVLAElements1D(Type1D); 1327 if (auto *C = dyn_cast<llvm::ConstantInt>(VlaSize.NumElts)) 1328 Dimensions.emplace_back(C, Type1D.getUnqualifiedType()); 1329 else { 1330 // Generate a locally unique name for the size expression. 1331 Twine Name = Twine("__vla_expr") + Twine(VLAExprCounter++); 1332 SmallString<12> Buffer; 1333 StringRef NameRef = Name.toStringRef(Buffer); 1334 auto &Ident = getContext().Idents.getOwn(NameRef); 1335 VLAExprNames.push_back(&Ident); 1336 auto SizeExprAddr = 1337 CreateDefaultAlignTempAlloca(VlaSize.NumElts->getType(), NameRef); 1338 Builder.CreateStore(VlaSize.NumElts, SizeExprAddr); 1339 Dimensions.emplace_back(SizeExprAddr.getPointer(), 1340 Type1D.getUnqualifiedType()); 1341 } 1342 Type1D = VlaSize.Type; 1343 } 1344 1345 if (!EmitDebugInfo) 1346 return; 1347 1348 // Register each dimension's size-expression with a DILocalVariable, 1349 // so that it can be used by CGDebugInfo when instantiating a DISubrange 1350 // to describe this array. 1351 unsigned NameIdx = 0; 1352 for (auto &VlaSize : Dimensions) { 1353 llvm::Metadata *MD; 1354 if (auto *C = dyn_cast<llvm::ConstantInt>(VlaSize.NumElts)) 1355 MD = llvm::ConstantAsMetadata::get(C); 1356 else { 1357 // Create an artificial VarDecl to generate debug info for. 1358 IdentifierInfo *NameIdent = VLAExprNames[NameIdx++]; 1359 auto VlaExprTy = VlaSize.NumElts->getType()->getPointerElementType(); 1360 auto QT = getContext().getIntTypeForBitwidth( 1361 VlaExprTy->getScalarSizeInBits(), false); 1362 auto *ArtificialDecl = VarDecl::Create( 1363 getContext(), const_cast<DeclContext *>(D.getDeclContext()), 1364 D.getLocation(), D.getLocation(), NameIdent, QT, 1365 getContext().CreateTypeSourceInfo(QT), SC_Auto); 1366 ArtificialDecl->setImplicit(); 1367 1368 MD = DI->EmitDeclareOfAutoVariable(ArtificialDecl, VlaSize.NumElts, 1369 Builder); 1370 } 1371 assert(MD && "No Size expression debug node created"); 1372 DI->registerVLASizeExpression(VlaSize.Type, MD); 1373 } 1374 } 1375 1376 /// EmitAutoVarAlloca - Emit the alloca and debug information for a 1377 /// local variable. Does not emit initialization or destruction. 1378 CodeGenFunction::AutoVarEmission 1379 CodeGenFunction::EmitAutoVarAlloca(const VarDecl &D) { 1380 QualType Ty = D.getType(); 1381 assert( 1382 Ty.getAddressSpace() == LangAS::Default || 1383 (Ty.getAddressSpace() == LangAS::opencl_private && getLangOpts().OpenCL)); 1384 1385 AutoVarEmission emission(D); 1386 1387 bool isEscapingByRef = D.isEscapingByref(); 1388 emission.IsEscapingByRef = isEscapingByRef; 1389 1390 CharUnits alignment = getContext().getDeclAlign(&D); 1391 1392 // If the type is variably-modified, emit all the VLA sizes for it. 1393 if (Ty->isVariablyModifiedType()) 1394 EmitVariablyModifiedType(Ty); 1395 1396 auto *DI = getDebugInfo(); 1397 bool EmitDebugInfo = DI && CGM.getCodeGenOpts().getDebugInfo() >= 1398 codegenoptions::LimitedDebugInfo; 1399 1400 Address address = Address::invalid(); 1401 Address AllocaAddr = Address::invalid(); 1402 Address OpenMPLocalAddr = 1403 getLangOpts().OpenMP 1404 ? CGM.getOpenMPRuntime().getAddressOfLocalVariable(*this, &D) 1405 : Address::invalid(); 1406 bool NRVO = getLangOpts().ElideConstructors && D.isNRVOVariable(); 1407 1408 if (getLangOpts().OpenMP && OpenMPLocalAddr.isValid()) { 1409 address = OpenMPLocalAddr; 1410 } else if (Ty->isConstantSizeType()) { 1411 // If this value is an array or struct with a statically determinable 1412 // constant initializer, there are optimizations we can do. 1413 // 1414 // TODO: We should constant-evaluate the initializer of any variable, 1415 // as long as it is initialized by a constant expression. Currently, 1416 // isConstantInitializer produces wrong answers for structs with 1417 // reference or bitfield members, and a few other cases, and checking 1418 // for POD-ness protects us from some of these. 1419 if (D.getInit() && (Ty->isArrayType() || Ty->isRecordType()) && 1420 (D.isConstexpr() || 1421 ((Ty.isPODType(getContext()) || 1422 getContext().getBaseElementType(Ty)->isObjCObjectPointerType()) && 1423 D.getInit()->isConstantInitializer(getContext(), false)))) { 1424 1425 // If the variable's a const type, and it's neither an NRVO 1426 // candidate nor a __block variable and has no mutable members, 1427 // emit it as a global instead. 1428 // Exception is if a variable is located in non-constant address space 1429 // in OpenCL. 1430 if ((!getLangOpts().OpenCL || 1431 Ty.getAddressSpace() == LangAS::opencl_constant) && 1432 (CGM.getCodeGenOpts().MergeAllConstants && !NRVO && 1433 !isEscapingByRef && CGM.isTypeConstant(Ty, true))) { 1434 EmitStaticVarDecl(D, llvm::GlobalValue::InternalLinkage); 1435 1436 // Signal this condition to later callbacks. 1437 emission.Addr = Address::invalid(); 1438 assert(emission.wasEmittedAsGlobal()); 1439 return emission; 1440 } 1441 1442 // Otherwise, tell the initialization code that we're in this case. 1443 emission.IsConstantAggregate = true; 1444 } 1445 1446 // A normal fixed sized variable becomes an alloca in the entry block, 1447 // unless: 1448 // - it's an NRVO variable. 1449 // - we are compiling OpenMP and it's an OpenMP local variable. 1450 if (NRVO) { 1451 // The named return value optimization: allocate this variable in the 1452 // return slot, so that we can elide the copy when returning this 1453 // variable (C++0x [class.copy]p34). 1454 address = ReturnValue; 1455 1456 if (const RecordType *RecordTy = Ty->getAs<RecordType>()) { 1457 const auto *RD = RecordTy->getDecl(); 1458 const auto *CXXRD = dyn_cast<CXXRecordDecl>(RD); 1459 if ((CXXRD && !CXXRD->hasTrivialDestructor()) || 1460 RD->isNonTrivialToPrimitiveDestroy()) { 1461 // Create a flag that is used to indicate when the NRVO was applied 1462 // to this variable. Set it to zero to indicate that NRVO was not 1463 // applied. 1464 llvm::Value *Zero = Builder.getFalse(); 1465 Address NRVOFlag = 1466 CreateTempAlloca(Zero->getType(), CharUnits::One(), "nrvo"); 1467 EnsureInsertPoint(); 1468 Builder.CreateStore(Zero, NRVOFlag); 1469 1470 // Record the NRVO flag for this variable. 1471 NRVOFlags[&D] = NRVOFlag.getPointer(); 1472 emission.NRVOFlag = NRVOFlag.getPointer(); 1473 } 1474 } 1475 } else { 1476 CharUnits allocaAlignment; 1477 llvm::Type *allocaTy; 1478 if (isEscapingByRef) { 1479 auto &byrefInfo = getBlockByrefInfo(&D); 1480 allocaTy = byrefInfo.Type; 1481 allocaAlignment = byrefInfo.ByrefAlignment; 1482 } else { 1483 allocaTy = ConvertTypeForMem(Ty); 1484 allocaAlignment = alignment; 1485 } 1486 1487 // Create the alloca. Note that we set the name separately from 1488 // building the instruction so that it's there even in no-asserts 1489 // builds. 1490 address = CreateTempAlloca(allocaTy, allocaAlignment, D.getName(), 1491 /*ArraySize=*/nullptr, &AllocaAddr); 1492 1493 // Don't emit lifetime markers for MSVC catch parameters. The lifetime of 1494 // the catch parameter starts in the catchpad instruction, and we can't 1495 // insert code in those basic blocks. 1496 bool IsMSCatchParam = 1497 D.isExceptionVariable() && getTarget().getCXXABI().isMicrosoft(); 1498 1499 // Emit a lifetime intrinsic if meaningful. There's no point in doing this 1500 // if we don't have a valid insertion point (?). 1501 if (HaveInsertPoint() && !IsMSCatchParam) { 1502 // If there's a jump into the lifetime of this variable, its lifetime 1503 // gets broken up into several regions in IR, which requires more work 1504 // to handle correctly. For now, just omit the intrinsics; this is a 1505 // rare case, and it's better to just be conservatively correct. 1506 // PR28267. 1507 // 1508 // We have to do this in all language modes if there's a jump past the 1509 // declaration. We also have to do it in C if there's a jump to an 1510 // earlier point in the current block because non-VLA lifetimes begin as 1511 // soon as the containing block is entered, not when its variables 1512 // actually come into scope; suppressing the lifetime annotations 1513 // completely in this case is unnecessarily pessimistic, but again, this 1514 // is rare. 1515 if (!Bypasses.IsBypassed(&D) && 1516 !(!getLangOpts().CPlusPlus && hasLabelBeenSeenInCurrentScope())) { 1517 uint64_t size = CGM.getDataLayout().getTypeAllocSize(allocaTy); 1518 emission.SizeForLifetimeMarkers = 1519 EmitLifetimeStart(size, AllocaAddr.getPointer()); 1520 } 1521 } else { 1522 assert(!emission.useLifetimeMarkers()); 1523 } 1524 } 1525 } else { 1526 EnsureInsertPoint(); 1527 1528 if (!DidCallStackSave) { 1529 // Save the stack. 1530 Address Stack = 1531 CreateTempAlloca(Int8PtrTy, getPointerAlign(), "saved_stack"); 1532 1533 llvm::Function *F = CGM.getIntrinsic(llvm::Intrinsic::stacksave); 1534 llvm::Value *V = Builder.CreateCall(F); 1535 Builder.CreateStore(V, Stack); 1536 1537 DidCallStackSave = true; 1538 1539 // Push a cleanup block and restore the stack there. 1540 // FIXME: in general circumstances, this should be an EH cleanup. 1541 pushStackRestore(NormalCleanup, Stack); 1542 } 1543 1544 auto VlaSize = getVLASize(Ty); 1545 llvm::Type *llvmTy = ConvertTypeForMem(VlaSize.Type); 1546 1547 // Allocate memory for the array. 1548 address = CreateTempAlloca(llvmTy, alignment, "vla", VlaSize.NumElts, 1549 &AllocaAddr); 1550 1551 // If we have debug info enabled, properly describe the VLA dimensions for 1552 // this type by registering the vla size expression for each of the 1553 // dimensions. 1554 EmitAndRegisterVariableArrayDimensions(DI, D, EmitDebugInfo); 1555 } 1556 1557 setAddrOfLocalVar(&D, address); 1558 emission.Addr = address; 1559 emission.AllocaAddr = AllocaAddr; 1560 1561 // Emit debug info for local var declaration. 1562 if (EmitDebugInfo && HaveInsertPoint()) { 1563 Address DebugAddr = address; 1564 bool UsePointerValue = NRVO && ReturnValuePointer.isValid(); 1565 DI->setLocation(D.getLocation()); 1566 1567 // If NRVO, use a pointer to the return address. 1568 if (UsePointerValue) 1569 DebugAddr = ReturnValuePointer; 1570 1571 (void)DI->EmitDeclareOfAutoVariable(&D, DebugAddr.getPointer(), Builder, 1572 UsePointerValue); 1573 } 1574 1575 if (D.hasAttr<AnnotateAttr>() && HaveInsertPoint()) 1576 EmitVarAnnotations(&D, address.getPointer()); 1577 1578 // Make sure we call @llvm.lifetime.end. 1579 if (emission.useLifetimeMarkers()) 1580 EHStack.pushCleanup<CallLifetimeEnd>(NormalEHLifetimeMarker, 1581 emission.getOriginalAllocatedAddress(), 1582 emission.getSizeForLifetimeMarkers()); 1583 1584 return emission; 1585 } 1586 1587 static bool isCapturedBy(const VarDecl &, const Expr *); 1588 1589 /// Determines whether the given __block variable is potentially 1590 /// captured by the given statement. 1591 static bool isCapturedBy(const VarDecl &Var, const Stmt *S) { 1592 if (const Expr *E = dyn_cast<Expr>(S)) 1593 return isCapturedBy(Var, E); 1594 for (const Stmt *SubStmt : S->children()) 1595 if (isCapturedBy(Var, SubStmt)) 1596 return true; 1597 return false; 1598 } 1599 1600 /// Determines whether the given __block variable is potentially 1601 /// captured by the given expression. 1602 static bool isCapturedBy(const VarDecl &Var, const Expr *E) { 1603 // Skip the most common kinds of expressions that make 1604 // hierarchy-walking expensive. 1605 E = E->IgnoreParenCasts(); 1606 1607 if (const BlockExpr *BE = dyn_cast<BlockExpr>(E)) { 1608 const BlockDecl *Block = BE->getBlockDecl(); 1609 for (const auto &I : Block->captures()) { 1610 if (I.getVariable() == &Var) 1611 return true; 1612 } 1613 1614 // No need to walk into the subexpressions. 1615 return false; 1616 } 1617 1618 if (const StmtExpr *SE = dyn_cast<StmtExpr>(E)) { 1619 const CompoundStmt *CS = SE->getSubStmt(); 1620 for (const auto *BI : CS->body()) 1621 if (const auto *BIE = dyn_cast<Expr>(BI)) { 1622 if (isCapturedBy(Var, BIE)) 1623 return true; 1624 } 1625 else if (const auto *DS = dyn_cast<DeclStmt>(BI)) { 1626 // special case declarations 1627 for (const auto *I : DS->decls()) { 1628 if (const auto *VD = dyn_cast<VarDecl>((I))) { 1629 const Expr *Init = VD->getInit(); 1630 if (Init && isCapturedBy(Var, Init)) 1631 return true; 1632 } 1633 } 1634 } 1635 else 1636 // FIXME. Make safe assumption assuming arbitrary statements cause capturing. 1637 // Later, provide code to poke into statements for capture analysis. 1638 return true; 1639 return false; 1640 } 1641 1642 for (const Stmt *SubStmt : E->children()) 1643 if (isCapturedBy(Var, SubStmt)) 1644 return true; 1645 1646 return false; 1647 } 1648 1649 /// Determine whether the given initializer is trivial in the sense 1650 /// that it requires no code to be generated. 1651 bool CodeGenFunction::isTrivialInitializer(const Expr *Init) { 1652 if (!Init) 1653 return true; 1654 1655 if (const CXXConstructExpr *Construct = dyn_cast<CXXConstructExpr>(Init)) 1656 if (CXXConstructorDecl *Constructor = Construct->getConstructor()) 1657 if (Constructor->isTrivial() && 1658 Constructor->isDefaultConstructor() && 1659 !Construct->requiresZeroInitialization()) 1660 return true; 1661 1662 return false; 1663 } 1664 1665 void CodeGenFunction::EmitAutoVarInit(const AutoVarEmission &emission) { 1666 assert(emission.Variable && "emission was not valid!"); 1667 1668 // If this was emitted as a global constant, we're done. 1669 if (emission.wasEmittedAsGlobal()) return; 1670 1671 const VarDecl &D = *emission.Variable; 1672 auto DL = ApplyDebugLocation::CreateDefaultArtificial(*this, D.getLocation()); 1673 QualType type = D.getType(); 1674 1675 // If this local has an initializer, emit it now. 1676 const Expr *Init = D.getInit(); 1677 1678 // If we are at an unreachable point, we don't need to emit the initializer 1679 // unless it contains a label. 1680 if (!HaveInsertPoint()) { 1681 if (!Init || !ContainsLabel(Init)) return; 1682 EnsureInsertPoint(); 1683 } 1684 1685 // Initialize the structure of a __block variable. 1686 if (emission.IsEscapingByRef) 1687 emitByrefStructureInit(emission); 1688 1689 // Initialize the variable here if it doesn't have a initializer and it is a 1690 // C struct that is non-trivial to initialize or an array containing such a 1691 // struct. 1692 if (!Init && 1693 type.isNonTrivialToPrimitiveDefaultInitialize() == 1694 QualType::PDIK_Struct) { 1695 LValue Dst = MakeAddrLValue(emission.getAllocatedAddress(), type); 1696 if (emission.IsEscapingByRef) 1697 drillIntoBlockVariable(*this, Dst, &D); 1698 defaultInitNonTrivialCStructVar(Dst); 1699 return; 1700 } 1701 1702 // Check whether this is a byref variable that's potentially 1703 // captured and moved by its own initializer. If so, we'll need to 1704 // emit the initializer first, then copy into the variable. 1705 bool capturedByInit = 1706 Init && emission.IsEscapingByRef && isCapturedBy(D, Init); 1707 1708 bool locIsByrefHeader = !capturedByInit; 1709 const Address Loc = 1710 locIsByrefHeader ? emission.getObjectAddress(*this) : emission.Addr; 1711 1712 // Note: constexpr already initializes everything correctly. 1713 LangOptions::TrivialAutoVarInitKind trivialAutoVarInit = 1714 (D.isConstexpr() 1715 ? LangOptions::TrivialAutoVarInitKind::Uninitialized 1716 : (D.getAttr<UninitializedAttr>() 1717 ? LangOptions::TrivialAutoVarInitKind::Uninitialized 1718 : getContext().getLangOpts().getTrivialAutoVarInit())); 1719 1720 auto initializeWhatIsTechnicallyUninitialized = [&](Address Loc) { 1721 if (trivialAutoVarInit == 1722 LangOptions::TrivialAutoVarInitKind::Uninitialized) 1723 return; 1724 1725 // Only initialize a __block's storage: we always initialize the header. 1726 if (emission.IsEscapingByRef && !locIsByrefHeader) 1727 Loc = emitBlockByrefAddress(Loc, &D, /*follow=*/false); 1728 1729 bool isVolatile = type.isVolatileQualified(); 1730 CharUnits Size = getContext().getTypeSizeInChars(type); 1731 if (!Size.isZero()) { 1732 switch (trivialAutoVarInit) { 1733 case LangOptions::TrivialAutoVarInitKind::Uninitialized: 1734 llvm_unreachable("Uninitialized handled above"); 1735 case LangOptions::TrivialAutoVarInitKind::Zero: 1736 emitStoresForZeroInit(CGM, D, Loc, isVolatile, Builder); 1737 break; 1738 case LangOptions::TrivialAutoVarInitKind::Pattern: 1739 emitStoresForPatternInit(CGM, D, Loc, isVolatile, Builder); 1740 break; 1741 } 1742 return; 1743 } 1744 1745 // VLAs look zero-sized to getTypeInfo. We can't emit constant stores to 1746 // them, so emit a memcpy with the VLA size to initialize each element. 1747 // Technically zero-sized or negative-sized VLAs are undefined, and UBSan 1748 // will catch that code, but there exists code which generates zero-sized 1749 // VLAs. Be nice and initialize whatever they requested. 1750 const auto *VlaType = getContext().getAsVariableArrayType(type); 1751 if (!VlaType) 1752 return; 1753 auto VlaSize = getVLASize(VlaType); 1754 auto SizeVal = VlaSize.NumElts; 1755 CharUnits EltSize = getContext().getTypeSizeInChars(VlaSize.Type); 1756 switch (trivialAutoVarInit) { 1757 case LangOptions::TrivialAutoVarInitKind::Uninitialized: 1758 llvm_unreachable("Uninitialized handled above"); 1759 1760 case LangOptions::TrivialAutoVarInitKind::Zero: 1761 if (!EltSize.isOne()) 1762 SizeVal = Builder.CreateNUWMul(SizeVal, CGM.getSize(EltSize)); 1763 Builder.CreateMemSet(Loc, llvm::ConstantInt::get(Int8Ty, 0), SizeVal, 1764 isVolatile); 1765 break; 1766 1767 case LangOptions::TrivialAutoVarInitKind::Pattern: { 1768 llvm::Type *ElTy = Loc.getElementType(); 1769 llvm::Constant *Constant = constWithPadding( 1770 CGM, IsPattern::Yes, initializationPatternFor(CGM, ElTy)); 1771 CharUnits ConstantAlign = getContext().getTypeAlignInChars(VlaSize.Type); 1772 llvm::BasicBlock *SetupBB = createBasicBlock("vla-setup.loop"); 1773 llvm::BasicBlock *LoopBB = createBasicBlock("vla-init.loop"); 1774 llvm::BasicBlock *ContBB = createBasicBlock("vla-init.cont"); 1775 llvm::Value *IsZeroSizedVLA = Builder.CreateICmpEQ( 1776 SizeVal, llvm::ConstantInt::get(SizeVal->getType(), 0), 1777 "vla.iszerosized"); 1778 Builder.CreateCondBr(IsZeroSizedVLA, ContBB, SetupBB); 1779 EmitBlock(SetupBB); 1780 if (!EltSize.isOne()) 1781 SizeVal = Builder.CreateNUWMul(SizeVal, CGM.getSize(EltSize)); 1782 llvm::Value *BaseSizeInChars = 1783 llvm::ConstantInt::get(IntPtrTy, EltSize.getQuantity()); 1784 Address Begin = Builder.CreateElementBitCast(Loc, Int8Ty, "vla.begin"); 1785 llvm::Value *End = 1786 Builder.CreateInBoundsGEP(Begin.getPointer(), SizeVal, "vla.end"); 1787 llvm::BasicBlock *OriginBB = Builder.GetInsertBlock(); 1788 EmitBlock(LoopBB); 1789 llvm::PHINode *Cur = Builder.CreatePHI(Begin.getType(), 2, "vla.cur"); 1790 Cur->addIncoming(Begin.getPointer(), OriginBB); 1791 CharUnits CurAlign = Loc.getAlignment().alignmentOfArrayElement(EltSize); 1792 Builder.CreateMemCpy(Address(Cur, CurAlign), 1793 createUnnamedGlobalForMemcpyFrom( 1794 CGM, D, Builder, Constant, ConstantAlign), 1795 BaseSizeInChars, isVolatile); 1796 llvm::Value *Next = 1797 Builder.CreateInBoundsGEP(Int8Ty, Cur, BaseSizeInChars, "vla.next"); 1798 llvm::Value *Done = Builder.CreateICmpEQ(Next, End, "vla-init.isdone"); 1799 Builder.CreateCondBr(Done, ContBB, LoopBB); 1800 Cur->addIncoming(Next, LoopBB); 1801 EmitBlock(ContBB); 1802 } break; 1803 } 1804 }; 1805 1806 if (isTrivialInitializer(Init)) { 1807 initializeWhatIsTechnicallyUninitialized(Loc); 1808 return; 1809 } 1810 1811 llvm::Constant *constant = nullptr; 1812 if (emission.IsConstantAggregate || 1813 D.mightBeUsableInConstantExpressions(getContext())) { 1814 assert(!capturedByInit && "constant init contains a capturing block?"); 1815 constant = ConstantEmitter(*this).tryEmitAbstractForInitializer(D); 1816 if (constant && !constant->isZeroValue() && 1817 (trivialAutoVarInit != 1818 LangOptions::TrivialAutoVarInitKind::Uninitialized)) { 1819 IsPattern isPattern = 1820 (trivialAutoVarInit == LangOptions::TrivialAutoVarInitKind::Pattern) 1821 ? IsPattern::Yes 1822 : IsPattern::No; 1823 // C guarantees that brace-init with fewer initializers than members in 1824 // the aggregate will initialize the rest of the aggregate as-if it were 1825 // static initialization. In turn static initialization guarantees that 1826 // padding is initialized to zero bits. We could instead pattern-init if D 1827 // has any ImplicitValueInitExpr, but that seems to be unintuitive 1828 // behavior. 1829 constant = constWithPadding(CGM, IsPattern::No, 1830 replaceUndef(CGM, isPattern, constant)); 1831 } 1832 } 1833 1834 if (!constant) { 1835 initializeWhatIsTechnicallyUninitialized(Loc); 1836 LValue lv = MakeAddrLValue(Loc, type); 1837 lv.setNonGC(true); 1838 return EmitExprAsInit(Init, &D, lv, capturedByInit); 1839 } 1840 1841 if (!emission.IsConstantAggregate) { 1842 // For simple scalar/complex initialization, store the value directly. 1843 LValue lv = MakeAddrLValue(Loc, type); 1844 lv.setNonGC(true); 1845 return EmitStoreThroughLValue(RValue::get(constant), lv, true); 1846 } 1847 1848 llvm::Type *BP = CGM.Int8Ty->getPointerTo(Loc.getAddressSpace()); 1849 emitStoresForConstant( 1850 CGM, D, (Loc.getType() == BP) ? Loc : Builder.CreateBitCast(Loc, BP), 1851 type.isVolatileQualified(), Builder, constant); 1852 } 1853 1854 /// Emit an expression as an initializer for an object (variable, field, etc.) 1855 /// at the given location. The expression is not necessarily the normal 1856 /// initializer for the object, and the address is not necessarily 1857 /// its normal location. 1858 /// 1859 /// \param init the initializing expression 1860 /// \param D the object to act as if we're initializing 1861 /// \param loc the address to initialize; its type is a pointer 1862 /// to the LLVM mapping of the object's type 1863 /// \param alignment the alignment of the address 1864 /// \param capturedByInit true if \p D is a __block variable 1865 /// whose address is potentially changed by the initializer 1866 void CodeGenFunction::EmitExprAsInit(const Expr *init, const ValueDecl *D, 1867 LValue lvalue, bool capturedByInit) { 1868 QualType type = D->getType(); 1869 1870 if (type->isReferenceType()) { 1871 RValue rvalue = EmitReferenceBindingToExpr(init); 1872 if (capturedByInit) 1873 drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D)); 1874 EmitStoreThroughLValue(rvalue, lvalue, true); 1875 return; 1876 } 1877 switch (getEvaluationKind(type)) { 1878 case TEK_Scalar: 1879 EmitScalarInit(init, D, lvalue, capturedByInit); 1880 return; 1881 case TEK_Complex: { 1882 ComplexPairTy complex = EmitComplexExpr(init); 1883 if (capturedByInit) 1884 drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D)); 1885 EmitStoreOfComplex(complex, lvalue, /*init*/ true); 1886 return; 1887 } 1888 case TEK_Aggregate: 1889 if (type->isAtomicType()) { 1890 EmitAtomicInit(const_cast<Expr*>(init), lvalue); 1891 } else { 1892 AggValueSlot::Overlap_t Overlap = AggValueSlot::MayOverlap; 1893 if (isa<VarDecl>(D)) 1894 Overlap = AggValueSlot::DoesNotOverlap; 1895 else if (auto *FD = dyn_cast<FieldDecl>(D)) 1896 Overlap = getOverlapForFieldInit(FD); 1897 // TODO: how can we delay here if D is captured by its initializer? 1898 EmitAggExpr(init, AggValueSlot::forLValue(lvalue, 1899 AggValueSlot::IsDestructed, 1900 AggValueSlot::DoesNotNeedGCBarriers, 1901 AggValueSlot::IsNotAliased, 1902 Overlap)); 1903 } 1904 return; 1905 } 1906 llvm_unreachable("bad evaluation kind"); 1907 } 1908 1909 /// Enter a destroy cleanup for the given local variable. 1910 void CodeGenFunction::emitAutoVarTypeCleanup( 1911 const CodeGenFunction::AutoVarEmission &emission, 1912 QualType::DestructionKind dtorKind) { 1913 assert(dtorKind != QualType::DK_none); 1914 1915 // Note that for __block variables, we want to destroy the 1916 // original stack object, not the possibly forwarded object. 1917 Address addr = emission.getObjectAddress(*this); 1918 1919 const VarDecl *var = emission.Variable; 1920 QualType type = var->getType(); 1921 1922 CleanupKind cleanupKind = NormalAndEHCleanup; 1923 CodeGenFunction::Destroyer *destroyer = nullptr; 1924 1925 switch (dtorKind) { 1926 case QualType::DK_none: 1927 llvm_unreachable("no cleanup for trivially-destructible variable"); 1928 1929 case QualType::DK_cxx_destructor: 1930 // If there's an NRVO flag on the emission, we need a different 1931 // cleanup. 1932 if (emission.NRVOFlag) { 1933 assert(!type->isArrayType()); 1934 CXXDestructorDecl *dtor = type->getAsCXXRecordDecl()->getDestructor(); 1935 EHStack.pushCleanup<DestroyNRVOVariableCXX>(cleanupKind, addr, dtor, 1936 emission.NRVOFlag); 1937 return; 1938 } 1939 break; 1940 1941 case QualType::DK_objc_strong_lifetime: 1942 // Suppress cleanups for pseudo-strong variables. 1943 if (var->isARCPseudoStrong()) return; 1944 1945 // Otherwise, consider whether to use an EH cleanup or not. 1946 cleanupKind = getARCCleanupKind(); 1947 1948 // Use the imprecise destroyer by default. 1949 if (!var->hasAttr<ObjCPreciseLifetimeAttr>()) 1950 destroyer = CodeGenFunction::destroyARCStrongImprecise; 1951 break; 1952 1953 case QualType::DK_objc_weak_lifetime: 1954 break; 1955 1956 case QualType::DK_nontrivial_c_struct: 1957 destroyer = CodeGenFunction::destroyNonTrivialCStruct; 1958 if (emission.NRVOFlag) { 1959 assert(!type->isArrayType()); 1960 EHStack.pushCleanup<DestroyNRVOVariableC>(cleanupKind, addr, 1961 emission.NRVOFlag, type); 1962 return; 1963 } 1964 break; 1965 } 1966 1967 // If we haven't chosen a more specific destroyer, use the default. 1968 if (!destroyer) destroyer = getDestroyer(dtorKind); 1969 1970 // Use an EH cleanup in array destructors iff the destructor itself 1971 // is being pushed as an EH cleanup. 1972 bool useEHCleanup = (cleanupKind & EHCleanup); 1973 EHStack.pushCleanup<DestroyObject>(cleanupKind, addr, type, destroyer, 1974 useEHCleanup); 1975 } 1976 1977 void CodeGenFunction::EmitAutoVarCleanups(const AutoVarEmission &emission) { 1978 assert(emission.Variable && "emission was not valid!"); 1979 1980 // If this was emitted as a global constant, we're done. 1981 if (emission.wasEmittedAsGlobal()) return; 1982 1983 // If we don't have an insertion point, we're done. Sema prevents 1984 // us from jumping into any of these scopes anyway. 1985 if (!HaveInsertPoint()) return; 1986 1987 const VarDecl &D = *emission.Variable; 1988 1989 // Check the type for a cleanup. 1990 if (QualType::DestructionKind dtorKind = D.getType().isDestructedType()) 1991 emitAutoVarTypeCleanup(emission, dtorKind); 1992 1993 // In GC mode, honor objc_precise_lifetime. 1994 if (getLangOpts().getGC() != LangOptions::NonGC && 1995 D.hasAttr<ObjCPreciseLifetimeAttr>()) { 1996 EHStack.pushCleanup<ExtendGCLifetime>(NormalCleanup, &D); 1997 } 1998 1999 // Handle the cleanup attribute. 2000 if (const CleanupAttr *CA = D.getAttr<CleanupAttr>()) { 2001 const FunctionDecl *FD = CA->getFunctionDecl(); 2002 2003 llvm::Constant *F = CGM.GetAddrOfFunction(FD); 2004 assert(F && "Could not find function!"); 2005 2006 const CGFunctionInfo &Info = CGM.getTypes().arrangeFunctionDeclaration(FD); 2007 EHStack.pushCleanup<CallCleanupFunction>(NormalAndEHCleanup, F, &Info, &D); 2008 } 2009 2010 // If this is a block variable, call _Block_object_destroy 2011 // (on the unforwarded address). Don't enter this cleanup if we're in pure-GC 2012 // mode. 2013 if (emission.IsEscapingByRef && 2014 CGM.getLangOpts().getGC() != LangOptions::GCOnly) { 2015 BlockFieldFlags Flags = BLOCK_FIELD_IS_BYREF; 2016 if (emission.Variable->getType().isObjCGCWeak()) 2017 Flags |= BLOCK_FIELD_IS_WEAK; 2018 enterByrefCleanup(NormalAndEHCleanup, emission.Addr, Flags, 2019 /*LoadBlockVarAddr*/ false, 2020 cxxDestructorCanThrow(emission.Variable->getType())); 2021 } 2022 } 2023 2024 CodeGenFunction::Destroyer * 2025 CodeGenFunction::getDestroyer(QualType::DestructionKind kind) { 2026 switch (kind) { 2027 case QualType::DK_none: llvm_unreachable("no destroyer for trivial dtor"); 2028 case QualType::DK_cxx_destructor: 2029 return destroyCXXObject; 2030 case QualType::DK_objc_strong_lifetime: 2031 return destroyARCStrongPrecise; 2032 case QualType::DK_objc_weak_lifetime: 2033 return destroyARCWeak; 2034 case QualType::DK_nontrivial_c_struct: 2035 return destroyNonTrivialCStruct; 2036 } 2037 llvm_unreachable("Unknown DestructionKind"); 2038 } 2039 2040 /// pushEHDestroy - Push the standard destructor for the given type as 2041 /// an EH-only cleanup. 2042 void CodeGenFunction::pushEHDestroy(QualType::DestructionKind dtorKind, 2043 Address addr, QualType type) { 2044 assert(dtorKind && "cannot push destructor for trivial type"); 2045 assert(needsEHCleanup(dtorKind)); 2046 2047 pushDestroy(EHCleanup, addr, type, getDestroyer(dtorKind), true); 2048 } 2049 2050 /// pushDestroy - Push the standard destructor for the given type as 2051 /// at least a normal cleanup. 2052 void CodeGenFunction::pushDestroy(QualType::DestructionKind dtorKind, 2053 Address addr, QualType type) { 2054 assert(dtorKind && "cannot push destructor for trivial type"); 2055 2056 CleanupKind cleanupKind = getCleanupKind(dtorKind); 2057 pushDestroy(cleanupKind, addr, type, getDestroyer(dtorKind), 2058 cleanupKind & EHCleanup); 2059 } 2060 2061 void CodeGenFunction::pushDestroy(CleanupKind cleanupKind, Address addr, 2062 QualType type, Destroyer *destroyer, 2063 bool useEHCleanupForArray) { 2064 pushFullExprCleanup<DestroyObject>(cleanupKind, addr, type, 2065 destroyer, useEHCleanupForArray); 2066 } 2067 2068 void CodeGenFunction::pushStackRestore(CleanupKind Kind, Address SPMem) { 2069 EHStack.pushCleanup<CallStackRestore>(Kind, SPMem); 2070 } 2071 2072 void CodeGenFunction::pushLifetimeExtendedDestroy( 2073 CleanupKind cleanupKind, Address addr, QualType type, 2074 Destroyer *destroyer, bool useEHCleanupForArray) { 2075 // Push an EH-only cleanup for the object now. 2076 // FIXME: When popping normal cleanups, we need to keep this EH cleanup 2077 // around in case a temporary's destructor throws an exception. 2078 if (cleanupKind & EHCleanup) 2079 EHStack.pushCleanup<DestroyObject>( 2080 static_cast<CleanupKind>(cleanupKind & ~NormalCleanup), addr, type, 2081 destroyer, useEHCleanupForArray); 2082 2083 // Remember that we need to push a full cleanup for the object at the 2084 // end of the full-expression. 2085 pushCleanupAfterFullExpr<DestroyObject>( 2086 cleanupKind, addr, type, destroyer, useEHCleanupForArray); 2087 } 2088 2089 /// emitDestroy - Immediately perform the destruction of the given 2090 /// object. 2091 /// 2092 /// \param addr - the address of the object; a type* 2093 /// \param type - the type of the object; if an array type, all 2094 /// objects are destroyed in reverse order 2095 /// \param destroyer - the function to call to destroy individual 2096 /// elements 2097 /// \param useEHCleanupForArray - whether an EH cleanup should be 2098 /// used when destroying array elements, in case one of the 2099 /// destructions throws an exception 2100 void CodeGenFunction::emitDestroy(Address addr, QualType type, 2101 Destroyer *destroyer, 2102 bool useEHCleanupForArray) { 2103 const ArrayType *arrayType = getContext().getAsArrayType(type); 2104 if (!arrayType) 2105 return destroyer(*this, addr, type); 2106 2107 llvm::Value *length = emitArrayLength(arrayType, type, addr); 2108 2109 CharUnits elementAlign = 2110 addr.getAlignment() 2111 .alignmentOfArrayElement(getContext().getTypeSizeInChars(type)); 2112 2113 // Normally we have to check whether the array is zero-length. 2114 bool checkZeroLength = true; 2115 2116 // But if the array length is constant, we can suppress that. 2117 if (llvm::ConstantInt *constLength = dyn_cast<llvm::ConstantInt>(length)) { 2118 // ...and if it's constant zero, we can just skip the entire thing. 2119 if (constLength->isZero()) return; 2120 checkZeroLength = false; 2121 } 2122 2123 llvm::Value *begin = addr.getPointer(); 2124 llvm::Value *end = Builder.CreateInBoundsGEP(begin, length); 2125 emitArrayDestroy(begin, end, type, elementAlign, destroyer, 2126 checkZeroLength, useEHCleanupForArray); 2127 } 2128 2129 /// emitArrayDestroy - Destroys all the elements of the given array, 2130 /// beginning from last to first. The array cannot be zero-length. 2131 /// 2132 /// \param begin - a type* denoting the first element of the array 2133 /// \param end - a type* denoting one past the end of the array 2134 /// \param elementType - the element type of the array 2135 /// \param destroyer - the function to call to destroy elements 2136 /// \param useEHCleanup - whether to push an EH cleanup to destroy 2137 /// the remaining elements in case the destruction of a single 2138 /// element throws 2139 void CodeGenFunction::emitArrayDestroy(llvm::Value *begin, 2140 llvm::Value *end, 2141 QualType elementType, 2142 CharUnits elementAlign, 2143 Destroyer *destroyer, 2144 bool checkZeroLength, 2145 bool useEHCleanup) { 2146 assert(!elementType->isArrayType()); 2147 2148 // The basic structure here is a do-while loop, because we don't 2149 // need to check for the zero-element case. 2150 llvm::BasicBlock *bodyBB = createBasicBlock("arraydestroy.body"); 2151 llvm::BasicBlock *doneBB = createBasicBlock("arraydestroy.done"); 2152 2153 if (checkZeroLength) { 2154 llvm::Value *isEmpty = Builder.CreateICmpEQ(begin, end, 2155 "arraydestroy.isempty"); 2156 Builder.CreateCondBr(isEmpty, doneBB, bodyBB); 2157 } 2158 2159 // Enter the loop body, making that address the current address. 2160 llvm::BasicBlock *entryBB = Builder.GetInsertBlock(); 2161 EmitBlock(bodyBB); 2162 llvm::PHINode *elementPast = 2163 Builder.CreatePHI(begin->getType(), 2, "arraydestroy.elementPast"); 2164 elementPast->addIncoming(end, entryBB); 2165 2166 // Shift the address back by one element. 2167 llvm::Value *negativeOne = llvm::ConstantInt::get(SizeTy, -1, true); 2168 llvm::Value *element = Builder.CreateInBoundsGEP(elementPast, negativeOne, 2169 "arraydestroy.element"); 2170 2171 if (useEHCleanup) 2172 pushRegularPartialArrayCleanup(begin, element, elementType, elementAlign, 2173 destroyer); 2174 2175 // Perform the actual destruction there. 2176 destroyer(*this, Address(element, elementAlign), elementType); 2177 2178 if (useEHCleanup) 2179 PopCleanupBlock(); 2180 2181 // Check whether we've reached the end. 2182 llvm::Value *done = Builder.CreateICmpEQ(element, begin, "arraydestroy.done"); 2183 Builder.CreateCondBr(done, doneBB, bodyBB); 2184 elementPast->addIncoming(element, Builder.GetInsertBlock()); 2185 2186 // Done. 2187 EmitBlock(doneBB); 2188 } 2189 2190 /// Perform partial array destruction as if in an EH cleanup. Unlike 2191 /// emitArrayDestroy, the element type here may still be an array type. 2192 static void emitPartialArrayDestroy(CodeGenFunction &CGF, 2193 llvm::Value *begin, llvm::Value *end, 2194 QualType type, CharUnits elementAlign, 2195 CodeGenFunction::Destroyer *destroyer) { 2196 // If the element type is itself an array, drill down. 2197 unsigned arrayDepth = 0; 2198 while (const ArrayType *arrayType = CGF.getContext().getAsArrayType(type)) { 2199 // VLAs don't require a GEP index to walk into. 2200 if (!isa<VariableArrayType>(arrayType)) 2201 arrayDepth++; 2202 type = arrayType->getElementType(); 2203 } 2204 2205 if (arrayDepth) { 2206 llvm::Value *zero = llvm::ConstantInt::get(CGF.SizeTy, 0); 2207 2208 SmallVector<llvm::Value*,4> gepIndices(arrayDepth+1, zero); 2209 begin = CGF.Builder.CreateInBoundsGEP(begin, gepIndices, "pad.arraybegin"); 2210 end = CGF.Builder.CreateInBoundsGEP(end, gepIndices, "pad.arrayend"); 2211 } 2212 2213 // Destroy the array. We don't ever need an EH cleanup because we 2214 // assume that we're in an EH cleanup ourselves, so a throwing 2215 // destructor causes an immediate terminate. 2216 CGF.emitArrayDestroy(begin, end, type, elementAlign, destroyer, 2217 /*checkZeroLength*/ true, /*useEHCleanup*/ false); 2218 } 2219 2220 namespace { 2221 /// RegularPartialArrayDestroy - a cleanup which performs a partial 2222 /// array destroy where the end pointer is regularly determined and 2223 /// does not need to be loaded from a local. 2224 class RegularPartialArrayDestroy final : public EHScopeStack::Cleanup { 2225 llvm::Value *ArrayBegin; 2226 llvm::Value *ArrayEnd; 2227 QualType ElementType; 2228 CodeGenFunction::Destroyer *Destroyer; 2229 CharUnits ElementAlign; 2230 public: 2231 RegularPartialArrayDestroy(llvm::Value *arrayBegin, llvm::Value *arrayEnd, 2232 QualType elementType, CharUnits elementAlign, 2233 CodeGenFunction::Destroyer *destroyer) 2234 : ArrayBegin(arrayBegin), ArrayEnd(arrayEnd), 2235 ElementType(elementType), Destroyer(destroyer), 2236 ElementAlign(elementAlign) {} 2237 2238 void Emit(CodeGenFunction &CGF, Flags flags) override { 2239 emitPartialArrayDestroy(CGF, ArrayBegin, ArrayEnd, 2240 ElementType, ElementAlign, Destroyer); 2241 } 2242 }; 2243 2244 /// IrregularPartialArrayDestroy - a cleanup which performs a 2245 /// partial array destroy where the end pointer is irregularly 2246 /// determined and must be loaded from a local. 2247 class IrregularPartialArrayDestroy final : public EHScopeStack::Cleanup { 2248 llvm::Value *ArrayBegin; 2249 Address ArrayEndPointer; 2250 QualType ElementType; 2251 CodeGenFunction::Destroyer *Destroyer; 2252 CharUnits ElementAlign; 2253 public: 2254 IrregularPartialArrayDestroy(llvm::Value *arrayBegin, 2255 Address arrayEndPointer, 2256 QualType elementType, 2257 CharUnits elementAlign, 2258 CodeGenFunction::Destroyer *destroyer) 2259 : ArrayBegin(arrayBegin), ArrayEndPointer(arrayEndPointer), 2260 ElementType(elementType), Destroyer(destroyer), 2261 ElementAlign(elementAlign) {} 2262 2263 void Emit(CodeGenFunction &CGF, Flags flags) override { 2264 llvm::Value *arrayEnd = CGF.Builder.CreateLoad(ArrayEndPointer); 2265 emitPartialArrayDestroy(CGF, ArrayBegin, arrayEnd, 2266 ElementType, ElementAlign, Destroyer); 2267 } 2268 }; 2269 } // end anonymous namespace 2270 2271 /// pushIrregularPartialArrayCleanup - Push an EH cleanup to destroy 2272 /// already-constructed elements of the given array. The cleanup 2273 /// may be popped with DeactivateCleanupBlock or PopCleanupBlock. 2274 /// 2275 /// \param elementType - the immediate element type of the array; 2276 /// possibly still an array type 2277 void CodeGenFunction::pushIrregularPartialArrayCleanup(llvm::Value *arrayBegin, 2278 Address arrayEndPointer, 2279 QualType elementType, 2280 CharUnits elementAlign, 2281 Destroyer *destroyer) { 2282 pushFullExprCleanup<IrregularPartialArrayDestroy>(EHCleanup, 2283 arrayBegin, arrayEndPointer, 2284 elementType, elementAlign, 2285 destroyer); 2286 } 2287 2288 /// pushRegularPartialArrayCleanup - Push an EH cleanup to destroy 2289 /// already-constructed elements of the given array. The cleanup 2290 /// may be popped with DeactivateCleanupBlock or PopCleanupBlock. 2291 /// 2292 /// \param elementType - the immediate element type of the array; 2293 /// possibly still an array type 2294 void CodeGenFunction::pushRegularPartialArrayCleanup(llvm::Value *arrayBegin, 2295 llvm::Value *arrayEnd, 2296 QualType elementType, 2297 CharUnits elementAlign, 2298 Destroyer *destroyer) { 2299 pushFullExprCleanup<RegularPartialArrayDestroy>(EHCleanup, 2300 arrayBegin, arrayEnd, 2301 elementType, elementAlign, 2302 destroyer); 2303 } 2304 2305 /// Lazily declare the @llvm.lifetime.start intrinsic. 2306 llvm::Function *CodeGenModule::getLLVMLifetimeStartFn() { 2307 if (LifetimeStartFn) 2308 return LifetimeStartFn; 2309 LifetimeStartFn = llvm::Intrinsic::getDeclaration(&getModule(), 2310 llvm::Intrinsic::lifetime_start, AllocaInt8PtrTy); 2311 return LifetimeStartFn; 2312 } 2313 2314 /// Lazily declare the @llvm.lifetime.end intrinsic. 2315 llvm::Function *CodeGenModule::getLLVMLifetimeEndFn() { 2316 if (LifetimeEndFn) 2317 return LifetimeEndFn; 2318 LifetimeEndFn = llvm::Intrinsic::getDeclaration(&getModule(), 2319 llvm::Intrinsic::lifetime_end, AllocaInt8PtrTy); 2320 return LifetimeEndFn; 2321 } 2322 2323 namespace { 2324 /// A cleanup to perform a release of an object at the end of a 2325 /// function. This is used to balance out the incoming +1 of a 2326 /// ns_consumed argument when we can't reasonably do that just by 2327 /// not doing the initial retain for a __block argument. 2328 struct ConsumeARCParameter final : EHScopeStack::Cleanup { 2329 ConsumeARCParameter(llvm::Value *param, 2330 ARCPreciseLifetime_t precise) 2331 : Param(param), Precise(precise) {} 2332 2333 llvm::Value *Param; 2334 ARCPreciseLifetime_t Precise; 2335 2336 void Emit(CodeGenFunction &CGF, Flags flags) override { 2337 CGF.EmitARCRelease(Param, Precise); 2338 } 2339 }; 2340 } // end anonymous namespace 2341 2342 /// Emit an alloca (or GlobalValue depending on target) 2343 /// for the specified parameter and set up LocalDeclMap. 2344 void CodeGenFunction::EmitParmDecl(const VarDecl &D, ParamValue Arg, 2345 unsigned ArgNo) { 2346 // FIXME: Why isn't ImplicitParamDecl a ParmVarDecl? 2347 assert((isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D)) && 2348 "Invalid argument to EmitParmDecl"); 2349 2350 Arg.getAnyValue()->setName(D.getName()); 2351 2352 QualType Ty = D.getType(); 2353 2354 // Use better IR generation for certain implicit parameters. 2355 if (auto IPD = dyn_cast<ImplicitParamDecl>(&D)) { 2356 // The only implicit argument a block has is its literal. 2357 // This may be passed as an inalloca'ed value on Windows x86. 2358 if (BlockInfo) { 2359 llvm::Value *V = Arg.isIndirect() 2360 ? Builder.CreateLoad(Arg.getIndirectAddress()) 2361 : Arg.getDirectValue(); 2362 setBlockContextParameter(IPD, ArgNo, V); 2363 return; 2364 } 2365 } 2366 2367 Address DeclPtr = Address::invalid(); 2368 bool DoStore = false; 2369 bool IsScalar = hasScalarEvaluationKind(Ty); 2370 // If we already have a pointer to the argument, reuse the input pointer. 2371 if (Arg.isIndirect()) { 2372 DeclPtr = Arg.getIndirectAddress(); 2373 // If we have a prettier pointer type at this point, bitcast to that. 2374 unsigned AS = DeclPtr.getType()->getAddressSpace(); 2375 llvm::Type *IRTy = ConvertTypeForMem(Ty)->getPointerTo(AS); 2376 if (DeclPtr.getType() != IRTy) 2377 DeclPtr = Builder.CreateBitCast(DeclPtr, IRTy, D.getName()); 2378 // Indirect argument is in alloca address space, which may be different 2379 // from the default address space. 2380 auto AllocaAS = CGM.getASTAllocaAddressSpace(); 2381 auto *V = DeclPtr.getPointer(); 2382 auto SrcLangAS = getLangOpts().OpenCL ? LangAS::opencl_private : AllocaAS; 2383 auto DestLangAS = 2384 getLangOpts().OpenCL ? LangAS::opencl_private : LangAS::Default; 2385 if (SrcLangAS != DestLangAS) { 2386 assert(getContext().getTargetAddressSpace(SrcLangAS) == 2387 CGM.getDataLayout().getAllocaAddrSpace()); 2388 auto DestAS = getContext().getTargetAddressSpace(DestLangAS); 2389 auto *T = V->getType()->getPointerElementType()->getPointerTo(DestAS); 2390 DeclPtr = Address(getTargetHooks().performAddrSpaceCast( 2391 *this, V, SrcLangAS, DestLangAS, T, true), 2392 DeclPtr.getAlignment()); 2393 } 2394 2395 // Push a destructor cleanup for this parameter if the ABI requires it. 2396 // Don't push a cleanup in a thunk for a method that will also emit a 2397 // cleanup. 2398 if (hasAggregateEvaluationKind(Ty) && !CurFuncIsThunk && 2399 Ty->getAs<RecordType>()->getDecl()->isParamDestroyedInCallee()) { 2400 if (QualType::DestructionKind DtorKind = Ty.isDestructedType()) { 2401 assert((DtorKind == QualType::DK_cxx_destructor || 2402 DtorKind == QualType::DK_nontrivial_c_struct) && 2403 "unexpected destructor type"); 2404 pushDestroy(DtorKind, DeclPtr, Ty); 2405 CalleeDestructedParamCleanups[cast<ParmVarDecl>(&D)] = 2406 EHStack.stable_begin(); 2407 } 2408 } 2409 } else { 2410 // Check if the parameter address is controlled by OpenMP runtime. 2411 Address OpenMPLocalAddr = 2412 getLangOpts().OpenMP 2413 ? CGM.getOpenMPRuntime().getAddressOfLocalVariable(*this, &D) 2414 : Address::invalid(); 2415 if (getLangOpts().OpenMP && OpenMPLocalAddr.isValid()) { 2416 DeclPtr = OpenMPLocalAddr; 2417 } else { 2418 // Otherwise, create a temporary to hold the value. 2419 DeclPtr = CreateMemTemp(Ty, getContext().getDeclAlign(&D), 2420 D.getName() + ".addr"); 2421 } 2422 DoStore = true; 2423 } 2424 2425 llvm::Value *ArgVal = (DoStore ? Arg.getDirectValue() : nullptr); 2426 2427 LValue lv = MakeAddrLValue(DeclPtr, Ty); 2428 if (IsScalar) { 2429 Qualifiers qs = Ty.getQualifiers(); 2430 if (Qualifiers::ObjCLifetime lt = qs.getObjCLifetime()) { 2431 // We honor __attribute__((ns_consumed)) for types with lifetime. 2432 // For __strong, it's handled by just skipping the initial retain; 2433 // otherwise we have to balance out the initial +1 with an extra 2434 // cleanup to do the release at the end of the function. 2435 bool isConsumed = D.hasAttr<NSConsumedAttr>(); 2436 2437 // If a parameter is pseudo-strong then we can omit the implicit retain. 2438 if (D.isARCPseudoStrong()) { 2439 assert(lt == Qualifiers::OCL_Strong && 2440 "pseudo-strong variable isn't strong?"); 2441 assert(qs.hasConst() && "pseudo-strong variable should be const!"); 2442 lt = Qualifiers::OCL_ExplicitNone; 2443 } 2444 2445 // Load objects passed indirectly. 2446 if (Arg.isIndirect() && !ArgVal) 2447 ArgVal = Builder.CreateLoad(DeclPtr); 2448 2449 if (lt == Qualifiers::OCL_Strong) { 2450 if (!isConsumed) { 2451 if (CGM.getCodeGenOpts().OptimizationLevel == 0) { 2452 // use objc_storeStrong(&dest, value) for retaining the 2453 // object. But first, store a null into 'dest' because 2454 // objc_storeStrong attempts to release its old value. 2455 llvm::Value *Null = CGM.EmitNullConstant(D.getType()); 2456 EmitStoreOfScalar(Null, lv, /* isInitialization */ true); 2457 EmitARCStoreStrongCall(lv.getAddress(), ArgVal, true); 2458 DoStore = false; 2459 } 2460 else 2461 // Don't use objc_retainBlock for block pointers, because we 2462 // don't want to Block_copy something just because we got it 2463 // as a parameter. 2464 ArgVal = EmitARCRetainNonBlock(ArgVal); 2465 } 2466 } else { 2467 // Push the cleanup for a consumed parameter. 2468 if (isConsumed) { 2469 ARCPreciseLifetime_t precise = (D.hasAttr<ObjCPreciseLifetimeAttr>() 2470 ? ARCPreciseLifetime : ARCImpreciseLifetime); 2471 EHStack.pushCleanup<ConsumeARCParameter>(getARCCleanupKind(), ArgVal, 2472 precise); 2473 } 2474 2475 if (lt == Qualifiers::OCL_Weak) { 2476 EmitARCInitWeak(DeclPtr, ArgVal); 2477 DoStore = false; // The weak init is a store, no need to do two. 2478 } 2479 } 2480 2481 // Enter the cleanup scope. 2482 EmitAutoVarWithLifetime(*this, D, DeclPtr, lt); 2483 } 2484 } 2485 2486 // Store the initial value into the alloca. 2487 if (DoStore) 2488 EmitStoreOfScalar(ArgVal, lv, /* isInitialization */ true); 2489 2490 setAddrOfLocalVar(&D, DeclPtr); 2491 2492 // Emit debug info for param declaration. 2493 if (CGDebugInfo *DI = getDebugInfo()) { 2494 if (CGM.getCodeGenOpts().getDebugInfo() >= 2495 codegenoptions::LimitedDebugInfo) { 2496 DI->EmitDeclareOfArgVariable(&D, DeclPtr.getPointer(), ArgNo, Builder); 2497 } 2498 } 2499 2500 if (D.hasAttr<AnnotateAttr>()) 2501 EmitVarAnnotations(&D, DeclPtr.getPointer()); 2502 2503 // We can only check return value nullability if all arguments to the 2504 // function satisfy their nullability preconditions. This makes it necessary 2505 // to emit null checks for args in the function body itself. 2506 if (requiresReturnValueNullabilityCheck()) { 2507 auto Nullability = Ty->getNullability(getContext()); 2508 if (Nullability && *Nullability == NullabilityKind::NonNull) { 2509 SanitizerScope SanScope(this); 2510 RetValNullabilityPrecondition = 2511 Builder.CreateAnd(RetValNullabilityPrecondition, 2512 Builder.CreateIsNotNull(Arg.getAnyValue())); 2513 } 2514 } 2515 } 2516 2517 void CodeGenModule::EmitOMPDeclareReduction(const OMPDeclareReductionDecl *D, 2518 CodeGenFunction *CGF) { 2519 if (!LangOpts.OpenMP || (!LangOpts.EmitAllDecls && !D->isUsed())) 2520 return; 2521 getOpenMPRuntime().emitUserDefinedReduction(CGF, D); 2522 } 2523 2524 void CodeGenModule::EmitOMPDeclareMapper(const OMPDeclareMapperDecl *D, 2525 CodeGenFunction *CGF) { 2526 if (!LangOpts.OpenMP || (!LangOpts.EmitAllDecls && !D->isUsed())) 2527 return; 2528 // FIXME: need to implement mapper code generation 2529 } 2530 2531 void CodeGenModule::EmitOMPRequiresDecl(const OMPRequiresDecl *D) { 2532 getOpenMPRuntime().checkArchForUnifiedAddressing(D); 2533 } 2534