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