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