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