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 TBAAAccessInfo CodeGenModule::getTBAAAccessInfo(QualType AccessType) { 582 return TBAAAccessInfo(getTBAATypeInfo(AccessType)); 583 } 584 585 TBAAAccessInfo CodeGenModule::getTBAAVTablePtrAccessInfo() { 586 if (!TBAA) 587 return TBAAAccessInfo(); 588 return TBAA->getVTablePtrAccessInfo(); 589 } 590 591 llvm::MDNode *CodeGenModule::getTBAAStructInfo(QualType QTy) { 592 if (!TBAA) 593 return nullptr; 594 return TBAA->getTBAAStructInfo(QTy); 595 } 596 597 llvm::MDNode *CodeGenModule::getTBAABaseTypeInfo(QualType QTy) { 598 if (!TBAA) 599 return nullptr; 600 return TBAA->getBaseTypeInfo(QTy); 601 } 602 603 llvm::MDNode *CodeGenModule::getTBAAAccessTagInfo(TBAAAccessInfo Info) { 604 if (!TBAA) 605 return nullptr; 606 return TBAA->getAccessTagInfo(Info); 607 } 608 609 TBAAAccessInfo CodeGenModule::getTBAAMayAliasAccessInfo() { 610 if (!TBAA) 611 return TBAAAccessInfo(); 612 return TBAA->getMayAliasAccessInfo(); 613 } 614 615 void CodeGenModule::DecorateInstructionWithTBAA(llvm::Instruction *Inst, 616 TBAAAccessInfo TBAAInfo) { 617 if (llvm::MDNode *Tag = getTBAAAccessTagInfo(TBAAInfo)) 618 Inst->setMetadata(llvm::LLVMContext::MD_tbaa, Tag); 619 } 620 621 void CodeGenModule::DecorateInstructionWithInvariantGroup( 622 llvm::Instruction *I, const CXXRecordDecl *RD) { 623 I->setMetadata(llvm::LLVMContext::MD_invariant_group, 624 llvm::MDNode::get(getLLVMContext(), {})); 625 } 626 627 void CodeGenModule::Error(SourceLocation loc, StringRef message) { 628 unsigned diagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error, "%0"); 629 getDiags().Report(Context.getFullLoc(loc), diagID) << message; 630 } 631 632 /// ErrorUnsupported - Print out an error that codegen doesn't support the 633 /// specified stmt yet. 634 void CodeGenModule::ErrorUnsupported(const Stmt *S, const char *Type) { 635 unsigned DiagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error, 636 "cannot compile this %0 yet"); 637 std::string Msg = Type; 638 getDiags().Report(Context.getFullLoc(S->getLocStart()), DiagID) 639 << Msg << S->getSourceRange(); 640 } 641 642 /// ErrorUnsupported - Print out an error that codegen doesn't support the 643 /// specified decl yet. 644 void CodeGenModule::ErrorUnsupported(const Decl *D, const char *Type) { 645 unsigned DiagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error, 646 "cannot compile this %0 yet"); 647 std::string Msg = Type; 648 getDiags().Report(Context.getFullLoc(D->getLocation()), DiagID) << Msg; 649 } 650 651 llvm::ConstantInt *CodeGenModule::getSize(CharUnits size) { 652 return llvm::ConstantInt::get(SizeTy, size.getQuantity()); 653 } 654 655 void CodeGenModule::setGlobalVisibility(llvm::GlobalValue *GV, 656 const NamedDecl *D) const { 657 // Internal definitions always have default visibility. 658 if (GV->hasLocalLinkage()) { 659 GV->setVisibility(llvm::GlobalValue::DefaultVisibility); 660 return; 661 } 662 663 // Set visibility for definitions. 664 LinkageInfo LV = D->getLinkageAndVisibility(); 665 if (LV.isVisibilityExplicit() || !GV->hasAvailableExternallyLinkage()) 666 GV->setVisibility(GetLLVMVisibility(LV.getVisibility())); 667 } 668 669 static llvm::GlobalVariable::ThreadLocalMode GetLLVMTLSModel(StringRef S) { 670 return llvm::StringSwitch<llvm::GlobalVariable::ThreadLocalMode>(S) 671 .Case("global-dynamic", llvm::GlobalVariable::GeneralDynamicTLSModel) 672 .Case("local-dynamic", llvm::GlobalVariable::LocalDynamicTLSModel) 673 .Case("initial-exec", llvm::GlobalVariable::InitialExecTLSModel) 674 .Case("local-exec", llvm::GlobalVariable::LocalExecTLSModel); 675 } 676 677 static llvm::GlobalVariable::ThreadLocalMode GetLLVMTLSModel( 678 CodeGenOptions::TLSModel M) { 679 switch (M) { 680 case CodeGenOptions::GeneralDynamicTLSModel: 681 return llvm::GlobalVariable::GeneralDynamicTLSModel; 682 case CodeGenOptions::LocalDynamicTLSModel: 683 return llvm::GlobalVariable::LocalDynamicTLSModel; 684 case CodeGenOptions::InitialExecTLSModel: 685 return llvm::GlobalVariable::InitialExecTLSModel; 686 case CodeGenOptions::LocalExecTLSModel: 687 return llvm::GlobalVariable::LocalExecTLSModel; 688 } 689 llvm_unreachable("Invalid TLS model!"); 690 } 691 692 void CodeGenModule::setTLSMode(llvm::GlobalValue *GV, const VarDecl &D) const { 693 assert(D.getTLSKind() && "setting TLS mode on non-TLS var!"); 694 695 llvm::GlobalValue::ThreadLocalMode TLM; 696 TLM = GetLLVMTLSModel(CodeGenOpts.getDefaultTLSModel()); 697 698 // Override the TLS model if it is explicitly specified. 699 if (const TLSModelAttr *Attr = D.getAttr<TLSModelAttr>()) { 700 TLM = GetLLVMTLSModel(Attr->getModel()); 701 } 702 703 GV->setThreadLocalMode(TLM); 704 } 705 706 StringRef CodeGenModule::getMangledName(GlobalDecl GD) { 707 GlobalDecl CanonicalGD = GD.getCanonicalDecl(); 708 709 // Some ABIs don't have constructor variants. Make sure that base and 710 // complete constructors get mangled the same. 711 if (const auto *CD = dyn_cast<CXXConstructorDecl>(CanonicalGD.getDecl())) { 712 if (!getTarget().getCXXABI().hasConstructorVariants()) { 713 CXXCtorType OrigCtorType = GD.getCtorType(); 714 assert(OrigCtorType == Ctor_Base || OrigCtorType == Ctor_Complete); 715 if (OrigCtorType == Ctor_Base) 716 CanonicalGD = GlobalDecl(CD, Ctor_Complete); 717 } 718 } 719 720 auto FoundName = MangledDeclNames.find(CanonicalGD); 721 if (FoundName != MangledDeclNames.end()) 722 return FoundName->second; 723 724 const auto *ND = cast<NamedDecl>(GD.getDecl()); 725 SmallString<256> Buffer; 726 StringRef Str; 727 if (getCXXABI().getMangleContext().shouldMangleDeclName(ND)) { 728 llvm::raw_svector_ostream Out(Buffer); 729 if (const auto *D = dyn_cast<CXXConstructorDecl>(ND)) 730 getCXXABI().getMangleContext().mangleCXXCtor(D, GD.getCtorType(), Out); 731 else if (const auto *D = dyn_cast<CXXDestructorDecl>(ND)) 732 getCXXABI().getMangleContext().mangleCXXDtor(D, GD.getDtorType(), Out); 733 else 734 getCXXABI().getMangleContext().mangleName(ND, Out); 735 Str = Out.str(); 736 } else { 737 IdentifierInfo *II = ND->getIdentifier(); 738 assert(II && "Attempt to mangle unnamed decl."); 739 const auto *FD = dyn_cast<FunctionDecl>(ND); 740 741 if (FD && 742 FD->getType()->castAs<FunctionType>()->getCallConv() == CC_X86RegCall) { 743 llvm::raw_svector_ostream Out(Buffer); 744 Out << "__regcall3__" << II->getName(); 745 Str = Out.str(); 746 } else { 747 Str = II->getName(); 748 } 749 } 750 751 // Keep the first result in the case of a mangling collision. 752 auto Result = Manglings.insert(std::make_pair(Str, GD)); 753 return MangledDeclNames[CanonicalGD] = Result.first->first(); 754 } 755 756 StringRef CodeGenModule::getBlockMangledName(GlobalDecl GD, 757 const BlockDecl *BD) { 758 MangleContext &MangleCtx = getCXXABI().getMangleContext(); 759 const Decl *D = GD.getDecl(); 760 761 SmallString<256> Buffer; 762 llvm::raw_svector_ostream Out(Buffer); 763 if (!D) 764 MangleCtx.mangleGlobalBlock(BD, 765 dyn_cast_or_null<VarDecl>(initializedGlobalDecl.getDecl()), Out); 766 else if (const auto *CD = dyn_cast<CXXConstructorDecl>(D)) 767 MangleCtx.mangleCtorBlock(CD, GD.getCtorType(), BD, Out); 768 else if (const auto *DD = dyn_cast<CXXDestructorDecl>(D)) 769 MangleCtx.mangleDtorBlock(DD, GD.getDtorType(), BD, Out); 770 else 771 MangleCtx.mangleBlock(cast<DeclContext>(D), BD, Out); 772 773 auto Result = Manglings.insert(std::make_pair(Out.str(), BD)); 774 return Result.first->first(); 775 } 776 777 llvm::GlobalValue *CodeGenModule::GetGlobalValue(StringRef Name) { 778 return getModule().getNamedValue(Name); 779 } 780 781 /// AddGlobalCtor - Add a function to the list that will be called before 782 /// main() runs. 783 void CodeGenModule::AddGlobalCtor(llvm::Function *Ctor, int Priority, 784 llvm::Constant *AssociatedData) { 785 // FIXME: Type coercion of void()* types. 786 GlobalCtors.push_back(Structor(Priority, Ctor, AssociatedData)); 787 } 788 789 /// AddGlobalDtor - Add a function to the list that will be called 790 /// when the module is unloaded. 791 void CodeGenModule::AddGlobalDtor(llvm::Function *Dtor, int Priority) { 792 // FIXME: Type coercion of void()* types. 793 GlobalDtors.push_back(Structor(Priority, Dtor, nullptr)); 794 } 795 796 void CodeGenModule::EmitCtorList(CtorList &Fns, const char *GlobalName) { 797 if (Fns.empty()) return; 798 799 // Ctor function type is void()*. 800 llvm::FunctionType* CtorFTy = llvm::FunctionType::get(VoidTy, false); 801 llvm::Type *CtorPFTy = llvm::PointerType::getUnqual(CtorFTy); 802 803 // Get the type of a ctor entry, { i32, void ()*, i8* }. 804 llvm::StructType *CtorStructTy = llvm::StructType::get( 805 Int32Ty, llvm::PointerType::getUnqual(CtorFTy), VoidPtrTy); 806 807 // Construct the constructor and destructor arrays. 808 ConstantInitBuilder builder(*this); 809 auto ctors = builder.beginArray(CtorStructTy); 810 for (const auto &I : Fns) { 811 auto ctor = ctors.beginStruct(CtorStructTy); 812 ctor.addInt(Int32Ty, I.Priority); 813 ctor.add(llvm::ConstantExpr::getBitCast(I.Initializer, CtorPFTy)); 814 if (I.AssociatedData) 815 ctor.add(llvm::ConstantExpr::getBitCast(I.AssociatedData, VoidPtrTy)); 816 else 817 ctor.addNullPointer(VoidPtrTy); 818 ctor.finishAndAddTo(ctors); 819 } 820 821 auto list = 822 ctors.finishAndCreateGlobal(GlobalName, getPointerAlign(), 823 /*constant*/ false, 824 llvm::GlobalValue::AppendingLinkage); 825 826 // The LTO linker doesn't seem to like it when we set an alignment 827 // on appending variables. Take it off as a workaround. 828 list->setAlignment(0); 829 830 Fns.clear(); 831 } 832 833 llvm::GlobalValue::LinkageTypes 834 CodeGenModule::getFunctionLinkage(GlobalDecl GD) { 835 const auto *D = cast<FunctionDecl>(GD.getDecl()); 836 837 GVALinkage Linkage = getContext().GetGVALinkageForFunction(D); 838 839 if (isa<CXXDestructorDecl>(D) && 840 getCXXABI().useThunkForDtorVariant(cast<CXXDestructorDecl>(D), 841 GD.getDtorType())) { 842 // Destructor variants in the Microsoft C++ ABI are always internal or 843 // linkonce_odr thunks emitted on an as-needed basis. 844 return Linkage == GVA_Internal ? llvm::GlobalValue::InternalLinkage 845 : llvm::GlobalValue::LinkOnceODRLinkage; 846 } 847 848 if (isa<CXXConstructorDecl>(D) && 849 cast<CXXConstructorDecl>(D)->isInheritingConstructor() && 850 Context.getTargetInfo().getCXXABI().isMicrosoft()) { 851 // Our approach to inheriting constructors is fundamentally different from 852 // that used by the MS ABI, so keep our inheriting constructor thunks 853 // internal rather than trying to pick an unambiguous mangling for them. 854 return llvm::GlobalValue::InternalLinkage; 855 } 856 857 return getLLVMLinkageForDeclarator(D, Linkage, /*isConstantVariable=*/false); 858 } 859 860 void CodeGenModule::setFunctionDLLStorageClass(GlobalDecl GD, llvm::Function *F) { 861 const auto *FD = cast<FunctionDecl>(GD.getDecl()); 862 863 if (const auto *Dtor = dyn_cast_or_null<CXXDestructorDecl>(FD)) { 864 if (getCXXABI().useThunkForDtorVariant(Dtor, GD.getDtorType())) { 865 // Don't dllexport/import destructor thunks. 866 F->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass); 867 return; 868 } 869 } 870 871 if (FD->hasAttr<DLLImportAttr>()) 872 F->setDLLStorageClass(llvm::GlobalVariable::DLLImportStorageClass); 873 else if (FD->hasAttr<DLLExportAttr>()) 874 F->setDLLStorageClass(llvm::GlobalVariable::DLLExportStorageClass); 875 else 876 F->setDLLStorageClass(llvm::GlobalVariable::DefaultStorageClass); 877 } 878 879 llvm::ConstantInt *CodeGenModule::CreateCrossDsoCfiTypeId(llvm::Metadata *MD) { 880 llvm::MDString *MDS = dyn_cast<llvm::MDString>(MD); 881 if (!MDS) return nullptr; 882 883 return llvm::ConstantInt::get(Int64Ty, llvm::MD5Hash(MDS->getString())); 884 } 885 886 void CodeGenModule::setFunctionDefinitionAttributes(const FunctionDecl *D, 887 llvm::Function *F) { 888 setNonAliasAttributes(D, F); 889 } 890 891 void CodeGenModule::SetLLVMFunctionAttributes(const Decl *D, 892 const CGFunctionInfo &Info, 893 llvm::Function *F) { 894 unsigned CallingConv; 895 llvm::AttributeList PAL; 896 ConstructAttributeList(F->getName(), Info, D, PAL, CallingConv, false); 897 F->setAttributes(PAL); 898 F->setCallingConv(static_cast<llvm::CallingConv::ID>(CallingConv)); 899 } 900 901 /// Determines whether the language options require us to model 902 /// unwind exceptions. We treat -fexceptions as mandating this 903 /// except under the fragile ObjC ABI with only ObjC exceptions 904 /// enabled. This means, for example, that C with -fexceptions 905 /// enables this. 906 static bool hasUnwindExceptions(const LangOptions &LangOpts) { 907 // If exceptions are completely disabled, obviously this is false. 908 if (!LangOpts.Exceptions) return false; 909 910 // If C++ exceptions are enabled, this is true. 911 if (LangOpts.CXXExceptions) return true; 912 913 // If ObjC exceptions are enabled, this depends on the ABI. 914 if (LangOpts.ObjCExceptions) { 915 return LangOpts.ObjCRuntime.hasUnwindExceptions(); 916 } 917 918 return true; 919 } 920 921 void CodeGenModule::SetLLVMFunctionAttributesForDefinition(const Decl *D, 922 llvm::Function *F) { 923 llvm::AttrBuilder B; 924 925 if (CodeGenOpts.UnwindTables) 926 B.addAttribute(llvm::Attribute::UWTable); 927 928 if (!hasUnwindExceptions(LangOpts)) 929 B.addAttribute(llvm::Attribute::NoUnwind); 930 931 if (LangOpts.getStackProtector() == LangOptions::SSPOn) 932 B.addAttribute(llvm::Attribute::StackProtect); 933 else if (LangOpts.getStackProtector() == LangOptions::SSPStrong) 934 B.addAttribute(llvm::Attribute::StackProtectStrong); 935 else if (LangOpts.getStackProtector() == LangOptions::SSPReq) 936 B.addAttribute(llvm::Attribute::StackProtectReq); 937 938 if (!D) { 939 // If we don't have a declaration to control inlining, the function isn't 940 // explicitly marked as alwaysinline for semantic reasons, and inlining is 941 // disabled, mark the function as noinline. 942 if (!F->hasFnAttribute(llvm::Attribute::AlwaysInline) && 943 CodeGenOpts.getInlining() == CodeGenOptions::OnlyAlwaysInlining) 944 B.addAttribute(llvm::Attribute::NoInline); 945 946 F->addAttributes(llvm::AttributeList::FunctionIndex, B); 947 return; 948 } 949 950 // Track whether we need to add the optnone LLVM attribute, 951 // starting with the default for this optimization level. 952 bool ShouldAddOptNone = 953 !CodeGenOpts.DisableO0ImplyOptNone && CodeGenOpts.OptimizationLevel == 0; 954 // We can't add optnone in the following cases, it won't pass the verifier. 955 ShouldAddOptNone &= !D->hasAttr<MinSizeAttr>(); 956 ShouldAddOptNone &= !F->hasFnAttribute(llvm::Attribute::AlwaysInline); 957 ShouldAddOptNone &= !D->hasAttr<AlwaysInlineAttr>(); 958 959 if (ShouldAddOptNone || D->hasAttr<OptimizeNoneAttr>()) { 960 B.addAttribute(llvm::Attribute::OptimizeNone); 961 962 // OptimizeNone implies noinline; we should not be inlining such functions. 963 B.addAttribute(llvm::Attribute::NoInline); 964 assert(!F->hasFnAttribute(llvm::Attribute::AlwaysInline) && 965 "OptimizeNone and AlwaysInline on same function!"); 966 967 // We still need to handle naked functions even though optnone subsumes 968 // much of their semantics. 969 if (D->hasAttr<NakedAttr>()) 970 B.addAttribute(llvm::Attribute::Naked); 971 972 // OptimizeNone wins over OptimizeForSize and MinSize. 973 F->removeFnAttr(llvm::Attribute::OptimizeForSize); 974 F->removeFnAttr(llvm::Attribute::MinSize); 975 } else if (D->hasAttr<NakedAttr>()) { 976 // Naked implies noinline: we should not be inlining such functions. 977 B.addAttribute(llvm::Attribute::Naked); 978 B.addAttribute(llvm::Attribute::NoInline); 979 } else if (D->hasAttr<NoDuplicateAttr>()) { 980 B.addAttribute(llvm::Attribute::NoDuplicate); 981 } else if (D->hasAttr<NoInlineAttr>()) { 982 B.addAttribute(llvm::Attribute::NoInline); 983 } else if (D->hasAttr<AlwaysInlineAttr>() && 984 !F->hasFnAttribute(llvm::Attribute::NoInline)) { 985 // (noinline wins over always_inline, and we can't specify both in IR) 986 B.addAttribute(llvm::Attribute::AlwaysInline); 987 } else if (CodeGenOpts.getInlining() == CodeGenOptions::OnlyAlwaysInlining) { 988 // If we're not inlining, then force everything that isn't always_inline to 989 // carry an explicit noinline attribute. 990 if (!F->hasFnAttribute(llvm::Attribute::AlwaysInline)) 991 B.addAttribute(llvm::Attribute::NoInline); 992 } else { 993 // Otherwise, propagate the inline hint attribute and potentially use its 994 // absence to mark things as noinline. 995 if (auto *FD = dyn_cast<FunctionDecl>(D)) { 996 if (any_of(FD->redecls(), [&](const FunctionDecl *Redecl) { 997 return Redecl->isInlineSpecified(); 998 })) { 999 B.addAttribute(llvm::Attribute::InlineHint); 1000 } else if (CodeGenOpts.getInlining() == 1001 CodeGenOptions::OnlyHintInlining && 1002 !FD->isInlined() && 1003 !F->hasFnAttribute(llvm::Attribute::AlwaysInline)) { 1004 B.addAttribute(llvm::Attribute::NoInline); 1005 } 1006 } 1007 } 1008 1009 // Add other optimization related attributes if we are optimizing this 1010 // function. 1011 if (!D->hasAttr<OptimizeNoneAttr>()) { 1012 if (D->hasAttr<ColdAttr>()) { 1013 if (!ShouldAddOptNone) 1014 B.addAttribute(llvm::Attribute::OptimizeForSize); 1015 B.addAttribute(llvm::Attribute::Cold); 1016 } 1017 1018 if (D->hasAttr<MinSizeAttr>()) 1019 B.addAttribute(llvm::Attribute::MinSize); 1020 } 1021 1022 F->addAttributes(llvm::AttributeList::FunctionIndex, B); 1023 1024 unsigned alignment = D->getMaxAlignment() / Context.getCharWidth(); 1025 if (alignment) 1026 F->setAlignment(alignment); 1027 1028 // Some C++ ABIs require 2-byte alignment for member functions, in order to 1029 // reserve a bit for differentiating between virtual and non-virtual member 1030 // functions. If the current target's C++ ABI requires this and this is a 1031 // member function, set its alignment accordingly. 1032 if (getTarget().getCXXABI().areMemberFunctionsAligned()) { 1033 if (F->getAlignment() < 2 && isa<CXXMethodDecl>(D)) 1034 F->setAlignment(2); 1035 } 1036 1037 // In the cross-dso CFI mode, we want !type attributes on definitions only. 1038 if (CodeGenOpts.SanitizeCfiCrossDso) 1039 if (auto *FD = dyn_cast<FunctionDecl>(D)) 1040 CreateFunctionTypeMetadata(FD, F); 1041 } 1042 1043 void CodeGenModule::SetCommonAttributes(const Decl *D, 1044 llvm::GlobalValue *GV) { 1045 if (const auto *ND = dyn_cast_or_null<NamedDecl>(D)) 1046 setGlobalVisibility(GV, ND); 1047 else 1048 GV->setVisibility(llvm::GlobalValue::DefaultVisibility); 1049 1050 if (D && D->hasAttr<UsedAttr>()) 1051 addUsedGlobal(GV); 1052 } 1053 1054 void CodeGenModule::setAliasAttributes(const Decl *D, 1055 llvm::GlobalValue *GV) { 1056 SetCommonAttributes(D, GV); 1057 1058 // Process the dllexport attribute based on whether the original definition 1059 // (not necessarily the aliasee) was exported. 1060 if (D->hasAttr<DLLExportAttr>()) 1061 GV->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass); 1062 } 1063 1064 void CodeGenModule::setNonAliasAttributes(const Decl *D, 1065 llvm::GlobalObject *GO) { 1066 SetCommonAttributes(D, GO); 1067 1068 if (D) { 1069 if (auto *GV = dyn_cast<llvm::GlobalVariable>(GO)) { 1070 if (auto *SA = D->getAttr<PragmaClangBSSSectionAttr>()) 1071 GV->addAttribute("bss-section", SA->getName()); 1072 if (auto *SA = D->getAttr<PragmaClangDataSectionAttr>()) 1073 GV->addAttribute("data-section", SA->getName()); 1074 if (auto *SA = D->getAttr<PragmaClangRodataSectionAttr>()) 1075 GV->addAttribute("rodata-section", SA->getName()); 1076 } 1077 1078 if (auto *F = dyn_cast<llvm::Function>(GO)) { 1079 if (auto *SA = D->getAttr<PragmaClangTextSectionAttr>()) 1080 if (!D->getAttr<SectionAttr>()) 1081 F->addFnAttr("implicit-section-name", SA->getName()); 1082 } 1083 1084 if (const SectionAttr *SA = D->getAttr<SectionAttr>()) 1085 GO->setSection(SA->getName()); 1086 } 1087 1088 getTargetCodeGenInfo().setTargetAttributes(D, GO, *this, ForDefinition); 1089 } 1090 1091 void CodeGenModule::SetInternalFunctionAttributes(const Decl *D, 1092 llvm::Function *F, 1093 const CGFunctionInfo &FI) { 1094 SetLLVMFunctionAttributes(D, FI, F); 1095 SetLLVMFunctionAttributesForDefinition(D, F); 1096 1097 F->setLinkage(llvm::Function::InternalLinkage); 1098 1099 setNonAliasAttributes(D, F); 1100 } 1101 1102 static void setLinkageAndVisibilityForGV(llvm::GlobalValue *GV, 1103 const NamedDecl *ND) { 1104 // Set linkage and visibility in case we never see a definition. 1105 LinkageInfo LV = ND->getLinkageAndVisibility(); 1106 if (!isExternallyVisible(LV.getLinkage())) { 1107 // Don't set internal linkage on declarations. 1108 } else { 1109 if (ND->hasAttr<DLLImportAttr>()) { 1110 GV->setLinkage(llvm::GlobalValue::ExternalLinkage); 1111 GV->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass); 1112 } else if (ND->hasAttr<DLLExportAttr>()) { 1113 GV->setLinkage(llvm::GlobalValue::ExternalLinkage); 1114 } else if (ND->hasAttr<WeakAttr>() || ND->isWeakImported()) { 1115 // "extern_weak" is overloaded in LLVM; we probably should have 1116 // separate linkage types for this. 1117 GV->setLinkage(llvm::GlobalValue::ExternalWeakLinkage); 1118 } 1119 1120 // Set visibility on a declaration only if it's explicit. 1121 if (LV.isVisibilityExplicit()) 1122 GV->setVisibility(CodeGenModule::GetLLVMVisibility(LV.getVisibility())); 1123 } 1124 } 1125 1126 void CodeGenModule::CreateFunctionTypeMetadata(const FunctionDecl *FD, 1127 llvm::Function *F) { 1128 // Only if we are checking indirect calls. 1129 if (!LangOpts.Sanitize.has(SanitizerKind::CFIICall)) 1130 return; 1131 1132 // Non-static class methods are handled via vtable pointer checks elsewhere. 1133 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic()) 1134 return; 1135 1136 // Additionally, if building with cross-DSO support... 1137 if (CodeGenOpts.SanitizeCfiCrossDso) { 1138 // Skip available_externally functions. They won't be codegen'ed in the 1139 // current module anyway. 1140 if (getContext().GetGVALinkageForFunction(FD) == GVA_AvailableExternally) 1141 return; 1142 } 1143 1144 llvm::Metadata *MD = CreateMetadataIdentifierForType(FD->getType()); 1145 F->addTypeMetadata(0, MD); 1146 1147 // Emit a hash-based bit set entry for cross-DSO calls. 1148 if (CodeGenOpts.SanitizeCfiCrossDso) 1149 if (auto CrossDsoTypeId = CreateCrossDsoCfiTypeId(MD)) 1150 F->addTypeMetadata(0, llvm::ConstantAsMetadata::get(CrossDsoTypeId)); 1151 } 1152 1153 void CodeGenModule::SetFunctionAttributes(GlobalDecl GD, llvm::Function *F, 1154 bool IsIncompleteFunction, 1155 bool IsThunk, 1156 ForDefinition_t IsForDefinition) { 1157 1158 if (llvm::Intrinsic::ID IID = F->getIntrinsicID()) { 1159 // If this is an intrinsic function, set the function's attributes 1160 // to the intrinsic's attributes. 1161 F->setAttributes(llvm::Intrinsic::getAttributes(getLLVMContext(), IID)); 1162 return; 1163 } 1164 1165 const auto *FD = cast<FunctionDecl>(GD.getDecl()); 1166 1167 if (!IsIncompleteFunction) { 1168 SetLLVMFunctionAttributes(FD, getTypes().arrangeGlobalDeclaration(GD), F); 1169 // Setup target-specific attributes. 1170 if (!IsForDefinition) 1171 getTargetCodeGenInfo().setTargetAttributes(FD, F, *this, 1172 NotForDefinition); 1173 } 1174 1175 // Add the Returned attribute for "this", except for iOS 5 and earlier 1176 // where substantial code, including the libstdc++ dylib, was compiled with 1177 // GCC and does not actually return "this". 1178 if (!IsThunk && getCXXABI().HasThisReturn(GD) && 1179 !(getTriple().isiOS() && getTriple().isOSVersionLT(6))) { 1180 assert(!F->arg_empty() && 1181 F->arg_begin()->getType() 1182 ->canLosslesslyBitCastTo(F->getReturnType()) && 1183 "unexpected this return"); 1184 F->addAttribute(1, llvm::Attribute::Returned); 1185 } 1186 1187 // Only a few attributes are set on declarations; these may later be 1188 // overridden by a definition. 1189 1190 setLinkageAndVisibilityForGV(F, FD); 1191 1192 if (FD->getAttr<PragmaClangTextSectionAttr>()) { 1193 F->addFnAttr("implicit-section-name"); 1194 } 1195 1196 if (const SectionAttr *SA = FD->getAttr<SectionAttr>()) 1197 F->setSection(SA->getName()); 1198 1199 if (FD->isReplaceableGlobalAllocationFunction()) { 1200 // A replaceable global allocation function does not act like a builtin by 1201 // default, only if it is invoked by a new-expression or delete-expression. 1202 F->addAttribute(llvm::AttributeList::FunctionIndex, 1203 llvm::Attribute::NoBuiltin); 1204 1205 // A sane operator new returns a non-aliasing pointer. 1206 // FIXME: Also add NonNull attribute to the return value 1207 // for the non-nothrow forms? 1208 auto Kind = FD->getDeclName().getCXXOverloadedOperator(); 1209 if (getCodeGenOpts().AssumeSaneOperatorNew && 1210 (Kind == OO_New || Kind == OO_Array_New)) 1211 F->addAttribute(llvm::AttributeList::ReturnIndex, 1212 llvm::Attribute::NoAlias); 1213 } 1214 1215 if (isa<CXXConstructorDecl>(FD) || isa<CXXDestructorDecl>(FD)) 1216 F->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global); 1217 else if (const auto *MD = dyn_cast<CXXMethodDecl>(FD)) 1218 if (MD->isVirtual()) 1219 F->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global); 1220 1221 // Don't emit entries for function declarations in the cross-DSO mode. This 1222 // is handled with better precision by the receiving DSO. 1223 if (!CodeGenOpts.SanitizeCfiCrossDso) 1224 CreateFunctionTypeMetadata(FD, F); 1225 } 1226 1227 void CodeGenModule::addUsedGlobal(llvm::GlobalValue *GV) { 1228 assert(!GV->isDeclaration() && 1229 "Only globals with definition can force usage."); 1230 LLVMUsed.emplace_back(GV); 1231 } 1232 1233 void CodeGenModule::addCompilerUsedGlobal(llvm::GlobalValue *GV) { 1234 assert(!GV->isDeclaration() && 1235 "Only globals with definition can force usage."); 1236 LLVMCompilerUsed.emplace_back(GV); 1237 } 1238 1239 static void emitUsed(CodeGenModule &CGM, StringRef Name, 1240 std::vector<llvm::WeakTrackingVH> &List) { 1241 // Don't create llvm.used if there is no need. 1242 if (List.empty()) 1243 return; 1244 1245 // Convert List to what ConstantArray needs. 1246 SmallVector<llvm::Constant*, 8> UsedArray; 1247 UsedArray.resize(List.size()); 1248 for (unsigned i = 0, e = List.size(); i != e; ++i) { 1249 UsedArray[i] = 1250 llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast( 1251 cast<llvm::Constant>(&*List[i]), CGM.Int8PtrTy); 1252 } 1253 1254 if (UsedArray.empty()) 1255 return; 1256 llvm::ArrayType *ATy = llvm::ArrayType::get(CGM.Int8PtrTy, UsedArray.size()); 1257 1258 auto *GV = new llvm::GlobalVariable( 1259 CGM.getModule(), ATy, false, llvm::GlobalValue::AppendingLinkage, 1260 llvm::ConstantArray::get(ATy, UsedArray), Name); 1261 1262 GV->setSection("llvm.metadata"); 1263 } 1264 1265 void CodeGenModule::emitLLVMUsed() { 1266 emitUsed(*this, "llvm.used", LLVMUsed); 1267 emitUsed(*this, "llvm.compiler.used", LLVMCompilerUsed); 1268 } 1269 1270 void CodeGenModule::AppendLinkerOptions(StringRef Opts) { 1271 auto *MDOpts = llvm::MDString::get(getLLVMContext(), Opts); 1272 LinkerOptionsMetadata.push_back(llvm::MDNode::get(getLLVMContext(), MDOpts)); 1273 } 1274 1275 void CodeGenModule::AddDetectMismatch(StringRef Name, StringRef Value) { 1276 llvm::SmallString<32> Opt; 1277 getTargetCodeGenInfo().getDetectMismatchOption(Name, Value, Opt); 1278 auto *MDOpts = llvm::MDString::get(getLLVMContext(), Opt); 1279 LinkerOptionsMetadata.push_back(llvm::MDNode::get(getLLVMContext(), MDOpts)); 1280 } 1281 1282 void CodeGenModule::AddDependentLib(StringRef Lib) { 1283 llvm::SmallString<24> Opt; 1284 getTargetCodeGenInfo().getDependentLibraryOption(Lib, Opt); 1285 auto *MDOpts = llvm::MDString::get(getLLVMContext(), Opt); 1286 LinkerOptionsMetadata.push_back(llvm::MDNode::get(getLLVMContext(), MDOpts)); 1287 } 1288 1289 /// \brief Add link options implied by the given module, including modules 1290 /// it depends on, using a postorder walk. 1291 static void addLinkOptionsPostorder(CodeGenModule &CGM, Module *Mod, 1292 SmallVectorImpl<llvm::MDNode *> &Metadata, 1293 llvm::SmallPtrSet<Module *, 16> &Visited) { 1294 // Import this module's parent. 1295 if (Mod->Parent && Visited.insert(Mod->Parent).second) { 1296 addLinkOptionsPostorder(CGM, Mod->Parent, Metadata, Visited); 1297 } 1298 1299 // Import this module's dependencies. 1300 for (unsigned I = Mod->Imports.size(); I > 0; --I) { 1301 if (Visited.insert(Mod->Imports[I - 1]).second) 1302 addLinkOptionsPostorder(CGM, Mod->Imports[I-1], Metadata, Visited); 1303 } 1304 1305 // Add linker options to link against the libraries/frameworks 1306 // described by this module. 1307 llvm::LLVMContext &Context = CGM.getLLVMContext(); 1308 for (unsigned I = Mod->LinkLibraries.size(); I > 0; --I) { 1309 // Link against a framework. Frameworks are currently Darwin only, so we 1310 // don't to ask TargetCodeGenInfo for the spelling of the linker option. 1311 if (Mod->LinkLibraries[I-1].IsFramework) { 1312 llvm::Metadata *Args[2] = { 1313 llvm::MDString::get(Context, "-framework"), 1314 llvm::MDString::get(Context, Mod->LinkLibraries[I - 1].Library)}; 1315 1316 Metadata.push_back(llvm::MDNode::get(Context, Args)); 1317 continue; 1318 } 1319 1320 // Link against a library. 1321 llvm::SmallString<24> Opt; 1322 CGM.getTargetCodeGenInfo().getDependentLibraryOption( 1323 Mod->LinkLibraries[I-1].Library, Opt); 1324 auto *OptString = llvm::MDString::get(Context, Opt); 1325 Metadata.push_back(llvm::MDNode::get(Context, OptString)); 1326 } 1327 } 1328 1329 void CodeGenModule::EmitModuleLinkOptions() { 1330 // Collect the set of all of the modules we want to visit to emit link 1331 // options, which is essentially the imported modules and all of their 1332 // non-explicit child modules. 1333 llvm::SetVector<clang::Module *> LinkModules; 1334 llvm::SmallPtrSet<clang::Module *, 16> Visited; 1335 SmallVector<clang::Module *, 16> Stack; 1336 1337 // Seed the stack with imported modules. 1338 for (Module *M : ImportedModules) { 1339 // Do not add any link flags when an implementation TU of a module imports 1340 // a header of that same module. 1341 if (M->getTopLevelModuleName() == getLangOpts().CurrentModule && 1342 !getLangOpts().isCompilingModule()) 1343 continue; 1344 if (Visited.insert(M).second) 1345 Stack.push_back(M); 1346 } 1347 1348 // Find all of the modules to import, making a little effort to prune 1349 // non-leaf modules. 1350 while (!Stack.empty()) { 1351 clang::Module *Mod = Stack.pop_back_val(); 1352 1353 bool AnyChildren = false; 1354 1355 // Visit the submodules of this module. 1356 for (clang::Module::submodule_iterator Sub = Mod->submodule_begin(), 1357 SubEnd = Mod->submodule_end(); 1358 Sub != SubEnd; ++Sub) { 1359 // Skip explicit children; they need to be explicitly imported to be 1360 // linked against. 1361 if ((*Sub)->IsExplicit) 1362 continue; 1363 1364 if (Visited.insert(*Sub).second) { 1365 Stack.push_back(*Sub); 1366 AnyChildren = true; 1367 } 1368 } 1369 1370 // We didn't find any children, so add this module to the list of 1371 // modules to link against. 1372 if (!AnyChildren) { 1373 LinkModules.insert(Mod); 1374 } 1375 } 1376 1377 // Add link options for all of the imported modules in reverse topological 1378 // order. We don't do anything to try to order import link flags with respect 1379 // to linker options inserted by things like #pragma comment(). 1380 SmallVector<llvm::MDNode *, 16> MetadataArgs; 1381 Visited.clear(); 1382 for (Module *M : LinkModules) 1383 if (Visited.insert(M).second) 1384 addLinkOptionsPostorder(*this, M, MetadataArgs, Visited); 1385 std::reverse(MetadataArgs.begin(), MetadataArgs.end()); 1386 LinkerOptionsMetadata.append(MetadataArgs.begin(), MetadataArgs.end()); 1387 1388 // Add the linker options metadata flag. 1389 auto *NMD = getModule().getOrInsertNamedMetadata("llvm.linker.options"); 1390 for (auto *MD : LinkerOptionsMetadata) 1391 NMD->addOperand(MD); 1392 } 1393 1394 void CodeGenModule::EmitDeferred() { 1395 // Emit code for any potentially referenced deferred decls. Since a 1396 // previously unused static decl may become used during the generation of code 1397 // for a static function, iterate until no changes are made. 1398 1399 if (!DeferredVTables.empty()) { 1400 EmitDeferredVTables(); 1401 1402 // Emitting a vtable doesn't directly cause more vtables to 1403 // become deferred, although it can cause functions to be 1404 // emitted that then need those vtables. 1405 assert(DeferredVTables.empty()); 1406 } 1407 1408 // Stop if we're out of both deferred vtables and deferred declarations. 1409 if (DeferredDeclsToEmit.empty()) 1410 return; 1411 1412 // Grab the list of decls to emit. If EmitGlobalDefinition schedules more 1413 // work, it will not interfere with this. 1414 std::vector<GlobalDecl> CurDeclsToEmit; 1415 CurDeclsToEmit.swap(DeferredDeclsToEmit); 1416 1417 for (GlobalDecl &D : CurDeclsToEmit) { 1418 // We should call GetAddrOfGlobal with IsForDefinition set to true in order 1419 // to get GlobalValue with exactly the type we need, not something that 1420 // might had been created for another decl with the same mangled name but 1421 // different type. 1422 llvm::GlobalValue *GV = dyn_cast<llvm::GlobalValue>( 1423 GetAddrOfGlobal(D, ForDefinition)); 1424 1425 // In case of different address spaces, we may still get a cast, even with 1426 // IsForDefinition equal to true. Query mangled names table to get 1427 // GlobalValue. 1428 if (!GV) 1429 GV = GetGlobalValue(getMangledName(D)); 1430 1431 // Make sure GetGlobalValue returned non-null. 1432 assert(GV); 1433 1434 // Check to see if we've already emitted this. This is necessary 1435 // for a couple of reasons: first, decls can end up in the 1436 // deferred-decls queue multiple times, and second, decls can end 1437 // up with definitions in unusual ways (e.g. by an extern inline 1438 // function acquiring a strong function redefinition). Just 1439 // ignore these cases. 1440 if (!GV->isDeclaration()) 1441 continue; 1442 1443 // Otherwise, emit the definition and move on to the next one. 1444 EmitGlobalDefinition(D, GV); 1445 1446 // If we found out that we need to emit more decls, do that recursively. 1447 // This has the advantage that the decls are emitted in a DFS and related 1448 // ones are close together, which is convenient for testing. 1449 if (!DeferredVTables.empty() || !DeferredDeclsToEmit.empty()) { 1450 EmitDeferred(); 1451 assert(DeferredVTables.empty() && DeferredDeclsToEmit.empty()); 1452 } 1453 } 1454 } 1455 1456 void CodeGenModule::EmitVTablesOpportunistically() { 1457 // Try to emit external vtables as available_externally if they have emitted 1458 // all inlined virtual functions. It runs after EmitDeferred() and therefore 1459 // is not allowed to create new references to things that need to be emitted 1460 // lazily. Note that it also uses fact that we eagerly emitting RTTI. 1461 1462 assert((OpportunisticVTables.empty() || shouldOpportunisticallyEmitVTables()) 1463 && "Only emit opportunistic vtables with optimizations"); 1464 1465 for (const CXXRecordDecl *RD : OpportunisticVTables) { 1466 assert(getVTables().isVTableExternal(RD) && 1467 "This queue should only contain external vtables"); 1468 if (getCXXABI().canSpeculativelyEmitVTable(RD)) 1469 VTables.GenerateClassData(RD); 1470 } 1471 OpportunisticVTables.clear(); 1472 } 1473 1474 void CodeGenModule::EmitGlobalAnnotations() { 1475 if (Annotations.empty()) 1476 return; 1477 1478 // Create a new global variable for the ConstantStruct in the Module. 1479 llvm::Constant *Array = llvm::ConstantArray::get(llvm::ArrayType::get( 1480 Annotations[0]->getType(), Annotations.size()), Annotations); 1481 auto *gv = new llvm::GlobalVariable(getModule(), Array->getType(), false, 1482 llvm::GlobalValue::AppendingLinkage, 1483 Array, "llvm.global.annotations"); 1484 gv->setSection(AnnotationSection); 1485 } 1486 1487 llvm::Constant *CodeGenModule::EmitAnnotationString(StringRef Str) { 1488 llvm::Constant *&AStr = AnnotationStrings[Str]; 1489 if (AStr) 1490 return AStr; 1491 1492 // Not found yet, create a new global. 1493 llvm::Constant *s = llvm::ConstantDataArray::getString(getLLVMContext(), Str); 1494 auto *gv = 1495 new llvm::GlobalVariable(getModule(), s->getType(), true, 1496 llvm::GlobalValue::PrivateLinkage, s, ".str"); 1497 gv->setSection(AnnotationSection); 1498 gv->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global); 1499 AStr = gv; 1500 return gv; 1501 } 1502 1503 llvm::Constant *CodeGenModule::EmitAnnotationUnit(SourceLocation Loc) { 1504 SourceManager &SM = getContext().getSourceManager(); 1505 PresumedLoc PLoc = SM.getPresumedLoc(Loc); 1506 if (PLoc.isValid()) 1507 return EmitAnnotationString(PLoc.getFilename()); 1508 return EmitAnnotationString(SM.getBufferName(Loc)); 1509 } 1510 1511 llvm::Constant *CodeGenModule::EmitAnnotationLineNo(SourceLocation L) { 1512 SourceManager &SM = getContext().getSourceManager(); 1513 PresumedLoc PLoc = SM.getPresumedLoc(L); 1514 unsigned LineNo = PLoc.isValid() ? PLoc.getLine() : 1515 SM.getExpansionLineNumber(L); 1516 return llvm::ConstantInt::get(Int32Ty, LineNo); 1517 } 1518 1519 llvm::Constant *CodeGenModule::EmitAnnotateAttr(llvm::GlobalValue *GV, 1520 const AnnotateAttr *AA, 1521 SourceLocation L) { 1522 // Get the globals for file name, annotation, and the line number. 1523 llvm::Constant *AnnoGV = EmitAnnotationString(AA->getAnnotation()), 1524 *UnitGV = EmitAnnotationUnit(L), 1525 *LineNoCst = EmitAnnotationLineNo(L); 1526 1527 // Create the ConstantStruct for the global annotation. 1528 llvm::Constant *Fields[4] = { 1529 llvm::ConstantExpr::getBitCast(GV, Int8PtrTy), 1530 llvm::ConstantExpr::getBitCast(AnnoGV, Int8PtrTy), 1531 llvm::ConstantExpr::getBitCast(UnitGV, Int8PtrTy), 1532 LineNoCst 1533 }; 1534 return llvm::ConstantStruct::getAnon(Fields); 1535 } 1536 1537 void CodeGenModule::AddGlobalAnnotations(const ValueDecl *D, 1538 llvm::GlobalValue *GV) { 1539 assert(D->hasAttr<AnnotateAttr>() && "no annotate attribute"); 1540 // Get the struct elements for these annotations. 1541 for (const auto *I : D->specific_attrs<AnnotateAttr>()) 1542 Annotations.push_back(EmitAnnotateAttr(GV, I, D->getLocation())); 1543 } 1544 1545 bool CodeGenModule::isInSanitizerBlacklist(SanitizerMask Kind, 1546 llvm::Function *Fn, 1547 SourceLocation Loc) const { 1548 const auto &SanitizerBL = getContext().getSanitizerBlacklist(); 1549 // Blacklist by function name. 1550 if (SanitizerBL.isBlacklistedFunction(Kind, Fn->getName())) 1551 return true; 1552 // Blacklist by location. 1553 if (Loc.isValid()) 1554 return SanitizerBL.isBlacklistedLocation(Kind, Loc); 1555 // If location is unknown, this may be a compiler-generated function. Assume 1556 // it's located in the main file. 1557 auto &SM = Context.getSourceManager(); 1558 if (const auto *MainFile = SM.getFileEntryForID(SM.getMainFileID())) { 1559 return SanitizerBL.isBlacklistedFile(Kind, MainFile->getName()); 1560 } 1561 return false; 1562 } 1563 1564 bool CodeGenModule::isInSanitizerBlacklist(llvm::GlobalVariable *GV, 1565 SourceLocation Loc, QualType Ty, 1566 StringRef Category) const { 1567 // For now globals can be blacklisted only in ASan and KASan. 1568 const SanitizerMask EnabledAsanMask = LangOpts.Sanitize.Mask & 1569 (SanitizerKind::Address | SanitizerKind::KernelAddress); 1570 if (!EnabledAsanMask) 1571 return false; 1572 const auto &SanitizerBL = getContext().getSanitizerBlacklist(); 1573 if (SanitizerBL.isBlacklistedGlobal(EnabledAsanMask, GV->getName(), Category)) 1574 return true; 1575 if (SanitizerBL.isBlacklistedLocation(EnabledAsanMask, Loc, Category)) 1576 return true; 1577 // Check global type. 1578 if (!Ty.isNull()) { 1579 // Drill down the array types: if global variable of a fixed type is 1580 // blacklisted, we also don't instrument arrays of them. 1581 while (auto AT = dyn_cast<ArrayType>(Ty.getTypePtr())) 1582 Ty = AT->getElementType(); 1583 Ty = Ty.getCanonicalType().getUnqualifiedType(); 1584 // We allow to blacklist only record types (classes, structs etc.) 1585 if (Ty->isRecordType()) { 1586 std::string TypeStr = Ty.getAsString(getContext().getPrintingPolicy()); 1587 if (SanitizerBL.isBlacklistedType(EnabledAsanMask, TypeStr, Category)) 1588 return true; 1589 } 1590 } 1591 return false; 1592 } 1593 1594 bool CodeGenModule::imbueXRayAttrs(llvm::Function *Fn, SourceLocation Loc, 1595 StringRef Category) const { 1596 if (!LangOpts.XRayInstrument) 1597 return false; 1598 const auto &XRayFilter = getContext().getXRayFilter(); 1599 using ImbueAttr = XRayFunctionFilter::ImbueAttribute; 1600 auto Attr = XRayFunctionFilter::ImbueAttribute::NONE; 1601 if (Loc.isValid()) 1602 Attr = XRayFilter.shouldImbueLocation(Loc, Category); 1603 if (Attr == ImbueAttr::NONE) 1604 Attr = XRayFilter.shouldImbueFunction(Fn->getName()); 1605 switch (Attr) { 1606 case ImbueAttr::NONE: 1607 return false; 1608 case ImbueAttr::ALWAYS: 1609 Fn->addFnAttr("function-instrument", "xray-always"); 1610 break; 1611 case ImbueAttr::ALWAYS_ARG1: 1612 Fn->addFnAttr("function-instrument", "xray-always"); 1613 Fn->addFnAttr("xray-log-args", "1"); 1614 break; 1615 case ImbueAttr::NEVER: 1616 Fn->addFnAttr("function-instrument", "xray-never"); 1617 break; 1618 } 1619 return true; 1620 } 1621 1622 bool CodeGenModule::MustBeEmitted(const ValueDecl *Global) { 1623 // Never defer when EmitAllDecls is specified. 1624 if (LangOpts.EmitAllDecls) 1625 return true; 1626 1627 return getContext().DeclMustBeEmitted(Global); 1628 } 1629 1630 bool CodeGenModule::MayBeEmittedEagerly(const ValueDecl *Global) { 1631 if (const auto *FD = dyn_cast<FunctionDecl>(Global)) 1632 if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation) 1633 // Implicit template instantiations may change linkage if they are later 1634 // explicitly instantiated, so they should not be emitted eagerly. 1635 return false; 1636 if (const auto *VD = dyn_cast<VarDecl>(Global)) 1637 if (Context.getInlineVariableDefinitionKind(VD) == 1638 ASTContext::InlineVariableDefinitionKind::WeakUnknown) 1639 // A definition of an inline constexpr static data member may change 1640 // linkage later if it's redeclared outside the class. 1641 return false; 1642 // If OpenMP is enabled and threadprivates must be generated like TLS, delay 1643 // codegen for global variables, because they may be marked as threadprivate. 1644 if (LangOpts.OpenMP && LangOpts.OpenMPUseTLS && 1645 getContext().getTargetInfo().isTLSSupported() && isa<VarDecl>(Global)) 1646 return false; 1647 1648 return true; 1649 } 1650 1651 ConstantAddress CodeGenModule::GetAddrOfUuidDescriptor( 1652 const CXXUuidofExpr* E) { 1653 // Sema has verified that IIDSource has a __declspec(uuid()), and that its 1654 // well-formed. 1655 StringRef Uuid = E->getUuidStr(); 1656 std::string Name = "_GUID_" + Uuid.lower(); 1657 std::replace(Name.begin(), Name.end(), '-', '_'); 1658 1659 // The UUID descriptor should be pointer aligned. 1660 CharUnits Alignment = CharUnits::fromQuantity(PointerAlignInBytes); 1661 1662 // Look for an existing global. 1663 if (llvm::GlobalVariable *GV = getModule().getNamedGlobal(Name)) 1664 return ConstantAddress(GV, Alignment); 1665 1666 llvm::Constant *Init = EmitUuidofInitializer(Uuid); 1667 assert(Init && "failed to initialize as constant"); 1668 1669 auto *GV = new llvm::GlobalVariable( 1670 getModule(), Init->getType(), 1671 /*isConstant=*/true, llvm::GlobalValue::LinkOnceODRLinkage, Init, Name); 1672 if (supportsCOMDAT()) 1673 GV->setComdat(TheModule.getOrInsertComdat(GV->getName())); 1674 return ConstantAddress(GV, Alignment); 1675 } 1676 1677 ConstantAddress CodeGenModule::GetWeakRefReference(const ValueDecl *VD) { 1678 const AliasAttr *AA = VD->getAttr<AliasAttr>(); 1679 assert(AA && "No alias?"); 1680 1681 CharUnits Alignment = getContext().getDeclAlign(VD); 1682 llvm::Type *DeclTy = getTypes().ConvertTypeForMem(VD->getType()); 1683 1684 // See if there is already something with the target's name in the module. 1685 llvm::GlobalValue *Entry = GetGlobalValue(AA->getAliasee()); 1686 if (Entry) { 1687 unsigned AS = getContext().getTargetAddressSpace(VD->getType()); 1688 auto Ptr = llvm::ConstantExpr::getBitCast(Entry, DeclTy->getPointerTo(AS)); 1689 return ConstantAddress(Ptr, Alignment); 1690 } 1691 1692 llvm::Constant *Aliasee; 1693 if (isa<llvm::FunctionType>(DeclTy)) 1694 Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy, 1695 GlobalDecl(cast<FunctionDecl>(VD)), 1696 /*ForVTable=*/false); 1697 else 1698 Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(), 1699 llvm::PointerType::getUnqual(DeclTy), 1700 nullptr); 1701 1702 auto *F = cast<llvm::GlobalValue>(Aliasee); 1703 F->setLinkage(llvm::Function::ExternalWeakLinkage); 1704 WeakRefReferences.insert(F); 1705 1706 return ConstantAddress(Aliasee, Alignment); 1707 } 1708 1709 void CodeGenModule::EmitGlobal(GlobalDecl GD) { 1710 const auto *Global = cast<ValueDecl>(GD.getDecl()); 1711 1712 // Weak references don't produce any output by themselves. 1713 if (Global->hasAttr<WeakRefAttr>()) 1714 return; 1715 1716 // If this is an alias definition (which otherwise looks like a declaration) 1717 // emit it now. 1718 if (Global->hasAttr<AliasAttr>()) 1719 return EmitAliasDefinition(GD); 1720 1721 // IFunc like an alias whose value is resolved at runtime by calling resolver. 1722 if (Global->hasAttr<IFuncAttr>()) 1723 return emitIFuncDefinition(GD); 1724 1725 // If this is CUDA, be selective about which declarations we emit. 1726 if (LangOpts.CUDA) { 1727 if (LangOpts.CUDAIsDevice) { 1728 if (!Global->hasAttr<CUDADeviceAttr>() && 1729 !Global->hasAttr<CUDAGlobalAttr>() && 1730 !Global->hasAttr<CUDAConstantAttr>() && 1731 !Global->hasAttr<CUDASharedAttr>()) 1732 return; 1733 } else { 1734 // We need to emit host-side 'shadows' for all global 1735 // device-side variables because the CUDA runtime needs their 1736 // size and host-side address in order to provide access to 1737 // their device-side incarnations. 1738 1739 // So device-only functions are the only things we skip. 1740 if (isa<FunctionDecl>(Global) && !Global->hasAttr<CUDAHostAttr>() && 1741 Global->hasAttr<CUDADeviceAttr>()) 1742 return; 1743 1744 assert((isa<FunctionDecl>(Global) || isa<VarDecl>(Global)) && 1745 "Expected Variable or Function"); 1746 } 1747 } 1748 1749 if (LangOpts.OpenMP) { 1750 // If this is OpenMP device, check if it is legal to emit this global 1751 // normally. 1752 if (OpenMPRuntime && OpenMPRuntime->emitTargetGlobal(GD)) 1753 return; 1754 if (auto *DRD = dyn_cast<OMPDeclareReductionDecl>(Global)) { 1755 if (MustBeEmitted(Global)) 1756 EmitOMPDeclareReduction(DRD); 1757 return; 1758 } 1759 } 1760 1761 // Ignore declarations, they will be emitted on their first use. 1762 if (const auto *FD = dyn_cast<FunctionDecl>(Global)) { 1763 // Forward declarations are emitted lazily on first use. 1764 if (!FD->doesThisDeclarationHaveABody()) { 1765 if (!FD->doesDeclarationForceExternallyVisibleDefinition()) 1766 return; 1767 1768 StringRef MangledName = getMangledName(GD); 1769 1770 // Compute the function info and LLVM type. 1771 const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD); 1772 llvm::Type *Ty = getTypes().GetFunctionType(FI); 1773 1774 GetOrCreateLLVMFunction(MangledName, Ty, GD, /*ForVTable=*/false, 1775 /*DontDefer=*/false); 1776 return; 1777 } 1778 } else { 1779 const auto *VD = cast<VarDecl>(Global); 1780 assert(VD->isFileVarDecl() && "Cannot emit local var decl as global."); 1781 // We need to emit device-side global CUDA variables even if a 1782 // variable does not have a definition -- we still need to define 1783 // host-side shadow for it. 1784 bool MustEmitForCuda = LangOpts.CUDA && !LangOpts.CUDAIsDevice && 1785 !VD->hasDefinition() && 1786 (VD->hasAttr<CUDAConstantAttr>() || 1787 VD->hasAttr<CUDADeviceAttr>()); 1788 if (!MustEmitForCuda && 1789 VD->isThisDeclarationADefinition() != VarDecl::Definition && 1790 !Context.isMSStaticDataMemberInlineDefinition(VD)) { 1791 // If this declaration may have caused an inline variable definition to 1792 // change linkage, make sure that it's emitted. 1793 if (Context.getInlineVariableDefinitionKind(VD) == 1794 ASTContext::InlineVariableDefinitionKind::Strong) 1795 GetAddrOfGlobalVar(VD); 1796 return; 1797 } 1798 } 1799 1800 // Defer code generation to first use when possible, e.g. if this is an inline 1801 // function. If the global must always be emitted, do it eagerly if possible 1802 // to benefit from cache locality. 1803 if (MustBeEmitted(Global) && MayBeEmittedEagerly(Global)) { 1804 // Emit the definition if it can't be deferred. 1805 EmitGlobalDefinition(GD); 1806 return; 1807 } 1808 1809 // If we're deferring emission of a C++ variable with an 1810 // initializer, remember the order in which it appeared in the file. 1811 if (getLangOpts().CPlusPlus && isa<VarDecl>(Global) && 1812 cast<VarDecl>(Global)->hasInit()) { 1813 DelayedCXXInitPosition[Global] = CXXGlobalInits.size(); 1814 CXXGlobalInits.push_back(nullptr); 1815 } 1816 1817 StringRef MangledName = getMangledName(GD); 1818 if (GetGlobalValue(MangledName) != nullptr) { 1819 // The value has already been used and should therefore be emitted. 1820 addDeferredDeclToEmit(GD); 1821 } else if (MustBeEmitted(Global)) { 1822 // The value must be emitted, but cannot be emitted eagerly. 1823 assert(!MayBeEmittedEagerly(Global)); 1824 addDeferredDeclToEmit(GD); 1825 } else { 1826 // Otherwise, remember that we saw a deferred decl with this name. The 1827 // first use of the mangled name will cause it to move into 1828 // DeferredDeclsToEmit. 1829 DeferredDecls[MangledName] = GD; 1830 } 1831 } 1832 1833 // Check if T is a class type with a destructor that's not dllimport. 1834 static bool HasNonDllImportDtor(QualType T) { 1835 if (const auto *RT = T->getBaseElementTypeUnsafe()->getAs<RecordType>()) 1836 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl())) 1837 if (RD->getDestructor() && !RD->getDestructor()->hasAttr<DLLImportAttr>()) 1838 return true; 1839 1840 return false; 1841 } 1842 1843 namespace { 1844 struct FunctionIsDirectlyRecursive : 1845 public RecursiveASTVisitor<FunctionIsDirectlyRecursive> { 1846 const StringRef Name; 1847 const Builtin::Context &BI; 1848 bool Result; 1849 FunctionIsDirectlyRecursive(StringRef N, const Builtin::Context &C) : 1850 Name(N), BI(C), Result(false) { 1851 } 1852 typedef RecursiveASTVisitor<FunctionIsDirectlyRecursive> Base; 1853 1854 bool TraverseCallExpr(CallExpr *E) { 1855 const FunctionDecl *FD = E->getDirectCallee(); 1856 if (!FD) 1857 return true; 1858 AsmLabelAttr *Attr = FD->getAttr<AsmLabelAttr>(); 1859 if (Attr && Name == Attr->getLabel()) { 1860 Result = true; 1861 return false; 1862 } 1863 unsigned BuiltinID = FD->getBuiltinID(); 1864 if (!BuiltinID || !BI.isLibFunction(BuiltinID)) 1865 return true; 1866 StringRef BuiltinName = BI.getName(BuiltinID); 1867 if (BuiltinName.startswith("__builtin_") && 1868 Name == BuiltinName.slice(strlen("__builtin_"), StringRef::npos)) { 1869 Result = true; 1870 return false; 1871 } 1872 return true; 1873 } 1874 }; 1875 1876 // Make sure we're not referencing non-imported vars or functions. 1877 struct DLLImportFunctionVisitor 1878 : public RecursiveASTVisitor<DLLImportFunctionVisitor> { 1879 bool SafeToInline = true; 1880 1881 bool shouldVisitImplicitCode() const { return true; } 1882 1883 bool VisitVarDecl(VarDecl *VD) { 1884 if (VD->getTLSKind()) { 1885 // A thread-local variable cannot be imported. 1886 SafeToInline = false; 1887 return SafeToInline; 1888 } 1889 1890 // A variable definition might imply a destructor call. 1891 if (VD->isThisDeclarationADefinition()) 1892 SafeToInline = !HasNonDllImportDtor(VD->getType()); 1893 1894 return SafeToInline; 1895 } 1896 1897 bool VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) { 1898 if (const auto *D = E->getTemporary()->getDestructor()) 1899 SafeToInline = D->hasAttr<DLLImportAttr>(); 1900 return SafeToInline; 1901 } 1902 1903 bool VisitDeclRefExpr(DeclRefExpr *E) { 1904 ValueDecl *VD = E->getDecl(); 1905 if (isa<FunctionDecl>(VD)) 1906 SafeToInline = VD->hasAttr<DLLImportAttr>(); 1907 else if (VarDecl *V = dyn_cast<VarDecl>(VD)) 1908 SafeToInline = !V->hasGlobalStorage() || V->hasAttr<DLLImportAttr>(); 1909 return SafeToInline; 1910 } 1911 1912 bool VisitCXXConstructExpr(CXXConstructExpr *E) { 1913 SafeToInline = E->getConstructor()->hasAttr<DLLImportAttr>(); 1914 return SafeToInline; 1915 } 1916 1917 bool VisitCXXMemberCallExpr(CXXMemberCallExpr *E) { 1918 CXXMethodDecl *M = E->getMethodDecl(); 1919 if (!M) { 1920 // Call through a pointer to member function. This is safe to inline. 1921 SafeToInline = true; 1922 } else { 1923 SafeToInline = M->hasAttr<DLLImportAttr>(); 1924 } 1925 return SafeToInline; 1926 } 1927 1928 bool VisitCXXDeleteExpr(CXXDeleteExpr *E) { 1929 SafeToInline = E->getOperatorDelete()->hasAttr<DLLImportAttr>(); 1930 return SafeToInline; 1931 } 1932 1933 bool VisitCXXNewExpr(CXXNewExpr *E) { 1934 SafeToInline = E->getOperatorNew()->hasAttr<DLLImportAttr>(); 1935 return SafeToInline; 1936 } 1937 }; 1938 } 1939 1940 // isTriviallyRecursive - Check if this function calls another 1941 // decl that, because of the asm attribute or the other decl being a builtin, 1942 // ends up pointing to itself. 1943 bool 1944 CodeGenModule::isTriviallyRecursive(const FunctionDecl *FD) { 1945 StringRef Name; 1946 if (getCXXABI().getMangleContext().shouldMangleDeclName(FD)) { 1947 // asm labels are a special kind of mangling we have to support. 1948 AsmLabelAttr *Attr = FD->getAttr<AsmLabelAttr>(); 1949 if (!Attr) 1950 return false; 1951 Name = Attr->getLabel(); 1952 } else { 1953 Name = FD->getName(); 1954 } 1955 1956 FunctionIsDirectlyRecursive Walker(Name, Context.BuiltinInfo); 1957 Walker.TraverseFunctionDecl(const_cast<FunctionDecl*>(FD)); 1958 return Walker.Result; 1959 } 1960 1961 bool CodeGenModule::shouldEmitFunction(GlobalDecl GD) { 1962 if (getFunctionLinkage(GD) != llvm::Function::AvailableExternallyLinkage) 1963 return true; 1964 const auto *F = cast<FunctionDecl>(GD.getDecl()); 1965 if (CodeGenOpts.OptimizationLevel == 0 && !F->hasAttr<AlwaysInlineAttr>()) 1966 return false; 1967 1968 if (F->hasAttr<DLLImportAttr>()) { 1969 // Check whether it would be safe to inline this dllimport function. 1970 DLLImportFunctionVisitor Visitor; 1971 Visitor.TraverseFunctionDecl(const_cast<FunctionDecl*>(F)); 1972 if (!Visitor.SafeToInline) 1973 return false; 1974 1975 if (const CXXDestructorDecl *Dtor = dyn_cast<CXXDestructorDecl>(F)) { 1976 // Implicit destructor invocations aren't captured in the AST, so the 1977 // check above can't see them. Check for them manually here. 1978 for (const Decl *Member : Dtor->getParent()->decls()) 1979 if (isa<FieldDecl>(Member)) 1980 if (HasNonDllImportDtor(cast<FieldDecl>(Member)->getType())) 1981 return false; 1982 for (const CXXBaseSpecifier &B : Dtor->getParent()->bases()) 1983 if (HasNonDllImportDtor(B.getType())) 1984 return false; 1985 } 1986 } 1987 1988 // PR9614. Avoid cases where the source code is lying to us. An available 1989 // externally function should have an equivalent function somewhere else, 1990 // but a function that calls itself is clearly not equivalent to the real 1991 // implementation. 1992 // This happens in glibc's btowc and in some configure checks. 1993 return !isTriviallyRecursive(F); 1994 } 1995 1996 bool CodeGenModule::shouldOpportunisticallyEmitVTables() { 1997 return CodeGenOpts.OptimizationLevel > 0; 1998 } 1999 2000 void CodeGenModule::EmitGlobalDefinition(GlobalDecl GD, llvm::GlobalValue *GV) { 2001 const auto *D = cast<ValueDecl>(GD.getDecl()); 2002 2003 PrettyStackTraceDecl CrashInfo(const_cast<ValueDecl *>(D), D->getLocation(), 2004 Context.getSourceManager(), 2005 "Generating code for declaration"); 2006 2007 if (isa<FunctionDecl>(D)) { 2008 // At -O0, don't generate IR for functions with available_externally 2009 // linkage. 2010 if (!shouldEmitFunction(GD)) 2011 return; 2012 2013 if (const auto *Method = dyn_cast<CXXMethodDecl>(D)) { 2014 // Make sure to emit the definition(s) before we emit the thunks. 2015 // This is necessary for the generation of certain thunks. 2016 if (const auto *CD = dyn_cast<CXXConstructorDecl>(Method)) 2017 ABI->emitCXXStructor(CD, getFromCtorType(GD.getCtorType())); 2018 else if (const auto *DD = dyn_cast<CXXDestructorDecl>(Method)) 2019 ABI->emitCXXStructor(DD, getFromDtorType(GD.getDtorType())); 2020 else 2021 EmitGlobalFunctionDefinition(GD, GV); 2022 2023 if (Method->isVirtual()) 2024 getVTables().EmitThunks(GD); 2025 2026 return; 2027 } 2028 2029 return EmitGlobalFunctionDefinition(GD, GV); 2030 } 2031 2032 if (const auto *VD = dyn_cast<VarDecl>(D)) 2033 return EmitGlobalVarDefinition(VD, !VD->hasDefinition()); 2034 2035 llvm_unreachable("Invalid argument to EmitGlobalDefinition()"); 2036 } 2037 2038 static void ReplaceUsesOfNonProtoTypeWithRealFunction(llvm::GlobalValue *Old, 2039 llvm::Function *NewFn); 2040 2041 /// GetOrCreateLLVMFunction - If the specified mangled name is not in the 2042 /// module, create and return an llvm Function with the specified type. If there 2043 /// is something in the module with the specified name, return it potentially 2044 /// bitcasted to the right type. 2045 /// 2046 /// If D is non-null, it specifies a decl that correspond to this. This is used 2047 /// to set the attributes on the function when it is first created. 2048 llvm::Constant *CodeGenModule::GetOrCreateLLVMFunction( 2049 StringRef MangledName, llvm::Type *Ty, GlobalDecl GD, bool ForVTable, 2050 bool DontDefer, bool IsThunk, llvm::AttributeList ExtraAttrs, 2051 ForDefinition_t IsForDefinition) { 2052 const Decl *D = GD.getDecl(); 2053 2054 // Lookup the entry, lazily creating it if necessary. 2055 llvm::GlobalValue *Entry = GetGlobalValue(MangledName); 2056 if (Entry) { 2057 if (WeakRefReferences.erase(Entry)) { 2058 const FunctionDecl *FD = cast_or_null<FunctionDecl>(D); 2059 if (FD && !FD->hasAttr<WeakAttr>()) 2060 Entry->setLinkage(llvm::Function::ExternalLinkage); 2061 } 2062 2063 // Handle dropped DLL attributes. 2064 if (D && !D->hasAttr<DLLImportAttr>() && !D->hasAttr<DLLExportAttr>()) 2065 Entry->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass); 2066 2067 // If there are two attempts to define the same mangled name, issue an 2068 // error. 2069 if (IsForDefinition && !Entry->isDeclaration()) { 2070 GlobalDecl OtherGD; 2071 // Check that GD is not yet in DiagnosedConflictingDefinitions is required 2072 // to make sure that we issue an error only once. 2073 if (lookupRepresentativeDecl(MangledName, OtherGD) && 2074 (GD.getCanonicalDecl().getDecl() != 2075 OtherGD.getCanonicalDecl().getDecl()) && 2076 DiagnosedConflictingDefinitions.insert(GD).second) { 2077 getDiags().Report(D->getLocation(), 2078 diag::err_duplicate_mangled_name); 2079 getDiags().Report(OtherGD.getDecl()->getLocation(), 2080 diag::note_previous_definition); 2081 } 2082 } 2083 2084 if ((isa<llvm::Function>(Entry) || isa<llvm::GlobalAlias>(Entry)) && 2085 (Entry->getType()->getElementType() == Ty)) { 2086 return Entry; 2087 } 2088 2089 // Make sure the result is of the correct type. 2090 // (If function is requested for a definition, we always need to create a new 2091 // function, not just return a bitcast.) 2092 if (!IsForDefinition) 2093 return llvm::ConstantExpr::getBitCast(Entry, Ty->getPointerTo()); 2094 } 2095 2096 // This function doesn't have a complete type (for example, the return 2097 // type is an incomplete struct). Use a fake type instead, and make 2098 // sure not to try to set attributes. 2099 bool IsIncompleteFunction = false; 2100 2101 llvm::FunctionType *FTy; 2102 if (isa<llvm::FunctionType>(Ty)) { 2103 FTy = cast<llvm::FunctionType>(Ty); 2104 } else { 2105 FTy = llvm::FunctionType::get(VoidTy, false); 2106 IsIncompleteFunction = true; 2107 } 2108 2109 llvm::Function *F = 2110 llvm::Function::Create(FTy, llvm::Function::ExternalLinkage, 2111 Entry ? StringRef() : MangledName, &getModule()); 2112 2113 // If we already created a function with the same mangled name (but different 2114 // type) before, take its name and add it to the list of functions to be 2115 // replaced with F at the end of CodeGen. 2116 // 2117 // This happens if there is a prototype for a function (e.g. "int f()") and 2118 // then a definition of a different type (e.g. "int f(int x)"). 2119 if (Entry) { 2120 F->takeName(Entry); 2121 2122 // This might be an implementation of a function without a prototype, in 2123 // which case, try to do special replacement of calls which match the new 2124 // prototype. The really key thing here is that we also potentially drop 2125 // arguments from the call site so as to make a direct call, which makes the 2126 // inliner happier and suppresses a number of optimizer warnings (!) about 2127 // dropping arguments. 2128 if (!Entry->use_empty()) { 2129 ReplaceUsesOfNonProtoTypeWithRealFunction(Entry, F); 2130 Entry->removeDeadConstantUsers(); 2131 } 2132 2133 llvm::Constant *BC = llvm::ConstantExpr::getBitCast( 2134 F, Entry->getType()->getElementType()->getPointerTo()); 2135 addGlobalValReplacement(Entry, BC); 2136 } 2137 2138 assert(F->getName() == MangledName && "name was uniqued!"); 2139 if (D) 2140 SetFunctionAttributes(GD, F, IsIncompleteFunction, IsThunk, 2141 IsForDefinition); 2142 if (ExtraAttrs.hasAttributes(llvm::AttributeList::FunctionIndex)) { 2143 llvm::AttrBuilder B(ExtraAttrs, llvm::AttributeList::FunctionIndex); 2144 F->addAttributes(llvm::AttributeList::FunctionIndex, B); 2145 } 2146 2147 if (!DontDefer) { 2148 // All MSVC dtors other than the base dtor are linkonce_odr and delegate to 2149 // each other bottoming out with the base dtor. Therefore we emit non-base 2150 // dtors on usage, even if there is no dtor definition in the TU. 2151 if (D && isa<CXXDestructorDecl>(D) && 2152 getCXXABI().useThunkForDtorVariant(cast<CXXDestructorDecl>(D), 2153 GD.getDtorType())) 2154 addDeferredDeclToEmit(GD); 2155 2156 // This is the first use or definition of a mangled name. If there is a 2157 // deferred decl with this name, remember that we need to emit it at the end 2158 // of the file. 2159 auto DDI = DeferredDecls.find(MangledName); 2160 if (DDI != DeferredDecls.end()) { 2161 // Move the potentially referenced deferred decl to the 2162 // DeferredDeclsToEmit list, and remove it from DeferredDecls (since we 2163 // don't need it anymore). 2164 addDeferredDeclToEmit(DDI->second); 2165 DeferredDecls.erase(DDI); 2166 2167 // Otherwise, there are cases we have to worry about where we're 2168 // using a declaration for which we must emit a definition but where 2169 // we might not find a top-level definition: 2170 // - member functions defined inline in their classes 2171 // - friend functions defined inline in some class 2172 // - special member functions with implicit definitions 2173 // If we ever change our AST traversal to walk into class methods, 2174 // this will be unnecessary. 2175 // 2176 // We also don't emit a definition for a function if it's going to be an 2177 // entry in a vtable, unless it's already marked as used. 2178 } else if (getLangOpts().CPlusPlus && D) { 2179 // Look for a declaration that's lexically in a record. 2180 for (const auto *FD = cast<FunctionDecl>(D)->getMostRecentDecl(); FD; 2181 FD = FD->getPreviousDecl()) { 2182 if (isa<CXXRecordDecl>(FD->getLexicalDeclContext())) { 2183 if (FD->doesThisDeclarationHaveABody()) { 2184 addDeferredDeclToEmit(GD.getWithDecl(FD)); 2185 break; 2186 } 2187 } 2188 } 2189 } 2190 } 2191 2192 // Make sure the result is of the requested type. 2193 if (!IsIncompleteFunction) { 2194 assert(F->getType()->getElementType() == Ty); 2195 return F; 2196 } 2197 2198 llvm::Type *PTy = llvm::PointerType::getUnqual(Ty); 2199 return llvm::ConstantExpr::getBitCast(F, PTy); 2200 } 2201 2202 /// GetAddrOfFunction - Return the address of the given function. If Ty is 2203 /// non-null, then this function will use the specified type if it has to 2204 /// create it (this occurs when we see a definition of the function). 2205 llvm::Constant *CodeGenModule::GetAddrOfFunction(GlobalDecl GD, 2206 llvm::Type *Ty, 2207 bool ForVTable, 2208 bool DontDefer, 2209 ForDefinition_t IsForDefinition) { 2210 // If there was no specific requested type, just convert it now. 2211 if (!Ty) { 2212 const auto *FD = cast<FunctionDecl>(GD.getDecl()); 2213 auto CanonTy = Context.getCanonicalType(FD->getType()); 2214 Ty = getTypes().ConvertFunctionType(CanonTy, FD); 2215 } 2216 2217 StringRef MangledName = getMangledName(GD); 2218 return GetOrCreateLLVMFunction(MangledName, Ty, GD, ForVTable, DontDefer, 2219 /*IsThunk=*/false, llvm::AttributeList(), 2220 IsForDefinition); 2221 } 2222 2223 static const FunctionDecl * 2224 GetRuntimeFunctionDecl(ASTContext &C, StringRef Name) { 2225 TranslationUnitDecl *TUDecl = C.getTranslationUnitDecl(); 2226 DeclContext *DC = TranslationUnitDecl::castToDeclContext(TUDecl); 2227 2228 IdentifierInfo &CII = C.Idents.get(Name); 2229 for (const auto &Result : DC->lookup(&CII)) 2230 if (const auto FD = dyn_cast<FunctionDecl>(Result)) 2231 return FD; 2232 2233 if (!C.getLangOpts().CPlusPlus) 2234 return nullptr; 2235 2236 // Demangle the premangled name from getTerminateFn() 2237 IdentifierInfo &CXXII = 2238 (Name == "_ZSt9terminatev" || Name == "\01?terminate@@YAXXZ") 2239 ? C.Idents.get("terminate") 2240 : C.Idents.get(Name); 2241 2242 for (const auto &N : {"__cxxabiv1", "std"}) { 2243 IdentifierInfo &NS = C.Idents.get(N); 2244 for (const auto &Result : DC->lookup(&NS)) { 2245 NamespaceDecl *ND = dyn_cast<NamespaceDecl>(Result); 2246 if (auto LSD = dyn_cast<LinkageSpecDecl>(Result)) 2247 for (const auto &Result : LSD->lookup(&NS)) 2248 if ((ND = dyn_cast<NamespaceDecl>(Result))) 2249 break; 2250 2251 if (ND) 2252 for (const auto &Result : ND->lookup(&CXXII)) 2253 if (const auto *FD = dyn_cast<FunctionDecl>(Result)) 2254 return FD; 2255 } 2256 } 2257 2258 return nullptr; 2259 } 2260 2261 /// CreateRuntimeFunction - Create a new runtime function with the specified 2262 /// type and name. 2263 llvm::Constant * 2264 CodeGenModule::CreateRuntimeFunction(llvm::FunctionType *FTy, StringRef Name, 2265 llvm::AttributeList ExtraAttrs, 2266 bool Local) { 2267 llvm::Constant *C = 2268 GetOrCreateLLVMFunction(Name, FTy, GlobalDecl(), /*ForVTable=*/false, 2269 /*DontDefer=*/false, /*IsThunk=*/false, 2270 ExtraAttrs); 2271 2272 if (auto *F = dyn_cast<llvm::Function>(C)) { 2273 if (F->empty()) { 2274 F->setCallingConv(getRuntimeCC()); 2275 2276 if (!Local && getTriple().isOSBinFormatCOFF() && 2277 !getCodeGenOpts().LTOVisibilityPublicStd) { 2278 const FunctionDecl *FD = GetRuntimeFunctionDecl(Context, Name); 2279 if (!FD || FD->hasAttr<DLLImportAttr>()) { 2280 F->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass); 2281 F->setLinkage(llvm::GlobalValue::ExternalLinkage); 2282 } 2283 } 2284 } 2285 } 2286 2287 return C; 2288 } 2289 2290 /// CreateBuiltinFunction - Create a new builtin function with the specified 2291 /// type and name. 2292 llvm::Constant * 2293 CodeGenModule::CreateBuiltinFunction(llvm::FunctionType *FTy, StringRef Name, 2294 llvm::AttributeList ExtraAttrs) { 2295 llvm::Constant *C = 2296 GetOrCreateLLVMFunction(Name, FTy, GlobalDecl(), /*ForVTable=*/false, 2297 /*DontDefer=*/false, /*IsThunk=*/false, ExtraAttrs); 2298 if (auto *F = dyn_cast<llvm::Function>(C)) 2299 if (F->empty()) 2300 F->setCallingConv(getBuiltinCC()); 2301 return C; 2302 } 2303 2304 /// isTypeConstant - Determine whether an object of this type can be emitted 2305 /// as a constant. 2306 /// 2307 /// If ExcludeCtor is true, the duration when the object's constructor runs 2308 /// will not be considered. The caller will need to verify that the object is 2309 /// not written to during its construction. 2310 bool CodeGenModule::isTypeConstant(QualType Ty, bool ExcludeCtor) { 2311 if (!Ty.isConstant(Context) && !Ty->isReferenceType()) 2312 return false; 2313 2314 if (Context.getLangOpts().CPlusPlus) { 2315 if (const CXXRecordDecl *Record 2316 = Context.getBaseElementType(Ty)->getAsCXXRecordDecl()) 2317 return ExcludeCtor && !Record->hasMutableFields() && 2318 Record->hasTrivialDestructor(); 2319 } 2320 2321 return true; 2322 } 2323 2324 /// GetOrCreateLLVMGlobal - If the specified mangled name is not in the module, 2325 /// create and return an llvm GlobalVariable with the specified type. If there 2326 /// is something in the module with the specified name, return it potentially 2327 /// bitcasted to the right type. 2328 /// 2329 /// If D is non-null, it specifies a decl that correspond to this. This is used 2330 /// to set the attributes on the global when it is first created. 2331 /// 2332 /// If IsForDefinition is true, it is guranteed that an actual global with 2333 /// type Ty will be returned, not conversion of a variable with the same 2334 /// mangled name but some other type. 2335 llvm::Constant * 2336 CodeGenModule::GetOrCreateLLVMGlobal(StringRef MangledName, 2337 llvm::PointerType *Ty, 2338 const VarDecl *D, 2339 ForDefinition_t IsForDefinition) { 2340 // Lookup the entry, lazily creating it if necessary. 2341 llvm::GlobalValue *Entry = GetGlobalValue(MangledName); 2342 if (Entry) { 2343 if (WeakRefReferences.erase(Entry)) { 2344 if (D && !D->hasAttr<WeakAttr>()) 2345 Entry->setLinkage(llvm::Function::ExternalLinkage); 2346 } 2347 2348 // Handle dropped DLL attributes. 2349 if (D && !D->hasAttr<DLLImportAttr>() && !D->hasAttr<DLLExportAttr>()) 2350 Entry->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass); 2351 2352 if (Entry->getType() == Ty) 2353 return Entry; 2354 2355 // If there are two attempts to define the same mangled name, issue an 2356 // error. 2357 if (IsForDefinition && !Entry->isDeclaration()) { 2358 GlobalDecl OtherGD; 2359 const VarDecl *OtherD; 2360 2361 // Check that D is not yet in DiagnosedConflictingDefinitions is required 2362 // to make sure that we issue an error only once. 2363 if (D && lookupRepresentativeDecl(MangledName, OtherGD) && 2364 (D->getCanonicalDecl() != OtherGD.getCanonicalDecl().getDecl()) && 2365 (OtherD = dyn_cast<VarDecl>(OtherGD.getDecl())) && 2366 OtherD->hasInit() && 2367 DiagnosedConflictingDefinitions.insert(D).second) { 2368 getDiags().Report(D->getLocation(), 2369 diag::err_duplicate_mangled_name); 2370 getDiags().Report(OtherGD.getDecl()->getLocation(), 2371 diag::note_previous_definition); 2372 } 2373 } 2374 2375 // Make sure the result is of the correct type. 2376 if (Entry->getType()->getAddressSpace() != Ty->getAddressSpace()) 2377 return llvm::ConstantExpr::getAddrSpaceCast(Entry, Ty); 2378 2379 // (If global is requested for a definition, we always need to create a new 2380 // global, not just return a bitcast.) 2381 if (!IsForDefinition) 2382 return llvm::ConstantExpr::getBitCast(Entry, Ty); 2383 } 2384 2385 auto AddrSpace = GetGlobalVarAddressSpace(D); 2386 auto TargetAddrSpace = getContext().getTargetAddressSpace(AddrSpace); 2387 2388 auto *GV = new llvm::GlobalVariable( 2389 getModule(), Ty->getElementType(), false, 2390 llvm::GlobalValue::ExternalLinkage, nullptr, MangledName, nullptr, 2391 llvm::GlobalVariable::NotThreadLocal, TargetAddrSpace); 2392 2393 // If we already created a global with the same mangled name (but different 2394 // type) before, take its name and remove it from its parent. 2395 if (Entry) { 2396 GV->takeName(Entry); 2397 2398 if (!Entry->use_empty()) { 2399 llvm::Constant *NewPtrForOldDecl = 2400 llvm::ConstantExpr::getBitCast(GV, Entry->getType()); 2401 Entry->replaceAllUsesWith(NewPtrForOldDecl); 2402 } 2403 2404 Entry->eraseFromParent(); 2405 } 2406 2407 // This is the first use or definition of a mangled name. If there is a 2408 // deferred decl with this name, remember that we need to emit it at the end 2409 // of the file. 2410 auto DDI = DeferredDecls.find(MangledName); 2411 if (DDI != DeferredDecls.end()) { 2412 // Move the potentially referenced deferred decl to the DeferredDeclsToEmit 2413 // list, and remove it from DeferredDecls (since we don't need it anymore). 2414 addDeferredDeclToEmit(DDI->second); 2415 DeferredDecls.erase(DDI); 2416 } 2417 2418 // Handle things which are present even on external declarations. 2419 if (D) { 2420 // FIXME: This code is overly simple and should be merged with other global 2421 // handling. 2422 GV->setConstant(isTypeConstant(D->getType(), false)); 2423 2424 GV->setAlignment(getContext().getDeclAlign(D).getQuantity()); 2425 2426 setLinkageAndVisibilityForGV(GV, D); 2427 2428 if (D->getTLSKind()) { 2429 if (D->getTLSKind() == VarDecl::TLS_Dynamic) 2430 CXXThreadLocals.push_back(D); 2431 setTLSMode(GV, *D); 2432 } 2433 2434 // If required by the ABI, treat declarations of static data members with 2435 // inline initializers as definitions. 2436 if (getContext().isMSStaticDataMemberInlineDefinition(D)) { 2437 EmitGlobalVarDefinition(D); 2438 } 2439 2440 // Emit section information for extern variables. 2441 if (D->hasExternalStorage()) { 2442 if (const SectionAttr *SA = D->getAttr<SectionAttr>()) 2443 GV->setSection(SA->getName()); 2444 } 2445 2446 // Handle XCore specific ABI requirements. 2447 if (getTriple().getArch() == llvm::Triple::xcore && 2448 D->getLanguageLinkage() == CLanguageLinkage && 2449 D->getType().isConstant(Context) && 2450 isExternallyVisible(D->getLinkageAndVisibility().getLinkage())) 2451 GV->setSection(".cp.rodata"); 2452 2453 // Check if we a have a const declaration with an initializer, we may be 2454 // able to emit it as available_externally to expose it's value to the 2455 // optimizer. 2456 if (Context.getLangOpts().CPlusPlus && GV->hasExternalLinkage() && 2457 D->getType().isConstQualified() && !GV->hasInitializer() && 2458 !D->hasDefinition() && D->hasInit() && !D->hasAttr<DLLImportAttr>()) { 2459 const auto *Record = 2460 Context.getBaseElementType(D->getType())->getAsCXXRecordDecl(); 2461 bool HasMutableFields = Record && Record->hasMutableFields(); 2462 if (!HasMutableFields) { 2463 const VarDecl *InitDecl; 2464 const Expr *InitExpr = D->getAnyInitializer(InitDecl); 2465 if (InitExpr) { 2466 ConstantEmitter emitter(*this); 2467 llvm::Constant *Init = emitter.tryEmitForInitializer(*InitDecl); 2468 if (Init) { 2469 auto *InitType = Init->getType(); 2470 if (GV->getType()->getElementType() != InitType) { 2471 // The type of the initializer does not match the definition. 2472 // This happens when an initializer has a different type from 2473 // the type of the global (because of padding at the end of a 2474 // structure for instance). 2475 GV->setName(StringRef()); 2476 // Make a new global with the correct type, this is now guaranteed 2477 // to work. 2478 auto *NewGV = cast<llvm::GlobalVariable>( 2479 GetAddrOfGlobalVar(D, InitType, IsForDefinition)); 2480 2481 // Erase the old global, since it is no longer used. 2482 cast<llvm::GlobalValue>(GV)->eraseFromParent(); 2483 GV = NewGV; 2484 } else { 2485 GV->setInitializer(Init); 2486 GV->setConstant(true); 2487 GV->setLinkage(llvm::GlobalValue::AvailableExternallyLinkage); 2488 } 2489 emitter.finalize(GV); 2490 } 2491 } 2492 } 2493 } 2494 } 2495 2496 LangAS ExpectedAS = 2497 D ? D->getType().getAddressSpace() 2498 : (LangOpts.OpenCL ? LangAS::opencl_global : LangAS::Default); 2499 assert(getContext().getTargetAddressSpace(ExpectedAS) == 2500 Ty->getPointerAddressSpace()); 2501 if (AddrSpace != ExpectedAS) 2502 return getTargetCodeGenInfo().performAddrSpaceCast(*this, GV, AddrSpace, 2503 ExpectedAS, Ty); 2504 2505 return GV; 2506 } 2507 2508 llvm::Constant * 2509 CodeGenModule::GetAddrOfGlobal(GlobalDecl GD, 2510 ForDefinition_t IsForDefinition) { 2511 const Decl *D = GD.getDecl(); 2512 if (isa<CXXConstructorDecl>(D)) 2513 return getAddrOfCXXStructor(cast<CXXConstructorDecl>(D), 2514 getFromCtorType(GD.getCtorType()), 2515 /*FnInfo=*/nullptr, /*FnType=*/nullptr, 2516 /*DontDefer=*/false, IsForDefinition); 2517 else if (isa<CXXDestructorDecl>(D)) 2518 return getAddrOfCXXStructor(cast<CXXDestructorDecl>(D), 2519 getFromDtorType(GD.getDtorType()), 2520 /*FnInfo=*/nullptr, /*FnType=*/nullptr, 2521 /*DontDefer=*/false, IsForDefinition); 2522 else if (isa<CXXMethodDecl>(D)) { 2523 auto FInfo = &getTypes().arrangeCXXMethodDeclaration( 2524 cast<CXXMethodDecl>(D)); 2525 auto Ty = getTypes().GetFunctionType(*FInfo); 2526 return GetAddrOfFunction(GD, Ty, /*ForVTable=*/false, /*DontDefer=*/false, 2527 IsForDefinition); 2528 } else if (isa<FunctionDecl>(D)) { 2529 const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD); 2530 llvm::FunctionType *Ty = getTypes().GetFunctionType(FI); 2531 return GetAddrOfFunction(GD, Ty, /*ForVTable=*/false, /*DontDefer=*/false, 2532 IsForDefinition); 2533 } else 2534 return GetAddrOfGlobalVar(cast<VarDecl>(D), /*Ty=*/nullptr, 2535 IsForDefinition); 2536 } 2537 2538 llvm::GlobalVariable * 2539 CodeGenModule::CreateOrReplaceCXXRuntimeVariable(StringRef Name, 2540 llvm::Type *Ty, 2541 llvm::GlobalValue::LinkageTypes Linkage) { 2542 llvm::GlobalVariable *GV = getModule().getNamedGlobal(Name); 2543 llvm::GlobalVariable *OldGV = nullptr; 2544 2545 if (GV) { 2546 // Check if the variable has the right type. 2547 if (GV->getType()->getElementType() == Ty) 2548 return GV; 2549 2550 // Because C++ name mangling, the only way we can end up with an already 2551 // existing global with the same name is if it has been declared extern "C". 2552 assert(GV->isDeclaration() && "Declaration has wrong type!"); 2553 OldGV = GV; 2554 } 2555 2556 // Create a new variable. 2557 GV = new llvm::GlobalVariable(getModule(), Ty, /*isConstant=*/true, 2558 Linkage, nullptr, Name); 2559 2560 if (OldGV) { 2561 // Replace occurrences of the old variable if needed. 2562 GV->takeName(OldGV); 2563 2564 if (!OldGV->use_empty()) { 2565 llvm::Constant *NewPtrForOldDecl = 2566 llvm::ConstantExpr::getBitCast(GV, OldGV->getType()); 2567 OldGV->replaceAllUsesWith(NewPtrForOldDecl); 2568 } 2569 2570 OldGV->eraseFromParent(); 2571 } 2572 2573 if (supportsCOMDAT() && GV->isWeakForLinker() && 2574 !GV->hasAvailableExternallyLinkage()) 2575 GV->setComdat(TheModule.getOrInsertComdat(GV->getName())); 2576 2577 return GV; 2578 } 2579 2580 /// GetAddrOfGlobalVar - Return the llvm::Constant for the address of the 2581 /// given global variable. If Ty is non-null and if the global doesn't exist, 2582 /// then it will be created with the specified type instead of whatever the 2583 /// normal requested type would be. If IsForDefinition is true, it is guranteed 2584 /// that an actual global with type Ty will be returned, not conversion of a 2585 /// variable with the same mangled name but some other type. 2586 llvm::Constant *CodeGenModule::GetAddrOfGlobalVar(const VarDecl *D, 2587 llvm::Type *Ty, 2588 ForDefinition_t IsForDefinition) { 2589 assert(D->hasGlobalStorage() && "Not a global variable"); 2590 QualType ASTTy = D->getType(); 2591 if (!Ty) 2592 Ty = getTypes().ConvertTypeForMem(ASTTy); 2593 2594 llvm::PointerType *PTy = 2595 llvm::PointerType::get(Ty, getContext().getTargetAddressSpace(ASTTy)); 2596 2597 StringRef MangledName = getMangledName(D); 2598 return GetOrCreateLLVMGlobal(MangledName, PTy, D, IsForDefinition); 2599 } 2600 2601 /// CreateRuntimeVariable - Create a new runtime global variable with the 2602 /// specified type and name. 2603 llvm::Constant * 2604 CodeGenModule::CreateRuntimeVariable(llvm::Type *Ty, 2605 StringRef Name) { 2606 return GetOrCreateLLVMGlobal(Name, llvm::PointerType::getUnqual(Ty), nullptr); 2607 } 2608 2609 void CodeGenModule::EmitTentativeDefinition(const VarDecl *D) { 2610 assert(!D->getInit() && "Cannot emit definite definitions here!"); 2611 2612 StringRef MangledName = getMangledName(D); 2613 llvm::GlobalValue *GV = GetGlobalValue(MangledName); 2614 2615 // We already have a definition, not declaration, with the same mangled name. 2616 // Emitting of declaration is not required (and actually overwrites emitted 2617 // definition). 2618 if (GV && !GV->isDeclaration()) 2619 return; 2620 2621 // If we have not seen a reference to this variable yet, place it into the 2622 // deferred declarations table to be emitted if needed later. 2623 if (!MustBeEmitted(D) && !GV) { 2624 DeferredDecls[MangledName] = D; 2625 return; 2626 } 2627 2628 // The tentative definition is the only definition. 2629 EmitGlobalVarDefinition(D); 2630 } 2631 2632 CharUnits CodeGenModule::GetTargetTypeStoreSize(llvm::Type *Ty) const { 2633 return Context.toCharUnitsFromBits( 2634 getDataLayout().getTypeStoreSizeInBits(Ty)); 2635 } 2636 2637 LangAS CodeGenModule::GetGlobalVarAddressSpace(const VarDecl *D) { 2638 LangAS AddrSpace = LangAS::Default; 2639 if (LangOpts.OpenCL) { 2640 AddrSpace = D ? D->getType().getAddressSpace() : 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 LangAS 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