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