46 #include "llvm/ADT/APSInt.h"
47 #include "llvm/ADT/Triple.h"
48 #include "llvm/IR/CallSite.h"
49 #include "llvm/IR/CallingConv.h"
50 #include "llvm/IR/DataLayout.h"
51 #include "llvm/IR/Intrinsics.h"
52 #include "llvm/IR/LLVMContext.h"
53 #include "llvm/IR/Module.h"
54 #include "llvm/ProfileData/InstrProfReader.h"
55 #include "llvm/Support/ConvertUTF.h"
56 #include "llvm/Support/ErrorHandling.h"
57 #include "llvm/Support/MD5.h"
59 using namespace clang;
60 using namespace CodeGen;
79 llvm_unreachable(
"invalid C++ ABI kind");
87 :
Context(C), LangOpts(C.getLangOpts()), HeaderSearchOpts(HSO),
88 PreprocessorOpts(PPO), CodeGenOpts(CGO), TheModule(M), Diags(diags),
90 VMContext(M.getContext()), Types(*this), VTables(*this),
94 llvm::LLVMContext &LLVMContext = M.getContext();
95 VoidTy = llvm::Type::getVoidTy(LLVMContext);
96 Int8Ty = llvm::Type::getInt8Ty(LLVMContext);
97 Int16Ty = llvm::Type::getInt16Ty(LLVMContext);
98 Int32Ty = llvm::Type::getInt32Ty(LLVMContext);
99 Int64Ty = llvm::Type::getInt64Ty(LLVMContext);
100 FloatTy = llvm::Type::getFloatTy(LLVMContext);
101 DoubleTy = llvm::Type::getDoubleTy(LLVMContext);
118 createOpenCLRuntime();
120 createOpenMPRuntime();
125 if (LangOpts.
Sanitize.
has(SanitizerKind::Thread) ||
126 (!CodeGenOpts.RelaxedAliasing && CodeGenOpts.OptimizationLevel > 0))
133 CodeGenOpts.EmitGcovArcs || CodeGenOpts.EmitGcovNotes)
136 Block.GlobalUniqueCount = 0;
144 if (
auto E = ReaderOrErr.takeError()) {
146 "Could not read profile %0: %1");
147 llvm::handleAllErrors(std::move(
E), [&](
const llvm::ErrorInfoBase &EI) {
152 PGOReader = std::move(ReaderOrErr.get());
157 if (CodeGenOpts.CoverageMapping)
163 void CodeGenModule::createObjCRuntime() {
180 llvm_unreachable(
"bad runtime kind");
183 void CodeGenModule::createOpenCLRuntime() {
187 void CodeGenModule::createOpenMPRuntime() {
192 case llvm::Triple::nvptx:
193 case llvm::Triple::nvptx64:
195 "OpenMP NVPTX is only prepared to deal with device code.");
204 void CodeGenModule::createCUDARuntime() {
209 Replacements[
Name] = C;
212 void CodeGenModule::applyReplacements() {
213 for (
auto &
I : Replacements) {
214 StringRef MangledName =
I.first();
219 auto *OldF = cast<llvm::Function>(Entry);
220 auto *NewF = dyn_cast<llvm::Function>(
Replacement);
222 if (
auto *Alias = dyn_cast<llvm::GlobalAlias>(Replacement)) {
223 NewF = dyn_cast<llvm::Function>(Alias->getAliasee());
226 assert(CE->getOpcode() == llvm::Instruction::BitCast ||
227 CE->getOpcode() == llvm::Instruction::GetElementPtr);
228 NewF = dyn_cast<llvm::Function>(CE->getOperand(0));
233 OldF->replaceAllUsesWith(Replacement);
235 NewF->removeFromParent();
236 OldF->getParent()->getFunctionList().insertAfter(OldF->getIterator(),
239 OldF->eraseFromParent();
244 GlobalValReplacements.push_back(std::make_pair(GV, C));
247 void CodeGenModule::applyGlobalValReplacements() {
248 for (
auto &
I : GlobalValReplacements) {
249 llvm::GlobalValue *GV =
I.first;
250 llvm::Constant *C =
I.second;
252 GV->replaceAllUsesWith(C);
253 GV->eraseFromParent();
260 const llvm::GlobalIndirectSymbol &GIS) {
261 llvm::SmallPtrSet<const llvm::GlobalIndirectSymbol*, 4> Visited;
262 const llvm::Constant *C = &GIS;
264 C = C->stripPointerCasts();
265 if (
auto *GO = dyn_cast<llvm::GlobalObject>(C))
268 auto *GIS2 = dyn_cast<llvm::GlobalIndirectSymbol>(C);
271 if (!Visited.insert(GIS2).second)
273 C = GIS2->getIndirectSymbol();
277 void CodeGenModule::checkAliases() {
284 const auto *D = cast<ValueDecl>(GD.getDecl());
286 bool IsIFunc = D->hasAttr<IFuncAttr>();
287 if (
const Attr *A = D->getDefiningAttr())
288 Location = A->getLocation();
290 llvm_unreachable(
"Not an alias or ifunc?");
293 auto *Alias = cast<llvm::GlobalIndirectSymbol>(Entry);
297 Diags.
Report(Location, diag::err_cyclic_alias) << IsIFunc;
298 }
else if (GV->isDeclaration()) {
300 Diags.
Report(Location, diag::err_alias_to_undefined)
301 << IsIFunc << IsIFunc;
302 }
else if (IsIFunc) {
304 llvm::FunctionType *FTy = dyn_cast<llvm::FunctionType>(
305 GV->getType()->getPointerElementType());
307 if (!FTy->getReturnType()->isPointerTy())
308 Diags.
Report(Location, diag::err_ifunc_resolver_return);
309 if (FTy->getNumParams())
310 Diags.
Report(Location, diag::err_ifunc_resolver_params);
313 llvm::Constant *Aliasee = Alias->getIndirectSymbol();
314 llvm::GlobalValue *AliaseeGV;
315 if (
auto CE = dyn_cast<llvm::ConstantExpr>(Aliasee))
316 AliaseeGV = cast<llvm::GlobalValue>(CE->getOperand(0));
318 AliaseeGV = cast<llvm::GlobalValue>(Aliasee);
320 if (
const SectionAttr *SA = D->getAttr<SectionAttr>()) {
321 StringRef AliasSection = SA->getName();
322 if (AliasSection != AliaseeGV->getSection())
323 Diags.
Report(SA->getLocation(), diag::warn_alias_with_section)
324 << AliasSection << IsIFunc << IsIFunc;
332 if (
auto GA = dyn_cast<llvm::GlobalIndirectSymbol>(AliaseeGV)) {
333 if (GA->isInterposable()) {
334 Diags.
Report(Location, diag::warn_alias_to_weak_alias)
335 << GV->getName() << GA->getName() << IsIFunc;
336 Aliasee = llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(
337 GA->getIndirectSymbol(), Alias->getType());
338 Alias->setIndirectSymbol(Aliasee);
348 auto *Alias = dyn_cast<llvm::GlobalIndirectSymbol>(Entry);
349 Alias->replaceAllUsesWith(llvm::UndefValue::get(Alias->getType()));
350 Alias->eraseFromParent();
355 DeferredDeclsToEmit.clear();
357 OpenMPRuntime->clear();
361 StringRef MainFile) {
364 if (VisitedInMainFile > 0 && VisitedInMainFile == MissingInMainFile) {
365 if (MainFile.empty())
366 MainFile =
"<stdin>";
367 Diags.
Report(diag::warn_profile_data_unprofiled) << MainFile;
369 Diags.
Report(diag::warn_profile_data_out_of_date) << Visited << Missing
375 applyGlobalValReplacements();
378 EmitCXXGlobalInitFunc();
379 EmitCXXGlobalDtorFunc();
380 EmitCXXThreadLocalInitFunc();
382 if (llvm::Function *ObjCInitFunction =
ObjCRuntime->ModuleInitFunction())
383 AddGlobalCtor(ObjCInitFunction);
386 if (llvm::Function *CudaCtorFunction = CUDARuntime->makeModuleCtorFunction())
387 AddGlobalCtor(CudaCtorFunction);
388 if (llvm::Function *CudaDtorFunction = CUDARuntime->makeModuleDtorFunction())
389 AddGlobalDtor(CudaDtorFunction);
392 if (llvm::Function *OpenMPRegistrationFunction =
393 OpenMPRuntime->emitRegistrationFunction())
394 AddGlobalCtor(OpenMPRegistrationFunction, 0);
396 getModule().setProfileSummary(PGOReader->getSummary().getMD(VMContext));
400 EmitCtorList(GlobalCtors,
"llvm.global_ctors");
401 EmitCtorList(GlobalDtors,
"llvm.global_dtors");
403 EmitStaticExternCAliases();
406 CoverageMapping->emit();
407 if (CodeGenOpts.SanitizeCfiCrossDso)
413 if (CodeGenOpts.Autolink &&
414 (Context.
getLangOpts().Modules || !LinkerOptionsMetadata.empty())) {
415 EmitModuleLinkOptions();
417 if (CodeGenOpts.DwarfVersion) {
421 CodeGenOpts.DwarfVersion);
423 if (CodeGenOpts.EmitCodeView) {
427 if (CodeGenOpts.OptimizationLevel > 0 && CodeGenOpts.StrictVTablePointers) {
434 llvm::Metadata *Ops[2] = {
435 llvm::MDString::get(VMContext,
"StrictVTablePointers"),
436 llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
437 llvm::Type::getInt32Ty(VMContext), 1))};
439 getModule().addModuleFlag(llvm::Module::Require,
440 "StrictVTablePointersRequirement",
441 llvm::MDNode::get(VMContext, Ops));
448 llvm::DEBUG_METADATA_VERSION);
453 if ( Arch == llvm::Triple::arm
454 || Arch == llvm::Triple::armeb
455 || Arch == llvm::Triple::thumb
456 || Arch == llvm::Triple::thumbeb) {
458 uint64_t WCharWidth =
463 uint64_t EnumWidth = Context.
getLangOpts().ShortEnums ? 1 : 4;
467 if (CodeGenOpts.SanitizeCfiCrossDso) {
469 getModule().addModuleFlag(llvm::Module::Override,
"Cross-DSO CFI", 1);
476 getModule().addModuleFlag(llvm::Module::Override,
"nvvm-reflect-ftz",
477 LangOpts.CUDADeviceFlushDenormalsToZero ? 1 : 0);
480 if (uint32_t PLevel = Context.
getLangOpts().PICLevel) {
481 assert(PLevel < 3 &&
"Invalid PIC Level");
482 getModule().setPICLevel(static_cast<llvm::PICLevel::Level>(PLevel));
484 getModule().setPIELevel(static_cast<llvm::PIELevel::Level>(PLevel));
487 SimplifyPersonality();
496 DebugInfo->finalize();
498 EmitVersionIdentMetadata();
500 EmitTargetMetadata();
516 return TBAA->getTBAAInfo(QTy);
522 return TBAA->getTBAAInfoForVTablePtr();
528 return TBAA->getTBAAStructInfo(QTy);
532 llvm::MDNode *AccessN,
536 return TBAA->getTBAAStructTagInfo(BaseTy, AccessN, O);
544 llvm::MDNode *TBAAInfo,
545 bool ConvertTypeToTag) {
546 if (ConvertTypeToTag && TBAA)
547 Inst->setMetadata(llvm::LLVMContext::MD_tbaa,
548 TBAA->getTBAAScalarTagInfo(TBAAInfo));
550 Inst->setMetadata(llvm::LLVMContext::MD_tbaa, TBAAInfo);
556 auto *MetaDataNode = dyn_cast<llvm::MDNode>(MD);
560 I->setMetadata(llvm::LLVMContext::MD_invariant_group, MetaDataNode);
572 "cannot compile this %0 yet");
573 std::string Msg =
Type;
575 << Msg << S->getSourceRange();
582 "cannot compile this %0 yet");
583 std::string Msg =
Type;
594 if (GV->hasLocalLinkage()) {
606 return llvm::StringSwitch<llvm::GlobalVariable::ThreadLocalMode>(
S)
607 .Case(
"global-dynamic", llvm::GlobalVariable::GeneralDynamicTLSModel)
608 .Case(
"local-dynamic", llvm::GlobalVariable::LocalDynamicTLSModel)
609 .Case(
"initial-exec", llvm::GlobalVariable::InitialExecTLSModel)
610 .Case(
"local-exec", llvm::GlobalVariable::LocalExecTLSModel);
617 return llvm::GlobalVariable::GeneralDynamicTLSModel;
619 return llvm::GlobalVariable::LocalDynamicTLSModel;
621 return llvm::GlobalVariable::InitialExecTLSModel;
623 return llvm::GlobalVariable::LocalExecTLSModel;
625 llvm_unreachable(
"Invalid TLS model!");
629 assert(D.
getTLSKind() &&
"setting TLS mode on non-TLS var!");
631 llvm::GlobalValue::ThreadLocalMode TLM;
635 if (
const TLSModelAttr *
Attr = D.getAttr<TLSModelAttr>()) {
639 GV->setThreadLocalMode(TLM);
647 if (
const auto *CD = dyn_cast<CXXConstructorDecl>(CanonicalGD.
getDecl())) {
656 StringRef &FoundStr = MangledDeclNames[CanonicalGD];
657 if (!FoundStr.empty())
660 const auto *ND = cast<NamedDecl>(GD.
getDecl());
664 llvm::raw_svector_ostream Out(Buffer);
665 if (
const auto *D = dyn_cast<CXXConstructorDecl>(ND))
667 else if (
const auto *D = dyn_cast<CXXDestructorDecl>(ND))
674 assert(II &&
"Attempt to mangle unnamed decl.");
679 auto Result = Manglings.insert(std::make_pair(Str, GD));
680 return FoundStr =
Result.first->first();
689 llvm::raw_svector_ostream Out(Buffer);
692 dyn_cast_or_null<VarDecl>(initializedGlobalDecl.
getDecl()), Out);
693 else if (
const auto *CD = dyn_cast<CXXConstructorDecl>(D))
695 else if (
const auto *DD = dyn_cast<CXXDestructorDecl>(D))
698 MangleCtx.
mangleBlock(cast<DeclContext>(D), BD, Out);
700 auto Result = Manglings.insert(std::make_pair(Out.str(), BD));
701 return Result.first->first();
710 void CodeGenModule::AddGlobalCtor(llvm::Function *Ctor,
int Priority,
711 llvm::Constant *AssociatedData) {
713 GlobalCtors.push_back(Structor(Priority, Ctor, AssociatedData));
718 void CodeGenModule::AddGlobalDtor(llvm::Function *Dtor,
int Priority) {
720 GlobalDtors.push_back(Structor(Priority, Dtor,
nullptr));
723 void CodeGenModule::EmitCtorList(
const CtorList &Fns,
const char *GlobalName) {
725 llvm::FunctionType* CtorFTy = llvm::FunctionType::get(
VoidTy,
false);
726 llvm::Type *CtorPFTy = llvm::PointerType::getUnqual(CtorFTy);
729 llvm::StructType *CtorStructTy = llvm::StructType::get(
734 for (
const auto &
I : Fns) {
735 llvm::Constant *
S[] = {
736 llvm::ConstantInt::get(
Int32Ty,
I.Priority,
false),
737 llvm::ConstantExpr::getBitCast(
I.Initializer, CtorPFTy),
739 ? llvm::ConstantExpr::getBitCast(
I.AssociatedData,
VoidPtrTy)
740 : llvm::Constant::getNullValue(
VoidPtrTy))};
741 Ctors.push_back(llvm::ConstantStruct::get(CtorStructTy, S));
744 if (!Ctors.empty()) {
745 llvm::ArrayType *AT = llvm::ArrayType::get(CtorStructTy, Ctors.size());
746 new llvm::GlobalVariable(TheModule, AT,
false,
747 llvm::GlobalValue::AppendingLinkage,
748 llvm::ConstantArray::get(AT, Ctors),
753 llvm::GlobalValue::LinkageTypes
755 const auto *D = cast<FunctionDecl>(GD.
getDecl());
759 if (isa<CXXDestructorDecl>(D) &&
760 getCXXABI().useThunkForDtorVariant(cast<CXXDestructorDecl>(D),
765 : llvm::GlobalValue::LinkOnceODRLinkage;
768 if (isa<CXXConstructorDecl>(D) &&
769 cast<CXXConstructorDecl>(D)->isInheritingConstructor() &&
781 const auto *FD = cast<FunctionDecl>(GD.
getDecl());
783 if (
const auto *Dtor = dyn_cast_or_null<CXXDestructorDecl>(FD)) {
786 F->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass);
791 if (FD->hasAttr<DLLImportAttr>())
792 F->setDLLStorageClass(llvm::GlobalVariable::DLLImportStorageClass);
793 else if (FD->hasAttr<DLLExportAttr>())
794 F->setDLLStorageClass(llvm::GlobalVariable::DLLExportStorageClass);
796 F->setDLLStorageClass(llvm::GlobalVariable::DefaultStorageClass);
800 llvm::MDString *MDS = dyn_cast<llvm::MDString>(MD);
801 if (!MDS)
return nullptr;
804 llvm::MD5::MD5Result result;
805 md5.update(MDS->getString());
808 for (
int i = 0; i < 8; ++i)
809 id |= static_cast<uint64_t>(result[i]) << (i * 8);
810 return llvm::ConstantInt::get(
Int64Ty,
id);
815 setNonAliasAttributes(D, F);
825 F->setAttributes(llvm::AttributeSet::get(
getLLVMContext(), AttributeList));
826 F->setCallingConv(static_cast<llvm::CallingConv::ID>(CallingConv));
836 if (!LangOpts.Exceptions)
return false;
839 if (LangOpts.CXXExceptions)
return true;
842 if (LangOpts.ObjCExceptions) {
853 if (CodeGenOpts.UnwindTables)
854 B.addAttribute(llvm::Attribute::UWTable);
857 B.addAttribute(llvm::Attribute::NoUnwind);
860 B.addAttribute(llvm::Attribute::StackProtect);
862 B.addAttribute(llvm::Attribute::StackProtectStrong);
864 B.addAttribute(llvm::Attribute::StackProtectReq);
867 F->addAttributes(llvm::AttributeSet::FunctionIndex,
868 llvm::AttributeSet::get(
870 llvm::AttributeSet::FunctionIndex, B));
874 if (D->hasAttr<NakedAttr>()) {
876 B.addAttribute(llvm::Attribute::Naked);
877 B.addAttribute(llvm::Attribute::NoInline);
878 }
else if (D->hasAttr<NoDuplicateAttr>()) {
879 B.addAttribute(llvm::Attribute::NoDuplicate);
880 }
else if (D->hasAttr<NoInlineAttr>()) {
881 B.addAttribute(llvm::Attribute::NoInline);
882 }
else if (D->hasAttr<AlwaysInlineAttr>() &&
883 !F->getAttributes().hasAttribute(llvm::AttributeSet::FunctionIndex,
884 llvm::Attribute::NoInline)) {
886 B.addAttribute(llvm::Attribute::AlwaysInline);
889 if (D->hasAttr<ColdAttr>()) {
890 if (!D->hasAttr<OptimizeNoneAttr>())
891 B.addAttribute(llvm::Attribute::OptimizeForSize);
892 B.addAttribute(llvm::Attribute::Cold);
895 if (D->hasAttr<MinSizeAttr>())
896 B.addAttribute(llvm::Attribute::MinSize);
898 F->addAttributes(llvm::AttributeSet::FunctionIndex,
899 llvm::AttributeSet::get(
900 F->getContext(), llvm::AttributeSet::FunctionIndex, B));
902 if (D->hasAttr<OptimizeNoneAttr>()) {
904 F->addFnAttr(llvm::Attribute::OptimizeNone);
905 F->addFnAttr(llvm::Attribute::NoInline);
908 F->removeFnAttr(llvm::Attribute::OptimizeForSize);
909 F->removeFnAttr(llvm::Attribute::MinSize);
910 assert(!F->hasFnAttribute(llvm::Attribute::AlwaysInline) &&
911 "OptimizeNone and AlwaysInline on same function!");
915 F->removeFnAttr(llvm::Attribute::InlineHint);
918 unsigned alignment = D->getMaxAlignment() / Context.
getCharWidth();
920 F->setAlignment(alignment);
927 if (F->getAlignment() < 2 && isa<CXXMethodDecl>(D))
933 llvm::GlobalValue *GV) {
934 if (
const auto *ND = dyn_cast_or_null<NamedDecl>(D))
939 if (D && D->hasAttr<UsedAttr>())
944 llvm::GlobalValue *GV) {
949 if (D->hasAttr<DLLExportAttr>())
950 GV->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass);
953 void CodeGenModule::setNonAliasAttributes(
const Decl *D,
954 llvm::GlobalObject *GO) {
958 if (
const SectionAttr *SA = D->getAttr<SectionAttr>())
959 GO->setSection(SA->getName());
972 setNonAliasAttributes(D, F);
982 if (ND->hasAttr<DLLImportAttr>()) {
984 GV->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
985 }
else if (ND->hasAttr<DLLExportAttr>()) {
987 GV->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass);
988 }
else if (ND->hasAttr<WeakAttr>() || ND->isWeakImported()) {
991 GV->setLinkage(llvm::GlobalValue::ExternalWeakLinkage);
1001 llvm::Function *F) {
1003 if (!LangOpts.
Sanitize.
has(SanitizerKind::CFIICall))
1007 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic())
1011 if (CodeGenOpts.SanitizeCfiCrossDso) {
1023 F->addTypeMetadata(0, MD);
1026 if (CodeGenOpts.SanitizeCfiCrossDso)
1028 F->addTypeMetadata(0, llvm::ConstantAsMetadata::get(CrossDsoTypeId));
1031 void CodeGenModule::SetFunctionAttributes(
GlobalDecl GD, llvm::Function *F,
1032 bool IsIncompleteFunction,
1037 F->setAttributes(llvm::Intrinsic::getAttributes(
getLLVMContext(), IID));
1041 const auto *FD = cast<FunctionDecl>(GD.
getDecl());
1043 if (!IsIncompleteFunction)
1049 if (!IsThunk &&
getCXXABI().HasThisReturn(GD) &&
1052 assert(!F->arg_empty() &&
1053 F->arg_begin()->getType()
1054 ->canLosslesslyBitCastTo(F->getReturnType()) &&
1055 "unexpected this return");
1056 F->addAttribute(1, llvm::Attribute::Returned);
1064 if (
const SectionAttr *SA = FD->getAttr<SectionAttr>())
1065 F->setSection(SA->getName());
1067 if (FD->isReplaceableGlobalAllocationFunction()) {
1070 F->addAttribute(llvm::AttributeSet::FunctionIndex,
1071 llvm::Attribute::NoBuiltin);
1076 auto Kind = FD->getDeclName().getCXXOverloadedOperator();
1078 (
Kind == OO_New ||
Kind == OO_Array_New))
1079 F->addAttribute(llvm::AttributeSet::ReturnIndex,
1080 llvm::Attribute::NoAlias);
1083 if (isa<CXXConstructorDecl>(FD) || isa<CXXDestructorDecl>(FD))
1084 F->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
1085 else if (
const auto *MD = dyn_cast<CXXMethodDecl>(FD))
1086 if (MD->isVirtual())
1087 F->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
1093 assert(!GV->isDeclaration() &&
1094 "Only globals with definition can force usage.");
1095 LLVMUsed.emplace_back(GV);
1099 assert(!GV->isDeclaration() &&
1100 "Only globals with definition can force usage.");
1101 LLVMCompilerUsed.emplace_back(GV);
1105 std::vector<llvm::WeakVH> &List) {
1112 UsedArray.resize(List.size());
1113 for (
unsigned i = 0, e = List.size(); i != e; ++i) {
1115 llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(
1116 cast<llvm::Constant>(&*List[i]), CGM.
Int8PtrTy);
1119 if (UsedArray.empty())
1121 llvm::ArrayType *ATy = llvm::ArrayType::get(CGM.
Int8PtrTy, UsedArray.size());
1123 auto *GV =
new llvm::GlobalVariable(
1124 CGM.
getModule(), ATy,
false, llvm::GlobalValue::AppendingLinkage,
1125 llvm::ConstantArray::get(ATy, UsedArray),
Name);
1127 GV->setSection(
"llvm.metadata");
1130 void CodeGenModule::emitLLVMUsed() {
1131 emitUsed(*
this,
"llvm.used", LLVMUsed);
1132 emitUsed(*
this,
"llvm.compiler.used", LLVMCompilerUsed);
1137 LinkerOptionsMetadata.push_back(llvm::MDNode::get(
getLLVMContext(), MDOpts));
1144 LinkerOptionsMetadata.push_back(llvm::MDNode::get(
getLLVMContext(), MDOpts));
1151 LinkerOptionsMetadata.push_back(llvm::MDNode::get(
getLLVMContext(), MDOpts));
1158 llvm::SmallPtrSet<Module *, 16> &Visited) {
1160 if (Mod->
Parent && Visited.insert(Mod->
Parent).second) {
1165 for (
unsigned I = Mod->
Imports.size();
I > 0; --
I) {
1166 if (Visited.insert(Mod->
Imports[
I - 1]).second)
1177 llvm::Metadata *Args[2] = {
1178 llvm::MDString::get(Context,
"-framework"),
1179 llvm::MDString::get(Context, Mod->
LinkLibraries[
I - 1].Library)};
1181 Metadata.push_back(llvm::MDNode::get(Context, Args));
1189 auto *OptString = llvm::MDString::get(Context, Opt);
1190 Metadata.push_back(llvm::MDNode::get(Context, OptString));
1194 void CodeGenModule::EmitModuleLinkOptions() {
1198 llvm::SetVector<clang::Module *> LinkModules;
1199 llvm::SmallPtrSet<clang::Module *, 16> Visited;
1203 for (
Module *M : ImportedModules)
1204 if (Visited.insert(M).second)
1209 while (!Stack.empty()) {
1212 bool AnyChildren =
false;
1217 Sub != SubEnd; ++Sub) {
1220 if ((*Sub)->IsExplicit)
1223 if (Visited.insert(*Sub).second) {
1224 Stack.push_back(*Sub);
1232 LinkModules.insert(Mod);
1241 for (
Module *M : LinkModules)
1242 if (Visited.insert(M).second)
1244 std::reverse(MetadataArgs.begin(), MetadataArgs.end());
1245 LinkerOptionsMetadata.append(MetadataArgs.begin(), MetadataArgs.end());
1248 getModule().addModuleFlag(llvm::Module::AppendUnique,
"Linker Options",
1250 LinkerOptionsMetadata));
1253 void CodeGenModule::EmitDeferred() {
1258 if (!DeferredVTables.empty()) {
1259 EmitDeferredVTables();
1264 assert(DeferredVTables.empty());
1268 if (DeferredDeclsToEmit.empty())
1273 std::vector<DeferredGlobal> CurDeclsToEmit;
1274 CurDeclsToEmit.swap(DeferredDeclsToEmit);
1276 for (DeferredGlobal &G : CurDeclsToEmit) {
1284 llvm::GlobalValue *GV = dyn_cast<llvm::GlobalValue>(
1302 if (!GV->isDeclaration())
1306 EmitGlobalDefinition(D, GV);
1311 if (!DeferredVTables.empty() || !DeferredDeclsToEmit.empty()) {
1313 assert(DeferredVTables.empty() && DeferredDeclsToEmit.empty());
1319 if (Annotations.empty())
1323 llvm::Constant *Array = llvm::ConstantArray::get(llvm::ArrayType::get(
1324 Annotations[0]->getType(), Annotations.size()), Annotations);
1325 auto *gv =
new llvm::GlobalVariable(
getModule(), Array->getType(),
false,
1326 llvm::GlobalValue::AppendingLinkage,
1327 Array,
"llvm.global.annotations");
1332 llvm::Constant *&AStr = AnnotationStrings[Str];
1337 llvm::Constant *s = llvm::ConstantDataArray::getString(
getLLVMContext(), Str);
1339 new llvm::GlobalVariable(
getModule(), s->getType(),
true,
1340 llvm::GlobalValue::PrivateLinkage, s,
".str");
1342 gv->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
1360 return llvm::ConstantInt::get(
Int32Ty, LineNo);
1364 const AnnotateAttr *AA,
1372 llvm::Constant *Fields[4] = {
1373 llvm::ConstantExpr::getBitCast(GV,
Int8PtrTy),
1374 llvm::ConstantExpr::getBitCast(AnnoGV,
Int8PtrTy),
1375 llvm::ConstantExpr::getBitCast(UnitGV,
Int8PtrTy),
1378 return llvm::ConstantStruct::getAnon(Fields);
1382 llvm::GlobalValue *GV) {
1383 assert(D->hasAttr<AnnotateAttr>() &&
"no annotate attribute");
1385 for (
const auto *
I : D->specific_attrs<AnnotateAttr>())
1393 if (SanitizerBL.isBlacklistedFunction(Fn->getName()))
1402 return SanitizerBL.isBlacklistedFile(MainFile->getName());
1412 SanitizerKind::Address | SanitizerKind::KernelAddress))
1415 if (SanitizerBL.isBlacklistedGlobal(GV->getName(),
Category))
1417 if (SanitizerBL.isBlacklistedLocation(Loc, Category))
1423 while (
auto AT = dyn_cast<ArrayType>(Ty.
getTypePtr()))
1424 Ty = AT->getElementType();
1429 if (SanitizerBL.isBlacklistedType(TypeStr, Category))
1436 bool CodeGenModule::MustBeEmitted(
const ValueDecl *Global) {
1438 if (LangOpts.EmitAllDecls)
1444 bool CodeGenModule::MayBeEmittedEagerly(
const ValueDecl *Global) {
1445 if (
const auto *FD = dyn_cast<FunctionDecl>(Global))
1450 if (
const auto *VD = dyn_cast<VarDecl>(Global))
1458 if (LangOpts.OpenMP && LangOpts.OpenMPUseTLS &&
1470 std::string
Name =
"_GUID_" + Uuid.lower();
1471 std::replace(Name.begin(), Name.end(),
'-',
'_');
1477 if (llvm::GlobalVariable *GV =
getModule().getNamedGlobal(Name))
1480 llvm::Constant *Init = EmitUuidofInitializer(Uuid);
1481 assert(Init &&
"failed to initialize as constant");
1483 auto *GV =
new llvm::GlobalVariable(
1485 true, llvm::GlobalValue::LinkOnceODRLinkage, Init,
Name);
1487 GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
1492 const AliasAttr *AA = VD->getAttr<AliasAttr>();
1493 assert(AA &&
"No alias?");
1502 auto Ptr = llvm::ConstantExpr::getBitCast(Entry, DeclTy->getPointerTo(AS));
1506 llvm::Constant *Aliasee;
1507 if (isa<llvm::FunctionType>(DeclTy))
1508 Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy,
1512 Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(),
1513 llvm::PointerType::getUnqual(DeclTy),
1516 auto *F = cast<llvm::GlobalValue>(Aliasee);
1517 F->setLinkage(llvm::Function::ExternalWeakLinkage);
1518 WeakRefReferences.insert(F);
1524 const auto *Global = cast<ValueDecl>(GD.
getDecl());
1527 if (Global->hasAttr<WeakRefAttr>())
1532 if (Global->hasAttr<AliasAttr>())
1533 return EmitAliasDefinition(GD);
1536 if (Global->hasAttr<IFuncAttr>())
1537 return emitIFuncDefinition(GD);
1540 if (LangOpts.CUDA) {
1541 if (LangOpts.CUDAIsDevice) {
1542 if (!Global->hasAttr<CUDADeviceAttr>() &&
1543 !Global->hasAttr<CUDAGlobalAttr>() &&
1544 !Global->hasAttr<CUDAConstantAttr>() &&
1545 !Global->hasAttr<CUDASharedAttr>())
1554 if (isa<FunctionDecl>(Global) && !Global->hasAttr<CUDAHostAttr>() &&
1555 Global->hasAttr<CUDADeviceAttr>())
1558 assert((isa<FunctionDecl>(Global) || isa<VarDecl>(Global)) &&
1559 "Expected Variable or Function");
1563 if (LangOpts.OpenMP) {
1566 if (OpenMPRuntime && OpenMPRuntime->emitTargetGlobal(GD))
1568 if (
auto *DRD = dyn_cast<OMPDeclareReductionDecl>(Global)) {
1569 if (MustBeEmitted(Global))
1576 if (
const auto *FD = dyn_cast<FunctionDecl>(Global)) {
1578 if (!FD->doesThisDeclarationHaveABody()) {
1579 if (!FD->doesDeclarationForceExternallyVisibleDefinition())
1588 GetOrCreateLLVMFunction(MangledName, Ty, GD,
false,
1593 const auto *VD = cast<VarDecl>(Global);
1594 assert(VD->isFileVarDecl() &&
"Cannot emit local var decl as global.");
1598 bool MustEmitForCuda = LangOpts.CUDA && !LangOpts.CUDAIsDevice &&
1599 !VD->hasDefinition() &&
1600 (VD->hasAttr<CUDAConstantAttr>() ||
1601 VD->hasAttr<CUDADeviceAttr>());
1602 if (!MustEmitForCuda &&
1617 if (MustBeEmitted(Global) && MayBeEmittedEagerly(Global)) {
1619 EmitGlobalDefinition(GD);
1626 cast<VarDecl>(Global)->hasInit()) {
1627 DelayedCXXInitPosition[Global] = CXXGlobalInits.size();
1628 CXXGlobalInits.push_back(
nullptr);
1634 addDeferredDeclToEmit(GV, GD);
1635 }
else if (MustBeEmitted(Global)) {
1637 assert(!MayBeEmittedEagerly(Global));
1638 addDeferredDeclToEmit(
nullptr, GD);
1643 DeferredDecls[MangledName] = GD;
1648 struct FunctionIsDirectlyRecursive :
1650 const StringRef
Name;
1662 AsmLabelAttr *
Attr = FD->getAttr<AsmLabelAttr>();
1663 if (Attr &&
Name == Attr->getLabel()) {
1668 if (!BuiltinID || !BI.isLibFunction(BuiltinID))
1670 StringRef BuiltinName = BI.getName(BuiltinID);
1671 if (BuiltinName.startswith(
"__builtin_") &&
1672 Name == BuiltinName.slice(strlen(
"__builtin_"), StringRef::npos)) {
1680 struct DLLImportFunctionVisitor
1682 bool SafeToInline =
true;
1684 bool VisitVarDecl(
VarDecl *VD) {
1687 return SafeToInline;
1693 if (isa<FunctionDecl>(VD))
1694 SafeToInline = VD->hasAttr<DLLImportAttr>();
1695 else if (
VarDecl *V = dyn_cast<VarDecl>(VD))
1696 SafeToInline = !V->hasGlobalStorage() || V->hasAttr<DLLImportAttr>();
1697 return SafeToInline;
1701 return SafeToInline;
1705 return SafeToInline;
1714 CodeGenModule::isTriviallyRecursive(
const FunctionDecl *FD) {
1716 if (
getCXXABI().getMangleContext().shouldMangleDeclName(FD)) {
1718 AsmLabelAttr *Attr = FD->getAttr<AsmLabelAttr>();
1721 Name = Attr->getLabel();
1726 FunctionIsDirectlyRecursive Walker(Name, Context.
BuiltinInfo);
1727 Walker.TraverseFunctionDecl(const_cast<FunctionDecl*>(FD));
1728 return Walker.Result;
1732 CodeGenModule::shouldEmitFunction(
GlobalDecl GD) {
1735 const auto *F = cast<FunctionDecl>(GD.
getDecl());
1736 if (CodeGenOpts.OptimizationLevel == 0 && !F->hasAttr<AlwaysInlineAttr>())
1739 if (F->hasAttr<DLLImportAttr>()) {
1741 DLLImportFunctionVisitor Visitor;
1742 Visitor.TraverseFunctionDecl(const_cast<FunctionDecl*>(F));
1743 if (!Visitor.SafeToInline)
1752 return !isTriviallyRecursive(F);
1760 void CodeGenModule::CompleteDIClassType(
const CXXMethodDecl* D) {
1767 DI->getOrCreateRecordType(ThisPtr->getPointeeType(), D->getLocation());
1771 void CodeGenModule::EmitGlobalDefinition(
GlobalDecl GD, llvm::GlobalValue *GV) {
1772 const auto *D = cast<ValueDecl>(GD.
getDecl());
1776 "Generating code for declaration");
1778 if (isa<FunctionDecl>(D)) {
1781 if (!shouldEmitFunction(GD))
1784 if (
const auto *Method = dyn_cast<CXXMethodDecl>(D)) {
1785 CompleteDIClassType(Method);
1788 if (
const auto *CD = dyn_cast<CXXConstructorDecl>(Method))
1790 else if (
const auto *DD = dyn_cast<CXXDestructorDecl>(Method))
1793 EmitGlobalFunctionDefinition(GD, GV);
1795 if (Method->isVirtual())
1801 return EmitGlobalFunctionDefinition(GD, GV);
1804 if (
const auto *VD = dyn_cast<VarDecl>(D))
1805 return EmitGlobalVarDefinition(VD, !VD->hasDefinition());
1807 llvm_unreachable(
"Invalid argument to EmitGlobalDefinition()");
1811 llvm::Function *NewFn);
1821 CodeGenModule::GetOrCreateLLVMFunction(StringRef MangledName,
1824 bool DontDefer,
bool IsThunk,
1825 llvm::AttributeSet ExtraAttrs,
1826 bool IsForDefinition) {
1832 if (WeakRefReferences.erase(Entry)) {
1833 const FunctionDecl *FD = cast_or_null<FunctionDecl>(D);
1834 if (FD && !FD->hasAttr<WeakAttr>())
1839 if (D && !D->hasAttr<DLLImportAttr>() && !D->hasAttr<DLLExportAttr>())
1840 Entry->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass);
1844 if (IsForDefinition && !Entry->isDeclaration()) {
1851 DiagnosedConflictingDefinitions.insert(GD).second) {
1853 diag::err_duplicate_mangled_name);
1855 diag::note_previous_definition);
1859 if ((isa<llvm::Function>(Entry) || isa<llvm::GlobalAlias>(Entry)) &&
1860 (Entry->getType()->getElementType() == Ty)) {
1867 if (!IsForDefinition)
1868 return llvm::ConstantExpr::getBitCast(Entry, Ty->getPointerTo());
1874 bool IsIncompleteFunction =
false;
1876 llvm::FunctionType *FTy;
1877 if (isa<llvm::FunctionType>(Ty)) {
1878 FTy = cast<llvm::FunctionType>(Ty);
1880 FTy = llvm::FunctionType::get(
VoidTy,
false);
1881 IsIncompleteFunction =
true;
1886 Entry ? StringRef() : MangledName, &
getModule());
1903 if (!Entry->use_empty()) {
1905 Entry->removeDeadConstantUsers();
1908 llvm::Constant *BC = llvm::ConstantExpr::getBitCast(
1909 F, Entry->getType()->getElementType()->getPointerTo());
1913 assert(F->getName() == MangledName &&
"name was uniqued!");
1915 SetFunctionAttributes(GD, F, IsIncompleteFunction, IsThunk);
1916 if (ExtraAttrs.hasAttributes(llvm::AttributeSet::FunctionIndex)) {
1917 llvm::AttrBuilder B(ExtraAttrs, llvm::AttributeSet::FunctionIndex);
1918 F->addAttributes(llvm::AttributeSet::FunctionIndex,
1919 llvm::AttributeSet::get(VMContext,
1920 llvm::AttributeSet::FunctionIndex,
1928 if (D && isa<CXXDestructorDecl>(D) &&
1929 getCXXABI().useThunkForDtorVariant(cast<CXXDestructorDecl>(D),
1931 addDeferredDeclToEmit(F, GD);
1936 auto DDI = DeferredDecls.find(MangledName);
1937 if (DDI != DeferredDecls.end()) {
1941 addDeferredDeclToEmit(F, DDI->second);
1942 DeferredDecls.erase(DDI);
1957 for (
const auto *FD = cast<FunctionDecl>(D)->getMostRecentDecl(); FD;
1959 if (isa<CXXRecordDecl>(FD->getLexicalDeclContext())) {
1970 if (!IsIncompleteFunction) {
1971 assert(F->getType()->getElementType() == Ty);
1975 llvm::Type *PTy = llvm::PointerType::getUnqual(Ty);
1976 return llvm::ConstantExpr::getBitCast(F, PTy);
1986 bool IsForDefinition) {
1989 const auto *FD = cast<FunctionDecl>(GD.
getDecl());
1995 return GetOrCreateLLVMFunction(MangledName, Ty, GD, ForVTable, DontDefer,
1996 false, llvm::AttributeSet(),
2005 llvm::AttributeSet ExtraAttrs) {
2007 GetOrCreateLLVMFunction(Name, FTy,
GlobalDecl(),
false,
2008 false,
false, ExtraAttrs);
2009 if (
auto *F = dyn_cast<llvm::Function>(C))
2020 llvm::AttributeSet ExtraAttrs) {
2022 GetOrCreateLLVMFunction(Name, FTy,
GlobalDecl(),
false,
2023 false,
false, ExtraAttrs);
2024 if (
auto *F = dyn_cast<llvm::Function>(C))
2043 return ExcludeCtor && !Record->hasMutableFields() &&
2044 Record->hasTrivialDestructor();
2062 CodeGenModule::GetOrCreateLLVMGlobal(StringRef MangledName,
2063 llvm::PointerType *Ty,
2065 bool IsForDefinition) {
2069 if (WeakRefReferences.erase(Entry)) {
2070 if (D && !D->hasAttr<WeakAttr>())
2075 if (D && !D->hasAttr<DLLImportAttr>() && !D->hasAttr<DLLExportAttr>())
2076 Entry->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass);
2078 if (Entry->getType() == Ty)
2083 if (IsForDefinition && !Entry->isDeclaration()) {
2091 (OtherD = dyn_cast<VarDecl>(OtherGD.
getDecl())) &&
2093 DiagnosedConflictingDefinitions.insert(D).second) {
2095 diag::err_duplicate_mangled_name);
2097 diag::note_previous_definition);
2102 if (Entry->getType()->getAddressSpace() != Ty->getAddressSpace())
2103 return llvm::ConstantExpr::getAddrSpaceCast(Entry, Ty);
2107 if (!IsForDefinition)
2108 return llvm::ConstantExpr::getBitCast(Entry, Ty);
2112 auto *GV =
new llvm::GlobalVariable(
2113 getModule(), Ty->getElementType(),
false,
2115 llvm::GlobalVariable::NotThreadLocal, AddrSpace);
2120 GV->takeName(Entry);
2122 if (!Entry->use_empty()) {
2123 llvm::Constant *NewPtrForOldDecl =
2124 llvm::ConstantExpr::getBitCast(GV, Entry->getType());
2125 Entry->replaceAllUsesWith(NewPtrForOldDecl);
2128 Entry->eraseFromParent();
2134 auto DDI = DeferredDecls.find(MangledName);
2135 if (DDI != DeferredDecls.end()) {
2138 addDeferredDeclToEmit(GV, DDI->second);
2139 DeferredDecls.erase(DDI);
2148 GV->setAlignment(
getContext().getDeclAlign(D).getQuantity());
2154 CXXThreadLocals.push_back(D);
2160 if (
getContext().isMSStaticDataMemberInlineDefinition(D)) {
2161 EmitGlobalVarDefinition(D);
2169 GV->setSection(
".cp.rodata");
2172 if (AddrSpace != Ty->getAddressSpace())
2173 return llvm::ConstantExpr::getAddrSpaceCast(GV, Ty);
2180 bool IsForDefinition) {
2181 if (isa<CXXConstructorDecl>(GD.
getDecl()))
2185 false, IsForDefinition);
2186 else if (isa<CXXDestructorDecl>(GD.
getDecl()))
2190 false, IsForDefinition);
2191 else if (isa<CXXMethodDecl>(GD.
getDecl())) {
2193 cast<CXXMethodDecl>(GD.
getDecl()));
2197 }
else if (isa<FunctionDecl>(GD.
getDecl())) {
2207 llvm::GlobalVariable *
2210 llvm::GlobalValue::LinkageTypes
Linkage) {
2211 llvm::GlobalVariable *GV =
getModule().getNamedGlobal(Name);
2212 llvm::GlobalVariable *OldGV =
nullptr;
2216 if (GV->getType()->getElementType() == Ty)
2221 assert(GV->isDeclaration() &&
"Declaration has wrong type!");
2226 GV =
new llvm::GlobalVariable(
getModule(), Ty,
true,
2227 Linkage,
nullptr, Name);
2231 GV->takeName(OldGV);
2233 if (!OldGV->use_empty()) {
2234 llvm::Constant *NewPtrForOldDecl =
2235 llvm::ConstantExpr::getBitCast(GV, OldGV->getType());
2236 OldGV->replaceAllUsesWith(NewPtrForOldDecl);
2239 OldGV->eraseFromParent();
2243 !GV->hasAvailableExternallyLinkage())
2244 GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
2257 bool IsForDefinition) {
2263 llvm::PointerType *PTy =
2264 llvm::PointerType::get(Ty,
getContext().getTargetAddressSpace(ASTTy));
2267 return GetOrCreateLLVMGlobal(MangledName, PTy, D, IsForDefinition);
2275 return GetOrCreateLLVMGlobal(Name, llvm::PointerType::getUnqual(Ty),
nullptr);
2279 assert(!D->
getInit() &&
"Cannot emit definite definitions here!");
2287 if (GV && !GV->isDeclaration())
2292 if (!MustBeEmitted(D) && !GV) {
2293 DeferredDecls[MangledName] = D;
2298 EmitGlobalVarDefinition(D);
2307 unsigned AddrSpace) {
2308 if (D && LangOpts.CUDA && LangOpts.CUDAIsDevice) {
2309 if (D->hasAttr<CUDAConstantAttr>())
2311 else if (D->hasAttr<CUDASharedAttr>())
2320 template<
typename SomeDecl>
2322 llvm::GlobalValue *GV) {
2328 if (!D->template hasAttr<UsedAttr>())
2337 const SomeDecl *First = D->getFirstDecl();
2338 if (First->getDeclContext()->isRecord() || !First->isInExternCContext())
2344 std::pair<StaticExternCMap::iterator, bool> R =
2345 StaticExternCValues.insert(std::make_pair(D->getIdentifier(), GV));
2350 R.first->second =
nullptr;
2357 if (D.hasAttr<SelectAnyAttr>())
2361 if (
auto *VD = dyn_cast<VarDecl>(&D))
2375 llvm_unreachable(
"No such linkage");
2379 llvm::GlobalObject &GO) {
2382 GO.setComdat(TheModule.getOrInsertComdat(GO.getName()));
2386 void CodeGenModule::EmitGlobalVarDefinition(
const VarDecl *D,
2388 llvm::Constant *Init =
nullptr;
2391 bool NeedsGlobalCtor =
false;
2401 D->hasAttr<CUDASharedAttr>())
2402 Init = llvm::UndefValue::get(
getTypes().ConvertType(ASTTy));
2403 else if (!InitExpr) {
2426 NeedsGlobalCtor =
true;
2429 Init = llvm::UndefValue::get(
getTypes().ConvertType(T));
2436 DelayedCXXInitPosition.erase(D);
2441 llvm::Constant *Entry =
2445 if (
auto *CE = dyn_cast<llvm::ConstantExpr>(Entry)) {
2446 assert(CE->getOpcode() == llvm::Instruction::BitCast ||
2447 CE->getOpcode() == llvm::Instruction::AddrSpaceCast ||
2449 CE->getOpcode() == llvm::Instruction::GetElementPtr);
2450 Entry = CE->getOperand(0);
2454 auto *GV = dyn_cast<llvm::GlobalVariable>(Entry);
2466 GV->getType()->getElementType() != InitType ||
2467 GV->getType()->getAddressSpace() !=
2471 Entry->setName(StringRef());
2474 GV = cast<llvm::GlobalVariable>(
2478 llvm::Constant *NewPtrForOldDecl =
2479 llvm::ConstantExpr::getBitCast(GV, Entry->getType());
2480 Entry->replaceAllUsesWith(NewPtrForOldDecl);
2483 cast<llvm::GlobalValue>(Entry)->eraseFromParent();
2488 if (D->hasAttr<AnnotateAttr>())
2492 llvm::GlobalValue::LinkageTypes
Linkage =
2502 if (GV && LangOpts.CUDA) {
2503 if (LangOpts.CUDAIsDevice) {
2504 if (D->hasAttr<CUDADeviceAttr>() || D->hasAttr<CUDAConstantAttr>())
2505 GV->setExternallyInitialized(
true);
2511 if (D->hasAttr<CUDADeviceAttr>() || D->hasAttr<CUDAConstantAttr>()) {
2519 if (D->hasAttr<CUDAConstantAttr>())
2522 }
else if (D->hasAttr<CUDASharedAttr>())
2531 GV->setInitializer(Init);
2534 GV->setConstant(!NeedsGlobalCtor && !NeedsGlobalDtor &&
2538 if (
const SectionAttr *SA = D->getAttr<SectionAttr>()) {
2541 GV->setConstant(
true);
2544 GV->setAlignment(
getContext().getDeclAlign(D).getQuantity());
2556 !llvm::GlobalVariable::isLinkOnceLinkage(Linkage) &&
2557 !llvm::GlobalVariable::isWeakLinkage(Linkage))
2560 GV->setLinkage(Linkage);
2561 if (D->hasAttr<DLLImportAttr>())
2562 GV->setDLLStorageClass(llvm::GlobalVariable::DLLImportStorageClass);
2563 else if (D->hasAttr<DLLExportAttr>())
2564 GV->setDLLStorageClass(llvm::GlobalVariable::DLLExportStorageClass);
2566 GV->setDLLStorageClass(llvm::GlobalVariable::DefaultStorageClass);
2568 if (Linkage == llvm::GlobalVariable::CommonLinkage)
2570 GV->setConstant(
false);
2572 setNonAliasAttributes(D, GV);
2574 if (D->
getTLSKind() && !GV->isThreadLocal()) {
2576 CXXThreadLocals.push_back(D);
2583 if (NeedsGlobalCtor || NeedsGlobalDtor)
2584 EmitCXXGlobalVarDeclInitFunc(D, GV, NeedsGlobalCtor);
2586 SanitizerMD->reportGlobalToASan(GV, *D, NeedsGlobalCtor);
2591 DI->EmitGlobalVariable(GV, D);
2599 if ((NoCommon || D->hasAttr<NoCommonAttr>()) && !D->hasAttr<CommonAttr>())
2610 if (D->hasAttr<SectionAttr>())
2618 if (D->hasAttr<WeakImportAttr>())
2628 if (D->hasAttr<AlignedAttr>())
2637 if (FD->isBitField())
2639 if (FD->hasAttr<AlignedAttr>())
2655 if (D->hasAttr<WeakAttr>()) {
2656 if (IsConstantVariable)
2657 return llvm::GlobalVariable::WeakODRLinkage;
2659 return llvm::GlobalVariable::WeakAnyLinkage;
2665 return llvm::Function::AvailableExternallyLinkage;
2679 return !Context.
getLangOpts().AppleKext ? llvm::Function::LinkOnceODRLinkage
2696 return llvm::Function::WeakODRLinkage;
2701 if (!
getLangOpts().CPlusPlus && isa<VarDecl>(D) &&
2703 CodeGenOpts.NoCommon))
2704 return llvm::GlobalVariable::CommonLinkage;
2710 if (D->hasAttr<SelectAnyAttr>())
2711 return llvm::GlobalVariable::WeakODRLinkage;
2719 const VarDecl *VD,
bool IsConstant) {
2727 llvm::Function *newFn) {
2729 if (old->use_empty())
return;
2731 llvm::Type *newRetTy = newFn->getReturnType();
2735 for (llvm::Value::use_iterator ui = old->use_begin(), ue = old->use_end();
2737 llvm::Value::use_iterator use = ui++;
2738 llvm::User *user = use->getUser();
2742 if (
auto *bitcast = dyn_cast<llvm::ConstantExpr>(user)) {
2743 if (bitcast->getOpcode() == llvm::Instruction::BitCast)
2749 llvm::CallSite callSite(user);
2750 if (!callSite)
continue;
2751 if (!callSite.isCallee(&*use))
continue;
2755 if (callSite->getType() != newRetTy && !callSite->use_empty())
2760 llvm::AttributeSet oldAttrs = callSite.getAttributes();
2763 if (oldAttrs.hasAttributes(llvm::AttributeSet::ReturnIndex))
2765 llvm::AttributeSet::get(newFn->getContext(),
2766 oldAttrs.getRetAttributes()));
2769 unsigned newNumArgs = newFn->arg_size();
2770 if (callSite.arg_size() < newNumArgs)
continue;
2775 bool dontTransform =
false;
2776 for (llvm::Function::arg_iterator ai = newFn->arg_begin(),
2777 ae = newFn->arg_end(); ai != ae; ++ai, ++argNo) {
2778 if (callSite.getArgument(argNo)->getType() != ai->getType()) {
2779 dontTransform =
true;
2784 if (oldAttrs.hasAttributes(argNo + 1))
2787 AttributeSet::get(newFn->getContext(),
2788 oldAttrs.getParamAttributes(argNo + 1)));
2793 if (oldAttrs.hasAttributes(llvm::AttributeSet::FunctionIndex))
2794 newAttrs.push_back(llvm::AttributeSet::get(newFn->getContext(),
2795 oldAttrs.getFnAttributes()));
2799 newArgs.append(callSite.arg_begin(), callSite.arg_begin() + argNo);
2802 callSite.getOperandBundlesAsDefs(newBundles);
2804 llvm::CallSite newCall;
2805 if (callSite.isCall()) {
2807 callSite.getInstruction());
2809 auto *oldInvoke = cast<llvm::InvokeInst>(callSite.getInstruction());
2811 oldInvoke->getNormalDest(),
2812 oldInvoke->getUnwindDest(),
2813 newArgs, newBundles,
"",
2814 callSite.getInstruction());
2818 if (!newCall->getType()->isVoidTy())
2819 newCall->takeName(callSite.getInstruction());
2820 newCall.setAttributes(
2821 llvm::AttributeSet::get(newFn->getContext(), newAttrs));
2822 newCall.setCallingConv(callSite.getCallingConv());
2825 if (!callSite->use_empty())
2826 callSite->replaceAllUsesWith(newCall.getInstruction());
2829 if (callSite->getDebugLoc())
2830 newCall->setDebugLoc(callSite->getDebugLoc());
2832 callSite->eraseFromParent();
2846 llvm::Function *NewFn) {
2848 if (!isa<llvm::Function>(Old))
return;
2867 void CodeGenModule::EmitGlobalFunctionDefinition(
GlobalDecl GD,
2868 llvm::GlobalValue *GV) {
2869 const auto *D = cast<FunctionDecl>(GD.
getDecl());
2876 if (!GV || (GV->getType()->getElementType() != Ty))
2882 if (!GV->isDeclaration())
2889 auto *Fn = cast<llvm::Function>(GV);
2905 if (
const ConstructorAttr *CA = D->getAttr<ConstructorAttr>())
2906 AddGlobalCtor(Fn, CA->getPriority());
2907 if (
const DestructorAttr *DA = D->getAttr<DestructorAttr>())
2908 AddGlobalDtor(Fn, DA->getPriority());
2909 if (D->hasAttr<AnnotateAttr>())
2913 void CodeGenModule::EmitAliasDefinition(
GlobalDecl GD) {
2914 const auto *D = cast<ValueDecl>(GD.
getDecl());
2915 const AliasAttr *AA = D->getAttr<AliasAttr>();
2916 assert(AA &&
"Not an alias?");
2920 if (AA->getAliasee() == MangledName) {
2921 Diags.
Report(AA->getLocation(), diag::err_cyclic_alias) << 0;
2928 if (Entry && !Entry->isDeclaration())
2931 Aliases.push_back(GD);
2937 llvm::Constant *Aliasee;
2938 if (isa<llvm::FunctionType>(DeclTy))
2939 Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy, GD,
2942 Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(),
2943 llvm::PointerType::getUnqual(DeclTy),
2951 if (GA->getAliasee() == Entry) {
2952 Diags.
Report(AA->getLocation(), diag::err_cyclic_alias) << 0;
2956 assert(Entry->isDeclaration());
2965 GA->takeName(Entry);
2967 Entry->replaceAllUsesWith(llvm::ConstantExpr::getBitCast(GA,
2969 Entry->eraseFromParent();
2971 GA->setName(MangledName);
2977 if (D->hasAttr<WeakAttr>() || D->hasAttr<WeakRefAttr>() ||
2978 D->isWeakImported()) {
2979 GA->setLinkage(llvm::Function::WeakAnyLinkage);
2982 if (
const auto *VD = dyn_cast<VarDecl>(D))
2983 if (VD->getTLSKind())
2989 void CodeGenModule::emitIFuncDefinition(
GlobalDecl GD) {
2990 const auto *D = cast<ValueDecl>(GD.
getDecl());
2991 const IFuncAttr *IFA = D->getAttr<IFuncAttr>();
2992 assert(IFA &&
"Not an ifunc?");
2996 if (IFA->getResolver() == MangledName) {
2997 Diags.
Report(IFA->getLocation(), diag::err_cyclic_alias) << 1;
3003 if (Entry && !Entry->isDeclaration()) {
3006 DiagnosedConflictingDefinitions.insert(GD).second) {
3007 Diags.
Report(D->getLocation(), diag::err_duplicate_mangled_name);
3009 diag::note_previous_definition);
3014 Aliases.push_back(GD);
3017 llvm::Constant *Resolver =
3018 GetOrCreateLLVMFunction(IFA->getResolver(), DeclTy, GD,
3020 llvm::GlobalIFunc *GIF =
3024 if (GIF->getResolver() == Entry) {
3025 Diags.
Report(IFA->getLocation(), diag::err_cyclic_alias) << 1;
3028 assert(Entry->isDeclaration());
3037 GIF->takeName(Entry);
3039 Entry->replaceAllUsesWith(llvm::ConstantExpr::getBitCast(GIF,
3041 Entry->eraseFromParent();
3043 GIF->setName(MangledName);
3054 static llvm::StringMapEntry<llvm::GlobalVariable *> &
3057 bool &IsUTF16,
unsigned &StringLength) {
3058 StringRef String = Literal->
getString();
3059 unsigned NumBytes = String.size();
3063 StringLength = NumBytes;
3064 return *Map.insert(std::make_pair(String,
nullptr)).first;
3071 const UTF8 *FromPtr = (
const UTF8 *)String.data();
3072 UTF16 *ToPtr = &ToBuf[0];
3074 (void)ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes,
3075 &ToPtr, ToPtr + NumBytes,
3079 StringLength = ToPtr - &ToBuf[0];
3083 return *Map.insert(std::make_pair(
3084 StringRef(reinterpret_cast<const char *>(ToBuf.data()),
3085 (StringLength + 1) * 2),
3089 static llvm::StringMapEntry<llvm::GlobalVariable *> &
3092 StringRef String = Literal->
getString();
3093 StringLength = String.size();
3094 return *Map.insert(std::make_pair(String,
nullptr)).first;
3099 unsigned StringLength = 0;
3100 bool isUTF16 =
false;
3101 llvm::StringMapEntry<llvm::GlobalVariable *> &Entry =
3106 if (
auto *C = Entry.second)
3109 llvm::Constant *Zero = llvm::Constant::getNullValue(
Int32Ty);
3110 llvm::Constant *Zeros[] = { Zero, Zero };
3114 if (!CFConstantStringClassRef) {
3116 Ty = llvm::ArrayType::get(Ty, 0);
3117 llvm::Constant *GV =
3124 llvm::GlobalValue *CGV = cast<llvm::GlobalValue>(GV);
3128 if ((VD = dyn_cast<VarDecl>(
Result)))
3131 if (!VD || !VD->hasAttr<DLLExportAttr>()) {
3132 CGV->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
3135 CGV->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass);
3141 V = llvm::ConstantExpr::getGetElementPtr(Ty, GV, Zeros);
3142 CFConstantStringClassRef = V;
3144 V = CFConstantStringClassRef;
3151 llvm::Constant *Fields[4];
3154 Fields[0] = cast<llvm::ConstantExpr>(V);
3158 Fields[1] = isUTF16 ? llvm::ConstantInt::get(Ty, 0x07d0)
3159 : llvm::ConstantInt::get(Ty, 0x07C8);
3162 llvm::Constant *C =
nullptr;
3164 auto Arr = llvm::makeArrayRef(
3165 reinterpret_cast<uint16_t *>(const_cast<char *>(Entry.first().data())),
3166 Entry.first().size() / 2);
3167 C = llvm::ConstantDataArray::get(VMContext, Arr);
3169 C = llvm::ConstantDataArray::getString(VMContext, Entry.first());
3175 new llvm::GlobalVariable(
getModule(), C->getType(),
true,
3176 llvm::GlobalValue::PrivateLinkage, C,
".str");
3177 GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
3189 GV->setSection(isUTF16 ?
"__TEXT,__ustring"
3190 :
"__TEXT,__cstring,cstring_literals");
3194 llvm::ConstantExpr::getGetElementPtr(GV->getValueType(), GV, Zeros);
3198 Fields[2] = llvm::ConstantExpr::getBitCast(Fields[2],
Int8PtrTy);
3202 Fields[3] = llvm::ConstantInt::get(Ty, StringLength);
3207 C = llvm::ConstantStruct::get(STy, Fields);
3208 GV =
new llvm::GlobalVariable(
getModule(), C->getType(),
true,
3209 llvm::GlobalVariable::PrivateLinkage, C,
3210 "_unnamed_cfstring_");
3213 case llvm::Triple::UnknownObjectFormat:
3214 llvm_unreachable(
"unknown file format");
3215 case llvm::Triple::COFF:
3216 case llvm::Triple::ELF:
3217 GV->setSection(
"cfstring");
3219 case llvm::Triple::MachO:
3220 GV->setSection(
"__DATA,__cfstring");
3230 unsigned StringLength = 0;
3231 llvm::StringMapEntry<llvm::GlobalVariable *> &Entry =
3234 if (
auto *C = Entry.second)
3237 llvm::Constant *Zero = llvm::Constant::getNullValue(
Int32Ty);
3238 llvm::Constant *Zeros[] = { Zero, Zero };
3241 if (!ConstantStringClassRef) {
3242 std::string StringClass(
getLangOpts().ObjCConstantStringClass);
3247 StringClass.empty() ?
"OBJC_CLASS_$_NSConstantString"
3248 :
"OBJC_CLASS_$_" + StringClass;
3251 llvm::Type *PTy = llvm::PointerType::getUnqual(Ty);
3252 V = llvm::ConstantExpr::getBitCast(GV, PTy);
3253 ConstantStringClassRef = V;
3256 StringClass.empty() ?
"_NSConstantStringClassReference"
3257 :
"_" + StringClass +
"ClassReference";
3258 llvm::Type *PTy = llvm::ArrayType::get(Ty, 0);
3261 V = llvm::ConstantExpr::getGetElementPtr(PTy, GV, Zeros);
3262 ConstantStringClassRef = V;
3265 V = ConstantStringClassRef;
3267 if (!NSConstantStringType) {
3282 for (
unsigned i = 0; i < 3; ++i) {
3286 FieldTypes[i],
nullptr,
3299 llvm::Constant *Fields[3];
3302 Fields[0] = cast<llvm::ConstantExpr>(V);
3306 llvm::ConstantDataArray::getString(VMContext, Entry.first());
3308 llvm::GlobalValue::LinkageTypes
Linkage;
3310 Linkage = llvm::GlobalValue::PrivateLinkage;
3311 isConstant = !LangOpts.WritableStrings;
3313 auto *GV =
new llvm::GlobalVariable(
getModule(), C->getType(), isConstant,
3315 GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
3321 llvm::ConstantExpr::getGetElementPtr(GV->getValueType(), GV, Zeros);
3325 Fields[2] = llvm::ConstantInt::get(Ty, StringLength);
3329 C = llvm::ConstantStruct::get(NSConstantStringType, Fields);
3330 GV =
new llvm::GlobalVariable(
getModule(), C->getType(),
true,
3331 llvm::GlobalVariable::PrivateLinkage, C,
3332 "_unnamed_nsstring_");
3334 const char *NSStringSection =
"__OBJC,__cstring_object,regular,no_dead_strip";
3335 const char *NSStringNonFragileABISection =
3336 "__DATA,__objc_stringobj,regular,no_dead_strip";
3339 ? NSStringNonFragileABISection
3347 if (ObjCFastEnumerationStateType.
isNull()) {
3359 for (
size_t i = 0; i < 4; ++i) {
3364 FieldTypes[i],
nullptr,
3376 return ObjCFastEnumerationStateType;
3390 Str.resize(CAT->getSize().getZExtValue());
3391 return llvm::ConstantDataArray::getString(VMContext, Str,
false);
3395 llvm::Type *ElemTy = AType->getElementType();
3396 unsigned NumElements = AType->getNumElements();
3399 if (ElemTy->getPrimitiveSizeInBits() == 16) {
3401 Elements.reserve(NumElements);
3403 for(
unsigned i = 0, e = E->
getLength(); i != e; ++i)
3405 Elements.resize(NumElements);
3406 return llvm::ConstantDataArray::get(VMContext, Elements);
3409 assert(ElemTy->getPrimitiveSizeInBits() == 32);
3411 Elements.reserve(NumElements);
3413 for(
unsigned i = 0, e = E->
getLength(); i != e; ++i)
3415 Elements.resize(NumElements);
3416 return llvm::ConstantDataArray::get(VMContext, Elements);
3419 static llvm::GlobalVariable *
3424 unsigned AddrSpace = 0;
3430 auto *GV =
new llvm::GlobalVariable(
3431 M, C->getType(), !CGM.
getLangOpts().WritableStrings, LT, C, GlobalName,
3432 nullptr, llvm::GlobalVariable::NotThreadLocal, AddrSpace);
3434 GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
3435 if (GV->isWeakForLinker()) {
3436 assert(CGM.
supportsCOMDAT() &&
"Only COFF uses weak string literals");
3437 GV->setComdat(M.getOrInsertComdat(GV->getName()));
3451 llvm::GlobalVariable **Entry =
nullptr;
3452 if (!LangOpts.WritableStrings) {
3453 Entry = &ConstantStringMap[C];
3454 if (
auto GV = *Entry) {
3462 StringRef GlobalVariableName;
3463 llvm::GlobalValue::LinkageTypes LT;
3468 if (!LangOpts.WritableStrings &&
3471 llvm::raw_svector_ostream Out(MangledNameBuffer);
3474 LT = llvm::GlobalValue::LinkOnceODRLinkage;
3475 GlobalVariableName = MangledNameBuffer;
3477 LT = llvm::GlobalValue::PrivateLinkage;
3478 GlobalVariableName =
Name;
3485 SanitizerMD->reportGlobalToASan(GV, S->
getStrTokenLoc(0),
"<string literal>",
3504 const std::string &Str,
const char *GlobalName) {
3505 StringRef StrWithNull(Str.c_str(), Str.size() + 1);
3510 llvm::ConstantDataArray::getString(
getLLVMContext(), StrWithNull,
false);
3513 llvm::GlobalVariable **Entry =
nullptr;
3514 if (!LangOpts.WritableStrings) {
3515 Entry = &ConstantStringMap[C];
3516 if (
auto GV = *Entry) {
3517 if (Alignment.getQuantity() > GV->getAlignment())
3518 GV->setAlignment(Alignment.getQuantity());
3525 GlobalName =
".str";
3528 GlobalName, Alignment);
3544 MaterializedType = E->
getType();
3548 if (llvm::Constant *Slot = MaterializedGlobalTemporaryMap[E])
3555 llvm::raw_svector_ostream Out(Name);
3557 VD, E->getManglingNumber(), Out);
3560 if (E->getStorageDuration() ==
SD_Static) {
3574 Value = &EvalResult.
Val;
3576 llvm::Constant *InitialValue =
nullptr;
3577 bool Constant =
false;
3583 Type = InitialValue->getType();
3591 llvm::GlobalValue::LinkageTypes Linkage =
3595 if (VD->isStaticDataMember() && VD->getAnyInitializer(InitVD) &&
3596 isa<CXXRecordDecl>(InitVD->getLexicalDeclContext())) {
3599 Linkage = llvm::GlobalVariable::LinkOnceODRLinkage;
3607 VD,
getContext().getTargetAddressSpace(MaterializedType));
3608 auto *GV =
new llvm::GlobalVariable(
3609 getModule(),
Type, Constant, Linkage, InitialValue, Name.c_str(),
3610 nullptr, llvm::GlobalVariable::NotThreadLocal,
3615 GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
3616 if (VD->getTLSKind())
3618 MaterializedGlobalTemporaryMap[
E] = GV;
3624 void CodeGenModule::EmitObjCPropertyImplementations(
const
3638 const_cast<ObjCImplementationDecl *>(D), PID);
3642 const_cast<ObjCImplementationDecl *>(D), PID);
3651 if (ivar->getType().isDestructedType())
3714 void CodeGenModule::EmitNamespace(
const NamespaceDecl *ND) {
3715 for (
auto *
I : ND->
decls()) {
3716 if (
const auto *VD = dyn_cast<VarDecl>(
I))
3732 for (
auto *
I : LSD->
decls()) {
3735 if (
auto *OID = dyn_cast<ObjCImplDecl>(
I)) {
3736 for (
auto *M : OID->methods())
3746 if (D->getDeclContext() && D->getDeclContext()->isDependentContext())
3749 switch (D->getKind()) {
3750 case Decl::CXXConversion:
3751 case Decl::CXXMethod:
3752 case Decl::Function:
3754 if (cast<FunctionDecl>(D)->getDescribedFunctionTemplate() ||
3755 cast<FunctionDecl>(D)->isLateTemplateParsed())
3766 if (cast<VarDecl>(D)->getDescribedVarTemplate())
3768 case Decl::VarTemplateSpecialization:
3774 case Decl::IndirectField:
3778 case Decl::Namespace:
3779 EmitNamespace(cast<NamespaceDecl>(D));
3781 case Decl::CXXRecord:
3783 for (
auto *
I : cast<CXXRecordDecl>(D)->decls())
3784 if (isa<VarDecl>(
I) || isa<CXXRecordDecl>(
I))
3788 case Decl::UsingShadow:
3789 case Decl::ClassTemplate:
3790 case Decl::VarTemplate:
3791 case Decl::VarTemplatePartialSpecialization:
3792 case Decl::FunctionTemplate:
3793 case Decl::TypeAliasTemplate:
3799 DI->EmitUsingDecl(cast<UsingDecl>(*D));
3801 case Decl::NamespaceAlias:
3803 DI->EmitNamespaceAlias(cast<NamespaceAliasDecl>(*D));
3805 case Decl::UsingDirective:
3807 DI->EmitUsingDirective(cast<UsingDirectiveDecl>(*D));
3809 case Decl::CXXConstructor:
3811 if (cast<FunctionDecl>(D)->getDescribedFunctionTemplate() ||
3812 cast<FunctionDecl>(D)->isLateTemplateParsed())
3817 case Decl::CXXDestructor:
3818 if (cast<FunctionDecl>(D)->isLateTemplateParsed())
3823 case Decl::StaticAssert:
3830 case Decl::ObjCInterface:
3831 case Decl::ObjCCategory:
3834 case Decl::ObjCProtocol: {
3835 auto *Proto = cast<ObjCProtocolDecl>(D);
3836 if (Proto->isThisDeclarationADefinition())
3841 case Decl::ObjCCategoryImpl:
3844 ObjCRuntime->GenerateCategory(cast<ObjCCategoryImplDecl>(D));
3847 case Decl::ObjCImplementation: {
3848 auto *OMD = cast<ObjCImplementationDecl>(D);
3849 EmitObjCPropertyImplementations(OMD);
3850 EmitObjCIvarInitializations(OMD);
3855 DI->getOrCreateInterfaceType(
getContext().getObjCInterfaceType(
3856 OMD->getClassInterface()), OMD->getLocation());
3859 case Decl::ObjCMethod: {
3860 auto *OMD = cast<ObjCMethodDecl>(D);
3866 case Decl::ObjCCompatibleAlias:
3867 ObjCRuntime->RegisterAlias(cast<ObjCCompatibleAliasDecl>(D));
3870 case Decl::PragmaComment: {
3871 const auto *PCD = cast<PragmaCommentDecl>(D);
3872 switch (PCD->getCommentKind()) {
3874 llvm_unreachable(
"unexpected pragma comment kind");
3889 case Decl::PragmaDetectMismatch: {
3890 const auto *PDMD = cast<PragmaDetectMismatchDecl>(D);
3895 case Decl::LinkageSpec:
3896 EmitLinkageSpec(cast<LinkageSpecDecl>(D));
3899 case Decl::FileScopeAsm: {
3901 if (LangOpts.CUDA && LangOpts.CUDAIsDevice)
3904 if (LangOpts.OpenMPIsDevice)
3906 auto *AD = cast<FileScopeAsmDecl>(D);
3907 getModule().appendModuleInlineAsm(AD->getAsmString()->getString());
3911 case Decl::Import: {
3912 auto *Import = cast<ImportDecl>(D);
3915 if (Import->getImportedOwningModule())
3918 DI->EmitImportDecl(*Import);
3920 ImportedModules.insert(Import->getImportedModule());
3924 case Decl::OMPThreadPrivate:
3928 case Decl::ClassTemplateSpecialization: {
3929 const auto *Spec = cast<ClassTemplateSpecializationDecl>(D);
3932 Spec->hasDefinition())
3933 DebugInfo->completeTemplateDefinition(*Spec);
3937 case Decl::OMPDeclareReduction:
3945 assert(isa<TypeDecl>(D) &&
"Unsupported decl kind");
3952 if (!CodeGenOpts.CoverageMapping)
3954 switch (D->getKind()) {
3955 case Decl::CXXConversion:
3956 case Decl::CXXMethod:
3957 case Decl::Function:
3958 case Decl::ObjCMethod:
3959 case Decl::CXXConstructor:
3960 case Decl::CXXDestructor: {
3961 if (!cast<FunctionDecl>(D)->doesThisDeclarationHaveABody())
3963 auto I = DeferredEmptyCoverageMappingDecls.find(D);
3964 if (
I == DeferredEmptyCoverageMappingDecls.end())
3965 DeferredEmptyCoverageMappingDecls[D] =
true;
3975 if (!CodeGenOpts.CoverageMapping)
3977 if (
const auto *Fn = dyn_cast<FunctionDecl>(D)) {
3978 if (Fn->isTemplateInstantiation())
3981 auto I = DeferredEmptyCoverageMappingDecls.find(D);
3982 if (
I == DeferredEmptyCoverageMappingDecls.end())
3983 DeferredEmptyCoverageMappingDecls[D] =
false;
3989 std::vector<const Decl *> DeferredDecls;
3990 for (
const auto &
I : DeferredEmptyCoverageMappingDecls) {
3993 DeferredDecls.push_back(
I.first);
3997 if (CodeGenOpts.DumpCoverageMapping)
3998 std::sort(DeferredDecls.begin(), DeferredDecls.end(),
3999 [] (
const Decl *LHS,
const Decl *RHS) {
4000 return LHS->getLocStart() < RHS->getLocStart();
4002 for (
const auto *D : DeferredDecls) {
4003 switch (D->getKind()) {
4004 case Decl::CXXConversion:
4005 case Decl::CXXMethod:
4006 case Decl::Function:
4007 case Decl::ObjCMethod: {
4014 case Decl::CXXConstructor: {
4021 case Decl::CXXDestructor: {
4038 llvm::Type *i64 = llvm::Type::getInt64Ty(Context);
4039 return llvm::ConstantInt::get(i64, PtrInt);
4043 llvm::NamedMDNode *&GlobalMetadata,
4045 llvm::GlobalValue *Addr) {
4046 if (!GlobalMetadata)
4048 CGM.
getModule().getOrInsertNamedMetadata(
"clang.global.decl.ptrs");
4051 llvm::Metadata *Ops[] = {llvm::ConstantAsMetadata::get(Addr),
4054 GlobalMetadata->addOperand(llvm::MDNode::get(CGM.
getLLVMContext(), Ops));
4062 void CodeGenModule::EmitStaticExternCAliases() {
4067 for (
auto &
I : StaticExternCValues) {
4069 llvm::GlobalValue *Val =
I.second;
4077 auto Res = Manglings.find(MangledName);
4078 if (Res == Manglings.end())
4080 Result = Res->getValue();
4091 void CodeGenModule::EmitDeclMetadata() {
4092 llvm::NamedMDNode *GlobalMetadata =
nullptr;
4094 for (
auto &
I : MangledDeclNames) {
4095 llvm::GlobalValue *Addr =
getModule().getNamedValue(
I.second);
4105 void CodeGenFunction::EmitDeclMetadata() {
4106 if (LocalDeclMap.empty())
return;
4111 unsigned DeclPtrKind = Context.getMDKindID(
"clang.decl.ptr");
4113 llvm::NamedMDNode *GlobalMetadata =
nullptr;
4115 for (
auto &
I : LocalDeclMap) {
4116 const Decl *D =
I.first;
4118 if (
auto *Alloca = dyn_cast<llvm::AllocaInst>(Addr)) {
4120 Alloca->setMetadata(
4121 DeclPtrKind, llvm::MDNode::get(
4122 Context, llvm::ValueAsMetadata::getConstant(DAddr)));
4123 }
else if (
auto *GV = dyn_cast<llvm::GlobalValue>(Addr)) {
4130 void CodeGenModule::EmitVersionIdentMetadata() {
4131 llvm::NamedMDNode *IdentMetadata =
4132 TheModule.getOrInsertNamedMetadata(
"llvm.ident");
4134 llvm::LLVMContext &Ctx = TheModule.getContext();
4136 llvm::Metadata *IdentNode[] = {llvm::MDString::get(Ctx, Version)};
4137 IdentMetadata->addOperand(llvm::MDNode::get(Ctx, IdentNode));
4140 void CodeGenModule::EmitTargetMetadata() {
4147 for (
unsigned I = 0;
I != MangledDeclNames.size(); ++
I) {
4148 auto Val = *(MangledDeclNames.begin() +
I);
4149 const Decl *D = Val.first.getDecl()->getMostRecentDecl();
4155 void CodeGenModule::EmitCoverageFile() {
4157 if (llvm::NamedMDNode *CUNode = TheModule.getNamedMetadata(
"llvm.dbg.cu")) {
4158 llvm::NamedMDNode *GCov = TheModule.getOrInsertNamedMetadata(
"llvm.gcov");
4159 llvm::LLVMContext &Ctx = TheModule.getContext();
4160 llvm::MDString *CoverageFile =
4162 for (
int i = 0, e = CUNode->getNumOperands(); i != e; ++i) {
4163 llvm::MDNode *CU = CUNode->getOperand(i);
4164 llvm::Metadata *Elts[] = {CoverageFile, CU};
4165 GCov->addOperand(llvm::MDNode::get(Ctx, Elts));
4171 llvm::Constant *CodeGenModule::EmitUuidofInitializer(StringRef Uuid) {
4174 assert(Uuid.size() == 36);
4175 for (
unsigned i = 0; i < 36; ++i) {
4176 if (i == 8 || i == 13 || i == 18 || i == 23) assert(Uuid[i] ==
'-');
4181 const unsigned Field3ValueOffsets[8] = { 19, 21, 24, 26, 28, 30, 32, 34 };
4183 llvm::Constant *Field3[8];
4184 for (
unsigned Idx = 0; Idx < 8; ++Idx)
4185 Field3[Idx] = llvm::ConstantInt::get(
4186 Int8Ty, Uuid.substr(Field3ValueOffsets[Idx], 2), 16);
4188 llvm::Constant *Fields[4] = {
4189 llvm::ConstantInt::get(
Int32Ty, Uuid.substr(0, 8), 16),
4190 llvm::ConstantInt::get(
Int16Ty, Uuid.substr(9, 4), 16),
4191 llvm::ConstantInt::get(
Int16Ty, Uuid.substr(14, 4), 16),
4192 llvm::ConstantArray::get(llvm::ArrayType::get(
Int8Ty, 8), Field3)
4195 return llvm::ConstantStruct::getAnon(Fields);
4204 return llvm::Constant::getNullValue(
Int8PtrTy);
4214 for (
auto RefExpr : D->
varlists()) {
4215 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(RefExpr)->getDecl());
4217 VD->getAnyInitializer() &&
4218 !VD->getAnyInitializer()->isConstantInitializer(
getContext(),
4223 VD, Addr, RefExpr->getLocStart(), PerformInit))
4224 CXXGlobalInits.push_back(InitFunction);
4234 std::string OutName;
4235 llvm::raw_string_ostream Out(OutName);
4251 return ((LangOpts.
Sanitize.
has(SanitizerKind::CFIVCall) &&
4253 (LangOpts.
Sanitize.
has(SanitizerKind::CFINVCall) &&
4255 (LangOpts.
Sanitize.
has(SanitizerKind::CFIDerivedCast) &&
4257 (LangOpts.
Sanitize.
has(SanitizerKind::CFIUnrelatedCast) &&
4264 llvm::Metadata *MD =
4266 VTable->addTypeMetadata(Offset.
getQuantity(), MD);
4268 if (CodeGenOpts.SanitizeCfiCrossDso)
4271 llvm::ConstantAsMetadata::get(CrossDsoTypeId));
4274 llvm::Metadata *MD = llvm::MDString::get(
getLLVMContext(),
"all-vtables");
4275 VTable->addTypeMetadata(Offset.
getQuantity(), MD);
4284 if (
const auto *TD = FD->getAttr<TargetAttr>()) {
4286 TargetAttr::ParsedTargetAttr ParsedAttr = TD->parse();
4290 ParsedAttr.first.insert(ParsedAttr.first.begin(),
4294 if (ParsedAttr.second !=
"")
4295 TargetCPU = ParsedAttr.second;
4310 SanStats = llvm::make_unique<llvm::SanitizerStatReport>(&
getModule());
void setLinkage(Linkage L)
llvm::PointerType * Int8PtrPtrTy
std::string ProfileInstrumentUsePath
Name of the profile file to use as input for -fprofile-instr-use.
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.
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
decl_range decls() const
decls_begin/decls_end - Iterate over the declarations stored in this context.
SanitizerSet Sanitize
Set of enabled sanitizers.
virtual void mangleCXXDtor(const CXXDestructorDecl *D, CXXDtorType Type, raw_ostream &)=0
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.
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.
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.
static void setLinkageAndVisibilityForGV(llvm::GlobalValue *GV, const NamedDecl *ND)
virtual void completeDefinition()
completeDefinition - Notes that the definition of this type is now complete.
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.
QualType getThisType(ASTContext &C) const
Returns the type of the this pointer.
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...
QualType withConst() const
Retrieves a version of this type with const applied.
GlobalDecl getCanonicalDecl() const
RecordDecl - Represents a struct/union/class.
Visibility getVisibility() const
bool hasBody(const FunctionDecl *&Definition) const
Returns true if the function has a body (definition).
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...
class LLVM_ALIGNAS(8) DependentTemplateSpecializationType const IdentifierInfo * Name
Represents a template specialization type whose template cannot be resolved, e.g. ...
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
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.
This declaration is definitely a definition.
void GenerateObjCCtorDtorMethod(ObjCImplementationDecl *IMP, ObjCMethodDecl *MD, bool ctor)
llvm::Constant * CreateBuiltinFunction(llvm::FunctionType *Ty, StringRef Name, llvm::AttributeSet ExtraAttrs=llvm::AttributeSet())
Create a new compiler builtin function with the specified type and name.
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 ...
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)
Module * Parent
The parent of this module.
Selector getSetterName() const
const SanitizerBlacklist & getSanitizerBlacklist() const
submodule_iterator submodule_end()
void addCompilerUsedGlobal(llvm::GlobalValue *GV)
Add a global to a list to be added to the llvm.compiler.used metadata.
llvm::Constant * GetAddrOfGlobal(GlobalDecl GD, bool IsForDefinition=false)
bool isIncompleteType(NamedDecl **Def=nullptr) const
Types are partitioned into 3 broad categories (C99 6.2.5p1): object types, function types...
llvm::Constant * CreateRuntimeVariable(llvm::Type *Ty, StringRef Name)
Create a new runtime global variable with the specified type and name.
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.
const CGFunctionInfo & arrangeGlobalDeclaration(GlobalDecl GD)
std::vector< Module * >::iterator submodule_iterator
void mangleName(const NamedDecl *D, raw_ostream &)
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...
void setHasDestructors(bool val)
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
static llvm::StringMapEntry< llvm::GlobalVariable * > & GetConstantStringEntry(llvm::StringMap< llvm::GlobalVariable * > &Map, const StringLiteral *Literal, unsigned &StringLength)
void getFunctionFeatureMap(llvm::StringMap< bool > &FeatureMap, const FunctionDecl *FD)
virtual llvm::GlobalVariable * GetClassGlobal(StringRef Name, bool Weak=false)=0
CGObjCRuntime & getObjCRuntime()
Return a reference to the configured Objective-C runtime.
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.
static void addLinkOptionsPostorder(CodeGenModule &CGM, Module *Mod, SmallVectorImpl< llvm::Metadata * > &Metadata, llvm::SmallPtrSet< Module *, 16 > &Visited)
Add link options implied by the given module, including modules it depends on, using a postorder walk...
void GenerateObjCMethod(const ObjCMethodDecl *OMD)
Generate an Objective-C method.
StorageDuration getStorageDuration() const
Retrieve the storage duration for the materialized temporary.
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...
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.
const char * getBufferName(SourceLocation Loc, bool *Invalid=nullptr) const
Return the filename or buffer identifier of the buffer the location is in.
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...
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.
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.
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)
The result type of a method or function.
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
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.
unsigned char IntAlignInBytes
bool doesThisDeclarationHaveABody() const
doesThisDeclarationHaveABody - Returns whether this specific declaration of the function has a body -...
llvm::CallingConv::ID getBuiltinCC() const
bool isNonFragile() const
Does this runtime follow the set of implied behaviors for a "non-fragile" ABI?
CharUnits getTypeAlignInChars(QualType T) const
Return the ABI-specified alignment of a (complete) type T, in characters.
SelectorTable & Selectors
llvm::Constant * CreateRuntimeFunction(llvm::FunctionType *Ty, StringRef Name, llvm::AttributeSet ExtraAttrs=llvm::AttributeSet())
Create a new runtime function with the specified type and name.
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.
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.
llvm::Constant * GetAddrOfGlobalVar(const VarDecl *D, llvm::Type *Ty=nullptr, bool IsForDefinition=false)
Return the llvm::Constant for the address of the given global variable.
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.
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
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.
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...
This template specialization was formed from a template-id but has not yet been declared, defined, or instantiated.
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.
llvm::Constant * getAddrOfCXXStructor(const CXXMethodDecl *MD, StructorType Type, const CGFunctionInfo *FnInfo=nullptr, llvm::FunctionType *FnType=nullptr, bool DontDefer=false, bool IsForDefinition=false)
Return the address of the constructor/destructor of the given type.
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...
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)
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.
ConstantAddress GetAddrOfConstantString(const StringLiteral *Literal)
Return a pointer to a constant NSString object for the given string.
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...
unsigned GetGlobalVarAddressSpace(const VarDecl *D, unsigned AddrSpace)
Return the address space of the underlying global variable for D, as determined by its declaration...
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)
const llvm::Triple & getTriple() const
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)
unsigned Map[Count]
The type of a lookup table which maps from language-specific address spaces to target-specific ones...
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...
Defines the Diagnostic-related interfaces.
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 "Linker Options" metadata value.
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.
This template specialization was declared or defined by an explicit specialization (C++ [temp...
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.
static void emitUsed(CodeGenModule &CGM, StringRef Name, std::vector< llvm::WeakVH > &List)
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...
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...
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...
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.
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.
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
A specialization of Address that requires the address to be an LLVM Constant.
ObjCIvarDecl - Represents an ObjC instance variable.
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...
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...
TranslationUnitDecl - The top declaration context.
unsigned getTargetAddressSpace(QualType T) const
A reference to a declared variable, function, enum, etc.
GVALinkage
A more specific kind of linkage than enum Linkage.
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...
static llvm::Constant * GetPointerConstant(llvm::LLVMContext &Context, const void *Ptr)
Turns the given pointer into a constant.
CodeGenVTables & getVTables()
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...
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...
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)
void ConstructAttributeList(StringRef Name, const CGFunctionInfo &Info, CGCalleeInfo CalleeInfo, AttributeListType &PAL, unsigned &CallingConv, bool AttrOnCallSite)
Get the LLVM attributes and calling convention to use for a particular function type.
llvm::Constant * GetAddrOfFunction(GlobalDecl GD, llvm::Type *Ty=nullptr, bool ForVTable=false, bool DontDefer=false, bool IsForDefinition=false)
Return the address of the given function.
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.
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 "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...
AttributeList - Represents a syntactic attribute.
CanQualType UnsignedIntTy
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.
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.