39#include "llvm/ADT/ArrayRef.h"
40#include "llvm/ADT/ScopeExit.h"
41#include "llvm/ADT/StringExtras.h"
42#include "llvm/Frontend/OpenMP/OMPIRBuilder.h"
43#include "llvm/IR/DataLayout.h"
44#include "llvm/IR/Dominators.h"
45#include "llvm/IR/FPEnv.h"
46#include "llvm/IR/Instruction.h"
47#include "llvm/IR/IntrinsicInst.h"
48#include "llvm/IR/Intrinsics.h"
49#include "llvm/IR/MDBuilder.h"
50#include "llvm/Support/CRC.h"
51#include "llvm/Support/SaveAndRestore.h"
52#include "llvm/Support/SipHash.h"
53#include "llvm/Support/xxhash.h"
54#include "llvm/Transforms/Scalar/LowerExpectIntrinsic.h"
55#include "llvm/Transforms/Utils/PromoteMemToReg.h"
61CodeGenFunction::CodeGenFunction(
CodeGenModule &cgm,
bool suppressNewContext)
65 DebugInfo(
CGM.getModuleDebugInfo()),
67 ShouldEmitLifetimeMarkers(
CodeGenUtils::shouldEmitLifetimeMarkers(
69 if (!suppressNewContext)
70 CGM.getCXXABI().getMangleContext().startNewFunction();
77 const auto *FD = dyn_cast_or_null<FunctionDecl>(
CurCodeDecl);
86 "missed to deactivate a cleanup");
89 CGM.getOpenMPRuntime().functionFinished(*
this);
95 llvm::OpenMPIRBuilder &OMPBuilder =
CGM.getOpenMPRuntime().getOMPBuilder();
96 if (
CGM.getLangOpts().OpenMPIRBuilder ||
97 OMPBuilder.hasPendingOutlines(
CurFn))
98 OMPBuilder.finalize(
CurFn);
104llvm::fp::ExceptionBehavior
112 llvm_unreachable(
"Unsupported FP Exception Behavior");
117 llvm::FastMathFlags FMF;
118 FMF.setAllowReassoc(FPFeatures.getAllowFPReassociate());
119 FMF.setNoNaNs(FPFeatures.getNoHonorNaNs());
120 FMF.setNoInfs(FPFeatures.getNoHonorInfs());
121 FMF.setNoSignedZeros(FPFeatures.getNoSignedZero());
122 FMF.setAllowReciprocal(FPFeatures.getAllowReciprocal());
123 FMF.setApproxFunc(FPFeatures.getAllowApproxFunc());
137 ConstructorHelper(FPFeatures);
140void CodeGenFunction::CGFPOptionsRAII::ConstructorHelper(
FPOptions FPFeatures) {
141 OldFPFeatures = CGF.CurFPFeatures;
142 CGF.CurFPFeatures = FPFeatures;
144 OldExcept = CGF.Builder.getDefaultConstrainedExcept();
145 OldRounding = CGF.Builder.getDefaultConstrainedRounding();
147 if (OldFPFeatures == FPFeatures)
150 FMFGuard.emplace(CGF.Builder);
153 CGF.Builder.setDefaultConstrainedRounding(NewRoundingBehavior);
154 auto NewExceptionBehavior =
156 CGF.Builder.setDefaultConstrainedExcept(NewExceptionBehavior);
158 CGF.SetFastMathFlags(FPFeatures);
160 assert((CGF.CurFuncDecl ==
nullptr || CGF.Builder.getIsFPConstrained() ||
163 (NewExceptionBehavior == llvm::fp::ebIgnore &&
164 NewRoundingBehavior == llvm::RoundingMode::NearestTiesToEven)) &&
165 "FPConstrained should be enabled on entire function");
167 auto mergeFnAttrValue = [&](StringRef Name,
bool Value) {
169 CGF.CurFn->getFnAttribute(Name).getValueAsBool();
170 auto NewValue = OldValue &
Value;
171 if (OldValue != NewValue)
172 CGF.CurFn->addFnAttr(Name, llvm::toStringRef(NewValue));
174 mergeFnAttrValue(
"no-signed-zeros-fp-math", FPFeatures.getNoSignedZero());
178 CGF.CurFPFeatures = OldFPFeatures;
179 CGF.Builder.setDefaultConstrainedExcept(OldExcept);
180 CGF.Builder.setDefaultConstrainedRounding(OldRounding);
194 nullptr, IsKnownNonNull)
202 return ::makeNaturalAlignAddrLValue(
V, T,
false,
209 return ::makeNaturalAlignAddrLValue(
V, T,
true,
215 return ::makeNaturalAlignAddrLValue(
V, T,
false,
221 return ::makeNaturalAlignAddrLValue(
V, T,
true,
226 return CGM.getTypes().ConvertTypeForMem(T);
230 return CGM.getTypes().ConvertType(T);
234 llvm::Type *LLVMTy) {
235 return CGM.getTypes().convertTypeForLoadStore(ASTTy, LLVMTy);
241 switch (
type->getTypeClass()) {
242#define TYPE(name, parent)
243#define ABSTRACT_TYPE(name, parent)
244#define NON_CANONICAL_TYPE(name, parent) case Type::name:
245#define DEPENDENT_TYPE(name, parent) case Type::name:
246#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(name, parent) case Type::name:
247#include "clang/AST/TypeNodes.inc"
248 llvm_unreachable(
"non-canonical or dependent type in IR-generation");
251 case Type::DeducedTemplateSpecialization:
252 llvm_unreachable(
"undeduced type in IR-generation");
257 case Type::BlockPointer:
258 case Type::LValueReference:
259 case Type::RValueReference:
260 case Type::MemberPointer:
262 case Type::ExtVector:
263 case Type::ConstantMatrix:
264 case Type::CooperativeMatrix:
265 case Type::FunctionProto:
266 case Type::FunctionNoProto:
268 case Type::ObjCObjectPointer:
271 case Type::HLSLAttributedResource:
272 case Type::HLSLInlineSpirv:
273 case Type::OverflowBehavior:
281 case Type::ConstantArray:
282 case Type::IncompleteArray:
283 case Type::VariableArray:
285 case Type::ObjCObject:
286 case Type::ObjCInterface:
287 case Type::ArrayParameter:
295 llvm_unreachable(
"unknown type kind!");
302 llvm::BasicBlock *CurBB =
Builder.GetInsertBlock();
305 assert(!CurBB->hasTerminator() &&
"Unexpected terminated block.");
309 if (CurBB->empty() ||
ReturnBlock.getBlock()->use_empty()) {
315 return llvm::DebugLoc();
323 dyn_cast<llvm::UncondBrInst>(*
ReturnBlock.getBlock()->user_begin());
324 if (BI && BI->getSuccessor(0) ==
ReturnBlock.getBlock()) {
327 llvm::DebugLoc Loc = BI->getDebugLoc();
328 Builder.SetInsertPoint(BI->getParent());
329 BI->eraseFromParent();
341 return llvm::DebugLoc();
346 if (!BB->use_empty()) {
354 assert(BreakContinueStack.empty() &&
355 "mismatched push/pop in break/continue stack!");
357 "mismatched push/pop of cleanups in EHStack!");
359 "mismatched activate/deactivate of cleanups!");
361 if (
CGM.shouldEmitConvergenceTokens()) {
364 "mismatched push/pop in convergence stack!");
367 bool OnlySimpleReturnStmts = NumSimpleReturnExprs > 0
368 && NumSimpleReturnExprs == NumReturnExprs
383 if (OnlySimpleReturnStmts)
384 DI->EmitLocation(
Builder, LastStopPoint);
386 DI->EmitLocation(
Builder, EndLoc);
394 bool HasOnlyNoopCleanups =
396 bool EmitRetDbgLoc = !HasCleanups || HasOnlyNoopCleanups;
398 std::optional<ApplyDebugLocation> OAL;
403 if (OnlySimpleReturnStmts)
404 DI->EmitLocation(
Builder, EndLoc);
418 if (
CGM.getCodeGenOpts().InstrumentFunctions)
419 CurFn->addFnAttr(
"instrument-function-exit",
"__cyg_profile_func_exit");
420 if (
CGM.getCodeGenOpts().InstrumentFunctionsAfterInlining)
421 CurFn->addFnAttr(
"instrument-function-exit-inlined",
422 "__cyg_profile_func_exit");
431 uint64_t RetKeyInstructionsAtomGroup = Loc ? Loc->getAtomGroup() : 0;
434 RetKeyInstructionsAtomGroup);
438 "did not remove all scopes from cleanup stack!");
442 if (IndirectBranch) {
449 if (!EscapedLocals.empty()) {
453 EscapeArgs.resize(EscapedLocals.size());
454 for (
auto &Pair : EscapedLocals)
455 EscapeArgs[Pair.second] = Pair.first;
456 llvm::Function *FrameEscapeFn = llvm::Intrinsic::getOrInsertDeclaration(
457 &
CGM.getModule(), llvm::Intrinsic::localescape);
464 Ptr->eraseFromParent();
468 if (PostAllocaInsertPt) {
469 llvm::Instruction *PostPtr = PostAllocaInsertPt;
470 PostAllocaInsertPt =
nullptr;
471 PostPtr->eraseFromParent();
476 if (IndirectBranch) {
478 if (PN->getNumIncomingValues() == 0) {
479 PN->replaceAllUsesWith(llvm::PoisonValue::get(PN->getType()));
480 PN->eraseFromParent();
489 for (
const auto &FuncletAndParent : TerminateFunclets)
492 if (
CGM.getCodeGenOpts().EmitDeclMetadata)
495 for (
const auto &R : DeferredReplacements) {
496 if (llvm::Value *Old = R.first) {
497 Old->replaceAllUsesWith(R.second);
501 DeferredReplacements.clear();
510 llvm::DominatorTree DT(*
CurFn);
511 llvm::PromoteMemToReg(
517 for (llvm::Argument &A :
CurFn->args())
518 if (
auto *VT = dyn_cast<llvm::VectorType>(A.getType()))
520 std::max((uint64_t)LargestVectorWidth,
521 VT->getPrimitiveSizeInBits().getKnownMinValue());
524 if (
auto *VT = dyn_cast<llvm::VectorType>(
CurFn->getReturnType()))
526 std::max((uint64_t)LargestVectorWidth,
527 VT->getPrimitiveSizeInBits().getKnownMinValue());
529 if (
CurFnInfo->getMaxVectorWidth() > LargestVectorWidth)
530 LargestVectorWidth =
CurFnInfo->getMaxVectorWidth();
540 CurFn->addFnAttr(
"min-legal-vector-width",
541 llvm::utostr(LargestVectorWidth));
550 dyn_cast<llvm::AllocaInst>(
ReturnValue.emitRawPointer(*
this));
551 if (RetAlloca && RetAlloca->use_empty()) {
552 RetAlloca->eraseFromParent();
561 if (!
CGM.getCodeGenOpts().InstrumentFunctions &&
562 !
CGM.getCodeGenOpts().InstrumentFunctionsAfterInlining &&
563 !
CGM.getCodeGenOpts().InstrumentFunctionEntryBare)
573 return CurFuncDecl->hasAttr<DisableSanitizerInstrumentationAttr>();
579 return CGM.getCodeGenOpts().XRayInstrumentFunctions;
585 return CGM.getCodeGenOpts().XRayInstrumentFunctions &&
586 (
CGM.getCodeGenOpts().XRayAlwaysEmitCustomEvents ||
587 CGM.getCodeGenOpts().XRayInstrumentationBundle.Mask ==
592 return CGM.getCodeGenOpts().XRayInstrumentFunctions &&
593 (
CGM.getCodeGenOpts().XRayAlwaysEmitTypedEvents ||
594 CGM.getCodeGenOpts().XRayInstrumentationBundle.Mask ==
605 llvm::raw_string_ostream Out(Mangled);
606 CGM.getCXXABI().getMangleContext().mangleCanonicalTypeName(Ty, Out,
false);
607 return llvm::ConstantInt::get(
608 CGM.Int32Ty,
static_cast<uint32_t
>(llvm::xxh3_64bits(Mangled)));
611void CodeGenFunction::EmitKernelMetadata(
const FunctionDecl *FD,
612 llvm::Function *Fn) {
613 if (!FD->
hasAttr<DeviceKernelAttr>() && !FD->
hasAttr<CUDAGlobalAttr>())
625 if (
const VecTypeHintAttr *A = FD->
getAttr<VecTypeHintAttr>()) {
626 QualType HintQTy = A->getTypeHint();
628 bool IsSignedInteger =
630 (HintEltQTy && HintEltQTy->
getElementType()->isSignedIntegerType());
631 llvm::Metadata *AttrMDArgs[] = {
632 llvm::ConstantAsMetadata::get(llvm::PoisonValue::get(
634 llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
635 llvm::IntegerType::get(Context, 32),
636 llvm::APInt(32, (uint64_t)(IsSignedInteger ? 1 : 0))))};
637 Fn->setMetadata(
"vec_type_hint", llvm::MDNode::get(Context, AttrMDArgs));
640 if (
const WorkGroupSizeHintAttr *A = FD->
getAttr<WorkGroupSizeHintAttr>()) {
641 auto Eval = [&](
Expr *E) {
642 return E->EvaluateKnownConstInt(FD->
getASTContext()).getExtValue();
644 llvm::Metadata *AttrMDArgs[] = {
645 llvm::ConstantAsMetadata::get(
Builder.getInt32(Eval(A->getXDim()))),
646 llvm::ConstantAsMetadata::get(
Builder.getInt32(Eval(A->getYDim()))),
647 llvm::ConstantAsMetadata::get(
Builder.getInt32(Eval(A->getZDim())))};
648 Fn->setMetadata(
"work_group_size_hint", llvm::MDNode::get(Context, AttrMDArgs));
651 if (
const ReqdWorkGroupSizeAttr *A = FD->
getAttr<ReqdWorkGroupSizeAttr>()) {
652 auto Eval = [&](Expr *E) {
653 return E->EvaluateKnownConstInt(FD->
getASTContext()).getExtValue();
655 llvm::Metadata *AttrMDArgs[] = {
656 llvm::ConstantAsMetadata::get(
Builder.getInt32(Eval(A->getXDim()))),
657 llvm::ConstantAsMetadata::get(
Builder.getInt32(Eval(A->getYDim()))),
658 llvm::ConstantAsMetadata::get(
Builder.getInt32(Eval(A->getZDim())))};
659 Fn->setMetadata(
"reqd_work_group_size", llvm::MDNode::get(Context, AttrMDArgs));
662 if (
const OpenCLIntelReqdSubGroupSizeAttr *A =
663 FD->
getAttr<OpenCLIntelReqdSubGroupSizeAttr>()) {
664 llvm::Metadata *AttrMDArgs[] = {
665 llvm::ConstantAsMetadata::get(
Builder.getInt32(A->getSubGroupSize()))};
666 Fn->setMetadata(
"intel_reqd_sub_group_size",
667 llvm::MDNode::get(Context, AttrMDArgs));
673 const Stmt *Body =
nullptr;
674 if (
auto *FD = dyn_cast_or_null<FunctionDecl>(F))
676 else if (
auto *OMD = dyn_cast_or_null<ObjCMethodDecl>(F))
677 Body = OMD->getBody();
679 if (
auto *CS = dyn_cast_or_null<CompoundStmt>(Body)) {
680 auto LastStmt = CS->body_rbegin();
681 if (LastStmt != CS->body_rend())
688 if (
SanOpts.has(SanitizerKind::Thread)) {
689 Fn->addFnAttr(
"sanitize_thread_no_checking_at_run_time");
690 Fn->removeFnAttr(llvm::Attribute::SanitizeThread);
692 if (
SanOpts.has(SanitizerKind::Concurrency)) {
693 Fn->addFnAttr(
"sanitize_concurrency_no_checking_at_run_time");
694 Fn->removeFnAttr(llvm::Attribute::SanitizeConcurrency);
699bool CodeGenFunction::requiresReturnValueCheck()
const {
700 return requiresReturnValueNullabilityCheck() ||
710 auto *MD = dyn_cast_or_null<CXXMethodDecl>(D);
711 if (!MD || !MD->getDeclName().getAsIdentifierInfo() ||
712 !MD->getDeclName().getAsIdentifierInfo()->isStr(
"allocate") ||
713 (MD->getNumParams() != 1 && MD->getNumParams() != 2))
719 if (MD->getNumParams() == 2) {
720 auto *PT = MD->parameters()[1]->getType()->getAs<
PointerType>();
721 if (!PT || !PT->isVoidPointerType() ||
722 !PT->getPointeeType().isConstQualified())
729bool CodeGenFunction::isInAllocaArgument(
CGCXXABI &ABI, QualType Ty) {
734bool CodeGenFunction::hasInAllocaArg(
const CXXMethodDecl *MD) {
737 llvm::any_of(MD->
parameters(), [&](ParmVarDecl *P) {
738 return isInAllocaArgument(CGM.getCXXABI(), P->getType());
745 if (
const auto *MD = dyn_cast<CXXMethodDecl>(FD))
758 "Do not use a CodeGenFunction object for more than one function");
762 DidCallStackSave =
false;
764 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
767 if (
const Stmt *Body = D ? D->
getBody() :
nullptr) {
770 ShouldEmitLifetimeMarkers =
true;
773 bool NeedsBypassDetection =
774 ShouldEmitLifetimeMarkers ||
775 (
CGM.getLangOpts().getTrivialAutoVarInit() !=
777 if (NeedsBypassDetection)
784 assert(
CurFn->isDeclaration() &&
"Function already has body?");
789#define SANITIZER(NAME, ID) \
790 if (SanOpts.empty()) \
792 if (SanOpts.has(SanitizerKind::ID)) \
793 if (CGM.isInNoSanitizeList(SanitizerKind::ID, Fn, Loc)) \
794 SanOpts.set(SanitizerKind::ID, false);
796#include "clang/Basic/Sanitizers.def"
801 const bool SanitizeBounds =
SanOpts.hasOneOf(SanitizerKind::Bounds);
803 bool NoSanitizeCoverage =
false;
806 no_sanitize_mask |=
Attr->getMask();
808 if (
Attr->hasCoverage())
809 NoSanitizeCoverage =
true;
813 SanOpts.Mask &= ~no_sanitize_mask;
814 if (no_sanitize_mask & SanitizerKind::Address)
815 SanOpts.set(SanitizerKind::KernelAddress,
false);
816 if (no_sanitize_mask & SanitizerKind::KernelAddress)
817 SanOpts.set(SanitizerKind::Address,
false);
818 if (no_sanitize_mask & SanitizerKind::HWAddress)
819 SanOpts.set(SanitizerKind::KernelHWAddress,
false);
820 if (no_sanitize_mask & SanitizerKind::KernelHWAddress)
821 SanOpts.set(SanitizerKind::HWAddress,
false);
823 if (SanitizeBounds && !
SanOpts.hasOneOf(SanitizerKind::Bounds))
824 Fn->addFnAttr(llvm::Attribute::NoSanitizeBounds);
826 if (NoSanitizeCoverage &&
CGM.getCodeGenOpts().hasSanitizeCoverage())
827 Fn->addFnAttr(llvm::Attribute::NoSanitizeCoverage);
830 if (
CGM.getCodeGenOpts().hasSanitizeBinaryMetadata()) {
831 if (no_sanitize_mask & SanitizerKind::Thread)
832 Fn->addFnAttr(
"no_sanitize_thread");
837 CurFn->addFnAttr(llvm::Attribute::DisableSanitizerInstrumentation);
840 if (
SanOpts.hasOneOf(SanitizerKind::Address | SanitizerKind::KernelAddress))
841 Fn->addFnAttr(llvm::Attribute::SanitizeAddress);
842 if (
SanOpts.hasOneOf(SanitizerKind::HWAddress |
843 SanitizerKind::KernelHWAddress))
844 Fn->addFnAttr(llvm::Attribute::SanitizeHWAddress);
845 if (
SanOpts.has(SanitizerKind::MemtagStack))
846 Fn->addFnAttr(llvm::Attribute::SanitizeMemTag);
847 if (
SanOpts.has(SanitizerKind::Thread))
848 Fn->addFnAttr(llvm::Attribute::SanitizeThread);
849 if (
SanOpts.has(SanitizerKind::Concurrency))
850 Fn->addFnAttr(llvm::Attribute::SanitizeConcurrency);
851 if (
SanOpts.has(SanitizerKind::Type))
852 Fn->addFnAttr(llvm::Attribute::SanitizeType);
853 if (
SanOpts.has(SanitizerKind::NumericalStability))
854 Fn->addFnAttr(llvm::Attribute::SanitizeNumericalStability);
855 if (
SanOpts.hasOneOf(SanitizerKind::Memory | SanitizerKind::KernelMemory))
856 Fn->addFnAttr(llvm::Attribute::SanitizeMemory);
857 if (
SanOpts.has(SanitizerKind::AllocToken))
858 Fn->addFnAttr(llvm::Attribute::SanitizeAllocToken);
860 if (
SanOpts.has(SanitizerKind::SafeStack))
861 Fn->addFnAttr(llvm::Attribute::SafeStack);
862 if (
SanOpts.has(SanitizerKind::ShadowCallStack))
863 Fn->addFnAttr(llvm::Attribute::ShadowCallStack);
865 if (
SanOpts.has(SanitizerKind::Realtime))
869 Fn->addFnAttr(llvm::Attribute::SanitizeRealtime);
871 Fn->addFnAttr(llvm::Attribute::SanitizeRealtimeBlocking);
875 if (
SanOpts.hasOneOf(SanitizerKind::Fuzzer | SanitizerKind::FuzzerNoLink))
876 Fn->addFnAttr(llvm::Attribute::OptForFuzzing);
881 if (
SanOpts.hasOneOf(SanitizerKind::Thread | SanitizerKind::Concurrency)) {
882 if (
const auto *OMD = dyn_cast_or_null<ObjCMethodDecl>(D)) {
883 const IdentifierInfo *II = OMD->getSelector().getIdentifierInfoForSlot(0);
886 (OMD->getSelector().isUnarySelector() && II->
isStr(
".cxx_destruct"))) {
895 if (D &&
SanOpts.has(SanitizerKind::CFIUnrelatedCast)) {
903 if (D &&
SanOpts.has(SanitizerKind::Null))
909 bool AlwaysXRayAttr =
false;
910 if (
const auto *XRayAttr = D ? D->
getAttr<XRayInstrumentAttr>() :
nullptr) {
911 if (
CGM.getCodeGenOpts().XRayInstrumentationBundle.has(
913 CGM.getCodeGenOpts().XRayInstrumentationBundle.has(
916 Fn->addFnAttr(
"function-instrument",
"xray-always");
917 AlwaysXRayAttr =
true;
919 if (XRayAttr->neverXRayInstrument())
920 Fn->addFnAttr(
"function-instrument",
"xray-never");
921 if (
const auto *LogArgs = D->
getAttr<XRayLogArgsAttr>())
923 Fn->addFnAttr(
"xray-log-args",
924 llvm::utostr(LogArgs->getArgumentCount()));
929 "xray-instruction-threshold",
930 llvm::itostr(
CGM.getCodeGenOpts().XRayInstructionThreshold));
934 if (
CGM.getCodeGenOpts().XRayIgnoreLoops)
935 Fn->addFnAttr(
"xray-ignore-loops");
937 if (!
CGM.getCodeGenOpts().XRayInstrumentationBundle.has(
939 Fn->addFnAttr(
"xray-skip-exit");
941 if (!
CGM.getCodeGenOpts().XRayInstrumentationBundle.has(
943 Fn->addFnAttr(
"xray-skip-entry");
945 auto FuncGroups =
CGM.getCodeGenOpts().XRayTotalFunctionGroups;
946 if (FuncGroups > 1) {
948 CurFn->getName().bytes_end());
949 auto Group = crc32(FuncName) % FuncGroups;
950 if (Group !=
CGM.getCodeGenOpts().XRaySelectedFunctionGroup &&
952 Fn->addFnAttr(
"function-instrument",
"xray-never");
956 if (
CGM.getCodeGenOpts().getProfileInstr() !=
957 llvm::driver::ProfileInstrKind::ProfileNone) {
958 switch (
CGM.isFunctionBlockedFromProfileInstr(Fn, Loc)) {
960 Fn->addFnAttr(llvm::Attribute::SkipProfile);
963 Fn->addFnAttr(llvm::Attribute::NoProfile);
970 unsigned Count, Offset;
972 if (
const auto *
Attr =
973 D ? D->
getAttr<PatchableFunctionEntryAttr>() :
nullptr) {
974 Count =
Attr->getCount();
975 Offset =
Attr->getOffset();
976 Section =
Attr->getSection();
978 Count =
CGM.getCodeGenOpts().PatchableFunctionEntryCount;
979 Offset =
CGM.getCodeGenOpts().PatchableFunctionEntryOffset;
982 Section =
CGM.getCodeGenOpts().PatchableFunctionEntrySection;
983 if (Count && Offset <= Count) {
984 Fn->addFnAttr(
"patchable-function-entry", std::to_string(Count - Offset));
986 Fn->addFnAttr(
"patchable-function-prefix", std::to_string(Offset));
987 if (!Section.empty())
988 Fn->addFnAttr(
"patchable-function-entry-section", Section);
994 if (
CGM.getCodeGenOpts().HotPatch &&
997 llvm::Triple::CODE16)
998 Fn->addFnAttr(
"patchable-function",
"prologue-short-redirect");
1001 if (
CGM.getCodeGenOpts().NoUseJumpTables)
1002 Fn->addFnAttr(
"no-jump-tables",
"true");
1005 if (
CGM.getCodeGenOpts().NoInlineLineTables)
1006 Fn->addFnAttr(
"no-inline-line-tables");
1009 if (
CGM.getCodeGenOpts().ProfileSampleAccurate)
1010 Fn->addFnAttr(
"profile-sample-accurate");
1012 if (!
CGM.getCodeGenOpts().SampleProfileFile.empty())
1013 Fn->addFnAttr(
"use-sample-profile");
1015 if (D && D->
hasAttr<CFICanonicalJumpTableAttr>())
1016 Fn->addFnAttr(
"cfi-canonical-jump-table");
1018 if (D && D->
hasAttr<NoProfileFunctionAttr>())
1019 Fn->addFnAttr(llvm::Attribute::NoProfile);
1021 if (D && D->
hasAttr<HybridPatchableAttr>())
1022 Fn->addFnAttr(llvm::Attribute::HybridPatchable);
1026 if (
auto *A = D->
getAttr<FunctionReturnThunksAttr>()) {
1027 switch (A->getThunkType()) {
1028 case FunctionReturnThunksAttr::Kind::Keep:
1030 case FunctionReturnThunksAttr::Kind::Extern:
1031 Fn->addFnAttr(llvm::Attribute::FnRetThunkExtern);
1034 }
else if (
CGM.getCodeGenOpts().FunctionReturnThunks)
1035 Fn->addFnAttr(llvm::Attribute::FnRetThunkExtern);
1044 EmitKernelMetadata(FD, Fn);
1047 if (FD && FD->
hasAttr<ClspvLibclcBuiltinAttr>()) {
1048 Fn->setMetadata(
"clspv_libclc_builtin",
1055 if (FD &&
SanOpts.has(SanitizerKind::Function) &&
1057 llvm::isCallableCC(Fn->getCallingConv())) {
1059 llvm::LLVMContext &Ctx = Fn->getContext();
1060 llvm::MDBuilder MDB(Ctx);
1062 llvm::LLVMContext::MD_func_sanitize,
1063 MDB.createRTTIPointerPrologue(
1070 if (
SanOpts.has(SanitizerKind::NullabilityReturn)) {
1071 auto Nullability =
FnRetTy->getNullability();
1074 if (!(
SanOpts.has(SanitizerKind::ReturnsNonnullAttribute) &&
1076 RetValNullabilityPrecondition =
1083 if (
CGM.getCodeGenOpts().CopyProf) {
1084 if (
const auto *MD = dyn_cast_or_null<CXXMethodDecl>(D)) {
1086 if (
const auto *CD = dyn_cast<CXXConstructorDecl>(MD)) {
1087 if (!CD->isMoveConstructor())
1089 CD->isCopyConstructor() ?
"copyprof-copy-ctor" :
"copyprof-ctor";
1091 Attr =
"copyprof-dtor";
1093 Attr =
"copyprof-copy-assign-op";
1095 if (!
Attr.empty()) {
1102 CGM.getCodeGenOpts().CopyProfStaticSizeThreshold)
1126 Fn->addFnAttr(llvm::Attribute::NoRecurse);
1129 llvm::fp::ExceptionBehavior FPExceptionBehavior =
1131 Builder.setDefaultConstrainedRounding(RM);
1132 Builder.setDefaultConstrainedExcept(FPExceptionBehavior);
1134 (!FD && (FPExceptionBehavior != llvm::fp::ebIgnore ||
1135 RM != llvm::RoundingMode::NearestTiesToEven))) {
1136 Builder.setIsFPConstrained(
true);
1137 Fn->addFnAttr(llvm::Attribute::StrictFP);
1143 CGM.getCodeGenOpts().StackAlignment))
1144 Fn->addFnAttr(
"stackrealign");
1150 if (T->getAArch64SMEAttributes() &
1157 const auto *FeatureMap =
1159 if (
auto VScaleRange =
getContext().getTargetInfo().getVScaleRange(
1161 CurFn->addFnAttr(llvm::Attribute::getWithVScaleRangeArgs(
1169 llvm::Value *Poison = llvm::PoisonValue::get(
Int32Ty);
1174 Builder.SetInsertPoint(EntryBB);
1178 if (requiresReturnValueCheck()) {
1189 DI->emitFunctionStart(GD, Loc, StartLoc,
1190 DI->getFunctionType(FD, RetTy, Args),
CurFn,
1195 if (
CGM.getCodeGenOpts().InstrumentFunctions)
1196 CurFn->addFnAttr(
"instrument-function-entry",
"__cyg_profile_func_enter");
1197 if (
CGM.getCodeGenOpts().InstrumentFunctionsAfterInlining)
1198 CurFn->addFnAttr(
"instrument-function-entry-inlined",
1199 "__cyg_profile_func_enter");
1200 if (
CGM.getCodeGenOpts().InstrumentFunctionEntryBare)
1201 CurFn->addFnAttr(
"instrument-function-entry-inlined",
1202 "__cyg_profile_func_enter_bare");
1209 if (
CGM.getCodeGenOpts().InstrumentForProfiling) {
1213 if (
CGM.getCodeGenOpts().CallFEntry)
1214 Fn->addFnAttr(
"fentry-call",
"true");
1216 Fn->addFnAttr(
"instrument-function-entry-inlined",
1219 if (
CGM.getCodeGenOpts().MNopMCount) {
1220 if (!
CGM.getCodeGenOpts().CallFEntry)
1221 CGM.getDiags().Report(diag::err_opt_not_valid_without_opt)
1222 <<
"-mnop-mcount" <<
"-mfentry";
1223 Fn->addFnAttr(
"mnop-mcount");
1226 if (
CGM.getCodeGenOpts().RecordMCount) {
1227 if (!
CGM.getCodeGenOpts().CallFEntry)
1228 CGM.getDiags().Report(diag::err_opt_not_valid_without_opt)
1229 <<
"-mrecord-mcount" <<
"-mfentry";
1230 Fn->addFnAttr(
"mrecord-mcount");
1235 if (
CGM.getCodeGenOpts().PackedStack) {
1237 llvm::Triple::systemz)
1238 CGM.getDiags().Report(diag::err_opt_not_valid_on_target)
1239 <<
"-mpacked-stack";
1240 Fn->addFnAttr(
"packed-stack");
1243 if (!
CGM.getCodeGenOpts().ZOSPPA1Name)
1244 Fn->addFnAttr(
"zos-ppa1-name",
"");
1246 FD->
hasAttr<AsmLabelAttr>()) {
1247 std::string SrcName =
CGM.getMangledNameIgnoringAsmLabel(GD, FD);
1248 Fn->addFnAttr(
"zos-ppa1-name", SrcName);
1251 if (
CGM.getCodeGenOpts().WarnStackSize !=
UINT_MAX &&
1252 !
CGM.getDiags().isIgnored(diag::warn_fe_backend_frame_larger_than, Loc))
1253 Fn->addFnAttr(
"warn-stack-size",
1254 std::to_string(
CGM.getCodeGenOpts().WarnStackSize));
1266 auto AI =
CurFn->arg_begin();
1267 if (
CurFnInfo->getReturnInfo().isSRetAfterThis())
1270 &*AI, RetTy,
CurFnInfo->getReturnInfo().getIndirectAlign(),
false,
1272 if (!
CurFnInfo->getReturnInfo().getIndirectByVal()) {
1281 unsigned Idx =
CurFnInfo->getReturnInfo().getInAllocaFieldIndex();
1282 llvm::Function::arg_iterator EI =
CurFn->arg_end();
1314 if (FD->
hasAttr<HLSLShaderAttr>()) {
1315 CGM.getHLSLRuntime().emitEntryFunction(FD, Fn);
1321 if (
const CXXMethodDecl *MD = dyn_cast_if_present<CXXMethodDecl>(D);
1326 CGM.getCXXABI().EmitInstanceFunctionProlog(*
this);
1342 CXXThisValue = ThisFieldLValue.
getPointer(*
this);
1351 if (FD->hasCapturedVLAType()) {
1354 auto VAT = FD->getCapturedVLAType();
1355 VLASizeMap[VAT->getSizeExpr()] = ExprArg;
1362 CXXThisValue = CXXABIThisValue;
1366 if (CXXABIThisValue) {
1368 SkippedChecks.
set(SanitizerKind::ObjectSize,
true);
1375 SkippedChecks.
set(SanitizerKind::Null,
true);
1379 Loc, CXXABIThisValue, ThisTy, CXXABIThisAlignment, SkippedChecks);
1386 if (!FD || !FD->
hasAttr<NakedAttr>()) {
1387 for (
const VarDecl *VD : Args) {
1392 if (
const ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(VD))
1393 Ty = PVD->getOriginalType();
1403 DI->EmitLocation(
Builder, StartLoc);
1407 if (
const auto *VecWidth =
CurFuncDecl->getAttr<MinVectorWidthAttr>())
1408 LargestVectorWidth = VecWidth->getVectorWidth();
1410 if (
CGM.shouldEmitConvergenceTokens())
1417 if (
const CompoundStmt *S = dyn_cast<CompoundStmt>(Body))
1429 llvm::BasicBlock *SkipCountBB =
nullptr;
1451 if (F->isInterposable())
return;
1453 for (llvm::BasicBlock &BB : *F)
1454 for (llvm::Instruction &I : BB)
1458 F->setDoesNotThrow();
1468 if (
CGM.getCXXABI().HasThisReturn(GD))
1470 else if (
CGM.getCXXABI().hasMostDerivedReturn(GD))
1471 ResTy =
CGM.getContext().VoidPtrTy;
1472 CGM.getCXXABI().buildThisParam(*
this, Args);
1478 bool PassedParams =
true;
1480 if (
auto Inherited = CD->getInheritedConstructor())
1486 Args.push_back(Param);
1487 if (!Param->hasAttr<PassObjectSizeAttr>())
1491 getContext(), Param->getDeclContext(), Param->getLocation(),
1499 CGM.getCXXABI().addImplicitStructorParams(*
this, ResTy, Args);
1506 assert(Fn &&
"generating code for null Function");
1513 CGM.getTargetCodeGenInfo().checkFunctionABI(
CGM, FD);
1519 std::string FDInlineName = (Fn->getName() +
".inline").str();
1520 llvm::Module *M = Fn->getParent();
1521 llvm::Function *Clone = M->getFunction(FDInlineName);
1523 Clone = llvm::Function::Create(Fn->getFunctionType(),
1524 llvm::GlobalValue::InternalLinkage,
1525 Fn->getAddressSpace(), FDInlineName, M);
1526 Clone->setCallingConv(Fn->getCallingConv());
1527 Clone->setAttributes(Fn->getAttributes());
1528 Clone->addFnAttr(llvm::Attribute::AlwaysInline);
1530 Fn->setLinkage(llvm::GlobalValue::ExternalLinkage);
1540 if (LLVM_UNLIKELY(PD->isInlineBuiltinDeclaration())) {
1541 std::string FDInlineName = (Fn->getName() +
".inline").str();
1542 llvm::Module *M = Fn->getParent();
1543 if (llvm::Function *Clone = M->getFunction(FDInlineName)) {
1544 Clone->replaceAllUsesWith(Fn);
1545 Clone->eraseFromParent();
1553 if (FD->
hasAttr<NoDebugAttr>()) {
1556 Fn->setSubprogram(
nullptr);
1558 DebugInfo =
nullptr;
1561 llvm::scope_exit Cleanup([
this] {
1563 DI->completeFunction();
1570 BodyRange = Body->getSourceRange();
1573 CurEHLocation = BodyRange.getEnd();
1585 if (SpecDecl->hasBody(SpecDecl))
1586 Loc = SpecDecl->getLocation();
1591 StartFunction(GD, ResTy, Fn, FnInfo, Args, Loc, BodyRange.getBegin());
1594 if (Body && isa_and_nonnull<CoroutineBodyStmt>(Body))
1602 CurFn->addFnAttr(llvm::Attribute::MustProgress);
1605 PGO->assignRegionCounters(GD,
CurFn);
1612 FD->
hasAttr<CUDAGlobalAttr>())
1613 CGM.getCUDARuntime().emitDeviceStub(*
this, Args);
1636 }
else if (DeviceKernelAttr::isOpenCLSpelling(
1637 FD->
getAttr<DeviceKernelAttr>()) &&
1640 for (
unsigned i = 0; i < Args.size(); ++i) {
1642 QualType ArgQualType = Args[i]->getType();
1644 CallArgs.
add(ArgRValue, ArgQualType);
1648 CGM.getTargetCodeGenInfo().setOCLKernelStubCallingConvention(FT);
1651 llvm::FunctionType *FTy =
CGM.getTypes().GetFunctionType(FnInfo);
1652 llvm::Constant *GDStubFunctionPointer =
1653 CGM.getRawFunctionPointer(GDStub, FTy);
1660 llvm_unreachable(
"no definition for emitted function");
1670 bool ShouldEmitUnreachable =
1671 CGM.getCodeGenOpts().StrictReturn ||
1673 if (
SanOpts.has(SanitizerKind::Return)) {
1674 auto CheckOrdinal = SanitizerKind::SO_Return;
1675 auto CheckHandler = SanitizerHandler::MissingReturn;
1677 llvm::Value *IsFalse =
Builder.getFalse();
1678 EmitCheck(std::make_pair(IsFalse, CheckOrdinal), CheckHandler,
1680 }
else if (ShouldEmitUnreachable) {
1681 if (
CGM.getCodeGenOpts().OptimizationLevel == 0)
1684 if (
SanOpts.has(SanitizerKind::Return) || ShouldEmitUnreachable) {
1686 Builder.ClearInsertionPoint();
1693 PGO->verifyCounterMap();
1696 StringRef Identifier =
1697 CurCodeDecl->getAttr<PersonalityAttr>()->getRoutine()->getName();
1698 llvm::FunctionCallee PersonalityRoutine =
1699 CGM.CreateRuntimeFunction(llvm::FunctionType::get(
CGM.Int32Ty,
true),
1700 Identifier, {},
true);
1706 if (!
CurFn->doesNotThrow())
1715 if (!S)
return false;
1732 IgnoreCaseStmts =
true;
1747 if (!S)
return false;
1767 if (!S)
return false;
1798 if (!AllowLabels &&
CGM.getCodeGenOpts().hasProfileClangInstr() &&
1799 CGM.getCodeGenOpts().MCDCCoverage)
1802 llvm::APSInt ResultInt;
1806 ResultBool = ResultInt.getBoolValue();
1814 llvm::APSInt &ResultInt,
1826 PGO->markStmtMaybeUsed(Cond);
1827 ResultInt = std::move(
Int);
1856 llvm::BasicBlock *FalseBlock, uint64_t TrueCount ,
1859 bool InstrumentRegions =
CGM.getCodeGenOpts().hasProfileClangInstr();
1863 const Stmt *CntrStmt = (CntrIdx ? CntrIdx : Cond);
1865 llvm::BasicBlock *ThenBlock =
nullptr;
1866 llvm::BasicBlock *ElseBlock =
nullptr;
1867 llvm::BasicBlock *NextBlock =
nullptr;
1872 llvm::BasicBlock *SkipIncrBlock =
1874 llvm::BasicBlock *SkipNextBlock =
nullptr;
1888 if (LOp == BO_LAnd) {
1889 SkipNextBlock = FalseBlock;
1890 ThenBlock = CounterIncrBlock;
1891 ElseBlock = (SkipIncrBlock ? SkipIncrBlock : SkipNextBlock);
1892 NextBlock = TrueBlock;
1907 else if (LOp == BO_LOr) {
1908 SkipNextBlock = TrueBlock;
1909 ThenBlock = (SkipIncrBlock ? SkipIncrBlock : SkipNextBlock);
1910 ElseBlock = CounterIncrBlock;
1911 NextBlock = FalseBlock;
1913 llvm_unreachable(
"Expected Opcode must be that of a Logical Operator");
1919 if (SkipIncrBlock) {
1943 const Expr *Cond, llvm::BasicBlock *TrueBlock, llvm::BasicBlock *FalseBlock,
1945 const VarDecl *ConditionalDecl) {
1948 if (
const BinaryOperator *CondBOp = dyn_cast<BinaryOperator>(Cond)) {
1952 if (CondBOp->getOpcode() == BO_LAnd) {
1955 bool ConstantBool =
false;
1961 FalseBlock, TrueCount, LH);
1971 FalseBlock, TrueCount, LH, CondBOp);
1978 llvm::BasicBlock *LHSFalse =
2006 FalseBlock, TrueCount, LH);
2011 if (CondBOp->getOpcode() == BO_LOr) {
2014 bool ConstantBool =
false;
2020 FalseBlock, TrueCount, LH);
2030 FalseBlock, TrueCount, LH, CondBOp);
2035 llvm::BasicBlock *LHSTrue =
2043 uint64_t RHSCount = TrueCount - LHSCount;
2074 if (
const UnaryOperator *CondUOp = dyn_cast<UnaryOperator>(Cond)) {
2079 bool MCDCCondition =
CGM.getCodeGenOpts().hasProfileClangInstr() &&
2080 CGM.getCodeGenOpts().MCDCCoverage &&
2082 if (CondUOp->getOpcode() == UO_LNot && !MCDCCondition) {
2109 uint64_t LHSScaledTrueCount = 0;
2113 LHSScaledTrueCount = TrueCount * LHSRatio;
2122 LHSScaledTrueCount, LH, CondOp);
2130 TrueCount - LHSScaledTrueCount, LH, CondOp);
2136 if (
const CXXThrowExpr *Throw = dyn_cast<CXXThrowExpr>(Cond)) {
2158 const Expr *MCDCBaseExpr = Cond;
2165 MCDCBaseExpr = ConditionalOp;
2172 llvm::MDNode *Weights =
nullptr;
2173 llvm::MDNode *Unpredictable =
nullptr;
2179 if (
Call &&
CGM.getCodeGenOpts().OptimizationLevel != 0) {
2180 auto *FD = dyn_cast_or_null<FunctionDecl>(
Call->getCalleeDecl());
2181 if (FD && FD->
getBuiltinID() == Builtin::BI__builtin_unpredictable) {
2183 Unpredictable = MDHelper.createUnpredictable();
2189 llvm::Value *NewCondV = emitCondLikelihoodViaExpectIntrinsic(CondV, LH);
2190 if (CondV != NewCondV)
2195 Weights = createProfileWeights(TrueCount, CurrentCount - TrueCount);
2198 llvm::Instruction *BrInst =
Builder.CreateCondBr(CondV, TrueBlock, FalseBlock,
2199 Weights, Unpredictable);
2203 case HLSLControlFlowHintAttr::Microsoft_branch:
2204 case HLSLControlFlowHintAttr::Microsoft_flatten: {
2205 llvm::MDBuilder MDHelper(
CGM.getLLVMContext());
2207 llvm::ConstantInt *BranchHintConstant =
2209 HLSLControlFlowHintAttr::Spelling::Microsoft_branch
2210 ? llvm::ConstantInt::get(
CGM.Int32Ty, 1)
2211 : llvm::ConstantInt::get(
CGM.Int32Ty, 2);
2214 {MDHelper.createString(
"hlsl.controlflow.hint"),
2215 MDHelper.createConstant(BranchHintConstant)});
2216 BrInst->setMetadata(
"hlsl.controlflow.hint",
2217 llvm::MDNode::get(
CGM.getLLVMContext(), Vals));
2221 case HLSLControlFlowHintAttr::SpellingNotCalculated:
2229 llvm::Value *Arg =
nullptr;
2230 if ((ICEArguments & (1 << Idx)) == 0) {
2235 std::optional<llvm::APSInt>
Result =
2237 assert(
Result &&
"Expected argument to be a constant");
2246 CGM.ErrorUnsupported(S,
Type);
2258 llvm::Value *sizeInChars) {
2262 llvm::Value *baseSizeInChars
2266 llvm::Value *end = Builder.CreateInBoundsGEP(begin.
getElementType(),
2268 sizeInChars,
"vla.end");
2270 llvm::BasicBlock *originBB = CGF.
Builder.GetInsertBlock();
2278 llvm::PHINode *cur = Builder.CreatePHI(begin.
getType(), 2,
"vla.cur");
2285 Builder.CreateMemCpy(
Address(cur, CGF.
Int8Ty, curAlign), src, baseSizeInChars,
2290 Builder.CreateInBoundsGEP(CGF.
Int8Ty, cur, baseSizeInChars,
"vla.next");
2293 llvm::Value *done = Builder.CreateICmpEQ(next, end,
"vla-init.isdone");
2294 Builder.CreateCondBr(done, contBB, loopBB);
2295 cur->addIncoming(next, loopBB);
2313 if (
CGM.getContext().arePFPFieldsTriviallyCopyable(Field->getParent())) {
2314 uint64_t FieldSignature =
2315 llvm::getPointerAuthStableSipHash(
CGM.getPFPFieldName(Field));
2316 Disc = llvm::ConstantInt::get(
CGM.Int64Ty, FieldSignature);
2320 llvm::GlobalValue *DS =
CGM.getPFPDeactivationSymbol(Field);
2321 llvm::OperandBundleDef DSBundle(
"deactivation-symbol", DS);
2324 Builder.CreateCall(
CGM.getIntrinsic(llvm::Intrinsic::protected_field_ptr,
2343 llvm::Value *SizeVal;
2350 dyn_cast_or_null<VariableArrayType>(
2353 SizeVal = VlaSize.NumElts;
2355 if (!eltSize.
isOne())
2356 SizeVal =
Builder.CreateNUWMul(SizeVal,
CGM.getSize(eltSize));
2362 SizeVal =
CGM.getSize(size);
2370 if (!
CGM.getTypes().isZeroInitializable(Ty)) {
2374 llvm::Constant *NullConstant =
CGM.EmitNullConstant(Ty);
2376 llvm::GlobalVariable *NullVariable =
2377 new llvm::GlobalVariable(
CGM.getModule(), NullConstant->getType(),
2379 llvm::GlobalVariable::PrivateLinkage,
2380 NullConstant, Twine());
2382 NullVariable->setAlignment(NullAlign.
getAsAlign());
2388 Builder.CreateMemCpy(DestPtr, SrcPtr, SizeVal,
false);
2394 Builder.CreateMemSet(DestPtr,
Builder.getInt8(0), SizeVal,
false);
2407 if (!IndirectBranch)
2413 IndirectBranch->addDestination(BB);
2414 return llvm::BlockAddress::get(
CurFn->getType(), BB);
2419 if (IndirectBranch)
return IndirectBranch->getParent();
2424 llvm::Value *DestVal = TmpBuilder.CreatePHI(
Int8PtrTy, 0,
2425 "indirect.goto.dest");
2428 IndirectBranch = TmpBuilder.CreateIndirectBr(DestVal);
2429 return IndirectBranch->getParent();
2441 llvm::Value *numVLAElements =
nullptr;
2453 baseType = elementType;
2454 return numVLAElements;
2468 llvm::ConstantInt *zero =
Builder.getInt32(0);
2469 gepIndices.push_back(zero);
2471 uint64_t countFromCLAs = 1;
2474 llvm::ArrayType *llvmArrayType =
2476 while (llvmArrayType) {
2479 llvmArrayType->getNumElements());
2481 gepIndices.push_back(zero);
2482 countFromCLAs *= llvmArrayType->getNumElements();
2486 dyn_cast<llvm::ArrayType>(llvmArrayType->getElementType());
2489 "LLVM and Clang types are out-of-synch");
2508 gepIndices,
"array.begin"),
2514 llvm::Value *numElements
2515 = llvm::ConstantInt::get(
SizeTy, countFromCLAs);
2519 numElements =
Builder.CreateNUWMul(numVLAElements, numElements);
2526 assert(vla &&
"type was not a variable array type!");
2533 llvm::Value *numElements =
nullptr;
2537 elementType =
type->getElementType();
2538 llvm::Value *vlaSize = VLASizeMap[
type->getSizeExpr()];
2539 assert(vlaSize &&
"no size for VLA!");
2540 assert(vlaSize->getType() ==
SizeTy);
2543 numElements = vlaSize;
2547 numElements =
Builder.CreateNUWMul(numElements, vlaSize);
2549 }
while ((
type =
getContext().getAsVariableArrayType(elementType)));
2551 return { numElements, elementType };
2557 assert(vla &&
"type was not a variable array type!");
2563 llvm::Value *VlaSize = VLASizeMap[Vla->
getSizeExpr()];
2564 assert(VlaSize &&
"no size for VLA!");
2565 assert(VlaSize->getType() ==
SizeTy);
2570 assert(
type->isVariablyModifiedType() &&
2571 "Must pass variably modified type to EmitVLASizes!");
2578 assert(
type->isVariablyModifiedType());
2580 const Type *ty =
type.getTypePtr();
2583#define TYPE(Class, Base)
2584#define ABSTRACT_TYPE(Class, Base)
2585#define NON_CANONICAL_TYPE(Class, Base)
2586#define DEPENDENT_TYPE(Class, Base) case Type::Class:
2587#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base)
2588#include "clang/AST/TypeNodes.inc"
2589 llvm_unreachable(
"unexpected dependent type!");
2595 case Type::ExtVector:
2596 case Type::ConstantMatrix:
2597 case Type::CooperativeMatrix:
2601 case Type::TemplateSpecialization:
2602 case Type::ObjCTypeParam:
2603 case Type::ObjCObject:
2604 case Type::ObjCInterface:
2605 case Type::ObjCObjectPointer:
2607 case Type::HLSLInlineSpirv:
2608 case Type::PredefinedSugar:
2609 llvm_unreachable(
"type class is never variably-modified!");
2611 case Type::Adjusted:
2623 case Type::BlockPointer:
2627 case Type::LValueReference:
2628 case Type::RValueReference:
2632 case Type::MemberPointer:
2636 case Type::ArrayParameter:
2637 case Type::ConstantArray:
2638 case Type::IncompleteArray:
2643 case Type::VariableArray: {
2652 llvm::Value *&entry = VLASizeMap[sizeExpr];
2660 if (
SanOpts.has(SanitizerKind::VLABound)) {
2661 auto CheckOrdinal = SanitizerKind::SO_VLABound;
2662 auto CheckHandler = SanitizerHandler::VLABoundNotPositive;
2664 llvm::Value *
Zero = llvm::Constant::getNullValue(size->getType());
2666 llvm::Value *CheckCondition =
2670 llvm::Constant *StaticArgs[] = {
2673 EmitCheck(std::make_pair(CheckCondition, CheckOrdinal),
2674 CheckHandler, StaticArgs, size);
2687 case Type::FunctionProto:
2688 case Type::FunctionNoProto:
2694 case Type::UnaryTransform:
2695 case Type::Attributed:
2696 case Type::BTFTagAttributed:
2697 case Type::OverflowBehavior:
2698 case Type::HLSLAttributedResource:
2699 case Type::SubstTemplateTypeParm:
2700 case Type::MacroQualified:
2701 case Type::CountAttributed:
2702 case Type::LateParsedAttr:
2708 case Type::Decltype:
2710 case Type::DeducedTemplateSpecialization:
2711 case Type::PackIndexing:
2715 case Type::TypeOfExpr:
2728 }
while (
type->isVariablyModifiedType());
2732 if (
getContext().getBuiltinVaListType()->isArrayType())
2747 assert(
Init.hasValue() &&
"Invalid DeclRefExpr initializer!");
2749 if (
CGM.getCodeGenOpts().hasReducedDebugInfo())
2765 llvm::Instruction *inst =
new llvm::BitCastInst(value, value->getType(),
"",
2769 protection.Inst = inst;
2774 if (!protection.Inst)
return;
2777 protection.Inst->eraseFromParent();
2783 llvm::Value *Alignment,
2784 llvm::Value *OffsetValue) {
2785 if (Alignment->getType() !=
IntPtrTy)
2788 if (OffsetValue && OffsetValue->getType() !=
IntPtrTy)
2791 if (
SanOpts.has(SanitizerKind::Alignment))
2794 Builder.CreateAlignmentAssumption(
CGM.getDataLayout(), PtrValue, Alignment,
2801 llvm::Value *Alignment,
2802 llvm::Value *OffsetValue) {
2811 llvm::Value *AnnotatedVal,
2812 StringRef AnnotationStr,
2814 const AnnotateAttr *
Attr) {
2817 CGM.EmitAnnotationString(AnnotationStr),
2818 CGM.EmitAnnotationUnit(Location),
2819 CGM.EmitAnnotationLineNo(Location),
2822 Args.push_back(
CGM.EmitAnnotationArgs(
Attr));
2823 return Builder.CreateCall(AnnotationFn, Args);
2827 assert(D->
hasAttr<AnnotateAttr>() &&
"no annotate attribute");
2830 {V->getType(), CGM.ConstGlobalsPtrTy}),
2836 assert(D->
hasAttr<AnnotateAttr>() &&
"no annotate attribute");
2837 llvm::Value *
V =
Addr.emitRawPointer(*
this);
2838 llvm::Type *VTy =
V->getType();
2839 auto *PTy = dyn_cast<llvm::PointerType>(VTy);
2840 unsigned AS = PTy ? PTy->getAddressSpace() : 0;
2841 llvm::PointerType *IntrinTy =
2842 llvm::PointerType::get(
CGM.getLLVMContext(), AS);
2843 llvm::Function *F =
CGM.getIntrinsic(llvm::Intrinsic::ptr_annotation,
2844 {IntrinTy,
CGM.ConstGlobalsPtrTy});
2850 if (VTy != IntrinTy)
2863 assert(!CGF->IsSanitizerScope);
2864 CGF->IsSanitizerScope =
true;
2868 CGF->IsSanitizerScope =
false;
2872 const llvm::Twine &Name,
2873 llvm::BasicBlock::iterator InsertPt)
const {
2876 I->setNoSanitizeMetadata();
2880 llvm::Instruction *I,
const llvm::Twine &Name,
2881 llvm::BasicBlock::iterator InsertPt)
const {
2882 llvm::IRBuilderDefaultInserter::InsertHelper(I, Name, InsertPt);
2884 CGF->InsertHelper(I, Name, InsertPt);
2906 if (!
CGM.getCodeGenOpts().SanitizeStats)
2909 llvm::IRBuilder<> IRB(
Builder.GetInsertPoint());
2910 IRB.SetCurrentDebugLocation(
Builder.getCurrentDebugLocation());
2911 CGM.getSanStats().create(IRB, SSK);
2923 Salt = Info.CFISalt;
2925 Bundles.emplace_back(
"kcfi",
CGM.CreateKCFITypeId(FP->
desugar(), Salt));
2929CodeGenFunction::FormAArch64ResolverCondition(
const FMVResolverOption &RO) {
2930 return RO.Features.empty() ?
nullptr : EmitAArch64CpuSupports(RO.Features);
2934CodeGenFunction::FormX86ResolverCondition(
const FMVResolverOption &RO) {
2937 if (RO.Architecture) {
2938 StringRef
Arch = *RO.Architecture;
2941 if (
Arch.starts_with(
"x86-64"))
2947 if (!RO.Features.empty()) {
2948 llvm::Value *FeatureCond = EmitX86CpuSupports(RO.Features);
2956 llvm::Function *Resolver,
2958 llvm::Function *FuncToReturn,
2959 bool SupportsIFunc) {
2960 if (SupportsIFunc) {
2961 Builder.CreateRet(FuncToReturn);
2966 llvm::make_pointer_range(Resolver->args()));
2968 llvm::CallInst *
Result = Builder.CreateCall(FuncToReturn, Args);
2969 Result->setTailCallKind(llvm::CallInst::TCK_MustTail);
2971 if (Resolver->getReturnType()->isVoidTy())
2972 Builder.CreateRetVoid();
2974 Builder.CreateRet(
Result);
2980 llvm::Triple::ArchType ArchType =
2984 case llvm::Triple::x86:
2985 case llvm::Triple::x86_64:
2988 case llvm::Triple::aarch64:
2991 case llvm::Triple::riscv32:
2992 case llvm::Triple::riscv64:
2993 case llvm::Triple::riscv32be:
2994 case llvm::Triple::riscv64be:
2997 case llvm::Triple::ppc:
2998 case llvm::Triple::ppc64:
3006 "Only implemented for x86, AArch64, RISC-V, and PowerPC AIX");
3033 Builder.SetInsertPoint(CurBlock);
3035 if (!RO.Architecture && RO.Features.empty()) {
3038 assert(&RO == Options.end() - 1 &&
3039 "Default or Generic case must be last");
3040 Builder.CreateRet(RO.Function);
3049 assert(RO.Features.size() == 1 &&
3050 "for now one feature requirement per version");
3052 StringRef FeatureStr = RO.Features[0];
3053 StringRef BuiltinCpuSupportsArg;
3054 bool IsNegated =
false;
3056 if (FeatureStr.starts_with(
"cpu=")) {
3058 StringRef CPU = FeatureStr.split(
"=").second.trim();
3059 BuiltinCpuSupportsArg = llvm::StringSwitch<StringRef>(CPU)
3060#define PPC_AIX_CLONES_CPU(CPU_NAME, AIX_BUILTIN_CPU_SUPPORTS_NAME, _) \
3061 .Case(CPU_NAME, AIX_BUILTIN_CPU_SUPPORTS_NAME)
3062#include "llvm/TargetParser/PPCTargetParser.def"
3068 if (FeatureStr.starts_with(
"no-")) {
3070 FeatureStr = FeatureStr.drop_front(3);
3074 BuiltinCpuSupportsArg =
3075 llvm::StringSwitch<StringRef>(FeatureStr)
3076#define PPC_AIX_CLONES_FEATURE(FEATURE_NAME, AIX_BUILTIN_CPU_SUPPORTS_NAME, _, \
3078 .Case(FEATURE_NAME, AIX_BUILTIN_CPU_SUPPORTS_NAME)
3079#include "llvm/TargetParser/PPCTargetParser.def"
3084 assert(!BuiltinCpuSupportsArg.empty() &&
3085 "Feature without runtime detection should have been rejected in "
3089 assert(
getContext().getTargetInfo().validateCpuSupports(
3090 BuiltinCpuSupportsArg));
3094 Builder.getInt1Ty(), BuiltinCpuSupportsArg);
3105 Builder.SetInsertPoint(ThenBlock);
3106 Builder.CreateRet(RO.Function);
3109 llvm_unreachable(
"Default case missing");
3116 llvm::Triple::OSType::Linux) {
3117 CGM.getDiags().Report(diag::err_os_unsupport_riscv_fmv);
3122 Builder.SetInsertPoint(CurBlock);
3126 bool HasDefault =
false;
3127 unsigned DefaultIndex = 0;
3130 for (
unsigned Index = 0; Index < Options.size(); Index++) {
3132 if (Options[Index].Features.empty()) {
3134 DefaultIndex = Index;
3138 Builder.SetInsertPoint(CurBlock);
3164 for (StringRef Feat : Options[Index].Features) {
3165 std::vector<std::string> FeatStr =
3168 assert(FeatStr.size() == 1 &&
"Feature string not delimited");
3170 std::string &CurrFeat = FeatStr.front();
3171 if (CurrFeat[0] ==
'+')
3172 TargetAttrFeats.push_back(CurrFeat.substr(1));
3175 if (TargetAttrFeats.empty())
3178 for (std::string &Feat : TargetAttrFeats)
3179 CurrTargetAttrFeats.push_back(Feat);
3181 Builder.SetInsertPoint(CurBlock);
3184 llvm::BasicBlock *RetBlock =
createBasicBlock(
"resolver_return", Resolver);
3187 Options[Index].
Function, SupportsIFunc);
3190 Builder.SetInsertPoint(CurBlock);
3191 Builder.CreateCondBr(FeatsCondition, RetBlock, ElseBlock);
3193 CurBlock = ElseBlock;
3198 Builder.SetInsertPoint(CurBlock);
3205 Builder.SetInsertPoint(CurBlock);
3211 assert(!Options.empty() &&
"No multiversion resolver options found");
3212 assert(Options.back().Features.size() == 0 &&
"Default case must be last");
3214 assert(SupportsIFunc &&
3215 "Multiversion resolver requires target IFUNC support");
3216 bool AArch64CpuInitialized =
false;
3221 if (RO.Function ==
nullptr)
3224 Builder.SetInsertPoint(CurBlock);
3225 llvm::Value *
Condition = FormAArch64ResolverCondition(RO);
3234 if (!AArch64CpuInitialized) {
3235 Builder.SetInsertPoint(CurBlock->begin());
3236 EmitAArch64CpuInit();
3237 AArch64CpuInitialized =
true;
3238 Builder.SetInsertPoint(CurBlock);
3241 llvm::BasicBlock *RetBlock =
createBasicBlock(
"resolver_return", Resolver);
3250 Builder.SetInsertPoint(CurBlock);
3261 Builder.SetInsertPoint(CurBlock);
3265 Builder.SetInsertPoint(CurBlock);
3266 llvm::Value *
Condition = FormX86ResolverCondition(RO);
3270 assert(&RO == Options.end() - 1 &&
3271 "Default or Generic case must be last");
3277 llvm::BasicBlock *RetBlock =
createBasicBlock(
"resolver_return", Resolver);
3286 Builder.SetInsertPoint(CurBlock);
3298 llvm::Value *DynamicLoc,
3300 llvm::Value *Alignment,
3301 llvm::Value *OffsetValue) {
3302 if (!CGF.
SanOpts.
has(SanitizerKind::Alignment))
3307 if (Alignment->getType() !=
IntPtrTy)
3309 Builder.CreateIntCast(Alignment,
IntPtrTy,
false,
"casted.align");
3310 if (OffsetValue && OffsetValue->getType() !=
IntPtrTy)
3312 Builder.CreateIntCast(OffsetValue,
IntPtrTy,
true,
"casted.offset");
3314 llvm::Value *PtrIntValue = Builder.CreatePtrToInt(Ptr,
IntPtrTy,
"ptrint");
3317 bool IsOffsetZero =
false;
3318 if (
const auto *CI = dyn_cast<llvm::ConstantInt>(OffsetValue))
3319 IsOffsetZero = CI->isZero();
3322 PtrIntValue = Builder.CreateSub(PtrIntValue, OffsetValue,
"offsetptr");
3325 llvm::Value *
Zero = llvm::ConstantInt::get(
IntPtrTy, 0);
3327 Builder.CreateSub(Alignment, llvm::ConstantInt::get(
IntPtrTy, 1));
3328 llvm::Value *MaskedPtr = Builder.CreateAnd(PtrIntValue, Mask,
"maskedptr");
3329 llvm::Value *TheCheck = Builder.CreateICmpEQ(MaskedPtr,
Zero,
"maskcond");
3336 auto CheckOrdinal = SanitizerKind::SO_Alignment;
3337 auto CheckHandler = !DynamicLoc ? SanitizerHandler::AlignmentAssumption
3338 : SanitizerHandler::ReturnAlignmentAssumption;
3342 OffsetValue = Builder.getInt1(
false);
3348 llvm::Value *DynamicData[] = {Ptr, Alignment, OffsetValue};
3349 CGF.
EmitCheck({std::make_pair(TheCheck, CheckOrdinal)}, CheckHandler,
3350 StaticData, DynamicData);
3354 llvm::Value *DynamicData[] = {DynamicLoc, Ptr, Alignment, OffsetValue};
3355 CGF.
EmitCheck({std::make_pair(TheCheck, CheckOrdinal)}, CheckHandler,
3356 StaticData, DynamicData);
3364 llvm::Value *Alignment,
3365 llvm::Value *OffsetValue) {
3367 Alignment, OffsetValue);
3372 llvm::Value *Alignment, llvm::Value *OffsetValue) {
3373 llvm::Value *SLocPtr =
Builder.CreateLoad(ReturnLocation,
"return.sloc.load");
3375 AssumptionLoc, Alignment, OffsetValue);
3380 return DI->SourceLocToDebugLoc(Location);
3382 return llvm::DebugLoc();
3386CodeGenFunction::emitCondLikelihoodViaExpectIntrinsic(llvm::Value *Cond,
3397 llvm::Type *CondTy = Cond->getType();
3398 assert(CondTy->isIntegerTy(1) &&
"expecting condition to be a boolean");
3399 llvm::Function *FnExpect =
3401 llvm::Value *ExpectedValueOfCond =
3403 return Builder.CreateCall(FnExpect, {Cond, ExpectedValueOfCond},
3404 Cond->getName() +
".expval");
3406 llvm_unreachable(
"Unknown Likelihood");
3410 unsigned NumElementsDst,
3411 const llvm::Twine &Name) {
3413 unsigned NumElementsSrc = SrcTy->getNumElements();
3414 if (NumElementsSrc == NumElementsDst)
3417 std::vector<int> ShuffleMask(NumElementsDst, -1);
3418 for (
unsigned MaskIdx = 0;
3419 MaskIdx < std::min<>(NumElementsDst, NumElementsSrc); ++MaskIdx)
3420 ShuffleMask[MaskIdx] = MaskIdx;
3422 return Builder.CreateShuffleVector(SrcVec, ShuffleMask, Name);
3435 Discriminator =
Builder.getSize(0);
3437 llvm::Value *Args[] = {Key, Discriminator};
3438 Bundles.emplace_back(
"ptrauth", Args);
3444 unsigned IntrinsicID) {
3451 if (!Discriminator) {
3456 auto OrigType =
Pointer->getType();
3474 llvm::Intrinsic::ptrauth_sign);
3480 auto StripIntrinsic = CGF.
CGM.
getIntrinsic(llvm::Intrinsic::ptrauth_strip);
3484 auto OrigType =
Pointer->getType();
3501 llvm::Intrinsic::ptrauth_auth);
3505 llvm::Instruction *KeyInstruction, llvm::Value *Backup) {
3507 DI->addInstToCurrentSourceAtom(KeyInstruction, Backup);
3511 llvm::Instruction *KeyInstruction, llvm::Value *Backup, uint64_t Atom) {
3513 DI->addInstToSpecificSourceAtom(KeyInstruction, Backup, Atom);
3517 llvm::Value *Backup) {
3520 DI->addInstToCurrentSourceAtom(KeyInstruction, Backup);
3527 if (
getContext().arePFPFieldsTriviallyCopyable(Field.Field->getParent()))
3531 Builder.CreateStore(
Builder.CreateLoad(SrcFieldPtr), DestFieldPtr);
static void findPFPFields(const ASTContext &Ctx, QualType Ty, CharUnits Offset, std::vector< PFPField > &Fields, bool IncludeVBases)
Defines the clang::ASTContext interface.
This file provides some common utility functions for processing Lambda related AST Constructs.
Defines enum values for all the target-independent builtin functions.
static llvm::Value * EmitPointerAuthCommon(CodeGenFunction &CGF, const CGPointerAuthInfo &PointerAuth, llvm::Value *Pointer, unsigned IntrinsicID)
static void CreateMultiVersionResolverReturn(CodeGenModule &CGM, llvm::Function *Resolver, CGBuilderTy &Builder, llvm::Function *FuncToReturn, bool SupportsIFunc)
static llvm::Value * EmitStrip(CodeGenFunction &CGF, const CGPointerAuthInfo &PointerAuth, llvm::Value *Pointer)
static void emitNonZeroVLAInit(CodeGenFunction &CGF, QualType baseType, Address dest, Address src, llvm::Value *sizeInChars)
emitNonZeroVLAInit - Emit the "zero" initialization of a variable-length array whose elements have a ...
static void EmitIfUsed(CodeGenFunction &CGF, llvm::BasicBlock *BB)
static LValue makeNaturalAlignAddrLValue(llvm::Value *V, QualType T, bool ForPointeeType, bool MightBeSigned, CodeGenFunction &CGF, KnownNonNull_t IsKnownNonNull=NotKnownNonNull)
static void TryMarkNoThrow(llvm::Function *F)
Tries to mark the given function nounwind based on the non-existence of any throwing calls within it.
static llvm::Constant * getPrologueSignature(CodeGenModule &CGM, const FunctionDecl *FD)
Return the UBSan prologue signature for FD if one is available.
static bool endsWithReturn(const Decl *F)
Determine whether the function F ends with a return stmt.
static bool matchesStlAllocatorFn(const Decl *D, const ASTContext &Ctx)
Defines the C++ Decl subclasses, other than those for templates (found in DeclTemplate....
Result
Implement __builtin_bit_cast and related operations.
static StringRef getTriple(const Command &Job)
Defines the Objective-C statement AST node classes.
APValue - This class implements a discriminated union of [uninitialized] [APSInt] [APFloat],...
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
const llvm::StringMap< bool > & getFunctionFeatureMap(const FunctionDecl *FD) const
QualType getFunctionTypeWithExceptionSpec(QualType Orig, const FunctionProtoType::ExceptionSpecInfo &ESI) const
Get a function type and produce the equivalent function type with the specified exception specificati...
QualType getBaseElementType(const ArrayType *VAT) const
Return the innermost element type of an array type.
bool hasAnyFunctionEffects() const
const ArrayType * getAsArrayType(QualType T) const
Type Query functions.
CharUnits getTypeSizeInChars(QualType T) const
Return the size of the specified (complete) type T, in characters.
static bool hasSameType(QualType T1, QualType T2)
Determine whether the given types T1 and T2 are equivalent.
const VariableArrayType * getAsVariableArrayType(QualType T) const
QualType getSizeType() const
Return the unique type for "size_t" (C99 7.17), defined in <stddef.h>.
const TargetInfo & getTargetInfo() const
Represents an array type, per C99 6.7.5.2 - Array Declarators.
QualType getElementType() const
Attr - This represents one attribute.
A builtin binary operation expression such as "x + y" or "x <= y".
static bool isLogicalOp(Opcode Opc)
BinaryOperatorKind Opcode
Represents a C++ constructor within a class.
Represents a static or instance method of a struct/union/class.
bool isImplicitObjectMemberFunction() const
[C++2b][dcl.fct]/p7 An implicit object member function is a non-static member function without an exp...
const CXXRecordDecl * getParent() const
Return the parent of this method declaration, which is the class in which this method is defined.
QualType getThisType() const
Return the type of the this pointer.
QualType getFunctionObjectParameterType() const
bool isCopyAssignmentOperator() const
Determine whether this is a copy-assignment operator, regardless of whether it was declared implicitl...
bool isLambda() const
Determine whether this class describes a lambda function object.
void getCaptureFields(llvm::DenseMap< const ValueDecl *, FieldDecl * > &Captures, FieldDecl *&ThisCapture) const
For a closure type, retrieve the mapping from captured variables and this to the non-static data memb...
bool isCapturelessLambda() const
bool isEmpty() const
Determine whether this is an empty class in the sense of (C++11 [meta.unary.prop]).
A C++ throw-expression (C++ [except.throw]).
CallExpr - Represents a function call (C99 6.5.2.2, C++ [expr.call]).
Expr * getArg(unsigned Arg)
getArg - Return the specified argument.
This is an opaque type for sizes expressed in character units.
bool isZero() const
Test whether the quantity equals zero.
llvm::Align getAsAlign() const
Returns Quantity as a valid llvm::Align, Beware llvm::Align assumes power of two 8-bit bytes.
QuantityType getQuantity() const
Get the raw integer representation of this quantity.
CharUnits alignmentOfArrayElement(CharUnits elementSize) const
Given that this is the alignment of the first element of an array, return the minimum alignment of an...
bool isOne() const
Test whether the quantity equals one.
@ InAlloca
InAlloca - Pass the argument directly using the LLVM inalloca attribute.
@ Indirect
Indirect - Pass the argument indirectly via a hidden pointer with the specified alignment (0 indicate...
Like RawAddress, an abstract representation of an aligned address, but the pointer contained in this ...
llvm::Value * getBasePointer() const
llvm::Value * emitRawPointer(CodeGenFunction &CGF) const
Return the pointer contained in this class after authenticating it and adding offset to it if necessa...
CharUnits getAlignment() const
llvm::Type * getElementType() const
Return the type of the values stored in this address.
Address withElementType(llvm::Type *ElemTy) const
Return address with different element type, but same pointer and alignment.
llvm::PointerType * getType() const
Return the type of the pointer value.
A scoped helper to set the current source atom group for CGDebugInfo::addInstToCurrentSourceAtom.
A scoped helper to set the current debug location to the specified location or preferred location of ...
static ApplyDebugLocation CreateDefaultArtificial(CodeGenFunction &CGF, SourceLocation TemporaryLocation)
Apply TemporaryLocation if it is valid.
void InsertHelper(llvm::Instruction *I, const llvm::Twine &Name, llvm::BasicBlock::iterator InsertPt) const
This forwards to CodeGenFunction::InsertHelper.
llvm::ConstantInt * getSize(CharUnits N)
@ RAA_DirectInMemory
Pass it on the stack using its defined layout.
virtual RecordArgABI getRecordArgABI(const CXXRecordDecl *RD) const =0
Returns how an argument of the given record type should be passed.
Abstract information about a function or function prototype.
const FunctionProtoType * getCalleeFunctionProtoType() const
All available information about a concrete callee.
static CGCallee forDirect(llvm::Constant *functionPtr, const CGCalleeInfo &abstractInfo=CGCalleeInfo())
This class gathers all debug information during compilation and is responsible for emitting to llvm g...
CGFunctionInfo - Class to encapsulate the information about a function definition.
bool isDelegateCall() const
llvm::Value * getDiscriminator() const
CallArgList - Type for representing both the value and type of arguments in a call.
void add(RValue rvalue, QualType type)
virtual ~CGCapturedStmtInfo()
CGFPOptionsRAII(CodeGenFunction &CGF, FPOptions FPFeatures)
An object to manage conditionally-evaluated expressions.
void begin(CodeGenFunction &CGF)
void end(CodeGenFunction &CGF)
An object which temporarily prevents a value from being destroyed by aggressive peephole optimization...
SanitizerScope(CodeGenFunction *CGF)
CodeGenFunction - This class organizes the per-function state that is used while generating LLVM code...
void EmitRISCVMultiVersionResolver(llvm::Function *Resolver, ArrayRef< FMVResolverOption > Options)
GlobalDecl CurGD
CurGD - The GlobalDecl for the current function being compiled.
void EmitBranchOnBoolExpr(const Expr *Cond, llvm::BasicBlock *TrueBlock, llvm::BasicBlock *FalseBlock, uint64_t TrueCount, Stmt::Likelihood LH=Stmt::LH_None, const Expr *ConditionalOp=nullptr, const VarDecl *ConditionalDecl=nullptr)
EmitBranchOnBoolExpr - Emit a branch on a boolean condition (e.g.
void setCurrentProfileCount(uint64_t Count)
Set the profiler's current count.
llvm::CallInst * EmitTrapCall(llvm::Intrinsic::ID IntrID, bool EnsureInsertPoint=true)
Emit a call to trap or debugtrap.
llvm::Value * emitBoolVecConversion(llvm::Value *SrcVec, unsigned NumElementsDst, const llvm::Twine &Name="")
void EmitAArch64MultiVersionResolver(llvm::Function *Resolver, ArrayRef< FMVResolverOption > Options)
JumpDest getJumpDestInCurrentScope(llvm::BasicBlock *Target)
The given basic block lies in the current EH scope, but may be a target of a potentially scope-crossi...
llvm::Value * EmitScalarOrConstFoldImmArg(unsigned ICEArguments, unsigned Idx, const CallExpr *E)
SanitizerSet SanOpts
Sanitizers enabled for this function.
@ UseSkipPath
Skip (false)
void EmitNullInitialization(Address DestPtr, QualType Ty)
EmitNullInitialization - Generate code to set a value of the given type to null, If the type contains...
void checkTargetFeatures(const CallExpr *E, const FunctionDecl *TargetDecl)
static bool ContainsLabel(const Stmt *S, bool IgnoreCaseStmts=false)
ContainsLabel - Return true if the statement contains a label in it.
void EmitPPCAIXMultiVersionResolver(llvm::Function *Resolver, ArrayRef< FMVResolverOption > Options)
define internal ptr @foo.resolver() { entry: is_version_1 = __builtin_cpu_supports(version_1) br i1 %...
bool ShouldSkipSanitizerInstrumentation()
ShouldSkipSanitizerInstrumentation - Return true if the current function should not be instrumented w...
llvm::Value * EmitPPCBuiltinCpu(unsigned BuiltinID, llvm::Type *ReturnType, StringRef CPUStr)
llvm::BlockAddress * GetAddrOfLabel(const LabelDecl *L)
llvm::Value * EmitRISCVCpuSupports(const CallExpr *E)
llvm::Value * EmitRISCVCpuInit()
static bool hasScalarEvaluationKind(QualType T)
llvm::Type * ConvertType(QualType T)
void GenerateCode(GlobalDecl GD, llvm::Function *Fn, const CGFunctionInfo &FnInfo)
void EmitSanitizerStatReport(llvm::SanitizerStatKind SSK)
void addInstToNewSourceAtom(llvm::Instruction *KeyInstruction, llvm::Value *Backup)
Add KeyInstruction and an optional Backup instruction to a new atom group (See ApplyAtomGroup for mor...
FieldDecl * LambdaThisCaptureField
PeepholeProtection protectFromPeepholes(RValue rvalue)
protectFromPeepholes - Protect a value that we're intending to store to the side, but which will prob...
void EmitLambdaStaticInvokeBody(const CXXMethodDecl *MD)
bool CurFuncIsThunk
In C++, whether we are code generating a thunk.
LValue MakeNaturalAlignPointeeAddrLValue(llvm::Value *V, QualType T)
Given a value of type T* that may not be to a complete object, construct an l-value with the natural ...
JumpDest getJumpDestForLabel(const LabelDecl *S)
getBasicBlockForLabel - Return the LLVM basicblock that the specified label maps to.
void EmitCXXThrowExpr(const CXXThrowExpr *E, bool KeepInsertionPoint=true)
SmallVector< llvm::ConvergenceControlInst *, 4 > ConvergenceTokenStack
Stack to track the controlled convergence tokens.
void unprotectFromPeepholes(PeepholeProtection protection)
RValue convertTempToRValue(Address addr, QualType type, SourceLocation Loc)
Given the address of a temporary variable, produce an r-value of its type.
llvm::Constant * EmitCheckSourceLocation(SourceLocation Loc)
Emit a description of a source location in a format suitable for passing to a runtime sanitizer handl...
llvm::SmallVector< DeferredDeactivateCleanup > DeferredDeactivationCleanupStack
llvm::BasicBlock * createBasicBlock(const Twine &name="", llvm::Function *parent=nullptr, llvm::BasicBlock *before=nullptr)
createBasicBlock - Create an LLVM basic block.
void addInstToCurrentSourceAtom(llvm::Instruction *KeyInstruction, llvm::Value *Backup)
See CGDebugInfo::addInstToCurrentSourceAtom.
const LangOptions & getLangOpts() const
void addInstToSpecificSourceAtom(llvm::Instruction *KeyInstruction, llvm::Value *Backup, uint64_t Atom)
See CGDebugInfo::addInstToSpecificSourceAtom.
LValue MakeNaturalAlignAddrLValue(llvm::Value *V, QualType T, KnownNonNull_t IsKnownNonNull=NotKnownNonNull)
void EmitVarAnnotations(const VarDecl *D, llvm::Value *V)
Emit local annotations for the local variable V, declared by D.
llvm::BasicBlock * EHResumeBlock
EHResumeBlock - Unified block containing a call to llvm.eh.resume.
Address EmitFieldAnnotations(const FieldDecl *D, Address V)
Emit field annotations for the given field & value.
void EmitConstructorBody(FunctionArgList &Args)
EmitConstructorBody - Emits the body of the current constructor.
void EmitKCFIOperandBundle(const CGCallee &Callee, SmallVectorImpl< llvm::OperandBundleDef > &Bundles)
void EmitDeclRefExprDbgValue(const DeclRefExpr *E, const APValue &Init)
Address makeNaturalAddressForPointer(llvm::Value *Ptr, QualType T, CharUnits Alignment=CharUnits::Zero(), bool ForPointeeType=false, LValueBaseInfo *BaseInfo=nullptr, TBAAAccessInfo *TBAAInfo=nullptr, KnownNonNull_t IsKnownNonNull=NotKnownNonNull)
Construct an address with the natural alignment of T.
LValue MakeNaturalAlignPointeeRawAddrLValue(llvm::Value *V, QualType T)
Same as MakeNaturalAlignPointeeAddrLValue except that the pointer is known to be unsigned.
@ TCK_ConstructorCall
Checking the 'this' pointer for a constructor call.
@ TCK_MemberCall
Checking the 'this' pointer for a call to a non-static member function.
const Decl * CurCodeDecl
CurCodeDecl - This is the inner-most code context, which includes blocks.
bool hasSkipCounter(const Stmt *S) const
llvm::AssertingVH< llvm::Instruction > AllocaInsertPt
AllocaInsertPoint - This is an instruction in the entry block before which we prefer to insert alloca...
void EmitFunctionBody(const Stmt *Body)
JumpDest ReturnBlock
ReturnBlock - Unified return block.
llvm::DebugLoc SourceLocToDebugLoc(SourceLocation Location)
Converts Location to a DebugLoc, if debug information is enabled.
llvm::Constant * EmitCheckTypeDescriptor(QualType T)
Emit a description of a type in a format suitable for passing to a runtime sanitizer handler.
llvm::DebugLoc EmitReturnBlock()
Emit the unified return block, trying to avoid its emission when possible.
RawAddress CreateDefaultAlignTempAlloca(llvm::Type *Ty, const Twine &Name="tmp")
CreateDefaultAlignedTempAlloca - This creates an alloca with the default ABI alignment of the given L...
const TargetInfo & getTarget() const
llvm::Value * EmitAnnotationCall(llvm::Function *AnnotationFn, llvm::Value *AnnotatedVal, StringRef AnnotationStr, SourceLocation Location, const AnnotateAttr *Attr)
Emit an annotation call (intrinsic).
Address EmitCompoundStmtWithoutScope(const CompoundStmt &S, bool GetLast=false, AggValueSlot AVS=AggValueSlot::ignored())
void PopCleanupBlocks(EHScopeStack::stable_iterator OldCleanupStackSize, std::initializer_list< llvm::Value ** > ValuesToReload={})
Takes the old cleanup stack size and emits the cleanup blocks that have been added.
void maybeCreateMCDCCondBitmap()
Allocate a temp value on the stack that MCDC can use to track condition results.
void emitReturnAlignmentAssumptionCheck(llvm::Value *Ptr, QualType Ty, SourceLocation AssumptionLoc, llvm::Value *Alignment, llvm::Value *OffsetValue=nullptr)
void EmitIgnoredExpr(const Expr *E)
EmitIgnoredExpr - Emit an expression in a context which ignores the result.
RValue EmitLoadOfLValue(LValue V, SourceLocation Loc)
EmitLoadOfLValue - Given an expression that represents a value lvalue, this method emits the address ...
static bool isInstrumentedCondition(const Expr *C)
isInstrumentedCondition - Determine whether the given condition is an instrumentable condition (i....
VlaSizePair getVLAElements1D(const VariableArrayType *vla)
Return the number of elements for a single dimension for the given array type.
RawAddress CreateIRTempWithoutCast(QualType T, const Twine &Name="tmp")
CreateIRTempWithoutCast - Create a temporary IR object of the given type, with appropriate alignment.
bool AlwaysEmitXRayCustomEvents() const
AlwaysEmitXRayCustomEvents - Return true if we must unconditionally emit XRay custom event handling c...
void StartFunction(GlobalDecl GD, QualType RetTy, llvm::Function *Fn, const CGFunctionInfo &FnInfo, const FunctionArgList &Args, SourceLocation Loc=SourceLocation(), SourceLocation StartLoc=SourceLocation())
Emit code for the start of a function.
llvm::Value * EmitPointerAuthSign(const CGPointerAuthInfo &Info, llvm::Value *Pointer)
void markAsIgnoreThreadCheckingAtRuntime(llvm::Function *Fn)
Annotate the function with an attribute that disables TSan checking at runtime.
llvm::Value * EvaluateExprAsBool(const Expr *E)
EvaluateExprAsBool - Perform the usual unary conversions on the specified expression and compare the ...
void EmitPointerAuthOperandBundle(const CGPointerAuthInfo &Info, SmallVectorImpl< llvm::OperandBundleDef > &Bundles)
void EmitCheck(ArrayRef< std::pair< llvm::Value *, SanitizerKind::SanitizerOrdinal > > Checked, SanitizerHandler Check, ArrayRef< llvm::Constant * > StaticArgs, ArrayRef< llvm::Value * > DynamicArgs, const TrapReason *TR=nullptr)
Create a basic block that will either trap or call a handler function in the UBSan runtime with the p...
void InsertHelper(llvm::Instruction *I, const llvm::Twine &Name, llvm::BasicBlock::iterator InsertPt) const
CGBuilder insert helper.
llvm::Value * emitArrayLength(const ArrayType *arrayType, QualType &baseType, Address &addr)
emitArrayLength - Compute the length of an array, even if it's a VLA, and drill down to the base elem...
bool HaveInsertPoint() const
HaveInsertPoint - True if an insertion point is defined.
bool AlwaysEmitXRayTypedEvents() const
AlwaysEmitXRayTypedEvents - Return true if clang must unconditionally emit XRay typed event handling ...
CGDebugInfo * getDebugInfo()
void EmitStartEHSpec(const Decl *D)
EmitStartEHSpec - Emit the start of the exception spec.
void EmitDestructorBody(FunctionArgList &Args)
EmitDestructorBody - Emits the body of the current destructor.
void EmitX86MultiVersionResolver(llvm::Function *Resolver, ArrayRef< FMVResolverOption > Options)
bool ShouldInstrumentFunction()
ShouldInstrumentFunction - Return true if the current function should be instrumented with __cyg_prof...
void maybeUpdateMCDCCondBitmap(const Expr *E, llvm::Value *Val)
Update the MCDC temp value with the condition's evaluated result.
RValue EmitCall(const CGFunctionInfo &CallInfo, const CGCallee &Callee, ReturnValueSlot ReturnValue, const CallArgList &Args, llvm::CallBase **CallOrInvoke, bool IsMustTail, SourceLocation Loc, bool IsVirtualFunctionPointerThunk=false)
EmitCall - Generate a call of the given function, expecting the given result type,...
llvm::ConstantInt * getUBSanFunctionTypeHash(QualType T) const
Return a type hash constant for a function instrumented by -fsanitize=function.
void EmitBranchToCounterBlock(const Expr *Cond, BinaryOperator::Opcode LOp, llvm::BasicBlock *TrueBlock, llvm::BasicBlock *FalseBlock, uint64_t TrueCount=0, Stmt::Likelihood LH=Stmt::LH_None, const Expr *CntrIdx=nullptr)
EmitBranchToCounterBlock - Emit a conditional branch to a new block that increments a profile counter...
void emitAlignmentAssumptionCheck(llvm::Value *Ptr, QualType Ty, SourceLocation Loc, SourceLocation AssumptionLoc, llvm::Value *Alignment, llvm::Value *OffsetValue=nullptr)
VlaSizePair getVLASize(const VariableArrayType *vla)
Returns an LLVM value that corresponds to the size, in non-variably-sized elements,...
ASTContext & getContext() const
bool isMCDCBranchExpr(const Expr *E) const
void EmitMultiVersionResolver(llvm::Function *Resolver, ArrayRef< FMVResolverOption > Options)
const Decl * CurFuncDecl
CurFuncDecl - Holds the Decl for the current outermost non-closure context.
static const Expr * stripCond(const Expr *C)
Ignore parentheses and logical-NOT to track conditions consistently.
void EmitFunctionProlog(const CGFunctionInfo &FI, llvm::Function *Fn, const FunctionArgList &Args)
EmitFunctionProlog - Emit the target specific LLVM code to load the arguments for the given function.
Address EmitAddressOfPFPField(Address RecordPtr, const PFPField &Field)
void SetFastMathFlags(FPOptions FPFeatures)
Set the codegen fast-math flags.
llvm::SmallVector< char, 256 > LifetimeExtendedCleanupStack
Address EmitVAListRef(const Expr *E)
void EmitLambdaInAllocaCallOpBody(const CXXMethodDecl *MD)
Address ReturnValuePointer
ReturnValuePointer - The temporary alloca to hold a pointer to sret.
static bool mightAddDeclToScope(const Stmt *S)
Determine if the given statement might introduce a declaration into the current scope,...
void EmitStmt(const Stmt *S, ArrayRef< const Attr * > Attrs={})
EmitStmt - Emit the code for the statement.
llvm::DenseMap< const ValueDecl *, FieldDecl * > LambdaCaptureFields
bool AutoreleaseResult
In ARC, whether we should autorelease the return value.
llvm::CallInst * EmitRuntimeCall(llvm::FunctionCallee callee, const Twine &name="")
uint64_t getCurrentProfileCount()
Get the profiler's current count.
llvm::Type * ConvertTypeForMem(QualType T)
void EmitEndEHSpec(const Decl *D)
EmitEndEHSpec - Emit the end of the exception spec.
LValue EmitLValueForLambdaField(const FieldDecl *Field)
void emitPFPPostCopyUpdates(Address DestPtr, Address SrcPtr, QualType Ty)
Copy all PFP fields from SrcPtr to DestPtr while updating signatures, assuming that DestPtr was alrea...
Address EmitZOSVAListRef(const Expr *E)
Emit a "reference" to a __builtin_zos_va_list; this is always the address of the expression,...
CodeGenTypes & getTypes() const
static TypeEvaluationKind getEvaluationKind(QualType T)
getEvaluationKind - Return the TypeEvaluationKind of QualType T.
bool IsSanitizerScope
True if CodeGen currently emits code implementing sanitizer checks.
static bool containsBreak(const Stmt *S)
containsBreak - Return true if the statement contains a break out of it.
void emitImplicitAssignmentOperatorBody(FunctionArgList &Args)
HLSLControlFlowHintAttr::Spelling HLSLControlFlowAttr
HLSL Branch attribute.
void EmitTypeCheck(TypeCheckKind TCK, SourceLocation Loc, LValue LV, QualType Type, SanitizerSet SkippedChecks=SanitizerSet(), llvm::Value *ArraySize=nullptr)
llvm::SmallVector< const ParmVarDecl *, 4 > FnArgs
Save Parameter Decl for coroutine.
const TargetInfo & Target
void EmitFunctionEpilog(const CGFunctionInfo &FI, bool EmitRetDbgLoc, SourceLocation EndLoc, uint64_t RetKeyInstructionsSourceAtom)
EmitFunctionEpilog - Emit the target specific LLVM code to return the given temporary.
Address EmitPointerWithAlignment(const Expr *Addr, LValueBaseInfo *BaseInfo=nullptr, TBAAAccessInfo *TBAAInfo=nullptr, KnownNonNull_t IsKnownNonNull=NotKnownNonNull)
EmitPointerWithAlignment - Given an expression with a pointer type, emit the value and compute our be...
void EmitBranch(llvm::BasicBlock *Block)
EmitBranch - Emit a branch to the specified basic block from the current insert block,...
RawAddress NormalCleanupDest
i32s containing the indexes of the cleanup destinations.
llvm::Type * convertTypeForLoadStore(QualType ASTTy, llvm::Type *LLVMTy=nullptr)
VarBypassDetector Bypasses
llvm::BasicBlock * GetIndirectGotoBlock()
EHScopeStack::stable_iterator PrologueCleanupDepth
PrologueCleanupDepth - The cleanup depth enclosing all the cleanups associated with the parameters.
Address EmitMSVAListRef(const Expr *E)
Emit a "reference" to a __builtin_ms_va_list; this is always the value of the expression,...
llvm::Value * EmitScalarExpr(const Expr *E, bool IgnoreResultAssign=false)
EmitScalarExpr - Emit the computation of the specified expression of LLVM scalar type,...
const FunctionDecl * getCurrentFunctionDecl() const
LValue MakeAddrLValue(Address Addr, QualType T, AlignmentSource Source=AlignmentSource::Type)
void EmitTrapCallAndMakeUnreachable()
Emit a call to '@llvm.trap()' and clear the current insert point.
void FinishFunction(SourceLocation EndLoc=SourceLocation())
FinishFunction - Complete IR generation of the current function.
const CGFunctionInfo * CurFnInfo
uint64_t getProfileCount(const Stmt *S)
Get the profiler's count for the given statement.
Address GetAddrOfLocalVar(const VarDecl *VD)
GetAddrOfLocalVar - Return the address of a local variable.
bool ConstantFoldsToSimpleInteger(const Expr *Cond, bool &Result, bool AllowLabels=false)
ConstantFoldsToSimpleInteger - If the specified expression does not fold to a constant,...
void ErrorUnsupported(const Stmt *S, const char *Type)
ErrorUnsupported - Print out an error that codegen doesn't support the specified stmt yet.
Address ReturnValue
ReturnValue - The temporary alloca to hold the return value.
LValue EmitLValue(const Expr *E, KnownNonNull_t IsKnownNonNull=NotKnownNonNull)
EmitLValue - Emit code to compute a designator that specifies the location of the expression.
bool ShouldXRayInstrumentFunction() const
ShouldXRayInstrument - Return true if the current function should be instrumented with XRay nop sleds...
void EnsureInsertPoint()
EnsureInsertPoint - Ensure that an insertion point is defined so that emitted IR has a place to go.
llvm::LLVMContext & getLLVMContext()
bool SawAsmBlock
Whether we processed a Microsoft-style asm block during CodeGen.
bool checkIfFunctionMustProgress()
Returns true if a function must make progress, which means the mustprogress attribute can be added.
void incrementProfileCounter(const Stmt *S, llvm::Value *StepV=nullptr)
Increment the profiler's counter for the given statement by StepV.
void emitAlignmentAssumption(llvm::Value *PtrValue, QualType Ty, SourceLocation Loc, SourceLocation AssumptionLoc, llvm::Value *Alignment, llvm::Value *OffsetValue=nullptr)
bool isMCDCDecisionExpr(const Expr *E) const
void EmitVariablyModifiedType(QualType Ty)
EmitVLASize - Capture all the sizes for the VLA expressions in the given variably-modified type and s...
void MaybeEmitDeferredVarDeclInit(const VarDecl *var)
void EmitBlockWithFallThrough(llvm::BasicBlock *BB, const Stmt *S)
When instrumenting to collect profile data, the counts for some blocks such as switch cases need to n...
void EmitBlock(llvm::BasicBlock *BB, bool IsFinished=false)
EmitBlock - Emit the given block.
LValue MakeNaturalAlignRawAddrLValue(llvm::Value *V, QualType T)
QualType BuildFunctionArgList(GlobalDecl GD, FunctionArgList &Args)
llvm::Value * EmitPointerAuthAuth(const CGPointerAuthInfo &Info, llvm::Value *Pointer)
This class organizes the cross-function state that is used while generating LLVM code.
CharUnits getNaturalTypeAlignment(QualType T, LValueBaseInfo *BaseInfo=nullptr, TBAAAccessInfo *TBAAInfo=nullptr, bool forPointeeType=false)
CodeGenTypes & getTypes()
const TargetCodeGenInfo & getTargetCodeGenInfo()
const CodeGenOptions & getCodeGenOpts() const
void GenKernelArgMetadata(llvm::Function *FN, const FunctionDecl *FD=nullptr, CodeGenFunction *CGF=nullptr)
OpenCL v1.2 s5.6.4.6 allows the compiler to store kernel argument information in the program executab...
llvm::Function * getIntrinsic(unsigned IID, ArrayRef< llvm::Type * > Tys={})
llvm::Type * ConvertType(QualType T)
ConvertType - Convert type T into a llvm::Type.
bool inheritingCtorHasParams(const InheritedConstructor &Inherited, CXXCtorType Type)
Determine if a C++ inheriting constructor should have parameters matching those of its inherited cons...
FunctionArgList - Type for representing both the decl and type of parameters to a function.
LValue - This represents an lvalue references.
llvm::Value * getPointer(CodeGenFunction &CGF) const
Address getAddress() const
RValue - This trivial value class is used to represent the result of an expression that is evaluated.
llvm::Value * getScalarVal() const
getScalarVal() - Return the Value* of this scalar value.
ReturnValueSlot - Contains the address where the return value of a function can be stored,...
virtual llvm::Constant * getUBSanFunctionSignature(CodeGen::CodeGenModule &CGM) const
Return a constant used by UBSan as a signature to identify functions possessing type information,...
CompoundStmt - This represents a group of statements like { stmt stmt }.
ConditionalOperator - The ?
A reference to a declared variable, function, enum, etc.
Decl - This represents one declaration (or definition), e.g.
ASTContext & getASTContext() const LLVM_READONLY
virtual Stmt * getBody() const
getBody - If this Decl represents a declaration for a body of code, such as a function or method defi...
Decl * getNonClosureContext()
Find the innermost non-closure ancestor of this declaration, walking up through blocks,...
llvm::iterator_range< specific_attr_iterator< T > > specific_attrs() const
SourceLocation getLocation() const
This represents one expression.
bool EvaluateAsInt(EvalResult &Result, const ASTContext &Ctx, SideEffectsKind AllowSideEffects=SE_NoSideEffects, bool InConstantContext=false) const
EvaluateAsInt - Return true if this is a constant which we can fold and convert to an integer,...
FPOptions getFPFeaturesInEffect(const LangOptions &LO) const
Returns the set of floating point options that apply to this expression.
Expr * IgnoreParens() LLVM_READONLY
Skip past any parentheses which might surround this expression until reaching a fixed point.
std::optional< llvm::APSInt > getIntegerConstantExpr(const ASTContext &Ctx, bool AllowRelaxedEval=false) const
isIntegerConstantExpr - Return the value if this expression is a valid integer constant expression.
Expr * IgnoreImpCasts() LLVM_READONLY
Skip past any implicit casts which might surround this expression until reaching a fixed point.
SourceLocation getExprLoc() const LLVM_READONLY
getExprLoc - Return the preferred location for the arrow when diagnosing a problem with a generic exp...
ExtVectorType - Extended vector type.
LangOptions::FPExceptionModeKind getExceptionMode() const
bool allowFPContractAcrossStatement() const
RoundingMode getRoundingMode() const
Represents a member of a struct/union/class.
Represents a function declaration or definition.
Stmt * getBody(const FunctionDecl *&Definition) const
Retrieve the body (definition) of the function.
unsigned getBuiltinID(bool ConsiderWrapperFunctions=false) const
Returns a value indicating whether this function corresponds to a builtin function.
bool UsesFPIntrin() const
Determine whether the function was declared in source context that requires constrained FP intrinsics...
bool usesSEHTry() const
Indicates the function uses __try.
QualType getReturnType() const
ArrayRef< ParmVarDecl * > parameters() const
FunctionDecl * getTemplateInstantiationPattern(bool ForDefinition=true) const
Retrieve the function declaration from which this function could be instantiated, if it is an instant...
FunctionEffectsRef getFunctionEffects() const
bool isMSVCRTEntryPoint() const
Determines whether this function is a MSVCRT user defined entry point.
bool isInlineBuiltinDeclaration() const
Determine if this function provides an inline implementation of a builtin.
bool hasImplicitReturnZero() const
Whether falling off this function implicitly returns null/zero.
bool isMain() const
Determines whether this function is "main", which is the entry point into an executable program.
bool isDefaulted() const
Whether this function is defaulted.
OverloadedOperatorKind getOverloadedOperator() const
getOverloadedOperator - Which C++ overloaded operator this function represents, if any.
FunctionDecl * getPreviousDecl()
Return the previous declaration of this declaration or NULL if this is the first declaration.
Represents a prototype with parameter type info, e.g.
FunctionTypeExtraAttributeInfo getExtraAttributeInfo() const
Return the extra attribute information.
FunctionType - C99 6.7.5.3 - Function Declarators.
@ SME_PStateSMCompatibleMask
GlobalDecl - represents a global declaration.
CXXCtorType getCtorType() const
KernelReferenceKind getKernelReferenceKind() const
const Decl * getDecl() const
One of these records is kept for each identifier that is lexed.
bool isStr(const char(&Str)[StrLen]) const
Return true if this is the identifier for the specified string.
static ImplicitParamDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation IdLoc, const IdentifierInfo *Id, QualType T, ImplicitParamKind ParamKind)
Create implicit parameter.
Represents the declaration of a label.
FPExceptionModeKind
Possible floating point exception behavior.
@ FPE_Strict
Strictly preserve the floating-point exception semantics.
@ FPE_MayTrap
Transformations do not cause new exceptions but may hide some.
@ FPE_Ignore
Assume that floating-point exceptions are masked.
RoundingMode getDefaultRoundingMode() const
Represents a parameter to a function.
PointerType - C99 6.7.5.1 - Pointer Declarators.
@ Forbid
Profiling is forbidden using the noprofile attribute.
@ Skip
Profiling is skipped using the skipprofile attribute.
@ Allow
Profiling is allowed.
A (possibly-)qualified type.
bool isVolatileQualified() const
Determine whether this type is volatile-qualified.
field_range fields() const
Encodes a location in the source.
A trivial tuple used to represent a source range.
Stmt - This represents one statement.
StmtClass getStmtClass() const
Likelihood
The likelihood of a branch being taken.
@ LH_Unlikely
Branch has the [[unlikely]] attribute.
@ LH_None
No attribute set or branches of the IfStmt have the same attribute.
@ LH_Likely
Branch has the [[likely]] attribute.
bool isMicrosoft() const
Is this ABI an MSVC-compatible ABI?
const llvm::Triple & getTriple() const
Returns the target triple of the primary target.
bool supportsIFunc() const
Identify whether this target supports IFuncs.
TargetCXXABI getCXXABI() const
Get the C++ ABI currently in use.
virtual ParsedTargetAttr parseTargetAttr(StringRef Str) const
bool isSignedIntegerType() const
Return true if this is an integer type that is signed, according to C99 6.2.5p4 [char,...
CXXRecordDecl * getAsCXXRecordDecl() const
Retrieves the CXXRecordDecl that this type refers to, either because the type is a RecordType or beca...
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee.
bool isVariablyModifiedType() const
Whether this type is a variably-modified type (C99 6.7.5).
TypeClass getTypeClass() const
const T * getAs() const
Member-template getAs<specific type>'.
bool isObjCRetainableType() const
bool isFunctionNoProtoType() const
bool isCFIUncheckedCalleeFunctionType() const
UnaryOperator - This represents the unary-expression's (except sizeof and alignof),...
Represents a variable declaration or definition.
Represents a C array with a specified size that is not an integer-constant-expression.
Expr * getSizeExpr() const
QualType getElementType() const
Defines the clang::TargetInfo interface.
void checkTargetFeatures(ASTContext &Ctx, DiagnosticsEngine &Diags, const LangOptions &LangOpts, const CallExpr *E, const FunctionDecl *Caller, const FunctionDecl *TargetDecl)
Check that a call to a target-specific builtin has the required target features enabled in the caller...
@ Type
The l-value was considered opaque, so the alignment was determined from a type.
@ Decl
The l-value was an access to a declared entity or something equivalently strong, like the address of ...
TypeEvaluationKind
The kind of evaluation to perform on values of a particular type.
CGBuilderInserter CGBuilderInserterTy
constexpr XRayInstrMask Typed
constexpr XRayInstrMask FunctionExit
constexpr XRayInstrMask FunctionEntry
constexpr XRayInstrMask Custom
const internal::VariadicAllOfMatcher< Type > type
Matches Types in the clang AST.
const AstTypeMatcher< ArrayType > arrayType
Top level wrappers for InstallAPI frontend operations.
bool isa(CodeGen::Address addr)
Expr * IgnoreBuiltinExpectSingleStep(Expr *E)
@ NonNull
Values of this type can never be null.
Expr * IgnoreExprNodes(Expr *E, FnTys &&... Fns)
Given an expression E and functions Fn_1,...,Fn_n : Expr * -> Expr *, Recursively apply each of the f...
nullptr
This class represents a compute construct, representing a 'Kind' of ‘parallel’, 'serial',...
bool isLambdaCallOperator(const CXXMethodDecl *MD)
@ Result
The result type of a method or function.
Expr * IgnoreImplicitCastsSingleStep(Expr *E)
Expr * IgnoreUOpLNotSingleStep(Expr *E)
Expr * IgnoreParensSingleStep(Expr *E)
llvm::fp::ExceptionBehavior ToConstrainedExceptMD(LangOptions::FPExceptionModeKind Kind)
U cast(CodeGen::Address addr)
bool IsArmStreamingFunction(const FunctionDecl *FD, bool IncludeLocallyStreaming)
Returns whether the given FunctionDecl has an __arm[_locally]_streaming attribute.
@ Other
Other implicit parameter.
@ EST_None
no exception specification
@ Implicit
An implicit conversion.
A jump destination is an abstract label, branching to which may require a jump out through normal cle...
llvm::BasicBlock * getBlock() const
This structure provides a set of types that are commonly used during IR emission.
llvm::PointerType * VoidPtrTy
llvm::IntegerType * Int8Ty
i8, i16, i32, and i64
llvm::IntegerType * SizeTy
llvm::IntegerType * Int32Ty
llvm::IntegerType * IntPtrTy
llvm::PointerType * Int8PtrTy
CharUnits getPointerAlign() const
EvalResult is a struct with detailed info about an evaluated expression.
A FunctionEffect plus a potential boolean expression determining whether the effect is declared (e....
std::vector< std::string > Features
void set(SanitizerMask K, bool Value)
Enable or disable a certain (single) sanitizer.
bool has(SanitizerMask K) const
Check if a certain (single) sanitizer is enabled.