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