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