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