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