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