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