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