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