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