41#include "llvm/ADT/STLExtras.h"
42#include "llvm/ADT/ScopeExit.h"
43#include "llvm/ADT/StringExtras.h"
44#include "llvm/IR/Constants.h"
45#include "llvm/IR/DataLayout.h"
46#include "llvm/IR/Intrinsics.h"
47#include "llvm/IR/LLVMContext.h"
48#include "llvm/IR/MDBuilder.h"
49#include "llvm/IR/MatrixBuilder.h"
50#include "llvm/Support/ConvertUTF.h"
51#include "llvm/Support/Endian.h"
52#include "llvm/Support/MathExtras.h"
53#include "llvm/Support/Path.h"
54#include "llvm/Support/xxhash.h"
55#include "llvm/Transforms/Utils/SanitizerStats.h"
68 "ubsan-guard-checks", llvm::cl::Optional,
69 llvm::cl::desc(
"Guard UBSAN checks with `llvm.allow.ubsan.check()`."));
95#define SANITIZER_CHECK(Enum, Name, Version, Msg) \
96 case SanitizerHandler::Enum: \
101 llvm_unreachable(
"unhandled switch case");
109 llvm::Value *ArraySize) {
111 auto Alloca =
Builder.CreateStructuredAlloca(Ty, Name);
122 llvm::Value *ArraySize) {
132 llvm::IRBuilderBase::InsertPointGuard IPG(Builder);
147 llvm::Value *ArraySize,
151 *AllocaAddr = Alloca;
152 return MaybeCastStackAddressSpace(Alloca, DestLangAS, ArraySize);
160 llvm::Value *ArraySize) {
161 llvm::AllocaInst *Alloca;
163 Alloca =
Builder.CreateAlloca(Ty, ArraySize, Name);
166 new llvm::AllocaInst(Ty,
CGM.getDataLayout().getAllocaAddrSpace(),
168 if (
SanOpts.Mask & SanitizerKind::Address) {
169 Alloca->addAnnotationMetadata({
"alloca_name_altered", Name.str()});
172 Allocas->Add(Alloca);
209 auto *ArrayElementTy = ArrayTy->getElementType();
210 auto ArrayElements = ArrayTy->getNumElements();
213 ArrayElementTy = VectorTy->getElementType();
214 ArrayElements *= VectorTy->getNumElements();
216 auto *VectorTy = llvm::FixedVectorType::get(ArrayElementTy, ArrayElements);
239 PGO->setCurrentStmt(E);
242 return CGM.getCXXABI().EmitMemberPointerIsNotNull(*
this, MemPtr, MPT);
265 if (
const auto *CondOp = dyn_cast<AbstractConditionalOperator>(
288 if (!ignoreResult && aggSlot.
isIgnored())
293 llvm_unreachable(
"bad evaluation kind");
335 llvm_unreachable(
"bad evaluation kind");
358 llvm_unreachable(
"bad evaluation kind");
398 bool Precise = isa_and_nonnull<VarDecl>(VD) &&
399 VD->
hasAttr<ObjCPreciseLifetimeAttr>();
420 llvm_unreachable(
"temporary cannot have dynamic storage duration");
422 llvm_unreachable(
"unknown storage duration");
432 if (
const auto *ClassDecl =
436 ReferenceTemporaryDtor = ClassDecl->getDestructor();
438 if (!ReferenceTemporaryDtor)
441 llvm::FunctionCallee CleanupFn;
442 llvm::Constant *CleanupArg;
448 CleanupArg = llvm::Constant::getNullValue(CGF.
Int8PtrTy);
465 llvm_unreachable(
"temporary cannot have dynamic storage duration");
487 auto *GV =
new llvm::GlobalVariable(
489 llvm::GlobalValue::PrivateLinkage,
Init,
".ref.tmp",
nullptr,
490 llvm::GlobalValue::NotThreadLocal,
494 llvm::Constant *
C = GV;
497 GV, llvm::PointerType::get(
501 return RawAddress(
C, GV->getValueType(), alignment);
510 llvm_unreachable(
"temporary can't have dynamic storage duration");
512 llvm_unreachable(
"unknown storage duration");
526 "Reference should never be pseudo-strong!");
534 if (
auto *Var = dyn_cast<llvm::GlobalVariable>(
Object.getPointer())) {
544 if (Var->hasInitializer())
547 Var->setInitializer(
CGM.EmitNullConstant(E->
getType()));
553 default: llvm_unreachable(
"expected scalar or aggregate expression");
576 for (
const auto &Ignored : CommaLHSs)
579 if (
const auto *opaque = dyn_cast<OpaqueValueExpr>(E)) {
580 if (opaque->getType()->isRecordType()) {
581 assert(Adjustments.empty());
589 if (
auto *Var = dyn_cast<llvm::GlobalVariable>(
590 Object.getPointer()->stripPointerCasts())) {
596 if (!Var->hasInitializer()) {
597 Var->setInitializer(
CGM.EmitNullConstant(E->
getType()));
618 if (!ShouldEmitLifetimeMarkers)
629 CGBuilderTy::InsertPoint OldIP;
631 ((!
SanOpts.has(SanitizerKind::HWAddress) &&
632 !
SanOpts.has(SanitizerKind::Memory) &&
633 !
SanOpts.has(SanitizerKind::MemtagStack) &&
634 !
CGM.getCodeGenOpts().SanitizeAddressUseAfterScope) ||
636 OldConditional = OutermostConditional;
637 OutermostConditional =
nullptr;
641 Builder.restoreIP(CGBuilderTy::InsertPoint(
642 Block, llvm::BasicBlock::iterator(
Block->back())));
649 if (OldConditional) {
650 OutermostConditional = OldConditional;
667 switch (Adjustment.Kind) {
671 Adjustment.DerivedToBase.BasePath->path_begin(),
672 Adjustment.DerivedToBase.BasePath->path_end(),
680 "materialized temporary field is not a simple lvalue");
688 E,
Object, Ptr, Adjustment.Ptr.MPT,
true);
721 const llvm::Constant *Elts) {
729 Builder.CreateMul(Ptr, Builder.getInt64(0xbf58476d1ce4e5b9u));
731 Builder.CreateXor(A0, Builder.CreateLShr(A0, Builder.getInt64(31)));
732 return Builder.CreateXor(Acc, A1);
749 return SanOpts.has(SanitizerKind::Null) ||
750 SanOpts.has(SanitizerKind::Alignment) ||
751 SanOpts.has(SanitizerKind::ObjectSize) ||
752 SanOpts.has(SanitizerKind::Vptr);
759 llvm::Value *ArraySize) {
766 if (Ptr->getType()->getPointerAddressSpace())
777 auto PtrToAlloca = dyn_cast<llvm::AllocaInst>(Ptr->stripPointerCasts());
779 llvm::Value *IsNonNull =
nullptr;
780 bool IsGuaranteedNonNull =
781 SkippedChecks.
has(SanitizerKind::Null) || PtrToAlloca;
783 llvm::BasicBlock *Done =
nullptr;
784 bool DoneViaNullSanitize =
false;
787 auto CheckHandler = SanitizerHandler::TypeMismatch;
789 {SanitizerKind::SO_Null,
790 SanitizerKind::SO_ObjectSize,
791 SanitizerKind::SO_Alignment},
799 if ((
SanOpts.has(SanitizerKind::Null) || AllowNullPointers) &&
800 !IsGuaranteedNonNull) {
802 IsNonNull =
Builder.CreateIsNotNull(Ptr);
806 IsGuaranteedNonNull = IsNonNull ==
True;
809 if (!IsGuaranteedNonNull) {
810 if (AllowNullPointers) {
814 DoneViaNullSanitize =
true;
816 Builder.CreateCondBr(IsNonNull, Rest, Done);
819 Checks.push_back(std::make_pair(IsNonNull, SanitizerKind::SO_Null));
824 if (
SanOpts.has(SanitizerKind::ObjectSize) &&
825 !SkippedChecks.
has(SanitizerKind::ObjectSize) &&
827 uint64_t TySize =
CGM.getMinimumObjectSize(Ty).getQuantity();
828 llvm::Value *Size = llvm::ConstantInt::get(
IntPtrTy, TySize);
830 Size =
Builder.CreateMul(Size, ArraySize);
833 llvm::Constant *ConstantSize = dyn_cast<llvm::Constant>(Size);
834 if (!ConstantSize || !ConstantSize->isNullValue()) {
841 llvm::Function *F =
CGM.getIntrinsic(llvm::Intrinsic::objectsize, Tys);
843 llvm::Value *NullIsUnknown =
Builder.getFalse();
844 llvm::Value *Dynamic =
Builder.getFalse();
845 llvm::Value *LargeEnough =
Builder.CreateICmpUGE(
846 Builder.CreateCall(F, {Ptr, Min, NullIsUnknown, Dynamic}), Size);
848 std::make_pair(LargeEnough, SanitizerKind::SO_ObjectSize));
852 llvm::MaybeAlign AlignVal;
853 llvm::Value *PtrAsInt =
nullptr;
855 if (
SanOpts.has(SanitizerKind::Alignment) &&
856 !SkippedChecks.
has(SanitizerKind::Alignment)) {
859 AlignVal =
CGM.getNaturalTypeAlignment(Ty,
nullptr,
nullptr,
864 if (AlignVal && *AlignVal > llvm::Align(1) &&
865 (!PtrToAlloca || PtrToAlloca->getAlign() < *AlignVal)) {
867 llvm::Value *Align =
Builder.CreateAnd(
868 PtrAsInt, llvm::ConstantInt::get(
IntPtrTy, AlignVal->value() - 1));
869 llvm::Value *Aligned =
873 std::make_pair(Aligned, SanitizerKind::SO_Alignment));
877 if (Checks.size() > 0) {
878 llvm::Constant *StaticData[] = {
880 llvm::ConstantInt::get(
Int8Ty, AlignVal ? llvm::Log2(*AlignVal) : 1),
881 llvm::ConstantInt::get(
Int8Ty, TCK)};
882 EmitCheck(Checks, CheckHandler, StaticData, PtrAsInt ? PtrAsInt : Ptr);
894 if (
SanOpts.has(SanitizerKind::Vptr) &&
897 SanitizerHandler::DynamicTypeCacheMiss);
901 if (!IsGuaranteedNonNull) {
903 IsNonNull =
Builder.CreateIsNotNull(Ptr);
907 Builder.CreateCondBr(IsNonNull, VptrNotNull, Done);
913 llvm::raw_svector_ostream Out(MangledName);
918 if (!
CGM.getContext().getNoSanitizeList().containsType(SanitizerKind::Vptr,
921 llvm::Value *TypeHash =
922 llvm::ConstantInt::get(
Int64Ty, xxh3_64bits(Out.str()));
936 const int CacheSize = 128;
937 llvm::Type *HashTable = llvm::ArrayType::get(
IntPtrTy, CacheSize);
938 llvm::Value *
Cache =
CGM.CreateRuntimeVariable(HashTable,
939 "__ubsan_vptr_type_cache");
940 llvm::Value *Slot =
Builder.CreateAnd(Hash,
943 llvm::Value *Indices[] = {
Builder.getInt32(0), Slot };
944 llvm::Value *CacheVal =
Builder.CreateAlignedLoad(
952 llvm::Value *EqualHash =
Builder.CreateICmpEQ(CacheVal, Hash);
953 llvm::Constant *StaticData[] = {
957 llvm::ConstantInt::get(
Int8Ty, TCK)
959 llvm::Value *DynamicData[] = { Ptr, Hash };
960 EmitCheck(std::make_pair(EqualHash, SanitizerKind::SO_Vptr),
961 SanitizerHandler::DynamicTypeCacheMiss, StaticData,
969 {DoneViaNullSanitize ? SanitizerKind::SO_Null : SanitizerKind::SO_Vptr},
970 DoneViaNullSanitize ? SanitizerHandler::TypeMismatch
971 : SanitizerHandler::DynamicTypeCacheMiss);
980 uint64_t EltSize =
C.getTypeSizeInChars(EltTy).getQuantity();
988 auto *ParamDecl = dyn_cast<ParmVarDecl>(ArrayDeclRef->getDecl());
992 auto *POSAttr = ParamDecl->getAttr<PassObjectSizeAttr>();
997 int POSType = POSAttr->getType();
998 if (POSType != 0 && POSType != 1)
1002 auto PassedSizeIt = SizeArguments.find(ParamDecl);
1003 if (PassedSizeIt == SizeArguments.end())
1007 assert(LocalDeclMap.count(PassedSizeDecl) &&
"Passed size not loadable");
1008 Address AddrOfSize = LocalDeclMap.find(PassedSizeDecl)->second;
1011 llvm::Value *SizeOfElement =
1012 llvm::ConstantInt::get(SizeInBytes->getType(), EltSize);
1013 return Builder.CreateUDiv(SizeInBytes, SizeOfElement);
1022 StrictFlexArraysLevel) {
1025 IndexedType =
Base->getType();
1026 return CGF.
Builder.getInt32(VT->getNumElements());
1031 if (
const auto *CE = dyn_cast<CastExpr>(
Base)) {
1032 if (CE->getCastKind() == CK_ArrayToPointerDecay &&
1033 !CE->getSubExpr()->isFlexibleArrayMemberLike(CGF.
getContext(),
1034 StrictFlexArraysLevel)) {
1037 IndexedType = CE->getSubExpr()->getType();
1039 if (
const auto *CAT = dyn_cast<ConstantArrayType>(AT))
1040 return CGF.
Builder.getInt(CAT->getSize());
1042 if (
const auto *VAT = dyn_cast<VariableArrayType>(AT))
1050 QualType EltTy{
Base->getType()->getPointeeOrArrayElementType(), 0};
1052 IndexedType =
Base->getType();
1077class StructAccessBase
1078 :
public ConstStmtVisitor<StructAccessBase, const Expr *> {
1079 const RecordDecl *ExpectedRD;
1081 bool IsExpectedRecordDecl(
const Expr *E)
const {
1089 StructAccessBase(
const RecordDecl *ExpectedRD) : ExpectedRD(ExpectedRD) {}
1108 const Expr *Visit(
const Expr *E) {
1109 return ConstStmtVisitor<StructAccessBase, const Expr *>::Visit(E);
1112 const Expr *VisitStmt(
const Stmt *S) {
return nullptr; }
1127 const Expr *VisitDeclRefExpr(
const DeclRefExpr *E) {
1128 return IsExpectedRecordDecl(E) ? E :
nullptr;
1130 const Expr *VisitMemberExpr(
const MemberExpr *E) {
1131 if (IsExpectedRecordDecl(E) && E->
isArrow())
1133 const Expr *Res = Visit(E->
getBase());
1134 return !Res && IsExpectedRecordDecl(E) ? E : Res;
1136 const Expr *VisitCompoundLiteralExpr(
const CompoundLiteralExpr *E) {
1137 return IsExpectedRecordDecl(E) ? E :
nullptr;
1139 const Expr *VisitCallExpr(
const CallExpr *E) {
1140 return IsExpectedRecordDecl(E) ? E :
nullptr;
1143 const Expr *VisitArraySubscriptExpr(
const ArraySubscriptExpr *E) {
1144 if (IsExpectedRecordDecl(E))
1148 const Expr *VisitCastExpr(
const CastExpr *E) {
1150 return IsExpectedRecordDecl(E) ? E :
nullptr;
1153 const Expr *VisitParenExpr(
const ParenExpr *E) {
1156 const Expr *VisitUnaryAddrOf(
const UnaryOperator *E) {
1159 const Expr *VisitUnaryDeref(
const UnaryOperator *E) {
1172 int64_t FieldNo = -1;
1181 Indices.emplace_back(CGF.
Builder.getInt32(FieldNo));
1190 Indices.emplace_back(CGF.
Builder.getInt32(FieldNo));
1215 const Expr *StructBase = StructAccessBase(RD).Visit(
Base);
1219 llvm::Value *Res =
nullptr;
1224 Res =
Addr.emitRawPointer(*
this);
1225 }
else if (StructBase->
isLValue()) {
1228 Res =
Addr.emitRawPointer(*
this);
1235 if (Indices.empty())
1238 Indices.push_back(
Builder.getInt32(0));
1262 const Expr *ArrayExprBase,
1263 llvm::Value *IndexVal,
QualType IndexType,
1265 assert(
SanOpts.has(SanitizerKind::ArrayBounds) &&
1266 "should not be called unless adding bounds checks");
1271 *
this, ArrayExprBase, ArrayExprBaseType, StrictFlexArraysLevel);
1274 BoundsVal,
getContext().getSizeType(), Accessed);
1279 llvm::Value *IndexVal,
1281 llvm::Value *BoundsVal,
1282 QualType BoundsType,
bool Accessed) {
1286 auto CheckKind = SanitizerKind::SO_ArrayBounds;
1287 auto CheckHandler = SanitizerHandler::OutOfBounds;
1299 llvm::Value *IndexInst =
Builder.CreateIntCast(IndexVal, Ty, IndexSigned);
1300 llvm::Value *BoundsInst =
Builder.CreateIntCast(BoundsVal, Ty,
false);
1302 llvm::Constant *StaticData[] = {
1308 llvm::Value *Check = Accessed ?
Builder.CreateICmpULT(IndexInst, BoundsInst)
1309 :
Builder.CreateICmpULE(IndexInst, BoundsInst);
1314 BoundsVal, llvm::ConstantInt::get(BoundsVal->getType(), 0));
1318 EmitCheck(std::make_pair(Check, CheckKind), CheckHandler, StaticData,
1328 auto *TypeNameMD = MDB.createString(ATMD->TypeName);
1329 auto *ContainsPtrC =
Builder.getInt1(ATMD->ContainsPointer);
1330 auto *ContainsPtrMD = MDB.createConstant(ContainsPtrC);
1333 return llvm::MDNode::get(
CGM.getLLVMContext(), {TypeNameMD, ContainsPtrMD});
1337 assert(
SanOpts.has(SanitizerKind::AllocToken) &&
1338 "Only needed with -fsanitize=alloc-token");
1339 CB->setMetadata(llvm::LLVMContext::MD_alloc_token,
1351 assert(
SanOpts.has(SanitizerKind::AllocToken) &&
1352 "Only needed with -fsanitize=alloc-token");
1354 CB->setMetadata(llvm::LLVMContext::MD_alloc_token, MDN);
1359 bool isInc,
bool isPre) {
1362 llvm::Value *NextVal;
1364 uint64_t AmountVal = isInc ? 1 : -1;
1365 NextVal = llvm::ConstantInt::get(InVal.first->getType(), AmountVal,
true);
1368 NextVal =
Builder.CreateAdd(InVal.first, NextVal, isInc ?
"inc" :
"dec");
1371 llvm::APFloat FVal(
getContext().getFloatTypeSemantics(ElemTy), 1);
1377 NextVal =
Builder.CreateFAdd(InVal.first, NextVal, isInc ?
"inc" :
"dec");
1385 CGM.getOpenMPRuntime().checkAndEmitLastprivateConditional(*
this,
1390 return isPre ? IncVal : InVal;
1400 DI->EmitExplicitCastType(E->
getType());
1411 if (
auto *constantIdx = dyn_cast<llvm::ConstantInt>(idx)) {
1412 CharUnits offset = constantIdx->getZExtValue() * eltSize;
1426 assert(BO->
isAdditiveOp() &&
"Expect an addition or subtraction.");
1429 bool isSubtraction = BO->
getOpcode() == BO_Sub;
1432 llvm::Value *
index =
nullptr;
1436 std::swap(pointerOperand, indexOperand);
1448 BO, pointerOperand, pointer, indexOperand,
index, isSubtraction);
1455 nullptr, IsKnownNonNull);
1468 if (
const CastExpr *CE = dyn_cast<CastExpr>(E)) {
1469 if (
const auto *ECE = dyn_cast<ExplicitCastExpr>(CE))
1472 switch (CE->getCastKind()) {
1476 case CK_AddressSpaceConversion:
1477 if (
auto PtrTy = CE->getSubExpr()->getType()->getAs<
PointerType>()) {
1478 if (PtrTy->getPointeeType()->isVoidType())
1484 CE->getSubExpr(), &InnerBaseInfo, &InnerTBAAInfo, IsKnownNonNull);
1485 if (BaseInfo) *BaseInfo = InnerBaseInfo;
1486 if (TBAAInfo) *TBAAInfo = InnerTBAAInfo;
1492 E->
getType(), &TargetTypeBaseInfo, &TargetTypeTBAAInfo);
1500 BaseInfo->mergeForCast(TargetTypeBaseInfo);
1501 Addr.setAlignment(Align);
1505 if (CGF.
SanOpts.
has(SanitizerKind::CFIUnrelatedCast) &&
1506 CE->getCastKind() == CK_BitCast) {
1514 llvm::Type *ElemTy =
1516 Addr =
Addr.withElementType(ElemTy);
1517 if (CE->getCastKind() == CK_AddressSpaceConversion)
1527 case CK_ArrayToPointerDecay:
1531 case CK_UncheckedDerivedToBase:
1532 case CK_DerivedToBase: {
1539 CE->getSubExpr(), BaseInfo,
nullptr,
1541 CE->getCastKind() == CK_UncheckedDerivedToBase));
1542 auto Derived = CE->getSubExpr()->
getType()->getPointeeCXXRecordDecl();
1544 Addr, Derived, CE->path_begin(), CE->path_end(),
1557 if (UO->getOpcode() == UO_AddrOf) {
1558 LValue LV = CGF.
EmitLValue(UO->getSubExpr(), IsKnownNonNull);
1559 if (BaseInfo) *BaseInfo = LV.getBaseInfo();
1560 if (TBAAInfo) *TBAAInfo = LV.getTBAAInfo();
1561 return LV.getAddress();
1566 if (
auto *
Call = dyn_cast<CallExpr>(E)) {
1567 switch (
Call->getBuiltinCallee()) {
1570 case Builtin::BIaddressof:
1571 case Builtin::BI__addressof:
1572 case Builtin::BI__builtin_addressof: {
1574 if (BaseInfo) *BaseInfo = LV.getBaseInfo();
1575 if (TBAAInfo) *TBAAInfo = LV.getTBAAInfo();
1576 return LV.getAddress();
1582 if (
auto *BO = dyn_cast<BinaryOperator>(E)) {
1583 if (BO->isAdditiveOp())
1592 true, BaseInfo, TBAAInfo, IsKnownNonNull);
1602 if (IsKnownNonNull && !
Addr.isKnownNonNull())
1603 Addr.setKnownNonNull();
1610 return CGM.getCXXABI().EmitMemberPointerIsNotNull(*
this,
V, MPT);
1611 return Builder.CreateICmpNE(
V, llvm::Constant::getNullValue(
V->getType()));
1622 llvm::Value *
U = llvm::UndefValue::get(EltTy);
1637 llvm_unreachable(
"bad evaluation kind");
1662 if (
const auto *CE = dyn_cast<CastExpr>(
Base)) {
1663 Base = CE->getSubExpr();
1664 }
else if (
const auto *PE = dyn_cast<ParenExpr>(
Base)) {
1665 Base = PE->getSubExpr();
1666 }
else if (
const auto *UO = dyn_cast<UnaryOperator>(
Base)) {
1667 if (UO->getOpcode() == UO_Extension)
1668 Base = UO->getSubExpr();
1686 if (
const auto *ME = dyn_cast<MemberExpr>(E)) {
1689 SkippedChecks.
set(SanitizerKind::Alignment,
true);
1691 SkippedChecks.
set(SanitizerKind::Null,
true);
1718 CGM.runWithSufficientStackSpace(
1719 E->
getExprLoc(), [&] { LV = EmitLValueHelper(E, IsKnownNonNull); });
1726LValue CodeGenFunction::EmitLValueHelper(
const Expr *E,
1732 case Expr::ObjCPropertyRefExprClass:
1733 llvm_unreachable(
"cannot emit a property reference directly");
1735 case Expr::ObjCSelectorExprClass:
1737 case Expr::ObjCIsaExprClass:
1739 case Expr::BinaryOperatorClass:
1741 case Expr::CompoundAssignOperatorClass: {
1744 Ty = AT->getValueType();
1749 case Expr::CallExprClass:
1750 case Expr::CXXMemberCallExprClass:
1751 case Expr::CXXOperatorCallExprClass:
1752 case Expr::UserDefinedLiteralClass:
1754 case Expr::CXXRewrittenBinaryOperatorClass:
1757 case Expr::VAArgExprClass:
1759 case Expr::DeclRefExprClass:
1761 case Expr::ConstantExprClass: {
1767 case Expr::ParenExprClass:
1769 case Expr::GenericSelectionExprClass:
1772 case Expr::PredefinedExprClass:
1774 case Expr::StringLiteralClass:
1776 case Expr::ObjCEncodeExprClass:
1778 case Expr::PseudoObjectExprClass:
1780 case Expr::InitListExprClass:
1782 case Expr::CXXTemporaryObjectExprClass:
1783 case Expr::CXXConstructExprClass:
1785 case Expr::CXXBindTemporaryExprClass:
1787 case Expr::CXXUuidofExprClass:
1789 case Expr::LambdaExprClass:
1792 case Expr::ExprWithCleanupsClass: {
1794 RunCleanupsScope
Scope(*
this);
1795 LValue LV =
EmitLValue(cleanups->getSubExpr(), IsKnownNonNull);
1796 if (LV.isSimple()) {
1800 llvm::Value *
V =
Addr.getBasePointer();
1801 Scope.ForceCleanup({&
V});
1802 Addr.replaceBasePointer(
V);
1804 LV.getBaseInfo(), LV.getTBAAInfo());
1811 case Expr::CXXDefaultArgExprClass: {
1814 return EmitLValue(DAE->getExpr(), IsKnownNonNull);
1816 case Expr::CXXDefaultInitExprClass: {
1819 return EmitLValue(DIE->getExpr(), IsKnownNonNull);
1821 case Expr::CXXTypeidExprClass:
1824 case Expr::ObjCMessageExprClass:
1826 case Expr::ObjCIvarRefExprClass:
1828 case Expr::StmtExprClass:
1830 case Expr::UnaryOperatorClass:
1832 case Expr::ArraySubscriptExprClass:
1834 case Expr::MatrixSingleSubscriptExprClass:
1836 case Expr::MatrixSubscriptExprClass:
1838 case Expr::ArraySectionExprClass:
1840 case Expr::ExtVectorElementExprClass:
1842 case Expr::MatrixElementExprClass:
1844 case Expr::CXXThisExprClass:
1846 case Expr::MemberExprClass:
1848 case Expr::CompoundLiteralExprClass:
1850 case Expr::ConditionalOperatorClass:
1852 case Expr::BinaryConditionalOperatorClass:
1854 case Expr::ChooseExprClass:
1856 case Expr::OpaqueValueExprClass:
1858 case Expr::SubstNonTypeTemplateParmExprClass:
1861 case Expr::ImplicitCastExprClass:
1862 case Expr::CStyleCastExprClass:
1863 case Expr::CXXFunctionalCastExprClass:
1864 case Expr::CXXStaticCastExprClass:
1865 case Expr::CXXDynamicCastExprClass:
1866 case Expr::CXXReinterpretCastExprClass:
1867 case Expr::CXXConstCastExprClass:
1868 case Expr::CXXAddrspaceCastExprClass:
1869 case Expr::ObjCBridgedCastExprClass:
1872 case Expr::MaterializeTemporaryExprClass:
1875 case Expr::CoawaitExprClass:
1877 case Expr::CoyieldExprClass:
1879 case Expr::PackIndexingExprClass:
1881 case Expr::HLSLOutArgExprClass:
1882 llvm_unreachable(
"cannot emit a HLSL out argument directly");
1889 assert(
type.isCanonical());
1890 assert(!
type->isReferenceType());
1898 if (
const auto *RT = dyn_cast<RecordType>(
type))
1899 if (
const auto *RD = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
1900 RD = RD->getDefinitionOrSelf();
1901 if (RD->hasMutableFields() || !RD->isTrivial())
1923 if (
const auto *ref = dyn_cast<ReferenceType>(
type)) {
1947 }
else if (
const auto *var = dyn_cast<VarDecl>(
Value)) {
1957 bool resultIsReference;
1963 resultIsReference =
false;
1969 resultIsReference =
true;
1990 auto *MD = dyn_cast_or_null<CXXMethodDecl>(
CurCodeDecl);
1991 if (
isLambdaMethod(MD) && MD->getOverloadedOperator() == OO_Call) {
1994 if (
const VarDecl *VD = dyn_cast<const VarDecl>(D)) {
1995 if (!VD->hasAttr<CUDADeviceAttr>()) {
2018 if (resultIsReference)
2045 assert(
Constant &&
"not a constant");
2068 llvm::APInt &End,
bool StrictEnums,
bool StrictBool,
2071 bool IsRegularCPlusPlusEnum =
2072 CGF.
getLangOpts().CPlusPlus && StrictEnums && ED && !ED->isFixed();
2073 if (!IsBool && !IsRegularCPlusPlusEnum)
2082 ED->getValueRange(End,
Min);
2087llvm::MDNode *CodeGenFunction::getRangeForLoadFromType(QualType Ty) {
2088 llvm::APInt
Min, End;
2090 bool StrictBoolEnabled =
CGM.getCodeGenOpts().getLoadBoolFromMem() ==
2093 CGM.getCodeGenOpts().StrictEnums,
2094 StrictBoolEnabled, IsBool))
2098 return MDHelper.createRange(
Min, End);
2106 }
else if (
CGM.getCodeGenOpts().isOptimizedBuild()) {
2107 if (llvm::MDNode *RangeInfo = getRangeForLoadFromType(Ty)) {
2108 Load->setMetadata(llvm::LLVMContext::MD_range, RangeInfo);
2109 Load->setMetadata(llvm::LLVMContext::MD_noundef,
2110 llvm::MDNode::get(
CGM.getLLVMContext(), {}));
2117 bool HasBoolCheck =
SanOpts.has(SanitizerKind::Bool);
2118 bool HasEnumCheck =
SanOpts.has(SanitizerKind::Enum);
2119 if (!HasBoolCheck && !HasEnumCheck)
2124 bool NeedsBoolCheck = HasBoolCheck && IsBool;
2126 if (!NeedsBoolCheck && !NeedsEnumCheck)
2136 if (NeedsEnumCheck &&
2137 getContext().isTypeIgnoredBySanitizer(SanitizerKind::Enum, Ty))
2140 llvm::APInt
Min, End;
2146 NeedsEnumCheck ? SanitizerKind::SO_Enum : SanitizerKind::SO_Bool;
2149 auto CheckHandler = SanitizerHandler::LoadInvalidValue;
2154 Check =
Builder.CreateICmpULE(
Value, llvm::ConstantInt::get(Ctx, End));
2156 llvm::Value *Upper =
2157 Builder.CreateICmpSLE(
Value, llvm::ConstantInt::get(Ctx, End));
2158 llvm::Value *Lower =
2160 Check =
Builder.CreateAnd(Upper, Lower);
2164 EmitCheck(std::make_pair(Check, Kind), CheckHandler, StaticArgs,
Value);
2173 bool isNontemporal) {
2174 if (
auto *GV = dyn_cast<llvm::GlobalValue>(
Addr.getBasePointer()))
2175 if (GV->isThreadLocal())
2181 if (ClangVecTy->isPackedVectorBoolType(
getContext())) {
2183 unsigned ValNumElems =
2186 auto *RawIntV =
Builder.CreateLoad(
Addr, Volatile,
"load_bits");
2187 const auto *RawIntTy = RawIntV->getType();
2188 assert(RawIntTy->isIntegerTy() &&
"compressed iN storage for bitvectors");
2190 auto *PaddedVecTy = llvm::FixedVectorType::get(
2191 Builder.getInt1Ty(), RawIntTy->getPrimitiveSizeInBits());
2192 llvm::Value *
V =
Builder.CreateBitCast(RawIntV, PaddedVecTy);
2205 if (VTy != NewVecTy) {
2207 llvm::Value *
V =
Builder.CreateLoad(Cast, Volatile,
"loadVecN");
2208 unsigned OldNumElements = VTy->getNumElements();
2210 std::iota(Mask.begin(), Mask.end(), 0);
2211 V =
Builder.CreateShuffleVector(
V, Mask,
"extractVec");
2226 llvm::LoadInst *Load =
Builder.CreateLoad(
Addr, Volatile);
2227 if (isNontemporal) {
2228 llvm::MDNode *Node = llvm::MDNode::get(
2229 Load->getContext(), llvm::ConstantAsMetadata::get(
Builder.getInt32(1)));
2230 Load->setMetadata(llvm::LLVMContext::MD_nontemporal, Node);
2233 CGM.DecorateInstructionWithTBAA(Load, TBAAInfo);
2245 Ty = AtomicTy->getValueType();
2253 if (StoreTy->isVectorTy() && StoreTy->getScalarSizeInBits() >
2258 unsigned MemNumElems = StoreTy->getPrimitiveSizeInBits();
2279 Ty = AtomicTy->getValueType();
2285 auto *PaddedVecTy = llvm::FixedVectorType::get(
2286 Builder.getInt1Ty(), RawIntTy->getPrimitiveSizeInBits());
2296 if (HasBoolRep &&
CGM.getCodeGenOpts().isConvertingBoolWithCmp0()) {
2310 bool IsVector =
true) {
2311 auto *ArrayTy = dyn_cast<llvm::ArrayType>(
Addr.getElementType());
2312 if (ArrayTy && IsVector) {
2313 auto ArrayElements = ArrayTy->getNumElements();
2314 auto *ArrayElementTy = ArrayTy->getElementType();
2317 ArrayElementTy = VectorTy->getElementType();
2318 ArrayElements *= VectorTy->getNumElements();
2320 auto *VectorTy = llvm::FixedVectorType::get(ArrayElementTy, ArrayElements);
2322 return Addr.withElementType(VectorTy);
2324 auto *VectorTy = dyn_cast<llvm::VectorType>(
Addr.getElementType());
2325 if (VectorTy && !IsVector) {
2326 auto *ArrayTy = llvm::ArrayType::get(
2327 VectorTy->getElementType(),
2330 return Addr.withElementType(ArrayTy);
2342 "Result must be a Constant Matrix");
2347 if (LTy->getScalarSizeInBits() > Mat->getType()->getScalarSizeInBits())
2348 Mat =
Builder.CreateZExt(Mat, LTy);
2349 Builder.CreateStore(Mat, MatMem);
2363 bool IsColMajor =
getLangOpts().getDefaultMatrixMemoryLayout() ==
2368 for (uint32_t &Idx : Indices) {
2370 unsigned Row = Idx / NumCols;
2371 unsigned Col = Idx % NumCols;
2373 Idx = MT->getColumnMajorFlattenedIndex(Row, Col);
2377 if (
Base.isSimple()) {
2381 MatAddr =
CGM.getHLSLRuntime().createBufferMatrixTempAddress(
2384 llvm::Constant *CV =
2387 CV, ResultType,
Base.getBaseInfo(),
2390 assert(
Base.isExtVectorElt() &&
"Can only subscript lvalue vec elts here!");
2392 llvm::Constant *BaseElts =
Base.getExtVectorElts();
2395 for (
unsigned Index : Indices)
2396 CElts.push_back(BaseElts->getAggregateElement(Index));
2397 llvm::Constant *CV = llvm::ConstantVector::get(CElts);
2410 value->getType()->isVectorTy());
2412 lvalue.getBaseInfo(), lvalue.getTBAAInfo(), isInit,
2413 lvalue.isNontemporal());
2420 bool isInit,
bool isNontemporal) {
2421 if (
auto *GV = dyn_cast<llvm::GlobalValue>(
Addr.getBasePointer()))
2422 if (GV->isThreadLocal())
2430 if (
auto *VecTy = dyn_cast<llvm::FixedVectorType>(SrcTy)) {
2432 CGM.getABIInfo().getOptimalVectorMemoryType(VecTy,
getLangOpts());
2433 if (!ClangVecTy->isPackedVectorBoolType(
getContext()) &&
2434 VecTy != NewVecTy) {
2436 VecTy->getNumElements());
2437 std::iota(Mask.begin(), Mask.begin() + VecTy->getNumElements(), 0);
2441 Mask,
"extractVec");
2444 if (
Addr.getElementType() != SrcTy)
2445 Addr =
Addr.withElementType(SrcTy);
2462 if (isNontemporal) {
2463 llvm::MDNode *Node =
2464 llvm::MDNode::get(Store->getContext(),
2465 llvm::ConstantAsMetadata::get(
Builder.getInt32(1)));
2466 Store->setMetadata(llvm::LLVMContext::MD_nontemporal, Node);
2469 CGM.DecorateInstructionWithTBAA(Store, TBAAInfo);
2488 assert(LV.getType()->isConstantMatrixType());
2499 LV.setAddress(
Addr);
2515 llvm_unreachable(
"bad evaluation kind");
2581 EltTy = MatTy->getElementType();
2582 if (
CGM.getCodeGenOpts().isOptimizedBuild()) {
2583 llvm::MatrixBuilder MB(
Builder);
2584 MB.CreateIndexAssumption(Idx, MatTy->getNumElementsFlattened());
2587 llvm::LoadInst *Load =
2589 llvm::Value *Elt =
Builder.CreateExtractElement(Load, Idx,
"matrixext");
2598 unsigned NumLanes = NumCols;
2602 llvm::Constant *ColConstsIndices =
nullptr;
2603 llvm::MatrixBuilder MB(
Builder);
2607 NumLanes = llvm::cast<llvm::FixedVectorType>(ColConstsIndices->getType())
2611 llvm::Type *RowTy = llvm::FixedVectorType::get(ElemTy, NumLanes);
2612 llvm::Value *
Result = llvm::PoisonValue::get(RowTy);
2614 for (
unsigned Col = 0; Col < NumLanes; ++Col) {
2615 llvm::Value *ColIdx;
2616 if (ColConstsIndices)
2617 ColIdx = ColConstsIndices->getAggregateElement(Col);
2619 ColIdx = llvm::ConstantInt::get(Row->getType(), Col);
2620 bool IsMatrixRowMajor =
getLangOpts().getDefaultMatrixMemoryLayout() ==
2622 llvm::Value *EltIndex =
2623 MB.CreateIndex(Row, ColIdx, NumRows, NumCols, IsMatrixRowMajor);
2624 llvm::Value *Elt =
Builder.CreateExtractElement(MatrixVec, EltIndex);
2625 llvm::Value *Lane = llvm::ConstantInt::get(
Builder.getInt32Ty(), Col);
2632 assert(LV.
isBitField() &&
"Unknown LValue type!");
2650 const unsigned StorageSize =
2653 assert(
static_cast<unsigned>(Offset + Info.
Size) <= StorageSize);
2654 unsigned HighBits = StorageSize - Offset - Info.
Size;
2656 Val =
Builder.CreateShl(Val, HighBits,
"bf.shl");
2657 if (Offset + HighBits)
2658 Val =
Builder.CreateAShr(Val, Offset + HighBits,
"bf.ashr");
2661 Val =
Builder.CreateLShr(Val, Offset,
"bf.lshr");
2662 if (
static_cast<unsigned>(Offset) + Info.
Size < StorageSize)
2664 Val, llvm::APInt::getLowBitsSet(StorageSize, Info.
Size),
"bf.clear");
2680 llvm::Type *DstTy = llvm::FixedVectorType::get(Vec->getType(), 1);
2681 llvm::Value *
Zero = llvm::Constant::getNullValue(
CGM.Int64Ty);
2682 Vec =
Builder.CreateInsertElement(DstTy, Vec,
Zero,
"cast.splat");
2692 llvm::Value *Elt = llvm::ConstantInt::get(
SizeTy, InIdx);
2694 llvm::Value *Element =
Builder.CreateExtractElement(Vec, Elt);
2697 if (Element->getType()->getPrimitiveSizeInBits() >
2698 LVTy->getPrimitiveSizeInBits()) {
2700 CGM.getCodeGenOpts().isConvertingBoolWithCmp0())
2701 Element =
Builder.CreateICmpNE(
2702 Element, llvm::Constant::getNullValue(Element->getType()));
2704 Element =
Builder.CreateTrunc(Element, LVTy);
2714 for (
unsigned i = 0; i != NumResultElts; ++i)
2717 Vec =
Builder.CreateShuffleVector(Vec, Mask);
2720 if (
CGM.getCodeGenOpts().isConvertingBoolWithCmp0())
2721 Vec =
Builder.CreateICmpNE(Vec,
2722 llvm::Constant::getNullValue(Vec->getType()));
2734 llvm::Type *VectorElementTy =
CGM.getTypes().ConvertType(EQT);
2742 Builder.CreateConstInBoundsGEP(CastToPointerElement, ix,
2745 return VectorBasePtrPlusIx;
2751 "Bad type for register variable");
2756 llvm::Type *OrigTy =
CGM.getTypes().ConvertType(LV.
getType());
2757 llvm::Type *Ty = OrigTy;
2758 if (OrigTy->isPointerTy())
2759 Ty =
CGM.getTypes().getDataLayout().getIntPtrType(OrigTy);
2760 llvm::Type *Types[] = { Ty };
2762 llvm::Function *F =
CGM.getIntrinsic(llvm::Intrinsic::read_register, Types);
2764 F, llvm::MetadataAsValue::get(Ty->getContext(), RegName));
2765 if (OrigTy->isPointerTy())
2783 llvm::Type *ElemTy = DestAddrTy->getScalarType();
2785 CGM.getDataLayout().getPrefTypeAlign(ElemTy));
2787 assert(ElemTy->getScalarSizeInBits() >= 8 &&
2788 "vector element type must be at least byte-sized");
2791 if (Val->getType()->getPrimitiveSizeInBits() <
2792 ElemTy->getScalarSizeInBits())
2793 Val =
Builder.CreateZExt(Val, ElemTy->getScalarType());
2796 llvm::Value *
Zero = llvm::ConstantInt::get(
Int32Ty, 0);
2798 Builder.CreateGEP(DstAddr, {
Zero, Idx}, DestAddrTy, ElemAlign);
2806 llvm::Type *VecTy = Vec->getType();
2809 if (VecTy->isVectorTy() && SrcVal->getType()->getPrimitiveSizeInBits() <
2810 VecTy->getScalarSizeInBits())
2811 SrcVal =
Builder.CreateZExt(SrcVal, VecTy->getScalarType());
2813 auto *IRStoreTy = dyn_cast<llvm::IntegerType>(Vec->getType());
2815 auto *IRVecTy = llvm::FixedVectorType::get(
2816 Builder.getInt1Ty(), IRStoreTy->getPrimitiveSizeInBits());
2817 Vec =
Builder.CreateBitCast(Vec, IRVecTy);
2824 if (
auto *EltTy = dyn_cast<llvm::FixedVectorType>(SrcVal->getType());
2825 EltTy && EltTy->getNumElements() == 1)
2826 SrcVal =
Builder.CreateBitCast(SrcVal, EltTy->getElementType());
2832 Vec =
Builder.CreateBitCast(Vec, IRStoreTy);
2856 llvm::Type *ElemTy = DestAddrTy->getScalarType();
2858 CGM.getDataLayout().getPrefTypeAlign(ElemTy));
2860 assert(ElemTy->getScalarSizeInBits() >= 8 &&
2861 "matrix element type must be at least byte-sized");
2864 if (Val->getType()->getPrimitiveSizeInBits() <
2865 ElemTy->getScalarSizeInBits())
2866 Val =
Builder.CreateZExt(Val, ElemTy->getScalarType());
2869 llvm::Value *
Zero = llvm::ConstantInt::get(
Int32Ty, 0);
2871 Builder.CreateGEP(DstAddr, {
Zero, Idx}, DestAddrTy, ElemAlign);
2877 if (
CGM.getCodeGenOpts().isOptimizedBuild()) {
2879 llvm::MatrixBuilder MB(
Builder);
2880 MB.CreateIndexAssumption(Idx, MatTy->getNumElementsFlattened());
2885 Builder.CreateInsertElement(Load, InsertVal, Idx,
"matins");
2896 "Store through matrix row LValues is only implemented for HLSL!");
2902 unsigned NumLanes = NumCols;
2906 llvm::Type *ElemTy = DestAddrTy->getScalarType();
2910 assert(ElemTy->getScalarSizeInBits() >= 8 &&
2911 "matrix element type must be at least byte-sized");
2914 if (RowVal->getType()->getScalarType()->getPrimitiveSizeInBits() <
2915 ElemTy->getScalarSizeInBits()) {
2917 llvm::Type *StorageElmTy = llvm::FixedVectorType::get(
2918 ElemTy->getScalarType(), RowValVecTy->getNumElements());
2919 RowVal =
Builder.CreateZExt(RowVal, StorageElmTy);
2922 llvm::MatrixBuilder MB(
Builder);
2924 llvm::Constant *ColConstsIndices =
nullptr;
2928 llvm::cast<llvm::FixedVectorType>(ColConstsIndices->getType())
2933 for (
unsigned Col = 0; Col < NumLanes; ++Col) {
2934 llvm::Value *ColIdx;
2935 if (ColConstsIndices)
2936 ColIdx = ColConstsIndices->getAggregateElement(Col);
2938 ColIdx = llvm::ConstantInt::get(Row->getType(), Col);
2939 bool IsMatrixRowMajor =
getLangOpts().getDefaultMatrixMemoryLayout() ==
2941 llvm::Value *EltIndex =
2942 MB.CreateIndex(Row, ColIdx, NumRows, NumCols, IsMatrixRowMajor);
2943 llvm::Value *Lane = llvm::ConstantInt::get(
Builder.getInt32Ty(), Col);
2944 llvm::Value *
Zero = llvm::ConstantInt::get(
Int32Ty, 0);
2945 llvm::Value *NewElt =
Builder.CreateExtractElement(RowVal, Lane);
2947 Builder.CreateGEP(DstAddr, {
Zero, EltIndex}, DestAddrTy, ElemAlign);
2954 assert(Dst.
isBitField() &&
"Unknown LValue type");
2969 llvm_unreachable(
"present but none");
3004 CGM.getObjCRuntime().EmitObjCWeakAssign(*
this, src, LvalueDst);
3017 RHS =
Builder.CreatePtrToInt(RHS, ResultType,
"sub.ptr.rhs.cast");
3019 ResultType,
"sub.ptr.lhs.cast");
3020 llvm::Value *BytesBetween =
Builder.CreateSub(LHS, RHS,
"ivar.offset");
3021 CGM.getObjCRuntime().EmitObjCIvarAssign(*
this, src, dst, BytesBetween);
3023 CGM.getObjCRuntime().EmitObjCGlobalAssign(*
this, src, LvalueDst,
3027 CGM.getObjCRuntime().EmitObjCStrongCastAssign(*
this, src, LvalueDst);
3031 assert(Src.
isScalar() &&
"Can't emit an agg store with this method");
3047 llvm::Value *MaskedVal = SrcVal;
3049 const bool UseVolatile =
3052 const unsigned StorageSize =
3057 if (StorageSize != Info.
Size) {
3058 assert(StorageSize > Info.
Size &&
"Invalid bitfield size.");
3065 SrcVal, llvm::APInt::getLowBitsSet(StorageSize, Info.
Size),
3069 SrcVal =
Builder.CreateShl(SrcVal, Offset,
"bf.shl");
3073 Val, ~llvm::APInt::getBitsSet(StorageSize, Offset, Offset + Info.
Size),
3077 SrcVal =
Builder.CreateOr(Val, SrcVal,
"bf.set");
3079 assert(Offset == 0);
3086 CGM.getCodeGenOpts().ForceAAPCSBitfieldLoad)
3087 Builder.CreateLoad(Ptr,
true,
"bf.load");
3096 llvm::Value *ResultVal = MaskedVal;
3100 assert(Info.
Size <= StorageSize);
3101 unsigned HighBits = StorageSize - Info.
Size;
3103 ResultVal =
Builder.CreateShl(ResultVal, HighBits,
"bf.result.shl");
3104 ResultVal =
Builder.CreateAShr(ResultVal, HighBits,
"bf.result.ashr");
3120 SrcVal->getType()->getScalarSizeInBits())
3129 if (!DestAddrTy->isVectorTy()) {
3131 "this should only occur for non-vector l-values");
3144 CGM.getDataLayout().getPrefTypeAlign(DestAddrTy->getScalarType()));
3145 llvm::Value *
Zero = llvm::ConstantInt::get(
Int32Ty, 0);
3147 for (
unsigned I = 0; I != NumSrcElts; ++I) {
3148 llvm::Value *Val = VTy ?
Builder.CreateExtractElement(
3149 SrcVal, llvm::ConstantInt::get(
Int32Ty, I))
3156 DstElemAddr =
Builder.CreateGEP(
3157 DstAddr, {
Zero, llvm::ConstantInt::get(
Int32Ty, FieldNo)},
3158 DestAddrTy, ElemAlign);
3167 llvm::Type *VecTy = Vec->getType();
3170 unsigned NumSrcElts = VTy->getNumElements();
3172 if (NumDstElts == NumSrcElts) {
3177 for (
unsigned i = 0; i != NumSrcElts; ++i)
3180 Vec =
Builder.CreateShuffleVector(SrcVal, Mask);
3181 }
else if (NumDstElts > NumSrcElts) {
3187 for (
unsigned i = 0; i != NumSrcElts; ++i)
3188 ExtMask.push_back(i);
3189 ExtMask.resize(NumDstElts, -1);
3190 llvm::Value *ExtSrcVal =
Builder.CreateShuffleVector(SrcVal, ExtMask);
3193 for (
unsigned i = 0; i != NumDstElts; ++i)
3203 for (
unsigned i = 0; i != NumSrcElts; ++i)
3205 Vec =
Builder.CreateShuffleVector(Vec, ExtSrcVal, Mask);
3208 llvm_unreachable(
"unexpected shorten vector length");
3214 llvm::Value *Elt = llvm::ConstantInt::get(
SizeTy, InIdx);
3216 Vec =
Builder.CreateInsertElement(Vec, SrcVal, Elt);
3226 "Bad type for register variable");
3229 assert(RegName &&
"Register LValue is not metadata");
3232 llvm::Type *OrigTy =
CGM.getTypes().ConvertType(Dst.
getType());
3233 llvm::Type *Ty = OrigTy;
3234 if (OrigTy->isPointerTy())
3235 Ty =
CGM.getTypes().getDataLayout().getIntPtrType(OrigTy);
3236 llvm::Type *Types[] = { Ty };
3238 llvm::Function *F =
CGM.getIntrinsic(llvm::Intrinsic::write_register, Types);
3240 if (OrigTy->isPointerTy())
3243 F, {llvm::MetadataAsValue::get(Ty->getContext(), RegName),
Value});
3251 bool IsMemberAccess=
false) {
3263 LV.setObjCIvar(
false);
3267 LV.setObjCIvar(
true);
3269 LV.setBaseIvarExp(Exp->getBase());
3274 if (
const auto *Exp = dyn_cast<DeclRefExpr>(E)) {
3275 if (
const auto *VD = dyn_cast<VarDecl>(Exp->getDecl())) {
3276 if (VD->hasGlobalStorage()) {
3277 LV.setGlobalObjCRef(
true);
3285 if (
const auto *Exp = dyn_cast<UnaryOperator>(E)) {
3290 if (
const auto *Exp = dyn_cast<ParenExpr>(E)) {
3292 if (LV.isObjCIvar()) {
3299 LV.setObjCIvar(
false);
3304 if (
const auto *Exp = dyn_cast<GenericSelectionExpr>(E)) {
3309 if (
const auto *Exp = dyn_cast<ImplicitCastExpr>(E)) {
3314 if (
const auto *Exp = dyn_cast<CStyleCastExpr>(E)) {
3319 if (
const auto *Exp = dyn_cast<ObjCBridgedCastExpr>(E)) {
3324 if (
const auto *Exp = dyn_cast<ArraySubscriptExpr>(E)) {
3326 if (LV.isObjCIvar() && !LV.isObjCArray())
3329 LV.setObjCIvar(
false);
3330 else if (LV.isGlobalObjCRef() && !LV.isObjCArray())
3333 LV.setGlobalObjCRef(
false);
3337 if (
const auto *Exp = dyn_cast<MemberExpr>(E)) {
3351 CGF, VD,
Addr, Loc);
3356 Addr =
Addr.withElementType(RealVarTy);
3362 std::optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
3363 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD);
3368 if (!Res || *Res == OMPDeclareTargetDeclAttr::MT_Local ||
3369 ((*Res == OMPDeclareTargetDeclAttr::MT_To ||
3370 *Res == OMPDeclareTargetDeclAttr::MT_Enter) &&
3373 assert(((*Res == OMPDeclareTargetDeclAttr::MT_Link) ||
3374 ((*Res == OMPDeclareTargetDeclAttr::MT_To ||
3375 *Res == OMPDeclareTargetDeclAttr::MT_Enter) &&
3377 "Expected link clause OR to clause with unified memory enabled.");
3387 llvm::LoadInst *Load =
3392 PTy, PointeeBaseInfo, PointeeTBAAInfo,
true);
3395 llvm::MDBuilder MDB(Ctx);
3397 if (
CGM.getTypes().getTargetAddressSpace(PTy) == 0 &&
3398 !
CGM.getCodeGenOpts().NullPointerIsValid)
3399 Load->setMetadata(llvm::LLVMContext::MD_nonnull,
3400 llvm::MDNode::get(Ctx, {}));
3406 llvm::LLVMContext::MD_align,
3407 llvm::MDNode::get(Ctx, MDB.createConstant(llvm::ConstantInt::get(
3408 Builder.getInt64Ty(), AlignVal))));
3413 true, PointeeBaseInfo,
3423 PointeeBaseInfo, PointeeTBAAInfo);
3433 BaseInfo, TBAAInfo);
3463 V = CGF.
Builder.CreateThreadLocalAddress(
V);
3471 VD->
hasAttr<OMPThreadPrivateDeclAttr>()) {
3486 if (FD->
hasAttr<WeakRefAttr>()) {
3501 if (
auto *GV = dyn_cast<llvm::GlobalValue>(
V))
3502 V = llvm::NoCFIValue::get(GV);
3509 llvm::Value *ThisValue) {
3522 AsmLabelAttr *
Asm = VD->
getAttr<AsmLabelAttr>();
3523 assert(
Asm->getLabel().size() < 64-Name.size() &&
3524 "Register name too big");
3525 Name.append(
Asm->getLabel());
3526 llvm::NamedMDNode *M =
3527 CGM.
getModule().getOrInsertNamedMetadata(Name);
3528 if (M->getNumOperands() == 0) {
3531 llvm::Metadata *Ops[] = {Str};
3538 llvm::MetadataAsValue::get(CGM.
getLLVMContext(), M->getOperand(0));
3581 case llvm::GlobalValue::ExternalLinkage:
3582 case llvm::GlobalValue::LinkOnceODRLinkage:
3583 case llvm::GlobalValue::WeakODRLinkage:
3584 case llvm::GlobalValue::InternalLinkage:
3585 case llvm::GlobalValue::PrivateLinkage:
3597 "should not emit an unevaluated operand");
3599 if (
const auto *VD = dyn_cast<VarDecl>(ND)) {
3602 VD->hasAttr<AsmLabelAttr>() && !VD->isLocalVarDecl())
3610 (VD->getType()->isReferenceType() ||
3612 VD->getAnyInitializer(VD);
3614 E->
getLocation(), *VD->evaluateValue(), VD->getType());
3615 assert(Val &&
"failed to emit constant expression");
3618 if (!VD->getType()->isReferenceType()) {
3620 Addr =
CGM.createUnnamedGlobalFrom(*VD, Val,
3623 auto *PTy = llvm::PointerType::get(
3642 VD = VD->getCanonicalDecl();
3646 auto I = LocalDeclMap.find(VD);
3647 if (I != LocalDeclMap.end()) {
3649 if (VD->getType()->isReferenceType())
3657 CGM.getOpenMPRuntime().isNontemporalDecl(VD))
3674 CGM.getOpenMPRuntime().isNontemporalDecl(VD))
3690 "Should not use decl without marking it used!");
3692 if (ND->
hasAttr<WeakRefAttr>()) {
3698 if (
const auto *VD = dyn_cast<VarDecl>(ND)) {
3700 if (VD->hasLinkage() || VD->isStaticDataMember())
3706 auto iter = LocalDeclMap.find(VD);
3707 if (iter != LocalDeclMap.end()) {
3708 addr = iter->second;
3712 }
else if (VD->isStaticLocal()) {
3713 llvm::Constant *var =
CGM.getOrCreateStaticVarDecl(
3714 *VD,
CGM.getLLVMLinkageVarDefinition(VD));
3720 llvm_unreachable(
"DeclRefExpr for Decl not entered in LocalDeclMap?");
3731 VD->hasAttr<OMPThreadPrivateDeclAttr>()) {
3738 bool isBlockByref = VD->isEscapingByref();
3744 LValue LV = VD->getType()->isReferenceType() ?
3748 bool isLocalStorage = VD->hasLocalStorage();
3750 bool NonGCable = isLocalStorage &&
3751 !VD->getType()->isReferenceType() &&
3758 bool isImpreciseLifetime =
3759 (isLocalStorage && !VD->hasAttr<ObjCPreciseLifetimeAttr>());
3760 if (isImpreciseLifetime)
3766 if (
const auto *FD = dyn_cast<FunctionDecl>(ND))
3772 if (
const auto *BD = dyn_cast<BindingDecl>(ND)) {
3789 if (
const auto *GD = dyn_cast<MSGuidDecl>(ND))
3793 if (
const auto *TPO = dyn_cast<TemplateParamObjectDecl>(ND)) {
3797 if (AS != T.getAddressSpace()) {
3800 llvm::PointerType::get(
CGM.getLLVMContext(), TargetAS);
3801 llvm::Constant *ASC =
CGM.performAddrSpaceCast(ATPO.
getPointer(), PtrTy);
3808 llvm_unreachable(
"Unhandled DeclRefExpr");
3818 default: llvm_unreachable(
"Unknown unary operator lvalue!");
3821 assert(!T.isNull() &&
"CodeGenFunction::EmitUnaryOpLValue: Illegal type");
3843 assert(LV.
isSimple() &&
"real/imag on non-ordinary l-value");
3860 CGM.getTBAAInfoForSubobject(LV, T));
3867 bool isInc = E->
getOpcode() == UO_PreInc;
3890 assert(SL !=
nullptr &&
"No StringLiteral name in PredefinedExpr");
3891 StringRef FnName =
CurFn->getName();
3892 FnName.consume_front(
"\01");
3893 StringRef NameItems[] = {
3895 std::string GVName = llvm::join(NameItems, NameItems + 2,
".");
3896 if (
auto *BD = dyn_cast_or_null<BlockDecl>(
CurCodeDecl)) {
3897 std::string Name = std::string(SL->getString());
3898 if (!Name.empty()) {
3899 unsigned Discriminator =
3900 CGM.getCXXABI().getMangleContext().getBlockId(BD,
true);
3902 Name +=
"_" + Twine(Discriminator + 1).str();
3903 auto C =
CGM.GetAddrOfConstantCString(Name, GVName);
3906 auto C =
CGM.GetAddrOfConstantCString(std::string(FnName), GVName);
3910 auto C =
CGM.GetAddrOfConstantStringFromLiteral(SL, GVName);
3927 if (llvm::Constant *
C =
CGM.getTypeDescriptorFromMap(T))
3932 bool IsBitInt =
false;
3934 if (T->isIntegerType()) {
3937 (T->isSignedIntegerType() ? 1 : 0);
3941 if (T->isSignedIntegerType() && T->getAs<
BitIntType>()) {
3944 " non positive amount of bits in __BitInt type");
3946 " too many bits in __BitInt type");
3953 }
else if (T->isFloatingType()) {
3962 (
intptr_t)T.getAsOpaquePtr(), StringRef(),
3963 StringRef(), {}, Buffer, {});
3968 char S[6] = {
'\0',
'\0',
'\0',
'\0',
'\0',
'\0'};
3971 llvm::support::endian::write32(S + 1, Bits,
3973 ? llvm::endianness::big
3974 : llvm::endianness::little);
3975 StringRef Str = StringRef(S,
sizeof(S) /
sizeof(
decltype(S[0])));
3979 llvm::Constant *Components[] = {
3983 llvm::Constant *Descriptor = llvm::ConstantStruct::getAnon(Components);
3985 auto *GV =
new llvm::GlobalVariable(
3986 CGM.getModule(), Descriptor->getType(),
3987 true, llvm::GlobalVariable::PrivateLinkage, Descriptor);
3988 GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
3989 CGM.getSanitizerMetadata()->disableSanitizerForGlobal(GV);
3992 CGM.setTypeDescriptorInMap(T, GV);
4000 if (
V->getType() == TargetTy)
4005 if (
V->getType()->isFloatingPointTy()) {
4006 unsigned Bits =
V->getType()->getPrimitiveSizeInBits().getFixedValue();
4007 if (Bits <= TargetTy->getIntegerBitWidth())
4013 if (
V->getType()->isIntegerTy() &&
4014 V->getType()->getIntegerBitWidth() <= TargetTy->getIntegerBitWidth())
4015 return Builder.CreateZExt(
V, TargetTy);
4018 if (!
V->getType()->isPointerTy()) {
4023 return Builder.CreatePtrToInt(
V, TargetTy);
4036 llvm::Constant *Filename;
4043 int PathComponentsToStrip =
4044 CGM.getCodeGenOpts().EmitCheckPathComponentsToStrip;
4045 if (PathComponentsToStrip < 0) {
4046 assert(PathComponentsToStrip !=
INT_MIN);
4047 int PathComponentsToKeep = -PathComponentsToStrip;
4048 auto I = llvm::sys::path::rbegin(FilenameString);
4049 auto E = llvm::sys::path::rend(FilenameString);
4050 while (I != E && --PathComponentsToKeep)
4053 FilenameString = FilenameString.substr(I - E);
4054 }
else if (PathComponentsToStrip > 0) {
4055 auto I = llvm::sys::path::begin(FilenameString);
4056 auto E = llvm::sys::path::end(FilenameString);
4057 while (I != E && PathComponentsToStrip--)
4062 FilenameString.substr(I - llvm::sys::path::begin(FilenameString));
4064 FilenameString = llvm::sys::path::filename(FilenameString);
4068 CGM.GetAddrOfConstantCString(std::string(FilenameString),
".src");
4069 CGM.getSanitizerMetadata()->disableSanitizerForGlobal(
4071 FilenameGV.getPointer()->stripPointerCasts()));
4072 Filename = FilenameGV.getPointer();
4076 Filename = llvm::Constant::getNullValue(
Int8PtrTy);
4083 return llvm::ConstantStruct::getAnon(
Data);
4088enum class CheckRecoverableKind {
4099static CheckRecoverableKind
4101 if (Ordinal == SanitizerKind::SO_Vptr)
4102 return CheckRecoverableKind::AlwaysRecoverable;
4103 else if (Ordinal == SanitizerKind::SO_Return ||
4104 Ordinal == SanitizerKind::SO_Unreachable)
4105 return CheckRecoverableKind::Unrecoverable;
4107 return CheckRecoverableKind::Recoverable;
4111struct SanitizerHandlerInfo {
4112 char const *
const Name;
4118#define SANITIZER_CHECK(Enum, Name, Version, Msg) {#Name, Version},
4120#undef SANITIZER_CHECK
4124 llvm::FunctionType *FnType,
4127 CheckRecoverableKind RecoverKind,
bool IsFatal,
4128 llvm::BasicBlock *ContBB,
bool NoMerge) {
4129 assert(IsFatal || RecoverKind != CheckRecoverableKind::Unrecoverable);
4130 std::optional<ApplyDebugLocation> DL;
4131 if (!CGF.
Builder.getCurrentDebugLocation()) {
4135 bool NeedsAbortSuffix =
4136 IsFatal && RecoverKind != CheckRecoverableKind::Unrecoverable;
4138 bool HandlerPreserveAllRegs =
4141 const StringRef CheckName = CheckInfo.Name;
4142 std::string FnName =
"__ubsan_handle_" + CheckName.str();
4143 if (CheckInfo.Version && !MinimalRuntime)
4144 FnName +=
"_v" + llvm::utostr(CheckInfo.Version);
4146 FnName +=
"_minimal";
4147 if (NeedsAbortSuffix)
4149 if (HandlerPreserveAllRegs && !NeedsAbortSuffix)
4150 FnName +=
"_preserve";
4152 !IsFatal || RecoverKind == CheckRecoverableKind::AlwaysRecoverable;
4156 B.addAttribute(llvm::Attribute::NoReturn)
4157 .addAttribute(llvm::Attribute::NoUnwind);
4159 B.addUWTableAttr(llvm::UWTableKind::Default);
4164 llvm::AttributeList::FunctionIndex, B),
4170 HandlerCall->addFnAttr(llvm::Attribute::NoMerge);
4171 if (HandlerPreserveAllRegs && !NeedsAbortSuffix) {
4173 HandlerCall->setCallingConv(llvm::CallingConv::PreserveAll);
4176 HandlerCall->setDoesNotReturn();
4177 CGF.
Builder.CreateUnreachable();
4184 ArrayRef<std::pair<llvm::Value *, SanitizerKind::SanitizerOrdinal>> Checked,
4188 assert(Checked.size() > 0);
4189 assert(CheckHandler >= 0 &&
4193 llvm::Value *FatalCond =
nullptr;
4194 llvm::Value *RecoverableCond =
nullptr;
4195 llvm::Value *TrapCond =
nullptr;
4196 bool NoMerge =
false;
4203 for (
auto &[Check, Ord] : Checked) {
4204 llvm::Value *GuardedCheck = Check;
4206 (
CGM.getCodeGenOpts().SanitizeSkipHotCutoffs[Ord] > 0)) {
4208 CGM.getIntrinsic(llvm::Intrinsic::allow_ubsan_check),
4209 llvm::ConstantInt::get(
CGM.Int8Ty, Ord));
4214 llvm::Value *&
Cond =
CGM.getCodeGenOpts().SanitizeTrap.has(Ord) ? TrapCond
4215 :
CGM.getCodeGenOpts().SanitizeRecover.has(Ord)
4220 if (!
CGM.getCodeGenOpts().SanitizeMergeHandlers.has(Ord))
4226 if (!FatalCond && !RecoverableCond)
4229 llvm::Value *JointCond;
4230 if (FatalCond && RecoverableCond)
4231 JointCond =
Builder.CreateAnd(FatalCond, RecoverableCond);
4233 JointCond = FatalCond ? FatalCond : RecoverableCond;
4237 assert(
SanOpts.has(Checked[0].second));
4239 for (
int i = 1, n = Checked.size(); i < n; ++i) {
4241 "All recoverable kinds in a single check must be same!");
4242 assert(
SanOpts.has(Checked[i].second));
4248 llvm::Instruction *Branch =
Builder.CreateCondBr(JointCond, Cont, Handlers);
4251 llvm::MDNode *Node = MDHelper.createLikelyBranchWeights();
4252 Branch->setMetadata(llvm::LLVMContext::MD_prof, Node);
4256 if (
CGM.getCodeGenOpts().SanitizeMinimalRuntime) {
4267 Args.reserve(DynamicArgs.size() + 1);
4268 ArgTypes.reserve(DynamicArgs.size() + 1);
4271 if (!StaticArgs.empty()) {
4272 llvm::Constant *Info = llvm::ConstantStruct::getAnon(StaticArgs);
4273 auto *InfoPtr =
new llvm::GlobalVariable(
4274 CGM.getModule(), Info->getType(),
4277 false, llvm::GlobalVariable::PrivateLinkage, Info,
"",
4278 nullptr, llvm::GlobalVariable::NotThreadLocal,
4279 CGM.getDataLayout().getDefaultGlobalsAddressSpace());
4280 InfoPtr->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
4281 CGM.getSanitizerMetadata()->disableSanitizerForGlobal(InfoPtr);
4282 Args.push_back(InfoPtr);
4283 ArgTypes.push_back(Args.back()->getType());
4286 for (llvm::Value *DynamicArg : DynamicArgs) {
4291 llvm::FunctionType *FnType =
4292 llvm::FunctionType::get(
CGM.VoidTy, ArgTypes,
false);
4294 if (!FatalCond || !RecoverableCond) {
4298 (FatalCond !=
nullptr), Cont, NoMerge);
4302 llvm::BasicBlock *NonFatalHandlerBB =
4305 Builder.CreateCondBr(FatalCond, NonFatalHandlerBB, FatalHandlerBB);
4308 NonFatalHandlerBB, NoMerge);
4319 llvm::ConstantInt *TypeId, llvm::Value *Ptr,
4324 llvm::CondBrInst *BI =
Builder.CreateCondBr(
Cond, Cont, CheckBB);
4327 llvm::MDNode *Node = MDHelper.createLikelyBranchWeights();
4328 BI->setMetadata(llvm::LLVMContext::MD_prof, Node);
4332 bool WithDiag = !
CGM.getCodeGenOpts().SanitizeTrap.has(Ordinal);
4334 llvm::CallInst *CheckCall;
4335 llvm::FunctionCallee SlowPathFn;
4337 llvm::Constant *Info = llvm::ConstantStruct::getAnon(StaticArgs);
4339 new llvm::GlobalVariable(
CGM.getModule(), Info->getType(),
false,
4340 llvm::GlobalVariable::PrivateLinkage, Info);
4341 InfoPtr->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
4342 CGM.getSanitizerMetadata()->disableSanitizerForGlobal(InfoPtr);
4344 SlowPathFn =
CGM.getModule().getOrInsertFunction(
4345 "__cfi_slowpath_diag",
4348 CheckCall =
Builder.CreateCall(SlowPathFn, {TypeId, Ptr, InfoPtr});
4350 SlowPathFn =
CGM.getModule().getOrInsertFunction(
4353 CheckCall =
Builder.CreateCall(SlowPathFn, {TypeId, Ptr});
4358 CheckCall->setDoesNotThrow();
4366 llvm::Module *M = &
CGM.getModule();
4368 QualType QInt64Ty =
C.getIntTypeForBitwidth(64,
false);
4370 auto *ArgCallsiteTypeId =
4374 auto *ArgCFICheckFailData =
4378 CGM.getTypes().arrangeBuiltinFunctionDeclaration(
C.VoidTy,
FnArgs);
4380 llvm::Function *F = llvm::Function::Create(
4382 llvm::GlobalValue::WeakAnyLinkage,
"__cfi_check", M);
4384 CGM.SetLLVMFunctionAttributesForDefinition(
nullptr, F);
4385 F->setAlignment(llvm::Align(4096));
4388 llvm::LLVMContext &Ctx = M->getContext();
4389 llvm::BasicBlock *BB = llvm::BasicBlock::Create(Ctx,
"entry", F);
4392 llvm::CallInst::Create(M->getFunction(
"__cfi_check_fail"), Args,
"", BB);
4393 llvm::ReturnInst::Create(Ctx,
nullptr, BB);
4404 auto CheckHandler = SanitizerHandler::CFICheckFail;
4411 {SanitizerKind::SO_CFIVCall, SanitizerKind::SO_CFINVCall,
4412 SanitizerKind::SO_CFIDerivedCast, SanitizerKind::SO_CFIUnrelatedCast,
4413 SanitizerKind::SO_CFIICall},
4424 llvm::Function *F = llvm::Function::Create(
4426 llvm::GlobalValue::WeakODRLinkage,
"__cfi_check_fail", &
CGM.getModule());
4429 CGM.SetLLVMFunctionAttributesForDefinition(
nullptr, F);
4430 F->setVisibility(llvm::GlobalValue::HiddenVisibility);
4444 CGM.getContext().VoidPtrTy, ArgData->getLocation());
4447 CGM.getContext().VoidPtrTy, ArgAddr->getLocation());
4450 llvm::Value *DataIsNotNullPtr =
4455 EmitTrapCheck(DataIsNotNullPtr, SanitizerHandler::CFICheckFail,
4458 llvm::StructType *SourceLocationTy =
4460 llvm::StructType *CfiCheckFailDataTy =
4463 llvm::Value *
V =
Builder.CreateConstGEP2_32(
4467 llvm::Value *CheckKind =
Builder.CreateLoad(CheckKindAddr);
4469 llvm::Value *AllVtables = llvm::MetadataAsValue::get(
4470 CGM.getLLVMContext(),
4471 llvm::MDString::get(
CGM.getLLVMContext(),
"all-vtables"));
4472 llvm::Value *ValidVtable =
Builder.CreateZExt(
4473 Builder.CreateCall(
CGM.getIntrinsic(llvm::Intrinsic::type_test),
4474 {Addr, AllVtables}),
4477 const std::pair<int, SanitizerKind::SanitizerOrdinal> CheckKinds[] = {
4484 for (
auto CheckKindOrdinalPair : CheckKinds) {
4485 int Kind = CheckKindOrdinalPair.first;
4492 Builder.CreateICmpNE(CheckKind, llvm::ConstantInt::get(
Int8Ty, Kind));
4493 if (
CGM.getLangOpts().Sanitize.has(Ordinal))
4494 EmitCheck(std::make_pair(
Cond, Ordinal), SanitizerHandler::CFICheckFail,
4507 CGM.addUsedGlobal(F);
4511 if (
SanOpts.has(SanitizerKind::Unreachable)) {
4512 auto CheckOrdinal = SanitizerKind::SO_Unreachable;
4513 auto CheckHandler = SanitizerHandler::BuiltinUnreachable;
4529 if ((
int)TrapBBs.size() <= CheckHandlerID)
4530 TrapBBs.resize(CheckHandlerID + 1);
4532 llvm::BasicBlock *&TrapBB = TrapBBs[CheckHandlerID];
4534 llvm::DILocation *TrapLocation =
Builder.getCurrentDebugLocation();
4535 llvm::StringRef TrapMessage;
4536 llvm::StringRef TrapCategory;
4537 auto DebugTrapReasonKind =
CGM.getCodeGenOpts().getSanitizeDebugTrapReasons();
4539 DebugTrapReasonKind ==
4545 TrapCategory =
"Undefined Behavior Sanitizer";
4549 DebugTrapReasonKind !=
4553 TrapLocation, TrapCategory, TrapMessage);
4556 NoMerge = NoMerge || !
CGM.getCodeGenOpts().isOptimizedBuild() ||
4560 if (TrapBB && !NoMerge) {
4561 auto Call = TrapBB->begin();
4564 Call->applyMergedLocation(
Call->getDebugLoc(), TrapLocation);
4566 Builder.CreateCondBr(Checked, Cont, TrapBB,
4567 MDHelper.createLikelyBranchWeights());
4570 Builder.CreateCondBr(Checked, Cont, TrapBB,
4571 MDHelper.createLikelyBranchWeights());
4576 llvm::CallInst *TrapCall;
4577 if (
CGM.getCodeGenOpts().SanitizeTrapLoop)
4579 Builder.CreateCall(
CGM.getIntrinsic(llvm::Intrinsic::looptrap));
4581 TrapCall =
Builder.CreateCall(
4582 CGM.getIntrinsic(llvm::Intrinsic::ubsantrap),
4583 llvm::ConstantInt::get(
CGM.Int8Ty, CheckHandlerID));
4585 if (!
CGM.getCodeGenOpts().TrapFuncName.empty()) {
4586 auto A = llvm::Attribute::get(
getLLVMContext(),
"trap-func-name",
4587 CGM.getCodeGenOpts().TrapFuncName);
4588 TrapCall->addFnAttr(A);
4591 TrapCall->addFnAttr(llvm::Attribute::NoMerge);
4592 TrapCall->setDoesNotReturn();
4593 TrapCall->setDoesNotThrow();
4601 llvm::CallInst *TrapCall =
4602 Builder.CreateCall(
CGM.getIntrinsic(IntrID));
4604 if (!
CGM.getCodeGenOpts().TrapFuncName.empty()) {
4605 auto A = llvm::Attribute::get(
getLLVMContext(),
"trap-func-name",
4606 CGM.getCodeGenOpts().TrapFuncName);
4607 TrapCall->addFnAttr(A);
4611 TrapCall->addFnAttr(llvm::Attribute::NoMerge);
4619 "Array to pointer decay must have array source type!");
4628 Addr =
Addr.withElementType(NewTy);
4634 "Expected pointer to array");
4640 Builder.CreateStructuredGEP(NewTy,
Addr.emitRawPointer(*
this), {});
4654 if (TBAAInfo) *TBAAInfo =
CGM.getTBAAAccessInfo(EltType);
4663 const auto *CE = dyn_cast<CastExpr>(E);
4664 if (!CE || CE->getCastKind() != CK_ArrayToPointerDecay)
4676 llvm::Type *elemType,
4682 const llvm::Twine &name =
"arrayidx") {
4683 if (inbounds && CGF.
getLangOpts().EmitLogicalPointer)
4684 return CGF.
Builder.CreateStructuredGEP(elemType, ptr, indices);
4698 llvm::Type *elementType,
bool inbounds,
4701 const llvm::Twine &name =
"arrayidx") {
4702 if (inbounds && CGF.
getLangOpts().EmitLogicalPointer)
4705 indices.drop_front()),
4706 elementType, align);
4727 return D && D->
hasAttr<BPFPreserveStaticOffsetAttr>();
4734 if (PointeeType.
isNull())
4747 llvm::Function *Fn =
4749 llvm::CallInst *
Call = CGF.
Builder.CreateCall(Fn, {
Addr.emitRawPointer(CGF)});
4767 if (
const auto *ME = dyn_cast<MemberExpr>(E))
4768 return ME->getMemberDecl()->hasAttr<BPFPreserveAccessIndexAttr>();
4770 if (
const auto *DRE = dyn_cast<DeclRefExpr>(E)) {
4771 const auto *VarDef = dyn_cast<VarDecl>(DRE->getDecl());
4775 const auto *PtrT = VarDef->getType()->getAs<
PointerType>();
4781 if (
const auto *RecT = dyn_cast<RecordType>(PointeeT))
4782 return RecT->getDecl()
4783 ->getMostRecentDecl()
4784 ->
hasAttr<BPFPreserveAccessIndexAttr>();
4797 const llvm::Twine &name =
"arrayidx") {
4800 for (
auto *idx : indices.drop_back())
4819 llvm::Value *eltPtr;
4820 auto LastIndex = dyn_cast<llvm::ConstantInt>(indices.back());
4827 signedIndices, loc, eltAlign, name);
4831 unsigned idx = LastIndex->getZExtValue();
4832 llvm::DIType *DbgInfo =
nullptr;
4835 eltPtr = CGF.
Builder.CreatePreserveArrayAccessIndex(
4847struct StructFieldAccess
4848 :
public ConstStmtVisitor<StructFieldAccess, const Expr *> {
4849 const Expr *VisitCastExpr(
const CastExpr *E) {
4854 const Expr *VisitParenExpr(
const ParenExpr *E) {
4863 const FieldDecl *Field, int64_t &Offset) {
4866 unsigned FieldNo = 0;
4901 if (FD1OuterRec != FD2OuterRec)
4903 return std::optional<int64_t>();
4905 int64_t FD1Offset = 0;
4907 return std::optional<int64_t>();
4909 int64_t FD2Offset = 0;
4911 return std::optional<int64_t>();
4913 return std::make_optional<int64_t>(FD1Offset - FD2Offset);
4925 QualType IndexType, llvm::Value *IndexVal,
bool Accessed,
4926 bool FlexibleArray) {
4927 const auto *ME = dyn_cast<MemberExpr>(ArrayExpr->
IgnoreImpCasts());
4928 if (!ME || !ME->getMemberDecl()->getType()->isCountAttributedType())
4933 if (FlexibleArray &&
4934 !ME->isFlexibleArrayMemberLike(
getContext(), StrictFlexArraysLevel))
4942 if (std::optional<int64_t> Diff =
4957 ArrayInst =
Builder.CreatePointerBitCastOrAddrSpaceCast(ArrayInst,
4961 llvm::Value *BoundsVal =
4963 Builder.getInt32(*Diff),
".counted_by.gep");
4965 ".counted_by.load");
4969 CountFD->
getType(), Accessed);
4977 llvm::Value *IdxPre =
4979 bool SignedIndices =
false;
4980 auto EmitIdxAfterBase = [&, IdxPre](
bool Promote) -> llvm::Value * {
4983 assert(E->
getRHS() == E->
getIdx() &&
"index was neither LHS nor RHS");
4989 SignedIndices |= IdxSigned;
4991 if (
SanOpts.has(SanitizerKind::ArrayBounds))
4995 if (Promote && Idx->getType() !=
IntPtrTy)
5008 auto *Idx = EmitIdxAfterBase(
false);
5009 assert(LHS.
isSimple() &&
"Can only subscript lvalue vectors here!");
5017 std::optional<LValue> LV;
5020 LV =
CGM.getHLSLRuntime().emitResourceArraySubscriptExpr(E, *
this);
5022 LV =
CGM.getHLSLRuntime().emitBufferArraySubscriptExpr(E, *
this,
5034 auto *Idx = EmitIdxAfterBase(
true);
5041 CGM.getTBAAInfoForSubobject(LV, EltType));
5053 auto *Idx = EmitIdxAfterBase(
true);
5063 Idx =
Builder.CreateMul(Idx, numElements);
5065 Idx =
Builder.CreateNSWMul(Idx, numElements);
5077 auto *Idx = EmitIdxAfterBase(
true);
5080 llvm::Value *InterfaceSizeVal =
5081 llvm::ConstantInt::get(Idx->getType(), InterfaceSize.
getQuantity());
5083 llvm::Value *ScaledIdx =
Builder.CreateMul(Idx, InterfaceSizeVal);
5089 llvm::Type *OrigBaseElemTy =
Addr.getElementType();
5094 llvm::Value *EltPtr =
5096 ScaledIdx,
false, SignedIndices, E->
getExprLoc());
5103 assert(Array->getType()->isArrayType() &&
5104 "Array to pointer decay must have array source type!");
5108 if (
const auto *ASE = dyn_cast<ArraySubscriptExpr>(Array))
5112 auto *Idx = EmitIdxAfterBase(
true);
5114 if (
SanOpts.has(SanitizerKind::ArrayBounds))
5122 *
this, ArrayLV.
getAddress(), {CGM.getSize(CharUnits::Zero()), Idx},
5126 if (!
CGM.getCodeGenOpts().NewStructPathTBAA) {
5129 EltTBAAInfo =
CGM.getTBAAInfoForSubobject(ArrayLV, E->
getType());
5134 EltTBAAInfo =
CGM.getTBAAAccessInfo(E->
getType());
5156 auto *Idx = EmitIdxAfterBase(
true);
5163 if (
SanOpts.has(SanitizerKind::ArrayBounds)) {
5164 StructFieldAccess Visitor;
5167 if (
const auto *CE = dyn_cast_if_present<CastExpr>(
Base);
5168 CE && CE->getCastKind() == CK_LValueToRValue)
5201 MatAddr =
CGM.getHLSLRuntime().createBufferMatrixTempAddress(
5212 "incomplete matrix subscript expressions should be rejected during Sema");
5218 llvm::MatrixBuilder MB(
Builder);
5221 unsigned NumRows = MatrixTy->getNumRows();
5222 bool IsMatrixRowMajor =
getLangOpts().getDefaultMatrixMemoryLayout() ==
5224 llvm::Value *FinalIdx =
5225 MB.CreateIndex(RowIdx, ColIdx, NumRows, NumCols, IsMatrixRowMajor);
5236 bool IsLowerBound) {
5238 if (
auto *ASE = dyn_cast<ArraySectionExpr>(
Base->IgnoreParenImpCasts())) {
5242 BaseInfo = BaseLVal.getBaseInfo();
5247 Addr =
Addr.withElementType(NewTy);
5253 "Expected pointer to array");
5263 BaseInfo.mergeForCast(TypeBaseInfo);
5272 bool IsLowerBound) {
5275 "OpenACC Array section codegen not implemented");
5279 if (
auto *AT =
getContext().getAsArrayType(BaseTy))
5280 ResultExprTy = AT->getElementType();
5283 llvm::Value *Idx =
nullptr;
5291 LowerBound->getType()->hasSignedIntegerRepresentation());
5293 Idx = llvm::ConstantInt::getNullValue(
IntPtrTy);
5298 auto &
C =
CGM.getContext();
5300 llvm::APSInt ConstLength;
5303 if (std::optional<llvm::APSInt>
CL = Length->getIntegerConstantExpr(
C)) {
5310 if (std::optional<llvm::APSInt> LB =
5311 LowerBound->getIntegerConstantExpr(
C)) {
5313 LowerBound =
nullptr;
5318 else if (!LowerBound)
5321 if (Length || LowerBound) {
5322 auto *LowerBoundVal =
5326 LowerBound->getType()->hasSignedIntegerRepresentation())
5327 : llvm::ConstantInt::get(
IntPtrTy, ConstLowerBound);
5332 Length->getType()->hasSignedIntegerRepresentation())
5333 : llvm::ConstantInt::get(
IntPtrTy, ConstLength);
5334 Idx =
Builder.CreateAdd(LowerBoundVal, LengthVal,
"lb_add_len",
5337 if (Length && LowerBound) {
5339 Idx, llvm::ConstantInt::get(
IntPtrTy, 1),
"idx_sub_1",
5343 Idx = llvm::ConstantInt::get(
IntPtrTy, ConstLength + ConstLowerBound);
5349 if (
auto *VAT =
C.getAsVariableArrayType(ArrayTy)) {
5350 Length = VAT->getSizeExpr();
5351 if (std::optional<llvm::APSInt> L = Length->getIntegerConstantExpr(
C)) {
5356 auto *CAT =
C.getAsConstantArrayType(ArrayTy);
5357 assert(CAT &&
"unexpected type for array initializer");
5358 ConstLength = CAT->getSize();
5361 auto *LengthVal =
Builder.CreateIntCast(
5363 Length->getType()->hasSignedIntegerRepresentation());
5365 LengthVal, llvm::ConstantInt::get(
IntPtrTy, 1),
"len_sub_1",
5370 Idx = llvm::ConstantInt::get(
IntPtrTy, ConstLength);
5379 if (
auto *VLA =
getContext().getAsVariableArrayType(ResultExprTy)) {
5385 BaseTy, VLA->getElementType(), IsLowerBound);
5394 Idx =
Builder.CreateMul(Idx, NumElements);
5396 Idx =
Builder.CreateNSWMul(Idx, NumElements);
5405 assert(Array->getType()->isArrayType() &&
5406 "Array to pointer decay must have array source type!");
5410 if (
const auto *ASE = dyn_cast<ArraySubscriptExpr>(Array))
5417 *
this, ArrayLV.
getAddress(), {CGM.getSize(CharUnits::Zero()), Idx},
5418 ResultExprTy, !
getLangOpts().PointerOverflowDefined,
5421 TBAAInfo =
CGM.getTBAAInfoForSubobject(ArrayLV, ResultExprTy);
5425 ResultExprTy, IsLowerBound);
5448 Base.getQuals().removeObjCGCAttr();
5457 "Result must be a vector");
5465 if (LTy->getScalarSizeInBits() > Vec->getType()->getScalarSizeInBits())
5466 Vec =
Builder.CreateZExt(Vec, LTy);
5467 Builder.CreateStore(Vec, VecMem);
5478 if (
Base.isSimple()) {
5479 llvm::Constant *CV =
5485 if (
Base.isMatrixRow()) {
5487 llvm::dyn_cast<llvm::ConstantInt>(
Base.getMatrixRowIdx())) {
5491 unsigned NumCols = Indices.size();
5493 unsigned Row = RowIdx->getZExtValue();
5497 QualType ElemQT = EVT->getElementType();
5500 for (
unsigned C = 0;
C < NumCols; ++
C) {
5501 unsigned Col = Indices[
C];
5502 unsigned Linear = Col * NumRows + Row;
5503 MatIndices.push_back(llvm::ConstantInt::get(
Int32Ty, Linear));
5506 llvm::Constant *ConstIdxs = llvm::ConstantVector::get(MatIndices);
5510 llvm::Constant *Cols =
5517 Base.getMatrixAddress(),
Base.getMatrixRowIdx(), Cols,
Base.getType(),
5521 assert(
Base.isExtVectorElt() &&
"Can only subscript lvalue vec elts here!");
5523 llvm::Constant *BaseElts =
Base.getExtVectorElts();
5526 for (
unsigned Index : Indices)
5527 CElts.push_back(BaseElts->getAggregateElement(Index));
5528 llvm::Constant *CV = llvm::ConstantVector::get(CElts);
5535 while (
auto *BaseMemberExpr = dyn_cast<MemberExpr>(UnderlyingBaseExpr))
5536 UnderlyingBaseExpr = BaseMemberExpr->getBase()->
IgnoreParens();
5549 return CGM.getHLSLRuntime().emitBufferMemberExpr(*
this, E);
5552 std::optional<LValue> LV;
5553 LV =
CGM.getHLSLRuntime().emitResourceMemberExpr(*
this, E);
5563 bool IsInBounds = !
getLangOpts().PointerOverflowDefined &&
5575 SkippedChecks.
set(SanitizerKind::Alignment,
true);
5577 SkippedChecks.
set(SanitizerKind::Null,
true);
5585 if (
auto *Field = dyn_cast<FieldDecl>(ND)) {
5593 CGM.getOpenMPRuntime().isNontemporalDecl(Field)) ||
5600 if (
const auto *FD = dyn_cast<FunctionDecl>(ND))
5603 llvm_unreachable(
"Unhandled member declaration!");
5610 llvm::Value *ThisValue) {
5611 bool HasExplicitObjectParameter =
false;
5612 const auto *MD = dyn_cast_if_present<CXXMethodDecl>(
CurCodeDecl);
5614 HasExplicitObjectParameter = MD->isExplicitObjectMemberFunction();
5615 assert(MD->getParent()->isLambda());
5616 assert(MD->getParent() == Field->getParent());
5619 if (HasExplicitObjectParameter) {
5621 auto It = LocalDeclMap.find(D);
5622 assert(It != LocalDeclMap.end() &&
"explicit parameter not loaded?");
5623 Address AddrOfExplicitObject = It->getSecond();
5634 if (ThisTy != LambdaTy) {
5637 LambdaLV.
getAddress(), ThisTy, BasePathArray.begin(),
5657 unsigned FieldIndex) {
5658 unsigned I = 0, Skipped = 0;
5661 if (I == FieldIndex)
5663 if (F->isUnnamedBitField())
5668 return FieldIndex - Skipped;
5678 if (Offset.isZero())
5700 llvm::Type *StructType =
5706 {CGF.Builder.getSize(idx)}),
5721 const FieldDecl *field,
bool IsInBounds) {
5748 if (RD->isDynamicClass())
5751 for (
const auto &
Base : RD->bases())
5755 for (
const FieldDecl *Field : RD->fields())
5770 const bool UseVolatile =
isAAPCS(
CGM.getTarget()) &&
5771 CGM.getCodeGenOpts().AAPCSBitfieldWidth &&
5802 llvm::Type *FieldIntTy = llvm::Type::getIntNTy(
getLLVMContext(), SS);
5803 Addr =
Addr.withElementType(FieldIntTy);
5838 assert(!FieldTBAAInfo.
Offset &&
5839 "Nonzero offset for an access with no base type!");
5852 FieldTBAAInfo.
Size =
5859 if (
auto *ClassDef = dyn_cast<CXXRecordDecl>(rec)) {
5860 if (
CGM.getCodeGenOpts().StrictVTablePointers &&
5861 ClassDef->isDynamicClass()) {
5875 if (
CGM.getCodeGenOpts().StrictVTablePointers &&
5879 addr =
Builder.CreateLaunderInvariantGroup(addr);
5922 if (field->
hasAttr<AnnotateAttr>())
5938 QualType FieldType = Field->getType();
5944 *
this,
Base.getAddress(), Field,
5949 V =
V.withElementType(llvmType);
5958 CGM.getTBAAInfoForSubobject(
Base, FieldType));
5994 assert(E->
isTransparent() &&
"non-transparent glvalue init list");
6002 const Expr *Operand) {
6003 if (
auto *ThrowExpr = dyn_cast<CXXThrowExpr>(Operand->IgnoreParens())) {
6005 return std::nullopt;
6014std::optional<LValue> HandleConditionalOperatorLValueSimpleCase(
6016 const Expr *condExpr = E->
getCond();
6021 std::swap(Live, Dead);
6031 if (
auto *ThrowExpr = dyn_cast<CXXThrowExpr>(Live->
IgnoreParens())) {
6042 return std::nullopt;
6044struct ConditionalInfo {
6045 llvm::BasicBlock *lhsBlock, *rhsBlock;
6046 std::optional<LValue> LHS, RHS;
6051template<
typename FuncTy>
6053 const AbstractConditionalOperator *E,
6054 const FuncTy &BranchGenFunc) {
6070 Info.lhsBlock = CGF.
Builder.GetInsertBlock();
6073 CGF.
Builder.CreateBr(endBlock);
6081 Info.rhsBlock = CGF.
Builder.GetInsertBlock();
6093 "Unexpected conditional operator!");
6098 if (HandleConditionalOperatorLValueSimpleCase(*
this, E))
6101 EmitConditionalBlocks(*
this, E, [](CodeGenFunction &CGF,
const Expr *E) {
6108 if (!
expr->isGLValue()) {
6111 "Unexpected conditional operator!");
6116 if (std::optional<LValue> Res =
6117 HandleConditionalOperatorLValueSimpleCase(*
this,
expr))
6120 ConditionalInfo Info = EmitConditionalBlocks(
6121 *
this,
expr, [](CodeGenFunction &CGF,
const Expr *E) {
6125 if ((Info.LHS && !Info.LHS->isSimple()) ||
6126 (Info.RHS && !Info.RHS->isSimple()))
6129 if (Info.LHS && Info.RHS) {
6130 Address lhsAddr = Info.LHS->getAddress();
6131 Address rhsAddr = Info.RHS->getAddress();
6133 lhsAddr, rhsAddr, Info.lhsBlock, Info.rhsBlock,
6136 std::max(Info.LHS->getBaseInfo().getAlignmentSource(),
6137 Info.RHS->getBaseInfo().getAlignmentSource());
6139 Info.LHS->getTBAAInfo(), Info.RHS->getTBAAInfo());
6143 assert((Info.LHS || Info.RHS) &&
6144 "both operands of glvalue conditional are throw-expressions?");
6145 return Info.LHS ? *Info.LHS : *Info.RHS;
6157 llvm::scope_exit RestoreCurCast([
this, Prev =
CurCast] {
CurCast = Prev; });
6162 case CK_LValueToRValueBitCast:
6163 case CK_ArrayToPointerDecay:
6164 case CK_FunctionToPointerDecay:
6165 case CK_NullToMemberPointer:
6166 case CK_NullToPointer:
6167 case CK_IntegralToPointer:
6168 case CK_PointerToIntegral:
6169 case CK_PointerToBoolean:
6170 case CK_IntegralCast:
6171 case CK_BooleanToSignedIntegral:
6172 case CK_IntegralToBoolean:
6173 case CK_IntegralToFloating:
6174 case CK_FloatingToIntegral:
6175 case CK_FloatingToBoolean:
6176 case CK_FloatingCast:
6177 case CK_FloatingRealToComplex:
6178 case CK_FloatingComplexToReal:
6179 case CK_FloatingComplexToBoolean:
6180 case CK_FloatingComplexCast:
6181 case CK_FloatingComplexToIntegralComplex:
6182 case CK_IntegralRealToComplex:
6183 case CK_IntegralComplexToReal:
6184 case CK_IntegralComplexToBoolean:
6185 case CK_IntegralComplexCast:
6186 case CK_IntegralComplexToFloatingComplex:
6187 case CK_DerivedToBaseMemberPointer:
6188 case CK_BaseToDerivedMemberPointer:
6189 case CK_MemberPointerToBoolean:
6190 case CK_ReinterpretMemberPointer:
6191 case CK_AnyPointerToBlockPointerCast:
6192 case CK_ARCProduceObject:
6193 case CK_ARCConsumeObject:
6194 case CK_ARCReclaimReturnedObject:
6195 case CK_ARCExtendBlockObject:
6196 case CK_CopyAndAutoreleaseBlockObject:
6197 case CK_IntToOCLSampler:
6198 case CK_FloatingToFixedPoint:
6199 case CK_FixedPointToFloating:
6200 case CK_FixedPointCast:
6201 case CK_FixedPointToBoolean:
6202 case CK_FixedPointToIntegral:
6203 case CK_IntegralToFixedPoint:
6205 case CK_HLSLVectorTruncation:
6206 case CK_HLSLMatrixTruncation:
6207 case CK_HLSLArrayRValue:
6208 case CK_HLSLElementwiseCast:
6209 case CK_HLSLAggregateSplatCast:
6213 llvm_unreachable(
"dependent cast kind in IR gen!");
6215 case CK_BuiltinFnToFnPtr:
6216 llvm_unreachable(
"builtin functions are handled elsewhere");
6219 case CK_NonAtomicToAtomic:
6220 case CK_AtomicToNonAtomic:
6230 case CK_ConstructorConversion:
6231 case CK_UserDefinedConversion:
6232 case CK_CPointerToObjCPointerCast:
6233 case CK_BlockPointerToObjCPointerCast:
6234 case CK_LValueToRValue:
6249 if (
V.getElementType() != T)
6256 case CK_UncheckedDerivedToBase:
6257 case CK_DerivedToBase: {
6271 CGM.getTBAAInfoForSubobject(LV, E->
getType()));
6275 case CK_BaseToDerived: {
6290 if (
SanOpts.has(SanitizerKind::CFIDerivedCast))
6296 CGM.getTBAAInfoForSubobject(LV, E->
getType()));
6298 case CK_LValueBitCast: {
6302 CGM.EmitExplicitCastExprType(CE,
this);
6307 if (
SanOpts.has(SanitizerKind::CFIUnrelatedCast))
6313 CGM.getTBAAInfoForSubobject(LV, E->
getType()));
6315 case CK_AddressSpaceConversion: {
6324 case CK_ObjCObjectLValueCast: {
6328 CGM.getTBAAInfoForSubobject(LV, E->
getType()));
6330 case CK_ZeroToOCLOpaqueType:
6331 llvm_unreachable(
"NULL to OpenCL opaque type lvalue cast is not valid");
6333 case CK_VectorSplat: {
6341 llvm_unreachable(
"Unhandled lvalue cast kind?");
6349std::pair<LValue, LValue>
6364 return std::make_pair(BaseLV, TempLV);
6372 llvm::Value *
Addr = TempLV.getAddress().getBasePointer();
6377 Address TmpAddr(
Addr, ElTy, TempLV.getAlignment());
6387 llvm::DenseMap<const OpaqueValueExpr*,LValue>::iterator
6388 it = OpaqueLValues.find(e);
6390 if (it != OpaqueLValues.end())
6393 assert(e->
isUnique() &&
"LValue for a nonunique OVE hasn't been emitted");
6401 llvm::DenseMap<const OpaqueValueExpr*,RValue>::iterator
6402 it = OpaqueRValues.find(e);
6404 if (it != OpaqueRValues.end())
6407 assert(e->
isUnique() &&
"RValue for a nonunique OVE hasn't been emitted");
6413 return OpaqueLValues.contains(E);
6414 return OpaqueRValues.contains(E);
6438 llvm_unreachable(
"bad evaluation kind");
6447 llvm::CallBase **CallOrInvoke) {
6448 llvm::CallBase *CallOrInvokeStorage;
6449 if (!CallOrInvoke) {
6450 CallOrInvoke = &CallOrInvokeStorage;
6453 llvm::scope_exit AddCoroElideSafeOnExit([&] {
6455 auto *I = *CallOrInvoke;
6457 I->addFnAttr(llvm::Attribute::CoroElideSafe);
6465 if (
const auto *CE = dyn_cast<CXXMemberCallExpr>(E))
6468 if (
const auto *CE = dyn_cast<CUDAKernelCallExpr>(E))
6473 if (
const auto *CE = dyn_cast<CXXOperatorCallExpr>(E))
6474 if (
const auto *MD =
6475 dyn_cast_if_present<CXXMethodDecl>(CE->getCalleeDecl());
6476 MD && MD->isImplicitObjectMemberFunction())
6491 nullptr, CallOrInvoke);
6497 llvm::CallBase **CallOrInvoke) {
6500 nullptr, CallOrInvoke);
6508 if (!PD->isInlineBuiltinDeclaration())
6517 std::string NoBuiltinFD = (
"no-builtin-" + FD->
getName()).str();
6518 std::string NoBuiltins =
"no-builtins";
6521 std::string FDInlineName = (Ident +
".inline").str();
6523 bool IsPredefinedLibFunction =
6525 bool HasAttributeNoBuiltin =
6526 CGF.
CurFn->getAttributes().hasFnAttr(NoBuiltinFD) ||
6527 CGF.
CurFn->getAttributes().hasFnAttr(NoBuiltins);
6531 if (CGF.
CurFn->getName() != FDInlineName &&
6534 llvm::Function *Fn = llvm::cast<llvm::Function>(CalleePtr);
6535 llvm::Module *M = Fn->getParent();
6536 llvm::Function *Clone = M->getFunction(FDInlineName);
6538 Clone = llvm::Function::Create(Fn->getFunctionType(),
6539 llvm::GlobalValue::InternalLinkage,
6540 Fn->getAddressSpace(), FDInlineName, M);
6541 Clone->addFnAttr(llvm::Attribute::AlwaysInline);
6552 else if (!IsPredefinedLibFunction || !HasAttributeNoBuiltin)
6558 FD->
hasAttr<CUDAGlobalAttr>())
6566 if (DeviceKernelAttr::isOpenCLSpelling(FD->
getAttr<DeviceKernelAttr>()))
6575 if (
auto ICE = dyn_cast<ImplicitCastExpr>(E)) {
6576 if (ICE->getCastKind() == CK_FunctionToPointerDecay ||
6577 ICE->getCastKind() == CK_BuiltinFnToFnPtr) {
6583 if (ICE->getCastKind() == CK_LValueToRValue) {
6584 const Expr *SubExpr = ICE->getSubExpr();
6586 std::pair<llvm::Value *, CGPointerAuthInfo>
Result =
6593 if (
const auto *VD =
6604 }
else if (
auto DRE = dyn_cast<DeclRefExpr>(E)) {
6605 if (
auto FD = dyn_cast<FunctionDecl>(DRE->getDecl())) {
6608 }
else if (
auto ME = dyn_cast<MemberExpr>(E)) {
6609 if (
auto FD = dyn_cast<FunctionDecl>(ME->getMemberDecl())) {
6615 }
else if (
auto NTTP = dyn_cast<SubstNonTypeTemplateParmExpr>(E)) {
6619 }
else if (
auto PDE = dyn_cast<CXXPseudoDestructorExpr>(E)) {
6624 llvm::Value *calleePtr;
6636 if (
const auto *VD =
6642 CGCallee callee(calleeInfo, calleePtr, pointerAuth);
6658 assert(E->
getOpcode() == BO_Assign &&
"unexpected binary l-value");
6721 llvm::Value *
Result =
nullptr;
6724 if (
SanOpts.has(SanitizerKind::ImplicitBitfieldConversion))
6739 CGM.getOpenMPRuntime().checkAndEmitLastprivateConditional(*
this,
6756 llvm_unreachable(
"bad evaluation kind");
6768 if (
CGM.getHLSLRuntime().emitResourceArrayCopy(LHS, E->
getRHS(), *
this))
6779 llvm::CallBase **CallOrInvoke) {
6787 "Can't have a scalar return unless the return type is a "
6800 &&
"binding l-value to type which needs a temporary");
6838 "Can't have a scalar return unless the return type is a "
6852 return CGM.getObjCRuntime().EmitIvarOffset(*
this,
Interface, Ivar);
6860 return Builder.CreateZExtOrTrunc(OffsetValue,
6865 llvm::Value *BaseValue,
6867 unsigned CVRQualifiers) {
6868 return CGM.getObjCRuntime().EmitObjCValueForIvar(*
this, ObjectTy, BaseValue,
6869 Ivar, CVRQualifiers);
6874 llvm::Value *BaseValue =
nullptr;
6885 ObjectTy = BaseExpr->
getType();
6907 llvm::CallBase **CallOrInvoke,
6912 "Call must have function pointer type!");
6914 const Decl *TargetDecl =
6917 assert((!isa_and_present<FunctionDecl>(TargetDecl) ||
6919 "trying to emit a call to an immediate function");
6929 if (
SanOpts.has(SanitizerKind::Function) &&
6932 if (llvm::Constant *PrefixSig =
6933 CGM.getTargetCodeGenInfo().getUBSanFunctionSignature(
CGM)) {
6934 auto CheckOrdinal = SanitizerKind::SO_Function;
6935 auto CheckHandler = SanitizerHandler::FunctionTypeMismatch;
6939 llvm::Type *PrefixSigType = PrefixSig->getType();
6940 llvm::StructType *PrefixStructTy = llvm::StructType::get(
6941 CGM.getLLVMContext(), {PrefixSigType, Int32Ty},
true);
6943 llvm::Value *CalleePtr = Callee.getFunctionPointer();
6944 if (
CGM.getCodeGenOpts().PointerAuth.FunctionPointers) {
6947 Address(CalleePtr, CalleePtr->getType(),
6949 CalleePtr->getPointerAlignment(
CGM.getDataLayout())),
6950 Callee.getPointerAuthInfo(),
nullptr);
6951 CalleePtr =
Addr.emitRawPointer(*
this);
6963 llvm::Value *AlignedCalleePtr;
6964 if (
CGM.getTriple().isARM() ||
CGM.getTriple().isThumb()) {
6965 AlignedCalleePtr =
Builder.CreateIntrinsic(
6966 CalleePtr->getType(), llvm::Intrinsic::ptrmask,
6967 {CalleePtr, llvm::ConstantInt::getSigned(IntPtrTy, ~1)});
6969 AlignedCalleePtr = CalleePtr;
6972 llvm::Value *CalleePrefixStruct = AlignedCalleePtr;
6973 llvm::Value *CalleeSigPtr =
6974 Builder.CreateConstGEP2_32(PrefixStructTy, CalleePrefixStruct, -1, 0);
6975 llvm::Value *CalleeSig =
6977 llvm::Value *CalleeSigMatch =
Builder.CreateICmpEQ(CalleeSig, PrefixSig);
6981 Builder.CreateCondBr(CalleeSigMatch, TypeCheck, Cont);
6984 llvm::Value *CalleeTypeHash =
Builder.CreateAlignedLoad(
6986 Builder.CreateConstGEP2_32(PrefixStructTy, CalleePrefixStruct, -1, 1),
6988 llvm::Value *CalleeTypeHashMatch =
6989 Builder.CreateICmpEQ(CalleeTypeHash, TypeHash);
6992 EmitCheck(std::make_pair(CalleeTypeHashMatch, CheckOrdinal), CheckHandler,
6993 StaticData, {CalleePtr});
7002 if (
const auto *FD = dyn_cast_or_null<FunctionDecl>(TargetDecl);
7003 FD && DeviceKernelAttr::isOpenCLSpelling(FD->getAttr<DeviceKernelAttr>()))
7004 CGM.getTargetCodeGenInfo().setOCLKernelStubCallingConvention(FnType);
7008 if (
SanOpts.has(SanitizerKind::CFIICall) &&
7010 auto CheckOrdinal = SanitizerKind::SO_CFIICall;
7011 auto CheckHandler = SanitizerHandler::CFICheckFail;
7015 llvm::Metadata *MD =
7016 CGM.CreateMetadataIdentifierForFnType(
QualType(FnType, 0));
7018 llvm::Value *TypeId = llvm::MetadataAsValue::get(
getLLVMContext(), MD);
7020 llvm::Value *CalleePtr = Callee.getFunctionPointer();
7021 llvm::Value *TypeTest =
Builder.CreateCall(
7022 CGM.getIntrinsic(llvm::Intrinsic::type_test), {CalleePtr, TypeId});
7024 auto CrossDsoTypeId =
CGM.CreateCrossDsoCfiTypeId(MD);
7025 llvm::Constant *StaticData[] = {
7030 if (
CGM.getCodeGenOpts().SanitizeCfiCrossDso && CrossDsoTypeId) {
7034 EmitCheck(std::make_pair(TypeTest, CheckOrdinal), CheckHandler,
7035 StaticData, {CalleePtr, llvm::UndefValue::get(
IntPtrTy)});
7050 bool StaticOperator =
false;
7051 if (
auto *OCE = dyn_cast<CXXOperatorCallExpr>(E)) {
7052 if (OCE->isAssignmentOp())
7055 switch (OCE->getOperator()) {
7057 case OO_GreaterGreater:
7069 if (
const auto *MD =
7070 dyn_cast_if_present<CXXMethodDecl>(OCE->getCalleeDecl());
7071 MD && MD->isStatic())
7072 StaticOperator =
true;
7076 if (StaticOperator) {
7080 Arguments = drop_begin(Arguments, 1);
7082 EmitCallArgs(Args, dyn_cast<FunctionProtoType>(FnType), Arguments,
7086 Args, FnType, Chain);
7089 *ResolvedFnInfo = &FnInfo;
7094 if (
CGM.getLangOpts().HIP && !
CGM.getLangOpts().CUDAIsDevice &&
7097 llvm::Value *Handle = Callee.getFunctionPointer();
7099 Address(Handle, Handle->getType(),
CGM.getPointerAlign()));
7100 Callee.setFunctionPointer(
Stub);
7107 if (
getLangOpts().OpenMPIsTargetDevice &&
CGM.getTriple().isGPU() &&
7111 while (CalleeExpr) {
7112 if ((DRE = dyn_cast<DeclRefExpr>(CalleeExpr)))
7114 if (
const auto *ME = dyn_cast<MemberExpr>(CalleeExpr))
7116 else if (
const auto *ASE = dyn_cast<ArraySubscriptExpr>(CalleeExpr))
7122 const auto *VD = DRE ? dyn_cast<VarDecl>(DRE->
getDecl()) :
nullptr;
7123 if (VD && VD->hasAttr<OMPTargetIndirectCallAttr>()) {
7124 auto *FuncPtrTy = llvm::PointerType::get(
7125 CGM.getLLVMContext(),
CGM.getDataLayout().getProgramAddressSpace());
7126 llvm::Type *RtlFnArgs[] = {FuncPtrTy};
7127 llvm::FunctionCallee DeviceRtlFn =
CGM.CreateRuntimeFunction(
7128 llvm::FunctionType::get(FuncPtrTy, RtlFnArgs,
false),
7129 "__llvm_omp_indirect_call_lookup");
7130 llvm::Value *
Func = Callee.getFunctionPointer();
7131 llvm::Type *BackupTy =
Func->getType();
7135 Callee.setFunctionPointer(
Func);
7139 llvm::CallBase *LocalCallOrInvoke =
nullptr;
7143 if (
auto *CalleeDecl = dyn_cast_or_null<FunctionDecl>(TargetDecl)) {
7144 if (CalleeDecl->hasAttr<RestrictAttr>() ||
7145 CalleeDecl->hasAttr<MallocSpanAttr>() ||
7146 CalleeDecl->hasAttr<AllocSizeAttr>()) {
7148 if (
SanOpts.has(SanitizerKind::AllocToken)) {
7155 *CallOrInvoke = LocalCallOrInvoke;
7174 bool IsInBounds = !
getLangOpts().PointerOverflowDefined &&
7177 E, BaseAddr, OffsetV, MPT, IsInBounds, &BaseInfo, &TBAAInfo);
7179 return MakeAddrLValue(MemberAddr, MPT->getPointeeType(), BaseInfo, TBAAInfo);
7196 llvm_unreachable(
"bad evaluation kind");
7200 assert(Val->getType()->isFPOrFPVectorTy());
7205 llvm::MDNode *Node = MDHelper.createFPMath(Accuracy);
7211 llvm::Type *EltTy = Val->getType()->getScalarType();
7212 if (!EltTy->isFloatTy() && !EltTy->isHalfTy())
7216 !
CGM.getCodeGenOpts().OpenCLCorrectlyRoundedDivSqrt) ||
7218 !
CGM.getCodeGenOpts().HIPCorrectlyRoundedDivSqrt)) {
7233 llvm::Type *EltTy = Val->getType()->getScalarType();
7234 if (!EltTy->isFloatTy() && !EltTy->isHalfTy())
7238 !
CGM.getCodeGenOpts().OpenCLCorrectlyRoundedDivSqrt) ||
7240 !
CGM.getCodeGenOpts().HIPCorrectlyRoundedDivSqrt)) {
7255 struct LValueOrRValue {
7269 LValueOrRValue result;
7273 const Expr *semantic = *i;
7277 if (
const auto *ov = dyn_cast<OpaqueValueExpr>(semantic)) {
7279 if (ov->isUnique()) {
7280 assert(ov != resultExpr &&
7281 "A unique OVE cannot be used as the result expression");
7289 if (ov == resultExpr && ov->
isPRValue() && !forLValue &&
7294 opaqueData = OVMA::bind(CGF, ov, LV);
7299 opaqueData = OVMA::bind(CGF, ov, ov->getSourceExpr());
7302 if (ov == resultExpr) {
7310 opaques.push_back(opaqueData);
7314 }
else if (semantic == resultExpr) {
7346 std::tuple<LValue, QualType, llvm::SmallVector<llvm::Value *, 4>>, 16>
7348 llvm::IntegerType *IdxTy = llvm::IntegerType::get(
getLLVMContext(), 32);
7349 WorkList.push_back({Val, Val.
getType(), {llvm::ConstantInt::get(IdxTy, 0)}});
7351 while (!WorkList.empty()) {
7352 auto [LVal, T, IdxList] = WorkList.pop_back_val();
7353 T = T.getCanonicalType().getUnqualifiedType();
7354 if (
const auto *CAT = dyn_cast<ConstantArrayType>(T)) {
7355 uint64_t Size = CAT->getZExtSize();
7356 for (int64_t I = Size - 1; I > -1; I--) {
7358 IdxListCopy.push_back(llvm::ConstantInt::get(IdxTy, I));
7359 WorkList.emplace_back(LVal, CAT->getElementType(), IdxListCopy);
7361 }
else if (
const auto *RT = dyn_cast<RecordType>(T)) {
7363 assert(!
Record->isUnion() &&
"Union types not supported in flat cast.");
7368 std::tuple<LValue, QualType, llvm::SmallVector<llvm::Value *, 4>>, 16>
7377 "HLSL doesn't support multiple inheritance.");
7380 IdxListCopy.push_back(llvm::ConstantInt::get(
7382 ReverseList.emplace_back(LVal,
Base->getType(), IdxListCopy);
7391 bool createdGEP =
false;
7392 for (
auto *FD :
Record->fields()) {
7393 if (FD->isBitField()) {
7394 if (FD->isUnnamedBitField())
7398 Address GEP =
Builder.CreateInBoundsGEP(LVal.getAddress(), IdxList,
7399 LLVMT, Align,
"gep");
7403 ReverseList.push_back({FieldLVal, FD->
getType(), {}});
7406 IdxListCopy.push_back(
7408 ReverseList.emplace_back(LVal, FD->getType(), IdxListCopy);
7412 std::reverse(ReverseList.begin(), ReverseList.end());
7413 llvm::append_range(WorkList, ReverseList);
7414 }
else if (
const auto *VT = dyn_cast<VectorType>(T)) {
7417 Address GEP =
Builder.CreateInBoundsGEP(LVal.getAddress(), IdxList, LLVMT,
7418 Align,
"vector.gep");
7420 for (
unsigned I = 0, E = VT->getNumElements(); I < E; I++) {
7421 llvm::Constant *Idx = llvm::ConstantInt::get(IdxTy, I);
7425 AccessList.emplace_back(LV);
7427 }
else if (
const auto *MT = dyn_cast<ConstantMatrixType>(T)) {
7435 Address GEP =
Builder.CreateInBoundsGEP(LVal.getAddress(), IdxList, LLVMT,
7436 Align,
"matrix.gep");
7439 unsigned NumRows = MT->getNumRows();
7440 unsigned NumCols = MT->getNumColumns();
7441 bool IsMatrixRowMajor =
getLangOpts().getDefaultMatrixMemoryLayout() ==
7443 llvm::MatrixBuilder MB(
Builder);
7444 for (
unsigned Row = 0; Row < MT->getNumRows(); Row++) {
7445 for (
unsigned Col = 0; Col < MT->getNumColumns(); Col++) {
7446 llvm::Value *RowIdx = llvm::ConstantInt::get(IdxTy, Row);
7447 llvm::Value *ColIdx = llvm::ConstantInt::get(IdxTy, Col);
7448 llvm::Value *Idx = MB.CreateIndex(RowIdx, ColIdx, NumRows, NumCols,
7453 AccessList.emplace_back(LV);
7457 if (!IdxList.empty()) {
7460 Address GEP =
Builder.CreateInBoundsGEP(LVal.getAddress(), IdxList,
7461 LLVMT, Align,
"gep");
7464 AccessList.emplace_back(LVal);
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 void setObjCGCLValueClass(const ASTContext &Ctx, const Expr *E, LValue &LV, bool IsMemberAccess=false)
static LValue EmitGlobalNamedRegister(const VarDecl *VD, CodeGenModule &CGM)
Named Registers are named metadata pointing to the register name which will be read from/written to a...
static bool getRangeForType(CodeGenFunction &CGF, QualType Ty, llvm::APInt &Min, llvm::APInt &End, bool StrictEnums, bool StrictBool, bool IsBool)
static llvm::Value * emitHashMix(CGBuilderTy &Builder, llvm::Value *Acc, llvm::Value *Ptr)
static const Expr * isSimpleArrayDecayOperand(const Expr *E)
isSimpleArrayDecayOperand - If the specified expr is a simple decay from an array to pointer,...
static bool getFieldOffsetInBits(CodeGenFunction &CGF, const RecordDecl *RD, const FieldDecl *Field, int64_t &Offset)
The offset of a field from the beginning of the record.
static bool hasBPFPreserveStaticOffset(const RecordDecl *D)
ConstantEmissionKind
Can we constant-emit a load of a reference to a variable of the given type?
static Address emitRawAddrOfFieldStorage(CodeGenFunction &CGF, Address base, const FieldDecl *field, bool IsInBounds)
Drill down to the storage of a field without walking into reference types, and without respect for po...
static bool isConstantEmittableObjectType(QualType type)
Given an object of the given canonical type, can we safely copy a value out of it based on its initia...
static LValue EmitCapturedFieldLValue(CodeGenFunction &CGF, const FieldDecl *FD, llvm::Value *ThisValue)
static std::optional< LValue > EmitLValueOrThrowExpression(CodeGenFunction &CGF, const Expr *Operand)
Emit the operand of a glvalue conditional operator.
static CheckRecoverableKind getRecoverableKind(SanitizerKind::SanitizerOrdinal Ordinal)
static llvm::Value * emitArraySubscriptGEP(CodeGenFunction &CGF, llvm::Type *elemType, llvm::Value *ptr, ArrayRef< llvm::Value * > indices, bool inbounds, bool signedIndices, SourceLocation loc, const llvm::Twine &name="arrayidx")
SmallVector< llvm::Value *, 8 > RecIndicesTy
static GlobalDecl getGlobalDeclForDirectCall(const FunctionDecl *FD)
static LValue EmitFunctionDeclLValue(CodeGenFunction &CGF, const Expr *E, GlobalDecl GD)
static RawAddress MaybeConvertMatrixAddress(RawAddress Addr, CodeGenFunction &CGF, bool IsVector=true)
static LValueOrRValue emitPseudoObjectExpr(CodeGenFunction &CGF, const PseudoObjectExpr *E, bool forLValue, AggValueSlot slot)
static Address wrapWithBPFPreserveStaticOffset(CodeGenFunction &CGF, Address &Addr)
static llvm::StringRef GetUBSanTrapForHandler(SanitizerHandler ID)
static llvm::Value * getArrayIndexingBound(CodeGenFunction &CGF, const Expr *Base, QualType &IndexedType, LangOptions::StrictFlexArraysLevelKind StrictFlexArraysLevel)
If Base is known to point to the start of an array, return the length of that array.
static RValue EmitLoadOfMatrixLValue(LValue LV, SourceLocation Loc, CodeGenFunction &CGF)
static ConstantEmissionKind checkVarTypeForConstantEmission(QualType type)
static Address emitAddrOfFieldStorage(CodeGenFunction &CGF, Address base, const FieldDecl *field, bool IsInBounds)
Drill down to the storage of a field without walking into reference types, wrapping the address in an...
static std::optional< int64_t > getOffsetDifferenceInBits(CodeGenFunction &CGF, const FieldDecl *FD1, const FieldDecl *FD2)
Returns the relative offset difference between FD1 and FD2.
static CGCallee EmitDirectCallee(CodeGenFunction &CGF, GlobalDecl GD)
static LValue EmitThreadPrivateVarDeclLValue(CodeGenFunction &CGF, const VarDecl *VD, QualType T, Address Addr, llvm::Type *RealVarTy, SourceLocation Loc)
static bool getGEPIndicesToField(CodeGenFunction &CGF, const RecordDecl *RD, const FieldDecl *Field, RecIndicesTy &Indices)
static bool OnlyHasInlineBuiltinDeclaration(const FunctionDecl *FD)
static LValue EmitGlobalVarDeclLValue(CodeGenFunction &CGF, const Expr *E, const VarDecl *VD)
static bool hasAnyVptr(const QualType Type, const ASTContext &Context)
static bool IsPreserveAIArrayBase(CodeGenFunction &CGF, const Expr *ArrayBase)
Given an array base, check whether its member access belongs to a record with preserve_access_index a...
static Address emitDeclTargetVarDeclLValue(CodeGenFunction &CGF, const VarDecl *VD, QualType T)
VariableTypeDescriptorKind
@ TK_Float
A floating-point type.
@ TK_Unknown
Any other type. The value representation is unspecified.
@ TK_Integer
An integer type.
@ TK_BitInt
An _BitInt(N) type.
static void EmitStoreOfMatrixScalar(llvm::Value *value, LValue lvalue, bool isInit, CodeGenFunction &CGF)
static Address EmitPointerWithAlignment(const Expr *E, LValueBaseInfo *BaseInfo, TBAAAccessInfo *TBAAInfo, KnownNonNull_t IsKnownNonNull, CodeGenFunction &CGF)
static Address emitPreserveStructAccess(CodeGenFunction &CGF, LValue base, Address addr, const FieldDecl *field)
const SanitizerHandlerInfo SanitizerHandlers[]
static void emitCheckHandlerCall(CodeGenFunction &CGF, llvm::FunctionType *FnType, ArrayRef< llvm::Value * > FnArgs, SanitizerHandler CheckHandler, CheckRecoverableKind RecoverKind, bool IsFatal, llvm::BasicBlock *ContBB, bool NoMerge)
static Address emitOMPArraySectionBase(CodeGenFunction &CGF, const Expr *Base, LValueBaseInfo &BaseInfo, TBAAAccessInfo &TBAAInfo, QualType BaseTy, QualType ElTy, bool IsLowerBound)
static mlir::Value emitPointerArithmetic(CIRGenFunction &cgf, const BinOpInfo &op, bool isSubtraction)
Emit pointer + index arithmetic.
static Address createReferenceTemporary(CIRGenFunction &cgf, const MaterializeTemporaryExpr *m, const Expr *inner)
static bool isAAPCS(const TargetInfo &targetInfo)
Helper method to check if the underlying ABI is AAPCS.
static CharUnits getArrayElementAlign(CharUnits arrayAlign, mlir::Value idx, CharUnits eltSize)
static void pushTemporaryCleanup(CIRGenFunction &cgf, const MaterializeTemporaryExpr *m, const Expr *e, Address referenceTemporary)
static QualType getFixedSizeElementType(const ASTContext &astContext, const VariableArrayType *vla)
static bool canEmitSpuriousReferenceToVariable(CIRGenFunction &cgf, const DeclRefExpr *e, const VarDecl *vd)
Determine whether we can emit a reference to vd from the current context, despite not necessarily hav...
static DeclRefExpr * tryToConvertMemberExprToDeclRefExpr(CIRGenFunction &cgf, const MemberExpr *me)
static Address emitAddrOfZeroSizeField(CIRGenFunction &cgf, Address base, const FieldDecl *field)
Get the address of a zero-sized field within a record.
static unsigned getCharWidth(tok::TokenKind kind, const TargetInfo &Target)
llvm::MachO::Record Record
Defines the clang::Module class, which describes a module in the source code.
static const SanitizerMask AlwaysRecoverable
static const SanitizerMask Unrecoverable
#define LIST_SANITIZER_CHECKS
Defines the SourceManager interface.
static QualType getPointeeType(const MemRegion *R)
a trap message and trap category.
const LValueBase getLValueBase() const
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
SourceManager & getSourceManager()
CharUnits getTypeAlignInChars(QualType T) const
Return the ABI-specified alignment of a (complete) type T, in characters.
uint64_t getFieldOffset(const ValueDecl *FD) const
Get the offset of a FieldDecl or IndirectFieldDecl, in bits.
bool isPFPField(const FieldDecl *Field) const
static CanQualType getCanonicalType(QualType T)
Return the canonical (structural) type corresponding to the specified potentially non-canonical type ...
const ASTRecordLayout & getASTRecordLayout(const RecordDecl *D) const
Get or compute information about the layout of the specified record (struct/union/class) D,...
QualType getPointerType(QualType T) const
Return the uniqued reference to the type for a pointer to the specified type.
Builtin::Context & BuiltinInfo
const LangOptions & getLangOpts() const
QualType getPointerDiffType() const
Return the unique type for "ptrdiff_t" (C99 7.17) defined in <stddef.h>.
llvm::DenseMap< const CXXMethodDecl *, CXXCastPath > LambdaCastPaths
For capturing lambdas with an explicit object parameter whose type is derived from the lambda type,...
CharUnits getDeclAlign(const Decl *D, bool ForAlignof=false) const
Return a conservative estimate of the alignment of the specified decl D.
uint64_t getTypeSize(QualType T) const
Return the size of the specified (complete) type T, in bits.
CharUnits getTypeSizeInChars(QualType T) const
Return the size of the specified (complete) type T, in characters.
const VariableArrayType * getAsVariableArrayType(QualType T) const
QualType getExtVectorType(QualType VectorType, unsigned NumElts) const
Return the unique reference to an extended vector type of the specified element type and size.
CharUnits toCharUnitsFromBits(int64_t BitSize) const
Convert a size in bits to a size in characters.
CanQualType getCanonicalTagType(const TagDecl *TD) const
unsigned getTargetAddressSpace(LangAS AS) const
bool isSentinelNullExpr(const Expr *E)
uint64_t getCharWidth() const
Return the size of the character type, in bits.
ASTRecordLayout - This class contains layout information for one RecordDecl, which is a struct/union/...
uint64_t getFieldOffset(unsigned FieldNo) const
getFieldOffset - Get the offset of the given field index, in bits.
AbstractConditionalOperator - An abstract base class for ConditionalOperator and BinaryConditionalOpe...
Expr * getCond() const
getCond - Return the expression representing the condition for the ?
Expr * getTrueExpr() const
getTrueExpr - Return the subexpression representing the value of the expression if the condition eval...
Expr * getFalseExpr() const
getFalseExpr - Return the subexpression representing the value of the expression if the condition eva...
This class represents BOTH the OpenMP Array Section and OpenACC 'subarray', with a boolean differenti...
Expr * getBase()
Get base of the array section.
Expr * getLength()
Get length of array section.
static QualType getBaseOriginalType(const Expr *Base)
Return original type of the base expression for array section.
SourceLocation getExprLoc() const LLVM_READONLY
Expr * getLowerBound()
Get lower bound of array section.
bool isOpenACCArraySection() const
SourceLocation getColonLocFirst() const
ArraySubscriptExpr - [C99 6.5.2.1] Array Subscripting.
SourceLocation getExprLoc() const LLVM_READONLY
Expr * getLHS()
An array access can be written A[4] or 4[A] (both are equivalent).
Represents an array type, per C99 6.7.5.2 - Array Declarators.
QualType getElementType() const
A builtin binary operation expression such as "x + y" or "x <= y".
SourceLocation getExprLoc() const
static bool isAdditiveOp(Opcode Opc)
A fixed int type of a specified bitwidth.
unsigned getNumBits() const
bool isPredefinedLibFunction(unsigned ID) const
Determines whether this builtin is a predefined libc/libm function, such as "malloc",...
Represents binding an expression to a temporary.
CXXTemporary * getTemporary()
const Expr * getSubExpr() const
Represents a call to a C++ constructor.
Represents a C++ destructor within a class.
Represents a C++ struct/union/class.
bool hasTrivialDestructor() const
Determine whether this class has a trivial destructor (C++ [class.dtor]p3)
bool isStandardLayout() const
Determine whether this class is standard-layout per C++ [class]p7.
unsigned getNumBases() const
Retrieves the number of base classes of this class.
base_class_iterator bases_begin()
bool isDynamicClass() const
bool hasDefinition() const
const CXXRecordDecl * getStandardLayoutBaseWithFields() const
If this is a standard-layout class or union, any and all data members will be declared in the same ty...
A C++ typeid expression (C++ [expr.typeid]), which gets the type_info that corresponds to the supplie...
A Microsoft C++ __uuidof expression, which gets the _GUID that corresponds to the supplied type or ex...
MSGuidDecl * getGuidDecl() const
CallExpr - Represents a function call (C99 6.5.2.2, C++ [expr.call]).
Expr * getArg(unsigned Arg)
getArg - Return the specified argument.
SourceLocation getBeginLoc() const
FunctionDecl * getDirectCallee()
If the callee is a FunctionDecl, return it. Otherwise return null.
bool isCoroElideSafe() const
QualType getCallReturnType(const ASTContext &Ctx) const
getCallReturnType - Get the return type of the call expr.
CastExpr - Base class for type casts, including both implicit casts (ImplicitCastExpr) and explicit c...
path_iterator path_begin()
CastKind getCastKind() const
bool changesVolatileQualification() const
Return.
CharUnits - This is an opaque type for sizes expressed in character units.
CharUnits alignmentAtOffset(CharUnits offset) const
Given that this is a non-zero alignment value, what is the alignment at the given offset?
llvm::MaybeAlign getAsMaybeAlign() const
getAsMaybeAlign - Returns Quantity as a valid llvm::Align or std::nullopt, Beware llvm::MaybeAlign as...
llvm::Align getAsAlign() const
getAsAlign - Returns Quantity as a valid llvm::Align, Beware llvm::Align assumes power of two 8-bit b...
QuantityType getQuantity() const
getQuantity - Get the raw integer representation of this quantity.
static CharUnits One()
One - Construct a CharUnits quantity of one.
CharUnits alignmentOfArrayElement(CharUnits elementSize) const
Given that this is the alignment of the first element of an array, return the minimum alignment of an...
static CharUnits fromQuantity(QuantityType Quantity)
fromQuantity - Construct a CharUnits quantity from a raw integer type.
static CharUnits Zero()
Zero - Construct a CharUnits quantity of zero.
@ None
Trap Messages are omitted.
@ Detailed
Trap Message includes more context (e.g.
@ Strict
In-memory bool values are assumed to be 0 or 1, and any other value is UB.
bool isOptimizedBuild() const
Are we building at -O1 or higher?
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 withPointer(llvm::Value *NewPointer, KnownNonNull_t IsKnownNonNull) const
Return address with different pointer, but same element type and alignment.
Address withElementType(llvm::Type *ElemTy) const
Return address with different element type, but same pointer and alignment.
Address withAlignment(CharUnits NewAlignment) const
Return address with different alignment, but same pointer and element type.
llvm::PointerType * getType() const
Return the type of the pointer value.
static AggValueSlot ignored()
ignored - Returns an aggregate value slot indicating that the aggregate value is being ignored.
Address getAddress() const
void setExternallyDestructed(bool destructed=true)
static AggValueSlot forLValue(const LValue &LV, IsDestructed_t isDestructed, NeedsGCBarriers_t needsGC, IsAliased_t isAliased, Overlap_t mayOverlap, IsZeroed_t isZeroed=IsNotZeroed, IsSanitizerChecked_t isChecked=IsNotSanitizerChecked)
static AggValueSlot forAddr(Address addr, Qualifiers quals, IsDestructed_t isDestructed, NeedsGCBarriers_t needsGC, IsAliased_t isAliased, Overlap_t mayOverlap, IsZeroed_t isZeroed=IsNotZeroed, IsSanitizerChecked_t isChecked=IsNotSanitizerChecked)
forAddr - Make a slot for an aggregate 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 CreateArtificial(CodeGenFunction &CGF)
Apply TemporaryLocation if it is valid.
Address CreateConstInBoundsByteGEP(Address Addr, CharUnits Offset, const llvm::Twine &Name="")
Given a pointer to i8, adjust it by a given constant offset.
Address CreateGEP(CodeGenFunction &CGF, Address Addr, llvm::Value *Index, const llvm::Twine &Name="")
Address CreateConstGEP2_32(Address Addr, unsigned Idx0, unsigned Idx1, const llvm::Twine &Name="")
Address CreateConstArrayGEP(Address Addr, uint64_t Index, const llvm::Twine &Name="")
Given addr = [n x T]* ... produce name = getelementptr inbounds addr, i64 0, i64 index where i64 is a...
Address CreateStructGEP(Address Addr, unsigned Index, const llvm::Twine &Name="")
llvm::LoadInst * CreateLoad(Address Addr, const llvm::Twine &Name="")
Address CreateConstByteGEP(Address Addr, CharUnits Offset, const llvm::Twine &Name="")
Address CreatePreserveStructAccessIndex(Address Addr, unsigned Index, unsigned FieldIndex, llvm::MDNode *DbgInfo)
Address CreateAddrSpaceCast(Address Addr, llvm::Type *Ty, llvm::Type *ElementTy, const llvm::Twine &Name="")
virtual llvm::Function * getKernelStub(llvm::GlobalValue *Handle)=0
Get kernel stub by kernel handle.
virtual void registerGlobalDtor(CodeGenFunction &CGF, const VarDecl &D, llvm::FunctionCallee Dtor, llvm::Constant *Addr)=0
Emit code to force the execution of a destructor during global teardown.
virtual LValue EmitThreadLocalVarDeclLValue(CodeGenFunction &CGF, const VarDecl *VD, QualType LValType)=0
Emit a reference to a non-local thread_local variable (including triggering the initialization of all...
virtual bool usesThreadWrapperFunction(const VarDecl *VD) const =0
Abstract information about a function or function prototype.
const GlobalDecl getCalleeDecl() const
All available information about a concrete callee.
CGCalleeInfo getAbstractInfo() const
const CXXPseudoDestructorExpr * getPseudoDestructorExpr() const
bool isPseudoDestructor() const
static CGCallee forBuiltin(unsigned builtinID, const FunctionDecl *builtinDecl)
unsigned getBuiltinID() const
static CGCallee forDirect(llvm::Constant *functionPtr, const CGCalleeInfo &abstractInfo=CGCalleeInfo())
const FunctionDecl * getBuiltinDecl() const
static CGCallee forPseudoDestructor(const CXXPseudoDestructorExpr *E)
This class gathers all debug information during compilation and is responsible for emitting to llvm g...
llvm::DIType * getOrCreateStandaloneType(QualType Ty, SourceLocation Loc)
Emit standalone debug info for a type.
llvm::DILocation * CreateTrapFailureMessageFor(llvm::DebugLoc TrapLocation, StringRef Category, StringRef FailureMsg)
Create a debug location from TrapLocation that adds an artificial inline frame where the frame name i...
llvm::DIType * getOrCreateRecordType(QualType Ty, SourceLocation L)
Emit record type's standalone debug info.
CGFunctionInfo - Class to encapsulate the information about a function definition.
RawAddress createBufferMatrixTempAddress(const LValue &LV, SourceLocation Loc, CodeGenFunction &CGF)
virtual Address getAddrOfThreadPrivate(CodeGenFunction &CGF, const VarDecl *VD, Address VDAddr, SourceLocation Loc)
Returns address of the threadprivate variable for the current thread.
virtual ConstantAddress getAddrOfDeclareTargetVar(const VarDecl *VD)
Returns the address of the variable marked as declare target with link clause OR as declare target wi...
bool hasRequiresUnifiedSharedMemory() const
Return whether the unified_shared_memory has been specified.
CGRecordLayout - This class handles struct and union layout info while lowering AST types to LLVM typ...
llvm::StructType * getLLVMType() const
Return the "complete object" LLVM type associated with this record.
const CGBitFieldInfo & getBitFieldInfo(const FieldDecl *FD) const
Return the BitFieldInfo that corresponds to the field FD.
unsigned getLLVMFieldNo(const FieldDecl *FD) const
Return llvm::StructType element number that corresponds to the field FD.
bool containsFieldDecl(const FieldDecl *FD) const
CallArgList - Type for representing both the value and type of arguments in a call.
void addWriteback(LValue srcLV, Address temporary, llvm::Value *toUse, const Expr *writebackExpr=nullptr)
void add(RValue rvalue, QualType type)
The scope of a CXXDefaultInitExpr.
An object to manage conditionally-evaluated expressions.
llvm::BasicBlock * getStartingBlock() const
Returns a block which will be executed prior to each evaluation of the conditional code.
static ConstantEmission forValue(llvm::Constant *C)
static ConstantEmission forReference(llvm::Constant *C)
A non-RAII class containing all the information about a bound opaque value.
static bool shouldBindAsLValue(const Expr *expr)
static OpaqueValueMappingData bind(CodeGenFunction &CGF, const OpaqueValueExpr *ov, const Expr *e)
An RAII object to set (and then clear) a mapping for an OpaqueValueExpr.
static bool shouldBindAsLValue(const Expr *expr)
RAII object to set/unset CodeGenFunction::IsSanitizerScope.
CodeGenFunction - This class organizes the per-function state that is used while generating LLVM code...
LValue EmitMatrixSubscriptExpr(const MatrixSubscriptExpr *E)
LValue EmitCoawaitLValue(const CoawaitExpr *E)
llvm::Value * GetVTablePtr(Address This, llvm::Type *VTableTy, const CXXRecordDecl *VTableClass, VTableAuthMode AuthMode=VTableAuthMode::Authenticate)
GetVTablePtr - Return the Value of the vtable pointer member pointed to by This.
llvm::Value * EmitObjCConsumeObject(QualType T, llvm::Value *Ptr)
Produce the code for a CK_ARCConsumeObject.
void EmitBoundsCheckImpl(const Expr *ArrayExpr, QualType ArrayBaseType, llvm::Value *IndexVal, QualType IndexType, llvm::Value *BoundsVal, QualType BoundsType, bool Accessed)
LValue EmitLoadOfReferenceLValue(LValue RefLVal)
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.
RValue EmitObjCMessageExpr(const ObjCMessageExpr *E, ReturnValueSlot Return=ReturnValueSlot())
llvm::Value * emitBoolVecConversion(llvm::Value *SrcVec, unsigned NumElementsDst, const llvm::Twine &Name="")
void EmitCXXConstructExpr(const CXXConstructExpr *E, AggValueSlot Dest)
LValue EmitCXXConstructLValue(const CXXConstructExpr *E)
llvm::Value * performAddrSpaceCast(llvm::Value *Src, llvm::Type *DestTy)
LValue EmitConditionalOperatorLValue(const AbstractConditionalOperator *E)
std::pair< LValue, llvm::Value * > EmitARCStoreAutoreleasing(const BinaryOperator *e)
ComplexPairTy EmitComplexPrePostIncDec(const UnaryOperator *E, LValue LV, bool isInc, bool isPre)
void SetDivFPAccuracy(llvm::Value *Val)
Set the minimum required accuracy of the given sqrt operation based on CodeGenOpts.
SanitizerSet SanOpts
Sanitizers enabled for this function.
@ UseSkipPath
Skip (false)
LValue EmitInitListLValue(const InitListExpr *E)
bool isUnderlyingBasePointerConstantNull(const Expr *E)
Check whether the underlying base pointer is a constant null.
void EmitARCInitWeak(Address addr, llvm::Value *value)
i8* @objc_initWeak(i8** addr, i8* value) Returns value.
LValue EmitArraySubscriptExpr(const ArraySubscriptExpr *E, bool Accessed=false)
Address LoadCXXThisAddress()
static bool ContainsLabel(const Stmt *S, bool IgnoreCaseStmts=false)
ContainsLabel - Return true if the statement contains a label in it.
LValue EmitObjCMessageExprLValue(const ObjCMessageExpr *E)
llvm::Value * GetCountedByFieldExprGEP(const Expr *Base, const FieldDecl *FD, const FieldDecl *CountDecl)
void EmitComplexExprIntoLValue(const Expr *E, LValue dest, bool isInit)
EmitComplexExprIntoLValue - Emit the given expression of complex type and place its result into the s...
const CastExpr * CurCast
If a cast expression is being visited, this holds the current cast's expression.
llvm::Type * ConvertType(QualType T)
Address EmitCXXUuidofExpr(const CXXUuidofExpr *E)
void EmitSanitizerStatReport(llvm::SanitizerStatKind SSK)
static Destroyer destroyARCWeak
CGCapturedStmtInfo * CapturedStmtInfo
RValue EmitCXXPseudoDestructorExpr(const CXXPseudoDestructorExpr *E)
ComplexPairTy EmitLoadOfComplex(LValue src, SourceLocation loc)
EmitLoadOfComplex - Load a complex number from the specified l-value.
bool inSuspendBlock() const
llvm::Value * EmitARCRetain(QualType type, llvm::Value *value)
Produce the code to do a retain.
llvm::Value * EmitPointerAuthQualify(PointerAuthQualifier Qualifier, llvm::Value *Pointer, QualType ValueType, Address StorageAddress, bool IsKnownNonNull)
CleanupKind getARCCleanupKind()
Retrieves the default cleanup kind for an ARC cleanup.
void EmitAggFinalDestCopy(QualType Type, AggValueSlot Dest, const LValue &Src, ExprValueKind SrcKind)
EmitAggFinalDestCopy - Emit copy of the specified aggregate into destination address.
Address GetAddressOfBaseClass(Address Value, const CXXRecordDecl *Derived, CastExpr::path_const_iterator PathBegin, CastExpr::path_const_iterator PathEnd, bool NullCheckValue, SourceLocation Loc)
GetAddressOfBaseClass - This function will add the necessary delta to the load of 'this' and returns ...
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 ...
void EmitStoreThroughExtVectorComponentLValue(RValue Src, LValue Dst)
RValue EmitBlockCallExpr(const CallExpr *E, ReturnValueSlot ReturnValue, llvm::CallBase **CallOrInvoke)
LValue EmitObjCEncodeExprLValue(const ObjCEncodeExpr *E)
void EmitCXXThrowExpr(const CXXThrowExpr *E, bool KeepInsertionPoint=true)
LValue EmitCompoundLiteralLValue(const CompoundLiteralExpr *E)
RValue convertTempToRValue(Address addr, QualType type, SourceLocation Loc)
Given the address of a temporary variable, produce an r-value of its type.
LValue EmitObjCIsaExpr(const ObjCIsaExpr *E)
void EmitStoreThroughBitfieldLValue(RValue Src, LValue Dst, llvm::Value **Result=nullptr)
EmitStoreThroughBitfieldLValue - Store Src into Dst with same constraints as EmitStoreThroughLValue.
llvm::Constant * EmitCheckSourceLocation(SourceLocation Loc)
Emit a description of a source location in a format suitable for passing to a runtime sanitizer handl...
LValue EmitCXXUuidofLValue(const CXXUuidofExpr *E)
llvm::Value * EmitScalarPrePostIncDec(const UnaryOperator *E, LValue LV, bool isInc, bool isPre)
void SetSqrtFPAccuracy(llvm::Value *Val)
Set the minimum required accuracy of the given sqrt operation based on CodeGenOpts.
RValue EmitSimpleCallExpr(const CallExpr *E, ReturnValueSlot ReturnValue, llvm::CallBase **CallOrInvoke=nullptr)
Emit a CallExpr without considering whether it might be a subclass.
static bool isNullPointerAllowed(TypeCheckKind TCK)
Determine whether the pointer type check TCK permits null pointers.
RValue EmitPseudoObjectRValue(const PseudoObjectExpr *e, AggValueSlot slot=AggValueSlot::ignored())
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.
unsigned getDebugInfoFIndex(const RecordDecl *Rec, unsigned FieldIndex)
Get the record field index as represented in debug info.
const LangOptions & getLangOpts() const
void EmitCfiCheckFail()
Emit a cross-DSO CFI failure handling function.
RValue EmitReferenceBindingToExpr(const Expr *E)
Emits a reference binding to the passed in expression.
llvm::Value * EmitARCStoreStrong(LValue lvalue, llvm::Value *value, bool resultIgnored)
Store into a strong object.
LValue MakeNaturalAlignAddrLValue(llvm::Value *V, QualType T, KnownNonNull_t IsKnownNonNull=NotKnownNonNull)
LValue EmitPointerToDataMemberBinaryExpr(const BinaryOperator *E)
LValue EmitLValueForIvar(QualType ObjectTy, llvm::Value *Base, const ObjCIvarDecl *Ivar, unsigned CVRQualifiers)
Address GetAddressOfDerivedClass(Address Value, const CXXRecordDecl *Derived, CastExpr::path_const_iterator PathBegin, CastExpr::path_const_iterator PathEnd, bool NullCheckValue)
void EmitIgnoredConditionalOperator(const AbstractConditionalOperator *E)
void EmitCountedByBoundsChecking(const Expr *ArrayExpr, QualType ArrayType, Address ArrayInst, QualType IndexType, llvm::Value *IndexVal, bool Accessed, bool FlexibleArray)
EmitCountedByBoundsChecking - If the array being accessed has a "counted_by" attribute,...
Address EmitFieldAnnotations(const FieldDecl *D, Address V)
Emit field annotations for the given field & value.
void pushDestroy(QualType::DestructionKind dtorKind, Address addr, QualType type)
pushDestroy - Push the standard destructor for the given type as at least a normal cleanup.
void EmitScalarInit(const Expr *init, const ValueDecl *D, LValue lvalue, bool capturedByInit)
void EmitNullabilityCheck(LValue LHS, llvm::Value *RHS, SourceLocation Loc)
Given an assignment *LHS = RHS, emit a test that checks if RHS is nonnull, if LHS is marked _Nonnull.
llvm::Value * EmitPointerAuthUnqualify(PointerAuthQualifier Qualifier, llvm::Value *Pointer, QualType PointerType, Address StorageAddress, bool IsKnownNonNull)
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.
static Destroyer destroyCXXObject
Address EmitLoadOfPointer(Address Ptr, const PointerType *PtrTy, LValueBaseInfo *BaseInfo=nullptr, TBAAAccessInfo *TBAAInfo=nullptr)
Load a pointer with type PtrTy stored at address Ptr.
RValue EmitLoadOfGlobalRegLValue(LValue LV)
Load of global named registers are always calls to intrinsics.
void EmitVTablePtrCheckForCast(QualType T, Address Derived, bool MayBeNull, CFITypeCheckKind TCK, SourceLocation Loc)
Derived is the presumed address of an object of type T after a cast.
TypeCheckKind
Situations in which we might emit a check for the suitability of a pointer or glvalue.
@ TCK_DowncastPointer
Checking the operand of a static_cast to a derived pointer type.
@ TCK_DowncastReference
Checking the operand of a static_cast to a derived reference type.
@ TCK_MemberAccess
Checking the object expression in a non-static data member access.
@ TCK_Store
Checking the destination of a store. Must be suitably sized and aligned.
@ TCK_UpcastToVirtualBase
Checking the operand of a cast to a virtual base object.
@ TCK_MemberCall
Checking the 'this' pointer for a call to a non-static member function.
@ TCK_DynamicOperation
Checking the operand of a dynamic_cast or a typeid expression.
@ TCK_ReferenceBinding
Checking the bound value in a reference binding.
@ TCK_Upcast
Checking the operand of a cast to a base object.
LValue EmitBinaryOperatorLValue(const BinaryOperator *E)
bool InNoMergeAttributedStmt
True if the current statement has nomerge attribute.
LValue EmitComplexCompoundAssignmentLValue(const CompoundAssignOperator *E)
const Decl * CurCodeDecl
CurCodeDecl - This is the inner-most code context, which includes blocks.
Destroyer * getDestroyer(QualType::DestructionKind destructionKind)
llvm::AssertingVH< llvm::Instruction > AllocaInsertPt
AllocaInsertPoint - This is an instruction in the entry block before which we prefer to insert alloca...
void maybeAttachRangeForLoad(llvm::LoadInst *Load, QualType Ty, SourceLocation Loc)
void EmitBitfieldConversionCheck(llvm::Value *Src, QualType SrcType, llvm::Value *Dst, QualType DstType, const CGBitFieldInfo &Info, SourceLocation Loc)
Emit a check that an [implicit] conversion of a bitfield.
LValue EmitPseudoObjectLValue(const PseudoObjectExpr *e)
llvm::Constant * EmitCheckTypeDescriptor(QualType T)
Emit a description of a type in a format suitable for passing to a runtime sanitizer handler.
LValue EmitOpaqueValueLValue(const OpaqueValueExpr *e)
llvm::Value * LoadPassedObjectSize(const Expr *E, QualType EltTy)
If E references a parameter with pass_object_size info or a constant array size modifier,...
@ ForceLeftToRight
! Language semantics require left-to-right evaluation.
@ Default
! No language constraints on evaluation order.
@ ForceRightToLeft
! Language semantics require right-to-left evaluation.
llvm::Value * EmitIvarOffsetAsPointerDiff(const ObjCInterfaceDecl *Interface, const ObjCIvarDecl *Ivar)
RValue EmitCUDAKernelCallExpr(const CUDAKernelCallExpr *E, ReturnValueSlot ReturnValue, llvm::CallBase **CallOrInvoke)
RValue EmitLoadOfAnyValue(LValue V, AggValueSlot Slot=AggValueSlot::ignored(), SourceLocation Loc={})
Like EmitLoadOfLValue but also handles complex and aggregate types.
LValue EmitLValueForField(LValue Base, const FieldDecl *Field, bool IsInBounds=true)
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
LValue EmitCompoundAssignmentLValue(const CompoundAssignOperator *E)
bool isInConditionalBranch() const
isInConditionalBranch - Return true if we're currently emitting one branch or the other of a conditio...
Address EmitCXXMemberDataPointerAddress(const Expr *E, Address base, llvm::Value *memberPtr, const MemberPointerType *memberPtrType, bool IsInBounds, LValueBaseInfo *BaseInfo=nullptr, TBAAAccessInfo *TBAAInfo=nullptr)
Emit the address of a field using a member data pointer.
LValue EmitHLSLOutArgExpr(const HLSLOutArgExpr *E, CallArgList &Args, QualType Ty)
static bool isVptrCheckRequired(TypeCheckKind TCK, QualType Ty)
Determine whether the pointer type check TCK requires a vptr check.
CGCallee EmitCallee(const Expr *E)
void EmitIgnoredExpr(const Expr *E)
EmitIgnoredExpr - Emit an expression in a context which ignores the result.
RValue EmitCallExpr(const CallExpr *E, ReturnValueSlot ReturnValue=ReturnValueSlot(), llvm::CallBase **CallOrInvoke=nullptr)
RValue EmitLoadOfLValue(LValue V, SourceLocation Loc)
EmitLoadOfLValue - Given an expression that represents a value lvalue, this method emits the address ...
LValue EmitMatrixSingleSubscriptExpr(const MatrixSingleSubscriptExpr *E)
LValue EmitArraySectionExpr(const ArraySectionExpr *E, bool IsLowerBound=true)
Address GetAddrOfBlockDecl(const VarDecl *var)
llvm::Value * EmitComplexToScalarConversion(ComplexPairTy Src, QualType SrcTy, QualType DstTy, SourceLocation Loc)
Emit a conversion from the specified complex type to the specified destination type,...
void pushCleanupAfterFullExpr(CleanupKind Kind, As... A)
Queue a cleanup to be pushed after finishing the current full-expression, potentially with an active ...
void EmitCfiCheckStub()
Emit a stub for the cross-DSO CFI check function.
RawAddress CreateIRTempWithoutCast(QualType T, const Twine &Name="tmp")
CreateIRTempWithoutCast - Create a temporary IR object of the given type, with appropriate alignment.
void pushFullExprCleanup(CleanupKind kind, As... A)
pushFullExprCleanup - Push a cleanup to be run at the end of the current full-expression.
static Destroyer destroyARCStrongImprecise
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.
LValue EmitAggExprToLValue(const Expr *E)
EmitAggExprToLValue - Emit the computation of the specified expression of aggregate type into a tempo...
void SetFPAccuracy(llvm::Value *Val, float Accuracy)
SetFPAccuracy - Set the minimum required accuracy of the given floating point operation,...
Address mergeAddressesInConditionalExpr(Address LHS, Address RHS, llvm::BasicBlock *LHSBlock, llvm::BasicBlock *RHSBlock, llvm::BasicBlock *MergeBlock, QualType MergedType)
Address emitAddrOfImagComponent(Address complex, QualType complexType)
void EmitBoundsCheck(const Expr *ArrayExpr, const Expr *ArrayExprBase, llvm::Value *Index, QualType IndexType, bool Accessed)
Emit a check that Base points into an array object, which we can access at index Index.
llvm::Value * EvaluateExprAsBool(const Expr *E)
EvaluateExprAsBool - Perform the usual unary conversions on the specified expression and compare the ...
LValue EmitPredefinedLValue(const PredefinedExpr *E)
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...
LValue EmitDeclRefLValue(const DeclRefExpr *E)
LValue EmitStringLiteralLValue(const StringLiteral *E)
AggValueSlot CreateAggTemp(QualType T, const Twine &Name="tmp", RawAddress *Alloca=nullptr)
CreateAggTemp - Create a temporary memory object for the given aggregate type.
RValue getOrCreateOpaqueRValueMapping(const OpaqueValueExpr *e)
Given an opaque value expression, return its RValue mapping if it exists, otherwise create one.
RValue EmitAtomicLoad(LValue LV, SourceLocation SL, AggValueSlot Slot=AggValueSlot::ignored())
CGDebugInfo * getDebugInfo()
llvm::Value * emitScalarConstant(const ConstantEmission &Constant, Expr *E)
llvm::Value * getTypeSize(QualType Ty)
Returns calculated size of the specified type.
bool EmitLifetimeStart(llvm::Value *Addr)
Emit a lifetime.begin marker if some criteria are satisfied.
LValue EmitUnsupportedLValue(const Expr *E, const char *Name)
EmitUnsupportedLValue - Emit a dummy l-value using the type of E and issue an ErrorUnsupported style ...
LValue MakeRawAddrLValue(llvm::Value *V, QualType T, CharUnits Alignment, AlignmentSource Source=AlignmentSource::Type)
Same as MakeAddrLValue above except that the pointer is known to be unsigned.
llvm::MDNode * buildAllocToken(QualType AllocType)
Build metadata used by the AllocToken instrumentation.
RValue EmitCXXMemberCallExpr(const CXXMemberCallExpr *E, ReturnValueSlot ReturnValue, llvm::CallBase **CallOrInvoke=nullptr)
LValue EmitLValueForFieldInitialization(LValue Base, const FieldDecl *Field)
EmitLValueForFieldInitialization - Like EmitLValueForField, except that if the Field is a reference,...
llvm::Value * EmitToMemory(llvm::Value *Value, QualType Ty)
EmitToMemory - Change a scalar value from its value representation to its in-memory representation.
Address emitBlockByrefAddress(Address baseAddr, const VarDecl *V, bool followForward=true)
BuildBlockByrefAddress - Computes the location of the data in a variable which is declared as __block...
llvm::AllocaInst * CreateTempAlloca(llvm::Type *Ty, const Twine &Name="tmp", llvm::Value *ArraySize=nullptr)
CreateTempAlloca - This creates an alloca and inserts it into the entry block if ArraySize is nullptr...
LValue getOrCreateOpaqueLValueMapping(const OpaqueValueExpr *e)
Given an opaque value expression, return its LValue mapping if it exists, otherwise create one.
bool EmitScalarRangeCheck(llvm::Value *Value, QualType Ty, SourceLocation Loc)
Check if the scalar Value is within the valid range for the given type Ty.
ComplexPairTy EmitComplexExpr(const Expr *E, bool IgnoreReal=false, bool IgnoreImag=false)
EmitComplexExpr - Emit the computation of the specified expression of complex type,...
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.
LValue EmitHLSLArrayAssignLValue(const BinaryOperator *E)
RawAddress CreateMemTempWithoutCast(QualType T, const Twine &Name="tmp")
CreateMemTemp - Create a temporary memory object of the given type, with appropriate alignmen without...
LValue EmitVAArgExprLValue(const VAArgExpr *E)
bool IsInPreservedAIRegion
True if CodeGen currently emits code inside presereved access index region.
RValue EmitAnyExprToTemp(const Expr *E)
EmitAnyExprToTemp - Similarly to EmitAnyExpr(), however, the result will always be accessible even if...
VlaSizePair getVLASize(const VariableArrayType *vla)
Returns an LLVM value that corresponds to the size, in non-variably-sized elements,...
LValue EmitStmtExprLValue(const StmtExpr *E)
llvm::Value * EmitARCLoadWeakRetained(Address addr)
i8* @objc_loadWeakRetained(i8** addr)
llvm::CallInst * EmitNounwindRuntimeCall(llvm::FunctionCallee callee, const Twine &name="")
ASTContext & getContext() const
RawAddress CreateTempAllocaWithoutCast(llvm::Type *Ty, CharUnits align, const Twine &Name="tmp", llvm::Value *ArraySize=nullptr)
CreateTempAlloca - This creates a alloca and inserts it into the entry block.
llvm::Value * EmitWithOriginalRHSBitfieldAssignment(const BinaryOperator *E, llvm::Value **Previous, QualType *SrcType)
Retrieve the implicit cast expression of the rhs in a binary operator expression by passing pointers ...
llvm::Value * EmitLoadOfScalar(Address Addr, bool Volatile, QualType Ty, SourceLocation Loc, AlignmentSource Source=AlignmentSource::Type, bool isNontemporal=false)
EmitLoadOfScalar - Load a scalar value from an address, taking care to appropriately convert from the...
void Destroyer(CodeGenFunction &CGF, Address addr, QualType ty)
void EmitStoreOfComplex(ComplexPairTy V, LValue dest, bool isInit)
EmitStoreOfComplex - Store a complex number into the specified l-value.
LValue EmitObjCIvarRefLValue(const ObjCIvarRefExpr *E)
Address EmitAddressOfPFPField(Address RecordPtr, const PFPField &Field)
void EmitStoreThroughLValue(RValue Src, LValue Dst, bool isInit=false)
EmitStoreThroughLValue - Store the specified rvalue into the specified lvalue, where both are guarant...
Address EmitArrayToPointerDecay(const Expr *Array, LValueBaseInfo *BaseInfo=nullptr, TBAAAccessInfo *TBAAInfo=nullptr)
void pushLifetimeExtendedDestroy(CleanupKind kind, Address addr, QualType type, Destroyer *destroyer, bool useEHCleanupForArray)
RValue EmitBuiltinExpr(const GlobalDecl GD, unsigned BuiltinID, const CallExpr *E, ReturnValueSlot ReturnValue)
RValue GetUndefRValue(QualType Ty)
GetUndefRValue - Get an appropriate 'undef' rvalue for the given type.
llvm::Instruction * getPostAllocaInsertPoint()
Return PostAllocaInsertPt.
void EmitAllocToken(llvm::CallBase *CB, QualType AllocType)
Emit and set additional metadata used by the AllocToken instrumentation.
LValue EmitComplexAssignmentLValue(const BinaryOperator *E)
Emit an l-value for an assignment (simple or compound) of complex type.
LValue EmitCastLValue(const CastExpr *E)
EmitCastLValue - Casts are never lvalues unless that cast is to a reference type.
llvm::Value * EmitPointerArithmetic(const BinaryOperator *BO, Expr *pointerOperand, llvm::Value *pointer, Expr *indexOperand, llvm::Value *index, bool isSubtraction)
Emit pointer + index arithmetic.
LValue EmitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E)
LValue EmitLoadOfPointerLValue(Address Ptr, const PointerType *PtrTy)
llvm::Value * EmitCheckValue(llvm::Value *V)
Convert a value into a format suitable for passing to a runtime sanitizer handler.
void EmitAnyExprToMem(const Expr *E, Address Location, Qualifiers Quals, bool IsInitializer)
EmitAnyExprToMem - Emits the code necessary to evaluate an arbitrary expression into the given memory...
RValue EmitAnyExpr(const Expr *E, AggValueSlot aggSlot=AggValueSlot::ignored(), bool ignoreResult=false)
EmitAnyExpr - Emit code to compute the specified expression which can have any type.
LValue EmitExtVectorElementExpr(const ExtVectorElementExpr *E)
llvm::DenseMap< const ValueDecl *, FieldDecl * > LambdaCaptureFields
RValue EmitUnsupportedRValue(const Expr *E, const char *Name)
EmitUnsupportedRValue - Emit a dummy r-value using the type of E and issue an ErrorUnsupported style ...
CleanupKind getCleanupKind(QualType::DestructionKind kind)
llvm::CallInst * EmitRuntimeCall(llvm::FunctionCallee callee, const Twine &name="")
std::pair< LValue, LValue > EmitHLSLOutArgLValues(const HLSLOutArgExpr *E, QualType Ty)
LValue EmitObjCSelectorLValue(const ObjCSelectorExpr *E)
llvm::Type * ConvertTypeForMem(QualType T)
LValue EmitCallExprLValue(const CallExpr *E, llvm::CallBase **CallOrInvoke=nullptr)
RValue EmitLoadOfBitfieldLValue(LValue LV, SourceLocation Loc)
llvm::Value * EmitARCLoadWeak(Address addr)
i8* @objc_loadWeak(i8** addr) Essentially objc_autorelease(objc_loadWeakRetained(addr)).
LValue EmitLValueForLambdaField(const FieldDecl *Field)
void markStmtMaybeUsed(const Stmt *S)
CodeGenTypes & getTypes() const
static TypeEvaluationKind getEvaluationKind(QualType T)
getEvaluationKind - Return the TypeEvaluationKind of QualType T.
llvm::Value * EmitIvarOffset(const ObjCInterfaceDecl *Interface, const ObjCIvarDecl *Ivar)
bool IsSanitizerScope
True if CodeGen currently emits code implementing sanitizer checks.
void FlattenAccessAndTypeLValue(LValue LVal, SmallVectorImpl< LValue > &AccessList)
LValue EmitCoyieldLValue(const CoyieldExpr *E)
void EmitTypeCheck(TypeCheckKind TCK, SourceLocation Loc, LValue LV, QualType Type, SanitizerSet SkippedChecks=SanitizerSet(), llvm::Value *ArraySize=nullptr)
void EmitCfiSlowPathCheck(SanitizerKind::SanitizerOrdinal Ordinal, llvm::Value *Cond, llvm::ConstantInt *TypeId, llvm::Value *Ptr, ArrayRef< llvm::Constant * > StaticArgs)
Emit a slow path cross-DSO CFI check which calls __cfi_slowpath if Cond if false.
llvm::SmallVector< const ParmVarDecl *, 4 > FnArgs
Save Parameter Decl for coroutine.
void EmitCXXTemporary(const CXXTemporary *Temporary, QualType TempType, Address Ptr)
Emits all the code to cause the given temporary to be cleaned up.
llvm::Value * authPointerToPointerCast(llvm::Value *ResultPtr, QualType SourceType, QualType DestType)
LValue EmitUnaryOpLValue(const UnaryOperator *E)
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...
bool LValueIsSuitableForInlineAtomic(LValue Src)
An LValue is a candidate for having its loads and stores be made atomic if we are operating under /vo...
LValue EmitCheckedLValue(const Expr *E, TypeCheckKind TCK)
Same as EmitLValue but additionally we generate checking code to guard against undefined behavior.
RawAddress CreateMemTemp(QualType T, const Twine &Name="tmp", RawAddress *Alloca=nullptr)
CreateMemTemp - Create a temporary memory object of the given type, with appropriate alignmen and cas...
Address EmitLoadOfReference(LValue RefLVal, LValueBaseInfo *PointeeBaseInfo=nullptr, TBAAAccessInfo *PointeeTBAAInfo=nullptr)
RValue EmitRValueForField(LValue LV, const FieldDecl *FD, SourceLocation Loc)
llvm::Value * EmitObjCExtendObjectLifetime(QualType T, llvm::Value *Ptr)
LValue EmitCXXBindTemporaryLValue(const CXXBindTemporaryExpr *E)
llvm::Type * convertTypeForLoadStore(QualType ASTTy, llvm::Type *LLVMTy=nullptr)
bool sanitizePerformTypeCheck() const
Whether any type-checking sanitizers are enabled.
Address EmitExtVectorElementLValue(LValue V)
Generates lvalue for partial ext_vector access.
llvm::Value * EmitCheckedInBoundsGEP(llvm::Type *ElemTy, llvm::Value *Ptr, ArrayRef< llvm::Value * > IdxList, bool SignedIndices, bool IsSubtraction, SourceLocation Loc, const Twine &Name="")
Same as IRBuilder::CreateInBoundsGEP, but additionally emits a check to detect undefined behavior whe...
void EmitInitializationToLValue(const Expr *E, LValue LV, AggValueSlot::IsZeroed_t IsZeroed=AggValueSlot::IsNotZeroed)
EmitInitializationToLValue - Emit an initializer to an LValue.
void EmitAggExpr(const Expr *E, AggValueSlot AS)
EmitAggExpr - Emit the computation of the specified expression of aggregate type.
Address emitAddrOfRealComponent(Address complex, QualType complexType)
llvm::Value * EmitScalarExpr(const Expr *E, bool IgnoreResultAssign=false)
EmitScalarExpr - Emit the computation of the specified expression of LLVM scalar type,...
RValue EmitLoadOfExtVectorElementLValue(LValue V)
static bool hasAggregateEvaluationKind(QualType T)
static bool IsWrappedCXXThis(const Expr *E)
Check if E is a C++ "this" pointer wrapped in value-preserving casts.
void EmitCallArgs(CallArgList &Args, PrototypeWrapper Prototype, llvm::iterator_range< CallExpr::const_arg_iterator > ArgRange, AbstractCallee AC=AbstractCallee(), unsigned ParamsToSkip=0, EvaluationOrder Order=EvaluationOrder::Default)
EmitCallArgs - Emit call arguments for a function.
llvm::Value * EmitMatrixIndexExpr(const Expr *E)
llvm::CallInst * EmitTrapCall(llvm::Intrinsic::ID IntrID)
Emit a call to trap or debugtrap and attach function attribute "trap-func-name" if specified.
LValue MakeAddrLValue(Address Addr, QualType T, AlignmentSource Source=AlignmentSource::Type)
void EmitTrapCheck(llvm::Value *Checked, SanitizerHandler CheckHandlerID, bool NoMerge=false, const TrapReason *TR=nullptr)
Create a basic block that will call the trap intrinsic, and emit a conditional branch to it,...
void FinishFunction(SourceLocation EndLoc=SourceLocation())
FinishFunction - Complete IR generation of the current function.
void EmitAtomicStore(RValue rvalue, LValue lvalue, bool isInit)
llvm::Value * EmitFromMemory(llvm::Value *Value, QualType Ty)
EmitFromMemory - Change a scalar value from its memory representation to its value representation.
const CallExpr * MustTailCall
uint64_t getProfileCount(const Stmt *S)
Get the profiler's count for the given statement.
llvm::Value * EmitLoadOfCountedByField(const Expr *Base, const FieldDecl *FD, const FieldDecl *CountDecl)
Build an expression accessing the "counted_by" field.
Address GetAddrOfLocalVar(const VarDecl *VD)
GetAddrOfLocalVar - Return the address of a local variable.
void EmitUnreachable(SourceLocation Loc)
Emit a reached-unreachable diagnostic if Loc is valid and runtime checking is enabled.
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.
LValue EmitCXXTypeidLValue(const CXXTypeidExpr *E)
llvm::Function * generateDestroyHelper(Address addr, QualType type, Destroyer *destroyer, bool useEHCleanupForArray, const VarDecl *VD)
generateDestroyHelper - Generates a helper function which, when invoked, destroys the given object.
LValue EmitMemberExpr(const MemberExpr *E)
std::pair< llvm::Value *, llvm::Value * > ComplexPairTy
Address ReturnValue
ReturnValue - The temporary alloca to hold the return value.
ConstantEmission tryEmitAsConstant(const DeclRefExpr *RefExpr)
Try to emit a reference to the given value without producing it as an l-value.
LValue EmitLValue(const Expr *E, KnownNonNull_t IsKnownNonNull=NotKnownNonNull)
EmitLValue - Emit code to compute a designator that specifies the location of the expression.
void EmitStoreThroughGlobalRegLValue(RValue Src, LValue Dst)
Store of global named registers are always calls to intrinsics.
bool isOpaqueValueEmitted(const OpaqueValueExpr *E)
isOpaqueValueEmitted - Return true if the opaque value expression has already been emitted.
std::pair< llvm::Value *, CGPointerAuthInfo > EmitOrigPointerRValue(const Expr *E)
Retrieve a pointer rvalue and its ptrauth info.
llvm::Value * EmitARCStoreWeak(Address addr, llvm::Value *value, bool ignored)
i8* @objc_storeWeak(i8** addr, i8* value) Returns value.
void EnsureInsertPoint()
EnsureInsertPoint - Ensure that an insertion point is defined so that emitted IR has a place to go.
llvm::LLVMContext & getLLVMContext()
RValue EmitCXXOperatorMemberCallExpr(const CXXOperatorCallExpr *E, const CXXMethodDecl *MD, ReturnValueSlot ReturnValue, llvm::CallBase **CallOrInvoke)
static Destroyer destroyARCStrongPrecise
LValue EmitMatrixElementExpr(const MatrixElementExpr *E)
void incrementProfileCounter(const Stmt *S, llvm::Value *StepV=nullptr)
Increment the profiler's counter for the given statement by StepV.
static unsigned getAccessedFieldNo(unsigned Idx, const llvm::Constant *Elts)
getAccessedFieldNo - Given an encoded value and a result number, return the input field number being ...
llvm::Value * EmitScalarConversion(llvm::Value *Src, QualType SrcTy, QualType DstTy, SourceLocation Loc)
Emit a conversion from the specified type to the specified destination type, both of which are LLVM s...
void EmitVariablyModifiedType(QualType Ty)
EmitVLASize - Capture all the sizes for the VLA expressions in the given variably-modified type and s...
static bool ShouldNullCheckClassCastValue(const CastExpr *Cast)
llvm::Value * EmitNonNullRValueCheck(RValue RV, QualType T)
Create a check that a scalar RValue is non-null.
void EmitStoreOfScalar(llvm::Value *Value, Address Addr, bool Volatile, QualType Ty, AlignmentSource Source=AlignmentSource::Type, bool isInit=false, bool isNontemporal=false)
EmitStoreOfScalar - Store a scalar value to an address, taking care to appropriately convert from the...
llvm::Value * EmitDynamicCast(Address V, const CXXDynamicCastExpr *DCE)
void EmitBlock(llvm::BasicBlock *BB, bool IsFinished=false)
EmitBlock - Emit the given block.
LValue MakeNaturalAlignRawAddrLValue(llvm::Value *V, QualType T)
llvm::Value * EmitCXXTypeidExpr(const CXXTypeidExpr *E)
This class organizes the cross-function state that is used while generating LLVM code.
void EmitExplicitCastExprType(const ExplicitCastExpr *E, CodeGenFunction *CGF=nullptr)
Emit type info if type of an expression is a variably modified type.
CGHLSLRuntime & getHLSLRuntime()
Return a reference to the configured HLSL runtime.
llvm::Module & getModule() const
llvm::FunctionCallee CreateRuntimeFunction(llvm::FunctionType *Ty, StringRef Name, llvm::AttributeList ExtraAttrs=llvm::AttributeList(), bool Local=false, bool AssumeConvergent=false)
Create or return a runtime function declaration with the specified type and name.
CGDebugInfo * getModuleDebugInfo()
llvm::Constant * performAddrSpaceCast(llvm::Constant *Src, llvm::Type *DestTy)
llvm::Constant * getRawFunctionPointer(GlobalDecl GD, llvm::Type *Ty=nullptr)
Return a function pointer for a reference to the given function.
llvm::FunctionCallee getAddrAndTypeOfCXXStructor(GlobalDecl GD, const CGFunctionInfo *FnInfo=nullptr, llvm::FunctionType *FnType=nullptr, bool DontDefer=false, ForDefinition_t IsForDefinition=NotForDefinition)
llvm::Constant * GetAddrOfFunction(GlobalDecl GD, llvm::Type *Ty=nullptr, bool ForVTable=false, bool DontDefer=false, ForDefinition_t IsForDefinition=NotForDefinition)
Return the address of the given function.
llvm::Constant * getFunctionPointer(GlobalDecl GD, llvm::Type *Ty=nullptr)
Return the ABI-correct function pointer value for a reference to the given function.
const LangOptions & getLangOpts() const
CGCUDARuntime & getCUDARuntime()
Return a reference to the configured CUDA runtime.
CharUnits getNaturalTypeAlignment(QualType T, LValueBaseInfo *BaseInfo=nullptr, TBAAAccessInfo *TBAAInfo=nullptr, bool forPointeeType=false)
CodeGenTypes & getTypes()
CGPointerAuthInfo getPointerAuthInfoForPointeeType(QualType type)
llvm::GlobalValue::LinkageTypes getLLVMLinkageVarDefinition(const VarDecl *VD)
Returns LLVM linkage for a declarator.
CGCXXABI & getCXXABI() const
ConstantAddress GetWeakRefReference(const ValueDecl *VD)
Get a reference to the target of VD.
CGOpenMPRuntime & getOpenMPRuntime()
Return a reference to the configured OpenMP runtime.
TBAAAccessInfo getTBAAAccessInfo(QualType AccessType)
getTBAAAccessInfo - Get TBAA information that describes an access to an object of the given type.
ASTContext & getContext() const
TBAAAccessInfo mergeTBAAInfoForCast(TBAAAccessInfo SourceInfo, TBAAAccessInfo TargetInfo)
mergeTBAAInfoForCast - Get merged TBAA information for the purposes of type casts.
llvm::Constant * GetAddrOfGlobalVar(const VarDecl *D, llvm::Type *Ty=nullptr, ForDefinition_t IsForDefinition=NotForDefinition)
Return the llvm::Constant for the address of the given global variable.
const CodeGenOptions & getCodeGenOpts() const
StringRef getMangledName(GlobalDecl GD)
CharUnits getNaturalPointeeTypeAlignment(QualType T, LValueBaseInfo *BaseInfo=nullptr, TBAAAccessInfo *TBAAInfo=nullptr)
llvm::LLVMContext & getLLVMContext()
llvm::Function * getIntrinsic(unsigned IID, ArrayRef< llvm::Type * > Tys={})
ConstantAddress GetAddrOfGlobalTemporary(const MaterializeTemporaryExpr *E, const Expr *Inner)
Returns a pointer to a global variable representing a temporary with static or thread storage duratio...
LangAS GetGlobalConstantAddressSpace() const
Return the AST address space of constant literal, which is used to emit the constant literal as globa...
const CGRecordLayout & getCGRecordLayout(const RecordDecl *)
getCGRecordLayout - Return record layout info for the given record decl.
llvm::Type * ConvertTypeForMem(QualType T)
ConvertTypeForMem - Convert type T into a llvm::Type.
A specialization of Address that requires the address to be an LLVM Constant.
llvm::Constant * getPointer() const
llvm::Constant * emitAbstract(const Expr *E, QualType T)
Emit the result of the given expression as an abstract constant, asserting that it succeeded.
llvm::Constant * tryEmitConstantExpr(const ConstantExpr *CE)
FunctionArgList - Type for representing both the decl and type of parameters to a function.
AlignmentSource getAlignmentSource() const
LValue - This represents an lvalue references.
llvm::Value * getMatrixRowIdx() const
static LValue MakeMatrixRow(Address Addr, llvm::Value *RowIdx, QualType MatrixTy, LValueBaseInfo BaseInfo, TBAAAccessInfo TBAAInfo)
Expr * getBaseIvarExp() const
llvm::Constant * getExtVectorElts() const
static LValue MakeGlobalReg(llvm::Value *V, CharUnits alignment, QualType type)
llvm::Constant * getMatrixRowElts() const
bool isObjCStrong() const
bool isMatrixRowSwizzle() const
bool isGlobalObjCRef() const
bool isVolatileQualified() const
RValue asAggregateRValue() const
llvm::Value * getPointer(CodeGenFunction &CGF) const
llvm::Value * getMatrixIdx() const
llvm::Value * getGlobalReg() const
static LValue MakeAddr(Address Addr, QualType type, ASTContext &Context, LValueBaseInfo BaseInfo, TBAAAccessInfo TBAAInfo)
const Qualifiers & getQuals() const
static LValue MakeExtVectorElt(Address Addr, llvm::Constant *Elts, QualType type, LValueBaseInfo BaseInfo, TBAAAccessInfo TBAAInfo)
Address getAddress() const
unsigned getVRQualifiers() const
bool isExtVectorElt() const
llvm::Value * getVectorIdx() const
void setNontemporal(bool Value)
LValueBaseInfo getBaseInfo() const
void setARCPreciseLifetime(ARCPreciseLifetime_t value)
const CGBitFieldInfo & getBitFieldInfo() const
bool isThreadLocalRef() const
KnownNonNull_t isKnownNonNull() const
TBAAAccessInfo getTBAAInfo() const
void setNonGC(bool Value)
static LValue MakeMatrixRowSwizzle(Address MatAddr, llvm::Value *RowIdx, llvm::Constant *Cols, QualType MatrixTy, LValueBaseInfo BaseInfo, TBAAAccessInfo TBAAInfo)
Address getVectorAddress() const
bool isNontemporal() const
static LValue MakeBitfield(Address Addr, const CGBitFieldInfo &Info, QualType type, LValueBaseInfo BaseInfo, TBAAAccessInfo TBAAInfo)
Create a new object to represent a bit-field access.
static LValue MakeVectorElt(Address vecAddress, llvm::Value *Idx, QualType type, LValueBaseInfo BaseInfo, TBAAAccessInfo TBAAInfo)
void setAddress(Address address)
Address getExtVectorAddress() const
static LValue MakeMatrixElt(Address matAddress, llvm::Value *Idx, QualType type, LValueBaseInfo BaseInfo, TBAAAccessInfo TBAAInfo)
Address getMatrixAddress() const
Address getBitFieldAddress() const
RValue - This trivial value class is used to represent the result of an expression that is evaluated.
static RValue get(llvm::Value *V)
static RValue getAggregate(Address addr, bool isVolatile=false)
Convert an Address to an RValue.
static RValue getComplex(llvm::Value *V1, llvm::Value *V2)
Address getAggregateAddress() const
getAggregateAddr() - Return the Value* of the address of the aggregate.
llvm::Value * getScalarVal() const
getScalarVal() - Return the Value* of this scalar value.
An abstract representation of an aligned address.
CharUnits getAlignment() const
Return the alignment of this pointer.
llvm::Type * getElementType() const
Return the type of the values stored in this address.
llvm::Value * getPointer() const
unsigned getAddressSpace() const
Return the address space that this address resides in.
ReturnValueSlot - Contains the address where the return value of a function can be stored,...
StringRef getCategory() const
StringRef getMessage() const
Complex values, per C99 6.2.5p11.
QualType getElementType() const
CompoundLiteralExpr - [C99 6.5.2.5].
const Expr * getInitializer() const
ConstantExpr - An expression that occurs in a constant context and optionally the result of evaluatin...
Represents a concrete matrix type with constant number of rows and columns.
unsigned getNumColumns() const
Returns the number of columns in the matrix.
unsigned getNumRows() const
Returns the number of rows in the matrix.
DeclContext * getLexicalParent()
getLexicalParent - Returns the containing lexical DeclContext.
RecordDecl * getOuterLexicalRecordContext()
Retrieve the outermost lexically enclosing record context.
A reference to a declared variable, function, enum, etc.
bool refersToEnclosingVariableOrCapture() const
Does this DeclRefExpr refer to an enclosing local or a captured variable?
static DeclRefExpr * Create(const ASTContext &Context, NestedNameSpecifierLoc QualifierLoc, SourceLocation TemplateKWLoc, ValueDecl *D, bool RefersToEnclosingVariableOrCapture, SourceLocation NameLoc, QualType T, ExprValueKind VK, NamedDecl *FoundD=nullptr, const TemplateArgumentListInfo *TemplateArgs=nullptr, NonOdrUseReason NOUR=NOUR_None)
NonOdrUseReason isNonOdrUse() const
Is this expression a non-odr-use reference, and if so, why?
SourceLocation getLocation() const
SourceLocation getLocation() const
bool isUsed(bool CheckUsedAttr=true) const
Whether any (re-)declaration of the entity was used, meaning that a definition is required.
DeclContext * getDeclContext()
const Expr * getBase() const
ExplicitCastExpr - An explicit cast written in the source code.
This represents one expression.
const Expr * skipRValueSubobjectAdjustments(SmallVectorImpl< const Expr * > &CommaLHS, SmallVectorImpl< SubobjectAdjustment > &Adjustments) const
Walk outwards from an expression we want to bind a reference to and find the expression whose lifetim...
Expr * IgnoreParenNoopCasts(const ASTContext &Ctx) LLVM_READONLY
Skip past any parentheses and casts which do not change the value (including ptr->int casts of the sa...
ExprValueKind getValueKind() const
getValueKind - The value kind that this expression produces.
Expr * IgnoreParenImpCasts() LLVM_READONLY
Skip past any parentheses and implicit casts which might surround this expression until reaching a fi...
Expr * IgnoreParens() LLVM_READONLY
Skip past any parentheses which might surround this expression until reaching a fixed point.
bool EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx, bool InConstantContext=false) const
EvaluateAsLValue - Evaluate an expression to see if we can fold it to an lvalue with link time known ...
bool isLValue() const
isLValue - True if this expression is an "l-value" according to the rules of the current language.
bool EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx, bool InConstantContext=false) const
EvaluateAsRValue - Return true if this is a constant which we can fold to an rvalue using any crazy t...
Decl * getReferencedDeclOfCallee()
bool HasSideEffects(const ASTContext &Ctx, bool IncludePossibleEffects=true) const
HasSideEffects - This routine returns true for all those expressions which have any effect other than...
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...
bool refersToBitField() const
Returns true if this expression is a gl-value that potentially refers to a bit-field.
bool isOBJCGCCandidate(ASTContext &Ctx) const
isOBJCGCCandidate - Return true if this expression may be used in a read/ write barrier.
ExtVectorElementExpr - This represents access to specific elements of a vector, and may occur on the ...
bool isArrow() const
isArrow - Return true if the base expression is a pointer to vector, return false if the base express...
void getEncodedElementAccess(SmallVectorImpl< uint32_t > &Elts) const
getEncodedElementAccess - Encode the elements accessed into an llvm aggregate Constant of ConstantInt...
ExtVectorType - Extended vector type.
Represents a member of a struct/union/class.
bool isBitField() const
Determines whether this field is a bitfield.
unsigned getFieldIndex() const
Returns the index of this field within its record, as appropriate for passing to ASTRecordLayout::get...
const RecordDecl * getParent() const
Returns the parent of this field declaration, which is the struct in which this field is defined.
const FieldDecl * findCountedByField() const
Find the FieldDecl specified in a FAM's "counted_by" attribute.
const Expr * getSubExpr() const
Represents a function declaration or definition.
unsigned getBuiltinID(bool ConsiderWrapperFunctions=false) const
Returns a value indicating whether this function corresponds to a builtin function.
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.
FunctionType - C99 6.7.5.3 - Function Declarators.
GlobalDecl - represents a global declaration.
const Decl * getDecl() const
This class represents temporary values used to represent inout and out arguments in HLSL.
const OpaqueValueExpr * getCastedTemporary() const
const OpaqueValueExpr * getOpaqueArgLValue() const
bool isInOut() const
returns true if the parameter is inout and false if the parameter is out.
const Expr * getWritebackCast() const
const Expr * getArgLValue() const
Return the l-value expression that was written as the argument in source.
static ImplicitParamDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation IdLoc, const IdentifierInfo *Id, QualType T, ImplicitParamKind ParamKind)
Create implicit parameter.
Describes an C or C++ initializer list.
bool isTransparent() const
Is this a transparent initializer list (that is, an InitListExpr that is purely syntactic,...
const Expr * getInit(unsigned Init) const
StrictFlexArraysLevelKind
Represents a prvalue temporary that is written into memory so that a reference can bind to it.
StorageDuration getStorageDuration() const
Retrieve the storage duration for the materialized temporary.
Expr * getSubExpr() const
Retrieve the temporary-generating subexpression whose value will be materialized into a glvalue.
ValueDecl * getExtendingDecl()
Get the declaration which triggered the lifetime-extension of this temporary, if any.
void getEncodedElementAccess(SmallVectorImpl< uint32_t > &Elts) const
getEncodedElementAccess - Encode the elements accessed into an llvm aggregate Constant of ConstantInt...
MatrixSingleSubscriptExpr - Matrix single subscript expression for the MatrixType extension when you ...
SourceLocation getExprLoc() const LLVM_READONLY
MatrixSubscriptExpr - Matrix subscript expression for the MatrixType extension.
bool isIncomplete() const
QualType getElementType() const
Returns type of the elements being stored in the matrix.
MemberExpr - [C99 6.5.2.3] Structure and Union Members.
ValueDecl * getMemberDecl() const
Retrieve the member declaration to which this expression refers.
NonOdrUseReason isNonOdrUse() const
Is this expression a non-odr-use reference, and if so, why?
SourceLocation getExprLoc() const LLVM_READONLY
A pointer to member type per C++ 8.3.3 - Pointers to members.
bool isObjCBOOLType(QualType T) const
Returns true if.
This represents a decl that may have a name.
StringRef getName() const
Get the name of identifier for this declaration as a StringRef.
A C++ nested-name-specifier augmented with source location information.
ObjCEncodeExpr, used for @encode in Objective-C.
Represents an ObjC class declaration.
ObjCIvarDecl - Represents an ObjC instance variable.
ObjCIvarRefExpr - A reference to an ObjC instance variable.
const Expr * getBase() const
An expression that sends a message to the given Objective-C object or class.
const ObjCMethodDecl * getMethodDecl() const
QualType getReturnType() const
ObjCSelectorExpr used for @selector in Objective-C.
Selector getSelector() const
OpaqueValueExpr - An expression referring to an opaque object of a fixed type and value class.
Expr * getSourceExpr() const
The source expression of an opaque value expression is the expression which originally generated the ...
const Expr * getSubExpr() const
Pointer-authentication qualifiers.
PointerType - C99 6.7.5.1 - Pointer Declarators.
QualType getPointeeType() const
[C99 6.4.2.2] - A predefined identifier such as func.
StringRef getIdentKindName() const
PredefinedIdentKind getIdentKind() const
StringLiteral * getFunctionName()
Represents an unpacked "presumed" location which can be presented to the user.
unsigned getColumn() const
Return the presumed column number of this location.
const char * getFilename() const
Return the presumed filename of this location.
unsigned getLine() const
Return the presumed line number of this location.
PseudoObjectExpr - An expression which accesses a pseudo-object l-value.
semantics_iterator semantics_end()
semantics_iterator semantics_begin()
const Expr *const * const_semantics_iterator
Expr * getResultExpr()
Return the result-bearing expression, or null if there is none.
A (possibly-)qualified type.
bool isVolatileQualified() const
Determine whether this type is volatile-qualified.
PointerAuthQualifier getPointerAuth() const
QualType withoutLocalFastQualifiers() const
bool isNull() const
Return true if this QualType doesn't point to a type yet.
LangAS getAddressSpace() const
Return the address space of this type.
Qualifiers getQualifiers() const
Retrieve the set of qualifiers applied to this type.
Qualifiers::ObjCLifetime getObjCLifetime() const
Returns lifetime attribute of this type.
QualType getNonReferenceType() const
If Type is a reference type (e.g., const int&), returns the type that the reference refers to ("const...
QualType getUnqualifiedType() const
Retrieve the unqualified variant of the given type, removing as little sugar as possible.
QualType withCVRQualifiers(unsigned CVR) const
DestructionKind isDestructedType() const
Returns a nonzero value if objects of this type require non-trivial work to clean up after.
bool isConstantStorage(const ASTContext &Ctx, bool ExcludeCtor, bool ExcludeDtor)
The collection of all-type qualifiers we support.
unsigned getCVRQualifiers() const
@ OCL_Strong
Assigning into this object requires the old value to be released and the new value to be retained.
@ OCL_ExplicitNone
This object can be modified without requiring retains or releases.
@ OCL_None
There is no lifetime qualification on this type.
@ OCL_Weak
Reading or writing from this object requires a barrier call.
@ OCL_Autoreleasing
Assigning into this object requires a lifetime extension.
void addCVRQualifiers(unsigned mask)
void addQualifiers(Qualifiers Q)
Add the qualifiers from the given set to this set.
void setAddressSpace(LangAS space)
PointerAuthQualifier getPointerAuth() const
ObjCLifetime getObjCLifetime() const
Represents a struct/union/class.
field_range fields() const
RecordDecl * getDefinition() const
Returns the RecordDecl that actually defines this struct/union/class.
bool isAnonymousStructOrUnion() const
Whether this is an anonymous struct or union.
Scope - A scope is a transient data structure that is used while parsing the program.
Encodes a location in the source.
bool isValid() const
Return true if this is a valid SourceLocation object.
PresumedLoc getPresumedLoc(SourceLocation Loc, bool UseLineDirectives=true) const
Returns the "presumed" location of a SourceLocation specifies.
StmtExpr - This is the GNU Statement Expression extension: ({int X=4; X;}).
StmtClass getStmtClass() const
SourceLocation getBeginLoc() const LLVM_READONLY
StringLiteral - This represents a string literal expression, e.g.
Exposes information about the current target.
const llvm::Triple & getTriple() const
Returns the target triple of the primary target.
virtual StringRef getABI() const
Get the ABI currently in use.
The base class of the type hierarchy.
bool isBlockPointerType() const
bool isSignedIntegerOrEnumerationType() const
Determines whether this is an integer type that is signed or an enumeration types whose underlying ty...
bool isPackedVectorBoolType(const ASTContext &ctx) const
bool hasAttr(attr::Kind AK) const
Determine whether this type had the specified attribute applied to it (looking through top-level type...
const ArrayType * castAsArrayTypeUnsafe() const
A variant of castAs<> for array type which silently discards qualifiers from the outermost type.
CXXRecordDecl * getAsCXXRecordDecl() const
Retrieves the CXXRecordDecl that this type refers to, either because the type is a RecordType or beca...
bool isConstantArrayType() const
RecordDecl * getAsRecordDecl() const
Retrieves the RecordDecl this type refers to.
bool isFunctionPointerType() const
CXXRecordDecl * castAsCXXRecordDecl() const
bool isArithmeticType() const
bool isConstantMatrixType() const
bool isPointerType() const
bool isIntegerType() const
isIntegerType() does not include complex integers (a GCC extension).
const T * castAs() const
Member-template castAs<specific type>.
bool isReferenceType() const
bool isEnumeralType() const
bool isVariableArrayType() const
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee.
bool isExtVectorBoolType() const
bool isBitIntType() const
bool isConstantMatrixBoolType() const
bool isAnyComplexType() const
bool hasPointeeToCFIUncheckedCalleeFunctionType() const
const Type * getBaseElementTypeUnsafe() const
Get the base element type of this type, potentially discarding type qualifiers.
bool isAtomicType() const
bool isVariablyModifiedType() const
Whether this type is a variably-modified type (C99 6.7.5).
bool isObjectType() const
Determine whether this type is an object type.
bool isHLSLResourceRecord() const
EnumDecl * getAsEnumDecl() const
Retrieves the EnumDecl this type refers to.
bool isIncompleteType(NamedDecl **Def=nullptr) const
Types are partitioned into 3 broad categories (C99 6.2.5p1): object types, function types,...
bool isFunctionType() const
bool isObjCObjectPointerType() const
bool isVectorType() const
bool isAnyPointerType() const
bool isSubscriptableVectorType() const
const T * getAs() const
Member-template getAs<specific type>'.
const Type * getUnqualifiedDesugaredType() const
Return the specified type with any "sugar" removed from the type, removing any typedefs,...
bool isRecordType() const
bool isHLSLResourceRecordArray() const
bool hasBooleanRepresentation() const
Determine whether this type has a boolean representation – i.e., it is a boolean type,...
bool isCFIUncheckedCalleeFunctionType() const
UnaryOperator - This represents the unary-expression's (except sizeof and alignof),...
SourceLocation getExprLoc() const
Expr * getSubExpr() const
Represents a call to the builtin function __builtin_va_arg.
Represent the declaration of a variable (in which case it is an lvalue) a function (in which case it ...
Represents a variable declaration or definition.
TLSKind getTLSKind() const
VarDecl * getDefinition(ASTContext &)
Get the real (not just tentative) definition for this declaration.
bool hasLocalStorage() const
Returns true if a variable with function scope is a non-static local variable.
@ TLS_Dynamic
TLS with a dynamic initializer.
@ TLS_None
Not a TLS variable.
Represents a C array with a specified size that is not an integer-constant-expression.
Represents a GCC generic vector type.
unsigned getNumElements() const
AlignmentSource
The source of the alignment of an l-value; an expression of confidence in the alignment actually matc...
@ 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 ...
bool isEmptyFieldForLayout(const ASTContext &Context, const FieldDecl *FD)
isEmptyFieldForLayout - Return true iff the field is "empty", that is, either a zero-width bit-field ...
@ EHCleanup
Denotes a cleanup that should run when a scope is exited using exceptional control flow (a throw stat...
static AlignmentSource getFieldAlignmentSource(AlignmentSource Source)
Given that the base address has the given alignment source, what's our confidence in the alignment of...
const internal::VariadicAllOfMatcher< Type > type
Matches Types in the clang AST.
const AstTypeMatcher< ArrayType > arrayType
const AstTypeMatcher< FunctionType > functionType
const internal::VariadicDynCastAllOfMatcher< Stmt, Expr > expr
Matches expressions.
std::optional< llvm::AllocTokenMetadata > getAllocTokenMetadata(QualType T, const ASTContext &Ctx)
Get the information required for construction of an allocation token ID.
QualType inferPossibleType(const CallExpr *E, const ASTContext &Ctx, const CastExpr *CastE)
Infer the possible allocated type from an allocation call expression.
The JSON file list parser is used to communicate input to InstallAPI.
CanQual< Type > CanQualType
Represents a canonical, potentially-qualified type.
bool isa(CodeGen::Address addr)
@ OK_BitField
A bitfield object is a bitfield on a C or C++ record.
@ Asm
Assembly: we accept this only so that we can preprocess it.
StorageDuration
The storage duration for an object (per C++ [basic.stc]).
@ SD_Thread
Thread storage duration.
@ SD_Static
Static storage duration.
@ SD_FullExpression
Full-expression storage duration (for temporaries).
@ SD_Automatic
Automatic storage duration (most local variables).
@ SD_Dynamic
Dynamic storage duration.
@ Result
The result type of a method or function.
@ Dtor_Complete
Complete object dtor.
LangAS
Defines the address space values used by the address space qualifier of QualType.
llvm::cl::opt< bool > ClSanitizeGuardChecks
SmallVector< CXXBaseSpecifier *, 4 > CXXCastPath
A simple array of base specifiers.
U cast(CodeGen::Address addr)
LangAS getLangASFromTargetAS(unsigned TargetAS)
@ Interface
The "__interface" keyword introduces the elaborated-type-specifier.
bool isLambdaMethod(const DeclContext *DC)
@ Other
Other implicit parameter.
@ NOUR_Unevaluated
This name appears in an unevaluated operand.
@ NOUR_Constant
This name appears as a potential result of an lvalue-to-rvalue conversion that is a constant expressi...
__INTPTR_TYPE__ intptr_t
A signed integer type with the property that any valid pointer to void can be converted to this type,...
Structure with information about how a bitfield should be accessed.
CharUnits VolatileStorageOffset
The offset of the bitfield storage from the start of the struct.
unsigned VolatileOffset
The offset within a contiguous run of bitfields that are represented as a single "field" within the L...
unsigned Offset
The offset within a contiguous run of bitfields that are represented as a single "field" within the L...
unsigned VolatileStorageSize
The storage size in bits which should be used when accessing this bitfield.
unsigned Size
The total size of the bit-field, in bits.
unsigned StorageSize
The storage size in bits which should be used when accessing this bitfield.
unsigned IsSigned
Whether the bit-field is signed.
static Address getAddrOfThreadPrivate(CodeGenFunction &CGF, const VarDecl *VD, Address VDAddr, SourceLocation Loc)
Returns address of the threadprivate variable for the current thread.
llvm::PointerType * VoidPtrTy
llvm::IntegerType * Int64Ty
CharUnits getIntAlign() const
llvm::IntegerType * Int8Ty
i8, i16, i32, and i64
unsigned char PointerWidthInBits
The width of a pointer into the generic address space.
llvm::IntegerType * SizeTy
llvm::IntegerType * Int32Ty
llvm::IntegerType * IntPtrTy
llvm::PointerType * Int8PtrTy
CharUnits getPointerAlign() const
llvm::PointerType * DefaultPtrTy
llvm::MDNode * AccessType
AccessType - The final access type.
uint64_t Offset
Offset - The byte offset of the final access within the base one.
static TBAAAccessInfo getMayAliasInfo()
uint64_t Size
Size - The size of access, in bytes.
llvm::MDNode * BaseType
BaseType - The base/leading access type.
bool isIncomplete() const
EvalResult is a struct with detailed info about an evaluated expression.
APValue Val
Val - This is the value the expression can be folded to.
bool HasSideEffects
Whether the evaluated expression has side effects.
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.
An adjustment to be made to the temporary created when emitting a reference binding,...
@ DerivedToBaseAdjustment
@ MemberPointerAdjustment