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