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