1 //===--- CodeGenModule.cpp - Emit LLVM Code from ASTs for a Module --------===// 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 coordinates the per-module state used while generating code. 10 // 11 //===----------------------------------------------------------------------===// 12 13 #include "CodeGenModule.h" 14 #include "CGBlocks.h" 15 #include "CGCUDARuntime.h" 16 #include "CGCXXABI.h" 17 #include "CGCall.h" 18 #include "CGDebugInfo.h" 19 #include "CGObjCRuntime.h" 20 #include "CGOpenCLRuntime.h" 21 #include "CGOpenMPRuntime.h" 22 #include "CGOpenMPRuntimeAMDGCN.h" 23 #include "CGOpenMPRuntimeNVPTX.h" 24 #include "CodeGenFunction.h" 25 #include "CodeGenPGO.h" 26 #include "ConstantEmitter.h" 27 #include "CoverageMappingGen.h" 28 #include "TargetInfo.h" 29 #include "clang/AST/ASTContext.h" 30 #include "clang/AST/CharUnits.h" 31 #include "clang/AST/DeclCXX.h" 32 #include "clang/AST/DeclObjC.h" 33 #include "clang/AST/DeclTemplate.h" 34 #include "clang/AST/Mangle.h" 35 #include "clang/AST/RecordLayout.h" 36 #include "clang/AST/RecursiveASTVisitor.h" 37 #include "clang/AST/StmtVisitor.h" 38 #include "clang/Basic/Builtins.h" 39 #include "clang/Basic/CharInfo.h" 40 #include "clang/Basic/CodeGenOptions.h" 41 #include "clang/Basic/Diagnostic.h" 42 #include "clang/Basic/FileManager.h" 43 #include "clang/Basic/Module.h" 44 #include "clang/Basic/SourceManager.h" 45 #include "clang/Basic/TargetInfo.h" 46 #include "clang/Basic/Version.h" 47 #include "clang/CodeGen/ConstantInitBuilder.h" 48 #include "clang/Frontend/FrontendDiagnostic.h" 49 #include "llvm/ADT/StringSwitch.h" 50 #include "llvm/ADT/Triple.h" 51 #include "llvm/Analysis/TargetLibraryInfo.h" 52 #include "llvm/Frontend/OpenMP/OMPIRBuilder.h" 53 #include "llvm/IR/CallingConv.h" 54 #include "llvm/IR/DataLayout.h" 55 #include "llvm/IR/Intrinsics.h" 56 #include "llvm/IR/LLVMContext.h" 57 #include "llvm/IR/Module.h" 58 #include "llvm/IR/ProfileSummary.h" 59 #include "llvm/ProfileData/InstrProfReader.h" 60 #include "llvm/Support/CodeGen.h" 61 #include "llvm/Support/CommandLine.h" 62 #include "llvm/Support/ConvertUTF.h" 63 #include "llvm/Support/ErrorHandling.h" 64 #include "llvm/Support/MD5.h" 65 #include "llvm/Support/TimeProfiler.h" 66 #include "llvm/Support/X86TargetParser.h" 67 68 using namespace clang; 69 using namespace CodeGen; 70 71 static llvm::cl::opt<bool> LimitedCoverage( 72 "limited-coverage-experimental", llvm::cl::ZeroOrMore, llvm::cl::Hidden, 73 llvm::cl::desc("Emit limited coverage mapping information (experimental)"), 74 llvm::cl::init(false)); 75 76 static const char AnnotationSection[] = "llvm.metadata"; 77 78 static CGCXXABI *createCXXABI(CodeGenModule &CGM) { 79 switch (CGM.getContext().getCXXABIKind()) { 80 case TargetCXXABI::AppleARM64: 81 case TargetCXXABI::Fuchsia: 82 case TargetCXXABI::GenericAArch64: 83 case TargetCXXABI::GenericARM: 84 case TargetCXXABI::iOS: 85 case TargetCXXABI::WatchOS: 86 case TargetCXXABI::GenericMIPS: 87 case TargetCXXABI::GenericItanium: 88 case TargetCXXABI::WebAssembly: 89 case TargetCXXABI::XL: 90 return CreateItaniumCXXABI(CGM); 91 case TargetCXXABI::Microsoft: 92 return CreateMicrosoftCXXABI(CGM); 93 } 94 95 llvm_unreachable("invalid C++ ABI kind"); 96 } 97 98 CodeGenModule::CodeGenModule(ASTContext &C, const HeaderSearchOptions &HSO, 99 const PreprocessorOptions &PPO, 100 const CodeGenOptions &CGO, llvm::Module &M, 101 DiagnosticsEngine &diags, 102 CoverageSourceInfo *CoverageInfo) 103 : Context(C), LangOpts(C.getLangOpts()), HeaderSearchOpts(HSO), 104 PreprocessorOpts(PPO), CodeGenOpts(CGO), TheModule(M), Diags(diags), 105 Target(C.getTargetInfo()), ABI(createCXXABI(*this)), 106 VMContext(M.getContext()), Types(*this), VTables(*this), 107 SanitizerMD(new SanitizerMetadata(*this)) { 108 109 // Initialize the type cache. 110 llvm::LLVMContext &LLVMContext = M.getContext(); 111 VoidTy = llvm::Type::getVoidTy(LLVMContext); 112 Int8Ty = llvm::Type::getInt8Ty(LLVMContext); 113 Int16Ty = llvm::Type::getInt16Ty(LLVMContext); 114 Int32Ty = llvm::Type::getInt32Ty(LLVMContext); 115 Int64Ty = llvm::Type::getInt64Ty(LLVMContext); 116 HalfTy = llvm::Type::getHalfTy(LLVMContext); 117 BFloatTy = llvm::Type::getBFloatTy(LLVMContext); 118 FloatTy = llvm::Type::getFloatTy(LLVMContext); 119 DoubleTy = llvm::Type::getDoubleTy(LLVMContext); 120 PointerWidthInBits = C.getTargetInfo().getPointerWidth(0); 121 PointerAlignInBytes = 122 C.toCharUnitsFromBits(C.getTargetInfo().getPointerAlign(0)).getQuantity(); 123 SizeSizeInBytes = 124 C.toCharUnitsFromBits(C.getTargetInfo().getMaxPointerWidth()).getQuantity(); 125 IntAlignInBytes = 126 C.toCharUnitsFromBits(C.getTargetInfo().getIntAlign()).getQuantity(); 127 CharTy = 128 llvm::IntegerType::get(LLVMContext, C.getTargetInfo().getCharWidth()); 129 IntTy = llvm::IntegerType::get(LLVMContext, C.getTargetInfo().getIntWidth()); 130 IntPtrTy = llvm::IntegerType::get(LLVMContext, 131 C.getTargetInfo().getMaxPointerWidth()); 132 Int8PtrTy = Int8Ty->getPointerTo(0); 133 Int8PtrPtrTy = Int8PtrTy->getPointerTo(0); 134 const llvm::DataLayout &DL = M.getDataLayout(); 135 AllocaInt8PtrTy = Int8Ty->getPointerTo(DL.getAllocaAddrSpace()); 136 GlobalsInt8PtrTy = Int8Ty->getPointerTo(DL.getDefaultGlobalsAddressSpace()); 137 ASTAllocaAddressSpace = getTargetCodeGenInfo().getASTAllocaAddressSpace(); 138 139 RuntimeCC = getTargetCodeGenInfo().getABIInfo().getRuntimeCC(); 140 141 if (LangOpts.ObjC) 142 createObjCRuntime(); 143 if (LangOpts.OpenCL) 144 createOpenCLRuntime(); 145 if (LangOpts.OpenMP) 146 createOpenMPRuntime(); 147 if (LangOpts.CUDA) 148 createCUDARuntime(); 149 150 // Enable TBAA unless it's suppressed. ThreadSanitizer needs TBAA even at O0. 151 if (LangOpts.Sanitize.has(SanitizerKind::Thread) || 152 (!CodeGenOpts.RelaxedAliasing && CodeGenOpts.OptimizationLevel > 0)) 153 TBAA.reset(new CodeGenTBAA(Context, TheModule, CodeGenOpts, getLangOpts(), 154 getCXXABI().getMangleContext())); 155 156 // If debug info or coverage generation is enabled, create the CGDebugInfo 157 // object. 158 if (CodeGenOpts.getDebugInfo() != codegenoptions::NoDebugInfo || 159 CodeGenOpts.EmitGcovArcs || CodeGenOpts.EmitGcovNotes) 160 DebugInfo.reset(new CGDebugInfo(*this)); 161 162 Block.GlobalUniqueCount = 0; 163 164 if (C.getLangOpts().ObjC) 165 ObjCData.reset(new ObjCEntrypoints()); 166 167 if (CodeGenOpts.hasProfileClangUse()) { 168 auto ReaderOrErr = llvm::IndexedInstrProfReader::create( 169 CodeGenOpts.ProfileInstrumentUsePath, CodeGenOpts.ProfileRemappingFile); 170 if (auto E = ReaderOrErr.takeError()) { 171 unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error, 172 "Could not read profile %0: %1"); 173 llvm::handleAllErrors(std::move(E), [&](const llvm::ErrorInfoBase &EI) { 174 getDiags().Report(DiagID) << CodeGenOpts.ProfileInstrumentUsePath 175 << EI.message(); 176 }); 177 } else 178 PGOReader = std::move(ReaderOrErr.get()); 179 } 180 181 // If coverage mapping generation is enabled, create the 182 // CoverageMappingModuleGen object. 183 if (CodeGenOpts.CoverageMapping) 184 CoverageMapping.reset(new CoverageMappingModuleGen(*this, *CoverageInfo)); 185 186 // Generate the module name hash here if needed. 187 if (CodeGenOpts.UniqueInternalLinkageNames && 188 !getModule().getSourceFileName().empty()) { 189 std::string Path = getModule().getSourceFileName(); 190 // Check if a path substitution is needed from the MacroPrefixMap. 191 for (const auto &Entry : LangOpts.MacroPrefixMap) 192 if (Path.rfind(Entry.first, 0) != std::string::npos) { 193 Path = Entry.second + Path.substr(Entry.first.size()); 194 break; 195 } 196 llvm::MD5 Md5; 197 Md5.update(Path); 198 llvm::MD5::MD5Result R; 199 Md5.final(R); 200 SmallString<32> Str; 201 llvm::MD5::stringifyResult(R, Str); 202 // Convert MD5hash to Decimal. Demangler suffixes can either contain 203 // numbers or characters but not both. 204 llvm::APInt IntHash(128, Str.str(), 16); 205 // Prepend "__uniq" before the hash for tools like profilers to understand 206 // that this symbol is of internal linkage type. The "__uniq" is the 207 // pre-determined prefix that is used to tell tools that this symbol was 208 // created with -funique-internal-linakge-symbols and the tools can strip or 209 // keep the prefix as needed. 210 ModuleNameHash = (Twine(".__uniq.") + 211 Twine(toString(IntHash, /* Radix = */ 10, /* Signed = */false))).str(); 212 } 213 } 214 215 CodeGenModule::~CodeGenModule() {} 216 217 void CodeGenModule::createObjCRuntime() { 218 // This is just isGNUFamily(), but we want to force implementors of 219 // new ABIs to decide how best to do this. 220 switch (LangOpts.ObjCRuntime.getKind()) { 221 case ObjCRuntime::GNUstep: 222 case ObjCRuntime::GCC: 223 case ObjCRuntime::ObjFW: 224 ObjCRuntime.reset(CreateGNUObjCRuntime(*this)); 225 return; 226 227 case ObjCRuntime::FragileMacOSX: 228 case ObjCRuntime::MacOSX: 229 case ObjCRuntime::iOS: 230 case ObjCRuntime::WatchOS: 231 ObjCRuntime.reset(CreateMacObjCRuntime(*this)); 232 return; 233 } 234 llvm_unreachable("bad runtime kind"); 235 } 236 237 void CodeGenModule::createOpenCLRuntime() { 238 OpenCLRuntime.reset(new CGOpenCLRuntime(*this)); 239 } 240 241 void CodeGenModule::createOpenMPRuntime() { 242 // Select a specialized code generation class based on the target, if any. 243 // If it does not exist use the default implementation. 244 switch (getTriple().getArch()) { 245 case llvm::Triple::nvptx: 246 case llvm::Triple::nvptx64: 247 assert(getLangOpts().OpenMPIsDevice && 248 "OpenMP NVPTX is only prepared to deal with device code."); 249 OpenMPRuntime.reset(new CGOpenMPRuntimeNVPTX(*this)); 250 break; 251 case llvm::Triple::amdgcn: 252 assert(getLangOpts().OpenMPIsDevice && 253 "OpenMP AMDGCN is only prepared to deal with device code."); 254 OpenMPRuntime.reset(new CGOpenMPRuntimeAMDGCN(*this)); 255 break; 256 default: 257 if (LangOpts.OpenMPSimd) 258 OpenMPRuntime.reset(new CGOpenMPSIMDRuntime(*this)); 259 else 260 OpenMPRuntime.reset(new CGOpenMPRuntime(*this)); 261 break; 262 } 263 } 264 265 void CodeGenModule::createCUDARuntime() { 266 CUDARuntime.reset(CreateNVCUDARuntime(*this)); 267 } 268 269 void CodeGenModule::addReplacement(StringRef Name, llvm::Constant *C) { 270 Replacements[Name] = C; 271 } 272 273 void CodeGenModule::applyReplacements() { 274 for (auto &I : Replacements) { 275 StringRef MangledName = I.first(); 276 llvm::Constant *Replacement = I.second; 277 llvm::GlobalValue *Entry = GetGlobalValue(MangledName); 278 if (!Entry) 279 continue; 280 auto *OldF = cast<llvm::Function>(Entry); 281 auto *NewF = dyn_cast<llvm::Function>(Replacement); 282 if (!NewF) { 283 if (auto *Alias = dyn_cast<llvm::GlobalAlias>(Replacement)) { 284 NewF = dyn_cast<llvm::Function>(Alias->getAliasee()); 285 } else { 286 auto *CE = cast<llvm::ConstantExpr>(Replacement); 287 assert(CE->getOpcode() == llvm::Instruction::BitCast || 288 CE->getOpcode() == llvm::Instruction::GetElementPtr); 289 NewF = dyn_cast<llvm::Function>(CE->getOperand(0)); 290 } 291 } 292 293 // Replace old with new, but keep the old order. 294 OldF->replaceAllUsesWith(Replacement); 295 if (NewF) { 296 NewF->removeFromParent(); 297 OldF->getParent()->getFunctionList().insertAfter(OldF->getIterator(), 298 NewF); 299 } 300 OldF->eraseFromParent(); 301 } 302 } 303 304 void CodeGenModule::addGlobalValReplacement(llvm::GlobalValue *GV, llvm::Constant *C) { 305 GlobalValReplacements.push_back(std::make_pair(GV, C)); 306 } 307 308 void CodeGenModule::applyGlobalValReplacements() { 309 for (auto &I : GlobalValReplacements) { 310 llvm::GlobalValue *GV = I.first; 311 llvm::Constant *C = I.second; 312 313 GV->replaceAllUsesWith(C); 314 GV->eraseFromParent(); 315 } 316 } 317 318 // This is only used in aliases that we created and we know they have a 319 // linear structure. 320 static const llvm::GlobalObject *getAliasedGlobal( 321 const llvm::GlobalIndirectSymbol &GIS) { 322 llvm::SmallPtrSet<const llvm::GlobalIndirectSymbol*, 4> Visited; 323 const llvm::Constant *C = &GIS; 324 for (;;) { 325 C = C->stripPointerCasts(); 326 if (auto *GO = dyn_cast<llvm::GlobalObject>(C)) 327 return GO; 328 // stripPointerCasts will not walk over weak aliases. 329 auto *GIS2 = dyn_cast<llvm::GlobalIndirectSymbol>(C); 330 if (!GIS2) 331 return nullptr; 332 if (!Visited.insert(GIS2).second) 333 return nullptr; 334 C = GIS2->getIndirectSymbol(); 335 } 336 } 337 338 void CodeGenModule::checkAliases() { 339 // Check if the constructed aliases are well formed. It is really unfortunate 340 // that we have to do this in CodeGen, but we only construct mangled names 341 // and aliases during codegen. 342 bool Error = false; 343 DiagnosticsEngine &Diags = getDiags(); 344 for (const GlobalDecl &GD : Aliases) { 345 const auto *D = cast<ValueDecl>(GD.getDecl()); 346 SourceLocation Location; 347 bool IsIFunc = D->hasAttr<IFuncAttr>(); 348 if (const Attr *A = D->getDefiningAttr()) 349 Location = A->getLocation(); 350 else 351 llvm_unreachable("Not an alias or ifunc?"); 352 StringRef MangledName = getMangledName(GD); 353 llvm::GlobalValue *Entry = GetGlobalValue(MangledName); 354 auto *Alias = cast<llvm::GlobalIndirectSymbol>(Entry); 355 const llvm::GlobalValue *GV = getAliasedGlobal(*Alias); 356 if (!GV) { 357 Error = true; 358 Diags.Report(Location, diag::err_cyclic_alias) << IsIFunc; 359 } else if (GV->isDeclaration()) { 360 Error = true; 361 Diags.Report(Location, diag::err_alias_to_undefined) 362 << IsIFunc << IsIFunc; 363 } else if (IsIFunc) { 364 // Check resolver function type. 365 llvm::FunctionType *FTy = dyn_cast<llvm::FunctionType>( 366 GV->getType()->getPointerElementType()); 367 assert(FTy); 368 if (!FTy->getReturnType()->isPointerTy()) 369 Diags.Report(Location, diag::err_ifunc_resolver_return); 370 } 371 372 llvm::Constant *Aliasee = Alias->getIndirectSymbol(); 373 llvm::GlobalValue *AliaseeGV; 374 if (auto CE = dyn_cast<llvm::ConstantExpr>(Aliasee)) 375 AliaseeGV = cast<llvm::GlobalValue>(CE->getOperand(0)); 376 else 377 AliaseeGV = cast<llvm::GlobalValue>(Aliasee); 378 379 if (const SectionAttr *SA = D->getAttr<SectionAttr>()) { 380 StringRef AliasSection = SA->getName(); 381 if (AliasSection != AliaseeGV->getSection()) 382 Diags.Report(SA->getLocation(), diag::warn_alias_with_section) 383 << AliasSection << IsIFunc << IsIFunc; 384 } 385 386 // We have to handle alias to weak aliases in here. LLVM itself disallows 387 // this since the object semantics would not match the IL one. For 388 // compatibility with gcc we implement it by just pointing the alias 389 // to its aliasee's aliasee. We also warn, since the user is probably 390 // expecting the link to be weak. 391 if (auto GA = dyn_cast<llvm::GlobalIndirectSymbol>(AliaseeGV)) { 392 if (GA->isInterposable()) { 393 Diags.Report(Location, diag::warn_alias_to_weak_alias) 394 << GV->getName() << GA->getName() << IsIFunc; 395 Aliasee = llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast( 396 GA->getIndirectSymbol(), Alias->getType()); 397 Alias->setIndirectSymbol(Aliasee); 398 } 399 } 400 } 401 if (!Error) 402 return; 403 404 for (const GlobalDecl &GD : Aliases) { 405 StringRef MangledName = getMangledName(GD); 406 llvm::GlobalValue *Entry = GetGlobalValue(MangledName); 407 auto *Alias = cast<llvm::GlobalIndirectSymbol>(Entry); 408 Alias->replaceAllUsesWith(llvm::UndefValue::get(Alias->getType())); 409 Alias->eraseFromParent(); 410 } 411 } 412 413 void CodeGenModule::clear() { 414 DeferredDeclsToEmit.clear(); 415 if (OpenMPRuntime) 416 OpenMPRuntime->clear(); 417 } 418 419 void InstrProfStats::reportDiagnostics(DiagnosticsEngine &Diags, 420 StringRef MainFile) { 421 if (!hasDiagnostics()) 422 return; 423 if (VisitedInMainFile > 0 && VisitedInMainFile == MissingInMainFile) { 424 if (MainFile.empty()) 425 MainFile = "<stdin>"; 426 Diags.Report(diag::warn_profile_data_unprofiled) << MainFile; 427 } else { 428 if (Mismatched > 0) 429 Diags.Report(diag::warn_profile_data_out_of_date) << Visited << Mismatched; 430 431 if (Missing > 0) 432 Diags.Report(diag::warn_profile_data_missing) << Visited << Missing; 433 } 434 } 435 436 static void setVisibilityFromDLLStorageClass(const clang::LangOptions &LO, 437 llvm::Module &M) { 438 if (!LO.VisibilityFromDLLStorageClass) 439 return; 440 441 llvm::GlobalValue::VisibilityTypes DLLExportVisibility = 442 CodeGenModule::GetLLVMVisibility(LO.getDLLExportVisibility()); 443 llvm::GlobalValue::VisibilityTypes NoDLLStorageClassVisibility = 444 CodeGenModule::GetLLVMVisibility(LO.getNoDLLStorageClassVisibility()); 445 llvm::GlobalValue::VisibilityTypes ExternDeclDLLImportVisibility = 446 CodeGenModule::GetLLVMVisibility(LO.getExternDeclDLLImportVisibility()); 447 llvm::GlobalValue::VisibilityTypes ExternDeclNoDLLStorageClassVisibility = 448 CodeGenModule::GetLLVMVisibility( 449 LO.getExternDeclNoDLLStorageClassVisibility()); 450 451 for (llvm::GlobalValue &GV : M.global_values()) { 452 if (GV.hasAppendingLinkage() || GV.hasLocalLinkage()) 453 continue; 454 455 // Reset DSO locality before setting the visibility. This removes 456 // any effects that visibility options and annotations may have 457 // had on the DSO locality. Setting the visibility will implicitly set 458 // appropriate globals to DSO Local; however, this will be pessimistic 459 // w.r.t. to the normal compiler IRGen. 460 GV.setDSOLocal(false); 461 462 if (GV.isDeclarationForLinker()) { 463 GV.setVisibility(GV.getDLLStorageClass() == 464 llvm::GlobalValue::DLLImportStorageClass 465 ? ExternDeclDLLImportVisibility 466 : ExternDeclNoDLLStorageClassVisibility); 467 } else { 468 GV.setVisibility(GV.getDLLStorageClass() == 469 llvm::GlobalValue::DLLExportStorageClass 470 ? DLLExportVisibility 471 : NoDLLStorageClassVisibility); 472 } 473 474 GV.setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass); 475 } 476 } 477 478 void CodeGenModule::Release() { 479 EmitDeferred(); 480 EmitVTablesOpportunistically(); 481 applyGlobalValReplacements(); 482 applyReplacements(); 483 checkAliases(); 484 emitMultiVersionFunctions(); 485 EmitCXXGlobalInitFunc(); 486 EmitCXXGlobalCleanUpFunc(); 487 registerGlobalDtorsWithAtExit(); 488 EmitCXXThreadLocalInitFunc(); 489 if (ObjCRuntime) 490 if (llvm::Function *ObjCInitFunction = ObjCRuntime->ModuleInitFunction()) 491 AddGlobalCtor(ObjCInitFunction); 492 if (Context.getLangOpts().CUDA && CUDARuntime) { 493 if (llvm::Function *CudaCtorFunction = CUDARuntime->finalizeModule()) 494 AddGlobalCtor(CudaCtorFunction); 495 } 496 if (OpenMPRuntime) { 497 if (llvm::Function *OpenMPRequiresDirectiveRegFun = 498 OpenMPRuntime->emitRequiresDirectiveRegFun()) { 499 AddGlobalCtor(OpenMPRequiresDirectiveRegFun, 0); 500 } 501 OpenMPRuntime->createOffloadEntriesAndInfoMetadata(); 502 OpenMPRuntime->clear(); 503 } 504 if (PGOReader) { 505 getModule().setProfileSummary( 506 PGOReader->getSummary(/* UseCS */ false).getMD(VMContext), 507 llvm::ProfileSummary::PSK_Instr); 508 if (PGOStats.hasDiagnostics()) 509 PGOStats.reportDiagnostics(getDiags(), getCodeGenOpts().MainFileName); 510 } 511 EmitCtorList(GlobalCtors, "llvm.global_ctors"); 512 EmitCtorList(GlobalDtors, "llvm.global_dtors"); 513 EmitGlobalAnnotations(); 514 EmitStaticExternCAliases(); 515 EmitDeferredUnusedCoverageMappings(); 516 CodeGenPGO(*this).setValueProfilingFlag(getModule()); 517 if (CoverageMapping) 518 CoverageMapping->emit(); 519 if (CodeGenOpts.SanitizeCfiCrossDso) { 520 CodeGenFunction(*this).EmitCfiCheckFail(); 521 CodeGenFunction(*this).EmitCfiCheckStub(); 522 } 523 emitAtAvailableLinkGuard(); 524 if (Context.getTargetInfo().getTriple().isWasm() && 525 !Context.getTargetInfo().getTriple().isOSEmscripten()) { 526 EmitMainVoidAlias(); 527 } 528 529 // Emit reference of __amdgpu_device_library_preserve_asan_functions to 530 // preserve ASAN functions in bitcode libraries. 531 if (LangOpts.Sanitize.has(SanitizerKind::Address) && getTriple().isAMDGPU()) { 532 auto *FT = llvm::FunctionType::get(VoidTy, {}); 533 auto *F = llvm::Function::Create( 534 FT, llvm::GlobalValue::ExternalLinkage, 535 "__amdgpu_device_library_preserve_asan_functions", &getModule()); 536 auto *Var = new llvm::GlobalVariable( 537 getModule(), FT->getPointerTo(), 538 /*isConstant=*/true, llvm::GlobalValue::WeakAnyLinkage, F, 539 "__amdgpu_device_library_preserve_asan_functions_ptr", nullptr, 540 llvm::GlobalVariable::NotThreadLocal); 541 addCompilerUsedGlobal(Var); 542 } 543 544 emitLLVMUsed(); 545 if (SanStats) 546 SanStats->finish(); 547 548 if (CodeGenOpts.Autolink && 549 (Context.getLangOpts().Modules || !LinkerOptionsMetadata.empty())) { 550 EmitModuleLinkOptions(); 551 } 552 553 // On ELF we pass the dependent library specifiers directly to the linker 554 // without manipulating them. This is in contrast to other platforms where 555 // they are mapped to a specific linker option by the compiler. This 556 // difference is a result of the greater variety of ELF linkers and the fact 557 // that ELF linkers tend to handle libraries in a more complicated fashion 558 // than on other platforms. This forces us to defer handling the dependent 559 // libs to the linker. 560 // 561 // CUDA/HIP device and host libraries are different. Currently there is no 562 // way to differentiate dependent libraries for host or device. Existing 563 // usage of #pragma comment(lib, *) is intended for host libraries on 564 // Windows. Therefore emit llvm.dependent-libraries only for host. 565 if (!ELFDependentLibraries.empty() && !Context.getLangOpts().CUDAIsDevice) { 566 auto *NMD = getModule().getOrInsertNamedMetadata("llvm.dependent-libraries"); 567 for (auto *MD : ELFDependentLibraries) 568 NMD->addOperand(MD); 569 } 570 571 // Record mregparm value now so it is visible through rest of codegen. 572 if (Context.getTargetInfo().getTriple().getArch() == llvm::Triple::x86) 573 getModule().addModuleFlag(llvm::Module::Error, "NumRegisterParameters", 574 CodeGenOpts.NumRegisterParameters); 575 576 if (CodeGenOpts.DwarfVersion) { 577 getModule().addModuleFlag(llvm::Module::Max, "Dwarf Version", 578 CodeGenOpts.DwarfVersion); 579 } 580 581 if (CodeGenOpts.Dwarf64) 582 getModule().addModuleFlag(llvm::Module::Max, "DWARF64", 1); 583 584 if (Context.getLangOpts().SemanticInterposition) 585 // Require various optimization to respect semantic interposition. 586 getModule().setSemanticInterposition(1); 587 588 if (CodeGenOpts.EmitCodeView) { 589 // Indicate that we want CodeView in the metadata. 590 getModule().addModuleFlag(llvm::Module::Warning, "CodeView", 1); 591 } 592 if (CodeGenOpts.CodeViewGHash) { 593 getModule().addModuleFlag(llvm::Module::Warning, "CodeViewGHash", 1); 594 } 595 if (CodeGenOpts.ControlFlowGuard) { 596 // Function ID tables and checks for Control Flow Guard (cfguard=2). 597 getModule().addModuleFlag(llvm::Module::Warning, "cfguard", 2); 598 } else if (CodeGenOpts.ControlFlowGuardNoChecks) { 599 // Function ID tables for Control Flow Guard (cfguard=1). 600 getModule().addModuleFlag(llvm::Module::Warning, "cfguard", 1); 601 } 602 if (CodeGenOpts.EHContGuard) { 603 // Function ID tables for EH Continuation Guard. 604 getModule().addModuleFlag(llvm::Module::Warning, "ehcontguard", 1); 605 } 606 if (CodeGenOpts.OptimizationLevel > 0 && CodeGenOpts.StrictVTablePointers) { 607 // We don't support LTO with 2 with different StrictVTablePointers 608 // FIXME: we could support it by stripping all the information introduced 609 // by StrictVTablePointers. 610 611 getModule().addModuleFlag(llvm::Module::Error, "StrictVTablePointers",1); 612 613 llvm::Metadata *Ops[2] = { 614 llvm::MDString::get(VMContext, "StrictVTablePointers"), 615 llvm::ConstantAsMetadata::get(llvm::ConstantInt::get( 616 llvm::Type::getInt32Ty(VMContext), 1))}; 617 618 getModule().addModuleFlag(llvm::Module::Require, 619 "StrictVTablePointersRequirement", 620 llvm::MDNode::get(VMContext, Ops)); 621 } 622 if (getModuleDebugInfo()) 623 // We support a single version in the linked module. The LLVM 624 // parser will drop debug info with a different version number 625 // (and warn about it, too). 626 getModule().addModuleFlag(llvm::Module::Warning, "Debug Info Version", 627 llvm::DEBUG_METADATA_VERSION); 628 629 // We need to record the widths of enums and wchar_t, so that we can generate 630 // the correct build attributes in the ARM backend. wchar_size is also used by 631 // TargetLibraryInfo. 632 uint64_t WCharWidth = 633 Context.getTypeSizeInChars(Context.getWideCharType()).getQuantity(); 634 getModule().addModuleFlag(llvm::Module::Error, "wchar_size", WCharWidth); 635 636 llvm::Triple::ArchType Arch = Context.getTargetInfo().getTriple().getArch(); 637 if ( Arch == llvm::Triple::arm 638 || Arch == llvm::Triple::armeb 639 || Arch == llvm::Triple::thumb 640 || Arch == llvm::Triple::thumbeb) { 641 // The minimum width of an enum in bytes 642 uint64_t EnumWidth = Context.getLangOpts().ShortEnums ? 1 : 4; 643 getModule().addModuleFlag(llvm::Module::Error, "min_enum_size", EnumWidth); 644 } 645 646 if (Arch == llvm::Triple::riscv32 || Arch == llvm::Triple::riscv64) { 647 StringRef ABIStr = Target.getABI(); 648 llvm::LLVMContext &Ctx = TheModule.getContext(); 649 getModule().addModuleFlag(llvm::Module::Error, "target-abi", 650 llvm::MDString::get(Ctx, ABIStr)); 651 } 652 653 if (CodeGenOpts.SanitizeCfiCrossDso) { 654 // Indicate that we want cross-DSO control flow integrity checks. 655 getModule().addModuleFlag(llvm::Module::Override, "Cross-DSO CFI", 1); 656 } 657 658 if (CodeGenOpts.WholeProgramVTables) { 659 // Indicate whether VFE was enabled for this module, so that the 660 // vcall_visibility metadata added under whole program vtables is handled 661 // appropriately in the optimizer. 662 getModule().addModuleFlag(llvm::Module::Error, "Virtual Function Elim", 663 CodeGenOpts.VirtualFunctionElimination); 664 } 665 666 if (LangOpts.Sanitize.has(SanitizerKind::CFIICall)) { 667 getModule().addModuleFlag(llvm::Module::Override, 668 "CFI Canonical Jump Tables", 669 CodeGenOpts.SanitizeCfiCanonicalJumpTables); 670 } 671 672 if (CodeGenOpts.CFProtectionReturn && 673 Target.checkCFProtectionReturnSupported(getDiags())) { 674 // Indicate that we want to instrument return control flow protection. 675 getModule().addModuleFlag(llvm::Module::Override, "cf-protection-return", 676 1); 677 } 678 679 if (CodeGenOpts.CFProtectionBranch && 680 Target.checkCFProtectionBranchSupported(getDiags())) { 681 // Indicate that we want to instrument branch control flow protection. 682 getModule().addModuleFlag(llvm::Module::Override, "cf-protection-branch", 683 1); 684 } 685 686 if (Arch == llvm::Triple::aarch64 || Arch == llvm::Triple::aarch64_32 || 687 Arch == llvm::Triple::aarch64_be) { 688 getModule().addModuleFlag(llvm::Module::Error, 689 "branch-target-enforcement", 690 LangOpts.BranchTargetEnforcement); 691 692 getModule().addModuleFlag(llvm::Module::Error, "sign-return-address", 693 LangOpts.hasSignReturnAddress()); 694 695 getModule().addModuleFlag(llvm::Module::Error, "sign-return-address-all", 696 LangOpts.isSignReturnAddressScopeAll()); 697 698 getModule().addModuleFlag(llvm::Module::Error, 699 "sign-return-address-with-bkey", 700 !LangOpts.isSignReturnAddressWithAKey()); 701 } 702 703 if (!CodeGenOpts.MemoryProfileOutput.empty()) { 704 llvm::LLVMContext &Ctx = TheModule.getContext(); 705 getModule().addModuleFlag( 706 llvm::Module::Error, "MemProfProfileFilename", 707 llvm::MDString::get(Ctx, CodeGenOpts.MemoryProfileOutput)); 708 } 709 710 if (LangOpts.CUDAIsDevice && getTriple().isNVPTX()) { 711 // Indicate whether __nvvm_reflect should be configured to flush denormal 712 // floating point values to 0. (This corresponds to its "__CUDA_FTZ" 713 // property.) 714 getModule().addModuleFlag(llvm::Module::Override, "nvvm-reflect-ftz", 715 CodeGenOpts.FP32DenormalMode.Output != 716 llvm::DenormalMode::IEEE); 717 } 718 719 if (LangOpts.EHAsynch) 720 getModule().addModuleFlag(llvm::Module::Warning, "eh-asynch", 1); 721 722 // Indicate whether this Module was compiled with -fopenmp 723 if (getLangOpts().OpenMP && !getLangOpts().OpenMPSimd) 724 getModule().addModuleFlag(llvm::Module::Max, "openmp", LangOpts.OpenMP); 725 if (getLangOpts().OpenMPIsDevice) 726 getModule().addModuleFlag(llvm::Module::Max, "openmp-device", 727 LangOpts.OpenMP); 728 729 // Emit OpenCL specific module metadata: OpenCL/SPIR version. 730 if (LangOpts.OpenCL) { 731 EmitOpenCLMetadata(); 732 // Emit SPIR version. 733 if (getTriple().isSPIR()) { 734 // SPIR v2.0 s2.12 - The SPIR version used by the module is stored in the 735 // opencl.spir.version named metadata. 736 // C++ for OpenCL has a distinct mapping for version compatibility with 737 // OpenCL. 738 auto Version = LangOpts.getOpenCLCompatibleVersion(); 739 llvm::Metadata *SPIRVerElts[] = { 740 llvm::ConstantAsMetadata::get(llvm::ConstantInt::get( 741 Int32Ty, Version / 100)), 742 llvm::ConstantAsMetadata::get(llvm::ConstantInt::get( 743 Int32Ty, (Version / 100 > 1) ? 0 : 2))}; 744 llvm::NamedMDNode *SPIRVerMD = 745 TheModule.getOrInsertNamedMetadata("opencl.spir.version"); 746 llvm::LLVMContext &Ctx = TheModule.getContext(); 747 SPIRVerMD->addOperand(llvm::MDNode::get(Ctx, SPIRVerElts)); 748 } 749 } 750 751 if (uint32_t PLevel = Context.getLangOpts().PICLevel) { 752 assert(PLevel < 3 && "Invalid PIC Level"); 753 getModule().setPICLevel(static_cast<llvm::PICLevel::Level>(PLevel)); 754 if (Context.getLangOpts().PIE) 755 getModule().setPIELevel(static_cast<llvm::PIELevel::Level>(PLevel)); 756 } 757 758 if (getCodeGenOpts().CodeModel.size() > 0) { 759 unsigned CM = llvm::StringSwitch<unsigned>(getCodeGenOpts().CodeModel) 760 .Case("tiny", llvm::CodeModel::Tiny) 761 .Case("small", llvm::CodeModel::Small) 762 .Case("kernel", llvm::CodeModel::Kernel) 763 .Case("medium", llvm::CodeModel::Medium) 764 .Case("large", llvm::CodeModel::Large) 765 .Default(~0u); 766 if (CM != ~0u) { 767 llvm::CodeModel::Model codeModel = static_cast<llvm::CodeModel::Model>(CM); 768 getModule().setCodeModel(codeModel); 769 } 770 } 771 772 if (CodeGenOpts.NoPLT) 773 getModule().setRtLibUseGOT(); 774 if (CodeGenOpts.UnwindTables) 775 getModule().setUwtable(); 776 777 switch (CodeGenOpts.getFramePointer()) { 778 case CodeGenOptions::FramePointerKind::None: 779 // 0 ("none") is the default. 780 break; 781 case CodeGenOptions::FramePointerKind::NonLeaf: 782 getModule().setFramePointer(llvm::FramePointerKind::NonLeaf); 783 break; 784 case CodeGenOptions::FramePointerKind::All: 785 getModule().setFramePointer(llvm::FramePointerKind::All); 786 break; 787 } 788 789 SimplifyPersonality(); 790 791 if (getCodeGenOpts().EmitDeclMetadata) 792 EmitDeclMetadata(); 793 794 if (getCodeGenOpts().EmitGcovArcs || getCodeGenOpts().EmitGcovNotes) 795 EmitCoverageFile(); 796 797 if (CGDebugInfo *DI = getModuleDebugInfo()) 798 DI->finalize(); 799 800 if (getCodeGenOpts().EmitVersionIdentMetadata) 801 EmitVersionIdentMetadata(); 802 803 if (!getCodeGenOpts().RecordCommandLine.empty()) 804 EmitCommandLineMetadata(); 805 806 if (!getCodeGenOpts().StackProtectorGuard.empty()) 807 getModule().setStackProtectorGuard(getCodeGenOpts().StackProtectorGuard); 808 if (!getCodeGenOpts().StackProtectorGuardReg.empty()) 809 getModule().setStackProtectorGuardReg( 810 getCodeGenOpts().StackProtectorGuardReg); 811 if (getCodeGenOpts().StackProtectorGuardOffset != INT_MAX) 812 getModule().setStackProtectorGuardOffset( 813 getCodeGenOpts().StackProtectorGuardOffset); 814 if (getCodeGenOpts().StackAlignment) 815 getModule().setOverrideStackAlignment(getCodeGenOpts().StackAlignment); 816 817 getTargetCodeGenInfo().emitTargetMetadata(*this, MangledDeclNames); 818 819 EmitBackendOptionsMetadata(getCodeGenOpts()); 820 821 // Set visibility from DLL storage class 822 // We do this at the end of LLVM IR generation; after any operation 823 // that might affect the DLL storage class or the visibility, and 824 // before anything that might act on these. 825 setVisibilityFromDLLStorageClass(LangOpts, getModule()); 826 } 827 828 void CodeGenModule::EmitOpenCLMetadata() { 829 // SPIR v2.0 s2.13 - The OpenCL version used by the module is stored in the 830 // opencl.ocl.version named metadata node. 831 // C++ for OpenCL has a distinct mapping for versions compatibile with OpenCL. 832 auto Version = LangOpts.getOpenCLCompatibleVersion(); 833 llvm::Metadata *OCLVerElts[] = { 834 llvm::ConstantAsMetadata::get(llvm::ConstantInt::get( 835 Int32Ty, Version / 100)), 836 llvm::ConstantAsMetadata::get(llvm::ConstantInt::get( 837 Int32Ty, (Version % 100) / 10))}; 838 llvm::NamedMDNode *OCLVerMD = 839 TheModule.getOrInsertNamedMetadata("opencl.ocl.version"); 840 llvm::LLVMContext &Ctx = TheModule.getContext(); 841 OCLVerMD->addOperand(llvm::MDNode::get(Ctx, OCLVerElts)); 842 } 843 844 void CodeGenModule::EmitBackendOptionsMetadata( 845 const CodeGenOptions CodeGenOpts) { 846 switch (getTriple().getArch()) { 847 default: 848 break; 849 case llvm::Triple::riscv32: 850 case llvm::Triple::riscv64: 851 getModule().addModuleFlag(llvm::Module::Error, "SmallDataLimit", 852 CodeGenOpts.SmallDataLimit); 853 break; 854 } 855 } 856 857 void CodeGenModule::UpdateCompletedType(const TagDecl *TD) { 858 // Make sure that this type is translated. 859 Types.UpdateCompletedType(TD); 860 } 861 862 void CodeGenModule::RefreshTypeCacheForClass(const CXXRecordDecl *RD) { 863 // Make sure that this type is translated. 864 Types.RefreshTypeCacheForClass(RD); 865 } 866 867 llvm::MDNode *CodeGenModule::getTBAATypeInfo(QualType QTy) { 868 if (!TBAA) 869 return nullptr; 870 return TBAA->getTypeInfo(QTy); 871 } 872 873 TBAAAccessInfo CodeGenModule::getTBAAAccessInfo(QualType AccessType) { 874 if (!TBAA) 875 return TBAAAccessInfo(); 876 if (getLangOpts().CUDAIsDevice) { 877 // As CUDA builtin surface/texture types are replaced, skip generating TBAA 878 // access info. 879 if (AccessType->isCUDADeviceBuiltinSurfaceType()) { 880 if (getTargetCodeGenInfo().getCUDADeviceBuiltinSurfaceDeviceType() != 881 nullptr) 882 return TBAAAccessInfo(); 883 } else if (AccessType->isCUDADeviceBuiltinTextureType()) { 884 if (getTargetCodeGenInfo().getCUDADeviceBuiltinTextureDeviceType() != 885 nullptr) 886 return TBAAAccessInfo(); 887 } 888 } 889 return TBAA->getAccessInfo(AccessType); 890 } 891 892 TBAAAccessInfo 893 CodeGenModule::getTBAAVTablePtrAccessInfo(llvm::Type *VTablePtrType) { 894 if (!TBAA) 895 return TBAAAccessInfo(); 896 return TBAA->getVTablePtrAccessInfo(VTablePtrType); 897 } 898 899 llvm::MDNode *CodeGenModule::getTBAAStructInfo(QualType QTy) { 900 if (!TBAA) 901 return nullptr; 902 return TBAA->getTBAAStructInfo(QTy); 903 } 904 905 llvm::MDNode *CodeGenModule::getTBAABaseTypeInfo(QualType QTy) { 906 if (!TBAA) 907 return nullptr; 908 return TBAA->getBaseTypeInfo(QTy); 909 } 910 911 llvm::MDNode *CodeGenModule::getTBAAAccessTagInfo(TBAAAccessInfo Info) { 912 if (!TBAA) 913 return nullptr; 914 return TBAA->getAccessTagInfo(Info); 915 } 916 917 TBAAAccessInfo CodeGenModule::mergeTBAAInfoForCast(TBAAAccessInfo SourceInfo, 918 TBAAAccessInfo TargetInfo) { 919 if (!TBAA) 920 return TBAAAccessInfo(); 921 return TBAA->mergeTBAAInfoForCast(SourceInfo, TargetInfo); 922 } 923 924 TBAAAccessInfo 925 CodeGenModule::mergeTBAAInfoForConditionalOperator(TBAAAccessInfo InfoA, 926 TBAAAccessInfo InfoB) { 927 if (!TBAA) 928 return TBAAAccessInfo(); 929 return TBAA->mergeTBAAInfoForConditionalOperator(InfoA, InfoB); 930 } 931 932 TBAAAccessInfo 933 CodeGenModule::mergeTBAAInfoForMemoryTransfer(TBAAAccessInfo DestInfo, 934 TBAAAccessInfo SrcInfo) { 935 if (!TBAA) 936 return TBAAAccessInfo(); 937 return TBAA->mergeTBAAInfoForConditionalOperator(DestInfo, SrcInfo); 938 } 939 940 void CodeGenModule::DecorateInstructionWithTBAA(llvm::Instruction *Inst, 941 TBAAAccessInfo TBAAInfo) { 942 if (llvm::MDNode *Tag = getTBAAAccessTagInfo(TBAAInfo)) 943 Inst->setMetadata(llvm::LLVMContext::MD_tbaa, Tag); 944 } 945 946 void CodeGenModule::DecorateInstructionWithInvariantGroup( 947 llvm::Instruction *I, const CXXRecordDecl *RD) { 948 I->setMetadata(llvm::LLVMContext::MD_invariant_group, 949 llvm::MDNode::get(getLLVMContext(), {})); 950 } 951 952 void CodeGenModule::Error(SourceLocation loc, StringRef message) { 953 unsigned diagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error, "%0"); 954 getDiags().Report(Context.getFullLoc(loc), diagID) << message; 955 } 956 957 /// ErrorUnsupported - Print out an error that codegen doesn't support the 958 /// specified stmt yet. 959 void CodeGenModule::ErrorUnsupported(const Stmt *S, const char *Type) { 960 unsigned DiagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error, 961 "cannot compile this %0 yet"); 962 std::string Msg = Type; 963 getDiags().Report(Context.getFullLoc(S->getBeginLoc()), DiagID) 964 << Msg << S->getSourceRange(); 965 } 966 967 /// ErrorUnsupported - Print out an error that codegen doesn't support the 968 /// specified decl yet. 969 void CodeGenModule::ErrorUnsupported(const Decl *D, const char *Type) { 970 unsigned DiagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error, 971 "cannot compile this %0 yet"); 972 std::string Msg = Type; 973 getDiags().Report(Context.getFullLoc(D->getLocation()), DiagID) << Msg; 974 } 975 976 llvm::ConstantInt *CodeGenModule::getSize(CharUnits size) { 977 return llvm::ConstantInt::get(SizeTy, size.getQuantity()); 978 } 979 980 void CodeGenModule::setGlobalVisibility(llvm::GlobalValue *GV, 981 const NamedDecl *D) const { 982 if (GV->hasDLLImportStorageClass()) 983 return; 984 // Internal definitions always have default visibility. 985 if (GV->hasLocalLinkage()) { 986 GV->setVisibility(llvm::GlobalValue::DefaultVisibility); 987 return; 988 } 989 if (!D) 990 return; 991 // Set visibility for definitions, and for declarations if requested globally 992 // or set explicitly. 993 LinkageInfo LV = D->getLinkageAndVisibility(); 994 if (LV.isVisibilityExplicit() || getLangOpts().SetVisibilityForExternDecls || 995 !GV->isDeclarationForLinker()) 996 GV->setVisibility(GetLLVMVisibility(LV.getVisibility())); 997 } 998 999 static bool shouldAssumeDSOLocal(const CodeGenModule &CGM, 1000 llvm::GlobalValue *GV) { 1001 if (GV->hasLocalLinkage()) 1002 return true; 1003 1004 if (!GV->hasDefaultVisibility() && !GV->hasExternalWeakLinkage()) 1005 return true; 1006 1007 // DLLImport explicitly marks the GV as external. 1008 if (GV->hasDLLImportStorageClass()) 1009 return false; 1010 1011 const llvm::Triple &TT = CGM.getTriple(); 1012 if (TT.isWindowsGNUEnvironment()) { 1013 // In MinGW, variables without DLLImport can still be automatically 1014 // imported from a DLL by the linker; don't mark variables that 1015 // potentially could come from another DLL as DSO local. 1016 1017 // With EmulatedTLS, TLS variables can be autoimported from other DLLs 1018 // (and this actually happens in the public interface of libstdc++), so 1019 // such variables can't be marked as DSO local. (Native TLS variables 1020 // can't be dllimported at all, though.) 1021 if (GV->isDeclarationForLinker() && isa<llvm::GlobalVariable>(GV) && 1022 (!GV->isThreadLocal() || CGM.getCodeGenOpts().EmulatedTLS)) 1023 return false; 1024 } 1025 1026 // On COFF, don't mark 'extern_weak' symbols as DSO local. If these symbols 1027 // remain unresolved in the link, they can be resolved to zero, which is 1028 // outside the current DSO. 1029 if (TT.isOSBinFormatCOFF() && GV->hasExternalWeakLinkage()) 1030 return false; 1031 1032 // Every other GV is local on COFF. 1033 // Make an exception for windows OS in the triple: Some firmware builds use 1034 // *-win32-macho triples. This (accidentally?) produced windows relocations 1035 // without GOT tables in older clang versions; Keep this behaviour. 1036 // FIXME: even thread local variables? 1037 if (TT.isOSBinFormatCOFF() || (TT.isOSWindows() && TT.isOSBinFormatMachO())) 1038 return true; 1039 1040 // Only handle COFF and ELF for now. 1041 if (!TT.isOSBinFormatELF()) 1042 return false; 1043 1044 // If this is not an executable, don't assume anything is local. 1045 const auto &CGOpts = CGM.getCodeGenOpts(); 1046 llvm::Reloc::Model RM = CGOpts.RelocationModel; 1047 const auto &LOpts = CGM.getLangOpts(); 1048 if (RM != llvm::Reloc::Static && !LOpts.PIE) { 1049 // On ELF, if -fno-semantic-interposition is specified and the target 1050 // supports local aliases, there will be neither CC1 1051 // -fsemantic-interposition nor -fhalf-no-semantic-interposition. Set 1052 // dso_local on the function if using a local alias is preferable (can avoid 1053 // PLT indirection). 1054 if (!(isa<llvm::Function>(GV) && GV->canBenefitFromLocalAlias())) 1055 return false; 1056 return !(CGM.getLangOpts().SemanticInterposition || 1057 CGM.getLangOpts().HalfNoSemanticInterposition); 1058 } 1059 1060 // A definition cannot be preempted from an executable. 1061 if (!GV->isDeclarationForLinker()) 1062 return true; 1063 1064 // Most PIC code sequences that assume that a symbol is local cannot produce a 1065 // 0 if it turns out the symbol is undefined. While this is ABI and relocation 1066 // depended, it seems worth it to handle it here. 1067 if (RM == llvm::Reloc::PIC_ && GV->hasExternalWeakLinkage()) 1068 return false; 1069 1070 // PowerPC64 prefers TOC indirection to avoid copy relocations. 1071 if (TT.isPPC64()) 1072 return false; 1073 1074 if (CGOpts.DirectAccessExternalData) { 1075 // If -fdirect-access-external-data (default for -fno-pic), set dso_local 1076 // for non-thread-local variables. If the symbol is not defined in the 1077 // executable, a copy relocation will be needed at link time. dso_local is 1078 // excluded for thread-local variables because they generally don't support 1079 // copy relocations. 1080 if (auto *Var = dyn_cast<llvm::GlobalVariable>(GV)) 1081 if (!Var->isThreadLocal()) 1082 return true; 1083 1084 // -fno-pic sets dso_local on a function declaration to allow direct 1085 // accesses when taking its address (similar to a data symbol). If the 1086 // function is not defined in the executable, a canonical PLT entry will be 1087 // needed at link time. -fno-direct-access-external-data can avoid the 1088 // canonical PLT entry. We don't generalize this condition to -fpie/-fpic as 1089 // it could just cause trouble without providing perceptible benefits. 1090 if (isa<llvm::Function>(GV) && !CGOpts.NoPLT && RM == llvm::Reloc::Static) 1091 return true; 1092 } 1093 1094 // If we can use copy relocations we can assume it is local. 1095 1096 // Otherwise don't assume it is local. 1097 return false; 1098 } 1099 1100 void CodeGenModule::setDSOLocal(llvm::GlobalValue *GV) const { 1101 GV->setDSOLocal(shouldAssumeDSOLocal(*this, GV)); 1102 } 1103 1104 void CodeGenModule::setDLLImportDLLExport(llvm::GlobalValue *GV, 1105 GlobalDecl GD) const { 1106 const auto *D = dyn_cast<NamedDecl>(GD.getDecl()); 1107 // C++ destructors have a few C++ ABI specific special cases. 1108 if (const auto *Dtor = dyn_cast_or_null<CXXDestructorDecl>(D)) { 1109 getCXXABI().setCXXDestructorDLLStorage(GV, Dtor, GD.getDtorType()); 1110 return; 1111 } 1112 setDLLImportDLLExport(GV, D); 1113 } 1114 1115 void CodeGenModule::setDLLImportDLLExport(llvm::GlobalValue *GV, 1116 const NamedDecl *D) const { 1117 if (D && D->isExternallyVisible()) { 1118 if (D->hasAttr<DLLImportAttr>()) 1119 GV->setDLLStorageClass(llvm::GlobalVariable::DLLImportStorageClass); 1120 else if (D->hasAttr<DLLExportAttr>() && !GV->isDeclarationForLinker()) 1121 GV->setDLLStorageClass(llvm::GlobalVariable::DLLExportStorageClass); 1122 } 1123 } 1124 1125 void CodeGenModule::setGVProperties(llvm::GlobalValue *GV, 1126 GlobalDecl GD) const { 1127 setDLLImportDLLExport(GV, GD); 1128 setGVPropertiesAux(GV, dyn_cast<NamedDecl>(GD.getDecl())); 1129 } 1130 1131 void CodeGenModule::setGVProperties(llvm::GlobalValue *GV, 1132 const NamedDecl *D) const { 1133 setDLLImportDLLExport(GV, D); 1134 setGVPropertiesAux(GV, D); 1135 } 1136 1137 void CodeGenModule::setGVPropertiesAux(llvm::GlobalValue *GV, 1138 const NamedDecl *D) const { 1139 setGlobalVisibility(GV, D); 1140 setDSOLocal(GV); 1141 GV->setPartition(CodeGenOpts.SymbolPartition); 1142 } 1143 1144 static llvm::GlobalVariable::ThreadLocalMode GetLLVMTLSModel(StringRef S) { 1145 return llvm::StringSwitch<llvm::GlobalVariable::ThreadLocalMode>(S) 1146 .Case("global-dynamic", llvm::GlobalVariable::GeneralDynamicTLSModel) 1147 .Case("local-dynamic", llvm::GlobalVariable::LocalDynamicTLSModel) 1148 .Case("initial-exec", llvm::GlobalVariable::InitialExecTLSModel) 1149 .Case("local-exec", llvm::GlobalVariable::LocalExecTLSModel); 1150 } 1151 1152 llvm::GlobalVariable::ThreadLocalMode 1153 CodeGenModule::GetDefaultLLVMTLSModel() const { 1154 switch (CodeGenOpts.getDefaultTLSModel()) { 1155 case CodeGenOptions::GeneralDynamicTLSModel: 1156 return llvm::GlobalVariable::GeneralDynamicTLSModel; 1157 case CodeGenOptions::LocalDynamicTLSModel: 1158 return llvm::GlobalVariable::LocalDynamicTLSModel; 1159 case CodeGenOptions::InitialExecTLSModel: 1160 return llvm::GlobalVariable::InitialExecTLSModel; 1161 case CodeGenOptions::LocalExecTLSModel: 1162 return llvm::GlobalVariable::LocalExecTLSModel; 1163 } 1164 llvm_unreachable("Invalid TLS model!"); 1165 } 1166 1167 void CodeGenModule::setTLSMode(llvm::GlobalValue *GV, const VarDecl &D) const { 1168 assert(D.getTLSKind() && "setting TLS mode on non-TLS var!"); 1169 1170 llvm::GlobalValue::ThreadLocalMode TLM; 1171 TLM = GetDefaultLLVMTLSModel(); 1172 1173 // Override the TLS model if it is explicitly specified. 1174 if (const TLSModelAttr *Attr = D.getAttr<TLSModelAttr>()) { 1175 TLM = GetLLVMTLSModel(Attr->getModel()); 1176 } 1177 1178 GV->setThreadLocalMode(TLM); 1179 } 1180 1181 static std::string getCPUSpecificMangling(const CodeGenModule &CGM, 1182 StringRef Name) { 1183 const TargetInfo &Target = CGM.getTarget(); 1184 return (Twine('.') + Twine(Target.CPUSpecificManglingCharacter(Name))).str(); 1185 } 1186 1187 static void AppendCPUSpecificCPUDispatchMangling(const CodeGenModule &CGM, 1188 const CPUSpecificAttr *Attr, 1189 unsigned CPUIndex, 1190 raw_ostream &Out) { 1191 // cpu_specific gets the current name, dispatch gets the resolver if IFunc is 1192 // supported. 1193 if (Attr) 1194 Out << getCPUSpecificMangling(CGM, Attr->getCPUName(CPUIndex)->getName()); 1195 else if (CGM.getTarget().supportsIFunc()) 1196 Out << ".resolver"; 1197 } 1198 1199 static void AppendTargetMangling(const CodeGenModule &CGM, 1200 const TargetAttr *Attr, raw_ostream &Out) { 1201 if (Attr->isDefaultVersion()) 1202 return; 1203 1204 Out << '.'; 1205 const TargetInfo &Target = CGM.getTarget(); 1206 ParsedTargetAttr Info = 1207 Attr->parse([&Target](StringRef LHS, StringRef RHS) { 1208 // Multiversioning doesn't allow "no-${feature}", so we can 1209 // only have "+" prefixes here. 1210 assert(LHS.startswith("+") && RHS.startswith("+") && 1211 "Features should always have a prefix."); 1212 return Target.multiVersionSortPriority(LHS.substr(1)) > 1213 Target.multiVersionSortPriority(RHS.substr(1)); 1214 }); 1215 1216 bool IsFirst = true; 1217 1218 if (!Info.Architecture.empty()) { 1219 IsFirst = false; 1220 Out << "arch_" << Info.Architecture; 1221 } 1222 1223 for (StringRef Feat : Info.Features) { 1224 if (!IsFirst) 1225 Out << '_'; 1226 IsFirst = false; 1227 Out << Feat.substr(1); 1228 } 1229 } 1230 1231 // Returns true if GD is a function decl with internal linkage and 1232 // needs a unique suffix after the mangled name. 1233 static bool isUniqueInternalLinkageDecl(GlobalDecl GD, 1234 CodeGenModule &CGM) { 1235 const Decl *D = GD.getDecl(); 1236 return !CGM.getModuleNameHash().empty() && isa<FunctionDecl>(D) && 1237 (CGM.getFunctionLinkage(GD) == llvm::GlobalValue::InternalLinkage); 1238 } 1239 1240 static std::string getMangledNameImpl(CodeGenModule &CGM, GlobalDecl GD, 1241 const NamedDecl *ND, 1242 bool OmitMultiVersionMangling = false) { 1243 SmallString<256> Buffer; 1244 llvm::raw_svector_ostream Out(Buffer); 1245 MangleContext &MC = CGM.getCXXABI().getMangleContext(); 1246 if (!CGM.getModuleNameHash().empty()) 1247 MC.needsUniqueInternalLinkageNames(); 1248 bool ShouldMangle = MC.shouldMangleDeclName(ND); 1249 if (ShouldMangle) 1250 MC.mangleName(GD.getWithDecl(ND), Out); 1251 else { 1252 IdentifierInfo *II = ND->getIdentifier(); 1253 assert(II && "Attempt to mangle unnamed decl."); 1254 const auto *FD = dyn_cast<FunctionDecl>(ND); 1255 1256 if (FD && 1257 FD->getType()->castAs<FunctionType>()->getCallConv() == CC_X86RegCall) { 1258 Out << "__regcall3__" << II->getName(); 1259 } else if (FD && FD->hasAttr<CUDAGlobalAttr>() && 1260 GD.getKernelReferenceKind() == KernelReferenceKind::Stub) { 1261 Out << "__device_stub__" << II->getName(); 1262 } else { 1263 Out << II->getName(); 1264 } 1265 } 1266 1267 // Check if the module name hash should be appended for internal linkage 1268 // symbols. This should come before multi-version target suffixes are 1269 // appended. This is to keep the name and module hash suffix of the 1270 // internal linkage function together. The unique suffix should only be 1271 // added when name mangling is done to make sure that the final name can 1272 // be properly demangled. For example, for C functions without prototypes, 1273 // name mangling is not done and the unique suffix should not be appeneded 1274 // then. 1275 if (ShouldMangle && isUniqueInternalLinkageDecl(GD, CGM)) { 1276 assert(CGM.getCodeGenOpts().UniqueInternalLinkageNames && 1277 "Hash computed when not explicitly requested"); 1278 Out << CGM.getModuleNameHash(); 1279 } 1280 1281 if (const auto *FD = dyn_cast<FunctionDecl>(ND)) 1282 if (FD->isMultiVersion() && !OmitMultiVersionMangling) { 1283 switch (FD->getMultiVersionKind()) { 1284 case MultiVersionKind::CPUDispatch: 1285 case MultiVersionKind::CPUSpecific: 1286 AppendCPUSpecificCPUDispatchMangling(CGM, 1287 FD->getAttr<CPUSpecificAttr>(), 1288 GD.getMultiVersionIndex(), Out); 1289 break; 1290 case MultiVersionKind::Target: 1291 AppendTargetMangling(CGM, FD->getAttr<TargetAttr>(), Out); 1292 break; 1293 case MultiVersionKind::None: 1294 llvm_unreachable("None multiversion type isn't valid here"); 1295 } 1296 } 1297 1298 // Make unique name for device side static file-scope variable for HIP. 1299 if (CGM.getContext().shouldExternalizeStaticVar(ND) && 1300 CGM.getLangOpts().GPURelocatableDeviceCode && 1301 CGM.getLangOpts().CUDAIsDevice && !CGM.getLangOpts().CUID.empty()) 1302 CGM.printPostfixForExternalizedStaticVar(Out); 1303 return std::string(Out.str()); 1304 } 1305 1306 void CodeGenModule::UpdateMultiVersionNames(GlobalDecl GD, 1307 const FunctionDecl *FD) { 1308 if (!FD->isMultiVersion()) 1309 return; 1310 1311 // Get the name of what this would be without the 'target' attribute. This 1312 // allows us to lookup the version that was emitted when this wasn't a 1313 // multiversion function. 1314 std::string NonTargetName = 1315 getMangledNameImpl(*this, GD, FD, /*OmitMultiVersionMangling=*/true); 1316 GlobalDecl OtherGD; 1317 if (lookupRepresentativeDecl(NonTargetName, OtherGD)) { 1318 assert(OtherGD.getCanonicalDecl() 1319 .getDecl() 1320 ->getAsFunction() 1321 ->isMultiVersion() && 1322 "Other GD should now be a multiversioned function"); 1323 // OtherFD is the version of this function that was mangled BEFORE 1324 // becoming a MultiVersion function. It potentially needs to be updated. 1325 const FunctionDecl *OtherFD = OtherGD.getCanonicalDecl() 1326 .getDecl() 1327 ->getAsFunction() 1328 ->getMostRecentDecl(); 1329 std::string OtherName = getMangledNameImpl(*this, OtherGD, OtherFD); 1330 // This is so that if the initial version was already the 'default' 1331 // version, we don't try to update it. 1332 if (OtherName != NonTargetName) { 1333 // Remove instead of erase, since others may have stored the StringRef 1334 // to this. 1335 const auto ExistingRecord = Manglings.find(NonTargetName); 1336 if (ExistingRecord != std::end(Manglings)) 1337 Manglings.remove(&(*ExistingRecord)); 1338 auto Result = Manglings.insert(std::make_pair(OtherName, OtherGD)); 1339 MangledDeclNames[OtherGD.getCanonicalDecl()] = Result.first->first(); 1340 if (llvm::GlobalValue *Entry = GetGlobalValue(NonTargetName)) 1341 Entry->setName(OtherName); 1342 } 1343 } 1344 } 1345 1346 StringRef CodeGenModule::getMangledName(GlobalDecl GD) { 1347 GlobalDecl CanonicalGD = GD.getCanonicalDecl(); 1348 1349 // Some ABIs don't have constructor variants. Make sure that base and 1350 // complete constructors get mangled the same. 1351 if (const auto *CD = dyn_cast<CXXConstructorDecl>(CanonicalGD.getDecl())) { 1352 if (!getTarget().getCXXABI().hasConstructorVariants()) { 1353 CXXCtorType OrigCtorType = GD.getCtorType(); 1354 assert(OrigCtorType == Ctor_Base || OrigCtorType == Ctor_Complete); 1355 if (OrigCtorType == Ctor_Base) 1356 CanonicalGD = GlobalDecl(CD, Ctor_Complete); 1357 } 1358 } 1359 1360 // In CUDA/HIP device compilation with -fgpu-rdc, the mangled name of a 1361 // static device variable depends on whether the variable is referenced by 1362 // a host or device host function. Therefore the mangled name cannot be 1363 // cached. 1364 if (!LangOpts.CUDAIsDevice || 1365 !getContext().mayExternalizeStaticVar(GD.getDecl())) { 1366 auto FoundName = MangledDeclNames.find(CanonicalGD); 1367 if (FoundName != MangledDeclNames.end()) 1368 return FoundName->second; 1369 } 1370 1371 // Keep the first result in the case of a mangling collision. 1372 const auto *ND = cast<NamedDecl>(GD.getDecl()); 1373 std::string MangledName = getMangledNameImpl(*this, GD, ND); 1374 1375 // Ensure either we have different ABIs between host and device compilations, 1376 // says host compilation following MSVC ABI but device compilation follows 1377 // Itanium C++ ABI or, if they follow the same ABI, kernel names after 1378 // mangling should be the same after name stubbing. The later checking is 1379 // very important as the device kernel name being mangled in host-compilation 1380 // is used to resolve the device binaries to be executed. Inconsistent naming 1381 // result in undefined behavior. Even though we cannot check that naming 1382 // directly between host- and device-compilations, the host- and 1383 // device-mangling in host compilation could help catching certain ones. 1384 assert(!isa<FunctionDecl>(ND) || !ND->hasAttr<CUDAGlobalAttr>() || 1385 getLangOpts().CUDAIsDevice || 1386 (getContext().getAuxTargetInfo() && 1387 (getContext().getAuxTargetInfo()->getCXXABI() != 1388 getContext().getTargetInfo().getCXXABI())) || 1389 getCUDARuntime().getDeviceSideName(ND) == 1390 getMangledNameImpl( 1391 *this, 1392 GD.getWithKernelReferenceKind(KernelReferenceKind::Kernel), 1393 ND)); 1394 1395 auto Result = Manglings.insert(std::make_pair(MangledName, GD)); 1396 return MangledDeclNames[CanonicalGD] = Result.first->first(); 1397 } 1398 1399 StringRef CodeGenModule::getBlockMangledName(GlobalDecl GD, 1400 const BlockDecl *BD) { 1401 MangleContext &MangleCtx = getCXXABI().getMangleContext(); 1402 const Decl *D = GD.getDecl(); 1403 1404 SmallString<256> Buffer; 1405 llvm::raw_svector_ostream Out(Buffer); 1406 if (!D) 1407 MangleCtx.mangleGlobalBlock(BD, 1408 dyn_cast_or_null<VarDecl>(initializedGlobalDecl.getDecl()), Out); 1409 else if (const auto *CD = dyn_cast<CXXConstructorDecl>(D)) 1410 MangleCtx.mangleCtorBlock(CD, GD.getCtorType(), BD, Out); 1411 else if (const auto *DD = dyn_cast<CXXDestructorDecl>(D)) 1412 MangleCtx.mangleDtorBlock(DD, GD.getDtorType(), BD, Out); 1413 else 1414 MangleCtx.mangleBlock(cast<DeclContext>(D), BD, Out); 1415 1416 auto Result = Manglings.insert(std::make_pair(Out.str(), BD)); 1417 return Result.first->first(); 1418 } 1419 1420 llvm::GlobalValue *CodeGenModule::GetGlobalValue(StringRef Name) { 1421 return getModule().getNamedValue(Name); 1422 } 1423 1424 /// AddGlobalCtor - Add a function to the list that will be called before 1425 /// main() runs. 1426 void CodeGenModule::AddGlobalCtor(llvm::Function *Ctor, int Priority, 1427 llvm::Constant *AssociatedData) { 1428 // FIXME: Type coercion of void()* types. 1429 GlobalCtors.push_back(Structor(Priority, Ctor, AssociatedData)); 1430 } 1431 1432 /// AddGlobalDtor - Add a function to the list that will be called 1433 /// when the module is unloaded. 1434 void CodeGenModule::AddGlobalDtor(llvm::Function *Dtor, int Priority, 1435 bool IsDtorAttrFunc) { 1436 if (CodeGenOpts.RegisterGlobalDtorsWithAtExit && 1437 (!getContext().getTargetInfo().getTriple().isOSAIX() || IsDtorAttrFunc)) { 1438 DtorsUsingAtExit[Priority].push_back(Dtor); 1439 return; 1440 } 1441 1442 // FIXME: Type coercion of void()* types. 1443 GlobalDtors.push_back(Structor(Priority, Dtor, nullptr)); 1444 } 1445 1446 void CodeGenModule::EmitCtorList(CtorList &Fns, const char *GlobalName) { 1447 if (Fns.empty()) return; 1448 1449 // Ctor function type is void()*. 1450 llvm::FunctionType* CtorFTy = llvm::FunctionType::get(VoidTy, false); 1451 llvm::Type *CtorPFTy = llvm::PointerType::get(CtorFTy, 1452 TheModule.getDataLayout().getProgramAddressSpace()); 1453 1454 // Get the type of a ctor entry, { i32, void ()*, i8* }. 1455 llvm::StructType *CtorStructTy = llvm::StructType::get( 1456 Int32Ty, CtorPFTy, VoidPtrTy); 1457 1458 // Construct the constructor and destructor arrays. 1459 ConstantInitBuilder builder(*this); 1460 auto ctors = builder.beginArray(CtorStructTy); 1461 for (const auto &I : Fns) { 1462 auto ctor = ctors.beginStruct(CtorStructTy); 1463 ctor.addInt(Int32Ty, I.Priority); 1464 ctor.add(llvm::ConstantExpr::getBitCast(I.Initializer, CtorPFTy)); 1465 if (I.AssociatedData) 1466 ctor.add(llvm::ConstantExpr::getBitCast(I.AssociatedData, VoidPtrTy)); 1467 else 1468 ctor.addNullPointer(VoidPtrTy); 1469 ctor.finishAndAddTo(ctors); 1470 } 1471 1472 auto list = 1473 ctors.finishAndCreateGlobal(GlobalName, getPointerAlign(), 1474 /*constant*/ false, 1475 llvm::GlobalValue::AppendingLinkage); 1476 1477 // The LTO linker doesn't seem to like it when we set an alignment 1478 // on appending variables. Take it off as a workaround. 1479 list->setAlignment(llvm::None); 1480 1481 Fns.clear(); 1482 } 1483 1484 llvm::GlobalValue::LinkageTypes 1485 CodeGenModule::getFunctionLinkage(GlobalDecl GD) { 1486 const auto *D = cast<FunctionDecl>(GD.getDecl()); 1487 1488 GVALinkage Linkage = getContext().GetGVALinkageForFunction(D); 1489 1490 if (const auto *Dtor = dyn_cast<CXXDestructorDecl>(D)) 1491 return getCXXABI().getCXXDestructorLinkage(Linkage, Dtor, GD.getDtorType()); 1492 1493 if (isa<CXXConstructorDecl>(D) && 1494 cast<CXXConstructorDecl>(D)->isInheritingConstructor() && 1495 Context.getTargetInfo().getCXXABI().isMicrosoft()) { 1496 // Our approach to inheriting constructors is fundamentally different from 1497 // that used by the MS ABI, so keep our inheriting constructor thunks 1498 // internal rather than trying to pick an unambiguous mangling for them. 1499 return llvm::GlobalValue::InternalLinkage; 1500 } 1501 1502 return getLLVMLinkageForDeclarator(D, Linkage, /*IsConstantVariable=*/false); 1503 } 1504 1505 llvm::ConstantInt *CodeGenModule::CreateCrossDsoCfiTypeId(llvm::Metadata *MD) { 1506 llvm::MDString *MDS = dyn_cast<llvm::MDString>(MD); 1507 if (!MDS) return nullptr; 1508 1509 return llvm::ConstantInt::get(Int64Ty, llvm::MD5Hash(MDS->getString())); 1510 } 1511 1512 void CodeGenModule::SetLLVMFunctionAttributes(GlobalDecl GD, 1513 const CGFunctionInfo &Info, 1514 llvm::Function *F, bool IsThunk) { 1515 unsigned CallingConv; 1516 llvm::AttributeList PAL; 1517 ConstructAttributeList(F->getName(), Info, GD, PAL, CallingConv, 1518 /*AttrOnCallSite=*/false, IsThunk); 1519 F->setAttributes(PAL); 1520 F->setCallingConv(static_cast<llvm::CallingConv::ID>(CallingConv)); 1521 } 1522 1523 static void removeImageAccessQualifier(std::string& TyName) { 1524 std::string ReadOnlyQual("__read_only"); 1525 std::string::size_type ReadOnlyPos = TyName.find(ReadOnlyQual); 1526 if (ReadOnlyPos != std::string::npos) 1527 // "+ 1" for the space after access qualifier. 1528 TyName.erase(ReadOnlyPos, ReadOnlyQual.size() + 1); 1529 else { 1530 std::string WriteOnlyQual("__write_only"); 1531 std::string::size_type WriteOnlyPos = TyName.find(WriteOnlyQual); 1532 if (WriteOnlyPos != std::string::npos) 1533 TyName.erase(WriteOnlyPos, WriteOnlyQual.size() + 1); 1534 else { 1535 std::string ReadWriteQual("__read_write"); 1536 std::string::size_type ReadWritePos = TyName.find(ReadWriteQual); 1537 if (ReadWritePos != std::string::npos) 1538 TyName.erase(ReadWritePos, ReadWriteQual.size() + 1); 1539 } 1540 } 1541 } 1542 1543 // Returns the address space id that should be produced to the 1544 // kernel_arg_addr_space metadata. This is always fixed to the ids 1545 // as specified in the SPIR 2.0 specification in order to differentiate 1546 // for example in clGetKernelArgInfo() implementation between the address 1547 // spaces with targets without unique mapping to the OpenCL address spaces 1548 // (basically all single AS CPUs). 1549 static unsigned ArgInfoAddressSpace(LangAS AS) { 1550 switch (AS) { 1551 case LangAS::opencl_global: 1552 return 1; 1553 case LangAS::opencl_constant: 1554 return 2; 1555 case LangAS::opencl_local: 1556 return 3; 1557 case LangAS::opencl_generic: 1558 return 4; // Not in SPIR 2.0 specs. 1559 case LangAS::opencl_global_device: 1560 return 5; 1561 case LangAS::opencl_global_host: 1562 return 6; 1563 default: 1564 return 0; // Assume private. 1565 } 1566 } 1567 1568 void CodeGenModule::GenOpenCLArgMetadata(llvm::Function *Fn, 1569 const FunctionDecl *FD, 1570 CodeGenFunction *CGF) { 1571 assert(((FD && CGF) || (!FD && !CGF)) && 1572 "Incorrect use - FD and CGF should either be both null or not!"); 1573 // Create MDNodes that represent the kernel arg metadata. 1574 // Each MDNode is a list in the form of "key", N number of values which is 1575 // the same number of values as their are kernel arguments. 1576 1577 const PrintingPolicy &Policy = Context.getPrintingPolicy(); 1578 1579 // MDNode for the kernel argument address space qualifiers. 1580 SmallVector<llvm::Metadata *, 8> addressQuals; 1581 1582 // MDNode for the kernel argument access qualifiers (images only). 1583 SmallVector<llvm::Metadata *, 8> accessQuals; 1584 1585 // MDNode for the kernel argument type names. 1586 SmallVector<llvm::Metadata *, 8> argTypeNames; 1587 1588 // MDNode for the kernel argument base type names. 1589 SmallVector<llvm::Metadata *, 8> argBaseTypeNames; 1590 1591 // MDNode for the kernel argument type qualifiers. 1592 SmallVector<llvm::Metadata *, 8> argTypeQuals; 1593 1594 // MDNode for the kernel argument names. 1595 SmallVector<llvm::Metadata *, 8> argNames; 1596 1597 if (FD && CGF) 1598 for (unsigned i = 0, e = FD->getNumParams(); i != e; ++i) { 1599 const ParmVarDecl *parm = FD->getParamDecl(i); 1600 QualType ty = parm->getType(); 1601 std::string typeQuals; 1602 1603 // Get image and pipe access qualifier: 1604 if (ty->isImageType() || ty->isPipeType()) { 1605 const Decl *PDecl = parm; 1606 if (auto *TD = dyn_cast<TypedefType>(ty)) 1607 PDecl = TD->getDecl(); 1608 const OpenCLAccessAttr *A = PDecl->getAttr<OpenCLAccessAttr>(); 1609 if (A && A->isWriteOnly()) 1610 accessQuals.push_back(llvm::MDString::get(VMContext, "write_only")); 1611 else if (A && A->isReadWrite()) 1612 accessQuals.push_back(llvm::MDString::get(VMContext, "read_write")); 1613 else 1614 accessQuals.push_back(llvm::MDString::get(VMContext, "read_only")); 1615 } else 1616 accessQuals.push_back(llvm::MDString::get(VMContext, "none")); 1617 1618 // Get argument name. 1619 argNames.push_back(llvm::MDString::get(VMContext, parm->getName())); 1620 1621 auto getTypeSpelling = [&](QualType Ty) { 1622 auto typeName = Ty.getUnqualifiedType().getAsString(Policy); 1623 1624 if (Ty.isCanonical()) { 1625 StringRef typeNameRef = typeName; 1626 // Turn "unsigned type" to "utype" 1627 if (typeNameRef.consume_front("unsigned ")) 1628 return std::string("u") + typeNameRef.str(); 1629 if (typeNameRef.consume_front("signed ")) 1630 return typeNameRef.str(); 1631 } 1632 1633 return typeName; 1634 }; 1635 1636 if (ty->isPointerType()) { 1637 QualType pointeeTy = ty->getPointeeType(); 1638 1639 // Get address qualifier. 1640 addressQuals.push_back( 1641 llvm::ConstantAsMetadata::get(CGF->Builder.getInt32( 1642 ArgInfoAddressSpace(pointeeTy.getAddressSpace())))); 1643 1644 // Get argument type name. 1645 std::string typeName = getTypeSpelling(pointeeTy) + "*"; 1646 std::string baseTypeName = 1647 getTypeSpelling(pointeeTy.getCanonicalType()) + "*"; 1648 argTypeNames.push_back(llvm::MDString::get(VMContext, typeName)); 1649 argBaseTypeNames.push_back( 1650 llvm::MDString::get(VMContext, baseTypeName)); 1651 1652 // Get argument type qualifiers: 1653 if (ty.isRestrictQualified()) 1654 typeQuals = "restrict"; 1655 if (pointeeTy.isConstQualified() || 1656 (pointeeTy.getAddressSpace() == LangAS::opencl_constant)) 1657 typeQuals += typeQuals.empty() ? "const" : " const"; 1658 if (pointeeTy.isVolatileQualified()) 1659 typeQuals += typeQuals.empty() ? "volatile" : " volatile"; 1660 } else { 1661 uint32_t AddrSpc = 0; 1662 bool isPipe = ty->isPipeType(); 1663 if (ty->isImageType() || isPipe) 1664 AddrSpc = ArgInfoAddressSpace(LangAS::opencl_global); 1665 1666 addressQuals.push_back( 1667 llvm::ConstantAsMetadata::get(CGF->Builder.getInt32(AddrSpc))); 1668 1669 // Get argument type name. 1670 ty = isPipe ? ty->castAs<PipeType>()->getElementType() : ty; 1671 std::string typeName = getTypeSpelling(ty); 1672 std::string baseTypeName = getTypeSpelling(ty.getCanonicalType()); 1673 1674 // Remove access qualifiers on images 1675 // (as they are inseparable from type in clang implementation, 1676 // but OpenCL spec provides a special query to get access qualifier 1677 // via clGetKernelArgInfo with CL_KERNEL_ARG_ACCESS_QUALIFIER): 1678 if (ty->isImageType()) { 1679 removeImageAccessQualifier(typeName); 1680 removeImageAccessQualifier(baseTypeName); 1681 } 1682 1683 argTypeNames.push_back(llvm::MDString::get(VMContext, typeName)); 1684 argBaseTypeNames.push_back( 1685 llvm::MDString::get(VMContext, baseTypeName)); 1686 1687 if (isPipe) 1688 typeQuals = "pipe"; 1689 } 1690 argTypeQuals.push_back(llvm::MDString::get(VMContext, typeQuals)); 1691 } 1692 1693 Fn->setMetadata("kernel_arg_addr_space", 1694 llvm::MDNode::get(VMContext, addressQuals)); 1695 Fn->setMetadata("kernel_arg_access_qual", 1696 llvm::MDNode::get(VMContext, accessQuals)); 1697 Fn->setMetadata("kernel_arg_type", 1698 llvm::MDNode::get(VMContext, argTypeNames)); 1699 Fn->setMetadata("kernel_arg_base_type", 1700 llvm::MDNode::get(VMContext, argBaseTypeNames)); 1701 Fn->setMetadata("kernel_arg_type_qual", 1702 llvm::MDNode::get(VMContext, argTypeQuals)); 1703 if (getCodeGenOpts().EmitOpenCLArgMetadata) 1704 Fn->setMetadata("kernel_arg_name", 1705 llvm::MDNode::get(VMContext, argNames)); 1706 } 1707 1708 /// Determines whether the language options require us to model 1709 /// unwind exceptions. We treat -fexceptions as mandating this 1710 /// except under the fragile ObjC ABI with only ObjC exceptions 1711 /// enabled. This means, for example, that C with -fexceptions 1712 /// enables this. 1713 static bool hasUnwindExceptions(const LangOptions &LangOpts) { 1714 // If exceptions are completely disabled, obviously this is false. 1715 if (!LangOpts.Exceptions) return false; 1716 1717 // If C++ exceptions are enabled, this is true. 1718 if (LangOpts.CXXExceptions) return true; 1719 1720 // If ObjC exceptions are enabled, this depends on the ABI. 1721 if (LangOpts.ObjCExceptions) { 1722 return LangOpts.ObjCRuntime.hasUnwindExceptions(); 1723 } 1724 1725 return true; 1726 } 1727 1728 static bool requiresMemberFunctionPointerTypeMetadata(CodeGenModule &CGM, 1729 const CXXMethodDecl *MD) { 1730 // Check that the type metadata can ever actually be used by a call. 1731 if (!CGM.getCodeGenOpts().LTOUnit || 1732 !CGM.HasHiddenLTOVisibility(MD->getParent())) 1733 return false; 1734 1735 // Only functions whose address can be taken with a member function pointer 1736 // need this sort of type metadata. 1737 return !MD->isStatic() && !MD->isVirtual() && !isa<CXXConstructorDecl>(MD) && 1738 !isa<CXXDestructorDecl>(MD); 1739 } 1740 1741 std::vector<const CXXRecordDecl *> 1742 CodeGenModule::getMostBaseClasses(const CXXRecordDecl *RD) { 1743 llvm::SetVector<const CXXRecordDecl *> MostBases; 1744 1745 std::function<void (const CXXRecordDecl *)> CollectMostBases; 1746 CollectMostBases = [&](const CXXRecordDecl *RD) { 1747 if (RD->getNumBases() == 0) 1748 MostBases.insert(RD); 1749 for (const CXXBaseSpecifier &B : RD->bases()) 1750 CollectMostBases(B.getType()->getAsCXXRecordDecl()); 1751 }; 1752 CollectMostBases(RD); 1753 return MostBases.takeVector(); 1754 } 1755 1756 void CodeGenModule::SetLLVMFunctionAttributesForDefinition(const Decl *D, 1757 llvm::Function *F) { 1758 llvm::AttrBuilder B; 1759 1760 if (CodeGenOpts.UnwindTables) 1761 B.addAttribute(llvm::Attribute::UWTable); 1762 1763 if (CodeGenOpts.StackClashProtector) 1764 B.addAttribute("probe-stack", "inline-asm"); 1765 1766 if (!hasUnwindExceptions(LangOpts)) 1767 B.addAttribute(llvm::Attribute::NoUnwind); 1768 1769 if (!D || !D->hasAttr<NoStackProtectorAttr>()) { 1770 if (LangOpts.getStackProtector() == LangOptions::SSPOn) 1771 B.addAttribute(llvm::Attribute::StackProtect); 1772 else if (LangOpts.getStackProtector() == LangOptions::SSPStrong) 1773 B.addAttribute(llvm::Attribute::StackProtectStrong); 1774 else if (LangOpts.getStackProtector() == LangOptions::SSPReq) 1775 B.addAttribute(llvm::Attribute::StackProtectReq); 1776 } 1777 1778 if (!D) { 1779 // If we don't have a declaration to control inlining, the function isn't 1780 // explicitly marked as alwaysinline for semantic reasons, and inlining is 1781 // disabled, mark the function as noinline. 1782 if (!F->hasFnAttribute(llvm::Attribute::AlwaysInline) && 1783 CodeGenOpts.getInlining() == CodeGenOptions::OnlyAlwaysInlining) 1784 B.addAttribute(llvm::Attribute::NoInline); 1785 1786 F->addFnAttrs(B); 1787 return; 1788 } 1789 1790 // Track whether we need to add the optnone LLVM attribute, 1791 // starting with the default for this optimization level. 1792 bool ShouldAddOptNone = 1793 !CodeGenOpts.DisableO0ImplyOptNone && CodeGenOpts.OptimizationLevel == 0; 1794 // We can't add optnone in the following cases, it won't pass the verifier. 1795 ShouldAddOptNone &= !D->hasAttr<MinSizeAttr>(); 1796 ShouldAddOptNone &= !D->hasAttr<AlwaysInlineAttr>(); 1797 1798 // Add optnone, but do so only if the function isn't always_inline. 1799 if ((ShouldAddOptNone || D->hasAttr<OptimizeNoneAttr>()) && 1800 !F->hasFnAttribute(llvm::Attribute::AlwaysInline)) { 1801 B.addAttribute(llvm::Attribute::OptimizeNone); 1802 1803 // OptimizeNone implies noinline; we should not be inlining such functions. 1804 B.addAttribute(llvm::Attribute::NoInline); 1805 1806 // We still need to handle naked functions even though optnone subsumes 1807 // much of their semantics. 1808 if (D->hasAttr<NakedAttr>()) 1809 B.addAttribute(llvm::Attribute::Naked); 1810 1811 // OptimizeNone wins over OptimizeForSize and MinSize. 1812 F->removeFnAttr(llvm::Attribute::OptimizeForSize); 1813 F->removeFnAttr(llvm::Attribute::MinSize); 1814 } else if (D->hasAttr<NakedAttr>()) { 1815 // Naked implies noinline: we should not be inlining such functions. 1816 B.addAttribute(llvm::Attribute::Naked); 1817 B.addAttribute(llvm::Attribute::NoInline); 1818 } else if (D->hasAttr<NoDuplicateAttr>()) { 1819 B.addAttribute(llvm::Attribute::NoDuplicate); 1820 } else if (D->hasAttr<NoInlineAttr>() && !F->hasFnAttribute(llvm::Attribute::AlwaysInline)) { 1821 // Add noinline if the function isn't always_inline. 1822 B.addAttribute(llvm::Attribute::NoInline); 1823 } else if (D->hasAttr<AlwaysInlineAttr>() && 1824 !F->hasFnAttribute(llvm::Attribute::NoInline)) { 1825 // (noinline wins over always_inline, and we can't specify both in IR) 1826 B.addAttribute(llvm::Attribute::AlwaysInline); 1827 } else if (CodeGenOpts.getInlining() == CodeGenOptions::OnlyAlwaysInlining) { 1828 // If we're not inlining, then force everything that isn't always_inline to 1829 // carry an explicit noinline attribute. 1830 if (!F->hasFnAttribute(llvm::Attribute::AlwaysInline)) 1831 B.addAttribute(llvm::Attribute::NoInline); 1832 } else { 1833 // Otherwise, propagate the inline hint attribute and potentially use its 1834 // absence to mark things as noinline. 1835 if (auto *FD = dyn_cast<FunctionDecl>(D)) { 1836 // Search function and template pattern redeclarations for inline. 1837 auto CheckForInline = [](const FunctionDecl *FD) { 1838 auto CheckRedeclForInline = [](const FunctionDecl *Redecl) { 1839 return Redecl->isInlineSpecified(); 1840 }; 1841 if (any_of(FD->redecls(), CheckRedeclForInline)) 1842 return true; 1843 const FunctionDecl *Pattern = FD->getTemplateInstantiationPattern(); 1844 if (!Pattern) 1845 return false; 1846 return any_of(Pattern->redecls(), CheckRedeclForInline); 1847 }; 1848 if (CheckForInline(FD)) { 1849 B.addAttribute(llvm::Attribute::InlineHint); 1850 } else if (CodeGenOpts.getInlining() == 1851 CodeGenOptions::OnlyHintInlining && 1852 !FD->isInlined() && 1853 !F->hasFnAttribute(llvm::Attribute::AlwaysInline)) { 1854 B.addAttribute(llvm::Attribute::NoInline); 1855 } 1856 } 1857 } 1858 1859 // Add other optimization related attributes if we are optimizing this 1860 // function. 1861 if (!D->hasAttr<OptimizeNoneAttr>()) { 1862 if (D->hasAttr<ColdAttr>()) { 1863 if (!ShouldAddOptNone) 1864 B.addAttribute(llvm::Attribute::OptimizeForSize); 1865 B.addAttribute(llvm::Attribute::Cold); 1866 } 1867 if (D->hasAttr<HotAttr>()) 1868 B.addAttribute(llvm::Attribute::Hot); 1869 if (D->hasAttr<MinSizeAttr>()) 1870 B.addAttribute(llvm::Attribute::MinSize); 1871 } 1872 1873 F->addFnAttrs(B); 1874 1875 unsigned alignment = D->getMaxAlignment() / Context.getCharWidth(); 1876 if (alignment) 1877 F->setAlignment(llvm::Align(alignment)); 1878 1879 if (!D->hasAttr<AlignedAttr>()) 1880 if (LangOpts.FunctionAlignment) 1881 F->setAlignment(llvm::Align(1ull << LangOpts.FunctionAlignment)); 1882 1883 // Some C++ ABIs require 2-byte alignment for member functions, in order to 1884 // reserve a bit for differentiating between virtual and non-virtual member 1885 // functions. If the current target's C++ ABI requires this and this is a 1886 // member function, set its alignment accordingly. 1887 if (getTarget().getCXXABI().areMemberFunctionsAligned()) { 1888 if (F->getAlignment() < 2 && isa<CXXMethodDecl>(D)) 1889 F->setAlignment(llvm::Align(2)); 1890 } 1891 1892 // In the cross-dso CFI mode with canonical jump tables, we want !type 1893 // attributes on definitions only. 1894 if (CodeGenOpts.SanitizeCfiCrossDso && 1895 CodeGenOpts.SanitizeCfiCanonicalJumpTables) { 1896 if (auto *FD = dyn_cast<FunctionDecl>(D)) { 1897 // Skip available_externally functions. They won't be codegen'ed in the 1898 // current module anyway. 1899 if (getContext().GetGVALinkageForFunction(FD) != GVA_AvailableExternally) 1900 CreateFunctionTypeMetadataForIcall(FD, F); 1901 } 1902 } 1903 1904 // Emit type metadata on member functions for member function pointer checks. 1905 // These are only ever necessary on definitions; we're guaranteed that the 1906 // definition will be present in the LTO unit as a result of LTO visibility. 1907 auto *MD = dyn_cast<CXXMethodDecl>(D); 1908 if (MD && requiresMemberFunctionPointerTypeMetadata(*this, MD)) { 1909 for (const CXXRecordDecl *Base : getMostBaseClasses(MD->getParent())) { 1910 llvm::Metadata *Id = 1911 CreateMetadataIdentifierForType(Context.getMemberPointerType( 1912 MD->getType(), Context.getRecordType(Base).getTypePtr())); 1913 F->addTypeMetadata(0, Id); 1914 } 1915 } 1916 } 1917 1918 void CodeGenModule::setLLVMFunctionFEnvAttributes(const FunctionDecl *D, 1919 llvm::Function *F) { 1920 if (D->hasAttr<StrictFPAttr>()) { 1921 llvm::AttrBuilder FuncAttrs; 1922 FuncAttrs.addAttribute("strictfp"); 1923 F->addFnAttrs(FuncAttrs); 1924 } 1925 } 1926 1927 void CodeGenModule::SetCommonAttributes(GlobalDecl GD, llvm::GlobalValue *GV) { 1928 const Decl *D = GD.getDecl(); 1929 if (dyn_cast_or_null<NamedDecl>(D)) 1930 setGVProperties(GV, GD); 1931 else 1932 GV->setVisibility(llvm::GlobalValue::DefaultVisibility); 1933 1934 if (D && D->hasAttr<UsedAttr>()) 1935 addUsedOrCompilerUsedGlobal(GV); 1936 1937 if (CodeGenOpts.KeepStaticConsts && D && isa<VarDecl>(D)) { 1938 const auto *VD = cast<VarDecl>(D); 1939 if (VD->getType().isConstQualified() && 1940 VD->getStorageDuration() == SD_Static) 1941 addUsedOrCompilerUsedGlobal(GV); 1942 } 1943 } 1944 1945 bool CodeGenModule::GetCPUAndFeaturesAttributes(GlobalDecl GD, 1946 llvm::AttrBuilder &Attrs) { 1947 // Add target-cpu and target-features attributes to functions. If 1948 // we have a decl for the function and it has a target attribute then 1949 // parse that and add it to the feature set. 1950 StringRef TargetCPU = getTarget().getTargetOpts().CPU; 1951 StringRef TuneCPU = getTarget().getTargetOpts().TuneCPU; 1952 std::vector<std::string> Features; 1953 const auto *FD = dyn_cast_or_null<FunctionDecl>(GD.getDecl()); 1954 FD = FD ? FD->getMostRecentDecl() : FD; 1955 const auto *TD = FD ? FD->getAttr<TargetAttr>() : nullptr; 1956 const auto *SD = FD ? FD->getAttr<CPUSpecificAttr>() : nullptr; 1957 bool AddedAttr = false; 1958 if (TD || SD) { 1959 llvm::StringMap<bool> FeatureMap; 1960 getContext().getFunctionFeatureMap(FeatureMap, GD); 1961 1962 // Produce the canonical string for this set of features. 1963 for (const llvm::StringMap<bool>::value_type &Entry : FeatureMap) 1964 Features.push_back((Entry.getValue() ? "+" : "-") + Entry.getKey().str()); 1965 1966 // Now add the target-cpu and target-features to the function. 1967 // While we populated the feature map above, we still need to 1968 // get and parse the target attribute so we can get the cpu for 1969 // the function. 1970 if (TD) { 1971 ParsedTargetAttr ParsedAttr = TD->parse(); 1972 if (!ParsedAttr.Architecture.empty() && 1973 getTarget().isValidCPUName(ParsedAttr.Architecture)) { 1974 TargetCPU = ParsedAttr.Architecture; 1975 TuneCPU = ""; // Clear the tune CPU. 1976 } 1977 if (!ParsedAttr.Tune.empty() && 1978 getTarget().isValidCPUName(ParsedAttr.Tune)) 1979 TuneCPU = ParsedAttr.Tune; 1980 } 1981 } else { 1982 // Otherwise just add the existing target cpu and target features to the 1983 // function. 1984 Features = getTarget().getTargetOpts().Features; 1985 } 1986 1987 if (!TargetCPU.empty()) { 1988 Attrs.addAttribute("target-cpu", TargetCPU); 1989 AddedAttr = true; 1990 } 1991 if (!TuneCPU.empty()) { 1992 Attrs.addAttribute("tune-cpu", TuneCPU); 1993 AddedAttr = true; 1994 } 1995 if (!Features.empty()) { 1996 llvm::sort(Features); 1997 Attrs.addAttribute("target-features", llvm::join(Features, ",")); 1998 AddedAttr = true; 1999 } 2000 2001 return AddedAttr; 2002 } 2003 2004 void CodeGenModule::setNonAliasAttributes(GlobalDecl GD, 2005 llvm::GlobalObject *GO) { 2006 const Decl *D = GD.getDecl(); 2007 SetCommonAttributes(GD, GO); 2008 2009 if (D) { 2010 if (auto *GV = dyn_cast<llvm::GlobalVariable>(GO)) { 2011 if (D->hasAttr<RetainAttr>()) 2012 addUsedGlobal(GV); 2013 if (auto *SA = D->getAttr<PragmaClangBSSSectionAttr>()) 2014 GV->addAttribute("bss-section", SA->getName()); 2015 if (auto *SA = D->getAttr<PragmaClangDataSectionAttr>()) 2016 GV->addAttribute("data-section", SA->getName()); 2017 if (auto *SA = D->getAttr<PragmaClangRodataSectionAttr>()) 2018 GV->addAttribute("rodata-section", SA->getName()); 2019 if (auto *SA = D->getAttr<PragmaClangRelroSectionAttr>()) 2020 GV->addAttribute("relro-section", SA->getName()); 2021 } 2022 2023 if (auto *F = dyn_cast<llvm::Function>(GO)) { 2024 if (D->hasAttr<RetainAttr>()) 2025 addUsedGlobal(F); 2026 if (auto *SA = D->getAttr<PragmaClangTextSectionAttr>()) 2027 if (!D->getAttr<SectionAttr>()) 2028 F->addFnAttr("implicit-section-name", SA->getName()); 2029 2030 llvm::AttrBuilder Attrs; 2031 if (GetCPUAndFeaturesAttributes(GD, Attrs)) { 2032 // We know that GetCPUAndFeaturesAttributes will always have the 2033 // newest set, since it has the newest possible FunctionDecl, so the 2034 // new ones should replace the old. 2035 llvm::AttrBuilder RemoveAttrs; 2036 RemoveAttrs.addAttribute("target-cpu"); 2037 RemoveAttrs.addAttribute("target-features"); 2038 RemoveAttrs.addAttribute("tune-cpu"); 2039 F->removeFnAttrs(RemoveAttrs); 2040 F->addFnAttrs(Attrs); 2041 } 2042 } 2043 2044 if (const auto *CSA = D->getAttr<CodeSegAttr>()) 2045 GO->setSection(CSA->getName()); 2046 else if (const auto *SA = D->getAttr<SectionAttr>()) 2047 GO->setSection(SA->getName()); 2048 } 2049 2050 getTargetCodeGenInfo().setTargetAttributes(D, GO, *this); 2051 } 2052 2053 void CodeGenModule::SetInternalFunctionAttributes(GlobalDecl GD, 2054 llvm::Function *F, 2055 const CGFunctionInfo &FI) { 2056 const Decl *D = GD.getDecl(); 2057 SetLLVMFunctionAttributes(GD, FI, F, /*IsThunk=*/false); 2058 SetLLVMFunctionAttributesForDefinition(D, F); 2059 2060 F->setLinkage(llvm::Function::InternalLinkage); 2061 2062 setNonAliasAttributes(GD, F); 2063 } 2064 2065 static void setLinkageForGV(llvm::GlobalValue *GV, const NamedDecl *ND) { 2066 // Set linkage and visibility in case we never see a definition. 2067 LinkageInfo LV = ND->getLinkageAndVisibility(); 2068 // Don't set internal linkage on declarations. 2069 // "extern_weak" is overloaded in LLVM; we probably should have 2070 // separate linkage types for this. 2071 if (isExternallyVisible(LV.getLinkage()) && 2072 (ND->hasAttr<WeakAttr>() || ND->isWeakImported())) 2073 GV->setLinkage(llvm::GlobalValue::ExternalWeakLinkage); 2074 } 2075 2076 void CodeGenModule::CreateFunctionTypeMetadataForIcall(const FunctionDecl *FD, 2077 llvm::Function *F) { 2078 // Only if we are checking indirect calls. 2079 if (!LangOpts.Sanitize.has(SanitizerKind::CFIICall)) 2080 return; 2081 2082 // Non-static class methods are handled via vtable or member function pointer 2083 // checks elsewhere. 2084 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic()) 2085 return; 2086 2087 llvm::Metadata *MD = CreateMetadataIdentifierForType(FD->getType()); 2088 F->addTypeMetadata(0, MD); 2089 F->addTypeMetadata(0, CreateMetadataIdentifierGeneralized(FD->getType())); 2090 2091 // Emit a hash-based bit set entry for cross-DSO calls. 2092 if (CodeGenOpts.SanitizeCfiCrossDso) 2093 if (auto CrossDsoTypeId = CreateCrossDsoCfiTypeId(MD)) 2094 F->addTypeMetadata(0, llvm::ConstantAsMetadata::get(CrossDsoTypeId)); 2095 } 2096 2097 void CodeGenModule::SetFunctionAttributes(GlobalDecl GD, llvm::Function *F, 2098 bool IsIncompleteFunction, 2099 bool IsThunk) { 2100 2101 if (llvm::Intrinsic::ID IID = F->getIntrinsicID()) { 2102 // If this is an intrinsic function, set the function's attributes 2103 // to the intrinsic's attributes. 2104 F->setAttributes(llvm::Intrinsic::getAttributes(getLLVMContext(), IID)); 2105 return; 2106 } 2107 2108 const auto *FD = cast<FunctionDecl>(GD.getDecl()); 2109 2110 if (!IsIncompleteFunction) 2111 SetLLVMFunctionAttributes(GD, getTypes().arrangeGlobalDeclaration(GD), F, 2112 IsThunk); 2113 2114 // Add the Returned attribute for "this", except for iOS 5 and earlier 2115 // where substantial code, including the libstdc++ dylib, was compiled with 2116 // GCC and does not actually return "this". 2117 if (!IsThunk && getCXXABI().HasThisReturn(GD) && 2118 !(getTriple().isiOS() && getTriple().isOSVersionLT(6))) { 2119 assert(!F->arg_empty() && 2120 F->arg_begin()->getType() 2121 ->canLosslesslyBitCastTo(F->getReturnType()) && 2122 "unexpected this return"); 2123 F->addParamAttr(0, llvm::Attribute::Returned); 2124 } 2125 2126 // Only a few attributes are set on declarations; these may later be 2127 // overridden by a definition. 2128 2129 setLinkageForGV(F, FD); 2130 setGVProperties(F, FD); 2131 2132 // Setup target-specific attributes. 2133 if (!IsIncompleteFunction && F->isDeclaration()) 2134 getTargetCodeGenInfo().setTargetAttributes(FD, F, *this); 2135 2136 if (const auto *CSA = FD->getAttr<CodeSegAttr>()) 2137 F->setSection(CSA->getName()); 2138 else if (const auto *SA = FD->getAttr<SectionAttr>()) 2139 F->setSection(SA->getName()); 2140 2141 if (const auto *EA = FD->getAttr<ErrorAttr>()) { 2142 if (EA->isError()) 2143 F->addFnAttr("dontcall-error", EA->getUserDiagnostic()); 2144 else if (EA->isWarning()) 2145 F->addFnAttr("dontcall-warn", EA->getUserDiagnostic()); 2146 } 2147 2148 // If we plan on emitting this inline builtin, we can't treat it as a builtin. 2149 if (FD->isInlineBuiltinDeclaration()) { 2150 const FunctionDecl *FDBody; 2151 bool HasBody = FD->hasBody(FDBody); 2152 (void)HasBody; 2153 assert(HasBody && "Inline builtin declarations should always have an " 2154 "available body!"); 2155 if (shouldEmitFunction(FDBody)) 2156 F->addFnAttr(llvm::Attribute::NoBuiltin); 2157 } 2158 2159 if (FD->isReplaceableGlobalAllocationFunction()) { 2160 // A replaceable global allocation function does not act like a builtin by 2161 // default, only if it is invoked by a new-expression or delete-expression. 2162 F->addFnAttr(llvm::Attribute::NoBuiltin); 2163 } 2164 2165 if (isa<CXXConstructorDecl>(FD) || isa<CXXDestructorDecl>(FD)) 2166 F->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global); 2167 else if (const auto *MD = dyn_cast<CXXMethodDecl>(FD)) 2168 if (MD->isVirtual()) 2169 F->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global); 2170 2171 // Don't emit entries for function declarations in the cross-DSO mode. This 2172 // is handled with better precision by the receiving DSO. But if jump tables 2173 // are non-canonical then we need type metadata in order to produce the local 2174 // jump table. 2175 if (!CodeGenOpts.SanitizeCfiCrossDso || 2176 !CodeGenOpts.SanitizeCfiCanonicalJumpTables) 2177 CreateFunctionTypeMetadataForIcall(FD, F); 2178 2179 if (getLangOpts().OpenMP && FD->hasAttr<OMPDeclareSimdDeclAttr>()) 2180 getOpenMPRuntime().emitDeclareSimdFunction(FD, F); 2181 2182 if (const auto *CB = FD->getAttr<CallbackAttr>()) { 2183 // Annotate the callback behavior as metadata: 2184 // - The callback callee (as argument number). 2185 // - The callback payloads (as argument numbers). 2186 llvm::LLVMContext &Ctx = F->getContext(); 2187 llvm::MDBuilder MDB(Ctx); 2188 2189 // The payload indices are all but the first one in the encoding. The first 2190 // identifies the callback callee. 2191 int CalleeIdx = *CB->encoding_begin(); 2192 ArrayRef<int> PayloadIndices(CB->encoding_begin() + 1, CB->encoding_end()); 2193 F->addMetadata(llvm::LLVMContext::MD_callback, 2194 *llvm::MDNode::get(Ctx, {MDB.createCallbackEncoding( 2195 CalleeIdx, PayloadIndices, 2196 /* VarArgsArePassed */ false)})); 2197 } 2198 2199 if (FD->hasAttr<AnnotateAttr>()) 2200 AddGlobalAnnotations(FD, F); 2201 } 2202 2203 void CodeGenModule::addUsedGlobal(llvm::GlobalValue *GV) { 2204 assert((isa<llvm::Function>(GV) || !GV->isDeclaration()) && 2205 "Only globals with definition can force usage."); 2206 LLVMUsed.emplace_back(GV); 2207 } 2208 2209 void CodeGenModule::addCompilerUsedGlobal(llvm::GlobalValue *GV) { 2210 assert(!GV->isDeclaration() && 2211 "Only globals with definition can force usage."); 2212 LLVMCompilerUsed.emplace_back(GV); 2213 } 2214 2215 void CodeGenModule::addUsedOrCompilerUsedGlobal(llvm::GlobalValue *GV) { 2216 assert((isa<llvm::Function>(GV) || !GV->isDeclaration()) && 2217 "Only globals with definition can force usage."); 2218 if (getTriple().isOSBinFormatELF()) 2219 LLVMCompilerUsed.emplace_back(GV); 2220 else 2221 LLVMUsed.emplace_back(GV); 2222 } 2223 2224 static void emitUsed(CodeGenModule &CGM, StringRef Name, 2225 std::vector<llvm::WeakTrackingVH> &List) { 2226 // Don't create llvm.used if there is no need. 2227 if (List.empty()) 2228 return; 2229 2230 // Convert List to what ConstantArray needs. 2231 SmallVector<llvm::Constant*, 8> UsedArray; 2232 UsedArray.resize(List.size()); 2233 for (unsigned i = 0, e = List.size(); i != e; ++i) { 2234 UsedArray[i] = 2235 llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast( 2236 cast<llvm::Constant>(&*List[i]), CGM.Int8PtrTy); 2237 } 2238 2239 if (UsedArray.empty()) 2240 return; 2241 llvm::ArrayType *ATy = llvm::ArrayType::get(CGM.Int8PtrTy, UsedArray.size()); 2242 2243 auto *GV = new llvm::GlobalVariable( 2244 CGM.getModule(), ATy, false, llvm::GlobalValue::AppendingLinkage, 2245 llvm::ConstantArray::get(ATy, UsedArray), Name); 2246 2247 GV->setSection("llvm.metadata"); 2248 } 2249 2250 void CodeGenModule::emitLLVMUsed() { 2251 emitUsed(*this, "llvm.used", LLVMUsed); 2252 emitUsed(*this, "llvm.compiler.used", LLVMCompilerUsed); 2253 } 2254 2255 void CodeGenModule::AppendLinkerOptions(StringRef Opts) { 2256 auto *MDOpts = llvm::MDString::get(getLLVMContext(), Opts); 2257 LinkerOptionsMetadata.push_back(llvm::MDNode::get(getLLVMContext(), MDOpts)); 2258 } 2259 2260 void CodeGenModule::AddDetectMismatch(StringRef Name, StringRef Value) { 2261 llvm::SmallString<32> Opt; 2262 getTargetCodeGenInfo().getDetectMismatchOption(Name, Value, Opt); 2263 if (Opt.empty()) 2264 return; 2265 auto *MDOpts = llvm::MDString::get(getLLVMContext(), Opt); 2266 LinkerOptionsMetadata.push_back(llvm::MDNode::get(getLLVMContext(), MDOpts)); 2267 } 2268 2269 void CodeGenModule::AddDependentLib(StringRef Lib) { 2270 auto &C = getLLVMContext(); 2271 if (getTarget().getTriple().isOSBinFormatELF()) { 2272 ELFDependentLibraries.push_back( 2273 llvm::MDNode::get(C, llvm::MDString::get(C, Lib))); 2274 return; 2275 } 2276 2277 llvm::SmallString<24> Opt; 2278 getTargetCodeGenInfo().getDependentLibraryOption(Lib, Opt); 2279 auto *MDOpts = llvm::MDString::get(getLLVMContext(), Opt); 2280 LinkerOptionsMetadata.push_back(llvm::MDNode::get(C, MDOpts)); 2281 } 2282 2283 /// Add link options implied by the given module, including modules 2284 /// it depends on, using a postorder walk. 2285 static void addLinkOptionsPostorder(CodeGenModule &CGM, Module *Mod, 2286 SmallVectorImpl<llvm::MDNode *> &Metadata, 2287 llvm::SmallPtrSet<Module *, 16> &Visited) { 2288 // Import this module's parent. 2289 if (Mod->Parent && Visited.insert(Mod->Parent).second) { 2290 addLinkOptionsPostorder(CGM, Mod->Parent, Metadata, Visited); 2291 } 2292 2293 // Import this module's dependencies. 2294 for (unsigned I = Mod->Imports.size(); I > 0; --I) { 2295 if (Visited.insert(Mod->Imports[I - 1]).second) 2296 addLinkOptionsPostorder(CGM, Mod->Imports[I-1], Metadata, Visited); 2297 } 2298 2299 // Add linker options to link against the libraries/frameworks 2300 // described by this module. 2301 llvm::LLVMContext &Context = CGM.getLLVMContext(); 2302 bool IsELF = CGM.getTarget().getTriple().isOSBinFormatELF(); 2303 2304 // For modules that use export_as for linking, use that module 2305 // name instead. 2306 if (Mod->UseExportAsModuleLinkName) 2307 return; 2308 2309 for (unsigned I = Mod->LinkLibraries.size(); I > 0; --I) { 2310 // Link against a framework. Frameworks are currently Darwin only, so we 2311 // don't to ask TargetCodeGenInfo for the spelling of the linker option. 2312 if (Mod->LinkLibraries[I-1].IsFramework) { 2313 llvm::Metadata *Args[2] = { 2314 llvm::MDString::get(Context, "-framework"), 2315 llvm::MDString::get(Context, Mod->LinkLibraries[I - 1].Library)}; 2316 2317 Metadata.push_back(llvm::MDNode::get(Context, Args)); 2318 continue; 2319 } 2320 2321 // Link against a library. 2322 if (IsELF) { 2323 llvm::Metadata *Args[2] = { 2324 llvm::MDString::get(Context, "lib"), 2325 llvm::MDString::get(Context, Mod->LinkLibraries[I - 1].Library), 2326 }; 2327 Metadata.push_back(llvm::MDNode::get(Context, Args)); 2328 } else { 2329 llvm::SmallString<24> Opt; 2330 CGM.getTargetCodeGenInfo().getDependentLibraryOption( 2331 Mod->LinkLibraries[I - 1].Library, Opt); 2332 auto *OptString = llvm::MDString::get(Context, Opt); 2333 Metadata.push_back(llvm::MDNode::get(Context, OptString)); 2334 } 2335 } 2336 } 2337 2338 void CodeGenModule::EmitModuleLinkOptions() { 2339 // Collect the set of all of the modules we want to visit to emit link 2340 // options, which is essentially the imported modules and all of their 2341 // non-explicit child modules. 2342 llvm::SetVector<clang::Module *> LinkModules; 2343 llvm::SmallPtrSet<clang::Module *, 16> Visited; 2344 SmallVector<clang::Module *, 16> Stack; 2345 2346 // Seed the stack with imported modules. 2347 for (Module *M : ImportedModules) { 2348 // Do not add any link flags when an implementation TU of a module imports 2349 // a header of that same module. 2350 if (M->getTopLevelModuleName() == getLangOpts().CurrentModule && 2351 !getLangOpts().isCompilingModule()) 2352 continue; 2353 if (Visited.insert(M).second) 2354 Stack.push_back(M); 2355 } 2356 2357 // Find all of the modules to import, making a little effort to prune 2358 // non-leaf modules. 2359 while (!Stack.empty()) { 2360 clang::Module *Mod = Stack.pop_back_val(); 2361 2362 bool AnyChildren = false; 2363 2364 // Visit the submodules of this module. 2365 for (const auto &SM : Mod->submodules()) { 2366 // Skip explicit children; they need to be explicitly imported to be 2367 // linked against. 2368 if (SM->IsExplicit) 2369 continue; 2370 2371 if (Visited.insert(SM).second) { 2372 Stack.push_back(SM); 2373 AnyChildren = true; 2374 } 2375 } 2376 2377 // We didn't find any children, so add this module to the list of 2378 // modules to link against. 2379 if (!AnyChildren) { 2380 LinkModules.insert(Mod); 2381 } 2382 } 2383 2384 // Add link options for all of the imported modules in reverse topological 2385 // order. We don't do anything to try to order import link flags with respect 2386 // to linker options inserted by things like #pragma comment(). 2387 SmallVector<llvm::MDNode *, 16> MetadataArgs; 2388 Visited.clear(); 2389 for (Module *M : LinkModules) 2390 if (Visited.insert(M).second) 2391 addLinkOptionsPostorder(*this, M, MetadataArgs, Visited); 2392 std::reverse(MetadataArgs.begin(), MetadataArgs.end()); 2393 LinkerOptionsMetadata.append(MetadataArgs.begin(), MetadataArgs.end()); 2394 2395 // Add the linker options metadata flag. 2396 auto *NMD = getModule().getOrInsertNamedMetadata("llvm.linker.options"); 2397 for (auto *MD : LinkerOptionsMetadata) 2398 NMD->addOperand(MD); 2399 } 2400 2401 void CodeGenModule::EmitDeferred() { 2402 // Emit deferred declare target declarations. 2403 if (getLangOpts().OpenMP && !getLangOpts().OpenMPSimd) 2404 getOpenMPRuntime().emitDeferredTargetDecls(); 2405 2406 // Emit code for any potentially referenced deferred decls. Since a 2407 // previously unused static decl may become used during the generation of code 2408 // for a static function, iterate until no changes are made. 2409 2410 if (!DeferredVTables.empty()) { 2411 EmitDeferredVTables(); 2412 2413 // Emitting a vtable doesn't directly cause more vtables to 2414 // become deferred, although it can cause functions to be 2415 // emitted that then need those vtables. 2416 assert(DeferredVTables.empty()); 2417 } 2418 2419 // Emit CUDA/HIP static device variables referenced by host code only. 2420 // Note we should not clear CUDADeviceVarODRUsedByHost since it is still 2421 // needed for further handling. 2422 if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice) 2423 for (const auto *V : getContext().CUDADeviceVarODRUsedByHost) 2424 DeferredDeclsToEmit.push_back(V); 2425 2426 // Stop if we're out of both deferred vtables and deferred declarations. 2427 if (DeferredDeclsToEmit.empty()) 2428 return; 2429 2430 // Grab the list of decls to emit. If EmitGlobalDefinition schedules more 2431 // work, it will not interfere with this. 2432 std::vector<GlobalDecl> CurDeclsToEmit; 2433 CurDeclsToEmit.swap(DeferredDeclsToEmit); 2434 2435 for (GlobalDecl &D : CurDeclsToEmit) { 2436 // We should call GetAddrOfGlobal with IsForDefinition set to true in order 2437 // to get GlobalValue with exactly the type we need, not something that 2438 // might had been created for another decl with the same mangled name but 2439 // different type. 2440 llvm::GlobalValue *GV = dyn_cast<llvm::GlobalValue>( 2441 GetAddrOfGlobal(D, ForDefinition)); 2442 2443 // In case of different address spaces, we may still get a cast, even with 2444 // IsForDefinition equal to true. Query mangled names table to get 2445 // GlobalValue. 2446 if (!GV) 2447 GV = GetGlobalValue(getMangledName(D)); 2448 2449 // Make sure GetGlobalValue returned non-null. 2450 assert(GV); 2451 2452 // Check to see if we've already emitted this. This is necessary 2453 // for a couple of reasons: first, decls can end up in the 2454 // deferred-decls queue multiple times, and second, decls can end 2455 // up with definitions in unusual ways (e.g. by an extern inline 2456 // function acquiring a strong function redefinition). Just 2457 // ignore these cases. 2458 if (!GV->isDeclaration()) 2459 continue; 2460 2461 // If this is OpenMP, check if it is legal to emit this global normally. 2462 if (LangOpts.OpenMP && OpenMPRuntime && OpenMPRuntime->emitTargetGlobal(D)) 2463 continue; 2464 2465 // Otherwise, emit the definition and move on to the next one. 2466 EmitGlobalDefinition(D, GV); 2467 2468 // If we found out that we need to emit more decls, do that recursively. 2469 // This has the advantage that the decls are emitted in a DFS and related 2470 // ones are close together, which is convenient for testing. 2471 if (!DeferredVTables.empty() || !DeferredDeclsToEmit.empty()) { 2472 EmitDeferred(); 2473 assert(DeferredVTables.empty() && DeferredDeclsToEmit.empty()); 2474 } 2475 } 2476 } 2477 2478 void CodeGenModule::EmitVTablesOpportunistically() { 2479 // Try to emit external vtables as available_externally if they have emitted 2480 // all inlined virtual functions. It runs after EmitDeferred() and therefore 2481 // is not allowed to create new references to things that need to be emitted 2482 // lazily. Note that it also uses fact that we eagerly emitting RTTI. 2483 2484 assert((OpportunisticVTables.empty() || shouldOpportunisticallyEmitVTables()) 2485 && "Only emit opportunistic vtables with optimizations"); 2486 2487 for (const CXXRecordDecl *RD : OpportunisticVTables) { 2488 assert(getVTables().isVTableExternal(RD) && 2489 "This queue should only contain external vtables"); 2490 if (getCXXABI().canSpeculativelyEmitVTable(RD)) 2491 VTables.GenerateClassData(RD); 2492 } 2493 OpportunisticVTables.clear(); 2494 } 2495 2496 void CodeGenModule::EmitGlobalAnnotations() { 2497 if (Annotations.empty()) 2498 return; 2499 2500 // Create a new global variable for the ConstantStruct in the Module. 2501 llvm::Constant *Array = llvm::ConstantArray::get(llvm::ArrayType::get( 2502 Annotations[0]->getType(), Annotations.size()), Annotations); 2503 auto *gv = new llvm::GlobalVariable(getModule(), Array->getType(), false, 2504 llvm::GlobalValue::AppendingLinkage, 2505 Array, "llvm.global.annotations"); 2506 gv->setSection(AnnotationSection); 2507 } 2508 2509 llvm::Constant *CodeGenModule::EmitAnnotationString(StringRef Str) { 2510 llvm::Constant *&AStr = AnnotationStrings[Str]; 2511 if (AStr) 2512 return AStr; 2513 2514 // Not found yet, create a new global. 2515 llvm::Constant *s = llvm::ConstantDataArray::getString(getLLVMContext(), Str); 2516 auto *gv = 2517 new llvm::GlobalVariable(getModule(), s->getType(), true, 2518 llvm::GlobalValue::PrivateLinkage, s, ".str"); 2519 gv->setSection(AnnotationSection); 2520 gv->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global); 2521 AStr = gv; 2522 return gv; 2523 } 2524 2525 llvm::Constant *CodeGenModule::EmitAnnotationUnit(SourceLocation Loc) { 2526 SourceManager &SM = getContext().getSourceManager(); 2527 PresumedLoc PLoc = SM.getPresumedLoc(Loc); 2528 if (PLoc.isValid()) 2529 return EmitAnnotationString(PLoc.getFilename()); 2530 return EmitAnnotationString(SM.getBufferName(Loc)); 2531 } 2532 2533 llvm::Constant *CodeGenModule::EmitAnnotationLineNo(SourceLocation L) { 2534 SourceManager &SM = getContext().getSourceManager(); 2535 PresumedLoc PLoc = SM.getPresumedLoc(L); 2536 unsigned LineNo = PLoc.isValid() ? PLoc.getLine() : 2537 SM.getExpansionLineNumber(L); 2538 return llvm::ConstantInt::get(Int32Ty, LineNo); 2539 } 2540 2541 llvm::Constant *CodeGenModule::EmitAnnotationArgs(const AnnotateAttr *Attr) { 2542 ArrayRef<Expr *> Exprs = {Attr->args_begin(), Attr->args_size()}; 2543 if (Exprs.empty()) 2544 return llvm::ConstantPointerNull::get(GlobalsInt8PtrTy); 2545 2546 llvm::FoldingSetNodeID ID; 2547 for (Expr *E : Exprs) { 2548 ID.Add(cast<clang::ConstantExpr>(E)->getAPValueResult()); 2549 } 2550 llvm::Constant *&Lookup = AnnotationArgs[ID.ComputeHash()]; 2551 if (Lookup) 2552 return Lookup; 2553 2554 llvm::SmallVector<llvm::Constant *, 4> LLVMArgs; 2555 LLVMArgs.reserve(Exprs.size()); 2556 ConstantEmitter ConstEmiter(*this); 2557 llvm::transform(Exprs, std::back_inserter(LLVMArgs), [&](const Expr *E) { 2558 const auto *CE = cast<clang::ConstantExpr>(E); 2559 return ConstEmiter.emitAbstract(CE->getBeginLoc(), CE->getAPValueResult(), 2560 CE->getType()); 2561 }); 2562 auto *Struct = llvm::ConstantStruct::getAnon(LLVMArgs); 2563 auto *GV = new llvm::GlobalVariable(getModule(), Struct->getType(), true, 2564 llvm::GlobalValue::PrivateLinkage, Struct, 2565 ".args"); 2566 GV->setSection(AnnotationSection); 2567 GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global); 2568 auto *Bitcasted = llvm::ConstantExpr::getBitCast(GV, GlobalsInt8PtrTy); 2569 2570 Lookup = Bitcasted; 2571 return Bitcasted; 2572 } 2573 2574 llvm::Constant *CodeGenModule::EmitAnnotateAttr(llvm::GlobalValue *GV, 2575 const AnnotateAttr *AA, 2576 SourceLocation L) { 2577 // Get the globals for file name, annotation, and the line number. 2578 llvm::Constant *AnnoGV = EmitAnnotationString(AA->getAnnotation()), 2579 *UnitGV = EmitAnnotationUnit(L), 2580 *LineNoCst = EmitAnnotationLineNo(L), 2581 *Args = EmitAnnotationArgs(AA); 2582 2583 llvm::Constant *GVInGlobalsAS = GV; 2584 if (GV->getAddressSpace() != 2585 getDataLayout().getDefaultGlobalsAddressSpace()) { 2586 GVInGlobalsAS = llvm::ConstantExpr::getAddrSpaceCast( 2587 GV, GV->getValueType()->getPointerTo( 2588 getDataLayout().getDefaultGlobalsAddressSpace())); 2589 } 2590 2591 // Create the ConstantStruct for the global annotation. 2592 llvm::Constant *Fields[] = { 2593 llvm::ConstantExpr::getBitCast(GVInGlobalsAS, GlobalsInt8PtrTy), 2594 llvm::ConstantExpr::getBitCast(AnnoGV, GlobalsInt8PtrTy), 2595 llvm::ConstantExpr::getBitCast(UnitGV, GlobalsInt8PtrTy), 2596 LineNoCst, 2597 Args, 2598 }; 2599 return llvm::ConstantStruct::getAnon(Fields); 2600 } 2601 2602 void CodeGenModule::AddGlobalAnnotations(const ValueDecl *D, 2603 llvm::GlobalValue *GV) { 2604 assert(D->hasAttr<AnnotateAttr>() && "no annotate attribute"); 2605 // Get the struct elements for these annotations. 2606 for (const auto *I : D->specific_attrs<AnnotateAttr>()) 2607 Annotations.push_back(EmitAnnotateAttr(GV, I, D->getLocation())); 2608 } 2609 2610 bool CodeGenModule::isInNoSanitizeList(SanitizerMask Kind, llvm::Function *Fn, 2611 SourceLocation Loc) const { 2612 const auto &NoSanitizeL = getContext().getNoSanitizeList(); 2613 // NoSanitize by function name. 2614 if (NoSanitizeL.containsFunction(Kind, Fn->getName())) 2615 return true; 2616 // NoSanitize by location. 2617 if (Loc.isValid()) 2618 return NoSanitizeL.containsLocation(Kind, Loc); 2619 // If location is unknown, this may be a compiler-generated function. Assume 2620 // it's located in the main file. 2621 auto &SM = Context.getSourceManager(); 2622 if (const auto *MainFile = SM.getFileEntryForID(SM.getMainFileID())) { 2623 return NoSanitizeL.containsFile(Kind, MainFile->getName()); 2624 } 2625 return false; 2626 } 2627 2628 bool CodeGenModule::isInNoSanitizeList(llvm::GlobalVariable *GV, 2629 SourceLocation Loc, QualType Ty, 2630 StringRef Category) const { 2631 // For now globals can be ignored only in ASan and KASan. 2632 const SanitizerMask EnabledAsanMask = 2633 LangOpts.Sanitize.Mask & 2634 (SanitizerKind::Address | SanitizerKind::KernelAddress | 2635 SanitizerKind::HWAddress | SanitizerKind::KernelHWAddress | 2636 SanitizerKind::MemTag); 2637 if (!EnabledAsanMask) 2638 return false; 2639 const auto &NoSanitizeL = getContext().getNoSanitizeList(); 2640 if (NoSanitizeL.containsGlobal(EnabledAsanMask, GV->getName(), Category)) 2641 return true; 2642 if (NoSanitizeL.containsLocation(EnabledAsanMask, Loc, Category)) 2643 return true; 2644 // Check global type. 2645 if (!Ty.isNull()) { 2646 // Drill down the array types: if global variable of a fixed type is 2647 // not sanitized, we also don't instrument arrays of them. 2648 while (auto AT = dyn_cast<ArrayType>(Ty.getTypePtr())) 2649 Ty = AT->getElementType(); 2650 Ty = Ty.getCanonicalType().getUnqualifiedType(); 2651 // Only record types (classes, structs etc.) are ignored. 2652 if (Ty->isRecordType()) { 2653 std::string TypeStr = Ty.getAsString(getContext().getPrintingPolicy()); 2654 if (NoSanitizeL.containsType(EnabledAsanMask, TypeStr, Category)) 2655 return true; 2656 } 2657 } 2658 return false; 2659 } 2660 2661 bool CodeGenModule::imbueXRayAttrs(llvm::Function *Fn, SourceLocation Loc, 2662 StringRef Category) const { 2663 const auto &XRayFilter = getContext().getXRayFilter(); 2664 using ImbueAttr = XRayFunctionFilter::ImbueAttribute; 2665 auto Attr = ImbueAttr::NONE; 2666 if (Loc.isValid()) 2667 Attr = XRayFilter.shouldImbueLocation(Loc, Category); 2668 if (Attr == ImbueAttr::NONE) 2669 Attr = XRayFilter.shouldImbueFunction(Fn->getName()); 2670 switch (Attr) { 2671 case ImbueAttr::NONE: 2672 return false; 2673 case ImbueAttr::ALWAYS: 2674 Fn->addFnAttr("function-instrument", "xray-always"); 2675 break; 2676 case ImbueAttr::ALWAYS_ARG1: 2677 Fn->addFnAttr("function-instrument", "xray-always"); 2678 Fn->addFnAttr("xray-log-args", "1"); 2679 break; 2680 case ImbueAttr::NEVER: 2681 Fn->addFnAttr("function-instrument", "xray-never"); 2682 break; 2683 } 2684 return true; 2685 } 2686 2687 bool CodeGenModule::isProfileInstrExcluded(llvm::Function *Fn, 2688 SourceLocation Loc) const { 2689 const auto &ProfileList = getContext().getProfileList(); 2690 // If the profile list is empty, then instrument everything. 2691 if (ProfileList.isEmpty()) 2692 return false; 2693 CodeGenOptions::ProfileInstrKind Kind = getCodeGenOpts().getProfileInstr(); 2694 // First, check the function name. 2695 Optional<bool> V = ProfileList.isFunctionExcluded(Fn->getName(), Kind); 2696 if (V.hasValue()) 2697 return *V; 2698 // Next, check the source location. 2699 if (Loc.isValid()) { 2700 Optional<bool> V = ProfileList.isLocationExcluded(Loc, Kind); 2701 if (V.hasValue()) 2702 return *V; 2703 } 2704 // If location is unknown, this may be a compiler-generated function. Assume 2705 // it's located in the main file. 2706 auto &SM = Context.getSourceManager(); 2707 if (const auto *MainFile = SM.getFileEntryForID(SM.getMainFileID())) { 2708 Optional<bool> V = ProfileList.isFileExcluded(MainFile->getName(), Kind); 2709 if (V.hasValue()) 2710 return *V; 2711 } 2712 return ProfileList.getDefault(); 2713 } 2714 2715 bool CodeGenModule::MustBeEmitted(const ValueDecl *Global) { 2716 // Never defer when EmitAllDecls is specified. 2717 if (LangOpts.EmitAllDecls) 2718 return true; 2719 2720 if (CodeGenOpts.KeepStaticConsts) { 2721 const auto *VD = dyn_cast<VarDecl>(Global); 2722 if (VD && VD->getType().isConstQualified() && 2723 VD->getStorageDuration() == SD_Static) 2724 return true; 2725 } 2726 2727 return getContext().DeclMustBeEmitted(Global); 2728 } 2729 2730 bool CodeGenModule::MayBeEmittedEagerly(const ValueDecl *Global) { 2731 // In OpenMP 5.0 variables and function may be marked as 2732 // device_type(host/nohost) and we should not emit them eagerly unless we sure 2733 // that they must be emitted on the host/device. To be sure we need to have 2734 // seen a declare target with an explicit mentioning of the function, we know 2735 // we have if the level of the declare target attribute is -1. Note that we 2736 // check somewhere else if we should emit this at all. 2737 if (LangOpts.OpenMP >= 50 && !LangOpts.OpenMPSimd) { 2738 llvm::Optional<OMPDeclareTargetDeclAttr *> ActiveAttr = 2739 OMPDeclareTargetDeclAttr::getActiveAttr(Global); 2740 if (!ActiveAttr || (*ActiveAttr)->getLevel() != (unsigned)-1) 2741 return false; 2742 } 2743 2744 if (const auto *FD = dyn_cast<FunctionDecl>(Global)) { 2745 if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation) 2746 // Implicit template instantiations may change linkage if they are later 2747 // explicitly instantiated, so they should not be emitted eagerly. 2748 return false; 2749 } 2750 if (const auto *VD = dyn_cast<VarDecl>(Global)) 2751 if (Context.getInlineVariableDefinitionKind(VD) == 2752 ASTContext::InlineVariableDefinitionKind::WeakUnknown) 2753 // A definition of an inline constexpr static data member may change 2754 // linkage later if it's redeclared outside the class. 2755 return false; 2756 // If OpenMP is enabled and threadprivates must be generated like TLS, delay 2757 // codegen for global variables, because they may be marked as threadprivate. 2758 if (LangOpts.OpenMP && LangOpts.OpenMPUseTLS && 2759 getContext().getTargetInfo().isTLSSupported() && isa<VarDecl>(Global) && 2760 !isTypeConstant(Global->getType(), false) && 2761 !OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(Global)) 2762 return false; 2763 2764 return true; 2765 } 2766 2767 ConstantAddress CodeGenModule::GetAddrOfMSGuidDecl(const MSGuidDecl *GD) { 2768 StringRef Name = getMangledName(GD); 2769 2770 // The UUID descriptor should be pointer aligned. 2771 CharUnits Alignment = CharUnits::fromQuantity(PointerAlignInBytes); 2772 2773 // Look for an existing global. 2774 if (llvm::GlobalVariable *GV = getModule().getNamedGlobal(Name)) 2775 return ConstantAddress(GV, Alignment); 2776 2777 ConstantEmitter Emitter(*this); 2778 llvm::Constant *Init; 2779 2780 APValue &V = GD->getAsAPValue(); 2781 if (!V.isAbsent()) { 2782 // If possible, emit the APValue version of the initializer. In particular, 2783 // this gets the type of the constant right. 2784 Init = Emitter.emitForInitializer( 2785 GD->getAsAPValue(), GD->getType().getAddressSpace(), GD->getType()); 2786 } else { 2787 // As a fallback, directly construct the constant. 2788 // FIXME: This may get padding wrong under esoteric struct layout rules. 2789 // MSVC appears to create a complete type 'struct __s_GUID' that it 2790 // presumably uses to represent these constants. 2791 MSGuidDecl::Parts Parts = GD->getParts(); 2792 llvm::Constant *Fields[4] = { 2793 llvm::ConstantInt::get(Int32Ty, Parts.Part1), 2794 llvm::ConstantInt::get(Int16Ty, Parts.Part2), 2795 llvm::ConstantInt::get(Int16Ty, Parts.Part3), 2796 llvm::ConstantDataArray::getRaw( 2797 StringRef(reinterpret_cast<char *>(Parts.Part4And5), 8), 8, 2798 Int8Ty)}; 2799 Init = llvm::ConstantStruct::getAnon(Fields); 2800 } 2801 2802 auto *GV = new llvm::GlobalVariable( 2803 getModule(), Init->getType(), 2804 /*isConstant=*/true, llvm::GlobalValue::LinkOnceODRLinkage, Init, Name); 2805 if (supportsCOMDAT()) 2806 GV->setComdat(TheModule.getOrInsertComdat(GV->getName())); 2807 setDSOLocal(GV); 2808 2809 llvm::Constant *Addr = GV; 2810 if (!V.isAbsent()) { 2811 Emitter.finalize(GV); 2812 } else { 2813 llvm::Type *Ty = getTypes().ConvertTypeForMem(GD->getType()); 2814 Addr = llvm::ConstantExpr::getBitCast( 2815 GV, Ty->getPointerTo(GV->getAddressSpace())); 2816 } 2817 return ConstantAddress(Addr, Alignment); 2818 } 2819 2820 ConstantAddress CodeGenModule::GetAddrOfTemplateParamObject( 2821 const TemplateParamObjectDecl *TPO) { 2822 StringRef Name = getMangledName(TPO); 2823 CharUnits Alignment = getNaturalTypeAlignment(TPO->getType()); 2824 2825 if (llvm::GlobalVariable *GV = getModule().getNamedGlobal(Name)) 2826 return ConstantAddress(GV, Alignment); 2827 2828 ConstantEmitter Emitter(*this); 2829 llvm::Constant *Init = Emitter.emitForInitializer( 2830 TPO->getValue(), TPO->getType().getAddressSpace(), TPO->getType()); 2831 2832 if (!Init) { 2833 ErrorUnsupported(TPO, "template parameter object"); 2834 return ConstantAddress::invalid(); 2835 } 2836 2837 auto *GV = new llvm::GlobalVariable( 2838 getModule(), Init->getType(), 2839 /*isConstant=*/true, llvm::GlobalValue::LinkOnceODRLinkage, Init, Name); 2840 if (supportsCOMDAT()) 2841 GV->setComdat(TheModule.getOrInsertComdat(GV->getName())); 2842 Emitter.finalize(GV); 2843 2844 return ConstantAddress(GV, Alignment); 2845 } 2846 2847 ConstantAddress CodeGenModule::GetWeakRefReference(const ValueDecl *VD) { 2848 const AliasAttr *AA = VD->getAttr<AliasAttr>(); 2849 assert(AA && "No alias?"); 2850 2851 CharUnits Alignment = getContext().getDeclAlign(VD); 2852 llvm::Type *DeclTy = getTypes().ConvertTypeForMem(VD->getType()); 2853 2854 // See if there is already something with the target's name in the module. 2855 llvm::GlobalValue *Entry = GetGlobalValue(AA->getAliasee()); 2856 if (Entry) { 2857 unsigned AS = getContext().getTargetAddressSpace(VD->getType()); 2858 auto Ptr = llvm::ConstantExpr::getBitCast(Entry, DeclTy->getPointerTo(AS)); 2859 return ConstantAddress(Ptr, Alignment); 2860 } 2861 2862 llvm::Constant *Aliasee; 2863 if (isa<llvm::FunctionType>(DeclTy)) 2864 Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy, 2865 GlobalDecl(cast<FunctionDecl>(VD)), 2866 /*ForVTable=*/false); 2867 else 2868 Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(), DeclTy, LangAS::Default, 2869 nullptr); 2870 2871 auto *F = cast<llvm::GlobalValue>(Aliasee); 2872 F->setLinkage(llvm::Function::ExternalWeakLinkage); 2873 WeakRefReferences.insert(F); 2874 2875 return ConstantAddress(Aliasee, Alignment); 2876 } 2877 2878 void CodeGenModule::EmitGlobal(GlobalDecl GD) { 2879 const auto *Global = cast<ValueDecl>(GD.getDecl()); 2880 2881 // Weak references don't produce any output by themselves. 2882 if (Global->hasAttr<WeakRefAttr>()) 2883 return; 2884 2885 // If this is an alias definition (which otherwise looks like a declaration) 2886 // emit it now. 2887 if (Global->hasAttr<AliasAttr>()) 2888 return EmitAliasDefinition(GD); 2889 2890 // IFunc like an alias whose value is resolved at runtime by calling resolver. 2891 if (Global->hasAttr<IFuncAttr>()) 2892 return emitIFuncDefinition(GD); 2893 2894 // If this is a cpu_dispatch multiversion function, emit the resolver. 2895 if (Global->hasAttr<CPUDispatchAttr>()) 2896 return emitCPUDispatchDefinition(GD); 2897 2898 // If this is CUDA, be selective about which declarations we emit. 2899 if (LangOpts.CUDA) { 2900 if (LangOpts.CUDAIsDevice) { 2901 if (!Global->hasAttr<CUDADeviceAttr>() && 2902 !Global->hasAttr<CUDAGlobalAttr>() && 2903 !Global->hasAttr<CUDAConstantAttr>() && 2904 !Global->hasAttr<CUDASharedAttr>() && 2905 !Global->getType()->isCUDADeviceBuiltinSurfaceType() && 2906 !Global->getType()->isCUDADeviceBuiltinTextureType()) 2907 return; 2908 } else { 2909 // We need to emit host-side 'shadows' for all global 2910 // device-side variables because the CUDA runtime needs their 2911 // size and host-side address in order to provide access to 2912 // their device-side incarnations. 2913 2914 // So device-only functions are the only things we skip. 2915 if (isa<FunctionDecl>(Global) && !Global->hasAttr<CUDAHostAttr>() && 2916 Global->hasAttr<CUDADeviceAttr>()) 2917 return; 2918 2919 assert((isa<FunctionDecl>(Global) || isa<VarDecl>(Global)) && 2920 "Expected Variable or Function"); 2921 } 2922 } 2923 2924 if (LangOpts.OpenMP) { 2925 // If this is OpenMP, check if it is legal to emit this global normally. 2926 if (OpenMPRuntime && OpenMPRuntime->emitTargetGlobal(GD)) 2927 return; 2928 if (auto *DRD = dyn_cast<OMPDeclareReductionDecl>(Global)) { 2929 if (MustBeEmitted(Global)) 2930 EmitOMPDeclareReduction(DRD); 2931 return; 2932 } else if (auto *DMD = dyn_cast<OMPDeclareMapperDecl>(Global)) { 2933 if (MustBeEmitted(Global)) 2934 EmitOMPDeclareMapper(DMD); 2935 return; 2936 } 2937 } 2938 2939 // Ignore declarations, they will be emitted on their first use. 2940 if (const auto *FD = dyn_cast<FunctionDecl>(Global)) { 2941 // Forward declarations are emitted lazily on first use. 2942 if (!FD->doesThisDeclarationHaveABody()) { 2943 if (!FD->doesDeclarationForceExternallyVisibleDefinition()) 2944 return; 2945 2946 StringRef MangledName = getMangledName(GD); 2947 2948 // Compute the function info and LLVM type. 2949 const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD); 2950 llvm::Type *Ty = getTypes().GetFunctionType(FI); 2951 2952 GetOrCreateLLVMFunction(MangledName, Ty, GD, /*ForVTable=*/false, 2953 /*DontDefer=*/false); 2954 return; 2955 } 2956 } else { 2957 const auto *VD = cast<VarDecl>(Global); 2958 assert(VD->isFileVarDecl() && "Cannot emit local var decl as global."); 2959 if (VD->isThisDeclarationADefinition() != VarDecl::Definition && 2960 !Context.isMSStaticDataMemberInlineDefinition(VD)) { 2961 if (LangOpts.OpenMP) { 2962 // Emit declaration of the must-be-emitted declare target variable. 2963 if (llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res = 2964 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD)) { 2965 bool UnifiedMemoryEnabled = 2966 getOpenMPRuntime().hasRequiresUnifiedSharedMemory(); 2967 if (*Res == OMPDeclareTargetDeclAttr::MT_To && 2968 !UnifiedMemoryEnabled) { 2969 (void)GetAddrOfGlobalVar(VD); 2970 } else { 2971 assert(((*Res == OMPDeclareTargetDeclAttr::MT_Link) || 2972 (*Res == OMPDeclareTargetDeclAttr::MT_To && 2973 UnifiedMemoryEnabled)) && 2974 "Link clause or to clause with unified memory expected."); 2975 (void)getOpenMPRuntime().getAddrOfDeclareTargetVar(VD); 2976 } 2977 2978 return; 2979 } 2980 } 2981 // If this declaration may have caused an inline variable definition to 2982 // change linkage, make sure that it's emitted. 2983 if (Context.getInlineVariableDefinitionKind(VD) == 2984 ASTContext::InlineVariableDefinitionKind::Strong) 2985 GetAddrOfGlobalVar(VD); 2986 return; 2987 } 2988 } 2989 2990 // Defer code generation to first use when possible, e.g. if this is an inline 2991 // function. If the global must always be emitted, do it eagerly if possible 2992 // to benefit from cache locality. 2993 if (MustBeEmitted(Global) && MayBeEmittedEagerly(Global)) { 2994 // Emit the definition if it can't be deferred. 2995 EmitGlobalDefinition(GD); 2996 return; 2997 } 2998 2999 // If we're deferring emission of a C++ variable with an 3000 // initializer, remember the order in which it appeared in the file. 3001 if (getLangOpts().CPlusPlus && isa<VarDecl>(Global) && 3002 cast<VarDecl>(Global)->hasInit()) { 3003 DelayedCXXInitPosition[Global] = CXXGlobalInits.size(); 3004 CXXGlobalInits.push_back(nullptr); 3005 } 3006 3007 StringRef MangledName = getMangledName(GD); 3008 if (GetGlobalValue(MangledName) != nullptr) { 3009 // The value has already been used and should therefore be emitted. 3010 addDeferredDeclToEmit(GD); 3011 } else if (MustBeEmitted(Global)) { 3012 // The value must be emitted, but cannot be emitted eagerly. 3013 assert(!MayBeEmittedEagerly(Global)); 3014 addDeferredDeclToEmit(GD); 3015 } else { 3016 // Otherwise, remember that we saw a deferred decl with this name. The 3017 // first use of the mangled name will cause it to move into 3018 // DeferredDeclsToEmit. 3019 DeferredDecls[MangledName] = GD; 3020 } 3021 } 3022 3023 // Check if T is a class type with a destructor that's not dllimport. 3024 static bool HasNonDllImportDtor(QualType T) { 3025 if (const auto *RT = T->getBaseElementTypeUnsafe()->getAs<RecordType>()) 3026 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl())) 3027 if (RD->getDestructor() && !RD->getDestructor()->hasAttr<DLLImportAttr>()) 3028 return true; 3029 3030 return false; 3031 } 3032 3033 namespace { 3034 struct FunctionIsDirectlyRecursive 3035 : public ConstStmtVisitor<FunctionIsDirectlyRecursive, bool> { 3036 const StringRef Name; 3037 const Builtin::Context &BI; 3038 FunctionIsDirectlyRecursive(StringRef N, const Builtin::Context &C) 3039 : Name(N), BI(C) {} 3040 3041 bool VisitCallExpr(const CallExpr *E) { 3042 const FunctionDecl *FD = E->getDirectCallee(); 3043 if (!FD) 3044 return false; 3045 AsmLabelAttr *Attr = FD->getAttr<AsmLabelAttr>(); 3046 if (Attr && Name == Attr->getLabel()) 3047 return true; 3048 unsigned BuiltinID = FD->getBuiltinID(); 3049 if (!BuiltinID || !BI.isLibFunction(BuiltinID)) 3050 return false; 3051 StringRef BuiltinName = BI.getName(BuiltinID); 3052 if (BuiltinName.startswith("__builtin_") && 3053 Name == BuiltinName.slice(strlen("__builtin_"), StringRef::npos)) { 3054 return true; 3055 } 3056 return false; 3057 } 3058 3059 bool VisitStmt(const Stmt *S) { 3060 for (const Stmt *Child : S->children()) 3061 if (Child && this->Visit(Child)) 3062 return true; 3063 return false; 3064 } 3065 }; 3066 3067 // Make sure we're not referencing non-imported vars or functions. 3068 struct DLLImportFunctionVisitor 3069 : public RecursiveASTVisitor<DLLImportFunctionVisitor> { 3070 bool SafeToInline = true; 3071 3072 bool shouldVisitImplicitCode() const { return true; } 3073 3074 bool VisitVarDecl(VarDecl *VD) { 3075 if (VD->getTLSKind()) { 3076 // A thread-local variable cannot be imported. 3077 SafeToInline = false; 3078 return SafeToInline; 3079 } 3080 3081 // A variable definition might imply a destructor call. 3082 if (VD->isThisDeclarationADefinition()) 3083 SafeToInline = !HasNonDllImportDtor(VD->getType()); 3084 3085 return SafeToInline; 3086 } 3087 3088 bool VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) { 3089 if (const auto *D = E->getTemporary()->getDestructor()) 3090 SafeToInline = D->hasAttr<DLLImportAttr>(); 3091 return SafeToInline; 3092 } 3093 3094 bool VisitDeclRefExpr(DeclRefExpr *E) { 3095 ValueDecl *VD = E->getDecl(); 3096 if (isa<FunctionDecl>(VD)) 3097 SafeToInline = VD->hasAttr<DLLImportAttr>(); 3098 else if (VarDecl *V = dyn_cast<VarDecl>(VD)) 3099 SafeToInline = !V->hasGlobalStorage() || V->hasAttr<DLLImportAttr>(); 3100 return SafeToInline; 3101 } 3102 3103 bool VisitCXXConstructExpr(CXXConstructExpr *E) { 3104 SafeToInline = E->getConstructor()->hasAttr<DLLImportAttr>(); 3105 return SafeToInline; 3106 } 3107 3108 bool VisitCXXMemberCallExpr(CXXMemberCallExpr *E) { 3109 CXXMethodDecl *M = E->getMethodDecl(); 3110 if (!M) { 3111 // Call through a pointer to member function. This is safe to inline. 3112 SafeToInline = true; 3113 } else { 3114 SafeToInline = M->hasAttr<DLLImportAttr>(); 3115 } 3116 return SafeToInline; 3117 } 3118 3119 bool VisitCXXDeleteExpr(CXXDeleteExpr *E) { 3120 SafeToInline = E->getOperatorDelete()->hasAttr<DLLImportAttr>(); 3121 return SafeToInline; 3122 } 3123 3124 bool VisitCXXNewExpr(CXXNewExpr *E) { 3125 SafeToInline = E->getOperatorNew()->hasAttr<DLLImportAttr>(); 3126 return SafeToInline; 3127 } 3128 }; 3129 } 3130 3131 // isTriviallyRecursive - Check if this function calls another 3132 // decl that, because of the asm attribute or the other decl being a builtin, 3133 // ends up pointing to itself. 3134 bool 3135 CodeGenModule::isTriviallyRecursive(const FunctionDecl *FD) { 3136 StringRef Name; 3137 if (getCXXABI().getMangleContext().shouldMangleDeclName(FD)) { 3138 // asm labels are a special kind of mangling we have to support. 3139 AsmLabelAttr *Attr = FD->getAttr<AsmLabelAttr>(); 3140 if (!Attr) 3141 return false; 3142 Name = Attr->getLabel(); 3143 } else { 3144 Name = FD->getName(); 3145 } 3146 3147 FunctionIsDirectlyRecursive Walker(Name, Context.BuiltinInfo); 3148 const Stmt *Body = FD->getBody(); 3149 return Body ? Walker.Visit(Body) : false; 3150 } 3151 3152 bool CodeGenModule::shouldEmitFunction(GlobalDecl GD) { 3153 if (getFunctionLinkage(GD) != llvm::Function::AvailableExternallyLinkage) 3154 return true; 3155 const auto *F = cast<FunctionDecl>(GD.getDecl()); 3156 if (CodeGenOpts.OptimizationLevel == 0 && !F->hasAttr<AlwaysInlineAttr>()) 3157 return false; 3158 3159 if (F->hasAttr<DLLImportAttr>() && !F->hasAttr<AlwaysInlineAttr>()) { 3160 // Check whether it would be safe to inline this dllimport function. 3161 DLLImportFunctionVisitor Visitor; 3162 Visitor.TraverseFunctionDecl(const_cast<FunctionDecl*>(F)); 3163 if (!Visitor.SafeToInline) 3164 return false; 3165 3166 if (const CXXDestructorDecl *Dtor = dyn_cast<CXXDestructorDecl>(F)) { 3167 // Implicit destructor invocations aren't captured in the AST, so the 3168 // check above can't see them. Check for them manually here. 3169 for (const Decl *Member : Dtor->getParent()->decls()) 3170 if (isa<FieldDecl>(Member)) 3171 if (HasNonDllImportDtor(cast<FieldDecl>(Member)->getType())) 3172 return false; 3173 for (const CXXBaseSpecifier &B : Dtor->getParent()->bases()) 3174 if (HasNonDllImportDtor(B.getType())) 3175 return false; 3176 } 3177 } 3178 3179 // Inline builtins declaration must be emitted. They often are fortified 3180 // functions. 3181 if (F->isInlineBuiltinDeclaration()) 3182 return true; 3183 3184 // PR9614. Avoid cases where the source code is lying to us. An available 3185 // externally function should have an equivalent function somewhere else, 3186 // but a function that calls itself through asm label/`__builtin_` trickery is 3187 // clearly not equivalent to the real implementation. 3188 // This happens in glibc's btowc and in some configure checks. 3189 return !isTriviallyRecursive(F); 3190 } 3191 3192 bool CodeGenModule::shouldOpportunisticallyEmitVTables() { 3193 return CodeGenOpts.OptimizationLevel > 0; 3194 } 3195 3196 void CodeGenModule::EmitMultiVersionFunctionDefinition(GlobalDecl GD, 3197 llvm::GlobalValue *GV) { 3198 const auto *FD = cast<FunctionDecl>(GD.getDecl()); 3199 3200 if (FD->isCPUSpecificMultiVersion()) { 3201 auto *Spec = FD->getAttr<CPUSpecificAttr>(); 3202 for (unsigned I = 0; I < Spec->cpus_size(); ++I) 3203 EmitGlobalFunctionDefinition(GD.getWithMultiVersionIndex(I), nullptr); 3204 // Requires multiple emits. 3205 } else 3206 EmitGlobalFunctionDefinition(GD, GV); 3207 } 3208 3209 void CodeGenModule::EmitGlobalDefinition(GlobalDecl GD, llvm::GlobalValue *GV) { 3210 const auto *D = cast<ValueDecl>(GD.getDecl()); 3211 3212 PrettyStackTraceDecl CrashInfo(const_cast<ValueDecl *>(D), D->getLocation(), 3213 Context.getSourceManager(), 3214 "Generating code for declaration"); 3215 3216 if (const auto *FD = dyn_cast<FunctionDecl>(D)) { 3217 // At -O0, don't generate IR for functions with available_externally 3218 // linkage. 3219 if (!shouldEmitFunction(GD)) 3220 return; 3221 3222 llvm::TimeTraceScope TimeScope("CodeGen Function", [&]() { 3223 std::string Name; 3224 llvm::raw_string_ostream OS(Name); 3225 FD->getNameForDiagnostic(OS, getContext().getPrintingPolicy(), 3226 /*Qualified=*/true); 3227 return Name; 3228 }); 3229 3230 if (const auto *Method = dyn_cast<CXXMethodDecl>(D)) { 3231 // Make sure to emit the definition(s) before we emit the thunks. 3232 // This is necessary for the generation of certain thunks. 3233 if (isa<CXXConstructorDecl>(Method) || isa<CXXDestructorDecl>(Method)) 3234 ABI->emitCXXStructor(GD); 3235 else if (FD->isMultiVersion()) 3236 EmitMultiVersionFunctionDefinition(GD, GV); 3237 else 3238 EmitGlobalFunctionDefinition(GD, GV); 3239 3240 if (Method->isVirtual()) 3241 getVTables().EmitThunks(GD); 3242 3243 return; 3244 } 3245 3246 if (FD->isMultiVersion()) 3247 return EmitMultiVersionFunctionDefinition(GD, GV); 3248 return EmitGlobalFunctionDefinition(GD, GV); 3249 } 3250 3251 if (const auto *VD = dyn_cast<VarDecl>(D)) 3252 return EmitGlobalVarDefinition(VD, !VD->hasDefinition()); 3253 3254 llvm_unreachable("Invalid argument to EmitGlobalDefinition()"); 3255 } 3256 3257 static void ReplaceUsesOfNonProtoTypeWithRealFunction(llvm::GlobalValue *Old, 3258 llvm::Function *NewFn); 3259 3260 static unsigned 3261 TargetMVPriority(const TargetInfo &TI, 3262 const CodeGenFunction::MultiVersionResolverOption &RO) { 3263 unsigned Priority = 0; 3264 for (StringRef Feat : RO.Conditions.Features) 3265 Priority = std::max(Priority, TI.multiVersionSortPriority(Feat)); 3266 3267 if (!RO.Conditions.Architecture.empty()) 3268 Priority = std::max( 3269 Priority, TI.multiVersionSortPriority(RO.Conditions.Architecture)); 3270 return Priority; 3271 } 3272 3273 // Multiversion functions should be at most 'WeakODRLinkage' so that a different 3274 // TU can forward declare the function without causing problems. Particularly 3275 // in the cases of CPUDispatch, this causes issues. This also makes sure we 3276 // work with internal linkage functions, so that the same function name can be 3277 // used with internal linkage in multiple TUs. 3278 llvm::GlobalValue::LinkageTypes getMultiversionLinkage(CodeGenModule &CGM, 3279 GlobalDecl GD) { 3280 const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl()); 3281 if (FD->getFormalLinkage() == InternalLinkage) 3282 return llvm::GlobalValue::InternalLinkage; 3283 return llvm::GlobalValue::WeakODRLinkage; 3284 } 3285 3286 void CodeGenModule::emitMultiVersionFunctions() { 3287 std::vector<GlobalDecl> MVFuncsToEmit; 3288 MultiVersionFuncs.swap(MVFuncsToEmit); 3289 for (GlobalDecl GD : MVFuncsToEmit) { 3290 SmallVector<CodeGenFunction::MultiVersionResolverOption, 10> Options; 3291 const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl()); 3292 getContext().forEachMultiversionedFunctionVersion( 3293 FD, [this, &GD, &Options](const FunctionDecl *CurFD) { 3294 GlobalDecl CurGD{ 3295 (CurFD->isDefined() ? CurFD->getDefinition() : CurFD)}; 3296 StringRef MangledName = getMangledName(CurGD); 3297 llvm::Constant *Func = GetGlobalValue(MangledName); 3298 if (!Func) { 3299 if (CurFD->isDefined()) { 3300 EmitGlobalFunctionDefinition(CurGD, nullptr); 3301 Func = GetGlobalValue(MangledName); 3302 } else { 3303 const CGFunctionInfo &FI = 3304 getTypes().arrangeGlobalDeclaration(GD); 3305 llvm::FunctionType *Ty = getTypes().GetFunctionType(FI); 3306 Func = GetAddrOfFunction(CurGD, Ty, /*ForVTable=*/false, 3307 /*DontDefer=*/false, ForDefinition); 3308 } 3309 assert(Func && "This should have just been created"); 3310 } 3311 3312 const auto *TA = CurFD->getAttr<TargetAttr>(); 3313 llvm::SmallVector<StringRef, 8> Feats; 3314 TA->getAddedFeatures(Feats); 3315 3316 Options.emplace_back(cast<llvm::Function>(Func), 3317 TA->getArchitecture(), Feats); 3318 }); 3319 3320 llvm::Function *ResolverFunc; 3321 const TargetInfo &TI = getTarget(); 3322 3323 if (TI.supportsIFunc() || FD->isTargetMultiVersion()) { 3324 ResolverFunc = cast<llvm::Function>( 3325 GetGlobalValue((getMangledName(GD) + ".resolver").str())); 3326 ResolverFunc->setLinkage(getMultiversionLinkage(*this, GD)); 3327 } else { 3328 ResolverFunc = cast<llvm::Function>(GetGlobalValue(getMangledName(GD))); 3329 } 3330 3331 if (supportsCOMDAT()) 3332 ResolverFunc->setComdat( 3333 getModule().getOrInsertComdat(ResolverFunc->getName())); 3334 3335 llvm::stable_sort( 3336 Options, [&TI](const CodeGenFunction::MultiVersionResolverOption &LHS, 3337 const CodeGenFunction::MultiVersionResolverOption &RHS) { 3338 return TargetMVPriority(TI, LHS) > TargetMVPriority(TI, RHS); 3339 }); 3340 CodeGenFunction CGF(*this); 3341 CGF.EmitMultiVersionResolver(ResolverFunc, Options); 3342 } 3343 3344 // Ensure that any additions to the deferred decls list caused by emitting a 3345 // variant are emitted. This can happen when the variant itself is inline and 3346 // calls a function without linkage. 3347 if (!MVFuncsToEmit.empty()) 3348 EmitDeferred(); 3349 3350 // Ensure that any additions to the multiversion funcs list from either the 3351 // deferred decls or the multiversion functions themselves are emitted. 3352 if (!MultiVersionFuncs.empty()) 3353 emitMultiVersionFunctions(); 3354 } 3355 3356 void CodeGenModule::emitCPUDispatchDefinition(GlobalDecl GD) { 3357 const auto *FD = cast<FunctionDecl>(GD.getDecl()); 3358 assert(FD && "Not a FunctionDecl?"); 3359 const auto *DD = FD->getAttr<CPUDispatchAttr>(); 3360 assert(DD && "Not a cpu_dispatch Function?"); 3361 llvm::Type *DeclTy = getTypes().ConvertType(FD->getType()); 3362 3363 if (const auto *CXXFD = dyn_cast<CXXMethodDecl>(FD)) { 3364 const CGFunctionInfo &FInfo = getTypes().arrangeCXXMethodDeclaration(CXXFD); 3365 DeclTy = getTypes().GetFunctionType(FInfo); 3366 } 3367 3368 StringRef ResolverName = getMangledName(GD); 3369 3370 llvm::Type *ResolverType; 3371 GlobalDecl ResolverGD; 3372 if (getTarget().supportsIFunc()) 3373 ResolverType = llvm::FunctionType::get( 3374 llvm::PointerType::get(DeclTy, 3375 Context.getTargetAddressSpace(FD->getType())), 3376 false); 3377 else { 3378 ResolverType = DeclTy; 3379 ResolverGD = GD; 3380 } 3381 3382 auto *ResolverFunc = cast<llvm::Function>(GetOrCreateLLVMFunction( 3383 ResolverName, ResolverType, ResolverGD, /*ForVTable=*/false)); 3384 ResolverFunc->setLinkage(getMultiversionLinkage(*this, GD)); 3385 if (supportsCOMDAT()) 3386 ResolverFunc->setComdat( 3387 getModule().getOrInsertComdat(ResolverFunc->getName())); 3388 3389 SmallVector<CodeGenFunction::MultiVersionResolverOption, 10> Options; 3390 const TargetInfo &Target = getTarget(); 3391 unsigned Index = 0; 3392 for (const IdentifierInfo *II : DD->cpus()) { 3393 // Get the name of the target function so we can look it up/create it. 3394 std::string MangledName = getMangledNameImpl(*this, GD, FD, true) + 3395 getCPUSpecificMangling(*this, II->getName()); 3396 3397 llvm::Constant *Func = GetGlobalValue(MangledName); 3398 3399 if (!Func) { 3400 GlobalDecl ExistingDecl = Manglings.lookup(MangledName); 3401 if (ExistingDecl.getDecl() && 3402 ExistingDecl.getDecl()->getAsFunction()->isDefined()) { 3403 EmitGlobalFunctionDefinition(ExistingDecl, nullptr); 3404 Func = GetGlobalValue(MangledName); 3405 } else { 3406 if (!ExistingDecl.getDecl()) 3407 ExistingDecl = GD.getWithMultiVersionIndex(Index); 3408 3409 Func = GetOrCreateLLVMFunction( 3410 MangledName, DeclTy, ExistingDecl, 3411 /*ForVTable=*/false, /*DontDefer=*/true, 3412 /*IsThunk=*/false, llvm::AttributeList(), ForDefinition); 3413 } 3414 } 3415 3416 llvm::SmallVector<StringRef, 32> Features; 3417 Target.getCPUSpecificCPUDispatchFeatures(II->getName(), Features); 3418 llvm::transform(Features, Features.begin(), 3419 [](StringRef Str) { return Str.substr(1); }); 3420 Features.erase(std::remove_if( 3421 Features.begin(), Features.end(), [&Target](StringRef Feat) { 3422 return !Target.validateCpuSupports(Feat); 3423 }), Features.end()); 3424 Options.emplace_back(cast<llvm::Function>(Func), StringRef{}, Features); 3425 ++Index; 3426 } 3427 3428 llvm::stable_sort( 3429 Options, [](const CodeGenFunction::MultiVersionResolverOption &LHS, 3430 const CodeGenFunction::MultiVersionResolverOption &RHS) { 3431 return llvm::X86::getCpuSupportsMask(LHS.Conditions.Features) > 3432 llvm::X86::getCpuSupportsMask(RHS.Conditions.Features); 3433 }); 3434 3435 // If the list contains multiple 'default' versions, such as when it contains 3436 // 'pentium' and 'generic', don't emit the call to the generic one (since we 3437 // always run on at least a 'pentium'). We do this by deleting the 'least 3438 // advanced' (read, lowest mangling letter). 3439 while (Options.size() > 1 && 3440 llvm::X86::getCpuSupportsMask( 3441 (Options.end() - 2)->Conditions.Features) == 0) { 3442 StringRef LHSName = (Options.end() - 2)->Function->getName(); 3443 StringRef RHSName = (Options.end() - 1)->Function->getName(); 3444 if (LHSName.compare(RHSName) < 0) 3445 Options.erase(Options.end() - 2); 3446 else 3447 Options.erase(Options.end() - 1); 3448 } 3449 3450 CodeGenFunction CGF(*this); 3451 CGF.EmitMultiVersionResolver(ResolverFunc, Options); 3452 3453 if (getTarget().supportsIFunc()) { 3454 std::string AliasName = getMangledNameImpl( 3455 *this, GD, FD, /*OmitMultiVersionMangling=*/true); 3456 llvm::Constant *AliasFunc = GetGlobalValue(AliasName); 3457 if (!AliasFunc) { 3458 auto *IFunc = cast<llvm::GlobalIFunc>(GetOrCreateLLVMFunction( 3459 AliasName, DeclTy, GD, /*ForVTable=*/false, /*DontDefer=*/true, 3460 /*IsThunk=*/false, llvm::AttributeList(), NotForDefinition)); 3461 auto *GA = llvm::GlobalAlias::create(DeclTy, 0, 3462 getMultiversionLinkage(*this, GD), 3463 AliasName, IFunc, &getModule()); 3464 SetCommonAttributes(GD, GA); 3465 } 3466 } 3467 } 3468 3469 /// If a dispatcher for the specified mangled name is not in the module, create 3470 /// and return an llvm Function with the specified type. 3471 llvm::Constant *CodeGenModule::GetOrCreateMultiVersionResolver( 3472 GlobalDecl GD, llvm::Type *DeclTy, const FunctionDecl *FD) { 3473 std::string MangledName = 3474 getMangledNameImpl(*this, GD, FD, /*OmitMultiVersionMangling=*/true); 3475 3476 // Holds the name of the resolver, in ifunc mode this is the ifunc (which has 3477 // a separate resolver). 3478 std::string ResolverName = MangledName; 3479 if (getTarget().supportsIFunc()) 3480 ResolverName += ".ifunc"; 3481 else if (FD->isTargetMultiVersion()) 3482 ResolverName += ".resolver"; 3483 3484 // If this already exists, just return that one. 3485 if (llvm::GlobalValue *ResolverGV = GetGlobalValue(ResolverName)) 3486 return ResolverGV; 3487 3488 // Since this is the first time we've created this IFunc, make sure 3489 // that we put this multiversioned function into the list to be 3490 // replaced later if necessary (target multiversioning only). 3491 if (!FD->isCPUDispatchMultiVersion() && !FD->isCPUSpecificMultiVersion()) 3492 MultiVersionFuncs.push_back(GD); 3493 3494 if (getTarget().supportsIFunc()) { 3495 llvm::Type *ResolverType = llvm::FunctionType::get( 3496 llvm::PointerType::get( 3497 DeclTy, getContext().getTargetAddressSpace(FD->getType())), 3498 false); 3499 llvm::Constant *Resolver = GetOrCreateLLVMFunction( 3500 MangledName + ".resolver", ResolverType, GlobalDecl{}, 3501 /*ForVTable=*/false); 3502 llvm::GlobalIFunc *GIF = 3503 llvm::GlobalIFunc::create(DeclTy, 0, getMultiversionLinkage(*this, GD), 3504 "", Resolver, &getModule()); 3505 GIF->setName(ResolverName); 3506 SetCommonAttributes(FD, GIF); 3507 3508 return GIF; 3509 } 3510 3511 llvm::Constant *Resolver = GetOrCreateLLVMFunction( 3512 ResolverName, DeclTy, GlobalDecl{}, /*ForVTable=*/false); 3513 assert(isa<llvm::GlobalValue>(Resolver) && 3514 "Resolver should be created for the first time"); 3515 SetCommonAttributes(FD, cast<llvm::GlobalValue>(Resolver)); 3516 return Resolver; 3517 } 3518 3519 /// GetOrCreateLLVMFunction - If the specified mangled name is not in the 3520 /// module, create and return an llvm Function with the specified type. If there 3521 /// is something in the module with the specified name, return it potentially 3522 /// bitcasted to the right type. 3523 /// 3524 /// If D is non-null, it specifies a decl that correspond to this. This is used 3525 /// to set the attributes on the function when it is first created. 3526 llvm::Constant *CodeGenModule::GetOrCreateLLVMFunction( 3527 StringRef MangledName, llvm::Type *Ty, GlobalDecl GD, bool ForVTable, 3528 bool DontDefer, bool IsThunk, llvm::AttributeList ExtraAttrs, 3529 ForDefinition_t IsForDefinition) { 3530 const Decl *D = GD.getDecl(); 3531 3532 // Any attempts to use a MultiVersion function should result in retrieving 3533 // the iFunc instead. Name Mangling will handle the rest of the changes. 3534 if (const FunctionDecl *FD = cast_or_null<FunctionDecl>(D)) { 3535 // For the device mark the function as one that should be emitted. 3536 if (getLangOpts().OpenMPIsDevice && OpenMPRuntime && 3537 !OpenMPRuntime->markAsGlobalTarget(GD) && FD->isDefined() && 3538 !DontDefer && !IsForDefinition) { 3539 if (const FunctionDecl *FDDef = FD->getDefinition()) { 3540 GlobalDecl GDDef; 3541 if (const auto *CD = dyn_cast<CXXConstructorDecl>(FDDef)) 3542 GDDef = GlobalDecl(CD, GD.getCtorType()); 3543 else if (const auto *DD = dyn_cast<CXXDestructorDecl>(FDDef)) 3544 GDDef = GlobalDecl(DD, GD.getDtorType()); 3545 else 3546 GDDef = GlobalDecl(FDDef); 3547 EmitGlobal(GDDef); 3548 } 3549 } 3550 3551 if (FD->isMultiVersion()) { 3552 if (FD->hasAttr<TargetAttr>()) 3553 UpdateMultiVersionNames(GD, FD); 3554 if (!IsForDefinition) 3555 return GetOrCreateMultiVersionResolver(GD, Ty, FD); 3556 } 3557 } 3558 3559 // Lookup the entry, lazily creating it if necessary. 3560 llvm::GlobalValue *Entry = GetGlobalValue(MangledName); 3561 if (Entry) { 3562 if (WeakRefReferences.erase(Entry)) { 3563 const FunctionDecl *FD = cast_or_null<FunctionDecl>(D); 3564 if (FD && !FD->hasAttr<WeakAttr>()) 3565 Entry->setLinkage(llvm::Function::ExternalLinkage); 3566 } 3567 3568 // Handle dropped DLL attributes. 3569 if (D && !D->hasAttr<DLLImportAttr>() && !D->hasAttr<DLLExportAttr>()) { 3570 Entry->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass); 3571 setDSOLocal(Entry); 3572 } 3573 3574 // If there are two attempts to define the same mangled name, issue an 3575 // error. 3576 if (IsForDefinition && !Entry->isDeclaration()) { 3577 GlobalDecl OtherGD; 3578 // Check that GD is not yet in DiagnosedConflictingDefinitions is required 3579 // to make sure that we issue an error only once. 3580 if (lookupRepresentativeDecl(MangledName, OtherGD) && 3581 (GD.getCanonicalDecl().getDecl() != 3582 OtherGD.getCanonicalDecl().getDecl()) && 3583 DiagnosedConflictingDefinitions.insert(GD).second) { 3584 getDiags().Report(D->getLocation(), diag::err_duplicate_mangled_name) 3585 << MangledName; 3586 getDiags().Report(OtherGD.getDecl()->getLocation(), 3587 diag::note_previous_definition); 3588 } 3589 } 3590 3591 if ((isa<llvm::Function>(Entry) || isa<llvm::GlobalAlias>(Entry)) && 3592 (Entry->getValueType() == Ty)) { 3593 return Entry; 3594 } 3595 3596 // Make sure the result is of the correct type. 3597 // (If function is requested for a definition, we always need to create a new 3598 // function, not just return a bitcast.) 3599 if (!IsForDefinition) 3600 return llvm::ConstantExpr::getBitCast(Entry, Ty->getPointerTo()); 3601 } 3602 3603 // This function doesn't have a complete type (for example, the return 3604 // type is an incomplete struct). Use a fake type instead, and make 3605 // sure not to try to set attributes. 3606 bool IsIncompleteFunction = false; 3607 3608 llvm::FunctionType *FTy; 3609 if (isa<llvm::FunctionType>(Ty)) { 3610 FTy = cast<llvm::FunctionType>(Ty); 3611 } else { 3612 FTy = llvm::FunctionType::get(VoidTy, false); 3613 IsIncompleteFunction = true; 3614 } 3615 3616 llvm::Function *F = 3617 llvm::Function::Create(FTy, llvm::Function::ExternalLinkage, 3618 Entry ? StringRef() : MangledName, &getModule()); 3619 3620 // If we already created a function with the same mangled name (but different 3621 // type) before, take its name and add it to the list of functions to be 3622 // replaced with F at the end of CodeGen. 3623 // 3624 // This happens if there is a prototype for a function (e.g. "int f()") and 3625 // then a definition of a different type (e.g. "int f(int x)"). 3626 if (Entry) { 3627 F->takeName(Entry); 3628 3629 // This might be an implementation of a function without a prototype, in 3630 // which case, try to do special replacement of calls which match the new 3631 // prototype. The really key thing here is that we also potentially drop 3632 // arguments from the call site so as to make a direct call, which makes the 3633 // inliner happier and suppresses a number of optimizer warnings (!) about 3634 // dropping arguments. 3635 if (!Entry->use_empty()) { 3636 ReplaceUsesOfNonProtoTypeWithRealFunction(Entry, F); 3637 Entry->removeDeadConstantUsers(); 3638 } 3639 3640 llvm::Constant *BC = llvm::ConstantExpr::getBitCast( 3641 F, Entry->getValueType()->getPointerTo()); 3642 addGlobalValReplacement(Entry, BC); 3643 } 3644 3645 assert(F->getName() == MangledName && "name was uniqued!"); 3646 if (D) 3647 SetFunctionAttributes(GD, F, IsIncompleteFunction, IsThunk); 3648 if (ExtraAttrs.hasFnAttrs()) { 3649 llvm::AttrBuilder B(ExtraAttrs, llvm::AttributeList::FunctionIndex); 3650 F->addFnAttrs(B); 3651 } 3652 3653 if (!DontDefer) { 3654 // All MSVC dtors other than the base dtor are linkonce_odr and delegate to 3655 // each other bottoming out with the base dtor. Therefore we emit non-base 3656 // dtors on usage, even if there is no dtor definition in the TU. 3657 if (D && isa<CXXDestructorDecl>(D) && 3658 getCXXABI().useThunkForDtorVariant(cast<CXXDestructorDecl>(D), 3659 GD.getDtorType())) 3660 addDeferredDeclToEmit(GD); 3661 3662 // This is the first use or definition of a mangled name. If there is a 3663 // deferred decl with this name, remember that we need to emit it at the end 3664 // of the file. 3665 auto DDI = DeferredDecls.find(MangledName); 3666 if (DDI != DeferredDecls.end()) { 3667 // Move the potentially referenced deferred decl to the 3668 // DeferredDeclsToEmit list, and remove it from DeferredDecls (since we 3669 // don't need it anymore). 3670 addDeferredDeclToEmit(DDI->second); 3671 DeferredDecls.erase(DDI); 3672 3673 // Otherwise, there are cases we have to worry about where we're 3674 // using a declaration for which we must emit a definition but where 3675 // we might not find a top-level definition: 3676 // - member functions defined inline in their classes 3677 // - friend functions defined inline in some class 3678 // - special member functions with implicit definitions 3679 // If we ever change our AST traversal to walk into class methods, 3680 // this will be unnecessary. 3681 // 3682 // We also don't emit a definition for a function if it's going to be an 3683 // entry in a vtable, unless it's already marked as used. 3684 } else if (getLangOpts().CPlusPlus && D) { 3685 // Look for a declaration that's lexically in a record. 3686 for (const auto *FD = cast<FunctionDecl>(D)->getMostRecentDecl(); FD; 3687 FD = FD->getPreviousDecl()) { 3688 if (isa<CXXRecordDecl>(FD->getLexicalDeclContext())) { 3689 if (FD->doesThisDeclarationHaveABody()) { 3690 addDeferredDeclToEmit(GD.getWithDecl(FD)); 3691 break; 3692 } 3693 } 3694 } 3695 } 3696 } 3697 3698 // Make sure the result is of the requested type. 3699 if (!IsIncompleteFunction) { 3700 assert(F->getFunctionType() == Ty); 3701 return F; 3702 } 3703 3704 llvm::Type *PTy = llvm::PointerType::getUnqual(Ty); 3705 return llvm::ConstantExpr::getBitCast(F, PTy); 3706 } 3707 3708 /// GetAddrOfFunction - Return the address of the given function. If Ty is 3709 /// non-null, then this function will use the specified type if it has to 3710 /// create it (this occurs when we see a definition of the function). 3711 llvm::Constant *CodeGenModule::GetAddrOfFunction(GlobalDecl GD, 3712 llvm::Type *Ty, 3713 bool ForVTable, 3714 bool DontDefer, 3715 ForDefinition_t IsForDefinition) { 3716 assert(!cast<FunctionDecl>(GD.getDecl())->isConsteval() && 3717 "consteval function should never be emitted"); 3718 // If there was no specific requested type, just convert it now. 3719 if (!Ty) { 3720 const auto *FD = cast<FunctionDecl>(GD.getDecl()); 3721 Ty = getTypes().ConvertType(FD->getType()); 3722 } 3723 3724 // Devirtualized destructor calls may come through here instead of via 3725 // getAddrOfCXXStructor. Make sure we use the MS ABI base destructor instead 3726 // of the complete destructor when necessary. 3727 if (const auto *DD = dyn_cast<CXXDestructorDecl>(GD.getDecl())) { 3728 if (getTarget().getCXXABI().isMicrosoft() && 3729 GD.getDtorType() == Dtor_Complete && 3730 DD->getParent()->getNumVBases() == 0) 3731 GD = GlobalDecl(DD, Dtor_Base); 3732 } 3733 3734 StringRef MangledName = getMangledName(GD); 3735 auto *F = GetOrCreateLLVMFunction(MangledName, Ty, GD, ForVTable, DontDefer, 3736 /*IsThunk=*/false, llvm::AttributeList(), 3737 IsForDefinition); 3738 // Returns kernel handle for HIP kernel stub function. 3739 if (LangOpts.CUDA && !LangOpts.CUDAIsDevice && 3740 cast<FunctionDecl>(GD.getDecl())->hasAttr<CUDAGlobalAttr>()) { 3741 auto *Handle = getCUDARuntime().getKernelHandle( 3742 cast<llvm::Function>(F->stripPointerCasts()), GD); 3743 if (IsForDefinition) 3744 return F; 3745 return llvm::ConstantExpr::getBitCast(Handle, Ty->getPointerTo()); 3746 } 3747 return F; 3748 } 3749 3750 static const FunctionDecl * 3751 GetRuntimeFunctionDecl(ASTContext &C, StringRef Name) { 3752 TranslationUnitDecl *TUDecl = C.getTranslationUnitDecl(); 3753 DeclContext *DC = TranslationUnitDecl::castToDeclContext(TUDecl); 3754 3755 IdentifierInfo &CII = C.Idents.get(Name); 3756 for (const auto *Result : DC->lookup(&CII)) 3757 if (const auto *FD = dyn_cast<FunctionDecl>(Result)) 3758 return FD; 3759 3760 if (!C.getLangOpts().CPlusPlus) 3761 return nullptr; 3762 3763 // Demangle the premangled name from getTerminateFn() 3764 IdentifierInfo &CXXII = 3765 (Name == "_ZSt9terminatev" || Name == "?terminate@@YAXXZ") 3766 ? C.Idents.get("terminate") 3767 : C.Idents.get(Name); 3768 3769 for (const auto &N : {"__cxxabiv1", "std"}) { 3770 IdentifierInfo &NS = C.Idents.get(N); 3771 for (const auto *Result : DC->lookup(&NS)) { 3772 const NamespaceDecl *ND = dyn_cast<NamespaceDecl>(Result); 3773 if (auto *LSD = dyn_cast<LinkageSpecDecl>(Result)) 3774 for (const auto *Result : LSD->lookup(&NS)) 3775 if ((ND = dyn_cast<NamespaceDecl>(Result))) 3776 break; 3777 3778 if (ND) 3779 for (const auto *Result : ND->lookup(&CXXII)) 3780 if (const auto *FD = dyn_cast<FunctionDecl>(Result)) 3781 return FD; 3782 } 3783 } 3784 3785 return nullptr; 3786 } 3787 3788 /// CreateRuntimeFunction - Create a new runtime function with the specified 3789 /// type and name. 3790 llvm::FunctionCallee 3791 CodeGenModule::CreateRuntimeFunction(llvm::FunctionType *FTy, StringRef Name, 3792 llvm::AttributeList ExtraAttrs, bool Local, 3793 bool AssumeConvergent) { 3794 if (AssumeConvergent) { 3795 ExtraAttrs = 3796 ExtraAttrs.addFnAttribute(VMContext, llvm::Attribute::Convergent); 3797 } 3798 3799 llvm::Constant *C = 3800 GetOrCreateLLVMFunction(Name, FTy, GlobalDecl(), /*ForVTable=*/false, 3801 /*DontDefer=*/false, /*IsThunk=*/false, 3802 ExtraAttrs); 3803 3804 if (auto *F = dyn_cast<llvm::Function>(C)) { 3805 if (F->empty()) { 3806 F->setCallingConv(getRuntimeCC()); 3807 3808 // In Windows Itanium environments, try to mark runtime functions 3809 // dllimport. For Mingw and MSVC, don't. We don't really know if the user 3810 // will link their standard library statically or dynamically. Marking 3811 // functions imported when they are not imported can cause linker errors 3812 // and warnings. 3813 if (!Local && getTriple().isWindowsItaniumEnvironment() && 3814 !getCodeGenOpts().LTOVisibilityPublicStd) { 3815 const FunctionDecl *FD = GetRuntimeFunctionDecl(Context, Name); 3816 if (!FD || FD->hasAttr<DLLImportAttr>()) { 3817 F->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass); 3818 F->setLinkage(llvm::GlobalValue::ExternalLinkage); 3819 } 3820 } 3821 setDSOLocal(F); 3822 } 3823 } 3824 3825 return {FTy, C}; 3826 } 3827 3828 /// isTypeConstant - Determine whether an object of this type can be emitted 3829 /// as a constant. 3830 /// 3831 /// If ExcludeCtor is true, the duration when the object's constructor runs 3832 /// will not be considered. The caller will need to verify that the object is 3833 /// not written to during its construction. 3834 bool CodeGenModule::isTypeConstant(QualType Ty, bool ExcludeCtor) { 3835 if (!Ty.isConstant(Context) && !Ty->isReferenceType()) 3836 return false; 3837 3838 if (Context.getLangOpts().CPlusPlus) { 3839 if (const CXXRecordDecl *Record 3840 = Context.getBaseElementType(Ty)->getAsCXXRecordDecl()) 3841 return ExcludeCtor && !Record->hasMutableFields() && 3842 Record->hasTrivialDestructor(); 3843 } 3844 3845 return true; 3846 } 3847 3848 /// GetOrCreateLLVMGlobal - If the specified mangled name is not in the module, 3849 /// create and return an llvm GlobalVariable with the specified type and address 3850 /// space. If there is something in the module with the specified name, return 3851 /// it potentially bitcasted to the right type. 3852 /// 3853 /// If D is non-null, it specifies a decl that correspond to this. This is used 3854 /// to set the attributes on the global when it is first created. 3855 /// 3856 /// If IsForDefinition is true, it is guaranteed that an actual global with 3857 /// type Ty will be returned, not conversion of a variable with the same 3858 /// mangled name but some other type. 3859 llvm::Constant * 3860 CodeGenModule::GetOrCreateLLVMGlobal(StringRef MangledName, llvm::Type *Ty, 3861 LangAS AddrSpace, const VarDecl *D, 3862 ForDefinition_t IsForDefinition) { 3863 // Lookup the entry, lazily creating it if necessary. 3864 llvm::GlobalValue *Entry = GetGlobalValue(MangledName); 3865 unsigned TargetAS = getContext().getTargetAddressSpace(AddrSpace); 3866 if (Entry) { 3867 if (WeakRefReferences.erase(Entry)) { 3868 if (D && !D->hasAttr<WeakAttr>()) 3869 Entry->setLinkage(llvm::Function::ExternalLinkage); 3870 } 3871 3872 // Handle dropped DLL attributes. 3873 if (D && !D->hasAttr<DLLImportAttr>() && !D->hasAttr<DLLExportAttr>()) 3874 Entry->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass); 3875 3876 if (LangOpts.OpenMP && !LangOpts.OpenMPSimd && D) 3877 getOpenMPRuntime().registerTargetGlobalVariable(D, Entry); 3878 3879 if (Entry->getValueType() == Ty && Entry->getAddressSpace() == TargetAS) 3880 return Entry; 3881 3882 // If there are two attempts to define the same mangled name, issue an 3883 // error. 3884 if (IsForDefinition && !Entry->isDeclaration()) { 3885 GlobalDecl OtherGD; 3886 const VarDecl *OtherD; 3887 3888 // Check that D is not yet in DiagnosedConflictingDefinitions is required 3889 // to make sure that we issue an error only once. 3890 if (D && lookupRepresentativeDecl(MangledName, OtherGD) && 3891 (D->getCanonicalDecl() != OtherGD.getCanonicalDecl().getDecl()) && 3892 (OtherD = dyn_cast<VarDecl>(OtherGD.getDecl())) && 3893 OtherD->hasInit() && 3894 DiagnosedConflictingDefinitions.insert(D).second) { 3895 getDiags().Report(D->getLocation(), diag::err_duplicate_mangled_name) 3896 << MangledName; 3897 getDiags().Report(OtherGD.getDecl()->getLocation(), 3898 diag::note_previous_definition); 3899 } 3900 } 3901 3902 // Make sure the result is of the correct type. 3903 if (Entry->getType()->getAddressSpace() != TargetAS) { 3904 return llvm::ConstantExpr::getAddrSpaceCast(Entry, 3905 Ty->getPointerTo(TargetAS)); 3906 } 3907 3908 // (If global is requested for a definition, we always need to create a new 3909 // global, not just return a bitcast.) 3910 if (!IsForDefinition) 3911 return llvm::ConstantExpr::getBitCast(Entry, Ty->getPointerTo(TargetAS)); 3912 } 3913 3914 auto DAddrSpace = GetGlobalVarAddressSpace(D); 3915 3916 auto *GV = new llvm::GlobalVariable( 3917 getModule(), Ty, false, llvm::GlobalValue::ExternalLinkage, nullptr, 3918 MangledName, nullptr, llvm::GlobalVariable::NotThreadLocal, 3919 getContext().getTargetAddressSpace(DAddrSpace)); 3920 3921 // If we already created a global with the same mangled name (but different 3922 // type) before, take its name and remove it from its parent. 3923 if (Entry) { 3924 GV->takeName(Entry); 3925 3926 if (!Entry->use_empty()) { 3927 llvm::Constant *NewPtrForOldDecl = 3928 llvm::ConstantExpr::getBitCast(GV, Entry->getType()); 3929 Entry->replaceAllUsesWith(NewPtrForOldDecl); 3930 } 3931 3932 Entry->eraseFromParent(); 3933 } 3934 3935 // This is the first use or definition of a mangled name. If there is a 3936 // deferred decl with this name, remember that we need to emit it at the end 3937 // of the file. 3938 auto DDI = DeferredDecls.find(MangledName); 3939 if (DDI != DeferredDecls.end()) { 3940 // Move the potentially referenced deferred decl to the DeferredDeclsToEmit 3941 // list, and remove it from DeferredDecls (since we don't need it anymore). 3942 addDeferredDeclToEmit(DDI->second); 3943 DeferredDecls.erase(DDI); 3944 } 3945 3946 // Handle things which are present even on external declarations. 3947 if (D) { 3948 if (LangOpts.OpenMP && !LangOpts.OpenMPSimd) 3949 getOpenMPRuntime().registerTargetGlobalVariable(D, GV); 3950 3951 // FIXME: This code is overly simple and should be merged with other global 3952 // handling. 3953 GV->setConstant(isTypeConstant(D->getType(), false)); 3954 3955 GV->setAlignment(getContext().getDeclAlign(D).getAsAlign()); 3956 3957 setLinkageForGV(GV, D); 3958 3959 if (D->getTLSKind()) { 3960 if (D->getTLSKind() == VarDecl::TLS_Dynamic) 3961 CXXThreadLocals.push_back(D); 3962 setTLSMode(GV, *D); 3963 } 3964 3965 setGVProperties(GV, D); 3966 3967 // If required by the ABI, treat declarations of static data members with 3968 // inline initializers as definitions. 3969 if (getContext().isMSStaticDataMemberInlineDefinition(D)) { 3970 EmitGlobalVarDefinition(D); 3971 } 3972 3973 // Emit section information for extern variables. 3974 if (D->hasExternalStorage()) { 3975 if (const SectionAttr *SA = D->getAttr<SectionAttr>()) 3976 GV->setSection(SA->getName()); 3977 } 3978 3979 // Handle XCore specific ABI requirements. 3980 if (getTriple().getArch() == llvm::Triple::xcore && 3981 D->getLanguageLinkage() == CLanguageLinkage && 3982 D->getType().isConstant(Context) && 3983 isExternallyVisible(D->getLinkageAndVisibility().getLinkage())) 3984 GV->setSection(".cp.rodata"); 3985 3986 // Check if we a have a const declaration with an initializer, we may be 3987 // able to emit it as available_externally to expose it's value to the 3988 // optimizer. 3989 if (Context.getLangOpts().CPlusPlus && GV->hasExternalLinkage() && 3990 D->getType().isConstQualified() && !GV->hasInitializer() && 3991 !D->hasDefinition() && D->hasInit() && !D->hasAttr<DLLImportAttr>()) { 3992 const auto *Record = 3993 Context.getBaseElementType(D->getType())->getAsCXXRecordDecl(); 3994 bool HasMutableFields = Record && Record->hasMutableFields(); 3995 if (!HasMutableFields) { 3996 const VarDecl *InitDecl; 3997 const Expr *InitExpr = D->getAnyInitializer(InitDecl); 3998 if (InitExpr) { 3999 ConstantEmitter emitter(*this); 4000 llvm::Constant *Init = emitter.tryEmitForInitializer(*InitDecl); 4001 if (Init) { 4002 auto *InitType = Init->getType(); 4003 if (GV->getValueType() != InitType) { 4004 // The type of the initializer does not match the definition. 4005 // This happens when an initializer has a different type from 4006 // the type of the global (because of padding at the end of a 4007 // structure for instance). 4008 GV->setName(StringRef()); 4009 // Make a new global with the correct type, this is now guaranteed 4010 // to work. 4011 auto *NewGV = cast<llvm::GlobalVariable>( 4012 GetAddrOfGlobalVar(D, InitType, IsForDefinition) 4013 ->stripPointerCasts()); 4014 4015 // Erase the old global, since it is no longer used. 4016 GV->eraseFromParent(); 4017 GV = NewGV; 4018 } else { 4019 GV->setInitializer(Init); 4020 GV->setConstant(true); 4021 GV->setLinkage(llvm::GlobalValue::AvailableExternallyLinkage); 4022 } 4023 emitter.finalize(GV); 4024 } 4025 } 4026 } 4027 } 4028 } 4029 4030 if (GV->isDeclaration()) { 4031 getTargetCodeGenInfo().setTargetAttributes(D, GV, *this); 4032 // External HIP managed variables needed to be recorded for transformation 4033 // in both device and host compilations. 4034 if (getLangOpts().CUDA && D && D->hasAttr<HIPManagedAttr>() && 4035 D->hasExternalStorage()) 4036 getCUDARuntime().handleVarRegistration(D, *GV); 4037 } 4038 4039 LangAS ExpectedAS = 4040 D ? D->getType().getAddressSpace() 4041 : (LangOpts.OpenCL ? LangAS::opencl_global : LangAS::Default); 4042 assert(getContext().getTargetAddressSpace(ExpectedAS) == TargetAS); 4043 if (DAddrSpace != ExpectedAS) { 4044 return getTargetCodeGenInfo().performAddrSpaceCast( 4045 *this, GV, DAddrSpace, ExpectedAS, Ty->getPointerTo(TargetAS)); 4046 } 4047 4048 return GV; 4049 } 4050 4051 llvm::Constant * 4052 CodeGenModule::GetAddrOfGlobal(GlobalDecl GD, ForDefinition_t IsForDefinition) { 4053 const Decl *D = GD.getDecl(); 4054 4055 if (isa<CXXConstructorDecl>(D) || isa<CXXDestructorDecl>(D)) 4056 return getAddrOfCXXStructor(GD, /*FnInfo=*/nullptr, /*FnType=*/nullptr, 4057 /*DontDefer=*/false, IsForDefinition); 4058 4059 if (isa<CXXMethodDecl>(D)) { 4060 auto FInfo = 4061 &getTypes().arrangeCXXMethodDeclaration(cast<CXXMethodDecl>(D)); 4062 auto Ty = getTypes().GetFunctionType(*FInfo); 4063 return GetAddrOfFunction(GD, Ty, /*ForVTable=*/false, /*DontDefer=*/false, 4064 IsForDefinition); 4065 } 4066 4067 if (isa<FunctionDecl>(D)) { 4068 const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD); 4069 llvm::FunctionType *Ty = getTypes().GetFunctionType(FI); 4070 return GetAddrOfFunction(GD, Ty, /*ForVTable=*/false, /*DontDefer=*/false, 4071 IsForDefinition); 4072 } 4073 4074 return GetAddrOfGlobalVar(cast<VarDecl>(D), /*Ty=*/nullptr, IsForDefinition); 4075 } 4076 4077 llvm::GlobalVariable *CodeGenModule::CreateOrReplaceCXXRuntimeVariable( 4078 StringRef Name, llvm::Type *Ty, llvm::GlobalValue::LinkageTypes Linkage, 4079 unsigned Alignment) { 4080 llvm::GlobalVariable *GV = getModule().getNamedGlobal(Name); 4081 llvm::GlobalVariable *OldGV = nullptr; 4082 4083 if (GV) { 4084 // Check if the variable has the right type. 4085 if (GV->getValueType() == Ty) 4086 return GV; 4087 4088 // Because C++ name mangling, the only way we can end up with an already 4089 // existing global with the same name is if it has been declared extern "C". 4090 assert(GV->isDeclaration() && "Declaration has wrong type!"); 4091 OldGV = GV; 4092 } 4093 4094 // Create a new variable. 4095 GV = new llvm::GlobalVariable(getModule(), Ty, /*isConstant=*/true, 4096 Linkage, nullptr, Name); 4097 4098 if (OldGV) { 4099 // Replace occurrences of the old variable if needed. 4100 GV->takeName(OldGV); 4101 4102 if (!OldGV->use_empty()) { 4103 llvm::Constant *NewPtrForOldDecl = 4104 llvm::ConstantExpr::getBitCast(GV, OldGV->getType()); 4105 OldGV->replaceAllUsesWith(NewPtrForOldDecl); 4106 } 4107 4108 OldGV->eraseFromParent(); 4109 } 4110 4111 if (supportsCOMDAT() && GV->isWeakForLinker() && 4112 !GV->hasAvailableExternallyLinkage()) 4113 GV->setComdat(TheModule.getOrInsertComdat(GV->getName())); 4114 4115 GV->setAlignment(llvm::MaybeAlign(Alignment)); 4116 4117 return GV; 4118 } 4119 4120 /// GetAddrOfGlobalVar - Return the llvm::Constant for the address of the 4121 /// given global variable. If Ty is non-null and if the global doesn't exist, 4122 /// then it will be created with the specified type instead of whatever the 4123 /// normal requested type would be. If IsForDefinition is true, it is guaranteed 4124 /// that an actual global with type Ty will be returned, not conversion of a 4125 /// variable with the same mangled name but some other type. 4126 llvm::Constant *CodeGenModule::GetAddrOfGlobalVar(const VarDecl *D, 4127 llvm::Type *Ty, 4128 ForDefinition_t IsForDefinition) { 4129 assert(D->hasGlobalStorage() && "Not a global variable"); 4130 QualType ASTTy = D->getType(); 4131 if (!Ty) 4132 Ty = getTypes().ConvertTypeForMem(ASTTy); 4133 4134 StringRef MangledName = getMangledName(D); 4135 return GetOrCreateLLVMGlobal(MangledName, Ty, ASTTy.getAddressSpace(), D, 4136 IsForDefinition); 4137 } 4138 4139 /// CreateRuntimeVariable - Create a new runtime global variable with the 4140 /// specified type and name. 4141 llvm::Constant * 4142 CodeGenModule::CreateRuntimeVariable(llvm::Type *Ty, 4143 StringRef Name) { 4144 LangAS AddrSpace = getContext().getLangOpts().OpenCL ? LangAS::opencl_global 4145 : LangAS::Default; 4146 auto *Ret = GetOrCreateLLVMGlobal(Name, Ty, AddrSpace, nullptr); 4147 setDSOLocal(cast<llvm::GlobalValue>(Ret->stripPointerCasts())); 4148 return Ret; 4149 } 4150 4151 void CodeGenModule::EmitTentativeDefinition(const VarDecl *D) { 4152 assert(!D->getInit() && "Cannot emit definite definitions here!"); 4153 4154 StringRef MangledName = getMangledName(D); 4155 llvm::GlobalValue *GV = GetGlobalValue(MangledName); 4156 4157 // We already have a definition, not declaration, with the same mangled name. 4158 // Emitting of declaration is not required (and actually overwrites emitted 4159 // definition). 4160 if (GV && !GV->isDeclaration()) 4161 return; 4162 4163 // If we have not seen a reference to this variable yet, place it into the 4164 // deferred declarations table to be emitted if needed later. 4165 if (!MustBeEmitted(D) && !GV) { 4166 DeferredDecls[MangledName] = D; 4167 return; 4168 } 4169 4170 // The tentative definition is the only definition. 4171 EmitGlobalVarDefinition(D); 4172 } 4173 4174 void CodeGenModule::EmitExternalDeclaration(const VarDecl *D) { 4175 EmitExternalVarDeclaration(D); 4176 } 4177 4178 CharUnits CodeGenModule::GetTargetTypeStoreSize(llvm::Type *Ty) const { 4179 return Context.toCharUnitsFromBits( 4180 getDataLayout().getTypeStoreSizeInBits(Ty)); 4181 } 4182 4183 LangAS CodeGenModule::GetGlobalVarAddressSpace(const VarDecl *D) { 4184 if (LangOpts.OpenCL) { 4185 LangAS AS = D ? D->getType().getAddressSpace() : LangAS::opencl_global; 4186 assert(AS == LangAS::opencl_global || 4187 AS == LangAS::opencl_global_device || 4188 AS == LangAS::opencl_global_host || 4189 AS == LangAS::opencl_constant || 4190 AS == LangAS::opencl_local || 4191 AS >= LangAS::FirstTargetAddressSpace); 4192 return AS; 4193 } 4194 4195 if (LangOpts.SYCLIsDevice && 4196 (!D || D->getType().getAddressSpace() == LangAS::Default)) 4197 return LangAS::sycl_global; 4198 4199 if (LangOpts.CUDA && LangOpts.CUDAIsDevice) { 4200 if (D && D->hasAttr<CUDAConstantAttr>()) 4201 return LangAS::cuda_constant; 4202 else if (D && D->hasAttr<CUDASharedAttr>()) 4203 return LangAS::cuda_shared; 4204 else if (D && D->hasAttr<CUDADeviceAttr>()) 4205 return LangAS::cuda_device; 4206 else if (D && D->getType().isConstQualified()) 4207 return LangAS::cuda_constant; 4208 else 4209 return LangAS::cuda_device; 4210 } 4211 4212 if (LangOpts.OpenMP) { 4213 LangAS AS; 4214 if (OpenMPRuntime->hasAllocateAttributeForGlobalVar(D, AS)) 4215 return AS; 4216 } 4217 return getTargetCodeGenInfo().getGlobalVarAddressSpace(*this, D); 4218 } 4219 4220 LangAS CodeGenModule::GetGlobalConstantAddressSpace() const { 4221 // OpenCL v1.2 s6.5.3: a string literal is in the constant address space. 4222 if (LangOpts.OpenCL) 4223 return LangAS::opencl_constant; 4224 if (LangOpts.SYCLIsDevice) 4225 return LangAS::sycl_global; 4226 if (auto AS = getTarget().getConstantAddressSpace()) 4227 return AS.getValue(); 4228 return LangAS::Default; 4229 } 4230 4231 // In address space agnostic languages, string literals are in default address 4232 // space in AST. However, certain targets (e.g. amdgcn) request them to be 4233 // emitted in constant address space in LLVM IR. To be consistent with other 4234 // parts of AST, string literal global variables in constant address space 4235 // need to be casted to default address space before being put into address 4236 // map and referenced by other part of CodeGen. 4237 // In OpenCL, string literals are in constant address space in AST, therefore 4238 // they should not be casted to default address space. 4239 static llvm::Constant * 4240 castStringLiteralToDefaultAddressSpace(CodeGenModule &CGM, 4241 llvm::GlobalVariable *GV) { 4242 llvm::Constant *Cast = GV; 4243 if (!CGM.getLangOpts().OpenCL) { 4244 auto AS = CGM.GetGlobalConstantAddressSpace(); 4245 if (AS != LangAS::Default) 4246 Cast = CGM.getTargetCodeGenInfo().performAddrSpaceCast( 4247 CGM, GV, AS, LangAS::Default, 4248 GV->getValueType()->getPointerTo( 4249 CGM.getContext().getTargetAddressSpace(LangAS::Default))); 4250 } 4251 return Cast; 4252 } 4253 4254 template<typename SomeDecl> 4255 void CodeGenModule::MaybeHandleStaticInExternC(const SomeDecl *D, 4256 llvm::GlobalValue *GV) { 4257 if (!getLangOpts().CPlusPlus) 4258 return; 4259 4260 // Must have 'used' attribute, or else inline assembly can't rely on 4261 // the name existing. 4262 if (!D->template hasAttr<UsedAttr>()) 4263 return; 4264 4265 // Must have internal linkage and an ordinary name. 4266 if (!D->getIdentifier() || D->getFormalLinkage() != InternalLinkage) 4267 return; 4268 4269 // Must be in an extern "C" context. Entities declared directly within 4270 // a record are not extern "C" even if the record is in such a context. 4271 const SomeDecl *First = D->getFirstDecl(); 4272 if (First->getDeclContext()->isRecord() || !First->isInExternCContext()) 4273 return; 4274 4275 // OK, this is an internal linkage entity inside an extern "C" linkage 4276 // specification. Make a note of that so we can give it the "expected" 4277 // mangled name if nothing else is using that name. 4278 std::pair<StaticExternCMap::iterator, bool> R = 4279 StaticExternCValues.insert(std::make_pair(D->getIdentifier(), GV)); 4280 4281 // If we have multiple internal linkage entities with the same name 4282 // in extern "C" regions, none of them gets that name. 4283 if (!R.second) 4284 R.first->second = nullptr; 4285 } 4286 4287 static bool shouldBeInCOMDAT(CodeGenModule &CGM, const Decl &D) { 4288 if (!CGM.supportsCOMDAT()) 4289 return false; 4290 4291 // Do not set COMDAT attribute for CUDA/HIP stub functions to prevent 4292 // them being "merged" by the COMDAT Folding linker optimization. 4293 if (D.hasAttr<CUDAGlobalAttr>()) 4294 return false; 4295 4296 if (D.hasAttr<SelectAnyAttr>()) 4297 return true; 4298 4299 GVALinkage Linkage; 4300 if (auto *VD = dyn_cast<VarDecl>(&D)) 4301 Linkage = CGM.getContext().GetGVALinkageForVariable(VD); 4302 else 4303 Linkage = CGM.getContext().GetGVALinkageForFunction(cast<FunctionDecl>(&D)); 4304 4305 switch (Linkage) { 4306 case GVA_Internal: 4307 case GVA_AvailableExternally: 4308 case GVA_StrongExternal: 4309 return false; 4310 case GVA_DiscardableODR: 4311 case GVA_StrongODR: 4312 return true; 4313 } 4314 llvm_unreachable("No such linkage"); 4315 } 4316 4317 void CodeGenModule::maybeSetTrivialComdat(const Decl &D, 4318 llvm::GlobalObject &GO) { 4319 if (!shouldBeInCOMDAT(*this, D)) 4320 return; 4321 GO.setComdat(TheModule.getOrInsertComdat(GO.getName())); 4322 } 4323 4324 /// Pass IsTentative as true if you want to create a tentative definition. 4325 void CodeGenModule::EmitGlobalVarDefinition(const VarDecl *D, 4326 bool IsTentative) { 4327 // OpenCL global variables of sampler type are translated to function calls, 4328 // therefore no need to be translated. 4329 QualType ASTTy = D->getType(); 4330 if (getLangOpts().OpenCL && ASTTy->isSamplerT()) 4331 return; 4332 4333 // If this is OpenMP device, check if it is legal to emit this global 4334 // normally. 4335 if (LangOpts.OpenMPIsDevice && OpenMPRuntime && 4336 OpenMPRuntime->emitTargetGlobalVariable(D)) 4337 return; 4338 4339 llvm::TrackingVH<llvm::Constant> Init; 4340 bool NeedsGlobalCtor = false; 4341 bool NeedsGlobalDtor = 4342 D->needsDestruction(getContext()) == QualType::DK_cxx_destructor; 4343 4344 const VarDecl *InitDecl; 4345 const Expr *InitExpr = D->getAnyInitializer(InitDecl); 4346 4347 Optional<ConstantEmitter> emitter; 4348 4349 // CUDA E.2.4.1 "__shared__ variables cannot have an initialization 4350 // as part of their declaration." Sema has already checked for 4351 // error cases, so we just need to set Init to UndefValue. 4352 bool IsCUDASharedVar = 4353 getLangOpts().CUDAIsDevice && D->hasAttr<CUDASharedAttr>(); 4354 // Shadows of initialized device-side global variables are also left 4355 // undefined. 4356 // Managed Variables should be initialized on both host side and device side. 4357 bool IsCUDAShadowVar = 4358 !getLangOpts().CUDAIsDevice && !D->hasAttr<HIPManagedAttr>() && 4359 (D->hasAttr<CUDAConstantAttr>() || D->hasAttr<CUDADeviceAttr>() || 4360 D->hasAttr<CUDASharedAttr>()); 4361 bool IsCUDADeviceShadowVar = 4362 getLangOpts().CUDAIsDevice && !D->hasAttr<HIPManagedAttr>() && 4363 (D->getType()->isCUDADeviceBuiltinSurfaceType() || 4364 D->getType()->isCUDADeviceBuiltinTextureType()); 4365 if (getLangOpts().CUDA && 4366 (IsCUDASharedVar || IsCUDAShadowVar || IsCUDADeviceShadowVar)) 4367 Init = llvm::UndefValue::get(getTypes().ConvertTypeForMem(ASTTy)); 4368 else if (D->hasAttr<LoaderUninitializedAttr>()) 4369 Init = llvm::UndefValue::get(getTypes().ConvertTypeForMem(ASTTy)); 4370 else if (!InitExpr) { 4371 // This is a tentative definition; tentative definitions are 4372 // implicitly initialized with { 0 }. 4373 // 4374 // Note that tentative definitions are only emitted at the end of 4375 // a translation unit, so they should never have incomplete 4376 // type. In addition, EmitTentativeDefinition makes sure that we 4377 // never attempt to emit a tentative definition if a real one 4378 // exists. A use may still exists, however, so we still may need 4379 // to do a RAUW. 4380 assert(!ASTTy->isIncompleteType() && "Unexpected incomplete type"); 4381 Init = EmitNullConstant(D->getType()); 4382 } else { 4383 initializedGlobalDecl = GlobalDecl(D); 4384 emitter.emplace(*this); 4385 llvm::Constant *Initializer = emitter->tryEmitForInitializer(*InitDecl); 4386 if (!Initializer) { 4387 QualType T = InitExpr->getType(); 4388 if (D->getType()->isReferenceType()) 4389 T = D->getType(); 4390 4391 if (getLangOpts().CPlusPlus) { 4392 Init = EmitNullConstant(T); 4393 NeedsGlobalCtor = true; 4394 } else { 4395 ErrorUnsupported(D, "static initializer"); 4396 Init = llvm::UndefValue::get(getTypes().ConvertType(T)); 4397 } 4398 } else { 4399 Init = Initializer; 4400 // We don't need an initializer, so remove the entry for the delayed 4401 // initializer position (just in case this entry was delayed) if we 4402 // also don't need to register a destructor. 4403 if (getLangOpts().CPlusPlus && !NeedsGlobalDtor) 4404 DelayedCXXInitPosition.erase(D); 4405 } 4406 } 4407 4408 llvm::Type* InitType = Init->getType(); 4409 llvm::Constant *Entry = 4410 GetAddrOfGlobalVar(D, InitType, ForDefinition_t(!IsTentative)); 4411 4412 // Strip off pointer casts if we got them. 4413 Entry = Entry->stripPointerCasts(); 4414 4415 // Entry is now either a Function or GlobalVariable. 4416 auto *GV = dyn_cast<llvm::GlobalVariable>(Entry); 4417 4418 // We have a definition after a declaration with the wrong type. 4419 // We must make a new GlobalVariable* and update everything that used OldGV 4420 // (a declaration or tentative definition) with the new GlobalVariable* 4421 // (which will be a definition). 4422 // 4423 // This happens if there is a prototype for a global (e.g. 4424 // "extern int x[];") and then a definition of a different type (e.g. 4425 // "int x[10];"). This also happens when an initializer has a different type 4426 // from the type of the global (this happens with unions). 4427 if (!GV || GV->getValueType() != InitType || 4428 GV->getType()->getAddressSpace() != 4429 getContext().getTargetAddressSpace(GetGlobalVarAddressSpace(D))) { 4430 4431 // Move the old entry aside so that we'll create a new one. 4432 Entry->setName(StringRef()); 4433 4434 // Make a new global with the correct type, this is now guaranteed to work. 4435 GV = cast<llvm::GlobalVariable>( 4436 GetAddrOfGlobalVar(D, InitType, ForDefinition_t(!IsTentative)) 4437 ->stripPointerCasts()); 4438 4439 // Replace all uses of the old global with the new global 4440 llvm::Constant *NewPtrForOldDecl = 4441 llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(GV, 4442 Entry->getType()); 4443 Entry->replaceAllUsesWith(NewPtrForOldDecl); 4444 4445 // Erase the old global, since it is no longer used. 4446 cast<llvm::GlobalValue>(Entry)->eraseFromParent(); 4447 } 4448 4449 MaybeHandleStaticInExternC(D, GV); 4450 4451 if (D->hasAttr<AnnotateAttr>()) 4452 AddGlobalAnnotations(D, GV); 4453 4454 // Set the llvm linkage type as appropriate. 4455 llvm::GlobalValue::LinkageTypes Linkage = 4456 getLLVMLinkageVarDefinition(D, GV->isConstant()); 4457 4458 // CUDA B.2.1 "The __device__ qualifier declares a variable that resides on 4459 // the device. [...]" 4460 // CUDA B.2.2 "The __constant__ qualifier, optionally used together with 4461 // __device__, declares a variable that: [...] 4462 // Is accessible from all the threads within the grid and from the host 4463 // through the runtime library (cudaGetSymbolAddress() / cudaGetSymbolSize() 4464 // / cudaMemcpyToSymbol() / cudaMemcpyFromSymbol())." 4465 if (GV && LangOpts.CUDA) { 4466 if (LangOpts.CUDAIsDevice) { 4467 if (Linkage != llvm::GlobalValue::InternalLinkage && 4468 (D->hasAttr<CUDADeviceAttr>() || D->hasAttr<CUDAConstantAttr>() || 4469 D->getType()->isCUDADeviceBuiltinSurfaceType() || 4470 D->getType()->isCUDADeviceBuiltinTextureType())) 4471 GV->setExternallyInitialized(true); 4472 } else { 4473 getCUDARuntime().internalizeDeviceSideVar(D, Linkage); 4474 } 4475 getCUDARuntime().handleVarRegistration(D, *GV); 4476 } 4477 4478 GV->setInitializer(Init); 4479 if (emitter) 4480 emitter->finalize(GV); 4481 4482 // If it is safe to mark the global 'constant', do so now. 4483 GV->setConstant(!NeedsGlobalCtor && !NeedsGlobalDtor && 4484 isTypeConstant(D->getType(), true)); 4485 4486 // If it is in a read-only section, mark it 'constant'. 4487 if (const SectionAttr *SA = D->getAttr<SectionAttr>()) { 4488 const ASTContext::SectionInfo &SI = Context.SectionInfos[SA->getName()]; 4489 if ((SI.SectionFlags & ASTContext::PSF_Write) == 0) 4490 GV->setConstant(true); 4491 } 4492 4493 GV->setAlignment(getContext().getDeclAlign(D).getAsAlign()); 4494 4495 // On Darwin, unlike other Itanium C++ ABI platforms, the thread-wrapper 4496 // function is only defined alongside the variable, not also alongside 4497 // callers. Normally, all accesses to a thread_local go through the 4498 // thread-wrapper in order to ensure initialization has occurred, underlying 4499 // variable will never be used other than the thread-wrapper, so it can be 4500 // converted to internal linkage. 4501 // 4502 // However, if the variable has the 'constinit' attribute, it _can_ be 4503 // referenced directly, without calling the thread-wrapper, so the linkage 4504 // must not be changed. 4505 // 4506 // Additionally, if the variable isn't plain external linkage, e.g. if it's 4507 // weak or linkonce, the de-duplication semantics are important to preserve, 4508 // so we don't change the linkage. 4509 if (D->getTLSKind() == VarDecl::TLS_Dynamic && 4510 Linkage == llvm::GlobalValue::ExternalLinkage && 4511 Context.getTargetInfo().getTriple().isOSDarwin() && 4512 !D->hasAttr<ConstInitAttr>()) 4513 Linkage = llvm::GlobalValue::InternalLinkage; 4514 4515 GV->setLinkage(Linkage); 4516 if (D->hasAttr<DLLImportAttr>()) 4517 GV->setDLLStorageClass(llvm::GlobalVariable::DLLImportStorageClass); 4518 else if (D->hasAttr<DLLExportAttr>()) 4519 GV->setDLLStorageClass(llvm::GlobalVariable::DLLExportStorageClass); 4520 else 4521 GV->setDLLStorageClass(llvm::GlobalVariable::DefaultStorageClass); 4522 4523 if (Linkage == llvm::GlobalVariable::CommonLinkage) { 4524 // common vars aren't constant even if declared const. 4525 GV->setConstant(false); 4526 // Tentative definition of global variables may be initialized with 4527 // non-zero null pointers. In this case they should have weak linkage 4528 // since common linkage must have zero initializer and must not have 4529 // explicit section therefore cannot have non-zero initial value. 4530 if (!GV->getInitializer()->isNullValue()) 4531 GV->setLinkage(llvm::GlobalVariable::WeakAnyLinkage); 4532 } 4533 4534 setNonAliasAttributes(D, GV); 4535 4536 if (D->getTLSKind() && !GV->isThreadLocal()) { 4537 if (D->getTLSKind() == VarDecl::TLS_Dynamic) 4538 CXXThreadLocals.push_back(D); 4539 setTLSMode(GV, *D); 4540 } 4541 4542 maybeSetTrivialComdat(*D, *GV); 4543 4544 // Emit the initializer function if necessary. 4545 if (NeedsGlobalCtor || NeedsGlobalDtor) 4546 EmitCXXGlobalVarDeclInitFunc(D, GV, NeedsGlobalCtor); 4547 4548 SanitizerMD->reportGlobalToASan(GV, *D, NeedsGlobalCtor); 4549 4550 // Emit global variable debug information. 4551 if (CGDebugInfo *DI = getModuleDebugInfo()) 4552 if (getCodeGenOpts().hasReducedDebugInfo()) 4553 DI->EmitGlobalVariable(GV, D); 4554 } 4555 4556 void CodeGenModule::EmitExternalVarDeclaration(const VarDecl *D) { 4557 if (CGDebugInfo *DI = getModuleDebugInfo()) 4558 if (getCodeGenOpts().hasReducedDebugInfo()) { 4559 QualType ASTTy = D->getType(); 4560 llvm::Type *Ty = getTypes().ConvertTypeForMem(D->getType()); 4561 llvm::Constant *GV = 4562 GetOrCreateLLVMGlobal(D->getName(), Ty, ASTTy.getAddressSpace(), D); 4563 DI->EmitExternalVariable( 4564 cast<llvm::GlobalVariable>(GV->stripPointerCasts()), D); 4565 } 4566 } 4567 4568 static bool isVarDeclStrongDefinition(const ASTContext &Context, 4569 CodeGenModule &CGM, const VarDecl *D, 4570 bool NoCommon) { 4571 // Don't give variables common linkage if -fno-common was specified unless it 4572 // was overridden by a NoCommon attribute. 4573 if ((NoCommon || D->hasAttr<NoCommonAttr>()) && !D->hasAttr<CommonAttr>()) 4574 return true; 4575 4576 // C11 6.9.2/2: 4577 // A declaration of an identifier for an object that has file scope without 4578 // an initializer, and without a storage-class specifier or with the 4579 // storage-class specifier static, constitutes a tentative definition. 4580 if (D->getInit() || D->hasExternalStorage()) 4581 return true; 4582 4583 // A variable cannot be both common and exist in a section. 4584 if (D->hasAttr<SectionAttr>()) 4585 return true; 4586 4587 // A variable cannot be both common and exist in a section. 4588 // We don't try to determine which is the right section in the front-end. 4589 // If no specialized section name is applicable, it will resort to default. 4590 if (D->hasAttr<PragmaClangBSSSectionAttr>() || 4591 D->hasAttr<PragmaClangDataSectionAttr>() || 4592 D->hasAttr<PragmaClangRelroSectionAttr>() || 4593 D->hasAttr<PragmaClangRodataSectionAttr>()) 4594 return true; 4595 4596 // Thread local vars aren't considered common linkage. 4597 if (D->getTLSKind()) 4598 return true; 4599 4600 // Tentative definitions marked with WeakImportAttr are true definitions. 4601 if (D->hasAttr<WeakImportAttr>()) 4602 return true; 4603 4604 // A variable cannot be both common and exist in a comdat. 4605 if (shouldBeInCOMDAT(CGM, *D)) 4606 return true; 4607 4608 // Declarations with a required alignment do not have common linkage in MSVC 4609 // mode. 4610 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) { 4611 if (D->hasAttr<AlignedAttr>()) 4612 return true; 4613 QualType VarType = D->getType(); 4614 if (Context.isAlignmentRequired(VarType)) 4615 return true; 4616 4617 if (const auto *RT = VarType->getAs<RecordType>()) { 4618 const RecordDecl *RD = RT->getDecl(); 4619 for (const FieldDecl *FD : RD->fields()) { 4620 if (FD->isBitField()) 4621 continue; 4622 if (FD->hasAttr<AlignedAttr>()) 4623 return true; 4624 if (Context.isAlignmentRequired(FD->getType())) 4625 return true; 4626 } 4627 } 4628 } 4629 4630 // Microsoft's link.exe doesn't support alignments greater than 32 bytes for 4631 // common symbols, so symbols with greater alignment requirements cannot be 4632 // common. 4633 // Other COFF linkers (ld.bfd and LLD) support arbitrary power-of-two 4634 // alignments for common symbols via the aligncomm directive, so this 4635 // restriction only applies to MSVC environments. 4636 if (Context.getTargetInfo().getTriple().isKnownWindowsMSVCEnvironment() && 4637 Context.getTypeAlignIfKnown(D->getType()) > 4638 Context.toBits(CharUnits::fromQuantity(32))) 4639 return true; 4640 4641 return false; 4642 } 4643 4644 llvm::GlobalValue::LinkageTypes CodeGenModule::getLLVMLinkageForDeclarator( 4645 const DeclaratorDecl *D, GVALinkage Linkage, bool IsConstantVariable) { 4646 if (Linkage == GVA_Internal) 4647 return llvm::Function::InternalLinkage; 4648 4649 if (D->hasAttr<WeakAttr>()) { 4650 if (IsConstantVariable) 4651 return llvm::GlobalVariable::WeakODRLinkage; 4652 else 4653 return llvm::GlobalVariable::WeakAnyLinkage; 4654 } 4655 4656 if (const auto *FD = D->getAsFunction()) 4657 if (FD->isMultiVersion() && Linkage == GVA_AvailableExternally) 4658 return llvm::GlobalVariable::LinkOnceAnyLinkage; 4659 4660 // We are guaranteed to have a strong definition somewhere else, 4661 // so we can use available_externally linkage. 4662 if (Linkage == GVA_AvailableExternally) 4663 return llvm::GlobalValue::AvailableExternallyLinkage; 4664 4665 // Note that Apple's kernel linker doesn't support symbol 4666 // coalescing, so we need to avoid linkonce and weak linkages there. 4667 // Normally, this means we just map to internal, but for explicit 4668 // instantiations we'll map to external. 4669 4670 // In C++, the compiler has to emit a definition in every translation unit 4671 // that references the function. We should use linkonce_odr because 4672 // a) if all references in this translation unit are optimized away, we 4673 // don't need to codegen it. b) if the function persists, it needs to be 4674 // merged with other definitions. c) C++ has the ODR, so we know the 4675 // definition is dependable. 4676 if (Linkage == GVA_DiscardableODR) 4677 return !Context.getLangOpts().AppleKext ? llvm::Function::LinkOnceODRLinkage 4678 : llvm::Function::InternalLinkage; 4679 4680 // An explicit instantiation of a template has weak linkage, since 4681 // explicit instantiations can occur in multiple translation units 4682 // and must all be equivalent. However, we are not allowed to 4683 // throw away these explicit instantiations. 4684 // 4685 // CUDA/HIP: For -fno-gpu-rdc case, device code is limited to one TU, 4686 // so say that CUDA templates are either external (for kernels) or internal. 4687 // This lets llvm perform aggressive inter-procedural optimizations. For 4688 // -fgpu-rdc case, device function calls across multiple TU's are allowed, 4689 // therefore we need to follow the normal linkage paradigm. 4690 if (Linkage == GVA_StrongODR) { 4691 if (getLangOpts().AppleKext) 4692 return llvm::Function::ExternalLinkage; 4693 if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice && 4694 !getLangOpts().GPURelocatableDeviceCode) 4695 return D->hasAttr<CUDAGlobalAttr>() ? llvm::Function::ExternalLinkage 4696 : llvm::Function::InternalLinkage; 4697 return llvm::Function::WeakODRLinkage; 4698 } 4699 4700 // C++ doesn't have tentative definitions and thus cannot have common 4701 // linkage. 4702 if (!getLangOpts().CPlusPlus && isa<VarDecl>(D) && 4703 !isVarDeclStrongDefinition(Context, *this, cast<VarDecl>(D), 4704 CodeGenOpts.NoCommon)) 4705 return llvm::GlobalVariable::CommonLinkage; 4706 4707 // selectany symbols are externally visible, so use weak instead of 4708 // linkonce. MSVC optimizes away references to const selectany globals, so 4709 // all definitions should be the same and ODR linkage should be used. 4710 // http://msdn.microsoft.com/en-us/library/5tkz6s71.aspx 4711 if (D->hasAttr<SelectAnyAttr>()) 4712 return llvm::GlobalVariable::WeakODRLinkage; 4713 4714 // Otherwise, we have strong external linkage. 4715 assert(Linkage == GVA_StrongExternal); 4716 return llvm::GlobalVariable::ExternalLinkage; 4717 } 4718 4719 llvm::GlobalValue::LinkageTypes CodeGenModule::getLLVMLinkageVarDefinition( 4720 const VarDecl *VD, bool IsConstant) { 4721 GVALinkage Linkage = getContext().GetGVALinkageForVariable(VD); 4722 return getLLVMLinkageForDeclarator(VD, Linkage, IsConstant); 4723 } 4724 4725 /// Replace the uses of a function that was declared with a non-proto type. 4726 /// We want to silently drop extra arguments from call sites 4727 static void replaceUsesOfNonProtoConstant(llvm::Constant *old, 4728 llvm::Function *newFn) { 4729 // Fast path. 4730 if (old->use_empty()) return; 4731 4732 llvm::Type *newRetTy = newFn->getReturnType(); 4733 SmallVector<llvm::Value*, 4> newArgs; 4734 4735 for (llvm::Value::use_iterator ui = old->use_begin(), ue = old->use_end(); 4736 ui != ue; ) { 4737 llvm::Value::use_iterator use = ui++; // Increment before the use is erased. 4738 llvm::User *user = use->getUser(); 4739 4740 // Recognize and replace uses of bitcasts. Most calls to 4741 // unprototyped functions will use bitcasts. 4742 if (auto *bitcast = dyn_cast<llvm::ConstantExpr>(user)) { 4743 if (bitcast->getOpcode() == llvm::Instruction::BitCast) 4744 replaceUsesOfNonProtoConstant(bitcast, newFn); 4745 continue; 4746 } 4747 4748 // Recognize calls to the function. 4749 llvm::CallBase *callSite = dyn_cast<llvm::CallBase>(user); 4750 if (!callSite) continue; 4751 if (!callSite->isCallee(&*use)) 4752 continue; 4753 4754 // If the return types don't match exactly, then we can't 4755 // transform this call unless it's dead. 4756 if (callSite->getType() != newRetTy && !callSite->use_empty()) 4757 continue; 4758 4759 // Get the call site's attribute list. 4760 SmallVector<llvm::AttributeSet, 8> newArgAttrs; 4761 llvm::AttributeList oldAttrs = callSite->getAttributes(); 4762 4763 // If the function was passed too few arguments, don't transform. 4764 unsigned newNumArgs = newFn->arg_size(); 4765 if (callSite->arg_size() < newNumArgs) 4766 continue; 4767 4768 // If extra arguments were passed, we silently drop them. 4769 // If any of the types mismatch, we don't transform. 4770 unsigned argNo = 0; 4771 bool dontTransform = false; 4772 for (llvm::Argument &A : newFn->args()) { 4773 if (callSite->getArgOperand(argNo)->getType() != A.getType()) { 4774 dontTransform = true; 4775 break; 4776 } 4777 4778 // Add any parameter attributes. 4779 newArgAttrs.push_back(oldAttrs.getParamAttrs(argNo)); 4780 argNo++; 4781 } 4782 if (dontTransform) 4783 continue; 4784 4785 // Okay, we can transform this. Create the new call instruction and copy 4786 // over the required information. 4787 newArgs.append(callSite->arg_begin(), callSite->arg_begin() + argNo); 4788 4789 // Copy over any operand bundles. 4790 SmallVector<llvm::OperandBundleDef, 1> newBundles; 4791 callSite->getOperandBundlesAsDefs(newBundles); 4792 4793 llvm::CallBase *newCall; 4794 if (dyn_cast<llvm::CallInst>(callSite)) { 4795 newCall = 4796 llvm::CallInst::Create(newFn, newArgs, newBundles, "", callSite); 4797 } else { 4798 auto *oldInvoke = cast<llvm::InvokeInst>(callSite); 4799 newCall = llvm::InvokeInst::Create(newFn, oldInvoke->getNormalDest(), 4800 oldInvoke->getUnwindDest(), newArgs, 4801 newBundles, "", callSite); 4802 } 4803 newArgs.clear(); // for the next iteration 4804 4805 if (!newCall->getType()->isVoidTy()) 4806 newCall->takeName(callSite); 4807 newCall->setAttributes( 4808 llvm::AttributeList::get(newFn->getContext(), oldAttrs.getFnAttrs(), 4809 oldAttrs.getRetAttrs(), newArgAttrs)); 4810 newCall->setCallingConv(callSite->getCallingConv()); 4811 4812 // Finally, remove the old call, replacing any uses with the new one. 4813 if (!callSite->use_empty()) 4814 callSite->replaceAllUsesWith(newCall); 4815 4816 // Copy debug location attached to CI. 4817 if (callSite->getDebugLoc()) 4818 newCall->setDebugLoc(callSite->getDebugLoc()); 4819 4820 callSite->eraseFromParent(); 4821 } 4822 } 4823 4824 /// ReplaceUsesOfNonProtoTypeWithRealFunction - This function is called when we 4825 /// implement a function with no prototype, e.g. "int foo() {}". If there are 4826 /// existing call uses of the old function in the module, this adjusts them to 4827 /// call the new function directly. 4828 /// 4829 /// This is not just a cleanup: the always_inline pass requires direct calls to 4830 /// functions to be able to inline them. If there is a bitcast in the way, it 4831 /// won't inline them. Instcombine normally deletes these calls, but it isn't 4832 /// run at -O0. 4833 static void ReplaceUsesOfNonProtoTypeWithRealFunction(llvm::GlobalValue *Old, 4834 llvm::Function *NewFn) { 4835 // If we're redefining a global as a function, don't transform it. 4836 if (!isa<llvm::Function>(Old)) return; 4837 4838 replaceUsesOfNonProtoConstant(Old, NewFn); 4839 } 4840 4841 void CodeGenModule::HandleCXXStaticMemberVarInstantiation(VarDecl *VD) { 4842 auto DK = VD->isThisDeclarationADefinition(); 4843 if (DK == VarDecl::Definition && VD->hasAttr<DLLImportAttr>()) 4844 return; 4845 4846 TemplateSpecializationKind TSK = VD->getTemplateSpecializationKind(); 4847 // If we have a definition, this might be a deferred decl. If the 4848 // instantiation is explicit, make sure we emit it at the end. 4849 if (VD->getDefinition() && TSK == TSK_ExplicitInstantiationDefinition) 4850 GetAddrOfGlobalVar(VD); 4851 4852 EmitTopLevelDecl(VD); 4853 } 4854 4855 void CodeGenModule::EmitGlobalFunctionDefinition(GlobalDecl GD, 4856 llvm::GlobalValue *GV) { 4857 const auto *D = cast<FunctionDecl>(GD.getDecl()); 4858 4859 // Compute the function info and LLVM type. 4860 const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD); 4861 llvm::FunctionType *Ty = getTypes().GetFunctionType(FI); 4862 4863 // Get or create the prototype for the function. 4864 if (!GV || (GV->getValueType() != Ty)) 4865 GV = cast<llvm::GlobalValue>(GetAddrOfFunction(GD, Ty, /*ForVTable=*/false, 4866 /*DontDefer=*/true, 4867 ForDefinition)); 4868 4869 // Already emitted. 4870 if (!GV->isDeclaration()) 4871 return; 4872 4873 // We need to set linkage and visibility on the function before 4874 // generating code for it because various parts of IR generation 4875 // want to propagate this information down (e.g. to local static 4876 // declarations). 4877 auto *Fn = cast<llvm::Function>(GV); 4878 setFunctionLinkage(GD, Fn); 4879 4880 // FIXME: this is redundant with part of setFunctionDefinitionAttributes 4881 setGVProperties(Fn, GD); 4882 4883 MaybeHandleStaticInExternC(D, Fn); 4884 4885 maybeSetTrivialComdat(*D, *Fn); 4886 4887 // Set CodeGen attributes that represent floating point environment. 4888 setLLVMFunctionFEnvAttributes(D, Fn); 4889 4890 CodeGenFunction(*this).GenerateCode(GD, Fn, FI); 4891 4892 setNonAliasAttributes(GD, Fn); 4893 SetLLVMFunctionAttributesForDefinition(D, Fn); 4894 4895 if (const ConstructorAttr *CA = D->getAttr<ConstructorAttr>()) 4896 AddGlobalCtor(Fn, CA->getPriority()); 4897 if (const DestructorAttr *DA = D->getAttr<DestructorAttr>()) 4898 AddGlobalDtor(Fn, DA->getPriority(), true); 4899 } 4900 4901 void CodeGenModule::EmitAliasDefinition(GlobalDecl GD) { 4902 const auto *D = cast<ValueDecl>(GD.getDecl()); 4903 const AliasAttr *AA = D->getAttr<AliasAttr>(); 4904 assert(AA && "Not an alias?"); 4905 4906 StringRef MangledName = getMangledName(GD); 4907 4908 if (AA->getAliasee() == MangledName) { 4909 Diags.Report(AA->getLocation(), diag::err_cyclic_alias) << 0; 4910 return; 4911 } 4912 4913 // If there is a definition in the module, then it wins over the alias. 4914 // This is dubious, but allow it to be safe. Just ignore the alias. 4915 llvm::GlobalValue *Entry = GetGlobalValue(MangledName); 4916 if (Entry && !Entry->isDeclaration()) 4917 return; 4918 4919 Aliases.push_back(GD); 4920 4921 llvm::Type *DeclTy = getTypes().ConvertTypeForMem(D->getType()); 4922 4923 // Create a reference to the named value. This ensures that it is emitted 4924 // if a deferred decl. 4925 llvm::Constant *Aliasee; 4926 llvm::GlobalValue::LinkageTypes LT; 4927 if (isa<llvm::FunctionType>(DeclTy)) { 4928 Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy, GD, 4929 /*ForVTable=*/false); 4930 LT = getFunctionLinkage(GD); 4931 } else { 4932 Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(), DeclTy, LangAS::Default, 4933 /*D=*/nullptr); 4934 if (const auto *VD = dyn_cast<VarDecl>(GD.getDecl())) 4935 LT = getLLVMLinkageVarDefinition(VD, D->getType().isConstQualified()); 4936 else 4937 LT = getFunctionLinkage(GD); 4938 } 4939 4940 // Create the new alias itself, but don't set a name yet. 4941 unsigned AS = Aliasee->getType()->getPointerAddressSpace(); 4942 auto *GA = 4943 llvm::GlobalAlias::create(DeclTy, AS, LT, "", Aliasee, &getModule()); 4944 4945 if (Entry) { 4946 if (GA->getAliasee() == Entry) { 4947 Diags.Report(AA->getLocation(), diag::err_cyclic_alias) << 0; 4948 return; 4949 } 4950 4951 assert(Entry->isDeclaration()); 4952 4953 // If there is a declaration in the module, then we had an extern followed 4954 // by the alias, as in: 4955 // extern int test6(); 4956 // ... 4957 // int test6() __attribute__((alias("test7"))); 4958 // 4959 // Remove it and replace uses of it with the alias. 4960 GA->takeName(Entry); 4961 4962 Entry->replaceAllUsesWith(llvm::ConstantExpr::getBitCast(GA, 4963 Entry->getType())); 4964 Entry->eraseFromParent(); 4965 } else { 4966 GA->setName(MangledName); 4967 } 4968 4969 // Set attributes which are particular to an alias; this is a 4970 // specialization of the attributes which may be set on a global 4971 // variable/function. 4972 if (D->hasAttr<WeakAttr>() || D->hasAttr<WeakRefAttr>() || 4973 D->isWeakImported()) { 4974 GA->setLinkage(llvm::Function::WeakAnyLinkage); 4975 } 4976 4977 if (const auto *VD = dyn_cast<VarDecl>(D)) 4978 if (VD->getTLSKind()) 4979 setTLSMode(GA, *VD); 4980 4981 SetCommonAttributes(GD, GA); 4982 } 4983 4984 void CodeGenModule::emitIFuncDefinition(GlobalDecl GD) { 4985 const auto *D = cast<ValueDecl>(GD.getDecl()); 4986 const IFuncAttr *IFA = D->getAttr<IFuncAttr>(); 4987 assert(IFA && "Not an ifunc?"); 4988 4989 StringRef MangledName = getMangledName(GD); 4990 4991 if (IFA->getResolver() == MangledName) { 4992 Diags.Report(IFA->getLocation(), diag::err_cyclic_alias) << 1; 4993 return; 4994 } 4995 4996 // Report an error if some definition overrides ifunc. 4997 llvm::GlobalValue *Entry = GetGlobalValue(MangledName); 4998 if (Entry && !Entry->isDeclaration()) { 4999 GlobalDecl OtherGD; 5000 if (lookupRepresentativeDecl(MangledName, OtherGD) && 5001 DiagnosedConflictingDefinitions.insert(GD).second) { 5002 Diags.Report(D->getLocation(), diag::err_duplicate_mangled_name) 5003 << MangledName; 5004 Diags.Report(OtherGD.getDecl()->getLocation(), 5005 diag::note_previous_definition); 5006 } 5007 return; 5008 } 5009 5010 Aliases.push_back(GD); 5011 5012 llvm::Type *DeclTy = getTypes().ConvertTypeForMem(D->getType()); 5013 llvm::Constant *Resolver = 5014 GetOrCreateLLVMFunction(IFA->getResolver(), DeclTy, GD, 5015 /*ForVTable=*/false); 5016 llvm::GlobalIFunc *GIF = 5017 llvm::GlobalIFunc::create(DeclTy, 0, llvm::Function::ExternalLinkage, 5018 "", Resolver, &getModule()); 5019 if (Entry) { 5020 if (GIF->getResolver() == Entry) { 5021 Diags.Report(IFA->getLocation(), diag::err_cyclic_alias) << 1; 5022 return; 5023 } 5024 assert(Entry->isDeclaration()); 5025 5026 // If there is a declaration in the module, then we had an extern followed 5027 // by the ifunc, as in: 5028 // extern int test(); 5029 // ... 5030 // int test() __attribute__((ifunc("resolver"))); 5031 // 5032 // Remove it and replace uses of it with the ifunc. 5033 GIF->takeName(Entry); 5034 5035 Entry->replaceAllUsesWith(llvm::ConstantExpr::getBitCast(GIF, 5036 Entry->getType())); 5037 Entry->eraseFromParent(); 5038 } else 5039 GIF->setName(MangledName); 5040 5041 SetCommonAttributes(GD, GIF); 5042 } 5043 5044 llvm::Function *CodeGenModule::getIntrinsic(unsigned IID, 5045 ArrayRef<llvm::Type*> Tys) { 5046 return llvm::Intrinsic::getDeclaration(&getModule(), (llvm::Intrinsic::ID)IID, 5047 Tys); 5048 } 5049 5050 static llvm::StringMapEntry<llvm::GlobalVariable *> & 5051 GetConstantCFStringEntry(llvm::StringMap<llvm::GlobalVariable *> &Map, 5052 const StringLiteral *Literal, bool TargetIsLSB, 5053 bool &IsUTF16, unsigned &StringLength) { 5054 StringRef String = Literal->getString(); 5055 unsigned NumBytes = String.size(); 5056 5057 // Check for simple case. 5058 if (!Literal->containsNonAsciiOrNull()) { 5059 StringLength = NumBytes; 5060 return *Map.insert(std::make_pair(String, nullptr)).first; 5061 } 5062 5063 // Otherwise, convert the UTF8 literals into a string of shorts. 5064 IsUTF16 = true; 5065 5066 SmallVector<llvm::UTF16, 128> ToBuf(NumBytes + 1); // +1 for ending nulls. 5067 const llvm::UTF8 *FromPtr = (const llvm::UTF8 *)String.data(); 5068 llvm::UTF16 *ToPtr = &ToBuf[0]; 5069 5070 (void)llvm::ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, &ToPtr, 5071 ToPtr + NumBytes, llvm::strictConversion); 5072 5073 // ConvertUTF8toUTF16 returns the length in ToPtr. 5074 StringLength = ToPtr - &ToBuf[0]; 5075 5076 // Add an explicit null. 5077 *ToPtr = 0; 5078 return *Map.insert(std::make_pair( 5079 StringRef(reinterpret_cast<const char *>(ToBuf.data()), 5080 (StringLength + 1) * 2), 5081 nullptr)).first; 5082 } 5083 5084 ConstantAddress 5085 CodeGenModule::GetAddrOfConstantCFString(const StringLiteral *Literal) { 5086 unsigned StringLength = 0; 5087 bool isUTF16 = false; 5088 llvm::StringMapEntry<llvm::GlobalVariable *> &Entry = 5089 GetConstantCFStringEntry(CFConstantStringMap, Literal, 5090 getDataLayout().isLittleEndian(), isUTF16, 5091 StringLength); 5092 5093 if (auto *C = Entry.second) 5094 return ConstantAddress(C, CharUnits::fromQuantity(C->getAlignment())); 5095 5096 llvm::Constant *Zero = llvm::Constant::getNullValue(Int32Ty); 5097 llvm::Constant *Zeros[] = { Zero, Zero }; 5098 5099 const ASTContext &Context = getContext(); 5100 const llvm::Triple &Triple = getTriple(); 5101 5102 const auto CFRuntime = getLangOpts().CFRuntime; 5103 const bool IsSwiftABI = 5104 static_cast<unsigned>(CFRuntime) >= 5105 static_cast<unsigned>(LangOptions::CoreFoundationABI::Swift); 5106 const bool IsSwift4_1 = CFRuntime == LangOptions::CoreFoundationABI::Swift4_1; 5107 5108 // If we don't already have it, get __CFConstantStringClassReference. 5109 if (!CFConstantStringClassRef) { 5110 const char *CFConstantStringClassName = "__CFConstantStringClassReference"; 5111 llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy); 5112 Ty = llvm::ArrayType::get(Ty, 0); 5113 5114 switch (CFRuntime) { 5115 default: break; 5116 case LangOptions::CoreFoundationABI::Swift: LLVM_FALLTHROUGH; 5117 case LangOptions::CoreFoundationABI::Swift5_0: 5118 CFConstantStringClassName = 5119 Triple.isOSDarwin() ? "$s15SwiftFoundation19_NSCFConstantStringCN" 5120 : "$s10Foundation19_NSCFConstantStringCN"; 5121 Ty = IntPtrTy; 5122 break; 5123 case LangOptions::CoreFoundationABI::Swift4_2: 5124 CFConstantStringClassName = 5125 Triple.isOSDarwin() ? "$S15SwiftFoundation19_NSCFConstantStringCN" 5126 : "$S10Foundation19_NSCFConstantStringCN"; 5127 Ty = IntPtrTy; 5128 break; 5129 case LangOptions::CoreFoundationABI::Swift4_1: 5130 CFConstantStringClassName = 5131 Triple.isOSDarwin() ? "__T015SwiftFoundation19_NSCFConstantStringCN" 5132 : "__T010Foundation19_NSCFConstantStringCN"; 5133 Ty = IntPtrTy; 5134 break; 5135 } 5136 5137 llvm::Constant *C = CreateRuntimeVariable(Ty, CFConstantStringClassName); 5138 5139 if (Triple.isOSBinFormatELF() || Triple.isOSBinFormatCOFF()) { 5140 llvm::GlobalValue *GV = nullptr; 5141 5142 if ((GV = dyn_cast<llvm::GlobalValue>(C))) { 5143 IdentifierInfo &II = Context.Idents.get(GV->getName()); 5144 TranslationUnitDecl *TUDecl = Context.getTranslationUnitDecl(); 5145 DeclContext *DC = TranslationUnitDecl::castToDeclContext(TUDecl); 5146 5147 const VarDecl *VD = nullptr; 5148 for (const auto *Result : DC->lookup(&II)) 5149 if ((VD = dyn_cast<VarDecl>(Result))) 5150 break; 5151 5152 if (Triple.isOSBinFormatELF()) { 5153 if (!VD) 5154 GV->setLinkage(llvm::GlobalValue::ExternalLinkage); 5155 } else { 5156 GV->setLinkage(llvm::GlobalValue::ExternalLinkage); 5157 if (!VD || !VD->hasAttr<DLLExportAttr>()) 5158 GV->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass); 5159 else 5160 GV->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass); 5161 } 5162 5163 setDSOLocal(GV); 5164 } 5165 } 5166 5167 // Decay array -> ptr 5168 CFConstantStringClassRef = 5169 IsSwiftABI ? llvm::ConstantExpr::getPtrToInt(C, Ty) 5170 : llvm::ConstantExpr::getGetElementPtr(Ty, C, Zeros); 5171 } 5172 5173 QualType CFTy = Context.getCFConstantStringType(); 5174 5175 auto *STy = cast<llvm::StructType>(getTypes().ConvertType(CFTy)); 5176 5177 ConstantInitBuilder Builder(*this); 5178 auto Fields = Builder.beginStruct(STy); 5179 5180 // Class pointer. 5181 Fields.add(cast<llvm::ConstantExpr>(CFConstantStringClassRef)); 5182 5183 // Flags. 5184 if (IsSwiftABI) { 5185 Fields.addInt(IntPtrTy, IsSwift4_1 ? 0x05 : 0x01); 5186 Fields.addInt(Int64Ty, isUTF16 ? 0x07d0 : 0x07c8); 5187 } else { 5188 Fields.addInt(IntTy, isUTF16 ? 0x07d0 : 0x07C8); 5189 } 5190 5191 // String pointer. 5192 llvm::Constant *C = nullptr; 5193 if (isUTF16) { 5194 auto Arr = llvm::makeArrayRef( 5195 reinterpret_cast<uint16_t *>(const_cast<char *>(Entry.first().data())), 5196 Entry.first().size() / 2); 5197 C = llvm::ConstantDataArray::get(VMContext, Arr); 5198 } else { 5199 C = llvm::ConstantDataArray::getString(VMContext, Entry.first()); 5200 } 5201 5202 // Note: -fwritable-strings doesn't make the backing store strings of 5203 // CFStrings writable. (See <rdar://problem/10657500>) 5204 auto *GV = 5205 new llvm::GlobalVariable(getModule(), C->getType(), /*isConstant=*/true, 5206 llvm::GlobalValue::PrivateLinkage, C, ".str"); 5207 GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global); 5208 // Don't enforce the target's minimum global alignment, since the only use 5209 // of the string is via this class initializer. 5210 CharUnits Align = isUTF16 ? Context.getTypeAlignInChars(Context.ShortTy) 5211 : Context.getTypeAlignInChars(Context.CharTy); 5212 GV->setAlignment(Align.getAsAlign()); 5213 5214 // FIXME: We set the section explicitly to avoid a bug in ld64 224.1. 5215 // Without it LLVM can merge the string with a non unnamed_addr one during 5216 // LTO. Doing that changes the section it ends in, which surprises ld64. 5217 if (Triple.isOSBinFormatMachO()) 5218 GV->setSection(isUTF16 ? "__TEXT,__ustring" 5219 : "__TEXT,__cstring,cstring_literals"); 5220 // Make sure the literal ends up in .rodata to allow for safe ICF and for 5221 // the static linker to adjust permissions to read-only later on. 5222 else if (Triple.isOSBinFormatELF()) 5223 GV->setSection(".rodata"); 5224 5225 // String. 5226 llvm::Constant *Str = 5227 llvm::ConstantExpr::getGetElementPtr(GV->getValueType(), GV, Zeros); 5228 5229 if (isUTF16) 5230 // Cast the UTF16 string to the correct type. 5231 Str = llvm::ConstantExpr::getBitCast(Str, Int8PtrTy); 5232 Fields.add(Str); 5233 5234 // String length. 5235 llvm::IntegerType *LengthTy = 5236 llvm::IntegerType::get(getModule().getContext(), 5237 Context.getTargetInfo().getLongWidth()); 5238 if (IsSwiftABI) { 5239 if (CFRuntime == LangOptions::CoreFoundationABI::Swift4_1 || 5240 CFRuntime == LangOptions::CoreFoundationABI::Swift4_2) 5241 LengthTy = Int32Ty; 5242 else 5243 LengthTy = IntPtrTy; 5244 } 5245 Fields.addInt(LengthTy, StringLength); 5246 5247 // Swift ABI requires 8-byte alignment to ensure that the _Atomic(uint64_t) is 5248 // properly aligned on 32-bit platforms. 5249 CharUnits Alignment = 5250 IsSwiftABI ? Context.toCharUnitsFromBits(64) : getPointerAlign(); 5251 5252 // The struct. 5253 GV = Fields.finishAndCreateGlobal("_unnamed_cfstring_", Alignment, 5254 /*isConstant=*/false, 5255 llvm::GlobalVariable::PrivateLinkage); 5256 GV->addAttribute("objc_arc_inert"); 5257 switch (Triple.getObjectFormat()) { 5258 case llvm::Triple::UnknownObjectFormat: 5259 llvm_unreachable("unknown file format"); 5260 case llvm::Triple::GOFF: 5261 llvm_unreachable("GOFF is not yet implemented"); 5262 case llvm::Triple::XCOFF: 5263 llvm_unreachable("XCOFF is not yet implemented"); 5264 case llvm::Triple::COFF: 5265 case llvm::Triple::ELF: 5266 case llvm::Triple::Wasm: 5267 GV->setSection("cfstring"); 5268 break; 5269 case llvm::Triple::MachO: 5270 GV->setSection("__DATA,__cfstring"); 5271 break; 5272 } 5273 Entry.second = GV; 5274 5275 return ConstantAddress(GV, Alignment); 5276 } 5277 5278 bool CodeGenModule::getExpressionLocationsEnabled() const { 5279 return !CodeGenOpts.EmitCodeView || CodeGenOpts.DebugColumnInfo; 5280 } 5281 5282 QualType CodeGenModule::getObjCFastEnumerationStateType() { 5283 if (ObjCFastEnumerationStateType.isNull()) { 5284 RecordDecl *D = Context.buildImplicitRecord("__objcFastEnumerationState"); 5285 D->startDefinition(); 5286 5287 QualType FieldTypes[] = { 5288 Context.UnsignedLongTy, 5289 Context.getPointerType(Context.getObjCIdType()), 5290 Context.getPointerType(Context.UnsignedLongTy), 5291 Context.getConstantArrayType(Context.UnsignedLongTy, 5292 llvm::APInt(32, 5), nullptr, ArrayType::Normal, 0) 5293 }; 5294 5295 for (size_t i = 0; i < 4; ++i) { 5296 FieldDecl *Field = FieldDecl::Create(Context, 5297 D, 5298 SourceLocation(), 5299 SourceLocation(), nullptr, 5300 FieldTypes[i], /*TInfo=*/nullptr, 5301 /*BitWidth=*/nullptr, 5302 /*Mutable=*/false, 5303 ICIS_NoInit); 5304 Field->setAccess(AS_public); 5305 D->addDecl(Field); 5306 } 5307 5308 D->completeDefinition(); 5309 ObjCFastEnumerationStateType = Context.getTagDeclType(D); 5310 } 5311 5312 return ObjCFastEnumerationStateType; 5313 } 5314 5315 llvm::Constant * 5316 CodeGenModule::GetConstantArrayFromStringLiteral(const StringLiteral *E) { 5317 assert(!E->getType()->isPointerType() && "Strings are always arrays"); 5318 5319 // Don't emit it as the address of the string, emit the string data itself 5320 // as an inline array. 5321 if (E->getCharByteWidth() == 1) { 5322 SmallString<64> Str(E->getString()); 5323 5324 // Resize the string to the right size, which is indicated by its type. 5325 const ConstantArrayType *CAT = Context.getAsConstantArrayType(E->getType()); 5326 Str.resize(CAT->getSize().getZExtValue()); 5327 return llvm::ConstantDataArray::getString(VMContext, Str, false); 5328 } 5329 5330 auto *AType = cast<llvm::ArrayType>(getTypes().ConvertType(E->getType())); 5331 llvm::Type *ElemTy = AType->getElementType(); 5332 unsigned NumElements = AType->getNumElements(); 5333 5334 // Wide strings have either 2-byte or 4-byte elements. 5335 if (ElemTy->getPrimitiveSizeInBits() == 16) { 5336 SmallVector<uint16_t, 32> Elements; 5337 Elements.reserve(NumElements); 5338 5339 for(unsigned i = 0, e = E->getLength(); i != e; ++i) 5340 Elements.push_back(E->getCodeUnit(i)); 5341 Elements.resize(NumElements); 5342 return llvm::ConstantDataArray::get(VMContext, Elements); 5343 } 5344 5345 assert(ElemTy->getPrimitiveSizeInBits() == 32); 5346 SmallVector<uint32_t, 32> Elements; 5347 Elements.reserve(NumElements); 5348 5349 for(unsigned i = 0, e = E->getLength(); i != e; ++i) 5350 Elements.push_back(E->getCodeUnit(i)); 5351 Elements.resize(NumElements); 5352 return llvm::ConstantDataArray::get(VMContext, Elements); 5353 } 5354 5355 static llvm::GlobalVariable * 5356 GenerateStringLiteral(llvm::Constant *C, llvm::GlobalValue::LinkageTypes LT, 5357 CodeGenModule &CGM, StringRef GlobalName, 5358 CharUnits Alignment) { 5359 unsigned AddrSpace = CGM.getContext().getTargetAddressSpace( 5360 CGM.GetGlobalConstantAddressSpace()); 5361 5362 llvm::Module &M = CGM.getModule(); 5363 // Create a global variable for this string 5364 auto *GV = new llvm::GlobalVariable( 5365 M, C->getType(), !CGM.getLangOpts().WritableStrings, LT, C, GlobalName, 5366 nullptr, llvm::GlobalVariable::NotThreadLocal, AddrSpace); 5367 GV->setAlignment(Alignment.getAsAlign()); 5368 GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global); 5369 if (GV->isWeakForLinker()) { 5370 assert(CGM.supportsCOMDAT() && "Only COFF uses weak string literals"); 5371 GV->setComdat(M.getOrInsertComdat(GV->getName())); 5372 } 5373 CGM.setDSOLocal(GV); 5374 5375 return GV; 5376 } 5377 5378 /// GetAddrOfConstantStringFromLiteral - Return a pointer to a 5379 /// constant array for the given string literal. 5380 ConstantAddress 5381 CodeGenModule::GetAddrOfConstantStringFromLiteral(const StringLiteral *S, 5382 StringRef Name) { 5383 CharUnits Alignment = getContext().getAlignOfGlobalVarInChars(S->getType()); 5384 5385 llvm::Constant *C = GetConstantArrayFromStringLiteral(S); 5386 llvm::GlobalVariable **Entry = nullptr; 5387 if (!LangOpts.WritableStrings) { 5388 Entry = &ConstantStringMap[C]; 5389 if (auto GV = *Entry) { 5390 if (uint64_t(Alignment.getQuantity()) > GV->getAlignment()) 5391 GV->setAlignment(Alignment.getAsAlign()); 5392 return ConstantAddress(castStringLiteralToDefaultAddressSpace(*this, GV), 5393 Alignment); 5394 } 5395 } 5396 5397 SmallString<256> MangledNameBuffer; 5398 StringRef GlobalVariableName; 5399 llvm::GlobalValue::LinkageTypes LT; 5400 5401 // Mangle the string literal if that's how the ABI merges duplicate strings. 5402 // Don't do it if they are writable, since we don't want writes in one TU to 5403 // affect strings in another. 5404 if (getCXXABI().getMangleContext().shouldMangleStringLiteral(S) && 5405 !LangOpts.WritableStrings) { 5406 llvm::raw_svector_ostream Out(MangledNameBuffer); 5407 getCXXABI().getMangleContext().mangleStringLiteral(S, Out); 5408 LT = llvm::GlobalValue::LinkOnceODRLinkage; 5409 GlobalVariableName = MangledNameBuffer; 5410 } else { 5411 LT = llvm::GlobalValue::PrivateLinkage; 5412 GlobalVariableName = Name; 5413 } 5414 5415 auto GV = GenerateStringLiteral(C, LT, *this, GlobalVariableName, Alignment); 5416 if (Entry) 5417 *Entry = GV; 5418 5419 SanitizerMD->reportGlobalToASan(GV, S->getStrTokenLoc(0), "<string literal>", 5420 QualType()); 5421 5422 return ConstantAddress(castStringLiteralToDefaultAddressSpace(*this, GV), 5423 Alignment); 5424 } 5425 5426 /// GetAddrOfConstantStringFromObjCEncode - Return a pointer to a constant 5427 /// array for the given ObjCEncodeExpr node. 5428 ConstantAddress 5429 CodeGenModule::GetAddrOfConstantStringFromObjCEncode(const ObjCEncodeExpr *E) { 5430 std::string Str; 5431 getContext().getObjCEncodingForType(E->getEncodedType(), Str); 5432 5433 return GetAddrOfConstantCString(Str); 5434 } 5435 5436 /// GetAddrOfConstantCString - Returns a pointer to a character array containing 5437 /// the literal and a terminating '\0' character. 5438 /// The result has pointer to array type. 5439 ConstantAddress CodeGenModule::GetAddrOfConstantCString( 5440 const std::string &Str, const char *GlobalName) { 5441 StringRef StrWithNull(Str.c_str(), Str.size() + 1); 5442 CharUnits Alignment = 5443 getContext().getAlignOfGlobalVarInChars(getContext().CharTy); 5444 5445 llvm::Constant *C = 5446 llvm::ConstantDataArray::getString(getLLVMContext(), StrWithNull, false); 5447 5448 // Don't share any string literals if strings aren't constant. 5449 llvm::GlobalVariable **Entry = nullptr; 5450 if (!LangOpts.WritableStrings) { 5451 Entry = &ConstantStringMap[C]; 5452 if (auto GV = *Entry) { 5453 if (uint64_t(Alignment.getQuantity()) > GV->getAlignment()) 5454 GV->setAlignment(Alignment.getAsAlign()); 5455 return ConstantAddress(castStringLiteralToDefaultAddressSpace(*this, GV), 5456 Alignment); 5457 } 5458 } 5459 5460 // Get the default prefix if a name wasn't specified. 5461 if (!GlobalName) 5462 GlobalName = ".str"; 5463 // Create a global variable for this. 5464 auto GV = GenerateStringLiteral(C, llvm::GlobalValue::PrivateLinkage, *this, 5465 GlobalName, Alignment); 5466 if (Entry) 5467 *Entry = GV; 5468 5469 return ConstantAddress(castStringLiteralToDefaultAddressSpace(*this, GV), 5470 Alignment); 5471 } 5472 5473 ConstantAddress CodeGenModule::GetAddrOfGlobalTemporary( 5474 const MaterializeTemporaryExpr *E, const Expr *Init) { 5475 assert((E->getStorageDuration() == SD_Static || 5476 E->getStorageDuration() == SD_Thread) && "not a global temporary"); 5477 const auto *VD = cast<VarDecl>(E->getExtendingDecl()); 5478 5479 // If we're not materializing a subobject of the temporary, keep the 5480 // cv-qualifiers from the type of the MaterializeTemporaryExpr. 5481 QualType MaterializedType = Init->getType(); 5482 if (Init == E->getSubExpr()) 5483 MaterializedType = E->getType(); 5484 5485 CharUnits Align = getContext().getTypeAlignInChars(MaterializedType); 5486 5487 auto InsertResult = MaterializedGlobalTemporaryMap.insert({E, nullptr}); 5488 if (!InsertResult.second) { 5489 // We've seen this before: either we already created it or we're in the 5490 // process of doing so. 5491 if (!InsertResult.first->second) { 5492 // We recursively re-entered this function, probably during emission of 5493 // the initializer. Create a placeholder. We'll clean this up in the 5494 // outer call, at the end of this function. 5495 llvm::Type *Type = getTypes().ConvertTypeForMem(MaterializedType); 5496 InsertResult.first->second = new llvm::GlobalVariable( 5497 getModule(), Type, false, llvm::GlobalVariable::InternalLinkage, 5498 nullptr); 5499 } 5500 return ConstantAddress(InsertResult.first->second, Align); 5501 } 5502 5503 // FIXME: If an externally-visible declaration extends multiple temporaries, 5504 // we need to give each temporary the same name in every translation unit (and 5505 // we also need to make the temporaries externally-visible). 5506 SmallString<256> Name; 5507 llvm::raw_svector_ostream Out(Name); 5508 getCXXABI().getMangleContext().mangleReferenceTemporary( 5509 VD, E->getManglingNumber(), Out); 5510 5511 APValue *Value = nullptr; 5512 if (E->getStorageDuration() == SD_Static && VD && VD->evaluateValue()) { 5513 // If the initializer of the extending declaration is a constant 5514 // initializer, we should have a cached constant initializer for this 5515 // temporary. Note that this might have a different value from the value 5516 // computed by evaluating the initializer if the surrounding constant 5517 // expression modifies the temporary. 5518 Value = E->getOrCreateValue(false); 5519 } 5520 5521 // Try evaluating it now, it might have a constant initializer. 5522 Expr::EvalResult EvalResult; 5523 if (!Value && Init->EvaluateAsRValue(EvalResult, getContext()) && 5524 !EvalResult.hasSideEffects()) 5525 Value = &EvalResult.Val; 5526 5527 LangAS AddrSpace = 5528 VD ? GetGlobalVarAddressSpace(VD) : MaterializedType.getAddressSpace(); 5529 5530 Optional<ConstantEmitter> emitter; 5531 llvm::Constant *InitialValue = nullptr; 5532 bool Constant = false; 5533 llvm::Type *Type; 5534 if (Value) { 5535 // The temporary has a constant initializer, use it. 5536 emitter.emplace(*this); 5537 InitialValue = emitter->emitForInitializer(*Value, AddrSpace, 5538 MaterializedType); 5539 Constant = isTypeConstant(MaterializedType, /*ExcludeCtor*/Value); 5540 Type = InitialValue->getType(); 5541 } else { 5542 // No initializer, the initialization will be provided when we 5543 // initialize the declaration which performed lifetime extension. 5544 Type = getTypes().ConvertTypeForMem(MaterializedType); 5545 } 5546 5547 // Create a global variable for this lifetime-extended temporary. 5548 llvm::GlobalValue::LinkageTypes Linkage = 5549 getLLVMLinkageVarDefinition(VD, Constant); 5550 if (Linkage == llvm::GlobalVariable::ExternalLinkage) { 5551 const VarDecl *InitVD; 5552 if (VD->isStaticDataMember() && VD->getAnyInitializer(InitVD) && 5553 isa<CXXRecordDecl>(InitVD->getLexicalDeclContext())) { 5554 // Temporaries defined inside a class get linkonce_odr linkage because the 5555 // class can be defined in multiple translation units. 5556 Linkage = llvm::GlobalVariable::LinkOnceODRLinkage; 5557 } else { 5558 // There is no need for this temporary to have external linkage if the 5559 // VarDecl has external linkage. 5560 Linkage = llvm::GlobalVariable::InternalLinkage; 5561 } 5562 } 5563 auto TargetAS = getContext().getTargetAddressSpace(AddrSpace); 5564 auto *GV = new llvm::GlobalVariable( 5565 getModule(), Type, Constant, Linkage, InitialValue, Name.c_str(), 5566 /*InsertBefore=*/nullptr, llvm::GlobalVariable::NotThreadLocal, TargetAS); 5567 if (emitter) emitter->finalize(GV); 5568 setGVProperties(GV, VD); 5569 GV->setAlignment(Align.getAsAlign()); 5570 if (supportsCOMDAT() && GV->isWeakForLinker()) 5571 GV->setComdat(TheModule.getOrInsertComdat(GV->getName())); 5572 if (VD->getTLSKind()) 5573 setTLSMode(GV, *VD); 5574 llvm::Constant *CV = GV; 5575 if (AddrSpace != LangAS::Default) 5576 CV = getTargetCodeGenInfo().performAddrSpaceCast( 5577 *this, GV, AddrSpace, LangAS::Default, 5578 Type->getPointerTo( 5579 getContext().getTargetAddressSpace(LangAS::Default))); 5580 5581 // Update the map with the new temporary. If we created a placeholder above, 5582 // replace it with the new global now. 5583 llvm::Constant *&Entry = MaterializedGlobalTemporaryMap[E]; 5584 if (Entry) { 5585 Entry->replaceAllUsesWith( 5586 llvm::ConstantExpr::getBitCast(CV, Entry->getType())); 5587 llvm::cast<llvm::GlobalVariable>(Entry)->eraseFromParent(); 5588 } 5589 Entry = CV; 5590 5591 return ConstantAddress(CV, Align); 5592 } 5593 5594 /// EmitObjCPropertyImplementations - Emit information for synthesized 5595 /// properties for an implementation. 5596 void CodeGenModule::EmitObjCPropertyImplementations(const 5597 ObjCImplementationDecl *D) { 5598 for (const auto *PID : D->property_impls()) { 5599 // Dynamic is just for type-checking. 5600 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize) { 5601 ObjCPropertyDecl *PD = PID->getPropertyDecl(); 5602 5603 // Determine which methods need to be implemented, some may have 5604 // been overridden. Note that ::isPropertyAccessor is not the method 5605 // we want, that just indicates if the decl came from a 5606 // property. What we want to know is if the method is defined in 5607 // this implementation. 5608 auto *Getter = PID->getGetterMethodDecl(); 5609 if (!Getter || Getter->isSynthesizedAccessorStub()) 5610 CodeGenFunction(*this).GenerateObjCGetter( 5611 const_cast<ObjCImplementationDecl *>(D), PID); 5612 auto *Setter = PID->getSetterMethodDecl(); 5613 if (!PD->isReadOnly() && (!Setter || Setter->isSynthesizedAccessorStub())) 5614 CodeGenFunction(*this).GenerateObjCSetter( 5615 const_cast<ObjCImplementationDecl *>(D), PID); 5616 } 5617 } 5618 } 5619 5620 static bool needsDestructMethod(ObjCImplementationDecl *impl) { 5621 const ObjCInterfaceDecl *iface = impl->getClassInterface(); 5622 for (const ObjCIvarDecl *ivar = iface->all_declared_ivar_begin(); 5623 ivar; ivar = ivar->getNextIvar()) 5624 if (ivar->getType().isDestructedType()) 5625 return true; 5626 5627 return false; 5628 } 5629 5630 static bool AllTrivialInitializers(CodeGenModule &CGM, 5631 ObjCImplementationDecl *D) { 5632 CodeGenFunction CGF(CGM); 5633 for (ObjCImplementationDecl::init_iterator B = D->init_begin(), 5634 E = D->init_end(); B != E; ++B) { 5635 CXXCtorInitializer *CtorInitExp = *B; 5636 Expr *Init = CtorInitExp->getInit(); 5637 if (!CGF.isTrivialInitializer(Init)) 5638 return false; 5639 } 5640 return true; 5641 } 5642 5643 /// EmitObjCIvarInitializations - Emit information for ivar initialization 5644 /// for an implementation. 5645 void CodeGenModule::EmitObjCIvarInitializations(ObjCImplementationDecl *D) { 5646 // We might need a .cxx_destruct even if we don't have any ivar initializers. 5647 if (needsDestructMethod(D)) { 5648 IdentifierInfo *II = &getContext().Idents.get(".cxx_destruct"); 5649 Selector cxxSelector = getContext().Selectors.getSelector(0, &II); 5650 ObjCMethodDecl *DTORMethod = ObjCMethodDecl::Create( 5651 getContext(), D->getLocation(), D->getLocation(), cxxSelector, 5652 getContext().VoidTy, nullptr, D, 5653 /*isInstance=*/true, /*isVariadic=*/false, 5654 /*isPropertyAccessor=*/true, /*isSynthesizedAccessorStub=*/false, 5655 /*isImplicitlyDeclared=*/true, 5656 /*isDefined=*/false, ObjCMethodDecl::Required); 5657 D->addInstanceMethod(DTORMethod); 5658 CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, DTORMethod, false); 5659 D->setHasDestructors(true); 5660 } 5661 5662 // If the implementation doesn't have any ivar initializers, we don't need 5663 // a .cxx_construct. 5664 if (D->getNumIvarInitializers() == 0 || 5665 AllTrivialInitializers(*this, D)) 5666 return; 5667 5668 IdentifierInfo *II = &getContext().Idents.get(".cxx_construct"); 5669 Selector cxxSelector = getContext().Selectors.getSelector(0, &II); 5670 // The constructor returns 'self'. 5671 ObjCMethodDecl *CTORMethod = ObjCMethodDecl::Create( 5672 getContext(), D->getLocation(), D->getLocation(), cxxSelector, 5673 getContext().getObjCIdType(), nullptr, D, /*isInstance=*/true, 5674 /*isVariadic=*/false, 5675 /*isPropertyAccessor=*/true, /*isSynthesizedAccessorStub=*/false, 5676 /*isImplicitlyDeclared=*/true, 5677 /*isDefined=*/false, ObjCMethodDecl::Required); 5678 D->addInstanceMethod(CTORMethod); 5679 CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, CTORMethod, true); 5680 D->setHasNonZeroConstructors(true); 5681 } 5682 5683 // EmitLinkageSpec - Emit all declarations in a linkage spec. 5684 void CodeGenModule::EmitLinkageSpec(const LinkageSpecDecl *LSD) { 5685 if (LSD->getLanguage() != LinkageSpecDecl::lang_c && 5686 LSD->getLanguage() != LinkageSpecDecl::lang_cxx) { 5687 ErrorUnsupported(LSD, "linkage spec"); 5688 return; 5689 } 5690 5691 EmitDeclContext(LSD); 5692 } 5693 5694 void CodeGenModule::EmitDeclContext(const DeclContext *DC) { 5695 for (auto *I : DC->decls()) { 5696 // Unlike other DeclContexts, the contents of an ObjCImplDecl at TU scope 5697 // are themselves considered "top-level", so EmitTopLevelDecl on an 5698 // ObjCImplDecl does not recursively visit them. We need to do that in 5699 // case they're nested inside another construct (LinkageSpecDecl / 5700 // ExportDecl) that does stop them from being considered "top-level". 5701 if (auto *OID = dyn_cast<ObjCImplDecl>(I)) { 5702 for (auto *M : OID->methods()) 5703 EmitTopLevelDecl(M); 5704 } 5705 5706 EmitTopLevelDecl(I); 5707 } 5708 } 5709 5710 /// EmitTopLevelDecl - Emit code for a single top level declaration. 5711 void CodeGenModule::EmitTopLevelDecl(Decl *D) { 5712 // Ignore dependent declarations. 5713 if (D->isTemplated()) 5714 return; 5715 5716 // Consteval function shouldn't be emitted. 5717 if (auto *FD = dyn_cast<FunctionDecl>(D)) 5718 if (FD->isConsteval()) 5719 return; 5720 5721 switch (D->getKind()) { 5722 case Decl::CXXConversion: 5723 case Decl::CXXMethod: 5724 case Decl::Function: 5725 EmitGlobal(cast<FunctionDecl>(D)); 5726 // Always provide some coverage mapping 5727 // even for the functions that aren't emitted. 5728 AddDeferredUnusedCoverageMapping(D); 5729 break; 5730 5731 case Decl::CXXDeductionGuide: 5732 // Function-like, but does not result in code emission. 5733 break; 5734 5735 case Decl::Var: 5736 case Decl::Decomposition: 5737 case Decl::VarTemplateSpecialization: 5738 EmitGlobal(cast<VarDecl>(D)); 5739 if (auto *DD = dyn_cast<DecompositionDecl>(D)) 5740 for (auto *B : DD->bindings()) 5741 if (auto *HD = B->getHoldingVar()) 5742 EmitGlobal(HD); 5743 break; 5744 5745 // Indirect fields from global anonymous structs and unions can be 5746 // ignored; only the actual variable requires IR gen support. 5747 case Decl::IndirectField: 5748 break; 5749 5750 // C++ Decls 5751 case Decl::Namespace: 5752 EmitDeclContext(cast<NamespaceDecl>(D)); 5753 break; 5754 case Decl::ClassTemplateSpecialization: { 5755 const auto *Spec = cast<ClassTemplateSpecializationDecl>(D); 5756 if (CGDebugInfo *DI = getModuleDebugInfo()) 5757 if (Spec->getSpecializationKind() == 5758 TSK_ExplicitInstantiationDefinition && 5759 Spec->hasDefinition()) 5760 DI->completeTemplateDefinition(*Spec); 5761 } LLVM_FALLTHROUGH; 5762 case Decl::CXXRecord: { 5763 CXXRecordDecl *CRD = cast<CXXRecordDecl>(D); 5764 if (CGDebugInfo *DI = getModuleDebugInfo()) { 5765 if (CRD->hasDefinition()) 5766 DI->EmitAndRetainType(getContext().getRecordType(cast<RecordDecl>(D))); 5767 if (auto *ES = D->getASTContext().getExternalSource()) 5768 if (ES->hasExternalDefinitions(D) == ExternalASTSource::EK_Never) 5769 DI->completeUnusedClass(*CRD); 5770 } 5771 // Emit any static data members, they may be definitions. 5772 for (auto *I : CRD->decls()) 5773 if (isa<VarDecl>(I) || isa<CXXRecordDecl>(I)) 5774 EmitTopLevelDecl(I); 5775 break; 5776 } 5777 // No code generation needed. 5778 case Decl::UsingShadow: 5779 case Decl::ClassTemplate: 5780 case Decl::VarTemplate: 5781 case Decl::Concept: 5782 case Decl::VarTemplatePartialSpecialization: 5783 case Decl::FunctionTemplate: 5784 case Decl::TypeAliasTemplate: 5785 case Decl::Block: 5786 case Decl::Empty: 5787 case Decl::Binding: 5788 break; 5789 case Decl::Using: // using X; [C++] 5790 if (CGDebugInfo *DI = getModuleDebugInfo()) 5791 DI->EmitUsingDecl(cast<UsingDecl>(*D)); 5792 break; 5793 case Decl::UsingEnum: // using enum X; [C++] 5794 if (CGDebugInfo *DI = getModuleDebugInfo()) 5795 DI->EmitUsingEnumDecl(cast<UsingEnumDecl>(*D)); 5796 break; 5797 case Decl::NamespaceAlias: 5798 if (CGDebugInfo *DI = getModuleDebugInfo()) 5799 DI->EmitNamespaceAlias(cast<NamespaceAliasDecl>(*D)); 5800 break; 5801 case Decl::UsingDirective: // using namespace X; [C++] 5802 if (CGDebugInfo *DI = getModuleDebugInfo()) 5803 DI->EmitUsingDirective(cast<UsingDirectiveDecl>(*D)); 5804 break; 5805 case Decl::CXXConstructor: 5806 getCXXABI().EmitCXXConstructors(cast<CXXConstructorDecl>(D)); 5807 break; 5808 case Decl::CXXDestructor: 5809 getCXXABI().EmitCXXDestructors(cast<CXXDestructorDecl>(D)); 5810 break; 5811 5812 case Decl::StaticAssert: 5813 // Nothing to do. 5814 break; 5815 5816 // Objective-C Decls 5817 5818 // Forward declarations, no (immediate) code generation. 5819 case Decl::ObjCInterface: 5820 case Decl::ObjCCategory: 5821 break; 5822 5823 case Decl::ObjCProtocol: { 5824 auto *Proto = cast<ObjCProtocolDecl>(D); 5825 if (Proto->isThisDeclarationADefinition()) 5826 ObjCRuntime->GenerateProtocol(Proto); 5827 break; 5828 } 5829 5830 case Decl::ObjCCategoryImpl: 5831 // Categories have properties but don't support synthesize so we 5832 // can ignore them here. 5833 ObjCRuntime->GenerateCategory(cast<ObjCCategoryImplDecl>(D)); 5834 break; 5835 5836 case Decl::ObjCImplementation: { 5837 auto *OMD = cast<ObjCImplementationDecl>(D); 5838 EmitObjCPropertyImplementations(OMD); 5839 EmitObjCIvarInitializations(OMD); 5840 ObjCRuntime->GenerateClass(OMD); 5841 // Emit global variable debug information. 5842 if (CGDebugInfo *DI = getModuleDebugInfo()) 5843 if (getCodeGenOpts().hasReducedDebugInfo()) 5844 DI->getOrCreateInterfaceType(getContext().getObjCInterfaceType( 5845 OMD->getClassInterface()), OMD->getLocation()); 5846 break; 5847 } 5848 case Decl::ObjCMethod: { 5849 auto *OMD = cast<ObjCMethodDecl>(D); 5850 // If this is not a prototype, emit the body. 5851 if (OMD->getBody()) 5852 CodeGenFunction(*this).GenerateObjCMethod(OMD); 5853 break; 5854 } 5855 case Decl::ObjCCompatibleAlias: 5856 ObjCRuntime->RegisterAlias(cast<ObjCCompatibleAliasDecl>(D)); 5857 break; 5858 5859 case Decl::PragmaComment: { 5860 const auto *PCD = cast<PragmaCommentDecl>(D); 5861 switch (PCD->getCommentKind()) { 5862 case PCK_Unknown: 5863 llvm_unreachable("unexpected pragma comment kind"); 5864 case PCK_Linker: 5865 AppendLinkerOptions(PCD->getArg()); 5866 break; 5867 case PCK_Lib: 5868 AddDependentLib(PCD->getArg()); 5869 break; 5870 case PCK_Compiler: 5871 case PCK_ExeStr: 5872 case PCK_User: 5873 break; // We ignore all of these. 5874 } 5875 break; 5876 } 5877 5878 case Decl::PragmaDetectMismatch: { 5879 const auto *PDMD = cast<PragmaDetectMismatchDecl>(D); 5880 AddDetectMismatch(PDMD->getName(), PDMD->getValue()); 5881 break; 5882 } 5883 5884 case Decl::LinkageSpec: 5885 EmitLinkageSpec(cast<LinkageSpecDecl>(D)); 5886 break; 5887 5888 case Decl::FileScopeAsm: { 5889 // File-scope asm is ignored during device-side CUDA compilation. 5890 if (LangOpts.CUDA && LangOpts.CUDAIsDevice) 5891 break; 5892 // File-scope asm is ignored during device-side OpenMP compilation. 5893 if (LangOpts.OpenMPIsDevice) 5894 break; 5895 // File-scope asm is ignored during device-side SYCL compilation. 5896 if (LangOpts.SYCLIsDevice) 5897 break; 5898 auto *AD = cast<FileScopeAsmDecl>(D); 5899 getModule().appendModuleInlineAsm(AD->getAsmString()->getString()); 5900 break; 5901 } 5902 5903 case Decl::Import: { 5904 auto *Import = cast<ImportDecl>(D); 5905 5906 // If we've already imported this module, we're done. 5907 if (!ImportedModules.insert(Import->getImportedModule())) 5908 break; 5909 5910 // Emit debug information for direct imports. 5911 if (!Import->getImportedOwningModule()) { 5912 if (CGDebugInfo *DI = getModuleDebugInfo()) 5913 DI->EmitImportDecl(*Import); 5914 } 5915 5916 // Find all of the submodules and emit the module initializers. 5917 llvm::SmallPtrSet<clang::Module *, 16> Visited; 5918 SmallVector<clang::Module *, 16> Stack; 5919 Visited.insert(Import->getImportedModule()); 5920 Stack.push_back(Import->getImportedModule()); 5921 5922 while (!Stack.empty()) { 5923 clang::Module *Mod = Stack.pop_back_val(); 5924 if (!EmittedModuleInitializers.insert(Mod).second) 5925 continue; 5926 5927 for (auto *D : Context.getModuleInitializers(Mod)) 5928 EmitTopLevelDecl(D); 5929 5930 // Visit the submodules of this module. 5931 for (clang::Module::submodule_iterator Sub = Mod->submodule_begin(), 5932 SubEnd = Mod->submodule_end(); 5933 Sub != SubEnd; ++Sub) { 5934 // Skip explicit children; they need to be explicitly imported to emit 5935 // the initializers. 5936 if ((*Sub)->IsExplicit) 5937 continue; 5938 5939 if (Visited.insert(*Sub).second) 5940 Stack.push_back(*Sub); 5941 } 5942 } 5943 break; 5944 } 5945 5946 case Decl::Export: 5947 EmitDeclContext(cast<ExportDecl>(D)); 5948 break; 5949 5950 case Decl::OMPThreadPrivate: 5951 EmitOMPThreadPrivateDecl(cast<OMPThreadPrivateDecl>(D)); 5952 break; 5953 5954 case Decl::OMPAllocate: 5955 EmitOMPAllocateDecl(cast<OMPAllocateDecl>(D)); 5956 break; 5957 5958 case Decl::OMPDeclareReduction: 5959 EmitOMPDeclareReduction(cast<OMPDeclareReductionDecl>(D)); 5960 break; 5961 5962 case Decl::OMPDeclareMapper: 5963 EmitOMPDeclareMapper(cast<OMPDeclareMapperDecl>(D)); 5964 break; 5965 5966 case Decl::OMPRequires: 5967 EmitOMPRequiresDecl(cast<OMPRequiresDecl>(D)); 5968 break; 5969 5970 case Decl::Typedef: 5971 case Decl::TypeAlias: // using foo = bar; [C++11] 5972 if (CGDebugInfo *DI = getModuleDebugInfo()) 5973 DI->EmitAndRetainType( 5974 getContext().getTypedefType(cast<TypedefNameDecl>(D))); 5975 break; 5976 5977 case Decl::Record: 5978 if (CGDebugInfo *DI = getModuleDebugInfo()) 5979 if (cast<RecordDecl>(D)->getDefinition()) 5980 DI->EmitAndRetainType(getContext().getRecordType(cast<RecordDecl>(D))); 5981 break; 5982 5983 case Decl::Enum: 5984 if (CGDebugInfo *DI = getModuleDebugInfo()) 5985 if (cast<EnumDecl>(D)->getDefinition()) 5986 DI->EmitAndRetainType(getContext().getEnumType(cast<EnumDecl>(D))); 5987 break; 5988 5989 default: 5990 // Make sure we handled everything we should, every other kind is a 5991 // non-top-level decl. FIXME: Would be nice to have an isTopLevelDeclKind 5992 // function. Need to recode Decl::Kind to do that easily. 5993 assert(isa<TypeDecl>(D) && "Unsupported decl kind"); 5994 break; 5995 } 5996 } 5997 5998 void CodeGenModule::AddDeferredUnusedCoverageMapping(Decl *D) { 5999 // Do we need to generate coverage mapping? 6000 if (!CodeGenOpts.CoverageMapping) 6001 return; 6002 switch (D->getKind()) { 6003 case Decl::CXXConversion: 6004 case Decl::CXXMethod: 6005 case Decl::Function: 6006 case Decl::ObjCMethod: 6007 case Decl::CXXConstructor: 6008 case Decl::CXXDestructor: { 6009 if (!cast<FunctionDecl>(D)->doesThisDeclarationHaveABody()) 6010 break; 6011 SourceManager &SM = getContext().getSourceManager(); 6012 if (LimitedCoverage && SM.getMainFileID() != SM.getFileID(D->getBeginLoc())) 6013 break; 6014 auto I = DeferredEmptyCoverageMappingDecls.find(D); 6015 if (I == DeferredEmptyCoverageMappingDecls.end()) 6016 DeferredEmptyCoverageMappingDecls[D] = true; 6017 break; 6018 } 6019 default: 6020 break; 6021 }; 6022 } 6023 6024 void CodeGenModule::ClearUnusedCoverageMapping(const Decl *D) { 6025 // Do we need to generate coverage mapping? 6026 if (!CodeGenOpts.CoverageMapping) 6027 return; 6028 if (const auto *Fn = dyn_cast<FunctionDecl>(D)) { 6029 if (Fn->isTemplateInstantiation()) 6030 ClearUnusedCoverageMapping(Fn->getTemplateInstantiationPattern()); 6031 } 6032 auto I = DeferredEmptyCoverageMappingDecls.find(D); 6033 if (I == DeferredEmptyCoverageMappingDecls.end()) 6034 DeferredEmptyCoverageMappingDecls[D] = false; 6035 else 6036 I->second = false; 6037 } 6038 6039 void CodeGenModule::EmitDeferredUnusedCoverageMappings() { 6040 // We call takeVector() here to avoid use-after-free. 6041 // FIXME: DeferredEmptyCoverageMappingDecls is getting mutated because 6042 // we deserialize function bodies to emit coverage info for them, and that 6043 // deserializes more declarations. How should we handle that case? 6044 for (const auto &Entry : DeferredEmptyCoverageMappingDecls.takeVector()) { 6045 if (!Entry.second) 6046 continue; 6047 const Decl *D = Entry.first; 6048 switch (D->getKind()) { 6049 case Decl::CXXConversion: 6050 case Decl::CXXMethod: 6051 case Decl::Function: 6052 case Decl::ObjCMethod: { 6053 CodeGenPGO PGO(*this); 6054 GlobalDecl GD(cast<FunctionDecl>(D)); 6055 PGO.emitEmptyCounterMapping(D, getMangledName(GD), 6056 getFunctionLinkage(GD)); 6057 break; 6058 } 6059 case Decl::CXXConstructor: { 6060 CodeGenPGO PGO(*this); 6061 GlobalDecl GD(cast<CXXConstructorDecl>(D), Ctor_Base); 6062 PGO.emitEmptyCounterMapping(D, getMangledName(GD), 6063 getFunctionLinkage(GD)); 6064 break; 6065 } 6066 case Decl::CXXDestructor: { 6067 CodeGenPGO PGO(*this); 6068 GlobalDecl GD(cast<CXXDestructorDecl>(D), Dtor_Base); 6069 PGO.emitEmptyCounterMapping(D, getMangledName(GD), 6070 getFunctionLinkage(GD)); 6071 break; 6072 } 6073 default: 6074 break; 6075 }; 6076 } 6077 } 6078 6079 void CodeGenModule::EmitMainVoidAlias() { 6080 // In order to transition away from "__original_main" gracefully, emit an 6081 // alias for "main" in the no-argument case so that libc can detect when 6082 // new-style no-argument main is in used. 6083 if (llvm::Function *F = getModule().getFunction("main")) { 6084 if (!F->isDeclaration() && F->arg_size() == 0 && !F->isVarArg() && 6085 F->getReturnType()->isIntegerTy(Context.getTargetInfo().getIntWidth())) 6086 addUsedGlobal(llvm::GlobalAlias::create("__main_void", F)); 6087 } 6088 } 6089 6090 /// Turns the given pointer into a constant. 6091 static llvm::Constant *GetPointerConstant(llvm::LLVMContext &Context, 6092 const void *Ptr) { 6093 uintptr_t PtrInt = reinterpret_cast<uintptr_t>(Ptr); 6094 llvm::Type *i64 = llvm::Type::getInt64Ty(Context); 6095 return llvm::ConstantInt::get(i64, PtrInt); 6096 } 6097 6098 static void EmitGlobalDeclMetadata(CodeGenModule &CGM, 6099 llvm::NamedMDNode *&GlobalMetadata, 6100 GlobalDecl D, 6101 llvm::GlobalValue *Addr) { 6102 if (!GlobalMetadata) 6103 GlobalMetadata = 6104 CGM.getModule().getOrInsertNamedMetadata("clang.global.decl.ptrs"); 6105 6106 // TODO: should we report variant information for ctors/dtors? 6107 llvm::Metadata *Ops[] = {llvm::ConstantAsMetadata::get(Addr), 6108 llvm::ConstantAsMetadata::get(GetPointerConstant( 6109 CGM.getLLVMContext(), D.getDecl()))}; 6110 GlobalMetadata->addOperand(llvm::MDNode::get(CGM.getLLVMContext(), Ops)); 6111 } 6112 6113 /// For each function which is declared within an extern "C" region and marked 6114 /// as 'used', but has internal linkage, create an alias from the unmangled 6115 /// name to the mangled name if possible. People expect to be able to refer 6116 /// to such functions with an unmangled name from inline assembly within the 6117 /// same translation unit. 6118 void CodeGenModule::EmitStaticExternCAliases() { 6119 if (!getTargetCodeGenInfo().shouldEmitStaticExternCAliases()) 6120 return; 6121 for (auto &I : StaticExternCValues) { 6122 IdentifierInfo *Name = I.first; 6123 llvm::GlobalValue *Val = I.second; 6124 if (Val && !getModule().getNamedValue(Name->getName())) 6125 addCompilerUsedGlobal(llvm::GlobalAlias::create(Name->getName(), Val)); 6126 } 6127 } 6128 6129 bool CodeGenModule::lookupRepresentativeDecl(StringRef MangledName, 6130 GlobalDecl &Result) const { 6131 auto Res = Manglings.find(MangledName); 6132 if (Res == Manglings.end()) 6133 return false; 6134 Result = Res->getValue(); 6135 return true; 6136 } 6137 6138 /// Emits metadata nodes associating all the global values in the 6139 /// current module with the Decls they came from. This is useful for 6140 /// projects using IR gen as a subroutine. 6141 /// 6142 /// Since there's currently no way to associate an MDNode directly 6143 /// with an llvm::GlobalValue, we create a global named metadata 6144 /// with the name 'clang.global.decl.ptrs'. 6145 void CodeGenModule::EmitDeclMetadata() { 6146 llvm::NamedMDNode *GlobalMetadata = nullptr; 6147 6148 for (auto &I : MangledDeclNames) { 6149 llvm::GlobalValue *Addr = getModule().getNamedValue(I.second); 6150 // Some mangled names don't necessarily have an associated GlobalValue 6151 // in this module, e.g. if we mangled it for DebugInfo. 6152 if (Addr) 6153 EmitGlobalDeclMetadata(*this, GlobalMetadata, I.first, Addr); 6154 } 6155 } 6156 6157 /// Emits metadata nodes for all the local variables in the current 6158 /// function. 6159 void CodeGenFunction::EmitDeclMetadata() { 6160 if (LocalDeclMap.empty()) return; 6161 6162 llvm::LLVMContext &Context = getLLVMContext(); 6163 6164 // Find the unique metadata ID for this name. 6165 unsigned DeclPtrKind = Context.getMDKindID("clang.decl.ptr"); 6166 6167 llvm::NamedMDNode *GlobalMetadata = nullptr; 6168 6169 for (auto &I : LocalDeclMap) { 6170 const Decl *D = I.first; 6171 llvm::Value *Addr = I.second.getPointer(); 6172 if (auto *Alloca = dyn_cast<llvm::AllocaInst>(Addr)) { 6173 llvm::Value *DAddr = GetPointerConstant(getLLVMContext(), D); 6174 Alloca->setMetadata( 6175 DeclPtrKind, llvm::MDNode::get( 6176 Context, llvm::ValueAsMetadata::getConstant(DAddr))); 6177 } else if (auto *GV = dyn_cast<llvm::GlobalValue>(Addr)) { 6178 GlobalDecl GD = GlobalDecl(cast<VarDecl>(D)); 6179 EmitGlobalDeclMetadata(CGM, GlobalMetadata, GD, GV); 6180 } 6181 } 6182 } 6183 6184 void CodeGenModule::EmitVersionIdentMetadata() { 6185 llvm::NamedMDNode *IdentMetadata = 6186 TheModule.getOrInsertNamedMetadata("llvm.ident"); 6187 std::string Version = getClangFullVersion(); 6188 llvm::LLVMContext &Ctx = TheModule.getContext(); 6189 6190 llvm::Metadata *IdentNode[] = {llvm::MDString::get(Ctx, Version)}; 6191 IdentMetadata->addOperand(llvm::MDNode::get(Ctx, IdentNode)); 6192 } 6193 6194 void CodeGenModule::EmitCommandLineMetadata() { 6195 llvm::NamedMDNode *CommandLineMetadata = 6196 TheModule.getOrInsertNamedMetadata("llvm.commandline"); 6197 std::string CommandLine = getCodeGenOpts().RecordCommandLine; 6198 llvm::LLVMContext &Ctx = TheModule.getContext(); 6199 6200 llvm::Metadata *CommandLineNode[] = {llvm::MDString::get(Ctx, CommandLine)}; 6201 CommandLineMetadata->addOperand(llvm::MDNode::get(Ctx, CommandLineNode)); 6202 } 6203 6204 void CodeGenModule::EmitCoverageFile() { 6205 if (getCodeGenOpts().CoverageDataFile.empty() && 6206 getCodeGenOpts().CoverageNotesFile.empty()) 6207 return; 6208 6209 llvm::NamedMDNode *CUNode = TheModule.getNamedMetadata("llvm.dbg.cu"); 6210 if (!CUNode) 6211 return; 6212 6213 llvm::NamedMDNode *GCov = TheModule.getOrInsertNamedMetadata("llvm.gcov"); 6214 llvm::LLVMContext &Ctx = TheModule.getContext(); 6215 auto *CoverageDataFile = 6216 llvm::MDString::get(Ctx, getCodeGenOpts().CoverageDataFile); 6217 auto *CoverageNotesFile = 6218 llvm::MDString::get(Ctx, getCodeGenOpts().CoverageNotesFile); 6219 for (int i = 0, e = CUNode->getNumOperands(); i != e; ++i) { 6220 llvm::MDNode *CU = CUNode->getOperand(i); 6221 llvm::Metadata *Elts[] = {CoverageNotesFile, CoverageDataFile, CU}; 6222 GCov->addOperand(llvm::MDNode::get(Ctx, Elts)); 6223 } 6224 } 6225 6226 llvm::Constant *CodeGenModule::GetAddrOfRTTIDescriptor(QualType Ty, 6227 bool ForEH) { 6228 // Return a bogus pointer if RTTI is disabled, unless it's for EH. 6229 // FIXME: should we even be calling this method if RTTI is disabled 6230 // and it's not for EH? 6231 if ((!ForEH && !getLangOpts().RTTI) || getLangOpts().CUDAIsDevice || 6232 (getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice && 6233 getTriple().isNVPTX())) 6234 return llvm::Constant::getNullValue(Int8PtrTy); 6235 6236 if (ForEH && Ty->isObjCObjectPointerType() && 6237 LangOpts.ObjCRuntime.isGNUFamily()) 6238 return ObjCRuntime->GetEHType(Ty); 6239 6240 return getCXXABI().getAddrOfRTTIDescriptor(Ty); 6241 } 6242 6243 void CodeGenModule::EmitOMPThreadPrivateDecl(const OMPThreadPrivateDecl *D) { 6244 // Do not emit threadprivates in simd-only mode. 6245 if (LangOpts.OpenMP && LangOpts.OpenMPSimd) 6246 return; 6247 for (auto RefExpr : D->varlists()) { 6248 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(RefExpr)->getDecl()); 6249 bool PerformInit = 6250 VD->getAnyInitializer() && 6251 !VD->getAnyInitializer()->isConstantInitializer(getContext(), 6252 /*ForRef=*/false); 6253 6254 Address Addr(GetAddrOfGlobalVar(VD), getContext().getDeclAlign(VD)); 6255 if (auto InitFunction = getOpenMPRuntime().emitThreadPrivateVarDefinition( 6256 VD, Addr, RefExpr->getBeginLoc(), PerformInit)) 6257 CXXGlobalInits.push_back(InitFunction); 6258 } 6259 } 6260 6261 llvm::Metadata * 6262 CodeGenModule::CreateMetadataIdentifierImpl(QualType T, MetadataTypeMap &Map, 6263 StringRef Suffix) { 6264 llvm::Metadata *&InternalId = Map[T.getCanonicalType()]; 6265 if (InternalId) 6266 return InternalId; 6267 6268 if (isExternallyVisible(T->getLinkage())) { 6269 std::string OutName; 6270 llvm::raw_string_ostream Out(OutName); 6271 getCXXABI().getMangleContext().mangleTypeName(T, Out); 6272 Out << Suffix; 6273 6274 InternalId = llvm::MDString::get(getLLVMContext(), Out.str()); 6275 } else { 6276 InternalId = llvm::MDNode::getDistinct(getLLVMContext(), 6277 llvm::ArrayRef<llvm::Metadata *>()); 6278 } 6279 6280 return InternalId; 6281 } 6282 6283 llvm::Metadata *CodeGenModule::CreateMetadataIdentifierForType(QualType T) { 6284 return CreateMetadataIdentifierImpl(T, MetadataIdMap, ""); 6285 } 6286 6287 llvm::Metadata * 6288 CodeGenModule::CreateMetadataIdentifierForVirtualMemPtrType(QualType T) { 6289 return CreateMetadataIdentifierImpl(T, VirtualMetadataIdMap, ".virtual"); 6290 } 6291 6292 // Generalize pointer types to a void pointer with the qualifiers of the 6293 // originally pointed-to type, e.g. 'const char *' and 'char * const *' 6294 // generalize to 'const void *' while 'char *' and 'const char **' generalize to 6295 // 'void *'. 6296 static QualType GeneralizeType(ASTContext &Ctx, QualType Ty) { 6297 if (!Ty->isPointerType()) 6298 return Ty; 6299 6300 return Ctx.getPointerType( 6301 QualType(Ctx.VoidTy).withCVRQualifiers( 6302 Ty->getPointeeType().getCVRQualifiers())); 6303 } 6304 6305 // Apply type generalization to a FunctionType's return and argument types 6306 static QualType GeneralizeFunctionType(ASTContext &Ctx, QualType Ty) { 6307 if (auto *FnType = Ty->getAs<FunctionProtoType>()) { 6308 SmallVector<QualType, 8> GeneralizedParams; 6309 for (auto &Param : FnType->param_types()) 6310 GeneralizedParams.push_back(GeneralizeType(Ctx, Param)); 6311 6312 return Ctx.getFunctionType( 6313 GeneralizeType(Ctx, FnType->getReturnType()), 6314 GeneralizedParams, FnType->getExtProtoInfo()); 6315 } 6316 6317 if (auto *FnType = Ty->getAs<FunctionNoProtoType>()) 6318 return Ctx.getFunctionNoProtoType( 6319 GeneralizeType(Ctx, FnType->getReturnType())); 6320 6321 llvm_unreachable("Encountered unknown FunctionType"); 6322 } 6323 6324 llvm::Metadata *CodeGenModule::CreateMetadataIdentifierGeneralized(QualType T) { 6325 return CreateMetadataIdentifierImpl(GeneralizeFunctionType(getContext(), T), 6326 GeneralizedMetadataIdMap, ".generalized"); 6327 } 6328 6329 /// Returns whether this module needs the "all-vtables" type identifier. 6330 bool CodeGenModule::NeedAllVtablesTypeId() const { 6331 // Returns true if at least one of vtable-based CFI checkers is enabled and 6332 // is not in the trapping mode. 6333 return ((LangOpts.Sanitize.has(SanitizerKind::CFIVCall) && 6334 !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFIVCall)) || 6335 (LangOpts.Sanitize.has(SanitizerKind::CFINVCall) && 6336 !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFINVCall)) || 6337 (LangOpts.Sanitize.has(SanitizerKind::CFIDerivedCast) && 6338 !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFIDerivedCast)) || 6339 (LangOpts.Sanitize.has(SanitizerKind::CFIUnrelatedCast) && 6340 !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFIUnrelatedCast))); 6341 } 6342 6343 void CodeGenModule::AddVTableTypeMetadata(llvm::GlobalVariable *VTable, 6344 CharUnits Offset, 6345 const CXXRecordDecl *RD) { 6346 llvm::Metadata *MD = 6347 CreateMetadataIdentifierForType(QualType(RD->getTypeForDecl(), 0)); 6348 VTable->addTypeMetadata(Offset.getQuantity(), MD); 6349 6350 if (CodeGenOpts.SanitizeCfiCrossDso) 6351 if (auto CrossDsoTypeId = CreateCrossDsoCfiTypeId(MD)) 6352 VTable->addTypeMetadata(Offset.getQuantity(), 6353 llvm::ConstantAsMetadata::get(CrossDsoTypeId)); 6354 6355 if (NeedAllVtablesTypeId()) { 6356 llvm::Metadata *MD = llvm::MDString::get(getLLVMContext(), "all-vtables"); 6357 VTable->addTypeMetadata(Offset.getQuantity(), MD); 6358 } 6359 } 6360 6361 llvm::SanitizerStatReport &CodeGenModule::getSanStats() { 6362 if (!SanStats) 6363 SanStats = std::make_unique<llvm::SanitizerStatReport>(&getModule()); 6364 6365 return *SanStats; 6366 } 6367 6368 llvm::Value * 6369 CodeGenModule::createOpenCLIntToSamplerConversion(const Expr *E, 6370 CodeGenFunction &CGF) { 6371 llvm::Constant *C = ConstantEmitter(CGF).emitAbstract(E, E->getType()); 6372 auto *SamplerT = getOpenCLRuntime().getSamplerType(E->getType().getTypePtr()); 6373 auto *FTy = llvm::FunctionType::get(SamplerT, {C->getType()}, false); 6374 auto *Call = CGF.EmitRuntimeCall( 6375 CreateRuntimeFunction(FTy, "__translate_sampler_initializer"), {C}); 6376 return Call; 6377 } 6378 6379 CharUnits CodeGenModule::getNaturalPointeeTypeAlignment( 6380 QualType T, LValueBaseInfo *BaseInfo, TBAAAccessInfo *TBAAInfo) { 6381 return getNaturalTypeAlignment(T->getPointeeType(), BaseInfo, TBAAInfo, 6382 /* forPointeeType= */ true); 6383 } 6384 6385 CharUnits CodeGenModule::getNaturalTypeAlignment(QualType T, 6386 LValueBaseInfo *BaseInfo, 6387 TBAAAccessInfo *TBAAInfo, 6388 bool forPointeeType) { 6389 if (TBAAInfo) 6390 *TBAAInfo = getTBAAAccessInfo(T); 6391 6392 // FIXME: This duplicates logic in ASTContext::getTypeAlignIfKnown. But 6393 // that doesn't return the information we need to compute BaseInfo. 6394 6395 // Honor alignment typedef attributes even on incomplete types. 6396 // We also honor them straight for C++ class types, even as pointees; 6397 // there's an expressivity gap here. 6398 if (auto TT = T->getAs<TypedefType>()) { 6399 if (auto Align = TT->getDecl()->getMaxAlignment()) { 6400 if (BaseInfo) 6401 *BaseInfo = LValueBaseInfo(AlignmentSource::AttributedType); 6402 return getContext().toCharUnitsFromBits(Align); 6403 } 6404 } 6405 6406 bool AlignForArray = T->isArrayType(); 6407 6408 // Analyze the base element type, so we don't get confused by incomplete 6409 // array types. 6410 T = getContext().getBaseElementType(T); 6411 6412 if (T->isIncompleteType()) { 6413 // We could try to replicate the logic from 6414 // ASTContext::getTypeAlignIfKnown, but nothing uses the alignment if the 6415 // type is incomplete, so it's impossible to test. We could try to reuse 6416 // getTypeAlignIfKnown, but that doesn't return the information we need 6417 // to set BaseInfo. So just ignore the possibility that the alignment is 6418 // greater than one. 6419 if (BaseInfo) 6420 *BaseInfo = LValueBaseInfo(AlignmentSource::Type); 6421 return CharUnits::One(); 6422 } 6423 6424 if (BaseInfo) 6425 *BaseInfo = LValueBaseInfo(AlignmentSource::Type); 6426 6427 CharUnits Alignment; 6428 const CXXRecordDecl *RD; 6429 if (T.getQualifiers().hasUnaligned()) { 6430 Alignment = CharUnits::One(); 6431 } else if (forPointeeType && !AlignForArray && 6432 (RD = T->getAsCXXRecordDecl())) { 6433 // For C++ class pointees, we don't know whether we're pointing at a 6434 // base or a complete object, so we generally need to use the 6435 // non-virtual alignment. 6436 Alignment = getClassPointerAlignment(RD); 6437 } else { 6438 Alignment = getContext().getTypeAlignInChars(T); 6439 } 6440 6441 // Cap to the global maximum type alignment unless the alignment 6442 // was somehow explicit on the type. 6443 if (unsigned MaxAlign = getLangOpts().MaxTypeAlign) { 6444 if (Alignment.getQuantity() > MaxAlign && 6445 !getContext().isAlignmentRequired(T)) 6446 Alignment = CharUnits::fromQuantity(MaxAlign); 6447 } 6448 return Alignment; 6449 } 6450 6451 bool CodeGenModule::stopAutoInit() { 6452 unsigned StopAfter = getContext().getLangOpts().TrivialAutoVarInitStopAfter; 6453 if (StopAfter) { 6454 // This number is positive only when -ftrivial-auto-var-init-stop-after=* is 6455 // used 6456 if (NumAutoVarInit >= StopAfter) { 6457 return true; 6458 } 6459 if (!NumAutoVarInit) { 6460 unsigned DiagID = getDiags().getCustomDiagID( 6461 DiagnosticsEngine::Warning, 6462 "-ftrivial-auto-var-init-stop-after=%0 has been enabled to limit the " 6463 "number of times ftrivial-auto-var-init=%1 gets applied."); 6464 getDiags().Report(DiagID) 6465 << StopAfter 6466 << (getContext().getLangOpts().getTrivialAutoVarInit() == 6467 LangOptions::TrivialAutoVarInitKind::Zero 6468 ? "zero" 6469 : "pattern"); 6470 } 6471 ++NumAutoVarInit; 6472 } 6473 return false; 6474 } 6475 6476 void CodeGenModule::printPostfixForExternalizedStaticVar( 6477 llvm::raw_ostream &OS) const { 6478 OS << "__static__" << getContext().getCUIDHash(); 6479 } 6480