Bug Summary

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