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