45 #include "llvm/ADT/APSInt.h"
46 #include "llvm/ADT/Triple.h"
47 #include "llvm/IR/CallSite.h"
48 #include "llvm/IR/CallingConv.h"
49 #include "llvm/IR/DataLayout.h"
50 #include "llvm/IR/Intrinsics.h"
51 #include "llvm/IR/LLVMContext.h"
52 #include "llvm/IR/Module.h"
53 #include "llvm/ProfileData/InstrProfReader.h"
54 #include "llvm/Support/ConvertUTF.h"
55 #include "llvm/Support/ErrorHandling.h"
56 #include "llvm/Support/MD5.h"
58 using namespace clang;
59 using namespace CodeGen;
78 llvm_unreachable(
"invalid C++ ABI kind");
86 :
Context(C), LangOpts(C.getLangOpts()), HeaderSearchOpts(HSO),
87 PreprocessorOpts(PPO), CodeGenOpts(CGO), TheModule(M), Diags(diags),
89 VMContext(M.getContext()), TBAA(nullptr), TheTargetCodeGenInfo(nullptr),
91 OpenCLRuntime(nullptr), OpenMPRuntime(nullptr), CUDARuntime(nullptr),
92 DebugInfo(nullptr), ObjCData(nullptr),
93 NoObjCARCExceptionsMetadata(nullptr), PGOReader(nullptr),
94 CFConstantStringClassRef(nullptr), ConstantStringClassRef(nullptr),
95 NSConstantStringType(nullptr), NSConcreteGlobalBlock(nullptr),
96 NSConcreteStackBlock(nullptr), BlockObjectAssign(nullptr),
97 BlockObjectDispose(nullptr), BlockDescriptorType(nullptr),
98 GenericBlockLiteralType(nullptr), LifetimeStartFn(nullptr),
102 llvm::LLVMContext &LLVMContext = M.getContext();
103 VoidTy = llvm::Type::getVoidTy(LLVMContext);
104 Int8Ty = llvm::Type::getInt8Ty(LLVMContext);
105 Int16Ty = llvm::Type::getInt16Ty(LLVMContext);
106 Int32Ty = llvm::Type::getInt32Ty(LLVMContext);
107 Int64Ty = llvm::Type::getInt64Ty(LLVMContext);
108 FloatTy = llvm::Type::getFloatTy(LLVMContext);
109 DoubleTy = llvm::Type::getDoubleTy(LLVMContext);
126 createOpenCLRuntime();
128 createOpenMPRuntime();
133 if (LangOpts.
Sanitize.
has(SanitizerKind::Thread) ||
134 (!CodeGenOpts.RelaxedAliasing && CodeGenOpts.OptimizationLevel > 0))
141 CodeGenOpts.EmitGcovArcs ||
142 CodeGenOpts.EmitGcovNotes)
145 Block.GlobalUniqueCount = 0;
153 if (std::error_code EC = ReaderOrErr.getError()) {
155 "Could not read profile %0: %1");
159 PGOReader = std::move(ReaderOrErr.get());
164 if (CodeGenOpts.CoverageMapping)
170 delete OpenCLRuntime;
171 delete OpenMPRuntime;
173 delete TheTargetCodeGenInfo;
179 void CodeGenModule::createObjCRuntime() {
196 llvm_unreachable(
"bad runtime kind");
199 void CodeGenModule::createOpenCLRuntime() {
203 void CodeGenModule::createOpenMPRuntime() {
207 void CodeGenModule::createCUDARuntime() {
212 Replacements[
Name] =
C;
215 void CodeGenModule::applyReplacements() {
216 for (
auto &
I : Replacements) {
217 StringRef MangledName =
I.first();
218 llvm::Constant *Replacement =
I.second;
222 auto *OldF = cast<llvm::Function>(Entry);
223 auto *NewF = dyn_cast<llvm::Function>(Replacement);
225 if (
auto *Alias = dyn_cast<llvm::GlobalAlias>(Replacement)) {
226 NewF = dyn_cast<llvm::Function>(Alias->getAliasee());
228 auto *CE = cast<llvm::ConstantExpr>(Replacement);
229 assert(CE->getOpcode() == llvm::Instruction::BitCast ||
230 CE->getOpcode() == llvm::Instruction::GetElementPtr);
231 NewF = dyn_cast<llvm::Function>(CE->getOperand(0));
236 OldF->replaceAllUsesWith(Replacement);
238 NewF->removeFromParent();
239 OldF->getParent()->getFunctionList().insertAfter(OldF->getIterator(),
242 OldF->eraseFromParent();
247 GlobalValReplacements.push_back(std::make_pair(GV, C));
250 void CodeGenModule::applyGlobalValReplacements() {
251 for (
auto &
I : GlobalValReplacements) {
252 llvm::GlobalValue *GV =
I.first;
253 llvm::Constant *
C =
I.second;
255 GV->replaceAllUsesWith(C);
256 GV->eraseFromParent();
263 llvm::SmallPtrSet<const llvm::GlobalAlias*, 4> Visited;
264 const llvm::Constant *C = &GA;
266 C = C->stripPointerCasts();
267 if (
auto *GO = dyn_cast<llvm::GlobalObject>(C))
270 auto *GA2 = dyn_cast<llvm::GlobalAlias>(
C);
273 if (!Visited.insert(GA2).second)
275 C = GA2->getAliasee();
279 void CodeGenModule::checkAliases() {
286 const auto *D = cast<ValueDecl>(GD.getDecl());
287 const AliasAttr *AA = D->getAttr<AliasAttr>();
290 auto *Alias = cast<llvm::GlobalAlias>(Entry);
294 Diags.
Report(AA->getLocation(), diag::err_cyclic_alias);
295 }
else if (GV->isDeclaration()) {
297 Diags.
Report(AA->getLocation(), diag::err_alias_to_undefined);
300 llvm::Constant *Aliasee = Alias->getAliasee();
301 llvm::GlobalValue *AliaseeGV;
302 if (
auto CE = dyn_cast<llvm::ConstantExpr>(Aliasee))
303 AliaseeGV = cast<llvm::GlobalValue>(CE->getOperand(0));
305 AliaseeGV = cast<llvm::GlobalValue>(Aliasee);
307 if (
const SectionAttr *SA = D->getAttr<SectionAttr>()) {
308 StringRef AliasSection = SA->getName();
309 if (AliasSection != AliaseeGV->getSection())
310 Diags.
Report(SA->getLocation(), diag::warn_alias_with_section)
319 if (
auto GA = dyn_cast<llvm::GlobalAlias>(AliaseeGV)) {
320 if (GA->mayBeOverridden()) {
321 Diags.
Report(AA->getLocation(), diag::warn_alias_to_weak_alias)
322 << GV->getName() << GA->getName();
323 Aliasee = llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(
324 GA->getAliasee(), Alias->getType());
325 Alias->setAliasee(Aliasee);
335 auto *Alias = cast<llvm::GlobalAlias>(Entry);
336 Alias->replaceAllUsesWith(llvm::UndefValue::get(Alias->getType()));
337 Alias->eraseFromParent();
342 DeferredDeclsToEmit.clear();
344 OpenMPRuntime->clear();
348 StringRef MainFile) {
351 if (VisitedInMainFile > 0 && VisitedInMainFile == MissingInMainFile) {
352 if (MainFile.empty())
353 MainFile =
"<stdin>";
354 Diags.
Report(diag::warn_profile_data_unprofiled) << MainFile;
356 Diags.
Report(diag::warn_profile_data_out_of_date) << Visited << Missing
362 applyGlobalValReplacements();
365 EmitCXXGlobalInitFunc();
366 EmitCXXGlobalDtorFunc();
367 EmitCXXThreadLocalInitFunc();
369 if (llvm::Function *ObjCInitFunction =
ObjCRuntime->ModuleInitFunction())
370 AddGlobalCtor(ObjCInitFunction);
374 AddGlobalCtor(CudaCtorFunction);
376 AddGlobalDtor(CudaDtorFunction);
379 if (llvm::Function *OpenMPRegistrationFunction =
380 OpenMPRuntime->emitRegistrationFunction())
381 AddGlobalCtor(OpenMPRegistrationFunction, 0);
383 getModule().setMaximumFunctionCount(PGOReader->getMaximumFunctionCount());
387 EmitCtorList(GlobalCtors,
"llvm.global_ctors");
388 EmitCtorList(GlobalDtors,
"llvm.global_dtors");
390 EmitStaticExternCAliases();
393 CoverageMapping->emit();
396 if (CodeGenOpts.Autolink &&
397 (Context.
getLangOpts().Modules || !LinkerOptionsMetadata.empty())) {
398 EmitModuleLinkOptions();
400 if (CodeGenOpts.DwarfVersion) {
404 CodeGenOpts.DwarfVersion);
406 if (CodeGenOpts.EmitCodeView) {
410 if (CodeGenOpts.OptimizationLevel > 0 && CodeGenOpts.StrictVTablePointers) {
417 llvm::Metadata *Ops[2] = {
418 llvm::MDString::get(VMContext,
"StrictVTablePointers"),
419 llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
420 llvm::Type::getInt32Ty(VMContext), 1))};
422 getModule().addModuleFlag(llvm::Module::Require,
423 "StrictVTablePointersRequirement",
424 llvm::MDNode::get(VMContext, Ops));
431 llvm::DEBUG_METADATA_VERSION);
436 if ( Arch == llvm::Triple::arm
437 || Arch == llvm::Triple::armeb
438 || Arch == llvm::Triple::thumb
439 || Arch == llvm::Triple::thumbeb) {
441 uint64_t WCharWidth =
446 uint64_t EnumWidth = Context.
getLangOpts().ShortEnums ? 1 : 4;
450 if (CodeGenOpts.SanitizeCfiCrossDso) {
452 getModule().addModuleFlag(llvm::Module::Override,
"Cross-DSO CFI", 1);
455 if (uint32_t PLevel = Context.
getLangOpts().PICLevel) {
459 case 1: PL = llvm::PICLevel::Small;
break;
460 case 2: PL = llvm::PICLevel::Large;
break;
461 default: llvm_unreachable(
"Invalid PIC Level");
467 SimplifyPersonality();
478 EmitVersionIdentMetadata();
480 EmitTargetMetadata();
507 llvm::MDNode *AccessN,
519 llvm::MDNode *TBAAInfo,
520 bool ConvertTypeToTag) {
521 if (ConvertTypeToTag && TBAA)
522 Inst->setMetadata(llvm::LLVMContext::MD_tbaa,
525 Inst->setMetadata(llvm::LLVMContext::MD_tbaa, TBAAInfo);
531 auto *MetaDataNode = dyn_cast<llvm::MDNode>(MD);
535 I->setMetadata(llvm::LLVMContext::MD_invariant_group, MetaDataNode);
547 "cannot compile this %0 yet");
548 std::string Msg =
Type;
550 << Msg << S->getSourceRange();
557 "cannot compile this %0 yet");
558 std::string Msg =
Type;
569 if (GV->hasLocalLinkage()) {
581 return llvm::StringSwitch<llvm::GlobalVariable::ThreadLocalMode>(
S)
582 .Case(
"global-dynamic", llvm::GlobalVariable::GeneralDynamicTLSModel)
583 .Case(
"local-dynamic", llvm::GlobalVariable::LocalDynamicTLSModel)
584 .Case(
"initial-exec", llvm::GlobalVariable::InitialExecTLSModel)
585 .Case(
"local-exec", llvm::GlobalVariable::LocalExecTLSModel);
592 return llvm::GlobalVariable::GeneralDynamicTLSModel;
594 return llvm::GlobalVariable::LocalDynamicTLSModel;
596 return llvm::GlobalVariable::InitialExecTLSModel;
598 return llvm::GlobalVariable::LocalExecTLSModel;
600 llvm_unreachable(
"Invalid TLS model!");
604 assert(D.
getTLSKind() &&
"setting TLS mode on non-TLS var!");
606 llvm::GlobalValue::ThreadLocalMode TLM;
610 if (
const TLSModelAttr *
Attr = D.
getAttr<TLSModelAttr>()) {
614 GV->setThreadLocalMode(TLM);
622 if (
const auto *CD = dyn_cast<CXXConstructorDecl>(CanonicalGD.
getDecl())) {
631 StringRef &FoundStr = MangledDeclNames[CanonicalGD];
632 if (!FoundStr.empty())
635 const auto *ND = cast<NamedDecl>(GD.
getDecl());
639 llvm::raw_svector_ostream Out(Buffer);
640 if (
const auto *D = dyn_cast<CXXConstructorDecl>(ND))
642 else if (
const auto *D = dyn_cast<CXXDestructorDecl>(ND))
649 assert(II &&
"Attempt to mangle unnamed decl.");
654 auto Result = Manglings.insert(std::make_pair(Str, GD));
655 return FoundStr =
Result.first->first();
664 llvm::raw_svector_ostream Out(Buffer);
667 dyn_cast_or_null<VarDecl>(initializedGlobalDecl.
getDecl()), Out);
668 else if (
const auto *CD = dyn_cast<CXXConstructorDecl>(D))
670 else if (
const auto *DD = dyn_cast<CXXDestructorDecl>(D))
673 MangleCtx.
mangleBlock(cast<DeclContext>(D), BD, Out);
675 auto Result = Manglings.insert(std::make_pair(Out.str(), BD));
676 return Result.first->first();
685 void CodeGenModule::AddGlobalCtor(llvm::Function *Ctor,
int Priority,
686 llvm::Constant *AssociatedData) {
688 GlobalCtors.push_back(Structor(Priority, Ctor, AssociatedData));
693 void CodeGenModule::AddGlobalDtor(llvm::Function *Dtor,
int Priority) {
695 GlobalDtors.push_back(Structor(Priority, Dtor,
nullptr));
698 void CodeGenModule::EmitCtorList(
const CtorList &Fns,
const char *GlobalName) {
700 llvm::FunctionType* CtorFTy = llvm::FunctionType::get(
VoidTy,
false);
701 llvm::Type *CtorPFTy = llvm::PointerType::getUnqual(CtorFTy);
704 llvm::StructType *CtorStructTy = llvm::StructType::get(
709 for (
const auto &
I : Fns) {
710 llvm::Constant *
S[] = {
711 llvm::ConstantInt::get(
Int32Ty,
I.Priority,
false),
712 llvm::ConstantExpr::getBitCast(
I.Initializer, CtorPFTy),
714 ? llvm::ConstantExpr::getBitCast(
I.AssociatedData,
VoidPtrTy)
715 : llvm::Constant::getNullValue(
VoidPtrTy))};
716 Ctors.push_back(llvm::ConstantStruct::get(CtorStructTy, S));
719 if (!Ctors.empty()) {
720 llvm::ArrayType *AT = llvm::ArrayType::get(CtorStructTy, Ctors.size());
721 new llvm::GlobalVariable(TheModule, AT,
false,
722 llvm::GlobalValue::AppendingLinkage,
723 llvm::ConstantArray::get(AT, Ctors),
728 llvm::GlobalValue::LinkageTypes
730 const auto *D = cast<FunctionDecl>(GD.
getDecl());
734 if (isa<CXXDestructorDecl>(D) &&
735 getCXXABI().useThunkForDtorVariant(cast<CXXDestructorDecl>(D),
740 : llvm::GlobalValue::LinkOnceODRLinkage;
747 const auto *FD = cast<FunctionDecl>(GD.
getDecl());
749 if (
const auto *Dtor = dyn_cast_or_null<CXXDestructorDecl>(FD)) {
752 F->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass);
757 if (FD->hasAttr<DLLImportAttr>())
758 F->setDLLStorageClass(llvm::GlobalVariable::DLLImportStorageClass);
759 else if (FD->hasAttr<DLLExportAttr>())
760 F->setDLLStorageClass(llvm::GlobalVariable::DLLExportStorageClass);
762 F->setDLLStorageClass(llvm::GlobalVariable::DefaultStorageClass);
767 llvm::MDString *MDS = dyn_cast<llvm::MDString>(MD);
768 if (!MDS)
return nullptr;
771 llvm::MD5::MD5Result result;
772 md5.update(MDS->getString());
775 for (
int i = 0; i < 8; ++i)
776 id |= static_cast<uint64_t>(result[i]) << (i * 8);
777 return llvm::ConstantInt::get(
Int64Ty,
id);
782 setNonAliasAttributes(D, F);
792 F->setAttributes(llvm::AttributeSet::get(
getLLVMContext(), AttributeList));
793 F->setCallingConv(static_cast<llvm::CallingConv::ID>(CallingConv));
803 if (!LangOpts.Exceptions)
return false;
806 if (LangOpts.CXXExceptions)
return true;
809 if (LangOpts.ObjCExceptions) {
820 if (CodeGenOpts.UnwindTables)
821 B.addAttribute(llvm::Attribute::UWTable);
824 B.addAttribute(llvm::Attribute::NoUnwind);
827 B.addAttribute(llvm::Attribute::StackProtect);
829 B.addAttribute(llvm::Attribute::StackProtectStrong);
831 B.addAttribute(llvm::Attribute::StackProtectReq);
834 F->addAttributes(llvm::AttributeSet::FunctionIndex,
835 llvm::AttributeSet::get(
837 llvm::AttributeSet::FunctionIndex, B));
843 B.addAttribute(llvm::Attribute::Naked);
844 B.addAttribute(llvm::Attribute::NoInline);
845 }
else if (D->
hasAttr<NoDuplicateAttr>()) {
846 B.addAttribute(llvm::Attribute::NoDuplicate);
847 }
else if (D->
hasAttr<NoInlineAttr>()) {
848 B.addAttribute(llvm::Attribute::NoInline);
849 }
else if (D->
hasAttr<AlwaysInlineAttr>() &&
850 !F->getAttributes().hasAttribute(llvm::AttributeSet::FunctionIndex,
851 llvm::Attribute::NoInline)) {
853 B.addAttribute(llvm::Attribute::AlwaysInline);
857 if (!D->
hasAttr<OptimizeNoneAttr>())
858 B.addAttribute(llvm::Attribute::OptimizeForSize);
859 B.addAttribute(llvm::Attribute::Cold);
863 B.addAttribute(llvm::Attribute::MinSize);
865 F->addAttributes(llvm::AttributeSet::FunctionIndex,
866 llvm::AttributeSet::get(
867 F->getContext(), llvm::AttributeSet::FunctionIndex, B));
869 if (D->
hasAttr<OptimizeNoneAttr>()) {
871 F->addFnAttr(llvm::Attribute::OptimizeNone);
872 F->addFnAttr(llvm::Attribute::NoInline);
875 F->removeFnAttr(llvm::Attribute::OptimizeForSize);
876 F->removeFnAttr(llvm::Attribute::MinSize);
877 assert(!F->hasFnAttribute(llvm::Attribute::AlwaysInline) &&
878 "OptimizeNone and AlwaysInline on same function!");
882 F->removeFnAttr(llvm::Attribute::InlineHint);
885 if (isa<CXXConstructorDecl>(D) || isa<CXXDestructorDecl>(D))
886 F->setUnnamedAddr(
true);
887 else if (
const auto *MD = dyn_cast<CXXMethodDecl>(D))
889 F->setUnnamedAddr(
true);
893 F->setAlignment(alignment);
900 if (F->getAlignment() < 2 && isa<CXXMethodDecl>(D))
906 llvm::GlobalValue *GV) {
907 if (
const auto *ND = dyn_cast_or_null<NamedDecl>(D))
912 if (D && D->
hasAttr<UsedAttr>())
917 llvm::GlobalValue *GV) {
922 if (D->
hasAttr<DLLExportAttr>())
923 GV->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass);
926 void CodeGenModule::setNonAliasAttributes(
const Decl *D,
927 llvm::GlobalObject *GO) {
931 if (
const SectionAttr *SA = D->
getAttr<SectionAttr>())
932 GO->setSection(SA->getName());
945 setNonAliasAttributes(D, F);
955 if (ND->
hasAttr<DLLImportAttr>()) {
957 GV->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
958 }
else if (ND->
hasAttr<DLLExportAttr>()) {
960 GV->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass);
964 GV->setLinkage(llvm::GlobalValue::ExternalWeakLinkage);
976 if (!LangOpts.
Sanitize.
has(SanitizerKind::CFIICall))
980 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic())
984 if (CodeGenOpts.SanitizeCfiCrossDso) {
995 llvm::NamedMDNode *BitsetsMD =
996 getModule().getOrInsertNamedMetadata(
"llvm.bitsets");
999 llvm::Metadata *BitsetOps[] = {
1000 MD, llvm::ConstantAsMetadata::get(F),
1001 llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
Int64Ty, 0))};
1002 BitsetsMD->addOperand(llvm::MDTuple::get(
getLLVMContext(), BitsetOps));
1005 if (CodeGenOpts.SanitizeCfiCrossDso) {
1007 llvm::Metadata *BitsetOps2[] = {
1008 llvm::ConstantAsMetadata::get(TypeId),
1009 llvm::ConstantAsMetadata::get(F),
1010 llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
Int64Ty, 0))};
1011 BitsetsMD->addOperand(llvm::MDTuple::get(
getLLVMContext(), BitsetOps2));
1016 void CodeGenModule::SetFunctionAttributes(
GlobalDecl GD, llvm::Function *F,
1017 bool IsIncompleteFunction,
1022 F->setAttributes(llvm::Intrinsic::getAttributes(
getLLVMContext(), IID));
1026 const auto *FD = cast<FunctionDecl>(GD.
getDecl());
1028 if (!IsIncompleteFunction)
1034 if (!IsThunk &&
getCXXABI().HasThisReturn(GD) &&
1037 assert(!F->arg_empty() &&
1038 F->arg_begin()->getType()
1039 ->canLosslesslyBitCastTo(F->getReturnType()) &&
1040 "unexpected this return");
1041 F->addAttribute(1, llvm::Attribute::Returned);
1049 if (
const SectionAttr *SA = FD->getAttr<SectionAttr>())
1050 F->setSection(SA->getName());
1054 if (FD->isReplaceableGlobalAllocationFunction())
1055 F->addAttribute(llvm::AttributeSet::FunctionIndex,
1056 llvm::Attribute::NoBuiltin);
1062 assert(!GV->isDeclaration() &&
1063 "Only globals with definition can force usage.");
1064 LLVMUsed.emplace_back(GV);
1068 assert(!GV->isDeclaration() &&
1069 "Only globals with definition can force usage.");
1070 LLVMCompilerUsed.emplace_back(GV);
1074 std::vector<llvm::WeakVH> &List) {
1081 UsedArray.resize(List.size());
1082 for (
unsigned i = 0, e = List.size(); i != e; ++i) {
1084 llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(
1085 cast<llvm::Constant>(&*List[i]), CGM.
Int8PtrTy);
1088 if (UsedArray.empty())
1090 llvm::ArrayType *ATy = llvm::ArrayType::get(CGM.
Int8PtrTy, UsedArray.size());
1092 auto *GV =
new llvm::GlobalVariable(
1093 CGM.
getModule(), ATy,
false, llvm::GlobalValue::AppendingLinkage,
1094 llvm::ConstantArray::get(ATy, UsedArray),
Name);
1096 GV->setSection(
"llvm.metadata");
1099 void CodeGenModule::emitLLVMUsed() {
1100 emitUsed(*
this,
"llvm.used", LLVMUsed);
1101 emitUsed(*
this,
"llvm.compiler.used", LLVMCompilerUsed);
1106 LinkerOptionsMetadata.push_back(llvm::MDNode::get(
getLLVMContext(), MDOpts));
1113 LinkerOptionsMetadata.push_back(llvm::MDNode::get(
getLLVMContext(), MDOpts));
1120 LinkerOptionsMetadata.push_back(llvm::MDNode::get(
getLLVMContext(), MDOpts));
1127 llvm::SmallPtrSet<Module *, 16> &Visited) {
1129 if (Mod->
Parent && Visited.insert(Mod->
Parent).second) {
1134 for (
unsigned I = Mod->
Imports.size();
I > 0; --
I) {
1135 if (Visited.insert(Mod->
Imports[
I - 1]).second)
1146 llvm::Metadata *Args[2] = {
1147 llvm::MDString::get(Context,
"-framework"),
1148 llvm::MDString::get(Context, Mod->
LinkLibraries[
I - 1].Library)};
1150 Metadata.push_back(llvm::MDNode::get(Context, Args));
1158 auto *OptString = llvm::MDString::get(Context, Opt);
1159 Metadata.push_back(llvm::MDNode::get(Context, OptString));
1163 void CodeGenModule::EmitModuleLinkOptions() {
1167 llvm::SetVector<clang::Module *> LinkModules;
1168 llvm::SmallPtrSet<clang::Module *, 16> Visited;
1172 for (
Module *M : ImportedModules)
1173 if (Visited.insert(M).second)
1178 while (!Stack.empty()) {
1181 bool AnyChildren =
false;
1186 Sub != SubEnd; ++Sub) {
1189 if ((*Sub)->IsExplicit)
1192 if (Visited.insert(*Sub).second) {
1193 Stack.push_back(*Sub);
1201 LinkModules.insert(Mod);
1210 for (
Module *M : LinkModules)
1211 if (Visited.insert(M).second)
1213 std::reverse(MetadataArgs.begin(), MetadataArgs.end());
1214 LinkerOptionsMetadata.append(MetadataArgs.begin(), MetadataArgs.end());
1217 getModule().addModuleFlag(llvm::Module::AppendUnique,
"Linker Options",
1219 LinkerOptionsMetadata));
1222 void CodeGenModule::EmitDeferred() {
1227 if (!DeferredVTables.empty()) {
1228 EmitDeferredVTables();
1233 assert(DeferredVTables.empty());
1237 if (DeferredDeclsToEmit.empty())
1242 std::vector<DeferredGlobal> CurDeclsToEmit;
1243 CurDeclsToEmit.swap(DeferredDeclsToEmit);
1245 for (DeferredGlobal &G : CurDeclsToEmit) {
1247 llvm::GlobalValue *GV = G.GV;
1255 if (isa<FunctionDecl>(D.
getDecl()))
1267 if (GV && !GV->isDeclaration())
1271 EmitGlobalDefinition(D, GV);
1276 if (!DeferredVTables.empty() || !DeferredDeclsToEmit.empty()) {
1278 assert(DeferredVTables.empty() && DeferredDeclsToEmit.empty());
1284 if (Annotations.empty())
1288 llvm::Constant *Array = llvm::ConstantArray::get(llvm::ArrayType::get(
1289 Annotations[0]->getType(), Annotations.size()), Annotations);
1290 auto *gv =
new llvm::GlobalVariable(
getModule(), Array->getType(),
false,
1291 llvm::GlobalValue::AppendingLinkage,
1292 Array,
"llvm.global.annotations");
1297 llvm::Constant *&AStr = AnnotationStrings[Str];
1302 llvm::Constant *s = llvm::ConstantDataArray::getString(
getLLVMContext(), Str);
1304 new llvm::GlobalVariable(
getModule(), s->getType(),
true,
1305 llvm::GlobalValue::PrivateLinkage, s,
".str");
1307 gv->setUnnamedAddr(
true);
1325 return llvm::ConstantInt::get(
Int32Ty, LineNo);
1329 const AnnotateAttr *AA,
1337 llvm::Constant *Fields[4] = {
1338 llvm::ConstantExpr::getBitCast(GV,
Int8PtrTy),
1339 llvm::ConstantExpr::getBitCast(AnnoGV,
Int8PtrTy),
1340 llvm::ConstantExpr::getBitCast(UnitGV,
Int8PtrTy),
1343 return llvm::ConstantStruct::getAnon(Fields);
1347 llvm::GlobalValue *GV) {
1348 assert(D->
hasAttr<AnnotateAttr>() &&
"no annotate attribute");
1358 if (SanitizerBL.isBlacklistedFunction(Fn->getName()))
1367 return SanitizerBL.isBlacklistedFile(MainFile->getName());
1377 SanitizerKind::Address | SanitizerKind::KernelAddress))
1380 if (SanitizerBL.isBlacklistedGlobal(GV->getName(),
Category))
1382 if (SanitizerBL.isBlacklistedLocation(Loc, Category))
1388 while (
auto AT = dyn_cast<ArrayType>(Ty.
getTypePtr()))
1389 Ty = AT->getElementType();
1394 if (SanitizerBL.isBlacklistedType(TypeStr, Category))
1401 bool CodeGenModule::MustBeEmitted(
const ValueDecl *Global) {
1403 if (LangOpts.EmitAllDecls)
1409 bool CodeGenModule::MayBeEmittedEagerly(
const ValueDecl *Global) {
1410 if (
const auto *FD = dyn_cast<FunctionDecl>(Global))
1417 if (LangOpts.OpenMP && LangOpts.OpenMPUseTLS &&
1429 std::string
Name =
"_GUID_" + Uuid.lower();
1430 std::replace(Name.begin(), Name.end(),
'-',
'_');
1436 if (llvm::GlobalVariable *GV =
getModule().getNamedGlobal(Name))
1439 llvm::Constant *Init = EmitUuidofInitializer(Uuid);
1440 assert(Init &&
"failed to initialize as constant");
1442 auto *GV =
new llvm::GlobalVariable(
1444 true, llvm::GlobalValue::LinkOnceODRLinkage, Init,
Name);
1446 GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
1451 const AliasAttr *AA = VD->
getAttr<AliasAttr>();
1452 assert(AA &&
"No alias?");
1461 auto Ptr = llvm::ConstantExpr::getBitCast(Entry, DeclTy->getPointerTo(AS));
1465 llvm::Constant *Aliasee;
1466 if (isa<llvm::FunctionType>(DeclTy))
1467 Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy,
1471 Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(),
1472 llvm::PointerType::getUnqual(DeclTy),
1475 auto *F = cast<llvm::GlobalValue>(Aliasee);
1476 F->setLinkage(llvm::Function::ExternalWeakLinkage);
1477 WeakRefReferences.insert(F);
1483 const auto *Global = cast<ValueDecl>(GD.
getDecl());
1486 if (Global->
hasAttr<WeakRefAttr>())
1491 if (Global->
hasAttr<AliasAttr>())
1492 return EmitAliasDefinition(GD);
1495 if (LangOpts.CUDA) {
1496 if (LangOpts.CUDAIsDevice) {
1497 if (!Global->
hasAttr<CUDADeviceAttr>() &&
1498 !Global->
hasAttr<CUDAGlobalAttr>() &&
1499 !Global->
hasAttr<CUDAConstantAttr>() &&
1500 !Global->
hasAttr<CUDASharedAttr>())
1503 if (!Global->
hasAttr<CUDAHostAttr>() && (
1504 Global->
hasAttr<CUDADeviceAttr>() ||
1505 Global->
hasAttr<CUDAConstantAttr>() ||
1506 Global->
hasAttr<CUDASharedAttr>()))
1513 if (OpenMPRuntime && OpenMPRuntime->emitTargetGlobal(GD))
1517 if (
const auto *FD = dyn_cast<FunctionDecl>(Global)) {
1519 if (!FD->doesThisDeclarationHaveABody()) {
1520 if (!FD->doesDeclarationForceExternallyVisibleDefinition())
1529 GetOrCreateLLVMFunction(MangledName, Ty, GD,
false,
1534 const auto *VD = cast<VarDecl>(Global);
1535 assert(VD->isFileVarDecl() &&
"Cannot emit local var decl as global.");
1545 if (MustBeEmitted(Global) && MayBeEmittedEagerly(Global)) {
1547 EmitGlobalDefinition(GD);
1554 cast<VarDecl>(Global)->hasInit()) {
1555 DelayedCXXInitPosition[Global] = CXXGlobalInits.size();
1556 CXXGlobalInits.push_back(
nullptr);
1562 addDeferredDeclToEmit(GV, GD);
1563 }
else if (MustBeEmitted(Global)) {
1565 assert(!MayBeEmittedEagerly(Global));
1566 addDeferredDeclToEmit(
nullptr, GD);
1571 DeferredDecls[MangledName] = GD;
1576 struct FunctionIsDirectlyRecursive :
1578 const StringRef
Name;
1591 if (Attr &&
Name == Attr->getLabel()) {
1596 if (!BuiltinID || !BI.isLibFunction(BuiltinID))
1598 StringRef BuiltinName = BI.getName(BuiltinID);
1599 if (BuiltinName.startswith(
"__builtin_") &&
1600 Name == BuiltinName.slice(strlen(
"__builtin_"), StringRef::npos)) {
1608 struct DLLImportFunctionVisitor
1610 bool SafeToInline =
true;
1612 bool VisitVarDecl(
VarDecl *VD) {
1615 return SafeToInline;
1621 if (isa<FunctionDecl>(VD))
1622 SafeToInline = VD->
hasAttr<DLLImportAttr>();
1623 else if (
VarDecl *V = dyn_cast<VarDecl>(VD))
1624 SafeToInline = !V->hasGlobalStorage() || V->hasAttr<DLLImportAttr>();
1625 return SafeToInline;
1629 return SafeToInline;
1633 return SafeToInline;
1642 CodeGenModule::isTriviallyRecursive(
const FunctionDecl *FD) {
1644 if (
getCXXABI().getMangleContext().shouldMangleDeclName(FD)) {
1646 AsmLabelAttr *Attr = FD->
getAttr<AsmLabelAttr>();
1649 Name = Attr->getLabel();
1654 FunctionIsDirectlyRecursive Walker(Name, Context.
BuiltinInfo);
1655 Walker.TraverseFunctionDecl(const_cast<FunctionDecl*>(FD));
1656 return Walker.Result;
1660 CodeGenModule::shouldEmitFunction(
GlobalDecl GD) {
1663 const auto *F = cast<FunctionDecl>(GD.
getDecl());
1664 if (CodeGenOpts.OptimizationLevel == 0 && !F->hasAttr<AlwaysInlineAttr>())
1667 if (F->hasAttr<DLLImportAttr>()) {
1669 DLLImportFunctionVisitor Visitor;
1670 Visitor.TraverseFunctionDecl(const_cast<FunctionDecl*>(F));
1671 if (!Visitor.SafeToInline)
1680 return !isTriviallyRecursive(F);
1688 void CodeGenModule::CompleteDIClassType(
const CXXMethodDecl* D) {
1695 DI->getOrCreateRecordType(ThisPtr->getPointeeType(), D->
getLocation());
1699 void CodeGenModule::EmitGlobalDefinition(
GlobalDecl GD, llvm::GlobalValue *GV) {
1700 const auto *D = cast<ValueDecl>(GD.
getDecl());
1704 "Generating code for declaration");
1706 if (isa<FunctionDecl>(D)) {
1709 if (!shouldEmitFunction(GD))
1712 if (
const auto *Method = dyn_cast<CXXMethodDecl>(D)) {
1713 CompleteDIClassType(Method);
1716 if (
const auto *CD = dyn_cast<CXXConstructorDecl>(Method))
1718 else if (
const auto *DD = dyn_cast<CXXDestructorDecl>(Method))
1721 EmitGlobalFunctionDefinition(GD, GV);
1723 if (Method->isVirtual())
1729 return EmitGlobalFunctionDefinition(GD, GV);
1732 if (
const auto *VD = dyn_cast<VarDecl>(D))
1733 return EmitGlobalVarDefinition(VD);
1735 llvm_unreachable(
"Invalid argument to EmitGlobalDefinition()");
1739 llvm::Function *NewFn);
1749 CodeGenModule::GetOrCreateLLVMFunction(StringRef MangledName,
1752 bool DontDefer,
bool IsThunk,
1753 llvm::AttributeSet ExtraAttrs,
1754 bool IsForDefinition) {
1760 if (WeakRefReferences.erase(Entry)) {
1761 const FunctionDecl *FD = cast_or_null<FunctionDecl>(D);
1762 if (FD && !FD->
hasAttr<WeakAttr>())
1767 if (D && !D->
hasAttr<DLLImportAttr>() && !D->
hasAttr<DLLExportAttr>())
1768 Entry->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass);
1772 if (IsForDefinition && !Entry->isDeclaration()) {
1779 DiagnosedConflictingDefinitions.insert(GD).second) {
1781 diag::err_duplicate_mangled_name);
1783 diag::note_previous_definition);
1787 if ((isa<llvm::Function>(Entry) || isa<llvm::GlobalAlias>(Entry)) &&
1788 (Entry->getType()->getElementType() == Ty)) {
1795 if (!IsForDefinition)
1796 return llvm::ConstantExpr::getBitCast(Entry, Ty->getPointerTo());
1802 bool IsIncompleteFunction =
false;
1804 llvm::FunctionType *FTy;
1805 if (isa<llvm::FunctionType>(Ty)) {
1806 FTy = cast<llvm::FunctionType>(Ty);
1808 FTy = llvm::FunctionType::get(
VoidTy,
false);
1809 IsIncompleteFunction =
true;
1814 Entry ? StringRef() : MangledName, &
getModule());
1831 if (!Entry->use_empty()) {
1833 Entry->removeDeadConstantUsers();
1836 llvm::Constant *BC = llvm::ConstantExpr::getBitCast(
1837 F, Entry->getType()->getElementType()->getPointerTo());
1841 assert(F->getName() == MangledName &&
"name was uniqued!");
1843 SetFunctionAttributes(GD, F, IsIncompleteFunction, IsThunk);
1844 if (ExtraAttrs.hasAttributes(llvm::AttributeSet::FunctionIndex)) {
1845 llvm::AttrBuilder B(ExtraAttrs, llvm::AttributeSet::FunctionIndex);
1846 F->addAttributes(llvm::AttributeSet::FunctionIndex,
1847 llvm::AttributeSet::get(VMContext,
1848 llvm::AttributeSet::FunctionIndex,
1856 if (D && isa<CXXDestructorDecl>(D) &&
1857 getCXXABI().useThunkForDtorVariant(cast<CXXDestructorDecl>(D),
1859 addDeferredDeclToEmit(F, GD);
1864 auto DDI = DeferredDecls.find(MangledName);
1865 if (DDI != DeferredDecls.end()) {
1869 addDeferredDeclToEmit(F, DDI->second);
1870 DeferredDecls.erase(DDI);
1885 for (
const auto *FD = cast<FunctionDecl>(D)->getMostRecentDecl(); FD;
1898 if (!IsIncompleteFunction) {
1899 assert(F->getType()->getElementType() == Ty);
1903 llvm::Type *PTy = llvm::PointerType::getUnqual(Ty);
1904 return llvm::ConstantExpr::getBitCast(F, PTy);
1914 bool IsForDefinition) {
1917 const auto *FD = cast<FunctionDecl>(GD.
getDecl());
1923 return GetOrCreateLLVMFunction(MangledName, Ty, GD, ForVTable, DontDefer,
1924 false, llvm::AttributeSet(),
1933 llvm::AttributeSet ExtraAttrs) {
1935 GetOrCreateLLVMFunction(Name, FTy,
GlobalDecl(),
false,
1936 false,
false, ExtraAttrs);
1937 if (
auto *F = dyn_cast<llvm::Function>(C))
1948 llvm::AttributeSet ExtraAttrs) {
1950 GetOrCreateLLVMFunction(Name, FTy,
GlobalDecl(),
false,
1951 false,
false, ExtraAttrs);
1952 if (
auto *F = dyn_cast<llvm::Function>(C))
1971 return ExcludeCtor && !Record->hasMutableFields() &&
1972 Record->hasTrivialDestructor();
1986 CodeGenModule::GetOrCreateLLVMGlobal(StringRef MangledName,
1987 llvm::PointerType *Ty,
1992 if (WeakRefReferences.erase(Entry)) {
1993 if (D && !D->
hasAttr<WeakAttr>())
1998 if (D && !D->
hasAttr<DLLImportAttr>() && !D->
hasAttr<DLLExportAttr>())
1999 Entry->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass);
2001 if (Entry->getType() == Ty)
2005 if (Entry->getType()->getAddressSpace() != Ty->getAddressSpace())
2006 return llvm::ConstantExpr::getAddrSpaceCast(Entry, Ty);
2008 return llvm::ConstantExpr::getBitCast(Entry, Ty);
2012 auto *GV =
new llvm::GlobalVariable(
2013 getModule(), Ty->getElementType(),
false,
2015 llvm::GlobalVariable::NotThreadLocal, AddrSpace);
2020 auto DDI = DeferredDecls.find(MangledName);
2021 if (DDI != DeferredDecls.end()) {
2024 addDeferredDeclToEmit(GV, DDI->second);
2025 DeferredDecls.erase(DDI);
2034 GV->setAlignment(
getContext().getDeclAlign(D).getQuantity());
2040 CXXThreadLocals.push_back(D);
2046 if (
getContext().isMSStaticDataMemberInlineDefinition(D)) {
2047 EmitGlobalVarDefinition(D);
2055 GV->setSection(
".cp.rodata");
2058 if (AddrSpace != Ty->getAddressSpace())
2059 return llvm::ConstantExpr::getAddrSpaceCast(GV, Ty);
2066 bool IsForDefinition) {
2067 if (isa<CXXConstructorDecl>(GD.
getDecl()))
2071 false, IsForDefinition);
2072 else if (isa<CXXDestructorDecl>(GD.
getDecl()))
2076 false, IsForDefinition);
2077 else if (isa<CXXMethodDecl>(GD.
getDecl())) {
2079 cast<CXXMethodDecl>(GD.
getDecl()));
2083 }
else if (isa<FunctionDecl>(GD.
getDecl())) {
2092 llvm::GlobalVariable *
2095 llvm::GlobalValue::LinkageTypes
Linkage) {
2096 llvm::GlobalVariable *GV =
getModule().getNamedGlobal(Name);
2097 llvm::GlobalVariable *OldGV =
nullptr;
2101 if (GV->getType()->getElementType() == Ty)
2106 assert(GV->isDeclaration() &&
"Declaration has wrong type!");
2111 GV =
new llvm::GlobalVariable(
getModule(), Ty,
true,
2112 Linkage,
nullptr, Name);
2116 GV->takeName(OldGV);
2118 if (!OldGV->use_empty()) {
2119 llvm::Constant *NewPtrForOldDecl =
2120 llvm::ConstantExpr::getBitCast(GV, OldGV->getType());
2121 OldGV->replaceAllUsesWith(NewPtrForOldDecl);
2124 OldGV->eraseFromParent();
2128 !GV->hasAvailableExternallyLinkage())
2129 GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
2145 llvm::PointerType *PTy =
2146 llvm::PointerType::get(Ty,
getContext().getTargetAddressSpace(ASTTy));
2149 return GetOrCreateLLVMGlobal(MangledName, PTy, D);
2157 return GetOrCreateLLVMGlobal(Name, llvm::PointerType::getUnqual(Ty),
nullptr);
2161 assert(!D->
getInit() &&
"Cannot emit definite definitions here!");
2163 if (!MustBeEmitted(D)) {
2169 DeferredDecls[MangledName] = D;
2175 EmitGlobalVarDefinition(D);
2184 unsigned AddrSpace) {
2185 if (LangOpts.CUDA && LangOpts.CUDAIsDevice) {
2186 if (D->
hasAttr<CUDAConstantAttr>())
2188 else if (D->
hasAttr<CUDASharedAttr>())
2197 template<
typename SomeDecl>
2199 llvm::GlobalValue *GV) {
2205 if (!D->template hasAttr<UsedAttr>())
2214 const SomeDecl *First = D->getFirstDecl();
2215 if (First->getDeclContext()->isRecord() || !First->isInExternCContext())
2221 std::pair<StaticExternCMap::iterator, bool> R =
2222 StaticExternCValues.insert(std::make_pair(D->getIdentifier(), GV));
2227 R.first->second =
nullptr;
2234 if (D.
hasAttr<SelectAnyAttr>())
2238 if (
auto *VD = dyn_cast<VarDecl>(&D))
2252 llvm_unreachable(
"No such linkage");
2256 llvm::GlobalObject &GO) {
2259 GO.setComdat(TheModule.getOrInsertComdat(GO.getName()));
2262 void CodeGenModule::EmitGlobalVarDefinition(
const VarDecl *D) {
2263 llvm::Constant *Init =
nullptr;
2266 bool NeedsGlobalCtor =
false;
2275 && D->
hasAttr<CUDASharedAttr>()) {
2278 if (C ==
nullptr || !C->getConstructor()->hasTrivialBody())
2280 "__shared__ variable cannot have an initialization.");
2282 Init = llvm::UndefValue::get(
getTypes().ConvertType(ASTTy));
2283 }
else if (!InitExpr) {
2306 NeedsGlobalCtor =
true;
2309 Init = llvm::UndefValue::get(
getTypes().ConvertType(T));
2316 DelayedCXXInitPosition.erase(D);
2324 if (
auto *CE = dyn_cast<llvm::ConstantExpr>(Entry)) {
2325 assert(CE->getOpcode() == llvm::Instruction::BitCast ||
2326 CE->getOpcode() == llvm::Instruction::AddrSpaceCast ||
2328 CE->getOpcode() == llvm::Instruction::GetElementPtr);
2329 Entry = CE->getOperand(0);
2333 auto *GV = dyn_cast<llvm::GlobalVariable>(Entry);
2345 GV->getType()->getElementType() != InitType ||
2346 GV->getType()->getAddressSpace() !=
2350 Entry->setName(StringRef());
2356 llvm::Constant *NewPtrForOldDecl =
2357 llvm::ConstantExpr::getBitCast(GV, Entry->getType());
2358 Entry->replaceAllUsesWith(NewPtrForOldDecl);
2361 cast<llvm::GlobalValue>(Entry)->eraseFromParent();
2366 if (D->
hasAttr<AnnotateAttr>())
2376 if (GV && LangOpts.CUDA && LangOpts.CUDAIsDevice &&
2377 (D->
hasAttr<CUDAConstantAttr>() || D->
hasAttr<CUDADeviceAttr>())) {
2378 GV->setExternallyInitialized(
true);
2380 GV->setInitializer(Init);
2383 GV->setConstant(!NeedsGlobalCtor && !NeedsGlobalDtor &&
2387 if (
const SectionAttr *SA = D->
getAttr<SectionAttr>()) {
2390 GV->setConstant(
true);
2393 GV->setAlignment(
getContext().getDeclAlign(D).getQuantity());
2396 llvm::GlobalValue::LinkageTypes
Linkage =
2408 !llvm::GlobalVariable::isLinkOnceLinkage(Linkage) &&
2409 !llvm::GlobalVariable::isWeakLinkage(Linkage))
2412 GV->setLinkage(Linkage);
2413 if (D->
hasAttr<DLLImportAttr>())
2414 GV->setDLLStorageClass(llvm::GlobalVariable::DLLImportStorageClass);
2415 else if (D->
hasAttr<DLLExportAttr>())
2416 GV->setDLLStorageClass(llvm::GlobalVariable::DLLExportStorageClass);
2418 GV->setDLLStorageClass(llvm::GlobalVariable::DefaultStorageClass);
2420 if (Linkage == llvm::GlobalVariable::CommonLinkage)
2422 GV->setConstant(
false);
2424 setNonAliasAttributes(D, GV);
2426 if (D->
getTLSKind() && !GV->isThreadLocal()) {
2428 CXXThreadLocals.push_back(D);
2435 if (NeedsGlobalCtor || NeedsGlobalDtor)
2436 EmitCXXGlobalVarDeclInitFunc(D, GV, NeedsGlobalCtor);
2438 SanitizerMD->reportGlobalToASan(GV, *D, NeedsGlobalCtor);
2443 DI->EmitGlobalVariable(GV, D);
2451 if ((NoCommon || D->
hasAttr<NoCommonAttr>()) && !D->
hasAttr<CommonAttr>())
2462 if (D->
hasAttr<SectionAttr>())
2470 if (D->
hasAttr<WeakImportAttr>())
2480 if (D->
hasAttr<AlignedAttr>())
2489 if (FD->isBitField())
2491 if (FD->
hasAttr<AlignedAttr>())
2508 if (IsConstantVariable)
2509 return llvm::GlobalVariable::WeakODRLinkage;
2511 return llvm::GlobalVariable::WeakAnyLinkage;
2517 return llvm::Function::AvailableExternallyLinkage;
2531 return !Context.
getLangOpts().AppleKext ? llvm::Function::LinkOnceODRLinkage
2539 return !Context.
getLangOpts().AppleKext ? llvm::Function::WeakODRLinkage
2546 CodeGenOpts.NoCommon))
2547 return llvm::GlobalVariable::CommonLinkage;
2553 if (D->
hasAttr<SelectAnyAttr>())
2554 return llvm::GlobalVariable::WeakODRLinkage;
2562 const VarDecl *VD,
bool IsConstant) {
2570 llvm::Function *newFn) {
2572 if (old->use_empty())
return;
2574 llvm::Type *newRetTy = newFn->getReturnType();
2578 for (llvm::Value::use_iterator ui = old->use_begin(), ue = old->use_end();
2580 llvm::Value::use_iterator use = ui++;
2581 llvm::User *user = use->getUser();
2585 if (
auto *bitcast = dyn_cast<llvm::ConstantExpr>(user)) {
2586 if (bitcast->getOpcode() == llvm::Instruction::BitCast)
2592 llvm::CallSite callSite(user);
2593 if (!callSite)
continue;
2594 if (!callSite.isCallee(&*use))
continue;
2598 if (callSite->getType() != newRetTy && !callSite->use_empty())
2603 llvm::AttributeSet oldAttrs = callSite.getAttributes();
2606 if (oldAttrs.hasAttributes(llvm::AttributeSet::ReturnIndex))
2608 llvm::AttributeSet::get(newFn->getContext(),
2609 oldAttrs.getRetAttributes()));
2612 unsigned newNumArgs = newFn->arg_size();
2613 if (callSite.arg_size() < newNumArgs)
continue;
2618 bool dontTransform =
false;
2619 for (llvm::Function::arg_iterator ai = newFn->arg_begin(),
2620 ae = newFn->arg_end(); ai != ae; ++ai, ++argNo) {
2621 if (callSite.getArgument(argNo)->getType() != ai->getType()) {
2622 dontTransform =
true;
2627 if (oldAttrs.hasAttributes(argNo + 1))
2630 AttributeSet::get(newFn->getContext(),
2631 oldAttrs.getParamAttributes(argNo + 1)));
2636 if (oldAttrs.hasAttributes(llvm::AttributeSet::FunctionIndex))
2637 newAttrs.push_back(llvm::AttributeSet::get(newFn->getContext(),
2638 oldAttrs.getFnAttributes()));
2642 newArgs.append(callSite.arg_begin(), callSite.arg_begin() + argNo);
2645 callSite.getOperandBundlesAsDefs(newBundles);
2647 llvm::CallSite newCall;
2648 if (callSite.isCall()) {
2650 callSite.getInstruction());
2652 auto *oldInvoke = cast<llvm::InvokeInst>(callSite.getInstruction());
2654 oldInvoke->getNormalDest(),
2655 oldInvoke->getUnwindDest(),
2656 newArgs, newBundles,
"",
2657 callSite.getInstruction());
2661 if (!newCall->getType()->isVoidTy())
2662 newCall->takeName(callSite.getInstruction());
2663 newCall.setAttributes(
2664 llvm::AttributeSet::get(newFn->getContext(), newAttrs));
2665 newCall.setCallingConv(callSite.getCallingConv());
2668 if (!callSite->use_empty())
2669 callSite->replaceAllUsesWith(newCall.getInstruction());
2672 if (callSite->getDebugLoc())
2673 newCall->setDebugLoc(callSite->getDebugLoc());
2675 callSite->eraseFromParent();
2689 llvm::Function *NewFn) {
2691 if (!isa<llvm::Function>(Old))
return;
2706 void CodeGenModule::EmitGlobalFunctionDefinition(
GlobalDecl GD,
2707 llvm::GlobalValue *GV) {
2708 const auto *D = cast<FunctionDecl>(GD.
getDecl());
2715 if (!GV || (GV->getType()->getElementType() != Ty))
2721 if (!GV->isDeclaration())
2728 auto *Fn = cast<llvm::Function>(GV);
2744 if (
const ConstructorAttr *CA = D->
getAttr<ConstructorAttr>())
2745 AddGlobalCtor(Fn, CA->getPriority());
2746 if (
const DestructorAttr *DA = D->
getAttr<DestructorAttr>())
2747 AddGlobalDtor(Fn, DA->getPriority());
2748 if (D->
hasAttr<AnnotateAttr>())
2752 void CodeGenModule::EmitAliasDefinition(
GlobalDecl GD) {
2753 const auto *D = cast<ValueDecl>(GD.
getDecl());
2754 const AliasAttr *AA = D->
getAttr<AliasAttr>();
2755 assert(AA &&
"Not an alias?");
2759 if (AA->getAliasee() == MangledName) {
2760 Diags.
Report(AA->getLocation(), diag::err_cyclic_alias);
2767 if (Entry && !Entry->isDeclaration())
2770 Aliases.push_back(GD);
2776 llvm::Constant *Aliasee;
2777 if (isa<llvm::FunctionType>(DeclTy))
2778 Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy, GD,
2781 Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(),
2782 llvm::PointerType::getUnqual(DeclTy),
2790 if (GA->getAliasee() == Entry) {
2791 Diags.
Report(AA->getLocation(), diag::err_cyclic_alias);
2795 assert(Entry->isDeclaration());
2804 GA->takeName(Entry);
2806 Entry->replaceAllUsesWith(llvm::ConstantExpr::getBitCast(GA,
2808 Entry->eraseFromParent();
2810 GA->setName(MangledName);
2818 GA->setLinkage(llvm::Function::WeakAnyLinkage);
2821 if (
const auto *VD = dyn_cast<VarDecl>(D))
2822 if (VD->getTLSKind())
2834 static llvm::StringMapEntry<llvm::GlobalVariable *> &
2837 bool &IsUTF16,
unsigned &StringLength) {
2838 StringRef String = Literal->
getString();
2839 unsigned NumBytes = String.size();
2843 StringLength = NumBytes;
2844 return *Map.insert(std::make_pair(String,
nullptr)).first;
2851 const UTF8 *FromPtr = (
const UTF8 *)String.data();
2852 UTF16 *ToPtr = &ToBuf[0];
2854 (void)ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes,
2855 &ToPtr, ToPtr + NumBytes,
2859 StringLength = ToPtr - &ToBuf[0];
2863 return *Map.insert(std::make_pair(
2864 StringRef(reinterpret_cast<const char *>(ToBuf.data()),
2865 (StringLength + 1) * 2),
2869 static llvm::StringMapEntry<llvm::GlobalVariable *> &
2872 StringRef String = Literal->
getString();
2873 StringLength = String.size();
2874 return *Map.insert(std::make_pair(String,
nullptr)).first;
2879 unsigned StringLength = 0;
2880 bool isUTF16 =
false;
2881 llvm::StringMapEntry<llvm::GlobalVariable *> &Entry =
2886 if (
auto *C = Entry.second)
2889 llvm::Constant *Zero = llvm::Constant::getNullValue(
Int32Ty);
2890 llvm::Constant *Zeros[] = { Zero, Zero };
2894 if (!CFConstantStringClassRef) {
2896 Ty = llvm::ArrayType::get(Ty, 0);
2898 "__CFConstantStringClassReference");
2900 V = llvm::ConstantExpr::getGetElementPtr(Ty, GV, Zeros);
2901 CFConstantStringClassRef = V;
2904 V = CFConstantStringClassRef;
2910 llvm::Constant *Fields[4];
2913 Fields[0] = cast<llvm::ConstantExpr>(V);
2917 Fields[1] = isUTF16 ? llvm::ConstantInt::get(Ty, 0x07d0) :
2918 llvm::ConstantInt::get(Ty, 0x07C8);
2921 llvm::Constant *C =
nullptr;
2923 auto Arr = llvm::makeArrayRef(
2924 reinterpret_cast<uint16_t *>(const_cast<char *>(Entry.first().data())),
2925 Entry.first().size() / 2);
2926 C = llvm::ConstantDataArray::get(VMContext, Arr);
2928 C = llvm::ConstantDataArray::getString(VMContext, Entry.first());
2934 new llvm::GlobalVariable(
getModule(), C->getType(),
true,
2935 llvm::GlobalValue::PrivateLinkage,
C,
".str");
2936 GV->setUnnamedAddr(
true);
2945 GV->setSection(
"__TEXT,__ustring");
2949 GV->setSection(
"__TEXT,__cstring,cstring_literals");
2954 llvm::ConstantExpr::getGetElementPtr(GV->getValueType(), GV, Zeros);
2958 Fields[2] = llvm::ConstantExpr::getBitCast(Fields[2],
Int8PtrTy);
2962 Fields[3] = llvm::ConstantInt::get(Ty, StringLength);
2967 C = llvm::ConstantStruct::get(STy, Fields);
2968 GV =
new llvm::GlobalVariable(
getModule(), C->getType(),
true,
2969 llvm::GlobalVariable::PrivateLinkage,
C,
2970 "_unnamed_cfstring_");
2971 GV->setSection(
"__DATA,__cfstring");
2980 unsigned StringLength = 0;
2981 llvm::StringMapEntry<llvm::GlobalVariable *> &Entry =
2984 if (
auto *C = Entry.second)
2987 llvm::Constant *Zero = llvm::Constant::getNullValue(
Int32Ty);
2988 llvm::Constant *Zeros[] = { Zero, Zero };
2991 if (!ConstantStringClassRef) {
2992 std::string StringClass(
getLangOpts().ObjCConstantStringClass);
2997 StringClass.empty() ?
"OBJC_CLASS_$_NSConstantString"
2998 :
"OBJC_CLASS_$_" + StringClass;
3001 llvm::Type *PTy = llvm::PointerType::getUnqual(Ty);
3002 V = llvm::ConstantExpr::getBitCast(GV, PTy);
3003 ConstantStringClassRef = V;
3006 StringClass.empty() ?
"_NSConstantStringClassReference"
3007 :
"_" + StringClass +
"ClassReference";
3008 llvm::Type *PTy = llvm::ArrayType::get(Ty, 0);
3011 V = llvm::ConstantExpr::getGetElementPtr(PTy, GV, Zeros);
3012 ConstantStringClassRef = V;
3015 V = ConstantStringClassRef;
3017 if (!NSConstantStringType) {
3032 for (
unsigned i = 0; i < 3; ++i) {
3036 FieldTypes[i],
nullptr,
3049 llvm::Constant *Fields[3];
3052 Fields[0] = cast<llvm::ConstantExpr>(V);
3056 llvm::ConstantDataArray::getString(VMContext, Entry.first());
3058 llvm::GlobalValue::LinkageTypes
Linkage;
3060 Linkage = llvm::GlobalValue::PrivateLinkage;
3061 isConstant = !LangOpts.WritableStrings;
3063 auto *GV =
new llvm::GlobalVariable(
getModule(), C->getType(), isConstant,
3065 GV->setUnnamedAddr(
true);
3071 llvm::ConstantExpr::getGetElementPtr(GV->getValueType(), GV, Zeros);
3075 Fields[2] = llvm::ConstantInt::get(Ty, StringLength);
3079 C = llvm::ConstantStruct::get(NSConstantStringType, Fields);
3080 GV =
new llvm::GlobalVariable(
getModule(), C->getType(),
true,
3081 llvm::GlobalVariable::PrivateLinkage,
C,
3082 "_unnamed_nsstring_");
3084 const char *NSStringSection =
"__OBJC,__cstring_object,regular,no_dead_strip";
3085 const char *NSStringNonFragileABISection =
3086 "__DATA,__objc_stringobj,regular,no_dead_strip";
3089 ? NSStringNonFragileABISection
3097 if (ObjCFastEnumerationStateType.
isNull()) {
3109 for (
size_t i = 0; i < 4; ++i) {
3114 FieldTypes[i],
nullptr,
3126 return ObjCFastEnumerationStateType;
3140 Str.resize(CAT->getSize().getZExtValue());
3141 return llvm::ConstantDataArray::getString(VMContext, Str,
false);
3145 llvm::Type *ElemTy = AType->getElementType();
3146 unsigned NumElements = AType->getNumElements();
3149 if (ElemTy->getPrimitiveSizeInBits() == 16) {
3151 Elements.reserve(NumElements);
3153 for(
unsigned i = 0, e = E->
getLength(); i != e; ++i)
3155 Elements.resize(NumElements);
3156 return llvm::ConstantDataArray::get(VMContext, Elements);
3159 assert(ElemTy->getPrimitiveSizeInBits() == 32);
3161 Elements.reserve(NumElements);
3163 for(
unsigned i = 0, e = E->
getLength(); i != e; ++i)
3165 Elements.resize(NumElements);
3166 return llvm::ConstantDataArray::get(VMContext, Elements);
3169 static llvm::GlobalVariable *
3174 unsigned AddrSpace = 0;
3180 auto *GV =
new llvm::GlobalVariable(
3181 M, C->getType(), !CGM.
getLangOpts().WritableStrings, LT,
C, GlobalName,
3182 nullptr, llvm::GlobalVariable::NotThreadLocal, AddrSpace);
3184 GV->setUnnamedAddr(
true);
3185 if (GV->isWeakForLinker()) {
3186 assert(CGM.
supportsCOMDAT() &&
"Only COFF uses weak string literals");
3187 GV->setComdat(M.getOrInsertComdat(GV->getName()));
3201 llvm::GlobalVariable **Entry =
nullptr;
3202 if (!LangOpts.WritableStrings) {
3203 Entry = &ConstantStringMap[
C];
3204 if (
auto GV = *Entry) {
3212 StringRef GlobalVariableName;
3213 llvm::GlobalValue::LinkageTypes LT;
3218 if (!LangOpts.WritableStrings &&
3221 llvm::raw_svector_ostream Out(MangledNameBuffer);
3224 LT = llvm::GlobalValue::LinkOnceODRLinkage;
3225 GlobalVariableName = MangledNameBuffer;
3227 LT = llvm::GlobalValue::PrivateLinkage;
3228 GlobalVariableName =
Name;
3235 SanitizerMD->reportGlobalToASan(GV, S->
getStrTokenLoc(0),
"<string literal>",
3254 const std::string &Str,
const char *GlobalName) {
3255 StringRef StrWithNull(Str.c_str(), Str.size() + 1);
3260 llvm::ConstantDataArray::getString(
getLLVMContext(), StrWithNull,
false);
3263 llvm::GlobalVariable **Entry =
nullptr;
3264 if (!LangOpts.WritableStrings) {
3265 Entry = &ConstantStringMap[
C];
3266 if (
auto GV = *Entry) {
3267 if (Alignment.getQuantity() > GV->getAlignment())
3268 GV->setAlignment(Alignment.getQuantity());
3275 GlobalName =
".str";
3278 GlobalName, Alignment);
3294 MaterializedType = E->
getType();
3298 if (llvm::Constant *Slot = MaterializedGlobalTemporaryMap[E])
3305 llvm::raw_svector_ostream Out(Name);
3307 VD, E->getManglingNumber(), Out);
3310 if (E->getStorageDuration() ==
SD_Static) {
3324 Value = &EvalResult.
Val;
3326 llvm::Constant *InitialValue =
nullptr;
3327 bool Constant =
false;
3333 Type = InitialValue->getType();
3341 llvm::GlobalValue::LinkageTypes Linkage =
3345 if (VD->isStaticDataMember() && VD->getAnyInitializer(InitVD) &&
3349 Linkage = llvm::GlobalVariable::LinkOnceODRLinkage;
3357 VD,
getContext().getTargetAddressSpace(MaterializedType));
3358 auto *GV =
new llvm::GlobalVariable(
3359 getModule(),
Type, Constant, Linkage, InitialValue, Name.c_str(),
3360 nullptr, llvm::GlobalVariable::NotThreadLocal,
3365 GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
3366 if (VD->getTLSKind())
3368 MaterializedGlobalTemporaryMap[
E] = GV;
3374 void CodeGenModule::EmitObjCPropertyImplementations(
const
3388 const_cast<ObjCImplementationDecl *>(D), PID);
3392 const_cast<ObjCImplementationDecl *>(D), PID);
3401 if (ivar->getType().isDestructedType())
3464 void CodeGenModule::EmitNamespace(
const NamespaceDecl *ND) {
3465 for (
auto *
I : ND->
decls()) {
3466 if (
const auto *VD = dyn_cast<VarDecl>(
I))
3482 for (
auto *
I : LSD->
decls()) {
3485 if (
auto *OID = dyn_cast<ObjCImplDecl>(
I)) {
3486 for (
auto *M : OID->methods())
3500 case Decl::CXXConversion:
3501 case Decl::CXXMethod:
3502 case Decl::Function:
3504 if (cast<FunctionDecl>(D)->getDescribedFunctionTemplate() ||
3505 cast<FunctionDecl>(D)->isLateTemplateParsed())
3516 if (cast<VarDecl>(D)->getDescribedVarTemplate())
3518 case Decl::VarTemplateSpecialization:
3524 case Decl::IndirectField:
3528 case Decl::Namespace:
3529 EmitNamespace(cast<NamespaceDecl>(D));
3532 case Decl::UsingShadow:
3533 case Decl::ClassTemplate:
3534 case Decl::VarTemplate:
3535 case Decl::VarTemplatePartialSpecialization:
3536 case Decl::FunctionTemplate:
3537 case Decl::TypeAliasTemplate:
3543 DI->EmitUsingDecl(cast<UsingDecl>(*D));
3545 case Decl::NamespaceAlias:
3547 DI->EmitNamespaceAlias(cast<NamespaceAliasDecl>(*D));
3549 case Decl::UsingDirective:
3551 DI->EmitUsingDirective(cast<UsingDirectiveDecl>(*D));
3553 case Decl::CXXConstructor:
3555 if (cast<FunctionDecl>(D)->getDescribedFunctionTemplate() ||
3556 cast<FunctionDecl>(D)->isLateTemplateParsed())
3561 case Decl::CXXDestructor:
3562 if (cast<FunctionDecl>(D)->isLateTemplateParsed())
3567 case Decl::StaticAssert:
3574 case Decl::ObjCInterface:
3575 case Decl::ObjCCategory:
3578 case Decl::ObjCProtocol: {
3579 auto *Proto = cast<ObjCProtocolDecl>(D);
3580 if (Proto->isThisDeclarationADefinition())
3585 case Decl::ObjCCategoryImpl:
3588 ObjCRuntime->GenerateCategory(cast<ObjCCategoryImplDecl>(D));
3591 case Decl::ObjCImplementation: {
3592 auto *OMD = cast<ObjCImplementationDecl>(D);
3593 EmitObjCPropertyImplementations(OMD);
3594 EmitObjCIvarInitializations(OMD);
3599 DI->getOrCreateInterfaceType(
getContext().getObjCInterfaceType(
3600 OMD->getClassInterface()), OMD->getLocation());
3603 case Decl::ObjCMethod: {
3604 auto *OMD = cast<ObjCMethodDecl>(D);
3610 case Decl::ObjCCompatibleAlias:
3611 ObjCRuntime->RegisterAlias(cast<ObjCCompatibleAliasDecl>(D));
3614 case Decl::LinkageSpec:
3615 EmitLinkageSpec(cast<LinkageSpecDecl>(D));
3618 case Decl::FileScopeAsm: {
3620 if (LangOpts.CUDA && LangOpts.CUDAIsDevice)
3623 if (LangOpts.OpenMPIsDevice)
3625 auto *AD = cast<FileScopeAsmDecl>(D);
3626 getModule().appendModuleInlineAsm(AD->getAsmString()->getString());
3630 case Decl::Import: {
3631 auto *Import = cast<ImportDecl>(D);
3634 if (Import->getImportedOwningModule())
3637 DI->EmitImportDecl(*Import);
3639 ImportedModules.insert(Import->getImportedModule());
3643 case Decl::OMPThreadPrivate:
3647 case Decl::ClassTemplateSpecialization: {
3648 const auto *Spec = cast<ClassTemplateSpecializationDecl>(D);
3651 Spec->hasDefinition())
3660 assert(isa<TypeDecl>(D) &&
"Unsupported decl kind");
3667 if (!CodeGenOpts.CoverageMapping)
3670 case Decl::CXXConversion:
3671 case Decl::CXXMethod:
3672 case Decl::Function:
3673 case Decl::ObjCMethod:
3674 case Decl::CXXConstructor:
3675 case Decl::CXXDestructor: {
3676 if (!cast<FunctionDecl>(D)->doesThisDeclarationHaveABody())
3678 auto I = DeferredEmptyCoverageMappingDecls.find(D);
3679 if (
I == DeferredEmptyCoverageMappingDecls.end())
3680 DeferredEmptyCoverageMappingDecls[D] =
true;
3690 if (!CodeGenOpts.CoverageMapping)
3692 if (
const auto *Fn = dyn_cast<FunctionDecl>(D)) {
3693 if (Fn->isTemplateInstantiation())
3696 auto I = DeferredEmptyCoverageMappingDecls.find(D);
3697 if (
I == DeferredEmptyCoverageMappingDecls.end())
3698 DeferredEmptyCoverageMappingDecls[D] =
false;
3704 std::vector<const Decl *> DeferredDecls;
3705 for (
const auto &
I : DeferredEmptyCoverageMappingDecls) {
3708 DeferredDecls.push_back(
I.first);
3712 if (CodeGenOpts.DumpCoverageMapping)
3713 std::sort(DeferredDecls.begin(), DeferredDecls.end(),
3714 [] (
const Decl *LHS,
const Decl *RHS) {
3717 for (
const auto *D : DeferredDecls) {
3719 case Decl::CXXConversion:
3720 case Decl::CXXMethod:
3721 case Decl::Function:
3722 case Decl::ObjCMethod: {
3729 case Decl::CXXConstructor: {
3736 case Decl::CXXDestructor: {
3752 uintptr_t PtrInt =
reinterpret_cast<uintptr_t
>(Ptr);
3753 llvm::Type *i64 = llvm::Type::getInt64Ty(Context);
3754 return llvm::ConstantInt::get(i64, PtrInt);
3758 llvm::NamedMDNode *&GlobalMetadata,
3760 llvm::GlobalValue *Addr) {
3761 if (!GlobalMetadata)
3763 CGM.
getModule().getOrInsertNamedMetadata(
"clang.global.decl.ptrs");
3766 llvm::Metadata *Ops[] = {llvm::ConstantAsMetadata::get(Addr),
3769 GlobalMetadata->addOperand(llvm::MDNode::get(CGM.
getLLVMContext(), Ops));
3777 void CodeGenModule::EmitStaticExternCAliases() {
3778 for (
auto &
I : StaticExternCValues) {
3780 llvm::GlobalValue *Val =
I.second;
3788 auto Res = Manglings.find(MangledName);
3789 if (Res == Manglings.end())
3791 Result = Res->getValue();
3802 void CodeGenModule::EmitDeclMetadata() {
3803 llvm::NamedMDNode *GlobalMetadata =
nullptr;
3805 for (
auto &
I : MangledDeclNames) {
3806 llvm::GlobalValue *Addr =
getModule().getNamedValue(
I.second);
3816 void CodeGenFunction::EmitDeclMetadata() {
3817 if (LocalDeclMap.empty())
return;
3822 unsigned DeclPtrKind = Context.getMDKindID(
"clang.decl.ptr");
3824 llvm::NamedMDNode *GlobalMetadata =
nullptr;
3826 for (
auto &
I : LocalDeclMap) {
3827 const Decl *D =
I.first;
3829 if (
auto *Alloca = dyn_cast<llvm::AllocaInst>(Addr)) {
3831 Alloca->setMetadata(
3832 DeclPtrKind, llvm::MDNode::get(
3833 Context, llvm::ValueAsMetadata::getConstant(DAddr)));
3834 }
else if (
auto *GV = dyn_cast<llvm::GlobalValue>(Addr)) {
3841 void CodeGenModule::EmitVersionIdentMetadata() {
3842 llvm::NamedMDNode *IdentMetadata =
3843 TheModule.getOrInsertNamedMetadata(
"llvm.ident");
3845 llvm::LLVMContext &Ctx = TheModule.getContext();
3847 llvm::Metadata *IdentNode[] = {llvm::MDString::get(Ctx, Version)};
3848 IdentMetadata->addOperand(llvm::MDNode::get(Ctx, IdentNode));
3851 void CodeGenModule::EmitTargetMetadata() {
3858 for (
unsigned I = 0;
I != MangledDeclNames.size(); ++
I) {
3859 auto Val = *(MangledDeclNames.begin() +
I);
3866 void CodeGenModule::EmitCoverageFile() {
3868 if (llvm::NamedMDNode *CUNode = TheModule.getNamedMetadata(
"llvm.dbg.cu")) {
3869 llvm::NamedMDNode *GCov = TheModule.getOrInsertNamedMetadata(
"llvm.gcov");
3870 llvm::LLVMContext &Ctx = TheModule.getContext();
3871 llvm::MDString *CoverageFile =
3873 for (
int i = 0, e = CUNode->getNumOperands(); i != e; ++i) {
3874 llvm::MDNode *CU = CUNode->getOperand(i);
3875 llvm::Metadata *Elts[] = {CoverageFile, CU};
3876 GCov->addOperand(llvm::MDNode::get(Ctx, Elts));
3882 llvm::Constant *CodeGenModule::EmitUuidofInitializer(StringRef Uuid) {
3885 assert(Uuid.size() == 36);
3886 for (
unsigned i = 0; i < 36; ++i) {
3887 if (i == 8 || i == 13 || i == 18 || i == 23) assert(Uuid[i] ==
'-');
3892 const unsigned Field3ValueOffsets[8] = { 19, 21, 24, 26, 28, 30, 32, 34 };
3894 llvm::Constant *Field3[8];
3895 for (
unsigned Idx = 0; Idx < 8; ++Idx)
3896 Field3[Idx] = llvm::ConstantInt::get(
3897 Int8Ty, Uuid.substr(Field3ValueOffsets[Idx], 2), 16);
3899 llvm::Constant *Fields[4] = {
3900 llvm::ConstantInt::get(
Int32Ty, Uuid.substr(0, 8), 16),
3901 llvm::ConstantInt::get(
Int16Ty, Uuid.substr(9, 4), 16),
3902 llvm::ConstantInt::get(
Int16Ty, Uuid.substr(14, 4), 16),
3903 llvm::ConstantArray::get(llvm::ArrayType::get(
Int8Ty, 8), Field3)
3906 return llvm::ConstantStruct::getAnon(Fields);
3915 return llvm::Constant::getNullValue(
Int8PtrTy);
3925 for (
auto RefExpr : D->
varlists()) {
3926 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(RefExpr)->getDecl());
3928 VD->getAnyInitializer() &&
3929 !VD->getAnyInitializer()->isConstantInitializer(
getContext(),
3934 VD, Addr, RefExpr->getLocStart(), PerformInit))
3935 CXXGlobalInits.push_back(InitFunction);
3945 std::string OutName;
3946 llvm::raw_string_ostream Out(OutName);
3959 llvm::GlobalVariable *VTable,
3962 llvm::Metadata *MD =
3964 llvm::Metadata *BitsetOps[] = {
3965 MD, llvm::ConstantAsMetadata::get(VTable),
3966 llvm::ConstantAsMetadata::get(
3968 BitsetsMD->addOperand(llvm::MDTuple::get(
getLLVMContext(), BitsetOps));
3970 if (CodeGenOpts.SanitizeCfiCrossDso) {
3972 llvm::Metadata *BitsetOps2[] = {
3973 llvm::ConstantAsMetadata::get(TypeId),
3974 llvm::ConstantAsMetadata::get(VTable),
3975 llvm::ConstantAsMetadata::get(
3977 BitsetsMD->addOperand(llvm::MDTuple::get(
getLLVMContext(), BitsetOps2));
3987 if (
const auto *TD = FD->
getAttr<TargetAttr>()) {
3989 TargetAttr::ParsedTargetAttr ParsedAttr = TD->parse();
3993 ParsedAttr.first.insert(ParsedAttr.first.begin(),
3997 if (ParsedAttr.second !=
"")
3998 TargetCPU = ParsedAttr.second;
void setLinkage(Linkage L)
llvm::PointerType * Int8PtrPtrTy
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
const ABIInfo & getABIInfo() const
getABIInfo() - Returns ABI info helper for the target.
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...
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()
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
StringRef getUuidAsStringRef(ASTContext &Context) const
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.
Decl - This represents one declaration (or definition), e.g.
llvm::MDNode * getTBAAStructInfo(QualType QTy)
virtual llvm::Function * emitThreadPrivateVarDefinition(const VarDecl *VD, Address VDAddr, SourceLocation Loc, bool PerformInit, CodeGenFunction *CGF=nullptr)
Emit a code for initialization of threadprivate variable.
virtual llvm::GlobalVariable * GetClassGlobal(const std::string &Name, bool Weak=false)=0
VarDecl * getDefinition(ASTContext &)
Get the real (not just tentative) definition for this declaration.
void setAliasAttributes(const Decl *D, llvm::GlobalValue *GV)
Set attributes which must be preserved by an alias.
Defines the C++ template declaration subclasses.
llvm::CallingConv::ID getRuntimeCC() const
bool isAlignmentRequired(const Type *T) const
Determine if the alignment the type has was required using an alignment attribute.
llvm::Type * FloatTy
float, double
std::string getAsString() const
const llvm::DataLayout & getDataLayout() const
FullSourceLoc getFullLoc(SourceLocation Loc) const
The base class of the type hierarchy.
bool isDependentContext() const
Determines whether this context is dependent on a template parameter.
void setFunctionLinkage(GlobalDecl GD, llvm::Function *F)
Stores additional source code information like skipped ranges which is required by the coverage mappi...
Emit only debug info necessary for generating line number tables (-gline-tables-only).
void GenerateObjCSetter(ObjCImplementationDecl *IMP, const ObjCPropertyImplDecl *PID)
GenerateObjCSetter - Synthesize an Objective-C property setter function for the given property...
std::unique_ptr< llvm::MemoryBuffer > Buffer
DiagnosticBuilder Report(SourceLocation Loc, unsigned DiagID)
Issue the message to the client.
void GenerateCode(GlobalDecl GD, llvm::Function *Fn, const CGFunctionInfo &FnInfo)
const Expr * getInit() const
NamespaceDecl - Represent a C++ namespace.
Represents a call to a C++ constructor.
static void setLinkageAndVisibilityForGV(llvm::GlobalValue *GV, const NamedDecl *ND)
virtual void completeDefinition()
completeDefinition - Notes that the definition of this type is now complete.
bool isWeakImported() const
Determine whether this is a weak-imported symbol.
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.
llvm::Constant * GetAddrOfGlobalVar(const VarDecl *D, llvm::Type *Ty=nullptr)
Return the llvm::Constant for the address of the given global variable.
llvm::Type * ConvertTypeForMem(QualType T)
ConvertTypeForMem - Convert type T into a llvm::Type.
void completeTemplateDefinition(const ClassTemplateSpecializationDecl &SD)
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.
llvm::CallingConv::ID getRuntimeCC() const
Return the calling convention to use for system runtime functions.
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).
unsigned getMaxAlignment() const
getMaxAlignment - return the maximum alignment specified by attributes on this decl, 0 if there are none.
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
StructorType getFromDtorType(CXXDtorType T)
void startDefinition()
Starts the definition of this tag declaration.
This declaration is definitely a definition.
void GenerateObjCCtorDtorMethod(ObjCImplementationDecl *IMP, ObjCMethodDecl *MD, bool ctor)
llvm::MDNode * getTBAAInfoForVTablePtr()
getTBAAInfoForVTablePtr - Get the TBAA MDNode to be used for a dereference of a vtable pointer...
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)
CGOpenMPRuntime(CodeGenModule &CGM)
bool isBlacklistedLocation(SourceLocation Loc, StringRef Category=StringRef()) const
uint32_t getCodeUnit(size_t i) const
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).
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.
DeclContext * getLexicalDeclContext()
getLexicalDeclContext - The declaration context where this Decl was lexically declared (LexicalDC)...
const CGFunctionInfo & arrangeCXXMethodDeclaration(const CXXMethodDecl *MD)
Arrange the argument and result information for a declaration or definition of the given C++ non-stat...
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)
A class that does preorder depth-first traversal on the entire Clang AST and visits each node...
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
ID
Defines the set of possible language-specific address spaces.
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)
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)
'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...
llvm::MDNode * getTBAAScalarTagInfo(llvm::MDNode *AccessNode)
Get the scalar tag MDNode for a given scalar type.
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.
Defines version macros and version-related utility functions for Clang.
Decl * getMostRecentDecl()
Retrieve the most recent declaration that declares the same entity as this declaration (which may be ...
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...
const char * getBufferName(SourceLocation Loc, bool *Invalid=nullptr) const
Return the filename or buffer identifier of the buffer the location is in.
DeclContext * getDeclContext()
ASTContext & getContext() const
unsigned getExpansionLineNumber(SourceLocation Loc, bool *Invalid=nullptr) const
static CharUnits fromQuantity(QuantityType Quantity)
fromQuantity - Construct a CharUnits quantity from a raw integer type.
static llvm::StringMapEntry< llvm::GlobalVariable * > & GetConstantCFStringEntry(llvm::StringMap< llvm::GlobalVariable * > &Map, const StringLiteral *Literal, bool TargetIsLSB, bool &IsUTF16, unsigned &StringLength)
llvm::SmallVector< LinkLibrary, 2 > LinkLibraries
The set of libraries or frameworks to link against when an entity from this module is used...
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.
CharUnits toCharUnitsFromBits(int64_t BitSize) const
Convert a size in bits to a size in characters.
llvm::IntegerType * Int32Ty
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::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.
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)
Creates clause with a list of variables VL and a linear step Step.
static bool isVarDeclStrongDefinition(const ASTContext &Context, CodeGenModule &CGM, const VarDecl *D, bool NoCommon)
llvm::Function * getIntrinsic(unsigned IID, ArrayRef< llvm::Type * > Tys=None)
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
bool lookupRepresentativeDecl(StringRef MangledName, GlobalDecl &Result) const
CallingConv
CallingConv - Specifies the calling convention that a function uses.
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.
llvm::CallingConv::ID getBuiltinCC() const
Return the calling convention to use for compiler builtins.
SourceLocation getLocStart() const LLVM_READONLY
unsigned char IntAlignInBytes
virtual llvm::Function * makeModuleDtorFunction()=0
Returns a module cleanup function or nullptr if it's not needed.
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.
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
IdentifierInfo & get(StringRef Name)
Return the identifier token info for the specified named identifier.
const Type * getTypePtr() const
Retrieves a pointer to the underlying (unqualified) type.
'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)"...
bool isConstant(ASTContext &Ctx) const
TagDecl - Represents the declaration of a struct/union/class/enum.
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.
const ConstantArrayType * getAsConstantArrayType(QualType T) const
SourceLocation getStrTokenLoc(unsigned TokNum) const
std::string InstrProfileInput
Name of the profile file to use as input for -fprofile-instr-use.
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
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?
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.
llvm::MDNode * getTBAAStructInfo(QualType QTy)
getTBAAStructInfo - Get the TBAAStruct MDNode to be used for a memcpy of the given type...
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.
llvm::MDNode * getTBAAStructTagInfo(QualType BaseQType, llvm::MDNode *AccessNode, uint64_t Offset)
Get the tag MDNode for a given base type, the actual scalar access MDNode and offset into the base ty...
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)
static const llvm::GlobalObject * getAliasedGlobal(const llvm::GlobalAlias &GA)
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.
void CreateFunctionBitSetEntry(const FunctionDecl *FD, llvm::Function *F)
Create a bitset entry for the given function and add it to BitsetsMD.
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)
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.
virtual llvm::Function * makeModuleCtorFunction()=0
Constructs and returns a module initialization function or nullptr if it's not needed.
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.
llvm::ConstantInt * CreateCfiIdForTypeMetadata(llvm::Metadata *MD)
Generate a cross-DSO type identifier for type.
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.
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
llvm::MDNode * getTBAAInfo(QualType QTy)
getTBAAInfo - Get the TBAA MDNode to be used for a dereference of the given type. ...
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
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.
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)
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
llvm::iterator_range< specific_attr_iterator< T > > specific_attrs() const
A specialization of Address that requires the address to be an LLVM Constant.
ObjCIvarDecl - Represents an ObjC instance variable.
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.
void CreateVTableBitSetEntry(llvm::NamedMDNode *BitsetsMD, llvm::GlobalVariable *VTable, CharUnits Offset, const CXXRecordDecl *RD)
Create a bitset entry for the given vtable and add it to BitsetsMD.
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]).
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)
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...
QualType getObjCFastEnumerationStateType()
Retrieve the record type that describes the state of an Objective-C fast enumeration loop (for...
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()
SourceLocation getLocation() const
NamedDecl - This represents a decl with a name.
ObjCIvarDecl * all_declared_ivar_begin()
all_declared_ivar_begin - return first ivar declared in this class, its extensions and its implementa...
void setAccess(AccessSpecifier AS)
static void replaceUsesOfNonProtoConstant(llvm::Constant *old, llvm::Function *newFn)
Replace the uses of a function that was declared with a non-proto type.
bool DeclMustBeEmitted(const Decl *D)
Determines if the decl can be CodeGen'ed or deserialized from PCH lazily, only when used; this is onl...
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.