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