192class ConstantOffsetExtractor {
201 static Value *Extract(
const Use &Idx, User *&UserTreeRoot,
207 static std::optional<APInt>
Find(
const Use &Idx);
212 std::optional<unsigned> LHS;
213 std::optional<unsigned> RHS;
219 void pushCast(CastInst *Cast) {
221 Casts.push_back(Cast);
224 void popCast() { Casts.pop_back(); }
226 bool hasSignExtension()
const {
237 bool hasExtensions()
const {
258 : IP(InsertionPt), DL(InsertionPt->getDataLayout()), SQ(DL) {}
268 std::optional<APInt>
find(
Value *
V,
const Use *Idx, CastState &Casts);
271 std::optional<APInt> findInOperands(RewriteNode &Node, CastState &Casts);
280 Value *rebuildWithoutConstOffset(
unsigned NodeIndex, CastState &Casts);
282 Value *rebuildWithoutConstOffset() {
284 return rebuildWithoutConstOffset(UserTree.size() - 1, Casts);
290 Value *applyCasts(
Value *
V,
const CastState &Casts);
298 bool canTraceInto(
const CastState &Casts, BinaryOperator *BO,
const Use *Idx);
319 std::optional<APInt> extractDisjointBitsFromXor(RewriteNode &Node);
326 static constexpr unsigned MaxVisitedNodes = 64;
329 unsigned NumVisited = 0;
334 const DataLayout &DL;
335 const SimplifyQuery SQ;
341class SeparateConstOffsetFromGEPLegacyPass :
public FunctionPass {
345 SeparateConstOffsetFromGEPLegacyPass(
bool LowerGEP =
false)
346 : FunctionPass(ID), LowerGEP(LowerGEP) {
351 void getAnalysisUsage(AnalysisUsage &AU)
const override {
368class SeparateConstOffsetFromGEP {
370 SeparateConstOffsetFromGEP(
371 DominatorTree *DT, LoopInfo *LI, TargetLibraryInfo *TLI,
372 function_ref<TargetTransformInfo &(
Function &)> GetTTI,
bool LowerGEP)
373 : DT(DT), LI(LI), TLI(TLI), GetTTI(GetTTI), LowerGEP(LowerGEP) {}
379 using ExprKey = std::pair<Value *, Value *>;
382 static ExprKey createNormalizedCommutablePair(
Value *
A,
Value *
B) {
390 bool splitGEP(GetElementPtrInst *
GEP);
395 bool reorderGEP(GetElementPtrInst *
GEP, TargetTransformInfo &
TTI);
404 void lowerToSingleIndexGEPs(GetElementPtrInst *Variadic,
405 const APInt &AccumulativeByteOffset);
413 APInt accumulateByteOffset(GetElementPtrInst *
GEP,
bool &NeedsExtraction,
414 bool &SignedOverflow);
431 bool canonicalizeArrayIndicesToIndexSize(GetElementPtrInst *
GEP);
445 bool reuniteExts(Instruction *
I);
449 ExprKey
Key, Instruction *Dominatee,
450 DenseMap<ExprKey, SmallVector<Instruction *, 2>> &DominatingExprs);
455 bool hasMoreThanOneUseInLoop(
Value *v,
Loop *L);
458 void swapGEPOperand(GetElementPtrInst *
First, GetElementPtrInst *Second);
461 bool isLegalToSwapOperand(GetElementPtrInst *
First, GetElementPtrInst *Second,
464 const DataLayout *DL =
nullptr;
465 DominatorTree *DT =
nullptr;
467 TargetLibraryInfo *TLI;
469 function_ref<TargetTransformInfo &(
Function &)> GetTTI;
475 DenseMap<ExprKey, SmallVector<Instruction *, 2>> DominatingAdds;
476 DenseMap<ExprKey, SmallVector<Instruction *, 2>> DominatingSubs;
481char SeparateConstOffsetFromGEPLegacyPass::ID = 0;
484 SeparateConstOffsetFromGEPLegacyPass,
"separate-const-offset-from-gep",
485 "Split GEPs to a variadic base and a constant offset for better CSE",
false,
493 SeparateConstOffsetFromGEPLegacyPass,
"separate-const-offset-from-gep",
494 "Split GEPs to a variadic base and a constant offset for better CSE",
false,
498 return new SeparateConstOffsetFromGEPLegacyPass(LowerGEP);
538 if (!
GEP->isInBounds())
541 const Value *Ptr =
GEP->getPointerOperand();
555 unsigned N =
Add->getType()->getIntegerBitWidth();
558 TypeSize ElemSize = GTI.getSequentialElementStride(
DL);
576 if (Idx->getOperandNo() == 1 &&
Base &&
600 if (
auto AllocSize = AI->getAllocationSize(
DL))
601 if (!AllocSize->isScalable())
602 ObjSize = AllocSize->getFixedValue();
604 TypeSize GVSize =
DL.getTypeAllocSize(GV->getValueType());
608 if (ObjSize > 0 &&
APInt(128, ObjSize).ult(Threshold))
614bool ConstantOffsetExtractor::canTraceInto(
const CastState &Casts,
616 bool SignExtended = Casts.hasSignExtension();
617 bool ZeroExtended = Casts.hasZeroExtension();
626 if (BO->
getOpcode() != Instruction::Add &&
639 if (BO->
getOpcode() == Instruction::Add && !ZeroExtended && Idx) {
644 GEP->hasNoUnsignedWrap())
658std::optional<APInt> ConstantOffsetExtractor::findInOperands(RewriteNode &Node,
665 Node.LHS = UserTree.size() - 1;
670 Node.RHS = UserTree.size() - 1;
676std::optional<APInt> ConstantOffsetExtractor::find(
Value *
V,
const Use *Idx,
684 if (NumVisited++ >= MaxVisitedNodes)
692 RewriteNode
Node{
U, std::nullopt, std::nullopt};
693 std::optional<APInt> ConstantOffset;
699 ConstantOffset = Casts.apply(CI->getValue());
700 Node.V = ConstantInt::getNullValue(CI->getType());
703 if (canTraceInto(Casts, BO, Idx))
704 ConstantOffset = findInOperands(Node, Casts);
705 else if (BO->
getOpcode() == Instruction::Xor) {
706 ConstantOffset = extractDisjointBitsFromXor(Node);
708 *ConstantOffset = Casts.apply(*ConstantOffset);
713 ConstantOffset =
find(
U->getOperand(0), Idx, Casts);
716 Node.LHS = UserTree.size() - 1;
720 UserTree.push_back(Node);
721 return ConstantOffset;
724Value *ConstantOffsetExtractor::applyCasts(
Value *
V,
const CastState &Casts) {
752Value *ConstantOffsetExtractor::rebuildWithoutConstOffset(
unsigned NodeIndex,
754 const RewriteNode &
Node = UserTree[NodeIndex];
756 return applyCasts(
Node.V, Casts);
759 Casts.pushCast(Cast);
767 : applyCasts(BO->getOperand(0), Casts);
769 : applyCasts(BO->getOperand(1), Casts);
778 BinaryOperator::BinaryOps NewOp = BO->
getOpcode();
793 NewOp = Instruction::Add;
802ConstantOffsetExtractor::extractDisjointBitsFromXor(RewriteNode &Node) {
804 assert(XorInst && XorInst->getOpcode() == Instruction::Xor &&
805 "Expected XOR instruction");
808 ConstantInt *XorConstantOp;
814 const APInt &ConstantValue = XorConstantOp->
getValue();
820 const APInt DisjointBits = ConstantValue & BaseKnownBits.
Zero;
821 if (DisjointBits.
isZero())
830 const APInt NonDisjointBits = ConstantValue & ~DisjointBits;
831 Node.RHS = UserTree.size();
832 UserTree.push_back({ConstantInt::get(XorInst->getContext(), NonDisjointBits),
833 std::nullopt, std::nullopt});
843 if (Opcode == BinaryOperator::Or) {
856 return TI->hasNoUnsignedWrap();
863 if (
auto IP =
I->getInsertionPointAfterDef())
868Value *ConstantOffsetExtractor::Extract(
const Use &Idx, User *&UserTreeRoot,
869 bool &PreservesNUW) {
873 if (!Extractor.find(Idx, &Idx, Casts)) {
874 UserTreeRoot =
nullptr;
879 PreservesNUW =
all_of(Extractor.UserTree, [](
const RewriteNode &Node) {
880 return allowsPreservingNUW(Node.V);
884 Value *IdxWithoutConstOffset = Extractor.rebuildWithoutConstOffset();
886 return IdxWithoutConstOffset;
889std::optional<APInt> ConstantOffsetExtractor::Find(
const Use &Idx) {
892 return ConstantOffsetExtractor(
GEP->getIterator()).find(Idx, &Idx, Casts);
895bool SeparateConstOffsetFromGEP::canonicalizeArrayIndicesToIndexSize(
896 GetElementPtrInst *
GEP) {
898 Type *PtrIdxTy =
DL->getIndexType(
GEP->getType());
901 I !=
E; ++
I, ++GTI) {
904 if ((*I)->getType() != PtrIdxTy) {
914APInt SeparateConstOffsetFromGEP::accumulateByteOffset(GetElementPtrInst *
GEP,
915 bool &NeedsExtraction,
916 bool &SignedOverflow) {
917 NeedsExtraction =
false;
918 SignedOverflow =
false;
919 unsigned IdxWidth =
DL->getIndexTypeSizeInBits(
GEP->getType());
920 APInt AccumulativeByteOffset(IdxWidth, 0);
922 for (
unsigned I = 1,
E =
GEP->getNumOperands();
I !=
E; ++
I, ++GTI) {
929 if (std::optional<APInt> ConstantOffset =
930 ConstantOffsetExtractor::Find(
GEP->getOperandUse(
I))) {
931 NeedsExtraction =
true;
937 auto ByteOffset = ConstantOffset->sextOrTrunc(IdxWidth).smul_ov(
938 APInt(IdxWidth, Stride,
true,
true),
940 SignedOverflow |= Overflow;
945 auto *
Offset = ConstantInt::get(
GEP->getContext(), *ConstantOffset);
948 OverflowResult::NeverOverflows;
950 AccumulativeByteOffset =
951 AccumulativeByteOffset.sadd_ov(ByteOffset, Overflow);
952 SignedOverflow |= Overflow;
954 }
else if (LowerGEP) {
959 NeedsExtraction =
true;
960 AccumulativeByteOffset +=
961 APInt(IdxWidth,
DL->getStructLayout(StTy)->getElementOffset(
Field),
966 return AccumulativeByteOffset;
969void SeparateConstOffsetFromGEP::lowerToSingleIndexGEPs(
970 GetElementPtrInst *Variadic,
const APInt &AccumulativeByteOffset) {
972 Builder.disableGEPCanonicalization();
978 bool isSwapCandidate =
979 L &&
L->isLoopInvariant(ResultPtr) &&
980 !hasMoreThanOneUseInLoop(ResultPtr, L);
981 Value *FirstResult =
nullptr;
986 for (
unsigned I = 1,
E =
Variadic->getNumOperands();
I !=
E; ++
I, ++GTI) {
997 if (ElementSize != 1) {
999 Idx = Builder.CreateShl(
1000 Idx, ConstantInt::get(PtrIndexTy, ElementSize.
logBase2()));
1003 Builder.CreateMul(Idx, ConstantInt::get(PtrIndexTy, ElementSize));
1007 ResultPtr = Builder.CreatePtrAdd(ResultPtr, Idx,
"uglygep");
1008 if (FirstResult ==
nullptr)
1009 FirstResult = ResultPtr;
1014 if (AccumulativeByteOffset != 0) {
1015 Value *
Offset = ConstantInt::get(PtrIndexTy, AccumulativeByteOffset);
1016 ResultPtr = Builder.CreatePtrAdd(ResultPtr,
Offset,
"uglygep");
1018 isSwapCandidate =
false;
1025 if (isSwapCandidate && isLegalToSwapOperand(FirstGEP, SecondGEP, L))
1026 swapGEPOperand(FirstGEP, SecondGEP);
1028 Variadic->replaceAllUsesWith(ResultPtr);
1032bool SeparateConstOffsetFromGEP::reorderGEP(GetElementPtrInst *
GEP,
1033 TargetTransformInfo &
TTI) {
1038 bool NestedNeedsExtraction, OffsetOverflow;
1039 APInt NestedByteOffset =
1040 accumulateByteOffset(PtrGEP, NestedNeedsExtraction, OffsetOverflow);
1041 if (!NestedNeedsExtraction)
1044 unsigned AddrSpace = PtrGEP->getPointerAddressSpace();
1048 true, 0, AddrSpace))
1051 bool GEPInBounds =
GEP->isInBounds();
1052 bool PtrGEPInBounds = PtrGEP->isInBounds();
1053 bool IsChainInBounds = GEPInBounds && PtrGEPInBounds;
1054 if (IsChainInBounds) {
1055 auto IsKnownNonNegative = [
this](
Value *
V) {
1058 IsChainInBounds &=
all_of(
GEP->indices(), IsKnownNonNegative);
1059 if (IsChainInBounds)
1060 IsChainInBounds &=
all_of(PtrGEP->indices(), IsKnownNonNegative);
1064 Builder.disableGEPCanonicalization();
1066 Value *NewSrc = Builder.CreateGEP(
1067 GEP->getSourceElementType(), PtrGEP->getPointerOperand(),
1068 SmallVector<Value *, 4>(
GEP->indices()),
"", IsChainInBounds);
1069 Value *NewGEP = Builder.CreateGEP(PtrGEP->getSourceElementType(), NewSrc,
1070 SmallVector<Value *, 4>(PtrGEP->indices()),
1071 "", IsChainInBounds);
1072 GEP->replaceAllUsesWith(NewGEP);
1077bool SeparateConstOffsetFromGEP::splitGEP(GetElementPtrInst *
GEP) {
1079 if (
GEP->getType()->isVectorTy())
1086 const APInt *BaseOffset;
1091 unsigned IdxWidth =
DL->getIndexTypeSizeInBits(
GEP->getType());
1092 APInt BaseByteOffset = ExtractBase ? *BaseOffset : APInt(IdxWidth, 0);
1096 if (
GEP->hasAllConstantIndices() && !ExtractBase)
1099 bool Changed = canonicalizeArrayIndicesToIndexSize(
GEP);
1101 bool NeedsExtraction, OffsetOverflow;
1102 APInt NonBaseByteOffset =
1103 accumulateByteOffset(
GEP, NeedsExtraction, OffsetOverflow);
1105 APInt AccumulativeByteOffset =
1109 TargetTransformInfo &
TTI = GetTTI(*
GEP->getFunction());
1111 if (!NeedsExtraction && !ExtractBase) {
1124 unsigned AddrSpace =
GEP->getPointerAddressSpace();
1126 GEP->getResultElementType(),
1128 true, 0, AddrSpace)) {
1134 ExtractBase =
false;
1135 BaseByteOffset = APInt(IdxWidth, 0);
1136 AccumulativeByteOffset = NonBaseByteOffset;
1138 GEP->getResultElementType(),
1140 true, 0, AddrSpace))
1143 NeedsExtraction =
true;
1148 bool AllOffsetsNonNegative =
1150 bool AllNUWPreserved =
GEP->hasNoUnsignedWrap();
1151 bool NewGEPInBounds =
GEP->isInBounds();
1152 bool NewGEPNUSW =
GEP->hasNoUnsignedSignedWrap();
1162 for (
unsigned I = 1,
E =
GEP->getNumOperands();
I !=
E; ++
I, ++GTI) {
1173 Value *NewIdx = ConstantOffsetExtractor::Extract(
1174 GEP->getOperandUse(
I), UserTreeRoot, PreservesNUW);
1175 if (NewIdx !=
nullptr) {
1177 GEP->setOperand(
I, NewIdx);
1185 AllNUWPreserved &= PreservesNUW;
1187 AllOffsetsNonNegative =
1193 AllNUWPreserved &=
Base->hasNoUnsignedWrap();
1194 NewGEPInBounds &=
Base->isInBounds();
1195 NewGEPNUSW &=
Base->hasNoUnsignedSignedWrap();
1198 GEP->setOperand(0, NewBase);
1224 bool CanPreserveInBoundsNUSW = AllOffsetsNonNegative;
1228 if (AllNUWPreserved) {
1236 CanPreserveInBoundsNUSW |= NewGEPNUSW;
1239 if (CanPreserveInBoundsNUSW) {
1242 else if (NewGEPNUSW)
1246 GEP->setNoWrapFlags(NewGEPFlags);
1250 lowerToSingleIndexGEPs(
GEP, AccumulativeByteOffset);
1255 if (AccumulativeByteOffset == 0)
1278 Type *PtrIdxTy =
DL->getIndexType(
GEP->getType());
1281 NewGEP, ConstantInt::get(PtrIdxTy, AccumulativeByteOffset),
1282 GEP->getName(), NewGEPFlags));
1285 GEP->replaceAllUsesWith(NewGEP);
1286 GEP->eraseFromParent();
1291bool SeparateConstOffsetFromGEPLegacyPass::runOnFunction(
Function &
F) {
1292 if (skipFunction(
F))
1294 auto *DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
1295 auto *LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
1296 auto *
TLI = &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(
F);
1297 auto GetTTI = [
this](
Function &
F) -> TargetTransformInfo & {
1298 return this->getAnalysis<TargetTransformInfoWrapperPass>().getTTI(
F);
1300 SeparateConstOffsetFromGEP Impl(DT, LI,
TLI, GetTTI, LowerGEP);
1304bool SeparateConstOffsetFromGEP::run(
Function &
F) {
1306 if (Opts.disable_separate_const_offset_from_gep)
1309 DL = &
F.getDataLayout();
1312 ReversePostOrderTraversal<Function *> RPOT(&
F);
1313 for (BasicBlock *
B : RPOT) {
1326 if (Opts.reassociate_geps_verify_no_dead_code)
1327 verifyNoDeadCode(
F);
1332Instruction *SeparateConstOffsetFromGEP::findClosestMatchingDominator(
1333 ExprKey
Key, Instruction *Dominatee,
1334 DenseMap<ExprKey, SmallVector<Instruction *, 2>> &DominatingExprs) {
1335 auto Pos = DominatingExprs.find(
Key);
1336 if (Pos == DominatingExprs.end())
1339 auto &Candidates = Pos->second;
1344 while (!Candidates.empty()) {
1346 if (DT->
dominates(Candidate, Dominatee))
1348 Candidates.pop_back();
1353bool SeparateConstOffsetFromGEP::reuniteExts(Instruction *
I) {
1354 if (!
I->getType()->isIntOrIntVectorTy())
1364 ExprKey
Key = createNormalizedCommutablePair(
LHS,
RHS);
1365 if (
auto *Dom = findClosestMatchingDominator(
Key,
I, DominatingAdds)) {
1367 new SExtInst(Dom,
I->getType(),
"",
I->getIterator());
1369 I->replaceAllUsesWith(NewSExt);
1378 findClosestMatchingDominator({
LHS,
RHS},
I, DominatingSubs)) {
1380 new SExtInst(Dom,
I->getType(),
"",
I->getIterator());
1382 I->replaceAllUsesWith(NewSExt);
1393 ExprKey
Key = createNormalizedCommutablePair(
LHS,
RHS);
1394 DominatingAdds[
Key].push_back(
I);
1398 DominatingSubs[{
LHS,
RHS}].push_back(
I);
1403bool SeparateConstOffsetFromGEP::reuniteExts(
Function &
F) {
1405 DominatingAdds.clear();
1406 DominatingSubs.clear();
1415void SeparateConstOffsetFromGEP::verifyNoDeadCode(
Function &
F) {
1416 for (BasicBlock &
B :
F) {
1417 for (Instruction &
I :
B) {
1419 std::string ErrMessage;
1420 raw_string_ostream RSO(ErrMessage);
1421 RSO <<
"Dead instruction detected!\n" <<
I <<
"\n";
1428bool SeparateConstOffsetFromGEP::isLegalToSwapOperand(
1429 GetElementPtrInst *FirstGEP, GetElementPtrInst *SecondGEP,
Loop *CurLoop) {
1430 if (!FirstGEP || !FirstGEP->
hasOneUse())
1436 if (FirstGEP == SecondGEP)
1442 if (FirstNum != SecondNum || FirstNum != 2)
1467 if (FirstOffsetDef && FirstOffsetDef->
isShift() &&
1476 if ((opc == Instruction::Add || opc == Instruction::Sub) &&
1484bool SeparateConstOffsetFromGEP::hasMoreThanOneUseInLoop(
Value *
V,
Loop *L) {
1491 for (User *U :
V->users()) {
1493 if (
L->contains(User))
1494 if (++UsesInLoop > 1)
1500void SeparateConstOffsetFromGEP::swapGEPOperand(GetElementPtrInst *
First,
1501 GetElementPtrInst *Second) {
1504 First->setOperand(1, Offset2);
1509 const DataLayout &DAL =
First->getDataLayout();
1513 auto ClearNoWrapFlags = [&] {
1519 APInt FirstOffset(IdxBits, 0);
1520 if (!
First->accumulateConstantOffset(DAL, FirstOffset)) {
1525 APInt BaseOffset(IdxBits, 0);
1530 bool Overflow =
false;
1531 APInt TotalOffset = BaseOffset.
uadd_ov(FirstOffset, Overflow);
1534 TotalOffset.
ugt(ObjectSize)) {
1539 First->setIsInBounds(
true);
1544 static_cast<PassInfoMixin<SeparateConstOffsetFromGEPPass> *
>(
this)
1560 SeparateConstOffsetFromGEP Impl(DT, LI,
TLI, GetTTI, LowerGEP);
const TargetLowering & TLI
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
This file implements a class to represent arbitrary precision integral constant values and operations...
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
static GCRegistry::Add< ShadowStackGC > C("shadow-stack", "Very portable GC for uncooperative code generators")
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
This file contains the declarations for the subclasses of Constant, which represent the different fla...
This file defines the DenseMap class.
This file builds on the ADT/GraphTraits.h file to build generic depth first graph iterator.
static bool runOnFunction(Function &F, bool PostInlining)
Module.h This file contains the declarations for the Module class.
This header defines various interfaces for pass management in LLVM.
static const T * Find(StringRef S, ArrayRef< T > A)
Find KV in array using binary search.
OptimizedStructLayoutField Field
#define INITIALIZE_PASS_DEPENDENCY(depName)
#define INITIALIZE_PASS_END(passName, arg, name, cfg, analysis)
#define INITIALIZE_PASS_BEGIN(passName, arg, name, cfg, analysis)
static bool allowsPreservingNUW(const User *U)
Check if reassociating through a tree node would invalidate GEP's nuw flag.
static bool canReorderAddSextToGEP(const Use *Idx, const BinaryOperator *Add, const DataLayout &DL)
static BasicBlock::iterator getIndexInsertionPoint(const Use &Idx)
This file defines the SmallVector class.
Class for arbitrary precision integers.
LLVM_ABI APInt zext(unsigned width) const
Zero extend to a new width.
LLVM_ABI APInt zextOrTrunc(unsigned width) const
Zero extend or truncate to width.
bool ugt(const APInt &RHS) const
Unsigned greater than comparison.
bool isZero() const
Determine if this value is zero, i.e. all bits are clear.
LLVM_ABI APInt sadd_ov(const APInt &RHS, bool &Overflow) const
LLVM_ABI APInt uadd_ov(const APInt &RHS, bool &Overflow) const
static APInt getSignedMinValue(unsigned numBits)
Gets minimum signed value of APInt for a specific bit width.
LLVM_ABI APInt sextOrTrunc(unsigned width) const
Sign extend or truncate to width.
unsigned logBase2() const
bool isNonNegative() const
Determine if this APInt Value is non-negative (>= 0)
bool isPowerOf2() const
Check if this APInt's value is a power of two greater than zero.
bool isSignBitSet() const
Determine if sign bit of this APInt is set.
int64_t getSExtValue() const
Get sign extended value.
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs... ExtraArgs)
Get the result of an analysis pass for a given IR unit.
AnalysisUsage & addRequired()
LLVM_ABI void setPreservesCFG()
This function should be called by the pass, iff they do not:
InstListType::iterator iterator
Instruction iterators...
BinaryOps getOpcode() const
static LLVM_ABI BinaryOperator * Create(BinaryOps Op, Value *S1, Value *S2, const Twine &Name=Twine(), InsertPosition InsertBefore=nullptr)
Construct a binary instruction, given the opcode and the two operands.
Represents analyses that only rely on functions' control flow.
static LLVM_ABI CastInst * CreateIntegerCast(Value *S, Type *Ty, bool isSigned, const Twine &Name="", InsertPosition InsertBefore=nullptr)
Create a ZExt, BitCast, or Trunc for int -> int casts.
This is the shared class of boolean and integer constants.
const APInt & getValue() const
Return the constant as an APInt value reference.
A parsed version of the target data layout string in and methods for querying it.
unsigned getIndexSizeInBits(unsigned AS) const
The size in bits of indices used for address calculation in getelementptr and for addresses in the gi...
Analysis pass which computes a DominatorTree.
Legacy analysis pass which computes a DominatorTree.
LLVM_ABI bool isReachableFromEntry(const Use &U) const
Provide an overload for a Use.
LLVM_ABI bool dominates(const BasicBlock *BB, const Use &U) const
Return true if the (end of the) basic block BB dominates the use U.
FunctionPass class - This class is used to implement most global optimizations.
static GEPNoWrapFlags inBounds()
static GEPNoWrapFlags noUnsignedWrap()
static GEPNoWrapFlags noUnsignedSignedWrap()
static GEPNoWrapFlags none()
LLVM_ABI void setNoWrapFlags(GEPNoWrapFlags NW)
Set nowrap flags for GEP instruction.
LLVM_ABI Instruction * clone() const
Create a copy of 'this' instruction that is identical in all ways except the following:
LLVM_ABI bool hasNoUnsignedWrap() const LLVM_READONLY
Determine whether the no unsigned wrap flag is set.
LLVM_ABI bool hasNoSignedWrap() const LLVM_READONLY
Determine whether the no signed wrap flag is set.
LLVM_ABI void insertBefore(InstListType::iterator InsertPos)
Insert an unlinked instruction into a basic block immediately before the specified position.
LLVM_ABI void dropPoisonGeneratingFlags()
Drops flags that may cause this instruction to evaluate to poison despite having non-poison inputs.
void setDebugLoc(DebugLoc Loc)
Set the debug location information for this instruction.
LLVM_ABI void copyMetadata(const Instruction &SrcInst, ArrayRef< unsigned > WL=ArrayRef< unsigned >())
Copy metadata from SrcInst to this instruction.
Analysis pass that exposes the LoopInfo for a function.
LoopT * getLoopFor(const BlockT *BB) const
Return the inner most loop that BB lives in.
The legacy pass manager's analysis pass to compute loop information.
LLVM_ABI bool isLoopInvariant(const Value *V) const
Return true if the specified value is loop invariant.
static LLVM_ABI PassRegistry * getPassRegistry()
getPassRegistry - Access the global registry object, which is automatically initialized at applicatio...
A set of analyses that are preserved following a run of a transformation pass.
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
PreservedAnalyses & preserveSet()
Mark an analysis set as preserved.
LLVM_ABI void printPipeline(raw_ostream &OS, function_ref< StringRef(StringRef)> MapClassName2PassName)
LLVM_ABI PreservedAnalyses run(Function &F, FunctionAnalysisManager &)
Represent a constant reference to a string, i.e.
Analysis pass providing the TargetTransformInfo.
Analysis pass providing the TargetLibraryInfo.
This class represents a truncation of integer types.
LLVM_ABI unsigned getIntegerBitWidth() const
LLVM_ABI bool isScalableTy() const
Return true if this is a type whose size is a known multiple of vscale.
A Use represents the edge between a Value definition and its users.
void setOperand(unsigned i, Value *Val)
Value * getOperand(unsigned i) const
unsigned getNumOperands() const
LLVM Value Representation.
Type * getType() const
All values are typed, get the type of this value.
const Value * stripAndAccumulateInBoundsConstantOffsets(const DataLayout &DL, APInt &Offset) const
This is a wrapper around stripAndAccumulateConstantOffsets with the in-bounds requirement set to fals...
bool hasOneUse() const
Return true if there is exactly one use of this value.
LLVM_ABI void takeName(Value *V)
Transfer the name from V to this value.
constexpr ScalarTy getFixedValue() const
constexpr bool isScalable() const
Returns whether the quantity is scaled by a runtime quantity (vscale).
An efficient, type-erasing, non-owning reference to a callable.
bool isSequential() const
StructType * getStructType() const
TypeSize getSequentialElementStride(const DataLayout &DL) const
Type * getIndexedType() const
const ParentTy * getParent() const
This class implements an extremely fast bulk output stream that can only output to a stream.
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
@ BasicBlock
Various leaf nodes.
BinaryOp_match< LHS, RHS, Instruction::Add > m_Add(const LHS &L, const RHS &R)
ap_match< APInt > m_APInt(const APInt *&Res)
Match a ConstantInt or splatted ConstantVector, binding the specified pointer to the contained APInt.
BinaryOp_match< LHS, RHS, Instruction::Xor > m_Xor(const LHS &L, const RHS &R)
OverflowingBinaryOp_match< LHS, RHS, Instruction::Sub, OverflowingBinaryOperator::NoSignedWrap > m_NSWSub(const LHS &L, const RHS &R)
bool match(Val *V, const Pattern &P)
auto m_Value()
Match an arbitrary value and ignore it.
is_zero< true > m_Zero()
Match any null constant or a vector with all elements equal to 0.
PtrAdd_match< PointerOpTy, OffsetOpTy > m_PtrAdd(const DataLayout &DL, const PointerOpTy &PointerOp, const OffsetOpTy &OffsetOp)
Matches GEP with i8 source element type and canonical index type.
OverflowingBinaryOp_match< LHS, RHS, Instruction::Add, OverflowingBinaryOperator::NoSignedWrap > m_NSWAdd(const LHS &L, const RHS &R)
CastInst_match< OpTy, SExtInst > m_SExt(const OpTy &Op)
Matches SExt.
BinaryOp_match< LHS, RHS, Instruction::Sub > m_Sub(const LHS &L, const RHS &R)
auto m_ConstantInt()
Match an arbitrary ConstantInt and ignore it.
void apply(Opt *O, const Mod &M, const Mods &... Ms)
PointerTypeMap run(const Module &M)
Compute the PointerTypeMap for the module M.
@ User
could "use" a pointer
NodeAddr< NodeBase * > Node
friend class Instruction
Iterator for Instructions in a `BasicBlock.
This is an optimization pass for GlobalISel generic memory operations.
@ NeverOverflows
Never overflows.
auto find(R &&Range, const T &Val)
Provide wrappers to std::find which take ranges instead of having to pass begin/end explicitly.
bool all_of(R &&range, UnaryPredicate P)
Provide wrappers to std::all_of which take ranges instead of having to pass begin/end explicitly.
LLVM_ABI bool RecursivelyDeleteTriviallyDeadInstructions(Value *V, const TargetLibraryInfo *TLI=nullptr, MemorySSAUpdater *MSSAU=nullptr, std::function< void(Value *)> AboutToDeleteCallback=std::function< void(Value *)>())
If the specified value is a trivially dead instruction, delete it.
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Value * GetPointerBaseWithConstantOffset(Value *Ptr, int64_t &Offset, const DataLayout &DL, bool AllowNonInbounds=true)
Analyze the specified pointer to see if it can be expressed as a base pointer plus a constant offset.
iterator_range< early_inc_iterator_impl< detail::IterOfRange< RangeT > > > make_early_inc_range(RangeT &&Range)
Make a range that does early increment to allow mutation of the underlying range without disrupting i...
LLVM_ABI void computeKnownBits(const Value *V, KnownBits &Known, const DataLayout &DL, AssumptionCache *AC=nullptr, const Instruction *CtxI=nullptr, const DominatorTree *DT=nullptr, bool UseInstrInfo=true, unsigned Depth=0)
Determine which bits of V are known to be either zero or one and return them in the KnownZero/KnownOn...
constexpr std::enable_if_t< std::is_signed_v< T >, std::pair< T, bool > > AddOverflow(T X, T Y)
Add two signed integers, computing the two's complement truncated result, returning a pair {result,...
const ScalarOptions & getScalarOptions(const LLVMContext &C)
LLVM_ABI void initializeSeparateConstOffsetFromGEPLegacyPassPass(PassRegistry &)
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Value
auto dyn_cast_or_null(const Y &Val)
bool any_of(R &&range, UnaryPredicate P)
Provide wrappers to std::any_of which take ranges instead of having to pass begin/end explicitly.
LLVM_ABI bool isInstructionTriviallyDead(Instruction *I, const TargetLibraryInfo *TLI=nullptr)
Return true if the result produced by the instruction is not used, and the instruction will return.
LLVM_ABI bool getObjectSize(const Value *Ptr, uint64_t &Size, const DataLayout &DL, const TargetLibraryInfo *TLI, ObjectSizeOpts Opts={})
Compute the size of the object pointed by Ptr.
auto reverse(ContainerTy &&C)
LLVM_ABI OverflowResult computeOverflowForSignedSub(const Value *LHS, const Value *RHS, const SimplifyQuery &SQ)
LLVM_ABI bool programUndefinedIfPoison(const Instruction *Inst)
IRBuilder(LLVMContext &, FolderTy, InserterTy) -> IRBuilder< FolderTy, InserterTy >
generic_gep_type_iterator<> gep_type_iterator
LLVM_ABI Constant * ConstantFoldCastOperand(unsigned Opcode, Constant *C, Type *DestTy, const DataLayout &DL)
Attempt to constant fold a cast with the specified operand.
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
LLVM_ABI const Value * getUnderlyingObject(const Value *V, unsigned MaxLookup=MaxLookupSearchDepth, bool MustPreserveProvenance=false)
This method strips off any GEP address adjustments, pointer casts or llvm.threadlocal....
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
LLVM_ATTRIBUTE_VISIBILITY_DEFAULT AnalysisKey InnerAnalysisManagerProxy< AnalysisManagerT, IRUnitT, ExtraArgTs... >::Key
LLVM_ABI FunctionPass * createSeparateConstOffsetFromGEPPass(bool LowerGEP=false)
@ First
Helpers to iterate all locations in the MemoryEffectsBase class.
LLVM_ABI OverflowResult computeOverflowForSignedAdd(const WithCache< const Value * > &LHS, const WithCache< const Value * > &RHS, const SimplifyQuery &SQ)
constexpr unsigned BitWidth
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
gep_type_iterator gep_type_begin(const User *GEP)
iterator_range< df_iterator< T > > depth_first(const T &G)
AnalysisManager< Function > FunctionAnalysisManager
Convenience typedef for the Function analysis manager.
LLVM_ABI bool isKnownNonNegative(const Value *V, const SimplifyQuery &SQ, unsigned Depth=0)
Returns true if the give value is known to be non-negative.
constexpr detail::IsaCheckPredicate< Types... > IsaPred
Function object wrapper for the llvm::isa type check.