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