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