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