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