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