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 != "" && 1774 getTarget().isValidCPUName(ParsedAttr.Architecture)) 1775 TargetCPU = ParsedAttr.Architecture; 1776 } 1777 } else { 1778 // Otherwise just add the existing target cpu and target features to the 1779 // function. 1780 Features = getTarget().getTargetOpts().Features; 1781 } 1782 1783 if (TargetCPU != "") { 1784 Attrs.addAttribute("target-cpu", TargetCPU); 1785 AddedAttr = true; 1786 } 1787 if (TuneCPU != "") { 1788 Attrs.addAttribute("tune-cpu", TuneCPU); 1789 AddedAttr = true; 1790 } 1791 if (!Features.empty()) { 1792 llvm::sort(Features); 1793 Attrs.addAttribute("target-features", llvm::join(Features, ",")); 1794 AddedAttr = true; 1795 } 1796 1797 return AddedAttr; 1798 } 1799 1800 void CodeGenModule::setNonAliasAttributes(GlobalDecl GD, 1801 llvm::GlobalObject *GO) { 1802 const Decl *D = GD.getDecl(); 1803 SetCommonAttributes(GD, GO); 1804 1805 if (D) { 1806 if (auto *GV = dyn_cast<llvm::GlobalVariable>(GO)) { 1807 if (auto *SA = D->getAttr<PragmaClangBSSSectionAttr>()) 1808 GV->addAttribute("bss-section", SA->getName()); 1809 if (auto *SA = D->getAttr<PragmaClangDataSectionAttr>()) 1810 GV->addAttribute("data-section", SA->getName()); 1811 if (auto *SA = D->getAttr<PragmaClangRodataSectionAttr>()) 1812 GV->addAttribute("rodata-section", SA->getName()); 1813 if (auto *SA = D->getAttr<PragmaClangRelroSectionAttr>()) 1814 GV->addAttribute("relro-section", SA->getName()); 1815 } 1816 1817 if (auto *F = dyn_cast<llvm::Function>(GO)) { 1818 if (auto *SA = D->getAttr<PragmaClangTextSectionAttr>()) 1819 if (!D->getAttr<SectionAttr>()) 1820 F->addFnAttr("implicit-section-name", SA->getName()); 1821 1822 llvm::AttrBuilder Attrs; 1823 if (GetCPUAndFeaturesAttributes(GD, Attrs)) { 1824 // We know that GetCPUAndFeaturesAttributes will always have the 1825 // newest set, since it has the newest possible FunctionDecl, so the 1826 // new ones should replace the old. 1827 F->removeFnAttr("target-cpu"); 1828 F->removeFnAttr("target-features"); 1829 F->addAttributes(llvm::AttributeList::FunctionIndex, Attrs); 1830 } 1831 } 1832 1833 if (const auto *CSA = D->getAttr<CodeSegAttr>()) 1834 GO->setSection(CSA->getName()); 1835 else if (const auto *SA = D->getAttr<SectionAttr>()) 1836 GO->setSection(SA->getName()); 1837 } 1838 1839 getTargetCodeGenInfo().setTargetAttributes(D, GO, *this); 1840 } 1841 1842 void CodeGenModule::SetInternalFunctionAttributes(GlobalDecl GD, 1843 llvm::Function *F, 1844 const CGFunctionInfo &FI) { 1845 const Decl *D = GD.getDecl(); 1846 SetLLVMFunctionAttributes(GD, FI, F); 1847 SetLLVMFunctionAttributesForDefinition(D, F); 1848 1849 F->setLinkage(llvm::Function::InternalLinkage); 1850 1851 setNonAliasAttributes(GD, F); 1852 } 1853 1854 static void setLinkageForGV(llvm::GlobalValue *GV, const NamedDecl *ND) { 1855 // Set linkage and visibility in case we never see a definition. 1856 LinkageInfo LV = ND->getLinkageAndVisibility(); 1857 // Don't set internal linkage on declarations. 1858 // "extern_weak" is overloaded in LLVM; we probably should have 1859 // separate linkage types for this. 1860 if (isExternallyVisible(LV.getLinkage()) && 1861 (ND->hasAttr<WeakAttr>() || ND->isWeakImported())) 1862 GV->setLinkage(llvm::GlobalValue::ExternalWeakLinkage); 1863 } 1864 1865 void CodeGenModule::CreateFunctionTypeMetadataForIcall(const FunctionDecl *FD, 1866 llvm::Function *F) { 1867 // Only if we are checking indirect calls. 1868 if (!LangOpts.Sanitize.has(SanitizerKind::CFIICall)) 1869 return; 1870 1871 // Non-static class methods are handled via vtable or member function pointer 1872 // checks elsewhere. 1873 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic()) 1874 return; 1875 1876 llvm::Metadata *MD = CreateMetadataIdentifierForType(FD->getType()); 1877 F->addTypeMetadata(0, MD); 1878 F->addTypeMetadata(0, CreateMetadataIdentifierGeneralized(FD->getType())); 1879 1880 // Emit a hash-based bit set entry for cross-DSO calls. 1881 if (CodeGenOpts.SanitizeCfiCrossDso) 1882 if (auto CrossDsoTypeId = CreateCrossDsoCfiTypeId(MD)) 1883 F->addTypeMetadata(0, llvm::ConstantAsMetadata::get(CrossDsoTypeId)); 1884 } 1885 1886 void CodeGenModule::SetFunctionAttributes(GlobalDecl GD, llvm::Function *F, 1887 bool IsIncompleteFunction, 1888 bool IsThunk) { 1889 1890 if (llvm::Intrinsic::ID IID = F->getIntrinsicID()) { 1891 // If this is an intrinsic function, set the function's attributes 1892 // to the intrinsic's attributes. 1893 F->setAttributes(llvm::Intrinsic::getAttributes(getLLVMContext(), IID)); 1894 return; 1895 } 1896 1897 const auto *FD = cast<FunctionDecl>(GD.getDecl()); 1898 1899 if (!IsIncompleteFunction) 1900 SetLLVMFunctionAttributes(GD, getTypes().arrangeGlobalDeclaration(GD), F); 1901 1902 // Add the Returned attribute for "this", except for iOS 5 and earlier 1903 // where substantial code, including the libstdc++ dylib, was compiled with 1904 // GCC and does not actually return "this". 1905 if (!IsThunk && getCXXABI().HasThisReturn(GD) && 1906 !(getTriple().isiOS() && getTriple().isOSVersionLT(6))) { 1907 assert(!F->arg_empty() && 1908 F->arg_begin()->getType() 1909 ->canLosslesslyBitCastTo(F->getReturnType()) && 1910 "unexpected this return"); 1911 F->addAttribute(1, llvm::Attribute::Returned); 1912 } 1913 1914 // Only a few attributes are set on declarations; these may later be 1915 // overridden by a definition. 1916 1917 setLinkageForGV(F, FD); 1918 setGVProperties(F, FD); 1919 1920 // Setup target-specific attributes. 1921 if (!IsIncompleteFunction && F->isDeclaration()) 1922 getTargetCodeGenInfo().setTargetAttributes(FD, F, *this); 1923 1924 if (const auto *CSA = FD->getAttr<CodeSegAttr>()) 1925 F->setSection(CSA->getName()); 1926 else if (const auto *SA = FD->getAttr<SectionAttr>()) 1927 F->setSection(SA->getName()); 1928 1929 // If we plan on emitting this inline builtin, we can't treat it as a builtin. 1930 if (FD->isInlineBuiltinDeclaration()) { 1931 const FunctionDecl *FDBody; 1932 bool HasBody = FD->hasBody(FDBody); 1933 (void)HasBody; 1934 assert(HasBody && "Inline builtin declarations should always have an " 1935 "available body!"); 1936 if (shouldEmitFunction(FDBody)) 1937 F->addAttribute(llvm::AttributeList::FunctionIndex, 1938 llvm::Attribute::NoBuiltin); 1939 } 1940 1941 if (FD->isReplaceableGlobalAllocationFunction()) { 1942 // A replaceable global allocation function does not act like a builtin by 1943 // default, only if it is invoked by a new-expression or delete-expression. 1944 F->addAttribute(llvm::AttributeList::FunctionIndex, 1945 llvm::Attribute::NoBuiltin); 1946 } 1947 1948 if (isa<CXXConstructorDecl>(FD) || isa<CXXDestructorDecl>(FD)) 1949 F->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global); 1950 else if (const auto *MD = dyn_cast<CXXMethodDecl>(FD)) 1951 if (MD->isVirtual()) 1952 F->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global); 1953 1954 // Don't emit entries for function declarations in the cross-DSO mode. This 1955 // is handled with better precision by the receiving DSO. But if jump tables 1956 // are non-canonical then we need type metadata in order to produce the local 1957 // jump table. 1958 if (!CodeGenOpts.SanitizeCfiCrossDso || 1959 !CodeGenOpts.SanitizeCfiCanonicalJumpTables) 1960 CreateFunctionTypeMetadataForIcall(FD, F); 1961 1962 if (getLangOpts().OpenMP && FD->hasAttr<OMPDeclareSimdDeclAttr>()) 1963 getOpenMPRuntime().emitDeclareSimdFunction(FD, F); 1964 1965 if (const auto *CB = FD->getAttr<CallbackAttr>()) { 1966 // Annotate the callback behavior as metadata: 1967 // - The callback callee (as argument number). 1968 // - The callback payloads (as argument numbers). 1969 llvm::LLVMContext &Ctx = F->getContext(); 1970 llvm::MDBuilder MDB(Ctx); 1971 1972 // The payload indices are all but the first one in the encoding. The first 1973 // identifies the callback callee. 1974 int CalleeIdx = *CB->encoding_begin(); 1975 ArrayRef<int> PayloadIndices(CB->encoding_begin() + 1, CB->encoding_end()); 1976 F->addMetadata(llvm::LLVMContext::MD_callback, 1977 *llvm::MDNode::get(Ctx, {MDB.createCallbackEncoding( 1978 CalleeIdx, PayloadIndices, 1979 /* VarArgsArePassed */ false)})); 1980 } 1981 } 1982 1983 void CodeGenModule::addUsedGlobal(llvm::GlobalValue *GV) { 1984 assert(!GV->isDeclaration() && 1985 "Only globals with definition can force usage."); 1986 LLVMUsed.emplace_back(GV); 1987 } 1988 1989 void CodeGenModule::addCompilerUsedGlobal(llvm::GlobalValue *GV) { 1990 assert(!GV->isDeclaration() && 1991 "Only globals with definition can force usage."); 1992 LLVMCompilerUsed.emplace_back(GV); 1993 } 1994 1995 static void emitUsed(CodeGenModule &CGM, StringRef Name, 1996 std::vector<llvm::WeakTrackingVH> &List) { 1997 // Don't create llvm.used if there is no need. 1998 if (List.empty()) 1999 return; 2000 2001 // Convert List to what ConstantArray needs. 2002 SmallVector<llvm::Constant*, 8> UsedArray; 2003 UsedArray.resize(List.size()); 2004 for (unsigned i = 0, e = List.size(); i != e; ++i) { 2005 UsedArray[i] = 2006 llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast( 2007 cast<llvm::Constant>(&*List[i]), CGM.Int8PtrTy); 2008 } 2009 2010 if (UsedArray.empty()) 2011 return; 2012 llvm::ArrayType *ATy = llvm::ArrayType::get(CGM.Int8PtrTy, UsedArray.size()); 2013 2014 auto *GV = new llvm::GlobalVariable( 2015 CGM.getModule(), ATy, false, llvm::GlobalValue::AppendingLinkage, 2016 llvm::ConstantArray::get(ATy, UsedArray), Name); 2017 2018 GV->setSection("llvm.metadata"); 2019 } 2020 2021 void CodeGenModule::emitLLVMUsed() { 2022 emitUsed(*this, "llvm.used", LLVMUsed); 2023 emitUsed(*this, "llvm.compiler.used", LLVMCompilerUsed); 2024 } 2025 2026 void CodeGenModule::AppendLinkerOptions(StringRef Opts) { 2027 auto *MDOpts = llvm::MDString::get(getLLVMContext(), Opts); 2028 LinkerOptionsMetadata.push_back(llvm::MDNode::get(getLLVMContext(), MDOpts)); 2029 } 2030 2031 void CodeGenModule::AddDetectMismatch(StringRef Name, StringRef Value) { 2032 llvm::SmallString<32> Opt; 2033 getTargetCodeGenInfo().getDetectMismatchOption(Name, Value, Opt); 2034 if (Opt.empty()) 2035 return; 2036 auto *MDOpts = llvm::MDString::get(getLLVMContext(), Opt); 2037 LinkerOptionsMetadata.push_back(llvm::MDNode::get(getLLVMContext(), MDOpts)); 2038 } 2039 2040 void CodeGenModule::AddDependentLib(StringRef Lib) { 2041 auto &C = getLLVMContext(); 2042 if (getTarget().getTriple().isOSBinFormatELF()) { 2043 ELFDependentLibraries.push_back( 2044 llvm::MDNode::get(C, llvm::MDString::get(C, Lib))); 2045 return; 2046 } 2047 2048 llvm::SmallString<24> Opt; 2049 getTargetCodeGenInfo().getDependentLibraryOption(Lib, Opt); 2050 auto *MDOpts = llvm::MDString::get(getLLVMContext(), Opt); 2051 LinkerOptionsMetadata.push_back(llvm::MDNode::get(C, MDOpts)); 2052 } 2053 2054 /// Add link options implied by the given module, including modules 2055 /// it depends on, using a postorder walk. 2056 static void addLinkOptionsPostorder(CodeGenModule &CGM, Module *Mod, 2057 SmallVectorImpl<llvm::MDNode *> &Metadata, 2058 llvm::SmallPtrSet<Module *, 16> &Visited) { 2059 // Import this module's parent. 2060 if (Mod->Parent && Visited.insert(Mod->Parent).second) { 2061 addLinkOptionsPostorder(CGM, Mod->Parent, Metadata, Visited); 2062 } 2063 2064 // Import this module's dependencies. 2065 for (unsigned I = Mod->Imports.size(); I > 0; --I) { 2066 if (Visited.insert(Mod->Imports[I - 1]).second) 2067 addLinkOptionsPostorder(CGM, Mod->Imports[I-1], Metadata, Visited); 2068 } 2069 2070 // Add linker options to link against the libraries/frameworks 2071 // described by this module. 2072 llvm::LLVMContext &Context = CGM.getLLVMContext(); 2073 bool IsELF = CGM.getTarget().getTriple().isOSBinFormatELF(); 2074 2075 // For modules that use export_as for linking, use that module 2076 // name instead. 2077 if (Mod->UseExportAsModuleLinkName) 2078 return; 2079 2080 for (unsigned I = Mod->LinkLibraries.size(); I > 0; --I) { 2081 // Link against a framework. Frameworks are currently Darwin only, so we 2082 // don't to ask TargetCodeGenInfo for the spelling of the linker option. 2083 if (Mod->LinkLibraries[I-1].IsFramework) { 2084 llvm::Metadata *Args[2] = { 2085 llvm::MDString::get(Context, "-framework"), 2086 llvm::MDString::get(Context, Mod->LinkLibraries[I - 1].Library)}; 2087 2088 Metadata.push_back(llvm::MDNode::get(Context, Args)); 2089 continue; 2090 } 2091 2092 // Link against a library. 2093 if (IsELF) { 2094 llvm::Metadata *Args[2] = { 2095 llvm::MDString::get(Context, "lib"), 2096 llvm::MDString::get(Context, Mod->LinkLibraries[I - 1].Library), 2097 }; 2098 Metadata.push_back(llvm::MDNode::get(Context, Args)); 2099 } else { 2100 llvm::SmallString<24> Opt; 2101 CGM.getTargetCodeGenInfo().getDependentLibraryOption( 2102 Mod->LinkLibraries[I - 1].Library, Opt); 2103 auto *OptString = llvm::MDString::get(Context, Opt); 2104 Metadata.push_back(llvm::MDNode::get(Context, OptString)); 2105 } 2106 } 2107 } 2108 2109 void CodeGenModule::EmitModuleLinkOptions() { 2110 // Collect the set of all of the modules we want to visit to emit link 2111 // options, which is essentially the imported modules and all of their 2112 // non-explicit child modules. 2113 llvm::SetVector<clang::Module *> LinkModules; 2114 llvm::SmallPtrSet<clang::Module *, 16> Visited; 2115 SmallVector<clang::Module *, 16> Stack; 2116 2117 // Seed the stack with imported modules. 2118 for (Module *M : ImportedModules) { 2119 // Do not add any link flags when an implementation TU of a module imports 2120 // a header of that same module. 2121 if (M->getTopLevelModuleName() == getLangOpts().CurrentModule && 2122 !getLangOpts().isCompilingModule()) 2123 continue; 2124 if (Visited.insert(M).second) 2125 Stack.push_back(M); 2126 } 2127 2128 // Find all of the modules to import, making a little effort to prune 2129 // non-leaf modules. 2130 while (!Stack.empty()) { 2131 clang::Module *Mod = Stack.pop_back_val(); 2132 2133 bool AnyChildren = false; 2134 2135 // Visit the submodules of this module. 2136 for (const auto &SM : Mod->submodules()) { 2137 // Skip explicit children; they need to be explicitly imported to be 2138 // linked against. 2139 if (SM->IsExplicit) 2140 continue; 2141 2142 if (Visited.insert(SM).second) { 2143 Stack.push_back(SM); 2144 AnyChildren = true; 2145 } 2146 } 2147 2148 // We didn't find any children, so add this module to the list of 2149 // modules to link against. 2150 if (!AnyChildren) { 2151 LinkModules.insert(Mod); 2152 } 2153 } 2154 2155 // Add link options for all of the imported modules in reverse topological 2156 // order. We don't do anything to try to order import link flags with respect 2157 // to linker options inserted by things like #pragma comment(). 2158 SmallVector<llvm::MDNode *, 16> MetadataArgs; 2159 Visited.clear(); 2160 for (Module *M : LinkModules) 2161 if (Visited.insert(M).second) 2162 addLinkOptionsPostorder(*this, M, MetadataArgs, Visited); 2163 std::reverse(MetadataArgs.begin(), MetadataArgs.end()); 2164 LinkerOptionsMetadata.append(MetadataArgs.begin(), MetadataArgs.end()); 2165 2166 // Add the linker options metadata flag. 2167 auto *NMD = getModule().getOrInsertNamedMetadata("llvm.linker.options"); 2168 for (auto *MD : LinkerOptionsMetadata) 2169 NMD->addOperand(MD); 2170 } 2171 2172 void CodeGenModule::EmitDeferred() { 2173 // Emit deferred declare target declarations. 2174 if (getLangOpts().OpenMP && !getLangOpts().OpenMPSimd) 2175 getOpenMPRuntime().emitDeferredTargetDecls(); 2176 2177 // Emit code for any potentially referenced deferred decls. Since a 2178 // previously unused static decl may become used during the generation of code 2179 // for a static function, iterate until no changes are made. 2180 2181 if (!DeferredVTables.empty()) { 2182 EmitDeferredVTables(); 2183 2184 // Emitting a vtable doesn't directly cause more vtables to 2185 // become deferred, although it can cause functions to be 2186 // emitted that then need those vtables. 2187 assert(DeferredVTables.empty()); 2188 } 2189 2190 // Stop if we're out of both deferred vtables and deferred declarations. 2191 if (DeferredDeclsToEmit.empty()) 2192 return; 2193 2194 // Grab the list of decls to emit. If EmitGlobalDefinition schedules more 2195 // work, it will not interfere with this. 2196 std::vector<GlobalDecl> CurDeclsToEmit; 2197 CurDeclsToEmit.swap(DeferredDeclsToEmit); 2198 2199 for (GlobalDecl &D : CurDeclsToEmit) { 2200 // We should call GetAddrOfGlobal with IsForDefinition set to true in order 2201 // to get GlobalValue with exactly the type we need, not something that 2202 // might had been created for another decl with the same mangled name but 2203 // different type. 2204 llvm::GlobalValue *GV = dyn_cast<llvm::GlobalValue>( 2205 GetAddrOfGlobal(D, ForDefinition)); 2206 2207 // In case of different address spaces, we may still get a cast, even with 2208 // IsForDefinition equal to true. Query mangled names table to get 2209 // GlobalValue. 2210 if (!GV) 2211 GV = GetGlobalValue(getMangledName(D)); 2212 2213 // Make sure GetGlobalValue returned non-null. 2214 assert(GV); 2215 2216 // Check to see if we've already emitted this. This is necessary 2217 // for a couple of reasons: first, decls can end up in the 2218 // deferred-decls queue multiple times, and second, decls can end 2219 // up with definitions in unusual ways (e.g. by an extern inline 2220 // function acquiring a strong function redefinition). Just 2221 // ignore these cases. 2222 if (!GV->isDeclaration()) 2223 continue; 2224 2225 // If this is OpenMP, check if it is legal to emit this global normally. 2226 if (LangOpts.OpenMP && OpenMPRuntime && OpenMPRuntime->emitTargetGlobal(D)) 2227 continue; 2228 2229 // Otherwise, emit the definition and move on to the next one. 2230 EmitGlobalDefinition(D, GV); 2231 2232 // If we found out that we need to emit more decls, do that recursively. 2233 // This has the advantage that the decls are emitted in a DFS and related 2234 // ones are close together, which is convenient for testing. 2235 if (!DeferredVTables.empty() || !DeferredDeclsToEmit.empty()) { 2236 EmitDeferred(); 2237 assert(DeferredVTables.empty() && DeferredDeclsToEmit.empty()); 2238 } 2239 } 2240 } 2241 2242 void CodeGenModule::EmitVTablesOpportunistically() { 2243 // Try to emit external vtables as available_externally if they have emitted 2244 // all inlined virtual functions. It runs after EmitDeferred() and therefore 2245 // is not allowed to create new references to things that need to be emitted 2246 // lazily. Note that it also uses fact that we eagerly emitting RTTI. 2247 2248 assert((OpportunisticVTables.empty() || shouldOpportunisticallyEmitVTables()) 2249 && "Only emit opportunistic vtables with optimizations"); 2250 2251 for (const CXXRecordDecl *RD : OpportunisticVTables) { 2252 assert(getVTables().isVTableExternal(RD) && 2253 "This queue should only contain external vtables"); 2254 if (getCXXABI().canSpeculativelyEmitVTable(RD)) 2255 VTables.GenerateClassData(RD); 2256 } 2257 OpportunisticVTables.clear(); 2258 } 2259 2260 void CodeGenModule::EmitGlobalAnnotations() { 2261 if (Annotations.empty()) 2262 return; 2263 2264 // Create a new global variable for the ConstantStruct in the Module. 2265 llvm::Constant *Array = llvm::ConstantArray::get(llvm::ArrayType::get( 2266 Annotations[0]->getType(), Annotations.size()), Annotations); 2267 auto *gv = new llvm::GlobalVariable(getModule(), Array->getType(), false, 2268 llvm::GlobalValue::AppendingLinkage, 2269 Array, "llvm.global.annotations"); 2270 gv->setSection(AnnotationSection); 2271 } 2272 2273 llvm::Constant *CodeGenModule::EmitAnnotationString(StringRef Str) { 2274 llvm::Constant *&AStr = AnnotationStrings[Str]; 2275 if (AStr) 2276 return AStr; 2277 2278 // Not found yet, create a new global. 2279 llvm::Constant *s = llvm::ConstantDataArray::getString(getLLVMContext(), Str); 2280 auto *gv = 2281 new llvm::GlobalVariable(getModule(), s->getType(), true, 2282 llvm::GlobalValue::PrivateLinkage, s, ".str"); 2283 gv->setSection(AnnotationSection); 2284 gv->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global); 2285 AStr = gv; 2286 return gv; 2287 } 2288 2289 llvm::Constant *CodeGenModule::EmitAnnotationUnit(SourceLocation Loc) { 2290 SourceManager &SM = getContext().getSourceManager(); 2291 PresumedLoc PLoc = SM.getPresumedLoc(Loc); 2292 if (PLoc.isValid()) 2293 return EmitAnnotationString(PLoc.getFilename()); 2294 return EmitAnnotationString(SM.getBufferName(Loc)); 2295 } 2296 2297 llvm::Constant *CodeGenModule::EmitAnnotationLineNo(SourceLocation L) { 2298 SourceManager &SM = getContext().getSourceManager(); 2299 PresumedLoc PLoc = SM.getPresumedLoc(L); 2300 unsigned LineNo = PLoc.isValid() ? PLoc.getLine() : 2301 SM.getExpansionLineNumber(L); 2302 return llvm::ConstantInt::get(Int32Ty, LineNo); 2303 } 2304 2305 llvm::Constant *CodeGenModule::EmitAnnotateAttr(llvm::GlobalValue *GV, 2306 const AnnotateAttr *AA, 2307 SourceLocation L) { 2308 // Get the globals for file name, annotation, and the line number. 2309 llvm::Constant *AnnoGV = EmitAnnotationString(AA->getAnnotation()), 2310 *UnitGV = EmitAnnotationUnit(L), 2311 *LineNoCst = EmitAnnotationLineNo(L); 2312 2313 llvm::Constant *ASZeroGV = GV; 2314 if (GV->getAddressSpace() != 0) { 2315 ASZeroGV = llvm::ConstantExpr::getAddrSpaceCast( 2316 GV, GV->getValueType()->getPointerTo(0)); 2317 } 2318 2319 // Create the ConstantStruct for the global annotation. 2320 llvm::Constant *Fields[4] = { 2321 llvm::ConstantExpr::getBitCast(ASZeroGV, Int8PtrTy), 2322 llvm::ConstantExpr::getBitCast(AnnoGV, Int8PtrTy), 2323 llvm::ConstantExpr::getBitCast(UnitGV, Int8PtrTy), 2324 LineNoCst 2325 }; 2326 return llvm::ConstantStruct::getAnon(Fields); 2327 } 2328 2329 void CodeGenModule::AddGlobalAnnotations(const ValueDecl *D, 2330 llvm::GlobalValue *GV) { 2331 assert(D->hasAttr<AnnotateAttr>() && "no annotate attribute"); 2332 // Get the struct elements for these annotations. 2333 for (const auto *I : D->specific_attrs<AnnotateAttr>()) 2334 Annotations.push_back(EmitAnnotateAttr(GV, I, D->getLocation())); 2335 } 2336 2337 bool CodeGenModule::isInSanitizerBlacklist(SanitizerMask Kind, 2338 llvm::Function *Fn, 2339 SourceLocation Loc) const { 2340 const auto &SanitizerBL = getContext().getSanitizerBlacklist(); 2341 // Blacklist by function name. 2342 if (SanitizerBL.isBlacklistedFunction(Kind, Fn->getName())) 2343 return true; 2344 // Blacklist by location. 2345 if (Loc.isValid()) 2346 return SanitizerBL.isBlacklistedLocation(Kind, Loc); 2347 // If location is unknown, this may be a compiler-generated function. Assume 2348 // it's located in the main file. 2349 auto &SM = Context.getSourceManager(); 2350 if (const auto *MainFile = SM.getFileEntryForID(SM.getMainFileID())) { 2351 return SanitizerBL.isBlacklistedFile(Kind, MainFile->getName()); 2352 } 2353 return false; 2354 } 2355 2356 bool CodeGenModule::isInSanitizerBlacklist(llvm::GlobalVariable *GV, 2357 SourceLocation Loc, QualType Ty, 2358 StringRef Category) const { 2359 // For now globals can be blacklisted only in ASan and KASan. 2360 const SanitizerMask EnabledAsanMask = 2361 LangOpts.Sanitize.Mask & 2362 (SanitizerKind::Address | SanitizerKind::KernelAddress | 2363 SanitizerKind::HWAddress | SanitizerKind::KernelHWAddress | 2364 SanitizerKind::MemTag); 2365 if (!EnabledAsanMask) 2366 return false; 2367 const auto &SanitizerBL = getContext().getSanitizerBlacklist(); 2368 if (SanitizerBL.isBlacklistedGlobal(EnabledAsanMask, GV->getName(), Category)) 2369 return true; 2370 if (SanitizerBL.isBlacklistedLocation(EnabledAsanMask, Loc, Category)) 2371 return true; 2372 // Check global type. 2373 if (!Ty.isNull()) { 2374 // Drill down the array types: if global variable of a fixed type is 2375 // blacklisted, we also don't instrument arrays of them. 2376 while (auto AT = dyn_cast<ArrayType>(Ty.getTypePtr())) 2377 Ty = AT->getElementType(); 2378 Ty = Ty.getCanonicalType().getUnqualifiedType(); 2379 // We allow to blacklist only record types (classes, structs etc.) 2380 if (Ty->isRecordType()) { 2381 std::string TypeStr = Ty.getAsString(getContext().getPrintingPolicy()); 2382 if (SanitizerBL.isBlacklistedType(EnabledAsanMask, TypeStr, Category)) 2383 return true; 2384 } 2385 } 2386 return false; 2387 } 2388 2389 bool CodeGenModule::imbueXRayAttrs(llvm::Function *Fn, SourceLocation Loc, 2390 StringRef Category) const { 2391 const auto &XRayFilter = getContext().getXRayFilter(); 2392 using ImbueAttr = XRayFunctionFilter::ImbueAttribute; 2393 auto Attr = ImbueAttr::NONE; 2394 if (Loc.isValid()) 2395 Attr = XRayFilter.shouldImbueLocation(Loc, Category); 2396 if (Attr == ImbueAttr::NONE) 2397 Attr = XRayFilter.shouldImbueFunction(Fn->getName()); 2398 switch (Attr) { 2399 case ImbueAttr::NONE: 2400 return false; 2401 case ImbueAttr::ALWAYS: 2402 Fn->addFnAttr("function-instrument", "xray-always"); 2403 break; 2404 case ImbueAttr::ALWAYS_ARG1: 2405 Fn->addFnAttr("function-instrument", "xray-always"); 2406 Fn->addFnAttr("xray-log-args", "1"); 2407 break; 2408 case ImbueAttr::NEVER: 2409 Fn->addFnAttr("function-instrument", "xray-never"); 2410 break; 2411 } 2412 return true; 2413 } 2414 2415 bool CodeGenModule::MustBeEmitted(const ValueDecl *Global) { 2416 // Never defer when EmitAllDecls is specified. 2417 if (LangOpts.EmitAllDecls) 2418 return true; 2419 2420 if (CodeGenOpts.KeepStaticConsts) { 2421 const auto *VD = dyn_cast<VarDecl>(Global); 2422 if (VD && VD->getType().isConstQualified() && 2423 VD->getStorageDuration() == SD_Static) 2424 return true; 2425 } 2426 2427 return getContext().DeclMustBeEmitted(Global); 2428 } 2429 2430 bool CodeGenModule::MayBeEmittedEagerly(const ValueDecl *Global) { 2431 if (const auto *FD = dyn_cast<FunctionDecl>(Global)) { 2432 if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation) 2433 // Implicit template instantiations may change linkage if they are later 2434 // explicitly instantiated, so they should not be emitted eagerly. 2435 return false; 2436 // In OpenMP 5.0 function may be marked as device_type(nohost) and we should 2437 // not emit them eagerly unless we sure that the function must be emitted on 2438 // the host. 2439 if (LangOpts.OpenMP >= 50 && !LangOpts.OpenMPSimd && 2440 !LangOpts.OpenMPIsDevice && 2441 !OMPDeclareTargetDeclAttr::getDeviceType(FD) && 2442 !FD->isUsed(/*CheckUsedAttr=*/false) && !FD->isReferenced()) 2443 return false; 2444 } 2445 if (const auto *VD = dyn_cast<VarDecl>(Global)) 2446 if (Context.getInlineVariableDefinitionKind(VD) == 2447 ASTContext::InlineVariableDefinitionKind::WeakUnknown) 2448 // A definition of an inline constexpr static data member may change 2449 // linkage later if it's redeclared outside the class. 2450 return false; 2451 // If OpenMP is enabled and threadprivates must be generated like TLS, delay 2452 // codegen for global variables, because they may be marked as threadprivate. 2453 if (LangOpts.OpenMP && LangOpts.OpenMPUseTLS && 2454 getContext().getTargetInfo().isTLSSupported() && isa<VarDecl>(Global) && 2455 !isTypeConstant(Global->getType(), false) && 2456 !OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(Global)) 2457 return false; 2458 2459 return true; 2460 } 2461 2462 ConstantAddress CodeGenModule::GetAddrOfMSGuidDecl(const MSGuidDecl *GD) { 2463 StringRef Name = getMangledName(GD); 2464 2465 // The UUID descriptor should be pointer aligned. 2466 CharUnits Alignment = CharUnits::fromQuantity(PointerAlignInBytes); 2467 2468 // Look for an existing global. 2469 if (llvm::GlobalVariable *GV = getModule().getNamedGlobal(Name)) 2470 return ConstantAddress(GV, Alignment); 2471 2472 ConstantEmitter Emitter(*this); 2473 llvm::Constant *Init; 2474 2475 APValue &V = GD->getAsAPValue(); 2476 if (!V.isAbsent()) { 2477 // If possible, emit the APValue version of the initializer. In particular, 2478 // this gets the type of the constant right. 2479 Init = Emitter.emitForInitializer( 2480 GD->getAsAPValue(), GD->getType().getAddressSpace(), GD->getType()); 2481 } else { 2482 // As a fallback, directly construct the constant. 2483 // FIXME: This may get padding wrong under esoteric struct layout rules. 2484 // MSVC appears to create a complete type 'struct __s_GUID' that it 2485 // presumably uses to represent these constants. 2486 MSGuidDecl::Parts Parts = GD->getParts(); 2487 llvm::Constant *Fields[4] = { 2488 llvm::ConstantInt::get(Int32Ty, Parts.Part1), 2489 llvm::ConstantInt::get(Int16Ty, Parts.Part2), 2490 llvm::ConstantInt::get(Int16Ty, Parts.Part3), 2491 llvm::ConstantDataArray::getRaw( 2492 StringRef(reinterpret_cast<char *>(Parts.Part4And5), 8), 8, 2493 Int8Ty)}; 2494 Init = llvm::ConstantStruct::getAnon(Fields); 2495 } 2496 2497 auto *GV = new llvm::GlobalVariable( 2498 getModule(), Init->getType(), 2499 /*isConstant=*/true, llvm::GlobalValue::LinkOnceODRLinkage, Init, Name); 2500 if (supportsCOMDAT()) 2501 GV->setComdat(TheModule.getOrInsertComdat(GV->getName())); 2502 setDSOLocal(GV); 2503 2504 llvm::Constant *Addr = GV; 2505 if (!V.isAbsent()) { 2506 Emitter.finalize(GV); 2507 } else { 2508 llvm::Type *Ty = getTypes().ConvertTypeForMem(GD->getType()); 2509 Addr = llvm::ConstantExpr::getBitCast( 2510 GV, Ty->getPointerTo(GV->getAddressSpace())); 2511 } 2512 return ConstantAddress(Addr, Alignment); 2513 } 2514 2515 ConstantAddress CodeGenModule::GetWeakRefReference(const ValueDecl *VD) { 2516 const AliasAttr *AA = VD->getAttr<AliasAttr>(); 2517 assert(AA && "No alias?"); 2518 2519 CharUnits Alignment = getContext().getDeclAlign(VD); 2520 llvm::Type *DeclTy = getTypes().ConvertTypeForMem(VD->getType()); 2521 2522 // See if there is already something with the target's name in the module. 2523 llvm::GlobalValue *Entry = GetGlobalValue(AA->getAliasee()); 2524 if (Entry) { 2525 unsigned AS = getContext().getTargetAddressSpace(VD->getType()); 2526 auto Ptr = llvm::ConstantExpr::getBitCast(Entry, DeclTy->getPointerTo(AS)); 2527 return ConstantAddress(Ptr, Alignment); 2528 } 2529 2530 llvm::Constant *Aliasee; 2531 if (isa<llvm::FunctionType>(DeclTy)) 2532 Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy, 2533 GlobalDecl(cast<FunctionDecl>(VD)), 2534 /*ForVTable=*/false); 2535 else 2536 Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(), 2537 llvm::PointerType::getUnqual(DeclTy), 2538 nullptr); 2539 2540 auto *F = cast<llvm::GlobalValue>(Aliasee); 2541 F->setLinkage(llvm::Function::ExternalWeakLinkage); 2542 WeakRefReferences.insert(F); 2543 2544 return ConstantAddress(Aliasee, Alignment); 2545 } 2546 2547 void CodeGenModule::EmitGlobal(GlobalDecl GD) { 2548 const auto *Global = cast<ValueDecl>(GD.getDecl()); 2549 2550 // Weak references don't produce any output by themselves. 2551 if (Global->hasAttr<WeakRefAttr>()) 2552 return; 2553 2554 // If this is an alias definition (which otherwise looks like a declaration) 2555 // emit it now. 2556 if (Global->hasAttr<AliasAttr>()) 2557 return EmitAliasDefinition(GD); 2558 2559 // IFunc like an alias whose value is resolved at runtime by calling resolver. 2560 if (Global->hasAttr<IFuncAttr>()) 2561 return emitIFuncDefinition(GD); 2562 2563 // If this is a cpu_dispatch multiversion function, emit the resolver. 2564 if (Global->hasAttr<CPUDispatchAttr>()) 2565 return emitCPUDispatchDefinition(GD); 2566 2567 // If this is CUDA, be selective about which declarations we emit. 2568 if (LangOpts.CUDA) { 2569 if (LangOpts.CUDAIsDevice) { 2570 if (!Global->hasAttr<CUDADeviceAttr>() && 2571 !Global->hasAttr<CUDAGlobalAttr>() && 2572 !Global->hasAttr<CUDAConstantAttr>() && 2573 !Global->hasAttr<CUDASharedAttr>() && 2574 !Global->getType()->isCUDADeviceBuiltinSurfaceType() && 2575 !Global->getType()->isCUDADeviceBuiltinTextureType()) 2576 return; 2577 } else { 2578 // We need to emit host-side 'shadows' for all global 2579 // device-side variables because the CUDA runtime needs their 2580 // size and host-side address in order to provide access to 2581 // their device-side incarnations. 2582 2583 // So device-only functions are the only things we skip. 2584 if (isa<FunctionDecl>(Global) && !Global->hasAttr<CUDAHostAttr>() && 2585 Global->hasAttr<CUDADeviceAttr>()) 2586 return; 2587 2588 assert((isa<FunctionDecl>(Global) || isa<VarDecl>(Global)) && 2589 "Expected Variable or Function"); 2590 } 2591 } 2592 2593 if (LangOpts.OpenMP) { 2594 // If this is OpenMP, check if it is legal to emit this global normally. 2595 if (OpenMPRuntime && OpenMPRuntime->emitTargetGlobal(GD)) 2596 return; 2597 if (auto *DRD = dyn_cast<OMPDeclareReductionDecl>(Global)) { 2598 if (MustBeEmitted(Global)) 2599 EmitOMPDeclareReduction(DRD); 2600 return; 2601 } else if (auto *DMD = dyn_cast<OMPDeclareMapperDecl>(Global)) { 2602 if (MustBeEmitted(Global)) 2603 EmitOMPDeclareMapper(DMD); 2604 return; 2605 } 2606 } 2607 2608 // Ignore declarations, they will be emitted on their first use. 2609 if (const auto *FD = dyn_cast<FunctionDecl>(Global)) { 2610 // Forward declarations are emitted lazily on first use. 2611 if (!FD->doesThisDeclarationHaveABody()) { 2612 if (!FD->doesDeclarationForceExternallyVisibleDefinition()) 2613 return; 2614 2615 StringRef MangledName = getMangledName(GD); 2616 2617 // Compute the function info and LLVM type. 2618 const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD); 2619 llvm::Type *Ty = getTypes().GetFunctionType(FI); 2620 2621 GetOrCreateLLVMFunction(MangledName, Ty, GD, /*ForVTable=*/false, 2622 /*DontDefer=*/false); 2623 return; 2624 } 2625 } else { 2626 const auto *VD = cast<VarDecl>(Global); 2627 assert(VD->isFileVarDecl() && "Cannot emit local var decl as global."); 2628 if (VD->isThisDeclarationADefinition() != VarDecl::Definition && 2629 !Context.isMSStaticDataMemberInlineDefinition(VD)) { 2630 if (LangOpts.OpenMP) { 2631 // Emit declaration of the must-be-emitted declare target variable. 2632 if (llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res = 2633 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD)) { 2634 bool UnifiedMemoryEnabled = 2635 getOpenMPRuntime().hasRequiresUnifiedSharedMemory(); 2636 if (*Res == OMPDeclareTargetDeclAttr::MT_To && 2637 !UnifiedMemoryEnabled) { 2638 (void)GetAddrOfGlobalVar(VD); 2639 } else { 2640 assert(((*Res == OMPDeclareTargetDeclAttr::MT_Link) || 2641 (*Res == OMPDeclareTargetDeclAttr::MT_To && 2642 UnifiedMemoryEnabled)) && 2643 "Link clause or to clause with unified memory expected."); 2644 (void)getOpenMPRuntime().getAddrOfDeclareTargetVar(VD); 2645 } 2646 2647 return; 2648 } 2649 } 2650 // If this declaration may have caused an inline variable definition to 2651 // change linkage, make sure that it's emitted. 2652 if (Context.getInlineVariableDefinitionKind(VD) == 2653 ASTContext::InlineVariableDefinitionKind::Strong) 2654 GetAddrOfGlobalVar(VD); 2655 return; 2656 } 2657 } 2658 2659 // Defer code generation to first use when possible, e.g. if this is an inline 2660 // function. If the global must always be emitted, do it eagerly if possible 2661 // to benefit from cache locality. 2662 if (MustBeEmitted(Global) && MayBeEmittedEagerly(Global)) { 2663 // Emit the definition if it can't be deferred. 2664 EmitGlobalDefinition(GD); 2665 return; 2666 } 2667 2668 // If we're deferring emission of a C++ variable with an 2669 // initializer, remember the order in which it appeared in the file. 2670 if (getLangOpts().CPlusPlus && isa<VarDecl>(Global) && 2671 cast<VarDecl>(Global)->hasInit()) { 2672 DelayedCXXInitPosition[Global] = CXXGlobalInits.size(); 2673 CXXGlobalInits.push_back(nullptr); 2674 } 2675 2676 StringRef MangledName = getMangledName(GD); 2677 if (GetGlobalValue(MangledName) != nullptr) { 2678 // The value has already been used and should therefore be emitted. 2679 addDeferredDeclToEmit(GD); 2680 } else if (MustBeEmitted(Global)) { 2681 // The value must be emitted, but cannot be emitted eagerly. 2682 assert(!MayBeEmittedEagerly(Global)); 2683 addDeferredDeclToEmit(GD); 2684 } else { 2685 // Otherwise, remember that we saw a deferred decl with this name. The 2686 // first use of the mangled name will cause it to move into 2687 // DeferredDeclsToEmit. 2688 DeferredDecls[MangledName] = GD; 2689 } 2690 } 2691 2692 // Check if T is a class type with a destructor that's not dllimport. 2693 static bool HasNonDllImportDtor(QualType T) { 2694 if (const auto *RT = T->getBaseElementTypeUnsafe()->getAs<RecordType>()) 2695 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl())) 2696 if (RD->getDestructor() && !RD->getDestructor()->hasAttr<DLLImportAttr>()) 2697 return true; 2698 2699 return false; 2700 } 2701 2702 namespace { 2703 struct FunctionIsDirectlyRecursive 2704 : public ConstStmtVisitor<FunctionIsDirectlyRecursive, bool> { 2705 const StringRef Name; 2706 const Builtin::Context &BI; 2707 FunctionIsDirectlyRecursive(StringRef N, const Builtin::Context &C) 2708 : Name(N), BI(C) {} 2709 2710 bool VisitCallExpr(const CallExpr *E) { 2711 const FunctionDecl *FD = E->getDirectCallee(); 2712 if (!FD) 2713 return false; 2714 AsmLabelAttr *Attr = FD->getAttr<AsmLabelAttr>(); 2715 if (Attr && Name == Attr->getLabel()) 2716 return true; 2717 unsigned BuiltinID = FD->getBuiltinID(); 2718 if (!BuiltinID || !BI.isLibFunction(BuiltinID)) 2719 return false; 2720 StringRef BuiltinName = BI.getName(BuiltinID); 2721 if (BuiltinName.startswith("__builtin_") && 2722 Name == BuiltinName.slice(strlen("__builtin_"), StringRef::npos)) { 2723 return true; 2724 } 2725 return false; 2726 } 2727 2728 bool VisitStmt(const Stmt *S) { 2729 for (const Stmt *Child : S->children()) 2730 if (Child && this->Visit(Child)) 2731 return true; 2732 return false; 2733 } 2734 }; 2735 2736 // Make sure we're not referencing non-imported vars or functions. 2737 struct DLLImportFunctionVisitor 2738 : public RecursiveASTVisitor<DLLImportFunctionVisitor> { 2739 bool SafeToInline = true; 2740 2741 bool shouldVisitImplicitCode() const { return true; } 2742 2743 bool VisitVarDecl(VarDecl *VD) { 2744 if (VD->getTLSKind()) { 2745 // A thread-local variable cannot be imported. 2746 SafeToInline = false; 2747 return SafeToInline; 2748 } 2749 2750 // A variable definition might imply a destructor call. 2751 if (VD->isThisDeclarationADefinition()) 2752 SafeToInline = !HasNonDllImportDtor(VD->getType()); 2753 2754 return SafeToInline; 2755 } 2756 2757 bool VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) { 2758 if (const auto *D = E->getTemporary()->getDestructor()) 2759 SafeToInline = D->hasAttr<DLLImportAttr>(); 2760 return SafeToInline; 2761 } 2762 2763 bool VisitDeclRefExpr(DeclRefExpr *E) { 2764 ValueDecl *VD = E->getDecl(); 2765 if (isa<FunctionDecl>(VD)) 2766 SafeToInline = VD->hasAttr<DLLImportAttr>(); 2767 else if (VarDecl *V = dyn_cast<VarDecl>(VD)) 2768 SafeToInline = !V->hasGlobalStorage() || V->hasAttr<DLLImportAttr>(); 2769 return SafeToInline; 2770 } 2771 2772 bool VisitCXXConstructExpr(CXXConstructExpr *E) { 2773 SafeToInline = E->getConstructor()->hasAttr<DLLImportAttr>(); 2774 return SafeToInline; 2775 } 2776 2777 bool VisitCXXMemberCallExpr(CXXMemberCallExpr *E) { 2778 CXXMethodDecl *M = E->getMethodDecl(); 2779 if (!M) { 2780 // Call through a pointer to member function. This is safe to inline. 2781 SafeToInline = true; 2782 } else { 2783 SafeToInline = M->hasAttr<DLLImportAttr>(); 2784 } 2785 return SafeToInline; 2786 } 2787 2788 bool VisitCXXDeleteExpr(CXXDeleteExpr *E) { 2789 SafeToInline = E->getOperatorDelete()->hasAttr<DLLImportAttr>(); 2790 return SafeToInline; 2791 } 2792 2793 bool VisitCXXNewExpr(CXXNewExpr *E) { 2794 SafeToInline = E->getOperatorNew()->hasAttr<DLLImportAttr>(); 2795 return SafeToInline; 2796 } 2797 }; 2798 } 2799 2800 // isTriviallyRecursive - Check if this function calls another 2801 // decl that, because of the asm attribute or the other decl being a builtin, 2802 // ends up pointing to itself. 2803 bool 2804 CodeGenModule::isTriviallyRecursive(const FunctionDecl *FD) { 2805 StringRef Name; 2806 if (getCXXABI().getMangleContext().shouldMangleDeclName(FD)) { 2807 // asm labels are a special kind of mangling we have to support. 2808 AsmLabelAttr *Attr = FD->getAttr<AsmLabelAttr>(); 2809 if (!Attr) 2810 return false; 2811 Name = Attr->getLabel(); 2812 } else { 2813 Name = FD->getName(); 2814 } 2815 2816 FunctionIsDirectlyRecursive Walker(Name, Context.BuiltinInfo); 2817 const Stmt *Body = FD->getBody(); 2818 return Body ? Walker.Visit(Body) : false; 2819 } 2820 2821 bool CodeGenModule::shouldEmitFunction(GlobalDecl GD) { 2822 if (getFunctionLinkage(GD) != llvm::Function::AvailableExternallyLinkage) 2823 return true; 2824 const auto *F = cast<FunctionDecl>(GD.getDecl()); 2825 if (CodeGenOpts.OptimizationLevel == 0 && !F->hasAttr<AlwaysInlineAttr>()) 2826 return false; 2827 2828 if (F->hasAttr<DLLImportAttr>()) { 2829 // Check whether it would be safe to inline this dllimport function. 2830 DLLImportFunctionVisitor Visitor; 2831 Visitor.TraverseFunctionDecl(const_cast<FunctionDecl*>(F)); 2832 if (!Visitor.SafeToInline) 2833 return false; 2834 2835 if (const CXXDestructorDecl *Dtor = dyn_cast<CXXDestructorDecl>(F)) { 2836 // Implicit destructor invocations aren't captured in the AST, so the 2837 // check above can't see them. Check for them manually here. 2838 for (const Decl *Member : Dtor->getParent()->decls()) 2839 if (isa<FieldDecl>(Member)) 2840 if (HasNonDllImportDtor(cast<FieldDecl>(Member)->getType())) 2841 return false; 2842 for (const CXXBaseSpecifier &B : Dtor->getParent()->bases()) 2843 if (HasNonDllImportDtor(B.getType())) 2844 return false; 2845 } 2846 } 2847 2848 // PR9614. Avoid cases where the source code is lying to us. An available 2849 // externally function should have an equivalent function somewhere else, 2850 // but a function that calls itself through asm label/`__builtin_` trickery is 2851 // clearly not equivalent to the real implementation. 2852 // This happens in glibc's btowc and in some configure checks. 2853 return !isTriviallyRecursive(F); 2854 } 2855 2856 bool CodeGenModule::shouldOpportunisticallyEmitVTables() { 2857 return CodeGenOpts.OptimizationLevel > 0; 2858 } 2859 2860 void CodeGenModule::EmitMultiVersionFunctionDefinition(GlobalDecl GD, 2861 llvm::GlobalValue *GV) { 2862 const auto *FD = cast<FunctionDecl>(GD.getDecl()); 2863 2864 if (FD->isCPUSpecificMultiVersion()) { 2865 auto *Spec = FD->getAttr<CPUSpecificAttr>(); 2866 for (unsigned I = 0; I < Spec->cpus_size(); ++I) 2867 EmitGlobalFunctionDefinition(GD.getWithMultiVersionIndex(I), nullptr); 2868 // Requires multiple emits. 2869 } else 2870 EmitGlobalFunctionDefinition(GD, GV); 2871 } 2872 2873 void CodeGenModule::EmitGlobalDefinition(GlobalDecl GD, llvm::GlobalValue *GV) { 2874 const auto *D = cast<ValueDecl>(GD.getDecl()); 2875 2876 PrettyStackTraceDecl CrashInfo(const_cast<ValueDecl *>(D), D->getLocation(), 2877 Context.getSourceManager(), 2878 "Generating code for declaration"); 2879 2880 if (const auto *FD = dyn_cast<FunctionDecl>(D)) { 2881 // At -O0, don't generate IR for functions with available_externally 2882 // linkage. 2883 if (!shouldEmitFunction(GD)) 2884 return; 2885 2886 llvm::TimeTraceScope TimeScope("CodeGen Function", [&]() { 2887 std::string Name; 2888 llvm::raw_string_ostream OS(Name); 2889 FD->getNameForDiagnostic(OS, getContext().getPrintingPolicy(), 2890 /*Qualified=*/true); 2891 return Name; 2892 }); 2893 2894 if (const auto *Method = dyn_cast<CXXMethodDecl>(D)) { 2895 // Make sure to emit the definition(s) before we emit the thunks. 2896 // This is necessary for the generation of certain thunks. 2897 if (isa<CXXConstructorDecl>(Method) || isa<CXXDestructorDecl>(Method)) 2898 ABI->emitCXXStructor(GD); 2899 else if (FD->isMultiVersion()) 2900 EmitMultiVersionFunctionDefinition(GD, GV); 2901 else 2902 EmitGlobalFunctionDefinition(GD, GV); 2903 2904 if (Method->isVirtual()) 2905 getVTables().EmitThunks(GD); 2906 2907 return; 2908 } 2909 2910 if (FD->isMultiVersion()) 2911 return EmitMultiVersionFunctionDefinition(GD, GV); 2912 return EmitGlobalFunctionDefinition(GD, GV); 2913 } 2914 2915 if (const auto *VD = dyn_cast<VarDecl>(D)) 2916 return EmitGlobalVarDefinition(VD, !VD->hasDefinition()); 2917 2918 llvm_unreachable("Invalid argument to EmitGlobalDefinition()"); 2919 } 2920 2921 static void ReplaceUsesOfNonProtoTypeWithRealFunction(llvm::GlobalValue *Old, 2922 llvm::Function *NewFn); 2923 2924 static unsigned 2925 TargetMVPriority(const TargetInfo &TI, 2926 const CodeGenFunction::MultiVersionResolverOption &RO) { 2927 unsigned Priority = 0; 2928 for (StringRef Feat : RO.Conditions.Features) 2929 Priority = std::max(Priority, TI.multiVersionSortPriority(Feat)); 2930 2931 if (!RO.Conditions.Architecture.empty()) 2932 Priority = std::max( 2933 Priority, TI.multiVersionSortPriority(RO.Conditions.Architecture)); 2934 return Priority; 2935 } 2936 2937 void CodeGenModule::emitMultiVersionFunctions() { 2938 for (GlobalDecl GD : MultiVersionFuncs) { 2939 SmallVector<CodeGenFunction::MultiVersionResolverOption, 10> Options; 2940 const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl()); 2941 getContext().forEachMultiversionedFunctionVersion( 2942 FD, [this, &GD, &Options](const FunctionDecl *CurFD) { 2943 GlobalDecl CurGD{ 2944 (CurFD->isDefined() ? CurFD->getDefinition() : CurFD)}; 2945 StringRef MangledName = getMangledName(CurGD); 2946 llvm::Constant *Func = GetGlobalValue(MangledName); 2947 if (!Func) { 2948 if (CurFD->isDefined()) { 2949 EmitGlobalFunctionDefinition(CurGD, nullptr); 2950 Func = GetGlobalValue(MangledName); 2951 } else { 2952 const CGFunctionInfo &FI = 2953 getTypes().arrangeGlobalDeclaration(GD); 2954 llvm::FunctionType *Ty = getTypes().GetFunctionType(FI); 2955 Func = GetAddrOfFunction(CurGD, Ty, /*ForVTable=*/false, 2956 /*DontDefer=*/false, ForDefinition); 2957 } 2958 assert(Func && "This should have just been created"); 2959 } 2960 2961 const auto *TA = CurFD->getAttr<TargetAttr>(); 2962 llvm::SmallVector<StringRef, 8> Feats; 2963 TA->getAddedFeatures(Feats); 2964 2965 Options.emplace_back(cast<llvm::Function>(Func), 2966 TA->getArchitecture(), Feats); 2967 }); 2968 2969 llvm::Function *ResolverFunc; 2970 const TargetInfo &TI = getTarget(); 2971 2972 if (TI.supportsIFunc() || FD->isTargetMultiVersion()) { 2973 ResolverFunc = cast<llvm::Function>( 2974 GetGlobalValue((getMangledName(GD) + ".resolver").str())); 2975 ResolverFunc->setLinkage(llvm::Function::WeakODRLinkage); 2976 } else { 2977 ResolverFunc = cast<llvm::Function>(GetGlobalValue(getMangledName(GD))); 2978 } 2979 2980 if (supportsCOMDAT()) 2981 ResolverFunc->setComdat( 2982 getModule().getOrInsertComdat(ResolverFunc->getName())); 2983 2984 llvm::stable_sort( 2985 Options, [&TI](const CodeGenFunction::MultiVersionResolverOption &LHS, 2986 const CodeGenFunction::MultiVersionResolverOption &RHS) { 2987 return TargetMVPriority(TI, LHS) > TargetMVPriority(TI, RHS); 2988 }); 2989 CodeGenFunction CGF(*this); 2990 CGF.EmitMultiVersionResolver(ResolverFunc, Options); 2991 } 2992 } 2993 2994 void CodeGenModule::emitCPUDispatchDefinition(GlobalDecl GD) { 2995 const auto *FD = cast<FunctionDecl>(GD.getDecl()); 2996 assert(FD && "Not a FunctionDecl?"); 2997 const auto *DD = FD->getAttr<CPUDispatchAttr>(); 2998 assert(DD && "Not a cpu_dispatch Function?"); 2999 llvm::Type *DeclTy = getTypes().ConvertType(FD->getType()); 3000 3001 if (const auto *CXXFD = dyn_cast<CXXMethodDecl>(FD)) { 3002 const CGFunctionInfo &FInfo = getTypes().arrangeCXXMethodDeclaration(CXXFD); 3003 DeclTy = getTypes().GetFunctionType(FInfo); 3004 } 3005 3006 StringRef ResolverName = getMangledName(GD); 3007 3008 llvm::Type *ResolverType; 3009 GlobalDecl ResolverGD; 3010 if (getTarget().supportsIFunc()) 3011 ResolverType = llvm::FunctionType::get( 3012 llvm::PointerType::get(DeclTy, 3013 Context.getTargetAddressSpace(FD->getType())), 3014 false); 3015 else { 3016 ResolverType = DeclTy; 3017 ResolverGD = GD; 3018 } 3019 3020 auto *ResolverFunc = cast<llvm::Function>(GetOrCreateLLVMFunction( 3021 ResolverName, ResolverType, ResolverGD, /*ForVTable=*/false)); 3022 ResolverFunc->setLinkage(llvm::Function::WeakODRLinkage); 3023 if (supportsCOMDAT()) 3024 ResolverFunc->setComdat( 3025 getModule().getOrInsertComdat(ResolverFunc->getName())); 3026 3027 SmallVector<CodeGenFunction::MultiVersionResolverOption, 10> Options; 3028 const TargetInfo &Target = getTarget(); 3029 unsigned Index = 0; 3030 for (const IdentifierInfo *II : DD->cpus()) { 3031 // Get the name of the target function so we can look it up/create it. 3032 std::string MangledName = getMangledNameImpl(*this, GD, FD, true) + 3033 getCPUSpecificMangling(*this, II->getName()); 3034 3035 llvm::Constant *Func = GetGlobalValue(MangledName); 3036 3037 if (!Func) { 3038 GlobalDecl ExistingDecl = Manglings.lookup(MangledName); 3039 if (ExistingDecl.getDecl() && 3040 ExistingDecl.getDecl()->getAsFunction()->isDefined()) { 3041 EmitGlobalFunctionDefinition(ExistingDecl, nullptr); 3042 Func = GetGlobalValue(MangledName); 3043 } else { 3044 if (!ExistingDecl.getDecl()) 3045 ExistingDecl = GD.getWithMultiVersionIndex(Index); 3046 3047 Func = GetOrCreateLLVMFunction( 3048 MangledName, DeclTy, ExistingDecl, 3049 /*ForVTable=*/false, /*DontDefer=*/true, 3050 /*IsThunk=*/false, llvm::AttributeList(), ForDefinition); 3051 } 3052 } 3053 3054 llvm::SmallVector<StringRef, 32> Features; 3055 Target.getCPUSpecificCPUDispatchFeatures(II->getName(), Features); 3056 llvm::transform(Features, Features.begin(), 3057 [](StringRef Str) { return Str.substr(1); }); 3058 Features.erase(std::remove_if( 3059 Features.begin(), Features.end(), [&Target](StringRef Feat) { 3060 return !Target.validateCpuSupports(Feat); 3061 }), Features.end()); 3062 Options.emplace_back(cast<llvm::Function>(Func), StringRef{}, Features); 3063 ++Index; 3064 } 3065 3066 llvm::sort( 3067 Options, [](const CodeGenFunction::MultiVersionResolverOption &LHS, 3068 const CodeGenFunction::MultiVersionResolverOption &RHS) { 3069 return CodeGenFunction::GetX86CpuSupportsMask(LHS.Conditions.Features) > 3070 CodeGenFunction::GetX86CpuSupportsMask(RHS.Conditions.Features); 3071 }); 3072 3073 // If the list contains multiple 'default' versions, such as when it contains 3074 // 'pentium' and 'generic', don't emit the call to the generic one (since we 3075 // always run on at least a 'pentium'). We do this by deleting the 'least 3076 // advanced' (read, lowest mangling letter). 3077 while (Options.size() > 1 && 3078 CodeGenFunction::GetX86CpuSupportsMask( 3079 (Options.end() - 2)->Conditions.Features) == 0) { 3080 StringRef LHSName = (Options.end() - 2)->Function->getName(); 3081 StringRef RHSName = (Options.end() - 1)->Function->getName(); 3082 if (LHSName.compare(RHSName) < 0) 3083 Options.erase(Options.end() - 2); 3084 else 3085 Options.erase(Options.end() - 1); 3086 } 3087 3088 CodeGenFunction CGF(*this); 3089 CGF.EmitMultiVersionResolver(ResolverFunc, Options); 3090 3091 if (getTarget().supportsIFunc()) { 3092 std::string AliasName = getMangledNameImpl( 3093 *this, GD, FD, /*OmitMultiVersionMangling=*/true); 3094 llvm::Constant *AliasFunc = GetGlobalValue(AliasName); 3095 if (!AliasFunc) { 3096 auto *IFunc = cast<llvm::GlobalIFunc>(GetOrCreateLLVMFunction( 3097 AliasName, DeclTy, GD, /*ForVTable=*/false, /*DontDefer=*/true, 3098 /*IsThunk=*/false, llvm::AttributeList(), NotForDefinition)); 3099 auto *GA = llvm::GlobalAlias::create( 3100 DeclTy, 0, getFunctionLinkage(GD), AliasName, IFunc, &getModule()); 3101 GA->setLinkage(llvm::Function::WeakODRLinkage); 3102 SetCommonAttributes(GD, GA); 3103 } 3104 } 3105 } 3106 3107 /// If a dispatcher for the specified mangled name is not in the module, create 3108 /// and return an llvm Function with the specified type. 3109 llvm::Constant *CodeGenModule::GetOrCreateMultiVersionResolver( 3110 GlobalDecl GD, llvm::Type *DeclTy, const FunctionDecl *FD) { 3111 std::string MangledName = 3112 getMangledNameImpl(*this, GD, FD, /*OmitMultiVersionMangling=*/true); 3113 3114 // Holds the name of the resolver, in ifunc mode this is the ifunc (which has 3115 // a separate resolver). 3116 std::string ResolverName = MangledName; 3117 if (getTarget().supportsIFunc()) 3118 ResolverName += ".ifunc"; 3119 else if (FD->isTargetMultiVersion()) 3120 ResolverName += ".resolver"; 3121 3122 // If this already exists, just return that one. 3123 if (llvm::GlobalValue *ResolverGV = GetGlobalValue(ResolverName)) 3124 return ResolverGV; 3125 3126 // Since this is the first time we've created this IFunc, make sure 3127 // that we put this multiversioned function into the list to be 3128 // replaced later if necessary (target multiversioning only). 3129 if (!FD->isCPUDispatchMultiVersion() && !FD->isCPUSpecificMultiVersion()) 3130 MultiVersionFuncs.push_back(GD); 3131 3132 if (getTarget().supportsIFunc()) { 3133 llvm::Type *ResolverType = llvm::FunctionType::get( 3134 llvm::PointerType::get( 3135 DeclTy, getContext().getTargetAddressSpace(FD->getType())), 3136 false); 3137 llvm::Constant *Resolver = GetOrCreateLLVMFunction( 3138 MangledName + ".resolver", ResolverType, GlobalDecl{}, 3139 /*ForVTable=*/false); 3140 llvm::GlobalIFunc *GIF = llvm::GlobalIFunc::create( 3141 DeclTy, 0, llvm::Function::WeakODRLinkage, "", Resolver, &getModule()); 3142 GIF->setName(ResolverName); 3143 SetCommonAttributes(FD, GIF); 3144 3145 return GIF; 3146 } 3147 3148 llvm::Constant *Resolver = GetOrCreateLLVMFunction( 3149 ResolverName, DeclTy, GlobalDecl{}, /*ForVTable=*/false); 3150 assert(isa<llvm::GlobalValue>(Resolver) && 3151 "Resolver should be created for the first time"); 3152 SetCommonAttributes(FD, cast<llvm::GlobalValue>(Resolver)); 3153 return Resolver; 3154 } 3155 3156 /// GetOrCreateLLVMFunction - If the specified mangled name is not in the 3157 /// module, create and return an llvm Function with the specified type. If there 3158 /// is something in the module with the specified name, return it potentially 3159 /// bitcasted to the right type. 3160 /// 3161 /// If D is non-null, it specifies a decl that correspond to this. This is used 3162 /// to set the attributes on the function when it is first created. 3163 llvm::Constant *CodeGenModule::GetOrCreateLLVMFunction( 3164 StringRef MangledName, llvm::Type *Ty, GlobalDecl GD, bool ForVTable, 3165 bool DontDefer, bool IsThunk, llvm::AttributeList ExtraAttrs, 3166 ForDefinition_t IsForDefinition) { 3167 const Decl *D = GD.getDecl(); 3168 3169 // Any attempts to use a MultiVersion function should result in retrieving 3170 // the iFunc instead. Name Mangling will handle the rest of the changes. 3171 if (const FunctionDecl *FD = cast_or_null<FunctionDecl>(D)) { 3172 // For the device mark the function as one that should be emitted. 3173 if (getLangOpts().OpenMPIsDevice && OpenMPRuntime && 3174 !OpenMPRuntime->markAsGlobalTarget(GD) && FD->isDefined() && 3175 !DontDefer && !IsForDefinition) { 3176 if (const FunctionDecl *FDDef = FD->getDefinition()) { 3177 GlobalDecl GDDef; 3178 if (const auto *CD = dyn_cast<CXXConstructorDecl>(FDDef)) 3179 GDDef = GlobalDecl(CD, GD.getCtorType()); 3180 else if (const auto *DD = dyn_cast<CXXDestructorDecl>(FDDef)) 3181 GDDef = GlobalDecl(DD, GD.getDtorType()); 3182 else 3183 GDDef = GlobalDecl(FDDef); 3184 EmitGlobal(GDDef); 3185 } 3186 } 3187 3188 if (FD->isMultiVersion()) { 3189 if (FD->hasAttr<TargetAttr>()) 3190 UpdateMultiVersionNames(GD, FD); 3191 if (!IsForDefinition) 3192 return GetOrCreateMultiVersionResolver(GD, Ty, FD); 3193 } 3194 } 3195 3196 // Lookup the entry, lazily creating it if necessary. 3197 llvm::GlobalValue *Entry = GetGlobalValue(MangledName); 3198 if (Entry) { 3199 if (WeakRefReferences.erase(Entry)) { 3200 const FunctionDecl *FD = cast_or_null<FunctionDecl>(D); 3201 if (FD && !FD->hasAttr<WeakAttr>()) 3202 Entry->setLinkage(llvm::Function::ExternalLinkage); 3203 } 3204 3205 // Handle dropped DLL attributes. 3206 if (D && !D->hasAttr<DLLImportAttr>() && !D->hasAttr<DLLExportAttr>()) { 3207 Entry->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass); 3208 setDSOLocal(Entry); 3209 } 3210 3211 // If there are two attempts to define the same mangled name, issue an 3212 // error. 3213 if (IsForDefinition && !Entry->isDeclaration()) { 3214 GlobalDecl OtherGD; 3215 // Check that GD is not yet in DiagnosedConflictingDefinitions is required 3216 // to make sure that we issue an error only once. 3217 if (lookupRepresentativeDecl(MangledName, OtherGD) && 3218 (GD.getCanonicalDecl().getDecl() != 3219 OtherGD.getCanonicalDecl().getDecl()) && 3220 DiagnosedConflictingDefinitions.insert(GD).second) { 3221 getDiags().Report(D->getLocation(), diag::err_duplicate_mangled_name) 3222 << MangledName; 3223 getDiags().Report(OtherGD.getDecl()->getLocation(), 3224 diag::note_previous_definition); 3225 } 3226 } 3227 3228 if ((isa<llvm::Function>(Entry) || isa<llvm::GlobalAlias>(Entry)) && 3229 (Entry->getValueType() == Ty)) { 3230 return Entry; 3231 } 3232 3233 // Make sure the result is of the correct type. 3234 // (If function is requested for a definition, we always need to create a new 3235 // function, not just return a bitcast.) 3236 if (!IsForDefinition) 3237 return llvm::ConstantExpr::getBitCast(Entry, Ty->getPointerTo()); 3238 } 3239 3240 // This function doesn't have a complete type (for example, the return 3241 // type is an incomplete struct). Use a fake type instead, and make 3242 // sure not to try to set attributes. 3243 bool IsIncompleteFunction = false; 3244 3245 llvm::FunctionType *FTy; 3246 if (isa<llvm::FunctionType>(Ty)) { 3247 FTy = cast<llvm::FunctionType>(Ty); 3248 } else { 3249 FTy = llvm::FunctionType::get(VoidTy, false); 3250 IsIncompleteFunction = true; 3251 } 3252 3253 llvm::Function *F = 3254 llvm::Function::Create(FTy, llvm::Function::ExternalLinkage, 3255 Entry ? StringRef() : MangledName, &getModule()); 3256 3257 // If we already created a function with the same mangled name (but different 3258 // type) before, take its name and add it to the list of functions to be 3259 // replaced with F at the end of CodeGen. 3260 // 3261 // This happens if there is a prototype for a function (e.g. "int f()") and 3262 // then a definition of a different type (e.g. "int f(int x)"). 3263 if (Entry) { 3264 F->takeName(Entry); 3265 3266 // This might be an implementation of a function without a prototype, in 3267 // which case, try to do special replacement of calls which match the new 3268 // prototype. The really key thing here is that we also potentially drop 3269 // arguments from the call site so as to make a direct call, which makes the 3270 // inliner happier and suppresses a number of optimizer warnings (!) about 3271 // dropping arguments. 3272 if (!Entry->use_empty()) { 3273 ReplaceUsesOfNonProtoTypeWithRealFunction(Entry, F); 3274 Entry->removeDeadConstantUsers(); 3275 } 3276 3277 llvm::Constant *BC = llvm::ConstantExpr::getBitCast( 3278 F, Entry->getValueType()->getPointerTo()); 3279 addGlobalValReplacement(Entry, BC); 3280 } 3281 3282 assert(F->getName() == MangledName && "name was uniqued!"); 3283 if (D) 3284 SetFunctionAttributes(GD, F, IsIncompleteFunction, IsThunk); 3285 if (ExtraAttrs.hasAttributes(llvm::AttributeList::FunctionIndex)) { 3286 llvm::AttrBuilder B(ExtraAttrs, llvm::AttributeList::FunctionIndex); 3287 F->addAttributes(llvm::AttributeList::FunctionIndex, B); 3288 } 3289 3290 if (!DontDefer) { 3291 // All MSVC dtors other than the base dtor are linkonce_odr and delegate to 3292 // each other bottoming out with the base dtor. Therefore we emit non-base 3293 // dtors on usage, even if there is no dtor definition in the TU. 3294 if (D && isa<CXXDestructorDecl>(D) && 3295 getCXXABI().useThunkForDtorVariant(cast<CXXDestructorDecl>(D), 3296 GD.getDtorType())) 3297 addDeferredDeclToEmit(GD); 3298 3299 // This is the first use or definition of a mangled name. If there is a 3300 // deferred decl with this name, remember that we need to emit it at the end 3301 // of the file. 3302 auto DDI = DeferredDecls.find(MangledName); 3303 if (DDI != DeferredDecls.end()) { 3304 // Move the potentially referenced deferred decl to the 3305 // DeferredDeclsToEmit list, and remove it from DeferredDecls (since we 3306 // don't need it anymore). 3307 addDeferredDeclToEmit(DDI->second); 3308 DeferredDecls.erase(DDI); 3309 3310 // Otherwise, there are cases we have to worry about where we're 3311 // using a declaration for which we must emit a definition but where 3312 // we might not find a top-level definition: 3313 // - member functions defined inline in their classes 3314 // - friend functions defined inline in some class 3315 // - special member functions with implicit definitions 3316 // If we ever change our AST traversal to walk into class methods, 3317 // this will be unnecessary. 3318 // 3319 // We also don't emit a definition for a function if it's going to be an 3320 // entry in a vtable, unless it's already marked as used. 3321 } else if (getLangOpts().CPlusPlus && D) { 3322 // Look for a declaration that's lexically in a record. 3323 for (const auto *FD = cast<FunctionDecl>(D)->getMostRecentDecl(); FD; 3324 FD = FD->getPreviousDecl()) { 3325 if (isa<CXXRecordDecl>(FD->getLexicalDeclContext())) { 3326 if (FD->doesThisDeclarationHaveABody()) { 3327 addDeferredDeclToEmit(GD.getWithDecl(FD)); 3328 break; 3329 } 3330 } 3331 } 3332 } 3333 } 3334 3335 // Make sure the result is of the requested type. 3336 if (!IsIncompleteFunction) { 3337 assert(F->getFunctionType() == Ty); 3338 return F; 3339 } 3340 3341 llvm::Type *PTy = llvm::PointerType::getUnqual(Ty); 3342 return llvm::ConstantExpr::getBitCast(F, PTy); 3343 } 3344 3345 /// GetAddrOfFunction - Return the address of the given function. If Ty is 3346 /// non-null, then this function will use the specified type if it has to 3347 /// create it (this occurs when we see a definition of the function). 3348 llvm::Constant *CodeGenModule::GetAddrOfFunction(GlobalDecl GD, 3349 llvm::Type *Ty, 3350 bool ForVTable, 3351 bool DontDefer, 3352 ForDefinition_t IsForDefinition) { 3353 assert(!cast<FunctionDecl>(GD.getDecl())->isConsteval() && 3354 "consteval function should never be emitted"); 3355 // If there was no specific requested type, just convert it now. 3356 if (!Ty) { 3357 const auto *FD = cast<FunctionDecl>(GD.getDecl()); 3358 Ty = getTypes().ConvertType(FD->getType()); 3359 } 3360 3361 // Devirtualized destructor calls may come through here instead of via 3362 // getAddrOfCXXStructor. Make sure we use the MS ABI base destructor instead 3363 // of the complete destructor when necessary. 3364 if (const auto *DD = dyn_cast<CXXDestructorDecl>(GD.getDecl())) { 3365 if (getTarget().getCXXABI().isMicrosoft() && 3366 GD.getDtorType() == Dtor_Complete && 3367 DD->getParent()->getNumVBases() == 0) 3368 GD = GlobalDecl(DD, Dtor_Base); 3369 } 3370 3371 StringRef MangledName = getMangledName(GD); 3372 return GetOrCreateLLVMFunction(MangledName, Ty, GD, ForVTable, DontDefer, 3373 /*IsThunk=*/false, llvm::AttributeList(), 3374 IsForDefinition); 3375 } 3376 3377 static const FunctionDecl * 3378 GetRuntimeFunctionDecl(ASTContext &C, StringRef Name) { 3379 TranslationUnitDecl *TUDecl = C.getTranslationUnitDecl(); 3380 DeclContext *DC = TranslationUnitDecl::castToDeclContext(TUDecl); 3381 3382 IdentifierInfo &CII = C.Idents.get(Name); 3383 for (const auto &Result : DC->lookup(&CII)) 3384 if (const auto FD = dyn_cast<FunctionDecl>(Result)) 3385 return FD; 3386 3387 if (!C.getLangOpts().CPlusPlus) 3388 return nullptr; 3389 3390 // Demangle the premangled name from getTerminateFn() 3391 IdentifierInfo &CXXII = 3392 (Name == "_ZSt9terminatev" || Name == "?terminate@@YAXXZ") 3393 ? C.Idents.get("terminate") 3394 : C.Idents.get(Name); 3395 3396 for (const auto &N : {"__cxxabiv1", "std"}) { 3397 IdentifierInfo &NS = C.Idents.get(N); 3398 for (const auto &Result : DC->lookup(&NS)) { 3399 NamespaceDecl *ND = dyn_cast<NamespaceDecl>(Result); 3400 if (auto LSD = dyn_cast<LinkageSpecDecl>(Result)) 3401 for (const auto &Result : LSD->lookup(&NS)) 3402 if ((ND = dyn_cast<NamespaceDecl>(Result))) 3403 break; 3404 3405 if (ND) 3406 for (const auto &Result : ND->lookup(&CXXII)) 3407 if (const auto *FD = dyn_cast<FunctionDecl>(Result)) 3408 return FD; 3409 } 3410 } 3411 3412 return nullptr; 3413 } 3414 3415 /// CreateRuntimeFunction - Create a new runtime function with the specified 3416 /// type and name. 3417 llvm::FunctionCallee 3418 CodeGenModule::CreateRuntimeFunction(llvm::FunctionType *FTy, StringRef Name, 3419 llvm::AttributeList ExtraAttrs, bool Local, 3420 bool AssumeConvergent) { 3421 if (AssumeConvergent) { 3422 ExtraAttrs = 3423 ExtraAttrs.addAttribute(VMContext, llvm::AttributeList::FunctionIndex, 3424 llvm::Attribute::Convergent); 3425 } 3426 3427 llvm::Constant *C = 3428 GetOrCreateLLVMFunction(Name, FTy, GlobalDecl(), /*ForVTable=*/false, 3429 /*DontDefer=*/false, /*IsThunk=*/false, 3430 ExtraAttrs); 3431 3432 if (auto *F = dyn_cast<llvm::Function>(C)) { 3433 if (F->empty()) { 3434 F->setCallingConv(getRuntimeCC()); 3435 3436 // In Windows Itanium environments, try to mark runtime functions 3437 // dllimport. For Mingw and MSVC, don't. We don't really know if the user 3438 // will link their standard library statically or dynamically. Marking 3439 // functions imported when they are not imported can cause linker errors 3440 // and warnings. 3441 if (!Local && getTriple().isWindowsItaniumEnvironment() && 3442 !getCodeGenOpts().LTOVisibilityPublicStd) { 3443 const FunctionDecl *FD = GetRuntimeFunctionDecl(Context, Name); 3444 if (!FD || FD->hasAttr<DLLImportAttr>()) { 3445 F->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass); 3446 F->setLinkage(llvm::GlobalValue::ExternalLinkage); 3447 } 3448 } 3449 setDSOLocal(F); 3450 } 3451 } 3452 3453 return {FTy, C}; 3454 } 3455 3456 /// isTypeConstant - Determine whether an object of this type can be emitted 3457 /// as a constant. 3458 /// 3459 /// If ExcludeCtor is true, the duration when the object's constructor runs 3460 /// will not be considered. The caller will need to verify that the object is 3461 /// not written to during its construction. 3462 bool CodeGenModule::isTypeConstant(QualType Ty, bool ExcludeCtor) { 3463 if (!Ty.isConstant(Context) && !Ty->isReferenceType()) 3464 return false; 3465 3466 if (Context.getLangOpts().CPlusPlus) { 3467 if (const CXXRecordDecl *Record 3468 = Context.getBaseElementType(Ty)->getAsCXXRecordDecl()) 3469 return ExcludeCtor && !Record->hasMutableFields() && 3470 Record->hasTrivialDestructor(); 3471 } 3472 3473 return true; 3474 } 3475 3476 /// GetOrCreateLLVMGlobal - If the specified mangled name is not in the module, 3477 /// create and return an llvm GlobalVariable with the specified type. If there 3478 /// is something in the module with the specified name, return it potentially 3479 /// bitcasted to the right type. 3480 /// 3481 /// If D is non-null, it specifies a decl that correspond to this. This is used 3482 /// to set the attributes on the global when it is first created. 3483 /// 3484 /// If IsForDefinition is true, it is guaranteed that an actual global with 3485 /// type Ty will be returned, not conversion of a variable with the same 3486 /// mangled name but some other type. 3487 llvm::Constant * 3488 CodeGenModule::GetOrCreateLLVMGlobal(StringRef MangledName, 3489 llvm::PointerType *Ty, 3490 const VarDecl *D, 3491 ForDefinition_t IsForDefinition) { 3492 // Lookup the entry, lazily creating it if necessary. 3493 llvm::GlobalValue *Entry = GetGlobalValue(MangledName); 3494 if (Entry) { 3495 if (WeakRefReferences.erase(Entry)) { 3496 if (D && !D->hasAttr<WeakAttr>()) 3497 Entry->setLinkage(llvm::Function::ExternalLinkage); 3498 } 3499 3500 // Handle dropped DLL attributes. 3501 if (D && !D->hasAttr<DLLImportAttr>() && !D->hasAttr<DLLExportAttr>()) 3502 Entry->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass); 3503 3504 if (LangOpts.OpenMP && !LangOpts.OpenMPSimd && D) 3505 getOpenMPRuntime().registerTargetGlobalVariable(D, Entry); 3506 3507 if (Entry->getType() == Ty) 3508 return Entry; 3509 3510 // If there are two attempts to define the same mangled name, issue an 3511 // error. 3512 if (IsForDefinition && !Entry->isDeclaration()) { 3513 GlobalDecl OtherGD; 3514 const VarDecl *OtherD; 3515 3516 // Check that D is not yet in DiagnosedConflictingDefinitions is required 3517 // to make sure that we issue an error only once. 3518 if (D && lookupRepresentativeDecl(MangledName, OtherGD) && 3519 (D->getCanonicalDecl() != OtherGD.getCanonicalDecl().getDecl()) && 3520 (OtherD = dyn_cast<VarDecl>(OtherGD.getDecl())) && 3521 OtherD->hasInit() && 3522 DiagnosedConflictingDefinitions.insert(D).second) { 3523 getDiags().Report(D->getLocation(), diag::err_duplicate_mangled_name) 3524 << MangledName; 3525 getDiags().Report(OtherGD.getDecl()->getLocation(), 3526 diag::note_previous_definition); 3527 } 3528 } 3529 3530 // Make sure the result is of the correct type. 3531 if (Entry->getType()->getAddressSpace() != Ty->getAddressSpace()) 3532 return llvm::ConstantExpr::getAddrSpaceCast(Entry, Ty); 3533 3534 // (If global is requested for a definition, we always need to create a new 3535 // global, not just return a bitcast.) 3536 if (!IsForDefinition) 3537 return llvm::ConstantExpr::getBitCast(Entry, Ty); 3538 } 3539 3540 auto AddrSpace = GetGlobalVarAddressSpace(D); 3541 auto TargetAddrSpace = getContext().getTargetAddressSpace(AddrSpace); 3542 3543 auto *GV = new llvm::GlobalVariable( 3544 getModule(), Ty->getElementType(), false, 3545 llvm::GlobalValue::ExternalLinkage, nullptr, MangledName, nullptr, 3546 llvm::GlobalVariable::NotThreadLocal, TargetAddrSpace); 3547 3548 // If we already created a global with the same mangled name (but different 3549 // type) before, take its name and remove it from its parent. 3550 if (Entry) { 3551 GV->takeName(Entry); 3552 3553 if (!Entry->use_empty()) { 3554 llvm::Constant *NewPtrForOldDecl = 3555 llvm::ConstantExpr::getBitCast(GV, Entry->getType()); 3556 Entry->replaceAllUsesWith(NewPtrForOldDecl); 3557 } 3558 3559 Entry->eraseFromParent(); 3560 } 3561 3562 // This is the first use or definition of a mangled name. If there is a 3563 // deferred decl with this name, remember that we need to emit it at the end 3564 // of the file. 3565 auto DDI = DeferredDecls.find(MangledName); 3566 if (DDI != DeferredDecls.end()) { 3567 // Move the potentially referenced deferred decl to the DeferredDeclsToEmit 3568 // list, and remove it from DeferredDecls (since we don't need it anymore). 3569 addDeferredDeclToEmit(DDI->second); 3570 DeferredDecls.erase(DDI); 3571 } 3572 3573 // Handle things which are present even on external declarations. 3574 if (D) { 3575 if (LangOpts.OpenMP && !LangOpts.OpenMPSimd) 3576 getOpenMPRuntime().registerTargetGlobalVariable(D, GV); 3577 3578 // FIXME: This code is overly simple and should be merged with other global 3579 // handling. 3580 GV->setConstant(isTypeConstant(D->getType(), false)); 3581 3582 GV->setAlignment(getContext().getDeclAlign(D).getAsAlign()); 3583 3584 setLinkageForGV(GV, D); 3585 3586 if (D->getTLSKind()) { 3587 if (D->getTLSKind() == VarDecl::TLS_Dynamic) 3588 CXXThreadLocals.push_back(D); 3589 setTLSMode(GV, *D); 3590 } 3591 3592 setGVProperties(GV, D); 3593 3594 // If required by the ABI, treat declarations of static data members with 3595 // inline initializers as definitions. 3596 if (getContext().isMSStaticDataMemberInlineDefinition(D)) { 3597 EmitGlobalVarDefinition(D); 3598 } 3599 3600 // Emit section information for extern variables. 3601 if (D->hasExternalStorage()) { 3602 if (const SectionAttr *SA = D->getAttr<SectionAttr>()) 3603 GV->setSection(SA->getName()); 3604 } 3605 3606 // Handle XCore specific ABI requirements. 3607 if (getTriple().getArch() == llvm::Triple::xcore && 3608 D->getLanguageLinkage() == CLanguageLinkage && 3609 D->getType().isConstant(Context) && 3610 isExternallyVisible(D->getLinkageAndVisibility().getLinkage())) 3611 GV->setSection(".cp.rodata"); 3612 3613 // Check if we a have a const declaration with an initializer, we may be 3614 // able to emit it as available_externally to expose it's value to the 3615 // optimizer. 3616 if (Context.getLangOpts().CPlusPlus && GV->hasExternalLinkage() && 3617 D->getType().isConstQualified() && !GV->hasInitializer() && 3618 !D->hasDefinition() && D->hasInit() && !D->hasAttr<DLLImportAttr>()) { 3619 const auto *Record = 3620 Context.getBaseElementType(D->getType())->getAsCXXRecordDecl(); 3621 bool HasMutableFields = Record && Record->hasMutableFields(); 3622 if (!HasMutableFields) { 3623 const VarDecl *InitDecl; 3624 const Expr *InitExpr = D->getAnyInitializer(InitDecl); 3625 if (InitExpr) { 3626 ConstantEmitter emitter(*this); 3627 llvm::Constant *Init = emitter.tryEmitForInitializer(*InitDecl); 3628 if (Init) { 3629 auto *InitType = Init->getType(); 3630 if (GV->getValueType() != InitType) { 3631 // The type of the initializer does not match the definition. 3632 // This happens when an initializer has a different type from 3633 // the type of the global (because of padding at the end of a 3634 // structure for instance). 3635 GV->setName(StringRef()); 3636 // Make a new global with the correct type, this is now guaranteed 3637 // to work. 3638 auto *NewGV = cast<llvm::GlobalVariable>( 3639 GetAddrOfGlobalVar(D, InitType, IsForDefinition) 3640 ->stripPointerCasts()); 3641 3642 // Erase the old global, since it is no longer used. 3643 GV->eraseFromParent(); 3644 GV = NewGV; 3645 } else { 3646 GV->setInitializer(Init); 3647 GV->setConstant(true); 3648 GV->setLinkage(llvm::GlobalValue::AvailableExternallyLinkage); 3649 } 3650 emitter.finalize(GV); 3651 } 3652 } 3653 } 3654 } 3655 } 3656 3657 if (GV->isDeclaration()) 3658 getTargetCodeGenInfo().setTargetAttributes(D, GV, *this); 3659 3660 LangAS ExpectedAS = 3661 D ? D->getType().getAddressSpace() 3662 : (LangOpts.OpenCL ? LangAS::opencl_global : LangAS::Default); 3663 assert(getContext().getTargetAddressSpace(ExpectedAS) == 3664 Ty->getPointerAddressSpace()); 3665 if (AddrSpace != ExpectedAS) 3666 return getTargetCodeGenInfo().performAddrSpaceCast(*this, GV, AddrSpace, 3667 ExpectedAS, Ty); 3668 3669 return GV; 3670 } 3671 3672 llvm::Constant * 3673 CodeGenModule::GetAddrOfGlobal(GlobalDecl GD, ForDefinition_t IsForDefinition) { 3674 const Decl *D = GD.getDecl(); 3675 3676 if (isa<CXXConstructorDecl>(D) || isa<CXXDestructorDecl>(D)) 3677 return getAddrOfCXXStructor(GD, /*FnInfo=*/nullptr, /*FnType=*/nullptr, 3678 /*DontDefer=*/false, IsForDefinition); 3679 3680 if (isa<CXXMethodDecl>(D)) { 3681 auto FInfo = 3682 &getTypes().arrangeCXXMethodDeclaration(cast<CXXMethodDecl>(D)); 3683 auto Ty = getTypes().GetFunctionType(*FInfo); 3684 return GetAddrOfFunction(GD, Ty, /*ForVTable=*/false, /*DontDefer=*/false, 3685 IsForDefinition); 3686 } 3687 3688 if (isa<FunctionDecl>(D)) { 3689 const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD); 3690 llvm::FunctionType *Ty = getTypes().GetFunctionType(FI); 3691 return GetAddrOfFunction(GD, Ty, /*ForVTable=*/false, /*DontDefer=*/false, 3692 IsForDefinition); 3693 } 3694 3695 return GetAddrOfGlobalVar(cast<VarDecl>(D), /*Ty=*/nullptr, IsForDefinition); 3696 } 3697 3698 llvm::GlobalVariable *CodeGenModule::CreateOrReplaceCXXRuntimeVariable( 3699 StringRef Name, llvm::Type *Ty, llvm::GlobalValue::LinkageTypes Linkage, 3700 unsigned Alignment) { 3701 llvm::GlobalVariable *GV = getModule().getNamedGlobal(Name); 3702 llvm::GlobalVariable *OldGV = nullptr; 3703 3704 if (GV) { 3705 // Check if the variable has the right type. 3706 if (GV->getValueType() == Ty) 3707 return GV; 3708 3709 // Because C++ name mangling, the only way we can end up with an already 3710 // existing global with the same name is if it has been declared extern "C". 3711 assert(GV->isDeclaration() && "Declaration has wrong type!"); 3712 OldGV = GV; 3713 } 3714 3715 // Create a new variable. 3716 GV = new llvm::GlobalVariable(getModule(), Ty, /*isConstant=*/true, 3717 Linkage, nullptr, Name); 3718 3719 if (OldGV) { 3720 // Replace occurrences of the old variable if needed. 3721 GV->takeName(OldGV); 3722 3723 if (!OldGV->use_empty()) { 3724 llvm::Constant *NewPtrForOldDecl = 3725 llvm::ConstantExpr::getBitCast(GV, OldGV->getType()); 3726 OldGV->replaceAllUsesWith(NewPtrForOldDecl); 3727 } 3728 3729 OldGV->eraseFromParent(); 3730 } 3731 3732 if (supportsCOMDAT() && GV->isWeakForLinker() && 3733 !GV->hasAvailableExternallyLinkage()) 3734 GV->setComdat(TheModule.getOrInsertComdat(GV->getName())); 3735 3736 GV->setAlignment(llvm::MaybeAlign(Alignment)); 3737 3738 return GV; 3739 } 3740 3741 /// GetAddrOfGlobalVar - Return the llvm::Constant for the address of the 3742 /// given global variable. If Ty is non-null and if the global doesn't exist, 3743 /// then it will be created with the specified type instead of whatever the 3744 /// normal requested type would be. If IsForDefinition is true, it is guaranteed 3745 /// that an actual global with type Ty will be returned, not conversion of a 3746 /// variable with the same mangled name but some other type. 3747 llvm::Constant *CodeGenModule::GetAddrOfGlobalVar(const VarDecl *D, 3748 llvm::Type *Ty, 3749 ForDefinition_t IsForDefinition) { 3750 assert(D->hasGlobalStorage() && "Not a global variable"); 3751 QualType ASTTy = D->getType(); 3752 if (!Ty) 3753 Ty = getTypes().ConvertTypeForMem(ASTTy); 3754 3755 llvm::PointerType *PTy = 3756 llvm::PointerType::get(Ty, getContext().getTargetAddressSpace(ASTTy)); 3757 3758 StringRef MangledName = getMangledName(D); 3759 return GetOrCreateLLVMGlobal(MangledName, PTy, D, IsForDefinition); 3760 } 3761 3762 /// CreateRuntimeVariable - Create a new runtime global variable with the 3763 /// specified type and name. 3764 llvm::Constant * 3765 CodeGenModule::CreateRuntimeVariable(llvm::Type *Ty, 3766 StringRef Name) { 3767 auto PtrTy = 3768 getContext().getLangOpts().OpenCL 3769 ? llvm::PointerType::get( 3770 Ty, getContext().getTargetAddressSpace(LangAS::opencl_global)) 3771 : llvm::PointerType::getUnqual(Ty); 3772 auto *Ret = GetOrCreateLLVMGlobal(Name, PtrTy, nullptr); 3773 setDSOLocal(cast<llvm::GlobalValue>(Ret->stripPointerCasts())); 3774 return Ret; 3775 } 3776 3777 void CodeGenModule::EmitTentativeDefinition(const VarDecl *D) { 3778 assert(!D->getInit() && "Cannot emit definite definitions here!"); 3779 3780 StringRef MangledName = getMangledName(D); 3781 llvm::GlobalValue *GV = GetGlobalValue(MangledName); 3782 3783 // We already have a definition, not declaration, with the same mangled name. 3784 // Emitting of declaration is not required (and actually overwrites emitted 3785 // definition). 3786 if (GV && !GV->isDeclaration()) 3787 return; 3788 3789 // If we have not seen a reference to this variable yet, place it into the 3790 // deferred declarations table to be emitted if needed later. 3791 if (!MustBeEmitted(D) && !GV) { 3792 DeferredDecls[MangledName] = D; 3793 return; 3794 } 3795 3796 // The tentative definition is the only definition. 3797 EmitGlobalVarDefinition(D); 3798 } 3799 3800 void CodeGenModule::EmitExternalDeclaration(const VarDecl *D) { 3801 EmitExternalVarDeclaration(D); 3802 } 3803 3804 CharUnits CodeGenModule::GetTargetTypeStoreSize(llvm::Type *Ty) const { 3805 return Context.toCharUnitsFromBits( 3806 getDataLayout().getTypeStoreSizeInBits(Ty)); 3807 } 3808 3809 LangAS CodeGenModule::GetGlobalVarAddressSpace(const VarDecl *D) { 3810 LangAS AddrSpace = LangAS::Default; 3811 if (LangOpts.OpenCL) { 3812 AddrSpace = D ? D->getType().getAddressSpace() : LangAS::opencl_global; 3813 assert(AddrSpace == LangAS::opencl_global || 3814 AddrSpace == LangAS::opencl_global_device || 3815 AddrSpace == LangAS::opencl_global_host || 3816 AddrSpace == LangAS::opencl_constant || 3817 AddrSpace == LangAS::opencl_local || 3818 AddrSpace >= LangAS::FirstTargetAddressSpace); 3819 return AddrSpace; 3820 } 3821 3822 if (LangOpts.CUDA && LangOpts.CUDAIsDevice) { 3823 if (D && D->hasAttr<CUDAConstantAttr>()) 3824 return LangAS::cuda_constant; 3825 else if (D && D->hasAttr<CUDASharedAttr>()) 3826 return LangAS::cuda_shared; 3827 else if (D && D->hasAttr<CUDADeviceAttr>()) 3828 return LangAS::cuda_device; 3829 else if (D && D->getType().isConstQualified()) 3830 return LangAS::cuda_constant; 3831 else 3832 return LangAS::cuda_device; 3833 } 3834 3835 if (LangOpts.OpenMP) { 3836 LangAS AS; 3837 if (OpenMPRuntime->hasAllocateAttributeForGlobalVar(D, AS)) 3838 return AS; 3839 } 3840 return getTargetCodeGenInfo().getGlobalVarAddressSpace(*this, D); 3841 } 3842 3843 LangAS CodeGenModule::getStringLiteralAddressSpace() const { 3844 // OpenCL v1.2 s6.5.3: a string literal is in the constant address space. 3845 if (LangOpts.OpenCL) 3846 return LangAS::opencl_constant; 3847 if (auto AS = getTarget().getConstantAddressSpace()) 3848 return AS.getValue(); 3849 return LangAS::Default; 3850 } 3851 3852 // In address space agnostic languages, string literals are in default address 3853 // space in AST. However, certain targets (e.g. amdgcn) request them to be 3854 // emitted in constant address space in LLVM IR. To be consistent with other 3855 // parts of AST, string literal global variables in constant address space 3856 // need to be casted to default address space before being put into address 3857 // map and referenced by other part of CodeGen. 3858 // In OpenCL, string literals are in constant address space in AST, therefore 3859 // they should not be casted to default address space. 3860 static llvm::Constant * 3861 castStringLiteralToDefaultAddressSpace(CodeGenModule &CGM, 3862 llvm::GlobalVariable *GV) { 3863 llvm::Constant *Cast = GV; 3864 if (!CGM.getLangOpts().OpenCL) { 3865 if (auto AS = CGM.getTarget().getConstantAddressSpace()) { 3866 if (AS != LangAS::Default) 3867 Cast = CGM.getTargetCodeGenInfo().performAddrSpaceCast( 3868 CGM, GV, AS.getValue(), LangAS::Default, 3869 GV->getValueType()->getPointerTo( 3870 CGM.getContext().getTargetAddressSpace(LangAS::Default))); 3871 } 3872 } 3873 return Cast; 3874 } 3875 3876 template<typename SomeDecl> 3877 void CodeGenModule::MaybeHandleStaticInExternC(const SomeDecl *D, 3878 llvm::GlobalValue *GV) { 3879 if (!getLangOpts().CPlusPlus) 3880 return; 3881 3882 // Must have 'used' attribute, or else inline assembly can't rely on 3883 // the name existing. 3884 if (!D->template hasAttr<UsedAttr>()) 3885 return; 3886 3887 // Must have internal linkage and an ordinary name. 3888 if (!D->getIdentifier() || D->getFormalLinkage() != InternalLinkage) 3889 return; 3890 3891 // Must be in an extern "C" context. Entities declared directly within 3892 // a record are not extern "C" even if the record is in such a context. 3893 const SomeDecl *First = D->getFirstDecl(); 3894 if (First->getDeclContext()->isRecord() || !First->isInExternCContext()) 3895 return; 3896 3897 // OK, this is an internal linkage entity inside an extern "C" linkage 3898 // specification. Make a note of that so we can give it the "expected" 3899 // mangled name if nothing else is using that name. 3900 std::pair<StaticExternCMap::iterator, bool> R = 3901 StaticExternCValues.insert(std::make_pair(D->getIdentifier(), GV)); 3902 3903 // If we have multiple internal linkage entities with the same name 3904 // in extern "C" regions, none of them gets that name. 3905 if (!R.second) 3906 R.first->second = nullptr; 3907 } 3908 3909 static bool shouldBeInCOMDAT(CodeGenModule &CGM, const Decl &D) { 3910 if (!CGM.supportsCOMDAT()) 3911 return false; 3912 3913 // Do not set COMDAT attribute for CUDA/HIP stub functions to prevent 3914 // them being "merged" by the COMDAT Folding linker optimization. 3915 if (D.hasAttr<CUDAGlobalAttr>()) 3916 return false; 3917 3918 if (D.hasAttr<SelectAnyAttr>()) 3919 return true; 3920 3921 GVALinkage Linkage; 3922 if (auto *VD = dyn_cast<VarDecl>(&D)) 3923 Linkage = CGM.getContext().GetGVALinkageForVariable(VD); 3924 else 3925 Linkage = CGM.getContext().GetGVALinkageForFunction(cast<FunctionDecl>(&D)); 3926 3927 switch (Linkage) { 3928 case GVA_Internal: 3929 case GVA_AvailableExternally: 3930 case GVA_StrongExternal: 3931 return false; 3932 case GVA_DiscardableODR: 3933 case GVA_StrongODR: 3934 return true; 3935 } 3936 llvm_unreachable("No such linkage"); 3937 } 3938 3939 void CodeGenModule::maybeSetTrivialComdat(const Decl &D, 3940 llvm::GlobalObject &GO) { 3941 if (!shouldBeInCOMDAT(*this, D)) 3942 return; 3943 GO.setComdat(TheModule.getOrInsertComdat(GO.getName())); 3944 } 3945 3946 /// Pass IsTentative as true if you want to create a tentative definition. 3947 void CodeGenModule::EmitGlobalVarDefinition(const VarDecl *D, 3948 bool IsTentative) { 3949 // OpenCL global variables of sampler type are translated to function calls, 3950 // therefore no need to be translated. 3951 QualType ASTTy = D->getType(); 3952 if (getLangOpts().OpenCL && ASTTy->isSamplerT()) 3953 return; 3954 3955 // If this is OpenMP device, check if it is legal to emit this global 3956 // normally. 3957 if (LangOpts.OpenMPIsDevice && OpenMPRuntime && 3958 OpenMPRuntime->emitTargetGlobalVariable(D)) 3959 return; 3960 3961 llvm::Constant *Init = nullptr; 3962 bool NeedsGlobalCtor = false; 3963 bool NeedsGlobalDtor = 3964 D->needsDestruction(getContext()) == QualType::DK_cxx_destructor; 3965 3966 const VarDecl *InitDecl; 3967 const Expr *InitExpr = D->getAnyInitializer(InitDecl); 3968 3969 Optional<ConstantEmitter> emitter; 3970 3971 // CUDA E.2.4.1 "__shared__ variables cannot have an initialization 3972 // as part of their declaration." Sema has already checked for 3973 // error cases, so we just need to set Init to UndefValue. 3974 bool IsCUDASharedVar = 3975 getLangOpts().CUDAIsDevice && D->hasAttr<CUDASharedAttr>(); 3976 // Shadows of initialized device-side global variables are also left 3977 // undefined. 3978 bool IsCUDAShadowVar = 3979 !getLangOpts().CUDAIsDevice && 3980 (D->hasAttr<CUDAConstantAttr>() || D->hasAttr<CUDADeviceAttr>() || 3981 D->hasAttr<CUDASharedAttr>()); 3982 bool IsCUDADeviceShadowVar = 3983 getLangOpts().CUDAIsDevice && 3984 (D->getType()->isCUDADeviceBuiltinSurfaceType() || 3985 D->getType()->isCUDADeviceBuiltinTextureType()); 3986 // HIP pinned shadow of initialized host-side global variables are also 3987 // left undefined. 3988 if (getLangOpts().CUDA && 3989 (IsCUDASharedVar || IsCUDAShadowVar || IsCUDADeviceShadowVar)) 3990 Init = llvm::UndefValue::get(getTypes().ConvertType(ASTTy)); 3991 else if (D->hasAttr<LoaderUninitializedAttr>()) 3992 Init = llvm::UndefValue::get(getTypes().ConvertType(ASTTy)); 3993 else if (!InitExpr) { 3994 // This is a tentative definition; tentative definitions are 3995 // implicitly initialized with { 0 }. 3996 // 3997 // Note that tentative definitions are only emitted at the end of 3998 // a translation unit, so they should never have incomplete 3999 // type. In addition, EmitTentativeDefinition makes sure that we 4000 // never attempt to emit a tentative definition if a real one 4001 // exists. A use may still exists, however, so we still may need 4002 // to do a RAUW. 4003 assert(!ASTTy->isIncompleteType() && "Unexpected incomplete type"); 4004 Init = EmitNullConstant(D->getType()); 4005 } else { 4006 initializedGlobalDecl = GlobalDecl(D); 4007 emitter.emplace(*this); 4008 Init = emitter->tryEmitForInitializer(*InitDecl); 4009 4010 if (!Init) { 4011 QualType T = InitExpr->getType(); 4012 if (D->getType()->isReferenceType()) 4013 T = D->getType(); 4014 4015 if (getLangOpts().CPlusPlus) { 4016 Init = EmitNullConstant(T); 4017 NeedsGlobalCtor = true; 4018 } else { 4019 ErrorUnsupported(D, "static initializer"); 4020 Init = llvm::UndefValue::get(getTypes().ConvertType(T)); 4021 } 4022 } else { 4023 // We don't need an initializer, so remove the entry for the delayed 4024 // initializer position (just in case this entry was delayed) if we 4025 // also don't need to register a destructor. 4026 if (getLangOpts().CPlusPlus && !NeedsGlobalDtor) 4027 DelayedCXXInitPosition.erase(D); 4028 } 4029 } 4030 4031 llvm::Type* InitType = Init->getType(); 4032 llvm::Constant *Entry = 4033 GetAddrOfGlobalVar(D, InitType, ForDefinition_t(!IsTentative)); 4034 4035 // Strip off pointer casts if we got them. 4036 Entry = Entry->stripPointerCasts(); 4037 4038 // Entry is now either a Function or GlobalVariable. 4039 auto *GV = dyn_cast<llvm::GlobalVariable>(Entry); 4040 4041 // We have a definition after a declaration with the wrong type. 4042 // We must make a new GlobalVariable* and update everything that used OldGV 4043 // (a declaration or tentative definition) with the new GlobalVariable* 4044 // (which will be a definition). 4045 // 4046 // This happens if there is a prototype for a global (e.g. 4047 // "extern int x[];") and then a definition of a different type (e.g. 4048 // "int x[10];"). This also happens when an initializer has a different type 4049 // from the type of the global (this happens with unions). 4050 if (!GV || GV->getValueType() != InitType || 4051 GV->getType()->getAddressSpace() != 4052 getContext().getTargetAddressSpace(GetGlobalVarAddressSpace(D))) { 4053 4054 // Move the old entry aside so that we'll create a new one. 4055 Entry->setName(StringRef()); 4056 4057 // Make a new global with the correct type, this is now guaranteed to work. 4058 GV = cast<llvm::GlobalVariable>( 4059 GetAddrOfGlobalVar(D, InitType, ForDefinition_t(!IsTentative)) 4060 ->stripPointerCasts()); 4061 4062 // Replace all uses of the old global with the new global 4063 llvm::Constant *NewPtrForOldDecl = 4064 llvm::ConstantExpr::getBitCast(GV, Entry->getType()); 4065 Entry->replaceAllUsesWith(NewPtrForOldDecl); 4066 4067 // Erase the old global, since it is no longer used. 4068 cast<llvm::GlobalValue>(Entry)->eraseFromParent(); 4069 } 4070 4071 MaybeHandleStaticInExternC(D, GV); 4072 4073 if (D->hasAttr<AnnotateAttr>()) 4074 AddGlobalAnnotations(D, GV); 4075 4076 // Set the llvm linkage type as appropriate. 4077 llvm::GlobalValue::LinkageTypes Linkage = 4078 getLLVMLinkageVarDefinition(D, GV->isConstant()); 4079 4080 // CUDA B.2.1 "The __device__ qualifier declares a variable that resides on 4081 // the device. [...]" 4082 // CUDA B.2.2 "The __constant__ qualifier, optionally used together with 4083 // __device__, declares a variable that: [...] 4084 // Is accessible from all the threads within the grid and from the host 4085 // through the runtime library (cudaGetSymbolAddress() / cudaGetSymbolSize() 4086 // / cudaMemcpyToSymbol() / cudaMemcpyFromSymbol())." 4087 if (GV && LangOpts.CUDA) { 4088 if (LangOpts.CUDAIsDevice) { 4089 if (Linkage != llvm::GlobalValue::InternalLinkage && 4090 (D->hasAttr<CUDADeviceAttr>() || D->hasAttr<CUDAConstantAttr>())) 4091 GV->setExternallyInitialized(true); 4092 } else { 4093 // Host-side shadows of external declarations of device-side 4094 // global variables become internal definitions. These have to 4095 // be internal in order to prevent name conflicts with global 4096 // host variables with the same name in a different TUs. 4097 if (D->hasAttr<CUDADeviceAttr>() || D->hasAttr<CUDAConstantAttr>()) { 4098 Linkage = llvm::GlobalValue::InternalLinkage; 4099 // Shadow variables and their properties must be registered with CUDA 4100 // runtime. Skip Extern global variables, which will be registered in 4101 // the TU where they are defined. 4102 if (!D->hasExternalStorage()) 4103 getCUDARuntime().registerDeviceVar(D, *GV, !D->hasDefinition(), 4104 D->hasAttr<CUDAConstantAttr>()); 4105 } else if (D->hasAttr<CUDASharedAttr>()) { 4106 // __shared__ variables are odd. Shadows do get created, but 4107 // they are not registered with the CUDA runtime, so they 4108 // can't really be used to access their device-side 4109 // counterparts. It's not clear yet whether it's nvcc's bug or 4110 // a feature, but we've got to do the same for compatibility. 4111 Linkage = llvm::GlobalValue::InternalLinkage; 4112 } else if (D->getType()->isCUDADeviceBuiltinSurfaceType() || 4113 D->getType()->isCUDADeviceBuiltinTextureType()) { 4114 // Builtin surfaces and textures and their template arguments are 4115 // also registered with CUDA runtime. 4116 Linkage = llvm::GlobalValue::InternalLinkage; 4117 const ClassTemplateSpecializationDecl *TD = 4118 cast<ClassTemplateSpecializationDecl>( 4119 D->getType()->getAs<RecordType>()->getDecl()); 4120 const TemplateArgumentList &Args = TD->getTemplateArgs(); 4121 if (TD->hasAttr<CUDADeviceBuiltinSurfaceTypeAttr>()) { 4122 assert(Args.size() == 2 && 4123 "Unexpected number of template arguments of CUDA device " 4124 "builtin surface type."); 4125 auto SurfType = Args[1].getAsIntegral(); 4126 if (!D->hasExternalStorage()) 4127 getCUDARuntime().registerDeviceSurf(D, *GV, !D->hasDefinition(), 4128 SurfType.getSExtValue()); 4129 } else { 4130 assert(Args.size() == 3 && 4131 "Unexpected number of template arguments of CUDA device " 4132 "builtin texture type."); 4133 auto TexType = Args[1].getAsIntegral(); 4134 auto Normalized = Args[2].getAsIntegral(); 4135 if (!D->hasExternalStorage()) 4136 getCUDARuntime().registerDeviceTex(D, *GV, !D->hasDefinition(), 4137 TexType.getSExtValue(), 4138 Normalized.getZExtValue()); 4139 } 4140 } 4141 } 4142 } 4143 4144 GV->setInitializer(Init); 4145 if (emitter) 4146 emitter->finalize(GV); 4147 4148 // If it is safe to mark the global 'constant', do so now. 4149 GV->setConstant(!NeedsGlobalCtor && !NeedsGlobalDtor && 4150 isTypeConstant(D->getType(), true)); 4151 4152 // If it is in a read-only section, mark it 'constant'. 4153 if (const SectionAttr *SA = D->getAttr<SectionAttr>()) { 4154 const ASTContext::SectionInfo &SI = Context.SectionInfos[SA->getName()]; 4155 if ((SI.SectionFlags & ASTContext::PSF_Write) == 0) 4156 GV->setConstant(true); 4157 } 4158 4159 GV->setAlignment(getContext().getDeclAlign(D).getAsAlign()); 4160 4161 // On Darwin, unlike other Itanium C++ ABI platforms, the thread-wrapper 4162 // function is only defined alongside the variable, not also alongside 4163 // callers. Normally, all accesses to a thread_local go through the 4164 // thread-wrapper in order to ensure initialization has occurred, underlying 4165 // variable will never be used other than the thread-wrapper, so it can be 4166 // converted to internal linkage. 4167 // 4168 // However, if the variable has the 'constinit' attribute, it _can_ be 4169 // referenced directly, without calling the thread-wrapper, so the linkage 4170 // must not be changed. 4171 // 4172 // Additionally, if the variable isn't plain external linkage, e.g. if it's 4173 // weak or linkonce, the de-duplication semantics are important to preserve, 4174 // so we don't change the linkage. 4175 if (D->getTLSKind() == VarDecl::TLS_Dynamic && 4176 Linkage == llvm::GlobalValue::ExternalLinkage && 4177 Context.getTargetInfo().getTriple().isOSDarwin() && 4178 !D->hasAttr<ConstInitAttr>()) 4179 Linkage = llvm::GlobalValue::InternalLinkage; 4180 4181 GV->setLinkage(Linkage); 4182 if (D->hasAttr<DLLImportAttr>()) 4183 GV->setDLLStorageClass(llvm::GlobalVariable::DLLImportStorageClass); 4184 else if (D->hasAttr<DLLExportAttr>()) 4185 GV->setDLLStorageClass(llvm::GlobalVariable::DLLExportStorageClass); 4186 else 4187 GV->setDLLStorageClass(llvm::GlobalVariable::DefaultStorageClass); 4188 4189 if (Linkage == llvm::GlobalVariable::CommonLinkage) { 4190 // common vars aren't constant even if declared const. 4191 GV->setConstant(false); 4192 // Tentative definition of global variables may be initialized with 4193 // non-zero null pointers. In this case they should have weak linkage 4194 // since common linkage must have zero initializer and must not have 4195 // explicit section therefore cannot have non-zero initial value. 4196 if (!GV->getInitializer()->isNullValue()) 4197 GV->setLinkage(llvm::GlobalVariable::WeakAnyLinkage); 4198 } 4199 4200 setNonAliasAttributes(D, GV); 4201 4202 if (D->getTLSKind() && !GV->isThreadLocal()) { 4203 if (D->getTLSKind() == VarDecl::TLS_Dynamic) 4204 CXXThreadLocals.push_back(D); 4205 setTLSMode(GV, *D); 4206 } 4207 4208 maybeSetTrivialComdat(*D, *GV); 4209 4210 // Emit the initializer function if necessary. 4211 if (NeedsGlobalCtor || NeedsGlobalDtor) 4212 EmitCXXGlobalVarDeclInitFunc(D, GV, NeedsGlobalCtor); 4213 4214 SanitizerMD->reportGlobalToASan(GV, *D, NeedsGlobalCtor); 4215 4216 // Emit global variable debug information. 4217 if (CGDebugInfo *DI = getModuleDebugInfo()) 4218 if (getCodeGenOpts().hasReducedDebugInfo()) 4219 DI->EmitGlobalVariable(GV, D); 4220 } 4221 4222 void CodeGenModule::EmitExternalVarDeclaration(const VarDecl *D) { 4223 if (CGDebugInfo *DI = getModuleDebugInfo()) 4224 if (getCodeGenOpts().hasReducedDebugInfo()) { 4225 QualType ASTTy = D->getType(); 4226 llvm::Type *Ty = getTypes().ConvertTypeForMem(D->getType()); 4227 llvm::PointerType *PTy = 4228 llvm::PointerType::get(Ty, getContext().getTargetAddressSpace(ASTTy)); 4229 llvm::Constant *GV = GetOrCreateLLVMGlobal(D->getName(), PTy, D); 4230 DI->EmitExternalVariable( 4231 cast<llvm::GlobalVariable>(GV->stripPointerCasts()), D); 4232 } 4233 } 4234 4235 static bool isVarDeclStrongDefinition(const ASTContext &Context, 4236 CodeGenModule &CGM, const VarDecl *D, 4237 bool NoCommon) { 4238 // Don't give variables common linkage if -fno-common was specified unless it 4239 // was overridden by a NoCommon attribute. 4240 if ((NoCommon || D->hasAttr<NoCommonAttr>()) && !D->hasAttr<CommonAttr>()) 4241 return true; 4242 4243 // C11 6.9.2/2: 4244 // A declaration of an identifier for an object that has file scope without 4245 // an initializer, and without a storage-class specifier or with the 4246 // storage-class specifier static, constitutes a tentative definition. 4247 if (D->getInit() || D->hasExternalStorage()) 4248 return true; 4249 4250 // A variable cannot be both common and exist in a section. 4251 if (D->hasAttr<SectionAttr>()) 4252 return true; 4253 4254 // A variable cannot be both common and exist in a section. 4255 // We don't try to determine which is the right section in the front-end. 4256 // If no specialized section name is applicable, it will resort to default. 4257 if (D->hasAttr<PragmaClangBSSSectionAttr>() || 4258 D->hasAttr<PragmaClangDataSectionAttr>() || 4259 D->hasAttr<PragmaClangRelroSectionAttr>() || 4260 D->hasAttr<PragmaClangRodataSectionAttr>()) 4261 return true; 4262 4263 // Thread local vars aren't considered common linkage. 4264 if (D->getTLSKind()) 4265 return true; 4266 4267 // Tentative definitions marked with WeakImportAttr are true definitions. 4268 if (D->hasAttr<WeakImportAttr>()) 4269 return true; 4270 4271 // A variable cannot be both common and exist in a comdat. 4272 if (shouldBeInCOMDAT(CGM, *D)) 4273 return true; 4274 4275 // Declarations with a required alignment do not have common linkage in MSVC 4276 // mode. 4277 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) { 4278 if (D->hasAttr<AlignedAttr>()) 4279 return true; 4280 QualType VarType = D->getType(); 4281 if (Context.isAlignmentRequired(VarType)) 4282 return true; 4283 4284 if (const auto *RT = VarType->getAs<RecordType>()) { 4285 const RecordDecl *RD = RT->getDecl(); 4286 for (const FieldDecl *FD : RD->fields()) { 4287 if (FD->isBitField()) 4288 continue; 4289 if (FD->hasAttr<AlignedAttr>()) 4290 return true; 4291 if (Context.isAlignmentRequired(FD->getType())) 4292 return true; 4293 } 4294 } 4295 } 4296 4297 // Microsoft's link.exe doesn't support alignments greater than 32 bytes for 4298 // common symbols, so symbols with greater alignment requirements cannot be 4299 // common. 4300 // Other COFF linkers (ld.bfd and LLD) support arbitrary power-of-two 4301 // alignments for common symbols via the aligncomm directive, so this 4302 // restriction only applies to MSVC environments. 4303 if (Context.getTargetInfo().getTriple().isKnownWindowsMSVCEnvironment() && 4304 Context.getTypeAlignIfKnown(D->getType()) > 4305 Context.toBits(CharUnits::fromQuantity(32))) 4306 return true; 4307 4308 return false; 4309 } 4310 4311 llvm::GlobalValue::LinkageTypes CodeGenModule::getLLVMLinkageForDeclarator( 4312 const DeclaratorDecl *D, GVALinkage Linkage, bool IsConstantVariable) { 4313 if (Linkage == GVA_Internal) 4314 return llvm::Function::InternalLinkage; 4315 4316 if (D->hasAttr<WeakAttr>()) { 4317 if (IsConstantVariable) 4318 return llvm::GlobalVariable::WeakODRLinkage; 4319 else 4320 return llvm::GlobalVariable::WeakAnyLinkage; 4321 } 4322 4323 if (const auto *FD = D->getAsFunction()) 4324 if (FD->isMultiVersion() && Linkage == GVA_AvailableExternally) 4325 return llvm::GlobalVariable::LinkOnceAnyLinkage; 4326 4327 // We are guaranteed to have a strong definition somewhere else, 4328 // so we can use available_externally linkage. 4329 if (Linkage == GVA_AvailableExternally) 4330 return llvm::GlobalValue::AvailableExternallyLinkage; 4331 4332 // Note that Apple's kernel linker doesn't support symbol 4333 // coalescing, so we need to avoid linkonce and weak linkages there. 4334 // Normally, this means we just map to internal, but for explicit 4335 // instantiations we'll map to external. 4336 4337 // In C++, the compiler has to emit a definition in every translation unit 4338 // that references the function. We should use linkonce_odr because 4339 // a) if all references in this translation unit are optimized away, we 4340 // don't need to codegen it. b) if the function persists, it needs to be 4341 // merged with other definitions. c) C++ has the ODR, so we know the 4342 // definition is dependable. 4343 if (Linkage == GVA_DiscardableODR) 4344 return !Context.getLangOpts().AppleKext ? llvm::Function::LinkOnceODRLinkage 4345 : llvm::Function::InternalLinkage; 4346 4347 // An explicit instantiation of a template has weak linkage, since 4348 // explicit instantiations can occur in multiple translation units 4349 // and must all be equivalent. However, we are not allowed to 4350 // throw away these explicit instantiations. 4351 // 4352 // We don't currently support CUDA device code spread out across multiple TUs, 4353 // so say that CUDA templates are either external (for kernels) or internal. 4354 // This lets llvm perform aggressive inter-procedural optimizations. 4355 if (Linkage == GVA_StrongODR) { 4356 if (Context.getLangOpts().AppleKext) 4357 return llvm::Function::ExternalLinkage; 4358 if (Context.getLangOpts().CUDA && Context.getLangOpts().CUDAIsDevice) 4359 return D->hasAttr<CUDAGlobalAttr>() ? llvm::Function::ExternalLinkage 4360 : llvm::Function::InternalLinkage; 4361 return llvm::Function::WeakODRLinkage; 4362 } 4363 4364 // C++ doesn't have tentative definitions and thus cannot have common 4365 // linkage. 4366 if (!getLangOpts().CPlusPlus && isa<VarDecl>(D) && 4367 !isVarDeclStrongDefinition(Context, *this, cast<VarDecl>(D), 4368 CodeGenOpts.NoCommon)) 4369 return llvm::GlobalVariable::CommonLinkage; 4370 4371 // selectany symbols are externally visible, so use weak instead of 4372 // linkonce. MSVC optimizes away references to const selectany globals, so 4373 // all definitions should be the same and ODR linkage should be used. 4374 // http://msdn.microsoft.com/en-us/library/5tkz6s71.aspx 4375 if (D->hasAttr<SelectAnyAttr>()) 4376 return llvm::GlobalVariable::WeakODRLinkage; 4377 4378 // Otherwise, we have strong external linkage. 4379 assert(Linkage == GVA_StrongExternal); 4380 return llvm::GlobalVariable::ExternalLinkage; 4381 } 4382 4383 llvm::GlobalValue::LinkageTypes CodeGenModule::getLLVMLinkageVarDefinition( 4384 const VarDecl *VD, bool IsConstant) { 4385 GVALinkage Linkage = getContext().GetGVALinkageForVariable(VD); 4386 return getLLVMLinkageForDeclarator(VD, Linkage, IsConstant); 4387 } 4388 4389 /// Replace the uses of a function that was declared with a non-proto type. 4390 /// We want to silently drop extra arguments from call sites 4391 static void replaceUsesOfNonProtoConstant(llvm::Constant *old, 4392 llvm::Function *newFn) { 4393 // Fast path. 4394 if (old->use_empty()) return; 4395 4396 llvm::Type *newRetTy = newFn->getReturnType(); 4397 SmallVector<llvm::Value*, 4> newArgs; 4398 SmallVector<llvm::OperandBundleDef, 1> newBundles; 4399 4400 for (llvm::Value::use_iterator ui = old->use_begin(), ue = old->use_end(); 4401 ui != ue; ) { 4402 llvm::Value::use_iterator use = ui++; // Increment before the use is erased. 4403 llvm::User *user = use->getUser(); 4404 4405 // Recognize and replace uses of bitcasts. Most calls to 4406 // unprototyped functions will use bitcasts. 4407 if (auto *bitcast = dyn_cast<llvm::ConstantExpr>(user)) { 4408 if (bitcast->getOpcode() == llvm::Instruction::BitCast) 4409 replaceUsesOfNonProtoConstant(bitcast, newFn); 4410 continue; 4411 } 4412 4413 // Recognize calls to the function. 4414 llvm::CallBase *callSite = dyn_cast<llvm::CallBase>(user); 4415 if (!callSite) continue; 4416 if (!callSite->isCallee(&*use)) 4417 continue; 4418 4419 // If the return types don't match exactly, then we can't 4420 // transform this call unless it's dead. 4421 if (callSite->getType() != newRetTy && !callSite->use_empty()) 4422 continue; 4423 4424 // Get the call site's attribute list. 4425 SmallVector<llvm::AttributeSet, 8> newArgAttrs; 4426 llvm::AttributeList oldAttrs = callSite->getAttributes(); 4427 4428 // If the function was passed too few arguments, don't transform. 4429 unsigned newNumArgs = newFn->arg_size(); 4430 if (callSite->arg_size() < newNumArgs) 4431 continue; 4432 4433 // If extra arguments were passed, we silently drop them. 4434 // If any of the types mismatch, we don't transform. 4435 unsigned argNo = 0; 4436 bool dontTransform = false; 4437 for (llvm::Argument &A : newFn->args()) { 4438 if (callSite->getArgOperand(argNo)->getType() != A.getType()) { 4439 dontTransform = true; 4440 break; 4441 } 4442 4443 // Add any parameter attributes. 4444 newArgAttrs.push_back(oldAttrs.getParamAttributes(argNo)); 4445 argNo++; 4446 } 4447 if (dontTransform) 4448 continue; 4449 4450 // Okay, we can transform this. Create the new call instruction and copy 4451 // over the required information. 4452 newArgs.append(callSite->arg_begin(), callSite->arg_begin() + argNo); 4453 4454 // Copy over any operand bundles. 4455 callSite->getOperandBundlesAsDefs(newBundles); 4456 4457 llvm::CallBase *newCall; 4458 if (dyn_cast<llvm::CallInst>(callSite)) { 4459 newCall = 4460 llvm::CallInst::Create(newFn, newArgs, newBundles, "", callSite); 4461 } else { 4462 auto *oldInvoke = cast<llvm::InvokeInst>(callSite); 4463 newCall = llvm::InvokeInst::Create(newFn, oldInvoke->getNormalDest(), 4464 oldInvoke->getUnwindDest(), newArgs, 4465 newBundles, "", callSite); 4466 } 4467 newArgs.clear(); // for the next iteration 4468 4469 if (!newCall->getType()->isVoidTy()) 4470 newCall->takeName(callSite); 4471 newCall->setAttributes(llvm::AttributeList::get( 4472 newFn->getContext(), oldAttrs.getFnAttributes(), 4473 oldAttrs.getRetAttributes(), newArgAttrs)); 4474 newCall->setCallingConv(callSite->getCallingConv()); 4475 4476 // Finally, remove the old call, replacing any uses with the new one. 4477 if (!callSite->use_empty()) 4478 callSite->replaceAllUsesWith(newCall); 4479 4480 // Copy debug location attached to CI. 4481 if (callSite->getDebugLoc()) 4482 newCall->setDebugLoc(callSite->getDebugLoc()); 4483 4484 callSite->eraseFromParent(); 4485 } 4486 } 4487 4488 /// ReplaceUsesOfNonProtoTypeWithRealFunction - This function is called when we 4489 /// implement a function with no prototype, e.g. "int foo() {}". If there are 4490 /// existing call uses of the old function in the module, this adjusts them to 4491 /// call the new function directly. 4492 /// 4493 /// This is not just a cleanup: the always_inline pass requires direct calls to 4494 /// functions to be able to inline them. If there is a bitcast in the way, it 4495 /// won't inline them. Instcombine normally deletes these calls, but it isn't 4496 /// run at -O0. 4497 static void ReplaceUsesOfNonProtoTypeWithRealFunction(llvm::GlobalValue *Old, 4498 llvm::Function *NewFn) { 4499 // If we're redefining a global as a function, don't transform it. 4500 if (!isa<llvm::Function>(Old)) return; 4501 4502 replaceUsesOfNonProtoConstant(Old, NewFn); 4503 } 4504 4505 void CodeGenModule::HandleCXXStaticMemberVarInstantiation(VarDecl *VD) { 4506 auto DK = VD->isThisDeclarationADefinition(); 4507 if (DK == VarDecl::Definition && VD->hasAttr<DLLImportAttr>()) 4508 return; 4509 4510 TemplateSpecializationKind TSK = VD->getTemplateSpecializationKind(); 4511 // If we have a definition, this might be a deferred decl. If the 4512 // instantiation is explicit, make sure we emit it at the end. 4513 if (VD->getDefinition() && TSK == TSK_ExplicitInstantiationDefinition) 4514 GetAddrOfGlobalVar(VD); 4515 4516 EmitTopLevelDecl(VD); 4517 } 4518 4519 void CodeGenModule::EmitGlobalFunctionDefinition(GlobalDecl GD, 4520 llvm::GlobalValue *GV) { 4521 const auto *D = cast<FunctionDecl>(GD.getDecl()); 4522 4523 // Compute the function info and LLVM type. 4524 const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD); 4525 llvm::FunctionType *Ty = getTypes().GetFunctionType(FI); 4526 4527 // Get or create the prototype for the function. 4528 if (!GV || (GV->getValueType() != Ty)) 4529 GV = cast<llvm::GlobalValue>(GetAddrOfFunction(GD, Ty, /*ForVTable=*/false, 4530 /*DontDefer=*/true, 4531 ForDefinition)); 4532 4533 // Already emitted. 4534 if (!GV->isDeclaration()) 4535 return; 4536 4537 // We need to set linkage and visibility on the function before 4538 // generating code for it because various parts of IR generation 4539 // want to propagate this information down (e.g. to local static 4540 // declarations). 4541 auto *Fn = cast<llvm::Function>(GV); 4542 setFunctionLinkage(GD, Fn); 4543 4544 // FIXME: this is redundant with part of setFunctionDefinitionAttributes 4545 setGVProperties(Fn, GD); 4546 4547 MaybeHandleStaticInExternC(D, Fn); 4548 4549 4550 maybeSetTrivialComdat(*D, *Fn); 4551 4552 CodeGenFunction(*this).GenerateCode(GD, Fn, FI); 4553 4554 setNonAliasAttributes(GD, Fn); 4555 SetLLVMFunctionAttributesForDefinition(D, Fn); 4556 4557 if (const ConstructorAttr *CA = D->getAttr<ConstructorAttr>()) 4558 AddGlobalCtor(Fn, CA->getPriority()); 4559 if (const DestructorAttr *DA = D->getAttr<DestructorAttr>()) 4560 AddGlobalDtor(Fn, DA->getPriority()); 4561 if (D->hasAttr<AnnotateAttr>()) 4562 AddGlobalAnnotations(D, Fn); 4563 } 4564 4565 void CodeGenModule::EmitAliasDefinition(GlobalDecl GD) { 4566 const auto *D = cast<ValueDecl>(GD.getDecl()); 4567 const AliasAttr *AA = D->getAttr<AliasAttr>(); 4568 assert(AA && "Not an alias?"); 4569 4570 StringRef MangledName = getMangledName(GD); 4571 4572 if (AA->getAliasee() == MangledName) { 4573 Diags.Report(AA->getLocation(), diag::err_cyclic_alias) << 0; 4574 return; 4575 } 4576 4577 // If there is a definition in the module, then it wins over the alias. 4578 // This is dubious, but allow it to be safe. Just ignore the alias. 4579 llvm::GlobalValue *Entry = GetGlobalValue(MangledName); 4580 if (Entry && !Entry->isDeclaration()) 4581 return; 4582 4583 Aliases.push_back(GD); 4584 4585 llvm::Type *DeclTy = getTypes().ConvertTypeForMem(D->getType()); 4586 4587 // Create a reference to the named value. This ensures that it is emitted 4588 // if a deferred decl. 4589 llvm::Constant *Aliasee; 4590 llvm::GlobalValue::LinkageTypes LT; 4591 if (isa<llvm::FunctionType>(DeclTy)) { 4592 Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy, GD, 4593 /*ForVTable=*/false); 4594 LT = getFunctionLinkage(GD); 4595 } else { 4596 Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(), 4597 llvm::PointerType::getUnqual(DeclTy), 4598 /*D=*/nullptr); 4599 LT = getLLVMLinkageVarDefinition(cast<VarDecl>(GD.getDecl()), 4600 D->getType().isConstQualified()); 4601 } 4602 4603 // Create the new alias itself, but don't set a name yet. 4604 unsigned AS = Aliasee->getType()->getPointerAddressSpace(); 4605 auto *GA = 4606 llvm::GlobalAlias::create(DeclTy, AS, LT, "", Aliasee, &getModule()); 4607 4608 if (Entry) { 4609 if (GA->getAliasee() == Entry) { 4610 Diags.Report(AA->getLocation(), diag::err_cyclic_alias) << 0; 4611 return; 4612 } 4613 4614 assert(Entry->isDeclaration()); 4615 4616 // If there is a declaration in the module, then we had an extern followed 4617 // by the alias, as in: 4618 // extern int test6(); 4619 // ... 4620 // int test6() __attribute__((alias("test7"))); 4621 // 4622 // Remove it and replace uses of it with the alias. 4623 GA->takeName(Entry); 4624 4625 Entry->replaceAllUsesWith(llvm::ConstantExpr::getBitCast(GA, 4626 Entry->getType())); 4627 Entry->eraseFromParent(); 4628 } else { 4629 GA->setName(MangledName); 4630 } 4631 4632 // Set attributes which are particular to an alias; this is a 4633 // specialization of the attributes which may be set on a global 4634 // variable/function. 4635 if (D->hasAttr<WeakAttr>() || D->hasAttr<WeakRefAttr>() || 4636 D->isWeakImported()) { 4637 GA->setLinkage(llvm::Function::WeakAnyLinkage); 4638 } 4639 4640 if (const auto *VD = dyn_cast<VarDecl>(D)) 4641 if (VD->getTLSKind()) 4642 setTLSMode(GA, *VD); 4643 4644 SetCommonAttributes(GD, GA); 4645 } 4646 4647 void CodeGenModule::emitIFuncDefinition(GlobalDecl GD) { 4648 const auto *D = cast<ValueDecl>(GD.getDecl()); 4649 const IFuncAttr *IFA = D->getAttr<IFuncAttr>(); 4650 assert(IFA && "Not an ifunc?"); 4651 4652 StringRef MangledName = getMangledName(GD); 4653 4654 if (IFA->getResolver() == MangledName) { 4655 Diags.Report(IFA->getLocation(), diag::err_cyclic_alias) << 1; 4656 return; 4657 } 4658 4659 // Report an error if some definition overrides ifunc. 4660 llvm::GlobalValue *Entry = GetGlobalValue(MangledName); 4661 if (Entry && !Entry->isDeclaration()) { 4662 GlobalDecl OtherGD; 4663 if (lookupRepresentativeDecl(MangledName, OtherGD) && 4664 DiagnosedConflictingDefinitions.insert(GD).second) { 4665 Diags.Report(D->getLocation(), diag::err_duplicate_mangled_name) 4666 << MangledName; 4667 Diags.Report(OtherGD.getDecl()->getLocation(), 4668 diag::note_previous_definition); 4669 } 4670 return; 4671 } 4672 4673 Aliases.push_back(GD); 4674 4675 llvm::Type *DeclTy = getTypes().ConvertTypeForMem(D->getType()); 4676 llvm::Constant *Resolver = 4677 GetOrCreateLLVMFunction(IFA->getResolver(), DeclTy, GD, 4678 /*ForVTable=*/false); 4679 llvm::GlobalIFunc *GIF = 4680 llvm::GlobalIFunc::create(DeclTy, 0, llvm::Function::ExternalLinkage, 4681 "", Resolver, &getModule()); 4682 if (Entry) { 4683 if (GIF->getResolver() == Entry) { 4684 Diags.Report(IFA->getLocation(), diag::err_cyclic_alias) << 1; 4685 return; 4686 } 4687 assert(Entry->isDeclaration()); 4688 4689 // If there is a declaration in the module, then we had an extern followed 4690 // by the ifunc, as in: 4691 // extern int test(); 4692 // ... 4693 // int test() __attribute__((ifunc("resolver"))); 4694 // 4695 // Remove it and replace uses of it with the ifunc. 4696 GIF->takeName(Entry); 4697 4698 Entry->replaceAllUsesWith(llvm::ConstantExpr::getBitCast(GIF, 4699 Entry->getType())); 4700 Entry->eraseFromParent(); 4701 } else 4702 GIF->setName(MangledName); 4703 4704 SetCommonAttributes(GD, GIF); 4705 } 4706 4707 llvm::Function *CodeGenModule::getIntrinsic(unsigned IID, 4708 ArrayRef<llvm::Type*> Tys) { 4709 return llvm::Intrinsic::getDeclaration(&getModule(), (llvm::Intrinsic::ID)IID, 4710 Tys); 4711 } 4712 4713 static llvm::StringMapEntry<llvm::GlobalVariable *> & 4714 GetConstantCFStringEntry(llvm::StringMap<llvm::GlobalVariable *> &Map, 4715 const StringLiteral *Literal, bool TargetIsLSB, 4716 bool &IsUTF16, unsigned &StringLength) { 4717 StringRef String = Literal->getString(); 4718 unsigned NumBytes = String.size(); 4719 4720 // Check for simple case. 4721 if (!Literal->containsNonAsciiOrNull()) { 4722 StringLength = NumBytes; 4723 return *Map.insert(std::make_pair(String, nullptr)).first; 4724 } 4725 4726 // Otherwise, convert the UTF8 literals into a string of shorts. 4727 IsUTF16 = true; 4728 4729 SmallVector<llvm::UTF16, 128> ToBuf(NumBytes + 1); // +1 for ending nulls. 4730 const llvm::UTF8 *FromPtr = (const llvm::UTF8 *)String.data(); 4731 llvm::UTF16 *ToPtr = &ToBuf[0]; 4732 4733 (void)llvm::ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, &ToPtr, 4734 ToPtr + NumBytes, llvm::strictConversion); 4735 4736 // ConvertUTF8toUTF16 returns the length in ToPtr. 4737 StringLength = ToPtr - &ToBuf[0]; 4738 4739 // Add an explicit null. 4740 *ToPtr = 0; 4741 return *Map.insert(std::make_pair( 4742 StringRef(reinterpret_cast<const char *>(ToBuf.data()), 4743 (StringLength + 1) * 2), 4744 nullptr)).first; 4745 } 4746 4747 ConstantAddress 4748 CodeGenModule::GetAddrOfConstantCFString(const StringLiteral *Literal) { 4749 unsigned StringLength = 0; 4750 bool isUTF16 = false; 4751 llvm::StringMapEntry<llvm::GlobalVariable *> &Entry = 4752 GetConstantCFStringEntry(CFConstantStringMap, Literal, 4753 getDataLayout().isLittleEndian(), isUTF16, 4754 StringLength); 4755 4756 if (auto *C = Entry.second) 4757 return ConstantAddress(C, CharUnits::fromQuantity(C->getAlignment())); 4758 4759 llvm::Constant *Zero = llvm::Constant::getNullValue(Int32Ty); 4760 llvm::Constant *Zeros[] = { Zero, Zero }; 4761 4762 const ASTContext &Context = getContext(); 4763 const llvm::Triple &Triple = getTriple(); 4764 4765 const auto CFRuntime = getLangOpts().CFRuntime; 4766 const bool IsSwiftABI = 4767 static_cast<unsigned>(CFRuntime) >= 4768 static_cast<unsigned>(LangOptions::CoreFoundationABI::Swift); 4769 const bool IsSwift4_1 = CFRuntime == LangOptions::CoreFoundationABI::Swift4_1; 4770 4771 // If we don't already have it, get __CFConstantStringClassReference. 4772 if (!CFConstantStringClassRef) { 4773 const char *CFConstantStringClassName = "__CFConstantStringClassReference"; 4774 llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy); 4775 Ty = llvm::ArrayType::get(Ty, 0); 4776 4777 switch (CFRuntime) { 4778 default: break; 4779 case LangOptions::CoreFoundationABI::Swift: LLVM_FALLTHROUGH; 4780 case LangOptions::CoreFoundationABI::Swift5_0: 4781 CFConstantStringClassName = 4782 Triple.isOSDarwin() ? "$s15SwiftFoundation19_NSCFConstantStringCN" 4783 : "$s10Foundation19_NSCFConstantStringCN"; 4784 Ty = IntPtrTy; 4785 break; 4786 case LangOptions::CoreFoundationABI::Swift4_2: 4787 CFConstantStringClassName = 4788 Triple.isOSDarwin() ? "$S15SwiftFoundation19_NSCFConstantStringCN" 4789 : "$S10Foundation19_NSCFConstantStringCN"; 4790 Ty = IntPtrTy; 4791 break; 4792 case LangOptions::CoreFoundationABI::Swift4_1: 4793 CFConstantStringClassName = 4794 Triple.isOSDarwin() ? "__T015SwiftFoundation19_NSCFConstantStringCN" 4795 : "__T010Foundation19_NSCFConstantStringCN"; 4796 Ty = IntPtrTy; 4797 break; 4798 } 4799 4800 llvm::Constant *C = CreateRuntimeVariable(Ty, CFConstantStringClassName); 4801 4802 if (Triple.isOSBinFormatELF() || Triple.isOSBinFormatCOFF()) { 4803 llvm::GlobalValue *GV = nullptr; 4804 4805 if ((GV = dyn_cast<llvm::GlobalValue>(C))) { 4806 IdentifierInfo &II = Context.Idents.get(GV->getName()); 4807 TranslationUnitDecl *TUDecl = Context.getTranslationUnitDecl(); 4808 DeclContext *DC = TranslationUnitDecl::castToDeclContext(TUDecl); 4809 4810 const VarDecl *VD = nullptr; 4811 for (const auto &Result : DC->lookup(&II)) 4812 if ((VD = dyn_cast<VarDecl>(Result))) 4813 break; 4814 4815 if (Triple.isOSBinFormatELF()) { 4816 if (!VD) 4817 GV->setLinkage(llvm::GlobalValue::ExternalLinkage); 4818 } else { 4819 GV->setLinkage(llvm::GlobalValue::ExternalLinkage); 4820 if (!VD || !VD->hasAttr<DLLExportAttr>()) 4821 GV->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass); 4822 else 4823 GV->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass); 4824 } 4825 4826 setDSOLocal(GV); 4827 } 4828 } 4829 4830 // Decay array -> ptr 4831 CFConstantStringClassRef = 4832 IsSwiftABI ? llvm::ConstantExpr::getPtrToInt(C, Ty) 4833 : llvm::ConstantExpr::getGetElementPtr(Ty, C, Zeros); 4834 } 4835 4836 QualType CFTy = Context.getCFConstantStringType(); 4837 4838 auto *STy = cast<llvm::StructType>(getTypes().ConvertType(CFTy)); 4839 4840 ConstantInitBuilder Builder(*this); 4841 auto Fields = Builder.beginStruct(STy); 4842 4843 // Class pointer. 4844 Fields.add(cast<llvm::ConstantExpr>(CFConstantStringClassRef)); 4845 4846 // Flags. 4847 if (IsSwiftABI) { 4848 Fields.addInt(IntPtrTy, IsSwift4_1 ? 0x05 : 0x01); 4849 Fields.addInt(Int64Ty, isUTF16 ? 0x07d0 : 0x07c8); 4850 } else { 4851 Fields.addInt(IntTy, isUTF16 ? 0x07d0 : 0x07C8); 4852 } 4853 4854 // String pointer. 4855 llvm::Constant *C = nullptr; 4856 if (isUTF16) { 4857 auto Arr = llvm::makeArrayRef( 4858 reinterpret_cast<uint16_t *>(const_cast<char *>(Entry.first().data())), 4859 Entry.first().size() / 2); 4860 C = llvm::ConstantDataArray::get(VMContext, Arr); 4861 } else { 4862 C = llvm::ConstantDataArray::getString(VMContext, Entry.first()); 4863 } 4864 4865 // Note: -fwritable-strings doesn't make the backing store strings of 4866 // CFStrings writable. (See <rdar://problem/10657500>) 4867 auto *GV = 4868 new llvm::GlobalVariable(getModule(), C->getType(), /*isConstant=*/true, 4869 llvm::GlobalValue::PrivateLinkage, C, ".str"); 4870 GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global); 4871 // Don't enforce the target's minimum global alignment, since the only use 4872 // of the string is via this class initializer. 4873 CharUnits Align = isUTF16 ? Context.getTypeAlignInChars(Context.ShortTy) 4874 : Context.getTypeAlignInChars(Context.CharTy); 4875 GV->setAlignment(Align.getAsAlign()); 4876 4877 // FIXME: We set the section explicitly to avoid a bug in ld64 224.1. 4878 // Without it LLVM can merge the string with a non unnamed_addr one during 4879 // LTO. Doing that changes the section it ends in, which surprises ld64. 4880 if (Triple.isOSBinFormatMachO()) 4881 GV->setSection(isUTF16 ? "__TEXT,__ustring" 4882 : "__TEXT,__cstring,cstring_literals"); 4883 // Make sure the literal ends up in .rodata to allow for safe ICF and for 4884 // the static linker to adjust permissions to read-only later on. 4885 else if (Triple.isOSBinFormatELF()) 4886 GV->setSection(".rodata"); 4887 4888 // String. 4889 llvm::Constant *Str = 4890 llvm::ConstantExpr::getGetElementPtr(GV->getValueType(), GV, Zeros); 4891 4892 if (isUTF16) 4893 // Cast the UTF16 string to the correct type. 4894 Str = llvm::ConstantExpr::getBitCast(Str, Int8PtrTy); 4895 Fields.add(Str); 4896 4897 // String length. 4898 llvm::IntegerType *LengthTy = 4899 llvm::IntegerType::get(getModule().getContext(), 4900 Context.getTargetInfo().getLongWidth()); 4901 if (IsSwiftABI) { 4902 if (CFRuntime == LangOptions::CoreFoundationABI::Swift4_1 || 4903 CFRuntime == LangOptions::CoreFoundationABI::Swift4_2) 4904 LengthTy = Int32Ty; 4905 else 4906 LengthTy = IntPtrTy; 4907 } 4908 Fields.addInt(LengthTy, StringLength); 4909 4910 // Swift ABI requires 8-byte alignment to ensure that the _Atomic(uint64_t) is 4911 // properly aligned on 32-bit platforms. 4912 CharUnits Alignment = 4913 IsSwiftABI ? Context.toCharUnitsFromBits(64) : getPointerAlign(); 4914 4915 // The struct. 4916 GV = Fields.finishAndCreateGlobal("_unnamed_cfstring_", Alignment, 4917 /*isConstant=*/false, 4918 llvm::GlobalVariable::PrivateLinkage); 4919 GV->addAttribute("objc_arc_inert"); 4920 switch (Triple.getObjectFormat()) { 4921 case llvm::Triple::UnknownObjectFormat: 4922 llvm_unreachable("unknown file format"); 4923 case llvm::Triple::GOFF: 4924 llvm_unreachable("GOFF is not yet implemented"); 4925 case llvm::Triple::XCOFF: 4926 llvm_unreachable("XCOFF is not yet implemented"); 4927 case llvm::Triple::COFF: 4928 case llvm::Triple::ELF: 4929 case llvm::Triple::Wasm: 4930 GV->setSection("cfstring"); 4931 break; 4932 case llvm::Triple::MachO: 4933 GV->setSection("__DATA,__cfstring"); 4934 break; 4935 } 4936 Entry.second = GV; 4937 4938 return ConstantAddress(GV, Alignment); 4939 } 4940 4941 bool CodeGenModule::getExpressionLocationsEnabled() const { 4942 return !CodeGenOpts.EmitCodeView || CodeGenOpts.DebugColumnInfo; 4943 } 4944 4945 QualType CodeGenModule::getObjCFastEnumerationStateType() { 4946 if (ObjCFastEnumerationStateType.isNull()) { 4947 RecordDecl *D = Context.buildImplicitRecord("__objcFastEnumerationState"); 4948 D->startDefinition(); 4949 4950 QualType FieldTypes[] = { 4951 Context.UnsignedLongTy, 4952 Context.getPointerType(Context.getObjCIdType()), 4953 Context.getPointerType(Context.UnsignedLongTy), 4954 Context.getConstantArrayType(Context.UnsignedLongTy, 4955 llvm::APInt(32, 5), nullptr, ArrayType::Normal, 0) 4956 }; 4957 4958 for (size_t i = 0; i < 4; ++i) { 4959 FieldDecl *Field = FieldDecl::Create(Context, 4960 D, 4961 SourceLocation(), 4962 SourceLocation(), nullptr, 4963 FieldTypes[i], /*TInfo=*/nullptr, 4964 /*BitWidth=*/nullptr, 4965 /*Mutable=*/false, 4966 ICIS_NoInit); 4967 Field->setAccess(AS_public); 4968 D->addDecl(Field); 4969 } 4970 4971 D->completeDefinition(); 4972 ObjCFastEnumerationStateType = Context.getTagDeclType(D); 4973 } 4974 4975 return ObjCFastEnumerationStateType; 4976 } 4977 4978 llvm::Constant * 4979 CodeGenModule::GetConstantArrayFromStringLiteral(const StringLiteral *E) { 4980 assert(!E->getType()->isPointerType() && "Strings are always arrays"); 4981 4982 // Don't emit it as the address of the string, emit the string data itself 4983 // as an inline array. 4984 if (E->getCharByteWidth() == 1) { 4985 SmallString<64> Str(E->getString()); 4986 4987 // Resize the string to the right size, which is indicated by its type. 4988 const ConstantArrayType *CAT = Context.getAsConstantArrayType(E->getType()); 4989 Str.resize(CAT->getSize().getZExtValue()); 4990 return llvm::ConstantDataArray::getString(VMContext, Str, false); 4991 } 4992 4993 auto *AType = cast<llvm::ArrayType>(getTypes().ConvertType(E->getType())); 4994 llvm::Type *ElemTy = AType->getElementType(); 4995 unsigned NumElements = AType->getNumElements(); 4996 4997 // Wide strings have either 2-byte or 4-byte elements. 4998 if (ElemTy->getPrimitiveSizeInBits() == 16) { 4999 SmallVector<uint16_t, 32> Elements; 5000 Elements.reserve(NumElements); 5001 5002 for(unsigned i = 0, e = E->getLength(); i != e; ++i) 5003 Elements.push_back(E->getCodeUnit(i)); 5004 Elements.resize(NumElements); 5005 return llvm::ConstantDataArray::get(VMContext, Elements); 5006 } 5007 5008 assert(ElemTy->getPrimitiveSizeInBits() == 32); 5009 SmallVector<uint32_t, 32> Elements; 5010 Elements.reserve(NumElements); 5011 5012 for(unsigned i = 0, e = E->getLength(); i != e; ++i) 5013 Elements.push_back(E->getCodeUnit(i)); 5014 Elements.resize(NumElements); 5015 return llvm::ConstantDataArray::get(VMContext, Elements); 5016 } 5017 5018 static llvm::GlobalVariable * 5019 GenerateStringLiteral(llvm::Constant *C, llvm::GlobalValue::LinkageTypes LT, 5020 CodeGenModule &CGM, StringRef GlobalName, 5021 CharUnits Alignment) { 5022 unsigned AddrSpace = CGM.getContext().getTargetAddressSpace( 5023 CGM.getStringLiteralAddressSpace()); 5024 5025 llvm::Module &M = CGM.getModule(); 5026 // Create a global variable for this string 5027 auto *GV = new llvm::GlobalVariable( 5028 M, C->getType(), !CGM.getLangOpts().WritableStrings, LT, C, GlobalName, 5029 nullptr, llvm::GlobalVariable::NotThreadLocal, AddrSpace); 5030 GV->setAlignment(Alignment.getAsAlign()); 5031 GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global); 5032 if (GV->isWeakForLinker()) { 5033 assert(CGM.supportsCOMDAT() && "Only COFF uses weak string literals"); 5034 GV->setComdat(M.getOrInsertComdat(GV->getName())); 5035 } 5036 CGM.setDSOLocal(GV); 5037 5038 return GV; 5039 } 5040 5041 /// GetAddrOfConstantStringFromLiteral - Return a pointer to a 5042 /// constant array for the given string literal. 5043 ConstantAddress 5044 CodeGenModule::GetAddrOfConstantStringFromLiteral(const StringLiteral *S, 5045 StringRef Name) { 5046 CharUnits Alignment = getContext().getAlignOfGlobalVarInChars(S->getType()); 5047 5048 llvm::Constant *C = GetConstantArrayFromStringLiteral(S); 5049 llvm::GlobalVariable **Entry = nullptr; 5050 if (!LangOpts.WritableStrings) { 5051 Entry = &ConstantStringMap[C]; 5052 if (auto GV = *Entry) { 5053 if (Alignment.getQuantity() > GV->getAlignment()) 5054 GV->setAlignment(Alignment.getAsAlign()); 5055 return ConstantAddress(castStringLiteralToDefaultAddressSpace(*this, GV), 5056 Alignment); 5057 } 5058 } 5059 5060 SmallString<256> MangledNameBuffer; 5061 StringRef GlobalVariableName; 5062 llvm::GlobalValue::LinkageTypes LT; 5063 5064 // Mangle the string literal if that's how the ABI merges duplicate strings. 5065 // Don't do it if they are writable, since we don't want writes in one TU to 5066 // affect strings in another. 5067 if (getCXXABI().getMangleContext().shouldMangleStringLiteral(S) && 5068 !LangOpts.WritableStrings) { 5069 llvm::raw_svector_ostream Out(MangledNameBuffer); 5070 getCXXABI().getMangleContext().mangleStringLiteral(S, Out); 5071 LT = llvm::GlobalValue::LinkOnceODRLinkage; 5072 GlobalVariableName = MangledNameBuffer; 5073 } else { 5074 LT = llvm::GlobalValue::PrivateLinkage; 5075 GlobalVariableName = Name; 5076 } 5077 5078 auto GV = GenerateStringLiteral(C, LT, *this, GlobalVariableName, Alignment); 5079 if (Entry) 5080 *Entry = GV; 5081 5082 SanitizerMD->reportGlobalToASan(GV, S->getStrTokenLoc(0), "<string literal>", 5083 QualType()); 5084 5085 return ConstantAddress(castStringLiteralToDefaultAddressSpace(*this, GV), 5086 Alignment); 5087 } 5088 5089 /// GetAddrOfConstantStringFromObjCEncode - Return a pointer to a constant 5090 /// array for the given ObjCEncodeExpr node. 5091 ConstantAddress 5092 CodeGenModule::GetAddrOfConstantStringFromObjCEncode(const ObjCEncodeExpr *E) { 5093 std::string Str; 5094 getContext().getObjCEncodingForType(E->getEncodedType(), Str); 5095 5096 return GetAddrOfConstantCString(Str); 5097 } 5098 5099 /// GetAddrOfConstantCString - Returns a pointer to a character array containing 5100 /// the literal and a terminating '\0' character. 5101 /// The result has pointer to array type. 5102 ConstantAddress CodeGenModule::GetAddrOfConstantCString( 5103 const std::string &Str, const char *GlobalName) { 5104 StringRef StrWithNull(Str.c_str(), Str.size() + 1); 5105 CharUnits Alignment = 5106 getContext().getAlignOfGlobalVarInChars(getContext().CharTy); 5107 5108 llvm::Constant *C = 5109 llvm::ConstantDataArray::getString(getLLVMContext(), StrWithNull, false); 5110 5111 // Don't share any string literals if strings aren't constant. 5112 llvm::GlobalVariable **Entry = nullptr; 5113 if (!LangOpts.WritableStrings) { 5114 Entry = &ConstantStringMap[C]; 5115 if (auto GV = *Entry) { 5116 if (Alignment.getQuantity() > GV->getAlignment()) 5117 GV->setAlignment(Alignment.getAsAlign()); 5118 return ConstantAddress(castStringLiteralToDefaultAddressSpace(*this, GV), 5119 Alignment); 5120 } 5121 } 5122 5123 // Get the default prefix if a name wasn't specified. 5124 if (!GlobalName) 5125 GlobalName = ".str"; 5126 // Create a global variable for this. 5127 auto GV = GenerateStringLiteral(C, llvm::GlobalValue::PrivateLinkage, *this, 5128 GlobalName, Alignment); 5129 if (Entry) 5130 *Entry = GV; 5131 5132 return ConstantAddress(castStringLiteralToDefaultAddressSpace(*this, GV), 5133 Alignment); 5134 } 5135 5136 ConstantAddress CodeGenModule::GetAddrOfGlobalTemporary( 5137 const MaterializeTemporaryExpr *E, const Expr *Init) { 5138 assert((E->getStorageDuration() == SD_Static || 5139 E->getStorageDuration() == SD_Thread) && "not a global temporary"); 5140 const auto *VD = cast<VarDecl>(E->getExtendingDecl()); 5141 5142 // If we're not materializing a subobject of the temporary, keep the 5143 // cv-qualifiers from the type of the MaterializeTemporaryExpr. 5144 QualType MaterializedType = Init->getType(); 5145 if (Init == E->getSubExpr()) 5146 MaterializedType = E->getType(); 5147 5148 CharUnits Align = getContext().getTypeAlignInChars(MaterializedType); 5149 5150 if (llvm::Constant *Slot = MaterializedGlobalTemporaryMap[E]) 5151 return ConstantAddress(Slot, Align); 5152 5153 // FIXME: If an externally-visible declaration extends multiple temporaries, 5154 // we need to give each temporary the same name in every translation unit (and 5155 // we also need to make the temporaries externally-visible). 5156 SmallString<256> Name; 5157 llvm::raw_svector_ostream Out(Name); 5158 getCXXABI().getMangleContext().mangleReferenceTemporary( 5159 VD, E->getManglingNumber(), Out); 5160 5161 APValue *Value = nullptr; 5162 if (E->getStorageDuration() == SD_Static && VD && VD->evaluateValue()) { 5163 // If the initializer of the extending declaration is a constant 5164 // initializer, we should have a cached constant initializer for this 5165 // temporary. Note that this might have a different value from the value 5166 // computed by evaluating the initializer if the surrounding constant 5167 // expression modifies the temporary. 5168 Value = E->getOrCreateValue(false); 5169 } 5170 5171 // Try evaluating it now, it might have a constant initializer. 5172 Expr::EvalResult EvalResult; 5173 if (!Value && Init->EvaluateAsRValue(EvalResult, getContext()) && 5174 !EvalResult.hasSideEffects()) 5175 Value = &EvalResult.Val; 5176 5177 LangAS AddrSpace = 5178 VD ? GetGlobalVarAddressSpace(VD) : MaterializedType.getAddressSpace(); 5179 5180 Optional<ConstantEmitter> emitter; 5181 llvm::Constant *InitialValue = nullptr; 5182 bool Constant = false; 5183 llvm::Type *Type; 5184 if (Value) { 5185 // The temporary has a constant initializer, use it. 5186 emitter.emplace(*this); 5187 InitialValue = emitter->emitForInitializer(*Value, AddrSpace, 5188 MaterializedType); 5189 Constant = isTypeConstant(MaterializedType, /*ExcludeCtor*/Value); 5190 Type = InitialValue->getType(); 5191 } else { 5192 // No initializer, the initialization will be provided when we 5193 // initialize the declaration which performed lifetime extension. 5194 Type = getTypes().ConvertTypeForMem(MaterializedType); 5195 } 5196 5197 // Create a global variable for this lifetime-extended temporary. 5198 llvm::GlobalValue::LinkageTypes Linkage = 5199 getLLVMLinkageVarDefinition(VD, Constant); 5200 if (Linkage == llvm::GlobalVariable::ExternalLinkage) { 5201 const VarDecl *InitVD; 5202 if (VD->isStaticDataMember() && VD->getAnyInitializer(InitVD) && 5203 isa<CXXRecordDecl>(InitVD->getLexicalDeclContext())) { 5204 // Temporaries defined inside a class get linkonce_odr linkage because the 5205 // class can be defined in multiple translation units. 5206 Linkage = llvm::GlobalVariable::LinkOnceODRLinkage; 5207 } else { 5208 // There is no need for this temporary to have external linkage if the 5209 // VarDecl has external linkage. 5210 Linkage = llvm::GlobalVariable::InternalLinkage; 5211 } 5212 } 5213 auto TargetAS = getContext().getTargetAddressSpace(AddrSpace); 5214 auto *GV = new llvm::GlobalVariable( 5215 getModule(), Type, Constant, Linkage, InitialValue, Name.c_str(), 5216 /*InsertBefore=*/nullptr, llvm::GlobalVariable::NotThreadLocal, TargetAS); 5217 if (emitter) emitter->finalize(GV); 5218 setGVProperties(GV, VD); 5219 GV->setAlignment(Align.getAsAlign()); 5220 if (supportsCOMDAT() && GV->isWeakForLinker()) 5221 GV->setComdat(TheModule.getOrInsertComdat(GV->getName())); 5222 if (VD->getTLSKind()) 5223 setTLSMode(GV, *VD); 5224 llvm::Constant *CV = GV; 5225 if (AddrSpace != LangAS::Default) 5226 CV = getTargetCodeGenInfo().performAddrSpaceCast( 5227 *this, GV, AddrSpace, LangAS::Default, 5228 Type->getPointerTo( 5229 getContext().getTargetAddressSpace(LangAS::Default))); 5230 MaterializedGlobalTemporaryMap[E] = CV; 5231 return ConstantAddress(CV, Align); 5232 } 5233 5234 /// EmitObjCPropertyImplementations - Emit information for synthesized 5235 /// properties for an implementation. 5236 void CodeGenModule::EmitObjCPropertyImplementations(const 5237 ObjCImplementationDecl *D) { 5238 for (const auto *PID : D->property_impls()) { 5239 // Dynamic is just for type-checking. 5240 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize) { 5241 ObjCPropertyDecl *PD = PID->getPropertyDecl(); 5242 5243 // Determine which methods need to be implemented, some may have 5244 // been overridden. Note that ::isPropertyAccessor is not the method 5245 // we want, that just indicates if the decl came from a 5246 // property. What we want to know is if the method is defined in 5247 // this implementation. 5248 auto *Getter = PID->getGetterMethodDecl(); 5249 if (!Getter || Getter->isSynthesizedAccessorStub()) 5250 CodeGenFunction(*this).GenerateObjCGetter( 5251 const_cast<ObjCImplementationDecl *>(D), PID); 5252 auto *Setter = PID->getSetterMethodDecl(); 5253 if (!PD->isReadOnly() && (!Setter || Setter->isSynthesizedAccessorStub())) 5254 CodeGenFunction(*this).GenerateObjCSetter( 5255 const_cast<ObjCImplementationDecl *>(D), PID); 5256 } 5257 } 5258 } 5259 5260 static bool needsDestructMethod(ObjCImplementationDecl *impl) { 5261 const ObjCInterfaceDecl *iface = impl->getClassInterface(); 5262 for (const ObjCIvarDecl *ivar = iface->all_declared_ivar_begin(); 5263 ivar; ivar = ivar->getNextIvar()) 5264 if (ivar->getType().isDestructedType()) 5265 return true; 5266 5267 return false; 5268 } 5269 5270 static bool AllTrivialInitializers(CodeGenModule &CGM, 5271 ObjCImplementationDecl *D) { 5272 CodeGenFunction CGF(CGM); 5273 for (ObjCImplementationDecl::init_iterator B = D->init_begin(), 5274 E = D->init_end(); B != E; ++B) { 5275 CXXCtorInitializer *CtorInitExp = *B; 5276 Expr *Init = CtorInitExp->getInit(); 5277 if (!CGF.isTrivialInitializer(Init)) 5278 return false; 5279 } 5280 return true; 5281 } 5282 5283 /// EmitObjCIvarInitializations - Emit information for ivar initialization 5284 /// for an implementation. 5285 void CodeGenModule::EmitObjCIvarInitializations(ObjCImplementationDecl *D) { 5286 // We might need a .cxx_destruct even if we don't have any ivar initializers. 5287 if (needsDestructMethod(D)) { 5288 IdentifierInfo *II = &getContext().Idents.get(".cxx_destruct"); 5289 Selector cxxSelector = getContext().Selectors.getSelector(0, &II); 5290 ObjCMethodDecl *DTORMethod = ObjCMethodDecl::Create( 5291 getContext(), D->getLocation(), D->getLocation(), cxxSelector, 5292 getContext().VoidTy, nullptr, D, 5293 /*isInstance=*/true, /*isVariadic=*/false, 5294 /*isPropertyAccessor=*/true, /*isSynthesizedAccessorStub=*/false, 5295 /*isImplicitlyDeclared=*/true, 5296 /*isDefined=*/false, ObjCMethodDecl::Required); 5297 D->addInstanceMethod(DTORMethod); 5298 CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, DTORMethod, false); 5299 D->setHasDestructors(true); 5300 } 5301 5302 // If the implementation doesn't have any ivar initializers, we don't need 5303 // a .cxx_construct. 5304 if (D->getNumIvarInitializers() == 0 || 5305 AllTrivialInitializers(*this, D)) 5306 return; 5307 5308 IdentifierInfo *II = &getContext().Idents.get(".cxx_construct"); 5309 Selector cxxSelector = getContext().Selectors.getSelector(0, &II); 5310 // The constructor returns 'self'. 5311 ObjCMethodDecl *CTORMethod = ObjCMethodDecl::Create( 5312 getContext(), D->getLocation(), D->getLocation(), cxxSelector, 5313 getContext().getObjCIdType(), nullptr, D, /*isInstance=*/true, 5314 /*isVariadic=*/false, 5315 /*isPropertyAccessor=*/true, /*isSynthesizedAccessorStub=*/false, 5316 /*isImplicitlyDeclared=*/true, 5317 /*isDefined=*/false, ObjCMethodDecl::Required); 5318 D->addInstanceMethod(CTORMethod); 5319 CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, CTORMethod, true); 5320 D->setHasNonZeroConstructors(true); 5321 } 5322 5323 // EmitLinkageSpec - Emit all declarations in a linkage spec. 5324 void CodeGenModule::EmitLinkageSpec(const LinkageSpecDecl *LSD) { 5325 if (LSD->getLanguage() != LinkageSpecDecl::lang_c && 5326 LSD->getLanguage() != LinkageSpecDecl::lang_cxx) { 5327 ErrorUnsupported(LSD, "linkage spec"); 5328 return; 5329 } 5330 5331 EmitDeclContext(LSD); 5332 } 5333 5334 void CodeGenModule::EmitDeclContext(const DeclContext *DC) { 5335 for (auto *I : DC->decls()) { 5336 // Unlike other DeclContexts, the contents of an ObjCImplDecl at TU scope 5337 // are themselves considered "top-level", so EmitTopLevelDecl on an 5338 // ObjCImplDecl does not recursively visit them. We need to do that in 5339 // case they're nested inside another construct (LinkageSpecDecl / 5340 // ExportDecl) that does stop them from being considered "top-level". 5341 if (auto *OID = dyn_cast<ObjCImplDecl>(I)) { 5342 for (auto *M : OID->methods()) 5343 EmitTopLevelDecl(M); 5344 } 5345 5346 EmitTopLevelDecl(I); 5347 } 5348 } 5349 5350 /// EmitTopLevelDecl - Emit code for a single top level declaration. 5351 void CodeGenModule::EmitTopLevelDecl(Decl *D) { 5352 // Ignore dependent declarations. 5353 if (D->isTemplated()) 5354 return; 5355 5356 // Consteval function shouldn't be emitted. 5357 if (auto *FD = dyn_cast<FunctionDecl>(D)) 5358 if (FD->isConsteval()) 5359 return; 5360 5361 switch (D->getKind()) { 5362 case Decl::CXXConversion: 5363 case Decl::CXXMethod: 5364 case Decl::Function: 5365 EmitGlobal(cast<FunctionDecl>(D)); 5366 // Always provide some coverage mapping 5367 // even for the functions that aren't emitted. 5368 AddDeferredUnusedCoverageMapping(D); 5369 break; 5370 5371 case Decl::CXXDeductionGuide: 5372 // Function-like, but does not result in code emission. 5373 break; 5374 5375 case Decl::Var: 5376 case Decl::Decomposition: 5377 case Decl::VarTemplateSpecialization: 5378 EmitGlobal(cast<VarDecl>(D)); 5379 if (auto *DD = dyn_cast<DecompositionDecl>(D)) 5380 for (auto *B : DD->bindings()) 5381 if (auto *HD = B->getHoldingVar()) 5382 EmitGlobal(HD); 5383 break; 5384 5385 // Indirect fields from global anonymous structs and unions can be 5386 // ignored; only the actual variable requires IR gen support. 5387 case Decl::IndirectField: 5388 break; 5389 5390 // C++ Decls 5391 case Decl::Namespace: 5392 EmitDeclContext(cast<NamespaceDecl>(D)); 5393 break; 5394 case Decl::ClassTemplateSpecialization: { 5395 const auto *Spec = cast<ClassTemplateSpecializationDecl>(D); 5396 if (CGDebugInfo *DI = getModuleDebugInfo()) 5397 if (Spec->getSpecializationKind() == 5398 TSK_ExplicitInstantiationDefinition && 5399 Spec->hasDefinition()) 5400 DI->completeTemplateDefinition(*Spec); 5401 } LLVM_FALLTHROUGH; 5402 case Decl::CXXRecord: { 5403 CXXRecordDecl *CRD = cast<CXXRecordDecl>(D); 5404 if (CGDebugInfo *DI = getModuleDebugInfo()) { 5405 if (CRD->hasDefinition()) 5406 DI->EmitAndRetainType(getContext().getRecordType(cast<RecordDecl>(D))); 5407 if (auto *ES = D->getASTContext().getExternalSource()) 5408 if (ES->hasExternalDefinitions(D) == ExternalASTSource::EK_Never) 5409 DI->completeUnusedClass(*CRD); 5410 } 5411 // Emit any static data members, they may be definitions. 5412 for (auto *I : CRD->decls()) 5413 if (isa<VarDecl>(I) || isa<CXXRecordDecl>(I)) 5414 EmitTopLevelDecl(I); 5415 break; 5416 } 5417 // No code generation needed. 5418 case Decl::UsingShadow: 5419 case Decl::ClassTemplate: 5420 case Decl::VarTemplate: 5421 case Decl::Concept: 5422 case Decl::VarTemplatePartialSpecialization: 5423 case Decl::FunctionTemplate: 5424 case Decl::TypeAliasTemplate: 5425 case Decl::Block: 5426 case Decl::Empty: 5427 case Decl::Binding: 5428 break; 5429 case Decl::Using: // using X; [C++] 5430 if (CGDebugInfo *DI = getModuleDebugInfo()) 5431 DI->EmitUsingDecl(cast<UsingDecl>(*D)); 5432 break; 5433 case Decl::NamespaceAlias: 5434 if (CGDebugInfo *DI = getModuleDebugInfo()) 5435 DI->EmitNamespaceAlias(cast<NamespaceAliasDecl>(*D)); 5436 break; 5437 case Decl::UsingDirective: // using namespace X; [C++] 5438 if (CGDebugInfo *DI = getModuleDebugInfo()) 5439 DI->EmitUsingDirective(cast<UsingDirectiveDecl>(*D)); 5440 break; 5441 case Decl::CXXConstructor: 5442 getCXXABI().EmitCXXConstructors(cast<CXXConstructorDecl>(D)); 5443 break; 5444 case Decl::CXXDestructor: 5445 getCXXABI().EmitCXXDestructors(cast<CXXDestructorDecl>(D)); 5446 break; 5447 5448 case Decl::StaticAssert: 5449 // Nothing to do. 5450 break; 5451 5452 // Objective-C Decls 5453 5454 // Forward declarations, no (immediate) code generation. 5455 case Decl::ObjCInterface: 5456 case Decl::ObjCCategory: 5457 break; 5458 5459 case Decl::ObjCProtocol: { 5460 auto *Proto = cast<ObjCProtocolDecl>(D); 5461 if (Proto->isThisDeclarationADefinition()) 5462 ObjCRuntime->GenerateProtocol(Proto); 5463 break; 5464 } 5465 5466 case Decl::ObjCCategoryImpl: 5467 // Categories have properties but don't support synthesize so we 5468 // can ignore them here. 5469 ObjCRuntime->GenerateCategory(cast<ObjCCategoryImplDecl>(D)); 5470 break; 5471 5472 case Decl::ObjCImplementation: { 5473 auto *OMD = cast<ObjCImplementationDecl>(D); 5474 EmitObjCPropertyImplementations(OMD); 5475 EmitObjCIvarInitializations(OMD); 5476 ObjCRuntime->GenerateClass(OMD); 5477 // Emit global variable debug information. 5478 if (CGDebugInfo *DI = getModuleDebugInfo()) 5479 if (getCodeGenOpts().hasReducedDebugInfo()) 5480 DI->getOrCreateInterfaceType(getContext().getObjCInterfaceType( 5481 OMD->getClassInterface()), OMD->getLocation()); 5482 break; 5483 } 5484 case Decl::ObjCMethod: { 5485 auto *OMD = cast<ObjCMethodDecl>(D); 5486 // If this is not a prototype, emit the body. 5487 if (OMD->getBody()) 5488 CodeGenFunction(*this).GenerateObjCMethod(OMD); 5489 break; 5490 } 5491 case Decl::ObjCCompatibleAlias: 5492 ObjCRuntime->RegisterAlias(cast<ObjCCompatibleAliasDecl>(D)); 5493 break; 5494 5495 case Decl::PragmaComment: { 5496 const auto *PCD = cast<PragmaCommentDecl>(D); 5497 switch (PCD->getCommentKind()) { 5498 case PCK_Unknown: 5499 llvm_unreachable("unexpected pragma comment kind"); 5500 case PCK_Linker: 5501 AppendLinkerOptions(PCD->getArg()); 5502 break; 5503 case PCK_Lib: 5504 AddDependentLib(PCD->getArg()); 5505 break; 5506 case PCK_Compiler: 5507 case PCK_ExeStr: 5508 case PCK_User: 5509 break; // We ignore all of these. 5510 } 5511 break; 5512 } 5513 5514 case Decl::PragmaDetectMismatch: { 5515 const auto *PDMD = cast<PragmaDetectMismatchDecl>(D); 5516 AddDetectMismatch(PDMD->getName(), PDMD->getValue()); 5517 break; 5518 } 5519 5520 case Decl::LinkageSpec: 5521 EmitLinkageSpec(cast<LinkageSpecDecl>(D)); 5522 break; 5523 5524 case Decl::FileScopeAsm: { 5525 // File-scope asm is ignored during device-side CUDA compilation. 5526 if (LangOpts.CUDA && LangOpts.CUDAIsDevice) 5527 break; 5528 // File-scope asm is ignored during device-side OpenMP compilation. 5529 if (LangOpts.OpenMPIsDevice) 5530 break; 5531 auto *AD = cast<FileScopeAsmDecl>(D); 5532 getModule().appendModuleInlineAsm(AD->getAsmString()->getString()); 5533 break; 5534 } 5535 5536 case Decl::Import: { 5537 auto *Import = cast<ImportDecl>(D); 5538 5539 // If we've already imported this module, we're done. 5540 if (!ImportedModules.insert(Import->getImportedModule())) 5541 break; 5542 5543 // Emit debug information for direct imports. 5544 if (!Import->getImportedOwningModule()) { 5545 if (CGDebugInfo *DI = getModuleDebugInfo()) 5546 DI->EmitImportDecl(*Import); 5547 } 5548 5549 // Find all of the submodules and emit the module initializers. 5550 llvm::SmallPtrSet<clang::Module *, 16> Visited; 5551 SmallVector<clang::Module *, 16> Stack; 5552 Visited.insert(Import->getImportedModule()); 5553 Stack.push_back(Import->getImportedModule()); 5554 5555 while (!Stack.empty()) { 5556 clang::Module *Mod = Stack.pop_back_val(); 5557 if (!EmittedModuleInitializers.insert(Mod).second) 5558 continue; 5559 5560 for (auto *D : Context.getModuleInitializers(Mod)) 5561 EmitTopLevelDecl(D); 5562 5563 // Visit the submodules of this module. 5564 for (clang::Module::submodule_iterator Sub = Mod->submodule_begin(), 5565 SubEnd = Mod->submodule_end(); 5566 Sub != SubEnd; ++Sub) { 5567 // Skip explicit children; they need to be explicitly imported to emit 5568 // the initializers. 5569 if ((*Sub)->IsExplicit) 5570 continue; 5571 5572 if (Visited.insert(*Sub).second) 5573 Stack.push_back(*Sub); 5574 } 5575 } 5576 break; 5577 } 5578 5579 case Decl::Export: 5580 EmitDeclContext(cast<ExportDecl>(D)); 5581 break; 5582 5583 case Decl::OMPThreadPrivate: 5584 EmitOMPThreadPrivateDecl(cast<OMPThreadPrivateDecl>(D)); 5585 break; 5586 5587 case Decl::OMPAllocate: 5588 break; 5589 5590 case Decl::OMPDeclareReduction: 5591 EmitOMPDeclareReduction(cast<OMPDeclareReductionDecl>(D)); 5592 break; 5593 5594 case Decl::OMPDeclareMapper: 5595 EmitOMPDeclareMapper(cast<OMPDeclareMapperDecl>(D)); 5596 break; 5597 5598 case Decl::OMPRequires: 5599 EmitOMPRequiresDecl(cast<OMPRequiresDecl>(D)); 5600 break; 5601 5602 case Decl::Typedef: 5603 case Decl::TypeAlias: // using foo = bar; [C++11] 5604 if (CGDebugInfo *DI = getModuleDebugInfo()) 5605 DI->EmitAndRetainType( 5606 getContext().getTypedefType(cast<TypedefNameDecl>(D))); 5607 break; 5608 5609 case Decl::Record: 5610 if (CGDebugInfo *DI = getModuleDebugInfo()) 5611 if (cast<RecordDecl>(D)->getDefinition()) 5612 DI->EmitAndRetainType(getContext().getRecordType(cast<RecordDecl>(D))); 5613 break; 5614 5615 case Decl::Enum: 5616 if (CGDebugInfo *DI = getModuleDebugInfo()) 5617 if (cast<EnumDecl>(D)->getDefinition()) 5618 DI->EmitAndRetainType(getContext().getEnumType(cast<EnumDecl>(D))); 5619 break; 5620 5621 default: 5622 // Make sure we handled everything we should, every other kind is a 5623 // non-top-level decl. FIXME: Would be nice to have an isTopLevelDeclKind 5624 // function. Need to recode Decl::Kind to do that easily. 5625 assert(isa<TypeDecl>(D) && "Unsupported decl kind"); 5626 break; 5627 } 5628 } 5629 5630 void CodeGenModule::AddDeferredUnusedCoverageMapping(Decl *D) { 5631 // Do we need to generate coverage mapping? 5632 if (!CodeGenOpts.CoverageMapping) 5633 return; 5634 switch (D->getKind()) { 5635 case Decl::CXXConversion: 5636 case Decl::CXXMethod: 5637 case Decl::Function: 5638 case Decl::ObjCMethod: 5639 case Decl::CXXConstructor: 5640 case Decl::CXXDestructor: { 5641 if (!cast<FunctionDecl>(D)->doesThisDeclarationHaveABody()) 5642 break; 5643 SourceManager &SM = getContext().getSourceManager(); 5644 if (LimitedCoverage && SM.getMainFileID() != SM.getFileID(D->getBeginLoc())) 5645 break; 5646 auto I = DeferredEmptyCoverageMappingDecls.find(D); 5647 if (I == DeferredEmptyCoverageMappingDecls.end()) 5648 DeferredEmptyCoverageMappingDecls[D] = true; 5649 break; 5650 } 5651 default: 5652 break; 5653 }; 5654 } 5655 5656 void CodeGenModule::ClearUnusedCoverageMapping(const Decl *D) { 5657 // Do we need to generate coverage mapping? 5658 if (!CodeGenOpts.CoverageMapping) 5659 return; 5660 if (const auto *Fn = dyn_cast<FunctionDecl>(D)) { 5661 if (Fn->isTemplateInstantiation()) 5662 ClearUnusedCoverageMapping(Fn->getTemplateInstantiationPattern()); 5663 } 5664 auto I = DeferredEmptyCoverageMappingDecls.find(D); 5665 if (I == DeferredEmptyCoverageMappingDecls.end()) 5666 DeferredEmptyCoverageMappingDecls[D] = false; 5667 else 5668 I->second = false; 5669 } 5670 5671 void CodeGenModule::EmitDeferredUnusedCoverageMappings() { 5672 // We call takeVector() here to avoid use-after-free. 5673 // FIXME: DeferredEmptyCoverageMappingDecls is getting mutated because 5674 // we deserialize function bodies to emit coverage info for them, and that 5675 // deserializes more declarations. How should we handle that case? 5676 for (const auto &Entry : DeferredEmptyCoverageMappingDecls.takeVector()) { 5677 if (!Entry.second) 5678 continue; 5679 const Decl *D = Entry.first; 5680 switch (D->getKind()) { 5681 case Decl::CXXConversion: 5682 case Decl::CXXMethod: 5683 case Decl::Function: 5684 case Decl::ObjCMethod: { 5685 CodeGenPGO PGO(*this); 5686 GlobalDecl GD(cast<FunctionDecl>(D)); 5687 PGO.emitEmptyCounterMapping(D, getMangledName(GD), 5688 getFunctionLinkage(GD)); 5689 break; 5690 } 5691 case Decl::CXXConstructor: { 5692 CodeGenPGO PGO(*this); 5693 GlobalDecl GD(cast<CXXConstructorDecl>(D), Ctor_Base); 5694 PGO.emitEmptyCounterMapping(D, getMangledName(GD), 5695 getFunctionLinkage(GD)); 5696 break; 5697 } 5698 case Decl::CXXDestructor: { 5699 CodeGenPGO PGO(*this); 5700 GlobalDecl GD(cast<CXXDestructorDecl>(D), Dtor_Base); 5701 PGO.emitEmptyCounterMapping(D, getMangledName(GD), 5702 getFunctionLinkage(GD)); 5703 break; 5704 } 5705 default: 5706 break; 5707 }; 5708 } 5709 } 5710 5711 void CodeGenModule::EmitMainVoidAlias() { 5712 // In order to transition away from "__original_main" gracefully, emit an 5713 // alias for "main" in the no-argument case so that libc can detect when 5714 // new-style no-argument main is in used. 5715 if (llvm::Function *F = getModule().getFunction("main")) { 5716 if (!F->isDeclaration() && F->arg_size() == 0 && !F->isVarArg() && 5717 F->getReturnType()->isIntegerTy(Context.getTargetInfo().getIntWidth())) 5718 addUsedGlobal(llvm::GlobalAlias::create("__main_void", F)); 5719 } 5720 } 5721 5722 /// Turns the given pointer into a constant. 5723 static llvm::Constant *GetPointerConstant(llvm::LLVMContext &Context, 5724 const void *Ptr) { 5725 uintptr_t PtrInt = reinterpret_cast<uintptr_t>(Ptr); 5726 llvm::Type *i64 = llvm::Type::getInt64Ty(Context); 5727 return llvm::ConstantInt::get(i64, PtrInt); 5728 } 5729 5730 static void EmitGlobalDeclMetadata(CodeGenModule &CGM, 5731 llvm::NamedMDNode *&GlobalMetadata, 5732 GlobalDecl D, 5733 llvm::GlobalValue *Addr) { 5734 if (!GlobalMetadata) 5735 GlobalMetadata = 5736 CGM.getModule().getOrInsertNamedMetadata("clang.global.decl.ptrs"); 5737 5738 // TODO: should we report variant information for ctors/dtors? 5739 llvm::Metadata *Ops[] = {llvm::ConstantAsMetadata::get(Addr), 5740 llvm::ConstantAsMetadata::get(GetPointerConstant( 5741 CGM.getLLVMContext(), D.getDecl()))}; 5742 GlobalMetadata->addOperand(llvm::MDNode::get(CGM.getLLVMContext(), Ops)); 5743 } 5744 5745 /// For each function which is declared within an extern "C" region and marked 5746 /// as 'used', but has internal linkage, create an alias from the unmangled 5747 /// name to the mangled name if possible. People expect to be able to refer 5748 /// to such functions with an unmangled name from inline assembly within the 5749 /// same translation unit. 5750 void CodeGenModule::EmitStaticExternCAliases() { 5751 if (!getTargetCodeGenInfo().shouldEmitStaticExternCAliases()) 5752 return; 5753 for (auto &I : StaticExternCValues) { 5754 IdentifierInfo *Name = I.first; 5755 llvm::GlobalValue *Val = I.second; 5756 if (Val && !getModule().getNamedValue(Name->getName())) 5757 addUsedGlobal(llvm::GlobalAlias::create(Name->getName(), Val)); 5758 } 5759 } 5760 5761 bool CodeGenModule::lookupRepresentativeDecl(StringRef MangledName, 5762 GlobalDecl &Result) const { 5763 auto Res = Manglings.find(MangledName); 5764 if (Res == Manglings.end()) 5765 return false; 5766 Result = Res->getValue(); 5767 return true; 5768 } 5769 5770 /// Emits metadata nodes associating all the global values in the 5771 /// current module with the Decls they came from. This is useful for 5772 /// projects using IR gen as a subroutine. 5773 /// 5774 /// Since there's currently no way to associate an MDNode directly 5775 /// with an llvm::GlobalValue, we create a global named metadata 5776 /// with the name 'clang.global.decl.ptrs'. 5777 void CodeGenModule::EmitDeclMetadata() { 5778 llvm::NamedMDNode *GlobalMetadata = nullptr; 5779 5780 for (auto &I : MangledDeclNames) { 5781 llvm::GlobalValue *Addr = getModule().getNamedValue(I.second); 5782 // Some mangled names don't necessarily have an associated GlobalValue 5783 // in this module, e.g. if we mangled it for DebugInfo. 5784 if (Addr) 5785 EmitGlobalDeclMetadata(*this, GlobalMetadata, I.first, Addr); 5786 } 5787 } 5788 5789 /// Emits metadata nodes for all the local variables in the current 5790 /// function. 5791 void CodeGenFunction::EmitDeclMetadata() { 5792 if (LocalDeclMap.empty()) return; 5793 5794 llvm::LLVMContext &Context = getLLVMContext(); 5795 5796 // Find the unique metadata ID for this name. 5797 unsigned DeclPtrKind = Context.getMDKindID("clang.decl.ptr"); 5798 5799 llvm::NamedMDNode *GlobalMetadata = nullptr; 5800 5801 for (auto &I : LocalDeclMap) { 5802 const Decl *D = I.first; 5803 llvm::Value *Addr = I.second.getPointer(); 5804 if (auto *Alloca = dyn_cast<llvm::AllocaInst>(Addr)) { 5805 llvm::Value *DAddr = GetPointerConstant(getLLVMContext(), D); 5806 Alloca->setMetadata( 5807 DeclPtrKind, llvm::MDNode::get( 5808 Context, llvm::ValueAsMetadata::getConstant(DAddr))); 5809 } else if (auto *GV = dyn_cast<llvm::GlobalValue>(Addr)) { 5810 GlobalDecl GD = GlobalDecl(cast<VarDecl>(D)); 5811 EmitGlobalDeclMetadata(CGM, GlobalMetadata, GD, GV); 5812 } 5813 } 5814 } 5815 5816 void CodeGenModule::EmitVersionIdentMetadata() { 5817 llvm::NamedMDNode *IdentMetadata = 5818 TheModule.getOrInsertNamedMetadata("llvm.ident"); 5819 std::string Version = getClangFullVersion(); 5820 llvm::LLVMContext &Ctx = TheModule.getContext(); 5821 5822 llvm::Metadata *IdentNode[] = {llvm::MDString::get(Ctx, Version)}; 5823 IdentMetadata->addOperand(llvm::MDNode::get(Ctx, IdentNode)); 5824 } 5825 5826 void CodeGenModule::EmitCommandLineMetadata() { 5827 llvm::NamedMDNode *CommandLineMetadata = 5828 TheModule.getOrInsertNamedMetadata("llvm.commandline"); 5829 std::string CommandLine = getCodeGenOpts().RecordCommandLine; 5830 llvm::LLVMContext &Ctx = TheModule.getContext(); 5831 5832 llvm::Metadata *CommandLineNode[] = {llvm::MDString::get(Ctx, CommandLine)}; 5833 CommandLineMetadata->addOperand(llvm::MDNode::get(Ctx, CommandLineNode)); 5834 } 5835 5836 void CodeGenModule::EmitCoverageFile() { 5837 if (getCodeGenOpts().CoverageDataFile.empty() && 5838 getCodeGenOpts().CoverageNotesFile.empty()) 5839 return; 5840 5841 llvm::NamedMDNode *CUNode = TheModule.getNamedMetadata("llvm.dbg.cu"); 5842 if (!CUNode) 5843 return; 5844 5845 llvm::NamedMDNode *GCov = TheModule.getOrInsertNamedMetadata("llvm.gcov"); 5846 llvm::LLVMContext &Ctx = TheModule.getContext(); 5847 auto *CoverageDataFile = 5848 llvm::MDString::get(Ctx, getCodeGenOpts().CoverageDataFile); 5849 auto *CoverageNotesFile = 5850 llvm::MDString::get(Ctx, getCodeGenOpts().CoverageNotesFile); 5851 for (int i = 0, e = CUNode->getNumOperands(); i != e; ++i) { 5852 llvm::MDNode *CU = CUNode->getOperand(i); 5853 llvm::Metadata *Elts[] = {CoverageNotesFile, CoverageDataFile, CU}; 5854 GCov->addOperand(llvm::MDNode::get(Ctx, Elts)); 5855 } 5856 } 5857 5858 llvm::Constant *CodeGenModule::GetAddrOfRTTIDescriptor(QualType Ty, 5859 bool ForEH) { 5860 // Return a bogus pointer if RTTI is disabled, unless it's for EH. 5861 // FIXME: should we even be calling this method if RTTI is disabled 5862 // and it's not for EH? 5863 if ((!ForEH && !getLangOpts().RTTI) || getLangOpts().CUDAIsDevice || 5864 (getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice && 5865 getTriple().isNVPTX())) 5866 return llvm::Constant::getNullValue(Int8PtrTy); 5867 5868 if (ForEH && Ty->isObjCObjectPointerType() && 5869 LangOpts.ObjCRuntime.isGNUFamily()) 5870 return ObjCRuntime->GetEHType(Ty); 5871 5872 return getCXXABI().getAddrOfRTTIDescriptor(Ty); 5873 } 5874 5875 void CodeGenModule::EmitOMPThreadPrivateDecl(const OMPThreadPrivateDecl *D) { 5876 // Do not emit threadprivates in simd-only mode. 5877 if (LangOpts.OpenMP && LangOpts.OpenMPSimd) 5878 return; 5879 for (auto RefExpr : D->varlists()) { 5880 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(RefExpr)->getDecl()); 5881 bool PerformInit = 5882 VD->getAnyInitializer() && 5883 !VD->getAnyInitializer()->isConstantInitializer(getContext(), 5884 /*ForRef=*/false); 5885 5886 Address Addr(GetAddrOfGlobalVar(VD), getContext().getDeclAlign(VD)); 5887 if (auto InitFunction = getOpenMPRuntime().emitThreadPrivateVarDefinition( 5888 VD, Addr, RefExpr->getBeginLoc(), PerformInit)) 5889 CXXGlobalInits.push_back(InitFunction); 5890 } 5891 } 5892 5893 llvm::Metadata * 5894 CodeGenModule::CreateMetadataIdentifierImpl(QualType T, MetadataTypeMap &Map, 5895 StringRef Suffix) { 5896 llvm::Metadata *&InternalId = Map[T.getCanonicalType()]; 5897 if (InternalId) 5898 return InternalId; 5899 5900 if (isExternallyVisible(T->getLinkage())) { 5901 std::string OutName; 5902 llvm::raw_string_ostream Out(OutName); 5903 getCXXABI().getMangleContext().mangleTypeName(T, Out); 5904 Out << Suffix; 5905 5906 InternalId = llvm::MDString::get(getLLVMContext(), Out.str()); 5907 } else { 5908 InternalId = llvm::MDNode::getDistinct(getLLVMContext(), 5909 llvm::ArrayRef<llvm::Metadata *>()); 5910 } 5911 5912 return InternalId; 5913 } 5914 5915 llvm::Metadata *CodeGenModule::CreateMetadataIdentifierForType(QualType T) { 5916 return CreateMetadataIdentifierImpl(T, MetadataIdMap, ""); 5917 } 5918 5919 llvm::Metadata * 5920 CodeGenModule::CreateMetadataIdentifierForVirtualMemPtrType(QualType T) { 5921 return CreateMetadataIdentifierImpl(T, VirtualMetadataIdMap, ".virtual"); 5922 } 5923 5924 // Generalize pointer types to a void pointer with the qualifiers of the 5925 // originally pointed-to type, e.g. 'const char *' and 'char * const *' 5926 // generalize to 'const void *' while 'char *' and 'const char **' generalize to 5927 // 'void *'. 5928 static QualType GeneralizeType(ASTContext &Ctx, QualType Ty) { 5929 if (!Ty->isPointerType()) 5930 return Ty; 5931 5932 return Ctx.getPointerType( 5933 QualType(Ctx.VoidTy).withCVRQualifiers( 5934 Ty->getPointeeType().getCVRQualifiers())); 5935 } 5936 5937 // Apply type generalization to a FunctionType's return and argument types 5938 static QualType GeneralizeFunctionType(ASTContext &Ctx, QualType Ty) { 5939 if (auto *FnType = Ty->getAs<FunctionProtoType>()) { 5940 SmallVector<QualType, 8> GeneralizedParams; 5941 for (auto &Param : FnType->param_types()) 5942 GeneralizedParams.push_back(GeneralizeType(Ctx, Param)); 5943 5944 return Ctx.getFunctionType( 5945 GeneralizeType(Ctx, FnType->getReturnType()), 5946 GeneralizedParams, FnType->getExtProtoInfo()); 5947 } 5948 5949 if (auto *FnType = Ty->getAs<FunctionNoProtoType>()) 5950 return Ctx.getFunctionNoProtoType( 5951 GeneralizeType(Ctx, FnType->getReturnType())); 5952 5953 llvm_unreachable("Encountered unknown FunctionType"); 5954 } 5955 5956 llvm::Metadata *CodeGenModule::CreateMetadataIdentifierGeneralized(QualType T) { 5957 return CreateMetadataIdentifierImpl(GeneralizeFunctionType(getContext(), T), 5958 GeneralizedMetadataIdMap, ".generalized"); 5959 } 5960 5961 /// Returns whether this module needs the "all-vtables" type identifier. 5962 bool CodeGenModule::NeedAllVtablesTypeId() const { 5963 // Returns true if at least one of vtable-based CFI checkers is enabled and 5964 // is not in the trapping mode. 5965 return ((LangOpts.Sanitize.has(SanitizerKind::CFIVCall) && 5966 !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFIVCall)) || 5967 (LangOpts.Sanitize.has(SanitizerKind::CFINVCall) && 5968 !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFINVCall)) || 5969 (LangOpts.Sanitize.has(SanitizerKind::CFIDerivedCast) && 5970 !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFIDerivedCast)) || 5971 (LangOpts.Sanitize.has(SanitizerKind::CFIUnrelatedCast) && 5972 !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFIUnrelatedCast))); 5973 } 5974 5975 void CodeGenModule::AddVTableTypeMetadata(llvm::GlobalVariable *VTable, 5976 CharUnits Offset, 5977 const CXXRecordDecl *RD) { 5978 llvm::Metadata *MD = 5979 CreateMetadataIdentifierForType(QualType(RD->getTypeForDecl(), 0)); 5980 VTable->addTypeMetadata(Offset.getQuantity(), MD); 5981 5982 if (CodeGenOpts.SanitizeCfiCrossDso) 5983 if (auto CrossDsoTypeId = CreateCrossDsoCfiTypeId(MD)) 5984 VTable->addTypeMetadata(Offset.getQuantity(), 5985 llvm::ConstantAsMetadata::get(CrossDsoTypeId)); 5986 5987 if (NeedAllVtablesTypeId()) { 5988 llvm::Metadata *MD = llvm::MDString::get(getLLVMContext(), "all-vtables"); 5989 VTable->addTypeMetadata(Offset.getQuantity(), MD); 5990 } 5991 } 5992 5993 llvm::SanitizerStatReport &CodeGenModule::getSanStats() { 5994 if (!SanStats) 5995 SanStats = std::make_unique<llvm::SanitizerStatReport>(&getModule()); 5996 5997 return *SanStats; 5998 } 5999 llvm::Value * 6000 CodeGenModule::createOpenCLIntToSamplerConversion(const Expr *E, 6001 CodeGenFunction &CGF) { 6002 llvm::Constant *C = ConstantEmitter(CGF).emitAbstract(E, E->getType()); 6003 auto SamplerT = getOpenCLRuntime().getSamplerType(E->getType().getTypePtr()); 6004 auto FTy = llvm::FunctionType::get(SamplerT, {C->getType()}, false); 6005 return CGF.Builder.CreateCall(CreateRuntimeFunction(FTy, 6006 "__translate_sampler_initializer"), 6007 {C}); 6008 } 6009 6010 CharUnits CodeGenModule::getNaturalPointeeTypeAlignment( 6011 QualType T, LValueBaseInfo *BaseInfo, TBAAAccessInfo *TBAAInfo) { 6012 return getNaturalTypeAlignment(T->getPointeeType(), BaseInfo, TBAAInfo, 6013 /* forPointeeType= */ true); 6014 } 6015 6016 CharUnits CodeGenModule::getNaturalTypeAlignment(QualType T, 6017 LValueBaseInfo *BaseInfo, 6018 TBAAAccessInfo *TBAAInfo, 6019 bool forPointeeType) { 6020 if (TBAAInfo) 6021 *TBAAInfo = getTBAAAccessInfo(T); 6022 6023 // FIXME: This duplicates logic in ASTContext::getTypeAlignIfKnown. But 6024 // that doesn't return the information we need to compute BaseInfo. 6025 6026 // Honor alignment typedef attributes even on incomplete types. 6027 // We also honor them straight for C++ class types, even as pointees; 6028 // there's an expressivity gap here. 6029 if (auto TT = T->getAs<TypedefType>()) { 6030 if (auto Align = TT->getDecl()->getMaxAlignment()) { 6031 if (BaseInfo) 6032 *BaseInfo = LValueBaseInfo(AlignmentSource::AttributedType); 6033 return getContext().toCharUnitsFromBits(Align); 6034 } 6035 } 6036 6037 bool AlignForArray = T->isArrayType(); 6038 6039 // Analyze the base element type, so we don't get confused by incomplete 6040 // array types. 6041 T = getContext().getBaseElementType(T); 6042 6043 if (T->isIncompleteType()) { 6044 // We could try to replicate the logic from 6045 // ASTContext::getTypeAlignIfKnown, but nothing uses the alignment if the 6046 // type is incomplete, so it's impossible to test. We could try to reuse 6047 // getTypeAlignIfKnown, but that doesn't return the information we need 6048 // to set BaseInfo. So just ignore the possibility that the alignment is 6049 // greater than one. 6050 if (BaseInfo) 6051 *BaseInfo = LValueBaseInfo(AlignmentSource::Type); 6052 return CharUnits::One(); 6053 } 6054 6055 if (BaseInfo) 6056 *BaseInfo = LValueBaseInfo(AlignmentSource::Type); 6057 6058 CharUnits Alignment; 6059 // For C++ class pointees, we don't know whether we're pointing at a 6060 // base or a complete object, so we generally need to use the 6061 // non-virtual alignment. 6062 const CXXRecordDecl *RD; 6063 if (forPointeeType && !AlignForArray && (RD = T->getAsCXXRecordDecl())) { 6064 Alignment = getClassPointerAlignment(RD); 6065 } else { 6066 Alignment = getContext().getTypeAlignInChars(T); 6067 if (T.getQualifiers().hasUnaligned()) 6068 Alignment = CharUnits::One(); 6069 } 6070 6071 // Cap to the global maximum type alignment unless the alignment 6072 // was somehow explicit on the type. 6073 if (unsigned MaxAlign = getLangOpts().MaxTypeAlign) { 6074 if (Alignment.getQuantity() > MaxAlign && 6075 !getContext().isAlignmentRequired(T)) 6076 Alignment = CharUnits::fromQuantity(MaxAlign); 6077 } 6078 return Alignment; 6079 } 6080 6081 bool CodeGenModule::stopAutoInit() { 6082 unsigned StopAfter = getContext().getLangOpts().TrivialAutoVarInitStopAfter; 6083 if (StopAfter) { 6084 // This number is positive only when -ftrivial-auto-var-init-stop-after=* is 6085 // used 6086 if (NumAutoVarInit >= StopAfter) { 6087 return true; 6088 } 6089 if (!NumAutoVarInit) { 6090 unsigned DiagID = getDiags().getCustomDiagID( 6091 DiagnosticsEngine::Warning, 6092 "-ftrivial-auto-var-init-stop-after=%0 has been enabled to limit the " 6093 "number of times ftrivial-auto-var-init=%1 gets applied."); 6094 getDiags().Report(DiagID) 6095 << StopAfter 6096 << (getContext().getLangOpts().getTrivialAutoVarInit() == 6097 LangOptions::TrivialAutoVarInitKind::Zero 6098 ? "zero" 6099 : "pattern"); 6100 } 6101 ++NumAutoVarInit; 6102 } 6103 return false; 6104 } 6105