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