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