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