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