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