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