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