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