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