LLVM  12.0.0git
LoopUnrollAnalyzer.cpp
Go to the documentation of this file.
1 //===- LoopUnrollAnalyzer.cpp - Unrolling Effect Estimation -----*- C++ -*-===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file implements UnrolledInstAnalyzer class. It's used for predicting
10 // potential effects that loop unrolling might have, such as enabling constant
11 // propagation and other optimizations.
12 //
13 //===----------------------------------------------------------------------===//
14 
16 #include "llvm/Analysis/LoopInfo.h"
17 
18 using namespace llvm;
19 
20 /// Try to simplify instruction \param I using its SCEV expression.
21 ///
22 /// The idea is that some AddRec expressions become constants, which then
23 /// could trigger folding of other instructions. However, that only happens
24 /// for expressions whose start value is also constant, which isn't always the
25 /// case. In another common and important case the start value is just some
26 /// address (i.e. SCEVUnknown) - in this case we compute the offset and save
27 /// it along with the base address instead.
28 bool UnrolledInstAnalyzer::simplifyInstWithSCEV(Instruction *I) {
29  if (!SE.isSCEVable(I->getType()))
30  return false;
31 
32  const SCEV *S = SE.getSCEV(I);
33  if (auto *SC = dyn_cast<SCEVConstant>(S)) {
34  SimplifiedValues[I] = SC->getValue();
35  return true;
36  }
37 
38  auto *AR = dyn_cast<SCEVAddRecExpr>(S);
39  if (!AR || AR->getLoop() != L)
40  return false;
41 
42  const SCEV *ValueAtIteration = AR->evaluateAtIteration(IterationNumber, SE);
43  // Check if the AddRec expression becomes a constant.
44  if (auto *SC = dyn_cast<SCEVConstant>(ValueAtIteration)) {
45  SimplifiedValues[I] = SC->getValue();
46  return true;
47  }
48 
49  // Check if the offset from the base address becomes a constant.
50  auto *Base = dyn_cast<SCEVUnknown>(SE.getPointerBase(S));
51  if (!Base)
52  return false;
53  auto *Offset =
54  dyn_cast<SCEVConstant>(SE.getMinusSCEV(ValueAtIteration, Base));
55  if (!Offset)
56  return false;
57  SimplifiedAddress Address;
58  Address.Base = Base->getValue();
59  Address.Offset = Offset->getValue();
60  SimplifiedAddresses[I] = Address;
61  return false;
62 }
63 
64 /// Try to simplify binary operator I.
65 ///
66 /// TODO: Probably it's worth to hoist the code for estimating the
67 /// simplifications effects to a separate class, since we have a very similar
68 /// code in InlineCost already.
69 bool UnrolledInstAnalyzer::visitBinaryOperator(BinaryOperator &I) {
70  Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
71  if (!isa<Constant>(LHS))
72  if (Constant *SimpleLHS = SimplifiedValues.lookup(LHS))
73  LHS = SimpleLHS;
74  if (!isa<Constant>(RHS))
75  if (Constant *SimpleRHS = SimplifiedValues.lookup(RHS))
76  RHS = SimpleRHS;
77 
78  Value *SimpleV = nullptr;
79  const DataLayout &DL = I.getModule()->getDataLayout();
80  if (auto FI = dyn_cast<FPMathOperator>(&I))
81  SimpleV =
82  SimplifyBinOp(I.getOpcode(), LHS, RHS, FI->getFastMathFlags(), DL);
83  else
84  SimpleV = SimplifyBinOp(I.getOpcode(), LHS, RHS, DL);
85 
86  if (Constant *C = dyn_cast_or_null<Constant>(SimpleV))
87  SimplifiedValues[&I] = C;
88 
89  if (SimpleV)
90  return true;
91  return Base::visitBinaryOperator(I);
92 }
93 
94 /// Try to fold load I.
95 bool UnrolledInstAnalyzer::visitLoad(LoadInst &I) {
96  Value *AddrOp = I.getPointerOperand();
97 
98  auto AddressIt = SimplifiedAddresses.find(AddrOp);
99  if (AddressIt == SimplifiedAddresses.end())
100  return false;
101  ConstantInt *SimplifiedAddrOp = AddressIt->second.Offset;
102 
103  auto *GV = dyn_cast<GlobalVariable>(AddressIt->second.Base);
104  // We're only interested in loads that can be completely folded to a
105  // constant.
106  if (!GV || !GV->hasDefinitiveInitializer() || !GV->isConstant())
107  return false;
108 
110  dyn_cast<ConstantDataSequential>(GV->getInitializer());
111  if (!CDS)
112  return false;
113 
114  // We might have a vector load from an array. FIXME: for now we just bail
115  // out in this case, but we should be able to resolve and simplify such
116  // loads.
117  if (CDS->getElementType() != I.getType())
118  return false;
119 
120  unsigned ElemSize = CDS->getElementType()->getPrimitiveSizeInBits() / 8U;
121  if (SimplifiedAddrOp->getValue().getActiveBits() > 64)
122  return false;
123  int64_t SimplifiedAddrOpV = SimplifiedAddrOp->getSExtValue();
124  if (SimplifiedAddrOpV < 0) {
125  // FIXME: For now we conservatively ignore out of bound accesses, but
126  // we're allowed to perform the optimization in this case.
127  return false;
128  }
129  uint64_t Index = static_cast<uint64_t>(SimplifiedAddrOpV) / ElemSize;
130  if (Index >= CDS->getNumElements()) {
131  // FIXME: For now we conservatively ignore out of bound accesses, but
132  // we're allowed to perform the optimization in this case.
133  return false;
134  }
135 
136  Constant *CV = CDS->getElementAsConstant(Index);
137  assert(CV && "Constant expected.");
138  SimplifiedValues[&I] = CV;
139 
140  return true;
141 }
142 
143 /// Try to simplify cast instruction.
144 bool UnrolledInstAnalyzer::visitCastInst(CastInst &I) {
145  // Propagate constants through casts.
146  Constant *COp = dyn_cast<Constant>(I.getOperand(0));
147  if (!COp)
148  COp = SimplifiedValues.lookup(I.getOperand(0));
149 
150  // If we know a simplified value for this operand and cast is valid, save the
151  // result to SimplifiedValues.
152  // The cast can be invalid, because SimplifiedValues contains results of SCEV
153  // analysis, which operates on integers (and, e.g., might convert i8* null to
154  // i32 0).
155  if (COp && CastInst::castIsValid(I.getOpcode(), COp, I.getType())) {
156  if (Constant *C =
157  ConstantExpr::getCast(I.getOpcode(), COp, I.getType())) {
158  SimplifiedValues[&I] = C;
159  return true;
160  }
161  }
162 
163  return Base::visitCastInst(I);
164 }
165 
166 /// Try to simplify cmp instruction.
167 bool UnrolledInstAnalyzer::visitCmpInst(CmpInst &I) {
168  Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
169 
170  // First try to handle simplified comparisons.
171  if (!isa<Constant>(LHS))
172  if (Constant *SimpleLHS = SimplifiedValues.lookup(LHS))
173  LHS = SimpleLHS;
174  if (!isa<Constant>(RHS))
175  if (Constant *SimpleRHS = SimplifiedValues.lookup(RHS))
176  RHS = SimpleRHS;
177 
178  if (!isa<Constant>(LHS) && !isa<Constant>(RHS)) {
179  auto SimplifiedLHS = SimplifiedAddresses.find(LHS);
180  if (SimplifiedLHS != SimplifiedAddresses.end()) {
181  auto SimplifiedRHS = SimplifiedAddresses.find(RHS);
182  if (SimplifiedRHS != SimplifiedAddresses.end()) {
183  SimplifiedAddress &LHSAddr = SimplifiedLHS->second;
184  SimplifiedAddress &RHSAddr = SimplifiedRHS->second;
185  if (LHSAddr.Base == RHSAddr.Base) {
186  LHS = LHSAddr.Offset;
187  RHS = RHSAddr.Offset;
188  }
189  }
190  }
191  }
192 
193  if (Constant *CLHS = dyn_cast<Constant>(LHS)) {
194  if (Constant *CRHS = dyn_cast<Constant>(RHS)) {
195  if (CLHS->getType() == CRHS->getType()) {
196  if (Constant *C = ConstantExpr::getCompare(I.getPredicate(), CLHS, CRHS)) {
197  SimplifiedValues[&I] = C;
198  return true;
199  }
200  }
201  }
202  }
203 
204  return Base::visitCmpInst(I);
205 }
206 
207 bool UnrolledInstAnalyzer::visitPHINode(PHINode &PN) {
208  // Run base visitor first. This way we can gather some useful for later
209  // analysis information.
210  if (Base::visitPHINode(PN))
211  return true;
212 
213  // The loop induction PHI nodes are definitionally free.
214  return PN.getParent() == L->getHeader();
215 }
uint64_t CallInst * C
A parsed version of the target data layout string in and methods for querying it. ...
Definition: DataLayout.h:111
This class is the base class for the comparison instructions.
Definition: InstrTypes.h:715
LLVM_NODISCARD std::enable_if_t< !is_simple_type< Y >::value, typename cast_retty< X, const Y >::ret_type > dyn_cast(const Y &Val)
Definition: Casting.h:334
This class represents lattice values for constants.
Definition: AllocatorList.h:23
BinaryOps getOpcode() const
Definition: InstrTypes.h:395
Constant * getElementAsConstant(unsigned i) const
Return a Constant for a specified index&#39;s element.
Definition: Constants.cpp:3030
const SCEV * getPointerBase(const SCEV *V)
Transitively follow the chain of pointer-type operands until reaching a SCEV that does not have a sin...
An instruction for reading from memory.
Definition: Instructions.h:173
static Constant * getCompare(unsigned short pred, Constant *C1, Constant *C2, bool OnlyIfReduced=false)
Return an ICmp or FCmp comparison operator constant expression.
Definition: Constants.cpp:2189
static bool castIsValid(Instruction::CastOps op, Value *S, Type *DstTy)
This method can be used to determine if a cast from S to DstTy using Opcode op is valid or not...
const DataLayout & getDataLayout() const
Get the data layout for the module&#39;s target platform.
Definition: Module.cpp:397
This is the base class for all instructions that perform data casts.
Definition: InstrTypes.h:432
BlockT * getHeader() const
Definition: LoopInfo.h:104
unsigned getActiveBits() const
Compute the number of active bits in the value.
Definition: APInt.h:1593
Instruction::CastOps getOpcode() const
Return the opcode of this CastInst.
Definition: InstrTypes.h:685
Type * getType() const
All values are typed, get the type of this value.
Definition: Value.h:244
This node represents a polynomial recurrence on the trip count of the specified loop.
ConstantDataSequential - A vector or array constant whose element type is a simple 1/2/4/8-byte integ...
Definition: Constants.h:583
const APInt & getValue() const
Return the constant as an APInt value reference.
Definition: Constants.h:131
Type * getElementType() const
Return the element type of the array/vector.
Definition: Constants.cpp:2664
Value * getOperand(unsigned i) const
Definition: User.h:169
This means that we are dealing with an entirely unknown SCEV value, and only represent it as its LLVM...
TypeSize getPrimitiveSizeInBits() const LLVM_READONLY
Return the basic size of this type if it is a primitive type.
Definition: Type.cpp:113
This is an important base class in LLVM.
Definition: Constant.h:41
Value * getPointerOperand()
Definition: Instructions.h:265
const SCEV * getMinusSCEV(const SCEV *LHS, const SCEV *RHS, SCEV::NoWrapFlags Flags=SCEV::FlagAnyWrap, unsigned Depth=0)
Return LHS-RHS. Minus is represented in SCEV as A+B*-1.
This is the shared class of boolean and integer constants.
Definition: Constants.h:77
CHAIN = SC CHAIN, Imm128 - System call.
const Module * getModule() const
Return the module owning the function this instruction belongs to or nullptr it the function does not...
Definition: Instruction.cpp:68
static Constant * getCast(unsigned ops, Constant *C, Type *Ty, bool OnlyIfReduced=false)
Convenience function for getting a Cast operation.
Definition: Constants.cpp:1780
Predicate getPredicate() const
Return the predicate for this instruction.
Definition: InstrTypes.h:802
This class represents an analyzed expression in the program.
#define I(x, y, z)
Definition: MD5.cpp:59
Value * SimplifyBinOp(unsigned Opcode, Value *LHS, Value *RHS, const SimplifyQuery &Q)
Given operands for a BinaryOperator, fold the result or return null.
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
LLVM Value Representation.
Definition: Value.h:74
const SCEV * getSCEV(Value *V)
Return a SCEV expression for the full generality of the specified expression.
bool isSCEVable(Type *Ty) const
Test if values of the given type are analyzable within the SCEV framework.
unsigned getNumElements() const
Return the number of elements in the array or vector.
Definition: Constants.cpp:2690
int64_t getSExtValue() const
Return the constant as a 64-bit integer value after it has been sign extended as appropriate for the ...
Definition: Constants.h:150
const BasicBlock * getParent() const
Definition: Instruction.h:94
This class represents a constant integer value.
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL