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, 704 ForDefinition_t IsForDefinition) const { 705 if (GV->hasDLLImportStorageClass()) 706 return; 707 // Internal definitions always have default visibility. 708 if (GV->hasLocalLinkage()) { 709 GV->setVisibility(llvm::GlobalValue::DefaultVisibility); 710 return; 711 } 712 713 // Set visibility for definitions. 714 LinkageInfo LV = D->getLinkageAndVisibility(); 715 if (LV.isVisibilityExplicit() || 716 (IsForDefinition && !GV->hasAvailableExternallyLinkage())) 717 GV->setVisibility(GetLLVMVisibility(LV.getVisibility())); 718 } 719 720 static bool shouldAssumeDSOLocal(const CodeGenModule &CGM, 721 llvm::GlobalValue *GV, const NamedDecl *D, 722 ForDefinition_t IsForDefinition) { 723 const llvm::Triple &TT = CGM.getTriple(); 724 // Only handle ELF for now. 725 if (!TT.isOSBinFormatELF()) 726 return false; 727 728 // If this is not an executable, don't assume anything is local. 729 const auto &CGOpts = CGM.getCodeGenOpts(); 730 llvm::Reloc::Model RM = CGOpts.RelocationModel; 731 const auto &LOpts = CGM.getLangOpts(); 732 if (RM != llvm::Reloc::Static && !LOpts.PIE) 733 return false; 734 735 // A definition cannot be preempted from an executable. 736 if (IsForDefinition) 737 return true; 738 739 // Most PIC code sequences that assume that a symbol is local cannot produce a 740 // 0 if it turns out the symbol is undefined. While this is ABI and relocation 741 // depended, it seems worth it to handle it here. 742 if (RM == llvm::Reloc::PIC_ && GV->hasExternalWeakLinkage()) 743 return false; 744 745 // PPC has no copy relocations and cannot use a plt entry as a symbol address. 746 llvm::Triple::ArchType Arch = TT.getArch(); 747 if (Arch == llvm::Triple::ppc || Arch == llvm::Triple::ppc64 || 748 Arch == llvm::Triple::ppc64le) 749 return false; 750 751 // If we can use copy relocations we can assume it is local. 752 if (isa<VarDecl>(D) && 753 (RM == llvm::Reloc::Static || CGOpts.PIECopyRelocations)) 754 return true; 755 756 // If we can use a plt entry as the symbol address we can assume it 757 // is local. 758 if (isa<FunctionDecl>(D) && !CGOpts.NoPLT) 759 return true; 760 761 // Otherwise don't assue it is local. 762 return false; 763 } 764 765 void CodeGenModule::setDSOLocal(llvm::GlobalValue *GV, const NamedDecl *D, 766 ForDefinition_t IsForDefinition) const { 767 if (shouldAssumeDSOLocal(*this, GV, D, IsForDefinition)) 768 GV->setDSOLocal(true); 769 } 770 771 void CodeGenModule::setGVProperties(llvm::GlobalValue *GV, const NamedDecl *D, 772 ForDefinition_t IsForDefinition) const { 773 setGlobalVisibility(GV, D, IsForDefinition); 774 setDSOLocal(GV, D, IsForDefinition); 775 } 776 777 static llvm::GlobalVariable::ThreadLocalMode GetLLVMTLSModel(StringRef S) { 778 return llvm::StringSwitch<llvm::GlobalVariable::ThreadLocalMode>(S) 779 .Case("global-dynamic", llvm::GlobalVariable::GeneralDynamicTLSModel) 780 .Case("local-dynamic", llvm::GlobalVariable::LocalDynamicTLSModel) 781 .Case("initial-exec", llvm::GlobalVariable::InitialExecTLSModel) 782 .Case("local-exec", llvm::GlobalVariable::LocalExecTLSModel); 783 } 784 785 static llvm::GlobalVariable::ThreadLocalMode GetLLVMTLSModel( 786 CodeGenOptions::TLSModel M) { 787 switch (M) { 788 case CodeGenOptions::GeneralDynamicTLSModel: 789 return llvm::GlobalVariable::GeneralDynamicTLSModel; 790 case CodeGenOptions::LocalDynamicTLSModel: 791 return llvm::GlobalVariable::LocalDynamicTLSModel; 792 case CodeGenOptions::InitialExecTLSModel: 793 return llvm::GlobalVariable::InitialExecTLSModel; 794 case CodeGenOptions::LocalExecTLSModel: 795 return llvm::GlobalVariable::LocalExecTLSModel; 796 } 797 llvm_unreachable("Invalid TLS model!"); 798 } 799 800 void CodeGenModule::setTLSMode(llvm::GlobalValue *GV, const VarDecl &D) const { 801 assert(D.getTLSKind() && "setting TLS mode on non-TLS var!"); 802 803 llvm::GlobalValue::ThreadLocalMode TLM; 804 TLM = GetLLVMTLSModel(CodeGenOpts.getDefaultTLSModel()); 805 806 // Override the TLS model if it is explicitly specified. 807 if (const TLSModelAttr *Attr = D.getAttr<TLSModelAttr>()) { 808 TLM = GetLLVMTLSModel(Attr->getModel()); 809 } 810 811 GV->setThreadLocalMode(TLM); 812 } 813 814 static void AppendTargetMangling(const CodeGenModule &CGM, 815 const TargetAttr *Attr, raw_ostream &Out) { 816 if (Attr->isDefaultVersion()) 817 return; 818 819 Out << '.'; 820 const auto &Target = CGM.getTarget(); 821 TargetAttr::ParsedTargetAttr Info = 822 Attr->parse([&Target](StringRef LHS, StringRef RHS) { 823 // Multiversioning doesn't allow "no-${feature}", so we can 824 // only have "+" prefixes here. 825 assert(LHS.startswith("+") && RHS.startswith("+") && 826 "Features should always have a prefix."); 827 return Target.multiVersionSortPriority(LHS.substr(1)) > 828 Target.multiVersionSortPriority(RHS.substr(1)); 829 }); 830 831 bool IsFirst = true; 832 833 if (!Info.Architecture.empty()) { 834 IsFirst = false; 835 Out << "arch_" << Info.Architecture; 836 } 837 838 for (StringRef Feat : Info.Features) { 839 if (!IsFirst) 840 Out << '_'; 841 IsFirst = false; 842 Out << Feat.substr(1); 843 } 844 } 845 846 static std::string getMangledNameImpl(const CodeGenModule &CGM, GlobalDecl GD, 847 const NamedDecl *ND, 848 bool OmitTargetMangling = false) { 849 SmallString<256> Buffer; 850 llvm::raw_svector_ostream Out(Buffer); 851 MangleContext &MC = CGM.getCXXABI().getMangleContext(); 852 if (MC.shouldMangleDeclName(ND)) { 853 llvm::raw_svector_ostream Out(Buffer); 854 if (const auto *D = dyn_cast<CXXConstructorDecl>(ND)) 855 MC.mangleCXXCtor(D, GD.getCtorType(), Out); 856 else if (const auto *D = dyn_cast<CXXDestructorDecl>(ND)) 857 MC.mangleCXXDtor(D, GD.getDtorType(), Out); 858 else 859 MC.mangleName(ND, Out); 860 } else { 861 IdentifierInfo *II = ND->getIdentifier(); 862 assert(II && "Attempt to mangle unnamed decl."); 863 const auto *FD = dyn_cast<FunctionDecl>(ND); 864 865 if (FD && 866 FD->getType()->castAs<FunctionType>()->getCallConv() == CC_X86RegCall) { 867 llvm::raw_svector_ostream Out(Buffer); 868 Out << "__regcall3__" << II->getName(); 869 } else { 870 Out << II->getName(); 871 } 872 } 873 874 if (const auto *FD = dyn_cast<FunctionDecl>(ND)) 875 if (FD->isMultiVersion() && !OmitTargetMangling) 876 AppendTargetMangling(CGM, FD->getAttr<TargetAttr>(), Out); 877 return Out.str(); 878 } 879 880 void CodeGenModule::UpdateMultiVersionNames(GlobalDecl GD, 881 const FunctionDecl *FD) { 882 if (!FD->isMultiVersion()) 883 return; 884 885 // Get the name of what this would be without the 'target' attribute. This 886 // allows us to lookup the version that was emitted when this wasn't a 887 // multiversion function. 888 std::string NonTargetName = 889 getMangledNameImpl(*this, GD, FD, /*OmitTargetMangling=*/true); 890 GlobalDecl OtherGD; 891 if (lookupRepresentativeDecl(NonTargetName, OtherGD)) { 892 assert(OtherGD.getCanonicalDecl() 893 .getDecl() 894 ->getAsFunction() 895 ->isMultiVersion() && 896 "Other GD should now be a multiversioned function"); 897 // OtherFD is the version of this function that was mangled BEFORE 898 // becoming a MultiVersion function. It potentially needs to be updated. 899 const FunctionDecl *OtherFD = 900 OtherGD.getCanonicalDecl().getDecl()->getAsFunction(); 901 std::string OtherName = getMangledNameImpl(*this, OtherGD, OtherFD); 902 // This is so that if the initial version was already the 'default' 903 // version, we don't try to update it. 904 if (OtherName != NonTargetName) { 905 // Remove instead of erase, since others may have stored the StringRef 906 // to this. 907 const auto ExistingRecord = Manglings.find(NonTargetName); 908 if (ExistingRecord != std::end(Manglings)) 909 Manglings.remove(&(*ExistingRecord)); 910 auto Result = Manglings.insert(std::make_pair(OtherName, OtherGD)); 911 MangledDeclNames[OtherGD.getCanonicalDecl()] = Result.first->first(); 912 if (llvm::GlobalValue *Entry = GetGlobalValue(NonTargetName)) 913 Entry->setName(OtherName); 914 } 915 } 916 } 917 918 StringRef CodeGenModule::getMangledName(GlobalDecl GD) { 919 GlobalDecl CanonicalGD = GD.getCanonicalDecl(); 920 921 // Some ABIs don't have constructor variants. Make sure that base and 922 // complete constructors get mangled the same. 923 if (const auto *CD = dyn_cast<CXXConstructorDecl>(CanonicalGD.getDecl())) { 924 if (!getTarget().getCXXABI().hasConstructorVariants()) { 925 CXXCtorType OrigCtorType = GD.getCtorType(); 926 assert(OrigCtorType == Ctor_Base || OrigCtorType == Ctor_Complete); 927 if (OrigCtorType == Ctor_Base) 928 CanonicalGD = GlobalDecl(CD, Ctor_Complete); 929 } 930 } 931 932 auto FoundName = MangledDeclNames.find(CanonicalGD); 933 if (FoundName != MangledDeclNames.end()) 934 return FoundName->second; 935 936 937 // Keep the first result in the case of a mangling collision. 938 const auto *ND = cast<NamedDecl>(GD.getDecl()); 939 auto Result = 940 Manglings.insert(std::make_pair(getMangledNameImpl(*this, GD, ND), GD)); 941 return MangledDeclNames[CanonicalGD] = Result.first->first(); 942 } 943 944 StringRef CodeGenModule::getBlockMangledName(GlobalDecl GD, 945 const BlockDecl *BD) { 946 MangleContext &MangleCtx = getCXXABI().getMangleContext(); 947 const Decl *D = GD.getDecl(); 948 949 SmallString<256> Buffer; 950 llvm::raw_svector_ostream Out(Buffer); 951 if (!D) 952 MangleCtx.mangleGlobalBlock(BD, 953 dyn_cast_or_null<VarDecl>(initializedGlobalDecl.getDecl()), Out); 954 else if (const auto *CD = dyn_cast<CXXConstructorDecl>(D)) 955 MangleCtx.mangleCtorBlock(CD, GD.getCtorType(), BD, Out); 956 else if (const auto *DD = dyn_cast<CXXDestructorDecl>(D)) 957 MangleCtx.mangleDtorBlock(DD, GD.getDtorType(), BD, Out); 958 else 959 MangleCtx.mangleBlock(cast<DeclContext>(D), BD, Out); 960 961 auto Result = Manglings.insert(std::make_pair(Out.str(), BD)); 962 return Result.first->first(); 963 } 964 965 llvm::GlobalValue *CodeGenModule::GetGlobalValue(StringRef Name) { 966 return getModule().getNamedValue(Name); 967 } 968 969 /// AddGlobalCtor - Add a function to the list that will be called before 970 /// main() runs. 971 void CodeGenModule::AddGlobalCtor(llvm::Function *Ctor, int Priority, 972 llvm::Constant *AssociatedData) { 973 // FIXME: Type coercion of void()* types. 974 GlobalCtors.push_back(Structor(Priority, Ctor, AssociatedData)); 975 } 976 977 /// AddGlobalDtor - Add a function to the list that will be called 978 /// when the module is unloaded. 979 void CodeGenModule::AddGlobalDtor(llvm::Function *Dtor, int Priority) { 980 // FIXME: Type coercion of void()* types. 981 GlobalDtors.push_back(Structor(Priority, Dtor, nullptr)); 982 } 983 984 void CodeGenModule::EmitCtorList(CtorList &Fns, const char *GlobalName) { 985 if (Fns.empty()) return; 986 987 // Ctor function type is void()*. 988 llvm::FunctionType* CtorFTy = llvm::FunctionType::get(VoidTy, false); 989 llvm::Type *CtorPFTy = llvm::PointerType::getUnqual(CtorFTy); 990 991 // Get the type of a ctor entry, { i32, void ()*, i8* }. 992 llvm::StructType *CtorStructTy = llvm::StructType::get( 993 Int32Ty, llvm::PointerType::getUnqual(CtorFTy), VoidPtrTy); 994 995 // Construct the constructor and destructor arrays. 996 ConstantInitBuilder builder(*this); 997 auto ctors = builder.beginArray(CtorStructTy); 998 for (const auto &I : Fns) { 999 auto ctor = ctors.beginStruct(CtorStructTy); 1000 ctor.addInt(Int32Ty, I.Priority); 1001 ctor.add(llvm::ConstantExpr::getBitCast(I.Initializer, CtorPFTy)); 1002 if (I.AssociatedData) 1003 ctor.add(llvm::ConstantExpr::getBitCast(I.AssociatedData, VoidPtrTy)); 1004 else 1005 ctor.addNullPointer(VoidPtrTy); 1006 ctor.finishAndAddTo(ctors); 1007 } 1008 1009 auto list = 1010 ctors.finishAndCreateGlobal(GlobalName, getPointerAlign(), 1011 /*constant*/ false, 1012 llvm::GlobalValue::AppendingLinkage); 1013 1014 // The LTO linker doesn't seem to like it when we set an alignment 1015 // on appending variables. Take it off as a workaround. 1016 list->setAlignment(0); 1017 1018 Fns.clear(); 1019 } 1020 1021 llvm::GlobalValue::LinkageTypes 1022 CodeGenModule::getFunctionLinkage(GlobalDecl GD) { 1023 const auto *D = cast<FunctionDecl>(GD.getDecl()); 1024 1025 GVALinkage Linkage = getContext().GetGVALinkageForFunction(D); 1026 1027 if (isa<CXXDestructorDecl>(D) && 1028 getCXXABI().useThunkForDtorVariant(cast<CXXDestructorDecl>(D), 1029 GD.getDtorType())) { 1030 // Destructor variants in the Microsoft C++ ABI are always internal or 1031 // linkonce_odr thunks emitted on an as-needed basis. 1032 return Linkage == GVA_Internal ? llvm::GlobalValue::InternalLinkage 1033 : llvm::GlobalValue::LinkOnceODRLinkage; 1034 } 1035 1036 if (isa<CXXConstructorDecl>(D) && 1037 cast<CXXConstructorDecl>(D)->isInheritingConstructor() && 1038 Context.getTargetInfo().getCXXABI().isMicrosoft()) { 1039 // Our approach to inheriting constructors is fundamentally different from 1040 // that used by the MS ABI, so keep our inheriting constructor thunks 1041 // internal rather than trying to pick an unambiguous mangling for them. 1042 return llvm::GlobalValue::InternalLinkage; 1043 } 1044 1045 return getLLVMLinkageForDeclarator(D, Linkage, /*isConstantVariable=*/false); 1046 } 1047 1048 void CodeGenModule::setFunctionDLLStorageClass(GlobalDecl GD, llvm::Function *F) { 1049 const auto *FD = cast<FunctionDecl>(GD.getDecl()); 1050 1051 if (const auto *Dtor = dyn_cast_or_null<CXXDestructorDecl>(FD)) { 1052 if (getCXXABI().useThunkForDtorVariant(Dtor, GD.getDtorType())) { 1053 // Don't dllexport/import destructor thunks. 1054 F->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass); 1055 return; 1056 } 1057 } 1058 1059 if (FD->hasAttr<DLLImportAttr>()) 1060 F->setDLLStorageClass(llvm::GlobalVariable::DLLImportStorageClass); 1061 else if (FD->hasAttr<DLLExportAttr>()) 1062 F->setDLLStorageClass(llvm::GlobalVariable::DLLExportStorageClass); 1063 else 1064 F->setDLLStorageClass(llvm::GlobalVariable::DefaultStorageClass); 1065 } 1066 1067 llvm::ConstantInt *CodeGenModule::CreateCrossDsoCfiTypeId(llvm::Metadata *MD) { 1068 llvm::MDString *MDS = dyn_cast<llvm::MDString>(MD); 1069 if (!MDS) return nullptr; 1070 1071 return llvm::ConstantInt::get(Int64Ty, llvm::MD5Hash(MDS->getString())); 1072 } 1073 1074 void CodeGenModule::setFunctionDefinitionAttributes(const FunctionDecl *D, 1075 llvm::Function *F) { 1076 setNonAliasAttributes(D, F); 1077 } 1078 1079 void CodeGenModule::SetLLVMFunctionAttributes(const Decl *D, 1080 const CGFunctionInfo &Info, 1081 llvm::Function *F) { 1082 unsigned CallingConv; 1083 llvm::AttributeList PAL; 1084 ConstructAttributeList(F->getName(), Info, D, PAL, CallingConv, false); 1085 F->setAttributes(PAL); 1086 F->setCallingConv(static_cast<llvm::CallingConv::ID>(CallingConv)); 1087 } 1088 1089 /// Determines whether the language options require us to model 1090 /// unwind exceptions. We treat -fexceptions as mandating this 1091 /// except under the fragile ObjC ABI with only ObjC exceptions 1092 /// enabled. This means, for example, that C with -fexceptions 1093 /// enables this. 1094 static bool hasUnwindExceptions(const LangOptions &LangOpts) { 1095 // If exceptions are completely disabled, obviously this is false. 1096 if (!LangOpts.Exceptions) return false; 1097 1098 // If C++ exceptions are enabled, this is true. 1099 if (LangOpts.CXXExceptions) return true; 1100 1101 // If ObjC exceptions are enabled, this depends on the ABI. 1102 if (LangOpts.ObjCExceptions) { 1103 return LangOpts.ObjCRuntime.hasUnwindExceptions(); 1104 } 1105 1106 return true; 1107 } 1108 1109 void CodeGenModule::SetLLVMFunctionAttributesForDefinition(const Decl *D, 1110 llvm::Function *F) { 1111 llvm::AttrBuilder B; 1112 1113 if (CodeGenOpts.UnwindTables) 1114 B.addAttribute(llvm::Attribute::UWTable); 1115 1116 if (!hasUnwindExceptions(LangOpts)) 1117 B.addAttribute(llvm::Attribute::NoUnwind); 1118 1119 if (LangOpts.getStackProtector() == LangOptions::SSPOn) 1120 B.addAttribute(llvm::Attribute::StackProtect); 1121 else if (LangOpts.getStackProtector() == LangOptions::SSPStrong) 1122 B.addAttribute(llvm::Attribute::StackProtectStrong); 1123 else if (LangOpts.getStackProtector() == LangOptions::SSPReq) 1124 B.addAttribute(llvm::Attribute::StackProtectReq); 1125 1126 if (!D) { 1127 // If we don't have a declaration to control inlining, the function isn't 1128 // explicitly marked as alwaysinline for semantic reasons, and inlining is 1129 // disabled, mark the function as noinline. 1130 if (!F->hasFnAttribute(llvm::Attribute::AlwaysInline) && 1131 CodeGenOpts.getInlining() == CodeGenOptions::OnlyAlwaysInlining) 1132 B.addAttribute(llvm::Attribute::NoInline); 1133 1134 F->addAttributes(llvm::AttributeList::FunctionIndex, B); 1135 return; 1136 } 1137 1138 // Track whether we need to add the optnone LLVM attribute, 1139 // starting with the default for this optimization level. 1140 bool ShouldAddOptNone = 1141 !CodeGenOpts.DisableO0ImplyOptNone && CodeGenOpts.OptimizationLevel == 0; 1142 // We can't add optnone in the following cases, it won't pass the verifier. 1143 ShouldAddOptNone &= !D->hasAttr<MinSizeAttr>(); 1144 ShouldAddOptNone &= !F->hasFnAttribute(llvm::Attribute::AlwaysInline); 1145 ShouldAddOptNone &= !D->hasAttr<AlwaysInlineAttr>(); 1146 1147 if (ShouldAddOptNone || D->hasAttr<OptimizeNoneAttr>()) { 1148 B.addAttribute(llvm::Attribute::OptimizeNone); 1149 1150 // OptimizeNone implies noinline; we should not be inlining such functions. 1151 B.addAttribute(llvm::Attribute::NoInline); 1152 assert(!F->hasFnAttribute(llvm::Attribute::AlwaysInline) && 1153 "OptimizeNone and AlwaysInline on same function!"); 1154 1155 // We still need to handle naked functions even though optnone subsumes 1156 // much of their semantics. 1157 if (D->hasAttr<NakedAttr>()) 1158 B.addAttribute(llvm::Attribute::Naked); 1159 1160 // OptimizeNone wins over OptimizeForSize and MinSize. 1161 F->removeFnAttr(llvm::Attribute::OptimizeForSize); 1162 F->removeFnAttr(llvm::Attribute::MinSize); 1163 } else if (D->hasAttr<NakedAttr>()) { 1164 // Naked implies noinline: we should not be inlining such functions. 1165 B.addAttribute(llvm::Attribute::Naked); 1166 B.addAttribute(llvm::Attribute::NoInline); 1167 } else if (D->hasAttr<NoDuplicateAttr>()) { 1168 B.addAttribute(llvm::Attribute::NoDuplicate); 1169 } else if (D->hasAttr<NoInlineAttr>()) { 1170 B.addAttribute(llvm::Attribute::NoInline); 1171 } else if (D->hasAttr<AlwaysInlineAttr>() && 1172 !F->hasFnAttribute(llvm::Attribute::NoInline)) { 1173 // (noinline wins over always_inline, and we can't specify both in IR) 1174 B.addAttribute(llvm::Attribute::AlwaysInline); 1175 } else if (CodeGenOpts.getInlining() == CodeGenOptions::OnlyAlwaysInlining) { 1176 // If we're not inlining, then force everything that isn't always_inline to 1177 // carry an explicit noinline attribute. 1178 if (!F->hasFnAttribute(llvm::Attribute::AlwaysInline)) 1179 B.addAttribute(llvm::Attribute::NoInline); 1180 } else { 1181 // Otherwise, propagate the inline hint attribute and potentially use its 1182 // absence to mark things as noinline. 1183 if (auto *FD = dyn_cast<FunctionDecl>(D)) { 1184 if (any_of(FD->redecls(), [&](const FunctionDecl *Redecl) { 1185 return Redecl->isInlineSpecified(); 1186 })) { 1187 B.addAttribute(llvm::Attribute::InlineHint); 1188 } else if (CodeGenOpts.getInlining() == 1189 CodeGenOptions::OnlyHintInlining && 1190 !FD->isInlined() && 1191 !F->hasFnAttribute(llvm::Attribute::AlwaysInline)) { 1192 B.addAttribute(llvm::Attribute::NoInline); 1193 } 1194 } 1195 } 1196 1197 // Add other optimization related attributes if we are optimizing this 1198 // function. 1199 if (!D->hasAttr<OptimizeNoneAttr>()) { 1200 if (D->hasAttr<ColdAttr>()) { 1201 if (!ShouldAddOptNone) 1202 B.addAttribute(llvm::Attribute::OptimizeForSize); 1203 B.addAttribute(llvm::Attribute::Cold); 1204 } 1205 1206 if (D->hasAttr<MinSizeAttr>()) 1207 B.addAttribute(llvm::Attribute::MinSize); 1208 } 1209 1210 F->addAttributes(llvm::AttributeList::FunctionIndex, B); 1211 1212 unsigned alignment = D->getMaxAlignment() / Context.getCharWidth(); 1213 if (alignment) 1214 F->setAlignment(alignment); 1215 1216 // Some C++ ABIs require 2-byte alignment for member functions, in order to 1217 // reserve a bit for differentiating between virtual and non-virtual member 1218 // functions. If the current target's C++ ABI requires this and this is a 1219 // member function, set its alignment accordingly. 1220 if (getTarget().getCXXABI().areMemberFunctionsAligned()) { 1221 if (F->getAlignment() < 2 && isa<CXXMethodDecl>(D)) 1222 F->setAlignment(2); 1223 } 1224 1225 // In the cross-dso CFI mode, we want !type attributes on definitions only. 1226 if (CodeGenOpts.SanitizeCfiCrossDso) 1227 if (auto *FD = dyn_cast<FunctionDecl>(D)) 1228 CreateFunctionTypeMetadata(FD, F); 1229 } 1230 1231 void CodeGenModule::SetCommonAttributes(const Decl *D, 1232 llvm::GlobalValue *GV) { 1233 if (const auto *ND = dyn_cast_or_null<NamedDecl>(D)) 1234 setGVProperties(GV, ND, ForDefinition); 1235 else 1236 GV->setVisibility(llvm::GlobalValue::DefaultVisibility); 1237 1238 if (D && D->hasAttr<UsedAttr>()) 1239 addUsedGlobal(GV); 1240 } 1241 1242 void CodeGenModule::setAliasAttributes(const Decl *D, 1243 llvm::GlobalValue *GV) { 1244 SetCommonAttributes(D, GV); 1245 1246 // Process the dllexport attribute based on whether the original definition 1247 // (not necessarily the aliasee) was exported. 1248 if (D->hasAttr<DLLExportAttr>()) 1249 GV->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass); 1250 } 1251 1252 void CodeGenModule::setNonAliasAttributes(const Decl *D, 1253 llvm::GlobalObject *GO) { 1254 SetCommonAttributes(D, GO); 1255 1256 if (D) { 1257 if (auto *GV = dyn_cast<llvm::GlobalVariable>(GO)) { 1258 if (auto *SA = D->getAttr<PragmaClangBSSSectionAttr>()) 1259 GV->addAttribute("bss-section", SA->getName()); 1260 if (auto *SA = D->getAttr<PragmaClangDataSectionAttr>()) 1261 GV->addAttribute("data-section", SA->getName()); 1262 if (auto *SA = D->getAttr<PragmaClangRodataSectionAttr>()) 1263 GV->addAttribute("rodata-section", SA->getName()); 1264 } 1265 1266 if (auto *F = dyn_cast<llvm::Function>(GO)) { 1267 if (auto *SA = D->getAttr<PragmaClangTextSectionAttr>()) 1268 if (!D->getAttr<SectionAttr>()) 1269 F->addFnAttr("implicit-section-name", SA->getName()); 1270 } 1271 1272 if (const SectionAttr *SA = D->getAttr<SectionAttr>()) 1273 GO->setSection(SA->getName()); 1274 } 1275 1276 getTargetCodeGenInfo().setTargetAttributes(D, GO, *this, ForDefinition); 1277 } 1278 1279 void CodeGenModule::SetInternalFunctionAttributes(const Decl *D, 1280 llvm::Function *F, 1281 const CGFunctionInfo &FI) { 1282 SetLLVMFunctionAttributes(D, FI, F); 1283 SetLLVMFunctionAttributesForDefinition(D, F); 1284 1285 F->setLinkage(llvm::Function::InternalLinkage); 1286 1287 setNonAliasAttributes(D, F); 1288 } 1289 1290 static void setLinkageForGV(llvm::GlobalValue *GV, 1291 const NamedDecl *ND) { 1292 // Set linkage and visibility in case we never see a definition. 1293 LinkageInfo LV = ND->getLinkageAndVisibility(); 1294 if (!isExternallyVisible(LV.getLinkage())) { 1295 // Don't set internal linkage on declarations. 1296 } else { 1297 if (ND->hasAttr<DLLImportAttr>()) { 1298 GV->setLinkage(llvm::GlobalValue::ExternalLinkage); 1299 GV->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass); 1300 } else if (ND->hasAttr<DLLExportAttr>()) { 1301 GV->setLinkage(llvm::GlobalValue::ExternalLinkage); 1302 } else if (ND->hasAttr<WeakAttr>() || ND->isWeakImported()) { 1303 // "extern_weak" is overloaded in LLVM; we probably should have 1304 // separate linkage types for this. 1305 GV->setLinkage(llvm::GlobalValue::ExternalWeakLinkage); 1306 } 1307 } 1308 } 1309 1310 void CodeGenModule::CreateFunctionTypeMetadata(const FunctionDecl *FD, 1311 llvm::Function *F) { 1312 // Only if we are checking indirect calls. 1313 if (!LangOpts.Sanitize.has(SanitizerKind::CFIICall)) 1314 return; 1315 1316 // Non-static class methods are handled via vtable pointer checks elsewhere. 1317 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic()) 1318 return; 1319 1320 // Additionally, if building with cross-DSO support... 1321 if (CodeGenOpts.SanitizeCfiCrossDso) { 1322 // Skip available_externally functions. They won't be codegen'ed in the 1323 // current module anyway. 1324 if (getContext().GetGVALinkageForFunction(FD) == GVA_AvailableExternally) 1325 return; 1326 } 1327 1328 llvm::Metadata *MD = CreateMetadataIdentifierForType(FD->getType()); 1329 F->addTypeMetadata(0, MD); 1330 F->addTypeMetadata(0, CreateMetadataIdentifierGeneralized(FD->getType())); 1331 1332 // Emit a hash-based bit set entry for cross-DSO calls. 1333 if (CodeGenOpts.SanitizeCfiCrossDso) 1334 if (auto CrossDsoTypeId = CreateCrossDsoCfiTypeId(MD)) 1335 F->addTypeMetadata(0, llvm::ConstantAsMetadata::get(CrossDsoTypeId)); 1336 } 1337 1338 void CodeGenModule::SetFunctionAttributes(GlobalDecl GD, llvm::Function *F, 1339 bool IsIncompleteFunction, 1340 bool IsThunk, 1341 ForDefinition_t IsForDefinition) { 1342 1343 if (llvm::Intrinsic::ID IID = F->getIntrinsicID()) { 1344 // If this is an intrinsic function, set the function's attributes 1345 // to the intrinsic's attributes. 1346 F->setAttributes(llvm::Intrinsic::getAttributes(getLLVMContext(), IID)); 1347 return; 1348 } 1349 1350 const auto *FD = cast<FunctionDecl>(GD.getDecl()); 1351 1352 if (!IsIncompleteFunction) { 1353 SetLLVMFunctionAttributes(FD, getTypes().arrangeGlobalDeclaration(GD), F); 1354 // Setup target-specific attributes. 1355 if (!IsForDefinition) 1356 getTargetCodeGenInfo().setTargetAttributes(FD, F, *this, 1357 NotForDefinition); 1358 } 1359 1360 // Add the Returned attribute for "this", except for iOS 5 and earlier 1361 // where substantial code, including the libstdc++ dylib, was compiled with 1362 // GCC and does not actually return "this". 1363 if (!IsThunk && getCXXABI().HasThisReturn(GD) && 1364 !(getTriple().isiOS() && getTriple().isOSVersionLT(6))) { 1365 assert(!F->arg_empty() && 1366 F->arg_begin()->getType() 1367 ->canLosslesslyBitCastTo(F->getReturnType()) && 1368 "unexpected this return"); 1369 F->addAttribute(1, llvm::Attribute::Returned); 1370 } 1371 1372 // Only a few attributes are set on declarations; these may later be 1373 // overridden by a definition. 1374 1375 setLinkageForGV(F, FD); 1376 setGVProperties(F, FD, NotForDefinition); 1377 1378 if (FD->getAttr<PragmaClangTextSectionAttr>()) { 1379 F->addFnAttr("implicit-section-name"); 1380 } 1381 1382 if (const SectionAttr *SA = FD->getAttr<SectionAttr>()) 1383 F->setSection(SA->getName()); 1384 1385 if (FD->isReplaceableGlobalAllocationFunction()) { 1386 // A replaceable global allocation function does not act like a builtin by 1387 // default, only if it is invoked by a new-expression or delete-expression. 1388 F->addAttribute(llvm::AttributeList::FunctionIndex, 1389 llvm::Attribute::NoBuiltin); 1390 1391 // A sane operator new returns a non-aliasing pointer. 1392 // FIXME: Also add NonNull attribute to the return value 1393 // for the non-nothrow forms? 1394 auto Kind = FD->getDeclName().getCXXOverloadedOperator(); 1395 if (getCodeGenOpts().AssumeSaneOperatorNew && 1396 (Kind == OO_New || Kind == OO_Array_New)) 1397 F->addAttribute(llvm::AttributeList::ReturnIndex, 1398 llvm::Attribute::NoAlias); 1399 } 1400 1401 if (isa<CXXConstructorDecl>(FD) || isa<CXXDestructorDecl>(FD)) 1402 F->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global); 1403 else if (const auto *MD = dyn_cast<CXXMethodDecl>(FD)) 1404 if (MD->isVirtual()) 1405 F->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global); 1406 1407 // Don't emit entries for function declarations in the cross-DSO mode. This 1408 // is handled with better precision by the receiving DSO. 1409 if (!CodeGenOpts.SanitizeCfiCrossDso) 1410 CreateFunctionTypeMetadata(FD, F); 1411 1412 if (getLangOpts().OpenMP && FD->hasAttr<OMPDeclareSimdDeclAttr>()) 1413 getOpenMPRuntime().emitDeclareSimdFunction(FD, F); 1414 } 1415 1416 void CodeGenModule::addUsedGlobal(llvm::GlobalValue *GV) { 1417 assert(!GV->isDeclaration() && 1418 "Only globals with definition can force usage."); 1419 LLVMUsed.emplace_back(GV); 1420 } 1421 1422 void CodeGenModule::addCompilerUsedGlobal(llvm::GlobalValue *GV) { 1423 assert(!GV->isDeclaration() && 1424 "Only globals with definition can force usage."); 1425 LLVMCompilerUsed.emplace_back(GV); 1426 } 1427 1428 static void emitUsed(CodeGenModule &CGM, StringRef Name, 1429 std::vector<llvm::WeakTrackingVH> &List) { 1430 // Don't create llvm.used if there is no need. 1431 if (List.empty()) 1432 return; 1433 1434 // Convert List to what ConstantArray needs. 1435 SmallVector<llvm::Constant*, 8> UsedArray; 1436 UsedArray.resize(List.size()); 1437 for (unsigned i = 0, e = List.size(); i != e; ++i) { 1438 UsedArray[i] = 1439 llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast( 1440 cast<llvm::Constant>(&*List[i]), CGM.Int8PtrTy); 1441 } 1442 1443 if (UsedArray.empty()) 1444 return; 1445 llvm::ArrayType *ATy = llvm::ArrayType::get(CGM.Int8PtrTy, UsedArray.size()); 1446 1447 auto *GV = new llvm::GlobalVariable( 1448 CGM.getModule(), ATy, false, llvm::GlobalValue::AppendingLinkage, 1449 llvm::ConstantArray::get(ATy, UsedArray), Name); 1450 1451 GV->setSection("llvm.metadata"); 1452 } 1453 1454 void CodeGenModule::emitLLVMUsed() { 1455 emitUsed(*this, "llvm.used", LLVMUsed); 1456 emitUsed(*this, "llvm.compiler.used", LLVMCompilerUsed); 1457 } 1458 1459 void CodeGenModule::AppendLinkerOptions(StringRef Opts) { 1460 auto *MDOpts = llvm::MDString::get(getLLVMContext(), Opts); 1461 LinkerOptionsMetadata.push_back(llvm::MDNode::get(getLLVMContext(), MDOpts)); 1462 } 1463 1464 void CodeGenModule::AddDetectMismatch(StringRef Name, StringRef Value) { 1465 llvm::SmallString<32> Opt; 1466 getTargetCodeGenInfo().getDetectMismatchOption(Name, Value, Opt); 1467 auto *MDOpts = llvm::MDString::get(getLLVMContext(), Opt); 1468 LinkerOptionsMetadata.push_back(llvm::MDNode::get(getLLVMContext(), MDOpts)); 1469 } 1470 1471 void CodeGenModule::AddDependentLib(StringRef Lib) { 1472 llvm::SmallString<24> Opt; 1473 getTargetCodeGenInfo().getDependentLibraryOption(Lib, Opt); 1474 auto *MDOpts = llvm::MDString::get(getLLVMContext(), Opt); 1475 LinkerOptionsMetadata.push_back(llvm::MDNode::get(getLLVMContext(), MDOpts)); 1476 } 1477 1478 /// \brief Add link options implied by the given module, including modules 1479 /// it depends on, using a postorder walk. 1480 static void addLinkOptionsPostorder(CodeGenModule &CGM, Module *Mod, 1481 SmallVectorImpl<llvm::MDNode *> &Metadata, 1482 llvm::SmallPtrSet<Module *, 16> &Visited) { 1483 // Import this module's parent. 1484 if (Mod->Parent && Visited.insert(Mod->Parent).second) { 1485 addLinkOptionsPostorder(CGM, Mod->Parent, Metadata, Visited); 1486 } 1487 1488 // Import this module's dependencies. 1489 for (unsigned I = Mod->Imports.size(); I > 0; --I) { 1490 if (Visited.insert(Mod->Imports[I - 1]).second) 1491 addLinkOptionsPostorder(CGM, Mod->Imports[I-1], Metadata, Visited); 1492 } 1493 1494 // Add linker options to link against the libraries/frameworks 1495 // described by this module. 1496 llvm::LLVMContext &Context = CGM.getLLVMContext(); 1497 for (unsigned I = Mod->LinkLibraries.size(); I > 0; --I) { 1498 // Link against a framework. Frameworks are currently Darwin only, so we 1499 // don't to ask TargetCodeGenInfo for the spelling of the linker option. 1500 if (Mod->LinkLibraries[I-1].IsFramework) { 1501 llvm::Metadata *Args[2] = { 1502 llvm::MDString::get(Context, "-framework"), 1503 llvm::MDString::get(Context, Mod->LinkLibraries[I - 1].Library)}; 1504 1505 Metadata.push_back(llvm::MDNode::get(Context, Args)); 1506 continue; 1507 } 1508 1509 // Link against a library. 1510 llvm::SmallString<24> Opt; 1511 CGM.getTargetCodeGenInfo().getDependentLibraryOption( 1512 Mod->LinkLibraries[I-1].Library, Opt); 1513 auto *OptString = llvm::MDString::get(Context, Opt); 1514 Metadata.push_back(llvm::MDNode::get(Context, OptString)); 1515 } 1516 } 1517 1518 void CodeGenModule::EmitModuleLinkOptions() { 1519 // Collect the set of all of the modules we want to visit to emit link 1520 // options, which is essentially the imported modules and all of their 1521 // non-explicit child modules. 1522 llvm::SetVector<clang::Module *> LinkModules; 1523 llvm::SmallPtrSet<clang::Module *, 16> Visited; 1524 SmallVector<clang::Module *, 16> Stack; 1525 1526 // Seed the stack with imported modules. 1527 for (Module *M : ImportedModules) { 1528 // Do not add any link flags when an implementation TU of a module imports 1529 // a header of that same module. 1530 if (M->getTopLevelModuleName() == getLangOpts().CurrentModule && 1531 !getLangOpts().isCompilingModule()) 1532 continue; 1533 if (Visited.insert(M).second) 1534 Stack.push_back(M); 1535 } 1536 1537 // Find all of the modules to import, making a little effort to prune 1538 // non-leaf modules. 1539 while (!Stack.empty()) { 1540 clang::Module *Mod = Stack.pop_back_val(); 1541 1542 bool AnyChildren = false; 1543 1544 // Visit the submodules of this module. 1545 for (clang::Module::submodule_iterator Sub = Mod->submodule_begin(), 1546 SubEnd = Mod->submodule_end(); 1547 Sub != SubEnd; ++Sub) { 1548 // Skip explicit children; they need to be explicitly imported to be 1549 // linked against. 1550 if ((*Sub)->IsExplicit) 1551 continue; 1552 1553 if (Visited.insert(*Sub).second) { 1554 Stack.push_back(*Sub); 1555 AnyChildren = true; 1556 } 1557 } 1558 1559 // We didn't find any children, so add this module to the list of 1560 // modules to link against. 1561 if (!AnyChildren) { 1562 LinkModules.insert(Mod); 1563 } 1564 } 1565 1566 // Add link options for all of the imported modules in reverse topological 1567 // order. We don't do anything to try to order import link flags with respect 1568 // to linker options inserted by things like #pragma comment(). 1569 SmallVector<llvm::MDNode *, 16> MetadataArgs; 1570 Visited.clear(); 1571 for (Module *M : LinkModules) 1572 if (Visited.insert(M).second) 1573 addLinkOptionsPostorder(*this, M, MetadataArgs, Visited); 1574 std::reverse(MetadataArgs.begin(), MetadataArgs.end()); 1575 LinkerOptionsMetadata.append(MetadataArgs.begin(), MetadataArgs.end()); 1576 1577 // Add the linker options metadata flag. 1578 auto *NMD = getModule().getOrInsertNamedMetadata("llvm.linker.options"); 1579 for (auto *MD : LinkerOptionsMetadata) 1580 NMD->addOperand(MD); 1581 } 1582 1583 void CodeGenModule::EmitDeferred() { 1584 // Emit code for any potentially referenced deferred decls. Since a 1585 // previously unused static decl may become used during the generation of code 1586 // for a static function, iterate until no changes are made. 1587 1588 if (!DeferredVTables.empty()) { 1589 EmitDeferredVTables(); 1590 1591 // Emitting a vtable doesn't directly cause more vtables to 1592 // become deferred, although it can cause functions to be 1593 // emitted that then need those vtables. 1594 assert(DeferredVTables.empty()); 1595 } 1596 1597 // Stop if we're out of both deferred vtables and deferred declarations. 1598 if (DeferredDeclsToEmit.empty()) 1599 return; 1600 1601 // Grab the list of decls to emit. If EmitGlobalDefinition schedules more 1602 // work, it will not interfere with this. 1603 std::vector<GlobalDecl> CurDeclsToEmit; 1604 CurDeclsToEmit.swap(DeferredDeclsToEmit); 1605 1606 for (GlobalDecl &D : CurDeclsToEmit) { 1607 // We should call GetAddrOfGlobal with IsForDefinition set to true in order 1608 // to get GlobalValue with exactly the type we need, not something that 1609 // might had been created for another decl with the same mangled name but 1610 // different type. 1611 llvm::GlobalValue *GV = dyn_cast<llvm::GlobalValue>( 1612 GetAddrOfGlobal(D, ForDefinition)); 1613 1614 // In case of different address spaces, we may still get a cast, even with 1615 // IsForDefinition equal to true. Query mangled names table to get 1616 // GlobalValue. 1617 if (!GV) 1618 GV = GetGlobalValue(getMangledName(D)); 1619 1620 // Make sure GetGlobalValue returned non-null. 1621 assert(GV); 1622 1623 // Check to see if we've already emitted this. This is necessary 1624 // for a couple of reasons: first, decls can end up in the 1625 // deferred-decls queue multiple times, and second, decls can end 1626 // up with definitions in unusual ways (e.g. by an extern inline 1627 // function acquiring a strong function redefinition). Just 1628 // ignore these cases. 1629 if (!GV->isDeclaration()) 1630 continue; 1631 1632 // Otherwise, emit the definition and move on to the next one. 1633 EmitGlobalDefinition(D, GV); 1634 1635 // If we found out that we need to emit more decls, do that recursively. 1636 // This has the advantage that the decls are emitted in a DFS and related 1637 // ones are close together, which is convenient for testing. 1638 if (!DeferredVTables.empty() || !DeferredDeclsToEmit.empty()) { 1639 EmitDeferred(); 1640 assert(DeferredVTables.empty() && DeferredDeclsToEmit.empty()); 1641 } 1642 } 1643 } 1644 1645 void CodeGenModule::EmitVTablesOpportunistically() { 1646 // Try to emit external vtables as available_externally if they have emitted 1647 // all inlined virtual functions. It runs after EmitDeferred() and therefore 1648 // is not allowed to create new references to things that need to be emitted 1649 // lazily. Note that it also uses fact that we eagerly emitting RTTI. 1650 1651 assert((OpportunisticVTables.empty() || shouldOpportunisticallyEmitVTables()) 1652 && "Only emit opportunistic vtables with optimizations"); 1653 1654 for (const CXXRecordDecl *RD : OpportunisticVTables) { 1655 assert(getVTables().isVTableExternal(RD) && 1656 "This queue should only contain external vtables"); 1657 if (getCXXABI().canSpeculativelyEmitVTable(RD)) 1658 VTables.GenerateClassData(RD); 1659 } 1660 OpportunisticVTables.clear(); 1661 } 1662 1663 void CodeGenModule::EmitGlobalAnnotations() { 1664 if (Annotations.empty()) 1665 return; 1666 1667 // Create a new global variable for the ConstantStruct in the Module. 1668 llvm::Constant *Array = llvm::ConstantArray::get(llvm::ArrayType::get( 1669 Annotations[0]->getType(), Annotations.size()), Annotations); 1670 auto *gv = new llvm::GlobalVariable(getModule(), Array->getType(), false, 1671 llvm::GlobalValue::AppendingLinkage, 1672 Array, "llvm.global.annotations"); 1673 gv->setSection(AnnotationSection); 1674 } 1675 1676 llvm::Constant *CodeGenModule::EmitAnnotationString(StringRef Str) { 1677 llvm::Constant *&AStr = AnnotationStrings[Str]; 1678 if (AStr) 1679 return AStr; 1680 1681 // Not found yet, create a new global. 1682 llvm::Constant *s = llvm::ConstantDataArray::getString(getLLVMContext(), Str); 1683 auto *gv = 1684 new llvm::GlobalVariable(getModule(), s->getType(), true, 1685 llvm::GlobalValue::PrivateLinkage, s, ".str"); 1686 gv->setSection(AnnotationSection); 1687 gv->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global); 1688 AStr = gv; 1689 return gv; 1690 } 1691 1692 llvm::Constant *CodeGenModule::EmitAnnotationUnit(SourceLocation Loc) { 1693 SourceManager &SM = getContext().getSourceManager(); 1694 PresumedLoc PLoc = SM.getPresumedLoc(Loc); 1695 if (PLoc.isValid()) 1696 return EmitAnnotationString(PLoc.getFilename()); 1697 return EmitAnnotationString(SM.getBufferName(Loc)); 1698 } 1699 1700 llvm::Constant *CodeGenModule::EmitAnnotationLineNo(SourceLocation L) { 1701 SourceManager &SM = getContext().getSourceManager(); 1702 PresumedLoc PLoc = SM.getPresumedLoc(L); 1703 unsigned LineNo = PLoc.isValid() ? PLoc.getLine() : 1704 SM.getExpansionLineNumber(L); 1705 return llvm::ConstantInt::get(Int32Ty, LineNo); 1706 } 1707 1708 llvm::Constant *CodeGenModule::EmitAnnotateAttr(llvm::GlobalValue *GV, 1709 const AnnotateAttr *AA, 1710 SourceLocation L) { 1711 // Get the globals for file name, annotation, and the line number. 1712 llvm::Constant *AnnoGV = EmitAnnotationString(AA->getAnnotation()), 1713 *UnitGV = EmitAnnotationUnit(L), 1714 *LineNoCst = EmitAnnotationLineNo(L); 1715 1716 // Create the ConstantStruct for the global annotation. 1717 llvm::Constant *Fields[4] = { 1718 llvm::ConstantExpr::getBitCast(GV, Int8PtrTy), 1719 llvm::ConstantExpr::getBitCast(AnnoGV, Int8PtrTy), 1720 llvm::ConstantExpr::getBitCast(UnitGV, Int8PtrTy), 1721 LineNoCst 1722 }; 1723 return llvm::ConstantStruct::getAnon(Fields); 1724 } 1725 1726 void CodeGenModule::AddGlobalAnnotations(const ValueDecl *D, 1727 llvm::GlobalValue *GV) { 1728 assert(D->hasAttr<AnnotateAttr>() && "no annotate attribute"); 1729 // Get the struct elements for these annotations. 1730 for (const auto *I : D->specific_attrs<AnnotateAttr>()) 1731 Annotations.push_back(EmitAnnotateAttr(GV, I, D->getLocation())); 1732 } 1733 1734 bool CodeGenModule::isInSanitizerBlacklist(SanitizerMask Kind, 1735 llvm::Function *Fn, 1736 SourceLocation Loc) const { 1737 const auto &SanitizerBL = getContext().getSanitizerBlacklist(); 1738 // Blacklist by function name. 1739 if (SanitizerBL.isBlacklistedFunction(Kind, Fn->getName())) 1740 return true; 1741 // Blacklist by location. 1742 if (Loc.isValid()) 1743 return SanitizerBL.isBlacklistedLocation(Kind, Loc); 1744 // If location is unknown, this may be a compiler-generated function. Assume 1745 // it's located in the main file. 1746 auto &SM = Context.getSourceManager(); 1747 if (const auto *MainFile = SM.getFileEntryForID(SM.getMainFileID())) { 1748 return SanitizerBL.isBlacklistedFile(Kind, MainFile->getName()); 1749 } 1750 return false; 1751 } 1752 1753 bool CodeGenModule::isInSanitizerBlacklist(llvm::GlobalVariable *GV, 1754 SourceLocation Loc, QualType Ty, 1755 StringRef Category) const { 1756 // For now globals can be blacklisted only in ASan and KASan. 1757 const SanitizerMask EnabledAsanMask = LangOpts.Sanitize.Mask & 1758 (SanitizerKind::Address | SanitizerKind::KernelAddress | SanitizerKind::HWAddress); 1759 if (!EnabledAsanMask) 1760 return false; 1761 const auto &SanitizerBL = getContext().getSanitizerBlacklist(); 1762 if (SanitizerBL.isBlacklistedGlobal(EnabledAsanMask, GV->getName(), Category)) 1763 return true; 1764 if (SanitizerBL.isBlacklistedLocation(EnabledAsanMask, Loc, Category)) 1765 return true; 1766 // Check global type. 1767 if (!Ty.isNull()) { 1768 // Drill down the array types: if global variable of a fixed type is 1769 // blacklisted, we also don't instrument arrays of them. 1770 while (auto AT = dyn_cast<ArrayType>(Ty.getTypePtr())) 1771 Ty = AT->getElementType(); 1772 Ty = Ty.getCanonicalType().getUnqualifiedType(); 1773 // We allow to blacklist only record types (classes, structs etc.) 1774 if (Ty->isRecordType()) { 1775 std::string TypeStr = Ty.getAsString(getContext().getPrintingPolicy()); 1776 if (SanitizerBL.isBlacklistedType(EnabledAsanMask, TypeStr, Category)) 1777 return true; 1778 } 1779 } 1780 return false; 1781 } 1782 1783 bool CodeGenModule::imbueXRayAttrs(llvm::Function *Fn, SourceLocation Loc, 1784 StringRef Category) const { 1785 if (!LangOpts.XRayInstrument) 1786 return false; 1787 const auto &XRayFilter = getContext().getXRayFilter(); 1788 using ImbueAttr = XRayFunctionFilter::ImbueAttribute; 1789 auto Attr = XRayFunctionFilter::ImbueAttribute::NONE; 1790 if (Loc.isValid()) 1791 Attr = XRayFilter.shouldImbueLocation(Loc, Category); 1792 if (Attr == ImbueAttr::NONE) 1793 Attr = XRayFilter.shouldImbueFunction(Fn->getName()); 1794 switch (Attr) { 1795 case ImbueAttr::NONE: 1796 return false; 1797 case ImbueAttr::ALWAYS: 1798 Fn->addFnAttr("function-instrument", "xray-always"); 1799 break; 1800 case ImbueAttr::ALWAYS_ARG1: 1801 Fn->addFnAttr("function-instrument", "xray-always"); 1802 Fn->addFnAttr("xray-log-args", "1"); 1803 break; 1804 case ImbueAttr::NEVER: 1805 Fn->addFnAttr("function-instrument", "xray-never"); 1806 break; 1807 } 1808 return true; 1809 } 1810 1811 bool CodeGenModule::MustBeEmitted(const ValueDecl *Global) { 1812 // Never defer when EmitAllDecls is specified. 1813 if (LangOpts.EmitAllDecls) 1814 return true; 1815 1816 return getContext().DeclMustBeEmitted(Global); 1817 } 1818 1819 bool CodeGenModule::MayBeEmittedEagerly(const ValueDecl *Global) { 1820 if (const auto *FD = dyn_cast<FunctionDecl>(Global)) 1821 if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation) 1822 // Implicit template instantiations may change linkage if they are later 1823 // explicitly instantiated, so they should not be emitted eagerly. 1824 return false; 1825 if (const auto *VD = dyn_cast<VarDecl>(Global)) 1826 if (Context.getInlineVariableDefinitionKind(VD) == 1827 ASTContext::InlineVariableDefinitionKind::WeakUnknown) 1828 // A definition of an inline constexpr static data member may change 1829 // linkage later if it's redeclared outside the class. 1830 return false; 1831 // If OpenMP is enabled and threadprivates must be generated like TLS, delay 1832 // codegen for global variables, because they may be marked as threadprivate. 1833 if (LangOpts.OpenMP && LangOpts.OpenMPUseTLS && 1834 getContext().getTargetInfo().isTLSSupported() && isa<VarDecl>(Global)) 1835 return false; 1836 1837 return true; 1838 } 1839 1840 ConstantAddress CodeGenModule::GetAddrOfUuidDescriptor( 1841 const CXXUuidofExpr* E) { 1842 // Sema has verified that IIDSource has a __declspec(uuid()), and that its 1843 // well-formed. 1844 StringRef Uuid = E->getUuidStr(); 1845 std::string Name = "_GUID_" + Uuid.lower(); 1846 std::replace(Name.begin(), Name.end(), '-', '_'); 1847 1848 // The UUID descriptor should be pointer aligned. 1849 CharUnits Alignment = CharUnits::fromQuantity(PointerAlignInBytes); 1850 1851 // Look for an existing global. 1852 if (llvm::GlobalVariable *GV = getModule().getNamedGlobal(Name)) 1853 return ConstantAddress(GV, Alignment); 1854 1855 llvm::Constant *Init = EmitUuidofInitializer(Uuid); 1856 assert(Init && "failed to initialize as constant"); 1857 1858 auto *GV = new llvm::GlobalVariable( 1859 getModule(), Init->getType(), 1860 /*isConstant=*/true, llvm::GlobalValue::LinkOnceODRLinkage, Init, Name); 1861 if (supportsCOMDAT()) 1862 GV->setComdat(TheModule.getOrInsertComdat(GV->getName())); 1863 return ConstantAddress(GV, Alignment); 1864 } 1865 1866 ConstantAddress CodeGenModule::GetWeakRefReference(const ValueDecl *VD) { 1867 const AliasAttr *AA = VD->getAttr<AliasAttr>(); 1868 assert(AA && "No alias?"); 1869 1870 CharUnits Alignment = getContext().getDeclAlign(VD); 1871 llvm::Type *DeclTy = getTypes().ConvertTypeForMem(VD->getType()); 1872 1873 // See if there is already something with the target's name in the module. 1874 llvm::GlobalValue *Entry = GetGlobalValue(AA->getAliasee()); 1875 if (Entry) { 1876 unsigned AS = getContext().getTargetAddressSpace(VD->getType()); 1877 auto Ptr = llvm::ConstantExpr::getBitCast(Entry, DeclTy->getPointerTo(AS)); 1878 return ConstantAddress(Ptr, Alignment); 1879 } 1880 1881 llvm::Constant *Aliasee; 1882 if (isa<llvm::FunctionType>(DeclTy)) 1883 Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy, 1884 GlobalDecl(cast<FunctionDecl>(VD)), 1885 /*ForVTable=*/false); 1886 else 1887 Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(), 1888 llvm::PointerType::getUnqual(DeclTy), 1889 nullptr); 1890 1891 auto *F = cast<llvm::GlobalValue>(Aliasee); 1892 F->setLinkage(llvm::Function::ExternalWeakLinkage); 1893 WeakRefReferences.insert(F); 1894 1895 return ConstantAddress(Aliasee, Alignment); 1896 } 1897 1898 void CodeGenModule::EmitGlobal(GlobalDecl GD) { 1899 const auto *Global = cast<ValueDecl>(GD.getDecl()); 1900 1901 // Weak references don't produce any output by themselves. 1902 if (Global->hasAttr<WeakRefAttr>()) 1903 return; 1904 1905 // If this is an alias definition (which otherwise looks like a declaration) 1906 // emit it now. 1907 if (Global->hasAttr<AliasAttr>()) 1908 return EmitAliasDefinition(GD); 1909 1910 // IFunc like an alias whose value is resolved at runtime by calling resolver. 1911 if (Global->hasAttr<IFuncAttr>()) 1912 return emitIFuncDefinition(GD); 1913 1914 // If this is CUDA, be selective about which declarations we emit. 1915 if (LangOpts.CUDA) { 1916 if (LangOpts.CUDAIsDevice) { 1917 if (!Global->hasAttr<CUDADeviceAttr>() && 1918 !Global->hasAttr<CUDAGlobalAttr>() && 1919 !Global->hasAttr<CUDAConstantAttr>() && 1920 !Global->hasAttr<CUDASharedAttr>()) 1921 return; 1922 } else { 1923 // We need to emit host-side 'shadows' for all global 1924 // device-side variables because the CUDA runtime needs their 1925 // size and host-side address in order to provide access to 1926 // their device-side incarnations. 1927 1928 // So device-only functions are the only things we skip. 1929 if (isa<FunctionDecl>(Global) && !Global->hasAttr<CUDAHostAttr>() && 1930 Global->hasAttr<CUDADeviceAttr>()) 1931 return; 1932 1933 assert((isa<FunctionDecl>(Global) || isa<VarDecl>(Global)) && 1934 "Expected Variable or Function"); 1935 } 1936 } 1937 1938 if (LangOpts.OpenMP) { 1939 // If this is OpenMP device, check if it is legal to emit this global 1940 // normally. 1941 if (OpenMPRuntime && OpenMPRuntime->emitTargetGlobal(GD)) 1942 return; 1943 if (auto *DRD = dyn_cast<OMPDeclareReductionDecl>(Global)) { 1944 if (MustBeEmitted(Global)) 1945 EmitOMPDeclareReduction(DRD); 1946 return; 1947 } 1948 } 1949 1950 // Ignore declarations, they will be emitted on their first use. 1951 if (const auto *FD = dyn_cast<FunctionDecl>(Global)) { 1952 // Forward declarations are emitted lazily on first use. 1953 if (!FD->doesThisDeclarationHaveABody()) { 1954 if (!FD->doesDeclarationForceExternallyVisibleDefinition()) 1955 return; 1956 1957 StringRef MangledName = getMangledName(GD); 1958 1959 // Compute the function info and LLVM type. 1960 const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD); 1961 llvm::Type *Ty = getTypes().GetFunctionType(FI); 1962 1963 GetOrCreateLLVMFunction(MangledName, Ty, GD, /*ForVTable=*/false, 1964 /*DontDefer=*/false); 1965 return; 1966 } 1967 } else { 1968 const auto *VD = cast<VarDecl>(Global); 1969 assert(VD->isFileVarDecl() && "Cannot emit local var decl as global."); 1970 // We need to emit device-side global CUDA variables even if a 1971 // variable does not have a definition -- we still need to define 1972 // host-side shadow for it. 1973 bool MustEmitForCuda = LangOpts.CUDA && !LangOpts.CUDAIsDevice && 1974 !VD->hasDefinition() && 1975 (VD->hasAttr<CUDAConstantAttr>() || 1976 VD->hasAttr<CUDADeviceAttr>()); 1977 if (!MustEmitForCuda && 1978 VD->isThisDeclarationADefinition() != VarDecl::Definition && 1979 !Context.isMSStaticDataMemberInlineDefinition(VD)) { 1980 // If this declaration may have caused an inline variable definition to 1981 // change linkage, make sure that it's emitted. 1982 if (Context.getInlineVariableDefinitionKind(VD) == 1983 ASTContext::InlineVariableDefinitionKind::Strong) 1984 GetAddrOfGlobalVar(VD); 1985 return; 1986 } 1987 } 1988 1989 // Defer code generation to first use when possible, e.g. if this is an inline 1990 // function. If the global must always be emitted, do it eagerly if possible 1991 // to benefit from cache locality. 1992 if (MustBeEmitted(Global) && MayBeEmittedEagerly(Global)) { 1993 // Emit the definition if it can't be deferred. 1994 EmitGlobalDefinition(GD); 1995 return; 1996 } 1997 1998 // If we're deferring emission of a C++ variable with an 1999 // initializer, remember the order in which it appeared in the file. 2000 if (getLangOpts().CPlusPlus && isa<VarDecl>(Global) && 2001 cast<VarDecl>(Global)->hasInit()) { 2002 DelayedCXXInitPosition[Global] = CXXGlobalInits.size(); 2003 CXXGlobalInits.push_back(nullptr); 2004 } 2005 2006 StringRef MangledName = getMangledName(GD); 2007 if (GetGlobalValue(MangledName) != nullptr) { 2008 // The value has already been used and should therefore be emitted. 2009 addDeferredDeclToEmit(GD); 2010 } else if (MustBeEmitted(Global)) { 2011 // The value must be emitted, but cannot be emitted eagerly. 2012 assert(!MayBeEmittedEagerly(Global)); 2013 addDeferredDeclToEmit(GD); 2014 } else { 2015 // Otherwise, remember that we saw a deferred decl with this name. The 2016 // first use of the mangled name will cause it to move into 2017 // DeferredDeclsToEmit. 2018 DeferredDecls[MangledName] = GD; 2019 } 2020 } 2021 2022 // Check if T is a class type with a destructor that's not dllimport. 2023 static bool HasNonDllImportDtor(QualType T) { 2024 if (const auto *RT = T->getBaseElementTypeUnsafe()->getAs<RecordType>()) 2025 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl())) 2026 if (RD->getDestructor() && !RD->getDestructor()->hasAttr<DLLImportAttr>()) 2027 return true; 2028 2029 return false; 2030 } 2031 2032 namespace { 2033 struct FunctionIsDirectlyRecursive : 2034 public RecursiveASTVisitor<FunctionIsDirectlyRecursive> { 2035 const StringRef Name; 2036 const Builtin::Context &BI; 2037 bool Result; 2038 FunctionIsDirectlyRecursive(StringRef N, const Builtin::Context &C) : 2039 Name(N), BI(C), Result(false) { 2040 } 2041 typedef RecursiveASTVisitor<FunctionIsDirectlyRecursive> Base; 2042 2043 bool TraverseCallExpr(CallExpr *E) { 2044 const FunctionDecl *FD = E->getDirectCallee(); 2045 if (!FD) 2046 return true; 2047 AsmLabelAttr *Attr = FD->getAttr<AsmLabelAttr>(); 2048 if (Attr && Name == Attr->getLabel()) { 2049 Result = true; 2050 return false; 2051 } 2052 unsigned BuiltinID = FD->getBuiltinID(); 2053 if (!BuiltinID || !BI.isLibFunction(BuiltinID)) 2054 return true; 2055 StringRef BuiltinName = BI.getName(BuiltinID); 2056 if (BuiltinName.startswith("__builtin_") && 2057 Name == BuiltinName.slice(strlen("__builtin_"), StringRef::npos)) { 2058 Result = true; 2059 return false; 2060 } 2061 return true; 2062 } 2063 }; 2064 2065 // Make sure we're not referencing non-imported vars or functions. 2066 struct DLLImportFunctionVisitor 2067 : public RecursiveASTVisitor<DLLImportFunctionVisitor> { 2068 bool SafeToInline = true; 2069 2070 bool shouldVisitImplicitCode() const { return true; } 2071 2072 bool VisitVarDecl(VarDecl *VD) { 2073 if (VD->getTLSKind()) { 2074 // A thread-local variable cannot be imported. 2075 SafeToInline = false; 2076 return SafeToInline; 2077 } 2078 2079 // A variable definition might imply a destructor call. 2080 if (VD->isThisDeclarationADefinition()) 2081 SafeToInline = !HasNonDllImportDtor(VD->getType()); 2082 2083 return SafeToInline; 2084 } 2085 2086 bool VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) { 2087 if (const auto *D = E->getTemporary()->getDestructor()) 2088 SafeToInline = D->hasAttr<DLLImportAttr>(); 2089 return SafeToInline; 2090 } 2091 2092 bool VisitDeclRefExpr(DeclRefExpr *E) { 2093 ValueDecl *VD = E->getDecl(); 2094 if (isa<FunctionDecl>(VD)) 2095 SafeToInline = VD->hasAttr<DLLImportAttr>(); 2096 else if (VarDecl *V = dyn_cast<VarDecl>(VD)) 2097 SafeToInline = !V->hasGlobalStorage() || V->hasAttr<DLLImportAttr>(); 2098 return SafeToInline; 2099 } 2100 2101 bool VisitCXXConstructExpr(CXXConstructExpr *E) { 2102 SafeToInline = E->getConstructor()->hasAttr<DLLImportAttr>(); 2103 return SafeToInline; 2104 } 2105 2106 bool VisitCXXMemberCallExpr(CXXMemberCallExpr *E) { 2107 CXXMethodDecl *M = E->getMethodDecl(); 2108 if (!M) { 2109 // Call through a pointer to member function. This is safe to inline. 2110 SafeToInline = true; 2111 } else { 2112 SafeToInline = M->hasAttr<DLLImportAttr>(); 2113 } 2114 return SafeToInline; 2115 } 2116 2117 bool VisitCXXDeleteExpr(CXXDeleteExpr *E) { 2118 SafeToInline = E->getOperatorDelete()->hasAttr<DLLImportAttr>(); 2119 return SafeToInline; 2120 } 2121 2122 bool VisitCXXNewExpr(CXXNewExpr *E) { 2123 SafeToInline = E->getOperatorNew()->hasAttr<DLLImportAttr>(); 2124 return SafeToInline; 2125 } 2126 }; 2127 } 2128 2129 // isTriviallyRecursive - Check if this function calls another 2130 // decl that, because of the asm attribute or the other decl being a builtin, 2131 // ends up pointing to itself. 2132 bool 2133 CodeGenModule::isTriviallyRecursive(const FunctionDecl *FD) { 2134 StringRef Name; 2135 if (getCXXABI().getMangleContext().shouldMangleDeclName(FD)) { 2136 // asm labels are a special kind of mangling we have to support. 2137 AsmLabelAttr *Attr = FD->getAttr<AsmLabelAttr>(); 2138 if (!Attr) 2139 return false; 2140 Name = Attr->getLabel(); 2141 } else { 2142 Name = FD->getName(); 2143 } 2144 2145 FunctionIsDirectlyRecursive Walker(Name, Context.BuiltinInfo); 2146 Walker.TraverseFunctionDecl(const_cast<FunctionDecl*>(FD)); 2147 return Walker.Result; 2148 } 2149 2150 bool CodeGenModule::shouldEmitFunction(GlobalDecl GD) { 2151 if (getFunctionLinkage(GD) != llvm::Function::AvailableExternallyLinkage) 2152 return true; 2153 const auto *F = cast<FunctionDecl>(GD.getDecl()); 2154 if (CodeGenOpts.OptimizationLevel == 0 && !F->hasAttr<AlwaysInlineAttr>()) 2155 return false; 2156 2157 if (F->hasAttr<DLLImportAttr>()) { 2158 // Check whether it would be safe to inline this dllimport function. 2159 DLLImportFunctionVisitor Visitor; 2160 Visitor.TraverseFunctionDecl(const_cast<FunctionDecl*>(F)); 2161 if (!Visitor.SafeToInline) 2162 return false; 2163 2164 if (const CXXDestructorDecl *Dtor = dyn_cast<CXXDestructorDecl>(F)) { 2165 // Implicit destructor invocations aren't captured in the AST, so the 2166 // check above can't see them. Check for them manually here. 2167 for (const Decl *Member : Dtor->getParent()->decls()) 2168 if (isa<FieldDecl>(Member)) 2169 if (HasNonDllImportDtor(cast<FieldDecl>(Member)->getType())) 2170 return false; 2171 for (const CXXBaseSpecifier &B : Dtor->getParent()->bases()) 2172 if (HasNonDllImportDtor(B.getType())) 2173 return false; 2174 } 2175 } 2176 2177 // PR9614. Avoid cases where the source code is lying to us. An available 2178 // externally function should have an equivalent function somewhere else, 2179 // but a function that calls itself is clearly not equivalent to the real 2180 // implementation. 2181 // This happens in glibc's btowc and in some configure checks. 2182 return !isTriviallyRecursive(F); 2183 } 2184 2185 bool CodeGenModule::shouldOpportunisticallyEmitVTables() { 2186 return CodeGenOpts.OptimizationLevel > 0; 2187 } 2188 2189 void CodeGenModule::EmitGlobalDefinition(GlobalDecl GD, llvm::GlobalValue *GV) { 2190 const auto *D = cast<ValueDecl>(GD.getDecl()); 2191 2192 PrettyStackTraceDecl CrashInfo(const_cast<ValueDecl *>(D), D->getLocation(), 2193 Context.getSourceManager(), 2194 "Generating code for declaration"); 2195 2196 if (isa<FunctionDecl>(D)) { 2197 // At -O0, don't generate IR for functions with available_externally 2198 // linkage. 2199 if (!shouldEmitFunction(GD)) 2200 return; 2201 2202 if (const auto *Method = dyn_cast<CXXMethodDecl>(D)) { 2203 // Make sure to emit the definition(s) before we emit the thunks. 2204 // This is necessary for the generation of certain thunks. 2205 if (const auto *CD = dyn_cast<CXXConstructorDecl>(Method)) 2206 ABI->emitCXXStructor(CD, getFromCtorType(GD.getCtorType())); 2207 else if (const auto *DD = dyn_cast<CXXDestructorDecl>(Method)) 2208 ABI->emitCXXStructor(DD, getFromDtorType(GD.getDtorType())); 2209 else 2210 EmitGlobalFunctionDefinition(GD, GV); 2211 2212 if (Method->isVirtual()) 2213 getVTables().EmitThunks(GD); 2214 2215 return; 2216 } 2217 2218 return EmitGlobalFunctionDefinition(GD, GV); 2219 } 2220 2221 if (const auto *VD = dyn_cast<VarDecl>(D)) 2222 return EmitGlobalVarDefinition(VD, !VD->hasDefinition()); 2223 2224 llvm_unreachable("Invalid argument to EmitGlobalDefinition()"); 2225 } 2226 2227 static void ReplaceUsesOfNonProtoTypeWithRealFunction(llvm::GlobalValue *Old, 2228 llvm::Function *NewFn); 2229 2230 void CodeGenModule::emitMultiVersionFunctions() { 2231 for (GlobalDecl GD : MultiVersionFuncs) { 2232 SmallVector<CodeGenFunction::MultiVersionResolverOption, 10> Options; 2233 const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl()); 2234 getContext().forEachMultiversionedFunctionVersion( 2235 FD, [this, &GD, &Options](const FunctionDecl *CurFD) { 2236 GlobalDecl CurGD{ 2237 (CurFD->isDefined() ? CurFD->getDefinition() : CurFD)}; 2238 StringRef MangledName = getMangledName(CurGD); 2239 llvm::Constant *Func = GetGlobalValue(MangledName); 2240 if (!Func) { 2241 if (CurFD->isDefined()) { 2242 EmitGlobalFunctionDefinition(CurGD, nullptr); 2243 Func = GetGlobalValue(MangledName); 2244 } else { 2245 const CGFunctionInfo &FI = 2246 getTypes().arrangeGlobalDeclaration(GD); 2247 llvm::FunctionType *Ty = getTypes().GetFunctionType(FI); 2248 Func = GetAddrOfFunction(CurGD, Ty, /*ForVTable=*/false, 2249 /*DontDefer=*/false, ForDefinition); 2250 } 2251 assert(Func && "This should have just been created"); 2252 } 2253 Options.emplace_back(getTarget(), cast<llvm::Function>(Func), 2254 CurFD->getAttr<TargetAttr>()->parse()); 2255 }); 2256 2257 llvm::Function *ResolverFunc = cast<llvm::Function>( 2258 GetGlobalValue((getMangledName(GD) + ".resolver").str())); 2259 if (supportsCOMDAT()) 2260 ResolverFunc->setComdat( 2261 getModule().getOrInsertComdat(ResolverFunc->getName())); 2262 std::stable_sort( 2263 Options.begin(), Options.end(), 2264 std::greater<CodeGenFunction::MultiVersionResolverOption>()); 2265 CodeGenFunction CGF(*this); 2266 CGF.EmitMultiVersionResolver(ResolverFunc, Options); 2267 } 2268 } 2269 2270 /// If an ifunc for the specified mangled name is not in the module, create and 2271 /// return an llvm IFunc Function with the specified type. 2272 llvm::Constant * 2273 CodeGenModule::GetOrCreateMultiVersionIFunc(GlobalDecl GD, llvm::Type *DeclTy, 2274 StringRef MangledName, 2275 const FunctionDecl *FD) { 2276 std::string IFuncName = (MangledName + ".ifunc").str(); 2277 if (llvm::GlobalValue *IFuncGV = GetGlobalValue(IFuncName)) 2278 return IFuncGV; 2279 2280 // Since this is the first time we've created this IFunc, make sure 2281 // that we put this multiversioned function into the list to be 2282 // replaced later. 2283 MultiVersionFuncs.push_back(GD); 2284 2285 std::string ResolverName = (MangledName + ".resolver").str(); 2286 llvm::Type *ResolverType = llvm::FunctionType::get( 2287 llvm::PointerType::get(DeclTy, 2288 Context.getTargetAddressSpace(FD->getType())), 2289 false); 2290 llvm::Constant *Resolver = 2291 GetOrCreateLLVMFunction(ResolverName, ResolverType, GlobalDecl{}, 2292 /*ForVTable=*/false); 2293 llvm::GlobalIFunc *GIF = llvm::GlobalIFunc::create( 2294 DeclTy, 0, llvm::Function::ExternalLinkage, "", Resolver, &getModule()); 2295 GIF->setName(IFuncName); 2296 SetCommonAttributes(FD, GIF); 2297 2298 return GIF; 2299 } 2300 2301 /// GetOrCreateLLVMFunction - If the specified mangled name is not in the 2302 /// module, create and return an llvm Function with the specified type. If there 2303 /// is something in the module with the specified name, return it potentially 2304 /// bitcasted to the right type. 2305 /// 2306 /// If D is non-null, it specifies a decl that correspond to this. This is used 2307 /// to set the attributes on the function when it is first created. 2308 llvm::Constant *CodeGenModule::GetOrCreateLLVMFunction( 2309 StringRef MangledName, llvm::Type *Ty, GlobalDecl GD, bool ForVTable, 2310 bool DontDefer, bool IsThunk, llvm::AttributeList ExtraAttrs, 2311 ForDefinition_t IsForDefinition) { 2312 const Decl *D = GD.getDecl(); 2313 2314 // Any attempts to use a MultiVersion function should result in retrieving 2315 // the iFunc instead. Name Mangling will handle the rest of the changes. 2316 if (const FunctionDecl *FD = cast_or_null<FunctionDecl>(D)) { 2317 if (FD->isMultiVersion() && FD->getAttr<TargetAttr>()->isDefaultVersion()) { 2318 UpdateMultiVersionNames(GD, FD); 2319 if (!IsForDefinition) 2320 return GetOrCreateMultiVersionIFunc(GD, Ty, MangledName, FD); 2321 } 2322 } 2323 2324 // Lookup the entry, lazily creating it if necessary. 2325 llvm::GlobalValue *Entry = GetGlobalValue(MangledName); 2326 if (Entry) { 2327 if (WeakRefReferences.erase(Entry)) { 2328 const FunctionDecl *FD = cast_or_null<FunctionDecl>(D); 2329 if (FD && !FD->hasAttr<WeakAttr>()) 2330 Entry->setLinkage(llvm::Function::ExternalLinkage); 2331 } 2332 2333 // Handle dropped DLL attributes. 2334 if (D && !D->hasAttr<DLLImportAttr>() && !D->hasAttr<DLLExportAttr>()) 2335 Entry->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass); 2336 2337 // If there are two attempts to define the same mangled name, issue an 2338 // error. 2339 if (IsForDefinition && !Entry->isDeclaration()) { 2340 GlobalDecl OtherGD; 2341 // Check that GD is not yet in DiagnosedConflictingDefinitions is required 2342 // to make sure that we issue an error only once. 2343 if (lookupRepresentativeDecl(MangledName, OtherGD) && 2344 (GD.getCanonicalDecl().getDecl() != 2345 OtherGD.getCanonicalDecl().getDecl()) && 2346 DiagnosedConflictingDefinitions.insert(GD).second) { 2347 getDiags().Report(D->getLocation(), 2348 diag::err_duplicate_mangled_name); 2349 getDiags().Report(OtherGD.getDecl()->getLocation(), 2350 diag::note_previous_definition); 2351 } 2352 } 2353 2354 if ((isa<llvm::Function>(Entry) || isa<llvm::GlobalAlias>(Entry)) && 2355 (Entry->getType()->getElementType() == Ty)) { 2356 return Entry; 2357 } 2358 2359 // Make sure the result is of the correct type. 2360 // (If function is requested for a definition, we always need to create a new 2361 // function, not just return a bitcast.) 2362 if (!IsForDefinition) 2363 return llvm::ConstantExpr::getBitCast(Entry, Ty->getPointerTo()); 2364 } 2365 2366 // This function doesn't have a complete type (for example, the return 2367 // type is an incomplete struct). Use a fake type instead, and make 2368 // sure not to try to set attributes. 2369 bool IsIncompleteFunction = false; 2370 2371 llvm::FunctionType *FTy; 2372 if (isa<llvm::FunctionType>(Ty)) { 2373 FTy = cast<llvm::FunctionType>(Ty); 2374 } else { 2375 FTy = llvm::FunctionType::get(VoidTy, false); 2376 IsIncompleteFunction = true; 2377 } 2378 2379 llvm::Function *F = 2380 llvm::Function::Create(FTy, llvm::Function::ExternalLinkage, 2381 Entry ? StringRef() : MangledName, &getModule()); 2382 2383 // If we already created a function with the same mangled name (but different 2384 // type) before, take its name and add it to the list of functions to be 2385 // replaced with F at the end of CodeGen. 2386 // 2387 // This happens if there is a prototype for a function (e.g. "int f()") and 2388 // then a definition of a different type (e.g. "int f(int x)"). 2389 if (Entry) { 2390 F->takeName(Entry); 2391 2392 // This might be an implementation of a function without a prototype, in 2393 // which case, try to do special replacement of calls which match the new 2394 // prototype. The really key thing here is that we also potentially drop 2395 // arguments from the call site so as to make a direct call, which makes the 2396 // inliner happier and suppresses a number of optimizer warnings (!) about 2397 // dropping arguments. 2398 if (!Entry->use_empty()) { 2399 ReplaceUsesOfNonProtoTypeWithRealFunction(Entry, F); 2400 Entry->removeDeadConstantUsers(); 2401 } 2402 2403 llvm::Constant *BC = llvm::ConstantExpr::getBitCast( 2404 F, Entry->getType()->getElementType()->getPointerTo()); 2405 addGlobalValReplacement(Entry, BC); 2406 } 2407 2408 assert(F->getName() == MangledName && "name was uniqued!"); 2409 if (D) 2410 SetFunctionAttributes(GD, F, IsIncompleteFunction, IsThunk, 2411 IsForDefinition); 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, NotForDefinition); 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, ForDefinition); 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, ForDefinition); 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 AddDependentLib(PCD->getArg()); 4390 break; 4391 case PCK_Compiler: 4392 case PCK_ExeStr: 4393 case PCK_User: 4394 break; // We ignore all of these. 4395 } 4396 break; 4397 } 4398 4399 case Decl::PragmaDetectMismatch: { 4400 const auto *PDMD = cast<PragmaDetectMismatchDecl>(D); 4401 AddDetectMismatch(PDMD->getName(), PDMD->getValue()); 4402 break; 4403 } 4404 4405 case Decl::LinkageSpec: 4406 EmitLinkageSpec(cast<LinkageSpecDecl>(D)); 4407 break; 4408 4409 case Decl::FileScopeAsm: { 4410 // File-scope asm is ignored during device-side CUDA compilation. 4411 if (LangOpts.CUDA && LangOpts.CUDAIsDevice) 4412 break; 4413 // File-scope asm is ignored during device-side OpenMP compilation. 4414 if (LangOpts.OpenMPIsDevice) 4415 break; 4416 auto *AD = cast<FileScopeAsmDecl>(D); 4417 getModule().appendModuleInlineAsm(AD->getAsmString()->getString()); 4418 break; 4419 } 4420 4421 case Decl::Import: { 4422 auto *Import = cast<ImportDecl>(D); 4423 4424 // If we've already imported this module, we're done. 4425 if (!ImportedModules.insert(Import->getImportedModule())) 4426 break; 4427 4428 // Emit debug information for direct imports. 4429 if (!Import->getImportedOwningModule()) { 4430 if (CGDebugInfo *DI = getModuleDebugInfo()) 4431 DI->EmitImportDecl(*Import); 4432 } 4433 4434 // Find all of the submodules and emit the module initializers. 4435 llvm::SmallPtrSet<clang::Module *, 16> Visited; 4436 SmallVector<clang::Module *, 16> Stack; 4437 Visited.insert(Import->getImportedModule()); 4438 Stack.push_back(Import->getImportedModule()); 4439 4440 while (!Stack.empty()) { 4441 clang::Module *Mod = Stack.pop_back_val(); 4442 if (!EmittedModuleInitializers.insert(Mod).second) 4443 continue; 4444 4445 for (auto *D : Context.getModuleInitializers(Mod)) 4446 EmitTopLevelDecl(D); 4447 4448 // Visit the submodules of this module. 4449 for (clang::Module::submodule_iterator Sub = Mod->submodule_begin(), 4450 SubEnd = Mod->submodule_end(); 4451 Sub != SubEnd; ++Sub) { 4452 // Skip explicit children; they need to be explicitly imported to emit 4453 // the initializers. 4454 if ((*Sub)->IsExplicit) 4455 continue; 4456 4457 if (Visited.insert(*Sub).second) 4458 Stack.push_back(*Sub); 4459 } 4460 } 4461 break; 4462 } 4463 4464 case Decl::Export: 4465 EmitDeclContext(cast<ExportDecl>(D)); 4466 break; 4467 4468 case Decl::OMPThreadPrivate: 4469 EmitOMPThreadPrivateDecl(cast<OMPThreadPrivateDecl>(D)); 4470 break; 4471 4472 case Decl::OMPDeclareReduction: 4473 EmitOMPDeclareReduction(cast<OMPDeclareReductionDecl>(D)); 4474 break; 4475 4476 default: 4477 // Make sure we handled everything we should, every other kind is a 4478 // non-top-level decl. FIXME: Would be nice to have an isTopLevelDeclKind 4479 // function. Need to recode Decl::Kind to do that easily. 4480 assert(isa<TypeDecl>(D) && "Unsupported decl kind"); 4481 break; 4482 } 4483 } 4484 4485 void CodeGenModule::AddDeferredUnusedCoverageMapping(Decl *D) { 4486 // Do we need to generate coverage mapping? 4487 if (!CodeGenOpts.CoverageMapping) 4488 return; 4489 switch (D->getKind()) { 4490 case Decl::CXXConversion: 4491 case Decl::CXXMethod: 4492 case Decl::Function: 4493 case Decl::ObjCMethod: 4494 case Decl::CXXConstructor: 4495 case Decl::CXXDestructor: { 4496 if (!cast<FunctionDecl>(D)->doesThisDeclarationHaveABody()) 4497 return; 4498 SourceManager &SM = getContext().getSourceManager(); 4499 if (LimitedCoverage && SM.getMainFileID() != SM.getFileID(D->getLocStart())) 4500 return; 4501 auto I = DeferredEmptyCoverageMappingDecls.find(D); 4502 if (I == DeferredEmptyCoverageMappingDecls.end()) 4503 DeferredEmptyCoverageMappingDecls[D] = true; 4504 break; 4505 } 4506 default: 4507 break; 4508 }; 4509 } 4510 4511 void CodeGenModule::ClearUnusedCoverageMapping(const Decl *D) { 4512 // Do we need to generate coverage mapping? 4513 if (!CodeGenOpts.CoverageMapping) 4514 return; 4515 if (const auto *Fn = dyn_cast<FunctionDecl>(D)) { 4516 if (Fn->isTemplateInstantiation()) 4517 ClearUnusedCoverageMapping(Fn->getTemplateInstantiationPattern()); 4518 } 4519 auto I = DeferredEmptyCoverageMappingDecls.find(D); 4520 if (I == DeferredEmptyCoverageMappingDecls.end()) 4521 DeferredEmptyCoverageMappingDecls[D] = false; 4522 else 4523 I->second = false; 4524 } 4525 4526 void CodeGenModule::EmitDeferredUnusedCoverageMappings() { 4527 // We call takeVector() here to avoid use-after-free. 4528 // FIXME: DeferredEmptyCoverageMappingDecls is getting mutated because 4529 // we deserialize function bodies to emit coverage info for them, and that 4530 // deserializes more declarations. How should we handle that case? 4531 for (const auto &Entry : DeferredEmptyCoverageMappingDecls.takeVector()) { 4532 if (!Entry.second) 4533 continue; 4534 const Decl *D = Entry.first; 4535 switch (D->getKind()) { 4536 case Decl::CXXConversion: 4537 case Decl::CXXMethod: 4538 case Decl::Function: 4539 case Decl::ObjCMethod: { 4540 CodeGenPGO PGO(*this); 4541 GlobalDecl GD(cast<FunctionDecl>(D)); 4542 PGO.emitEmptyCounterMapping(D, getMangledName(GD), 4543 getFunctionLinkage(GD)); 4544 break; 4545 } 4546 case Decl::CXXConstructor: { 4547 CodeGenPGO PGO(*this); 4548 GlobalDecl GD(cast<CXXConstructorDecl>(D), Ctor_Base); 4549 PGO.emitEmptyCounterMapping(D, getMangledName(GD), 4550 getFunctionLinkage(GD)); 4551 break; 4552 } 4553 case Decl::CXXDestructor: { 4554 CodeGenPGO PGO(*this); 4555 GlobalDecl GD(cast<CXXDestructorDecl>(D), Dtor_Base); 4556 PGO.emitEmptyCounterMapping(D, getMangledName(GD), 4557 getFunctionLinkage(GD)); 4558 break; 4559 } 4560 default: 4561 break; 4562 }; 4563 } 4564 } 4565 4566 /// Turns the given pointer into a constant. 4567 static llvm::Constant *GetPointerConstant(llvm::LLVMContext &Context, 4568 const void *Ptr) { 4569 uintptr_t PtrInt = reinterpret_cast<uintptr_t>(Ptr); 4570 llvm::Type *i64 = llvm::Type::getInt64Ty(Context); 4571 return llvm::ConstantInt::get(i64, PtrInt); 4572 } 4573 4574 static void EmitGlobalDeclMetadata(CodeGenModule &CGM, 4575 llvm::NamedMDNode *&GlobalMetadata, 4576 GlobalDecl D, 4577 llvm::GlobalValue *Addr) { 4578 if (!GlobalMetadata) 4579 GlobalMetadata = 4580 CGM.getModule().getOrInsertNamedMetadata("clang.global.decl.ptrs"); 4581 4582 // TODO: should we report variant information for ctors/dtors? 4583 llvm::Metadata *Ops[] = {llvm::ConstantAsMetadata::get(Addr), 4584 llvm::ConstantAsMetadata::get(GetPointerConstant( 4585 CGM.getLLVMContext(), D.getDecl()))}; 4586 GlobalMetadata->addOperand(llvm::MDNode::get(CGM.getLLVMContext(), Ops)); 4587 } 4588 4589 /// For each function which is declared within an extern "C" region and marked 4590 /// as 'used', but has internal linkage, create an alias from the unmangled 4591 /// name to the mangled name if possible. People expect to be able to refer 4592 /// to such functions with an unmangled name from inline assembly within the 4593 /// same translation unit. 4594 void CodeGenModule::EmitStaticExternCAliases() { 4595 // Don't do anything if we're generating CUDA device code -- the NVPTX 4596 // assembly target doesn't support aliases. 4597 if (Context.getTargetInfo().getTriple().isNVPTX()) 4598 return; 4599 for (auto &I : StaticExternCValues) { 4600 IdentifierInfo *Name = I.first; 4601 llvm::GlobalValue *Val = I.second; 4602 if (Val && !getModule().getNamedValue(Name->getName())) 4603 addUsedGlobal(llvm::GlobalAlias::create(Name->getName(), Val)); 4604 } 4605 } 4606 4607 bool CodeGenModule::lookupRepresentativeDecl(StringRef MangledName, 4608 GlobalDecl &Result) const { 4609 auto Res = Manglings.find(MangledName); 4610 if (Res == Manglings.end()) 4611 return false; 4612 Result = Res->getValue(); 4613 return true; 4614 } 4615 4616 /// Emits metadata nodes associating all the global values in the 4617 /// current module with the Decls they came from. This is useful for 4618 /// projects using IR gen as a subroutine. 4619 /// 4620 /// Since there's currently no way to associate an MDNode directly 4621 /// with an llvm::GlobalValue, we create a global named metadata 4622 /// with the name 'clang.global.decl.ptrs'. 4623 void CodeGenModule::EmitDeclMetadata() { 4624 llvm::NamedMDNode *GlobalMetadata = nullptr; 4625 4626 for (auto &I : MangledDeclNames) { 4627 llvm::GlobalValue *Addr = getModule().getNamedValue(I.second); 4628 // Some mangled names don't necessarily have an associated GlobalValue 4629 // in this module, e.g. if we mangled it for DebugInfo. 4630 if (Addr) 4631 EmitGlobalDeclMetadata(*this, GlobalMetadata, I.first, Addr); 4632 } 4633 } 4634 4635 /// Emits metadata nodes for all the local variables in the current 4636 /// function. 4637 void CodeGenFunction::EmitDeclMetadata() { 4638 if (LocalDeclMap.empty()) return; 4639 4640 llvm::LLVMContext &Context = getLLVMContext(); 4641 4642 // Find the unique metadata ID for this name. 4643 unsigned DeclPtrKind = Context.getMDKindID("clang.decl.ptr"); 4644 4645 llvm::NamedMDNode *GlobalMetadata = nullptr; 4646 4647 for (auto &I : LocalDeclMap) { 4648 const Decl *D = I.first; 4649 llvm::Value *Addr = I.second.getPointer(); 4650 if (auto *Alloca = dyn_cast<llvm::AllocaInst>(Addr)) { 4651 llvm::Value *DAddr = GetPointerConstant(getLLVMContext(), D); 4652 Alloca->setMetadata( 4653 DeclPtrKind, llvm::MDNode::get( 4654 Context, llvm::ValueAsMetadata::getConstant(DAddr))); 4655 } else if (auto *GV = dyn_cast<llvm::GlobalValue>(Addr)) { 4656 GlobalDecl GD = GlobalDecl(cast<VarDecl>(D)); 4657 EmitGlobalDeclMetadata(CGM, GlobalMetadata, GD, GV); 4658 } 4659 } 4660 } 4661 4662 void CodeGenModule::EmitVersionIdentMetadata() { 4663 llvm::NamedMDNode *IdentMetadata = 4664 TheModule.getOrInsertNamedMetadata("llvm.ident"); 4665 std::string Version = getClangFullVersion(); 4666 llvm::LLVMContext &Ctx = TheModule.getContext(); 4667 4668 llvm::Metadata *IdentNode[] = {llvm::MDString::get(Ctx, Version)}; 4669 IdentMetadata->addOperand(llvm::MDNode::get(Ctx, IdentNode)); 4670 } 4671 4672 void CodeGenModule::EmitTargetMetadata() { 4673 // Warning, new MangledDeclNames may be appended within this loop. 4674 // We rely on MapVector insertions adding new elements to the end 4675 // of the container. 4676 // FIXME: Move this loop into the one target that needs it, and only 4677 // loop over those declarations for which we couldn't emit the target 4678 // metadata when we emitted the declaration. 4679 for (unsigned I = 0; I != MangledDeclNames.size(); ++I) { 4680 auto Val = *(MangledDeclNames.begin() + I); 4681 const Decl *D = Val.first.getDecl()->getMostRecentDecl(); 4682 llvm::GlobalValue *GV = GetGlobalValue(Val.second); 4683 getTargetCodeGenInfo().emitTargetMD(D, GV, *this); 4684 } 4685 } 4686 4687 void CodeGenModule::EmitCoverageFile() { 4688 if (getCodeGenOpts().CoverageDataFile.empty() && 4689 getCodeGenOpts().CoverageNotesFile.empty()) 4690 return; 4691 4692 llvm::NamedMDNode *CUNode = TheModule.getNamedMetadata("llvm.dbg.cu"); 4693 if (!CUNode) 4694 return; 4695 4696 llvm::NamedMDNode *GCov = TheModule.getOrInsertNamedMetadata("llvm.gcov"); 4697 llvm::LLVMContext &Ctx = TheModule.getContext(); 4698 auto *CoverageDataFile = 4699 llvm::MDString::get(Ctx, getCodeGenOpts().CoverageDataFile); 4700 auto *CoverageNotesFile = 4701 llvm::MDString::get(Ctx, getCodeGenOpts().CoverageNotesFile); 4702 for (int i = 0, e = CUNode->getNumOperands(); i != e; ++i) { 4703 llvm::MDNode *CU = CUNode->getOperand(i); 4704 llvm::Metadata *Elts[] = {CoverageNotesFile, CoverageDataFile, CU}; 4705 GCov->addOperand(llvm::MDNode::get(Ctx, Elts)); 4706 } 4707 } 4708 4709 llvm::Constant *CodeGenModule::EmitUuidofInitializer(StringRef Uuid) { 4710 // Sema has checked that all uuid strings are of the form 4711 // "12345678-1234-1234-1234-1234567890ab". 4712 assert(Uuid.size() == 36); 4713 for (unsigned i = 0; i < 36; ++i) { 4714 if (i == 8 || i == 13 || i == 18 || i == 23) assert(Uuid[i] == '-'); 4715 else assert(isHexDigit(Uuid[i])); 4716 } 4717 4718 // The starts of all bytes of Field3 in Uuid. Field 3 is "1234-1234567890ab". 4719 const unsigned Field3ValueOffsets[8] = { 19, 21, 24, 26, 28, 30, 32, 34 }; 4720 4721 llvm::Constant *Field3[8]; 4722 for (unsigned Idx = 0; Idx < 8; ++Idx) 4723 Field3[Idx] = llvm::ConstantInt::get( 4724 Int8Ty, Uuid.substr(Field3ValueOffsets[Idx], 2), 16); 4725 4726 llvm::Constant *Fields[4] = { 4727 llvm::ConstantInt::get(Int32Ty, Uuid.substr(0, 8), 16), 4728 llvm::ConstantInt::get(Int16Ty, Uuid.substr(9, 4), 16), 4729 llvm::ConstantInt::get(Int16Ty, Uuid.substr(14, 4), 16), 4730 llvm::ConstantArray::get(llvm::ArrayType::get(Int8Ty, 8), Field3) 4731 }; 4732 4733 return llvm::ConstantStruct::getAnon(Fields); 4734 } 4735 4736 llvm::Constant *CodeGenModule::GetAddrOfRTTIDescriptor(QualType Ty, 4737 bool ForEH) { 4738 // Return a bogus pointer if RTTI is disabled, unless it's for EH. 4739 // FIXME: should we even be calling this method if RTTI is disabled 4740 // and it's not for EH? 4741 if (!ForEH && !getLangOpts().RTTI) 4742 return llvm::Constant::getNullValue(Int8PtrTy); 4743 4744 if (ForEH && Ty->isObjCObjectPointerType() && 4745 LangOpts.ObjCRuntime.isGNUFamily()) 4746 return ObjCRuntime->GetEHType(Ty); 4747 4748 return getCXXABI().getAddrOfRTTIDescriptor(Ty); 4749 } 4750 4751 void CodeGenModule::EmitOMPThreadPrivateDecl(const OMPThreadPrivateDecl *D) { 4752 // Do not emit threadprivates in simd-only mode. 4753 if (LangOpts.OpenMP && LangOpts.OpenMPSimd) 4754 return; 4755 for (auto RefExpr : D->varlists()) { 4756 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(RefExpr)->getDecl()); 4757 bool PerformInit = 4758 VD->getAnyInitializer() && 4759 !VD->getAnyInitializer()->isConstantInitializer(getContext(), 4760 /*ForRef=*/false); 4761 4762 Address Addr(GetAddrOfGlobalVar(VD), getContext().getDeclAlign(VD)); 4763 if (auto InitFunction = getOpenMPRuntime().emitThreadPrivateVarDefinition( 4764 VD, Addr, RefExpr->getLocStart(), PerformInit)) 4765 CXXGlobalInits.push_back(InitFunction); 4766 } 4767 } 4768 4769 llvm::Metadata *CodeGenModule::CreateMetadataIdentifierForType(QualType T) { 4770 llvm::Metadata *&InternalId = MetadataIdMap[T.getCanonicalType()]; 4771 if (InternalId) 4772 return InternalId; 4773 4774 if (isExternallyVisible(T->getLinkage())) { 4775 std::string OutName; 4776 llvm::raw_string_ostream Out(OutName); 4777 getCXXABI().getMangleContext().mangleTypeName(T, Out); 4778 4779 InternalId = llvm::MDString::get(getLLVMContext(), Out.str()); 4780 } else { 4781 InternalId = llvm::MDNode::getDistinct(getLLVMContext(), 4782 llvm::ArrayRef<llvm::Metadata *>()); 4783 } 4784 4785 return InternalId; 4786 } 4787 4788 // Generalize pointer types to a void pointer with the qualifiers of the 4789 // originally pointed-to type, e.g. 'const char *' and 'char * const *' 4790 // generalize to 'const void *' while 'char *' and 'const char **' generalize to 4791 // 'void *'. 4792 static QualType GeneralizeType(ASTContext &Ctx, QualType Ty) { 4793 if (!Ty->isPointerType()) 4794 return Ty; 4795 4796 return Ctx.getPointerType( 4797 QualType(Ctx.VoidTy).withCVRQualifiers( 4798 Ty->getPointeeType().getCVRQualifiers())); 4799 } 4800 4801 // Apply type generalization to a FunctionType's return and argument types 4802 static QualType GeneralizeFunctionType(ASTContext &Ctx, QualType Ty) { 4803 if (auto *FnType = Ty->getAs<FunctionProtoType>()) { 4804 SmallVector<QualType, 8> GeneralizedParams; 4805 for (auto &Param : FnType->param_types()) 4806 GeneralizedParams.push_back(GeneralizeType(Ctx, Param)); 4807 4808 return Ctx.getFunctionType( 4809 GeneralizeType(Ctx, FnType->getReturnType()), 4810 GeneralizedParams, FnType->getExtProtoInfo()); 4811 } 4812 4813 if (auto *FnType = Ty->getAs<FunctionNoProtoType>()) 4814 return Ctx.getFunctionNoProtoType( 4815 GeneralizeType(Ctx, FnType->getReturnType())); 4816 4817 llvm_unreachable("Encountered unknown FunctionType"); 4818 } 4819 4820 llvm::Metadata *CodeGenModule::CreateMetadataIdentifierGeneralized(QualType T) { 4821 T = GeneralizeFunctionType(getContext(), T); 4822 4823 llvm::Metadata *&InternalId = GeneralizedMetadataIdMap[T.getCanonicalType()]; 4824 if (InternalId) 4825 return InternalId; 4826 4827 if (isExternallyVisible(T->getLinkage())) { 4828 std::string OutName; 4829 llvm::raw_string_ostream Out(OutName); 4830 getCXXABI().getMangleContext().mangleTypeName(T, Out); 4831 Out << ".generalized"; 4832 4833 InternalId = llvm::MDString::get(getLLVMContext(), Out.str()); 4834 } else { 4835 InternalId = llvm::MDNode::getDistinct(getLLVMContext(), 4836 llvm::ArrayRef<llvm::Metadata *>()); 4837 } 4838 4839 return InternalId; 4840 } 4841 4842 /// Returns whether this module needs the "all-vtables" type identifier. 4843 bool CodeGenModule::NeedAllVtablesTypeId() const { 4844 // Returns true if at least one of vtable-based CFI checkers is enabled and 4845 // is not in the trapping mode. 4846 return ((LangOpts.Sanitize.has(SanitizerKind::CFIVCall) && 4847 !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFIVCall)) || 4848 (LangOpts.Sanitize.has(SanitizerKind::CFINVCall) && 4849 !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFINVCall)) || 4850 (LangOpts.Sanitize.has(SanitizerKind::CFIDerivedCast) && 4851 !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFIDerivedCast)) || 4852 (LangOpts.Sanitize.has(SanitizerKind::CFIUnrelatedCast) && 4853 !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFIUnrelatedCast))); 4854 } 4855 4856 void CodeGenModule::AddVTableTypeMetadata(llvm::GlobalVariable *VTable, 4857 CharUnits Offset, 4858 const CXXRecordDecl *RD) { 4859 llvm::Metadata *MD = 4860 CreateMetadataIdentifierForType(QualType(RD->getTypeForDecl(), 0)); 4861 VTable->addTypeMetadata(Offset.getQuantity(), MD); 4862 4863 if (CodeGenOpts.SanitizeCfiCrossDso) 4864 if (auto CrossDsoTypeId = CreateCrossDsoCfiTypeId(MD)) 4865 VTable->addTypeMetadata(Offset.getQuantity(), 4866 llvm::ConstantAsMetadata::get(CrossDsoTypeId)); 4867 4868 if (NeedAllVtablesTypeId()) { 4869 llvm::Metadata *MD = llvm::MDString::get(getLLVMContext(), "all-vtables"); 4870 VTable->addTypeMetadata(Offset.getQuantity(), MD); 4871 } 4872 } 4873 4874 // Fills in the supplied string map with the set of target features for the 4875 // passed in function. 4876 void CodeGenModule::getFunctionFeatureMap(llvm::StringMap<bool> &FeatureMap, 4877 const FunctionDecl *FD) { 4878 StringRef TargetCPU = Target.getTargetOpts().CPU; 4879 if (const auto *TD = FD->getAttr<TargetAttr>()) { 4880 // If we have a TargetAttr build up the feature map based on that. 4881 TargetAttr::ParsedTargetAttr ParsedAttr = TD->parse(); 4882 4883 ParsedAttr.Features.erase( 4884 llvm::remove_if(ParsedAttr.Features, 4885 [&](const std::string &Feat) { 4886 return !Target.isValidFeatureName( 4887 StringRef{Feat}.substr(1)); 4888 }), 4889 ParsedAttr.Features.end()); 4890 4891 // Make a copy of the features as passed on the command line into the 4892 // beginning of the additional features from the function to override. 4893 ParsedAttr.Features.insert(ParsedAttr.Features.begin(), 4894 Target.getTargetOpts().FeaturesAsWritten.begin(), 4895 Target.getTargetOpts().FeaturesAsWritten.end()); 4896 4897 if (ParsedAttr.Architecture != "" && 4898 Target.isValidCPUName(ParsedAttr.Architecture)) 4899 TargetCPU = ParsedAttr.Architecture; 4900 4901 // Now populate the feature map, first with the TargetCPU which is either 4902 // the default or a new one from the target attribute string. Then we'll use 4903 // the passed in features (FeaturesAsWritten) along with the new ones from 4904 // the attribute. 4905 Target.initFeatureMap(FeatureMap, getDiags(), TargetCPU, 4906 ParsedAttr.Features); 4907 } else { 4908 Target.initFeatureMap(FeatureMap, getDiags(), TargetCPU, 4909 Target.getTargetOpts().Features); 4910 } 4911 } 4912 4913 llvm::SanitizerStatReport &CodeGenModule::getSanStats() { 4914 if (!SanStats) 4915 SanStats = llvm::make_unique<llvm::SanitizerStatReport>(&getModule()); 4916 4917 return *SanStats; 4918 } 4919 llvm::Value * 4920 CodeGenModule::createOpenCLIntToSamplerConversion(const Expr *E, 4921 CodeGenFunction &CGF) { 4922 llvm::Constant *C = ConstantEmitter(CGF).emitAbstract(E, E->getType()); 4923 auto SamplerT = getOpenCLRuntime().getSamplerType(E->getType().getTypePtr()); 4924 auto FTy = llvm::FunctionType::get(SamplerT, {C->getType()}, false); 4925 return CGF.Builder.CreateCall(CreateRuntimeFunction(FTy, 4926 "__translate_sampler_initializer"), 4927 {C}); 4928 } 4929