Bug Summary

File:lib/Analysis/ScalarEvolution.cpp
Warning:line 10064, column 15
Value stored to 'MaxBECount' during its initialization is never read

Annotated Source Code

1//===- ScalarEvolution.cpp - Scalar Evolution Analysis --------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file contains the implementation of the scalar evolution analysis
11// engine, which is used primarily to analyze expressions involving induction
12// variables in loops.
13//
14// There are several aspects to this library. First is the representation of
15// scalar expressions, which are represented as subclasses of the SCEV class.
16// These classes are used to represent certain types of subexpressions that we
17// can handle. We only create one SCEV of a particular shape, so
18// pointer-comparisons for equality are legal.
19//
20// One important aspect of the SCEV objects is that they are never cyclic, even
21// if there is a cycle in the dataflow for an expression (ie, a PHI node). If
22// the PHI node is one of the idioms that we can represent (e.g., a polynomial
23// recurrence) then we represent it directly as a recurrence node, otherwise we
24// represent it as a SCEVUnknown node.
25//
26// In addition to being able to represent expressions of various types, we also
27// have folders that are used to build the *canonical* representation for a
28// particular expression. These folders are capable of using a variety of
29// rewrite rules to simplify the expressions.
30//
31// Once the folders are defined, we can implement the more interesting
32// higher-level code, such as the code that recognizes PHI nodes of various
33// types, computes the execution count of a loop, etc.
34//
35// TODO: We should use these routines and value representations to implement
36// dependence analysis!
37//
38//===----------------------------------------------------------------------===//
39//
40// There are several good references for the techniques used in this analysis.
41//
42// Chains of recurrences -- a method to expedite the evaluation
43// of closed-form functions
44// Olaf Bachmann, Paul S. Wang, Eugene V. Zima
45//
46// On computational properties of chains of recurrences
47// Eugene V. Zima
48//
49// Symbolic Evaluation of Chains of Recurrences for Loop Optimization
50// Robert A. van Engelen
51//
52// Efficient Symbolic Analysis for Optimizing Compilers
53// Robert A. van Engelen
54//
55// Using the chains of recurrences algebra for data dependence testing and
56// induction variable substitution
57// MS Thesis, Johnie Birch
58//
59//===----------------------------------------------------------------------===//
60
61#include "llvm/Analysis/ScalarEvolution.h"
62#include "llvm/ADT/APInt.h"
63#include "llvm/ADT/ArrayRef.h"
64#include "llvm/ADT/DenseMap.h"
65#include "llvm/ADT/DepthFirstIterator.h"
66#include "llvm/ADT/EquivalenceClasses.h"
67#include "llvm/ADT/FoldingSet.h"
68#include "llvm/ADT/None.h"
69#include "llvm/ADT/Optional.h"
70#include "llvm/ADT/STLExtras.h"
71#include "llvm/ADT/ScopeExit.h"
72#include "llvm/ADT/Sequence.h"
73#include "llvm/ADT/SetVector.h"
74#include "llvm/ADT/SmallPtrSet.h"
75#include "llvm/ADT/SmallSet.h"
76#include "llvm/ADT/SmallVector.h"
77#include "llvm/ADT/Statistic.h"
78#include "llvm/ADT/StringRef.h"
79#include "llvm/Analysis/AssumptionCache.h"
80#include "llvm/Analysis/ConstantFolding.h"
81#include "llvm/Analysis/InstructionSimplify.h"
82#include "llvm/Analysis/LoopInfo.h"
83#include "llvm/Analysis/ScalarEvolutionExpressions.h"
84#include "llvm/Analysis/TargetLibraryInfo.h"
85#include "llvm/Analysis/ValueTracking.h"
86#include "llvm/IR/Argument.h"
87#include "llvm/IR/BasicBlock.h"
88#include "llvm/IR/CFG.h"
89#include "llvm/IR/CallSite.h"
90#include "llvm/IR/Constant.h"
91#include "llvm/IR/ConstantRange.h"
92#include "llvm/IR/Constants.h"
93#include "llvm/IR/DataLayout.h"
94#include "llvm/IR/DerivedTypes.h"
95#include "llvm/IR/Dominators.h"
96#include "llvm/IR/Function.h"
97#include "llvm/IR/GlobalAlias.h"
98#include "llvm/IR/GlobalValue.h"
99#include "llvm/IR/GlobalVariable.h"
100#include "llvm/IR/InstIterator.h"
101#include "llvm/IR/InstrTypes.h"
102#include "llvm/IR/Instruction.h"
103#include "llvm/IR/Instructions.h"
104#include "llvm/IR/IntrinsicInst.h"
105#include "llvm/IR/Intrinsics.h"
106#include "llvm/IR/LLVMContext.h"
107#include "llvm/IR/Metadata.h"
108#include "llvm/IR/Operator.h"
109#include "llvm/IR/PatternMatch.h"
110#include "llvm/IR/Type.h"
111#include "llvm/IR/Use.h"
112#include "llvm/IR/User.h"
113#include "llvm/IR/Value.h"
114#include "llvm/Pass.h"
115#include "llvm/Support/Casting.h"
116#include "llvm/Support/CommandLine.h"
117#include "llvm/Support/Compiler.h"
118#include "llvm/Support/Debug.h"
119#include "llvm/Support/ErrorHandling.h"
120#include "llvm/Support/KnownBits.h"
121#include "llvm/Support/SaveAndRestore.h"
122#include "llvm/Support/raw_ostream.h"
123#include <algorithm>
124#include <cassert>
125#include <climits>
126#include <cstddef>
127#include <cstdint>
128#include <cstdlib>
129#include <map>
130#include <memory>
131#include <tuple>
132#include <utility>
133#include <vector>
134
135using namespace llvm;
136
137#define DEBUG_TYPE"scalar-evolution" "scalar-evolution"
138
139STATISTIC(NumArrayLenItCounts,static llvm::Statistic NumArrayLenItCounts = {"scalar-evolution"
, "NumArrayLenItCounts", "Number of trip counts computed with array length"
, {0}, false}
140 "Number of trip counts computed with array length")static llvm::Statistic NumArrayLenItCounts = {"scalar-evolution"
, "NumArrayLenItCounts", "Number of trip counts computed with array length"
, {0}, false}
;
141STATISTIC(NumTripCountsComputed,static llvm::Statistic NumTripCountsComputed = {"scalar-evolution"
, "NumTripCountsComputed", "Number of loops with predictable loop counts"
, {0}, false}
142 "Number of loops with predictable loop counts")static llvm::Statistic NumTripCountsComputed = {"scalar-evolution"
, "NumTripCountsComputed", "Number of loops with predictable loop counts"
, {0}, false}
;
143STATISTIC(NumTripCountsNotComputed,static llvm::Statistic NumTripCountsNotComputed = {"scalar-evolution"
, "NumTripCountsNotComputed", "Number of loops without predictable loop counts"
, {0}, false}
144 "Number of loops without predictable loop counts")static llvm::Statistic NumTripCountsNotComputed = {"scalar-evolution"
, "NumTripCountsNotComputed", "Number of loops without predictable loop counts"
, {0}, false}
;
145STATISTIC(NumBruteForceTripCountsComputed,static llvm::Statistic NumBruteForceTripCountsComputed = {"scalar-evolution"
, "NumBruteForceTripCountsComputed", "Number of loops with trip counts computed by force"
, {0}, false}
146 "Number of loops with trip counts computed by force")static llvm::Statistic NumBruteForceTripCountsComputed = {"scalar-evolution"
, "NumBruteForceTripCountsComputed", "Number of loops with trip counts computed by force"
, {0}, false}
;
147
148static cl::opt<unsigned>
149MaxBruteForceIterations("scalar-evolution-max-iterations", cl::ReallyHidden,
150 cl::desc("Maximum number of iterations SCEV will "
151 "symbolically execute a constant "
152 "derived loop"),
153 cl::init(100));
154
155// FIXME: Enable this with EXPENSIVE_CHECKS when the test suite is clean.
156static cl::opt<bool> VerifySCEV(
157 "verify-scev", cl::Hidden,
158 cl::desc("Verify ScalarEvolution's backedge taken counts (slow)"));
159static cl::opt<bool>
160 VerifySCEVMap("verify-scev-maps", cl::Hidden,
161 cl::desc("Verify no dangling value in ScalarEvolution's "
162 "ExprValueMap (slow)"));
163
164static cl::opt<unsigned> MulOpsInlineThreshold(
165 "scev-mulops-inline-threshold", cl::Hidden,
166 cl::desc("Threshold for inlining multiplication operands into a SCEV"),
167 cl::init(32));
168
169static cl::opt<unsigned> AddOpsInlineThreshold(
170 "scev-addops-inline-threshold", cl::Hidden,
171 cl::desc("Threshold for inlining addition operands into a SCEV"),
172 cl::init(500));
173
174static cl::opt<unsigned> MaxSCEVCompareDepth(
175 "scalar-evolution-max-scev-compare-depth", cl::Hidden,
176 cl::desc("Maximum depth of recursive SCEV complexity comparisons"),
177 cl::init(32));
178
179static cl::opt<unsigned> MaxSCEVOperationsImplicationDepth(
180 "scalar-evolution-max-scev-operations-implication-depth", cl::Hidden,
181 cl::desc("Maximum depth of recursive SCEV operations implication analysis"),
182 cl::init(2));
183
184static cl::opt<unsigned> MaxValueCompareDepth(
185 "scalar-evolution-max-value-compare-depth", cl::Hidden,
186 cl::desc("Maximum depth of recursive value complexity comparisons"),
187 cl::init(2));
188
189static cl::opt<unsigned>
190 MaxArithDepth("scalar-evolution-max-arith-depth", cl::Hidden,
191 cl::desc("Maximum depth of recursive arithmetics"),
192 cl::init(32));
193
194static cl::opt<unsigned> MaxConstantEvolvingDepth(
195 "scalar-evolution-max-constant-evolving-depth", cl::Hidden,
196 cl::desc("Maximum depth of recursive constant evolving"), cl::init(32));
197
198static cl::opt<unsigned>
199 MaxExtDepth("scalar-evolution-max-ext-depth", cl::Hidden,
200 cl::desc("Maximum depth of recursive SExt/ZExt"),
201 cl::init(8));
202
203static cl::opt<unsigned>
204 MaxAddRecSize("scalar-evolution-max-add-rec-size", cl::Hidden,
205 cl::desc("Max coefficients in AddRec during evolving"),
206 cl::init(16));
207
208//===----------------------------------------------------------------------===//
209// SCEV class definitions
210//===----------------------------------------------------------------------===//
211
212//===----------------------------------------------------------------------===//
213// Implementation of the SCEV class.
214//
215
216#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
217LLVM_DUMP_METHOD__attribute__((noinline)) __attribute__((__used__)) void SCEV::dump() const {
218 print(dbgs());
219 dbgs() << '\n';
220}
221#endif
222
223void SCEV::print(raw_ostream &OS) const {
224 switch (static_cast<SCEVTypes>(getSCEVType())) {
225 case scConstant:
226 cast<SCEVConstant>(this)->getValue()->printAsOperand(OS, false);
227 return;
228 case scTruncate: {
229 const SCEVTruncateExpr *Trunc = cast<SCEVTruncateExpr>(this);
230 const SCEV *Op = Trunc->getOperand();
231 OS << "(trunc " << *Op->getType() << " " << *Op << " to "
232 << *Trunc->getType() << ")";
233 return;
234 }
235 case scZeroExtend: {
236 const SCEVZeroExtendExpr *ZExt = cast<SCEVZeroExtendExpr>(this);
237 const SCEV *Op = ZExt->getOperand();
238 OS << "(zext " << *Op->getType() << " " << *Op << " to "
239 << *ZExt->getType() << ")";
240 return;
241 }
242 case scSignExtend: {
243 const SCEVSignExtendExpr *SExt = cast<SCEVSignExtendExpr>(this);
244 const SCEV *Op = SExt->getOperand();
245 OS << "(sext " << *Op->getType() << " " << *Op << " to "
246 << *SExt->getType() << ")";
247 return;
248 }
249 case scAddRecExpr: {
250 const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(this);
251 OS << "{" << *AR->getOperand(0);
252 for (unsigned i = 1, e = AR->getNumOperands(); i != e; ++i)
253 OS << ",+," << *AR->getOperand(i);
254 OS << "}<";
255 if (AR->hasNoUnsignedWrap())
256 OS << "nuw><";
257 if (AR->hasNoSignedWrap())
258 OS << "nsw><";
259 if (AR->hasNoSelfWrap() &&
260 !AR->getNoWrapFlags((NoWrapFlags)(FlagNUW | FlagNSW)))
261 OS << "nw><";
262 AR->getLoop()->getHeader()->printAsOperand(OS, /*PrintType=*/false);
263 OS << ">";
264 return;
265 }
266 case scAddExpr:
267 case scMulExpr:
268 case scUMaxExpr:
269 case scSMaxExpr: {
270 const SCEVNAryExpr *NAry = cast<SCEVNAryExpr>(this);
271 const char *OpStr = nullptr;
272 switch (NAry->getSCEVType()) {
273 case scAddExpr: OpStr = " + "; break;
274 case scMulExpr: OpStr = " * "; break;
275 case scUMaxExpr: OpStr = " umax "; break;
276 case scSMaxExpr: OpStr = " smax "; break;
277 }
278 OS << "(";
279 for (SCEVNAryExpr::op_iterator I = NAry->op_begin(), E = NAry->op_end();
280 I != E; ++I) {
281 OS << **I;
282 if (std::next(I) != E)
283 OS << OpStr;
284 }
285 OS << ")";
286 switch (NAry->getSCEVType()) {
287 case scAddExpr:
288 case scMulExpr:
289 if (NAry->hasNoUnsignedWrap())
290 OS << "<nuw>";
291 if (NAry->hasNoSignedWrap())
292 OS << "<nsw>";
293 }
294 return;
295 }
296 case scUDivExpr: {
297 const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(this);
298 OS << "(" << *UDiv->getLHS() << " /u " << *UDiv->getRHS() << ")";
299 return;
300 }
301 case scUnknown: {
302 const SCEVUnknown *U = cast<SCEVUnknown>(this);
303 Type *AllocTy;
304 if (U->isSizeOf(AllocTy)) {
305 OS << "sizeof(" << *AllocTy << ")";
306 return;
307 }
308 if (U->isAlignOf(AllocTy)) {
309 OS << "alignof(" << *AllocTy << ")";
310 return;
311 }
312
313 Type *CTy;
314 Constant *FieldNo;
315 if (U->isOffsetOf(CTy, FieldNo)) {
316 OS << "offsetof(" << *CTy << ", ";
317 FieldNo->printAsOperand(OS, false);
318 OS << ")";
319 return;
320 }
321
322 // Otherwise just print it normally.
323 U->getValue()->printAsOperand(OS, false);
324 return;
325 }
326 case scCouldNotCompute:
327 OS << "***COULDNOTCOMPUTE***";
328 return;
329 }
330 llvm_unreachable("Unknown SCEV kind!")::llvm::llvm_unreachable_internal("Unknown SCEV kind!", "/build/llvm-toolchain-snapshot-6.0~svn320940/lib/Analysis/ScalarEvolution.cpp"
, 330)
;
331}
332
333Type *SCEV::getType() const {
334 switch (static_cast<SCEVTypes>(getSCEVType())) {
335 case scConstant:
336 return cast<SCEVConstant>(this)->getType();
337 case scTruncate:
338 case scZeroExtend:
339 case scSignExtend:
340 return cast<SCEVCastExpr>(this)->getType();
341 case scAddRecExpr:
342 case scMulExpr:
343 case scUMaxExpr:
344 case scSMaxExpr:
345 return cast<SCEVNAryExpr>(this)->getType();
346 case scAddExpr:
347 return cast<SCEVAddExpr>(this)->getType();
348 case scUDivExpr:
349 return cast<SCEVUDivExpr>(this)->getType();
350 case scUnknown:
351 return cast<SCEVUnknown>(this)->getType();
352 case scCouldNotCompute:
353 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!")::llvm::llvm_unreachable_internal("Attempt to use a SCEVCouldNotCompute object!"
, "/build/llvm-toolchain-snapshot-6.0~svn320940/lib/Analysis/ScalarEvolution.cpp"
, 353)
;
354 }
355 llvm_unreachable("Unknown SCEV kind!")::llvm::llvm_unreachable_internal("Unknown SCEV kind!", "/build/llvm-toolchain-snapshot-6.0~svn320940/lib/Analysis/ScalarEvolution.cpp"
, 355)
;
356}
357
358bool SCEV::isZero() const {
359 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this))
360 return SC->getValue()->isZero();
361 return false;
362}
363
364bool SCEV::isOne() const {
365 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this))
366 return SC->getValue()->isOne();
367 return false;
368}
369
370bool SCEV::isAllOnesValue() const {
371 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this))
372 return SC->getValue()->isMinusOne();
373 return false;
374}
375
376bool SCEV::isNonConstantNegative() const {
377 const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(this);
378 if (!Mul) return false;
379
380 // If there is a constant factor, it will be first.
381 const SCEVConstant *SC = dyn_cast<SCEVConstant>(Mul->getOperand(0));
382 if (!SC) return false;
383
384 // Return true if the value is negative, this matches things like (-42 * V).
385 return SC->getAPInt().isNegative();
386}
387
388SCEVCouldNotCompute::SCEVCouldNotCompute() :
389 SCEV(FoldingSetNodeIDRef(), scCouldNotCompute) {}
390
391bool SCEVCouldNotCompute::classof(const SCEV *S) {
392 return S->getSCEVType() == scCouldNotCompute;
393}
394
395const SCEV *ScalarEvolution::getConstant(ConstantInt *V) {
396 FoldingSetNodeID ID;
397 ID.AddInteger(scConstant);
398 ID.AddPointer(V);
399 void *IP = nullptr;
400 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
401 SCEV *S = new (SCEVAllocator) SCEVConstant(ID.Intern(SCEVAllocator), V);
402 UniqueSCEVs.InsertNode(S, IP);
403 return S;
404}
405
406const SCEV *ScalarEvolution::getConstant(const APInt &Val) {
407 return getConstant(ConstantInt::get(getContext(), Val));
408}
409
410const SCEV *
411ScalarEvolution::getConstant(Type *Ty, uint64_t V, bool isSigned) {
412 IntegerType *ITy = cast<IntegerType>(getEffectiveSCEVType(Ty));
413 return getConstant(ConstantInt::get(ITy, V, isSigned));
414}
415
416SCEVCastExpr::SCEVCastExpr(const FoldingSetNodeIDRef ID,
417 unsigned SCEVTy, const SCEV *op, Type *ty)
418 : SCEV(ID, SCEVTy), Op(op), Ty(ty) {}
419
420SCEVTruncateExpr::SCEVTruncateExpr(const FoldingSetNodeIDRef ID,
421 const SCEV *op, Type *ty)
422 : SCEVCastExpr(ID, scTruncate, op, ty) {
423 assert((Op->getType()->isIntegerTy() || Op->getType()->isPointerTy()) &&(static_cast <bool> ((Op->getType()->isIntegerTy(
) || Op->getType()->isPointerTy()) && (Ty->isIntegerTy
() || Ty->isPointerTy()) && "Cannot truncate non-integer value!"
) ? void (0) : __assert_fail ("(Op->getType()->isIntegerTy() || Op->getType()->isPointerTy()) && (Ty->isIntegerTy() || Ty->isPointerTy()) && \"Cannot truncate non-integer value!\""
, "/build/llvm-toolchain-snapshot-6.0~svn320940/lib/Analysis/ScalarEvolution.cpp"
, 425, __extension__ __PRETTY_FUNCTION__))
424 (Ty->isIntegerTy() || Ty->isPointerTy()) &&(static_cast <bool> ((Op->getType()->isIntegerTy(
) || Op->getType()->isPointerTy()) && (Ty->isIntegerTy
() || Ty->isPointerTy()) && "Cannot truncate non-integer value!"
) ? void (0) : __assert_fail ("(Op->getType()->isIntegerTy() || Op->getType()->isPointerTy()) && (Ty->isIntegerTy() || Ty->isPointerTy()) && \"Cannot truncate non-integer value!\""
, "/build/llvm-toolchain-snapshot-6.0~svn320940/lib/Analysis/ScalarEvolution.cpp"
, 425, __extension__ __PRETTY_FUNCTION__))
425 "Cannot truncate non-integer value!")(static_cast <bool> ((Op->getType()->isIntegerTy(
) || Op->getType()->isPointerTy()) && (Ty->isIntegerTy
() || Ty->isPointerTy()) && "Cannot truncate non-integer value!"
) ? void (0) : __assert_fail ("(Op->getType()->isIntegerTy() || Op->getType()->isPointerTy()) && (Ty->isIntegerTy() || Ty->isPointerTy()) && \"Cannot truncate non-integer value!\""
, "/build/llvm-toolchain-snapshot-6.0~svn320940/lib/Analysis/ScalarEvolution.cpp"
, 425, __extension__ __PRETTY_FUNCTION__))
;
426}
427
428SCEVZeroExtendExpr::SCEVZeroExtendExpr(const FoldingSetNodeIDRef ID,
429 const SCEV *op, Type *ty)
430 : SCEVCastExpr(ID, scZeroExtend, op, ty) {
431 assert((Op->getType()->isIntegerTy() || Op->getType()->isPointerTy()) &&(static_cast <bool> ((Op->getType()->isIntegerTy(
) || Op->getType()->isPointerTy()) && (Ty->isIntegerTy
() || Ty->isPointerTy()) && "Cannot zero extend non-integer value!"
) ? void (0) : __assert_fail ("(Op->getType()->isIntegerTy() || Op->getType()->isPointerTy()) && (Ty->isIntegerTy() || Ty->isPointerTy()) && \"Cannot zero extend non-integer value!\""
, "/build/llvm-toolchain-snapshot-6.0~svn320940/lib/Analysis/ScalarEvolution.cpp"
, 433, __extension__ __PRETTY_FUNCTION__))
432 (Ty->isIntegerTy() || Ty->isPointerTy()) &&(static_cast <bool> ((Op->getType()->isIntegerTy(
) || Op->getType()->isPointerTy()) && (Ty->isIntegerTy
() || Ty->isPointerTy()) && "Cannot zero extend non-integer value!"
) ? void (0) : __assert_fail ("(Op->getType()->isIntegerTy() || Op->getType()->isPointerTy()) && (Ty->isIntegerTy() || Ty->isPointerTy()) && \"Cannot zero extend non-integer value!\""
, "/build/llvm-toolchain-snapshot-6.0~svn320940/lib/Analysis/ScalarEvolution.cpp"
, 433, __extension__ __PRETTY_FUNCTION__))
433 "Cannot zero extend non-integer value!")(static_cast <bool> ((Op->getType()->isIntegerTy(
) || Op->getType()->isPointerTy()) && (Ty->isIntegerTy
() || Ty->isPointerTy()) && "Cannot zero extend non-integer value!"
) ? void (0) : __assert_fail ("(Op->getType()->isIntegerTy() || Op->getType()->isPointerTy()) && (Ty->isIntegerTy() || Ty->isPointerTy()) && \"Cannot zero extend non-integer value!\""
, "/build/llvm-toolchain-snapshot-6.0~svn320940/lib/Analysis/ScalarEvolution.cpp"
, 433, __extension__ __PRETTY_FUNCTION__))
;
434}
435
436SCEVSignExtendExpr::SCEVSignExtendExpr(const FoldingSetNodeIDRef ID,
437 const SCEV *op, Type *ty)
438 : SCEVCastExpr(ID, scSignExtend, op, ty) {
439 assert((Op->getType()->isIntegerTy() || Op->getType()->isPointerTy()) &&(static_cast <bool> ((Op->getType()->isIntegerTy(
) || Op->getType()->isPointerTy()) && (Ty->isIntegerTy
() || Ty->isPointerTy()) && "Cannot sign extend non-integer value!"
) ? void (0) : __assert_fail ("(Op->getType()->isIntegerTy() || Op->getType()->isPointerTy()) && (Ty->isIntegerTy() || Ty->isPointerTy()) && \"Cannot sign extend non-integer value!\""
, "/build/llvm-toolchain-snapshot-6.0~svn320940/lib/Analysis/ScalarEvolution.cpp"
, 441, __extension__ __PRETTY_FUNCTION__))
440 (Ty->isIntegerTy() || Ty->isPointerTy()) &&(static_cast <bool> ((Op->getType()->isIntegerTy(
) || Op->getType()->isPointerTy()) && (Ty->isIntegerTy
() || Ty->isPointerTy()) && "Cannot sign extend non-integer value!"
) ? void (0) : __assert_fail ("(Op->getType()->isIntegerTy() || Op->getType()->isPointerTy()) && (Ty->isIntegerTy() || Ty->isPointerTy()) && \"Cannot sign extend non-integer value!\""
, "/build/llvm-toolchain-snapshot-6.0~svn320940/lib/Analysis/ScalarEvolution.cpp"
, 441, __extension__ __PRETTY_FUNCTION__))
441 "Cannot sign extend non-integer value!")(static_cast <bool> ((Op->getType()->isIntegerTy(
) || Op->getType()->isPointerTy()) && (Ty->isIntegerTy
() || Ty->isPointerTy()) && "Cannot sign extend non-integer value!"
) ? void (0) : __assert_fail ("(Op->getType()->isIntegerTy() || Op->getType()->isPointerTy()) && (Ty->isIntegerTy() || Ty->isPointerTy()) && \"Cannot sign extend non-integer value!\""
, "/build/llvm-toolchain-snapshot-6.0~svn320940/lib/Analysis/ScalarEvolution.cpp"
, 441, __extension__ __PRETTY_FUNCTION__))
;
442}
443
444void SCEVUnknown::deleted() {
445 // Clear this SCEVUnknown from various maps.
446 SE->forgetMemoizedResults(this);
447
448 // Remove this SCEVUnknown from the uniquing map.
449 SE->UniqueSCEVs.RemoveNode(this);
450
451 // Release the value.
452 setValPtr(nullptr);
453}
454
455void SCEVUnknown::allUsesReplacedWith(Value *New) {
456 // Remove this SCEVUnknown from the uniquing map.
457 SE->UniqueSCEVs.RemoveNode(this);
458
459 // Update this SCEVUnknown to point to the new value. This is needed
460 // because there may still be outstanding SCEVs which still point to
461 // this SCEVUnknown.
462 setValPtr(New);
463}
464
465bool SCEVUnknown::isSizeOf(Type *&AllocTy) const {
466 if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue()))
467 if (VCE->getOpcode() == Instruction::PtrToInt)
468 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0)))
469 if (CE->getOpcode() == Instruction::GetElementPtr &&
470 CE->getOperand(0)->isNullValue() &&
471 CE->getNumOperands() == 2)
472 if (ConstantInt *CI = dyn_cast<ConstantInt>(CE->getOperand(1)))
473 if (CI->isOne()) {
474 AllocTy = cast<PointerType>(CE->getOperand(0)->getType())
475 ->getElementType();
476 return true;
477 }
478
479 return false;
480}
481
482bool SCEVUnknown::isAlignOf(Type *&AllocTy) const {
483 if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue()))
484 if (VCE->getOpcode() == Instruction::PtrToInt)
485 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0)))
486 if (CE->getOpcode() == Instruction::GetElementPtr &&
487 CE->getOperand(0)->isNullValue()) {
488 Type *Ty =
489 cast<PointerType>(CE->getOperand(0)->getType())->getElementType();
490 if (StructType *STy = dyn_cast<StructType>(Ty))
491 if (!STy->isPacked() &&
492 CE->getNumOperands() == 3 &&
493 CE->getOperand(1)->isNullValue()) {
494 if (ConstantInt *CI = dyn_cast<ConstantInt>(CE->getOperand(2)))
495 if (CI->isOne() &&
496 STy->getNumElements() == 2 &&
497 STy->getElementType(0)->isIntegerTy(1)) {
498 AllocTy = STy->getElementType(1);
499 return true;
500 }
501 }
502 }
503
504 return false;
505}
506
507bool SCEVUnknown::isOffsetOf(Type *&CTy, Constant *&FieldNo) const {
508 if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue()))
509 if (VCE->getOpcode() == Instruction::PtrToInt)
510 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0)))
511 if (CE->getOpcode() == Instruction::GetElementPtr &&
512 CE->getNumOperands() == 3 &&
513 CE->getOperand(0)->isNullValue() &&
514 CE->getOperand(1)->isNullValue()) {
515 Type *Ty =
516 cast<PointerType>(CE->getOperand(0)->getType())->getElementType();
517 // Ignore vector types here so that ScalarEvolutionExpander doesn't
518 // emit getelementptrs that index into vectors.
519 if (Ty->isStructTy() || Ty->isArrayTy()) {
520 CTy = Ty;
521 FieldNo = CE->getOperand(2);
522 return true;
523 }
524 }
525
526 return false;
527}
528
529//===----------------------------------------------------------------------===//
530// SCEV Utilities
531//===----------------------------------------------------------------------===//
532
533/// Compare the two values \p LV and \p RV in terms of their "complexity" where
534/// "complexity" is a partial (and somewhat ad-hoc) relation used to order
535/// operands in SCEV expressions. \p EqCache is a set of pairs of values that
536/// have been previously deemed to be "equally complex" by this routine. It is
537/// intended to avoid exponential time complexity in cases like:
538///
539/// %a = f(%x, %y)
540/// %b = f(%a, %a)
541/// %c = f(%b, %b)
542///
543/// %d = f(%x, %y)
544/// %e = f(%d, %d)
545/// %f = f(%e, %e)
546///
547/// CompareValueComplexity(%f, %c)
548///
549/// Since we do not continue running this routine on expression trees once we
550/// have seen unequal values, there is no need to track them in the cache.
551static int
552CompareValueComplexity(EquivalenceClasses<const Value *> &EqCacheValue,
553 const LoopInfo *const LI, Value *LV, Value *RV,
554 unsigned Depth) {
555 if (Depth > MaxValueCompareDepth || EqCacheValue.isEquivalent(LV, RV))
556 return 0;
557
558 // Order pointer values after integer values. This helps SCEVExpander form
559 // GEPs.
560 bool LIsPointer = LV->getType()->isPointerTy(),
561 RIsPointer = RV->getType()->isPointerTy();
562 if (LIsPointer != RIsPointer)
563 return (int)LIsPointer - (int)RIsPointer;
564
565 // Compare getValueID values.
566 unsigned LID = LV->getValueID(), RID = RV->getValueID();
567 if (LID != RID)
568 return (int)LID - (int)RID;
569
570 // Sort arguments by their position.
571 if (const auto *LA = dyn_cast<Argument>(LV)) {
572 const auto *RA = cast<Argument>(RV);
573 unsigned LArgNo = LA->getArgNo(), RArgNo = RA->getArgNo();
574 return (int)LArgNo - (int)RArgNo;
575 }
576
577 if (const auto *LGV = dyn_cast<GlobalValue>(LV)) {
578 const auto *RGV = cast<GlobalValue>(RV);
579
580 const auto IsGVNameSemantic = [&](const GlobalValue *GV) {
581 auto LT = GV->getLinkage();
582 return !(GlobalValue::isPrivateLinkage(LT) ||
583 GlobalValue::isInternalLinkage(LT));
584 };
585
586 // Use the names to distinguish the two values, but only if the
587 // names are semantically important.
588 if (IsGVNameSemantic(LGV) && IsGVNameSemantic(RGV))
589 return LGV->getName().compare(RGV->getName());
590 }
591
592 // For instructions, compare their loop depth, and their operand count. This
593 // is pretty loose.
594 if (const auto *LInst = dyn_cast<Instruction>(LV)) {
595 const auto *RInst = cast<Instruction>(RV);
596
597 // Compare loop depths.
598 const BasicBlock *LParent = LInst->getParent(),
599 *RParent = RInst->getParent();
600 if (LParent != RParent) {
601 unsigned LDepth = LI->getLoopDepth(LParent),
602 RDepth = LI->getLoopDepth(RParent);
603 if (LDepth != RDepth)
604 return (int)LDepth - (int)RDepth;
605 }
606
607 // Compare the number of operands.
608 unsigned LNumOps = LInst->getNumOperands(),
609 RNumOps = RInst->getNumOperands();
610 if (LNumOps != RNumOps)
611 return (int)LNumOps - (int)RNumOps;
612
613 for (unsigned Idx : seq(0u, LNumOps)) {
614 int Result =
615 CompareValueComplexity(EqCacheValue, LI, LInst->getOperand(Idx),
616 RInst->getOperand(Idx), Depth + 1);
617 if (Result != 0)
618 return Result;
619 }
620 }
621
622 EqCacheValue.unionSets(LV, RV);
623 return 0;
624}
625
626// Return negative, zero, or positive, if LHS is less than, equal to, or greater
627// than RHS, respectively. A three-way result allows recursive comparisons to be
628// more efficient.
629static int CompareSCEVComplexity(
630 EquivalenceClasses<const SCEV *> &EqCacheSCEV,
631 EquivalenceClasses<const Value *> &EqCacheValue,
632 const LoopInfo *const LI, const SCEV *LHS, const SCEV *RHS,
633 DominatorTree &DT, unsigned Depth = 0) {
634 // Fast-path: SCEVs are uniqued so we can do a quick equality check.
635 if (LHS == RHS)
636 return 0;
637
638 // Primarily, sort the SCEVs by their getSCEVType().
639 unsigned LType = LHS->getSCEVType(), RType = RHS->getSCEVType();
640 if (LType != RType)
641 return (int)LType - (int)RType;
642
643 if (Depth > MaxSCEVCompareDepth || EqCacheSCEV.isEquivalent(LHS, RHS))
644 return 0;
645 // Aside from the getSCEVType() ordering, the particular ordering
646 // isn't very important except that it's beneficial to be consistent,
647 // so that (a + b) and (b + a) don't end up as different expressions.
648 switch (static_cast<SCEVTypes>(LType)) {
649 case scUnknown: {
650 const SCEVUnknown *LU = cast<SCEVUnknown>(LHS);
651 const SCEVUnknown *RU = cast<SCEVUnknown>(RHS);
652
653 int X = CompareValueComplexity(EqCacheValue, LI, LU->getValue(),
654 RU->getValue(), Depth + 1);
655 if (X == 0)
656 EqCacheSCEV.unionSets(LHS, RHS);
657 return X;
658 }
659
660 case scConstant: {
661 const SCEVConstant *LC = cast<SCEVConstant>(LHS);
662 const SCEVConstant *RC = cast<SCEVConstant>(RHS);
663
664 // Compare constant values.
665 const APInt &LA = LC->getAPInt();
666 const APInt &RA = RC->getAPInt();
667 unsigned LBitWidth = LA.getBitWidth(), RBitWidth = RA.getBitWidth();
668 if (LBitWidth != RBitWidth)
669 return (int)LBitWidth - (int)RBitWidth;
670 return LA.ult(RA) ? -1 : 1;
671 }
672
673 case scAddRecExpr: {
674 const SCEVAddRecExpr *LA = cast<SCEVAddRecExpr>(LHS);
675 const SCEVAddRecExpr *RA = cast<SCEVAddRecExpr>(RHS);
676
677 // There is always a dominance between two recs that are used by one SCEV,
678 // so we can safely sort recs by loop header dominance. We require such
679 // order in getAddExpr.
680 const Loop *LLoop = LA->getLoop(), *RLoop = RA->getLoop();
681 if (LLoop != RLoop) {
682 const BasicBlock *LHead = LLoop->getHeader(), *RHead = RLoop->getHeader();
683 assert(LHead != RHead && "Two loops share the same header?")(static_cast <bool> (LHead != RHead && "Two loops share the same header?"
) ? void (0) : __assert_fail ("LHead != RHead && \"Two loops share the same header?\""
, "/build/llvm-toolchain-snapshot-6.0~svn320940/lib/Analysis/ScalarEvolution.cpp"
, 683, __extension__ __PRETTY_FUNCTION__))
;
684 if (DT.dominates(LHead, RHead))
685 return 1;
686 else
687 assert(DT.dominates(RHead, LHead) &&(static_cast <bool> (DT.dominates(RHead, LHead) &&
"No dominance between recurrences used by one SCEV?") ? void
(0) : __assert_fail ("DT.dominates(RHead, LHead) && \"No dominance between recurrences used by one SCEV?\""
, "/build/llvm-toolchain-snapshot-6.0~svn320940/lib/Analysis/ScalarEvolution.cpp"
, 688, __extension__ __PRETTY_FUNCTION__))
688 "No dominance between recurrences used by one SCEV?")(static_cast <bool> (DT.dominates(RHead, LHead) &&
"No dominance between recurrences used by one SCEV?") ? void
(0) : __assert_fail ("DT.dominates(RHead, LHead) && \"No dominance between recurrences used by one SCEV?\""
, "/build/llvm-toolchain-snapshot-6.0~svn320940/lib/Analysis/ScalarEvolution.cpp"
, 688, __extension__ __PRETTY_FUNCTION__))
;
689 return -1;
690 }
691
692 // Addrec complexity grows with operand count.
693 unsigned LNumOps = LA->getNumOperands(), RNumOps = RA->getNumOperands();
694 if (LNumOps != RNumOps)
695 return (int)LNumOps - (int)RNumOps;
696
697 // Compare NoWrap flags.
698 if (LA->getNoWrapFlags() != RA->getNoWrapFlags())
699 return (int)LA->getNoWrapFlags() - (int)RA->getNoWrapFlags();
700
701 // Lexicographically compare.
702 for (unsigned i = 0; i != LNumOps; ++i) {
703 int X = CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI,
704 LA->getOperand(i), RA->getOperand(i), DT,
705 Depth + 1);
706 if (X != 0)
707 return X;
708 }
709 EqCacheSCEV.unionSets(LHS, RHS);
710 return 0;
711 }
712
713 case scAddExpr:
714 case scMulExpr:
715 case scSMaxExpr:
716 case scUMaxExpr: {
717 const SCEVNAryExpr *LC = cast<SCEVNAryExpr>(LHS);
718 const SCEVNAryExpr *RC = cast<SCEVNAryExpr>(RHS);
719
720 // Lexicographically compare n-ary expressions.
721 unsigned LNumOps = LC->getNumOperands(), RNumOps = RC->getNumOperands();
722 if (LNumOps != RNumOps)
723 return (int)LNumOps - (int)RNumOps;
724
725 // Compare NoWrap flags.
726 if (LC->getNoWrapFlags() != RC->getNoWrapFlags())
727 return (int)LC->getNoWrapFlags() - (int)RC->getNoWrapFlags();
728
729 for (unsigned i = 0; i != LNumOps; ++i) {
730 int X = CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI,
731 LC->getOperand(i), RC->getOperand(i), DT,
732 Depth + 1);
733 if (X != 0)
734 return X;
735 }
736 EqCacheSCEV.unionSets(LHS, RHS);
737 return 0;
738 }
739
740 case scUDivExpr: {
741 const SCEVUDivExpr *LC = cast<SCEVUDivExpr>(LHS);
742 const SCEVUDivExpr *RC = cast<SCEVUDivExpr>(RHS);
743
744 // Lexicographically compare udiv expressions.
745 int X = CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI, LC->getLHS(),
746 RC->getLHS(), DT, Depth + 1);
747 if (X != 0)
748 return X;
749 X = CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI, LC->getRHS(),
750 RC->getRHS(), DT, Depth + 1);
751 if (X == 0)
752 EqCacheSCEV.unionSets(LHS, RHS);
753 return X;
754 }
755
756 case scTruncate:
757 case scZeroExtend:
758 case scSignExtend: {
759 const SCEVCastExpr *LC = cast<SCEVCastExpr>(LHS);
760 const SCEVCastExpr *RC = cast<SCEVCastExpr>(RHS);
761
762 // Compare cast expressions by operand.
763 int X = CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI,
764 LC->getOperand(), RC->getOperand(), DT,
765 Depth + 1);
766 if (X == 0)
767 EqCacheSCEV.unionSets(LHS, RHS);
768 return X;
769 }
770
771 case scCouldNotCompute:
772 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!")::llvm::llvm_unreachable_internal("Attempt to use a SCEVCouldNotCompute object!"
, "/build/llvm-toolchain-snapshot-6.0~svn320940/lib/Analysis/ScalarEvolution.cpp"
, 772)
;
773 }
774 llvm_unreachable("Unknown SCEV kind!")::llvm::llvm_unreachable_internal("Unknown SCEV kind!", "/build/llvm-toolchain-snapshot-6.0~svn320940/lib/Analysis/ScalarEvolution.cpp"
, 774)
;
775}
776
777/// Given a list of SCEV objects, order them by their complexity, and group
778/// objects of the same complexity together by value. When this routine is
779/// finished, we know that any duplicates in the vector are consecutive and that
780/// complexity is monotonically increasing.
781///
782/// Note that we go take special precautions to ensure that we get deterministic
783/// results from this routine. In other words, we don't want the results of
784/// this to depend on where the addresses of various SCEV objects happened to
785/// land in memory.
786static void GroupByComplexity(SmallVectorImpl<const SCEV *> &Ops,
787 LoopInfo *LI, DominatorTree &DT) {
788 if (Ops.size() < 2) return; // Noop
789
790 EquivalenceClasses<const SCEV *> EqCacheSCEV;
791 EquivalenceClasses<const Value *> EqCacheValue;
792 if (Ops.size() == 2) {
793 // This is the common case, which also happens to be trivially simple.
794 // Special case it.
795 const SCEV *&LHS = Ops[0], *&RHS = Ops[1];
796 if (CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI, RHS, LHS, DT) < 0)
797 std::swap(LHS, RHS);
798 return;
799 }
800
801 // Do the rough sort by complexity.
802 std::stable_sort(Ops.begin(), Ops.end(),
803 [&](const SCEV *LHS, const SCEV *RHS) {
804 return CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI,
805 LHS, RHS, DT) < 0;
806 });
807
808 // Now that we are sorted by complexity, group elements of the same
809 // complexity. Note that this is, at worst, N^2, but the vector is likely to
810 // be extremely short in practice. Note that we take this approach because we
811 // do not want to depend on the addresses of the objects we are grouping.
812 for (unsigned i = 0, e = Ops.size(); i != e-2; ++i) {
813 const SCEV *S = Ops[i];
814 unsigned Complexity = S->getSCEVType();
815
816 // If there are any objects of the same complexity and same value as this
817 // one, group them.
818 for (unsigned j = i+1; j != e && Ops[j]->getSCEVType() == Complexity; ++j) {
819 if (Ops[j] == S) { // Found a duplicate.
820 // Move it to immediately after i'th element.
821 std::swap(Ops[i+1], Ops[j]);
822 ++i; // no need to rescan it.
823 if (i == e-2) return; // Done!
824 }
825 }
826 }
827}
828
829// Returns the size of the SCEV S.
830static inline int sizeOfSCEV(const SCEV *S) {
831 struct FindSCEVSize {
832 int Size = 0;
833
834 FindSCEVSize() = default;
835
836 bool follow(const SCEV *S) {
837 ++Size;
838 // Keep looking at all operands of S.
839 return true;
840 }
841
842 bool isDone() const {
843 return false;
844 }
845 };
846
847 FindSCEVSize F;
848 SCEVTraversal<FindSCEVSize> ST(F);
849 ST.visitAll(S);
850 return F.Size;
851}
852
853namespace {
854
855struct SCEVDivision : public SCEVVisitor<SCEVDivision, void> {
856public:
857 // Computes the Quotient and Remainder of the division of Numerator by
858 // Denominator.
859 static void divide(ScalarEvolution &SE, const SCEV *Numerator,
860 const SCEV *Denominator, const SCEV **Quotient,
861 const SCEV **Remainder) {
862 assert(Numerator && Denominator && "Uninitialized SCEV")(static_cast <bool> (Numerator && Denominator &&
"Uninitialized SCEV") ? void (0) : __assert_fail ("Numerator && Denominator && \"Uninitialized SCEV\""
, "/build/llvm-toolchain-snapshot-6.0~svn320940/lib/Analysis/ScalarEvolution.cpp"
, 862, __extension__ __PRETTY_FUNCTION__))
;
863
864 SCEVDivision D(SE, Numerator, Denominator);
865
866 // Check for the trivial case here to avoid having to check for it in the
867 // rest of the code.
868 if (Numerator == Denominator) {
869 *Quotient = D.One;
870 *Remainder = D.Zero;
871 return;
872 }
873
874 if (Numerator->isZero()) {
875 *Quotient = D.Zero;
876 *Remainder = D.Zero;
877 return;
878 }
879
880 // A simple case when N/1. The quotient is N.
881 if (Denominator->isOne()) {
882 *Quotient = Numerator;
883 *Remainder = D.Zero;
884 return;
885 }
886
887 // Split the Denominator when it is a product.
888 if (const SCEVMulExpr *T = dyn_cast<SCEVMulExpr>(Denominator)) {
889 const SCEV *Q, *R;
890 *Quotient = Numerator;
891 for (const SCEV *Op : T->operands()) {
892 divide(SE, *Quotient, Op, &Q, &R);
893 *Quotient = Q;
894
895 // Bail out when the Numerator is not divisible by one of the terms of
896 // the Denominator.
897 if (!R->isZero()) {
898 *Quotient = D.Zero;
899 *Remainder = Numerator;
900 return;
901 }
902 }
903 *Remainder = D.Zero;
904 return;
905 }
906
907 D.visit(Numerator);
908 *Quotient = D.Quotient;
909 *Remainder = D.Remainder;
910 }
911
912 // Except in the trivial case described above, we do not know how to divide
913 // Expr by Denominator for the following functions with empty implementation.
914 void visitTruncateExpr(const SCEVTruncateExpr *Numerator) {}
915 void visitZeroExtendExpr(const SCEVZeroExtendExpr *Numerator) {}
916 void visitSignExtendExpr(const SCEVSignExtendExpr *Numerator) {}
917 void visitUDivExpr(const SCEVUDivExpr *Numerator) {}
918 void visitSMaxExpr(const SCEVSMaxExpr *Numerator) {}
919 void visitUMaxExpr(const SCEVUMaxExpr *Numerator) {}
920 void visitUnknown(const SCEVUnknown *Numerator) {}
921 void visitCouldNotCompute(const SCEVCouldNotCompute *Numerator) {}
922
923 void visitConstant(const SCEVConstant *Numerator) {
924 if (const SCEVConstant *D = dyn_cast<SCEVConstant>(Denominator)) {
925 APInt NumeratorVal = Numerator->getAPInt();
926 APInt DenominatorVal = D->getAPInt();
927 uint32_t NumeratorBW = NumeratorVal.getBitWidth();
928 uint32_t DenominatorBW = DenominatorVal.getBitWidth();
929
930 if (NumeratorBW > DenominatorBW)
931 DenominatorVal = DenominatorVal.sext(NumeratorBW);
932 else if (NumeratorBW < DenominatorBW)
933 NumeratorVal = NumeratorVal.sext(DenominatorBW);
934
935 APInt QuotientVal(NumeratorVal.getBitWidth(), 0);
936 APInt RemainderVal(NumeratorVal.getBitWidth(), 0);
937 APInt::sdivrem(NumeratorVal, DenominatorVal, QuotientVal, RemainderVal);
938 Quotient = SE.getConstant(QuotientVal);
939 Remainder = SE.getConstant(RemainderVal);
940 return;
941 }
942 }
943
944 void visitAddRecExpr(const SCEVAddRecExpr *Numerator) {
945 const SCEV *StartQ, *StartR, *StepQ, *StepR;
946 if (!Numerator->isAffine())
947 return cannotDivide(Numerator);
948 divide(SE, Numerator->getStart(), Denominator, &StartQ, &StartR);
949 divide(SE, Numerator->getStepRecurrence(SE), Denominator, &StepQ, &StepR);
950 // Bail out if the types do not match.
951 Type *Ty = Denominator->getType();
952 if (Ty != StartQ->getType() || Ty != StartR->getType() ||
953 Ty != StepQ->getType() || Ty != StepR->getType())
954 return cannotDivide(Numerator);
955 Quotient = SE.getAddRecExpr(StartQ, StepQ, Numerator->getLoop(),
956 Numerator->getNoWrapFlags());
957 Remainder = SE.getAddRecExpr(StartR, StepR, Numerator->getLoop(),
958 Numerator->getNoWrapFlags());
959 }
960
961 void visitAddExpr(const SCEVAddExpr *Numerator) {
962 SmallVector<const SCEV *, 2> Qs, Rs;
963 Type *Ty = Denominator->getType();
964
965 for (const SCEV *Op : Numerator->operands()) {
966 const SCEV *Q, *R;
967 divide(SE, Op, Denominator, &Q, &R);
968
969 // Bail out if types do not match.
970 if (Ty != Q->getType() || Ty != R->getType())
971 return cannotDivide(Numerator);
972
973 Qs.push_back(Q);
974 Rs.push_back(R);
975 }
976
977 if (Qs.size() == 1) {
978 Quotient = Qs[0];
979 Remainder = Rs[0];
980 return;
981 }
982
983 Quotient = SE.getAddExpr(Qs);
984 Remainder = SE.getAddExpr(Rs);
985 }
986
987 void visitMulExpr(const SCEVMulExpr *Numerator) {
988 SmallVector<const SCEV *, 2> Qs;
989 Type *Ty = Denominator->getType();
990
991 bool FoundDenominatorTerm = false;
992 for (const SCEV *Op : Numerator->operands()) {
993 // Bail out if types do not match.
994 if (Ty != Op->getType())
995 return cannotDivide(Numerator);
996
997 if (FoundDenominatorTerm) {
998 Qs.push_back(Op);
999 continue;
1000 }
1001
1002 // Check whether Denominator divides one of the product operands.
1003 const SCEV *Q, *R;
1004 divide(SE, Op, Denominator, &Q, &R);
1005 if (!R->isZero()) {
1006 Qs.push_back(Op);
1007 continue;
1008 }
1009
1010 // Bail out if types do not match.
1011 if (Ty != Q->getType())
1012 return cannotDivide(Numerator);
1013
1014 FoundDenominatorTerm = true;
1015 Qs.push_back(Q);
1016 }
1017
1018 if (FoundDenominatorTerm) {
1019 Remainder = Zero;
1020 if (Qs.size() == 1)
1021 Quotient = Qs[0];
1022 else
1023 Quotient = SE.getMulExpr(Qs);
1024 return;
1025 }
1026
1027 if (!isa<SCEVUnknown>(Denominator))
1028 return cannotDivide(Numerator);
1029
1030 // The Remainder is obtained by replacing Denominator by 0 in Numerator.
1031 ValueToValueMap RewriteMap;
1032 RewriteMap[cast<SCEVUnknown>(Denominator)->getValue()] =
1033 cast<SCEVConstant>(Zero)->getValue();
1034 Remainder = SCEVParameterRewriter::rewrite(Numerator, SE, RewriteMap, true);
1035
1036 if (Remainder->isZero()) {
1037 // The Quotient is obtained by replacing Denominator by 1 in Numerator.
1038 RewriteMap[cast<SCEVUnknown>(Denominator)->getValue()] =
1039 cast<SCEVConstant>(One)->getValue();
1040 Quotient =
1041 SCEVParameterRewriter::rewrite(Numerator, SE, RewriteMap, true);
1042 return;
1043 }
1044
1045 // Quotient is (Numerator - Remainder) divided by Denominator.
1046 const SCEV *Q, *R;
1047 const SCEV *Diff = SE.getMinusSCEV(Numerator, Remainder);
1048 // This SCEV does not seem to simplify: fail the division here.
1049 if (sizeOfSCEV(Diff) > sizeOfSCEV(Numerator))
1050 return cannotDivide(Numerator);
1051 divide(SE, Diff, Denominator, &Q, &R);
1052 if (R != Zero)
1053 return cannotDivide(Numerator);
1054 Quotient = Q;
1055 }
1056
1057private:
1058 SCEVDivision(ScalarEvolution &S, const SCEV *Numerator,
1059 const SCEV *Denominator)
1060 : SE(S), Denominator(Denominator) {
1061 Zero = SE.getZero(Denominator->getType());
1062 One = SE.getOne(Denominator->getType());
1063
1064 // We generally do not know how to divide Expr by Denominator. We
1065 // initialize the division to a "cannot divide" state to simplify the rest
1066 // of the code.
1067 cannotDivide(Numerator);
1068 }
1069
1070 // Convenience function for giving up on the division. We set the quotient to
1071 // be equal to zero and the remainder to be equal to the numerator.
1072 void cannotDivide(const SCEV *Numerator) {
1073 Quotient = Zero;
1074 Remainder = Numerator;
1075 }
1076
1077 ScalarEvolution &SE;
1078 const SCEV *Denominator, *Quotient, *Remainder, *Zero, *One;
1079};
1080
1081} // end anonymous namespace
1082
1083//===----------------------------------------------------------------------===//
1084// Simple SCEV method implementations
1085//===----------------------------------------------------------------------===//
1086
1087/// Compute BC(It, K). The result has width W. Assume, K > 0.
1088static const SCEV *BinomialCoefficient(const SCEV *It, unsigned K,
1089 ScalarEvolution &SE,
1090 Type *ResultTy) {
1091 // Handle the simplest case efficiently.
1092 if (K == 1)
1093 return SE.getTruncateOrZeroExtend(It, ResultTy);
1094
1095 // We are using the following formula for BC(It, K):
1096 //
1097 // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / K!
1098 //
1099 // Suppose, W is the bitwidth of the return value. We must be prepared for
1100 // overflow. Hence, we must assure that the result of our computation is
1101 // equal to the accurate one modulo 2^W. Unfortunately, division isn't
1102 // safe in modular arithmetic.
1103 //
1104 // However, this code doesn't use exactly that formula; the formula it uses
1105 // is something like the following, where T is the number of factors of 2 in
1106 // K! (i.e. trailing zeros in the binary representation of K!), and ^ is
1107 // exponentiation:
1108 //
1109 // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / 2^T / (K! / 2^T)
1110 //
1111 // This formula is trivially equivalent to the previous formula. However,
1112 // this formula can be implemented much more efficiently. The trick is that
1113 // K! / 2^T is odd, and exact division by an odd number *is* safe in modular
1114 // arithmetic. To do exact division in modular arithmetic, all we have
1115 // to do is multiply by the inverse. Therefore, this step can be done at
1116 // width W.
1117 //
1118 // The next issue is how to safely do the division by 2^T. The way this
1119 // is done is by doing the multiplication step at a width of at least W + T
1120 // bits. This way, the bottom W+T bits of the product are accurate. Then,
1121 // when we perform the division by 2^T (which is equivalent to a right shift
1122 // by T), the bottom W bits are accurate. Extra bits are okay; they'll get
1123 // truncated out after the division by 2^T.
1124 //
1125 // In comparison to just directly using the first formula, this technique
1126 // is much more efficient; using the first formula requires W * K bits,
1127 // but this formula less than W + K bits. Also, the first formula requires
1128 // a division step, whereas this formula only requires multiplies and shifts.
1129 //
1130 // It doesn't matter whether the subtraction step is done in the calculation
1131 // width or the input iteration count's width; if the subtraction overflows,
1132 // the result must be zero anyway. We prefer here to do it in the width of
1133 // the induction variable because it helps a lot for certain cases; CodeGen
1134 // isn't smart enough to ignore the overflow, which leads to much less
1135 // efficient code if the width of the subtraction is wider than the native
1136 // register width.
1137 //
1138 // (It's possible to not widen at all by pulling out factors of 2 before
1139 // the multiplication; for example, K=2 can be calculated as
1140 // It/2*(It+(It*INT_MIN/INT_MIN)+-1). However, it requires
1141 // extra arithmetic, so it's not an obvious win, and it gets
1142 // much more complicated for K > 3.)
1143
1144 // Protection from insane SCEVs; this bound is conservative,
1145 // but it probably doesn't matter.
1146 if (K > 1000)
1147 return SE.getCouldNotCompute();
1148
1149 unsigned W = SE.getTypeSizeInBits(ResultTy);
1150
1151 // Calculate K! / 2^T and T; we divide out the factors of two before
1152 // multiplying for calculating K! / 2^T to avoid overflow.
1153 // Other overflow doesn't matter because we only care about the bottom
1154 // W bits of the result.
1155 APInt OddFactorial(W, 1);
1156 unsigned T = 1;
1157 for (unsigned i = 3; i <= K; ++i) {
1158 APInt Mult(W, i);
1159 unsigned TwoFactors = Mult.countTrailingZeros();
1160 T += TwoFactors;
1161 Mult.lshrInPlace(TwoFactors);
1162 OddFactorial *= Mult;
1163 }
1164
1165 // We need at least W + T bits for the multiplication step
1166 unsigned CalculationBits = W + T;
1167
1168 // Calculate 2^T, at width T+W.
1169 APInt DivFactor = APInt::getOneBitSet(CalculationBits, T);
1170
1171 // Calculate the multiplicative inverse of K! / 2^T;
1172 // this multiplication factor will perform the exact division by
1173 // K! / 2^T.
1174 APInt Mod = APInt::getSignedMinValue(W+1);
1175 APInt MultiplyFactor = OddFactorial.zext(W+1);
1176 MultiplyFactor = MultiplyFactor.multiplicativeInverse(Mod);
1177 MultiplyFactor = MultiplyFactor.trunc(W);
1178
1179 // Calculate the product, at width T+W
1180 IntegerType *CalculationTy = IntegerType::get(SE.getContext(),
1181 CalculationBits);
1182 const SCEV *Dividend = SE.getTruncateOrZeroExtend(It, CalculationTy);
1183 for (unsigned i = 1; i != K; ++i) {
1184 const SCEV *S = SE.getMinusSCEV(It, SE.getConstant(It->getType(), i));
1185 Dividend = SE.getMulExpr(Dividend,
1186 SE.getTruncateOrZeroExtend(S, CalculationTy));
1187 }
1188
1189 // Divide by 2^T
1190 const SCEV *DivResult = SE.getUDivExpr(Dividend, SE.getConstant(DivFactor));
1191
1192 // Truncate the result, and divide by K! / 2^T.
1193
1194 return SE.getMulExpr(SE.getConstant(MultiplyFactor),
1195 SE.getTruncateOrZeroExtend(DivResult, ResultTy));
1196}
1197
1198/// Return the value of this chain of recurrences at the specified iteration
1199/// number. We can evaluate this recurrence by multiplying each element in the
1200/// chain by the binomial coefficient corresponding to it. In other words, we
1201/// can evaluate {A,+,B,+,C,+,D} as:
1202///
1203/// A*BC(It, 0) + B*BC(It, 1) + C*BC(It, 2) + D*BC(It, 3)
1204///
1205/// where BC(It, k) stands for binomial coefficient.
1206const SCEV *SCEVAddRecExpr::evaluateAtIteration(const SCEV *It,
1207 ScalarEvolution &SE) const {
1208 const SCEV *Result = getStart();
1209 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
1210 // The computation is correct in the face of overflow provided that the
1211 // multiplication is performed _after_ the evaluation of the binomial
1212 // coefficient.
1213 const SCEV *Coeff = BinomialCoefficient(It, i, SE, getType());
1214 if (isa<SCEVCouldNotCompute>(Coeff))
1215 return Coeff;
1216
1217 Result = SE.getAddExpr(Result, SE.getMulExpr(getOperand(i), Coeff));
1218 }
1219 return Result;
1220}
1221
1222//===----------------------------------------------------------------------===//
1223// SCEV Expression folder implementations
1224//===----------------------------------------------------------------------===//
1225
1226const SCEV *ScalarEvolution::getTruncateExpr(const SCEV *Op,
1227 Type *Ty) {
1228 assert(getTypeSizeInBits(Op->getType()) > getTypeSizeInBits(Ty) &&(static_cast <bool> (getTypeSizeInBits(Op->getType()
) > getTypeSizeInBits(Ty) && "This is not a truncating conversion!"
) ? void (0) : __assert_fail ("getTypeSizeInBits(Op->getType()) > getTypeSizeInBits(Ty) && \"This is not a truncating conversion!\""
, "/build/llvm-toolchain-snapshot-6.0~svn320940/lib/Analysis/ScalarEvolution.cpp"
, 1229, __extension__ __PRETTY_FUNCTION__))
1229 "This is not a truncating conversion!")(static_cast <bool> (getTypeSizeInBits(Op->getType()
) > getTypeSizeInBits(Ty) && "This is not a truncating conversion!"
) ? void (0) : __assert_fail ("getTypeSizeInBits(Op->getType()) > getTypeSizeInBits(Ty) && \"This is not a truncating conversion!\""
, "/build/llvm-toolchain-snapshot-6.0~svn320940/lib/Analysis/ScalarEvolution.cpp"
, 1229, __extension__ __PRETTY_FUNCTION__))
;
1230 assert(isSCEVable(Ty) &&(static_cast <bool> (isSCEVable(Ty) && "This is not a conversion to a SCEVable type!"
) ? void (0) : __assert_fail ("isSCEVable(Ty) && \"This is not a conversion to a SCEVable type!\""
, "/build/llvm-toolchain-snapshot-6.0~svn320940/lib/Analysis/ScalarEvolution.cpp"
, 1231, __extension__ __PRETTY_FUNCTION__))
1231 "This is not a conversion to a SCEVable type!")(static_cast <bool> (isSCEVable(Ty) && "This is not a conversion to a SCEVable type!"
) ? void (0) : __assert_fail ("isSCEVable(Ty) && \"This is not a conversion to a SCEVable type!\""
, "/build/llvm-toolchain-snapshot-6.0~svn320940/lib/Analysis/ScalarEvolution.cpp"
, 1231, __extension__ __PRETTY_FUNCTION__))
;
1232 Ty = getEffectiveSCEVType(Ty);
1233
1234 FoldingSetNodeID ID;
1235 ID.AddInteger(scTruncate);
1236 ID.AddPointer(Op);
1237 ID.AddPointer(Ty);
1238 void *IP = nullptr;
1239 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1240
1241 // Fold if the operand is constant.
1242 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
1243 return getConstant(
1244 cast<ConstantInt>(ConstantExpr::getTrunc(SC->getValue(), Ty)));
1245
1246 // trunc(trunc(x)) --> trunc(x)
1247 if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op))
1248 return getTruncateExpr(ST->getOperand(), Ty);
1249
1250 // trunc(sext(x)) --> sext(x) if widening or trunc(x) if narrowing
1251 if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op))
1252 return getTruncateOrSignExtend(SS->getOperand(), Ty);
1253
1254 // trunc(zext(x)) --> zext(x) if widening or trunc(x) if narrowing
1255 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
1256 return getTruncateOrZeroExtend(SZ->getOperand(), Ty);
1257
1258 // trunc(x1+x2+...+xN) --> trunc(x1)+trunc(x2)+...+trunc(xN) if we can
1259 // eliminate all the truncates, or we replace other casts with truncates.
1260 if (const SCEVAddExpr *SA = dyn_cast<SCEVAddExpr>(Op)) {
1261 SmallVector<const SCEV *, 4> Operands;
1262 bool hasTrunc = false;
1263 for (unsigned i = 0, e = SA->getNumOperands(); i != e && !hasTrunc; ++i) {
1264 const SCEV *S = getTruncateExpr(SA->getOperand(i), Ty);
1265 if (!isa<SCEVCastExpr>(SA->getOperand(i)))
1266 hasTrunc = isa<SCEVTruncateExpr>(S);
1267 Operands.push_back(S);
1268 }
1269 if (!hasTrunc)
1270 return getAddExpr(Operands);
1271 UniqueSCEVs.FindNodeOrInsertPos(ID, IP); // Mutates IP, returns NULL.
1272 }
1273
1274 // trunc(x1*x2*...*xN) --> trunc(x1)*trunc(x2)*...*trunc(xN) if we can
1275 // eliminate all the truncates, or we replace other casts with truncates.
1276 if (const SCEVMulExpr *SM = dyn_cast<SCEVMulExpr>(Op)) {
1277 SmallVector<const SCEV *, 4> Operands;
1278 bool hasTrunc = false;
1279 for (unsigned i = 0, e = SM->getNumOperands(); i != e && !hasTrunc; ++i) {
1280 const SCEV *S = getTruncateExpr(SM->getOperand(i), Ty);
1281 if (!isa<SCEVCastExpr>(SM->getOperand(i)))
1282 hasTrunc = isa<SCEVTruncateExpr>(S);
1283 Operands.push_back(S);
1284 }
1285 if (!hasTrunc)
1286 return getMulExpr(Operands);
1287 UniqueSCEVs.FindNodeOrInsertPos(ID, IP); // Mutates IP, returns NULL.
1288 }
1289
1290 // If the input value is a chrec scev, truncate the chrec's operands.
1291 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) {
1292 SmallVector<const SCEV *, 4> Operands;
1293 for (const SCEV *Op : AddRec->operands())
1294 Operands.push_back(getTruncateExpr(Op, Ty));
1295 return getAddRecExpr(Operands, AddRec->getLoop(), SCEV::FlagAnyWrap);
1296 }
1297
1298 // The cast wasn't folded; create an explicit cast node. We can reuse
1299 // the existing insert position since if we get here, we won't have
1300 // made any changes which would invalidate it.
1301 SCEV *S = new (SCEVAllocator) SCEVTruncateExpr(ID.Intern(SCEVAllocator),
1302 Op, Ty);
1303 UniqueSCEVs.InsertNode(S, IP);
1304 addToLoopUseLists(S);
1305 return S;
1306}
1307
1308// Get the limit of a recurrence such that incrementing by Step cannot cause
1309// signed overflow as long as the value of the recurrence within the
1310// loop does not exceed this limit before incrementing.
1311static const SCEV *getSignedOverflowLimitForStep(const SCEV *Step,
1312 ICmpInst::Predicate *Pred,
1313 ScalarEvolution *SE) {
1314 unsigned BitWidth = SE->getTypeSizeInBits(Step->getType());
1315 if (SE->isKnownPositive(Step)) {
1316 *Pred = ICmpInst::ICMP_SLT;
1317 return SE->getConstant(APInt::getSignedMinValue(BitWidth) -
1318 SE->getSignedRangeMax(Step));
1319 }
1320 if (SE->isKnownNegative(Step)) {
1321 *Pred = ICmpInst::ICMP_SGT;
1322 return SE->getConstant(APInt::getSignedMaxValue(BitWidth) -
1323 SE->getSignedRangeMin(Step));
1324 }
1325 return nullptr;
1326}
1327
1328// Get the limit of a recurrence such that incrementing by Step cannot cause
1329// unsigned overflow as long as the value of the recurrence within the loop does
1330// not exceed this limit before incrementing.
1331static const SCEV *getUnsignedOverflowLimitForStep(const SCEV *Step,
1332 ICmpInst::Predicate *Pred,
1333 ScalarEvolution *SE) {
1334 unsigned BitWidth = SE->getTypeSizeInBits(Step->getType());
1335 *Pred = ICmpInst::ICMP_ULT;
1336
1337 return SE->getConstant(APInt::getMinValue(BitWidth) -
1338 SE->getUnsignedRangeMax(Step));
1339}
1340
1341namespace {
1342
1343struct ExtendOpTraitsBase {
1344 typedef const SCEV *(ScalarEvolution::*GetExtendExprTy)(const SCEV *, Type *,
1345 unsigned);
1346};
1347
1348// Used to make code generic over signed and unsigned overflow.
1349template <typename ExtendOp> struct ExtendOpTraits {
1350 // Members present:
1351 //
1352 // static const SCEV::NoWrapFlags WrapType;
1353 //
1354 // static const ExtendOpTraitsBase::GetExtendExprTy GetExtendExpr;
1355 //
1356 // static const SCEV *getOverflowLimitForStep(const SCEV *Step,
1357 // ICmpInst::Predicate *Pred,
1358 // ScalarEvolution *SE);
1359};
1360
1361template <>
1362struct ExtendOpTraits<SCEVSignExtendExpr> : public ExtendOpTraitsBase {
1363 static const SCEV::NoWrapFlags WrapType = SCEV::FlagNSW;
1364
1365 static const GetExtendExprTy GetExtendExpr;
1366
1367 static const SCEV *getOverflowLimitForStep(const SCEV *Step,
1368 ICmpInst::Predicate *Pred,
1369 ScalarEvolution *SE) {
1370 return getSignedOverflowLimitForStep(Step, Pred, SE);
1371 }
1372};
1373
1374const ExtendOpTraitsBase::GetExtendExprTy ExtendOpTraits<
1375 SCEVSignExtendExpr>::GetExtendExpr = &ScalarEvolution::getSignExtendExpr;
1376
1377template <>
1378struct ExtendOpTraits<SCEVZeroExtendExpr> : public ExtendOpTraitsBase {
1379 static const SCEV::NoWrapFlags WrapType = SCEV::FlagNUW;
1380
1381 static const GetExtendExprTy GetExtendExpr;
1382
1383 static const SCEV *getOverflowLimitForStep(const SCEV *Step,
1384 ICmpInst::Predicate *Pred,
1385 ScalarEvolution *SE) {
1386 return getUnsignedOverflowLimitForStep(Step, Pred, SE);
1387 }
1388};
1389
1390const ExtendOpTraitsBase::GetExtendExprTy ExtendOpTraits<
1391 SCEVZeroExtendExpr>::GetExtendExpr = &ScalarEvolution::getZeroExtendExpr;
1392
1393} // end anonymous namespace
1394
1395// The recurrence AR has been shown to have no signed/unsigned wrap or something
1396// close to it. Typically, if we can prove NSW/NUW for AR, then we can just as
1397// easily prove NSW/NUW for its preincrement or postincrement sibling. This
1398// allows normalizing a sign/zero extended AddRec as such: {sext/zext(Step +
1399// Start),+,Step} => {(Step + sext/zext(Start),+,Step} As a result, the
1400// expression "Step + sext/zext(PreIncAR)" is congruent with
1401// "sext/zext(PostIncAR)"
1402template <typename ExtendOpTy>
1403static const SCEV *getPreStartForExtend(const SCEVAddRecExpr *AR, Type *Ty,
1404 ScalarEvolution *SE, unsigned Depth) {
1405 auto WrapType = ExtendOpTraits<ExtendOpTy>::WrapType;
1406 auto GetExtendExpr = ExtendOpTraits<ExtendOpTy>::GetExtendExpr;
1407
1408 const Loop *L = AR->getLoop();
1409 const SCEV *Start = AR->getStart();
1410 const SCEV *Step = AR->getStepRecurrence(*SE);
1411
1412 // Check for a simple looking step prior to loop entry.
1413 const SCEVAddExpr *SA = dyn_cast<SCEVAddExpr>(Start);
1414 if (!SA)
1415 return nullptr;
1416
1417 // Create an AddExpr for "PreStart" after subtracting Step. Full SCEV
1418 // subtraction is expensive. For this purpose, perform a quick and dirty
1419 // difference, by checking for Step in the operand list.
1420 SmallVector<const SCEV *, 4> DiffOps;
1421 for (const SCEV *Op : SA->operands())
1422 if (Op != Step)
1423 DiffOps.push_back(Op);
1424
1425 if (DiffOps.size() == SA->getNumOperands())
1426 return nullptr;
1427
1428 // Try to prove `WrapType` (SCEV::FlagNSW or SCEV::FlagNUW) on `PreStart` +
1429 // `Step`:
1430
1431 // 1. NSW/NUW flags on the step increment.
1432 auto PreStartFlags =
1433 ScalarEvolution::maskFlags(SA->getNoWrapFlags(), SCEV::FlagNUW);
1434 const SCEV *PreStart = SE->getAddExpr(DiffOps, PreStartFlags);
1435 const SCEVAddRecExpr *PreAR = dyn_cast<SCEVAddRecExpr>(
1436 SE->getAddRecExpr(PreStart, Step, L, SCEV::FlagAnyWrap));
1437
1438 // "{S,+,X} is <nsw>/<nuw>" and "the backedge is taken at least once" implies
1439 // "S+X does not sign/unsign-overflow".
1440 //
1441
1442 const SCEV *BECount = SE->getBackedgeTakenCount(L);
1443 if (PreAR && PreAR->getNoWrapFlags(WrapType) &&
1444 !isa<SCEVCouldNotCompute>(BECount) && SE->isKnownPositive(BECount))
1445 return PreStart;
1446
1447 // 2. Direct overflow check on the step operation's expression.
1448 unsigned BitWidth = SE->getTypeSizeInBits(AR->getType());
1449 Type *WideTy = IntegerType::get(SE->getContext(), BitWidth * 2);
1450 const SCEV *OperandExtendedStart =
1451 SE->getAddExpr((SE->*GetExtendExpr)(PreStart, WideTy, Depth),
1452 (SE->*GetExtendExpr)(Step, WideTy, Depth));
1453 if ((SE->*GetExtendExpr)(Start, WideTy, Depth) == OperandExtendedStart) {
1454 if (PreAR && AR->getNoWrapFlags(WrapType)) {
1455 // If we know `AR` == {`PreStart`+`Step`,+,`Step`} is `WrapType` (FlagNSW
1456 // or FlagNUW) and that `PreStart` + `Step` is `WrapType` too, then
1457 // `PreAR` == {`PreStart`,+,`Step`} is also `WrapType`. Cache this fact.
1458 const_cast<SCEVAddRecExpr *>(PreAR)->setNoWrapFlags(WrapType);
1459 }
1460 return PreStart;
1461 }
1462
1463 // 3. Loop precondition.
1464 ICmpInst::Predicate Pred;
1465 const SCEV *OverflowLimit =
1466 ExtendOpTraits<ExtendOpTy>::getOverflowLimitForStep(Step, &Pred, SE);
1467
1468 if (OverflowLimit &&
1469 SE->isLoopEntryGuardedByCond(L, Pred, PreStart, OverflowLimit))
1470 return PreStart;
1471
1472 return nullptr;
1473}
1474
1475// Get the normalized zero or sign extended expression for this AddRec's Start.
1476template <typename ExtendOpTy>
1477static const SCEV *getExtendAddRecStart(const SCEVAddRecExpr *AR, Type *Ty,
1478 ScalarEvolution *SE,
1479 unsigned Depth) {
1480 auto GetExtendExpr = ExtendOpTraits<ExtendOpTy>::GetExtendExpr;
1481
1482 const SCEV *PreStart = getPreStartForExtend<ExtendOpTy>(AR, Ty, SE, Depth);
1483 if (!PreStart)
1484 return (SE->*GetExtendExpr)(AR->getStart(), Ty, Depth);
1485
1486 return SE->getAddExpr((SE->*GetExtendExpr)(AR->getStepRecurrence(*SE), Ty,
1487 Depth),
1488 (SE->*GetExtendExpr)(PreStart, Ty, Depth));
1489}
1490
1491// Try to prove away overflow by looking at "nearby" add recurrences. A
1492// motivating example for this rule: if we know `{0,+,4}` is `ult` `-1` and it
1493// does not itself wrap then we can conclude that `{1,+,4}` is `nuw`.
1494//
1495// Formally:
1496//
1497// {S,+,X} == {S-T,+,X} + T
1498// => Ext({S,+,X}) == Ext({S-T,+,X} + T)
1499//
1500// If ({S-T,+,X} + T) does not overflow ... (1)
1501//
1502// RHS == Ext({S-T,+,X} + T) == Ext({S-T,+,X}) + Ext(T)
1503//
1504// If {S-T,+,X} does not overflow ... (2)
1505//
1506// RHS == Ext({S-T,+,X}) + Ext(T) == {Ext(S-T),+,Ext(X)} + Ext(T)
1507// == {Ext(S-T)+Ext(T),+,Ext(X)}
1508//
1509// If (S-T)+T does not overflow ... (3)
1510//
1511// RHS == {Ext(S-T)+Ext(T),+,Ext(X)} == {Ext(S-T+T),+,Ext(X)}
1512// == {Ext(S),+,Ext(X)} == LHS
1513//
1514// Thus, if (1), (2) and (3) are true for some T, then
1515// Ext({S,+,X}) == {Ext(S),+,Ext(X)}
1516//
1517// (3) is implied by (1) -- "(S-T)+T does not overflow" is simply "({S-T,+,X}+T)
1518// does not overflow" restricted to the 0th iteration. Therefore we only need
1519// to check for (1) and (2).
1520//
1521// In the current context, S is `Start`, X is `Step`, Ext is `ExtendOpTy` and T
1522// is `Delta` (defined below).
1523template <typename ExtendOpTy>
1524bool ScalarEvolution::proveNoWrapByVaryingStart(const SCEV *Start,
1525 const SCEV *Step,
1526 const Loop *L) {
1527 auto WrapType = ExtendOpTraits<ExtendOpTy>::WrapType;
1528
1529 // We restrict `Start` to a constant to prevent SCEV from spending too much
1530 // time here. It is correct (but more expensive) to continue with a
1531 // non-constant `Start` and do a general SCEV subtraction to compute
1532 // `PreStart` below.
1533 const SCEVConstant *StartC = dyn_cast<SCEVConstant>(Start);
1534 if (!StartC)
1535 return false;
1536
1537 APInt StartAI = StartC->getAPInt();
1538
1539 for (unsigned Delta : {-2, -1, 1, 2}) {
1540 const SCEV *PreStart = getConstant(StartAI - Delta);
1541
1542 FoldingSetNodeID ID;
1543 ID.AddInteger(scAddRecExpr);
1544 ID.AddPointer(PreStart);
1545 ID.AddPointer(Step);
1546 ID.AddPointer(L);
1547 void *IP = nullptr;
1548 const auto *PreAR =
1549 static_cast<SCEVAddRecExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
1550
1551 // Give up if we don't already have the add recurrence we need because
1552 // actually constructing an add recurrence is relatively expensive.
1553 if (PreAR && PreAR->getNoWrapFlags(WrapType)) { // proves (2)
1554 const SCEV *DeltaS = getConstant(StartC->getType(), Delta);
1555 ICmpInst::Predicate Pred = ICmpInst::BAD_ICMP_PREDICATE;
1556 const SCEV *Limit = ExtendOpTraits<ExtendOpTy>::getOverflowLimitForStep(
1557 DeltaS, &Pred, this);
1558 if (Limit && isKnownPredicate(Pred, PreAR, Limit)) // proves (1)
1559 return true;
1560 }
1561 }
1562
1563 return false;
1564}
1565
1566const SCEV *
1567ScalarEvolution::getZeroExtendExpr(const SCEV *Op, Type *Ty, unsigned Depth) {
1568 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&(static_cast <bool> (getTypeSizeInBits(Op->getType()
) < getTypeSizeInBits(Ty) && "This is not an extending conversion!"
) ? void (0) : __assert_fail ("getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) && \"This is not an extending conversion!\""
, "/build/llvm-toolchain-snapshot-6.0~svn320940/lib/Analysis/ScalarEvolution.cpp"
, 1569, __extension__ __PRETTY_FUNCTION__))
1569 "This is not an extending conversion!")(static_cast <bool> (getTypeSizeInBits(Op->getType()
) < getTypeSizeInBits(Ty) && "This is not an extending conversion!"
) ? void (0) : __assert_fail ("getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) && \"This is not an extending conversion!\""
, "/build/llvm-toolchain-snapshot-6.0~svn320940/lib/Analysis/ScalarEvolution.cpp"
, 1569, __extension__ __PRETTY_FUNCTION__))
;
1570 assert(isSCEVable(Ty) &&(static_cast <bool> (isSCEVable(Ty) && "This is not a conversion to a SCEVable type!"
) ? void (0) : __assert_fail ("isSCEVable(Ty) && \"This is not a conversion to a SCEVable type!\""
, "/build/llvm-toolchain-snapshot-6.0~svn320940/lib/Analysis/ScalarEvolution.cpp"
, 1571, __extension__ __PRETTY_FUNCTION__))
1571 "This is not a conversion to a SCEVable type!")(static_cast <bool> (isSCEVable(Ty) && "This is not a conversion to a SCEVable type!"
) ? void (0) : __assert_fail ("isSCEVable(Ty) && \"This is not a conversion to a SCEVable type!\""
, "/build/llvm-toolchain-snapshot-6.0~svn320940/lib/Analysis/ScalarEvolution.cpp"
, 1571, __extension__ __PRETTY_FUNCTION__))
;
1572 Ty = getEffectiveSCEVType(Ty);
1573
1574 // Fold if the operand is constant.
1575 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
1576 return getConstant(
1577 cast<ConstantInt>(ConstantExpr::getZExt(SC->getValue(), Ty)));
1578
1579 // zext(zext(x)) --> zext(x)
1580 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
1581 return getZeroExtendExpr(SZ->getOperand(), Ty, Depth + 1);
1582
1583 // Before doing any expensive analysis, check to see if we've already
1584 // computed a SCEV for this Op and Ty.
1585 FoldingSetNodeID ID;
1586 ID.AddInteger(scZeroExtend);
1587 ID.AddPointer(Op);
1588 ID.AddPointer(Ty);
1589 void *IP = nullptr;
1590 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1591 if (Depth > MaxExtDepth) {
1592 SCEV *S = new (SCEVAllocator) SCEVZeroExtendExpr(ID.Intern(SCEVAllocator),
1593 Op, Ty);
1594 UniqueSCEVs.InsertNode(S, IP);
1595 addToLoopUseLists(S);
1596 return S;
1597 }
1598
1599 // zext(trunc(x)) --> zext(x) or x or trunc(x)
1600 if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op)) {
1601 // It's possible the bits taken off by the truncate were all zero bits. If
1602 // so, we should be able to simplify this further.
1603 const SCEV *X = ST->getOperand();
1604 ConstantRange CR = getUnsignedRange(X);
1605 unsigned TruncBits = getTypeSizeInBits(ST->getType());
1606 unsigned NewBits = getTypeSizeInBits(Ty);
1607 if (CR.truncate(TruncBits).zeroExtend(NewBits).contains(
1608 CR.zextOrTrunc(NewBits)))
1609 return getTruncateOrZeroExtend(X, Ty);
1610 }
1611
1612 // If the input value is a chrec scev, and we can prove that the value
1613 // did not overflow the old, smaller, value, we can zero extend all of the
1614 // operands (often constants). This allows analysis of something like
1615 // this: for (unsigned char X = 0; X < 100; ++X) { int Y = X; }
1616 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op))
1617 if (AR->isAffine()) {
1618 const SCEV *Start = AR->getStart();
1619 const SCEV *Step = AR->getStepRecurrence(*this);
1620 unsigned BitWidth = getTypeSizeInBits(AR->getType());
1621 const Loop *L = AR->getLoop();
1622
1623 if (!AR->hasNoUnsignedWrap()) {
1624 auto NewFlags = proveNoWrapViaConstantRanges(AR);
1625 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(NewFlags);
1626 }
1627
1628 // If we have special knowledge that this addrec won't overflow,
1629 // we don't need to do any further analysis.
1630 if (AR->hasNoUnsignedWrap())
1631 return getAddRecExpr(
1632 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, Depth + 1),
1633 getZeroExtendExpr(Step, Ty, Depth + 1), L, AR->getNoWrapFlags());
1634
1635 // Check whether the backedge-taken count is SCEVCouldNotCompute.
1636 // Note that this serves two purposes: It filters out loops that are
1637 // simply not analyzable, and it covers the case where this code is
1638 // being called from within backedge-taken count analysis, such that
1639 // attempting to ask for the backedge-taken count would likely result
1640 // in infinite recursion. In the later case, the analysis code will
1641 // cope with a conservative value, and it will take care to purge
1642 // that value once it has finished.
1643 const SCEV *MaxBECount = getMaxBackedgeTakenCount(L);
1644 if (!isa<SCEVCouldNotCompute>(MaxBECount)) {
1645 // Manually compute the final value for AR, checking for
1646 // overflow.
1647
1648 // Check whether the backedge-taken count can be losslessly casted to
1649 // the addrec's type. The count is always unsigned.
1650 const SCEV *CastedMaxBECount =
1651 getTruncateOrZeroExtend(MaxBECount, Start->getType());
1652 const SCEV *RecastedMaxBECount =
1653 getTruncateOrZeroExtend(CastedMaxBECount, MaxBECount->getType());
1654 if (MaxBECount == RecastedMaxBECount) {
1655 Type *WideTy = IntegerType::get(getContext(), BitWidth * 2);
1656 // Check whether Start+Step*MaxBECount has no unsigned overflow.
1657 const SCEV *ZMul = getMulExpr(CastedMaxBECount, Step,
1658 SCEV::FlagAnyWrap, Depth + 1);
1659 const SCEV *ZAdd = getZeroExtendExpr(getAddExpr(Start, ZMul,
1660 SCEV::FlagAnyWrap,
1661 Depth + 1),
1662 WideTy, Depth + 1);
1663 const SCEV *WideStart = getZeroExtendExpr(Start, WideTy, Depth + 1);
1664 const SCEV *WideMaxBECount =
1665 getZeroExtendExpr(CastedMaxBECount, WideTy, Depth + 1);
1666 const SCEV *OperandExtendedAdd =
1667 getAddExpr(WideStart,
1668 getMulExpr(WideMaxBECount,
1669 getZeroExtendExpr(Step, WideTy, Depth + 1),
1670 SCEV::FlagAnyWrap, Depth + 1),
1671 SCEV::FlagAnyWrap, Depth + 1);
1672 if (ZAdd == OperandExtendedAdd) {
1673 // Cache knowledge of AR NUW, which is propagated to this AddRec.
1674 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNUW);
1675 // Return the expression with the addrec on the outside.
1676 return getAddRecExpr(
1677 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this,
1678 Depth + 1),
1679 getZeroExtendExpr(Step, Ty, Depth + 1), L,
1680 AR->getNoWrapFlags());
1681 }
1682 // Similar to above, only this time treat the step value as signed.
1683 // This covers loops that count down.
1684 OperandExtendedAdd =
1685 getAddExpr(WideStart,
1686 getMulExpr(WideMaxBECount,
1687 getSignExtendExpr(Step, WideTy, Depth + 1),
1688 SCEV::FlagAnyWrap, Depth + 1),
1689 SCEV::FlagAnyWrap, Depth + 1);
1690 if (ZAdd == OperandExtendedAdd) {
1691 // Cache knowledge of AR NW, which is propagated to this AddRec.
1692 // Negative step causes unsigned wrap, but it still can't self-wrap.
1693 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNW);
1694 // Return the expression with the addrec on the outside.
1695 return getAddRecExpr(
1696 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this,
1697 Depth + 1),
1698 getSignExtendExpr(Step, Ty, Depth + 1), L,
1699 AR->getNoWrapFlags());
1700 }
1701 }
1702 }
1703
1704 // Normally, in the cases we can prove no-overflow via a
1705 // backedge guarding condition, we can also compute a backedge
1706 // taken count for the loop. The exceptions are assumptions and
1707 // guards present in the loop -- SCEV is not great at exploiting
1708 // these to compute max backedge taken counts, but can still use
1709 // these to prove lack of overflow. Use this fact to avoid
1710 // doing extra work that may not pay off.
1711 if (!isa<SCEVCouldNotCompute>(MaxBECount) || HasGuards ||
1712 !AC.assumptions().empty()) {
1713 // If the backedge is guarded by a comparison with the pre-inc
1714 // value the addrec is safe. Also, if the entry is guarded by
1715 // a comparison with the start value and the backedge is
1716 // guarded by a comparison with the post-inc value, the addrec
1717 // is safe.
1718 if (isKnownPositive(Step)) {
1719 const SCEV *N = getConstant(APInt::getMinValue(BitWidth) -
1720 getUnsignedRangeMax(Step));
1721 if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_ULT, AR, N) ||
1722 (isLoopEntryGuardedByCond(L, ICmpInst::ICMP_ULT, Start, N) &&
1723 isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_ULT,
1724 AR->getPostIncExpr(*this), N))) {
1725 // Cache knowledge of AR NUW, which is propagated to this
1726 // AddRec.
1727 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNUW);
1728 // Return the expression with the addrec on the outside.
1729 return getAddRecExpr(
1730 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this,
1731 Depth + 1),
1732 getZeroExtendExpr(Step, Ty, Depth + 1), L,
1733 AR->getNoWrapFlags());
1734 }
1735 } else if (isKnownNegative(Step)) {
1736 const SCEV *N = getConstant(APInt::getMaxValue(BitWidth) -
1737 getSignedRangeMin(Step));
1738 if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_UGT, AR, N) ||
1739 (isLoopEntryGuardedByCond(L, ICmpInst::ICMP_UGT, Start, N) &&
1740 isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_UGT,
1741 AR->getPostIncExpr(*this), N))) {
1742 // Cache knowledge of AR NW, which is propagated to this
1743 // AddRec. Negative step causes unsigned wrap, but it
1744 // still can't self-wrap.
1745 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNW);
1746 // Return the expression with the addrec on the outside.
1747 return getAddRecExpr(
1748 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this,
1749 Depth + 1),
1750 getSignExtendExpr(Step, Ty, Depth + 1), L,
1751 AR->getNoWrapFlags());
1752 }
1753 }
1754 }
1755
1756 if (proveNoWrapByVaryingStart<SCEVZeroExtendExpr>(Start, Step, L)) {
1757 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNUW);
1758 return getAddRecExpr(
1759 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, Depth + 1),
1760 getZeroExtendExpr(Step, Ty, Depth + 1), L, AR->getNoWrapFlags());
1761 }
1762 }
1763
1764 if (auto *SA = dyn_cast<SCEVAddExpr>(Op)) {
1765 // zext((A + B + ...)<nuw>) --> (zext(A) + zext(B) + ...)<nuw>
1766 if (SA->hasNoUnsignedWrap()) {
1767 // If the addition does not unsign overflow then we can, by definition,
1768 // commute the zero extension with the addition operation.
1769 SmallVector<const SCEV *, 4> Ops;
1770 for (const auto *Op : SA->operands())
1771 Ops.push_back(getZeroExtendExpr(Op, Ty, Depth + 1));
1772 return getAddExpr(Ops, SCEV::FlagNUW, Depth + 1);
1773 }
1774 }
1775
1776 // The cast wasn't folded; create an explicit cast node.
1777 // Recompute the insert position, as it may have been invalidated.
1778 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1779 SCEV *S = new (SCEVAllocator) SCEVZeroExtendExpr(ID.Intern(SCEVAllocator),
1780 Op, Ty);
1781 UniqueSCEVs.InsertNode(S, IP);
1782 addToLoopUseLists(S);
1783 return S;
1784}
1785
1786const SCEV *
1787ScalarEvolution::getSignExtendExpr(const SCEV *Op, Type *Ty, unsigned Depth) {
1788 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&(static_cast <bool> (getTypeSizeInBits(Op->getType()
) < getTypeSizeInBits(Ty) && "This is not an extending conversion!"
) ? void (0) : __assert_fail ("getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) && \"This is not an extending conversion!\""
, "/build/llvm-toolchain-snapshot-6.0~svn320940/lib/Analysis/ScalarEvolution.cpp"
, 1789, __extension__ __PRETTY_FUNCTION__))
1789 "This is not an extending conversion!")(static_cast <bool> (getTypeSizeInBits(Op->getType()
) < getTypeSizeInBits(Ty) && "This is not an extending conversion!"
) ? void (0) : __assert_fail ("getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) && \"This is not an extending conversion!\""
, "/build/llvm-toolchain-snapshot-6.0~svn320940/lib/Analysis/ScalarEvolution.cpp"
, 1789, __extension__ __PRETTY_FUNCTION__))
;
1790 assert(isSCEVable(Ty) &&(static_cast <bool> (isSCEVable(Ty) && "This is not a conversion to a SCEVable type!"
) ? void (0) : __assert_fail ("isSCEVable(Ty) && \"This is not a conversion to a SCEVable type!\""
, "/build/llvm-toolchain-snapshot-6.0~svn320940/lib/Analysis/ScalarEvolution.cpp"
, 1791, __extension__ __PRETTY_FUNCTION__))
1791 "This is not a conversion to a SCEVable type!")(static_cast <bool> (isSCEVable(Ty) && "This is not a conversion to a SCEVable type!"
) ? void (0) : __assert_fail ("isSCEVable(Ty) && \"This is not a conversion to a SCEVable type!\""
, "/build/llvm-toolchain-snapshot-6.0~svn320940/lib/Analysis/ScalarEvolution.cpp"
, 1791, __extension__ __PRETTY_FUNCTION__))
;
1792 Ty = getEffectiveSCEVType(Ty);
1793
1794 // Fold if the operand is constant.
1795 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
1796 return getConstant(
1797 cast<ConstantInt>(ConstantExpr::getSExt(SC->getValue(), Ty)));
1798
1799 // sext(sext(x)) --> sext(x)
1800 if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op))
1801 return getSignExtendExpr(SS->getOperand(), Ty, Depth + 1);
1802
1803 // sext(zext(x)) --> zext(x)
1804 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
1805 return getZeroExtendExpr(SZ->getOperand(), Ty, Depth + 1);
1806
1807 // Before doing any expensive analysis, check to see if we've already
1808 // computed a SCEV for this Op and Ty.
1809 FoldingSetNodeID ID;
1810 ID.AddInteger(scSignExtend);
1811 ID.AddPointer(Op);
1812 ID.AddPointer(Ty);
1813 void *IP = nullptr;
1814 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1815 // Limit recursion depth.
1816 if (Depth > MaxExtDepth) {
1817 SCEV *S = new (SCEVAllocator) SCEVSignExtendExpr(ID.Intern(SCEVAllocator),
1818 Op, Ty);
1819 UniqueSCEVs.InsertNode(S, IP);
1820 addToLoopUseLists(S);
1821 return S;
1822 }
1823
1824 // sext(trunc(x)) --> sext(x) or x or trunc(x)
1825 if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op)) {
1826 // It's possible the bits taken off by the truncate were all sign bits. If
1827 // so, we should be able to simplify this further.
1828 const SCEV *X = ST->getOperand();
1829 ConstantRange CR = getSignedRange(X);
1830 unsigned TruncBits = getTypeSizeInBits(ST->getType());
1831 unsigned NewBits = getTypeSizeInBits(Ty);
1832 if (CR.truncate(TruncBits).signExtend(NewBits).contains(
1833 CR.sextOrTrunc(NewBits)))
1834 return getTruncateOrSignExtend(X, Ty);
1835 }
1836
1837 // sext(C1 + (C2 * x)) --> C1 + sext(C2 * x) if C1 < C2
1838 if (auto *SA = dyn_cast<SCEVAddExpr>(Op)) {
1839 if (SA->getNumOperands() == 2) {
1840 auto *SC1 = dyn_cast<SCEVConstant>(SA->getOperand(0));
1841 auto *SMul = dyn_cast<SCEVMulExpr>(SA->getOperand(1));
1842 if (SMul && SC1) {
1843 if (auto *SC2 = dyn_cast<SCEVConstant>(SMul->getOperand(0))) {
1844 const APInt &C1 = SC1->getAPInt();
1845 const APInt &C2 = SC2->getAPInt();
1846 if (C1.isStrictlyPositive() && C2.isStrictlyPositive() &&
1847 C2.ugt(C1) && C2.isPowerOf2())
1848 return getAddExpr(getSignExtendExpr(SC1, Ty, Depth + 1),
1849 getSignExtendExpr(SMul, Ty, Depth + 1),
1850 SCEV::FlagAnyWrap, Depth + 1);
1851 }
1852 }
1853 }
1854
1855 // sext((A + B + ...)<nsw>) --> (sext(A) + sext(B) + ...)<nsw>
1856 if (SA->hasNoSignedWrap()) {
1857 // If the addition does not sign overflow then we can, by definition,
1858 // commute the sign extension with the addition operation.
1859 SmallVector<const SCEV *, 4> Ops;
1860 for (const auto *Op : SA->operands())
1861 Ops.push_back(getSignExtendExpr(Op, Ty, Depth + 1));
1862 return getAddExpr(Ops, SCEV::FlagNSW, Depth + 1);
1863 }
1864 }
1865 // If the input value is a chrec scev, and we can prove that the value
1866 // did not overflow the old, smaller, value, we can sign extend all of the
1867 // operands (often constants). This allows analysis of something like
1868 // this: for (signed char X = 0; X < 100; ++X) { int Y = X; }
1869 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op))
1870 if (AR->isAffine()) {
1871 const SCEV *Start = AR->getStart();
1872 const SCEV *Step = AR->getStepRecurrence(*this);
1873 unsigned BitWidth = getTypeSizeInBits(AR->getType());
1874 const Loop *L = AR->getLoop();
1875
1876 if (!AR->hasNoSignedWrap()) {
1877 auto NewFlags = proveNoWrapViaConstantRanges(AR);
1878 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(NewFlags);
1879 }
1880
1881 // If we have special knowledge that this addrec won't overflow,
1882 // we don't need to do any further analysis.
1883 if (AR->hasNoSignedWrap())
1884 return getAddRecExpr(
1885 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, Depth + 1),
1886 getSignExtendExpr(Step, Ty, Depth + 1), L, SCEV::FlagNSW);
1887
1888 // Check whether the backedge-taken count is SCEVCouldNotCompute.
1889 // Note that this serves two purposes: It filters out loops that are
1890 // simply not analyzable, and it covers the case where this code is
1891 // being called from within backedge-taken count analysis, such that
1892 // attempting to ask for the backedge-taken count would likely result
1893 // in infinite recursion. In the later case, the analysis code will
1894 // cope with a conservative value, and it will take care to purge
1895 // that value once it has finished.
1896 const SCEV *MaxBECount = getMaxBackedgeTakenCount(L);
1897 if (!isa<SCEVCouldNotCompute>(MaxBECount)) {
1898 // Manually compute the final value for AR, checking for
1899 // overflow.
1900
1901 // Check whether the backedge-taken count can be losslessly casted to
1902 // the addrec's type. The count is always unsigned.
1903 const SCEV *CastedMaxBECount =
1904 getTruncateOrZeroExtend(MaxBECount, Start->getType());
1905 const SCEV *RecastedMaxBECount =
1906 getTruncateOrZeroExtend(CastedMaxBECount, MaxBECount->getType());
1907 if (MaxBECount == RecastedMaxBECount) {
1908 Type *WideTy = IntegerType::get(getContext(), BitWidth * 2);
1909 // Check whether Start+Step*MaxBECount has no signed overflow.
1910 const SCEV *SMul = getMulExpr(CastedMaxBECount, Step,
1911 SCEV::FlagAnyWrap, Depth + 1);
1912 const SCEV *SAdd = getSignExtendExpr(getAddExpr(Start, SMul,
1913 SCEV::FlagAnyWrap,
1914 Depth + 1),
1915 WideTy, Depth + 1);
1916 const SCEV *WideStart = getSignExtendExpr(Start, WideTy, Depth + 1);
1917 const SCEV *WideMaxBECount =
1918 getZeroExtendExpr(CastedMaxBECount, WideTy, Depth + 1);
1919 const SCEV *OperandExtendedAdd =
1920 getAddExpr(WideStart,
1921 getMulExpr(WideMaxBECount,
1922 getSignExtendExpr(Step, WideTy, Depth + 1),
1923 SCEV::FlagAnyWrap, Depth + 1),
1924 SCEV::FlagAnyWrap, Depth + 1);
1925 if (SAdd == OperandExtendedAdd) {
1926 // Cache knowledge of AR NSW, which is propagated to this AddRec.
1927 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNSW);
1928 // Return the expression with the addrec on the outside.
1929 return getAddRecExpr(
1930 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this,
1931 Depth + 1),
1932 getSignExtendExpr(Step, Ty, Depth + 1), L,
1933 AR->getNoWrapFlags());
1934 }
1935 // Similar to above, only this time treat the step value as unsigned.
1936 // This covers loops that count up with an unsigned step.
1937 OperandExtendedAdd =
1938 getAddExpr(WideStart,
1939 getMulExpr(WideMaxBECount,
1940 getZeroExtendExpr(Step, WideTy, Depth + 1),
1941 SCEV::FlagAnyWrap, Depth + 1),
1942 SCEV::FlagAnyWrap, Depth + 1);
1943 if (SAdd == OperandExtendedAdd) {
1944 // If AR wraps around then
1945 //
1946 // abs(Step) * MaxBECount > unsigned-max(AR->getType())
1947 // => SAdd != OperandExtendedAdd
1948 //
1949 // Thus (AR is not NW => SAdd != OperandExtendedAdd) <=>
1950 // (SAdd == OperandExtendedAdd => AR is NW)
1951
1952 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNW);
1953
1954 // Return the expression with the addrec on the outside.
1955 return getAddRecExpr(
1956 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this,
1957 Depth + 1),
1958 getZeroExtendExpr(Step, Ty, Depth + 1), L,
1959 AR->getNoWrapFlags());
1960 }
1961 }
1962 }
1963
1964 // Normally, in the cases we can prove no-overflow via a
1965 // backedge guarding condition, we can also compute a backedge
1966 // taken count for the loop. The exceptions are assumptions and
1967 // guards present in the loop -- SCEV is not great at exploiting
1968 // these to compute max backedge taken counts, but can still use
1969 // these to prove lack of overflow. Use this fact to avoid
1970 // doing extra work that may not pay off.
1971
1972 if (!isa<SCEVCouldNotCompute>(MaxBECount) || HasGuards ||
1973 !AC.assumptions().empty()) {
1974 // If the backedge is guarded by a comparison with the pre-inc
1975 // value the addrec is safe. Also, if the entry is guarded by
1976 // a comparison with the start value and the backedge is
1977 // guarded by a comparison with the post-inc value, the addrec
1978 // is safe.
1979 ICmpInst::Predicate Pred;
1980 const SCEV *OverflowLimit =
1981 getSignedOverflowLimitForStep(Step, &Pred, this);
1982 if (OverflowLimit &&
1983 (isLoopBackedgeGuardedByCond(L, Pred, AR, OverflowLimit) ||
1984 (isLoopEntryGuardedByCond(L, Pred, Start, OverflowLimit) &&
1985 isLoopBackedgeGuardedByCond(L, Pred, AR->getPostIncExpr(*this),
1986 OverflowLimit)))) {
1987 // Cache knowledge of AR NSW, then propagate NSW to the wide AddRec.
1988 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNSW);
1989 return getAddRecExpr(
1990 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, Depth + 1),
1991 getSignExtendExpr(Step, Ty, Depth + 1), L, AR->getNoWrapFlags());
1992 }
1993 }
1994
1995 // If Start and Step are constants, check if we can apply this
1996 // transformation:
1997 // sext{C1,+,C2} --> C1 + sext{0,+,C2} if C1 < C2
1998 auto *SC1 = dyn_cast<SCEVConstant>(Start);
1999 auto *SC2 = dyn_cast<SCEVConstant>(Step);
2000 if (SC1 && SC2) {
2001 const APInt &C1 = SC1->getAPInt();
2002 const APInt &C2 = SC2->getAPInt();
2003 if (C1.isStrictlyPositive() && C2.isStrictlyPositive() && C2.ugt(C1) &&
2004 C2.isPowerOf2()) {
2005 Start = getSignExtendExpr(Start, Ty, Depth + 1);
2006 const SCEV *NewAR = getAddRecExpr(getZero(AR->getType()), Step, L,
2007 AR->getNoWrapFlags());
2008 return getAddExpr(Start, getSignExtendExpr(NewAR, Ty, Depth + 1),
2009 SCEV::FlagAnyWrap, Depth + 1);
2010 }
2011 }
2012
2013 if (proveNoWrapByVaryingStart<SCEVSignExtendExpr>(Start, Step, L)) {
2014 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNSW);
2015 return getAddRecExpr(
2016 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, Depth + 1),
2017 getSignExtendExpr(Step, Ty, Depth + 1), L, AR->getNoWrapFlags());
2018 }
2019 }
2020
2021 // If the input value is provably positive and we could not simplify
2022 // away the sext build a zext instead.
2023 if (isKnownNonNegative(Op))
2024 return getZeroExtendExpr(Op, Ty, Depth + 1);
2025
2026 // The cast wasn't folded; create an explicit cast node.
2027 // Recompute the insert position, as it may have been invalidated.
2028 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
2029 SCEV *S = new (SCEVAllocator) SCEVSignExtendExpr(ID.Intern(SCEVAllocator),
2030 Op, Ty);
2031 UniqueSCEVs.InsertNode(S, IP);
2032 addToLoopUseLists(S);
2033 return S;
2034}
2035
2036/// getAnyExtendExpr - Return a SCEV for the given operand extended with
2037/// unspecified bits out to the given type.
2038const SCEV *ScalarEvolution::getAnyExtendExpr(const SCEV *Op,
2039 Type *Ty) {
2040 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&(static_cast <bool> (getTypeSizeInBits(Op->getType()
) < getTypeSizeInBits(Ty) && "This is not an extending conversion!"
) ? void (0) : __assert_fail ("getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) && \"This is not an extending conversion!\""
, "/build/llvm-toolchain-snapshot-6.0~svn320940/lib/Analysis/ScalarEvolution.cpp"
, 2041, __extension__ __PRETTY_FUNCTION__))
2041 "This is not an extending conversion!")(static_cast <bool> (getTypeSizeInBits(Op->getType()
) < getTypeSizeInBits(Ty) && "This is not an extending conversion!"
) ? void (0) : __assert_fail ("getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) && \"This is not an extending conversion!\""
, "/build/llvm-toolchain-snapshot-6.0~svn320940/lib/Analysis/ScalarEvolution.cpp"
, 2041, __extension__ __PRETTY_FUNCTION__))
;
2042 assert(isSCEVable(Ty) &&(static_cast <bool> (isSCEVable(Ty) && "This is not a conversion to a SCEVable type!"
) ? void (0) : __assert_fail ("isSCEVable(Ty) && \"This is not a conversion to a SCEVable type!\""
, "/build/llvm-toolchain-snapshot-6.0~svn320940/lib/Analysis/ScalarEvolution.cpp"
, 2043, __extension__ __PRETTY_FUNCTION__))
2043 "This is not a conversion to a SCEVable type!")(static_cast <bool> (isSCEVable(Ty) && "This is not a conversion to a SCEVable type!"
) ? void (0) : __assert_fail ("isSCEVable(Ty) && \"This is not a conversion to a SCEVable type!\""
, "/build/llvm-toolchain-snapshot-6.0~svn320940/lib/Analysis/ScalarEvolution.cpp"
, 2043, __extension__ __PRETTY_FUNCTION__))
;
2044 Ty = getEffectiveSCEVType(Ty);
2045
2046 // Sign-extend negative constants.
2047 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
2048 if (SC->getAPInt().isNegative())
2049 return getSignExtendExpr(Op, Ty);
2050
2051 // Peel off a truncate cast.
2052 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Op)) {
2053 const SCEV *NewOp = T->getOperand();
2054 if (getTypeSizeInBits(NewOp->getType()) < getTypeSizeInBits(Ty))
2055 return getAnyExtendExpr(NewOp, Ty);
2056 return getTruncateOrNoop(NewOp, Ty);
2057 }
2058
2059 // Next try a zext cast. If the cast is folded, use it.
2060 const SCEV *ZExt = getZeroExtendExpr(Op, Ty);
2061 if (!isa<SCEVZeroExtendExpr>(ZExt))
2062 return ZExt;
2063
2064 // Next try a sext cast. If the cast is folded, use it.
2065 const SCEV *SExt = getSignExtendExpr(Op, Ty);
2066 if (!isa<SCEVSignExtendExpr>(SExt))
2067 return SExt;
2068
2069 // Force the cast to be folded into the operands of an addrec.
2070 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op)) {
2071 SmallVector<const SCEV *, 4> Ops;
2072 for (const SCEV *Op : AR->operands())
2073 Ops.push_back(getAnyExtendExpr(Op, Ty));
2074 return getAddRecExpr(Ops, AR->getLoop(), SCEV::FlagNW);
2075 }
2076
2077 // If the expression is obviously signed, use the sext cast value.
2078 if (isa<SCEVSMaxExpr>(Op))
2079 return SExt;
2080
2081 // Absent any other information, use the zext cast value.
2082 return ZExt;
2083}
2084
2085/// Process the given Ops list, which is a list of operands to be added under
2086/// the given scale, update the given map. This is a helper function for
2087/// getAddRecExpr. As an example of what it does, given a sequence of operands
2088/// that would form an add expression like this:
2089///
2090/// m + n + 13 + (A * (o + p + (B * (q + m + 29)))) + r + (-1 * r)
2091///
2092/// where A and B are constants, update the map with these values:
2093///
2094/// (m, 1+A*B), (n, 1), (o, A), (p, A), (q, A*B), (r, 0)
2095///
2096/// and add 13 + A*B*29 to AccumulatedConstant.
2097/// This will allow getAddRecExpr to produce this:
2098///
2099/// 13+A*B*29 + n + (m * (1+A*B)) + ((o + p) * A) + (q * A*B)
2100///
2101/// This form often exposes folding opportunities that are hidden in
2102/// the original operand list.
2103///
2104/// Return true iff it appears that any interesting folding opportunities
2105/// may be exposed. This helps getAddRecExpr short-circuit extra work in
2106/// the common case where no interesting opportunities are present, and
2107/// is also used as a check to avoid infinite recursion.
2108static bool
2109CollectAddOperandsWithScales(DenseMap<const SCEV *, APInt> &M,
2110 SmallVectorImpl<const SCEV *> &NewOps,
2111 APInt &AccumulatedConstant,
2112 const SCEV *const *Ops, size_t NumOperands,
2113 const APInt &Scale,
2114 ScalarEvolution &SE) {
2115 bool Interesting = false;
2116
2117 // Iterate over the add operands. They are sorted, with constants first.
2118 unsigned i = 0;
2119 while (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) {
2120 ++i;
2121 // Pull a buried constant out to the outside.
2122 if (Scale != 1 || AccumulatedConstant != 0 || C->getValue()->isZero())
2123 Interesting = true;
2124 AccumulatedConstant += Scale * C->getAPInt();
2125 }
2126
2127 // Next comes everything else. We're especially interested in multiplies
2128 // here, but they're in the middle, so just visit the rest with one loop.
2129 for (; i != NumOperands; ++i) {
2130 const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[i]);
2131 if (Mul && isa<SCEVConstant>(Mul->getOperand(0))) {
2132 APInt NewScale =
2133 Scale * cast<SCEVConstant>(Mul->getOperand(0))->getAPInt();
2134 if (Mul->getNumOperands() == 2 && isa<SCEVAddExpr>(Mul->getOperand(1))) {
2135 // A multiplication of a constant with another add; recurse.
2136 const SCEVAddExpr *Add = cast<SCEVAddExpr>(Mul->getOperand(1));
2137 Interesting |=
2138 CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant,
2139 Add->op_begin(), Add->getNumOperands(),
2140 NewScale, SE);
2141 } else {
2142 // A multiplication of a constant with some other value. Update
2143 // the map.
2144 SmallVector<const SCEV *, 4> MulOps(Mul->op_begin()+1, Mul->op_end());
2145 const SCEV *Key = SE.getMulExpr(MulOps);
2146 auto Pair = M.insert({Key, NewScale});
2147 if (Pair.second) {
2148 NewOps.push_back(Pair.first->first);
2149 } else {
2150 Pair.first->second += NewScale;
2151 // The map already had an entry for this value, which may indicate
2152 // a folding opportunity.
2153 Interesting = true;
2154 }
2155 }
2156 } else {
2157 // An ordinary operand. Update the map.
2158 std::pair<DenseMap<const SCEV *, APInt>::iterator, bool> Pair =
2159 M.insert({Ops[i], Scale});
2160 if (Pair.second) {
2161 NewOps.push_back(Pair.first->first);
2162 } else {
2163 Pair.first->second += Scale;
2164 // The map already had an entry for this value, which may indicate
2165 // a folding opportunity.
2166 Interesting = true;
2167 }
2168 }
2169 }
2170
2171 return Interesting;
2172}
2173
2174// We're trying to construct a SCEV of type `Type' with `Ops' as operands and
2175// `OldFlags' as can't-wrap behavior. Infer a more aggressive set of
2176// can't-overflow flags for the operation if possible.
2177static SCEV::NoWrapFlags
2178StrengthenNoWrapFlags(ScalarEvolution *SE, SCEVTypes Type,
2179 const SmallVectorImpl<const SCEV *> &Ops,
2180 SCEV::NoWrapFlags Flags) {
2181 using namespace std::placeholders;
2182
2183 using OBO = OverflowingBinaryOperator;
2184
2185 bool CanAnalyze =
2186 Type == scAddExpr || Type == scAddRecExpr || Type == scMulExpr;
2187 (void)CanAnalyze;
2188 assert(CanAnalyze && "don't call from other places!")(static_cast <bool> (CanAnalyze && "don't call from other places!"
) ? void (0) : __assert_fail ("CanAnalyze && \"don't call from other places!\""
, "/build/llvm-toolchain-snapshot-6.0~svn320940/lib/Analysis/ScalarEvolution.cpp"
, 2188, __extension__ __PRETTY_FUNCTION__))
;
2189
2190 int SignOrUnsignMask = SCEV::FlagNUW | SCEV::FlagNSW;
2191 SCEV::NoWrapFlags SignOrUnsignWrap =
2192 ScalarEvolution::maskFlags(Flags, SignOrUnsignMask);
2193
2194 // If FlagNSW is true and all the operands are non-negative, infer FlagNUW.
2195 auto IsKnownNonNegative = [&](const SCEV *S) {
2196 return SE->isKnownNonNegative(S);
2197 };
2198
2199 if (SignOrUnsignWrap == SCEV::FlagNSW && all_of(Ops, IsKnownNonNegative))
2200 Flags =
2201 ScalarEvolution::setFlags(Flags, (SCEV::NoWrapFlags)SignOrUnsignMask);
2202
2203 SignOrUnsignWrap = ScalarEvolution::maskFlags(Flags, SignOrUnsignMask);
2204
2205 if (SignOrUnsignWrap != SignOrUnsignMask && Type == scAddExpr &&
2206 Ops.size() == 2 && isa<SCEVConstant>(Ops[0])) {
2207
2208 // (A + C) --> (A + C)<nsw> if the addition does not sign overflow
2209 // (A + C) --> (A + C)<nuw> if the addition does not unsign overflow
2210
2211 const APInt &C = cast<SCEVConstant>(Ops[0])->getAPInt();
2212 if (!(SignOrUnsignWrap & SCEV::FlagNSW)) {
2213 auto NSWRegion = ConstantRange::makeGuaranteedNoWrapRegion(
2214 Instruction::Add, C, OBO::NoSignedWrap);
2215 if (NSWRegion.contains(SE->getSignedRange(Ops[1])))
2216 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNSW);
2217 }
2218 if (!(SignOrUnsignWrap & SCEV::FlagNUW)) {
2219 auto NUWRegion = ConstantRange::makeGuaranteedNoWrapRegion(
2220 Instruction::Add, C, OBO::NoUnsignedWrap);
2221 if (NUWRegion.contains(SE->getUnsignedRange(Ops[1])))
2222 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNUW);
2223 }
2224 }
2225
2226 return Flags;
2227}
2228
2229bool ScalarEvolution::isAvailableAtLoopEntry(const SCEV *S, const Loop *L) {
2230 if (!isLoopInvariant(S, L))
2231 return false;
2232 // If a value depends on a SCEVUnknown which is defined after the loop, we
2233 // conservatively assume that we cannot calculate it at the loop's entry.
2234 struct FindDominatedSCEVUnknown {
2235 bool Found = false;
2236 const Loop *L;
2237 DominatorTree &DT;
2238 LoopInfo &LI;
2239
2240 FindDominatedSCEVUnknown(const Loop *L, DominatorTree &DT, LoopInfo &LI)
2241 : L(L), DT(DT), LI(LI) {}
2242
2243 bool checkSCEVUnknown(const SCEVUnknown *SU) {
2244 if (auto *I = dyn_cast<Instruction>(SU->getValue())) {
2245 if (DT.dominates(L->getHeader(), I->getParent()))
2246 Found = true;
2247 else
2248 assert(DT.dominates(I->getParent(), L->getHeader()) &&(static_cast <bool> (DT.dominates(I->getParent(), L->
getHeader()) && "No dominance relationship between SCEV and loop?"
) ? void (0) : __assert_fail ("DT.dominates(I->getParent(), L->getHeader()) && \"No dominance relationship between SCEV and loop?\""
, "/build/llvm-toolchain-snapshot-6.0~svn320940/lib/Analysis/ScalarEvolution.cpp"
, 2249, __extension__ __PRETTY_FUNCTION__))
2249 "No dominance relationship between SCEV and loop?")(static_cast <bool> (DT.dominates(I->getParent(), L->
getHeader()) && "No dominance relationship between SCEV and loop?"
) ? void (0) : __assert_fail ("DT.dominates(I->getParent(), L->getHeader()) && \"No dominance relationship between SCEV and loop?\""
, "/build/llvm-toolchain-snapshot-6.0~svn320940/lib/Analysis/ScalarEvolution.cpp"
, 2249, __extension__ __PRETTY_FUNCTION__))
;
2250 }
2251 return false;
2252 }
2253
2254 bool follow(const SCEV *S) {
2255 switch (static_cast<SCEVTypes>(S->getSCEVType())) {
2256 case scConstant:
2257 return false;
2258 case scAddRecExpr:
2259 case scTruncate:
2260 case scZeroExtend:
2261 case scSignExtend:
2262 case scAddExpr:
2263 case scMulExpr:
2264 case scUMaxExpr:
2265 case scSMaxExpr:
2266 case scUDivExpr:
2267 return true;
2268 case scUnknown:
2269 return checkSCEVUnknown(cast<SCEVUnknown>(S));
2270 case scCouldNotCompute:
2271 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!")::llvm::llvm_unreachable_internal("Attempt to use a SCEVCouldNotCompute object!"
, "/build/llvm-toolchain-snapshot-6.0~svn320940/lib/Analysis/ScalarEvolution.cpp"
, 2271)
;
2272 }
2273 return false;
2274 }
2275
2276 bool isDone() { return Found; }
2277 };
2278
2279 FindDominatedSCEVUnknown FSU(L, DT, LI);
2280 SCEVTraversal<FindDominatedSCEVUnknown> ST(FSU);
2281 ST.visitAll(S);
2282 return !FSU.Found;
2283}
2284
2285/// Get a canonical add expression, or something simpler if possible.
2286const SCEV *ScalarEvolution::getAddExpr(SmallVectorImpl<const SCEV *> &Ops,
2287 SCEV::NoWrapFlags Flags,
2288 unsigned Depth) {
2289 assert(!(Flags & ~(SCEV::FlagNUW | SCEV::FlagNSW)) &&(static_cast <bool> (!(Flags & ~(SCEV::FlagNUW | SCEV
::FlagNSW)) && "only nuw or nsw allowed") ? void (0) :
__assert_fail ("!(Flags & ~(SCEV::FlagNUW | SCEV::FlagNSW)) && \"only nuw or nsw allowed\""
, "/build/llvm-toolchain-snapshot-6.0~svn320940/lib/Analysis/ScalarEvolution.cpp"
, 2290, __extension__ __PRETTY_FUNCTION__))
2290 "only nuw or nsw allowed")(static_cast <bool> (!(Flags & ~(SCEV::FlagNUW | SCEV
::FlagNSW)) && "only nuw or nsw allowed") ? void (0) :
__assert_fail ("!(Flags & ~(SCEV::FlagNUW | SCEV::FlagNSW)) && \"only nuw or nsw allowed\""
, "/build/llvm-toolchain-snapshot-6.0~svn320940/lib/Analysis/ScalarEvolution.cpp"
, 2290, __extension__ __PRETTY_FUNCTION__))
;
2291 assert(!Ops.empty() && "Cannot get empty add!")(static_cast <bool> (!Ops.empty() && "Cannot get empty add!"
) ? void (0) : __assert_fail ("!Ops.empty() && \"Cannot get empty add!\""
, "/build/llvm-toolchain-snapshot-6.0~svn320940/lib/Analysis/ScalarEvolution.cpp"
, 2291, __extension__ __PRETTY_FUNCTION__))
;
2292 if (Ops.size() == 1) return Ops[0];
2293#ifndef NDEBUG
2294 Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
2295 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
2296 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&(static_cast <bool> (getEffectiveSCEVType(Ops[i]->getType
()) == ETy && "SCEVAddExpr operand types don't match!"
) ? void (0) : __assert_fail ("getEffectiveSCEVType(Ops[i]->getType()) == ETy && \"SCEVAddExpr operand types don't match!\""
, "/build/llvm-toolchain-snapshot-6.0~svn320940/lib/Analysis/ScalarEvolution.cpp"
, 2297, __extension__ __PRETTY_FUNCTION__))
2297 "SCEVAddExpr operand types don't match!")(static_cast <bool> (getEffectiveSCEVType(Ops[i]->getType
()) == ETy && "SCEVAddExpr operand types don't match!"
) ? void (0) : __assert_fail ("getEffectiveSCEVType(Ops[i]->getType()) == ETy && \"SCEVAddExpr operand types don't match!\""
, "/build/llvm-toolchain-snapshot-6.0~svn320940/lib/Analysis/ScalarEvolution.cpp"
, 2297, __extension__ __PRETTY_FUNCTION__))
;
2298#endif
2299
2300 // Sort by complexity, this groups all similar expression types together.
2301 GroupByComplexity(Ops, &LI, DT);
2302
2303 Flags = StrengthenNoWrapFlags(this, scAddExpr, Ops, Flags);
2304
2305 // If there are any constants, fold them together.
2306 unsigned Idx = 0;
2307 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
2308 ++Idx;
2309 assert(Idx < Ops.size())(static_cast <bool> (Idx < Ops.size()) ? void (0) : __assert_fail
("Idx < Ops.size()", "/build/llvm-toolchain-snapshot-6.0~svn320940/lib/Analysis/ScalarEvolution.cpp"
, 2309, __extension__ __PRETTY_FUNCTION__))
;
2310 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
2311 // We found two constants, fold them together!
2312 Ops[0] = getConstant(LHSC->getAPInt() + RHSC->getAPInt());
2313 if (Ops.size() == 2) return Ops[0];
2314 Ops.erase(Ops.begin()+1); // Erase the folded element
2315 LHSC = cast<SCEVConstant>(Ops[0]);
2316 }
2317
2318 // If we are left with a constant zero being added, strip it off.
2319 if (LHSC->getValue()->isZero()) {
2320 Ops.erase(Ops.begin());
2321 --Idx;
2322 }
2323
2324 if (Ops.size() == 1) return Ops[0];
2325 }
2326
2327 // Limit recursion calls depth.
2328 if (Depth > MaxArithDepth)
2329 return getOrCreateAddExpr(Ops, Flags);
2330
2331 // Okay, check to see if the same value occurs in the operand list more than
2332 // once. If so, merge them together into an multiply expression. Since we
2333 // sorted the list, these values are required to be adjacent.
2334 Type *Ty = Ops[0]->getType();
2335 bool FoundMatch = false;
2336 for (unsigned i = 0, e = Ops.size(); i != e-1; ++i)
2337 if (Ops[i] == Ops[i+1]) { // X + Y + Y --> X + Y*2
2338 // Scan ahead to count how many equal operands there are.
2339 unsigned Count = 2;
2340 while (i+Count != e && Ops[i+Count] == Ops[i])
2341 ++Count;
2342 // Merge the values into a multiply.
2343 const SCEV *Scale = getConstant(Ty, Count);
2344 const SCEV *Mul = getMulExpr(Scale, Ops[i], SCEV::FlagAnyWrap, Depth + 1);
2345 if (Ops.size() == Count)
2346 return Mul;
2347 Ops[i] = Mul;
2348 Ops.erase(Ops.begin()+i+1, Ops.begin()+i+Count);
2349 --i; e -= Count - 1;
2350 FoundMatch = true;
2351 }
2352 if (FoundMatch)
2353 return getAddExpr(Ops, Flags);
2354
2355 // Check for truncates. If all the operands are truncated from the same
2356 // type, see if factoring out the truncate would permit the result to be
2357 // folded. eg., n*trunc(x) + m*trunc(y) --> trunc(trunc(m)*x + trunc(n)*y)
2358 // if the contents of the resulting outer trunc fold to something simple.
2359 auto FindTruncSrcType = [&]() -> Type * {
2360 // We're ultimately looking to fold an addrec of truncs and muls of only
2361 // constants and truncs, so if we find any other types of SCEV
2362 // as operands of the addrec then we bail and return nullptr here.
2363 // Otherwise, we return the type of the operand of a trunc that we find.
2364 if (auto *T = dyn_cast<SCEVTruncateExpr>(Ops[Idx]))
2365 return T->getOperand()->getType();
2366 if (const auto *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) {
2367 const auto *LastOp = Mul->getOperand(Mul->getNumOperands() - 1);
2368 if (const auto *T = dyn_cast<SCEVTruncateExpr>(LastOp))
2369 return T->getOperand()->getType();
2370 }
2371 return nullptr;
2372 };
2373 if (auto *SrcType = FindTruncSrcType()) {
2374 SmallVector<const SCEV *, 8> LargeOps;
2375 bool Ok = true;
2376 // Check all the operands to see if they can be represented in the
2377 // source type of the truncate.
2378 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
2379 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Ops[i])) {
2380 if (T->getOperand()->getType() != SrcType) {
2381 Ok = false;
2382 break;
2383 }
2384 LargeOps.push_back(T->getOperand());
2385 } else if (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) {
2386 LargeOps.push_back(getAnyExtendExpr(C, SrcType));
2387 } else if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(Ops[i])) {
2388 SmallVector<const SCEV *, 8> LargeMulOps;
2389 for (unsigned j = 0, f = M->getNumOperands(); j != f && Ok; ++j) {
2390 if (const SCEVTruncateExpr *T =
2391 dyn_cast<SCEVTruncateExpr>(M->getOperand(j))) {
2392 if (T->getOperand()->getType() != SrcType) {
2393 Ok = false;
2394 break;
2395 }
2396 LargeMulOps.push_back(T->getOperand());
2397 } else if (const auto *C = dyn_cast<SCEVConstant>(M->getOperand(j))) {
2398 LargeMulOps.push_back(getAnyExtendExpr(C, SrcType));
2399 } else {
2400 Ok = false;
2401 break;
2402 }
2403 }
2404 if (Ok)
2405 LargeOps.push_back(getMulExpr(LargeMulOps, SCEV::FlagAnyWrap, Depth + 1));
2406 } else {
2407 Ok = false;
2408 break;
2409 }
2410 }
2411 if (Ok) {
2412 // Evaluate the expression in the larger type.
2413 const SCEV *Fold = getAddExpr(LargeOps, Flags, Depth + 1);
2414 // If it folds to something simple, use it. Otherwise, don't.
2415 if (isa<SCEVConstant>(Fold) || isa<SCEVUnknown>(Fold))
2416 return getTruncateExpr(Fold, Ty);
2417 }
2418 }
2419
2420 // Skip past any other cast SCEVs.
2421 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddExpr)
2422 ++Idx;
2423
2424 // If there are add operands they would be next.
2425 if (Idx < Ops.size()) {
2426 bool DeletedAdd = false;
2427 while (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[Idx])) {
2428 if (Ops.size() > AddOpsInlineThreshold ||
2429 Add->getNumOperands() > AddOpsInlineThreshold)
2430 break;
2431 // If we have an add, expand the add operands onto the end of the operands
2432 // list.
2433 Ops.erase(Ops.begin()+Idx);
2434 Ops.append(Add->op_begin(), Add->op_end());
2435 DeletedAdd = true;
2436 }
2437
2438 // If we deleted at least one add, we added operands to the end of the list,
2439 // and they are not necessarily sorted. Recurse to resort and resimplify
2440 // any operands we just acquired.
2441 if (DeletedAdd)
2442 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
2443 }
2444
2445 // Skip over the add expression until we get to a multiply.
2446 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
2447 ++Idx;
2448
2449 // Check to see if there are any folding opportunities present with
2450 // operands multiplied by constant values.
2451 if (Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx])) {
2452 uint64_t BitWidth = getTypeSizeInBits(Ty);
2453 DenseMap<const SCEV *, APInt> M;
2454 SmallVector<const SCEV *, 8> NewOps;
2455 APInt AccumulatedConstant(BitWidth, 0);
2456 if (CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant,
2457 Ops.data(), Ops.size(),
2458 APInt(BitWidth, 1), *this)) {
2459 struct APIntCompare {
2460 bool operator()(const APInt &LHS, const APInt &RHS) const {
2461 return LHS.ult(RHS);
2462 }
2463 };
2464
2465 // Some interesting folding opportunity is present, so its worthwhile to
2466 // re-generate the operands list. Group the operands by constant scale,
2467 // to avoid multiplying by the same constant scale multiple times.
2468 std::map<APInt, SmallVector<const SCEV *, 4>, APIntCompare> MulOpLists;
2469 for (const SCEV *NewOp : NewOps)
2470 MulOpLists[M.find(NewOp)->second].push_back(NewOp);
2471 // Re-generate the operands list.
2472 Ops.clear();
2473 if (AccumulatedConstant != 0)
2474 Ops.push_back(getConstant(AccumulatedConstant));
2475 for (auto &MulOp : MulOpLists)
2476 if (MulOp.first != 0)
2477 Ops.push_back(getMulExpr(
2478 getConstant(MulOp.first),
2479 getAddExpr(MulOp.second, SCEV::FlagAnyWrap, Depth + 1),
2480 SCEV::FlagAnyWrap, Depth + 1));
2481 if (Ops.empty())
2482 return getZero(Ty);
2483 if (Ops.size() == 1)
2484 return Ops[0];
2485 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
2486 }
2487 }
2488
2489 // If we are adding something to a multiply expression, make sure the
2490 // something is not already an operand of the multiply. If so, merge it into
2491 // the multiply.
2492 for (; Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx]); ++Idx) {
2493 const SCEVMulExpr *Mul = cast<SCEVMulExpr>(Ops[Idx]);
2494 for (unsigned MulOp = 0, e = Mul->getNumOperands(); MulOp != e; ++MulOp) {
2495 const SCEV *MulOpSCEV = Mul->getOperand(MulOp);
2496 if (isa<SCEVConstant>(MulOpSCEV))
2497 continue;
2498 for (unsigned AddOp = 0, e = Ops.size(); AddOp != e; ++AddOp)
2499 if (MulOpSCEV == Ops[AddOp]) {
2500 // Fold W + X + (X * Y * Z) --> W + (X * ((Y*Z)+1))
2501 const SCEV *InnerMul = Mul->getOperand(MulOp == 0);
2502 if (Mul->getNumOperands() != 2) {
2503 // If the multiply has more than two operands, we must get the
2504 // Y*Z term.
2505 SmallVector<const SCEV *, 4> MulOps(Mul->op_begin(),
2506 Mul->op_begin()+MulOp);
2507 MulOps.append(Mul->op_begin()+MulOp+1, Mul->op_end());
2508 InnerMul = getMulExpr(MulOps, SCEV::FlagAnyWrap, Depth + 1);
2509 }
2510 SmallVector<const SCEV *, 2> TwoOps = {getOne(Ty), InnerMul};
2511 const SCEV *AddOne = getAddExpr(TwoOps, SCEV::FlagAnyWrap, Depth + 1);
2512 const SCEV *OuterMul = getMulExpr(AddOne, MulOpSCEV,
2513 SCEV::FlagAnyWrap, Depth + 1);
2514 if (Ops.size() == 2) return OuterMul;
2515 if (AddOp < Idx) {
2516 Ops.erase(Ops.begin()+AddOp);
2517 Ops.erase(Ops.begin()+Idx-1);
2518 } else {
2519 Ops.erase(Ops.begin()+Idx);
2520 Ops.erase(Ops.begin()+AddOp-1);
2521 }
2522 Ops.push_back(OuterMul);
2523 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
2524 }
2525
2526 // Check this multiply against other multiplies being added together.
2527 for (unsigned OtherMulIdx = Idx+1;
2528 OtherMulIdx < Ops.size() && isa<SCEVMulExpr>(Ops[OtherMulIdx]);
2529 ++OtherMulIdx) {
2530 const SCEVMulExpr *OtherMul = cast<SCEVMulExpr>(Ops[OtherMulIdx]);
2531 // If MulOp occurs in OtherMul, we can fold the two multiplies
2532 // together.
2533 for (unsigned OMulOp = 0, e = OtherMul->getNumOperands();
2534 OMulOp != e; ++OMulOp)
2535 if (OtherMul->getOperand(OMulOp) == MulOpSCEV) {
2536 // Fold X + (A*B*C) + (A*D*E) --> X + (A*(B*C+D*E))
2537 const SCEV *InnerMul1 = Mul->getOperand(MulOp == 0);
2538 if (Mul->getNumOperands() != 2) {
2539 SmallVector<const SCEV *, 4> MulOps(Mul->op_begin(),
2540 Mul->op_begin()+MulOp);
2541 MulOps.append(Mul->op_begin()+MulOp+1, Mul->op_end());
2542 InnerMul1 = getMulExpr(MulOps, SCEV::FlagAnyWrap, Depth + 1);
2543 }
2544 const SCEV *InnerMul2 = OtherMul->getOperand(OMulOp == 0);
2545 if (OtherMul->getNumOperands() != 2) {
2546 SmallVector<const SCEV *, 4> MulOps(OtherMul->op_begin(),
2547 OtherMul->op_begin()+OMulOp);
2548 MulOps.append(OtherMul->op_begin()+OMulOp+1, OtherMul->op_end());
2549 InnerMul2 = getMulExpr(MulOps, SCEV::FlagAnyWrap, Depth + 1);
2550 }
2551 SmallVector<const SCEV *, 2> TwoOps = {InnerMul1, InnerMul2};
2552 const SCEV *InnerMulSum =
2553 getAddExpr(TwoOps, SCEV::FlagAnyWrap, Depth + 1);
2554 const SCEV *OuterMul = getMulExpr(MulOpSCEV, InnerMulSum,
2555 SCEV::FlagAnyWrap, Depth + 1);
2556 if (Ops.size() == 2) return OuterMul;
2557 Ops.erase(Ops.begin()+Idx);
2558 Ops.erase(Ops.begin()+OtherMulIdx-1);
2559 Ops.push_back(OuterMul);
2560 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
2561 }
2562 }
2563 }
2564 }
2565
2566 // If there are any add recurrences in the operands list, see if any other
2567 // added values are loop invariant. If so, we can fold them into the
2568 // recurrence.
2569 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
2570 ++Idx;
2571
2572 // Scan over all recurrences, trying to fold loop invariants into them.
2573 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
2574 // Scan all of the other operands to this add and add them to the vector if
2575 // they are loop invariant w.r.t. the recurrence.
2576 SmallVector<const SCEV *, 8> LIOps;
2577 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
2578 const Loop *AddRecLoop = AddRec->getLoop();
2579 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2580 if (isAvailableAtLoopEntry(Ops[i], AddRecLoop)) {
2581 LIOps.push_back(Ops[i]);
2582 Ops.erase(Ops.begin()+i);
2583 --i; --e;
2584 }
2585
2586 // If we found some loop invariants, fold them into the recurrence.
2587 if (!LIOps.empty()) {
2588 // NLI + LI + {Start,+,Step} --> NLI + {LI+Start,+,Step}
2589 LIOps.push_back(AddRec->getStart());
2590
2591 SmallVector<const SCEV *, 4> AddRecOps(AddRec->op_begin(),
2592 AddRec->op_end());
2593 // This follows from the fact that the no-wrap flags on the outer add
2594 // expression are applicable on the 0th iteration, when the add recurrence
2595 // will be equal to its start value.
2596 AddRecOps[0] = getAddExpr(LIOps, Flags, Depth + 1);
2597
2598 // Build the new addrec. Propagate the NUW and NSW flags if both the
2599 // outer add and the inner addrec are guaranteed to have no overflow.
2600 // Always propagate NW.
2601 Flags = AddRec->getNoWrapFlags(setFlags(Flags, SCEV::FlagNW));
2602 const SCEV *NewRec = getAddRecExpr(AddRecOps, AddRecLoop, Flags);
2603
2604 // If all of the other operands were loop invariant, we are done.
2605 if (Ops.size() == 1) return NewRec;
2606
2607 // Otherwise, add the folded AddRec by the non-invariant parts.
2608 for (unsigned i = 0;; ++i)
2609 if (Ops[i] == AddRec) {
2610 Ops[i] = NewRec;
2611 break;
2612 }
2613 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
2614 }
2615
2616 // Okay, if there weren't any loop invariants to be folded, check to see if
2617 // there are multiple AddRec's with the same loop induction variable being
2618 // added together. If so, we can fold them.
2619 for (unsigned OtherIdx = Idx+1;
2620 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);
2621 ++OtherIdx) {
2622 // We expect the AddRecExpr's to be sorted in reverse dominance order,
2623 // so that the 1st found AddRecExpr is dominated by all others.
2624 assert(DT.dominates((static_cast <bool> (DT.dominates( cast<SCEVAddRecExpr
>(Ops[OtherIdx])->getLoop()->getHeader(), AddRec->
getLoop()->getHeader()) && "AddRecExprs are not sorted in reverse dominance order?"
) ? void (0) : __assert_fail ("DT.dominates( cast<SCEVAddRecExpr>(Ops[OtherIdx])->getLoop()->getHeader(), AddRec->getLoop()->getHeader()) && \"AddRecExprs are not sorted in reverse dominance order?\""
, "/build/llvm-toolchain-snapshot-6.0~svn320940/lib/Analysis/ScalarEvolution.cpp"
, 2627, __extension__ __PRETTY_FUNCTION__))
2625 cast<SCEVAddRecExpr>(Ops[OtherIdx])->getLoop()->getHeader(),(static_cast <bool> (DT.dominates( cast<SCEVAddRecExpr
>(Ops[OtherIdx])->getLoop()->getHeader(), AddRec->
getLoop()->getHeader()) && "AddRecExprs are not sorted in reverse dominance order?"
) ? void (0) : __assert_fail ("DT.dominates( cast<SCEVAddRecExpr>(Ops[OtherIdx])->getLoop()->getHeader(), AddRec->getLoop()->getHeader()) && \"AddRecExprs are not sorted in reverse dominance order?\""
, "/build/llvm-toolchain-snapshot-6.0~svn320940/lib/Analysis/ScalarEvolution.cpp"
, 2627, __extension__ __PRETTY_FUNCTION__))
2626 AddRec->getLoop()->getHeader()) &&(static_cast <bool> (DT.dominates( cast<SCEVAddRecExpr
>(Ops[OtherIdx])->getLoop()->getHeader(), AddRec->
getLoop()->getHeader()) && "AddRecExprs are not sorted in reverse dominance order?"
) ? void (0) : __assert_fail ("DT.dominates( cast<SCEVAddRecExpr>(Ops[OtherIdx])->getLoop()->getHeader(), AddRec->getLoop()->getHeader()) && \"AddRecExprs are not sorted in reverse dominance order?\""
, "/build/llvm-toolchain-snapshot-6.0~svn320940/lib/Analysis/ScalarEvolution.cpp"
, 2627, __extension__ __PRETTY_FUNCTION__))
2627 "AddRecExprs are not sorted in reverse dominance order?")(static_cast <bool> (DT.dominates( cast<SCEVAddRecExpr
>(Ops[OtherIdx])->getLoop()->getHeader(), AddRec->
getLoop()->getHeader()) && "AddRecExprs are not sorted in reverse dominance order?"
) ? void (0) : __assert_fail ("DT.dominates( cast<SCEVAddRecExpr>(Ops[OtherIdx])->getLoop()->getHeader(), AddRec->getLoop()->getHeader()) && \"AddRecExprs are not sorted in reverse dominance order?\""
, "/build/llvm-toolchain-snapshot-6.0~svn320940/lib/Analysis/ScalarEvolution.cpp"
, 2627, __extension__ __PRETTY_FUNCTION__))
;
2628 if (AddRecLoop == cast<SCEVAddRecExpr>(Ops[OtherIdx])->getLoop()) {
2629 // Other + {A,+,B}<L> + {C,+,D}<L> --> Other + {A+C,+,B+D}<L>
2630 SmallVector<const SCEV *, 4> AddRecOps(AddRec->op_begin(),
2631 AddRec->op_end());
2632 for (; OtherIdx != Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);
2633 ++OtherIdx) {
2634 const auto *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]);
2635 if (OtherAddRec->getLoop() == AddRecLoop) {
2636 for (unsigned i = 0, e = OtherAddRec->getNumOperands();
2637 i != e; ++i) {
2638 if (i >= AddRecOps.size()) {
2639 AddRecOps.append(OtherAddRec->op_begin()+i,
2640 OtherAddRec->op_end());
2641 break;
2642 }
2643 SmallVector<const SCEV *, 2> TwoOps = {
2644 AddRecOps[i], OtherAddRec->getOperand(i)};
2645 AddRecOps[i] = getAddExpr(TwoOps, SCEV::FlagAnyWrap, Depth + 1);
2646 }
2647 Ops.erase(Ops.begin() + OtherIdx); --OtherIdx;
2648 }
2649 }
2650 // Step size has changed, so we cannot guarantee no self-wraparound.
2651 Ops[Idx] = getAddRecExpr(AddRecOps, AddRecLoop, SCEV::FlagAnyWrap);
2652 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
2653 }
2654 }
2655
2656 // Otherwise couldn't fold anything into this recurrence. Move onto the
2657 // next one.
2658 }
2659
2660 // Okay, it looks like we really DO need an add expr. Check to see if we
2661 // already have one, otherwise create a new one.
2662 return getOrCreateAddExpr(Ops, Flags);
2663}
2664
2665const SCEV *
2666ScalarEvolution::getOrCreateAddExpr(SmallVectorImpl<const SCEV *> &Ops,
2667 SCEV::NoWrapFlags Flags) {
2668 FoldingSetNodeID ID;
2669 ID.AddInteger(scAddExpr);
2670 for (const SCEV *Op : Ops)
2671 ID.AddPointer(Op);
2672 void *IP = nullptr;
2673 SCEVAddExpr *S =
2674 static_cast<SCEVAddExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
2675 if (!S) {
2676 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
2677 std::uninitialized_copy(Ops.begin(), Ops.end(), O);
2678 S = new (SCEVAllocator)
2679 SCEVAddExpr(ID.Intern(SCEVAllocator), O, Ops.size());
2680 UniqueSCEVs.InsertNode(S, IP);
2681 addToLoopUseLists(S);
2682 }
2683 S->setNoWrapFlags(Flags);
2684 return S;
2685}
2686
2687const SCEV *
2688ScalarEvolution::getOrCreateMulExpr(SmallVectorImpl<const SCEV *> &Ops,
2689 SCEV::NoWrapFlags Flags) {
2690 FoldingSetNodeID ID;
2691 ID.AddInteger(scMulExpr);
2692 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2693 ID.AddPointer(Ops[i]);
2694 void *IP = nullptr;
2695 SCEVMulExpr *S =
2696 static_cast<SCEVMulExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
2697 if (!S) {
2698 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
2699 std::uninitialized_copy(Ops.begin(), Ops.end(), O);
2700 S = new (SCEVAllocator) SCEVMulExpr(ID.Intern(SCEVAllocator),
2701 O, Ops.size());
2702 UniqueSCEVs.InsertNode(S, IP);
2703 addToLoopUseLists(S);
2704 }
2705 S->setNoWrapFlags(Flags);
2706 return S;
2707}
2708
2709static uint64_t umul_ov(uint64_t i, uint64_t j, bool &Overflow) {
2710 uint64_t k = i*j;
2711 if (j > 1 && k / j != i) Overflow = true;
2712 return k;
2713}
2714
2715/// Compute the result of "n choose k", the binomial coefficient. If an
2716/// intermediate computation overflows, Overflow will be set and the return will
2717/// be garbage. Overflow is not cleared on absence of overflow.
2718static uint64_t Choose(uint64_t n, uint64_t k, bool &Overflow) {
2719 // We use the multiplicative formula:
2720 // n(n-1)(n-2)...(n-(k-1)) / k(k-1)(k-2)...1 .
2721 // At each iteration, we take the n-th term of the numeral and divide by the
2722 // (k-n)th term of the denominator. This division will always produce an
2723 // integral result, and helps reduce the chance of overflow in the
2724 // intermediate computations. However, we can still overflow even when the
2725 // final result would fit.
2726
2727 if (n == 0 || n == k) return 1;
2728 if (k > n) return 0;
2729
2730 if (k > n/2)
2731 k = n-k;
2732
2733 uint64_t r = 1;
2734 for (uint64_t i = 1; i <= k; ++i) {
2735 r = umul_ov(r, n-(i-1), Overflow);
2736 r /= i;
2737 }
2738 return r;
2739}
2740
2741/// Determine if any of the operands in this SCEV are a constant or if
2742/// any of the add or multiply expressions in this SCEV contain a constant.
2743static bool containsConstantInAddMulChain(const SCEV *StartExpr) {
2744 struct FindConstantInAddMulChain {
2745 bool FoundConstant = false;
2746
2747 bool follow(const SCEV *S) {
2748 FoundConstant |= isa<SCEVConstant>(S);
2749 return isa<SCEVAddExpr>(S) || isa<SCEVMulExpr>(S);
2750 }
2751
2752 bool isDone() const {
2753 return FoundConstant;
2754 }
2755 };
2756
2757 FindConstantInAddMulChain F;
2758 SCEVTraversal<FindConstantInAddMulChain> ST(F);
2759 ST.visitAll(StartExpr);
2760 return F.FoundConstant;
2761}
2762
2763/// Get a canonical multiply expression, or something simpler if possible.
2764const SCEV *ScalarEvolution::getMulExpr(SmallVectorImpl<const SCEV *> &Ops,
2765 SCEV::NoWrapFlags Flags,
2766 unsigned Depth) {
2767 assert(Flags == maskFlags(Flags, SCEV::FlagNUW | SCEV::FlagNSW) &&(static_cast <bool> (Flags == maskFlags(Flags, SCEV::FlagNUW
| SCEV::FlagNSW) && "only nuw or nsw allowed") ? void
(0) : __assert_fail ("Flags == maskFlags(Flags, SCEV::FlagNUW | SCEV::FlagNSW) && \"only nuw or nsw allowed\""
, "/build/llvm-toolchain-snapshot-6.0~svn320940/lib/Analysis/ScalarEvolution.cpp"
, 2768, __extension__ __PRETTY_FUNCTION__))
2768 "only nuw or nsw allowed")(static_cast <bool> (Flags == maskFlags(Flags, SCEV::FlagNUW
| SCEV::FlagNSW) && "only nuw or nsw allowed") ? void
(0) : __assert_fail ("Flags == maskFlags(Flags, SCEV::FlagNUW | SCEV::FlagNSW) && \"only nuw or nsw allowed\""
, "/build/llvm-toolchain-snapshot-6.0~svn320940/lib/Analysis/ScalarEvolution.cpp"
, 2768, __extension__ __PRETTY_FUNCTION__))
;
2769 assert(!Ops.empty() && "Cannot get empty mul!")(static_cast <bool> (!Ops.empty() && "Cannot get empty mul!"
) ? void (0) : __assert_fail ("!Ops.empty() && \"Cannot get empty mul!\""
, "/build/llvm-toolchain-snapshot-6.0~svn320940/lib/Analysis/ScalarEvolution.cpp"
, 2769, __extension__ __PRETTY_FUNCTION__))
;
2770 if (Ops.size() == 1) return Ops[0];
2771#ifndef NDEBUG
2772 Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
2773 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
2774 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&(static_cast <bool> (getEffectiveSCEVType(Ops[i]->getType
()) == ETy && "SCEVMulExpr operand types don't match!"
) ? void (0) : __assert_fail ("getEffectiveSCEVType(Ops[i]->getType()) == ETy && \"SCEVMulExpr operand types don't match!\""
, "/build/llvm-toolchain-snapshot-6.0~svn320940/lib/Analysis/ScalarEvolution.cpp"
, 2775, __extension__ __PRETTY_FUNCTION__))
2775 "SCEVMulExpr operand types don't match!")(static_cast <bool> (getEffectiveSCEVType(Ops[i]->getType
()) == ETy && "SCEVMulExpr operand types don't match!"
) ? void (0) : __assert_fail ("getEffectiveSCEVType(Ops[i]->getType()) == ETy && \"SCEVMulExpr operand types don't match!\""
, "/build/llvm-toolchain-snapshot-6.0~svn320940/lib/Analysis/ScalarEvolution.cpp"
, 2775, __extension__ __PRETTY_FUNCTION__))
;
2776#endif
2777
2778 // Sort by complexity, this groups all similar expression types together.
2779 GroupByComplexity(Ops, &LI, DT);
2780
2781 Flags = StrengthenNoWrapFlags(this, scMulExpr, Ops, Flags);
2782
2783 // Limit recursion calls depth.
2784 if (Depth > MaxArithDepth)
2785 return getOrCreateMulExpr(Ops, Flags);
2786
2787 // If there are any constants, fold them together.
2788 unsigned Idx = 0;
2789 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
2790
2791 // C1*(C2+V) -> C1*C2 + C1*V
2792 if (Ops.size() == 2)
2793 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1]))
2794 // If any of Add's ops are Adds or Muls with a constant,
2795 // apply this transformation as well.
2796 if (Add->getNumOperands() == 2)
2797 // TODO: There are some cases where this transformation is not
2798 // profitable, for example:
2799 // Add = (C0 + X) * Y + Z.
2800 // Maybe the scope of this transformation should be narrowed down.
2801 if (containsConstantInAddMulChain(Add))
2802 return getAddExpr(getMulExpr(LHSC, Add->getOperand(0),
2803 SCEV::FlagAnyWrap, Depth + 1),
2804 getMulExpr(LHSC, Add->getOperand(1),
2805 SCEV::FlagAnyWrap, Depth + 1),
2806 SCEV::FlagAnyWrap, Depth + 1);
2807
2808 ++Idx;
2809 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
2810 // We found two constants, fold them together!
2811 ConstantInt *Fold =
2812 ConstantInt::get(getContext(), LHSC->getAPInt() * RHSC->getAPInt());
2813 Ops[0] = getConstant(Fold);
2814 Ops.erase(Ops.begin()+1); // Erase the folded element
2815 if (Ops.size() == 1) return Ops[0];
2816 LHSC = cast<SCEVConstant>(Ops[0]);
2817 }
2818
2819 // If we are left with a constant one being multiplied, strip it off.
2820 if (cast<SCEVConstant>(Ops[0])->getValue()->isOne()) {
2821 Ops.erase(Ops.begin());
2822 --Idx;
2823 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isZero()) {
2824 // If we have a multiply of zero, it will always be zero.
2825 return Ops[0];
2826 } else if (Ops[0]->isAllOnesValue()) {
2827 // If we have a mul by -1 of an add, try distributing the -1 among the
2828 // add operands.
2829 if (Ops.size() == 2) {
2830 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1])) {
2831 SmallVector<const SCEV *, 4> NewOps;
2832 bool AnyFolded = false;
2833 for (const SCEV *AddOp : Add->operands()) {
2834 const SCEV *Mul = getMulExpr(Ops[0], AddOp, SCEV::FlagAnyWrap,
2835 Depth + 1);
2836 if (!isa<SCEVMulExpr>(Mul)) AnyFolded = true;
2837 NewOps.push_back(Mul);
2838 }
2839 if (AnyFolded)
2840 return getAddExpr(NewOps, SCEV::FlagAnyWrap, Depth + 1);
2841 } else if (const auto *AddRec = dyn_cast<SCEVAddRecExpr>(Ops[1])) {
2842 // Negation preserves a recurrence's no self-wrap property.
2843 SmallVector<const SCEV *, 4> Operands;
2844 for (const SCEV *AddRecOp : AddRec->operands())
2845 Operands.push_back(getMulExpr(Ops[0], AddRecOp, SCEV::FlagAnyWrap,
2846 Depth + 1));
2847
2848 return getAddRecExpr(Operands, AddRec->getLoop(),
2849 AddRec->getNoWrapFlags(SCEV::FlagNW));
2850 }
2851 }
2852 }
2853
2854 if (Ops.size() == 1)
2855 return Ops[0];
2856 }
2857
2858 // Skip over the add expression until we get to a multiply.
2859 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
2860 ++Idx;
2861
2862 // If there are mul operands inline them all into this expression.
2863 if (Idx < Ops.size()) {
2864 bool DeletedMul = false;
2865 while (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) {
2866 if (Ops.size() > MulOpsInlineThreshold)
2867 break;
2868 // If we have an mul, expand the mul operands onto the end of the
2869 // operands list.
2870 Ops.erase(Ops.begin()+Idx);
2871 Ops.append(Mul->op_begin(), Mul->op_end());
2872 DeletedMul = true;
2873 }
2874
2875 // If we deleted at least one mul, we added operands to the end of the
2876 // list, and they are not necessarily sorted. Recurse to resort and
2877 // resimplify any operands we just acquired.
2878 if (DeletedMul)
2879 return getMulExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
2880 }
2881
2882 // If there are any add recurrences in the operands list, see if any other
2883 // added values are loop invariant. If so, we can fold them into the
2884 // recurrence.
2885 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
2886 ++Idx;
2887
2888 // Scan over all recurrences, trying to fold loop invariants into them.
2889 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
2890 // Scan all of the other operands to this mul and add them to the vector
2891 // if they are loop invariant w.r.t. the recurrence.
2892 SmallVector<const SCEV *, 8> LIOps;
2893 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
2894 const Loop *AddRecLoop = AddRec->getLoop();
2895 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2896 if (isAvailableAtLoopEntry(Ops[i], AddRecLoop)) {
2897 LIOps.push_back(Ops[i]);
2898 Ops.erase(Ops.begin()+i);
2899 --i; --e;
2900 }
2901
2902 // If we found some loop invariants, fold them into the recurrence.
2903 if (!LIOps.empty()) {
2904 // NLI * LI * {Start,+,Step} --> NLI * {LI*Start,+,LI*Step}
2905 SmallVector<const SCEV *, 4> NewOps;
2906 NewOps.reserve(AddRec->getNumOperands());
2907 const SCEV *Scale = getMulExpr(LIOps, SCEV::FlagAnyWrap, Depth + 1);
2908 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i)
2909 NewOps.push_back(getMulExpr(Scale, AddRec->getOperand(i),
2910 SCEV::FlagAnyWrap, Depth + 1));
2911
2912 // Build the new addrec. Propagate the NUW and NSW flags if both the
2913 // outer mul and the inner addrec are guaranteed to have no overflow.
2914 //
2915 // No self-wrap cannot be guaranteed after changing the step size, but
2916 // will be inferred if either NUW or NSW is true.
2917 Flags = AddRec->getNoWrapFlags(clearFlags(Flags, SCEV::FlagNW));
2918 const SCEV *NewRec = getAddRecExpr(NewOps, AddRecLoop, Flags);
2919
2920 // If all of the other operands were loop invariant, we are done.
2921 if (Ops.size() == 1) return NewRec;
2922
2923 // Otherwise, multiply the folded AddRec by the non-invariant parts.
2924 for (unsigned i = 0;; ++i)
2925 if (Ops[i] == AddRec) {
2926 Ops[i] = NewRec;
2927 break;
2928 }
2929 return getMulExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
2930 }
2931
2932 // Okay, if there weren't any loop invariants to be folded, check to see
2933 // if there are multiple AddRec's with the same loop induction variable
2934 // being multiplied together. If so, we can fold them.
2935
2936 // {A1,+,A2,+,...,+,An}<L> * {B1,+,B2,+,...,+,Bn}<L>
2937 // = {x=1 in [ sum y=x..2x [ sum z=max(y-x, y-n)..min(x,n) [
2938 // choose(x, 2x)*choose(2x-y, x-z)*A_{y-z}*B_z
2939 // ]]],+,...up to x=2n}.
2940 // Note that the arguments to choose() are always integers with values
2941 // known at compile time, never SCEV objects.
2942 //
2943 // The implementation avoids pointless extra computations when the two
2944 // addrec's are of different length (mathematically, it's equivalent to
2945 // an infinite stream of zeros on the right).
2946 bool OpsModified = false;
2947 for (unsigned OtherIdx = Idx+1;
2948 OtherIdx != Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);
2949 ++OtherIdx) {
2950 const SCEVAddRecExpr *OtherAddRec =
2951 dyn_cast<SCEVAddRecExpr>(Ops[OtherIdx]);
2952 if (!OtherAddRec || OtherAddRec->getLoop() != AddRecLoop)
2953 continue;
2954
2955 // Limit max number of arguments to avoid creation of unreasonably big
2956 // SCEVAddRecs with very complex operands.
2957 if (AddRec->getNumOperands() + OtherAddRec->getNumOperands() - 1 >
2958 MaxAddRecSize)
2959 continue;
2960
2961 bool Overflow = false;
2962 Type *Ty = AddRec->getType();
2963 bool LargerThan64Bits = getTypeSizeInBits(Ty) > 64;
2964 SmallVector<const SCEV*, 7> AddRecOps;
2965 for (int x = 0, xe = AddRec->getNumOperands() +
2966 OtherAddRec->getNumOperands() - 1; x != xe && !Overflow; ++x) {
2967 const SCEV *Term = getZero(Ty);
2968 for (int y = x, ye = 2*x+1; y != ye && !Overflow; ++y) {
2969 uint64_t Coeff1 = Choose(x, 2*x - y, Overflow);
2970 for (int z = std::max(y-x, y-(int)AddRec->getNumOperands()+1),
2971 ze = std::min(x+1, (int)OtherAddRec->getNumOperands());
2972 z < ze && !Overflow; ++z) {
2973 uint64_t Coeff2 = Choose(2*x - y, x-z, Overflow);
2974 uint64_t Coeff;
2975 if (LargerThan64Bits)
2976 Coeff = umul_ov(Coeff1, Coeff2, Overflow);
2977 else
2978 Coeff = Coeff1*Coeff2;
2979 const SCEV *CoeffTerm = getConstant(Ty, Coeff);
2980 const SCEV *Term1 = AddRec->getOperand(y-z);
2981 const SCEV *Term2 = OtherAddRec->getOperand(z);
2982 Term = getAddExpr(Term, getMulExpr(CoeffTerm, Term1, Term2,
2983 SCEV::FlagAnyWrap, Depth + 1),
2984 SCEV::FlagAnyWrap, Depth + 1);
2985 }
2986 }
2987 AddRecOps.push_back(Term);
2988 }
2989 if (!Overflow) {
2990 const SCEV *NewAddRec = getAddRecExpr(AddRecOps, AddRec->getLoop(),
2991 SCEV::FlagAnyWrap);
2992 if (Ops.size() == 2) return NewAddRec;
2993 Ops[Idx] = NewAddRec;
2994 Ops.erase(Ops.begin() + OtherIdx); --OtherIdx;
2995 OpsModified = true;
2996 AddRec = dyn_cast<SCEVAddRecExpr>(NewAddRec);
2997 if (!AddRec)
2998 break;
2999 }
3000 }
3001 if (OpsModified)
3002 return getMulExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
3003
3004 // Otherwise couldn't fold anything into this recurrence. Move onto the
3005 // next one.
3006 }
3007
3008 // Okay, it looks like we really DO need an mul expr. Check to see if we
3009 // already have one, otherwise create a new one.
3010 return getOrCreateMulExpr(Ops, Flags);
3011}
3012
3013/// Represents an unsigned remainder expression based on unsigned division.
3014const SCEV *ScalarEvolution::getURemExpr(const SCEV *LHS,
3015 const SCEV *RHS) {
3016 assert(getEffectiveSCEVType(LHS->getType()) ==(static_cast <bool> (getEffectiveSCEVType(LHS->getType
()) == getEffectiveSCEVType(RHS->getType()) && "SCEVURemExpr operand types don't match!"
) ? void (0) : __assert_fail ("getEffectiveSCEVType(LHS->getType()) == getEffectiveSCEVType(RHS->getType()) && \"SCEVURemExpr operand types don't match!\""
, "/build/llvm-toolchain-snapshot-6.0~svn320940/lib/Analysis/ScalarEvolution.cpp"
, 3018, __extension__ __PRETTY_FUNCTION__))
3017 getEffectiveSCEVType(RHS->getType()) &&(static_cast <bool> (getEffectiveSCEVType(LHS->getType
()) == getEffectiveSCEVType(RHS->getType()) && "SCEVURemExpr operand types don't match!"
) ? void (0) : __assert_fail ("getEffectiveSCEVType(LHS->getType()) == getEffectiveSCEVType(RHS->getType()) && \"SCEVURemExpr operand types don't match!\""
, "/build/llvm-toolchain-snapshot-6.0~svn320940/lib/Analysis/ScalarEvolution.cpp"
, 3018, __extension__ __PRETTY_FUNCTION__))
3018 "SCEVURemExpr operand types don't match!")(static_cast <bool> (getEffectiveSCEVType(LHS->getType
()) == getEffectiveSCEVType(RHS->getType()) && "SCEVURemExpr operand types don't match!"
) ? void (0) : __assert_fail ("getEffectiveSCEVType(LHS->getType()) == getEffectiveSCEVType(RHS->getType()) && \"SCEVURemExpr operand types don't match!\""
, "/build/llvm-toolchain-snapshot-6.0~svn320940/lib/Analysis/ScalarEvolution.cpp"
, 3018, __extension__ __PRETTY_FUNCTION__))
;
3019
3020 // Short-circuit easy cases
3021 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
3022 // If constant is one, the result is trivial
3023 if (RHSC->getValue()->isOne())
3024 return getZero(LHS->getType()); // X urem 1 --> 0
3025
3026 // If constant is a power of two, fold into a zext(trunc(LHS)).
3027 if (RHSC->getAPInt().isPowerOf2()) {
3028 Type *FullTy = LHS->getType();
3029 Type *TruncTy =
3030 IntegerType::get(getContext(), RHSC->getAPInt().logBase2());
3031 return getZeroExtendExpr(getTruncateExpr(LHS, TruncTy), FullTy);
3032 }
3033 }
3034
3035 // Fallback to %a == %x urem %y == %x -<nuw> ((%x udiv %y) *<nuw> %y)
3036 const SCEV *UDiv = getUDivExpr(LHS, RHS);
3037 const SCEV *Mult = getMulExpr(UDiv, RHS, SCEV::FlagNUW);
3038 return getMinusSCEV(LHS, Mult, SCEV::FlagNUW);
3039}
3040
3041/// Get a canonical unsigned division expression, or something simpler if
3042/// possible.
3043const SCEV *ScalarEvolution::getUDivExpr(const SCEV *LHS,
3044 const SCEV *RHS) {
3045 assert(getEffectiveSCEVType(LHS->getType()) ==(static_cast <bool> (getEffectiveSCEVType(LHS->getType
()) == getEffectiveSCEVType(RHS->getType()) && "SCEVUDivExpr operand types don't match!"
) ? void (0) : __assert_fail ("getEffectiveSCEVType(LHS->getType()) == getEffectiveSCEVType(RHS->getType()) && \"SCEVUDivExpr operand types don't match!\""
, "/build/llvm-toolchain-snapshot-6.0~svn320940/lib/Analysis/ScalarEvolution.cpp"
, 3047, __extension__ __PRETTY_FUNCTION__))
3046 getEffectiveSCEVType(RHS->getType()) &&(static_cast <bool> (getEffectiveSCEVType(LHS->getType
()) == getEffectiveSCEVType(RHS->getType()) && "SCEVUDivExpr operand types don't match!"
) ? void (0) : __assert_fail ("getEffectiveSCEVType(LHS->getType()) == getEffectiveSCEVType(RHS->getType()) && \"SCEVUDivExpr operand types don't match!\""
, "/build/llvm-toolchain-snapshot-6.0~svn320940/lib/Analysis/ScalarEvolution.cpp"
, 3047, __extension__ __PRETTY_FUNCTION__))
3047 "SCEVUDivExpr operand types don't match!")(static_cast <bool> (getEffectiveSCEVType(LHS->getType
()) == getEffectiveSCEVType(RHS->getType()) && "SCEVUDivExpr operand types don't match!"
) ? void (0) : __assert_fail ("getEffectiveSCEVType(LHS->getType()) == getEffectiveSCEVType(RHS->getType()) && \"SCEVUDivExpr operand types don't match!\""
, "/build/llvm-toolchain-snapshot-6.0~svn320940/lib/Analysis/ScalarEvolution.cpp"
, 3047, __extension__ __PRETTY_FUNCTION__))
;
3048
3049 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
3050 if (RHSC->getValue()->isOne())
3051 return LHS; // X udiv 1 --> x
3052 // If the denominator is zero, the result of the udiv is undefined. Don't
3053 // try to analyze it, because the resolution chosen here may differ from
3054 // the resolution chosen in other parts of the compiler.
3055 if (!RHSC->getValue()->isZero()) {
3056 // Determine if the division can be folded into the operands of
3057 // its operands.
3058 // TODO: Generalize this to non-constants by using known-bits information.
3059 Type *Ty = LHS->getType();
3060 unsigned LZ = RHSC->getAPInt().countLeadingZeros();
3061 unsigned MaxShiftAmt = getTypeSizeInBits(Ty) - LZ - 1;
3062 // For non-power-of-two values, effectively round the value up to the
3063 // nearest power of two.
3064 if (!RHSC->getAPInt().isPowerOf2())
3065 ++MaxShiftAmt;
3066 IntegerType *ExtTy =
3067 IntegerType::get(getContext(), getTypeSizeInBits(Ty) + MaxShiftAmt);
3068 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(LHS))
3069 if (const SCEVConstant *Step =
3070 dyn_cast<SCEVConstant>(AR->getStepRecurrence(*this))) {
3071 // {X,+,N}/C --> {X/C,+,N/C} if safe and N/C can be folded.
3072 const APInt &StepInt = Step->getAPInt();
3073 const APInt &DivInt = RHSC->getAPInt();
3074 if (!StepInt.urem(DivInt) &&
3075 getZeroExtendExpr(AR, ExtTy) ==
3076 getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy),
3077 getZeroExtendExpr(Step, ExtTy),
3078 AR->getLoop(), SCEV::FlagAnyWrap)) {
3079 SmallVector<const SCEV *, 4> Operands;
3080 for (const SCEV *Op : AR->operands())
3081 Operands.push_back(getUDivExpr(Op, RHS));
3082 return getAddRecExpr(Operands, AR->getLoop(), SCEV::FlagNW);
3083 }
3084 /// Get a canonical UDivExpr for a recurrence.
3085 /// {X,+,N}/C => {Y,+,N}/C where Y=X-(X%N). Safe when C%N=0.
3086 // We can currently only fold X%N if X is constant.
3087 const SCEVConstant *StartC = dyn_cast<SCEVConstant>(AR->getStart());
3088 if (StartC && !DivInt.urem(StepInt) &&
3089 getZeroExtendExpr(AR, ExtTy) ==
3090 getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy),
3091 getZeroExtendExpr(Step, ExtTy),
3092 AR->getLoop(), SCEV::FlagAnyWrap)) {
3093 const APInt &StartInt = StartC->getAPInt();
3094 const APInt &StartRem = StartInt.urem(StepInt);
3095 if (StartRem != 0)
3096 LHS = getAddRecExpr(getConstant(StartInt - StartRem), Step,
3097 AR->getLoop(), SCEV::FlagNW);
3098 }
3099 }
3100 // (A*B)/C --> A*(B/C) if safe and B/C can be folded.
3101 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(LHS)) {
3102 SmallVector<const SCEV *, 4> Operands;
3103 for (const SCEV *Op : M->operands())
3104 Operands.push_back(getZeroExtendExpr(Op, ExtTy));
3105 if (getZeroExtendExpr(M, ExtTy) == getMulExpr(Operands))
3106 // Find an operand that's safely divisible.
3107 for (unsigned i = 0, e = M->getNumOperands(); i != e; ++i) {
3108 const SCEV *Op = M->getOperand(i);
3109 const SCEV *Div = getUDivExpr(Op, RHSC);
3110 if (!isa<SCEVUDivExpr>(Div) && getMulExpr(Div, RHSC) == Op) {
3111 Operands = SmallVector<const SCEV *, 4>(M->op_begin(),
3112 M->op_end());
3113 Operands[i] = Div;
3114 return getMulExpr(Operands);
3115 }
3116 }
3117 }
3118 // (A+B)/C --> (A/C + B/C) if safe and A/C and B/C can be folded.
3119 if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(LHS)) {
3120 SmallVector<const SCEV *, 4> Operands;
3121 for (const SCEV *Op : A->operands())
3122 Operands.push_back(getZeroExtendExpr(Op, ExtTy));
3123 if (getZeroExtendExpr(A, ExtTy) == getAddExpr(Operands)) {
3124 Operands.clear();
3125 for (unsigned i = 0, e = A->getNumOperands(); i != e; ++i) {
3126 const SCEV *Op = getUDivExpr(A->getOperand(i), RHS);
3127 if (isa<SCEVUDivExpr>(Op) ||
3128 getMulExpr(Op, RHS) != A->getOperand(i))
3129 break;
3130 Operands.push_back(Op);
3131 }
3132 if (Operands.size() == A->getNumOperands())
3133 return getAddExpr(Operands);
3134 }
3135 }
3136
3137 // Fold if both operands are constant.
3138 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) {
3139 Constant *LHSCV = LHSC->getValue();
3140 Constant *RHSCV = RHSC->getValue();
3141 return getConstant(cast<ConstantInt>(ConstantExpr::getUDiv(LHSCV,
3142 RHSCV)));
3143 }
3144 }
3145 }
3146
3147 FoldingSetNodeID ID;
3148 ID.AddInteger(scUDivExpr);
3149 ID.AddPointer(LHS);
3150 ID.AddPointer(RHS);
3151 void *IP = nullptr;
3152 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
3153 SCEV *S = new (SCEVAllocator) SCEVUDivExpr(ID.Intern(SCEVAllocator),
3154 LHS, RHS);
3155 UniqueSCEVs.InsertNode(S, IP);
3156 addToLoopUseLists(S);
3157 return S;
3158}
3159
3160static const APInt gcd(const SCEVConstant *C1, const SCEVConstant *C2) {
3161 APInt A = C1->getAPInt().abs();
3162 APInt B = C2->getAPInt().abs();
3163 uint32_t ABW = A.getBitWidth();
3164 uint32_t BBW = B.getBitWidth();
3165
3166 if (ABW > BBW)
3167 B = B.zext(ABW);
3168 else if (ABW < BBW)
3169 A = A.zext(BBW);
3170
3171 return APIntOps::GreatestCommonDivisor(std::move(A), std::move(B));
3172}
3173
3174/// Get a canonical unsigned division expression, or something simpler if
3175/// possible. There is no representation for an exact udiv in SCEV IR, but we
3176/// can attempt to remove factors from the LHS and RHS. We can't do this when
3177/// it's not exact because the udiv may be clearing bits.
3178const SCEV *ScalarEvolution::getUDivExactExpr(const SCEV *LHS,
3179 const SCEV *RHS) {
3180 // TODO: we could try to find factors in all sorts of things, but for now we
3181 // just deal with u/exact (multiply, constant). See SCEVDivision towards the
3182 // end of this file for inspiration.
3183
3184 const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(LHS);
3185 if (!Mul || !Mul->hasNoUnsignedWrap())
3186 return getUDivExpr(LHS, RHS);
3187
3188 if (const SCEVConstant *RHSCst = dyn_cast<SCEVConstant>(RHS)) {
3189 // If the mulexpr multiplies by a constant, then that constant must be the
3190 // first element of the mulexpr.
3191 if (const auto *LHSCst = dyn_cast<SCEVConstant>(Mul->getOperand(0))) {
3192 if (LHSCst == RHSCst) {
3193 SmallVector<const SCEV *, 2> Operands;
3194 Operands.append(Mul->op_begin() + 1, Mul->op_end());
3195 return getMulExpr(Operands);
3196 }
3197
3198 // We can't just assume that LHSCst divides RHSCst cleanly, it could be
3199 // that there's a factor provided by one of the other terms. We need to
3200 // check.
3201 APInt Factor = gcd(LHSCst, RHSCst);
3202 if (!Factor.isIntN(1)) {
3203 LHSCst =
3204 cast<SCEVConstant>(getConstant(LHSCst->getAPInt().udiv(Factor)));
3205 RHSCst =
3206 cast<SCEVConstant>(getConstant(RHSCst->getAPInt().udiv(Factor)));
3207 SmallVector<const SCEV *, 2> Operands;
3208 Operands.push_back(LHSCst);
3209 Operands.append(Mul->op_begin() + 1, Mul->op_end());
3210 LHS = getMulExpr(Operands);
3211 RHS = RHSCst;
3212 Mul = dyn_cast<SCEVMulExpr>(LHS);
3213 if (!Mul)
3214 return getUDivExactExpr(LHS, RHS);
3215 }
3216 }
3217 }
3218
3219 for (int i = 0, e = Mul->getNumOperands(); i != e; ++i) {
3220 if (Mul->getOperand(i) == RHS) {
3221 SmallVector<const SCEV *, 2> Operands;
3222 Operands.append(Mul->op_begin(), Mul->op_begin() + i);
3223 Operands.append(Mul->op_begin() + i + 1, Mul->op_end());
3224 return getMulExpr(Operands);
3225 }
3226 }
3227
3228 return getUDivExpr(LHS, RHS);
3229}
3230
3231/// Get an add recurrence expression for the specified loop. Simplify the
3232/// expression as much as possible.
3233const SCEV *ScalarEvolution::getAddRecExpr(const SCEV *Start, const SCEV *Step,
3234 const Loop *L,
3235 SCEV::NoWrapFlags Flags) {
3236 SmallVector<const SCEV *, 4> Operands;
3237 Operands.push_back(Start);
3238 if (const SCEVAddRecExpr *StepChrec = dyn_cast<SCEVAddRecExpr>(Step))
3239 if (StepChrec->getLoop() == L) {
3240 Operands.append(StepChrec->op_begin(), StepChrec->op_end());
3241 return getAddRecExpr(Operands, L, maskFlags(Flags, SCEV::FlagNW));
3242 }
3243
3244 Operands.push_back(Step);
3245 return getAddRecExpr(Operands, L, Flags);
3246}
3247
3248/// Get an add recurrence expression for the specified loop. Simplify the
3249/// expression as much as possible.
3250const SCEV *
3251ScalarEvolution::getAddRecExpr(SmallVectorImpl<const SCEV *> &Operands,
3252 const Loop *L, SCEV::NoWrapFlags Flags) {
3253 if (Operands.size() == 1) return Operands[0];
3254#ifndef NDEBUG
3255 Type *ETy = getEffectiveSCEVType(Operands[0]->getType());
3256 for (unsigned i = 1, e = Operands.size(); i != e; ++i)
3257 assert(getEffectiveSCEVType(Operands[i]->getType()) == ETy &&(static_cast <bool> (getEffectiveSCEVType(Operands[i]->
getType()) == ETy && "SCEVAddRecExpr operand types don't match!"
) ? void (0) : __assert_fail ("getEffectiveSCEVType(Operands[i]->getType()) == ETy && \"SCEVAddRecExpr operand types don't match!\""
, "/build/llvm-toolchain-snapshot-6.0~svn320940/lib/Analysis/ScalarEvolution.cpp"
, 3258, __extension__ __PRETTY_FUNCTION__))
3258 "SCEVAddRecExpr operand types don't match!")(static_cast <bool> (getEffectiveSCEVType(Operands[i]->
getType()) == ETy && "SCEVAddRecExpr operand types don't match!"
) ? void (0) : __assert_fail ("getEffectiveSCEVType(Operands[i]->getType()) == ETy && \"SCEVAddRecExpr operand types don't match!\""
, "/build/llvm-toolchain-snapshot-6.0~svn320940/lib/Analysis/ScalarEvolution.cpp"
, 3258, __extension__ __PRETTY_FUNCTION__))
;
3259 for (unsigned i = 0, e = Operands.size(); i != e; ++i)
3260 assert(isLoopInvariant(Operands[i], L) &&(static_cast <bool> (isLoopInvariant(Operands[i], L) &&
"SCEVAddRecExpr operand is not loop-invariant!") ? void (0) :
__assert_fail ("isLoopInvariant(Operands[i], L) && \"SCEVAddRecExpr operand is not loop-invariant!\""
, "/build/llvm-toolchain-snapshot-6.0~svn320940/lib/Analysis/ScalarEvolution.cpp"
, 3261, __extension__ __PRETTY_FUNCTION__))
3261 "SCEVAddRecExpr operand is not loop-invariant!")(static_cast <bool> (isLoopInvariant(Operands[i], L) &&
"SCEVAddRecExpr operand is not loop-invariant!") ? void (0) :
__assert_fail ("isLoopInvariant(Operands[i], L) && \"SCEVAddRecExpr operand is not loop-invariant!\""
, "/build/llvm-toolchain-snapshot-6.0~svn320940/lib/Analysis/ScalarEvolution.cpp"
, 3261, __extension__ __PRETTY_FUNCTION__))
;
3262#endif
3263
3264 if (Operands.back()->isZero()) {
3265 Operands.pop_back();
3266 return getAddRecExpr(Operands, L, SCEV::FlagAnyWrap); // {X,+,0} --> X
3267 }
3268
3269 // It's tempting to want to call getMaxBackedgeTakenCount count here and
3270 // use that information to infer NUW and NSW flags. However, computing a
3271 // BE count requires calling getAddRecExpr, so we may not yet have a
3272 // meaningful BE count at this point (and if we don't, we'd be stuck
3273 // with a SCEVCouldNotCompute as the cached BE count).
3274
3275 Flags = StrengthenNoWrapFlags(this, scAddRecExpr, Operands, Flags);
3276
3277 // Canonicalize nested AddRecs in by nesting them in order of loop depth.
3278 if (const SCEVAddRecExpr *NestedAR = dyn_cast<SCEVAddRecExpr>(Operands[0])) {
3279 const Loop *NestedLoop = NestedAR->getLoop();
3280 if (L->contains(NestedLoop)
3281 ? (L->getLoopDepth() < NestedLoop->getLoopDepth())
3282 : (!NestedLoop->contains(L) &&
3283 DT.dominates(L->getHeader(), NestedLoop->getHeader()))) {
3284 SmallVector<const SCEV *, 4> NestedOperands(NestedAR->op_begin(),
3285 NestedAR->op_end());
3286 Operands[0] = NestedAR->getStart();
3287 // AddRecs require their operands be loop-invariant with respect to their
3288 // loops. Don't perform this transformation if it would break this
3289 // requirement.
3290 bool AllInvariant = all_of(
3291 Operands, [&](const SCEV *Op) { return isLoopInvariant(Op, L); });
3292
3293 if (AllInvariant) {
3294 // Create a recurrence for the outer loop with the same step size.
3295 //
3296 // The outer recurrence keeps its NW flag but only keeps NUW/NSW if the
3297 // inner recurrence has the same property.
3298 SCEV::NoWrapFlags OuterFlags =
3299 maskFlags(Flags, SCEV::FlagNW | NestedAR->getNoWrapFlags());
3300
3301 NestedOperands[0] = getAddRecExpr(Operands, L, OuterFlags);
3302 AllInvariant = all_of(NestedOperands, [&](const SCEV *Op) {
3303 return isLoopInvariant(Op, NestedLoop);
3304 });
3305
3306 if (AllInvariant) {
3307 // Ok, both add recurrences are valid after the transformation.
3308 //
3309 // The inner recurrence keeps its NW flag but only keeps NUW/NSW if
3310 // the outer recurrence has the same property.
3311 SCEV::NoWrapFlags InnerFlags =
3312 maskFlags(NestedAR->getNoWrapFlags(), SCEV::FlagNW | Flags);
3313 return getAddRecExpr(NestedOperands, NestedLoop, InnerFlags);
3314 }
3315 }
3316 // Reset Operands to its original state.
3317 Operands[0] = NestedAR;
3318 }
3319 }
3320
3321 // Okay, it looks like we really DO need an addrec expr. Check to see if we
3322 // already have one, otherwise create a new one.
3323 FoldingSetNodeID ID;
3324 ID.AddInteger(scAddRecExpr);
3325 for (unsigned i = 0, e = Operands.size(); i != e; ++i)
3326 ID.AddPointer(Operands[i]);
3327 ID.AddPointer(L);
3328 void *IP = nullptr;
3329 SCEVAddRecExpr *S =
3330 static_cast<SCEVAddRecExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
3331 if (!S) {
3332 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Operands.size());
3333 std::uninitialized_copy(Operands.begin(), Operands.end(), O);
3334 S = new (SCEVAllocator) SCEVAddRecExpr(ID.Intern(SCEVAllocator),
3335 O, Operands.size(), L);
3336 UniqueSCEVs.InsertNode(S, IP);
3337 addToLoopUseLists(S);
3338 }
3339 S->setNoWrapFlags(Flags);
3340 return S;
3341}
3342
3343const SCEV *
3344ScalarEvolution::getGEPExpr(GEPOperator *GEP,
3345 const SmallVectorImpl<const SCEV *> &IndexExprs) {
3346 const SCEV *BaseExpr = getSCEV(GEP->getPointerOperand());
3347 // getSCEV(Base)->getType() has the same address space as Base->getType()
3348 // because SCEV::getType() preserves the address space.
3349 Type *IntPtrTy = getEffectiveSCEVType(BaseExpr->getType());
3350 // FIXME(PR23527): Don't blindly transfer the inbounds flag from the GEP
3351 // instruction to its SCEV, because the Instruction may be guarded by control
3352 // flow and the no-overflow bits may not be valid for the expression in any
3353 // context. This can be fixed similarly to how these flags are handled for
3354 // adds.
3355 SCEV::NoWrapFlags Wrap = GEP->isInBounds() ? SCEV::FlagNSW
3356 : SCEV::FlagAnyWrap;
3357
3358 const SCEV *TotalOffset = getZero(IntPtrTy);
3359 // The array size is unimportant. The first thing we do on CurTy is getting
3360 // its element type.
3361 Type *CurTy = ArrayType::get(GEP->getSourceElementType(), 0);
3362 for (const SCEV *IndexExpr : IndexExprs) {
3363 // Compute the (potentially symbolic) offset in bytes for this index.
3364 if (StructType *STy = dyn_cast<StructType>(CurTy)) {
3365 // For a struct, add the member offset.
3366 ConstantInt *Index = cast<SCEVConstant>(IndexExpr)->getValue();
3367 unsigned FieldNo = Index->getZExtValue();
3368 const SCEV *FieldOffset = getOffsetOfExpr(IntPtrTy, STy, FieldNo);
3369
3370 // Add the field offset to the running total offset.
3371 TotalOffset = getAddExpr(TotalOffset, FieldOffset);
3372
3373 // Update CurTy to the type of the field at Index.
3374 CurTy = STy->getTypeAtIndex(Index);
3375 } else {
3376 // Update CurTy to its element type.
3377 CurTy = cast<SequentialType>(CurTy)->getElementType();
3378 // For an array, add the element offset, explicitly scaled.
3379 const SCEV *ElementSize = getSizeOfExpr(IntPtrTy, CurTy);
3380 // Getelementptr indices are signed.
3381 IndexExpr = getTruncateOrSignExtend(IndexExpr, IntPtrTy);
3382
3383 // Multiply the index by the element size to compute the element offset.
3384 const SCEV *LocalOffset = getMulExpr(IndexExpr, ElementSize, Wrap);
3385
3386 // Add the element offset to the running total offset.
3387 TotalOffset = getAddExpr(TotalOffset, LocalOffset);
3388 }
3389 }
3390
3391 // Add the total offset from all the GEP indices to the base.
3392 return getAddExpr(BaseExpr, TotalOffset, Wrap);
3393}
3394
3395const SCEV *ScalarEvolution::getSMaxExpr(const SCEV *LHS,
3396 const SCEV *RHS) {
3397 SmallVector<const SCEV *, 2> Ops = {LHS, RHS};
3398 return getSMaxExpr(Ops);
3399}
3400
3401const SCEV *
3402ScalarEvolution::getSMaxExpr(SmallVectorImpl<const SCEV *> &Ops) {
3403 assert(!Ops.empty() && "Cannot get empty smax!")(static_cast <bool> (!Ops.empty() && "Cannot get empty smax!"
) ? void (0) : __assert_fail ("!Ops.empty() && \"Cannot get empty smax!\""
, "/build/llvm-toolchain-snapshot-6.0~svn320940/lib/Analysis/ScalarEvolution.cpp"
, 3403, __extension__ __PRETTY_FUNCTION__))
;
3404 if (Ops.size() == 1) return Ops[0];
3405#ifndef NDEBUG
3406 Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
3407 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
3408 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&(static_cast <bool> (getEffectiveSCEVType(Ops[i]->getType
()) == ETy && "SCEVSMaxExpr operand types don't match!"
) ? void (0) : __assert_fail ("getEffectiveSCEVType(Ops[i]->getType()) == ETy && \"SCEVSMaxExpr operand types don't match!\""
, "/build/llvm-toolchain-snapshot-6.0~svn320940/lib/Analysis/ScalarEvolution.cpp"
, 3409, __extension__ __PRETTY_FUNCTION__))
3409 "SCEVSMaxExpr operand types don't match!")(static_cast <bool> (getEffectiveSCEVType(Ops[i]->getType
()) == ETy && "SCEVSMaxExpr operand types don't match!"
) ? void (0) : __assert_fail ("getEffectiveSCEVType(Ops[i]->getType()) == ETy && \"SCEVSMaxExpr operand types don't match!\""
, "/build/llvm-toolchain-snapshot-6.0~svn320940/lib/Analysis/ScalarEvolution.cpp"
, 3409, __extension__ __PRETTY_FUNCTION__))
;
3410#endif
3411
3412 // Sort by complexity, this groups all similar expression types together.
3413 GroupByComplexity(Ops, &LI, DT);
3414
3415 // If there are any constants, fold them together.
3416 unsigned Idx = 0;
3417 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
3418 ++Idx;
3419 assert(Idx < Ops.size())(static_cast <bool> (Idx < Ops.size()) ? void (0) : __assert_fail
("Idx < Ops.size()", "/build/llvm-toolchain-snapshot-6.0~svn320940/lib/Analysis/ScalarEvolution.cpp"
, 3419, __extension__ __PRETTY_FUNCTION__))
;
3420 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
3421 // We found two constants, fold them together!
3422 ConstantInt *Fold = ConstantInt::get(
3423 getContext(), APIntOps::smax(LHSC->getAPInt(), RHSC->getAPInt()));
3424 Ops[0] = getConstant(Fold);
3425 Ops.erase(Ops.begin()+1); // Erase the folded element
3426 if (Ops.size() == 1) return Ops[0];
3427 LHSC = cast<SCEVConstant>(Ops[0]);
3428 }
3429
3430 // If we are left with a constant minimum-int, strip it off.
3431 if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(true)) {
3432 Ops.erase(Ops.begin());
3433 --Idx;
3434 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isMaxValue(true)) {
3435 // If we have an smax with a constant maximum-int, it will always be
3436 // maximum-int.
3437 return Ops[0];
3438 }
3439
3440 if (Ops.size() == 1) return Ops[0];
3441 }
3442
3443 // Find the first SMax
3444 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scSMaxExpr)
3445 ++Idx;
3446
3447 // Check to see if one of the operands is an SMax. If so, expand its operands
3448 // onto our operand list, and recurse to simplify.
3449 if (Idx < Ops.size()) {
3450 bool DeletedSMax = false;
3451 while (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(Ops[Idx])) {
3452 Ops.erase(Ops.begin()+Idx);
3453 Ops.append(SMax->op_begin(), SMax->op_end());
3454 DeletedSMax = true;
3455 }
3456
3457 if (DeletedSMax)
3458 return getSMaxExpr(Ops);
3459 }
3460
3461 // Okay, check to see if the same value occurs in the operand list twice. If
3462 // so, delete one. Since we sorted the list, these values are required to
3463 // be adjacent.
3464 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
3465 // X smax Y smax Y --> X smax Y
3466 // X smax Y --> X, if X is always greater than Y
3467 if (Ops[i] == Ops[i+1] ||
3468 isKnownPredicate(ICmpInst::ICMP_SGE, Ops[i], Ops[i+1])) {
3469 Ops.erase(Ops.begin()+i+1, Ops.begin()+i+2);
3470 --i; --e;
3471 } else if (isKnownPredicate(ICmpInst::ICMP_SLE, Ops[i], Ops[i+1])) {
3472 Ops.erase(Ops.begin()+i, Ops.begin()+i+1);
3473 --i; --e;
3474 }
3475
3476 if (Ops.size() == 1) return Ops[0];
3477
3478 assert(!Ops.empty() && "Reduced smax down to nothing!")(static_cast <bool> (!Ops.empty() && "Reduced smax down to nothing!"
) ? void (0) : __assert_fail ("!Ops.empty() && \"Reduced smax down to nothing!\""
, "/build/llvm-toolchain-snapshot-6.0~svn320940/lib/Analysis/ScalarEvolution.cpp"
, 3478, __extension__ __PRETTY_FUNCTION__))
;
3479
3480 // Okay, it looks like we really DO need an smax expr. Check to see if we
3481 // already have one, otherwise create a new one.
3482 FoldingSetNodeID ID;
3483 ID.AddInteger(scSMaxExpr);
3484 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
3485 ID.AddPointer(Ops[i]);
3486 void *IP = nullptr;
3487 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
3488 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
3489 std::uninitialized_copy(Ops.begin(), Ops.end(), O);
3490 SCEV *S = new (SCEVAllocator) SCEVSMaxExpr(ID.Intern(SCEVAllocator),
3491 O, Ops.size());
3492 UniqueSCEVs.InsertNode(S, IP);
3493 addToLoopUseLists(S);
3494 return S;
3495}
3496
3497const SCEV *ScalarEvolution::getUMaxExpr(const SCEV *LHS,
3498 const SCEV *RHS) {
3499 SmallVector<const SCEV *, 2> Ops = {LHS, RHS};
3500 return getUMaxExpr(Ops);
3501}
3502
3503const SCEV *
3504ScalarEvolution::getUMaxExpr(SmallVectorImpl<const SCEV *> &Ops) {
3505 assert(!Ops.empty() && "Cannot get empty umax!")(static_cast <bool> (!Ops.empty() && "Cannot get empty umax!"
) ? void (0) : __assert_fail ("!Ops.empty() && \"Cannot get empty umax!\""
, "/build/llvm-toolchain-snapshot-6.0~svn320940/lib/Analysis/ScalarEvolution.cpp"
, 3505, __extension__ __PRETTY_FUNCTION__))
;
3506 if (Ops.size() == 1) return Ops[0];
3507#ifndef NDEBUG
3508 Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
3509 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
3510 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&(static_cast <bool> (getEffectiveSCEVType(Ops[i]->getType
()) == ETy && "SCEVUMaxExpr operand types don't match!"
) ? void (0) : __assert_fail ("getEffectiveSCEVType(Ops[i]->getType()) == ETy && \"SCEVUMaxExpr operand types don't match!\""
, "/build/llvm-toolchain-snapshot-6.0~svn320940/lib/Analysis/ScalarEvolution.cpp"
, 3511, __extension__ __PRETTY_FUNCTION__))
3511 "SCEVUMaxExpr operand types don't match!")(static_cast <bool> (getEffectiveSCEVType(Ops[i]->getType
()) == ETy && "SCEVUMaxExpr operand types don't match!"
) ? void (0) : __assert_fail ("getEffectiveSCEVType(Ops[i]->getType()) == ETy && \"SCEVUMaxExpr operand types don't match!\""
, "/build/llvm-toolchain-snapshot-6.0~svn320940/lib/Analysis/ScalarEvolution.cpp"
, 3511, __extension__ __PRETTY_FUNCTION__))
;
3512#endif
3513
3514 // Sort by complexity, this groups all similar expression types together.
3515 GroupByComplexity(Ops, &LI, DT);
3516
3517 // If there are any constants, fold them together.
3518 unsigned Idx = 0;
3519 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
3520 ++Idx;
3521 assert(Idx < Ops.size())(static_cast <bool> (Idx < Ops.size()) ? void (0) : __assert_fail
("Idx < Ops.size()", "/build/llvm-toolchain-snapshot-6.0~svn320940/lib/Analysis/ScalarEvolution.cpp"
, 3521, __extension__ __PRETTY_FUNCTION__))
;
3522 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
3523 // We found two constants, fold them together!
3524 ConstantInt *Fold = ConstantInt::get(
3525 getContext(), APIntOps::umax(LHSC->getAPInt(), RHSC->getAPInt()));
3526 Ops[0] = getConstant(Fold);
3527 Ops.erase(Ops.begin()+1); // Erase the folded element
3528 if (Ops.size() == 1) return Ops[0];
3529 LHSC = cast<SCEVConstant>(Ops[0]);
3530 }
3531
3532 // If we are left with a constant minimum-int, strip it off.
3533 if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(false)) {
3534 Ops.erase(Ops.begin());
3535 --Idx;
3536 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isMaxValue(false)) {
3537 // If we have an umax with a constant maximum-int, it will always be
3538 // maximum-int.
3539 return Ops[0];
3540 }
3541
3542 if (Ops.size() == 1) return Ops[0];
3543 }
3544
3545 // Find the first UMax
3546 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scUMaxExpr)
3547 ++Idx;
3548
3549 // Check to see if one of the operands is a UMax. If so, expand its operands
3550 // onto our operand list, and recurse to simplify.
3551 if (Idx < Ops.size()) {
3552 bool DeletedUMax = false;
3553 while (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(Ops[Idx])) {
3554 Ops.erase(Ops.begin()+Idx);
3555 Ops.append(UMax->op_begin(), UMax->op_end());
3556 DeletedUMax = true;
3557 }
3558
3559 if (DeletedUMax)
3560 return getUMaxExpr(Ops);
3561 }
3562
3563 // Okay, check to see if the same value occurs in the operand list twice. If
3564 // so, delete one. Since we sorted the list, these values are required to
3565 // be adjacent.
3566 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
3567 // X umax Y umax Y --> X umax Y
3568 // X umax Y --> X, if X is always greater than Y
3569 if (Ops[i] == Ops[i+1] ||
3570 isKnownPredicate(ICmpInst::ICMP_UGE, Ops[i], Ops[i+1])) {
3571 Ops.erase(Ops.begin()+i+1, Ops.begin()+i+2);
3572 --i; --e;
3573 } else if (isKnownPredicate(ICmpInst::ICMP_ULE, Ops[i], Ops[i+1])) {
3574 Ops.erase(Ops.begin()+i, Ops.begin()+i+1);
3575 --i; --e;
3576 }
3577
3578 if (Ops.size() == 1) return Ops[0];
3579
3580 assert(!Ops.empty() && "Reduced umax down to nothing!")(static_cast <bool> (!Ops.empty() && "Reduced umax down to nothing!"
) ? void (0) : __assert_fail ("!Ops.empty() && \"Reduced umax down to nothing!\""
, "/build/llvm-toolchain-snapshot-6.0~svn320940/lib/Analysis/ScalarEvolution.cpp"
, 3580, __extension__ __PRETTY_FUNCTION__))
;
3581
3582 // Okay, it looks like we really DO need a umax expr. Check to see if we
3583 // already have one, otherwise create a new one.
3584 FoldingSetNodeID ID;
3585 ID.AddInteger(scUMaxExpr);
3586 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
3587 ID.AddPointer(Ops[i]);
3588 void *IP = nullptr;
3589 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
3590 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
3591 std::uninitialized_copy(Ops.begin(), Ops.end(), O);
3592 SCEV *S = new (SCEVAllocator) SCEVUMaxExpr(ID.Intern(SCEVAllocator),
3593 O, Ops.size());
3594 UniqueSCEVs.InsertNode(S, IP);
3595 addToLoopUseLists(S);
3596 return S;
3597}
3598
3599const SCEV *ScalarEvolution::getSMinExpr(const SCEV *LHS,
3600 const SCEV *RHS) {
3601 // ~smax(~x, ~y) == smin(x, y).
3602 return getNotSCEV(getSMaxExpr(getNotSCEV(LHS), getNotSCEV(RHS)));
3603}
3604
3605const SCEV *ScalarEvolution::getUMinExpr(const SCEV *LHS,
3606 const SCEV *RHS) {
3607 // ~umax(~x, ~y) == umin(x, y)
3608 return getNotSCEV(getUMaxExpr(getNotSCEV(LHS), getNotSCEV(RHS)));
3609}
3610
3611const SCEV *ScalarEvolution::getSizeOfExpr(Type *IntTy, Type *AllocTy) {
3612 // We can bypass creating a target-independent
3613 // constant expression and then folding it back into a ConstantInt.
3614 // This is just a compile-time optimization.
3615 return getConstant(IntTy, getDataLayout().getTypeAllocSize(AllocTy));
3616}
3617
3618const SCEV *ScalarEvolution::getOffsetOfExpr(Type *IntTy,
3619 StructType *STy,
3620 unsigned FieldNo) {
3621 // We can bypass creating a target-independent
3622 // constant expression and then folding it back into a ConstantInt.
3623 // This is just a compile-time optimization.
3624 return getConstant(
3625 IntTy, getDataLayout().getStructLayout(STy)->getElementOffset(FieldNo));
3626}
3627
3628const SCEV *ScalarEvolution::getUnknown(Value *V) {
3629 // Don't attempt to do anything other than create a SCEVUnknown object
3630 // here. createSCEV only calls getUnknown after checking for all other
3631 // interesting possibilities, and any other code that calls getUnknown
3632 // is doing so in order to hide a value from SCEV canonicalization.
3633
3634 FoldingSetNodeID ID;
3635 ID.AddInteger(scUnknown);
3636 ID.AddPointer(V);
3637 void *IP = nullptr;
3638 if (SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) {
3639 assert(cast<SCEVUnknown>(S)->getValue() == V &&(static_cast <bool> (cast<SCEVUnknown>(S)->getValue
() == V && "Stale SCEVUnknown in uniquing map!") ? void
(0) : __assert_fail ("cast<SCEVUnknown>(S)->getValue() == V && \"Stale SCEVUnknown in uniquing map!\""
, "/build/llvm-toolchain-snapshot-6.0~svn320940/lib/Analysis/ScalarEvolution.cpp"
, 3640, __extension__ __PRETTY_FUNCTION__))
3640 "Stale SCEVUnknown in uniquing map!")(static_cast <bool> (cast<SCEVUnknown>(S)->getValue
() == V && "Stale SCEVUnknown in uniquing map!") ? void
(0) : __assert_fail ("cast<SCEVUnknown>(S)->getValue() == V && \"Stale SCEVUnknown in uniquing map!\""
, "/build/llvm-toolchain-snapshot-6.0~svn320940/lib/Analysis/ScalarEvolution.cpp"
, 3640, __extension__ __PRETTY_FUNCTION__))
;
3641 return S;
3642 }
3643 SCEV *S = new (SCEVAllocator) SCEVUnknown(ID.Intern(SCEVAllocator), V, this,
3644 FirstUnknown);
3645 FirstUnknown = cast<SCEVUnknown>(S);
3646 UniqueSCEVs.InsertNode(S, IP);
3647 return S;
3648}
3649
3650//===----------------------------------------------------------------------===//
3651// Basic SCEV Analysis and PHI Idiom Recognition Code
3652//
3653
3654/// Test if values of the given type are analyzable within the SCEV
3655/// framework. This primarily includes integer types, and it can optionally
3656/// include pointer types if the ScalarEvolution class has access to
3657/// target-specific information.
3658bool ScalarEvolution::isSCEVable(Type *Ty) const {
3659 // Integers and pointers are always SCEVable.
3660 return Ty->isIntegerTy() || Ty->isPointerTy();
3661}
3662
3663/// Return the size in bits of the specified type, for which isSCEVable must
3664/// return true.
3665uint64_t ScalarEvolution::getTypeSizeInBits(Type *Ty) const {
3666 assert(isSCEVable(Ty) && "Type is not SCEVable!")(static_cast <bool> (isSCEVable(Ty) && "Type is not SCEVable!"
) ? void (0) : __assert_fail ("isSCEVable(Ty) && \"Type is not SCEVable!\""
, "/build/llvm-toolchain-snapshot-6.0~svn320940/lib/Analysis/ScalarEvolution.cpp"
, 3666, __extension__ __PRETTY_FUNCTION__))
;
3667 return getDataLayout().getTypeSizeInBits(Ty);
3668}
3669
3670/// Return a type with the same bitwidth as the given type and which represents
3671/// how SCEV will treat the given type, for which isSCEVable must return
3672/// true. For pointer types, this is the pointer-sized integer type.
3673Type *ScalarEvolution::getEffectiveSCEVType(Type *Ty) const {
3674 assert(isSCEVable(Ty) && "Type is not SCEVable!")(static_cast <bool> (isSCEVable(Ty) && "Type is not SCEVable!"
) ? void (0) : __assert_fail ("isSCEVable(Ty) && \"Type is not SCEVable!\""
, "/build/llvm-toolchain-snapshot-6.0~svn320940/lib/Analysis/ScalarEvolution.cpp"
, 3674, __extension__ __PRETTY_FUNCTION__))
;
3675
3676 if (Ty->isIntegerTy())
3677 return Ty;
3678
3679 // The only other support type is pointer.
3680 assert(Ty->isPointerTy() && "Unexpected non-pointer non-integer type!")(static_cast <bool> (Ty->isPointerTy() && "Unexpected non-pointer non-integer type!"
) ? void (0) : __assert_fail ("Ty->isPointerTy() && \"Unexpected non-pointer non-integer type!\""
, "/build/llvm-toolchain-snapshot-6.0~svn320940/lib/Analysis/ScalarEvolution.cpp"
, 3680, __extension__ __PRETTY_FUNCTION__))
;
3681 return getDataLayout().getIntPtrType(Ty);
3682}
3683
3684Type *ScalarEvolution::getWiderType(Type *T1, Type *T2) const {
3685 return getTypeSizeInBits(T1) >= getTypeSizeInBits(T2) ? T1 : T2;
3686}
3687
3688const SCEV *ScalarEvolution::getCouldNotCompute() {
3689 return CouldNotCompute.get();
3690}
3691
3692bool ScalarEvolution::checkValidity(const SCEV *S) const {
3693 bool ContainsNulls = SCEVExprContains(S, [](const SCEV *S) {
3694 auto *SU = dyn_cast<SCEVUnknown>(S);
3695 return SU && SU->getValue() == nullptr;
3696 });
3697
3698 return !ContainsNulls;
3699}
3700
3701bool ScalarEvolution::containsAddRecurrence(const SCEV *S) {
3702 HasRecMapType::iterator I = HasRecMap.find(S);
3703 if (I != HasRecMap.end())
3704 return I->second;
3705
3706 bool FoundAddRec = SCEVExprContains(S, isa<SCEVAddRecExpr, const SCEV *>);
3707 HasRecMap.insert({S, FoundAddRec});
3708 return FoundAddRec;
3709}
3710
3711/// Try to split a SCEVAddExpr into a pair of {SCEV, ConstantInt}.
3712/// If \p S is a SCEVAddExpr and is composed of a sub SCEV S' and an
3713/// offset I, then return {S', I}, else return {\p S, nullptr}.
3714static std::pair<const SCEV *, ConstantInt *> splitAddExpr(const SCEV *S) {
3715 const auto *Add = dyn_cast<SCEVAddExpr>(S);
3716 if (!Add)
3717 return {S, nullptr};
3718
3719 if (Add->getNumOperands() != 2)
3720 return {S, nullptr};
3721
3722 auto *ConstOp = dyn_cast<SCEVConstant>(Add->getOperand(0));
3723 if (!ConstOp)
3724 return {S, nullptr};
3725
3726 return {Add->getOperand(1), ConstOp->getValue()};
3727}
3728
3729/// Return the ValueOffsetPair set for \p S. \p S can be represented
3730/// by the value and offset from any ValueOffsetPair in the set.
3731SetVector<ScalarEvolution::ValueOffsetPair> *
3732ScalarEvolution::getSCEVValues(const SCEV *S) {
3733 ExprValueMapType::iterator SI = ExprValueMap.find_as(S);
3734 if (SI == ExprValueMap.end())
3735 return nullptr;
3736#ifndef NDEBUG
3737 if (VerifySCEVMap) {
3738 // Check there is no dangling Value in the set returned.
3739 for (const auto &VE : SI->second)
3740 assert(ValueExprMap.count(VE.first))(static_cast <bool> (ValueExprMap.count(VE.first)) ? void
(0) : __assert_fail ("ValueExprMap.count(VE.first)", "/build/llvm-toolchain-snapshot-6.0~svn320940/lib/Analysis/ScalarEvolution.cpp"
, 3740, __extension__ __PRETTY_FUNCTION__))
;
3741 }
3742#endif
3743 return &SI->second;
3744}
3745
3746/// Erase Value from ValueExprMap and ExprValueMap. ValueExprMap.erase(V)
3747/// cannot be used separately. eraseValueFromMap should be used to remove
3748/// V from ValueExprMap and ExprValueMap at the same time.
3749void ScalarEvolution::eraseValueFromMap(Value *V) {
3750 ValueExprMapType::iterator I = ValueExprMap.find_as(V);
3751 if (I != ValueExprMap.end()) {
3752 const SCEV *S = I->second;
3753 // Remove {V, 0} from the set of ExprValueMap[S]
3754 if (SetVector<ValueOffsetPair> *SV = getSCEVValues(S))
3755 SV->remove({V, nullptr});
3756
3757 // Remove {V, Offset} from the set of ExprValueMap[Stripped]
3758 const SCEV *Stripped;
3759 ConstantInt *Offset;
3760 std::tie(Stripped, Offset) = splitAddExpr(S);
3761 if (Offset != nullptr) {
3762 if (SetVector<ValueOffsetPair> *SV = getSCEVValues(Stripped))
3763 SV->remove({V, Offset});
3764 }
3765 ValueExprMap.erase(V);
3766 }
3767}
3768
3769/// Return an existing SCEV if it exists, otherwise analyze the expression and
3770/// create a new one.
3771const SCEV *ScalarEvolution::getSCEV(Value *V) {
3772 assert(isSCEVable(V->getType()) && "Value is not SCEVable!")(static_cast <bool> (isSCEVable(V->getType()) &&
"Value is not SCEVable!") ? void (0) : __assert_fail ("isSCEVable(V->getType()) && \"Value is not SCEVable!\""
, "/build/llvm-toolchain-snapshot-6.0~svn320940/lib/Analysis/ScalarEvolution.cpp"
, 3772, __extension__ __PRETTY_FUNCTION__))
;
3773
3774 const SCEV *S = getExistingSCEV(V);
3775 if (S == nullptr) {
3776 S = createSCEV(V);
3777 // During PHI resolution, it is possible to create two SCEVs for the same
3778 // V, so it is needed to double check whether V->S is inserted into
3779 // ValueExprMap before insert S->{V, 0} into ExprValueMap.
3780 std::pair<ValueExprMapType::iterator, bool> Pair =
3781 ValueExprMap.insert({SCEVCallbackVH(V, this), S});
3782 if (Pair.second) {
3783 ExprValueMap[S].insert({V, nullptr});
3784
3785 // If S == Stripped + Offset, add Stripped -> {V, Offset} into
3786 // ExprValueMap.
3787 const SCEV *Stripped = S;
3788 ConstantInt *Offset = nullptr;
3789 std::tie(Stripped, Offset) = splitAddExpr(S);
3790 // If stripped is SCEVUnknown, don't bother to save
3791 // Stripped -> {V, offset}. It doesn't simplify and sometimes even
3792 // increase the complexity of the expansion code.
3793 // If V is GetElementPtrInst, don't save Stripped -> {V, offset}
3794 // because it may generate add/sub instead of GEP in SCEV expansion.
3795 if (Offset != nullptr && !isa<SCEVUnknown>(Stripped) &&
3796 !isa<GetElementPtrInst>(V))
3797 ExprValueMap[Stripped].insert({V, Offset});
3798 }
3799 }
3800 return S;
3801}
3802
3803const SCEV *ScalarEvolution::getExistingSCEV(Value *V) {
3804 assert(isSCEVable(V->getType()) && "Value is not SCEVable!")(static_cast <bool> (isSCEVable(V->getType()) &&
"Value is not SCEVable!") ? void (0) : __assert_fail ("isSCEVable(V->getType()) && \"Value is not SCEVable!\""
, "/build/llvm-toolchain-snapshot-6.0~svn320940/lib/Analysis/ScalarEvolution.cpp"
, 3804, __extension__ __PRETTY_FUNCTION__))
;
3805
3806 ValueExprMapType::iterator I = ValueExprMap.find_as(V);
3807 if (I != ValueExprMap.end()) {
3808 const SCEV *S = I->second;
3809 if (checkValidity(S))
3810 return S;
3811 eraseValueFromMap(V);
3812 forgetMemoizedResults(S);
3813 }
3814 return nullptr;
3815}
3816
3817/// Return a SCEV corresponding to -V = -1*V
3818const SCEV *ScalarEvolution::getNegativeSCEV(const SCEV *V,
3819 SCEV::NoWrapFlags Flags) {
3820 if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
3821 return getConstant(
3822 cast<ConstantInt>(ConstantExpr::getNeg(VC->getValue())));
3823
3824 Type *Ty = V->getType();
3825 Ty = getEffectiveSCEVType(Ty);
3826 return getMulExpr(
3827 V, getConstant(cast<ConstantInt>(Constant::getAllOnesValue(Ty))), Flags);
3828}
3829
3830/// Return a SCEV corresponding to ~V = -1-V
3831const SCEV *ScalarEvolution::getNotSCEV(const SCEV *V) {
3832 if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
3833 return getConstant(
3834 cast<ConstantInt>(ConstantExpr::getNot(VC->getValue())));
3835
3836 Type *Ty = V->getType();
3837 Ty = getEffectiveSCEVType(Ty);
3838 const SCEV *AllOnes =
3839 getConstant(cast<ConstantInt>(Constant::getAllOnesValue(Ty)));
3840 return getMinusSCEV(AllOnes, V);
3841}
3842
3843const SCEV *ScalarEvolution::getMinusSCEV(const SCEV *LHS, const SCEV *RHS,
3844 SCEV::NoWrapFlags Flags,
3845 unsigned Depth) {
3846 // Fast path: X - X --> 0.
3847 if (LHS == RHS)
3848 return getZero(LHS->getType());
3849
3850 // We represent LHS - RHS as LHS + (-1)*RHS. This transformation
3851 // makes it so that we cannot make much use of NUW.
3852 auto AddFlags = SCEV::FlagAnyWrap;
3853 const bool RHSIsNotMinSigned =
3854 !getSignedRangeMin(RHS).isMinSignedValue();
3855 if (maskFlags(Flags, SCEV::FlagNSW) == SCEV::FlagNSW) {
3856 // Let M be the minimum representable signed value. Then (-1)*RHS
3857 // signed-wraps if and only if RHS is M. That can happen even for
3858 // a NSW subtraction because e.g. (-1)*M signed-wraps even though
3859 // -1 - M does not. So to transfer NSW from LHS - RHS to LHS +
3860 // (-1)*RHS, we need to prove that RHS != M.
3861 //
3862 // If LHS is non-negative and we know that LHS - RHS does not
3863 // signed-wrap, then RHS cannot be M. So we can rule out signed-wrap
3864 // either by proving that RHS > M or that LHS >= 0.
3865 if (RHSIsNotMinSigned || isKnownNonNegative(LHS)) {
3866 AddFlags = SCEV::FlagNSW;
3867 }
3868 }
3869
3870 // FIXME: Find a correct way to transfer NSW to (-1)*M when LHS -
3871 // RHS is NSW and LHS >= 0.
3872 //
3873 // The difficulty here is that the NSW flag may have been proven
3874 // relative to a loop that is to be found in a recurrence in LHS and
3875 // not in RHS. Applying NSW to (-1)*M may then let the NSW have a
3876 // larger scope than intended.
3877 auto NegFlags = RHSIsNotMinSigned ? SCEV::FlagNSW : SCEV::FlagAnyWrap;
3878
3879 return getAddExpr(LHS, getNegativeSCEV(RHS, NegFlags), AddFlags, Depth);
3880}
3881
3882const SCEV *
3883ScalarEvolution::getTruncateOrZeroExtend(const SCEV *V, Type *Ty) {
3884 Type *SrcTy = V->getType();
3885 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&(static_cast <bool> ((SrcTy->isIntegerTy() || SrcTy->
isPointerTy()) && (Ty->isIntegerTy() || Ty->isPointerTy
()) && "Cannot truncate or zero extend with non-integer arguments!"
) ? void (0) : __assert_fail ("(SrcTy->isIntegerTy() || SrcTy->isPointerTy()) && (Ty->isIntegerTy() || Ty->isPointerTy()) && \"Cannot truncate or zero extend with non-integer arguments!\""
, "/build/llvm-toolchain-snapshot-6.0~svn320940/lib/Analysis/ScalarEvolution.cpp"
, 3887, __extension__ __PRETTY_FUNCTION__))
3886 (Ty->isIntegerTy() || Ty->isPointerTy()) &&(static_cast <bool> ((SrcTy->isIntegerTy() || SrcTy->
isPointerTy()) && (Ty->isIntegerTy() || Ty->isPointerTy
()) && "Cannot truncate or zero extend with non-integer arguments!"
) ? void (0) : __assert_fail ("(SrcTy->isIntegerTy() || SrcTy->isPointerTy()) && (Ty->isIntegerTy() || Ty->isPointerTy()) && \"Cannot truncate or zero extend with non-integer arguments!\""
, "/build/llvm-toolchain-snapshot-6.0~svn320940/lib/Analysis/ScalarEvolution.cpp"
, 3887, __extension__ __PRETTY_FUNCTION__))
3887 "Cannot truncate or zero extend with non-integer arguments!")(static_cast <bool> ((SrcTy->isIntegerTy() || SrcTy->
isPointerTy()) && (Ty->isIntegerTy() || Ty->isPointerTy
()) && "Cannot truncate or zero extend with non-integer arguments!"
) ? void (0) : __assert_fail ("(SrcTy->isIntegerTy() || SrcTy->isPointerTy()) && (Ty->isIntegerTy() || Ty->isPointerTy()) && \"Cannot truncate or zero extend with non-integer arguments!\""
, "/build/llvm-toolchain-snapshot-6.0~svn320940/lib/Analysis/ScalarEvolution.cpp"
, 3887, __extension__ __PRETTY_FUNCTION__))
;
3888 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
3889 return V; // No conversion
3890 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty))
3891 return getTruncateExpr(V, Ty);
3892 return getZeroExtendExpr(V, Ty);
3893}
3894
3895const SCEV *
3896ScalarEvolution::getTruncateOrSignExtend(const SCEV *V,
3897 Type *Ty) {
3898 Type *SrcTy = V->getType();
3899 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&(static_cast <bool> ((SrcTy->isIntegerTy() || SrcTy->
isPointerTy()) && (Ty->isIntegerTy() || Ty->isPointerTy
()) && "Cannot truncate or zero extend with non-integer arguments!"
) ? void (0) : __assert_fail ("(SrcTy->isIntegerTy() || SrcTy->isPointerTy()) && (Ty->isIntegerTy() || Ty->isPointerTy()) && \"Cannot truncate or zero extend with non-integer arguments!\""
, "/build/llvm-toolchain-snapshot-6.0~svn320940/lib/Analysis/ScalarEvolution.cpp"
, 3901, __extension__ __PRETTY_FUNCTION__))
3900 (Ty->isIntegerTy() || Ty->isPointerTy()) &&(static_cast <bool> ((SrcTy->isIntegerTy() || SrcTy->
isPointerTy()) && (Ty->isIntegerTy() || Ty->isPointerTy
()) && "Cannot truncate or zero extend with non-integer arguments!"
) ? void (0) : __assert_fail ("(SrcTy->isIntegerTy() || SrcTy->isPointerTy()) && (Ty->isIntegerTy() || Ty->isPointerTy()) && \"Cannot truncate or zero extend with non-integer arguments!\""
, "/build/llvm-toolchain-snapshot-6.0~svn320940/lib/Analysis/ScalarEvolution.cpp"
, 3901, __extension__ __PRETTY_FUNCTION__))
3901 "Cannot truncate or zero extend with non-integer arguments!")(static_cast <bool> ((SrcTy->isIntegerTy() || SrcTy->
isPointerTy()) && (Ty->isIntegerTy() || Ty->isPointerTy
()) && "Cannot truncate or zero extend with non-integer arguments!"
) ? void (0) : __assert_fail ("(SrcTy->isIntegerTy() || SrcTy->isPointerTy()) && (Ty->isIntegerTy() || Ty->isPointerTy()) && \"Cannot truncate or zero extend with non-integer arguments!\""
, "/build/llvm-toolchain-snapshot-6.0~svn320940/lib/Analysis/ScalarEvolution.cpp"
, 3901, __extension__ __PRETTY_FUNCTION__))
;
3902 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
3903 return V; // No conversion
3904 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty))
3905 return getTruncateExpr(V, Ty);
3906 return getSignExtendExpr(V, Ty);
3907}
3908
3909const SCEV *
3910ScalarEvolution::getNoopOrZeroExtend(const SCEV *V, Type *Ty) {
3911 Type *SrcTy = V->getType();
3912 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&(static_cast <bool> ((SrcTy->isIntegerTy() || SrcTy->
isPointerTy()) && (Ty->isIntegerTy() || Ty->isPointerTy
()) && "Cannot noop or zero extend with non-integer arguments!"
) ? void (0) : __assert_fail ("(SrcTy->isIntegerTy() || SrcTy->isPointerTy()) && (Ty->isIntegerTy() || Ty->isPointerTy()) && \"Cannot noop or zero extend with non-integer arguments!\""
, "/build/llvm-toolchain-snapshot-6.0~svn320940/lib/Analysis/ScalarEvolution.cpp"
, 3914, __extension__ __PRETTY_FUNCTION__))
3913 (Ty->isIntegerTy() || Ty->isPointerTy()) &&(static_cast <bool> ((SrcTy->isIntegerTy() || SrcTy->
isPointerTy()) && (Ty->isIntegerTy() || Ty->isPointerTy
()) && "Cannot noop or zero extend with non-integer arguments!"
) ? void (0) : __assert_fail ("(SrcTy->isIntegerTy() || SrcTy->isPointerTy()) && (Ty->isIntegerTy() || Ty->isPointerTy()) && \"Cannot noop or zero extend with non-integer arguments!\""
, "/build/llvm-toolchain-snapshot-6.0~svn320940/lib/Analysis/ScalarEvolution.cpp"
, 3914, __extension__ __PRETTY_FUNCTION__))
3914 "Cannot noop or zero extend with non-integer arguments!")(static_cast <bool> ((SrcTy->isIntegerTy() || SrcTy->
isPointerTy()) && (Ty->isIntegerTy() || Ty->isPointerTy
()) && "Cannot noop or zero extend with non-integer arguments!"
) ? void (0) : __assert_fail ("(SrcTy->isIntegerTy() || SrcTy->isPointerTy()) && (Ty->isIntegerTy() || Ty->isPointerTy()) && \"Cannot noop or zero extend with non-integer arguments!\""
, "/build/llvm-toolchain-snapshot-6.0~svn320940/lib/Analysis/ScalarEvolution.cpp"
, 3914, __extension__ __PRETTY_FUNCTION__))
;
3915 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&(static_cast <bool> (getTypeSizeInBits(SrcTy) <= getTypeSizeInBits
(Ty) && "getNoopOrZeroExtend cannot truncate!") ? void
(0) : __assert_fail ("getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) && \"getNoopOrZeroExtend cannot truncate!\""
, "/build/llvm-toolchain-snapshot-6.0~svn320940/lib/Analysis/ScalarEvolution.cpp"
, 3916, __extension__ __PRETTY_FUNCTION__))
3916 "getNoopOrZeroExtend cannot truncate!")(static_cast <bool> (getTypeSizeInBits(SrcTy) <= getTypeSizeInBits
(Ty) && "getNoopOrZeroExtend cannot truncate!") ? void
(0) : __assert_fail ("getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) && \"getNoopOrZeroExtend cannot truncate!\""
, "/build/llvm-toolchain-snapshot-6.0~svn320940/lib/Analysis/ScalarEvolution.cpp"
, 3916, __extension__ __PRETTY_FUNCTION__))
;
3917 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
3918 return V; // No conversion
3919 return getZeroExtendExpr(V, Ty);
3920}
3921
3922const SCEV *
3923ScalarEvolution::getNoopOrSignExtend(const SCEV *V, Type *Ty) {
3924 Type *SrcTy = V->getType();
3925 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&(static_cast <bool> ((SrcTy->isIntegerTy() || SrcTy->
isPointerTy()) && (Ty->isIntegerTy() || Ty->isPointerTy
()) && "Cannot noop or sign extend with non-integer arguments!"
) ? void (0) : __assert_fail ("(SrcTy->isIntegerTy() || SrcTy->isPointerTy()) && (Ty->isIntegerTy() || Ty->isPointerTy()) && \"Cannot noop or sign extend with non-integer arguments!\""
, "/build/llvm-toolchain-snapshot-6.0~svn320940/lib/Analysis/ScalarEvolution.cpp"
, 3927, __extension__ __PRETTY_FUNCTION__))
3926 (Ty->isIntegerTy() || Ty->isPointerTy()) &&(static_cast <bool> ((SrcTy->isIntegerTy() || SrcTy->
isPointerTy()) && (Ty->isIntegerTy() || Ty->isPointerTy
()) && "Cannot noop or sign extend with non-integer arguments!"
) ? void (0) : __assert_fail ("(SrcTy->isIntegerTy() || SrcTy->isPointerTy()) && (Ty->isIntegerTy() || Ty->isPointerTy()) && \"Cannot noop or sign extend with non-integer arguments!\""
, "/build/llvm-toolchain-snapshot-6.0~svn320940/lib/Analysis/ScalarEvolution.cpp"
, 3927, __extension__ __PRETTY_FUNCTION__))
3927 "Cannot noop or sign extend with non-integer arguments!")(static_cast <bool> ((SrcTy->isIntegerTy() || SrcTy->
isPointerTy()) && (Ty->isIntegerTy() || Ty->isPointerTy
()) && "Cannot noop or sign extend with non-integer arguments!"
) ? void (0) : __assert_fail ("(SrcTy->isIntegerTy() || SrcTy->isPointerTy()) && (Ty->isIntegerTy() || Ty->isPointerTy()) && \"Cannot noop or sign extend with non-integer arguments!\""
, "/build/llvm-toolchain-snapshot-6.0~svn320940/lib/Analysis/ScalarEvolution.cpp"
, 3927, __extension__ __PRETTY_FUNCTION__))
;
3928 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&(static_cast <bool> (getTypeSizeInBits(SrcTy) <= getTypeSizeInBits
(Ty) && "getNoopOrSignExtend cannot truncate!") ? void
(0) : __assert_fail ("getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) && \"getNoopOrSignExtend cannot truncate!\""
, "/build/llvm-toolchain-snapshot-6.0~svn320940/lib/Analysis/ScalarEvolution.cpp"
, 3929, __extension__ __PRETTY_FUNCTION__))
3929 "getNoopOrSignExtend cannot truncate!")(static_cast <bool> (getTypeSizeInBits(SrcTy) <= getTypeSizeInBits
(Ty) && "getNoopOrSignExtend cannot truncate!") ? void
(0) : __assert_fail ("getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) && \"getNoopOrSignExtend cannot truncate!\""
, "/build/llvm-toolchain-snapshot-6.0~svn320940/lib/Analysis/ScalarEvolution.cpp"
, 3929, __extension__ __PRETTY_FUNCTION__))
;
3930 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
3931 return V; // No conversion
3932 return getSignExtendExpr(V, Ty);
3933}
3934
3935const SCEV *
3936ScalarEvolution::getNoopOrAnyExtend(const SCEV *V, Type *Ty) {
3937 Type *SrcTy = V->getType();
3938 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&(static_cast <bool> ((SrcTy->isIntegerTy() || SrcTy->
isPointerTy()) && (Ty->isIntegerTy() || Ty->isPointerTy
()) && "Cannot noop or any extend with non-integer arguments!"
) ? void (0) : __assert_fail ("(SrcTy->isIntegerTy() || SrcTy->isPointerTy()) && (Ty->isIntegerTy() || Ty->isPointerTy()) && \"Cannot noop or any extend with non-integer arguments!\""
, "/build/llvm-toolchain-snapshot-6.0~svn320940/lib/Analysis/ScalarEvolution.cpp"
, 3940, __extension__ __PRETTY_FUNCTION__))
3939 (Ty->isIntegerTy() || Ty->isPointerTy()) &&(static_cast <bool> ((SrcTy->isIntegerTy() || SrcTy->
isPointerTy()) && (Ty->isIntegerTy() || Ty->isPointerTy
()) && "Cannot noop or any extend with non-integer arguments!"
) ? void (0) : __assert_fail ("(SrcTy->isIntegerTy() || SrcTy->isPointerTy()) && (Ty->isIntegerTy() || Ty->isPointerTy()) && \"Cannot noop or any extend with non-integer arguments!\""
, "/build/llvm-toolchain-snapshot-6.0~svn320940/lib/Analysis/ScalarEvolution.cpp"
, 3940, __extension__ __PRETTY_FUNCTION__))
3940 "Cannot noop or any extend with non-integer arguments!")(static_cast <bool> ((SrcTy->isIntegerTy() || SrcTy->
isPointerTy()) && (Ty->isIntegerTy() || Ty->isPointerTy
()) && "Cannot noop or any extend with non-integer arguments!"
) ? void (0) : __assert_fail ("(SrcTy->isIntegerTy() || SrcTy->isPointerTy()) && (Ty->isIntegerTy() || Ty->isPointerTy()) && \"Cannot noop or any extend with non-integer arguments!\""
, "/build/llvm-toolchain-snapshot-6.0~svn320940/lib/Analysis/ScalarEvolution.cpp"
, 3940, __extension__ __PRETTY_FUNCTION__))
;
3941 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&(static_cast <bool> (getTypeSizeInBits(SrcTy) <= getTypeSizeInBits
(Ty) && "getNoopOrAnyExtend cannot truncate!") ? void
(0) : __assert_fail ("getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) && \"getNoopOrAnyExtend cannot truncate!\""
, "/build/llvm-toolchain-snapshot-6.0~svn320940/lib/Analysis/ScalarEvolution.cpp"
, 3942, __extension__ __PRETTY_FUNCTION__))
3942 "getNoopOrAnyExtend cannot truncate!")(static_cast <bool> (getTypeSizeInBits(SrcTy) <= getTypeSizeInBits
(Ty) && "getNoopOrAnyExtend cannot truncate!") ? void
(0) : __assert_fail ("getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) && \"getNoopOrAnyExtend cannot truncate!\""
, "/build/llvm-toolchain-snapshot-6.0~svn320940/lib/Analysis/ScalarEvolution.cpp"
, 3942, __extension__ __PRETTY_FUNCTION__))
;
3943 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
3944 return V; // No conversion
3945 return getAnyExtendExpr(V, Ty);
3946}
3947
3948const SCEV *
3949ScalarEvolution::getTruncateOrNoop(const SCEV *V, Type *Ty) {
3950 Type *SrcTy = V->getType();
3951 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&(static_cast <bool> ((SrcTy->isIntegerTy() || SrcTy->
isPointerTy()) && (Ty->isIntegerTy() || Ty->isPointerTy
()) && "Cannot truncate or noop with non-integer arguments!"
) ? void (0) : __assert_fail ("(SrcTy->isIntegerTy() || SrcTy->isPointerTy()) && (Ty->isIntegerTy() || Ty->isPointerTy()) && \"Cannot truncate or noop with non-integer arguments!\""
, "/build/llvm-toolchain-snapshot-6.0~svn320940/lib/Analysis/ScalarEvolution.cpp"
, 3953, __extension__ __PRETTY_FUNCTION__))
3952 (Ty->isIntegerTy() || Ty->isPointerTy()) &&(static_cast <bool> ((SrcTy->isIntegerTy() || SrcTy->
isPointerTy()) && (Ty->isIntegerTy() || Ty->isPointerTy
()) && "Cannot truncate or noop with non-integer arguments!"
) ? void (0) : __assert_fail ("(SrcTy->isIntegerTy() || SrcTy->isPointerTy()) && (Ty->isIntegerTy() || Ty->isPointerTy()) && \"Cannot truncate or noop with non-integer arguments!\""
, "/build/llvm-toolchain-snapshot-6.0~svn320940/lib/Analysis/ScalarEvolution.cpp"
, 3953, __extension__ __PRETTY_FUNCTION__))
3953 "Cannot truncate or noop with non-integer arguments!")(static_cast <bool> ((SrcTy->isIntegerTy() || SrcTy->
isPointerTy()) && (Ty->isIntegerTy() || Ty->isPointerTy
()) && "Cannot truncate or noop with non-integer arguments!"
) ? void (0) : __assert_fail ("(SrcTy->isIntegerTy() || SrcTy->isPointerTy()) && (Ty->isIntegerTy() || Ty->isPointerTy()) && \"Cannot truncate or noop with non-integer arguments!\""
, "/build/llvm-toolchain-snapshot-6.0~svn320940/lib/Analysis/ScalarEvolution.cpp"
, 3953, __extension__ __PRETTY_FUNCTION__))
;
3954 assert(getTypeSizeInBits(SrcTy) >= getTypeSizeInBits(Ty) &&(static_cast <bool> (getTypeSizeInBits(SrcTy) >= getTypeSizeInBits
(Ty) && "getTruncateOrNoop cannot extend!") ? void (0
) : __assert_fail ("getTypeSizeInBits(SrcTy) >= getTypeSizeInBits(Ty) && \"getTruncateOrNoop cannot extend!\""
, "/build/llvm-toolchain-snapshot-6.0~svn320940/lib/Analysis/ScalarEvolution.cpp"
, 3955, __extension__ __PRETTY_FUNCTION__))
3955 "getTruncateOrNoop cannot extend!")(static_cast <bool> (getTypeSizeInBits(SrcTy) >= getTypeSizeInBits
(Ty) && "getTruncateOrNoop cannot extend!") ? void (0
) : __assert_fail ("getTypeSizeInBits(SrcTy) >= getTypeSizeInBits(Ty) && \"getTruncateOrNoop cannot extend!\""
, "/build/llvm-toolchain-snapshot-6.0~svn320940/lib/Analysis/ScalarEvolution.cpp"
, 3955, __extension__ __PRETTY_FUNCTION__))
;
3956 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
3957 return V; // No conversion
3958 return getTruncateExpr(V, Ty);
3959}
3960
3961const SCEV *ScalarEvolution::getUMaxFromMismatchedTypes(const SCEV *LHS,
3962 const SCEV *RHS) {
3963 const SCEV *PromotedLHS = LHS;
3964 const SCEV *PromotedRHS = RHS;
3965
3966 if (getTypeSizeInBits(LHS->getType()) > getTypeSizeInBits(RHS->getType()))
3967 PromotedRHS = getZeroExtendExpr(RHS, LHS->getType());
3968 else
3969 PromotedLHS = getNoopOrZeroExtend(LHS, RHS->getType());
3970
3971 return getUMaxExpr(PromotedLHS, PromotedRHS);
3972}
3973
3974const SCEV *ScalarEvolution::getUMinFromMismatchedTypes(const SCEV *LHS,
3975 const SCEV *RHS) {
3976 const SCEV *PromotedLHS = LHS;
3977 const SCEV *PromotedRHS = RHS;
3978
3979 if (getTypeSizeInBits(LHS->getType()) > getTypeSizeInBits(RHS->getType()))
3980 PromotedRHS = getZeroExtendExpr(RHS, LHS->getType());
3981 else
3982 PromotedLHS = getNoopOrZeroExtend(LHS, RHS->getType());
3983
3984 return getUMinExpr(PromotedLHS, PromotedRHS);
3985}
3986
3987const SCEV *ScalarEvolution::getPointerBase(const SCEV *V) {
3988 // A pointer operand may evaluate to a nonpointer expression, such as null.
3989 if (!V->getType()->isPointerTy())
3990 return V;
3991
3992 if (const SCEVCastExpr *Cast = dyn_cast<SCEVCastExpr>(V)) {
3993 return getPointerBase(Cast->getOperand());
3994 } else if (const SCEVNAryExpr *NAry = dyn_cast<SCEVNAryExpr>(V)) {
3995 const SCEV *PtrOp = nullptr;
3996 for (const SCEV *NAryOp : NAry->operands()) {
3997 if (NAryOp->getType()->isPointerTy()) {
3998 // Cannot find the base of an expression with multiple pointer operands.
3999 if (PtrOp)
4000 return V;
4001 PtrOp = NAryOp;
4002 }
4003 }
4004 if (!PtrOp)
4005 return V;
4006 return getPointerBase(PtrOp);
4007 }
4008 return V;
4009}
4010
4011/// Push users of the given Instruction onto the given Worklist.
4012static void
4013PushDefUseChildren(Instruction *I,
4014 SmallVectorImpl<Instruction *> &Worklist) {
4015 // Push the def-use children onto the Worklist stack.
4016 for (User *U : I->users())
4017 Worklist.push_back(cast<Instruction>(U));
4018}
4019
4020void ScalarEvolution::forgetSymbolicName(Instruction *PN, const SCEV *SymName) {
4021 SmallVector<Instruction *, 16> Worklist;
4022 PushDefUseChildren(PN, Worklist);
4023
4024 SmallPtrSet<Instruction *, 8> Visited;
4025 Visited.insert(PN);
4026 while (!Worklist.empty()) {
4027 Instruction *I = Worklist.pop_back_val();
4028 if (!Visited.insert(I).second)
4029 continue;
4030
4031 auto It = ValueExprMap.find_as(static_cast<Value *>(I));
4032 if (It != ValueExprMap.end()) {
4033 const SCEV *Old = It->second;
4034
4035 // Short-circuit the def-use traversal if the symbolic name
4036 // ceases to appear in expressions.
4037 if (Old != SymName && !hasOperand(Old, SymName))
4038 continue;
4039
4040 // SCEVUnknown for a PHI either means that it has an unrecognized
4041 // structure, it's a PHI that's in the progress of being computed
4042 // by createNodeForPHI, or it's a single-value PHI. In the first case,
4043 // additional loop trip count information isn't going to change anything.
4044 // In the second case, createNodeForPHI will perform the necessary
4045 // updates on its own when it gets to that point. In the third, we do
4046 // want to forget the SCEVUnknown.
4047 if (!isa<PHINode>(I) ||
4048 !isa<SCEVUnknown>(Old) ||
4049 (I != PN && Old == SymName)) {
4050 eraseValueFromMap(It->first);
4051 forgetMemoizedResults(Old);
4052 }
4053 }
4054
4055 PushDefUseChildren(I, Worklist);
4056 }
4057}
4058
4059namespace {
4060
4061class SCEVInitRewriter : public SCEVRewriteVisitor<SCEVInitRewriter> {
4062public:
4063 static const SCEV *rewrite(const SCEV *S, const Loop *L,
4064 ScalarEvolution &SE) {
4065 SCEVInitRewriter Rewriter(L, SE);
4066 const SCEV *Result = Rewriter.visit(S);
4067 return Rewriter.isValid() ? Result : SE.getCouldNotCompute();
4068 }
4069
4070 const SCEV *visitUnknown(const SCEVUnknown *Expr) {
4071 if (!SE.isLoopInvariant(Expr, L))
4072 Valid = false;
4073 return Expr;
4074 }
4075
4076 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) {
4077 // Only allow AddRecExprs for this loop.
4078 if (Expr->getLoop() == L)
4079 return Expr->getStart();
4080 Valid = false;
4081 return Expr;
4082 }
4083
4084 bool isValid() { return Valid; }
4085
4086private:
4087 explicit SCEVInitRewriter(const Loop *L, ScalarEvolution &SE)
4088 : SCEVRewriteVisitor(SE), L(L) {}
4089
4090 const Loop *L;
4091 bool Valid = true;
4092};
4093
4094/// This class evaluates the compare condition by matching it against the
4095/// condition of loop latch. If there is a match we assume a true value
4096/// for the condition while building SCEV nodes.
4097class SCEVBackedgeConditionFolder
4098 : public SCEVRewriteVisitor<SCEVBackedgeConditionFolder> {
4099public:
4100 static const SCEV *rewrite(const SCEV *S, const Loop *L,
4101 ScalarEvolution &SE) {
4102 bool IsPosBECond = false;
4103 Value *BECond = nullptr;
4104 if (BasicBlock *Latch = L->getLoopLatch()) {
4105 BranchInst *BI = dyn_cast<BranchInst>(Latch->getTerminator());
4106 if (BI && BI->isConditional()) {
4107 assert(BI->getSuccessor(0) != BI->getSuccessor(1) &&(static_cast <bool> (BI->getSuccessor(0) != BI->getSuccessor
(1) && "Both outgoing branches should not target same header!"
) ? void (0) : __assert_fail ("BI->getSuccessor(0) != BI->getSuccessor(1) && \"Both outgoing branches should not target same header!\""
, "/build/llvm-toolchain-snapshot-6.0~svn320940/lib/Analysis/ScalarEvolution.cpp"
, 4108, __extension__ __PRETTY_FUNCTION__))
4108 "Both outgoing branches should not target same header!")(static_cast <bool> (BI->getSuccessor(0) != BI->getSuccessor
(1) && "Both outgoing branches should not target same header!"
) ? void (0) : __assert_fail ("BI->getSuccessor(0) != BI->getSuccessor(1) && \"Both outgoing branches should not target same header!\""
, "/build/llvm-toolchain-snapshot-6.0~svn320940/lib/Analysis/ScalarEvolution.cpp"
, 4108, __extension__ __PRETTY_FUNCTION__))
;
4109 BECond = BI->getCondition();
4110 IsPosBECond = BI->getSuccessor(0) == L->getHeader();
4111 } else {
4112 return S;
4113 }
4114 }
4115 SCEVBackedgeConditionFolder Rewriter(L, BECond, IsPosBECond, SE);
4116 return Rewriter.visit(S);
4117 }
4118
4119 const SCEV *visitUnknown(const SCEVUnknown *Expr) {
4120 const SCEV *Result = Expr;
4121 bool InvariantF = SE.isLoopInvariant(Expr, L);
4122
4123 if (!InvariantF) {
4124 Instruction *I = cast<Instruction>(Expr->getValue());
4125 switch (I->getOpcode()) {
4126 case Instruction::Select: {
4127 SelectInst *SI = cast<SelectInst>(I);
4128 Optional<const SCEV *> Res =
4129 compareWithBackedgeCondition(SI->getCondition());
4130 if (Res.hasValue()) {
4131 bool IsOne = cast<SCEVConstant>(Res.getValue())->getValue()->isOne();
4132 Result = SE.getSCEV(IsOne ? SI->getTrueValue() : SI->getFalseValue());
4133 }
4134 break;
4135 }
4136 default: {
4137 Optional<const SCEV *> Res = compareWithBackedgeCondition(I);
4138 if (Res.hasValue())
4139 Result = Res.getValue();
4140 break;
4141 }
4142 }
4143 }
4144 return Result;
4145 }
4146
4147private:
4148 explicit SCEVBackedgeConditionFolder(const Loop *L, Value *BECond,
4149 bool IsPosBECond, ScalarEvolution &SE)
4150 : SCEVRewriteVisitor(SE), L(L), BackedgeCond(BECond),
4151 IsPositiveBECond(IsPosBECond) {}
4152
4153 Optional<const SCEV *> compareWithBackedgeCondition(Value *IC);
4154
4155 const Loop *L;
4156 /// Loop back condition.
4157 Value *BackedgeCond = nullptr;
4158 /// Set to true if loop back is on positive branch condition.
4159 bool IsPositiveBECond;
4160};
4161
4162Optional<const SCEV *>
4163SCEVBackedgeConditionFolder::compareWithBackedgeCondition(Value *IC) {
4164
4165 // If value matches the backedge condition for loop latch,
4166 // then return a constant evolution node based on loopback
4167 // branch taken.
4168 if (BackedgeCond == IC)
4169 return IsPositiveBECond ? SE.getOne(Type::getInt1Ty(SE.getContext()))
4170 : SE.getZero(Type::getInt1Ty(SE.getContext()));
4171 return None;
4172}
4173
4174class SCEVShiftRewriter : public SCEVRewriteVisitor<SCEVShiftRewriter> {
4175public:
4176 static const SCEV *rewrite(const SCEV *S, const Loop *L,
4177 ScalarEvolution &SE) {
4178 SCEVShiftRewriter Rewriter(L, SE);
4179 const SCEV *Result = Rewriter.visit(S);
4180 return Rewriter.isValid() ? Result : SE.getCouldNotCompute();
4181 }
4182
4183 const SCEV *visitUnknown(const SCEVUnknown *Expr) {
4184 // Only allow AddRecExprs for this loop.
4185 if (!SE.isLoopInvariant(Expr, L))
4186 Valid = false;
4187 return Expr;
4188 }
4189
4190 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) {
4191 if (Expr->getLoop() == L && Expr->isAffine())
4192 return SE.getMinusSCEV(Expr, Expr->getStepRecurrence(SE));
4193 Valid = false;
4194 return Expr;
4195 }
4196
4197 bool isValid() { return Valid; }
4198
4199private:
4200 explicit SCEVShiftRewriter(const Loop *L, ScalarEvolution &SE)
4201 : SCEVRewriteVisitor(SE), L(L) {}
4202
4203 const Loop *L;
4204 bool Valid = true;
4205};
4206
4207} // end anonymous namespace
4208
4209SCEV::NoWrapFlags
4210ScalarEvolution::proveNoWrapViaConstantRanges(const SCEVAddRecExpr *AR) {
4211 if (!AR->isAffine())
4212 return SCEV::FlagAnyWrap;
4213
4214 using OBO = OverflowingBinaryOperator;
4215
4216 SCEV::NoWrapFlags Result = SCEV::FlagAnyWrap;
4217
4218 if (!AR->hasNoSignedWrap()) {
4219 ConstantRange AddRecRange = getSignedRange(AR);
4220 ConstantRange IncRange = getSignedRange(AR->getStepRecurrence(*this));
4221
4222 auto NSWRegion = ConstantRange::makeGuaranteedNoWrapRegion(
4223 Instruction::Add, IncRange, OBO::NoSignedWrap);
4224 if (NSWRegion.contains(AddRecRange))
4225 Result = ScalarEvolution::setFlags(Result, SCEV::FlagNSW);
4226 }
4227
4228 if (!AR->hasNoUnsignedWrap()) {
4229 ConstantRange AddRecRange = getUnsignedRange(AR);
4230 ConstantRange IncRange = getUnsignedRange(AR->getStepRecurrence(*this));
4231
4232 auto NUWRegion = ConstantRange::makeGuaranteedNoWrapRegion(
4233 Instruction::Add, IncRange, OBO::NoUnsignedWrap);
4234 if (NUWRegion.contains(AddRecRange))
4235 Result = ScalarEvolution::setFlags(Result, SCEV::FlagNUW);
4236 }
4237
4238 return Result;
4239}
4240
4241namespace {
4242
4243/// Represents an abstract binary operation. This may exist as a
4244/// normal instruction or constant expression, or may have been
4245/// derived from an expression tree.
4246struct BinaryOp {
4247 unsigned Opcode;
4248 Value *LHS;
4249 Value *RHS;
4250 bool IsNSW = false;
4251 bool IsNUW = false;
4252
4253 /// Op is set if this BinaryOp corresponds to a concrete LLVM instruction or
4254 /// constant expression.
4255 Operator *Op = nullptr;
4256
4257 explicit BinaryOp(Operator *Op)
4258 : Opcode(Op->getOpcode()), LHS(Op->getOperand(0)), RHS(Op->getOperand(1)),
4259 Op(Op) {
4260 if (auto *OBO = dyn_cast<OverflowingBinaryOperator>(Op)) {
4261 IsNSW = OBO->hasNoSignedWrap();
4262 IsNUW = OBO->hasNoUnsignedWrap();
4263 }
4264 }
4265
4266 explicit BinaryOp(unsigned Opcode, Value *LHS, Value *RHS, bool IsNSW = false,
4267 bool IsNUW = false)
4268 : Opcode(Opcode), LHS(LHS), RHS(RHS), IsNSW(IsNSW), IsNUW(IsNUW) {}
4269};
4270
4271} // end anonymous namespace
4272
4273/// Try to map \p V into a BinaryOp, and return \c None on failure.
4274static Optional<BinaryOp> MatchBinaryOp(Value *V, DominatorTree &DT) {
4275 auto *Op = dyn_cast<Operator>(V);
4276 if (!Op)
4277 return None;
4278
4279 // Implementation detail: all the cleverness here should happen without
4280 // creating new SCEV expressions -- our caller knowns tricks to avoid creating
4281 // SCEV expressions when possible, and we should not break that.
4282
4283 switch (Op->getOpcode()) {
4284 case Instruction::Add:
4285 case Instruction::Sub:
4286 case Instruction::Mul:
4287 case Instruction::UDiv:
4288 case Instruction::URem:
4289 case Instruction::And:
4290 case Instruction::Or:
4291 case Instruction::AShr:
4292 case Instruction::Shl:
4293 return BinaryOp(Op);
4294
4295 case Instruction::Xor:
4296 if (auto *RHSC = dyn_cast<ConstantInt>(Op->getOperand(1)))
4297 // If the RHS of the xor is a signmask, then this is just an add.
4298 // Instcombine turns add of signmask into xor as a strength reduction step.
4299 if (RHSC->getValue().isSignMask())
4300 return BinaryOp(Instruction::Add, Op->getOperand(0), Op->getOperand(1));
4301 return BinaryOp(Op);
4302
4303 case Instruction::LShr:
4304 // Turn logical shift right of a constant into a unsigned divide.
4305 if (ConstantInt *SA = dyn_cast<ConstantInt>(Op->getOperand(1))) {
4306 uint32_t BitWidth = cast<IntegerType>(Op->getType())->getBitWidth();
4307
4308 // If the shift count is not less than the bitwidth, the result of
4309 // the shift is undefined. Don't try to analyze it, because the
4310 // resolution chosen here may differ from the resolution chosen in
4311 // other parts of the compiler.
4312 if (SA->getValue().ult(BitWidth)) {
4313 Constant *X =
4314 ConstantInt::get(SA->getContext(),
4315 APInt::getOneBitSet(BitWidth, SA->getZExtValue()));
4316 return BinaryOp(Instruction::UDiv, Op->getOperand(0), X);
4317 }
4318 }
4319 return BinaryOp(Op);
4320
4321 case Instruction::ExtractValue: {
4322 auto *EVI = cast<ExtractValueInst>(Op);
4323 if (EVI->getNumIndices() != 1 || EVI->getIndices()[0] != 0)
4324 break;
4325
4326 auto *CI = dyn_cast<CallInst>(EVI->getAggregateOperand());
4327 if (!CI)
4328 break;
4329
4330 if (auto *F = CI->getCalledFunction())
4331 switch (F->getIntrinsicID()) {
4332 case Intrinsic::sadd_with_overflow:
4333 case Intrinsic::uadd_with_overflow:
4334 if (!isOverflowIntrinsicNoWrap(cast<IntrinsicInst>(CI), DT))
4335 return BinaryOp(Instruction::Add, CI->getArgOperand(0),
4336 CI->getArgOperand(1));
4337
4338 // Now that we know that all uses of the arithmetic-result component of
4339 // CI are guarded by the overflow check, we can go ahead and pretend
4340 // that the arithmetic is non-overflowing.
4341 if (F->getIntrinsicID() == Intrinsic::sadd_with_overflow)
4342 return BinaryOp(Instruction::Add, CI->getArgOperand(0),
4343 CI->getArgOperand(1), /* IsNSW = */ true,
4344 /* IsNUW = */ false);
4345 else
4346 return BinaryOp(Instruction::Add, CI->getArgOperand(0),
4347 CI->getArgOperand(1), /* IsNSW = */ false,
4348 /* IsNUW*/ true);
4349 case Intrinsic::ssub_with_overflow:
4350 case Intrinsic::usub_with_overflow:
4351 if (!isOverflowIntrinsicNoWrap(cast<IntrinsicInst>(CI), DT))
4352 return BinaryOp(Instruction::Sub, CI->getArgOperand(0),
4353 CI->getArgOperand(1));
4354
4355 // The same reasoning as sadd/uadd above.
4356 if (F->getIntrinsicID() == Intrinsic::ssub_with_overflow)
4357 return BinaryOp(Instruction::Sub, CI->getArgOperand(0),
4358 CI->getArgOperand(1), /* IsNSW = */ true,
4359 /* IsNUW = */ false);
4360 else
4361 return BinaryOp(Instruction::Sub, CI->getArgOperand(0),
4362 CI->getArgOperand(1), /* IsNSW = */ false,
4363 /* IsNUW = */ true);
4364 case Intrinsic::smul_with_overflow:
4365 case Intrinsic::umul_with_overflow:
4366 return BinaryOp(Instruction::Mul, CI->getArgOperand(0),
4367 CI->getArgOperand(1));
4368 default:
4369 break;
4370 }
4371 }
4372
4373 default:
4374 break;
4375 }
4376
4377 return None;
4378}
4379
4380/// Helper function to createAddRecFromPHIWithCasts. We have a phi
4381/// node whose symbolic (unknown) SCEV is \p SymbolicPHI, which is updated via
4382/// the loop backedge by a SCEVAddExpr, possibly also with a few casts on the
4383/// way. This function checks if \p Op, an operand of this SCEVAddExpr,
4384/// follows one of the following patterns:
4385/// Op == (SExt ix (Trunc iy (%SymbolicPHI) to ix) to iy)
4386/// Op == (ZExt ix (Trunc iy (%SymbolicPHI) to ix) to iy)
4387/// If the SCEV expression of \p Op conforms with one of the expected patterns
4388/// we return the type of the truncation operation, and indicate whether the
4389/// truncated type should be treated as signed/unsigned by setting
4390/// \p Signed to true/false, respectively.
4391static Type *isSimpleCastedPHI(const SCEV *Op, const SCEVUnknown *SymbolicPHI,
4392 bool &Signed, ScalarEvolution &SE) {
4393 // The case where Op == SymbolicPHI (that is, with no type conversions on
4394 // the way) is handled by the regular add recurrence creating logic and
4395 // would have already been triggered in createAddRecForPHI. Reaching it here
4396 // means that createAddRecFromPHI had failed for this PHI before (e.g.,
4397 // because one of the other operands of the SCEVAddExpr updating this PHI is
4398 // not invariant).
4399 //
4400 // Here we look for the case where Op = (ext(trunc(SymbolicPHI))), and in
4401 // this case predicates that allow us to prove that Op == SymbolicPHI will
4402 // be added.
4403 if (Op == SymbolicPHI)
4404 return nullptr;
4405
4406 unsigned SourceBits = SE.getTypeSizeInBits(SymbolicPHI->getType());
4407 unsigned NewBits = SE.getTypeSizeInBits(Op->getType());
4408 if (SourceBits != NewBits)
4409 return nullptr;
4410
4411 const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(Op);
4412 const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(Op);
4413 if (!SExt && !ZExt)
4414 return nullptr;
4415 const SCEVTruncateExpr *Trunc =
4416 SExt ? dyn_cast<SCEVTruncateExpr>(SExt->getOperand())
4417 : dyn_cast<SCEVTruncateExpr>(ZExt->getOperand());
4418 if (!Trunc)
4419 return nullptr;
4420 const SCEV *X = Trunc->getOperand();
4421 if (X != SymbolicPHI)
4422 return nullptr;
4423 Signed = SExt != nullptr;
4424 return Trunc->getType();
4425}
4426
4427static const Loop *isIntegerLoopHeaderPHI(const PHINode *PN, LoopInfo &LI) {
4428 if (!PN->getType()->isIntegerTy())
4429 return nullptr;
4430 const Loop *L = LI.getLoopFor(PN->getParent());
4431 if (!L || L->getHeader() != PN->getParent())
4432 return nullptr;
4433 return L;
4434}
4435
4436// Analyze \p SymbolicPHI, a SCEV expression of a phi node, and check if the
4437// computation that updates the phi follows the following pattern:
4438// (SExt/ZExt ix (Trunc iy (%SymbolicPHI) to ix) to iy) + InvariantAccum
4439// which correspond to a phi->trunc->sext/zext->add->phi update chain.
4440// If so, try to see if it can be rewritten as an AddRecExpr under some
4441// Predicates. If successful, return them as a pair. Also cache the results
4442// of the analysis.
4443//
4444// Example usage scenario:
4445// Say the Rewriter is called for the following SCEV:
4446// 8 * ((sext i32 (trunc i64 %X to i32) to i64) + %Step)
4447// where:
4448// %X = phi i64 (%Start, %BEValue)
4449// It will visitMul->visitAdd->visitSExt->visitTrunc->visitUnknown(%X),
4450// and call this function with %SymbolicPHI = %X.
4451//
4452// The analysis will find that the value coming around the backedge has
4453// the following SCEV:
4454// BEValue = ((sext i32 (trunc i64 %X to i32) to i64) + %Step)
4455// Upon concluding that this matches the desired pattern, the function
4456// will return the pair {NewAddRec, SmallPredsVec} where:
4457// NewAddRec = {%Start,+,%Step}
4458// SmallPredsVec = {P1, P2, P3} as follows:
4459// P1(WrapPred): AR: {trunc(%Start),+,(trunc %Step)}<nsw> Flags: <nssw>
4460// P2(EqualPred): %Start == (sext i32 (trunc i64 %Start to i32) to i64)
4461// P3(EqualPred): %Step == (sext i32 (trunc i64 %Step to i32) to i64)
4462// The returned pair means that SymbolicPHI can be rewritten into NewAddRec
4463// under the predicates {P1,P2,P3}.
4464// This predicated rewrite will be cached in PredicatedSCEVRewrites:
4465// PredicatedSCEVRewrites[{%X,L}] = {NewAddRec, {P1,P2,P3)}
4466//
4467// TODO's:
4468//
4469// 1) Extend the Induction descriptor to also support inductions that involve
4470// casts: When needed (namely, when we are called in the context of the
4471// vectorizer induction analysis), a Set of cast instructions will be
4472// populated by this method, and provided back to isInductionPHI. This is
4473// needed to allow the vectorizer to properly record them to be ignored by
4474// the cost model and to avoid vectorizing them (otherwise these casts,
4475// which are redundant under the runtime overflow checks, will be
4476// vectorized, which can be costly).
4477//
4478// 2) Support additional induction/PHISCEV patterns: We also want to support
4479// inductions where the sext-trunc / zext-trunc operations (partly) occur
4480// after the induction update operation (the induction increment):
4481//
4482// (Trunc iy (SExt/ZExt ix (%SymbolicPHI + InvariantAccum) to iy) to ix)
4483// which correspond to a phi->add->trunc->sext/zext->phi update chain.
4484//
4485// (Trunc iy ((SExt/ZExt ix (%SymbolicPhi) to iy) + InvariantAccum) to ix)
4486// which correspond to a phi->trunc->add->sext/zext->phi update chain.
4487//
4488// 3) Outline common code with createAddRecFromPHI to avoid duplication.
4489Optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>>
4490ScalarEvolution::createAddRecFromPHIWithCastsImpl(const SCEVUnknown *SymbolicPHI) {
4491 SmallVector<const SCEVPredicate *, 3> Predicates;
4492
4493 // *** Part1: Analyze if we have a phi-with-cast pattern for which we can
4494 // return an AddRec expression under some predicate.
4495
4496 auto *PN = cast<PHINode>(SymbolicPHI->getValue());
4497 const Loop *L = isIntegerLoopHeaderPHI(PN, LI);
4498 assert(L && "Expecting an integer loop header phi")(static_cast <bool> (L && "Expecting an integer loop header phi"
) ? void (0) : __assert_fail ("L && \"Expecting an integer loop header phi\""
, "/build/llvm-toolchain-snapshot-6.0~svn320940/lib/Analysis/ScalarEvolution.cpp"
, 4498, __extension__ __PRETTY_FUNCTION__))
;
4499
4500 // The loop may have multiple entrances or multiple exits; we can analyze
4501 // this phi as an addrec if it has a unique entry value and a unique
4502 // backedge value.
4503 Value *BEValueV = nullptr, *StartValueV = nullptr;
4504 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
4505 Value *V = PN->getIncomingValue(i);
4506 if (L->contains(PN->getIncomingBlock(i))) {
4507 if (!BEValueV) {
4508 BEValueV = V;
4509 } else if (BEValueV != V) {
4510 BEValueV = nullptr;
4511 break;
4512 }
4513 } else if (!StartValueV) {
4514 StartValueV = V;
4515 } else if (StartValueV != V) {
4516 StartValueV = nullptr;
4517 break;
4518 }
4519 }
4520 if (!BEValueV || !StartValueV)
4521 return None;
4522
4523 const SCEV *BEValue = getSCEV(BEValueV);
4524
4525 // If the value coming around the backedge is an add with the symbolic
4526 // value we just inserted, possibly with casts that we can ignore under
4527 // an appropriate runtime guard, then we found a simple induction variable!
4528 const auto *Add = dyn_cast<SCEVAddExpr>(BEValue);
4529 if (!Add)
4530 return None;
4531
4532 // If there is a single occurrence of the symbolic value, possibly
4533 // casted, replace it with a recurrence.
4534 unsigned FoundIndex = Add->getNumOperands();
4535 Type *TruncTy = nullptr;
4536 bool Signed;
4537 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
4538 if ((TruncTy =
4539 isSimpleCastedPHI(Add->getOperand(i), SymbolicPHI, Signed, *this)))
4540 if (FoundIndex == e) {
4541 FoundIndex = i;
4542 break;
4543 }
4544
4545 if (FoundIndex == Add->getNumOperands())
4546 return None;
4547
4548 // Create an add with everything but the specified operand.
4549 SmallVector<const SCEV *, 8> Ops;
4550 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
4551 if (i != FoundIndex)
4552 Ops.push_back(Add->getOperand(i));
4553 const SCEV *Accum = getAddExpr(Ops);
4554
4555 // The runtime checks will not be valid if the step amount is
4556 // varying inside the loop.
4557 if (!isLoopInvariant(Accum, L))
4558 return None;
4559
4560 // *** Part2: Create the predicates
4561
4562 // Analysis was successful: we have a phi-with-cast pattern for which we
4563 // can return an AddRec expression under the following predicates:
4564 //
4565 // P1: A Wrap predicate that guarantees that Trunc(Start) + i*Trunc(Accum)
4566 // fits within the truncated type (does not overflow) for i = 0 to n-1.
4567 // P2: An Equal predicate that guarantees that
4568 // Start = (Ext ix (Trunc iy (Start) to ix) to iy)
4569 // P3: An Equal predicate that guarantees that
4570 // Accum = (Ext ix (Trunc iy (Accum) to ix) to iy)
4571 //
4572 // As we next prove, the above predicates guarantee that:
4573 // Start + i*Accum = (Ext ix (Trunc iy ( Start + i*Accum ) to ix) to iy)
4574 //
4575 //
4576 // More formally, we want to prove that:
4577 // Expr(i+1) = Start + (i+1) * Accum
4578 // = (Ext ix (Trunc iy (Expr(i)) to ix) to iy) + Accum
4579 //
4580 // Given that:
4581 // 1) Expr(0) = Start
4582 // 2) Expr(1) = Start + Accum
4583 // = (Ext ix (Trunc iy (Start) to ix) to iy) + Accum :: from P2
4584 // 3) Induction hypothesis (step i):
4585 // Expr(i) = (Ext ix (Trunc iy (Expr(i-1)) to ix) to iy) + Accum
4586 //
4587 // Proof:
4588 // Expr(i+1) =
4589 // = Start + (i+1)*Accum
4590 // = (Start + i*Accum) + Accum
4591 // = Expr(i) + Accum
4592 // = (Ext ix (Trunc iy (Expr(i-1)) to ix) to iy) + Accum + Accum
4593 // :: from step i
4594 //
4595 // = (Ext ix (Trunc iy (Start + (i-1)*Accum) to ix) to iy) + Accum + Accum
4596 //
4597 // = (Ext ix (Trunc iy (Start + (i-1)*Accum) to ix) to iy)
4598 // + (Ext ix (Trunc iy (Accum) to ix) to iy)
4599 // + Accum :: from P3
4600 //
4601 // = (Ext ix (Trunc iy ((Start + (i-1)*Accum) + Accum) to ix) to iy)
4602 // + Accum :: from P1: Ext(x)+Ext(y)=>Ext(x+y)
4603 //
4604 // = (Ext ix (Trunc iy (Start + i*Accum) to ix) to iy) + Accum
4605 // = (Ext ix (Trunc iy (Expr(i)) to ix) to iy) + Accum
4606 //
4607 // By induction, the same applies to all iterations 1<=i<n:
4608 //
4609
4610 // Create a truncated addrec for which we will add a no overflow check (P1).
4611 const SCEV *StartVal = getSCEV(StartValueV);
4612 const SCEV *PHISCEV =
4613 getAddRecExpr(getTruncateExpr(StartVal, TruncTy),
4614 getTruncateExpr(Accum, TruncTy), L, SCEV::FlagAnyWrap);
4615
4616 // PHISCEV can be either a SCEVConstant or a SCEVAddRecExpr.
4617 // ex: If truncated Accum is 0 and StartVal is a constant, then PHISCEV
4618 // will be constant.
4619 //
4620 // If PHISCEV is a constant, then P1 degenerates into P2 or P3, so we don't
4621 // add P1.
4622 if (const auto *AR = dyn_cast<SCEVAddRecExpr>(PHISCEV)) {
4623 SCEVWrapPredicate::IncrementWrapFlags AddedFlags =
4624 Signed ? SCEVWrapPredicate::IncrementNSSW
4625 : SCEVWrapPredicate::IncrementNUSW;
4626 const SCEVPredicate *AddRecPred = getWrapPredicate(AR, AddedFlags);
4627 Predicates.push_back(AddRecPred);
4628 }
4629
4630 // Create the Equal Predicates P2,P3:
4631
4632 // It is possible that the predicates P2 and/or P3 are computable at
4633 // compile time due to StartVal and/or Accum being constants.
4634 // If either one is, then we can check that now and escape if either P2
4635 // or P3 is false.
4636
4637 // Construct the extended SCEV: (Ext ix (Trunc iy (Expr) to ix) to iy)
4638 // for each of StartVal and Accum
4639 auto getExtendedExpr = [&](const SCEV *Expr,
4640 bool CreateSignExtend) -> const SCEV * {
4641 assert(isLoopInvariant(Expr, L) && "Expr is expected to be invariant")(static_cast <bool> (isLoopInvariant(Expr, L) &&
"Expr is expected to be invariant") ? void (0) : __assert_fail
("isLoopInvariant(Expr, L) && \"Expr is expected to be invariant\""
, "/build/llvm-toolchain-snapshot-6.0~svn320940/lib/Analysis/ScalarEvolution.cpp"
, 4641, __extension__ __PRETTY_FUNCTION__))
;
4642 const SCEV *TruncatedExpr = getTruncateExpr(Expr, TruncTy);
4643 const SCEV *ExtendedExpr =
4644 CreateSignExtend ? getSignExtendExpr(TruncatedExpr, Expr->getType())
4645 : getZeroExtendExpr(TruncatedExpr, Expr->getType());
4646 return ExtendedExpr;
4647 };
4648
4649 // Given:
4650 // ExtendedExpr = (Ext ix (Trunc iy (Expr) to ix) to iy
4651 // = getExtendedExpr(Expr)
4652 // Determine whether the predicate P: Expr == ExtendedExpr
4653 // is known to be false at compile time
4654 auto PredIsKnownFalse = [&](const SCEV *Expr,
4655 const SCEV *ExtendedExpr) -> bool {
4656 return Expr != ExtendedExpr &&
4657 isKnownPredicate(ICmpInst::ICMP_NE, Expr, ExtendedExpr);
4658 };
4659
4660 const SCEV *StartExtended = getExtendedExpr(StartVal, Signed);
4661 if (PredIsKnownFalse(StartVal, StartExtended)) {
4662 DEBUG(dbgs() << "P2 is compile-time false\n";)do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("scalar-evolution")) { dbgs() << "P2 is compile-time false\n"
;; } } while (false)
;
4663 return None;
4664 }
4665
4666 // The Step is always Signed (because the overflow checks are either
4667 // NSSW or NUSW)
4668 const SCEV *AccumExtended = getExtendedExpr(Accum, /*CreateSignExtend=*/true);
4669 if (PredIsKnownFalse(Accum, AccumExtended)) {
4670 DEBUG(dbgs() << "P3 is compile-time false\n";)do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("scalar-evolution")) { dbgs() << "P3 is compile-time false\n"
;; } } while (false)
;
4671 return None;
4672 }
4673
4674 auto AppendPredicate = [&](const SCEV *Expr,
4675 const SCEV *ExtendedExpr) -> void {
4676 if (Expr != ExtendedExpr &&
4677 !isKnownPredicate(ICmpInst::ICMP_EQ, Expr, ExtendedExpr)) {
4678 const SCEVPredicate *Pred = getEqualPredicate(Expr, ExtendedExpr);
4679 DEBUG (dbgs() << "Added Predicate: " << *Pred)do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("scalar-evolution")) { dbgs() << "Added Predicate: " <<
*Pred; } } while (false)
;
4680 Predicates.push_back(Pred);
4681 }
4682 };
4683
4684 AppendPredicate(StartVal, StartExtended);
4685 AppendPredicate(Accum, AccumExtended);
4686
4687 // *** Part3: Predicates are ready. Now go ahead and create the new addrec in
4688 // which the casts had been folded away. The caller can rewrite SymbolicPHI
4689 // into NewAR if it will also add the runtime overflow checks specified in
4690 // Predicates.
4691 auto *NewAR = getAddRecExpr(StartVal, Accum, L, SCEV::FlagAnyWrap);
4692
4693 std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>> PredRewrite =
4694 std::make_pair(NewAR, Predicates);
4695 // Remember the result of the analysis for this SCEV at this locayyytion.
4696 PredicatedSCEVRewrites[{SymbolicPHI, L}] = PredRewrite;
4697 return PredRewrite;
4698}
4699
4700Optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>>
4701ScalarEvolution::createAddRecFromPHIWithCasts(const SCEVUnknown *SymbolicPHI) {
4702 auto *PN = cast<PHINode>(SymbolicPHI->getValue());
4703 const Loop *L = isIntegerLoopHeaderPHI(PN, LI);
4704 if (!L)
4705 return None;
4706
4707 // Check to see if we already analyzed this PHI.
4708 auto I = PredicatedSCEVRewrites.find({SymbolicPHI, L});
4709 if (I != PredicatedSCEVRewrites.end()) {
4710 std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>> Rewrite =
4711 I->second;
4712 // Analysis was done before and failed to create an AddRec:
4713 if (Rewrite.first == SymbolicPHI)
4714 return None;
4715 // Analysis was done before and succeeded to create an AddRec under
4716 // a predicate:
4717 assert(isa<SCEVAddRecExpr>(Rewrite.first) && "Expected an AddRec")(static_cast <bool> (isa<SCEVAddRecExpr>(Rewrite.
first) && "Expected an AddRec") ? void (0) : __assert_fail
("isa<SCEVAddRecExpr>(Rewrite.first) && \"Expected an AddRec\""
, "/build/llvm-toolchain-snapshot-6.0~svn320940/lib/Analysis/ScalarEvolution.cpp"
, 4717, __extension__ __PRETTY_FUNCTION__))
;
4718 assert(!(Rewrite.second).empty() && "Expected to find Predicates")(static_cast <bool> (!(Rewrite.second).empty() &&
"Expected to find Predicates") ? void (0) : __assert_fail ("!(Rewrite.second).empty() && \"Expected to find Predicates\""
, "/build/llvm-toolchain-snapshot-6.0~svn320940/lib/Analysis/ScalarEvolution.cpp"
, 4718, __extension__ __PRETTY_FUNCTION__))
;
4719 return Rewrite;
4720 }
4721
4722 Optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>>
4723 Rewrite = createAddRecFromPHIWithCastsImpl(SymbolicPHI);
4724
4725 // Record in the cache that the analysis failed
4726 if (!Rewrite) {
4727 SmallVector<const SCEVPredicate *, 3> Predicates;
4728 PredicatedSCEVRewrites[{SymbolicPHI, L}] = {SymbolicPHI, Predicates};
4729 return None;
4730 }
4731
4732 return Rewrite;
4733}
4734
4735// FIXME: This utility is currently required because the Rewriter currently
4736// does not rewrite this expression:
4737// {0, +, (sext ix (trunc iy to ix) to iy)}
4738// into {0, +, %step},
4739// even when the following Equal predicate exists:
4740// "%step == (sext ix (trunc iy to ix) to iy)".
4741bool PredicatedScalarEvolution::areAddRecsEqualWithPreds(
4742 const SCEVAddRecExpr *AR1, const SCEVAddRecExpr *AR2) const {
4743 if (AR1 == AR2)
4744 return true;
4745
4746 auto areExprsEqual = [&](const SCEV *Expr1, const SCEV *Expr2) -> bool {
4747 if (Expr1 != Expr2 && !Preds.implies(SE.getEqualPredicate(Expr1, Expr2)) &&
4748 !Preds.implies(SE.getEqualPredicate(Expr2, Expr1)))
4749 return false;
4750 return true;
4751 };
4752
4753 if (!areExprsEqual(AR1->getStart(), AR2->getStart()) ||
4754 !areExprsEqual(AR1->getStepRecurrence(SE), AR2->getStepRecurrence(SE)))
4755 return false;
4756 return true;
4757}
4758
4759/// A helper function for createAddRecFromPHI to handle simple cases.
4760///
4761/// This function tries to find an AddRec expression for the simplest (yet most
4762/// common) cases: PN = PHI(Start, OP(Self, LoopInvariant)).
4763/// If it fails, createAddRecFromPHI will use a more general, but slow,
4764/// technique for finding the AddRec expression.
4765const SCEV *ScalarEvolution::createSimpleAffineAddRec(PHINode *PN,
4766 Value *BEValueV,
4767 Value *StartValueV) {
4768 const Loop *L = LI.getLoopFor(PN->getParent());
4769 assert(L && L->getHeader() == PN->getParent())(static_cast <bool> (L && L->getHeader() == PN
->getParent()) ? void (0) : __assert_fail ("L && L->getHeader() == PN->getParent()"
, "/build/llvm-toolchain-snapshot-6.0~svn320940/lib/Analysis/ScalarEvolution.cpp"
, 4769, __extension__ __PRETTY_FUNCTION__))
;
4770 assert(BEValueV && StartValueV)(static_cast <bool> (BEValueV && StartValueV) ?
void (0) : __assert_fail ("BEValueV && StartValueV",
"/build/llvm-toolchain-snapshot-6.0~svn320940/lib/Analysis/ScalarEvolution.cpp"
, 4770, __extension__ __PRETTY_FUNCTION__))
;
4771
4772 auto BO = MatchBinaryOp(BEValueV, DT);
4773 if (!BO)
4774 return nullptr;
4775
4776 if (BO->Opcode != Instruction::Add)
4777 return nullptr;
4778
4779 const SCEV *Accum = nullptr;
4780 if (BO->LHS == PN && L->isLoopInvariant(BO->RHS))
4781 Accum = getSCEV(BO->RHS);
4782 else if (BO->RHS == PN && L->isLoopInvariant(BO->LHS))
4783 Accum = getSCEV(BO->LHS);
4784
4785 if (!Accum)
4786 return nullptr;
4787
4788 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap;
4789 if (BO->IsNUW)
4790 Flags = setFlags(Flags, SCEV::FlagNUW);
4791 if (BO->IsNSW)
4792 Flags = setFlags(Flags, SCEV::FlagNSW);
4793
4794 const SCEV *StartVal = getSCEV(StartValueV);
4795 const SCEV *PHISCEV = getAddRecExpr(StartVal, Accum, L, Flags);
4796
4797 ValueExprMap[SCEVCallbackVH(PN, this)] = PHISCEV;
4798
4799 // We can add Flags to the post-inc expression only if we
4800 // know that it is *undefined behavior* for BEValueV to
4801 // overflow.
4802 if (auto *BEInst = dyn_cast<Instruction>(BEValueV))
4803 if (isLoopInvariant(Accum, L) && isAddRecNeverPoison(BEInst, L))
4804 (void)getAddRecExpr(getAddExpr(StartVal, Accum), Accum, L, Flags);
4805
4806 return PHISCEV;
4807}
4808
4809const SCEV *ScalarEvolution::createAddRecFromPHI(PHINode *PN) {
4810 const Loop *L = LI.getLoopFor(PN->getParent());
4811 if (!L || L->getHeader() != PN->getParent())
4812 return nullptr;
4813
4814 // The loop may have multiple entrances or multiple exits; we can analyze
4815 // this phi as an addrec if it has a unique entry value and a unique
4816 // backedge value.
4817 Value *BEValueV = nullptr, *StartValueV = nullptr;
4818 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
4819 Value *V = PN->getIncomingValue(i);
4820 if (L->contains(PN->getIncomingBlock(i))) {
4821 if (!BEValueV) {
4822 BEValueV = V;
4823 } else if (BEValueV != V) {
4824 BEValueV = nullptr;
4825 break;
4826 }
4827 } else if (!StartValueV) {
4828 StartValueV = V;
4829 } else if (StartValueV != V) {
4830 StartValueV = nullptr;
4831 break;
4832 }
4833 }
4834 if (!BEValueV || !StartValueV)
4835 return nullptr;
4836
4837 assert(ValueExprMap.find_as(PN) == ValueExprMap.end() &&(static_cast <bool> (ValueExprMap.find_as(PN) == ValueExprMap
.end() && "PHI node already processed?") ? void (0) :
__assert_fail ("ValueExprMap.find_as(PN) == ValueExprMap.end() && \"PHI node already processed?\""
, "/build/llvm-toolchain-snapshot-6.0~svn320940/lib/Analysis/ScalarEvolution.cpp"
, 4838, __extension__ __PRETTY_FUNCTION__))
4838 "PHI node already processed?")(static_cast <bool> (ValueExprMap.find_as(PN) == ValueExprMap
.end() && "PHI node already processed?") ? void (0) :
__assert_fail ("ValueExprMap.find_as(PN) == ValueExprMap.end() && \"PHI node already processed?\""
, "/build/llvm-toolchain-snapshot-6.0~svn320940/lib/Analysis/ScalarEvolution.cpp"
, 4838, __extension__ __PRETTY_FUNCTION__))
;
4839
4840 // First, try to find AddRec expression without creating a fictituos symbolic
4841 // value for PN.
4842 if (auto *S = createSimpleAffineAddRec(PN, BEValueV, StartValueV))
4843 return S;
4844
4845 // Handle PHI node value symbolically.
4846 const SCEV *SymbolicName = getUnknown(PN);
4847 ValueExprMap.insert({SCEVCallbackVH(PN, this), SymbolicName});
4848
4849 // Using this symbolic name for the PHI, analyze the value coming around
4850 // the back-edge.
4851 const SCEV *BEValue = getSCEV(BEValueV);
4852
4853 // NOTE: If BEValue is loop invariant, we know that the PHI node just
4854 // has a special value for the first iteration of the loop.
4855
4856 // If the value coming around the backedge is an add with the symbolic
4857 // value we just inserted, then we found a simple induction variable!
4858 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(BEValue)) {
4859 // If there is a single occurrence of the symbolic value, replace it
4860 // with a recurrence.
4861 unsigned FoundIndex = Add->getNumOperands();
4862 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
4863 if (Add->getOperand(i) == SymbolicName)
4864 if (FoundIndex == e) {
4865 FoundIndex = i;
4866 break;
4867 }
4868
4869 if (FoundIndex != Add->getNumOperands()) {
4870 // Create an add with everything but the specified operand.
4871 SmallVector<const SCEV *, 8> Ops;
4872 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
4873 if (i != FoundIndex)
4874 Ops.push_back(SCEVBackedgeConditionFolder::rewrite(Add->getOperand(i),
4875 L, *this));
4876 const SCEV *Accum = getAddExpr(Ops);
4877
4878 // This is not a valid addrec if the step amount is varying each
4879 // loop iteration, but is not itself an addrec in this loop.
4880 if (isLoopInvariant(Accum, L) ||
4881 (isa<SCEVAddRecExpr>(Accum) &&
4882 cast<SCEVAddRecExpr>(Accum)->getLoop() == L)) {
4883 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap;
4884
4885 if (auto BO = MatchBinaryOp(BEValueV, DT)) {
4886 if (BO->Opcode == Instruction::Add && BO->LHS == PN) {
4887 if (BO->IsNUW)
4888 Flags = setFlags(Flags, SCEV::FlagNUW);
4889 if (BO->IsNSW)
4890 Flags = setFlags(Flags, SCEV::FlagNSW);
4891 }
4892 } else if (GEPOperator *GEP = dyn_cast<GEPOperator>(BEValueV)) {
4893 // If the increment is an inbounds GEP, then we know the address
4894 // space cannot be wrapped around. We cannot make any guarantee
4895 // about signed or unsigned overflow because pointers are
4896 // unsigned but we may have a negative index from the base
4897 // pointer. We can guarantee that no unsigned wrap occurs if the
4898 // indices form a positive value.
4899 if (GEP->isInBounds() && GEP->getOperand(0) == PN) {
4900 Flags = setFlags(Flags, SCEV::FlagNW);
4901
4902 const SCEV *Ptr = getSCEV(GEP->getPointerOperand());
4903 if (isKnownPositive(getMinusSCEV(getSCEV(GEP), Ptr)))
4904 Flags = setFlags(Flags, SCEV::FlagNUW);
4905 }
4906
4907 // We cannot transfer nuw and nsw flags from subtraction
4908 // operations -- sub nuw X, Y is not the same as add nuw X, -Y
4909 // for instance.
4910 }
4911
4912 const SCEV *StartVal = getSCEV(StartValueV);
4913 const SCEV *PHISCEV = getAddRecExpr(StartVal, Accum, L, Flags);
4914
4915 // Okay, for the entire analysis of this edge we assumed the PHI
4916 // to be symbolic. We now need to go back and purge all of the
4917 // entries for the scalars that use the symbolic expression.
4918 forgetSymbolicName(PN, SymbolicName);
4919 ValueExprMap[SCEVCallbackVH(PN, this)] = PHISCEV;
4920
4921 // We can add Flags to the post-inc expression only if we
4922 // know that it is *undefined behavior* for BEValueV to
4923 // overflow.
4924 if (auto *BEInst = dyn_cast<Instruction>(BEValueV))
4925 if (isLoopInvariant(Accum, L) && isAddRecNeverPoison(BEInst, L))
4926 (void)getAddRecExpr(getAddExpr(StartVal, Accum), Accum, L, Flags);
4927
4928 return PHISCEV;
4929 }
4930 }
4931 } else {
4932 // Otherwise, this could be a loop like this:
4933 // i = 0; for (j = 1; ..; ++j) { .... i = j; }
4934 // In this case, j = {1,+,1} and BEValue is j.
4935 // Because the other in-value of i (0) fits the evolution of BEValue
4936 // i really is an addrec evolution.
4937 //
4938 // We can generalize this saying that i is the shifted value of BEValue
4939 // by one iteration:
4940 // PHI(f(0), f({1,+,1})) --> f({0,+,1})
4941 const SCEV *Shifted = SCEVShiftRewriter::rewrite(BEValue, L, *this);
4942 const SCEV *Start = SCEVInitRewriter::rewrite(Shifted, L, *this);
4943 if (Shifted != getCouldNotCompute() &&
4944 Start != getCouldNotCompute()) {
4945 const SCEV *StartVal = getSCEV(StartValueV);
4946 if (Start == StartVal) {
4947 // Okay, for the entire analysis of this edge we assumed the PHI
4948 // to be symbolic. We now need to go back and purge all of the
4949 // entries for the scalars that use the symbolic expression.
4950 forgetSymbolicName(PN, SymbolicName);
4951 ValueExprMap[SCEVCallbackVH(PN, this)] = Shifted;
4952 return Shifted;
4953 }
4954 }
4955 }
4956
4957 // Remove the temporary PHI node SCEV that has been inserted while intending
4958 // to create an AddRecExpr for this PHI node. We can not keep this temporary
4959 // as it will prevent later (possibly simpler) SCEV expressions to be added
4960 // to the ValueExprMap.
4961 eraseValueFromMap(PN);
4962
4963 return nullptr;
4964}
4965
4966// Checks if the SCEV S is available at BB. S is considered available at BB
4967// if S can be materialized at BB without introducing a fault.
4968static bool IsAvailableOnEntry(const Loop *L, DominatorTree &DT, const SCEV *S,
4969 BasicBlock *BB) {
4970 struct CheckAvailable {
4971 bool TraversalDone = false;
4972 bool Available = true;
4973
4974 const Loop *L = nullptr; // The loop BB is in (can be nullptr)
4975 BasicBlock *BB = nullptr;
4976 DominatorTree &DT;
4977
4978 CheckAvailable(const Loop *L, BasicBlock *BB, DominatorTree &DT)
4979 : L(L), BB(BB), DT(DT) {}
4980
4981 bool setUnavailable() {
4982 TraversalDone = true;
4983 Available = false;
4984 return false;
4985 }
4986
4987 bool follow(const SCEV *S) {
4988 switch (S->getSCEVType()) {
4989 case scConstant: case scTruncate: case scZeroExtend: case scSignExtend:
4990 case scAddExpr: case scMulExpr: case scUMaxExpr: case scSMaxExpr:
4991 // These expressions are available if their operand(s) is/are.
4992 return true;
4993
4994 case scAddRecExpr: {
4995 // We allow add recurrences that are on the loop BB is in, or some
4996 // outer loop. This guarantees availability because the value of the
4997 // add recurrence at BB is simply the "current" value of the induction
4998 // variable. We can relax this in the future; for instance an add
4999 // recurrence on a sibling dominating loop is also available at BB.
5000 const auto *ARLoop = cast<SCEVAddRecExpr>(S)->getLoop();
5001 if (L && (ARLoop == L || ARLoop->contains(L)))
5002 return true;
5003
5004 return setUnavailable();
5005 }
5006
5007 case scUnknown: {
5008 // For SCEVUnknown, we check for simple dominance.
5009 const auto *SU = cast<SCEVUnknown>(S);
5010 Value *V = SU->getValue();
5011
5012 if (isa<Argument>(V))
5013 return false;
5014
5015 if (isa<Instruction>(V) && DT.dominates(cast<Instruction>(V), BB))
5016 return false;
5017
5018 return setUnavailable();
5019 }
5020
5021 case scUDivExpr:
5022 case scCouldNotCompute:
5023 // We do not try to smart about these at all.
5024 return setUnavailable();
5025 }
5026 llvm_unreachable("switch should be fully covered!")::llvm::llvm_unreachable_internal("switch should be fully covered!"
, "/build/llvm-toolchain-snapshot-6.0~svn320940/lib/Analysis/ScalarEvolution.cpp"
, 5026)
;
5027 }
5028
5029 bool isDone() { return TraversalDone; }
5030 };
5031
5032 CheckAvailable CA(L, BB, DT);
5033 SCEVTraversal<CheckAvailable> ST(CA);
5034
5035 ST.visitAll(S);
5036 return CA.Available;
5037}
5038
5039// Try to match a control flow sequence that branches out at BI and merges back
5040// at Merge into a "C ? LHS : RHS" select pattern. Return true on a successful
5041// match.
5042static bool BrPHIToSelect(DominatorTree &DT, BranchInst *BI, PHINode *Merge,
5043 Value *&C, Value *&LHS, Value *&RHS) {
5044 C = BI->getCondition();
5045
5046 BasicBlockEdge LeftEdge(BI->getParent(), BI->getSuccessor(0));
5047 BasicBlockEdge RightEdge(BI->getParent(), BI->getSuccessor(1));
5048
5049 if (!LeftEdge.isSingleEdge())
5050 return false;
5051
5052 assert(RightEdge.isSingleEdge() && "Follows from LeftEdge.isSingleEdge()")(static_cast <bool> (RightEdge.isSingleEdge() &&
"Follows from LeftEdge.isSingleEdge()") ? void (0) : __assert_fail
("RightEdge.isSingleEdge() && \"Follows from LeftEdge.isSingleEdge()\""
, "/build/llvm-toolchain-snapshot-6.0~svn320940/lib/Analysis/ScalarEvolution.cpp"
, 5052, __extension__ __PRETTY_FUNCTION__))
;
5053
5054 Use &LeftUse = Merge->getOperandUse(0);
5055 Use &RightUse = Merge->getOperandUse(1);
5056
5057 if (DT.dominates(LeftEdge, LeftUse) && DT.dominates(RightEdge, RightUse)) {
5058 LHS = LeftUse;
5059 RHS = RightUse;
5060 return true;
5061 }
5062
5063 if (DT.dominates(LeftEdge, RightUse) && DT.dominates(RightEdge, LeftUse)) {
5064 LHS = RightUse;
5065 RHS = LeftUse;
5066 return true;
5067 }
5068
5069 return false;
5070}
5071
5072const SCEV *ScalarEvolution::createNodeFromSelectLikePHI(PHINode *PN) {
5073 auto IsReachable =
5074 [&](BasicBlock *BB) { return DT.isReachableFromEntry(BB); };
5075 if (PN->getNumIncomingValues() == 2 && all_of(PN->blocks(), IsReachable)) {
5076 const Loop *L = LI.getLoopFor(PN->getParent());
5077
5078 // We don't want to break LCSSA, even in a SCEV expression tree.
5079 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
5080 if (LI.getLoopFor(PN->getIncomingBlock(i)) != L)
5081 return nullptr;
5082
5083 // Try to match
5084 //
5085 // br %cond, label %left, label %right
5086 // left:
5087 // br label %merge
5088 // right:
5089 // br label %merge
5090 // merge:
5091 // V = phi [ %x, %left ], [ %y, %right ]
5092 //
5093 // as "select %cond, %x, %y"
5094
5095 BasicBlock *IDom = DT[PN->getParent()]->getIDom()->getBlock();
5096 assert(IDom && "At least the entry block should dominate PN")(static_cast <bool> (IDom && "At least the entry block should dominate PN"
) ? void (0) : __assert_fail ("IDom && \"At least the entry block should dominate PN\""
, "/build/llvm-toolchain-snapshot-6.0~svn320940/lib/Analysis/ScalarEvolution.cpp"
, 5096, __extension__ __PRETTY_FUNCTION__))
;
5097
5098 auto *BI = dyn_cast<BranchInst>(IDom->getTerminator());
5099 Value *Cond = nullptr, *LHS = nullptr, *RHS = nullptr;
5100
5101 if (BI && BI->isConditional() &&
5102 BrPHIToSelect(DT, BI, PN, Cond, LHS, RHS) &&
5103 IsAvailableOnEntry(L, DT, getSCEV(LHS), PN->getParent()) &&
5104 IsAvailableOnEntry(L, DT, getSCEV(RHS), PN->getParent()))
5105 return createNodeForSelectOrPHI(PN, Cond, LHS, RHS);
5106 }
5107
5108 return nullptr;
5109}
5110
5111const SCEV *ScalarEvolution::createNodeForPHI(PHINode *PN) {
5112 if (const SCEV *S = createAddRecFromPHI(PN))
5113 return S;
5114
5115 if (const SCEV *S = createNodeFromSelectLikePHI(PN))
5116 return S;
5117
5118 // If the PHI has a single incoming value, follow that value, unless the
5119 // PHI's incoming blocks are in a different loop, in which case doing so
5120 // risks breaking LCSSA form. Instcombine would normally zap these, but
5121 // it doesn't have DominatorTree information, so it may miss cases.
5122 if (Value *V = SimplifyInstruction(PN, {getDataLayout(), &TLI, &DT, &AC}))
5123 if (LI.replacementPreservesLCSSAForm(PN, V))
5124 return getSCEV(V);
5125
5126 // If it's not a loop phi, we can't handle it yet.
5127 return getUnknown(PN);
5128}
5129
5130const SCEV *ScalarEvolution::createNodeForSelectOrPHI(Instruction *I,
5131 Value *Cond,
5132 Value *TrueVal,
5133 Value *FalseVal) {
5134 // Handle "constant" branch or select. This can occur for instance when a
5135 // loop pass transforms an inner loop and moves on to process the outer loop.
5136 if (auto *CI = dyn_cast<ConstantInt>(Cond))
5137 return getSCEV(CI->isOne() ? TrueVal : FalseVal);
5138
5139 // Try to match some simple smax or umax patterns.
5140 auto *ICI = dyn_cast<ICmpInst>(Cond);
5141 if (!ICI)
5142 return getUnknown(I);
5143
5144 Value *LHS = ICI->getOperand(0);
5145 Value *RHS = ICI->getOperand(1);
5146
5147 switch (ICI->getPredicate()) {
5148 case ICmpInst::ICMP_SLT:
5149 case ICmpInst::ICMP_SLE:
5150 std::swap(LHS, RHS);
5151 LLVM_FALLTHROUGH[[clang::fallthrough]];
5152 case ICmpInst::ICMP_SGT:
5153 case ICmpInst::ICMP_SGE:
5154 // a >s b ? a+x : b+x -> smax(a, b)+x
5155 // a >s b ? b+x : a+x -> smin(a, b)+x
5156 if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType())) {
5157 const SCEV *LS = getNoopOrSignExtend(getSCEV(LHS), I->getType());
5158 const SCEV *RS = getNoopOrSignExtend(getSCEV(RHS), I->getType());
5159 const SCEV *LA = getSCEV(TrueVal);
5160 const SCEV *RA = getSCEV(FalseVal);
5161 const SCEV *LDiff = getMinusSCEV(LA, LS);
5162 const SCEV *RDiff = getMinusSCEV(RA, RS);
5163 if (LDiff == RDiff)
5164 return getAddExpr(getSMaxExpr(LS, RS), LDiff);
5165 LDiff = getMinusSCEV(LA, RS);
5166 RDiff = getMinusSCEV(RA, LS);
5167 if (LDiff == RDiff)
5168 return getAddExpr(getSMinExpr(LS, RS), LDiff);
5169 }
5170 break;
5171 case ICmpInst::ICMP_ULT:
5172 case ICmpInst::ICMP_ULE:
5173 std::swap(LHS, RHS);
5174 LLVM_FALLTHROUGH[[clang::fallthrough]];
5175 case ICmpInst::ICMP_UGT:
5176 case ICmpInst::ICMP_UGE:
5177 // a >u b ? a+x : b+x -> umax(a, b)+x
5178 // a >u b ? b+x : a+x -> umin(a, b)+x
5179 if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType())) {
5180 const SCEV *LS = getNoopOrZeroExtend(getSCEV(LHS), I->getType());
5181 const SCEV *RS = getNoopOrZeroExtend(getSCEV(RHS), I->getType());
5182 const SCEV *LA = getSCEV(TrueVal);
5183 const SCEV *RA = getSCEV(FalseVal);
5184 const SCEV *LDiff = getMinusSCEV(LA, LS);
5185 const SCEV *RDiff = getMinusSCEV(RA, RS);
5186 if (LDiff == RDiff)
5187 return getAddExpr(getUMaxExpr(LS, RS), LDiff);
5188 LDiff = getMinusSCEV(LA, RS);
5189 RDiff = getMinusSCEV(RA, LS);
5190 if (LDiff == RDiff)
5191 return getAddExpr(getUMinExpr(LS, RS), LDiff);
5192 }
5193 break;
5194 case ICmpInst::ICMP_NE:
5195 // n != 0 ? n+x : 1+x -> umax(n, 1)+x
5196 if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType()) &&
5197 isa<ConstantInt>(RHS) && cast<ConstantInt>(RHS)->isZero()) {
5198 const SCEV *One = getOne(I->getType());
5199 const SCEV *LS = getNoopOrZeroExtend(getSCEV(LHS), I->getType());
5200 const SCEV *LA = getSCEV(TrueVal);
5201 const SCEV *RA = getSCEV(FalseVal);
5202 const SCEV *LDiff = getMinusSCEV(LA, LS);
5203 const SCEV *RDiff = getMinusSCEV(RA, One);
5204 if (LDiff == RDiff)
5205 return getAddExpr(getUMaxExpr(One, LS), LDiff);
5206 }
5207 break;
5208 case ICmpInst::ICMP_EQ:
5209 // n == 0 ? 1+x : n+x -> umax(n, 1)+x
5210 if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType()) &&
5211 isa<ConstantInt>(RHS) && cast<ConstantInt>(RHS)->isZero()) {
5212 const SCEV *One = getOne(I->getType());
5213 const SCEV *LS = getNoopOrZeroExtend(getSCEV(LHS), I->getType());
5214 const SCEV *LA = getSCEV(TrueVal);
5215 const SCEV *RA = getSCEV(FalseVal);
5216 const SCEV *LDiff = getMinusSCEV(LA, One);
5217 const SCEV *RDiff = getMinusSCEV(RA, LS);
5218 if (LDiff == RDiff)
5219 return getAddExpr(getUMaxExpr(One, LS), LDiff);
5220 }
5221 break;
5222 default:
5223 break;
5224 }
5225
5226 return getUnknown(I);
5227}
5228
5229/// Expand GEP instructions into add and multiply operations. This allows them
5230/// to be analyzed by regular SCEV code.
5231const SCEV *ScalarEvolution::createNodeForGEP(GEPOperator *GEP) {
5232 // Don't attempt to analyze GEPs over unsized objects.
5233 if (!GEP->getSourceElementType()->isSized())
5234 return getUnknown(GEP);
5235
5236 SmallVector<const SCEV *, 4> IndexExprs;
5237 for (auto Index = GEP->idx_begin(); Index != GEP->idx_end(); ++Index)
5238 IndexExprs.push_back(getSCEV(*Index));
5239 return getGEPExpr(GEP, IndexExprs);
5240}
5241
5242uint32_t ScalarEvolution::GetMinTrailingZerosImpl(const SCEV *S) {
5243 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S))
5244 return C->getAPInt().countTrailingZeros();
5245
5246 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(S))
5247 return std::min(GetMinTrailingZeros(T->getOperand()),
5248 (uint32_t)getTypeSizeInBits(T->getType()));
5249
5250 if (const SCEVZeroExtendExpr *E = dyn_cast<SCEVZeroExtendExpr>(S)) {
5251 uint32_t OpRes = GetMinTrailingZeros(E->getOperand());
5252 return OpRes == getTypeSizeInBits(E->getOperand()->getType())
5253 ? getTypeSizeInBits(E->getType())
5254 : OpRes;
5255 }
5256
5257 if (const SCEVSignExtendExpr *E = dyn_cast<SCEVSignExtendExpr>(S)) {
5258 uint32_t OpRes = GetMinTrailingZeros(E->getOperand());
5259 return OpRes == getTypeSizeInBits(E->getOperand()->getType())
5260 ? getTypeSizeInBits(E->getType())
5261 : OpRes;
5262 }
5263
5264 if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(S)) {
5265 // The result is the min of all operands results.
5266 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0));
5267 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
5268 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i)));
5269 return MinOpRes;
5270 }
5271
5272 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(S)) {
5273 // The result is the sum of all operands results.
5274 uint32_t SumOpRes = GetMinTrailingZeros(M->getOperand(0));
5275 uint32_t BitWidth = getTypeSizeInBits(M->getType());
5276 for (unsigned i = 1, e = M->getNumOperands();
5277 SumOpRes != BitWidth && i != e; ++i)
5278 SumOpRes =
5279 std::min(SumOpRes + GetMinTrailingZeros(M->getOperand(i)), BitWidth);
5280 return SumOpRes;
5281 }
5282
5283 if (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(S)) {
5284 // The result is the min of all operands results.
5285 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0));
5286 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
5287 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i)));
5288 return MinOpRes;
5289 }
5290
5291 if (const SCEVSMaxExpr *M = dyn_cast<SCEVSMaxExpr>(S)) {
5292 // The result is the min of all operands results.
5293 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0));
5294 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
5295 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i)));
5296 return MinOpRes;
5297 }
5298
5299 if (const SCEVUMaxExpr *M = dyn_cast<SCEVUMaxExpr>(S)) {
5300 // The result is the min of all operands results.
5301 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0));
5302 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
5303 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i)));
5304 return MinOpRes;
5305 }
5306
5307 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
5308 // For a SCEVUnknown, ask ValueTracking.
5309 KnownBits Known = computeKnownBits(U->getValue(), getDataLayout(), 0, &AC, nullptr, &DT);
5310 return Known.countMinTrailingZeros();
5311 }
5312
5313 // SCEVUDivExpr
5314 return 0;
5315}
5316
5317uint32_t ScalarEvolution::GetMinTrailingZeros(const SCEV *S) {
5318 auto I = MinTrailingZerosCache.find(S);
5319 if (I != MinTrailingZerosCache.end())
5320 return I->second;
5321
5322 uint32_t Result = GetMinTrailingZerosImpl(S);
5323 auto InsertPair = MinTrailingZerosCache.insert({S, Result});
5324 assert(InsertPair.second && "Should insert a new key")(static_cast <bool> (InsertPair.second && "Should insert a new key"
) ? void (0) : __assert_fail ("InsertPair.second && \"Should insert a new key\""
, "/build/llvm-toolchain-snapshot-6.0~svn320940/lib/Analysis/ScalarEvolution.cpp"
, 5324, __extension__ __PRETTY_FUNCTION__))
;
5325 return InsertPair.first->second;
5326}
5327
5328/// Helper method to assign a range to V from metadata present in the IR.
5329static Optional<ConstantRange> GetRangeFromMetadata(Value *V) {
5330 if (Instruction *I = dyn_cast<Instruction>(V))
5331 if (MDNode *MD = I->getMetadata(LLVMContext::MD_range))
5332 return getConstantRangeFromMetadata(*MD);
5333
5334 return None;
5335}
5336
5337/// Determine the range for a particular SCEV. If SignHint is
5338/// HINT_RANGE_UNSIGNED (resp. HINT_RANGE_SIGNED) then getRange prefers ranges
5339/// with a "cleaner" unsigned (resp. signed) representation.
5340const ConstantRange &
5341ScalarEvolution::getRangeRef(const SCEV *S,
5342 ScalarEvolution::RangeSignHint SignHint) {
5343 DenseMap<const SCEV *, ConstantRange> &Cache =
5344 SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED ? UnsignedRanges
5345 : SignedRanges;
5346
5347 // See if we've computed this range already.
5348 DenseMap<const SCEV *, ConstantRange>::iterator I = Cache.find(S);
5349 if (I != Cache.end())
5350 return I->second;
5351
5352 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S))
5353 return setRange(C, SignHint, ConstantRange(C->getAPInt()));
5354
5355 unsigned BitWidth = getTypeSizeInBits(S->getType());
5356 ConstantRange ConservativeResult(BitWidth, /*isFullSet=*/true);
5357
5358 // If the value has known zeros, the maximum value will have those known zeros
5359 // as well.
5360 uint32_t TZ = GetMinTrailingZeros(S);
5361 if (TZ != 0) {
5362 if (SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED)
5363 ConservativeResult =
5364 ConstantRange(APInt::getMinValue(BitWidth),
5365 APInt::getMaxValue(BitWidth).lshr(TZ).shl(TZ) + 1);
5366 else
5367 ConservativeResult = ConstantRange(
5368 APInt::getSignedMinValue(BitWidth),
5369 APInt::getSignedMaxValue(BitWidth).ashr(TZ).shl(TZ) + 1);
5370 }
5371
5372 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) {
5373 ConstantRange X = getRangeRef(Add->getOperand(0), SignHint);
5374 for (unsigned i = 1, e = Add->getNumOperands(); i != e; ++i)
5375 X = X.add(getRangeRef(Add->getOperand(i), SignHint));
5376 return setRange(Add, SignHint, ConservativeResult.intersectWith(X));
5377 }
5378
5379 if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(S)) {
5380 ConstantRange X = getRangeRef(Mul->getOperand(0), SignHint);
5381 for (unsigned i = 1, e = Mul->getNumOperands(); i != e; ++i)
5382 X = X.multiply(getRangeRef(Mul->getOperand(i), SignHint));
5383 return setRange(Mul, SignHint, ConservativeResult.intersectWith(X));
5384 }
5385
5386 if (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(S)) {
5387 ConstantRange X = getRangeRef(SMax->getOperand(0), SignHint);
5388 for (unsigned i = 1, e = SMax->getNumOperands(); i != e; ++i)
5389 X = X.smax(getRangeRef(SMax->getOperand(i), SignHint));
5390 return setRange(SMax, SignHint, ConservativeResult.intersectWith(X));
5391 }
5392
5393 if (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(S)) {
5394 ConstantRange X = getRangeRef(UMax->getOperand(0), SignHint);
5395 for (unsigned i = 1, e = UMax->getNumOperands(); i != e; ++i)
5396 X = X.umax(getRangeRef(UMax->getOperand(i), SignHint));
5397 return setRange(UMax, SignHint, ConservativeResult.intersectWith(X));
5398 }
5399
5400 if (const SCEVUDivExpr *UDiv = dyn_cast<SCEVUDivExpr>(S)) {
5401 ConstantRange X = getRangeRef(UDiv->getLHS(), SignHint);
5402 ConstantRange Y = getRangeRef(UDiv->getRHS(), SignHint);
5403 return setRange(UDiv, SignHint,
5404 ConservativeResult.intersectWith(X.udiv(Y)));
5405 }
5406
5407 if (const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(S)) {
5408 ConstantRange X = getRangeRef(ZExt->getOperand(), SignHint);
5409 return setRange(ZExt, SignHint,
5410 ConservativeResult.intersectWith(X.zeroExtend(BitWidth)));
5411 }
5412
5413 if (const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(S)) {
5414 ConstantRange X = getRangeRef(SExt->getOperand(), SignHint);
5415 return setRange(SExt, SignHint,
5416 ConservativeResult.intersectWith(X.signExtend(BitWidth)));
5417 }
5418
5419 if (const SCEVTruncateExpr *Trunc = dyn_cast<SCEVTruncateExpr>(S)) {
5420 ConstantRange X = getRangeRef(Trunc->getOperand(), SignHint);
5421 return setRange(Trunc, SignHint,
5422 ConservativeResult.intersectWith(X.truncate(BitWidth)));
5423 }
5424
5425 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(S)) {
5426 // If there's no unsigned wrap, the value will never be less than its
5427 // initial value.
5428 if (AddRec->hasNoUnsignedWrap())
5429 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(AddRec->getStart()))
5430 if (!C->getValue()->isZero())
5431 ConservativeResult = ConservativeResult.intersectWith(
5432 ConstantRange(C->getAPInt(), APInt(BitWidth, 0)));
5433
5434 // If there's no signed wrap, and all the operands have the same sign or
5435 // zero, the value won't ever change sign.
5436 if (AddRec->hasNoSignedWrap()) {
5437 bool AllNonNeg = true;
5438 bool AllNonPos = true;
5439 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) {
5440 if (!isKnownNonNegative(AddRec->getOperand(i))) AllNonNeg = false;
5441 if (!isKnownNonPositive(AddRec->getOperand(i))) AllNonPos = false;
5442 }
5443 if (AllNonNeg)
5444 ConservativeResult = ConservativeResult.intersectWith(
5445 ConstantRange(APInt(BitWidth, 0),
5446 APInt::getSignedMinValue(BitWidth)));
5447 else if (AllNonPos)
5448 ConservativeResult = ConservativeResult.intersectWith(
5449 ConstantRange(APInt::getSignedMinValue(BitWidth),
5450 APInt(BitWidth, 1)));
5451 }
5452
5453 // TODO: non-affine addrec
5454 if (AddRec->isAffine()) {
5455 const SCEV *MaxBECount = getMaxBackedgeTakenCount(AddRec->getLoop());
5456 if (!isa<SCEVCouldNotCompute>(MaxBECount) &&
5457 getTypeSizeInBits(MaxBECount->getType()) <= BitWidth) {
5458 auto RangeFromAffine = getRangeForAffineAR(
5459 AddRec->getStart(), AddRec->getStepRecurrence(*this), MaxBECount,
5460 BitWidth);
5461 if (!RangeFromAffine.isFullSet())
5462 ConservativeResult =
5463 ConservativeResult.intersectWith(RangeFromAffine);
5464
5465 auto RangeFromFactoring = getRangeViaFactoring(
5466 AddRec->getStart(), AddRec->getStepRecurrence(*this), MaxBECount,
5467 BitWidth);
5468 if (!RangeFromFactoring.isFullSet())
5469 ConservativeResult =
5470 ConservativeResult.intersectWith(RangeFromFactoring);
5471 }
5472 }
5473
5474 return setRange(AddRec, SignHint, std::move(ConservativeResult));
5475 }
5476
5477 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
5478 // Check if the IR explicitly contains !range metadata.
5479 Optional<ConstantRange> MDRange = GetRangeFromMetadata(U->getValue());
5480 if (MDRange.hasValue())
5481 ConservativeResult = ConservativeResult.intersectWith(MDRange.getValue());
5482
5483 // Split here to avoid paying the compile-time cost of calling both
5484 // computeKnownBits and ComputeNumSignBits. This restriction can be lifted
5485 // if needed.
5486 const DataLayout &DL = getDataLayout();
5487 if (SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED) {
5488 // For a SCEVUnknown, ask ValueTracking.
5489 KnownBits Known = computeKnownBits(U->getValue(), DL, 0, &AC, nullptr, &DT);
5490 if (Known.One != ~Known.Zero + 1)
5491 ConservativeResult =
5492 ConservativeResult.intersectWith(ConstantRange(Known.One,
5493 ~Known.Zero + 1));
5494 } else {
5495 assert(SignHint == ScalarEvolution::HINT_RANGE_SIGNED &&(static_cast <bool> (SignHint == ScalarEvolution::HINT_RANGE_SIGNED
&& "generalize as needed!") ? void (0) : __assert_fail
("SignHint == ScalarEvolution::HINT_RANGE_SIGNED && \"generalize as needed!\""
, "/build/llvm-toolchain-snapshot-6.0~svn320940/lib/Analysis/ScalarEvolution.cpp"
, 5496, __extension__ __PRETTY_FUNCTION__))
5496 "generalize as needed!")(static_cast <bool> (SignHint == ScalarEvolution::HINT_RANGE_SIGNED
&& "generalize as needed!") ? void (0) : __assert_fail
("SignHint == ScalarEvolution::HINT_RANGE_SIGNED && \"generalize as needed!\""
, "/build/llvm-toolchain-snapshot-6.0~svn320940/lib/Analysis/ScalarEvolution.cpp"
, 5496, __extension__ __PRETTY_FUNCTION__))
;
5497 unsigned NS = ComputeNumSignBits(U->getValue(), DL, 0, &AC, nullptr, &DT);
5498 if (NS > 1)
5499 ConservativeResult = ConservativeResult.intersectWith(
5500 ConstantRange(APInt::getSignedMinValue(BitWidth).ashr(NS - 1),
5501 APInt::getSignedMaxValue(BitWidth).ashr(NS - 1) + 1));
5502 }
5503
5504 return setRange(U, SignHint, std::move(ConservativeResult));
5505 }
5506
5507 return setRange(S, SignHint, std::move(ConservativeResult));
5508}
5509
5510// Given a StartRange, Step and MaxBECount for an expression compute a range of
5511// values that the expression can take. Initially, the expression has a value
5512// from StartRange and then is changed by Step up to MaxBECount times. Signed
5513// argument defines if we treat Step as signed or unsigned.
5514static ConstantRange getRangeForAffineARHelper(APInt Step,
5515 const ConstantRange &StartRange,
5516 const APInt &MaxBECount,
5517 unsigned BitWidth, bool Signed) {
5518 // If either Step or MaxBECount is 0, then the expression won't change, and we
5519 // just need to return the initial range.
5520 if (Step == 0 || MaxBECount == 0)
5521 return StartRange;
5522
5523 // If we don't know anything about the initial value (i.e. StartRange is
5524 // FullRange), then we don't know anything about the final range either.
5525 // Return FullRange.
5526 if (StartRange.isFullSet())
5527 return ConstantRange(BitWidth, /* isFullSet = */ true);
5528
5529 // If Step is signed and negative, then we use its absolute value, but we also
5530 // note that we're moving in the opposite direction.
5531 bool Descending = Signed && Step.isNegative();
5532
5533 if (Signed)
5534 // This is correct even for INT_SMIN. Let's look at i8 to illustrate this:
5535 // abs(INT_SMIN) = abs(-128) = abs(0x80) = -0x80 = 0x80 = 128.
5536 // This equations hold true due to the well-defined wrap-around behavior of
5537 // APInt.
5538 Step = Step.abs();
5539
5540 // Check if Offset is more than full span of BitWidth. If it is, the
5541 // expression is guaranteed to overflow.
5542 if (APInt::getMaxValue(StartRange.getBitWidth()).udiv(Step).ult(MaxBECount))
5543 return ConstantRange(BitWidth, /* isFullSet = */ true);
5544
5545 // Offset is by how much the expression can change. Checks above guarantee no
5546 // overflow here.
5547 APInt Offset = Step * MaxBECount;
5548
5549 // Minimum value of the final range will match the minimal value of StartRange
5550 // if the expression is increasing and will be decreased by Offset otherwise.
5551 // Maximum value of the final range will match the maximal value of StartRange
5552 // if the expression is decreasing and will be increased by Offset otherwise.
5553 APInt StartLower = StartRange.getLower();
5554 APInt StartUpper = StartRange.getUpper() - 1;
5555 APInt MovedBoundary = Descending ? (StartLower - std::move(Offset))
5556 : (StartUpper + std::move(Offset));
5557
5558 // It's possible that the new minimum/maximum value will fall into the initial
5559 // range (due to wrap around). This means that the expression can take any
5560 // value in this bitwidth, and we have to return full range.
5561 if (StartRange.contains(MovedBoundary))
5562 return ConstantRange(BitWidth, /* isFullSet = */ true);
5563
5564 APInt NewLower =
5565 Descending ? std::move(MovedBoundary) : std::move(StartLower);
5566 APInt NewUpper =
5567 Descending ? std::move(StartUpper) : std::move(MovedBoundary);
5568 NewUpper += 1;
5569
5570 // If we end up with full range, return a proper full range.
5571 if (NewLower == NewUpper)
5572 return ConstantRange(BitWidth, /* isFullSet = */ true);
5573
5574 // No overflow detected, return [StartLower, StartUpper + Offset + 1) range.
5575 return ConstantRange(std::move(NewLower), std::move(NewUpper));
5576}
5577
5578ConstantRange ScalarEvolution::getRangeForAffineAR(const SCEV *Start,
5579 const SCEV *Step,
5580 const SCEV *MaxBECount,
5581 unsigned BitWidth) {
5582 assert(!isa<SCEVCouldNotCompute>(MaxBECount) &&(static_cast <bool> (!isa<SCEVCouldNotCompute>(MaxBECount
) && getTypeSizeInBits(MaxBECount->getType()) <=
BitWidth && "Precondition!") ? void (0) : __assert_fail
("!isa<SCEVCouldNotCompute>(MaxBECount) && getTypeSizeInBits(MaxBECount->getType()) <= BitWidth && \"Precondition!\""
, "/build/llvm-toolchain-snapshot-6.0~svn320940/lib/Analysis/ScalarEvolution.cpp"
, 5584, __extension__ __PRETTY_FUNCTION__))
5583 getTypeSizeInBits(MaxBECount->getType()) <= BitWidth &&(static_cast <bool> (!isa<SCEVCouldNotCompute>(MaxBECount
) && getTypeSizeInBits(MaxBECount->getType()) <=
BitWidth && "Precondition!") ? void (0) : __assert_fail
("!isa<SCEVCouldNotCompute>(MaxBECount) && getTypeSizeInBits(MaxBECount->getType()) <= BitWidth && \"Precondition!\""
, "/build/llvm-toolchain-snapshot-6.0~svn320940/lib/Analysis/ScalarEvolution.cpp"
, 5584, __extension__ __PRETTY_FUNCTION__))
5584 "Precondition!")(static_cast <bool> (!isa<SCEVCouldNotCompute>(MaxBECount
) && getTypeSizeInBits(MaxBECount->getType()) <=
BitWidth && "Precondition!") ? void (0) : __assert_fail
("!isa<SCEVCouldNotCompute>(MaxBECount) && getTypeSizeInBits(MaxBECount->getType()) <= BitWidth && \"Precondition!\""
, "/build/llvm-toolchain-snapshot-6.0~svn320940/lib/Analysis/ScalarEvolution.cpp"
, 5584, __extension__ __PRETTY_FUNCTION__))
;
5585
5586 MaxBECount = getNoopOrZeroExtend(MaxBECount, Start->getType());
5587 APInt MaxBECountValue = getUnsignedRangeMax(MaxBECount);
5588
5589 // First, consider step signed.
5590 ConstantRange StartSRange = getSignedRange(Start);
5591 ConstantRange StepSRange = getSignedRange(Step);
5592
5593 // If Step can be both positive and negative, we need to find ranges for the
5594 // maximum absolute step values in both directions and union them.
5595 ConstantRange SR =
5596 getRangeForAffineARHelper(StepSRange.getSignedMin(), StartSRange,
5597 MaxBECountValue, BitWidth, /* Signed = */ true);
5598 SR = SR.unionWith(getRangeForAffineARHelper(StepSRange.getSignedMax(),
5599 StartSRange, MaxBECountValue,
5600 BitWidth, /* Signed = */ true));
5601
5602 // Next, consider step unsigned.
5603 ConstantRange UR = getRangeForAffineARHelper(
5604 getUnsignedRangeMax(Step), getUnsignedRange(Start),
5605 MaxBECountValue, BitWidth, /* Signed = */ false);
5606
5607 // Finally, intersect signed and unsigned ranges.
5608 return SR.intersectWith(UR);
5609}
5610
5611ConstantRange ScalarEvolution::getRangeViaFactoring(const SCEV *Start,
5612 const SCEV *Step,
5613 const SCEV *MaxBECount,
5614 unsigned BitWidth) {
5615 // RangeOf({C?A:B,+,C?P:Q}) == RangeOf(C?{A,+,P}:{B,+,Q})
5616 // == RangeOf({A,+,P}) union RangeOf({B,+,Q})
5617
5618 struct SelectPattern {
5619 Value *Condition = nullptr;
5620 APInt TrueValue;
5621 APInt FalseValue;
5622
5623 explicit SelectPattern(ScalarEvolution &SE, unsigned BitWidth,
5624 const SCEV *S) {
5625 Optional<unsigned> CastOp;
5626 APInt Offset(BitWidth, 0);
5627
5628 assert(SE.getTypeSizeInBits(S->getType()) == BitWidth &&(static_cast <bool> (SE.getTypeSizeInBits(S->getType
()) == BitWidth && "Should be!") ? void (0) : __assert_fail
("SE.getTypeSizeInBits(S->getType()) == BitWidth && \"Should be!\""
, "/build/llvm-toolchain-snapshot-6.0~svn320940/lib/Analysis/ScalarEvolution.cpp"
, 5629, __extension__ __PRETTY_FUNCTION__))
5629 "Should be!")(static_cast <bool> (SE.getTypeSizeInBits(S->getType
()) == BitWidth && "Should be!") ? void (0) : __assert_fail
("SE.getTypeSizeInBits(S->getType()) == BitWidth && \"Should be!\""
, "/build/llvm-toolchain-snapshot-6.0~svn320940/lib/Analysis/ScalarEvolution.cpp"
, 5629, __extension__ __PRETTY_FUNCTION__))
;
5630
5631 // Peel off a constant offset:
5632 if (auto *SA = dyn_cast<SCEVAddExpr>(S)) {
5633 // In the future we could consider being smarter here and handle
5634 // {Start+Step,+,Step} too.
5635 if (SA->getNumOperands() != 2 || !isa<SCEVConstant>(SA->getOperand(0)))
5636 return;
5637
5638 Offset = cast<SCEVConstant>(SA->getOperand(0))->getAPInt();
5639 S = SA->getOperand(1);
5640 }
5641
5642 // Peel off a cast operation
5643 if (auto *SCast = dyn_cast<SCEVCastExpr>(S)) {
5644 CastOp = SCast->getSCEVType();
5645 S = SCast->getOperand();
5646 }
5647
5648 using namespace llvm::PatternMatch;
5649
5650 auto *SU = dyn_cast<SCEVUnknown>(S);
5651 const APInt *TrueVal, *FalseVal;
5652 if (!SU ||
5653 !match(SU->getValue(), m_Select(m_Value(Condition), m_APInt(TrueVal),
5654 m_APInt(FalseVal)))) {
5655 Condition = nullptr;
5656 return;
5657 }
5658
5659 TrueValue = *TrueVal;
5660 FalseValue = *FalseVal;
5661
5662 // Re-apply the cast we peeled off earlier
5663 if (CastOp.hasValue())
5664 switch (*CastOp) {
5665 default:
5666 llvm_unreachable("Unknown SCEV cast type!")::llvm::llvm_unreachable_internal("Unknown SCEV cast type!", "/build/llvm-toolchain-snapshot-6.0~svn320940/lib/Analysis/ScalarEvolution.cpp"
, 5666)
;
5667
5668 case scTruncate:
5669 TrueValue = TrueValue.trunc(BitWidth);
5670 FalseValue = FalseValue.trunc(BitWidth);
5671 break;
5672 case scZeroExtend:
5673 TrueValue = TrueValue.zext(BitWidth);
5674 FalseValue = FalseValue.zext(BitWidth);
5675 break;
5676 case scSignExtend:
5677 TrueValue = TrueValue.sext(BitWidth);
5678 FalseValue = FalseValue.sext(BitWidth);
5679 break;
5680 }
5681
5682 // Re-apply the constant offset we peeled off earlier
5683 TrueValue += Offset;
5684 FalseValue += Offset;
5685 }
5686
5687 bool isRecognized() { return Condition != nullptr; }
5688 };
5689
5690 SelectPattern StartPattern(*this, BitWidth, Start);
5691 if (!StartPattern.isRecognized())
5692 return ConstantRange(BitWidth, /* isFullSet = */ true);
5693
5694 SelectPattern StepPattern(*this, BitWidth, Step);
5695 if (!StepPattern.isRecognized())
5696 return ConstantRange(BitWidth, /* isFullSet = */ true);
5697
5698 if (StartPattern.Condition != StepPattern.Condition) {
5699 // We don't handle this case today; but we could, by considering four
5700 // possibilities below instead of two. I'm not sure if there are cases where
5701 // that will help over what getRange already does, though.
5702 return ConstantRange(BitWidth, /* isFullSet = */ true);
5703 }
5704
5705 // NB! Calling ScalarEvolution::getConstant is fine, but we should not try to
5706 // construct arbitrary general SCEV expressions here. This function is called
5707 // from deep in the call stack, and calling getSCEV (on a sext instruction,
5708 // say) can end up caching a suboptimal value.
5709
5710 // FIXME: without the explicit `this` receiver below, MSVC errors out with
5711 // C2352 and C2512 (otherwise it isn't needed).
5712
5713 const SCEV *TrueStart = this->getConstant(StartPattern.TrueValue);
5714 const SCEV *TrueStep = this->getConstant(StepPattern.TrueValue);
5715 const SCEV *FalseStart = this->getConstant(StartPattern.FalseValue);
5716 const SCEV *FalseStep = this->getConstant(StepPattern.FalseValue);
5717
5718 ConstantRange TrueRange =
5719 this->getRangeForAffineAR(TrueStart, TrueStep, MaxBECount, BitWidth);
5720 ConstantRange FalseRange =
5721 this->getRangeForAffineAR(FalseStart, FalseStep, MaxBECount, BitWidth);
5722
5723 return TrueRange.unionWith(FalseRange);
5724}
5725
5726SCEV::NoWrapFlags ScalarEvolution::getNoWrapFlagsFromUB(const Value *V) {
5727 if (isa<ConstantExpr>(V)) return SCEV::FlagAnyWrap;
5728 const BinaryOperator *BinOp = cast<BinaryOperator>(V);
5729
5730 // Return early if there are no flags to propagate to the SCEV.
5731 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap;
5732 if (BinOp->hasNoUnsignedWrap())
5733 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNUW);
5734 if (BinOp->hasNoSignedWrap())
5735 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNSW);
5736 if (Flags == SCEV::FlagAnyWrap)
5737 return SCEV::FlagAnyWrap;
5738
5739 return isSCEVExprNeverPoison(BinOp) ? Flags : SCEV::FlagAnyWrap;
5740}
5741
5742bool ScalarEvolution::isSCEVExprNeverPoison(const Instruction *I) {
5743 // Here we check that I is in the header of the innermost loop containing I,
5744 // since we only deal with instructions in the loop header. The actual loop we
5745 // need to check later will come from an add recurrence, but getting that
5746 // requires computing the SCEV of the operands, which can be expensive. This
5747 // check we can do cheaply to rule out some cases early.
5748 Loop *InnermostContainingLoop = LI.getLoopFor(I->getParent());
5749 if (InnermostContainingLoop == nullptr ||
5750 InnermostContainingLoop->getHeader() != I->getParent())
5751 return false;
5752
5753 // Only proceed if we can prove that I does not yield poison.
5754 if (!programUndefinedIfFullPoison(I))
5755 return false;
5756
5757 // At this point we know that if I is executed, then it does not wrap
5758 // according to at least one of NSW or NUW. If I is not executed, then we do
5759 // not know if the calculation that I represents would wrap. Multiple
5760 // instructions can map to the same SCEV. If we apply NSW or NUW from I to
5761 // the SCEV, we must guarantee no wrapping for that SCEV also when it is
5762 // derived from other instructions that map to the same SCEV. We cannot make
5763 // that guarantee for cases where I is not executed. So we need to find the
5764 // loop that I is considered in relation to and prove that I is executed for
5765 // every iteration of that loop. That implies that the value that I
5766 // calculates does not wrap anywhere in the loop, so then we can apply the
5767 // flags to the SCEV.
5768 //
5769 // We check isLoopInvariant to disambiguate in case we are adding recurrences
5770 // from different loops, so that we know which loop to prove that I is
5771 // executed in.
5772 for (unsigned OpIndex = 0; OpIndex < I->getNumOperands(); ++OpIndex) {
5773 // I could be an extractvalue from a call to an overflow intrinsic.
5774 // TODO: We can do better here in some cases.
5775 if (!isSCEVable(I->getOperand(OpIndex)->getType()))
5776 return false;
5777 const SCEV *Op = getSCEV(I->getOperand(OpIndex));
5778 if (auto *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) {
5779 bool AllOtherOpsLoopInvariant = true;
5780 for (unsigned OtherOpIndex = 0; OtherOpIndex < I->getNumOperands();
5781 ++OtherOpIndex) {
5782 if (OtherOpIndex != OpIndex) {
5783 const SCEV *OtherOp = getSCEV(I->getOperand(OtherOpIndex));
5784 if (!isLoopInvariant(OtherOp, AddRec->getLoop())) {
5785 AllOtherOpsLoopInvariant = false;
5786 break;
5787 }
5788 }
5789 }
5790 if (AllOtherOpsLoopInvariant &&
5791 isGuaranteedToExecuteForEveryIteration(I, AddRec->getLoop()))
5792 return true;
5793 }
5794 }
5795 return false;
5796}
5797
5798bool ScalarEvolution::isAddRecNeverPoison(const Instruction *I, const Loop *L) {
5799 // If we know that \c I can never be poison period, then that's enough.
5800 if (isSCEVExprNeverPoison(I))
5801 return true;
5802
5803 // For an add recurrence specifically, we assume that infinite loops without
5804 // side effects are undefined behavior, and then reason as follows:
5805 //
5806 // If the add recurrence is poison in any iteration, it is poison on all
5807 // future iterations (since incrementing poison yields poison). If the result
5808 // of the add recurrence is fed into the loop latch condition and the loop
5809 // does not contain any throws or exiting blocks other than the latch, we now
5810 // have the ability to "choose" whether the backedge is taken or not (by
5811 // choosing a sufficiently evil value for the poison feeding into the branch)
5812 // for every iteration including and after the one in which \p I first became
5813 // poison. There are two possibilities (let's call the iteration in which \p
5814 // I first became poison as K):
5815 //
5816 // 1. In the set of iterations including and after K, the loop body executes
5817 // no side effects. In this case executing the backege an infinte number
5818 // of times will yield undefined behavior.
5819 //
5820 // 2. In the set of iterations including and after K, the loop body executes
5821 // at least one side effect. In this case, that specific instance of side
5822 // effect is control dependent on poison, which also yields undefined
5823 // behavior.
5824
5825 auto *ExitingBB = L->getExitingBlock();
5826 auto *LatchBB = L->getLoopLatch();
5827 if (!ExitingBB || !LatchBB || ExitingBB != LatchBB)
5828 return false;
5829
5830 SmallPtrSet<const Instruction *, 16> Pushed;
5831 SmallVector<const Instruction *, 8> PoisonStack;
5832
5833 // We start by assuming \c I, the post-inc add recurrence, is poison. Only
5834 // things that are known to be fully poison under that assumption go on the
5835 // PoisonStack.
5836 Pushed.insert(I);
5837 PoisonStack.push_back(I);
5838
5839 bool LatchControlDependentOnPoison = false;
5840 while (!PoisonStack.empty() && !LatchControlDependentOnPoison) {
5841 const Instruction *Poison = PoisonStack.pop_back_val();
5842
5843 for (auto *PoisonUser : Poison->users()) {
5844 if (propagatesFullPoison(cast<Instruction>(PoisonUser))) {
5845 if (Pushed.insert(cast<Instruction>(PoisonUser)).second)
5846 PoisonStack.push_back(cast<Instruction>(PoisonUser));
5847 } else if (auto *BI = dyn_cast<BranchInst>(PoisonUser)) {
5848 assert(BI->isConditional() && "Only possibility!")(static_cast <bool> (BI->isConditional() && "Only possibility!"
) ? void (0) : __assert_fail ("BI->isConditional() && \"Only possibility!\""
, "/build/llvm-toolchain-snapshot-6.0~svn320940/lib/Analysis/ScalarEvolution.cpp"
, 5848, __extension__ __PRETTY_FUNCTION__))
;
5849 if (BI->getParent() == LatchBB) {
5850 LatchControlDependentOnPoison = true;
5851 break;
5852 }
5853 }
5854 }
5855 }
5856
5857 return LatchControlDependentOnPoison && loopHasNoAbnormalExits(L);
5858}
5859
5860ScalarEvolution::LoopProperties
5861ScalarEvolution::getLoopProperties(const Loop *L) {
5862 using LoopProperties = ScalarEvolution::LoopProperties;
5863
5864 auto Itr = LoopPropertiesCache.find(L);
5865 if (Itr == LoopPropertiesCache.end()) {
5866 auto HasSideEffects = [](Instruction *I) {
5867 if (auto *SI = dyn_cast<StoreInst>(I))
5868 return !SI->isSimple();
5869
5870 return I->mayHaveSideEffects();
5871 };
5872
5873 LoopProperties LP = {/* HasNoAbnormalExits */ true,
5874 /*HasNoSideEffects*/ true};
5875
5876 for (auto *BB : L->getBlocks())
5877 for (auto &I : *BB) {
5878 if (!isGuaranteedToTransferExecutionToSuccessor(&I))
5879 LP.HasNoAbnormalExits = false;
5880 if (HasSideEffects(&I))
5881 LP.HasNoSideEffects = false;
5882 if (!LP.HasNoAbnormalExits && !LP.HasNoSideEffects)
5883 break; // We're already as pessimistic as we can get.
5884 }
5885
5886 auto InsertPair = LoopPropertiesCache.insert({L, LP});
5887 assert(InsertPair.second && "We just checked!")(static_cast <bool> (InsertPair.second && "We just checked!"
) ? void (0) : __assert_fail ("InsertPair.second && \"We just checked!\""
, "/build/llvm-toolchain-snapshot-6.0~svn320940/lib/Analysis/ScalarEvolution.cpp"
, 5887, __extension__ __PRETTY_FUNCTION__))
;
5888 Itr = InsertPair.first;
5889 }
5890
5891 return Itr->second;
5892}
5893
5894const SCEV *ScalarEvolution::createSCEV(Value *V) {
5895 if (!isSCEVable(V->getType()))
5896 return getUnknown(V);
5897
5898 if (Instruction *I = dyn_cast<Instruction>(V)) {
5899 // Don't attempt to analyze instructions in blocks that aren't
5900 // reachable. Such instructions don't matter, and they aren't required
5901 // to obey basic rules for definitions dominating uses which this
5902 // analysis depends on.
5903 if (!DT.isReachableFromEntry(I->getParent()))
5904 return getUnknown(V);
5905 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
5906 return getConstant(CI);
5907 else if (isa<ConstantPointerNull>(V))
5908 return getZero(V->getType());
5909 else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V))
5910 return GA->isInterposable() ? getUnknown(V) : getSCEV(GA->getAliasee());
5911 else if (!isa<ConstantExpr>(V))
5912 return getUnknown(V);
5913
5914 Operator *U = cast<Operator>(V);
5915 if (auto BO = MatchBinaryOp(U, DT)) {
5916 switch (BO->Opcode) {
5917 case Instruction::Add: {
5918 // The simple thing to do would be to just call getSCEV on both operands
5919 // and call getAddExpr with the result. However if we're looking at a
5920 // bunch of things all added together, this can be quite inefficient,
5921 // because it leads to N-1 getAddExpr calls for N ultimate operands.
5922 // Instead, gather up all the operands and make a single getAddExpr call.
5923 // LLVM IR canonical form means we need only traverse the left operands.
5924 SmallVector<const SCEV *, 4> AddOps;
5925 do {
5926 if (BO->Op) {
5927 if (auto *OpSCEV = getExistingSCEV(BO->Op)) {
5928 AddOps.push_back(OpSCEV);
5929 break;
5930 }
5931
5932 // If a NUW or NSW flag can be applied to the SCEV for this
5933 // addition, then compute the SCEV for this addition by itself
5934 // with a separate call to getAddExpr. We need to do that
5935 // instead of pushing the operands of the addition onto AddOps,
5936 // since the flags are only known to apply to this particular
5937 // addition - they may not apply to other additions that can be
5938 // formed with operands from AddOps.
5939 const SCEV *RHS = getSCEV(BO->RHS);
5940 SCEV::NoWrapFlags Flags = getNoWrapFlagsFromUB(BO->Op);
5941 if (Flags != SCEV::FlagAnyWrap) {
5942 const SCEV *LHS = getSCEV(BO->LHS);
5943 if (BO->Opcode == Instruction::Sub)
5944 AddOps.push_back(getMinusSCEV(LHS, RHS, Flags));
5945 else
5946 AddOps.push_back(getAddExpr(LHS, RHS, Flags));
5947 break;
5948 }
5949 }
5950
5951 if (BO->Opcode == Instruction::Sub)
5952 AddOps.push_back(getNegativeSCEV(getSCEV(BO->RHS)));
5953 else
5954 AddOps.push_back(getSCEV(BO->RHS));
5955
5956 auto NewBO = MatchBinaryOp(BO->LHS, DT);
5957 if (!NewBO || (NewBO->Opcode != Instruction::Add &&
5958 NewBO->Opcode != Instruction::Sub)) {
5959 AddOps.push_back(getSCEV(BO->LHS));
5960 break;
5961 }
5962 BO = NewBO;
5963 } while (true);
5964
5965 return getAddExpr(AddOps);
5966 }
5967
5968 case Instruction::Mul: {
5969 SmallVector<const SCEV *, 4> MulOps;
5970 do {
5971 if (BO->Op) {
5972 if (auto *OpSCEV = getExistingSCEV(BO->Op)) {
5973 MulOps.push_back(OpSCEV);
5974 break;
5975 }
5976
5977 SCEV::NoWrapFlags Flags = getNoWrapFlagsFromUB(BO->Op);
5978 if (Flags != SCEV::FlagAnyWrap) {
5979 MulOps.push_back(
5980 getMulExpr(getSCEV(BO->LHS), getSCEV(BO->RHS), Flags));
5981 break;
5982 }
5983 }
5984
5985 MulOps.push_back(getSCEV(BO->RHS));
5986 auto NewBO = MatchBinaryOp(BO->LHS, DT);
5987 if (!NewBO || NewBO->Opcode != Instruction::Mul) {
5988 MulOps.push_back(getSCEV(BO->LHS));
5989 break;
5990 }
5991 BO = NewBO;
5992 } while (true);
5993
5994 return getMulExpr(MulOps);
5995 }
5996 case Instruction::UDiv:
5997 return getUDivExpr(getSCEV(BO->LHS), getSCEV(BO->RHS));
5998 case Instruction::URem:
5999 return getURemExpr(getSCEV(BO->LHS), getSCEV(BO->RHS));
6000 case Instruction::Sub: {
6001 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap;
6002 if (BO->Op)
6003 Flags = getNoWrapFlagsFromUB(BO->Op);
6004 return getMinusSCEV(getSCEV(BO->LHS), getSCEV(BO->RHS), Flags);
6005 }
6006 case Instruction::And:
6007 // For an expression like x&255 that merely masks off the high bits,
6008 // use zext(trunc(x)) as the SCEV expression.
6009 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) {
6010 if (CI->isZero())
6011 return getSCEV(BO->RHS);
6012 if (CI->isMinusOne())
6013 return getSCEV(BO->LHS);
6014 const APInt &A = CI->getValue();
6015
6016 // Instcombine's ShrinkDemandedConstant may strip bits out of
6017 // constants, obscuring what would otherwise be a low-bits mask.
6018 // Use computeKnownBits to compute what ShrinkDemandedConstant
6019 // knew about to reconstruct a low-bits mask value.
6020 unsigned LZ = A.countLeadingZeros();
6021 unsigned TZ = A.countTrailingZeros();
6022 unsigned BitWidth = A.getBitWidth();
6023 KnownBits Known(BitWidth);
6024 computeKnownBits(BO->LHS, Known, getDataLayout(),
6025 0, &AC, nullptr, &DT);
6026
6027 APInt EffectiveMask =
6028 APInt::getLowBitsSet(BitWidth, BitWidth - LZ - TZ).shl(TZ);
6029 if ((LZ != 0 || TZ != 0) && !((~A & ~Known.Zero) & EffectiveMask)) {
6030 const SCEV *MulCount = getConstant(APInt::getOneBitSet(BitWidth, TZ));
6031 const SCEV *LHS = getSCEV(BO->LHS);
6032 const SCEV *ShiftedLHS = nullptr;
6033 if (auto *LHSMul = dyn_cast<SCEVMulExpr>(LHS)) {
6034 if (auto *OpC = dyn_cast<SCEVConstant>(LHSMul->getOperand(0))) {
6035 // For an expression like (x * 8) & 8, simplify the multiply.
6036 unsigned MulZeros = OpC->getAPInt().countTrailingZeros();
6037 unsigned GCD = std::min(MulZeros, TZ);
6038 APInt DivAmt = APInt::getOneBitSet(BitWidth, TZ - GCD);
6039 SmallVector<const SCEV*, 4> MulOps;
6040 MulOps.push_back(getConstant(OpC->getAPInt().lshr(GCD)));
6041 MulOps.append(LHSMul->op_begin() + 1, LHSMul->op_end());
6042 auto *NewMul = getMulExpr(MulOps, LHSMul->getNoWrapFlags());
6043 ShiftedLHS = getUDivExpr(NewMul, getConstant(DivAmt));
6044 }
6045 }
6046 if (!ShiftedLHS)
6047 ShiftedLHS = getUDivExpr(LHS, MulCount);
6048 return getMulExpr(
6049 getZeroExtendExpr(
6050 getTruncateExpr(ShiftedLHS,
6051 IntegerType::get(getContext(), BitWidth - LZ - TZ)),
6052 BO->LHS->getType()),
6053 MulCount);
6054 }
6055 }
6056 break;
6057
6058 case Instruction::Or:
6059 // If the RHS of the Or is a constant, we may have something like:
6060 // X*4+1 which got turned into X*4|1. Handle this as an Add so loop
6061 // optimizations will transparently handle this case.
6062 //
6063 // In order for this transformation to be safe, the LHS must be of the
6064 // form X*(2^n) and the Or constant must be less than 2^n.
6065 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) {
6066 const SCEV *LHS = getSCEV(BO->LHS);
6067 const APInt &CIVal = CI->getValue();
6068 if (GetMinTrailingZeros(LHS) >=
6069 (CIVal.getBitWidth() - CIVal.countLeadingZeros())) {
6070 // Build a plain add SCEV.
6071 const SCEV *S = getAddExpr(LHS, getSCEV(CI));
6072 // If the LHS of the add was an addrec and it has no-wrap flags,
6073 // transfer the no-wrap flags, since an or won't introduce a wrap.
6074 if (const SCEVAddRecExpr *NewAR = dyn_cast<SCEVAddRecExpr>(S)) {
6075 const SCEVAddRecExpr *OldAR = cast<SCEVAddRecExpr>(LHS);
6076 const_cast<SCEVAddRecExpr *>(NewAR)->setNoWrapFlags(
6077 OldAR->getNoWrapFlags());
6078 }
6079 return S;
6080 }
6081 }
6082 break;
6083
6084 case Instruction::Xor:
6085 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) {
6086 // If the RHS of xor is -1, then this is a not operation.
6087 if (CI->isMinusOne())
6088 return getNotSCEV(getSCEV(BO->LHS));
6089
6090 // Model xor(and(x, C), C) as and(~x, C), if C is a low-bits mask.
6091 // This is a variant of the check for xor with -1, and it handles
6092 // the case where instcombine has trimmed non-demanded bits out
6093 // of an xor with -1.
6094 if (auto *LBO = dyn_cast<BinaryOperator>(BO->LHS))
6095 if (ConstantInt *LCI = dyn_cast<ConstantInt>(LBO->getOperand(1)))
6096 if (LBO->getOpcode() == Instruction::And &&
6097 LCI->getValue() == CI->getValue())
6098 if (const SCEVZeroExtendExpr *Z =
6099 dyn_cast<SCEVZeroExtendExpr>(getSCEV(BO->LHS))) {
6100 Type *UTy = BO->LHS->getType();
6101 const SCEV *Z0 = Z->getOperand();
6102 Type *Z0Ty = Z0->getType();
6103 unsigned Z0TySize = getTypeSizeInBits(Z0Ty);
6104
6105 // If C is a low-bits mask, the zero extend is serving to
6106 // mask off the high bits. Complement the operand and
6107 // re-apply the zext.
6108 if (CI->getValue().isMask(Z0TySize))
6109 return getZeroExtendExpr(getNotSCEV(Z0), UTy);
6110
6111 // If C is a single bit, it may be in the sign-bit position
6112 // before the zero-extend. In this case, represent the xor
6113 // using an add, which is equivalent, and re-apply the zext.
6114 APInt Trunc = CI->getValue().trunc(Z0TySize);
6115 if (Trunc.zext(getTypeSizeInBits(UTy)) == CI->getValue() &&
6116 Trunc.isSignMask())
6117 return getZeroExtendExpr(getAddExpr(Z0, getConstant(Trunc)),
6118 UTy);
6119 }
6120 }
6121 break;
6122
6123 case Instruction::Shl:
6124 // Turn shift left of a constant amount into a multiply.
6125 if (ConstantInt *SA = dyn_cast<ConstantInt>(BO->RHS)) {
6126 uint32_t BitWidth = cast<IntegerType>(SA->getType())->getBitWidth();
6127
6128 // If the shift count is not less than the bitwidth, the result of
6129 // the shift is undefined. Don't try to analyze it, because the
6130 // resolution chosen here may differ from the resolution chosen in
6131 // other parts of the compiler.
6132 if (SA->getValue().uge(BitWidth))
6133 break;
6134
6135 // It is currently not resolved how to interpret NSW for left
6136 // shift by BitWidth - 1, so we avoid applying flags in that
6137 // case. Remove this check (or this comment) once the situation
6138 // is resolved. See
6139 // http://lists.llvm.org/pipermail/llvm-dev/2015-April/084195.html
6140 // and http://reviews.llvm.org/D8890 .
6141 auto Flags = SCEV::FlagAnyWrap;
6142 if (BO->Op && SA->getValue().ult(BitWidth - 1))
6143 Flags = getNoWrapFlagsFromUB(BO->Op);
6144
6145 Constant *X = ConstantInt::get(getContext(),
6146 APInt::getOneBitSet(BitWidth, SA->getZExtValue()));
6147 return getMulExpr(getSCEV(BO->LHS), getSCEV(X), Flags);
6148 }
6149 break;
6150
6151 case Instruction::AShr: {
6152 // AShr X, C, where C is a constant.
6153 ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS);
6154 if (!CI)
6155 break;
6156
6157 Type *OuterTy = BO->LHS->getType();
6158 uint64_t BitWidth = getTypeSizeInBits(OuterTy);
6159 // If the shift count is not less than the bitwidth, the result of
6160 // the shift is undefined. Don't try to analyze it, because the
6161 // resolution chosen here may differ from the resolution chosen in
6162 // other parts of the compiler.
6163 if (CI->getValue().uge(BitWidth))
6164 break;
6165
6166 if (CI->isZero())
6167 return getSCEV(BO->LHS); // shift by zero --> noop
6168
6169 uint64_t AShrAmt = CI->getZExtValue();
6170 Type *TruncTy = IntegerType::get(getContext(), BitWidth - AShrAmt);
6171
6172 Operator *L = dyn_cast<Operator>(BO->LHS);
6173 if (L && L->getOpcode() == Instruction::Shl) {
6174 // X = Shl A, n
6175 // Y = AShr X, m
6176 // Both n and m are constant.
6177
6178 const SCEV *ShlOp0SCEV = getSCEV(L->getOperand(0));
6179 if (L->getOperand(1) == BO->RHS)
6180 // For a two-shift sext-inreg, i.e. n = m,
6181 // use sext(trunc(x)) as the SCEV expression.
6182 return getSignExtendExpr(
6183 getTruncateExpr(ShlOp0SCEV, TruncTy), OuterTy);
6184
6185 ConstantInt *ShlAmtCI = dyn_cast<ConstantInt>(L->getOperand(1));
6186 if (ShlAmtCI && ShlAmtCI->getValue().ult(BitWidth)) {
6187 uint64_t ShlAmt = ShlAmtCI->getZExtValue();
6188 if (ShlAmt > AShrAmt) {
6189 // When n > m, use sext(mul(trunc(x), 2^(n-m)))) as the SCEV
6190 // expression. We already checked that ShlAmt < BitWidth, so
6191 // the multiplier, 1 << (ShlAmt - AShrAmt), fits into TruncTy as
6192 // ShlAmt - AShrAmt < Amt.
6193 APInt Mul = APInt::getOneBitSet(BitWidth - AShrAmt,
6194 ShlAmt - AShrAmt);
6195 return getSignExtendExpr(
6196 getMulExpr(getTruncateExpr(ShlOp0SCEV, TruncTy),
6197 getConstant(Mul)), OuterTy);
6198 }
6199 }
6200 }
6201 break;
6202 }
6203 }
6204 }
6205
6206 switch (U->getOpcode()) {
6207 case Instruction::Trunc:
6208 return getTruncateExpr(getSCEV(U->getOperand(0)), U->getType());
6209
6210 case Instruction::ZExt:
6211 return getZeroExtendExpr(getSCEV(U->getOperand(0)), U->getType());
6212
6213 case Instruction::SExt:
6214 if (auto BO = MatchBinaryOp(U->getOperand(0), DT)) {
6215 // The NSW flag of a subtract does not always survive the conversion to
6216 // A + (-1)*B. By pushing sign extension onto its operands we are much
6217 // more likely to preserve NSW and allow later AddRec optimisations.
6218 //
6219 // NOTE: This is effectively duplicating this logic from getSignExtend:
6220 // sext((A + B + ...)<nsw>) --> (sext(A) + sext(B) + ...)<nsw>
6221 // but by that point the NSW information has potentially been lost.
6222 if (BO->Opcode == Instruction::Sub && BO->IsNSW) {
6223 Type *Ty = U->getType();
6224 auto *V1 = getSignExtendExpr(getSCEV(BO->LHS), Ty);
6225 auto *V2 = getSignExtendExpr(getSCEV(BO->RHS), Ty);
6226 return getMinusSCEV(V1, V2, SCEV::FlagNSW);
6227 }
6228 }
6229 return getSignExtendExpr(getSCEV(U->getOperand(0)), U->getType());
6230
6231 case Instruction::BitCast:
6232 // BitCasts are no-op casts so we just eliminate the cast.
6233 if (isSCEVable(U->getType()) && isSCEVable(U->getOperand(0)->getType()))
6234 return getSCEV(U->getOperand(0));
6235 break;
6236
6237 // It's tempting to handle inttoptr and ptrtoint as no-ops, however this can
6238 // lead to pointer expressions which cannot safely be expanded to GEPs,
6239 // because ScalarEvolution doesn't respect the GEP aliasing rules when
6240 // simplifying integer expressions.
6241
6242 case Instruction::GetElementPtr:
6243 return createNodeForGEP(cast<GEPOperator>(U));
6244
6245 case Instruction::PHI:
6246 return createNodeForPHI(cast<PHINode>(U));
6247
6248 case Instruction::Select:
6249 // U can also be a select constant expr, which let fall through. Since
6250 // createNodeForSelect only works for a condition that is an `ICmpInst`, and
6251 // constant expressions cannot have instructions as operands, we'd have
6252 // returned getUnknown for a select constant expressions anyway.
6253 if (isa<Instruction>(U))
6254 return createNodeForSelectOrPHI(cast<Instruction>(U), U->getOperand(0),
6255 U->getOperand(1), U->getOperand(2));
6256 break;
6257
6258 case Instruction::Call:
6259 case Instruction::Invoke:
6260 if (Value *RV = CallSite(U).getReturnedArgOperand())
6261 return getSCEV(RV);
6262 break;
6263 }
6264
6265 return getUnknown(V);
6266}
6267
6268//===----------------------------------------------------------------------===//
6269// Iteration Count Computation Code
6270//
6271
6272static unsigned getConstantTripCount(const SCEVConstant *ExitCount) {
6273 if (!ExitCount)
6274 return 0;
6275
6276 ConstantInt *ExitConst = ExitCount->getValue();
6277
6278 // Guard against huge trip counts.
6279 if (ExitConst->getValue().getActiveBits() > 32)
6280 return 0;
6281
6282 // In case of integer overflow, this returns 0, which is correct.
6283 return ((unsigned)ExitConst->getZExtValue()) + 1;
6284}
6285
6286unsigned ScalarEvolution::getSmallConstantTripCount(const Loop *L) {
6287 if (BasicBlock *ExitingBB = L->getExitingBlock())
6288 return getSmallConstantTripCount(L, ExitingBB);
6289
6290 // No trip count information for multiple exits.
6291 return 0;
6292}
6293
6294unsigned ScalarEvolution::getSmallConstantTripCount(const Loop *L,
6295 BasicBlock *ExitingBlock) {
6296 assert(ExitingBlock && "Must pass a non-null exiting block!")(static_cast <bool> (ExitingBlock && "Must pass a non-null exiting block!"
) ? void (0) : __assert_fail ("ExitingBlock && \"Must pass a non-null exiting block!\""
, "/build/llvm-toolchain-snapshot-6.0~svn320940/lib/Analysis/ScalarEvolution.cpp"
, 6296, __extension__ __PRETTY_FUNCTION__))
;
6297 assert(L->isLoopExiting(ExitingBlock) &&(static_cast <bool> (L->isLoopExiting(ExitingBlock) &&
"Exiting block must actually branch out of the loop!") ? void
(0) : __assert_fail ("L->isLoopExiting(ExitingBlock) && \"Exiting block must actually branch out of the loop!\""
, "/build/llvm-toolchain-snapshot-6.0~svn320940/lib/Analysis/ScalarEvolution.cpp"
, 6298, __extension__ __PRETTY_FUNCTION__))
6298 "Exiting block must actually branch out of the loop!")(static_cast <bool> (L->isLoopExiting(ExitingBlock) &&
"Exiting block must actually branch out of the loop!") ? void
(0) : __assert_fail ("L->isLoopExiting(ExitingBlock) && \"Exiting block must actually branch out of the loop!\""
, "/build/llvm-toolchain-snapshot-6.0~svn320940/lib/Analysis/ScalarEvolution.cpp"
, 6298, __extension__ __PRETTY_FUNCTION__))
;
6299 const SCEVConstant *ExitCount =
6300 dyn_cast<SCEVConstant>(getExitCount(L, ExitingBlock));
6301 return getConstantTripCount(ExitCount);
6302}
6303
6304unsigned ScalarEvolution::getSmallConstantMaxTripCount(const Loop *L) {
6305 const auto *MaxExitCount =
6306 dyn_cast<SCEVConstant>(getMaxBackedgeTakenCount(L));
6307 return getConstantTripCount(MaxExitCount);
6308}
6309
6310unsigned ScalarEvolution::getSmallConstantTripMultiple(const Loop *L) {
6311 if (BasicBlock *ExitingBB = L->getExitingBlock())
6312 return getSmallConstantTripMultiple(L, ExitingBB);
6313
6314 // No trip multiple information for multiple exits.
6315 return 0;
6316}
6317
6318/// Returns the largest constant divisor of the trip count of this loop as a
6319/// normal unsigned value, if possible. This means that the actual trip count is
6320/// always a multiple of the returned value (don't forget the trip count could
6321/// very well be zero as well!).
6322///
6323/// Returns 1 if the trip count is unknown or not guaranteed to be the
6324/// multiple of a constant (which is also the case if the trip count is simply
6325/// constant, use getSmallConstantTripCount for that case), Will also return 1
6326/// if the trip count is very large (>= 2^32).
6327///
6328/// As explained in the comments for getSmallConstantTripCount, this assumes
6329/// that control exits the loop via ExitingBlock.
6330unsigned
6331ScalarEvolution::getSmallConstantTripMultiple(const Loop *L,
6332 BasicBlock *ExitingBlock) {
6333 assert(ExitingBlock && "Must pass a non-null exiting block!")(static_cast <bool> (ExitingBlock && "Must pass a non-null exiting block!"
) ? void (0) : __assert_fail ("ExitingBlock && \"Must pass a non-null exiting block!\""
, "/build/llvm-toolchain-snapshot-6.0~svn320940/lib/Analysis/ScalarEvolution.cpp"
, 6333, __extension__ __PRETTY_FUNCTION__))
;
6334 assert(L->isLoopExiting(ExitingBlock) &&(static_cast <bool> (L->isLoopExiting(ExitingBlock) &&
"Exiting block must actually branch out of the loop!") ? void
(0) : __assert_fail ("L->isLoopExiting(ExitingBlock) && \"Exiting block must actually branch out of the loop!\""
, "/build/llvm-toolchain-snapshot-6.0~svn320940/lib/Analysis/ScalarEvolution.cpp"
, 6335, __extension__ __PRETTY_FUNCTION__))
6335 "Exiting block must actually branch out of the loop!")(static_cast <bool> (L->isLoopExiting(ExitingBlock) &&
"Exiting block must actually branch out of the loop!") ? void
(0) : __assert_fail ("L->isLoopExiting(ExitingBlock) && \"Exiting block must actually branch out of the loop!\""
, "/build/llvm-toolchain-snapshot-6.0~svn320940/lib/Analysis/ScalarEvolution.cpp"
, 6335, __extension__ __PRETTY_FUNCTION__))
;
6336 const SCEV *ExitCount = getExitCount(L, ExitingBlock);
6337 if (ExitCount == getCouldNotCompute())
6338 return 1;
6339
6340 // Get the trip count from the BE count by adding 1.
6341 const SCEV *TCExpr = getAddExpr(ExitCount, getOne(ExitCount->getType()));
6342
6343 const SCEVConstant *TC = dyn_cast<SCEVConstant>(TCExpr);
6344 if (!TC)
6345 // Attempt to factor more general cases. Returns the greatest power of
6346 // two divisor. If overflow happens, the trip count expression is still
6347 // divisible by the greatest power of 2 divisor returned.
6348 return 1U << std::min((uint32_t)31, GetMinTrailingZeros(TCExpr));
6349
6350 ConstantInt *Result = TC->getValue();
6351
6352 // Guard against huge trip counts (this requires checking
6353 // for zero to handle the case where the trip count == -1 and the
6354 // addition wraps).
6355 if (!Result || Result->getValue().getActiveBits() > 32 ||
6356 Result->getValue().getActiveBits() == 0)
6357 return 1;
6358
6359 return (unsigned)Result->getZExtValue();
6360}
6361
6362/// Get the expression for the number of loop iterations for which this loop is
6363/// guaranteed not to exit via ExitingBlock. Otherwise return
6364/// SCEVCouldNotCompute.
6365const SCEV *ScalarEvolution::getExitCount(const Loop *L,
6366 BasicBlock *ExitingBlock) {
6367 return getBackedgeTakenInfo(L).getExact(ExitingBlock, this);
6368}
6369
6370const SCEV *
6371ScalarEvolution::getPredicatedBackedgeTakenCount(const Loop *L,
6372 SCEVUnionPredicate &Preds) {
6373 return getPredicatedBackedgeTakenInfo(L).getExact(this, &Preds);
6374}
6375
6376const SCEV *ScalarEvolution::getBackedgeTakenCount(const Loop *L) {
6377 return getBackedgeTakenInfo(L).getExact(this);
6378}
6379
6380/// Similar to getBackedgeTakenCount, except return the least SCEV value that is
6381/// known never to be less than the actual backedge taken count.
6382const SCEV *ScalarEvolution::getMaxBackedgeTakenCount(const Loop *L) {
6383 return getBackedgeTakenInfo(L).getMax(this);
6384}
6385
6386bool ScalarEvolution::isBackedgeTakenCountMaxOrZero(const Loop *L) {
6387 return getBackedgeTakenInfo(L).isMaxOrZero(this);
6388}
6389
6390/// Push PHI nodes in the header of the given loop onto the given Worklist.
6391static void
6392PushLoopPHIs(const Loop *L, SmallVectorImpl<Instruction *> &Worklist) {
6393 BasicBlock *Header = L->getHeader();
6394
6395 // Push all Loop-header PHIs onto the Worklist stack.
6396 for (BasicBlock::iterator I = Header->begin();
6397 PHINode *PN = dyn_cast<PHINode>(I); ++I)
6398 Worklist.push_back(PN);
6399}
6400
6401const ScalarEvolution::BackedgeTakenInfo &
6402ScalarEvolution::getPredicatedBackedgeTakenInfo(const Loop *L) {
6403 auto &BTI = getBackedgeTakenInfo(L);
6404 if (BTI.hasFullInfo())
6405 return BTI;
6406
6407 auto Pair = PredicatedBackedgeTakenCounts.insert({L, BackedgeTakenInfo()});
6408
6409 if (!Pair.second)
6410 return Pair.first->second;
6411
6412 BackedgeTakenInfo Result =
6413 computeBackedgeTakenCount(L, /*AllowPredicates=*/true);
6414
6415 return PredicatedBackedgeTakenCounts.find(L)->second = std::move(Result);
6416}
6417
6418const ScalarEvolution::BackedgeTakenInfo &
6419ScalarEvolution::getBackedgeTakenInfo(const Loop *L) {
6420 // Initially insert an invalid entry for this loop. If the insertion
6421 // succeeds, proceed to actually compute a backedge-taken count and
6422 // update the value. The temporary CouldNotCompute value tells SCEV
6423 // code elsewhere that it shouldn't attempt to request a new
6424 // backedge-taken count, which could result in infinite recursion.
6425 std::pair<DenseMap<const Loop *, BackedgeTakenInfo>::iterator, bool> Pair =
6426 BackedgeTakenCounts.insert({L, BackedgeTakenInfo()});
6427 if (!Pair.second)
6428 return Pair.first->second;
6429
6430 // computeBackedgeTakenCount may allocate memory for its result. Inserting it
6431 // into the BackedgeTakenCounts map transfers ownership. Otherwise, the result
6432 // must be cleared in this scope.
6433 BackedgeTakenInfo Result = computeBackedgeTakenCount(L);
6434
6435 if (Result.getExact(this) != getCouldNotCompute()) {
6436 assert(isLoopInvariant(Result.getExact(this), L) &&(static_cast <bool> (isLoopInvariant(Result.getExact(this
), L) && isLoopInvariant(Result.getMax(this), L) &&
"Computed backedge-taken count isn't loop invariant for loop!"
) ? void (0) : __assert_fail ("isLoopInvariant(Result.getExact(this), L) && isLoopInvariant(Result.getMax(this), L) && \"Computed backedge-taken count isn't loop invariant for loop!\""
, "/build/llvm-toolchain-snapshot-6.0~svn320940/lib/Analysis/ScalarEvolution.cpp"
, 6438, __extension__ __PRETTY_FUNCTION__))
6437 isLoopInvariant(Result.getMax(this), L) &&(static_cast <bool> (isLoopInvariant(Result.getExact(this
), L) && isLoopInvariant(Result.getMax(this), L) &&
"Computed backedge-taken count isn't loop invariant for loop!"
) ? void (0) : __assert_fail ("isLoopInvariant(Result.getExact(this), L) && isLoopInvariant(Result.getMax(this), L) && \"Computed backedge-taken count isn't loop invariant for loop!\""
, "/build/llvm-toolchain-snapshot-6.0~svn320940/lib/Analysis/ScalarEvolution.cpp"
, 6438, __extension__ __PRETTY_FUNCTION__))
6438 "Computed backedge-taken count isn't loop invariant for loop!")(static_cast <bool> (isLoopInvariant(Result.getExact(this
), L) && isLoopInvariant(Result.getMax(this), L) &&
"Computed backedge-taken count isn't loop invariant for loop!"
) ? void (0) : __assert_fail ("isLoopInvariant(Result.getExact(this), L) && isLoopInvariant(Result.getMax(this), L) && \"Computed backedge-taken count isn't loop invariant for loop!\""
, "/build/llvm-toolchain-snapshot-6.0~svn320940/lib/Analysis/ScalarEvolution.cpp"
, 6438, __extension__ __PRETTY_FUNCTION__))
;
6439 ++NumTripCountsComputed;
6440 }
6441 else if (Result.getMax(this) == getCouldNotCompute() &&
6442 isa<PHINode>(L->getHeader()->begin())) {
6443 // Only count loops that have phi nodes as not being computable.
6444 ++NumTripCountsNotComputed;
6445 }
6446
6447 // Now that we know more about the trip count for this loop, forget any
6448 // existing SCEV values for PHI nodes in this loop since they are only
6449 // conservative estimates made without the benefit of trip count
6450 // information. This is similar to the code in forgetLoop, except that
6451 // it handles SCEVUnknown PHI nodes specially.
6452 if (Result.hasAnyInfo()) {
6453 SmallVector<Instruction *, 16> Worklist;
6454 PushLoopPHIs(L, Worklist);
6455
6456 SmallPtrSet<Instruction *, 8> Discovered;
6457 while (!Worklist.empty()) {
6458 Instruction *I = Worklist.pop_back_val();
6459
6460 ValueExprMapType::iterator It =
6461 ValueExprMap.find_as(static_cast<Value *>(I));
6462 if (It != ValueExprMap.end()) {
6463 const SCEV *Old = It->second;
6464
6465 // SCEVUnknown for a PHI either means that it has an unrecognized
6466 // structure, or it's a PHI that's in the progress of being computed
6467 // by createNodeForPHI. In the former case, additional loop trip
6468 // count information isn't going to change anything. In the later
6469 // case, createNodeForPHI will perform the necessary updates on its
6470 // own when it gets to that point.
6471 if (!isa<PHINode>(I) || !isa<SCEVUnknown>(Old)) {
6472 eraseValueFromMap(It->first);
6473 forgetMemoizedResults(Old);
6474 }
6475 if (PHINode *PN = dyn_cast<PHINode>(I))
6476 ConstantEvolutionLoopExitValue.erase(PN);
6477 }
6478
6479 // Since we don't need to invalidate anything for correctness and we're
6480 // only invalidating to make SCEV's results more precise, we get to stop
6481 // early to avoid invalidating too much. This is especially important in
6482 // cases like:
6483 //
6484 // %v = f(pn0, pn1) // pn0 and pn1 used through some other phi node
6485 // loop0:
6486 // %pn0 = phi
6487 // ...
6488 // loop1:
6489 // %pn1 = phi
6490 // ...
6491 //
6492 // where both loop0 and loop1's backedge taken count uses the SCEV
6493 // expression for %v. If we don't have the early stop below then in cases
6494 // like the above, getBackedgeTakenInfo(loop1) will clear out the trip
6495 // count for loop0 and getBackedgeTakenInfo(loop0) will clear out the trip
6496 // count for loop1, effectively nullifying SCEV's trip count cache.
6497 for (auto *U : I->users())
6498 if (auto *I = dyn_cast<Instruction>(U)) {
6499 auto *LoopForUser = LI.getLoopFor(I->getParent());
6500 if (LoopForUser && L->contains(LoopForUser) &&
6501 Discovered.insert(I).second)
6502 Worklist.push_back(I);
6503 }
6504 }
6505 }
6506
6507 // Re-lookup the insert position, since the call to
6508 // computeBackedgeTakenCount above could result in a
6509 // recusive call to getBackedgeTakenInfo (on a different
6510 // loop), which would invalidate the iterator computed
6511 // earlier.
6512 return BackedgeTakenCounts.find(L)->second = std::move(Result);
6513}
6514
6515void ScalarEvolution::forgetLoop(const Loop *L) {
6516 // Drop any stored trip count value.
6517 auto RemoveLoopFromBackedgeMap =
6518 [](DenseMap<const Loop *, BackedgeTakenInfo> &Map, const Loop *L) {
6519 auto BTCPos = Map.find(L);
6520 if (BTCPos != Map.end()) {
6521 BTCPos->second.clear();
6522 Map.erase(BTCPos);
6523 }
6524 };
6525
6526 SmallVector<const Loop *, 16> LoopWorklist(1, L);
6527 SmallVector<Instruction *, 32> Worklist;
6528 SmallPtrSet<Instruction *, 16> Visited;
6529
6530 // Iterate over all the loops and sub-loops to drop SCEV information.
6531 while (!LoopWorklist.empty()) {
6532 auto *CurrL = LoopWorklist.pop_back_val();
6533
6534 RemoveLoopFromBackedgeMap(BackedgeTakenCounts, CurrL);
6535 RemoveLoopFromBackedgeMap(PredicatedBackedgeTakenCounts, CurrL);
6536
6537 // Drop information about predicated SCEV rewrites for this loop.
6538 for (auto I = PredicatedSCEVRewrites.begin();
6539 I != PredicatedSCEVRewrites.end();) {
6540 std::pair<const SCEV *, const Loop *> Entry = I->first;
6541 if (Entry.second == CurrL)
6542 PredicatedSCEVRewrites.erase(I++);
6543 else
6544 ++I;
6545 }
6546
6547 auto LoopUsersItr = LoopUsers.find(CurrL);
6548 if (LoopUsersItr != LoopUsers.end()) {
6549 for (auto *S : LoopUsersItr->second)
6550 forgetMemoizedResults(S);
6551 LoopUsers.erase(LoopUsersItr);
6552 }
6553
6554 // Drop information about expressions based on loop-header PHIs.
6555 PushLoopPHIs(CurrL, Worklist);
6556
6557 while (!Worklist.empty()) {
6558 Instruction *I = Worklist.pop_back_val();
6559 if (!Visited.insert(I).second)
6560 continue;
6561
6562 ValueExprMapType::iterator It =
6563 ValueExprMap.find_as(static_cast<Value *>(I));
6564 if (It != ValueExprMap.end()) {
6565 eraseValueFromMap(It->first);
6566 forgetMemoizedResults(It->second);
6567 if (PHINode *PN = dyn_cast<PHINode>(I))
6568 ConstantEvolutionLoopExitValue.erase(PN);
6569 }
6570
6571 PushDefUseChildren(I, Worklist);
6572 }
6573
6574 LoopPropertiesCache.erase(CurrL);
6575 // Forget all contained loops too, to avoid dangling entries in the
6576 // ValuesAtScopes map.
6577 LoopWorklist.append(CurrL->begin(), CurrL->end());
6578 }
6579}
6580
6581void ScalarEvolution::forgetValue(Value *V) {
6582 Instruction *I = dyn_cast<Instruction>(V);
6583 if (!I) return;
6584
6585 // Drop information about expressions based on loop-header PHIs.
6586 SmallVector<Instruction *, 16> Worklist;
6587 Worklist.push_back(I);
6588
6589 SmallPtrSet<Instruction *, 8> Visited;
6590 while (!Worklist.empty()) {
6591 I = Worklist.pop_back_val();
6592 if (!Visited.insert(I).second)
6593 continue;
6594
6595 ValueExprMapType::iterator It =
6596 ValueExprMap.find_as(static_cast<Value *>(I));
6597 if (It != ValueExprMap.end()) {
6598 eraseValueFromMap(It->first);
6599 forgetMemoizedResults(It->second);
6600 if (PHINode *PN = dyn_cast<PHINode>(I))
6601 ConstantEvolutionLoopExitValue.erase(PN);
6602 }
6603
6604 PushDefUseChildren(I, Worklist);
6605 }
6606}
6607
6608/// Get the exact loop backedge taken count considering all loop exits. A
6609/// computable result can only be returned for loops with a single exit.
6610/// Returning the minimum taken count among all exits is incorrect because one
6611/// of the loop's exit limit's may have been skipped. howFarToZero assumes that
6612/// the limit of each loop test is never skipped. This is a valid assumption as
6613/// long as the loop exits via that test. For precise results, it is the
6614/// caller's responsibility to specify the relevant loop exit using
6615/// getExact(ExitingBlock, SE).
6616const SCEV *
6617ScalarEvolution::BackedgeTakenInfo::getExact(ScalarEvolution *SE,
6618 SCEVUnionPredicate *Preds) const {
6619 // If any exits were not computable, the loop is not computable.
6620 if (!isComplete() || ExitNotTaken.empty())
6621 return SE->getCouldNotCompute();
6622
6623 const SCEV *BECount = nullptr;
6624 for (auto &ENT : ExitNotTaken) {
6625 assert(ENT.ExactNotTaken != SE->getCouldNotCompute() && "bad exit SCEV")(static_cast <bool> (ENT.ExactNotTaken != SE->getCouldNotCompute
() && "bad exit SCEV") ? void (0) : __assert_fail ("ENT.ExactNotTaken != SE->getCouldNotCompute() && \"bad exit SCEV\""
, "/build/llvm-toolchain-snapshot-6.0~svn320940/lib/Analysis/ScalarEvolution.cpp"
, 6625, __extension__ __PRETTY_FUNCTION__))
;
6626
6627 if (!BECount)
6628 BECount = ENT.ExactNotTaken;
6629 else if (BECount != ENT.ExactNotTaken)
6630 return SE->getCouldNotCompute();
6631 if (Preds && !ENT.hasAlwaysTruePredicate())
6632 Preds->add(ENT.Predicate.get());
6633
6634 assert((Preds || ENT.hasAlwaysTruePredicate()) &&(static_cast <bool> ((Preds || ENT.hasAlwaysTruePredicate
()) && "Predicate should be always true!") ? void (0)
: __assert_fail ("(Preds || ENT.hasAlwaysTruePredicate()) && \"Predicate should be always true!\""
, "/build/llvm-toolchain-snapshot-6.0~svn320940/lib/Analysis/ScalarEvolution.cpp"
, 6635, __extension__ __PRETTY_FUNCTION__))
6635 "Predicate should be always true!")(static_cast <bool> ((Preds || ENT.hasAlwaysTruePredicate
()) && "Predicate should be always true!") ? void (0)
: __assert_fail ("(Preds || ENT.hasAlwaysTruePredicate()) && \"Predicate should be always true!\""
, "/build/llvm-toolchain-snapshot-6.0~svn320940/lib/Analysis/ScalarEvolution.cpp"
, 6635, __extension__ __PRETTY_FUNCTION__))
;
6636 }
6637
6638 assert(BECount && "Invalid not taken count for loop exit")(static_cast <bool> (BECount && "Invalid not taken count for loop exit"
) ? void (0) : __assert_fail ("BECount && \"Invalid not taken count for loop exit\""
, "/build/llvm-toolchain-snapshot-6.0~svn320940/lib/Analysis/ScalarEvolution.cpp"
, 6638, __extension__ __PRETTY_FUNCTION__))
;
6639 return BECount;
6640}
6641
6642/// Get the exact not taken count for this loop exit.
6643const SCEV *
6644ScalarEvolution::BackedgeTakenInfo::getExact(BasicBlock *ExitingBlock,
6645 ScalarEvolution *SE) const {
6646 for (auto &ENT : ExitNotTaken)
6647 if (ENT.ExitingBlock == ExitingBlock && ENT.hasAlwaysTruePredicate())
6648 return ENT.ExactNotTaken;
6649
6650 return SE->getCouldNotCompute();
6651}
6652
6653/// getMax - Get the max backedge taken count for the loop.
6654const SCEV *
6655ScalarEvolution::BackedgeTakenInfo::getMax(ScalarEvolution *SE) const {
6656 auto PredicateNotAlwaysTrue = [](const ExitNotTakenInfo &ENT) {
6657 return !ENT.hasAlwaysTruePredicate();
6658 };
6659
6660 if (any_of(ExitNotTaken, PredicateNotAlwaysTrue) || !getMax())
6661 return SE->getCouldNotCompute();
6662
6663 assert((isa<SCEVCouldNotCompute>(getMax()) || isa<SCEVConstant>(getMax())) &&(static_cast <bool> ((isa<SCEVCouldNotCompute>(getMax
()) || isa<SCEVConstant>(getMax())) && "No point in having a non-constant max backedge taken count!"
) ? void (0) : __assert_fail ("(isa<SCEVCouldNotCompute>(getMax()) || isa<SCEVConstant>(getMax())) && \"No point in having a non-constant max backedge taken count!\""
, "/build/llvm-toolchain-snapshot-6.0~svn320940/lib/Analysis/ScalarEvolution.cpp"
, 6664, __extension__ __PRETTY_FUNCTION__))
6664 "No point in having a non-constant max backedge taken count!")(static_cast <bool> ((isa<SCEVCouldNotCompute>(getMax
()) || isa<SCEVConstant>(getMax())) && "No point in having a non-constant max backedge taken count!"
) ? void (0) : __assert_fail ("(isa<SCEVCouldNotCompute>(getMax()) || isa<SCEVConstant>(getMax())) && \"No point in having a non-constant max backedge taken count!\""
, "/build/llvm-toolchain-snapshot-6.0~svn320940/lib/Analysis/ScalarEvolution.cpp"
, 6664, __extension__ __PRETTY_FUNCTION__))
;
6665 return getMax();
6666}
6667
6668bool ScalarEvolution::BackedgeTakenInfo::isMaxOrZero(ScalarEvolution *SE) const {
6669 auto PredicateNotAlwaysTrue = [](const ExitNotTakenInfo &ENT) {
6670 return !ENT.hasAlwaysTruePredicate();
6671 };
6672 return MaxOrZero && !any_of(ExitNotTaken, PredicateNotAlwaysTrue);
6673}
6674
6675bool ScalarEvolution::BackedgeTakenInfo::hasOperand(const SCEV *S,
6676 ScalarEvolution *SE) const {
6677 if (getMax() && getMax() != SE->getCouldNotCompute() &&
6678 SE->hasOperand(getMax(), S))
6679 return true;
6680
6681 for (auto &ENT : ExitNotTaken)
6682 if (ENT.ExactNotTaken != SE->getCouldNotCompute() &&
6683 SE->hasOperand(ENT.ExactNotTaken, S))
6684 return true;
6685
6686 return false;
6687}
6688
6689ScalarEvolution::ExitLimit::ExitLimit(const SCEV *E)
6690 : ExactNotTaken(E), MaxNotTaken(E) {
6691 assert((isa<SCEVCouldNotCompute>(MaxNotTaken) ||(static_cast <bool> ((isa<SCEVCouldNotCompute>(MaxNotTaken
) || isa<SCEVConstant>(MaxNotTaken)) && "No point in having a non-constant max backedge taken count!"
) ? void (0) : __assert_fail ("(isa<SCEVCouldNotCompute>(MaxNotTaken) || isa<SCEVConstant>(MaxNotTaken)) && \"No point in having a non-constant max backedge taken count!\""
, "/build/llvm-toolchain-snapshot-6.0~svn320940/lib/Analysis/ScalarEvolution.cpp"
, 6693, __extension__ __PRETTY_FUNCTION__))
6692 isa<SCEVConstant>(MaxNotTaken)) &&(static_cast <bool> ((isa<SCEVCouldNotCompute>(MaxNotTaken
) || isa<SCEVConstant>(MaxNotTaken)) && "No point in having a non-constant max backedge taken count!"
) ? void (0) : __assert_fail ("(isa<SCEVCouldNotCompute>(MaxNotTaken) || isa<SCEVConstant>(MaxNotTaken)) && \"No point in having a non-constant max backedge taken count!\""
, "/build/llvm-toolchain-snapshot-6.0~svn320940/lib/Analysis/ScalarEvolution.cpp"
, 6693, __extension__ __PRETTY_FUNCTION__))
6693 "No point in having a non-constant max backedge taken count!")(static_cast <bool> ((isa<SCEVCouldNotCompute>(MaxNotTaken
) || isa<SCEVConstant>(MaxNotTaken)) && "No point in having a non-constant max backedge taken count!"
) ? void (0) : __assert_fail ("(isa<SCEVCouldNotCompute>(MaxNotTaken) || isa<SCEVConstant>(MaxNotTaken)) && \"No point in having a non-constant max backedge taken count!\""
, "/build/llvm-toolchain-snapshot-6.0~svn320940/lib/Analysis/ScalarEvolution.cpp"
, 6693, __extension__ __PRETTY_FUNCTION__))
;
6694}
6695
6696ScalarEvolution::ExitLimit::ExitLimit(
6697 const SCEV *E, const SCEV *M, bool MaxOrZero,
6698 ArrayRef<const SmallPtrSetImpl<const SCEVPredicate *> *> PredSetList)
6699 : ExactNotTaken(E), MaxNotTaken(M), MaxOrZero(MaxOrZero) {
6700 assert((isa<SCEVCouldNotCompute>(ExactNotTaken) ||(static_cast <bool> ((isa<SCEVCouldNotCompute>(ExactNotTaken
) || !isa<SCEVCouldNotCompute>(MaxNotTaken)) &&
"Exact is not allowed to be less precise than Max") ? void (
0) : __assert_fail ("(isa<SCEVCouldNotCompute>(ExactNotTaken) || !isa<SCEVCouldNotCompute>(MaxNotTaken)) && \"Exact is not allowed to be less precise than Max\""
, "/build/llvm-toolchain-snapshot-6.0~svn320940/lib/Analysis/ScalarEvolution.cpp"
, 6702, __extension__ __PRETTY_FUNCTION__))
6701 !isa<SCEVCouldNotCompute>(MaxNotTaken)) &&(static_cast <bool> ((isa<SCEVCouldNotCompute>(ExactNotTaken
) || !isa<SCEVCouldNotCompute>(MaxNotTaken)) &&
"Exact is not allowed to be less precise than Max") ? void (
0) : __assert_fail ("(isa<SCEVCouldNotCompute>(ExactNotTaken) || !isa<SCEVCouldNotCompute>(MaxNotTaken)) && \"Exact is not allowed to be less precise than Max\""
, "/build/llvm-toolchain-snapshot-6.0~svn320940/lib/Analysis/ScalarEvolution.cpp"
, 6702, __extension__ __PRETTY_FUNCTION__))
6702 "Exact is not allowed to be less precise than Max")(static_cast <bool> ((isa<SCEVCouldNotCompute>(ExactNotTaken
) || !isa<SCEVCouldNotCompute>(MaxNotTaken)) &&
"Exact is not allowed to be less precise than Max") ? void (
0) : __assert_fail ("(isa<SCEVCouldNotCompute>(ExactNotTaken) || !isa<SCEVCouldNotCompute>(MaxNotTaken)) && \"Exact is not allowed to be less precise than Max\""
, "/build/llvm-toolchain-snapshot-6.0~svn320940/lib/Analysis/ScalarEvolution.cpp"
, 6702, __extension__ __PRETTY_FUNCTION__))
;
6703 assert((isa<SCEVCouldNotCompute>(MaxNotTaken) ||(static_cast <bool> ((isa<SCEVCouldNotCompute>(MaxNotTaken
) || isa<SCEVConstant>(MaxNotTaken)) && "No point in having a non-constant max backedge taken count!"
) ? void (0) : __assert_fail ("(isa<SCEVCouldNotCompute>(MaxNotTaken) || isa<SCEVConstant>(MaxNotTaken)) && \"No point in having a non-constant max backedge taken count!\""
, "/build/llvm-toolchain-snapshot-6.0~svn320940/lib/Analysis/ScalarEvolution.cpp"
, 6705, __extension__ __PRETTY_FUNCTION__))
6704 isa<SCEVConstant>(MaxNotTaken)) &&(static_cast <bool> ((isa<SCEVCouldNotCompute>(MaxNotTaken
) || isa<SCEVConstant>(MaxNotTaken)) && "No point in having a non-constant max backedge taken count!"
) ? void (0) : __assert_fail ("(isa<SCEVCouldNotCompute>(MaxNotTaken) || isa<SCEVConstant>(MaxNotTaken)) && \"No point in having a non-constant max backedge taken count!\""
, "/build/llvm-toolchain-snapshot-6.0~svn320940/lib/Analysis/ScalarEvolution.cpp"
, 6705, __extension__ __PRETTY_FUNCTION__))
6705 "No point in having a non-constant max backedge taken count!")(static_cast <bool> ((isa<SCEVCouldNotCompute>(MaxNotTaken
) || isa<SCEVConstant>(MaxNotTaken)) && "No point in having a non-constant max backedge taken count!"
) ? void (0) : __assert_fail ("(isa<SCEVCouldNotCompute>(MaxNotTaken) || isa<SCEVConstant>(MaxNotTaken)) && \"No point in having a non-constant max backedge taken count!\""
, "/build/llvm-toolchain-snapshot-6.0~svn320940/lib/Analysis/ScalarEvolution.cpp"
, 6705, __extension__ __PRETTY_FUNCTION__))
;
6706 for (auto *PredSet : PredSetList)
6707 for (auto *P : *PredSet)
6708 addPredicate(P);
6709}
6710
6711ScalarEvolution::ExitLimit::ExitLimit(
6712 const SCEV *E, const SCEV *M, bool MaxOrZero,
6713 const SmallPtrSetImpl<const SCEVPredicate *> &PredSet)
6714 : ExitLimit(E, M, MaxOrZero, {&PredSet}) {
6715 assert((isa<SCEVCouldNotCompute>(MaxNotTaken) ||(static_cast <bool> ((isa<SCEVCouldNotCompute>(MaxNotTaken
) || isa<SCEVConstant>(MaxNotTaken)) && "No point in having a non-constant max backedge taken count!"
) ? void (0) : __assert_fail ("(isa<SCEVCouldNotCompute>(MaxNotTaken) || isa<SCEVConstant>(MaxNotTaken)) && \"No point in having a non-constant max backedge taken count!\""
, "/build/llvm-toolchain-snapshot-6.0~svn320940/lib/Analysis/ScalarEvolution.cpp"
, 6717, __extension__ __PRETTY_FUNCTION__))
6716 isa<SCEVConstant>(MaxNotTaken)) &&(static_cast <bool> ((isa<SCEVCouldNotCompute>(MaxNotTaken
) || isa<SCEVConstant>(MaxNotTaken)) && "No point in having a non-constant max backedge taken count!"
) ? void (0) : __assert_fail ("(isa<SCEVCouldNotCompute>(MaxNotTaken) || isa<SCEVConstant>(MaxNotTaken)) && \"No point in having a non-constant max backedge taken count!\""
, "/build/llvm-toolchain-snapshot-6.0~svn320940/lib/Analysis/ScalarEvolution.cpp"
, 6717, __extension__ __PRETTY_FUNCTION__))
6717 "No point in having a non-constant max backedge taken count!")(static_cast <bool> ((isa<SCEVCouldNotCompute>(MaxNotTaken
) || isa<SCEVConstant>(MaxNotTaken)) && "No point in having a non-constant max backedge taken count!"
) ? void (0) : __assert_fail ("(isa<SCEVCouldNotCompute>(MaxNotTaken) || isa<SCEVConstant>(MaxNotTaken)) && \"No point in having a non-constant max backedge taken count!\""
, "/build/llvm-toolchain-snapshot-6.0~svn320940/lib/Analysis/ScalarEvolution.cpp"
, 6717, __extension__ __PRETTY_FUNCTION__))
;
6718}
6719
6720ScalarEvolution::ExitLimit::ExitLimit(const SCEV *E, const SCEV *M,
6721 bool MaxOrZero)
6722 : ExitLimit(E, M, MaxOrZero, None) {
6723 assert((isa<SCEVCouldNotCompute>(MaxNotTaken) ||(static_cast <bool> ((isa<SCEVCouldNotCompute>(MaxNotTaken
) || isa<SCEVConstant>(MaxNotTaken)) && "No point in having a non-constant max backedge taken count!"
) ? void (0) : __assert_fail ("(isa<SCEVCouldNotCompute>(MaxNotTaken) || isa<SCEVConstant>(MaxNotTaken)) && \"No point in having a non-constant max backedge taken count!\""
, "/build/llvm-toolchain-snapshot-6.0~svn320940/lib/Analysis/ScalarEvolution.cpp"
, 6725, __extension__ __PRETTY_FUNCTION__))
6724 isa<SCEVConstant>(MaxNotTaken)) &&(static_cast <bool> ((isa<SCEVCouldNotCompute>(MaxNotTaken
) || isa<SCEVConstant>(MaxNotTaken)) && "No point in having a non-constant max backedge taken count!"
) ? void (0) : __assert_fail ("(isa<SCEVCouldNotCompute>(MaxNotTaken) || isa<SCEVConstant>(MaxNotTaken)) && \"No point in having a non-constant max backedge taken count!\""
, "/build/llvm-toolchain-snapshot-6.0~svn320940/lib/Analysis/ScalarEvolution.cpp"
, 6725, __extension__ __PRETTY_FUNCTION__))
6725 "No point in having a non-constant max backedge taken count!")(static_cast <bool> ((isa<SCEVCouldNotCompute>(MaxNotTaken
) || isa<SCEVConstant>(MaxNotTaken)) && "No point in having a non-constant max backedge taken count!"
) ? void (0) : __assert_fail ("(isa<SCEVCouldNotCompute>(MaxNotTaken) || isa<SCEVConstant>(MaxNotTaken)) && \"No point in having a non-constant max backedge taken count!\""
, "/build/llvm-toolchain-snapshot-6.0~svn320940/lib/Analysis/ScalarEvolution.cpp"
, 6725, __extension__ __PRETTY_FUNCTION__))
;
6726}
6727
6728/// Allocate memory for BackedgeTakenInfo and copy the not-taken count of each
6729/// computable exit into a persistent ExitNotTakenInfo array.
6730ScalarEvolution::BackedgeTakenInfo::BackedgeTakenInfo(
6731 SmallVectorImpl<ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo>
6732 &&ExitCounts,
6733 bool Complete, const SCEV *MaxCount, bool MaxOrZero)
6734 : MaxAndComplete(MaxCount, Complete), MaxOrZero(MaxOrZero) {
6735 using EdgeExitInfo = ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo;
6736
6737 ExitNotTaken.reserve(ExitCounts.size());
6738 std::transform(
6739 ExitCounts.begin(), ExitCounts.end(), std::back_inserter(ExitNotTaken),
6740 [&](const EdgeExitInfo &EEI) {
6741 BasicBlock *ExitBB = EEI.first;
6742 const ExitLimit &EL = EEI.second;
6743 if (EL.Predicates.empty())
6744 return ExitNotTakenInfo(ExitBB, EL.ExactNotTaken, nullptr);
6745
6746 std::unique_ptr<SCEVUnionPredicate> Predicate(new SCEVUnionPredicate);
6747 for (auto *Pred : EL.Predicates)
6748 Predicate->add(Pred);
6749
6750 return ExitNotTakenInfo(ExitBB, EL.ExactNotTaken, std::move(Predicate));
6751 });
6752 assert((isa<SCEVCouldNotCompute>(MaxCount) || isa<SCEVConstant>(MaxCount)) &&(static_cast <bool> ((isa<SCEVCouldNotCompute>(MaxCount
) || isa<SCEVConstant>(MaxCount)) && "No point in having a non-constant max backedge taken count!"
) ? void (0) : __assert_fail ("(isa<SCEVCouldNotCompute>(MaxCount) || isa<SCEVConstant>(MaxCount)) && \"No point in having a non-constant max backedge taken count!\""
, "/build/llvm-toolchain-snapshot-6.0~svn320940/lib/Analysis/ScalarEvolution.cpp"
, 6753, __extension__ __PRETTY_FUNCTION__))
6753 "No point in having a non-constant max backedge taken count!")(static_cast <bool> ((isa<SCEVCouldNotCompute>(MaxCount
) || isa<SCEVConstant>(MaxCount)) && "No point in having a non-constant max backedge taken count!"
) ? void (0) : __assert_fail ("(isa<SCEVCouldNotCompute>(MaxCount) || isa<SCEVConstant>(MaxCount)) && \"No point in having a non-constant max backedge taken count!\""
, "/build/llvm-toolchain-snapshot-6.0~svn320940/lib/Analysis/ScalarEvolution.cpp"
, 6753, __extension__ __PRETTY_FUNCTION__))
;
6754}
6755
6756/// Invalidate this result and free the ExitNotTakenInfo array.
6757void ScalarEvolution::BackedgeTakenInfo::clear() {
6758 ExitNotTaken.clear();
6759}
6760
6761/// Compute the number of times the backedge of the specified loop will execute.
6762ScalarEvolution::BackedgeTakenInfo
6763ScalarEvolution::computeBackedgeTakenCount(const Loop *L,
6764 bool AllowPredicates) {
6765 SmallVector<BasicBlock *, 8> ExitingBlocks;
6766 L->getExitingBlocks(ExitingBlocks);
6767
6768 using EdgeExitInfo = ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo;
6769
6770 SmallVector<EdgeExitInfo, 4> ExitCounts;
6771 bool CouldComputeBECount = true;
6772 BasicBlock *Latch = L->getLoopLatch(); // may be NULL.
6773 const SCEV *MustExitMaxBECount = nullptr;
6774 const SCEV *MayExitMaxBECount = nullptr;
6775 bool MustExitMaxOrZero = false;
6776
6777 // Compute the ExitLimit for each loop exit. Use this to populate ExitCounts
6778 // and compute maxBECount.
6779 // Do a union of all the predicates here.
6780 for (unsigned i = 0, e = ExitingBlocks.size(); i != e; ++i) {
6781 BasicBlock *ExitBB = ExitingBlocks[i];
6782 ExitLimit EL = computeExitLimit(L, ExitBB, AllowPredicates);
6783
6784 assert((AllowPredicates || EL.Predicates.empty()) &&(static_cast <bool> ((AllowPredicates || EL.Predicates.
empty()) && "Predicated exit limit when predicates are not allowed!"
) ? void (0) : __assert_fail ("(AllowPredicates || EL.Predicates.empty()) && \"Predicated exit limit when predicates are not allowed!\""
, "/build/llvm-toolchain-snapshot-6.0~svn320940/lib/Analysis/ScalarEvolution.cpp"
, 6785, __extension__ __PRETTY_FUNCTION__))
6785 "Predicated exit limit when predicates are not allowed!")(static_cast <bool> ((AllowPredicates || EL.Predicates.
empty()) && "Predicated exit limit when predicates are not allowed!"
) ? void (0) : __assert_fail ("(AllowPredicates || EL.Predicates.empty()) && \"Predicated exit limit when predicates are not allowed!\""
, "/build/llvm-toolchain-snapshot-6.0~svn320940/lib/Analysis/ScalarEvolution.cpp"
, 6785, __extension__ __PRETTY_FUNCTION__))
;
6786
6787 // 1. For each exit that can be computed, add an entry to ExitCounts.
6788 // CouldComputeBECount is true only if all exits can be computed.
6789 if (EL.ExactNotTaken == getCouldNotCompute())
6790 // We couldn't compute an exact value for this exit, so
6791 // we won't be able to compute an exact value for the loop.
6792 CouldComputeBECount = false;
6793 else
6794 ExitCounts.emplace_back(ExitBB, EL);
6795
6796 // 2. Derive the loop's MaxBECount from each exit's max number of
6797 // non-exiting iterations. Partition the loop exits into two kinds:
6798 // LoopMustExits and LoopMayExits.
6799 //
6800 // If the exit dominates the loop latch, it is a LoopMustExit otherwise it
6801 // is a LoopMayExit. If any computable LoopMustExit is found, then
6802 // MaxBECount is the minimum EL.MaxNotTaken of computable
6803 // LoopMustExits. Otherwise, MaxBECount is conservatively the maximum
6804 // EL.MaxNotTaken, where CouldNotCompute is considered greater than any
6805 // computable EL.MaxNotTaken.
6806 if (EL.MaxNotTaken != getCouldNotCompute() && Latch &&
6807 DT.dominates(ExitBB, Latch)) {
6808 if (!MustExitMaxBECount) {
6809 MustExitMaxBECount = EL.MaxNotTaken;
6810 MustExitMaxOrZero = EL.MaxOrZero;
6811 } else {
6812 MustExitMaxBECount =
6813 getUMinFromMismatchedTypes(MustExitMaxBECount, EL.MaxNotTaken);
6814 }
6815 } else if (MayExitMaxBECount != getCouldNotCompute()) {
6816 if (!MayExitMaxBECount || EL.MaxNotTaken == getCouldNotCompute())
6817 MayExitMaxBECount = EL.MaxNotTaken;
6818 else {
6819 MayExitMaxBECount =
6820 getUMaxFromMismatchedTypes(MayExitMaxBECount, EL.MaxNotTaken);
6821 }
6822 }
6823 }
6824 const SCEV *MaxBECount = MustExitMaxBECount ? MustExitMaxBECount :
6825 (MayExitMaxBECount ? MayExitMaxBECount : getCouldNotCompute());
6826 // The loop backedge will be taken the maximum or zero times if there's
6827 // a single exit that must be taken the maximum or zero times.
6828 bool MaxOrZero = (MustExitMaxOrZero && ExitingBlocks.size() == 1);
6829 return BackedgeTakenInfo(std::move(ExitCounts), CouldComputeBECount,
6830 MaxBECount, MaxOrZero);
6831}
6832
6833ScalarEvolution::ExitLimit
6834ScalarEvolution::computeExitLimit(const Loop *L, BasicBlock *ExitingBlock,
6835 bool AllowPredicates) {
6836 // Okay, we've chosen an exiting block. See what condition causes us to exit
6837 // at this block and remember the exit block and whether all other targets
6838 // lead to the loop header.
6839 bool MustExecuteLoopHeader = true;
6840 BasicBlock *Exit = nullptr;
6841 for (auto *SBB : successors(ExitingBlock))
6842 if (!L->contains(SBB)) {
6843 if (Exit) // Multiple exit successors.
6844 return getCouldNotCompute();
6845 Exit = SBB;
6846 } else if (SBB != L->getHeader()) {
6847 MustExecuteLoopHeader = false;
6848 }
6849
6850 // At this point, we know we have a conditional branch that determines whether
6851 // the loop is exited. However, we don't know if the branch is executed each
6852 // time through the loop. If not, then the execution count of the branch will
6853 // not be equal to the trip count of the loop.
6854 //
6855 // Currently we check for this by checking to see if the Exit branch goes to
6856 // the loop header. If so, we know it will always execute the same number of
6857 // times as the loop. We also handle the case where the exit block *is* the
6858 // loop header. This is common for un-rotated loops.
6859 //
6860 // If both of those tests fail, walk up the unique predecessor chain to the
6861 // header, stopping if there is an edge that doesn't exit the loop. If the
6862 // header is reached, the execution count of the branch will be equal to the
6863 // trip count of the loop.
6864 //
6865 // More extensive analysis could be done to handle more cases here.
6866 //
6867 if (!MustExecuteLoopHeader && ExitingBlock != L->getHeader()) {
6868 // The simple checks failed, try climbing the unique predecessor chain
6869 // up to the header.
6870 bool Ok = false;
6871 for (BasicBlock *BB = ExitingBlock; BB; ) {
6872 BasicBlock *Pred = BB->getUniquePredecessor();
6873 if (!Pred)
6874 return getCouldNotCompute();
6875 TerminatorInst *PredTerm = Pred->getTerminator();
6876 for (const BasicBlock *PredSucc : PredTerm->successors()) {
6877 if (PredSucc == BB)
6878 continue;
6879 // If the predecessor has a successor that isn't BB and isn't
6880 // outside the loop, assume the worst.
6881 if (L->contains(PredSucc))
6882 return getCouldNotCompute();
6883 }
6884 if (Pred == L->getHeader()) {
6885 Ok = true;
6886 break;
6887 }
6888 BB = Pred;
6889 }
6890 if (!Ok)
6891 return getCouldNotCompute();
6892 }
6893
6894 bool IsOnlyExit = (L->getExitingBlock() != nullptr);
6895 TerminatorInst *Term = ExitingBlock->getTerminator();
6896 if (BranchInst *BI = dyn_cast<BranchInst>(Term)) {
6897 assert(BI->isConditional() && "If unconditional, it can't be in loop!")(static_cast <bool> (BI->isConditional() && "If unconditional, it can't be in loop!"
) ? void (0) : __assert_fail ("BI->isConditional() && \"If unconditional, it can't be in loop!\""
, "/build/llvm-toolchain-snapshot-6.0~svn320940/lib/Analysis/ScalarEvolution.cpp"
, 6897, __extension__ __PRETTY_FUNCTION__))
;
6898 // Proceed to the next level to examine the exit condition expression.
6899 return computeExitLimitFromCond(
6900 L, BI->getCondition(), BI->getSuccessor(0), BI->getSuccessor(1),
6901 /*ControlsExit=*/IsOnlyExit, AllowPredicates);
6902 }
6903
6904 if (SwitchInst *SI = dyn_cast<SwitchInst>(Term))
6905 return computeExitLimitFromSingleExitSwitch(L, SI, Exit,
6906 /*ControlsExit=*/IsOnlyExit);
6907
6908 return getCouldNotCompute();
6909}
6910
6911ScalarEvolution::ExitLimit ScalarEvolution::computeExitLimitFromCond(
6912 const Loop *L, Value *ExitCond, BasicBlock *TBB, BasicBlock *FBB,
6913 bool ControlsExit, bool AllowPredicates) {
6914 ScalarEvolution::ExitLimitCacheTy Cache(L, TBB, FBB, AllowPredicates);
6915 return computeExitLimitFromCondCached(Cache, L, ExitCond, TBB, FBB,
6916 ControlsExit, AllowPredicates);
6917}
6918
6919Optional<ScalarEvolution::ExitLimit>
6920ScalarEvolution::ExitLimitCache::find(const Loop *L, Value *ExitCond,
6921 BasicBlock *TBB, BasicBlock *FBB,
6922 bool ControlsExit, bool AllowPredicates) {
6923 (void)this->L;
6924 (void)this->TBB;
6925 (void)this->FBB;
6926 (void)this->AllowPredicates;
6927
6928 assert(this->L == L && this->TBB == TBB && this->FBB == FBB &&(static_cast <bool> (this->L == L && this->
TBB == TBB && this->FBB == FBB && this->
AllowPredicates == AllowPredicates && "Variance in assumed invariant key components!"
) ? void (0) : __assert_fail ("this->L == L && this->TBB == TBB && this->FBB == FBB && this->AllowPredicates == AllowPredicates && \"Variance in assumed invariant key components!\""
, "/build/llvm-toolchain-snapshot-6.0~svn320940/lib/Analysis/ScalarEvolution.cpp"
, 6930, __extension__ __PRETTY_FUNCTION__))
6929 this->AllowPredicates == AllowPredicates &&(static_cast <bool> (this->L == L && this->
TBB == TBB && this->FBB == FBB && this->
AllowPredicates == AllowPredicates && "Variance in assumed invariant key components!"
) ? void (0) : __assert_fail ("this->L == L && this->TBB == TBB && this->FBB == FBB && this->AllowPredicates == AllowPredicates && \"Variance in assumed invariant key components!\""
, "/build/llvm-toolchain-snapshot-6.0~svn320940/lib/Analysis/ScalarEvolution.cpp"
, 6930, __extension__ __PRETTY_FUNCTION__))
6930 "Variance in assumed invariant key components!")(static_cast <bool> (this->L == L && this->
TBB == TBB && this->FBB == FBB && this->
AllowPredicates == AllowPredicates && "Variance in assumed invariant key components!"
) ? void (0) : __assert_fail ("this->L == L && this->TBB == TBB && this->FBB == FBB && this->AllowPredicates == AllowPredicates && \"Variance in assumed invariant key components!\""
, "/build/llvm-toolchain-snapshot-6.0~svn320940/lib/Analysis/ScalarEvolution.cpp"
, 6930, __extension__ __PRETTY_FUNCTION__))
;
6931 auto Itr = TripCountMap.find({ExitCond, ControlsExit});
6932 if (Itr == TripCountMap.end())
6933 return None;
6934 return Itr->second;
6935}
6936
6937void ScalarEvolution::ExitLimitCache::insert(const Loop *L, Value *ExitCond,
6938 BasicBlock *TBB, BasicBlock *FBB,
6939 bool ControlsExit,
6940 bool AllowPredicates,
6941 const ExitLimit &EL) {
6942 assert(this->L == L && this->TBB == TBB && this->FBB == FBB &&(static_cast <bool> (this->L == L && this->
TBB == TBB && this->FBB == FBB && this->
AllowPredicates == AllowPredicates && "Variance in assumed invariant key components!"
) ? void (0) : __assert_fail ("this->L == L && this->TBB == TBB && this->FBB == FBB && this->AllowPredicates == AllowPredicates && \"Variance in assumed invariant key components!\""
, "/build/llvm-toolchain-snapshot-6.0~svn320940/lib/Analysis/ScalarEvolution.cpp"
, 6944, __extension__ __PRETTY_FUNCTION__))
6943 this->AllowPredicates == AllowPredicates &&(static_cast <bool> (this->L == L && this->
TBB == TBB && this->FBB == FBB && this->
AllowPredicates == AllowPredicates && "Variance in assumed invariant key components!"
) ? void (0) : __assert_fail ("this->L == L && this->TBB == TBB && this->FBB == FBB && this->AllowPredicates == AllowPredicates && \"Variance in assumed invariant key components!\""
, "/build/llvm-toolchain-snapshot-6.0~svn320940/lib/Analysis/ScalarEvolution.cpp"
, 6944, __extension__ __PRETTY_FUNCTION__))
6944 "Variance in assumed invariant key components!")(static_cast <bool> (this->L == L && this->
TBB == TBB && this->FBB == FBB && this->
AllowPredicates == AllowPredicates && "Variance in assumed invariant key components!"
) ? void (0) : __assert_fail ("this->L == L && this->TBB == TBB && this->FBB == FBB && this->AllowPredicates == AllowPredicates && \"Variance in assumed invariant key components!\""
, "/build/llvm-toolchain-snapshot-6.0~svn320940/lib/Analysis/ScalarEvolution.cpp"
, 6944, __extension__ __PRETTY_FUNCTION__))
;
6945
6946 auto InsertResult = TripCountMap.insert({{ExitCond, ControlsExit}, EL});
6947 assert(InsertResult.second && "Expected successful insertion!")(static_cast <bool> (InsertResult.second && "Expected successful insertion!"
) ? void (0) : __assert_fail ("InsertResult.second && \"Expected successful insertion!\""
, "/build/llvm-toolchain-snapshot-6.0~svn320940/lib/Analysis/ScalarEvolution.cpp"
, 6947, __extension__ __PRETTY_FUNCTION__))
;
6948 (void)InsertResult;
6949}
6950
6951ScalarEvolution::ExitLimit ScalarEvolution::computeExitLimitFromCondCached(
6952 ExitLimitCacheTy &Cache, const Loop *L, Value *ExitCond, BasicBlock *TBB,
6953 BasicBlock *FBB, bool ControlsExit, bool AllowPredicates) {
6954
6955 if (auto MaybeEL =
6956 Cache.find(L, ExitCond, TBB, FBB, ControlsExit, AllowPredicates))
6957 return *MaybeEL;
6958
6959 ExitLimit EL = computeExitLimitFromCondImpl(Cache, L, ExitCond, TBB, FBB,
6960 ControlsExit, AllowPredicates);
6961 Cache.insert(L, ExitCond, TBB, FBB, ControlsExit, AllowPredicates, EL);
6962 return EL;
6963}
6964
6965ScalarEvolution::ExitLimit ScalarEvolution::computeExitLimitFromCondImpl(
6966 ExitLimitCacheTy &Cache, const Loop *L, Value *ExitCond, BasicBlock *TBB,
6967 BasicBlock *FBB, bool ControlsExit, bool AllowPredicates) {
6968 // Check if the controlling expression for this loop is an And or Or.
6969 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(ExitCond)) {
6970 if (BO->getOpcode() == Instruction::And) {
6971 // Recurse on the operands of the and.
6972 bool EitherMayExit = L->contains(TBB);
6973 ExitLimit EL0 = computeExitLimitFromCondCached(
6974 Cache, L, BO->getOperand(0), TBB, FBB, ControlsExit && !EitherMayExit,
6975 AllowPredicates);
6976 ExitLimit EL1 = computeExitLimitFromCondCached(
6977 Cache, L, BO->getOperand(1), TBB, FBB, ControlsExit && !EitherMayExit,
6978 AllowPredicates);
6979 const SCEV *BECount = getCouldNotCompute();
6980 const SCEV *MaxBECount = getCouldNotCompute();
6981 if (EitherMayExit) {
6982 // Both conditions must be true for the loop to continue executing.
6983 // Choose the less conservative count.
6984 if (EL0.ExactNotTaken == getCouldNotCompute() ||
6985 EL1.ExactNotTaken == getCouldNotCompute())
6986 BECount = getCouldNotCompute();
6987 else
6988 BECount =
6989 getUMinFromMismatchedTypes(EL0.ExactNotTaken, EL1.ExactNotTaken);
6990 if (EL0.MaxNotTaken == getCouldNotCompute())
6991 MaxBECount = EL1.MaxNotTaken;
6992 else if (EL1.MaxNotTaken == getCouldNotCompute())
6993 MaxBECount = EL0.MaxNotTaken;
6994 else
6995 MaxBECount =
6996 getUMinFromMismatchedTypes(EL0.MaxNotTaken, EL1.MaxNotTaken);
6997 } else {
6998 // Both conditions must be true at the same time for the loop to exit.
6999 // For now, be conservative.
7000 assert(L->contains(FBB) && "Loop block has no successor in loop!")(static_cast <bool> (L->contains(FBB) && "Loop block has no successor in loop!"
) ? void (0) : __assert_fail ("L->contains(FBB) && \"Loop block has no successor in loop!\""
, "/build/llvm-toolchain-snapshot-6.0~svn320940/lib/Analysis/ScalarEvolution.cpp"
, 7000, __extension__ __PRETTY_FUNCTION__))
;
7001 if (EL0.MaxNotTaken == EL1.MaxNotTaken)
7002 MaxBECount = EL0.MaxNotTaken;
7003 if (EL0.ExactNotTaken == EL1.ExactNotTaken)
7004 BECount = EL0.ExactNotTaken;
7005 }
7006
7007 // There are cases (e.g. PR26207) where computeExitLimitFromCond is able
7008 // to be more aggressive when computing BECount than when computing
7009 // MaxBECount. In these cases it is possible for EL0.ExactNotTaken and
7010 // EL1.ExactNotTaken to match, but for EL0.MaxNotTaken and EL1.MaxNotTaken
7011 // to not.
7012 if (isa<SCEVCouldNotCompute>(MaxBECount) &&
7013 !isa<SCEVCouldNotCompute>(BECount))
7014 MaxBECount = getConstant(getUnsignedRangeMax(BECount));
7015
7016 return ExitLimit(BECount, MaxBECount, false,
7017 {&EL0.Predicates, &EL1.Predicates});
7018 }
7019 if (BO->getOpcode() == Instruction::Or) {
7020 // Recurse on the operands of the or.
7021 bool EitherMayExit = L->contains(FBB);
7022 ExitLimit EL0 = computeExitLimitFromCondCached(
7023 Cache, L, BO->getOperand(0), TBB, FBB, ControlsExit && !EitherMayExit,
7024 AllowPredicates);
7025 ExitLimit EL1 = computeExitLimitFromCondCached(
7026 Cache, L, BO->getOperand(1), TBB, FBB, ControlsExit && !EitherMayExit,
7027 AllowPredicates);
7028 const SCEV *BECount = getCouldNotCompute();
7029 const SCEV *MaxBECount = getCouldNotCompute();
7030 if (EitherMayExit) {
7031 // Both conditions must be false for the loop to continue executing.
7032 // Choose the less conservative count.
7033 if (EL0.ExactNotTaken == getCouldNotCompute() ||
7034 EL1.ExactNotTaken == getCouldNotCompute())
7035 BECount = getCouldNotCompute();
7036 else
7037 BECount =
7038 getUMinFromMismatchedTypes(EL0.ExactNotTaken, EL1.ExactNotTaken);
7039 if (EL0.MaxNotTaken == getCouldNotCompute())
7040 MaxBECount = EL1.MaxNotTaken;
7041 else if (EL1.MaxNotTaken == getCouldNotCompute())
7042 MaxBECount = EL0.MaxNotTaken;
7043 else
7044 MaxBECount =
7045 getUMinFromMismatchedTypes(EL0.MaxNotTaken, EL1.MaxNotTaken);
7046 } else {
7047 // Both conditions must be false at the same time for the loop to exit.
7048 // For now, be conservative.
7049 assert(L->contains(TBB) && "Loop block has no successor in loop!")(static_cast <bool> (L->contains(TBB) && "Loop block has no successor in loop!"
) ? void (0) : __assert_fail ("L->contains(TBB) && \"Loop block has no successor in loop!\""
, "/build/llvm-toolchain-snapshot-6.0~svn320940/lib/Analysis/ScalarEvolution.cpp"
, 7049, __extension__ __PRETTY_FUNCTION__))
;
7050 if (EL0.MaxNotTaken == EL1.MaxNotTaken)
7051 MaxBECount = EL0.MaxNotTaken;
7052 if (EL0.ExactNotTaken == EL1.ExactNotTaken)
7053 BECount = EL0.ExactNotTaken;
7054 }
7055
7056 return ExitLimit(BECount, MaxBECount, false,
7057 {&EL0.Predicates, &EL1.Predicates});
7058 }
7059 }
7060
7061 // With an icmp, it may be feasible to compute an exact backedge-taken count.
7062 // Proceed to the next level to examine the icmp.
7063 if (ICmpInst *ExitCondICmp = dyn_cast<ICmpInst>(ExitCond)) {
7064 ExitLimit EL =
7065 computeExitLimitFromICmp(L, ExitCondICmp, TBB, FBB, ControlsExit);
7066 if (EL.hasFullInfo() || !AllowPredicates)
7067 return EL;
7068
7069 // Try again, but use SCEV predicates this time.
7070 return computeExitLimitFromICmp(L, ExitCondICmp, TBB, FBB, ControlsExit,
7071 /*AllowPredicates=*/true);
7072 }
7073
7074 // Check for a constant condition. These are normally stripped out by
7075 // SimplifyCFG, but ScalarEvolution may be used by a pass which wishes to
7076 // preserve the CFG and is temporarily leaving constant conditions
7077 // in place.
7078 if (ConstantInt *CI = dyn_cast<ConstantInt>(ExitCond)) {
7079 if (L->contains(FBB) == !CI->getZExtValue())
7080 // The backedge is always taken.
7081 return getCouldNotCompute();
7082 else
7083 // The backedge is never taken.
7084 return getZero(CI->getType());
7085 }
7086
7087 // If it's not an integer or pointer comparison then compute it the hard way.
7088 return computeExitCountExhaustively(L, ExitCond, !L->contains(TBB));
7089}
7090
7091ScalarEvolution::ExitLimit
7092ScalarEvolution::computeExitLimitFromICmp(const Loop *L,
7093 ICmpInst *ExitCond,
7094 BasicBlock *TBB,
7095 BasicBlock *FBB,
7096 bool ControlsExit,
7097 bool AllowPredicates) {
7098 // If the condition was exit on true, convert the condition to exit on false
7099 ICmpInst::Predicate Pred;
7100 if (!L->contains(FBB))
7101 Pred = ExitCond->getPredicate();
7102 else
7103 Pred = ExitCond->getInversePredicate();
7104 const ICmpInst::Predicate OriginalPred = Pred;
7105
7106 // Handle common loops like: for (X = "string"; *X; ++X)
7107 if (LoadInst *LI = dyn_cast<LoadInst>(ExitCond->getOperand(0)))
7108 if (Constant *RHS = dyn_cast<Constant>(ExitCond->getOperand(1))) {
7109 ExitLimit ItCnt =
7110 computeLoadConstantCompareExitLimit(LI, RHS, L, Pred);
7111 if (ItCnt.hasAnyInfo())
7112 return ItCnt;
7113 }
7114
7115 const SCEV *LHS = getSCEV(ExitCond->getOperand(0));
7116 const SCEV *RHS = getSCEV(ExitCond->getOperand(1));
7117
7118 // Try to evaluate any dependencies out of the loop.
7119 LHS = getSCEVAtScope(LHS, L);
7120 RHS = getSCEVAtScope(RHS, L);
7121
7122 // At this point, we would like to compute how many iterations of the
7123 // loop the predicate will return true for these inputs.
7124 if (isLoopInvariant(LHS, L) && !isLoopInvariant(RHS, L)) {
7125 // If there is a loop-invariant, force it into the RHS.
7126 std::swap(LHS, RHS);
7127 Pred = ICmpInst::getSwappedPredicate(Pred);
7128 }
7129
7130 // Simplify the operands before analyzing them.
7131 (void)SimplifyICmpOperands(Pred, LHS, RHS);
7132
7133 // If we have a comparison of a chrec against a constant, try to use value
7134 // ranges to answer this query.
7135 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS))
7136 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS))
7137 if (AddRec->getLoop() == L) {
7138 // Form the constant range.
7139 ConstantRange CompRange =
7140 ConstantRange::makeExactICmpRegion(Pred, RHSC->getAPInt());
7141
7142 const SCEV *Ret = AddRec->getNumIterationsInRange(CompRange, *this);
7143 if (!isa<SCEVCouldNotCompute>(Ret)) return Ret;
7144 }
7145
7146 switch (Pred) {
7147 case ICmpInst::ICMP_NE: { // while (X != Y)
7148 // Convert to: while (X-Y != 0)
7149 ExitLimit EL = howFarToZero(getMinusSCEV(LHS, RHS), L, ControlsExit,
7150 AllowPredicates);
7151 if (EL.hasAnyInfo()) return EL;
7152 break;
7153 }
7154 case ICmpInst::ICMP_EQ: { // while (X == Y)
7155 // Convert to: while (X-Y == 0)
7156 ExitLimit EL = howFarToNonZero(getMinusSCEV(LHS, RHS), L);
7157 if (EL.hasAnyInfo()) return EL;
7158 break;
7159 }
7160 case ICmpInst::ICMP_SLT:
7161 case ICmpInst::ICMP_ULT: { // while (X < Y)
7162 bool IsSigned = Pred == ICmpInst::ICMP_SLT;
7163 ExitLimit EL = howManyLessThans(LHS, RHS, L, IsSigned, ControlsExit,
7164 AllowPredicates);
7165 if (EL.hasAnyInfo()) return EL;
7166 break;
7167 }
7168 case ICmpInst::ICMP_SGT:
7169 case ICmpInst::ICMP_UGT: { // while (X > Y)
7170 bool IsSigned = Pred == ICmpInst::ICMP_SGT;
7171 ExitLimit EL =
7172 howManyGreaterThans(LHS, RHS, L, IsSigned, ControlsExit,
7173 AllowPredicates);
7174 if (EL.hasAnyInfo()) return EL;
7175 break;
7176 }
7177 default:
7178 break;
7179 }
7180
7181 auto *ExhaustiveCount =
7182 computeExitCountExhaustively(L, ExitCond, !L->contains(TBB));
7183
7184 if (!isa<SCEVCouldNotCompute>(ExhaustiveCount))
7185 return ExhaustiveCount;
7186
7187 return computeShiftCompareExitLimit(ExitCond->getOperand(0),
7188 ExitCond->getOperand(1), L, OriginalPred);
7189}
7190
7191ScalarEvolution::ExitLimit
7192ScalarEvolution::computeExitLimitFromSingleExitSwitch(const Loop *L,
7193 SwitchInst *Switch,
7194 BasicBlock *ExitingBlock,
7195 bool ControlsExit) {
7196 assert(!L->contains(ExitingBlock) && "Not an exiting block!")(static_cast <bool> (!L->contains(ExitingBlock) &&
"Not an exiting block!") ? void (0) : __assert_fail ("!L->contains(ExitingBlock) && \"Not an exiting block!\""
, "/build/llvm-toolchain-snapshot-6.0~svn320940/lib/Analysis/ScalarEvolution.cpp"
, 7196, __extension__ __PRETTY_FUNCTION__))
;
7197
7198 // Give up if the exit is the default dest of a switch.
7199 if (Switch->getDefaultDest() == ExitingBlock)
7200 return getCouldNotCompute();
7201
7202 assert(L->contains(Switch->getDefaultDest()) &&(static_cast <bool> (L->contains(Switch->getDefaultDest
()) && "Default case must not exit the loop!") ? void
(0) : __assert_fail ("L->contains(Switch->getDefaultDest()) && \"Default case must not exit the loop!\""
, "/build/llvm-toolchain-snapshot-6.0~svn320940/lib/Analysis/ScalarEvolution.cpp"
, 7203, __extension__ __PRETTY_FUNCTION__))
7203 "Default case must not exit the loop!")(static_cast <bool> (L->contains(Switch->getDefaultDest
()) && "Default case must not exit the loop!") ? void
(0) : __assert_fail ("L->contains(Switch->getDefaultDest()) && \"Default case must not exit the loop!\""
, "/build/llvm-toolchain-snapshot-6.0~svn320940/lib/Analysis/ScalarEvolution.cpp"
, 7203, __extension__ __PRETTY_FUNCTION__))
;
7204 const SCEV *LHS = getSCEVAtScope(Switch->getCondition(), L);
7205 const SCEV *RHS = getConstant(Switch->findCaseDest(ExitingBlock));
7206
7207 // while (X != Y) --> while (X-Y != 0)
7208 ExitLimit EL = howFarToZero(getMinusSCEV(LHS, RHS), L, ControlsExit);
7209 if (EL.hasAnyInfo())
7210 return EL;
7211
7212 return getCouldNotCompute();
7213}
7214
7215static ConstantInt *
7216EvaluateConstantChrecAtConstant(const SCEVAddRecExpr *AddRec, ConstantInt *C,
7217 ScalarEvolution &SE) {
7218 const SCEV *InVal = SE.getConstant(C);
7219 const SCEV *Val = AddRec->evaluateAtIteration(InVal, SE);
7220 assert(isa<SCEVConstant>(Val) &&(static_cast <bool> (isa<SCEVConstant>(Val) &&
"Evaluation of SCEV at constant didn't fold correctly?") ? void
(0) : __assert_fail ("isa<SCEVConstant>(Val) && \"Evaluation of SCEV at constant didn't fold correctly?\""
, "/build/llvm-toolchain-snapshot-6.0~svn320940/lib/Analysis/ScalarEvolution.cpp"
, 7221, __extension__ __PRETTY_FUNCTION__))
7221 "Evaluation of SCEV at constant didn't fold correctly?")(static_cast <bool> (isa<SCEVConstant>(Val) &&
"Evaluation of SCEV at constant didn't fold correctly?") ? void
(0) : __assert_fail ("isa<SCEVConstant>(Val) && \"Evaluation of SCEV at constant didn't fold correctly?\""
, "/build/llvm-toolchain-snapshot-6.0~svn320940/lib/Analysis/ScalarEvolution.cpp"
, 7221, __extension__ __PRETTY_FUNCTION__))
;
7222 return cast<SCEVConstant>(Val)->getValue();
7223}
7224
7225/// Given an exit condition of 'icmp op load X, cst', try to see if we can
7226/// compute the backedge execution count.
7227ScalarEvolution::ExitLimit
7228ScalarEvolution::computeLoadConstantCompareExitLimit(
7229 LoadInst *LI,
7230 Constant *RHS,
7231 const Loop *L,
7232 ICmpInst::Predicate predicate) {
7233 if (LI->isVolatile()) return getCouldNotCompute();
7234
7235 // Check to see if the loaded pointer is a getelementptr of a global.
7236 // TODO: Use SCEV instead of manually grubbing with GEPs.
7237 GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(LI->getOperand(0));
7238 if (!GEP) return getCouldNotCompute();
7239
7240 // Make sure that it is really a constant global we are gepping, with an
7241 // initializer, and make sure the first IDX is really 0.
7242 GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0));
7243 if (!GV || !GV->isConstant() || !GV->hasDefinitiveInitializer() ||
7244 GEP->getNumOperands() < 3 || !isa<Constant>(GEP->getOperand(1)) ||
7245 !cast<Constant>(GEP->getOperand(1))->isNullValue())
7246 return getCouldNotCompute();
7247
7248 // Okay, we allow one non-constant index into the GEP instruction.
7249 Value *VarIdx = nullptr;
7250 std::vector<Constant*> Indexes;
7251 unsigned VarIdxNum = 0;
7252 for (unsigned i = 2, e = GEP->getNumOperands(); i != e; ++i)
7253 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
7254 Indexes.push_back(CI);
7255 } else if (!isa<ConstantInt>(GEP->getOperand(i))) {
7256 if (VarIdx) return getCouldNotCompute(); // Multiple non-constant idx's.
7257 VarIdx = GEP->getOperand(i);
7258 VarIdxNum = i-2;
7259 Indexes.push_back(nullptr);
7260 }
7261
7262 // Loop-invariant loads may be a byproduct of loop optimization. Skip them.
7263 if (!VarIdx)
7264 return getCouldNotCompute();
7265
7266 // Okay, we know we have a (load (gep GV, 0, X)) comparison with a constant.
7267 // Check to see if X is a loop variant variable value now.
7268 const SCEV *Idx = getSCEV(VarIdx);
7269 Idx = getSCEVAtScope(Idx, L);
7270
7271 // We can only recognize very limited forms of loop index expressions, in
7272 // particular, only affine AddRec's like {C1,+,C2}.
7273 const SCEVAddRecExpr *IdxExpr = dyn_cast<SCEVAddRecExpr>(Idx);
7274 if (!IdxExpr || !IdxExpr->isAffine() || isLoopInvariant(IdxExpr, L) ||
7275 !isa<SCEVConstant>(IdxExpr->getOperand(0)) ||
7276 !isa<SCEVConstant>(IdxExpr->getOperand(1)))
7277 return getCouldNotCompute();
7278
7279 unsigned MaxSteps = MaxBruteForceIterations;
7280 for (unsigned IterationNum = 0; IterationNum != MaxSteps; ++IterationNum) {
7281 ConstantInt *ItCst = ConstantInt::get(
7282 cast<IntegerType>(IdxExpr->getType()), IterationNum);
7283 ConstantInt *Val = EvaluateConstantChrecAtConstant(IdxExpr, ItCst, *this);
7284
7285 // Form the GEP offset.
7286 Indexes[VarIdxNum] = Val;
7287
7288 Constant *Result = ConstantFoldLoadThroughGEPIndices(GV->getInitializer(),
7289 Indexes);
7290 if (!Result) break; // Cannot compute!
7291
7292 // Evaluate the condition for this iteration.
7293 Result = ConstantExpr::getICmp(predicate, Result, RHS);
7294 if (!isa<ConstantInt>(Result)) break; // Couldn't decide for sure
7295 if (cast<ConstantInt>(Result)->getValue().isMinValue()) {
7296 ++NumArrayLenItCounts;
7297 return getConstant(ItCst); // Found terminating iteration!
7298 }
7299 }
7300 return getCouldNotCompute();
7301}
7302
7303ScalarEvolution::ExitLimit ScalarEvolution::computeShiftCompareExitLimit(
7304 Value *LHS, Value *RHSV, const Loop *L, ICmpInst::Predicate Pred) {
7305 ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV);
7306 if (!RHS)
7307 return getCouldNotCompute();
7308
7309 const BasicBlock *Latch = L->getLoopLatch();
7310 if (!Latch)
7311 return getCouldNotCompute();
7312
7313 const BasicBlock *Predecessor = L->getLoopPredecessor();
7314 if (!Predecessor)
7315 return getCouldNotCompute();
7316
7317 // Return true if V is of the form "LHS `shift_op` <positive constant>".
7318 // Return LHS in OutLHS and shift_opt in OutOpCode.<