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