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