47 #include "llvm/ADT/Triple.h"
48 #include "llvm/Analysis/TargetLibraryInfo.h"
49 #include "llvm/IR/CallSite.h"
50 #include "llvm/IR/CallingConv.h"
51 #include "llvm/IR/DataLayout.h"
52 #include "llvm/IR/Intrinsics.h"
53 #include "llvm/IR/LLVMContext.h"
54 #include "llvm/IR/Module.h"
55 #include "llvm/ProfileData/InstrProfReader.h"
56 #include "llvm/Support/ConvertUTF.h"
57 #include "llvm/Support/ErrorHandling.h"
58 #include "llvm/Support/MD5.h"
60 using namespace clang;
61 using namespace CodeGen;
80 llvm_unreachable(
"invalid C++ ABI kind");
88 :
Context(C), LangOpts(C.getLangOpts()), HeaderSearchOpts(HSO),
89 PreprocessorOpts(PPO), CodeGenOpts(CGO), TheModule(M), Diags(diags),
91 VMContext(M.getContext()), Types(*this), VTables(*this),
95 llvm::LLVMContext &LLVMContext = M.getContext();
96 VoidTy = llvm::Type::getVoidTy(LLVMContext);
97 Int8Ty = llvm::Type::getInt8Ty(LLVMContext);
98 Int16Ty = llvm::Type::getInt16Ty(LLVMContext);
99 Int32Ty = llvm::Type::getInt32Ty(LLVMContext);
100 Int64Ty = llvm::Type::getInt64Ty(LLVMContext);
101 FloatTy = llvm::Type::getFloatTy(LLVMContext);
102 DoubleTy = llvm::Type::getDoubleTy(LLVMContext);
111 IntPtrTy = llvm::IntegerType::get(LLVMContext,
116 M.getDataLayout().getAllocaAddrSpace());
125 createOpenCLRuntime();
127 createOpenMPRuntime();
132 if (LangOpts.
Sanitize.
has(SanitizerKind::Thread) ||
133 (!CodeGenOpts.RelaxedAliasing && CodeGenOpts.OptimizationLevel > 0))
140 CodeGenOpts.EmitGcovArcs || CodeGenOpts.EmitGcovNotes)
143 Block.GlobalUniqueCount = 0;
151 if (
auto E = ReaderOrErr.takeError()) {
153 "Could not read profile %0: %1");
154 llvm::handleAllErrors(std::move(
E), [&](
const llvm::ErrorInfoBase &EI) {
159 PGOReader = std::move(ReaderOrErr.get());
164 if (CodeGenOpts.CoverageMapping)
170 void CodeGenModule::createObjCRuntime() {
187 llvm_unreachable(
"bad runtime kind");
190 void CodeGenModule::createOpenCLRuntime() {
194 void CodeGenModule::createOpenMPRuntime() {
198 case llvm::Triple::nvptx:
199 case llvm::Triple::nvptx64:
201 "OpenMP NVPTX is only prepared to deal with device code.");
210 void CodeGenModule::createCUDARuntime() {
215 Replacements[
Name] = C;
218 void CodeGenModule::applyReplacements() {
219 for (
auto &
I : Replacements) {
220 StringRef MangledName =
I.first();
225 auto *OldF = cast<llvm::Function>(Entry);
226 auto *NewF = dyn_cast<llvm::Function>(
Replacement);
228 if (
auto *Alias = dyn_cast<llvm::GlobalAlias>(Replacement)) {
229 NewF = dyn_cast<llvm::Function>(Alias->getAliasee());
232 assert(CE->getOpcode() == llvm::Instruction::BitCast ||
233 CE->getOpcode() == llvm::Instruction::GetElementPtr);
234 NewF = dyn_cast<llvm::Function>(CE->getOperand(0));
239 OldF->replaceAllUsesWith(Replacement);
241 NewF->removeFromParent();
242 OldF->getParent()->getFunctionList().insertAfter(OldF->getIterator(),
245 OldF->eraseFromParent();
250 GlobalValReplacements.push_back(std::make_pair(GV, C));
253 void CodeGenModule::applyGlobalValReplacements() {
254 for (
auto &
I : GlobalValReplacements) {
255 llvm::GlobalValue *GV =
I.first;
256 llvm::Constant *C =
I.second;
258 GV->replaceAllUsesWith(C);
259 GV->eraseFromParent();
266 const llvm::GlobalIndirectSymbol &GIS) {
267 llvm::SmallPtrSet<const llvm::GlobalIndirectSymbol*, 4> Visited;
268 const llvm::Constant *C = &GIS;
270 C = C->stripPointerCasts();
271 if (
auto *GO = dyn_cast<llvm::GlobalObject>(C))
274 auto *GIS2 = dyn_cast<llvm::GlobalIndirectSymbol>(C);
277 if (!Visited.insert(GIS2).second)
279 C = GIS2->getIndirectSymbol();
283 void CodeGenModule::checkAliases() {
290 const auto *D = cast<ValueDecl>(GD.getDecl());
292 bool IsIFunc = D->hasAttr<IFuncAttr>();
293 if (
const Attr *A = D->getDefiningAttr())
294 Location = A->getLocation();
296 llvm_unreachable(
"Not an alias or ifunc?");
299 auto *Alias = cast<llvm::GlobalIndirectSymbol>(Entry);
303 Diags.
Report(Location, diag::err_cyclic_alias) << IsIFunc;
304 }
else if (GV->isDeclaration()) {
306 Diags.
Report(Location, diag::err_alias_to_undefined)
307 << IsIFunc << IsIFunc;
308 }
else if (IsIFunc) {
310 llvm::FunctionType *FTy = dyn_cast<llvm::FunctionType>(
311 GV->getType()->getPointerElementType());
313 if (!FTy->getReturnType()->isPointerTy())
314 Diags.
Report(Location, diag::err_ifunc_resolver_return);
315 if (FTy->getNumParams())
316 Diags.
Report(Location, diag::err_ifunc_resolver_params);
319 llvm::Constant *Aliasee = Alias->getIndirectSymbol();
320 llvm::GlobalValue *AliaseeGV;
321 if (
auto CE = dyn_cast<llvm::ConstantExpr>(Aliasee))
322 AliaseeGV = cast<llvm::GlobalValue>(CE->getOperand(0));
324 AliaseeGV = cast<llvm::GlobalValue>(Aliasee);
326 if (
const SectionAttr *SA = D->getAttr<SectionAttr>()) {
327 StringRef AliasSection = SA->getName();
328 if (AliasSection != AliaseeGV->getSection())
329 Diags.
Report(SA->getLocation(), diag::warn_alias_with_section)
330 << AliasSection << IsIFunc << IsIFunc;
338 if (
auto GA = dyn_cast<llvm::GlobalIndirectSymbol>(AliaseeGV)) {
339 if (GA->isInterposable()) {
340 Diags.
Report(Location, diag::warn_alias_to_weak_alias)
341 << GV->getName() << GA->getName() << IsIFunc;
342 Aliasee = llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(
343 GA->getIndirectSymbol(), Alias->getType());
344 Alias->setIndirectSymbol(Aliasee);
354 auto *Alias = dyn_cast<llvm::GlobalIndirectSymbol>(Entry);
355 Alias->replaceAllUsesWith(llvm::UndefValue::get(Alias->getType()));
356 Alias->eraseFromParent();
361 DeferredDeclsToEmit.clear();
363 OpenMPRuntime->clear();
367 StringRef MainFile) {
370 if (VisitedInMainFile > 0 && VisitedInMainFile == MissingInMainFile) {
371 if (MainFile.empty())
372 MainFile =
"<stdin>";
373 Diags.
Report(diag::warn_profile_data_unprofiled) << MainFile;
376 Diags.
Report(diag::warn_profile_data_out_of_date) << Visited << Mismatched;
379 Diags.
Report(diag::warn_profile_data_missing) << Visited << Missing;
385 EmitVTablesOpportunistically();
386 applyGlobalValReplacements();
389 EmitCXXGlobalInitFunc();
390 EmitCXXGlobalDtorFunc();
391 EmitCXXThreadLocalInitFunc();
393 if (llvm::Function *ObjCInitFunction =
ObjCRuntime->ModuleInitFunction())
394 AddGlobalCtor(ObjCInitFunction);
397 if (llvm::Function *CudaCtorFunction = CUDARuntime->makeModuleCtorFunction())
398 AddGlobalCtor(CudaCtorFunction);
399 if (llvm::Function *CudaDtorFunction = CUDARuntime->makeModuleDtorFunction())
400 AddGlobalDtor(CudaDtorFunction);
403 if (llvm::Function *OpenMPRegistrationFunction =
404 OpenMPRuntime->emitRegistrationFunction()) {
405 auto ComdatKey = OpenMPRegistrationFunction->hasComdat() ?
406 OpenMPRegistrationFunction :
nullptr;
407 AddGlobalCtor(OpenMPRegistrationFunction, 0, ComdatKey);
410 getModule().setProfileSummary(PGOReader->getSummary().getMD(VMContext));
414 EmitCtorList(GlobalCtors,
"llvm.global_ctors");
415 EmitCtorList(GlobalDtors,
"llvm.global_dtors");
417 EmitStaticExternCAliases();
420 CoverageMapping->emit();
421 if (CodeGenOpts.SanitizeCfiCrossDso) {
425 emitAtAvailableLinkGuard();
430 if (CodeGenOpts.Autolink &&
431 (Context.
getLangOpts().Modules || !LinkerOptionsMetadata.empty())) {
432 EmitModuleLinkOptions();
438 CodeGenOpts.NumRegisterParameters);
440 if (CodeGenOpts.DwarfVersion) {
444 CodeGenOpts.DwarfVersion);
446 if (CodeGenOpts.EmitCodeView) {
450 if (CodeGenOpts.OptimizationLevel > 0 && CodeGenOpts.StrictVTablePointers) {
457 llvm::Metadata *Ops[2] = {
458 llvm::MDString::get(VMContext,
"StrictVTablePointers"),
459 llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
460 llvm::Type::getInt32Ty(VMContext), 1))};
462 getModule().addModuleFlag(llvm::Module::Require,
463 "StrictVTablePointersRequirement",
464 llvm::MDNode::get(VMContext, Ops));
471 llvm::DEBUG_METADATA_VERSION);
474 uint64_t WCharWidth =
476 assert((LangOpts.ShortWChar ||
477 llvm::TargetLibraryInfoImpl::getTargetWCharSize(Target.
getTriple()) ==
479 "LLVM wchar_t size out of sync");
487 if ( Arch == llvm::Triple::arm
488 || Arch == llvm::Triple::armeb
489 || Arch == llvm::Triple::thumb
490 || Arch == llvm::Triple::thumbeb) {
492 uint64_t EnumWidth = Context.
getLangOpts().ShortEnums ? 1 : 4;
496 if (CodeGenOpts.SanitizeCfiCrossDso) {
498 getModule().addModuleFlag(llvm::Module::Override,
"Cross-DSO CFI", 1);
501 if (LangOpts.CUDAIsDevice &&
getTriple().isNVPTX()) {
505 getModule().addModuleFlag(llvm::Module::Override,
"nvvm-reflect-ftz",
506 LangOpts.CUDADeviceFlushDenormalsToZero ? 1 : 0);
510 if (LangOpts.OpenCL) {
511 EmitOpenCLMetadata();
513 if (
getTriple().getArch() == llvm::Triple::spir ||
514 getTriple().getArch() == llvm::Triple::spir64) {
517 llvm::Metadata *SPIRVerElts[] = {
518 llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
519 Int32Ty, LangOpts.OpenCLVersion / 100)),
520 llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
521 Int32Ty, (LangOpts.OpenCLVersion / 100 > 1) ? 0 : 2))};
522 llvm::NamedMDNode *SPIRVerMD =
523 TheModule.getOrInsertNamedMetadata(
"opencl.spir.version");
524 llvm::LLVMContext &Ctx = TheModule.getContext();
525 SPIRVerMD->addOperand(llvm::MDNode::get(Ctx, SPIRVerElts));
529 if (uint32_t PLevel = Context.
getLangOpts().PICLevel) {
530 assert(PLevel < 3 &&
"Invalid PIC Level");
531 getModule().setPICLevel(static_cast<llvm::PICLevel::Level>(PLevel));
533 getModule().setPIELevel(static_cast<llvm::PIELevel::Level>(PLevel));
536 SimplifyPersonality();
545 DebugInfo->finalize();
547 EmitVersionIdentMetadata();
549 EmitTargetMetadata();
552 void CodeGenModule::EmitOpenCLMetadata() {
555 llvm::Metadata *OCLVerElts[] = {
556 llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
557 Int32Ty, LangOpts.OpenCLVersion / 100)),
558 llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
559 Int32Ty, (LangOpts.OpenCLVersion % 100) / 10))};
560 llvm::NamedMDNode *OCLVerMD =
561 TheModule.getOrInsertNamedMetadata(
"opencl.ocl.version");
562 llvm::LLVMContext &Ctx = TheModule.getContext();
563 OCLVerMD->addOperand(llvm::MDNode::get(Ctx, OCLVerElts));
579 return TBAA->getTBAAInfo(QTy);
585 return TBAA->getTBAAInfoForVTablePtr();
591 return TBAA->getTBAAStructInfo(QTy);
595 llvm::MDNode *AccessN,
599 return TBAA->getTBAAStructTagInfo(BaseTy, AccessN, O);
607 llvm::MDNode *TBAAInfo,
608 bool ConvertTypeToTag) {
609 if (ConvertTypeToTag && TBAA)
610 Inst->setMetadata(llvm::LLVMContext::MD_tbaa,
611 TBAA->getTBAAScalarTagInfo(TBAAInfo));
613 Inst->setMetadata(llvm::LLVMContext::MD_tbaa, TBAAInfo);
618 I->setMetadata(llvm::LLVMContext::MD_invariant_group,
631 "cannot compile this %0 yet");
632 std::string Msg =
Type;
641 "cannot compile this %0 yet");
642 std::string Msg =
Type;
653 if (GV->hasLocalLinkage()) {
665 return llvm::StringSwitch<llvm::GlobalVariable::ThreadLocalMode>(
S)
666 .Case(
"global-dynamic", llvm::GlobalVariable::GeneralDynamicTLSModel)
667 .Case(
"local-dynamic", llvm::GlobalVariable::LocalDynamicTLSModel)
668 .Case(
"initial-exec", llvm::GlobalVariable::InitialExecTLSModel)
669 .Case(
"local-exec", llvm::GlobalVariable::LocalExecTLSModel);
676 return llvm::GlobalVariable::GeneralDynamicTLSModel;
678 return llvm::GlobalVariable::LocalDynamicTLSModel;
680 return llvm::GlobalVariable::InitialExecTLSModel;
682 return llvm::GlobalVariable::LocalExecTLSModel;
684 llvm_unreachable(
"Invalid TLS model!");
688 assert(D.
getTLSKind() &&
"setting TLS mode on non-TLS var!");
690 llvm::GlobalValue::ThreadLocalMode TLM;
694 if (
const TLSModelAttr *
Attr = D.
getAttr<TLSModelAttr>()) {
698 GV->setThreadLocalMode(TLM);
706 if (
const auto *CD = dyn_cast<CXXConstructorDecl>(CanonicalGD.
getDecl())) {
715 StringRef &FoundStr = MangledDeclNames[CanonicalGD];
716 if (!FoundStr.empty())
719 const auto *ND = cast<NamedDecl>(GD.
getDecl());
723 llvm::raw_svector_ostream Out(Buffer);
724 if (
const auto *D = dyn_cast<CXXConstructorDecl>(ND))
726 else if (
const auto *D = dyn_cast<CXXDestructorDecl>(ND))
733 assert(II &&
"Attempt to mangle unnamed decl.");
738 llvm::raw_svector_ostream Out(Buffer);
739 Out <<
"__regcall3__" << II->
getName();
747 auto Result = Manglings.insert(std::make_pair(Str, GD));
748 return FoundStr =
Result.first->first();
757 llvm::raw_svector_ostream Out(Buffer);
760 dyn_cast_or_null<VarDecl>(initializedGlobalDecl.
getDecl()), Out);
761 else if (
const auto *CD = dyn_cast<CXXConstructorDecl>(D))
763 else if (
const auto *DD = dyn_cast<CXXDestructorDecl>(D))
766 MangleCtx.
mangleBlock(cast<DeclContext>(D), BD, Out);
768 auto Result = Manglings.insert(std::make_pair(Out.str(), BD));
769 return Result.first->first();
778 void CodeGenModule::AddGlobalCtor(llvm::Function *Ctor,
int Priority,
779 llvm::Constant *AssociatedData) {
781 GlobalCtors.push_back(Structor(Priority, Ctor, AssociatedData));
786 void CodeGenModule::AddGlobalDtor(llvm::Function *Dtor,
int Priority) {
788 GlobalDtors.push_back(Structor(Priority, Dtor,
nullptr));
791 void CodeGenModule::EmitCtorList(CtorList &Fns,
const char *GlobalName) {
792 if (Fns.empty())
return;
795 llvm::FunctionType* CtorFTy = llvm::FunctionType::get(
VoidTy,
false);
796 llvm::Type *CtorPFTy = llvm::PointerType::getUnqual(CtorFTy);
799 llvm::StructType *CtorStructTy = llvm::StructType::get(
804 auto ctors = builder.beginArray(CtorStructTy);
805 for (
const auto &
I : Fns) {
806 auto ctor = ctors.beginStruct(CtorStructTy);
808 ctor.add(llvm::ConstantExpr::getBitCast(
I.Initializer, CtorPFTy));
809 if (
I.AssociatedData)
810 ctor.add(llvm::ConstantExpr::getBitCast(
I.AssociatedData,
VoidPtrTy));
813 ctor.finishAndAddTo(ctors);
819 llvm::GlobalValue::AppendingLinkage);
823 list->setAlignment(0);
828 llvm::GlobalValue::LinkageTypes
830 const auto *D = cast<FunctionDecl>(GD.
getDecl());
834 if (isa<CXXDestructorDecl>(D) &&
835 getCXXABI().useThunkForDtorVariant(cast<CXXDestructorDecl>(D),
840 : llvm::GlobalValue::LinkOnceODRLinkage;
843 if (isa<CXXConstructorDecl>(D) &&
844 cast<CXXConstructorDecl>(D)->isInheritingConstructor() &&
856 const auto *FD = cast<FunctionDecl>(GD.
getDecl());
858 if (
const auto *Dtor = dyn_cast_or_null<CXXDestructorDecl>(FD)) {
861 F->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass);
866 if (FD->hasAttr<DLLImportAttr>())
867 F->setDLLStorageClass(llvm::GlobalVariable::DLLImportStorageClass);
868 else if (FD->hasAttr<DLLExportAttr>())
869 F->setDLLStorageClass(llvm::GlobalVariable::DLLExportStorageClass);
871 F->setDLLStorageClass(llvm::GlobalVariable::DefaultStorageClass);
875 llvm::MDString *MDS = dyn_cast<llvm::MDString>(MD);
876 if (!MDS)
return nullptr;
878 return llvm::ConstantInt::get(
Int64Ty, llvm::MD5Hash(MDS->getString()));
883 setNonAliasAttributes(D, F);
890 llvm::AttributeList PAL;
892 F->setAttributes(PAL);
893 F->setCallingConv(static_cast<llvm::CallingConv::ID>(CallingConv));
903 if (!LangOpts.Exceptions)
return false;
906 if (LangOpts.CXXExceptions)
return true;
909 if (LangOpts.ObjCExceptions) {
920 if (CodeGenOpts.UnwindTables)
921 B.addAttribute(llvm::Attribute::UWTable);
924 B.addAttribute(llvm::Attribute::NoUnwind);
927 B.addAttribute(llvm::Attribute::StackProtect);
929 B.addAttribute(llvm::Attribute::StackProtectStrong);
931 B.addAttribute(llvm::Attribute::StackProtectReq);
937 if (!F->hasFnAttribute(llvm::Attribute::AlwaysInline) &&
939 B.addAttribute(llvm::Attribute::NoInline);
941 F->addAttributes(llvm::AttributeList::FunctionIndex, B);
947 bool ShouldAddOptNone =
948 !CodeGenOpts.DisableO0ImplyOptNone && CodeGenOpts.OptimizationLevel == 0;
950 ShouldAddOptNone &= !D->
hasAttr<MinSizeAttr>();
951 ShouldAddOptNone &= !F->hasFnAttribute(llvm::Attribute::AlwaysInline);
952 ShouldAddOptNone &= !D->
hasAttr<AlwaysInlineAttr>();
954 if (ShouldAddOptNone || D->
hasAttr<OptimizeNoneAttr>()) {
955 B.addAttribute(llvm::Attribute::OptimizeNone);
958 B.addAttribute(llvm::Attribute::NoInline);
959 assert(!F->hasFnAttribute(llvm::Attribute::AlwaysInline) &&
960 "OptimizeNone and AlwaysInline on same function!");
965 B.addAttribute(llvm::Attribute::Naked);
968 F->removeFnAttr(llvm::Attribute::OptimizeForSize);
969 F->removeFnAttr(llvm::Attribute::MinSize);
970 }
else if (D->
hasAttr<NakedAttr>()) {
972 B.addAttribute(llvm::Attribute::Naked);
973 B.addAttribute(llvm::Attribute::NoInline);
974 }
else if (D->
hasAttr<NoDuplicateAttr>()) {
975 B.addAttribute(llvm::Attribute::NoDuplicate);
976 }
else if (D->
hasAttr<NoInlineAttr>()) {
977 B.addAttribute(llvm::Attribute::NoInline);
978 }
else if (D->
hasAttr<AlwaysInlineAttr>() &&
979 !F->hasFnAttribute(llvm::Attribute::NoInline)) {
981 B.addAttribute(llvm::Attribute::AlwaysInline);
985 if (!F->hasFnAttribute(llvm::Attribute::AlwaysInline))
986 B.addAttribute(llvm::Attribute::NoInline);
990 if (
auto *FD = dyn_cast<FunctionDecl>(D)) {
991 if (any_of(FD->redecls(), [&](
const FunctionDecl *Redecl) {
992 return Redecl->isInlineSpecified();
994 B.addAttribute(llvm::Attribute::InlineHint);
995 }
else if (CodeGenOpts.getInlining() ==
998 !F->hasFnAttribute(llvm::Attribute::AlwaysInline)) {
999 B.addAttribute(llvm::Attribute::NoInline);
1006 if (!D->
hasAttr<OptimizeNoneAttr>()) {
1008 if (!ShouldAddOptNone)
1009 B.addAttribute(llvm::Attribute::OptimizeForSize);
1010 B.addAttribute(llvm::Attribute::Cold);
1013 if (D->
hasAttr<MinSizeAttr>())
1014 B.addAttribute(llvm::Attribute::MinSize);
1017 F->addAttributes(llvm::AttributeList::FunctionIndex, B);
1021 F->setAlignment(alignment);
1028 if (F->getAlignment() < 2 && isa<CXXMethodDecl>(D))
1033 if (CodeGenOpts.SanitizeCfiCrossDso)
1034 if (
auto *FD = dyn_cast<FunctionDecl>(D))
1039 llvm::GlobalValue *GV) {
1040 if (
const auto *ND = dyn_cast_or_null<NamedDecl>(D))
1045 if (D && D->
hasAttr<UsedAttr>())
1050 llvm::GlobalValue *GV) {
1055 if (D->
hasAttr<DLLExportAttr>())
1056 GV->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass);
1059 void CodeGenModule::setNonAliasAttributes(
const Decl *D,
1060 llvm::GlobalObject *GO) {
1064 if (
auto *GV = dyn_cast<llvm::GlobalVariable>(GO)) {
1065 if (
auto *SA = D->
getAttr<PragmaClangBSSSectionAttr>())
1066 GV->addAttribute(
"bss-section", SA->getName());
1067 if (
auto *SA = D->
getAttr<PragmaClangDataSectionAttr>())
1068 GV->addAttribute(
"data-section", SA->getName());
1069 if (
auto *SA = D->
getAttr<PragmaClangRodataSectionAttr>())
1070 GV->addAttribute(
"rodata-section", SA->getName());
1073 if (
auto *F = dyn_cast<llvm::Function>(GO)) {
1074 if (
auto *SA = D->
getAttr<PragmaClangTextSectionAttr>())
1075 if (!D->
getAttr<SectionAttr>())
1076 F->addFnAttr(
"implicit-section-name", SA->getName());
1079 if (
const SectionAttr *SA = D->
getAttr<SectionAttr>())
1080 GO->setSection(SA->getName());
1094 setNonAliasAttributes(D, F);
1104 if (ND->
hasAttr<DLLImportAttr>()) {
1106 GV->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
1107 }
else if (ND->
hasAttr<DLLExportAttr>()) {
1112 GV->setLinkage(llvm::GlobalValue::ExternalWeakLinkage);
1122 llvm::Function *F) {
1124 if (!LangOpts.
Sanitize.
has(SanitizerKind::CFIICall))
1128 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic())
1132 if (CodeGenOpts.SanitizeCfiCrossDso) {
1140 F->addTypeMetadata(0, MD);
1143 if (CodeGenOpts.SanitizeCfiCrossDso)
1145 F->addTypeMetadata(0, llvm::ConstantAsMetadata::get(CrossDsoTypeId));
1148 void CodeGenModule::SetFunctionAttributes(
GlobalDecl GD, llvm::Function *F,
1149 bool IsIncompleteFunction,
1154 F->setAttributes(llvm::Intrinsic::getAttributes(
getLLVMContext(), IID));
1158 const auto *FD = cast<FunctionDecl>(GD.
getDecl());
1160 if (!IsIncompleteFunction)
1166 if (!IsThunk &&
getCXXABI().HasThisReturn(GD) &&
1168 assert(!F->arg_empty() &&
1169 F->arg_begin()->getType()
1170 ->canLosslesslyBitCastTo(F->getReturnType()) &&
1171 "unexpected this return");
1172 F->addAttribute(1, llvm::Attribute::Returned);
1180 if (FD->getAttr<PragmaClangTextSectionAttr>()) {
1181 F->addFnAttr(
"implicit-section-name");
1184 if (
const SectionAttr *SA = FD->getAttr<SectionAttr>())
1185 F->setSection(SA->getName());
1187 if (FD->isReplaceableGlobalAllocationFunction()) {
1190 F->addAttribute(llvm::AttributeList::FunctionIndex,
1191 llvm::Attribute::NoBuiltin);
1196 auto Kind = FD->getDeclName().getCXXOverloadedOperator();
1198 (
Kind == OO_New ||
Kind == OO_Array_New))
1199 F->addAttribute(llvm::AttributeList::ReturnIndex,
1200 llvm::Attribute::NoAlias);
1203 if (isa<CXXConstructorDecl>(FD) || isa<CXXDestructorDecl>(FD))
1204 F->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
1205 else if (
const auto *MD = dyn_cast<CXXMethodDecl>(FD))
1206 if (MD->isVirtual())
1207 F->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
1211 if (!CodeGenOpts.SanitizeCfiCrossDso)
1216 assert(!GV->isDeclaration() &&
1217 "Only globals with definition can force usage.");
1218 LLVMUsed.emplace_back(GV);
1222 assert(!GV->isDeclaration() &&
1223 "Only globals with definition can force usage.");
1224 LLVMCompilerUsed.emplace_back(GV);
1228 std::vector<llvm::WeakTrackingVH> &List) {
1235 UsedArray.resize(List.size());
1236 for (
unsigned i = 0, e = List.size(); i != e; ++i) {
1238 llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(
1239 cast<llvm::Constant>(&*List[i]), CGM.
Int8PtrTy);
1242 if (UsedArray.empty())
1244 llvm::ArrayType *ATy = llvm::ArrayType::get(CGM.
Int8PtrTy, UsedArray.size());
1246 auto *GV =
new llvm::GlobalVariable(
1247 CGM.
getModule(), ATy,
false, llvm::GlobalValue::AppendingLinkage,
1248 llvm::ConstantArray::get(ATy, UsedArray),
Name);
1250 GV->setSection(
"llvm.metadata");
1253 void CodeGenModule::emitLLVMUsed() {
1254 emitUsed(*
this,
"llvm.used", LLVMUsed);
1255 emitUsed(*
this,
"llvm.compiler.used", LLVMCompilerUsed);
1260 LinkerOptionsMetadata.push_back(llvm::MDNode::get(
getLLVMContext(), MDOpts));
1267 LinkerOptionsMetadata.push_back(llvm::MDNode::get(
getLLVMContext(), MDOpts));
1274 LinkerOptionsMetadata.push_back(llvm::MDNode::get(
getLLVMContext(), MDOpts));
1281 llvm::SmallPtrSet<Module *, 16> &Visited) {
1283 if (Mod->
Parent && Visited.insert(Mod->
Parent).second) {
1288 for (
unsigned I = Mod->
Imports.size();
I > 0; --
I) {
1289 if (Visited.insert(Mod->
Imports[
I - 1]).second)
1300 llvm::Metadata *Args[2] = {
1301 llvm::MDString::get(Context,
"-framework"),
1302 llvm::MDString::get(Context, Mod->
LinkLibraries[
I - 1].Library)};
1304 Metadata.push_back(llvm::MDNode::get(Context, Args));
1312 auto *OptString = llvm::MDString::get(Context, Opt);
1313 Metadata.push_back(llvm::MDNode::get(Context, OptString));
1317 void CodeGenModule::EmitModuleLinkOptions() {
1321 llvm::SetVector<clang::Module *> LinkModules;
1322 llvm::SmallPtrSet<clang::Module *, 16> Visited;
1326 for (
Module *M : ImportedModules) {
1332 if (Visited.insert(M).second)
1338 while (!Stack.empty()) {
1341 bool AnyChildren =
false;
1346 Sub != SubEnd; ++Sub) {
1349 if ((*Sub)->IsExplicit)
1352 if (Visited.insert(*Sub).second) {
1353 Stack.push_back(*Sub);
1361 LinkModules.insert(Mod);
1370 for (
Module *M : LinkModules)
1371 if (Visited.insert(M).second)
1373 std::reverse(MetadataArgs.begin(), MetadataArgs.end());
1374 LinkerOptionsMetadata.append(MetadataArgs.begin(), MetadataArgs.end());
1377 auto *NMD =
getModule().getOrInsertNamedMetadata(
"llvm.linker.options");
1378 for (
auto *MD : LinkerOptionsMetadata)
1379 NMD->addOperand(MD);
1382 void CodeGenModule::EmitDeferred() {
1387 if (!DeferredVTables.empty()) {
1388 EmitDeferredVTables();
1393 assert(DeferredVTables.empty());
1397 if (DeferredDeclsToEmit.empty())
1402 std::vector<GlobalDecl> CurDeclsToEmit;
1403 CurDeclsToEmit.swap(DeferredDeclsToEmit);
1410 llvm::GlobalValue *GV = dyn_cast<llvm::GlobalValue>(
1428 if (!GV->isDeclaration())
1432 EmitGlobalDefinition(D, GV);
1437 if (!DeferredVTables.empty() || !DeferredDeclsToEmit.empty()) {
1439 assert(DeferredVTables.empty() && DeferredDeclsToEmit.empty());
1444 void CodeGenModule::EmitVTablesOpportunistically() {
1450 assert((OpportunisticVTables.empty() || shouldOpportunisticallyEmitVTables())
1451 &&
"Only emit opportunistic vtables with optimizations");
1455 "This queue should only contain external vtables");
1456 if (
getCXXABI().canSpeculativelyEmitVTable(RD))
1459 OpportunisticVTables.clear();
1463 if (Annotations.empty())
1467 llvm::Constant *Array = llvm::ConstantArray::get(llvm::ArrayType::get(
1468 Annotations[0]->getType(), Annotations.size()), Annotations);
1469 auto *gv =
new llvm::GlobalVariable(
getModule(), Array->getType(),
false,
1470 llvm::GlobalValue::AppendingLinkage,
1471 Array,
"llvm.global.annotations");
1476 llvm::Constant *&AStr = AnnotationStrings[Str];
1481 llvm::Constant *s = llvm::ConstantDataArray::getString(
getLLVMContext(), Str);
1483 new llvm::GlobalVariable(
getModule(), s->getType(),
true,
1484 llvm::GlobalValue::PrivateLinkage, s,
".str");
1486 gv->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
1504 return llvm::ConstantInt::get(
Int32Ty, LineNo);
1508 const AnnotateAttr *AA,
1516 llvm::Constant *Fields[4] = {
1517 llvm::ConstantExpr::getBitCast(GV,
Int8PtrTy),
1518 llvm::ConstantExpr::getBitCast(AnnoGV,
Int8PtrTy),
1519 llvm::ConstantExpr::getBitCast(UnitGV,
Int8PtrTy),
1522 return llvm::ConstantStruct::getAnon(Fields);
1526 llvm::GlobalValue *GV) {
1527 assert(D->
hasAttr<AnnotateAttr>() &&
"no annotate attribute");
1537 if (SanitizerBL.isBlacklistedFunction(Fn->getName()))
1546 return SanitizerBL.isBlacklistedFile(MainFile->getName());
1556 SanitizerKind::Address | SanitizerKind::KernelAddress))
1559 if (SanitizerBL.isBlacklistedGlobal(GV->getName(),
Category))
1561 if (SanitizerBL.isBlacklistedLocation(Loc, Category))
1567 while (
auto AT = dyn_cast<ArrayType>(Ty.
getTypePtr()))
1568 Ty = AT->getElementType();
1573 if (SanitizerBL.isBlacklistedType(TypeStr, Category))
1582 if (!LangOpts.XRayInstrument)
1588 Attr = XRayFilter.shouldImbueLocation(Loc, Category);
1589 if (
Attr == ImbueAttr::NONE)
1590 Attr = XRayFilter.shouldImbueFunction(Fn->getName());
1592 case ImbueAttr::NONE:
1594 case ImbueAttr::ALWAYS:
1595 Fn->addFnAttr(
"function-instrument",
"xray-always");
1597 case ImbueAttr::ALWAYS_ARG1:
1598 Fn->addFnAttr(
"function-instrument",
"xray-always");
1599 Fn->addFnAttr(
"xray-log-args",
"1");
1601 case ImbueAttr::NEVER:
1602 Fn->addFnAttr(
"function-instrument",
"xray-never");
1608 bool CodeGenModule::MustBeEmitted(
const ValueDecl *Global) {
1610 if (LangOpts.EmitAllDecls)
1616 bool CodeGenModule::MayBeEmittedEagerly(
const ValueDecl *Global) {
1617 if (
const auto *FD = dyn_cast<FunctionDecl>(Global))
1622 if (
const auto *VD = dyn_cast<VarDecl>(Global))
1630 if (LangOpts.OpenMP && LangOpts.OpenMPUseTLS &&
1642 std::string
Name =
"_GUID_" + Uuid.lower();
1643 std::replace(Name.begin(), Name.end(),
'-',
'_');
1649 if (llvm::GlobalVariable *GV =
getModule().getNamedGlobal(Name))
1652 llvm::Constant *Init = EmitUuidofInitializer(Uuid);
1653 assert(Init &&
"failed to initialize as constant");
1655 auto *GV =
new llvm::GlobalVariable(
1657 true, llvm::GlobalValue::LinkOnceODRLinkage, Init,
Name);
1659 GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
1664 const AliasAttr *AA = VD->
getAttr<AliasAttr>();
1665 assert(AA &&
"No alias?");
1674 auto Ptr = llvm::ConstantExpr::getBitCast(Entry, DeclTy->getPointerTo(AS));
1678 llvm::Constant *Aliasee;
1679 if (isa<llvm::FunctionType>(DeclTy))
1680 Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy,
1684 Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(),
1685 llvm::PointerType::getUnqual(DeclTy),
1688 auto *F = cast<llvm::GlobalValue>(Aliasee);
1689 F->setLinkage(llvm::Function::ExternalWeakLinkage);
1690 WeakRefReferences.insert(F);
1696 const auto *Global = cast<ValueDecl>(GD.
getDecl());
1699 if (Global->
hasAttr<WeakRefAttr>())
1704 if (Global->
hasAttr<AliasAttr>())
1705 return EmitAliasDefinition(GD);
1708 if (Global->
hasAttr<IFuncAttr>())
1709 return emitIFuncDefinition(GD);
1712 if (LangOpts.CUDA) {
1713 if (LangOpts.CUDAIsDevice) {
1714 if (!Global->
hasAttr<CUDADeviceAttr>() &&
1715 !Global->
hasAttr<CUDAGlobalAttr>() &&
1716 !Global->
hasAttr<CUDAConstantAttr>() &&
1717 !Global->
hasAttr<CUDASharedAttr>())
1726 if (isa<FunctionDecl>(Global) && !Global->
hasAttr<CUDAHostAttr>() &&
1727 Global->
hasAttr<CUDADeviceAttr>())
1730 assert((isa<FunctionDecl>(Global) || isa<VarDecl>(Global)) &&
1731 "Expected Variable or Function");
1735 if (LangOpts.OpenMP) {
1738 if (OpenMPRuntime && OpenMPRuntime->emitTargetGlobal(GD))
1740 if (
auto *DRD = dyn_cast<OMPDeclareReductionDecl>(Global)) {
1741 if (MustBeEmitted(Global))
1748 if (
const auto *FD = dyn_cast<FunctionDecl>(Global)) {
1750 if (!FD->doesThisDeclarationHaveABody()) {
1751 if (!FD->doesDeclarationForceExternallyVisibleDefinition())
1760 GetOrCreateLLVMFunction(MangledName, Ty, GD,
false,
1765 const auto *VD = cast<VarDecl>(Global);
1766 assert(VD->isFileVarDecl() &&
"Cannot emit local var decl as global.");
1770 bool MustEmitForCuda = LangOpts.CUDA && !LangOpts.CUDAIsDevice &&
1771 !VD->hasDefinition() &&
1772 (VD->hasAttr<CUDAConstantAttr>() ||
1773 VD->hasAttr<CUDADeviceAttr>());
1774 if (!MustEmitForCuda &&
1789 if (MustBeEmitted(Global) && MayBeEmittedEagerly(Global)) {
1791 EmitGlobalDefinition(GD);
1798 cast<VarDecl>(Global)->hasInit()) {
1799 DelayedCXXInitPosition[Global] = CXXGlobalInits.size();
1800 CXXGlobalInits.push_back(
nullptr);
1806 addDeferredDeclToEmit(GD);
1807 }
else if (MustBeEmitted(Global)) {
1809 assert(!MayBeEmittedEagerly(Global));
1810 addDeferredDeclToEmit(GD);
1815 DeferredDecls[MangledName] = GD;
1822 if (
CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl()))
1823 if (RD->getDestructor() && !RD->getDestructor()->hasAttr<DLLImportAttr>())
1830 struct FunctionIsDirectlyRecursive :
1832 const StringRef
Name;
1845 if (Attr &&
Name == Attr->getLabel()) {
1850 if (!BuiltinID || !BI.isLibFunction(BuiltinID))
1852 StringRef BuiltinName = BI.getName(BuiltinID);
1853 if (BuiltinName.startswith(
"__builtin_") &&
1854 Name == BuiltinName.slice(strlen(
"__builtin_"), StringRef::npos)) {
1863 struct DLLImportFunctionVisitor
1865 bool SafeToInline =
true;
1867 bool shouldVisitImplicitCode()
const {
return true; }
1869 bool VisitVarDecl(
VarDecl *VD) {
1872 SafeToInline =
false;
1873 return SafeToInline;
1880 return SafeToInline;
1885 SafeToInline = D->
hasAttr<DLLImportAttr>();
1886 return SafeToInline;
1891 if (isa<FunctionDecl>(VD))
1892 SafeToInline = VD->
hasAttr<DLLImportAttr>();
1893 else if (
VarDecl *V = dyn_cast<VarDecl>(VD))
1894 SafeToInline = !V->hasGlobalStorage() || V->hasAttr<DLLImportAttr>();
1895 return SafeToInline;
1900 return SafeToInline;
1907 SafeToInline =
true;
1909 SafeToInline = M->
hasAttr<DLLImportAttr>();
1911 return SafeToInline;
1916 return SafeToInline;
1921 return SafeToInline;
1930 CodeGenModule::isTriviallyRecursive(
const FunctionDecl *FD) {
1932 if (
getCXXABI().getMangleContext().shouldMangleDeclName(FD)) {
1934 AsmLabelAttr *Attr = FD->
getAttr<AsmLabelAttr>();
1937 Name = Attr->getLabel();
1942 FunctionIsDirectlyRecursive Walker(Name, Context.
BuiltinInfo);
1943 Walker.TraverseFunctionDecl(const_cast<FunctionDecl*>(FD));
1944 return Walker.Result;
1947 bool CodeGenModule::shouldEmitFunction(
GlobalDecl GD) {
1950 const auto *F = cast<FunctionDecl>(GD.
getDecl());
1951 if (CodeGenOpts.OptimizationLevel == 0 && !F->hasAttr<AlwaysInlineAttr>())
1954 if (F->hasAttr<DLLImportAttr>()) {
1956 DLLImportFunctionVisitor Visitor;
1957 Visitor.TraverseFunctionDecl(const_cast<FunctionDecl*>(F));
1958 if (!Visitor.SafeToInline)
1964 for (
const Decl *Member : Dtor->getParent()->decls())
1965 if (isa<FieldDecl>(Member))
1979 return !isTriviallyRecursive(F);
1982 bool CodeGenModule::shouldOpportunisticallyEmitVTables() {
1983 return CodeGenOpts.OptimizationLevel > 0;
1986 void CodeGenModule::EmitGlobalDefinition(
GlobalDecl GD, llvm::GlobalValue *GV) {
1987 const auto *D = cast<ValueDecl>(GD.
getDecl());
1991 "Generating code for declaration");
1993 if (isa<FunctionDecl>(D)) {
1996 if (!shouldEmitFunction(GD))
1999 if (
const auto *Method = dyn_cast<CXXMethodDecl>(D)) {
2002 if (
const auto *CD = dyn_cast<CXXConstructorDecl>(Method))
2004 else if (
const auto *DD = dyn_cast<CXXDestructorDecl>(Method))
2007 EmitGlobalFunctionDefinition(GD, GV);
2009 if (Method->isVirtual())
2015 return EmitGlobalFunctionDefinition(GD, GV);
2018 if (
const auto *VD = dyn_cast<VarDecl>(D))
2019 return EmitGlobalVarDefinition(VD, !VD->hasDefinition());
2021 llvm_unreachable(
"Invalid argument to EmitGlobalDefinition()");
2025 llvm::Function *NewFn);
2034 llvm::Constant *CodeGenModule::GetOrCreateLLVMFunction(
2036 bool DontDefer,
bool IsThunk, llvm::AttributeList ExtraAttrs,
2043 if (WeakRefReferences.erase(Entry)) {
2044 const FunctionDecl *FD = cast_or_null<FunctionDecl>(D);
2045 if (FD && !FD->
hasAttr<WeakAttr>())
2050 if (D && !D->
hasAttr<DLLImportAttr>() && !D->
hasAttr<DLLExportAttr>())
2051 Entry->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass);
2055 if (IsForDefinition && !Entry->isDeclaration()) {
2062 DiagnosedConflictingDefinitions.insert(GD).second) {
2064 diag::err_duplicate_mangled_name);
2066 diag::note_previous_definition);
2070 if ((isa<llvm::Function>(Entry) || isa<llvm::GlobalAlias>(Entry)) &&
2071 (Entry->getType()->getElementType() == Ty)) {
2078 if (!IsForDefinition)
2079 return llvm::ConstantExpr::getBitCast(Entry, Ty->getPointerTo());
2085 bool IsIncompleteFunction =
false;
2087 llvm::FunctionType *FTy;
2088 if (isa<llvm::FunctionType>(Ty)) {
2089 FTy = cast<llvm::FunctionType>(Ty);
2091 FTy = llvm::FunctionType::get(
VoidTy,
false);
2092 IsIncompleteFunction =
true;
2097 Entry ? StringRef() : MangledName, &
getModule());
2114 if (!Entry->use_empty()) {
2116 Entry->removeDeadConstantUsers();
2119 llvm::Constant *BC = llvm::ConstantExpr::getBitCast(
2120 F, Entry->getType()->getElementType()->getPointerTo());
2124 assert(F->getName() == MangledName &&
"name was uniqued!");
2126 SetFunctionAttributes(GD, F, IsIncompleteFunction, IsThunk);
2127 if (ExtraAttrs.hasAttributes(llvm::AttributeList::FunctionIndex)) {
2128 llvm::AttrBuilder B(ExtraAttrs, llvm::AttributeList::FunctionIndex);
2129 F->addAttributes(llvm::AttributeList::FunctionIndex, B);
2136 if (D && isa<CXXDestructorDecl>(D) &&
2137 getCXXABI().useThunkForDtorVariant(cast<CXXDestructorDecl>(D),
2139 addDeferredDeclToEmit(GD);
2144 auto DDI = DeferredDecls.find(MangledName);
2145 if (DDI != DeferredDecls.end()) {
2149 addDeferredDeclToEmit(DDI->second);
2150 DeferredDecls.erase(DDI);
2165 for (
const auto *FD = cast<FunctionDecl>(D)->getMostRecentDecl(); FD;
2178 if (!IsIncompleteFunction) {
2179 assert(F->getType()->getElementType() == Ty);
2183 llvm::Type *PTy = llvm::PointerType::getUnqual(Ty);
2184 return llvm::ConstantExpr::getBitCast(F, PTy);
2197 const auto *FD = cast<FunctionDecl>(GD.
getDecl());
2203 return GetOrCreateLLVMFunction(MangledName, Ty, GD, ForVTable, DontDefer,
2204 false, llvm::AttributeList(),
2215 if (
const auto FD = dyn_cast<FunctionDecl>(
Result))
2223 (Name ==
"_ZSt9terminatev" || Name ==
"\01?terminate@@YAXXZ")
2227 for (
const auto &N : {
"__cxxabiv1",
"std"}) {
2231 if (
auto LSD = dyn_cast<LinkageSpecDecl>(
Result))
2232 for (
const auto &
Result : LSD->lookup(&NS))
2233 if ((ND = dyn_cast<NamespaceDecl>(
Result)))
2238 if (
const auto *FD = dyn_cast<FunctionDecl>(
Result))
2250 llvm::AttributeList ExtraAttrs,
2253 GetOrCreateLLVMFunction(Name, FTy,
GlobalDecl(),
false,
2257 if (
auto *F = dyn_cast<llvm::Function>(C)) {
2261 if (!Local &&
getTriple().isOSBinFormatCOFF() &&
2264 if (!FD || FD->
hasAttr<DLLImportAttr>()) {
2265 F->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
2279 llvm::AttributeList ExtraAttrs) {
2281 GetOrCreateLLVMFunction(Name, FTy,
GlobalDecl(),
false,
2282 false,
false, ExtraAttrs);
2283 if (
auto *F = dyn_cast<llvm::Function>(C))
2302 return ExcludeCtor && !Record->hasMutableFields() &&
2303 Record->hasTrivialDestructor();
2321 CodeGenModule::GetOrCreateLLVMGlobal(StringRef MangledName,
2322 llvm::PointerType *Ty,
2328 if (WeakRefReferences.erase(Entry)) {
2329 if (D && !D->
hasAttr<WeakAttr>())
2334 if (D && !D->
hasAttr<DLLImportAttr>() && !D->
hasAttr<DLLExportAttr>())
2335 Entry->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass);
2337 if (Entry->getType() == Ty)
2342 if (IsForDefinition && !Entry->isDeclaration()) {
2350 (OtherD = dyn_cast<VarDecl>(OtherGD.
getDecl())) &&
2352 DiagnosedConflictingDefinitions.insert(D).second) {
2354 diag::err_duplicate_mangled_name);
2356 diag::note_previous_definition);
2361 if (Entry->getType()->getAddressSpace() != Ty->getAddressSpace())
2362 return llvm::ConstantExpr::getAddrSpaceCast(Entry, Ty);
2366 if (!IsForDefinition)
2367 return llvm::ConstantExpr::getBitCast(Entry, Ty);
2373 auto *GV =
new llvm::GlobalVariable(
2374 getModule(), Ty->getElementType(),
false,
2376 llvm::GlobalVariable::NotThreadLocal, TargetAddrSpace);
2381 GV->takeName(Entry);
2383 if (!Entry->use_empty()) {
2384 llvm::Constant *NewPtrForOldDecl =
2385 llvm::ConstantExpr::getBitCast(GV, Entry->getType());
2386 Entry->replaceAllUsesWith(NewPtrForOldDecl);
2389 Entry->eraseFromParent();
2395 auto DDI = DeferredDecls.find(MangledName);
2396 if (DDI != DeferredDecls.end()) {
2399 addDeferredDeclToEmit(DDI->second);
2400 DeferredDecls.erase(DDI);
2415 CXXThreadLocals.push_back(D);
2421 if (
getContext().isMSStaticDataMemberInlineDefinition(D)) {
2422 EmitGlobalVarDefinition(D);
2426 if (
getTriple().getArch() == llvm::Triple::xcore &&
2430 GV->setSection(
".cp.rodata");
2437 assert(
getContext().getTargetAddressSpace(ExpectedAS) ==
2438 Ty->getPointerAddressSpace());
2439 if (AddrSpace != ExpectedAS)
2450 if (isa<CXXConstructorDecl>(D))
2454 false, IsForDefinition);
2455 else if (isa<CXXDestructorDecl>(D))
2459 false, IsForDefinition);
2460 else if (isa<CXXMethodDecl>(D)) {
2462 cast<CXXMethodDecl>(D));
2466 }
else if (isa<FunctionDecl>(D)) {
2476 llvm::GlobalVariable *
2479 llvm::GlobalValue::LinkageTypes
Linkage) {
2480 llvm::GlobalVariable *GV =
getModule().getNamedGlobal(Name);
2481 llvm::GlobalVariable *OldGV =
nullptr;
2485 if (GV->getType()->getElementType() == Ty)
2490 assert(GV->isDeclaration() &&
"Declaration has wrong type!");
2495 GV =
new llvm::GlobalVariable(
getModule(), Ty,
true,
2496 Linkage,
nullptr, Name);
2500 GV->takeName(OldGV);
2502 if (!OldGV->use_empty()) {
2503 llvm::Constant *NewPtrForOldDecl =
2504 llvm::ConstantExpr::getBitCast(GV, OldGV->getType());
2505 OldGV->replaceAllUsesWith(NewPtrForOldDecl);
2508 OldGV->eraseFromParent();
2512 !GV->hasAvailableExternallyLinkage())
2513 GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
2532 llvm::PointerType *PTy =
2533 llvm::PointerType::get(Ty,
getContext().getTargetAddressSpace(ASTTy));
2536 return GetOrCreateLLVMGlobal(MangledName, PTy, D, IsForDefinition);
2544 return GetOrCreateLLVMGlobal(Name, llvm::PointerType::getUnqual(Ty),
nullptr);
2548 assert(!D->
getInit() &&
"Cannot emit definite definitions here!");
2556 if (GV && !GV->isDeclaration())
2561 if (!MustBeEmitted(D) && !GV) {
2562 DeferredDecls[MangledName] = D;
2567 EmitGlobalVarDefinition(D);
2577 if (LangOpts.OpenCL) {
2587 if (LangOpts.CUDA && LangOpts.CUDAIsDevice) {
2588 if (D && D->
hasAttr<CUDAConstantAttr>())
2590 else if (D && D->
hasAttr<CUDASharedAttr>())
2599 template<
typename SomeDecl>
2601 llvm::GlobalValue *GV) {
2607 if (!D->template hasAttr<UsedAttr>())
2616 const SomeDecl *First = D->getFirstDecl();
2617 if (First->getDeclContext()->isRecord() || !First->isInExternCContext())
2623 std::pair<StaticExternCMap::iterator, bool> R =
2624 StaticExternCValues.insert(std::make_pair(D->getIdentifier(), GV));
2629 R.first->second =
nullptr;
2636 if (D.
hasAttr<SelectAnyAttr>())
2640 if (
auto *VD = dyn_cast<VarDecl>(&D))
2654 llvm_unreachable(
"No such linkage");
2658 llvm::GlobalObject &GO) {
2661 GO.setComdat(TheModule.getOrInsertComdat(GO.getName()));
2665 void CodeGenModule::EmitGlobalVarDefinition(
const VarDecl *D,
2673 llvm::Constant *Init =
nullptr;
2675 bool NeedsGlobalCtor =
false;
2686 Init = llvm::UndefValue::get(
getTypes().ConvertType(ASTTy));
2687 else if (!InitExpr) {
2710 NeedsGlobalCtor =
true;
2713 Init = llvm::UndefValue::get(
getTypes().ConvertType(T));
2720 DelayedCXXInitPosition.erase(D);
2725 llvm::Constant *Entry =
2729 if (
auto *CE = dyn_cast<llvm::ConstantExpr>(Entry)) {
2730 assert(CE->getOpcode() == llvm::Instruction::BitCast ||
2731 CE->getOpcode() == llvm::Instruction::AddrSpaceCast ||
2733 CE->getOpcode() == llvm::Instruction::GetElementPtr);
2734 Entry = CE->getOperand(0);
2738 auto *GV = dyn_cast<llvm::GlobalVariable>(Entry);
2749 if (!GV || GV->getType()->getElementType() != InitType ||
2750 GV->getType()->getAddressSpace() !=
2754 Entry->setName(StringRef());
2757 GV = cast<llvm::GlobalVariable>(
2761 llvm::Constant *NewPtrForOldDecl =
2762 llvm::ConstantExpr::getBitCast(GV, Entry->getType());
2763 Entry->replaceAllUsesWith(NewPtrForOldDecl);
2766 cast<llvm::GlobalValue>(Entry)->eraseFromParent();
2771 if (D->
hasAttr<AnnotateAttr>())
2775 llvm::GlobalValue::LinkageTypes
Linkage =
2785 if (GV && LangOpts.CUDA) {
2786 if (LangOpts.CUDAIsDevice) {
2787 if (D->
hasAttr<CUDADeviceAttr>() || D->
hasAttr<CUDAConstantAttr>())
2788 GV->setExternallyInitialized(
true);
2794 if (D->
hasAttr<CUDADeviceAttr>() || D->
hasAttr<CUDAConstantAttr>()) {
2802 if (D->
hasAttr<CUDAConstantAttr>())
2805 }
else if (D->
hasAttr<CUDASharedAttr>())
2814 GV->setInitializer(Init);
2817 GV->setConstant(!NeedsGlobalCtor && !NeedsGlobalDtor &&
2821 if (
const SectionAttr *SA = D->
getAttr<SectionAttr>()) {
2824 GV->setConstant(
true);
2839 !llvm::GlobalVariable::isLinkOnceLinkage(Linkage) &&
2840 !llvm::GlobalVariable::isWeakLinkage(Linkage))
2843 GV->setLinkage(Linkage);
2844 if (D->
hasAttr<DLLImportAttr>())
2845 GV->setDLLStorageClass(llvm::GlobalVariable::DLLImportStorageClass);
2846 else if (D->
hasAttr<DLLExportAttr>())
2847 GV->setDLLStorageClass(llvm::GlobalVariable::DLLExportStorageClass);
2849 GV->setDLLStorageClass(llvm::GlobalVariable::DefaultStorageClass);
2851 if (Linkage == llvm::GlobalVariable::CommonLinkage) {
2853 GV->setConstant(
false);
2858 if (!GV->getInitializer()->isNullValue())
2859 GV->setLinkage(llvm::GlobalVariable::WeakAnyLinkage);
2862 setNonAliasAttributes(D, GV);
2864 if (D->
getTLSKind() && !GV->isThreadLocal()) {
2866 CXXThreadLocals.push_back(D);
2873 if (NeedsGlobalCtor || NeedsGlobalDtor)
2874 EmitCXXGlobalVarDeclInitFunc(D, GV, NeedsGlobalCtor);
2876 SanitizerMD->reportGlobalToASan(GV, *D, NeedsGlobalCtor);
2881 DI->EmitGlobalVariable(GV, D);
2889 if ((NoCommon || D->
hasAttr<NoCommonAttr>()) && !D->
hasAttr<CommonAttr>())
2900 if (D->
hasAttr<SectionAttr>())
2906 if (D->
hasAttr<PragmaClangBSSSectionAttr>() ||
2907 D->
hasAttr<PragmaClangDataSectionAttr>() ||
2908 D->
hasAttr<PragmaClangRodataSectionAttr>())
2916 if (D->
hasAttr<WeakImportAttr>())
2926 if (D->
hasAttr<AlignedAttr>())
2935 if (FD->isBitField())
2937 if (FD->
hasAttr<AlignedAttr>())
2954 if (IsConstantVariable)
2955 return llvm::GlobalVariable::WeakODRLinkage;
2957 return llvm::GlobalVariable::WeakAnyLinkage;
2963 return llvm::GlobalValue::AvailableExternallyLinkage;
2977 return !Context.
getLangOpts().AppleKext ? llvm::Function::LinkOnceODRLinkage
2994 return llvm::Function::WeakODRLinkage;
2999 if (!
getLangOpts().CPlusPlus && isa<VarDecl>(D) &&
3001 CodeGenOpts.NoCommon))
3002 return llvm::GlobalVariable::CommonLinkage;
3008 if (D->
hasAttr<SelectAnyAttr>())
3009 return llvm::GlobalVariable::WeakODRLinkage;
3017 const VarDecl *VD,
bool IsConstant) {
3025 llvm::Function *newFn) {
3027 if (old->use_empty())
return;
3029 llvm::Type *newRetTy = newFn->getReturnType();
3033 for (llvm::Value::use_iterator ui = old->use_begin(), ue = old->use_end();
3035 llvm::Value::use_iterator use = ui++;
3036 llvm::User *user = use->getUser();
3040 if (
auto *bitcast = dyn_cast<llvm::ConstantExpr>(user)) {
3041 if (bitcast->getOpcode() == llvm::Instruction::BitCast)
3047 llvm::CallSite callSite(user);
3048 if (!callSite)
continue;
3049 if (!callSite.isCallee(&*use))
continue;
3053 if (callSite->getType() != newRetTy && !callSite->use_empty())
3058 llvm::AttributeList oldAttrs = callSite.getAttributes();
3061 unsigned newNumArgs = newFn->arg_size();
3062 if (callSite.arg_size() < newNumArgs)
continue;
3067 bool dontTransform =
false;
3068 for (llvm::Argument &A : newFn->args()) {
3069 if (callSite.getArgument(argNo)->getType() != A.getType()) {
3070 dontTransform =
true;
3075 newArgAttrs.push_back(oldAttrs.getParamAttributes(argNo));
3083 newArgs.append(callSite.arg_begin(), callSite.arg_begin() + argNo);
3086 callSite.getOperandBundlesAsDefs(newBundles);
3088 llvm::CallSite newCall;
3089 if (callSite.isCall()) {
3091 callSite.getInstruction());
3093 auto *oldInvoke = cast<llvm::InvokeInst>(callSite.getInstruction());
3095 oldInvoke->getNormalDest(),
3096 oldInvoke->getUnwindDest(),
3097 newArgs, newBundles,
"",
3098 callSite.getInstruction());
3102 if (!newCall->getType()->isVoidTy())
3103 newCall->takeName(callSite.getInstruction());
3104 newCall.setAttributes(llvm::AttributeList::get(
3105 newFn->getContext(), oldAttrs.getFnAttributes(),
3106 oldAttrs.getRetAttributes(), newArgAttrs));
3107 newCall.setCallingConv(callSite.getCallingConv());
3110 if (!callSite->use_empty())
3111 callSite->replaceAllUsesWith(newCall.getInstruction());
3114 if (callSite->getDebugLoc())
3115 newCall->setDebugLoc(callSite->getDebugLoc());
3117 callSite->eraseFromParent();
3131 llvm::Function *NewFn) {
3133 if (!isa<llvm::Function>(Old))
return;
3152 void CodeGenModule::EmitGlobalFunctionDefinition(
GlobalDecl GD,
3153 llvm::GlobalValue *GV) {
3154 const auto *D = cast<FunctionDecl>(GD.
getDecl());
3161 if (!GV || (GV->getType()->getElementType() != Ty))
3167 if (!GV->isDeclaration())
3174 auto *Fn = cast<llvm::Function>(GV);
3190 if (
const ConstructorAttr *CA = D->
getAttr<ConstructorAttr>())
3191 AddGlobalCtor(Fn, CA->getPriority());
3192 if (
const DestructorAttr *DA = D->
getAttr<DestructorAttr>())
3193 AddGlobalDtor(Fn, DA->getPriority());
3194 if (D->
hasAttr<AnnotateAttr>())
3198 void CodeGenModule::EmitAliasDefinition(
GlobalDecl GD) {
3199 const auto *D = cast<ValueDecl>(GD.
getDecl());
3200 const AliasAttr *AA = D->
getAttr<AliasAttr>();
3201 assert(AA &&
"Not an alias?");
3205 if (AA->getAliasee() == MangledName) {
3206 Diags.
Report(AA->getLocation(), diag::err_cyclic_alias) << 0;
3213 if (Entry && !Entry->isDeclaration())
3216 Aliases.push_back(GD);
3222 llvm::Constant *Aliasee;
3223 if (isa<llvm::FunctionType>(DeclTy))
3224 Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy, GD,
3227 Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(),
3228 llvm::PointerType::getUnqual(DeclTy),
3236 if (GA->getAliasee() == Entry) {
3237 Diags.
Report(AA->getLocation(), diag::err_cyclic_alias) << 0;
3241 assert(Entry->isDeclaration());
3250 GA->takeName(Entry);
3252 Entry->replaceAllUsesWith(llvm::ConstantExpr::getBitCast(GA,
3254 Entry->eraseFromParent();
3256 GA->setName(MangledName);
3264 GA->setLinkage(llvm::Function::WeakAnyLinkage);
3267 if (
const auto *VD = dyn_cast<VarDecl>(D))
3268 if (VD->getTLSKind())
3274 void CodeGenModule::emitIFuncDefinition(
GlobalDecl GD) {
3275 const auto *D = cast<ValueDecl>(GD.
getDecl());
3276 const IFuncAttr *IFA = D->
getAttr<IFuncAttr>();
3277 assert(IFA &&
"Not an ifunc?");
3281 if (IFA->getResolver() == MangledName) {
3282 Diags.
Report(IFA->getLocation(), diag::err_cyclic_alias) << 1;
3288 if (Entry && !Entry->isDeclaration()) {
3291 DiagnosedConflictingDefinitions.insert(GD).second) {
3294 diag::note_previous_definition);
3299 Aliases.push_back(GD);
3302 llvm::Constant *Resolver =
3303 GetOrCreateLLVMFunction(IFA->getResolver(), DeclTy, GD,
3305 llvm::GlobalIFunc *GIF =
3309 if (GIF->getResolver() == Entry) {
3310 Diags.
Report(IFA->getLocation(), diag::err_cyclic_alias) << 1;
3313 assert(Entry->isDeclaration());
3322 GIF->takeName(Entry);
3324 Entry->replaceAllUsesWith(llvm::ConstantExpr::getBitCast(GIF,
3326 Entry->eraseFromParent();
3328 GIF->setName(MangledName);
3339 static llvm::StringMapEntry<llvm::GlobalVariable *> &
3342 bool &IsUTF16,
unsigned &StringLength) {
3343 StringRef String = Literal->
getString();
3344 unsigned NumBytes = String.size();
3348 StringLength = NumBytes;
3349 return *Map.insert(std::make_pair(String,
nullptr)).first;
3356 const llvm::UTF8 *FromPtr = (
const llvm::UTF8 *)String.data();
3357 llvm::UTF16 *ToPtr = &ToBuf[0];
3359 (void)llvm::ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, &ToPtr,
3360 ToPtr + NumBytes, llvm::strictConversion);
3363 StringLength = ToPtr - &ToBuf[0];
3367 return *Map.insert(std::make_pair(
3368 StringRef(reinterpret_cast<const char *>(ToBuf.data()),
3369 (StringLength + 1) * 2),
3375 unsigned StringLength = 0;
3376 bool isUTF16 =
false;
3377 llvm::StringMapEntry<llvm::GlobalVariable *> &Entry =
3382 if (
auto *C = Entry.second)
3385 llvm::Constant *Zero = llvm::Constant::getNullValue(
Int32Ty);
3386 llvm::Constant *Zeros[] = { Zero, Zero };
3389 if (!CFConstantStringClassRef) {
3391 Ty = llvm::ArrayType::get(Ty, 0);
3392 llvm::Constant *GV =
3399 llvm::GlobalValue *CGV = cast<llvm::GlobalValue>(GV);
3403 if ((VD = dyn_cast<VarDecl>(
Result)))
3406 if (!VD || !VD->hasAttr<DLLExportAttr>()) {
3407 CGV->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
3410 CGV->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass);
3416 CFConstantStringClassRef =
3417 llvm::ConstantExpr::getGetElementPtr(Ty, GV, Zeros);
3425 auto Fields = Builder.beginStruct(STy);
3428 Fields.add(cast<llvm::ConstantExpr>(CFConstantStringClassRef));
3431 Fields.addInt(
IntTy, isUTF16 ? 0x07d0 : 0x07C8);
3434 llvm::Constant *C =
nullptr;
3436 auto Arr = llvm::makeArrayRef(
3437 reinterpret_cast<uint16_t *>(const_cast<char *>(Entry.first().data())),
3438 Entry.first().size() / 2);
3439 C = llvm::ConstantDataArray::get(VMContext, Arr);
3441 C = llvm::ConstantDataArray::getString(VMContext, Entry.first());
3447 new llvm::GlobalVariable(
getModule(), C->getType(),
true,
3448 llvm::GlobalValue::PrivateLinkage, C,
".str");
3449 GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
3461 GV->setSection(isUTF16 ?
"__TEXT,__ustring"
3462 :
"__TEXT,__cstring,cstring_literals");
3465 llvm::Constant *Str =
3466 llvm::ConstantExpr::getGetElementPtr(GV->getValueType(), GV, Zeros);
3470 Str = llvm::ConstantExpr::getBitCast(Str,
Int8PtrTy);
3475 Fields.addInt(cast<llvm::IntegerType>(Ty), StringLength);
3480 GV = Fields.finishAndCreateGlobal(
"_unnamed_cfstring_", Alignment,
3482 llvm::GlobalVariable::PrivateLinkage);
3483 switch (
getTriple().getObjectFormat()) {
3484 case llvm::Triple::UnknownObjectFormat:
3485 llvm_unreachable(
"unknown file format");
3486 case llvm::Triple::COFF:
3487 case llvm::Triple::ELF:
3488 case llvm::Triple::Wasm:
3489 GV->setSection(
"cfstring");
3491 case llvm::Triple::MachO:
3492 GV->setSection(
"__DATA,__cfstring");
3501 if (ObjCFastEnumerationStateType.
isNull()) {
3513 for (
size_t i = 0; i < 4; ++i) {
3518 FieldTypes[i],
nullptr,
3530 return ObjCFastEnumerationStateType;
3544 Str.resize(CAT->getSize().getZExtValue());
3545 return llvm::ConstantDataArray::getString(VMContext, Str,
false);
3549 llvm::Type *ElemTy = AType->getElementType();
3550 unsigned NumElements = AType->getNumElements();
3553 if (ElemTy->getPrimitiveSizeInBits() == 16) {
3555 Elements.reserve(NumElements);
3557 for(
unsigned i = 0, e = E->
getLength(); i != e; ++i)
3559 Elements.resize(NumElements);
3560 return llvm::ConstantDataArray::get(VMContext, Elements);
3563 assert(ElemTy->getPrimitiveSizeInBits() == 32);
3565 Elements.reserve(NumElements);
3567 for(
unsigned i = 0, e = E->
getLength(); i != e; ++i)
3569 Elements.resize(NumElements);
3570 return llvm::ConstantDataArray::get(VMContext, Elements);
3573 static llvm::GlobalVariable *
3578 unsigned AddrSpace = 0;
3584 auto *GV =
new llvm::GlobalVariable(
3585 M, C->getType(), !CGM.
getLangOpts().WritableStrings, LT, C, GlobalName,
3586 nullptr, llvm::GlobalVariable::NotThreadLocal, AddrSpace);
3588 GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
3589 if (GV->isWeakForLinker()) {
3590 assert(CGM.
supportsCOMDAT() &&
"Only COFF uses weak string literals");
3591 GV->setComdat(M.getOrInsertComdat(GV->getName()));
3605 llvm::GlobalVariable **Entry =
nullptr;
3606 if (!LangOpts.WritableStrings) {
3607 Entry = &ConstantStringMap[C];
3608 if (
auto GV = *Entry) {
3616 StringRef GlobalVariableName;
3617 llvm::GlobalValue::LinkageTypes LT;
3622 if (!LangOpts.WritableStrings &&
3625 llvm::raw_svector_ostream Out(MangledNameBuffer);
3628 LT = llvm::GlobalValue::LinkOnceODRLinkage;
3629 GlobalVariableName = MangledNameBuffer;
3631 LT = llvm::GlobalValue::PrivateLinkage;
3632 GlobalVariableName =
Name;
3639 SanitizerMD->reportGlobalToASan(GV, S->
getStrTokenLoc(0),
"<string literal>",
3658 const std::string &Str,
const char *GlobalName) {
3659 StringRef StrWithNull(Str.c_str(), Str.size() + 1);
3664 llvm::ConstantDataArray::getString(
getLLVMContext(), StrWithNull,
false);
3667 llvm::GlobalVariable **Entry =
nullptr;
3668 if (!LangOpts.WritableStrings) {
3669 Entry = &ConstantStringMap[C];
3670 if (
auto GV = *Entry) {
3671 if (Alignment.getQuantity() > GV->getAlignment())
3672 GV->setAlignment(Alignment.getQuantity());
3679 GlobalName =
".str";
3682 GlobalName, Alignment);
3698 MaterializedType = E->
getType();
3702 if (llvm::Constant *Slot = MaterializedGlobalTemporaryMap[E])
3709 llvm::raw_svector_ostream Out(Name);
3711 VD, E->getManglingNumber(), Out);
3714 if (E->getStorageDuration() ==
SD_Static) {
3728 Value = &EvalResult.
Val;
3730 llvm::Constant *InitialValue =
nullptr;
3731 bool Constant =
false;
3737 Type = InitialValue->getType();
3745 llvm::GlobalValue::LinkageTypes Linkage =
3749 if (VD->isStaticDataMember() && VD->getAnyInitializer(InitVD) &&
3753 Linkage = llvm::GlobalVariable::LinkOnceODRLinkage;
3760 unsigned AddrSpace =
3763 auto *GV =
new llvm::GlobalVariable(
3764 getModule(),
Type, Constant, Linkage, InitialValue, Name.c_str(),
3765 nullptr, llvm::GlobalVariable::NotThreadLocal, TargetAS);
3769 GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
3770 if (VD->getTLSKind())
3772 llvm::Constant *CV = GV;
3778 MaterializedGlobalTemporaryMap[
E] = CV;
3784 void CodeGenModule::EmitObjCPropertyImplementations(
const
3798 const_cast<ObjCImplementationDecl *>(D), PID);
3802 const_cast<ObjCImplementationDecl *>(D), PID);
3811 if (ivar->getType().isDestructedType())
3881 EmitDeclContext(LSD);
3884 void CodeGenModule::EmitDeclContext(
const DeclContext *DC) {
3885 for (
auto *
I : DC->
decls()) {
3891 if (
auto *OID = dyn_cast<ObjCImplDecl>(
I)) {
3892 for (
auto *M : OID->methods())
3907 case Decl::CXXConversion:
3908 case Decl::CXXMethod:
3909 case Decl::Function:
3911 if (cast<FunctionDecl>(D)->getDescribedFunctionTemplate() ||
3912 cast<FunctionDecl>(D)->isLateTemplateParsed())
3921 case Decl::CXXDeductionGuide:
3926 case Decl::Decomposition:
3928 if (cast<VarDecl>(D)->getDescribedVarTemplate())
3931 case Decl::VarTemplateSpecialization:
3933 if (
auto *DD = dyn_cast<DecompositionDecl>(D))
3934 for (
auto *B : DD->bindings())
3935 if (
auto *HD = B->getHoldingVar())
3941 case Decl::IndirectField:
3945 case Decl::Namespace:
3946 EmitDeclContext(cast<NamespaceDecl>(D));
3948 case Decl::CXXRecord:
3952 DebugInfo->completeUnusedClass(cast<CXXRecordDecl>(*D));
3955 for (
auto *
I : cast<CXXRecordDecl>(D)->decls())
3956 if (isa<VarDecl>(
I) || isa<CXXRecordDecl>(
I))
3960 case Decl::UsingShadow:
3961 case Decl::ClassTemplate:
3962 case Decl::VarTemplate:
3963 case Decl::VarTemplatePartialSpecialization:
3964 case Decl::FunctionTemplate:
3965 case Decl::TypeAliasTemplate:
3971 DI->EmitUsingDecl(cast<UsingDecl>(*D));
3973 case Decl::NamespaceAlias:
3975 DI->EmitNamespaceAlias(cast<NamespaceAliasDecl>(*D));
3977 case Decl::UsingDirective:
3979 DI->EmitUsingDirective(cast<UsingDirectiveDecl>(*D));
3981 case Decl::CXXConstructor:
3983 if (cast<FunctionDecl>(D)->getDescribedFunctionTemplate() ||
3984 cast<FunctionDecl>(D)->isLateTemplateParsed())
3989 case Decl::CXXDestructor:
3990 if (cast<FunctionDecl>(D)->isLateTemplateParsed())
3995 case Decl::StaticAssert:
4002 case Decl::ObjCInterface:
4003 case Decl::ObjCCategory:
4006 case Decl::ObjCProtocol: {
4007 auto *Proto = cast<ObjCProtocolDecl>(D);
4008 if (Proto->isThisDeclarationADefinition())
4013 case Decl::ObjCCategoryImpl:
4016 ObjCRuntime->GenerateCategory(cast<ObjCCategoryImplDecl>(D));
4019 case Decl::ObjCImplementation: {
4020 auto *OMD = cast<ObjCImplementationDecl>(D);
4021 EmitObjCPropertyImplementations(OMD);
4022 EmitObjCIvarInitializations(OMD);
4027 DI->getOrCreateInterfaceType(
getContext().getObjCInterfaceType(
4028 OMD->getClassInterface()), OMD->getLocation());
4031 case Decl::ObjCMethod: {
4032 auto *OMD = cast<ObjCMethodDecl>(D);
4038 case Decl::ObjCCompatibleAlias:
4039 ObjCRuntime->RegisterAlias(cast<ObjCCompatibleAliasDecl>(D));
4042 case Decl::PragmaComment: {
4043 const auto *PCD = cast<PragmaCommentDecl>(D);
4044 switch (PCD->getCommentKind()) {
4046 llvm_unreachable(
"unexpected pragma comment kind");
4061 case Decl::PragmaDetectMismatch: {
4062 const auto *PDMD = cast<PragmaDetectMismatchDecl>(D);
4067 case Decl::LinkageSpec:
4068 EmitLinkageSpec(cast<LinkageSpecDecl>(D));
4071 case Decl::FileScopeAsm: {
4073 if (LangOpts.CUDA && LangOpts.CUDAIsDevice)
4076 if (LangOpts.OpenMPIsDevice)
4078 auto *AD = cast<FileScopeAsmDecl>(D);
4079 getModule().appendModuleInlineAsm(AD->getAsmString()->getString());
4083 case Decl::Import: {
4084 auto *Import = cast<ImportDecl>(D);
4087 if (!ImportedModules.insert(Import->getImportedModule()))
4091 if (!Import->getImportedOwningModule()) {
4093 DI->EmitImportDecl(*Import);
4097 llvm::SmallPtrSet<clang::Module *, 16> Visited;
4099 Visited.insert(Import->getImportedModule());
4100 Stack.push_back(Import->getImportedModule());
4102 while (!Stack.empty()) {
4104 if (!EmittedModuleInitializers.insert(Mod).second)
4113 Sub != SubEnd; ++Sub) {
4116 if ((*Sub)->IsExplicit)
4119 if (Visited.insert(*Sub).second)
4120 Stack.push_back(*Sub);
4127 EmitDeclContext(cast<ExportDecl>(D));
4130 case Decl::OMPThreadPrivate:
4134 case Decl::ClassTemplateSpecialization: {
4135 const auto *Spec = cast<ClassTemplateSpecializationDecl>(D);
4138 Spec->hasDefinition())
4139 DebugInfo->completeTemplateDefinition(*Spec);
4143 case Decl::OMPDeclareReduction:
4151 assert(isa<TypeDecl>(D) &&
"Unsupported decl kind");
4158 if (!CodeGenOpts.CoverageMapping)
4161 case Decl::CXXConversion:
4162 case Decl::CXXMethod:
4163 case Decl::Function:
4164 case Decl::ObjCMethod:
4165 case Decl::CXXConstructor:
4166 case Decl::CXXDestructor: {
4167 if (!cast<FunctionDecl>(D)->doesThisDeclarationHaveABody())
4169 auto I = DeferredEmptyCoverageMappingDecls.find(D);
4170 if (
I == DeferredEmptyCoverageMappingDecls.end())
4171 DeferredEmptyCoverageMappingDecls[D] =
true;
4181 if (!CodeGenOpts.CoverageMapping)
4183 if (
const auto *Fn = dyn_cast<FunctionDecl>(D)) {
4184 if (Fn->isTemplateInstantiation())
4187 auto I = DeferredEmptyCoverageMappingDecls.find(D);
4188 if (
I == DeferredEmptyCoverageMappingDecls.end())
4189 DeferredEmptyCoverageMappingDecls[D] =
false;
4195 std::vector<const Decl *> DeferredDecls;
4196 for (
const auto &
I : DeferredEmptyCoverageMappingDecls) {
4199 DeferredDecls.push_back(
I.first);
4203 if (CodeGenOpts.DumpCoverageMapping)
4204 std::sort(DeferredDecls.begin(), DeferredDecls.end(),
4205 [] (
const Decl *LHS,
const Decl *RHS) {
4208 for (
const auto *D : DeferredDecls) {
4210 case Decl::CXXConversion:
4211 case Decl::CXXMethod:
4212 case Decl::Function:
4213 case Decl::ObjCMethod: {
4220 case Decl::CXXConstructor: {
4227 case Decl::CXXDestructor: {
4244 llvm::Type *i64 = llvm::Type::getInt64Ty(Context);
4245 return llvm::ConstantInt::get(i64, PtrInt);
4249 llvm::NamedMDNode *&GlobalMetadata,
4251 llvm::GlobalValue *Addr) {
4252 if (!GlobalMetadata)
4254 CGM.
getModule().getOrInsertNamedMetadata(
"clang.global.decl.ptrs");
4257 llvm::Metadata *Ops[] = {llvm::ConstantAsMetadata::get(Addr),
4260 GlobalMetadata->addOperand(llvm::MDNode::get(CGM.
getLLVMContext(), Ops));
4268 void CodeGenModule::EmitStaticExternCAliases() {
4273 for (
auto &
I : StaticExternCValues) {
4275 llvm::GlobalValue *Val =
I.second;
4283 auto Res = Manglings.find(MangledName);
4284 if (Res == Manglings.end())
4286 Result = Res->getValue();
4297 void CodeGenModule::EmitDeclMetadata() {
4298 llvm::NamedMDNode *GlobalMetadata =
nullptr;
4300 for (
auto &
I : MangledDeclNames) {
4301 llvm::GlobalValue *Addr =
getModule().getNamedValue(
I.second);
4311 void CodeGenFunction::EmitDeclMetadata() {
4312 if (LocalDeclMap.empty())
return;
4317 unsigned DeclPtrKind = Context.getMDKindID(
"clang.decl.ptr");
4319 llvm::NamedMDNode *GlobalMetadata =
nullptr;
4321 for (
auto &
I : LocalDeclMap) {
4322 const Decl *D =
I.first;
4324 if (
auto *Alloca = dyn_cast<llvm::AllocaInst>(Addr)) {
4326 Alloca->setMetadata(
4327 DeclPtrKind, llvm::MDNode::get(
4328 Context, llvm::ValueAsMetadata::getConstant(DAddr)));
4329 }
else if (
auto *GV = dyn_cast<llvm::GlobalValue>(Addr)) {
4336 void CodeGenModule::EmitVersionIdentMetadata() {
4337 llvm::NamedMDNode *IdentMetadata =
4338 TheModule.getOrInsertNamedMetadata(
"llvm.ident");
4340 llvm::LLVMContext &Ctx = TheModule.getContext();
4342 llvm::Metadata *IdentNode[] = {llvm::MDString::get(Ctx, Version)};
4343 IdentMetadata->addOperand(llvm::MDNode::get(Ctx, IdentNode));
4346 void CodeGenModule::EmitTargetMetadata() {
4353 for (
unsigned I = 0;
I != MangledDeclNames.size(); ++
I) {
4354 auto Val = *(MangledDeclNames.begin() +
I);
4361 void CodeGenModule::EmitCoverageFile() {
4366 llvm::NamedMDNode *CUNode = TheModule.getNamedMetadata(
"llvm.dbg.cu");
4370 llvm::NamedMDNode *GCov = TheModule.getOrInsertNamedMetadata(
"llvm.gcov");
4371 llvm::LLVMContext &Ctx = TheModule.getContext();
4372 auto *CoverageDataFile =
4374 auto *CoverageNotesFile =
4376 for (
int i = 0, e = CUNode->getNumOperands(); i != e; ++i) {
4377 llvm::MDNode *CU = CUNode->getOperand(i);
4378 llvm::Metadata *Elts[] = {CoverageNotesFile, CoverageDataFile, CU};
4379 GCov->addOperand(llvm::MDNode::get(Ctx, Elts));
4383 llvm::Constant *CodeGenModule::EmitUuidofInitializer(StringRef Uuid) {
4386 assert(Uuid.size() == 36);
4387 for (
unsigned i = 0; i < 36; ++i) {
4388 if (i == 8 || i == 13 || i == 18 || i == 23) assert(Uuid[i] ==
'-');
4393 const unsigned Field3ValueOffsets[8] = { 19, 21, 24, 26, 28, 30, 32, 34 };
4395 llvm::Constant *Field3[8];
4396 for (
unsigned Idx = 0; Idx < 8; ++Idx)
4397 Field3[Idx] = llvm::ConstantInt::get(
4398 Int8Ty, Uuid.substr(Field3ValueOffsets[Idx], 2), 16);
4400 llvm::Constant *Fields[4] = {
4401 llvm::ConstantInt::get(
Int32Ty, Uuid.substr(0, 8), 16),
4402 llvm::ConstantInt::get(
Int16Ty, Uuid.substr(9, 4), 16),
4403 llvm::ConstantInt::get(
Int16Ty, Uuid.substr(14, 4), 16),
4404 llvm::ConstantArray::get(llvm::ArrayType::get(
Int8Ty, 8), Field3)
4407 return llvm::ConstantStruct::getAnon(Fields);
4416 return llvm::Constant::getNullValue(
Int8PtrTy);
4426 for (
auto RefExpr : D->
varlists()) {
4427 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(RefExpr)->getDecl());
4429 VD->getAnyInitializer() &&
4430 !VD->getAnyInitializer()->isConstantInitializer(
getContext(),
4435 VD, Addr, RefExpr->getLocStart(), PerformInit))
4436 CXXGlobalInits.push_back(InitFunction);
4446 std::string OutName;
4447 llvm::raw_string_ostream Out(OutName);
4463 return ((LangOpts.
Sanitize.
has(SanitizerKind::CFIVCall) &&
4465 (LangOpts.
Sanitize.
has(SanitizerKind::CFINVCall) &&
4467 (LangOpts.
Sanitize.
has(SanitizerKind::CFIDerivedCast) &&
4469 (LangOpts.
Sanitize.
has(SanitizerKind::CFIUnrelatedCast) &&
4476 llvm::Metadata *MD =
4478 VTable->addTypeMetadata(Offset.
getQuantity(), MD);
4480 if (CodeGenOpts.SanitizeCfiCrossDso)
4483 llvm::ConstantAsMetadata::get(CrossDsoTypeId));
4486 llvm::Metadata *MD = llvm::MDString::get(
getLLVMContext(),
"all-vtables");
4487 VTable->addTypeMetadata(Offset.
getQuantity(), MD);
4496 if (
const auto *TD = FD->
getAttr<TargetAttr>()) {
4498 TargetAttr::ParsedTargetAttr ParsedAttr = TD->parse();
4502 ParsedAttr.Features.insert(ParsedAttr.Features.begin(),
4506 if (ParsedAttr.Architecture !=
"")
4507 TargetCPU = ParsedAttr.Architecture ;
4514 ParsedAttr.Features);
4523 SanStats = llvm::make_unique<llvm::SanitizerStatReport>(&
getModule());
4532 auto FTy = llvm::FunctionType::get(SamplerT, {C->getType()},
false);
4534 "__translate_sampler_initializer"),
void setLinkage(Linkage L)
std::string CoverageNotesFile
The filename with path we use for coverage notes files.
llvm::PointerType * Int8PtrPtrTy
std::string ProfileInstrumentUsePath
Name of the profile file to use as input for -fprofile-instr-use.
unsigned getAddressSpace() const
Return the address space of this type.
CGOpenCLRuntime & getOpenCLRuntime()
Return a reference to the configured OpenCL runtime.
Defines the clang::ASTContext interface.
The generic AArch64 ABI is also a modified version of the Itanium ABI, but it has fewer divergences t...
FunctionDecl - An instance of this class is created to represent a function declaration or definition...
llvm::IntegerType * IntTy
int
External linkage, which indicates that the entity can be referred to from other translation units...
StringRef getName() const
getName - Get the name of identifier for this declaration as a StringRef.
void EmitDeferredUnusedCoverageMappings()
Emit all the deferred coverage mappings for the uninstrumented functions.
Smart pointer class that efficiently represents Objective-C method names.
void DecorateInstructionWithInvariantGroup(llvm::Instruction *I, const CXXRecordDecl *RD)
Adds !invariant.barrier !tag to instruction.
Holds information about both target-independent and target-specific builtins, allowing easy queries b...
GVALinkage GetGVALinkageForFunction(const FunctionDecl *FD) const
TemplateSpecializationKind getTemplateSpecializationKind() const
If this variable is an instantiation of a variable template or a static data member of a class templa...
A (possibly-)qualified type.
The iOS 64-bit ABI is follows ARM's published 64-bit ABI more closely, but we don't guarantee to foll...
const ABIInfo & getABIInfo() const
getABIInfo() - Returns ABI info helper for the target.
CodeGenTypes & getTypes()
GlobalDecl getWithDecl(const Decl *D)
CharUnits getDeclAlign(const Decl *D, bool ForAlignof=false) const
Return a conservative estimate of the alignment of the specified decl D.
bool hasTrivialDestructor() const
Determine whether this class has a trivial destructor (C++ [class.dtor]p3)
void UpdateCompletedType(const TagDecl *TD)
UpdateCompletedType - When we find the full definition for a TagDecl, replace the 'opaque' type we pr...
CXXCtorType getCtorType() const
llvm::Module & getModule() const
RecordDecl * buildImplicitRecord(StringRef Name, RecordDecl::TagKind TK=TTK_Struct) const
Create a new implicit TU-level CXXRecordDecl or RecordDecl declaration.
llvm::LLVMContext & getLLVMContext()
llvm::CallingConv::ID getBuiltinCC() const
Return the calling convention to use for compiler builtins.
unsigned ASTAllocaAddressSpace
std::string getClangFullVersion()
Retrieves a string representing the complete clang version, which includes the clang version number...
ConstantAddress GetAddrOfConstantStringFromObjCEncode(const ObjCEncodeExpr *)
Return a pointer to a constant array for the given ObjCEncodeExpr node.
submodule_iterator submodule_begin()
llvm::CallingConv::ID BuiltinCC
The standard implementation of ConstantInitBuilder used in Clang.
Stmt - This represents one statement.
decl_range decls() const
decls_begin/decls_end - Iterate over the declarations stored in this context.
FunctionType - C99 6.7.5.3 - Function Declarators.
SanitizerSet Sanitize
Set of enabled sanitizers.
virtual void mangleCXXDtor(const CXXDestructorDecl *D, CXXDtorType Type, raw_ostream &)=0
unsigned GetGlobalVarAddressSpace(const VarDecl *D)
Return the AST address space of the underlying global variable for D, as determined by its declaratio...
Expr * GetTemporaryExpr() const
Retrieve the temporary-generating subexpression whose value will be materialized into a glvalue...
Defines the SourceManager interface.
QuantityType getQuantity() const
getQuantity - Get the raw integer representation of this quantity.
bool isRecordType() const
virtual void mangleCXXCtor(const CXXConstructorDecl *D, CXXCtorType Type, raw_ostream &)=0
Defines the clang::Module class, which describes a module in the source code.
Decl - This represents one declaration (or definition), e.g.
llvm::MDNode * getTBAAStructInfo(QualType QTy)
VarDecl * getDefinition(ASTContext &)
Get the real (not just tentative) definition for this declaration.
void setAliasAttributes(const Decl *D, llvm::GlobalValue *GV)
Set attributes which must be preserved by an alias.
Defines the C++ template declaration subclasses.
llvm::CallingConv::ID getRuntimeCC() const
bool isAlignmentRequired(const Type *T) const
Determine if the alignment the type has was required using an alignment attribute.
llvm::Type * FloatTy
float, double
std::string getAsString() const
const llvm::DataLayout & getDataLayout() const
FullSourceLoc getFullLoc(SourceLocation Loc) const
The base class of the type hierarchy.
bool isDependentContext() const
Determines whether this context is dependent on a template parameter.
void setFunctionLinkage(GlobalDecl GD, llvm::Function *F)
Stores additional source code information like skipped ranges which is required by the coverage mappi...
void GenerateObjCSetter(ObjCImplementationDecl *IMP, const ObjCPropertyImplDecl *PID)
GenerateObjCSetter - Synthesize an Objective-C property setter function for the given property...
std::unique_ptr< llvm::MemoryBuffer > Buffer
DiagnosticBuilder Report(SourceLocation Loc, unsigned DiagID)
Issue the message to the client.
void GenerateCode(GlobalDecl GD, llvm::Function *Fn, const CGFunctionInfo &FnInfo)
const Expr * getInit() const
NamespaceDecl - Represent a C++ namespace.
Represents a call to a C++ constructor.
static void setLinkageAndVisibilityForGV(llvm::GlobalValue *GV, const NamedDecl *ND)
virtual void completeDefinition()
completeDefinition - Notes that the definition of this type is now complete.
bool isWeakImported() const
Determine whether this is a weak-imported symbol.
void EmitCfiCheckFail()
Emit a cross-DSO CFI failure handling function.
static const llvm::GlobalObject * getAliasedGlobal(const llvm::GlobalIndirectSymbol &GIS)
PreprocessorOptions - This class is used for passing the various options used in preprocessor initial...
llvm::IntegerType * Int8Ty
i8, i16, i32, and i64
Represents a prvalue temporary that is written into memory so that a reference can bind to it...
static llvm::GlobalValue::VisibilityTypes GetLLVMVisibility(Visibility V)
llvm::Constant * EmitConstantValue(const APValue &Value, QualType DestType, CodeGenFunction *CGF=nullptr)
Emit the given constant value as a constant, in the type's scalar representation. ...
'gcc' is the Objective-C runtime shipped with GCC, implementing a fragile Objective-C ABI ...
void HandleCXXStaticMemberVarInstantiation(VarDecl *VD)
Tell the consumer that this variable has been instantiated.
VarDecl - An instance of this class is created to represent a variable declaration or definition...
Expr * getInit() const
Get the initializer.
TLSKind getTLSKind() const
void setFunctionDefinitionAttributes(const FunctionDecl *D, llvm::Function *F)
Set attributes for a global definition.
CGDebugInfo * getModuleDebugInfo()
void setFunctionDLLStorageClass(GlobalDecl GD, llvm::Function *F)
Set the DLL storage class on F.
This class gathers all debug information during compilation and is responsible for emitting to llvm g...
CharUnits GetTargetTypeStoreSize(llvm::Type *Ty) const
Return the store size, in character units, of the given LLVM type.
static llvm::GlobalVariable * GenerateStringLiteral(llvm::Constant *C, llvm::GlobalValue::LinkageTypes LT, CodeGenModule &CGM, StringRef GlobalName, CharUnits Alignment)
ObjCMethodDecl - Represents an instance or class method declaration.
bool hasGlobalStorage() const
Returns true for all variables that do not have local storage.
virtual void getDependentLibraryOption(llvm::StringRef Lib, llvm::SmallString< 24 > &Opt) const
Gets the linker options necessary to link a dependent library on this platform.
llvm::Type * ConvertTypeForMem(QualType T)
ConvertTypeForMem - Convert type T into a llvm::Type.
bool NeedAllVtablesTypeId() const
Returns whether this module needs the "all-vtables" type identifier.
Linkage
Describes the different kinds of linkage (C++ [basic.link], C99 6.2.2) that an entity may have...
GlobalDecl getCanonicalDecl() const
RecordDecl - Represents a struct/union/class.
Visibility getVisibility() const
unsigned getMaxAlignment() const
getMaxAlignment - return the maximum alignment specified by attributes on this decl, 0 if there are none.
static const FunctionDecl * GetRuntimeFunctionDecl(ASTContext &C, StringRef Name)
One of these records is kept for each identifier that is lexed.
'macosx-fragile' is the Apple-provided NeXT-derived runtime on Mac OS X platforms that use the fragil...
CodeGenFunction - This class organizes the per-function state that is used while generating LLVM code...
llvm::Type * ConvertType(QualType T)
ConvertType - Convert type T into a llvm::Type.
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
llvm::IntegerType * Int64Ty
bool isReferenceType() const
llvm::Constant * getAddrOfCXXStructor(const CXXMethodDecl *MD, StructorType Type, const CGFunctionInfo *FnInfo=nullptr, llvm::FunctionType *FnType=nullptr, bool DontDefer=false, ForDefinition_t IsForDefinition=NotForDefinition)
Return the address of the constructor/destructor of the given type.
The generic Mips ABI is a modified version of the Itanium ABI.
FieldDecl - An instance of this class is created by Sema::ActOnField to represent a member of a struc...
static CGCXXABI * createCXXABI(CodeGenModule &CGM)
llvm::IntegerType * SizeTy
InlineVariableDefinitionKind getInlineVariableDefinitionKind(const VarDecl *VD) const
Determine whether a definition of this inline variable should be treated as a weak or strong definiti...
StructorType getFromDtorType(CXXDtorType T)
virtual void emitTargetMD(const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &M) const
emitTargetMD - Provides a convenient hook to handle extra target-specific metadata for the given glob...
void startDefinition()
Starts the definition of this tag declaration.
StringRef getBufferName(SourceLocation Loc, bool *Invalid=nullptr) const
Return the filename or buffer identifier of the buffer the location is in.
This declaration is definitely a definition.
void GenerateObjCCtorDtorMethod(ObjCImplementationDecl *IMP, ObjCMethodDecl *MD, bool ctor)
virtual bool initFeatureMap(llvm::StringMap< bool > &Features, DiagnosticsEngine &Diags, StringRef CPU, const std::vector< std::string > &FeatureVec) const
Initialize the map with the default set of target features for the CPU this should include all legal ...
bool imbueXRayAttrs(llvm::Function *Fn, SourceLocation Loc, StringRef Category=StringRef()) const
Imbue XRay attributes to a function, applying the always/never attribute lists in the process...
Keeps track of the various options that can be enabled, which controls the dialect of C or C++ that i...
llvm::CallingConv::ID RuntimeCC
const Decl * getDecl() const
Linkage getLinkage() const
Describes a module or submodule.
bool shouldMangleDeclName(const NamedDecl *D)
bool hasExternalStorage() const
Returns true if a variable has extern or private_extern storage.
Objects with "default" visibility are seen by the dynamic linker and act like normal objects...
llvm::Constant * GetConstantArrayFromStringLiteral(const StringLiteral *E)
Return a constant array for the given string.
static void EmitGlobalDeclMetadata(CodeGenModule &CGM, llvm::NamedMDNode *&GlobalMetadata, GlobalDecl D, llvm::GlobalValue *Addr)
bool isBlacklistedLocation(SourceLocation Loc, StringRef Category=StringRef()) const
uint32_t getCodeUnit(size_t i) const
CGCUDARuntime & getCUDARuntime()
Return a reference to the configured CUDA runtime.
const TargetInfo & getTargetInfo() const
const LangOptions & getLangOpts() const
unsigned getLength() const
CharUnits - This is an opaque type for sizes expressed in character units.
APValue Val
Val - This is the value the expression can be folded to.
const ValueDecl * getExtendingDecl() const
Get the declaration which triggered the lifetime-extension of this temporary, if any.
The Microsoft ABI is the ABI used by Microsoft Visual Studio (and compatible compilers).
void EmitOMPDeclareReduction(const OMPDeclareReductionDecl *D, CodeGenFunction *CGF=nullptr)
Emit a code for declare reduction construct.
virtual void mangleReferenceTemporary(const VarDecl *D, unsigned ManglingNumber, raw_ostream &)=0
unsigned char PointerWidthInBits
The width of a pointer into the generic address space.
field_range fields() const
llvm::PointerType * VoidPtrTy
Concrete class used by the front-end to report problems and issues.
CGObjCRuntime * CreateMacObjCRuntime(CodeGenModule &CGM)
void ConstructAttributeList(StringRef Name, const CGFunctionInfo &Info, CGCalleeInfo CalleeInfo, llvm::AttributeList &Attrs, unsigned &CallingConv, bool AttrOnCallSite)
Get the LLVM attributes and calling convention to use for a particular function type.
Module * Parent
The parent of this module.
Selector getSetterName() const
const SanitizerBlacklist & getSanitizerBlacklist() const
Defines the Diagnostic-related interfaces.
submodule_iterator submodule_end()
virtual uint64_t getMaxPointerWidth() const
Return the maximum width of pointers on this target.
void addCompilerUsedGlobal(llvm::GlobalValue *GV)
Add a global to a list to be added to the llvm.compiler.used metadata.
bool isIncompleteType(NamedDecl **Def=nullptr) const
Types are partitioned into 3 broad categories (C99 6.2.5p1): object types, function types...
Represents binding an expression to a temporary.
llvm::Constant * CreateRuntimeVariable(llvm::Type *Ty, StringRef Name)
Create a new runtime global variable with the specified type and name.
DeclContext * getLexicalDeclContext()
getLexicalDeclContext - The declaration context where this Decl was lexically declared (LexicalDC)...
CXXTemporary * getTemporary()
const CGFunctionInfo & arrangeCXXMethodDeclaration(const CXXMethodDecl *MD)
C++ methods have some special rules and also have implicit parameters.
bool isStaticLocal() const
isStaticLocal - Returns true if a variable with function scope is a static local variable.
CharUnits getTypeSizeInChars(QualType T) const
Return the size of the specified (complete) type T, in characters.
void EmitTentativeDefinition(const VarDecl *D)
unsigned getLine() const
Return the presumed line number of this location.
void addInstanceMethod(ObjCMethodDecl *method)
llvm::SanitizerStatReport & getSanStats()
A class that does preordor or postorder depth-first traversal on the entire Clang AST and visits each...
Represents an ObjC class declaration.
propimpl_range property_impls() const
Represents a linkage specification.
void setGlobalVisibility(llvm::GlobalValue *GV, const NamedDecl *D) const
Set the visibility for the given LLVM GlobalValue.
detail::InMemoryDirectory::const_iterator I
The iOS ABI is a partial implementation of the ARM ABI.
unsigned getWCharWidth() const
getWCharWidth/Align - Return the size of 'wchar_t' for this target, in bits.
const CGFunctionInfo & arrangeGlobalDeclaration(GlobalDecl GD)
std::vector< Module * >::iterator submodule_iterator
void mangleName(const NamedDecl *D, raw_ostream &)
llvm::Constant * CreateRuntimeFunction(llvm::FunctionType *Ty, StringRef Name, llvm::AttributeList ExtraAttrs=llvm::AttributeList(), bool Local=false)
Create a new runtime function with the specified type and name.
bool isTypeConstant(QualType QTy, bool ExcludeCtorDtor)
isTypeConstant - Determine whether an object of this type can be emitted as a constant.
bool hasUnwindExceptions() const
Does this runtime use zero-cost exceptions?
FunctionDecl * getOperatorDelete() const
'watchos' is a variant of iOS for Apple's watchOS.
llvm::StringMap< SectionInfo > SectionInfos
static bool hasUnwindExceptions(const LangOptions &LangOpts)
Determines whether the language options require us to model unwind exceptions.
const FileEntry * getFileEntryForID(FileID FID) const
Returns the FileEntry record for the provided FileID.
static bool AllTrivialInitializers(CodeGenModule &CGM, ObjCImplementationDecl *D)
The generic ARM ABI is a modified version of the Itanium ABI proposed by ARM for use on ARM-based pla...
std::string CurrentModule
The name of the current module, of which the main source file is a part.
void setHasDestructors(bool val)
CXXMethodDecl * getMethodDecl() const
Retrieves the declaration of the called method.
const TargetCodeGenInfo & getTargetCodeGenInfo()
void AddDetectMismatch(StringRef Name, StringRef Value)
Appends a detect mismatch command to the linker options.
const TargetInfo & getTarget() const
Represents a ValueDecl that came out of a declarator.
bool EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx) const
EvaluateAsRValue - Return true if this is a constant which we can fold to an rvalue using any crazy t...
bool hasConstructorVariants() const
Does this ABI have different entrypoints for complete-object and base-subobject constructors?
llvm::SmallSetVector< Module *, 2 > Imports
The set of modules imported by this module, and on which this module depends.
void getObjCEncodingForType(QualType T, std::string &S, const FieldDecl *Field=nullptr, QualType *NotEncodedT=nullptr) const
Emit the Objective-CC type encoding for the given type T into S.
StringRef getBlockMangledName(GlobalDecl GD, const BlockDecl *BD)
std::vector< bool > & Stack
void getFunctionFeatureMap(llvm::StringMap< bool > &FeatureMap, const FunctionDecl *FD)
void DecorateInstructionWithTBAA(llvm::Instruction *Inst, llvm::MDNode *TBAAInfo, bool ConvertTypeToTag=true)
Decorate the instruction with a TBAA tag.
void SetLLVMFunctionAttributes(const Decl *D, const CGFunctionInfo &Info, llvm::Function *F)
Set the LLVM function attributes (sext, zext, etc).
llvm::Constant * EmitAnnotationUnit(SourceLocation Loc)
Emit the annotation's translation unit.
bool isMSStaticDataMemberInlineDefinition(const VarDecl *VD) const
Returns true if this is an inline-initialized static data member which is treated as a definition for...
virtual void EmitCXXConstructors(const CXXConstructorDecl *D)=0
Emit constructor variants required by this ABI.
bool isMicrosoft() const
Is this ABI an MSVC-compatible ABI?
const Type * getTypeForDecl() const
BlockDecl - This represents a block literal declaration, which is like an unnamed FunctionDecl...
ValueDecl - Represent the declaration of a variable (in which case it is an lvalue) a function (in wh...
Expr - This represents one expression.
StringRef getName() const
Return the actual identifier string.
CXXDtorType getDtorType() const
static ObjCMethodDecl * Create(ASTContext &C, SourceLocation beginLoc, SourceLocation endLoc, Selector SelInfo, QualType T, TypeSourceInfo *ReturnTInfo, DeclContext *contextDecl, bool isInstance=true, bool isVariadic=false, bool isPropertyAccessor=false, bool isImplicitlyDeclared=false, bool isDefined=false, ImplementationControl impControl=None, bool HasRelatedResultType=false)
Emit only debug info necessary for generating line number tables (-gline-tables-only).
'macosx' is the Apple-provided NeXT-derived runtime on Mac OS X platforms that use the non-fragile AB...
virtual void EmitCXXDestructors(const CXXDestructorDecl *D)=0
Emit destructor variants required by this ABI.
CGCXXABI & getCXXABI() const
void AddGlobalAnnotations(const ValueDecl *D, llvm::GlobalValue *GV)
Add global annotations that are set on D, for the global GV.
void GenerateObjCMethod(const ObjCMethodDecl *OMD)
Generate an Objective-C method.
StorageDuration getStorageDuration() const
Retrieve the storage duration for the materialized temporary.
llvm::Constant * GetAddrOfGlobalVar(const VarDecl *D, llvm::Type *Ty=nullptr, ForDefinition_t IsForDefinition=NotForDefinition)
Return the llvm::Constant for the address of the given global variable.
void SetInternalFunctionAttributes(const Decl *D, llvm::Function *F, const CGFunctionInfo &FI)
Set the attributes on the LLVM function for the given decl and function info.
Organizes the cross-function state that is used while generating code coverage mapping data...
Represents a C++ destructor within a class.
void reportDiagnostics(DiagnosticsEngine &Diags, StringRef MainFile)
Report potential problems we've found to Diags.
TranslationUnitDecl * getTranslationUnitDecl() const
Defines version macros and version-related utility functions for Clang.
Decl * getMostRecentDecl()
Retrieve the most recent declaration that declares the same entity as this declaration (which may be ...
DeclContext * getDeclContext()
ASTContext & getContext() const
unsigned getExpansionLineNumber(SourceLocation Loc, bool *Invalid=nullptr) const
static CharUnits fromQuantity(QuantityType Quantity)
fromQuantity - Construct a CharUnits quantity from a raw integer type.
static llvm::StringMapEntry< llvm::GlobalVariable * > & GetConstantCFStringEntry(llvm::StringMap< llvm::GlobalVariable * > &Map, const StringLiteral *Literal, bool TargetIsLSB, bool &IsUTF16, unsigned &StringLength)
llvm::SmallVector< LinkLibrary, 2 > LinkLibraries
The set of libraries or frameworks to link against when an entity from this module is used...
llvm::LLVMContext & getLLVMContext()
CharUnits toCharUnitsFromBits(int64_t BitSize) const
Convert a size in bits to a size in characters.
llvm::IntegerType * Int32Ty
llvm::GlobalValue::LinkageTypes getLLVMLinkageVarDefinition(const VarDecl *VD, bool IsConstant)
Returns LLVM linkage for a declarator.
clang::ObjCRuntime ObjCRuntime
llvm::Constant * EmitAnnotationString(StringRef Str)
Emit an annotation string.
llvm::PointerType * AllocaInt8PtrTy
QualType getObjCIdType() const
Represents the Objective-CC id type.
bool isExternallyVisible(Linkage L)
ConstantAddress GetAddrOfUuidDescriptor(const CXXUuidofExpr *E)
Get the address of a uuid descriptor .
llvm::GlobalVariable::LinkageTypes getFunctionLinkage(GlobalDecl GD)
Represents an unpacked "presumed" location which can be presented to the user.
unsigned Map[FirstTargetAddressSpace]
The type of a lookup table which maps from language-specific address spaces to target-specific ones...
StringRef getUuidStr() const
static bool isVarDeclStrongDefinition(const ASTContext &Context, CodeGenModule &CGM, const VarDecl *D, bool NoCommon)
llvm::Function * getIntrinsic(unsigned IID, ArrayRef< llvm::Type * > Tys=None)
CGOpenMPRuntime(CodeGenModule &CGM)
This template specialization was implicitly instantiated from a template.
'gnustep' is the modern non-fragile GNUstep runtime.
unsigned getIntAlign() const
void AddVTableTypeMetadata(llvm::GlobalVariable *VTable, CharUnits Offset, const CXXRecordDecl *RD)
Create and attach type metadata for the given vtable.
bool lookupRepresentativeDecl(StringRef MangledName, GlobalDecl &Result) const
__UINTPTR_TYPE__ uintptr_t
An unsigned integer type with the property that any valid pointer to void can be converted to this ty...
CallingConv
CallingConv - Specifies the calling convention that a function uses.
VarDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
QualType getWideCharType() const
Return the type of wide characters.
GlobalDecl - represents a global declaration.
llvm::GlobalVariable * CreateOrReplaceCXXRuntimeVariable(StringRef Name, llvm::Type *Ty, llvm::GlobalValue::LinkageTypes Linkage)
Will return a global variable of the given type.
const Expr * getAnyInitializer() const
getAnyInitializer - Get the initializer for this variable, no matter which declaration it is attached...
llvm::Constant * EmitAnnotateAttr(llvm::GlobalValue *GV, const AnnotateAttr *AA, SourceLocation L)
Generate the llvm::ConstantStruct which contains the annotation information for a given GlobalValue...
init_iterator init_begin()
init_begin() - Retrieve an iterator to the first initializer.
ConstantAddress GetAddrOfGlobalTemporary(const MaterializeTemporaryExpr *E, const Expr *Inner)
Returns a pointer to a global variable representing a temporary with static or thread storage duratio...
WatchOS is a modernisation of the iOS ABI, which roughly means it's the iOS64 ABI ported to 32-bits...
std::string CPU
If given, the name of the target CPU to generate code for.
The l-value was considered opaque, so the alignment was determined from a type.
SourceLocation getLocStart() const LLVM_READONLY
unsigned char IntAlignInBytes
bool doesThisDeclarationHaveABody() const
doesThisDeclarationHaveABody - Returns whether this specific declaration of the function has a body -...
llvm::CallingConv::ID getBuiltinCC() const
static void emitUsed(CodeGenModule &CGM, StringRef Name, std::vector< llvm::WeakTrackingVH > &List)
CharUnits getTypeAlignInChars(QualType T) const
Return the ABI-specified alignment of a (complete) type T, in characters.
SelectorTable & Selectors
bool hasOneOf(SanitizerMask K) const
Check if one or more sanitizers are enabled.
void RefreshTypeCacheForClass(const CXXRecordDecl *Class)
uint64_t getPointerAlign(unsigned AddrSpace) const
decl_type * getPreviousDecl()
Return the previous declaration of this declaration or NULL if this is the first declaration.
void MaybeHandleStaticInExternC(const SomeDecl *D, llvm::GlobalValue *GV)
If the declaration has internal linkage but is inside an extern "C" linkage specification, prepare to emit an alias for it to the expected name.
const char * getFilename() const
Return the presumed filename of this location.
llvm::Constant * EmitConstantExpr(const Expr *E, QualType DestType, CodeGenFunction *CGF=nullptr)
Try to emit the given expression as a constant; returns 0 if the expression cannot be emitted as a co...
Encodes a location in the source.
CharUnits getPointerAlign() const
virtual bool shouldMangleStringLiteral(const StringLiteral *SL)=0
static DeclContext * castToDeclContext(const TranslationUnitDecl *D)
IdentifierInfo & get(StringRef Name)
Return the identifier token info for the specified named identifier.
ExternalASTSource * getExternalSource() const
Retrieve a pointer to the external AST source associated with this AST context, if any...
const Type * getTypePtr() const
Retrieves a pointer to the underlying (unqualified) type.
bool isConstant(const ASTContext &Ctx) const
'objfw' is the Objective-C runtime included in ObjFW
ConstantAddress GetAddrOfConstantCFString(const StringLiteral *Literal)
Return a pointer to a constant CFString object for the given string.
bool hasSideEffects() const
bool isValid() const
Return true if this is a valid SourceLocation object.
Represents a new-expression for memory allocation and constructor calls, e.g: "new CXXNewExpr(foo)"...
TagDecl - Represents the declaration of a struct/union/class/enum.
Represents a call to a member function that may be written either with member call syntax (e...
ASTContext & getASTContext() const LLVM_READONLY
static OMPLinearClause * Create(const ASTContext &C, SourceLocation StartLoc, SourceLocation LParenLoc, OpenMPLinearClauseKind Modifier, SourceLocation ModifierLoc, SourceLocation ColonLoc, SourceLocation EndLoc, ArrayRef< Expr * > VL, ArrayRef< Expr * > PL, ArrayRef< Expr * > IL, Expr *Step, Expr *CalcStep, Stmt *PreInit, Expr *PostUpdate)
Creates clause with a list of variables VL and a linear step Step.
llvm::Metadata * CreateMetadataIdentifierForType(QualType T)
Create a metadata identifier for the given type.
llvm::IntegerType * Int16Ty
const XRayFunctionFilter & getXRayFilter() const
void mangleDtorBlock(const CXXDestructorDecl *CD, CXXDtorType DT, const BlockDecl *BD, raw_ostream &Out)
Represents a static or instance method of a struct/union/class.
MangleContext - Context for tracking state which persists across multiple calls to the C++ name mangl...
ConstantAddress GetAddrOfConstantStringFromLiteral(const StringLiteral *S, StringRef Name=".str")
Return a pointer to a constant array for the given string literal.
Weak for now, might become strong later in this TU.
llvm::Constant * CreateBuiltinFunction(llvm::FunctionType *Ty, StringRef Name, llvm::AttributeList ExtraAttrs=llvm::AttributeList())
Create a new compiler builtin function with the specified type and name.
const ConstantArrayType * getAsConstantArrayType(QualType T) const
SourceLocation getStrTokenLoc(unsigned TokNum) const
llvm::Constant * GetAddrOfRTTIDescriptor(QualType Ty, bool ForEH=false)
Get the address of the RTTI descriptor for the given type.
std::vector< std::string > Features
The list of target specific features to enable or disable – this should be a list of strings starting...
const ObjCInterfaceDecl * getClassInterface() const
bool isTrivialInitializer(const Expr *Init)
Determine whether the given initializer is trivial in the sense that it requires no code to be genera...
llvm::MDNode * getTBAAStructTagInfo(QualType BaseTy, llvm::MDNode *AccessN, uint64_t O)
Return the path-aware tag for given base type, access node and offset.
unsigned getCharByteWidth() const
SanitizerSet SanitizeTrap
Set of sanitizer checks that trap rather than diagnose.
const CodeGenOptions & getCodeGenOpts() const
void addGlobalValReplacement(llvm::GlobalValue *GV, llvm::Constant *C)
const Type * getBaseElementTypeUnsafe() const
Get the base element type of this type, potentially discarding type qualifiers.
ConstantAddress GetWeakRefReference(const ValueDecl *VD)
Get a reference to the target of VD.
LinkageInfo getLinkageAndVisibility() const
Determines the linkage and visibility of this entity.
init_iterator init_end()
init_end() - Retrieve an iterator past the last initializer.
const LangOptions & getLangOpts() const
Represents one property declaration in an Objective-C interface.
void SetLLVMFunctionAttributesForDefinition(const Decl *D, llvm::Function *F)
Set the LLVM function attributes which only apply to a function definition.
bool containsNonAsciiOrNull() const
std::vector< std::string > FeaturesAsWritten
The list of target specific features to enable or disable, as written on the command line...
The generic Itanium ABI is the standard ABI of most open-source and Unix-like platforms.
bool isGNUFamily() const
Is this runtime basically of the GNU family of runtimes?
lookup_result lookup(DeclarationName Name) const
lookup - Find the declarations (if any) with the given Name in this context.
unsigned getCustomDiagID(Level L, const char(&FormatString)[N])
Return an ID for a diagnostic with the specified format string and level.
void EmitTopLevelDecl(Decl *D)
Emit code for a single top level declaration.
MangleContext & getMangleContext()
Gets the mangle context.
This template specialization was instantiated from a template due to an explicit instantiation defini...
FileID getMainFileID() const
Returns the FileID of the main source file.
CGCXXABI * CreateMicrosoftCXXABI(CodeGenModule &CGM)
Creates a Microsoft-family ABI.
void CreateFunctionTypeMetadata(const FunctionDecl *FD, llvm::Function *F)
Create and attach type metadata to the given function.
llvm::Constant * EmitAnnotationLineNo(SourceLocation L)
Emit the annotation line number.
unsigned getBuiltinID() const
Returns a value indicating whether this function corresponds to a builtin function.
void Error(SourceLocation loc, StringRef error)
Emit a general error that something can't be done.
virtual void mangleTypeName(QualType T, raw_ostream &)=0
Generates a unique string for an externally visible type for use with TBAA or type uniquing...
CXXCtorType
C++ constructor types.
The WebAssembly ABI is a modified version of the Itanium ABI.
void addReplacement(StringRef Name, llvm::Constant *C)
ConstantAddress GetAddrOfConstantCString(const std::string &Str, const char *GlobalName=nullptr)
Returns a pointer to a character array containing the literal and a terminating '\0' character...
llvm::Constant * GetAddrOfGlobal(GlobalDecl GD, ForDefinition_t IsForDefinition=NotForDefinition)
ArrayRef< Decl * > getModuleInitializers(Module *M)
Get the initializations to perform when importing a module, if any.
void addUsedGlobal(llvm::GlobalValue *GV)
Add a global to a list to be added to the llvm.used metadata.
ObjCIvarDecl * getNextIvar()
if(T->getSizeExpr()) TRY_TO(TraverseStmt(T-> getSizeExpr()))
TLS with a dynamic initializer.
void ErrorUnsupported(const Stmt *S, const char *Type)
Print out an error that codegen doesn't support the specified stmt yet.
CGFunctionInfo - Class to encapsulate the information about a function definition.
This class organizes the cross-function state that is used while generating LLVM code.
CGOpenMPRuntime & getOpenMPRuntime()
Return a reference to the configured OpenMP runtime.
virtual void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &M) const
setTargetAttributes - Provides a convenient hook to handle extra target-specific attributes for the g...
llvm::GlobalValue * GetGlobalValue(StringRef Ref)
void mangleGlobalBlock(const BlockDecl *BD, const NamedDecl *ID, raw_ostream &Out)
void mangleBlock(const DeclContext *DC, const BlockDecl *BD, raw_ostream &Out)
virtual unsigned getASTAllocaAddressSpace() const
Get the AST address space for alloca.
DeclContext - This is used only as base class of specific decl types that can act as declaration cont...
EvalResult is a struct with detailed info about an evaluated expression.
Represents a delete expression for memory deallocation and destructor calls, e.g. ...
void GenerateObjCGetter(ObjCImplementationDecl *IMP, const ObjCPropertyImplDecl *PID)
GenerateObjCGetter - Synthesize an Objective-C property getter function.
unsigned char PointerAlignInBytes
FunctionDecl * getDirectCallee()
If the callee is a FunctionDecl, return it. Otherwise return 0.
ObjCMethodDecl * getInstanceMethod(Selector Sel, bool AllowHidden=false) const
The basic abstraction for the target Objective-C runtime.
void setTLSMode(llvm::GlobalValue *GV, const VarDecl &D) const
Set the TLS mode for the given LLVM GlobalValue for the thread-local variable declaration D...
void EmitOMPThreadPrivateDecl(const OMPThreadPrivateDecl *D)
Emit a code for threadprivate directive.
std::unique_ptr< DiagnosticConsumer > create(StringRef OutputFile, DiagnosticOptions *Diags, bool MergeChildRecords=false)
Returns a DiagnosticConsumer that serializes diagnostics to a bitcode file.
LanguageIDs getLanguage() const
Return the language specified by this linkage specification.
bool hasProfileClangUse() const
Check if Clang profile use is on.
llvm::IntegerType * IntPtrTy
QualType getPointerType(QualType T) const
Return the uniqued reference to the type for a pointer to the specified type.
Selector getGetterName() const
DefinitionKind isThisDeclarationADefinition(ASTContext &) const
Check whether this declaration is a definition.
StringRef getString() const
llvm::Constant * EmitNullConstant(QualType T)
Return the result of value-initializing the given type, i.e.
const llvm::Triple & getTriple() const
Returns the target triple of the primary target.
void UpdateCompletedType(const TagDecl *TD)
detail::InMemoryDirectory::const_iterator E
static bool needsDestructMethod(ObjCImplementationDecl *impl)
TemplateSpecializationKind
Describes the kind of template specialization that a particular template specialization declaration r...
static void addLinkOptionsPostorder(CodeGenModule &CGM, Module *Mod, SmallVectorImpl< llvm::MDNode * > &Metadata, llvm::SmallPtrSet< Module *, 16 > &Visited)
Add link options implied by the given module, including modules it depends on, using a postorder walk...
CanQualType getCanonicalType(QualType T) const
Return the canonical (structural) type corresponding to the specified potentially non-canonical type ...
static llvm::GlobalVariable::ThreadLocalMode GetLLVMTLSModel(StringRef S)
virtual llvm::Function * emitThreadPrivateVarDefinition(const VarDecl *VD, Address VDAddr, SourceLocation Loc, bool PerformInit, CodeGenFunction *CGF=nullptr)
Emit a code for initialization of threadprivate variable.
void maybeSetTrivialComdat(const Decl &D, llvm::GlobalObject &GO)
bool isInSanitizerBlacklist(llvm::Function *Fn, SourceLocation Loc) const
void EmitThunks(GlobalDecl GD)
EmitThunks - Emit the associated thunks for the given global decl.
virtual void registerDeviceVar(llvm::GlobalVariable &Var, unsigned Flags)=0
void AddDeferredUnusedCoverageMapping(Decl *D)
Stored a deferred empty coverage mapping for an unused and thus uninstrumented top level declaration...
bool isVisibilityExplicit() const
GVALinkage GetGVALinkageForVariable(const VarDecl *VD)
'ios' is the Apple-provided NeXT-derived runtime on iOS or the iOS simulator; it is always non-fragil...
void emitEmptyCounterMapping(const Decl *D, StringRef FuncName, llvm::GlobalValue::LinkageTypes Linkage)
Emit a coverage mapping range with a counter zero for an unused declaration.
ObjCImplementationDecl - Represents a class definition - this is where method definitions are specifi...
A helper class that allows the use of isa/cast/dyncast to detect TagType objects of structs/unions/cl...
StructorType getFromCtorType(CXXCtorType T)
FunctionDecl * getOperatorNew() const
const T * getAs() const
Member-template getAs<specific type>'.
void AppendLinkerOptions(StringRef Opts)
Appends Opts to the "llvm.linker.options" metadata value.
llvm::PointerType * getSamplerType()
void setHasNonZeroConstructors(bool val)
llvm::Type * ConvertFunctionType(QualType FT, const FunctionDecl *FD=nullptr)
Converts the GlobalDecl into an llvm::Type.
QualType getCanonicalType() const
TargetOptions & getTargetOpts() const
Retrieve the target options.
Represents a C++ base or member initializer.
virtual llvm::Constant * getAddrOfRTTIDescriptor(QualType Ty)=0
CanQualType UnsignedLongTy
Implements C++ ABI-specific code generation functions.
ObjCEncodeExpr, used for @encode in Objective-C.
Selector getSelector(unsigned NumArgs, IdentifierInfo **IIV)
Can create any sort of selector.
bool hasDiagnostics()
Whether or not the stats we've gathered indicate any potential problems.
llvm::PointerType * Int8PtrTy
bool has(SanitizerMask K) const
Check if a certain (single) sanitizer is enabled.
void GenerateClassData(const CXXRecordDecl *RD)
GenerateClassData - Generate all the class data required to be generated upon definition of a KeyFunc...
CodeGenOptions - Track various options which control how the code is optimized and passed to the back...
LanguageLinkage getLanguageLinkage() const
Compute the language linkage.
static void ReplaceUsesOfNonProtoTypeWithRealFunction(llvm::GlobalValue *Old, llvm::Function *NewFn)
ReplaceUsesOfNonProtoTypeWithRealFunction - This function is called when we implement a function with...
CXXConstructorDecl * getConstructor() const
Get the constructor that this expression will (ultimately) call.
llvm::Constant * GetAddrOfFunction(GlobalDecl GD, llvm::Type *Ty=nullptr, bool ForVTable=false, bool DontDefer=false, ForDefinition_t IsForDefinition=NotForDefinition)
Return the address of the given function.
CXXRecordDecl * getAsCXXRecordDecl() const
Retrieves the CXXRecordDecl that this type refers to, either because the type is a RecordType or beca...
StringRef getMangledName(GlobalDecl GD)
virtual void getDetectMismatchOption(llvm::StringRef Name, llvm::StringRef Value, llvm::SmallString< 32 > &Opt) const
Gets the linker options necessary to detect object file mismatches on this platform.
uint64_t getCharWidth() const
Return the size of the character type, in bits.
Internal linkage, which indicates that the entity can be referred to from within the translation unit...
llvm::Value * createOpenCLIntToSamplerConversion(const Expr *E, CodeGenFunction &CGF)
void addDecl(Decl *D)
Add the declaration D into this context.
CGCUDARuntime * CreateNVCUDARuntime(CodeGenModule &CGM)
Creates an instance of a CUDA runtime class.
unsigned getIntWidth() const
getIntWidth/Align - Return the size of 'signed int' and 'unsigned int' for this target, in bits.
QualType getTagDeclType(const TagDecl *Decl) const
Return the unique reference to the type for the specified TagDecl (struct/union/class/enum) decl...
APValue - This class implements a discriminated union of [uninitialized] [APSInt] [APFloat]...
CodeGenTBAA - This class organizes the cross-module state that is used while lowering AST types to LL...
Represents a base class of a C++ class.
llvm::Constant * EmitConstantInit(const VarDecl &D, CodeGenFunction *CGF=nullptr)
Try to emit the initializer for the given declaration as a constant; returns 0 if the expression cann...
static const char AnnotationSection[]
Linkage getLinkage() const
Determine the linkage of this type.
SourceManager & getSourceManager()
bool isTLSSupported() const
Whether the target supports thread-local storage.
llvm::ConstantInt * getSize(CharUnits numChars)
Emit the given number of characters as a value of type size_t.
uint64_t getPointerWidth(unsigned AddrSpace) const
Return the width of pointers on this target, for the specified address space.
virtual llvm::Value * performAddrSpaceCast(CodeGen::CodeGenFunction &CGF, llvm::Value *V, unsigned SrcAddr, unsigned DestAddr, llvm::Type *DestTy, bool IsNonNull=false) const
Perform address space cast of an expression of pointer type.
Defines the C++ Decl subclasses, other than those for templates (found in DeclTemplate.h) and friends (in DeclFriend.h).
DiagnosticsEngine & getDiags() const
QualType getUnqualifiedType() const
Retrieve the unqualified variant of the given type, removing as little sugar as possible.
Represents a C++ struct/union/class.
CGCXXABI * CreateItaniumCXXABI(CodeGenModule &CGM)
Creates an Itanium-family ABI.
BoundNodesTreeBuilder *const Builder
TargetCXXABI getCXXABI() const
Get the C++ ABI currently in use.
bool isReadOnly() const
isReadOnly - Return true iff the property has a setter.
bool isObjCObjectPointerType() const
QualType getEncodedType() const
llvm::iterator_range< specific_attr_iterator< T > > specific_attrs() const
A specialization of Address that requires the address to be an LLVM Constant.
ObjCIvarDecl - Represents an ObjC instance variable.
static bool HasNonDllImportDtor(QualType T)
void Release()
Finalize LLVM code generation.
static bool shouldBeInCOMDAT(CodeGenModule &CGM, const Decl &D)
void ClearUnusedCoverageMapping(const Decl *D)
Remove the deferred empty coverage mapping as this declaration is actually instrumented.
Builtin::Context & BuiltinInfo
virtual void mangleStringLiteral(const StringLiteral *SL, raw_ostream &)=0
void EmitGlobalAnnotations()
Emit all the global annotations.
llvm::ConstantInt * CreateCrossDsoCfiTypeId(llvm::Metadata *MD)
Generate a cross-DSO type identifier for MD.
llvm::CallingConv::ID getRuntimeCC() const
Return the calling convention to use for system runtime functions.
void SetCommonAttributes(const Decl *D, llvm::GlobalValue *GV)
Set attributes which are common to any form of a global definition (alias, Objective-C method...
SourceRange getSourceRange() const LLVM_READONLY
SourceLocation tokens are not useful in isolation - they are low level value objects created/interpre...
StringLiteral - This represents a string literal expression, e.g.
Defines the clang::TargetInfo interface.
CallExpr - Represents a function call (C99 6.5.2.2, C++ [expr.call]).
void RefreshTypeCacheForClass(const CXXRecordDecl *RD)
Remove stale types from the type cache when an inheritance model gets assigned to a class...
virtual bool useThunkForDtorVariant(const CXXDestructorDecl *Dtor, CXXDtorType DT) const =0
Returns true if the given destructor type should be emitted as a linkonce delegating thunk...
llvm::MDNode * getTBAAInfo(QualType QTy)
QualType getObjCFastEnumerationStateType()
Retrieve the record type that describes the state of an Objective-C fast enumeration loop (for...
bool isCompilingModule() const
Are we compiling a module interface (.cppm or module map)?
TranslationUnitDecl - The top declaration context.
unsigned getTargetAddressSpace(QualType T) const
unsigned char SizeSizeInBytes
A reference to a declared variable, function, enum, etc.
GVALinkage
A more specific kind of linkage than enum Linkage.
const llvm::Triple & getTriple() const
QualType getConstantArrayType(QualType EltTy, const llvm::APInt &ArySize, ArrayType::ArraySizeModifier ASM, unsigned IndexTypeQuals) const
Return the unique reference to the type for a constant array of the specified element type...
virtual unsigned getGlobalVarAddressSpace(CodeGenModule &CGM, const VarDecl *D) const
Get target favored AST address space of a global variable for languages other than OpenCL and CUDA...
static llvm::Constant * GetPointerConstant(llvm::LLVMContext &Context, const void *Ptr)
Turns the given pointer into a constant.
CodeGenVTables & getVTables()
SourceLocation getLocation() const
NamedDecl - This represents a decl with a name.
ObjCIvarDecl * all_declared_ivar_begin()
all_declared_ivar_begin - return first ivar declared in this class, its extensions and its implementa...
void setAccess(AccessSpecifier AS)
static void replaceUsesOfNonProtoConstant(llvm::Constant *old, llvm::Function *newFn)
Replace the uses of a function that was declared with a non-proto type.
bool DeclMustBeEmitted(const Decl *D)
Determines if the decl can be CodeGen'ed or deserialized from PCH lazily, only when used; this is onl...
DefinitionKind hasDefinition(ASTContext &) const
Check whether this variable is defined in this translation unit.
A Microsoft C++ __uuidof expression, which gets the _GUID that corresponds to the supplied type or ex...
CharUnits getAlignOfGlobalVarInChars(QualType T) const
Return the alignment in characters that should be given to a global variable with type T...
void EmitCfiCheckStub()
Emit a stub for the cross-DSO CFI check function.
bool isNull() const
Return true if this QualType doesn't point to a type yet.
void mangleCtorBlock(const CXXConstructorDecl *CD, CXXCtorType CT, const BlockDecl *BD, raw_ostream &Out)
static FieldDecl * Create(const ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, IdentifierInfo *Id, QualType T, TypeSourceInfo *TInfo, Expr *BW, bool Mutable, InClassInitStyle InitStyle)
SourceLocation getLocStart() const LLVM_READONLY
This represents '#pragma omp threadprivate ...' directive.
Represents the canonical version of C arrays with a specified constant size.
This class handles loading and caching of source files into memory.
const CXXDestructorDecl * getDestructor() const
QualType getBaseElementType(const ArrayType *VAT) const
Return the innermost element type of an array type.
void EmitGlobal(GlobalDecl D)
Emit code for a singal global function or var decl.
Defines enum values for all the target-independent builtin functions.
void AddDependentLib(StringRef Lib)
Appends a dependent lib to the "llvm.linker.options" metadata value.
llvm::GlobalValue::LinkageTypes getLLVMLinkageForDeclarator(const DeclaratorDecl *D, GVALinkage Linkage, bool IsConstantVariable)
Returns LLVM linkage for a declarator.
Attr - This represents one attribute.
bool supportsCOMDAT() const
APValue * getMaterializedTemporaryValue(const MaterializeTemporaryExpr *E, bool MayCreate)
Get the storage for the constant value of a materialized temporary of static storage duration...
llvm::MDNode * getTBAAInfoForVTablePtr()
PrettyStackTraceDecl - If a crash occurs, indicate that it happened when doing something to a specifi...
unsigned getNumIvarInitializers() const
getNumArgs - Number of ivars which must be initialized.
static CharUnits getDeclAlign(Expr *E, CharUnits TypeAlign, ASTContext &Context)
A helper function to get the alignment of a Decl referred to by DeclRefExpr or MemberExpr.
CGObjCRuntime * CreateGNUObjCRuntime(CodeGenModule &CGM)
Creates an instance of an Objective-C runtime class.
bool isPointerType() const
static LLVM_READONLY bool isHexDigit(unsigned char c)
Return true if this character is an ASCII hex digit: [0-9a-fA-F].
llvm::FunctionType * GetFunctionType(const CGFunctionInfo &Info)
GetFunctionType - Get the LLVM function type for.
QualType getCFConstantStringType() const
Return the C structure type used to represent constant CFStrings.
PresumedLoc getPresumedLoc(SourceLocation Loc, bool UseLineDirectives=true) const
Returns the "presumed" location of a SourceLocation specifies.