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