ConstantRange.cpp 48 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437
  1. //===- ConstantRange.cpp - ConstantRange implementation -------------------===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. //
  9. // Represent a range of possible values that may occur when the program is run
  10. // for an integral value. This keeps track of a lower and upper bound for the
  11. // constant, which MAY wrap around the end of the numeric range. To do this, it
  12. // keeps track of a [lower, upper) bound, which specifies an interval just like
  13. // STL iterators. When used with boolean values, the following are important
  14. // ranges (other integral ranges use min/max values for special range values):
  15. //
  16. // [F, F) = {} = Empty set
  17. // [T, F) = {T}
  18. // [F, T) = {F}
  19. // [T, T) = {F, T} = Full set
  20. //
  21. //===----------------------------------------------------------------------===//
  22. #include "llvm/ADT/APInt.h"
  23. #include "llvm/Config/llvm-config.h"
  24. #include "llvm/IR/ConstantRange.h"
  25. #include "llvm/IR/Constants.h"
  26. #include "llvm/IR/InstrTypes.h"
  27. #include "llvm/IR/Instruction.h"
  28. #include "llvm/IR/Metadata.h"
  29. #include "llvm/IR/Operator.h"
  30. #include "llvm/Support/Compiler.h"
  31. #include "llvm/Support/Debug.h"
  32. #include "llvm/Support/ErrorHandling.h"
  33. #include "llvm/Support/KnownBits.h"
  34. #include "llvm/Support/raw_ostream.h"
  35. #include <algorithm>
  36. #include <cassert>
  37. #include <cstdint>
  38. using namespace llvm;
  39. ConstantRange::ConstantRange(uint32_t BitWidth, bool Full)
  40. : Lower(Full ? APInt::getMaxValue(BitWidth) : APInt::getMinValue(BitWidth)),
  41. Upper(Lower) {}
  42. ConstantRange::ConstantRange(APInt V)
  43. : Lower(std::move(V)), Upper(Lower + 1) {}
  44. ConstantRange::ConstantRange(APInt L, APInt U)
  45. : Lower(std::move(L)), Upper(std::move(U)) {
  46. assert(Lower.getBitWidth() == Upper.getBitWidth() &&
  47. "ConstantRange with unequal bit widths");
  48. assert((Lower != Upper || (Lower.isMaxValue() || Lower.isMinValue())) &&
  49. "Lower == Upper, but they aren't min or max value!");
  50. }
  51. ConstantRange ConstantRange::fromKnownBits(const KnownBits &Known,
  52. bool IsSigned) {
  53. assert(!Known.hasConflict() && "Expected valid KnownBits");
  54. if (Known.isUnknown())
  55. return getFull(Known.getBitWidth());
  56. // For unsigned ranges, or signed ranges with known sign bit, create a simple
  57. // range between the smallest and largest possible value.
  58. if (!IsSigned || Known.isNegative() || Known.isNonNegative())
  59. return ConstantRange(Known.One, ~Known.Zero + 1);
  60. // If we don't know the sign bit, pick the lower bound as a negative number
  61. // and the upper bound as a non-negative one.
  62. APInt Lower = Known.One, Upper = ~Known.Zero;
  63. Lower.setSignBit();
  64. Upper.clearSignBit();
  65. return ConstantRange(Lower, Upper + 1);
  66. }
  67. ConstantRange ConstantRange::makeAllowedICmpRegion(CmpInst::Predicate Pred,
  68. const ConstantRange &CR) {
  69. if (CR.isEmptySet())
  70. return CR;
  71. uint32_t W = CR.getBitWidth();
  72. switch (Pred) {
  73. default:
  74. llvm_unreachable("Invalid ICmp predicate to makeAllowedICmpRegion()");
  75. case CmpInst::ICMP_EQ:
  76. return CR;
  77. case CmpInst::ICMP_NE:
  78. if (CR.isSingleElement())
  79. return ConstantRange(CR.getUpper(), CR.getLower());
  80. return getFull(W);
  81. case CmpInst::ICMP_ULT: {
  82. APInt UMax(CR.getUnsignedMax());
  83. if (UMax.isMinValue())
  84. return getEmpty(W);
  85. return ConstantRange(APInt::getMinValue(W), std::move(UMax));
  86. }
  87. case CmpInst::ICMP_SLT: {
  88. APInt SMax(CR.getSignedMax());
  89. if (SMax.isMinSignedValue())
  90. return getEmpty(W);
  91. return ConstantRange(APInt::getSignedMinValue(W), std::move(SMax));
  92. }
  93. case CmpInst::ICMP_ULE:
  94. return getNonEmpty(APInt::getMinValue(W), CR.getUnsignedMax() + 1);
  95. case CmpInst::ICMP_SLE:
  96. return getNonEmpty(APInt::getSignedMinValue(W), CR.getSignedMax() + 1);
  97. case CmpInst::ICMP_UGT: {
  98. APInt UMin(CR.getUnsignedMin());
  99. if (UMin.isMaxValue())
  100. return getEmpty(W);
  101. return ConstantRange(std::move(UMin) + 1, APInt::getNullValue(W));
  102. }
  103. case CmpInst::ICMP_SGT: {
  104. APInt SMin(CR.getSignedMin());
  105. if (SMin.isMaxSignedValue())
  106. return getEmpty(W);
  107. return ConstantRange(std::move(SMin) + 1, APInt::getSignedMinValue(W));
  108. }
  109. case CmpInst::ICMP_UGE:
  110. return getNonEmpty(CR.getUnsignedMin(), APInt::getNullValue(W));
  111. case CmpInst::ICMP_SGE:
  112. return getNonEmpty(CR.getSignedMin(), APInt::getSignedMinValue(W));
  113. }
  114. }
  115. ConstantRange ConstantRange::makeSatisfyingICmpRegion(CmpInst::Predicate Pred,
  116. const ConstantRange &CR) {
  117. // Follows from De-Morgan's laws:
  118. //
  119. // ~(~A union ~B) == A intersect B.
  120. //
  121. return makeAllowedICmpRegion(CmpInst::getInversePredicate(Pred), CR)
  122. .inverse();
  123. }
  124. ConstantRange ConstantRange::makeExactICmpRegion(CmpInst::Predicate Pred,
  125. const APInt &C) {
  126. // Computes the exact range that is equal to both the constant ranges returned
  127. // by makeAllowedICmpRegion and makeSatisfyingICmpRegion. This is always true
  128. // when RHS is a singleton such as an APInt and so the assert is valid.
  129. // However for non-singleton RHS, for example ult [2,5) makeAllowedICmpRegion
  130. // returns [0,4) but makeSatisfyICmpRegion returns [0,2).
  131. //
  132. assert(makeAllowedICmpRegion(Pred, C) == makeSatisfyingICmpRegion(Pred, C));
  133. return makeAllowedICmpRegion(Pred, C);
  134. }
  135. bool ConstantRange::getEquivalentICmp(CmpInst::Predicate &Pred,
  136. APInt &RHS) const {
  137. bool Success = false;
  138. if (isFullSet() || isEmptySet()) {
  139. Pred = isEmptySet() ? CmpInst::ICMP_ULT : CmpInst::ICMP_UGE;
  140. RHS = APInt(getBitWidth(), 0);
  141. Success = true;
  142. } else if (auto *OnlyElt = getSingleElement()) {
  143. Pred = CmpInst::ICMP_EQ;
  144. RHS = *OnlyElt;
  145. Success = true;
  146. } else if (auto *OnlyMissingElt = getSingleMissingElement()) {
  147. Pred = CmpInst::ICMP_NE;
  148. RHS = *OnlyMissingElt;
  149. Success = true;
  150. } else if (getLower().isMinSignedValue() || getLower().isMinValue()) {
  151. Pred =
  152. getLower().isMinSignedValue() ? CmpInst::ICMP_SLT : CmpInst::ICMP_ULT;
  153. RHS = getUpper();
  154. Success = true;
  155. } else if (getUpper().isMinSignedValue() || getUpper().isMinValue()) {
  156. Pred =
  157. getUpper().isMinSignedValue() ? CmpInst::ICMP_SGE : CmpInst::ICMP_UGE;
  158. RHS = getLower();
  159. Success = true;
  160. }
  161. assert((!Success || ConstantRange::makeExactICmpRegion(Pred, RHS) == *this) &&
  162. "Bad result!");
  163. return Success;
  164. }
  165. /// Exact mul nuw region for single element RHS.
  166. static ConstantRange makeExactMulNUWRegion(const APInt &V) {
  167. unsigned BitWidth = V.getBitWidth();
  168. if (V == 0)
  169. return ConstantRange::getFull(V.getBitWidth());
  170. return ConstantRange::getNonEmpty(
  171. APIntOps::RoundingUDiv(APInt::getMinValue(BitWidth), V,
  172. APInt::Rounding::UP),
  173. APIntOps::RoundingUDiv(APInt::getMaxValue(BitWidth), V,
  174. APInt::Rounding::DOWN) + 1);
  175. }
  176. /// Exact mul nsw region for single element RHS.
  177. static ConstantRange makeExactMulNSWRegion(const APInt &V) {
  178. // Handle special case for 0, -1 and 1. See the last for reason why we
  179. // specialize -1 and 1.
  180. unsigned BitWidth = V.getBitWidth();
  181. if (V == 0 || V.isOneValue())
  182. return ConstantRange::getFull(BitWidth);
  183. APInt MinValue = APInt::getSignedMinValue(BitWidth);
  184. APInt MaxValue = APInt::getSignedMaxValue(BitWidth);
  185. // e.g. Returning [-127, 127], represented as [-127, -128).
  186. if (V.isAllOnesValue())
  187. return ConstantRange(-MaxValue, MinValue);
  188. APInt Lower, Upper;
  189. if (V.isNegative()) {
  190. Lower = APIntOps::RoundingSDiv(MaxValue, V, APInt::Rounding::UP);
  191. Upper = APIntOps::RoundingSDiv(MinValue, V, APInt::Rounding::DOWN);
  192. } else {
  193. Lower = APIntOps::RoundingSDiv(MinValue, V, APInt::Rounding::UP);
  194. Upper = APIntOps::RoundingSDiv(MaxValue, V, APInt::Rounding::DOWN);
  195. }
  196. // ConstantRange ctor take a half inclusive interval [Lower, Upper + 1).
  197. // Upper + 1 is guaranteed not to overflow, because |divisor| > 1. 0, -1,
  198. // and 1 are already handled as special cases.
  199. return ConstantRange(Lower, Upper + 1);
  200. }
  201. ConstantRange
  202. ConstantRange::makeGuaranteedNoWrapRegion(Instruction::BinaryOps BinOp,
  203. const ConstantRange &Other,
  204. unsigned NoWrapKind) {
  205. using OBO = OverflowingBinaryOperator;
  206. assert(Instruction::isBinaryOp(BinOp) && "Binary operators only!");
  207. assert((NoWrapKind == OBO::NoSignedWrap ||
  208. NoWrapKind == OBO::NoUnsignedWrap) &&
  209. "NoWrapKind invalid!");
  210. bool Unsigned = NoWrapKind == OBO::NoUnsignedWrap;
  211. unsigned BitWidth = Other.getBitWidth();
  212. switch (BinOp) {
  213. default:
  214. llvm_unreachable("Unsupported binary op");
  215. case Instruction::Add: {
  216. if (Unsigned)
  217. return getNonEmpty(APInt::getNullValue(BitWidth),
  218. -Other.getUnsignedMax());
  219. APInt SignedMinVal = APInt::getSignedMinValue(BitWidth);
  220. APInt SMin = Other.getSignedMin(), SMax = Other.getSignedMax();
  221. return getNonEmpty(
  222. SMin.isNegative() ? SignedMinVal - SMin : SignedMinVal,
  223. SMax.isStrictlyPositive() ? SignedMinVal - SMax : SignedMinVal);
  224. }
  225. case Instruction::Sub: {
  226. if (Unsigned)
  227. return getNonEmpty(Other.getUnsignedMax(), APInt::getMinValue(BitWidth));
  228. APInt SignedMinVal = APInt::getSignedMinValue(BitWidth);
  229. APInt SMin = Other.getSignedMin(), SMax = Other.getSignedMax();
  230. return getNonEmpty(
  231. SMax.isStrictlyPositive() ? SignedMinVal + SMax : SignedMinVal,
  232. SMin.isNegative() ? SignedMinVal + SMin : SignedMinVal);
  233. }
  234. case Instruction::Mul:
  235. if (Unsigned)
  236. return makeExactMulNUWRegion(Other.getUnsignedMax());
  237. return makeExactMulNSWRegion(Other.getSignedMin())
  238. .intersectWith(makeExactMulNSWRegion(Other.getSignedMax()));
  239. }
  240. }
  241. ConstantRange ConstantRange::makeExactNoWrapRegion(Instruction::BinaryOps BinOp,
  242. const APInt &Other,
  243. unsigned NoWrapKind) {
  244. // makeGuaranteedNoWrapRegion() is exact for single-element ranges, as
  245. // "for all" and "for any" coincide in this case.
  246. return makeGuaranteedNoWrapRegion(BinOp, ConstantRange(Other), NoWrapKind);
  247. }
  248. bool ConstantRange::isFullSet() const {
  249. return Lower == Upper && Lower.isMaxValue();
  250. }
  251. bool ConstantRange::isEmptySet() const {
  252. return Lower == Upper && Lower.isMinValue();
  253. }
  254. bool ConstantRange::isWrappedSet() const {
  255. return Lower.ugt(Upper) && !Upper.isNullValue();
  256. }
  257. bool ConstantRange::isUpperWrapped() const {
  258. return Lower.ugt(Upper);
  259. }
  260. bool ConstantRange::isSignWrappedSet() const {
  261. return Lower.sgt(Upper) && !Upper.isMinSignedValue();
  262. }
  263. bool ConstantRange::isUpperSignWrapped() const {
  264. return Lower.sgt(Upper);
  265. }
  266. bool
  267. ConstantRange::isSizeStrictlySmallerThan(const ConstantRange &Other) const {
  268. assert(getBitWidth() == Other.getBitWidth());
  269. if (isFullSet())
  270. return false;
  271. if (Other.isFullSet())
  272. return true;
  273. return (Upper - Lower).ult(Other.Upper - Other.Lower);
  274. }
  275. bool
  276. ConstantRange::isSizeLargerThan(uint64_t MaxSize) const {
  277. assert(MaxSize && "MaxSize can't be 0.");
  278. // If this a full set, we need special handling to avoid needing an extra bit
  279. // to represent the size.
  280. if (isFullSet())
  281. return APInt::getMaxValue(getBitWidth()).ugt(MaxSize - 1);
  282. return (Upper - Lower).ugt(MaxSize);
  283. }
  284. bool ConstantRange::isAllNegative() const {
  285. // Empty set is all negative, full set is not.
  286. if (isEmptySet())
  287. return true;
  288. if (isFullSet())
  289. return false;
  290. return !isUpperSignWrapped() && !Upper.isStrictlyPositive();
  291. }
  292. bool ConstantRange::isAllNonNegative() const {
  293. // Empty and full set are automatically treated correctly.
  294. return !isSignWrappedSet() && Lower.isNonNegative();
  295. }
  296. APInt ConstantRange::getUnsignedMax() const {
  297. if (isFullSet() || isUpperWrapped())
  298. return APInt::getMaxValue(getBitWidth());
  299. return getUpper() - 1;
  300. }
  301. APInt ConstantRange::getUnsignedMin() const {
  302. if (isFullSet() || isWrappedSet())
  303. return APInt::getMinValue(getBitWidth());
  304. return getLower();
  305. }
  306. APInt ConstantRange::getSignedMax() const {
  307. if (isFullSet() || isUpperSignWrapped())
  308. return APInt::getSignedMaxValue(getBitWidth());
  309. return getUpper() - 1;
  310. }
  311. APInt ConstantRange::getSignedMin() const {
  312. if (isFullSet() || isSignWrappedSet())
  313. return APInt::getSignedMinValue(getBitWidth());
  314. return getLower();
  315. }
  316. bool ConstantRange::contains(const APInt &V) const {
  317. if (Lower == Upper)
  318. return isFullSet();
  319. if (!isUpperWrapped())
  320. return Lower.ule(V) && V.ult(Upper);
  321. return Lower.ule(V) || V.ult(Upper);
  322. }
  323. bool ConstantRange::contains(const ConstantRange &Other) const {
  324. if (isFullSet() || Other.isEmptySet()) return true;
  325. if (isEmptySet() || Other.isFullSet()) return false;
  326. if (!isUpperWrapped()) {
  327. if (Other.isUpperWrapped())
  328. return false;
  329. return Lower.ule(Other.getLower()) && Other.getUpper().ule(Upper);
  330. }
  331. if (!Other.isUpperWrapped())
  332. return Other.getUpper().ule(Upper) ||
  333. Lower.ule(Other.getLower());
  334. return Other.getUpper().ule(Upper) && Lower.ule(Other.getLower());
  335. }
  336. ConstantRange ConstantRange::subtract(const APInt &Val) const {
  337. assert(Val.getBitWidth() == getBitWidth() && "Wrong bit width");
  338. // If the set is empty or full, don't modify the endpoints.
  339. if (Lower == Upper)
  340. return *this;
  341. return ConstantRange(Lower - Val, Upper - Val);
  342. }
  343. ConstantRange ConstantRange::difference(const ConstantRange &CR) const {
  344. return intersectWith(CR.inverse());
  345. }
  346. static ConstantRange getPreferredRange(
  347. const ConstantRange &CR1, const ConstantRange &CR2,
  348. ConstantRange::PreferredRangeType Type) {
  349. if (Type == ConstantRange::Unsigned) {
  350. if (!CR1.isWrappedSet() && CR2.isWrappedSet())
  351. return CR1;
  352. if (CR1.isWrappedSet() && !CR2.isWrappedSet())
  353. return CR2;
  354. } else if (Type == ConstantRange::Signed) {
  355. if (!CR1.isSignWrappedSet() && CR2.isSignWrappedSet())
  356. return CR1;
  357. if (CR1.isSignWrappedSet() && !CR2.isSignWrappedSet())
  358. return CR2;
  359. }
  360. if (CR1.isSizeStrictlySmallerThan(CR2))
  361. return CR1;
  362. return CR2;
  363. }
  364. ConstantRange ConstantRange::intersectWith(const ConstantRange &CR,
  365. PreferredRangeType Type) const {
  366. assert(getBitWidth() == CR.getBitWidth() &&
  367. "ConstantRange types don't agree!");
  368. // Handle common cases.
  369. if ( isEmptySet() || CR.isFullSet()) return *this;
  370. if (CR.isEmptySet() || isFullSet()) return CR;
  371. if (!isUpperWrapped() && CR.isUpperWrapped())
  372. return CR.intersectWith(*this, Type);
  373. if (!isUpperWrapped() && !CR.isUpperWrapped()) {
  374. if (Lower.ult(CR.Lower)) {
  375. // L---U : this
  376. // L---U : CR
  377. if (Upper.ule(CR.Lower))
  378. return getEmpty();
  379. // L---U : this
  380. // L---U : CR
  381. if (Upper.ult(CR.Upper))
  382. return ConstantRange(CR.Lower, Upper);
  383. // L-------U : this
  384. // L---U : CR
  385. return CR;
  386. }
  387. // L---U : this
  388. // L-------U : CR
  389. if (Upper.ult(CR.Upper))
  390. return *this;
  391. // L-----U : this
  392. // L-----U : CR
  393. if (Lower.ult(CR.Upper))
  394. return ConstantRange(Lower, CR.Upper);
  395. // L---U : this
  396. // L---U : CR
  397. return getEmpty();
  398. }
  399. if (isUpperWrapped() && !CR.isUpperWrapped()) {
  400. if (CR.Lower.ult(Upper)) {
  401. // ------U L--- : this
  402. // L--U : CR
  403. if (CR.Upper.ult(Upper))
  404. return CR;
  405. // ------U L--- : this
  406. // L------U : CR
  407. if (CR.Upper.ule(Lower))
  408. return ConstantRange(CR.Lower, Upper);
  409. // ------U L--- : this
  410. // L----------U : CR
  411. return getPreferredRange(*this, CR, Type);
  412. }
  413. if (CR.Lower.ult(Lower)) {
  414. // --U L---- : this
  415. // L--U : CR
  416. if (CR.Upper.ule(Lower))
  417. return getEmpty();
  418. // --U L---- : this
  419. // L------U : CR
  420. return ConstantRange(Lower, CR.Upper);
  421. }
  422. // --U L------ : this
  423. // L--U : CR
  424. return CR;
  425. }
  426. if (CR.Upper.ult(Upper)) {
  427. // ------U L-- : this
  428. // --U L------ : CR
  429. if (CR.Lower.ult(Upper))
  430. return getPreferredRange(*this, CR, Type);
  431. // ----U L-- : this
  432. // --U L---- : CR
  433. if (CR.Lower.ult(Lower))
  434. return ConstantRange(Lower, CR.Upper);
  435. // ----U L---- : this
  436. // --U L-- : CR
  437. return CR;
  438. }
  439. if (CR.Upper.ule(Lower)) {
  440. // --U L-- : this
  441. // ----U L---- : CR
  442. if (CR.Lower.ult(Lower))
  443. return *this;
  444. // --U L---- : this
  445. // ----U L-- : CR
  446. return ConstantRange(CR.Lower, Upper);
  447. }
  448. // --U L------ : this
  449. // ------U L-- : CR
  450. return getPreferredRange(*this, CR, Type);
  451. }
  452. ConstantRange ConstantRange::unionWith(const ConstantRange &CR,
  453. PreferredRangeType Type) const {
  454. assert(getBitWidth() == CR.getBitWidth() &&
  455. "ConstantRange types don't agree!");
  456. if ( isFullSet() || CR.isEmptySet()) return *this;
  457. if (CR.isFullSet() || isEmptySet()) return CR;
  458. if (!isUpperWrapped() && CR.isUpperWrapped())
  459. return CR.unionWith(*this, Type);
  460. if (!isUpperWrapped() && !CR.isUpperWrapped()) {
  461. // L---U and L---U : this
  462. // L---U L---U : CR
  463. // result in one of
  464. // L---------U
  465. // -----U L-----
  466. if (CR.Upper.ult(Lower) || Upper.ult(CR.Lower))
  467. return getPreferredRange(
  468. ConstantRange(Lower, CR.Upper), ConstantRange(CR.Lower, Upper), Type);
  469. APInt L = CR.Lower.ult(Lower) ? CR.Lower : Lower;
  470. APInt U = (CR.Upper - 1).ugt(Upper - 1) ? CR.Upper : Upper;
  471. if (L.isNullValue() && U.isNullValue())
  472. return getFull();
  473. return ConstantRange(std::move(L), std::move(U));
  474. }
  475. if (!CR.isUpperWrapped()) {
  476. // ------U L----- and ------U L----- : this
  477. // L--U L--U : CR
  478. if (CR.Upper.ule(Upper) || CR.Lower.uge(Lower))
  479. return *this;
  480. // ------U L----- : this
  481. // L---------U : CR
  482. if (CR.Lower.ule(Upper) && Lower.ule(CR.Upper))
  483. return getFull();
  484. // ----U L---- : this
  485. // L---U : CR
  486. // results in one of
  487. // ----------U L----
  488. // ----U L----------
  489. if (Upper.ult(CR.Lower) && CR.Upper.ult(Lower))
  490. return getPreferredRange(
  491. ConstantRange(Lower, CR.Upper), ConstantRange(CR.Lower, Upper), Type);
  492. // ----U L----- : this
  493. // L----U : CR
  494. if (Upper.ult(CR.Lower) && Lower.ule(CR.Upper))
  495. return ConstantRange(CR.Lower, Upper);
  496. // ------U L---- : this
  497. // L-----U : CR
  498. assert(CR.Lower.ule(Upper) && CR.Upper.ult(Lower) &&
  499. "ConstantRange::unionWith missed a case with one range wrapped");
  500. return ConstantRange(Lower, CR.Upper);
  501. }
  502. // ------U L---- and ------U L---- : this
  503. // -U L----------- and ------------U L : CR
  504. if (CR.Lower.ule(Upper) || Lower.ule(CR.Upper))
  505. return getFull();
  506. APInt L = CR.Lower.ult(Lower) ? CR.Lower : Lower;
  507. APInt U = CR.Upper.ugt(Upper) ? CR.Upper : Upper;
  508. return ConstantRange(std::move(L), std::move(U));
  509. }
  510. ConstantRange ConstantRange::castOp(Instruction::CastOps CastOp,
  511. uint32_t ResultBitWidth) const {
  512. switch (CastOp) {
  513. default:
  514. llvm_unreachable("unsupported cast type");
  515. case Instruction::Trunc:
  516. return truncate(ResultBitWidth);
  517. case Instruction::SExt:
  518. return signExtend(ResultBitWidth);
  519. case Instruction::ZExt:
  520. return zeroExtend(ResultBitWidth);
  521. case Instruction::BitCast:
  522. return *this;
  523. case Instruction::FPToUI:
  524. case Instruction::FPToSI:
  525. if (getBitWidth() == ResultBitWidth)
  526. return *this;
  527. else
  528. return getFull();
  529. case Instruction::UIToFP: {
  530. // TODO: use input range if available
  531. auto BW = getBitWidth();
  532. APInt Min = APInt::getMinValue(BW).zextOrSelf(ResultBitWidth);
  533. APInt Max = APInt::getMaxValue(BW).zextOrSelf(ResultBitWidth);
  534. return ConstantRange(std::move(Min), std::move(Max));
  535. }
  536. case Instruction::SIToFP: {
  537. // TODO: use input range if available
  538. auto BW = getBitWidth();
  539. APInt SMin = APInt::getSignedMinValue(BW).sextOrSelf(ResultBitWidth);
  540. APInt SMax = APInt::getSignedMaxValue(BW).sextOrSelf(ResultBitWidth);
  541. return ConstantRange(std::move(SMin), std::move(SMax));
  542. }
  543. case Instruction::FPTrunc:
  544. case Instruction::FPExt:
  545. case Instruction::IntToPtr:
  546. case Instruction::PtrToInt:
  547. case Instruction::AddrSpaceCast:
  548. // Conservatively return getFull set.
  549. return getFull();
  550. };
  551. }
  552. ConstantRange ConstantRange::zeroExtend(uint32_t DstTySize) const {
  553. if (isEmptySet()) return getEmpty(DstTySize);
  554. unsigned SrcTySize = getBitWidth();
  555. assert(SrcTySize < DstTySize && "Not a value extension");
  556. if (isFullSet() || isUpperWrapped()) {
  557. // Change into [0, 1 << src bit width)
  558. APInt LowerExt(DstTySize, 0);
  559. if (!Upper) // special case: [X, 0) -- not really wrapping around
  560. LowerExt = Lower.zext(DstTySize);
  561. return ConstantRange(std::move(LowerExt),
  562. APInt::getOneBitSet(DstTySize, SrcTySize));
  563. }
  564. return ConstantRange(Lower.zext(DstTySize), Upper.zext(DstTySize));
  565. }
  566. ConstantRange ConstantRange::signExtend(uint32_t DstTySize) const {
  567. if (isEmptySet()) return getEmpty(DstTySize);
  568. unsigned SrcTySize = getBitWidth();
  569. assert(SrcTySize < DstTySize && "Not a value extension");
  570. // special case: [X, INT_MIN) -- not really wrapping around
  571. if (Upper.isMinSignedValue())
  572. return ConstantRange(Lower.sext(DstTySize), Upper.zext(DstTySize));
  573. if (isFullSet() || isSignWrappedSet()) {
  574. return ConstantRange(APInt::getHighBitsSet(DstTySize,DstTySize-SrcTySize+1),
  575. APInt::getLowBitsSet(DstTySize, SrcTySize-1) + 1);
  576. }
  577. return ConstantRange(Lower.sext(DstTySize), Upper.sext(DstTySize));
  578. }
  579. ConstantRange ConstantRange::truncate(uint32_t DstTySize) const {
  580. assert(getBitWidth() > DstTySize && "Not a value truncation");
  581. if (isEmptySet())
  582. return getEmpty(DstTySize);
  583. if (isFullSet())
  584. return getFull(DstTySize);
  585. APInt LowerDiv(Lower), UpperDiv(Upper);
  586. ConstantRange Union(DstTySize, /*isFullSet=*/false);
  587. // Analyze wrapped sets in their two parts: [0, Upper) \/ [Lower, MaxValue]
  588. // We use the non-wrapped set code to analyze the [Lower, MaxValue) part, and
  589. // then we do the union with [MaxValue, Upper)
  590. if (isUpperWrapped()) {
  591. // If Upper is greater than or equal to MaxValue(DstTy), it covers the whole
  592. // truncated range.
  593. if (Upper.getActiveBits() > DstTySize ||
  594. Upper.countTrailingOnes() == DstTySize)
  595. return getFull(DstTySize);
  596. Union = ConstantRange(APInt::getMaxValue(DstTySize),Upper.trunc(DstTySize));
  597. UpperDiv.setAllBits();
  598. // Union covers the MaxValue case, so return if the remaining range is just
  599. // MaxValue(DstTy).
  600. if (LowerDiv == UpperDiv)
  601. return Union;
  602. }
  603. // Chop off the most significant bits that are past the destination bitwidth.
  604. if (LowerDiv.getActiveBits() > DstTySize) {
  605. // Mask to just the signficant bits and subtract from LowerDiv/UpperDiv.
  606. APInt Adjust = LowerDiv & APInt::getBitsSetFrom(getBitWidth(), DstTySize);
  607. LowerDiv -= Adjust;
  608. UpperDiv -= Adjust;
  609. }
  610. unsigned UpperDivWidth = UpperDiv.getActiveBits();
  611. if (UpperDivWidth <= DstTySize)
  612. return ConstantRange(LowerDiv.trunc(DstTySize),
  613. UpperDiv.trunc(DstTySize)).unionWith(Union);
  614. // The truncated value wraps around. Check if we can do better than fullset.
  615. if (UpperDivWidth == DstTySize + 1) {
  616. // Clear the MSB so that UpperDiv wraps around.
  617. UpperDiv.clearBit(DstTySize);
  618. if (UpperDiv.ult(LowerDiv))
  619. return ConstantRange(LowerDiv.trunc(DstTySize),
  620. UpperDiv.trunc(DstTySize)).unionWith(Union);
  621. }
  622. return getFull(DstTySize);
  623. }
  624. ConstantRange ConstantRange::zextOrTrunc(uint32_t DstTySize) const {
  625. unsigned SrcTySize = getBitWidth();
  626. if (SrcTySize > DstTySize)
  627. return truncate(DstTySize);
  628. if (SrcTySize < DstTySize)
  629. return zeroExtend(DstTySize);
  630. return *this;
  631. }
  632. ConstantRange ConstantRange::sextOrTrunc(uint32_t DstTySize) const {
  633. unsigned SrcTySize = getBitWidth();
  634. if (SrcTySize > DstTySize)
  635. return truncate(DstTySize);
  636. if (SrcTySize < DstTySize)
  637. return signExtend(DstTySize);
  638. return *this;
  639. }
  640. ConstantRange ConstantRange::binaryOp(Instruction::BinaryOps BinOp,
  641. const ConstantRange &Other) const {
  642. assert(Instruction::isBinaryOp(BinOp) && "Binary operators only!");
  643. switch (BinOp) {
  644. case Instruction::Add:
  645. return add(Other);
  646. case Instruction::Sub:
  647. return sub(Other);
  648. case Instruction::Mul:
  649. return multiply(Other);
  650. case Instruction::UDiv:
  651. return udiv(Other);
  652. case Instruction::SDiv:
  653. return sdiv(Other);
  654. case Instruction::URem:
  655. return urem(Other);
  656. case Instruction::SRem:
  657. return srem(Other);
  658. case Instruction::Shl:
  659. return shl(Other);
  660. case Instruction::LShr:
  661. return lshr(Other);
  662. case Instruction::AShr:
  663. return ashr(Other);
  664. case Instruction::And:
  665. return binaryAnd(Other);
  666. case Instruction::Or:
  667. return binaryOr(Other);
  668. // Note: floating point operations applied to abstract ranges are just
  669. // ideal integer operations with a lossy representation
  670. case Instruction::FAdd:
  671. return add(Other);
  672. case Instruction::FSub:
  673. return sub(Other);
  674. case Instruction::FMul:
  675. return multiply(Other);
  676. default:
  677. // Conservatively return getFull set.
  678. return getFull();
  679. }
  680. }
  681. ConstantRange
  682. ConstantRange::add(const ConstantRange &Other) const {
  683. if (isEmptySet() || Other.isEmptySet())
  684. return getEmpty();
  685. if (isFullSet() || Other.isFullSet())
  686. return getFull();
  687. APInt NewLower = getLower() + Other.getLower();
  688. APInt NewUpper = getUpper() + Other.getUpper() - 1;
  689. if (NewLower == NewUpper)
  690. return getFull();
  691. ConstantRange X = ConstantRange(std::move(NewLower), std::move(NewUpper));
  692. if (X.isSizeStrictlySmallerThan(*this) ||
  693. X.isSizeStrictlySmallerThan(Other))
  694. // We've wrapped, therefore, full set.
  695. return getFull();
  696. return X;
  697. }
  698. ConstantRange ConstantRange::addWithNoSignedWrap(const APInt &Other) const {
  699. // Calculate the subset of this range such that "X + Other" is
  700. // guaranteed not to wrap (overflow) for all X in this subset.
  701. auto NSWRange = ConstantRange::makeExactNoWrapRegion(
  702. BinaryOperator::Add, Other, OverflowingBinaryOperator::NoSignedWrap);
  703. auto NSWConstrainedRange = intersectWith(NSWRange);
  704. return NSWConstrainedRange.add(ConstantRange(Other));
  705. }
  706. ConstantRange
  707. ConstantRange::sub(const ConstantRange &Other) const {
  708. if (isEmptySet() || Other.isEmptySet())
  709. return getEmpty();
  710. if (isFullSet() || Other.isFullSet())
  711. return getFull();
  712. APInt NewLower = getLower() - Other.getUpper() + 1;
  713. APInt NewUpper = getUpper() - Other.getLower();
  714. if (NewLower == NewUpper)
  715. return getFull();
  716. ConstantRange X = ConstantRange(std::move(NewLower), std::move(NewUpper));
  717. if (X.isSizeStrictlySmallerThan(*this) ||
  718. X.isSizeStrictlySmallerThan(Other))
  719. // We've wrapped, therefore, full set.
  720. return getFull();
  721. return X;
  722. }
  723. ConstantRange
  724. ConstantRange::multiply(const ConstantRange &Other) const {
  725. // TODO: If either operand is a single element and the multiply is known to
  726. // be non-wrapping, round the result min and max value to the appropriate
  727. // multiple of that element. If wrapping is possible, at least adjust the
  728. // range according to the greatest power-of-two factor of the single element.
  729. if (isEmptySet() || Other.isEmptySet())
  730. return getEmpty();
  731. // Multiplication is signedness-independent. However different ranges can be
  732. // obtained depending on how the input ranges are treated. These different
  733. // ranges are all conservatively correct, but one might be better than the
  734. // other. We calculate two ranges; one treating the inputs as unsigned
  735. // and the other signed, then return the smallest of these ranges.
  736. // Unsigned range first.
  737. APInt this_min = getUnsignedMin().zext(getBitWidth() * 2);
  738. APInt this_max = getUnsignedMax().zext(getBitWidth() * 2);
  739. APInt Other_min = Other.getUnsignedMin().zext(getBitWidth() * 2);
  740. APInt Other_max = Other.getUnsignedMax().zext(getBitWidth() * 2);
  741. ConstantRange Result_zext = ConstantRange(this_min * Other_min,
  742. this_max * Other_max + 1);
  743. ConstantRange UR = Result_zext.truncate(getBitWidth());
  744. // If the unsigned range doesn't wrap, and isn't negative then it's a range
  745. // from one positive number to another which is as good as we can generate.
  746. // In this case, skip the extra work of generating signed ranges which aren't
  747. // going to be better than this range.
  748. if (!UR.isUpperWrapped() &&
  749. (UR.getUpper().isNonNegative() || UR.getUpper().isMinSignedValue()))
  750. return UR;
  751. // Now the signed range. Because we could be dealing with negative numbers
  752. // here, the lower bound is the smallest of the cartesian product of the
  753. // lower and upper ranges; for example:
  754. // [-1,4) * [-2,3) = min(-1*-2, -1*2, 3*-2, 3*2) = -6.
  755. // Similarly for the upper bound, swapping min for max.
  756. this_min = getSignedMin().sext(getBitWidth() * 2);
  757. this_max = getSignedMax().sext(getBitWidth() * 2);
  758. Other_min = Other.getSignedMin().sext(getBitWidth() * 2);
  759. Other_max = Other.getSignedMax().sext(getBitWidth() * 2);
  760. auto L = {this_min * Other_min, this_min * Other_max,
  761. this_max * Other_min, this_max * Other_max};
  762. auto Compare = [](const APInt &A, const APInt &B) { return A.slt(B); };
  763. ConstantRange Result_sext(std::min(L, Compare), std::max(L, Compare) + 1);
  764. ConstantRange SR = Result_sext.truncate(getBitWidth());
  765. return UR.isSizeStrictlySmallerThan(SR) ? UR : SR;
  766. }
  767. ConstantRange
  768. ConstantRange::smax(const ConstantRange &Other) const {
  769. // X smax Y is: range(smax(X_smin, Y_smin),
  770. // smax(X_smax, Y_smax))
  771. if (isEmptySet() || Other.isEmptySet())
  772. return getEmpty();
  773. APInt NewL = APIntOps::smax(getSignedMin(), Other.getSignedMin());
  774. APInt NewU = APIntOps::smax(getSignedMax(), Other.getSignedMax()) + 1;
  775. return getNonEmpty(std::move(NewL), std::move(NewU));
  776. }
  777. ConstantRange
  778. ConstantRange::umax(const ConstantRange &Other) const {
  779. // X umax Y is: range(umax(X_umin, Y_umin),
  780. // umax(X_umax, Y_umax))
  781. if (isEmptySet() || Other.isEmptySet())
  782. return getEmpty();
  783. APInt NewL = APIntOps::umax(getUnsignedMin(), Other.getUnsignedMin());
  784. APInt NewU = APIntOps::umax(getUnsignedMax(), Other.getUnsignedMax()) + 1;
  785. return getNonEmpty(std::move(NewL), std::move(NewU));
  786. }
  787. ConstantRange
  788. ConstantRange::smin(const ConstantRange &Other) const {
  789. // X smin Y is: range(smin(X_smin, Y_smin),
  790. // smin(X_smax, Y_smax))
  791. if (isEmptySet() || Other.isEmptySet())
  792. return getEmpty();
  793. APInt NewL = APIntOps::smin(getSignedMin(), Other.getSignedMin());
  794. APInt NewU = APIntOps::smin(getSignedMax(), Other.getSignedMax()) + 1;
  795. return getNonEmpty(std::move(NewL), std::move(NewU));
  796. }
  797. ConstantRange
  798. ConstantRange::umin(const ConstantRange &Other) const {
  799. // X umin Y is: range(umin(X_umin, Y_umin),
  800. // umin(X_umax, Y_umax))
  801. if (isEmptySet() || Other.isEmptySet())
  802. return getEmpty();
  803. APInt NewL = APIntOps::umin(getUnsignedMin(), Other.getUnsignedMin());
  804. APInt NewU = APIntOps::umin(getUnsignedMax(), Other.getUnsignedMax()) + 1;
  805. return getNonEmpty(std::move(NewL), std::move(NewU));
  806. }
  807. ConstantRange
  808. ConstantRange::udiv(const ConstantRange &RHS) const {
  809. if (isEmptySet() || RHS.isEmptySet() || RHS.getUnsignedMax().isNullValue())
  810. return getEmpty();
  811. APInt Lower = getUnsignedMin().udiv(RHS.getUnsignedMax());
  812. APInt RHS_umin = RHS.getUnsignedMin();
  813. if (RHS_umin.isNullValue()) {
  814. // We want the lowest value in RHS excluding zero. Usually that would be 1
  815. // except for a range in the form of [X, 1) in which case it would be X.
  816. if (RHS.getUpper() == 1)
  817. RHS_umin = RHS.getLower();
  818. else
  819. RHS_umin = 1;
  820. }
  821. APInt Upper = getUnsignedMax().udiv(RHS_umin) + 1;
  822. return getNonEmpty(std::move(Lower), std::move(Upper));
  823. }
  824. ConstantRange ConstantRange::sdiv(const ConstantRange &RHS) const {
  825. // We split up the LHS and RHS into positive and negative components
  826. // and then also compute the positive and negative components of the result
  827. // separately by combining division results with the appropriate signs.
  828. APInt Zero = APInt::getNullValue(getBitWidth());
  829. APInt SignedMin = APInt::getSignedMinValue(getBitWidth());
  830. ConstantRange PosFilter(APInt(getBitWidth(), 1), SignedMin);
  831. ConstantRange NegFilter(SignedMin, Zero);
  832. ConstantRange PosL = intersectWith(PosFilter);
  833. ConstantRange NegL = intersectWith(NegFilter);
  834. ConstantRange PosR = RHS.intersectWith(PosFilter);
  835. ConstantRange NegR = RHS.intersectWith(NegFilter);
  836. ConstantRange PosRes = getEmpty();
  837. if (!PosL.isEmptySet() && !PosR.isEmptySet())
  838. // pos / pos = pos.
  839. PosRes = ConstantRange(PosL.Lower.sdiv(PosR.Upper - 1),
  840. (PosL.Upper - 1).sdiv(PosR.Lower) + 1);
  841. if (!NegL.isEmptySet() && !NegR.isEmptySet()) {
  842. // neg / neg = pos.
  843. //
  844. // We need to deal with one tricky case here: SignedMin / -1 is UB on the
  845. // IR level, so we'll want to exclude this case when calculating bounds.
  846. // (For APInts the operation is well-defined and yields SignedMin.) We
  847. // handle this by dropping either SignedMin from the LHS or -1 from the RHS.
  848. APInt Lo = (NegL.Upper - 1).sdiv(NegR.Lower);
  849. if (NegL.Lower.isMinSignedValue() && NegR.Upper.isNullValue()) {
  850. // Remove -1 from the LHS. Skip if it's the only element, as this would
  851. // leave us with an empty set.
  852. if (!NegR.Lower.isAllOnesValue()) {
  853. APInt AdjNegRUpper;
  854. if (RHS.Lower.isAllOnesValue())
  855. // Negative part of [-1, X] without -1 is [SignedMin, X].
  856. AdjNegRUpper = RHS.Upper;
  857. else
  858. // [X, -1] without -1 is [X, -2].
  859. AdjNegRUpper = NegR.Upper - 1;
  860. PosRes = PosRes.unionWith(
  861. ConstantRange(Lo, NegL.Lower.sdiv(AdjNegRUpper - 1) + 1));
  862. }
  863. // Remove SignedMin from the RHS. Skip if it's the only element, as this
  864. // would leave us with an empty set.
  865. if (NegL.Upper != SignedMin + 1) {
  866. APInt AdjNegLLower;
  867. if (Upper == SignedMin + 1)
  868. // Negative part of [X, SignedMin] without SignedMin is [X, -1].
  869. AdjNegLLower = Lower;
  870. else
  871. // [SignedMin, X] without SignedMin is [SignedMin + 1, X].
  872. AdjNegLLower = NegL.Lower + 1;
  873. PosRes = PosRes.unionWith(
  874. ConstantRange(std::move(Lo),
  875. AdjNegLLower.sdiv(NegR.Upper - 1) + 1));
  876. }
  877. } else {
  878. PosRes = PosRes.unionWith(
  879. ConstantRange(std::move(Lo), NegL.Lower.sdiv(NegR.Upper - 1) + 1));
  880. }
  881. }
  882. ConstantRange NegRes = getEmpty();
  883. if (!PosL.isEmptySet() && !NegR.isEmptySet())
  884. // pos / neg = neg.
  885. NegRes = ConstantRange((PosL.Upper - 1).sdiv(NegR.Upper - 1),
  886. PosL.Lower.sdiv(NegR.Lower) + 1);
  887. if (!NegL.isEmptySet() && !PosR.isEmptySet())
  888. // neg / pos = neg.
  889. NegRes = NegRes.unionWith(
  890. ConstantRange(NegL.Lower.sdiv(PosR.Lower),
  891. (NegL.Upper - 1).sdiv(PosR.Upper - 1) + 1));
  892. // Prefer a non-wrapping signed range here.
  893. ConstantRange Res = NegRes.unionWith(PosRes, PreferredRangeType::Signed);
  894. // Preserve the zero that we dropped when splitting the LHS by sign.
  895. if (contains(Zero) && (!PosR.isEmptySet() || !NegR.isEmptySet()))
  896. Res = Res.unionWith(ConstantRange(Zero));
  897. return Res;
  898. }
  899. ConstantRange ConstantRange::urem(const ConstantRange &RHS) const {
  900. if (isEmptySet() || RHS.isEmptySet() || RHS.getUnsignedMax().isNullValue())
  901. return getEmpty();
  902. // L % R for L < R is L.
  903. if (getUnsignedMax().ult(RHS.getUnsignedMin()))
  904. return *this;
  905. // L % R is <= L and < R.
  906. APInt Upper = APIntOps::umin(getUnsignedMax(), RHS.getUnsignedMax() - 1) + 1;
  907. return getNonEmpty(APInt::getNullValue(getBitWidth()), std::move(Upper));
  908. }
  909. ConstantRange ConstantRange::srem(const ConstantRange &RHS) const {
  910. if (isEmptySet() || RHS.isEmptySet())
  911. return getEmpty();
  912. ConstantRange AbsRHS = RHS.abs();
  913. APInt MinAbsRHS = AbsRHS.getUnsignedMin();
  914. APInt MaxAbsRHS = AbsRHS.getUnsignedMax();
  915. // Modulus by zero is UB.
  916. if (MaxAbsRHS.isNullValue())
  917. return getEmpty();
  918. if (MinAbsRHS.isNullValue())
  919. ++MinAbsRHS;
  920. APInt MinLHS = getSignedMin(), MaxLHS = getSignedMax();
  921. if (MinLHS.isNonNegative()) {
  922. // L % R for L < R is L.
  923. if (MaxLHS.ult(MinAbsRHS))
  924. return *this;
  925. // L % R is <= L and < R.
  926. APInt Upper = APIntOps::umin(MaxLHS, MaxAbsRHS - 1) + 1;
  927. return ConstantRange(APInt::getNullValue(getBitWidth()), std::move(Upper));
  928. }
  929. // Same basic logic as above, but the result is negative.
  930. if (MaxLHS.isNegative()) {
  931. if (MinLHS.ugt(-MinAbsRHS))
  932. return *this;
  933. APInt Lower = APIntOps::umax(MinLHS, -MaxAbsRHS + 1);
  934. return ConstantRange(std::move(Lower), APInt(getBitWidth(), 1));
  935. }
  936. // LHS range crosses zero.
  937. APInt Lower = APIntOps::umax(MinLHS, -MaxAbsRHS + 1);
  938. APInt Upper = APIntOps::umin(MaxLHS, MaxAbsRHS - 1) + 1;
  939. return ConstantRange(std::move(Lower), std::move(Upper));
  940. }
  941. ConstantRange
  942. ConstantRange::binaryAnd(const ConstantRange &Other) const {
  943. if (isEmptySet() || Other.isEmptySet())
  944. return getEmpty();
  945. // TODO: replace this with something less conservative
  946. APInt umin = APIntOps::umin(Other.getUnsignedMax(), getUnsignedMax());
  947. return getNonEmpty(APInt::getNullValue(getBitWidth()), std::move(umin) + 1);
  948. }
  949. ConstantRange
  950. ConstantRange::binaryOr(const ConstantRange &Other) const {
  951. if (isEmptySet() || Other.isEmptySet())
  952. return getEmpty();
  953. // TODO: replace this with something less conservative
  954. APInt umax = APIntOps::umax(getUnsignedMin(), Other.getUnsignedMin());
  955. return getNonEmpty(std::move(umax), APInt::getNullValue(getBitWidth()));
  956. }
  957. ConstantRange
  958. ConstantRange::shl(const ConstantRange &Other) const {
  959. if (isEmptySet() || Other.isEmptySet())
  960. return getEmpty();
  961. APInt max = getUnsignedMax();
  962. APInt Other_umax = Other.getUnsignedMax();
  963. // If we are shifting by maximum amount of
  964. // zero return return the original range.
  965. if (Other_umax.isNullValue())
  966. return *this;
  967. // there's overflow!
  968. if (Other_umax.ugt(max.countLeadingZeros()))
  969. return getFull();
  970. // FIXME: implement the other tricky cases
  971. APInt min = getUnsignedMin();
  972. min <<= Other.getUnsignedMin();
  973. max <<= Other_umax;
  974. return ConstantRange(std::move(min), std::move(max) + 1);
  975. }
  976. ConstantRange
  977. ConstantRange::lshr(const ConstantRange &Other) const {
  978. if (isEmptySet() || Other.isEmptySet())
  979. return getEmpty();
  980. APInt max = getUnsignedMax().lshr(Other.getUnsignedMin()) + 1;
  981. APInt min = getUnsignedMin().lshr(Other.getUnsignedMax());
  982. return getNonEmpty(std::move(min), std::move(max));
  983. }
  984. ConstantRange
  985. ConstantRange::ashr(const ConstantRange &Other) const {
  986. if (isEmptySet() || Other.isEmptySet())
  987. return getEmpty();
  988. // May straddle zero, so handle both positive and negative cases.
  989. // 'PosMax' is the upper bound of the result of the ashr
  990. // operation, when Upper of the LHS of ashr is a non-negative.
  991. // number. Since ashr of a non-negative number will result in a
  992. // smaller number, the Upper value of LHS is shifted right with
  993. // the minimum value of 'Other' instead of the maximum value.
  994. APInt PosMax = getSignedMax().ashr(Other.getUnsignedMin()) + 1;
  995. // 'PosMin' is the lower bound of the result of the ashr
  996. // operation, when Lower of the LHS is a non-negative number.
  997. // Since ashr of a non-negative number will result in a smaller
  998. // number, the Lower value of LHS is shifted right with the
  999. // maximum value of 'Other'.
  1000. APInt PosMin = getSignedMin().ashr(Other.getUnsignedMax());
  1001. // 'NegMax' is the upper bound of the result of the ashr
  1002. // operation, when Upper of the LHS of ashr is a negative number.
  1003. // Since 'ashr' of a negative number will result in a bigger
  1004. // number, the Upper value of LHS is shifted right with the
  1005. // maximum value of 'Other'.
  1006. APInt NegMax = getSignedMax().ashr(Other.getUnsignedMax()) + 1;
  1007. // 'NegMin' is the lower bound of the result of the ashr
  1008. // operation, when Lower of the LHS of ashr is a negative number.
  1009. // Since 'ashr' of a negative number will result in a bigger
  1010. // number, the Lower value of LHS is shifted right with the
  1011. // minimum value of 'Other'.
  1012. APInt NegMin = getSignedMin().ashr(Other.getUnsignedMin());
  1013. APInt max, min;
  1014. if (getSignedMin().isNonNegative()) {
  1015. // Upper and Lower of LHS are non-negative.
  1016. min = PosMin;
  1017. max = PosMax;
  1018. } else if (getSignedMax().isNegative()) {
  1019. // Upper and Lower of LHS are negative.
  1020. min = NegMin;
  1021. max = NegMax;
  1022. } else {
  1023. // Upper is non-negative and Lower is negative.
  1024. min = NegMin;
  1025. max = PosMax;
  1026. }
  1027. return getNonEmpty(std::move(min), std::move(max));
  1028. }
  1029. ConstantRange ConstantRange::uadd_sat(const ConstantRange &Other) const {
  1030. if (isEmptySet() || Other.isEmptySet())
  1031. return getEmpty();
  1032. APInt NewL = getUnsignedMin().uadd_sat(Other.getUnsignedMin());
  1033. APInt NewU = getUnsignedMax().uadd_sat(Other.getUnsignedMax()) + 1;
  1034. return getNonEmpty(std::move(NewL), std::move(NewU));
  1035. }
  1036. ConstantRange ConstantRange::sadd_sat(const ConstantRange &Other) const {
  1037. if (isEmptySet() || Other.isEmptySet())
  1038. return getEmpty();
  1039. APInt NewL = getSignedMin().sadd_sat(Other.getSignedMin());
  1040. APInt NewU = getSignedMax().sadd_sat(Other.getSignedMax()) + 1;
  1041. return getNonEmpty(std::move(NewL), std::move(NewU));
  1042. }
  1043. ConstantRange ConstantRange::usub_sat(const ConstantRange &Other) const {
  1044. if (isEmptySet() || Other.isEmptySet())
  1045. return getEmpty();
  1046. APInt NewL = getUnsignedMin().usub_sat(Other.getUnsignedMax());
  1047. APInt NewU = getUnsignedMax().usub_sat(Other.getUnsignedMin()) + 1;
  1048. return getNonEmpty(std::move(NewL), std::move(NewU));
  1049. }
  1050. ConstantRange ConstantRange::ssub_sat(const ConstantRange &Other) const {
  1051. if (isEmptySet() || Other.isEmptySet())
  1052. return getEmpty();
  1053. APInt NewL = getSignedMin().ssub_sat(Other.getSignedMax());
  1054. APInt NewU = getSignedMax().ssub_sat(Other.getSignedMin()) + 1;
  1055. return getNonEmpty(std::move(NewL), std::move(NewU));
  1056. }
  1057. ConstantRange ConstantRange::inverse() const {
  1058. if (isFullSet())
  1059. return getEmpty();
  1060. if (isEmptySet())
  1061. return getFull();
  1062. return ConstantRange(Upper, Lower);
  1063. }
  1064. ConstantRange ConstantRange::abs() const {
  1065. if (isEmptySet())
  1066. return getEmpty();
  1067. if (isSignWrappedSet()) {
  1068. APInt Lo;
  1069. // Check whether the range crosses zero.
  1070. if (Upper.isStrictlyPositive() || !Lower.isStrictlyPositive())
  1071. Lo = APInt::getNullValue(getBitWidth());
  1072. else
  1073. Lo = APIntOps::umin(Lower, -Upper + 1);
  1074. // SignedMin is included in the result range.
  1075. return ConstantRange(Lo, APInt::getSignedMinValue(getBitWidth()) + 1);
  1076. }
  1077. APInt SMin = getSignedMin(), SMax = getSignedMax();
  1078. // All non-negative.
  1079. if (SMin.isNonNegative())
  1080. return *this;
  1081. // All negative.
  1082. if (SMax.isNegative())
  1083. return ConstantRange(-SMax, -SMin + 1);
  1084. // Range crosses zero.
  1085. return ConstantRange(APInt::getNullValue(getBitWidth()),
  1086. APIntOps::umax(-SMin, SMax) + 1);
  1087. }
  1088. ConstantRange::OverflowResult ConstantRange::unsignedAddMayOverflow(
  1089. const ConstantRange &Other) const {
  1090. if (isEmptySet() || Other.isEmptySet())
  1091. return OverflowResult::MayOverflow;
  1092. APInt Min = getUnsignedMin(), Max = getUnsignedMax();
  1093. APInt OtherMin = Other.getUnsignedMin(), OtherMax = Other.getUnsignedMax();
  1094. // a u+ b overflows high iff a u> ~b.
  1095. if (Min.ugt(~OtherMin))
  1096. return OverflowResult::AlwaysOverflowsHigh;
  1097. if (Max.ugt(~OtherMax))
  1098. return OverflowResult::MayOverflow;
  1099. return OverflowResult::NeverOverflows;
  1100. }
  1101. ConstantRange::OverflowResult ConstantRange::signedAddMayOverflow(
  1102. const ConstantRange &Other) const {
  1103. if (isEmptySet() || Other.isEmptySet())
  1104. return OverflowResult::MayOverflow;
  1105. APInt Min = getSignedMin(), Max = getSignedMax();
  1106. APInt OtherMin = Other.getSignedMin(), OtherMax = Other.getSignedMax();
  1107. APInt SignedMin = APInt::getSignedMinValue(getBitWidth());
  1108. APInt SignedMax = APInt::getSignedMaxValue(getBitWidth());
  1109. // a s+ b overflows high iff a s>=0 && b s>= 0 && a s> smax - b.
  1110. // a s+ b overflows low iff a s< 0 && b s< 0 && a s< smin - b.
  1111. if (Min.isNonNegative() && OtherMin.isNonNegative() &&
  1112. Min.sgt(SignedMax - OtherMin))
  1113. return OverflowResult::AlwaysOverflowsHigh;
  1114. if (Max.isNegative() && OtherMax.isNegative() &&
  1115. Max.slt(SignedMin - OtherMax))
  1116. return OverflowResult::AlwaysOverflowsLow;
  1117. if (Max.isNonNegative() && OtherMax.isNonNegative() &&
  1118. Max.sgt(SignedMax - OtherMax))
  1119. return OverflowResult::MayOverflow;
  1120. if (Min.isNegative() && OtherMin.isNegative() &&
  1121. Min.slt(SignedMin - OtherMin))
  1122. return OverflowResult::MayOverflow;
  1123. return OverflowResult::NeverOverflows;
  1124. }
  1125. ConstantRange::OverflowResult ConstantRange::unsignedSubMayOverflow(
  1126. const ConstantRange &Other) const {
  1127. if (isEmptySet() || Other.isEmptySet())
  1128. return OverflowResult::MayOverflow;
  1129. APInt Min = getUnsignedMin(), Max = getUnsignedMax();
  1130. APInt OtherMin = Other.getUnsignedMin(), OtherMax = Other.getUnsignedMax();
  1131. // a u- b overflows low iff a u< b.
  1132. if (Max.ult(OtherMin))
  1133. return OverflowResult::AlwaysOverflowsLow;
  1134. if (Min.ult(OtherMax))
  1135. return OverflowResult::MayOverflow;
  1136. return OverflowResult::NeverOverflows;
  1137. }
  1138. ConstantRange::OverflowResult ConstantRange::signedSubMayOverflow(
  1139. const ConstantRange &Other) const {
  1140. if (isEmptySet() || Other.isEmptySet())
  1141. return OverflowResult::MayOverflow;
  1142. APInt Min = getSignedMin(), Max = getSignedMax();
  1143. APInt OtherMin = Other.getSignedMin(), OtherMax = Other.getSignedMax();
  1144. APInt SignedMin = APInt::getSignedMinValue(getBitWidth());
  1145. APInt SignedMax = APInt::getSignedMaxValue(getBitWidth());
  1146. // a s- b overflows high iff a s>=0 && b s< 0 && a s> smax + b.
  1147. // a s- b overflows low iff a s< 0 && b s>= 0 && a s< smin + b.
  1148. if (Min.isNonNegative() && OtherMax.isNegative() &&
  1149. Min.sgt(SignedMax + OtherMax))
  1150. return OverflowResult::AlwaysOverflowsHigh;
  1151. if (Max.isNegative() && OtherMin.isNonNegative() &&
  1152. Max.slt(SignedMin + OtherMin))
  1153. return OverflowResult::AlwaysOverflowsLow;
  1154. if (Max.isNonNegative() && OtherMin.isNegative() &&
  1155. Max.sgt(SignedMax + OtherMin))
  1156. return OverflowResult::MayOverflow;
  1157. if (Min.isNegative() && OtherMax.isNonNegative() &&
  1158. Min.slt(SignedMin + OtherMax))
  1159. return OverflowResult::MayOverflow;
  1160. return OverflowResult::NeverOverflows;
  1161. }
  1162. ConstantRange::OverflowResult ConstantRange::unsignedMulMayOverflow(
  1163. const ConstantRange &Other) const {
  1164. if (isEmptySet() || Other.isEmptySet())
  1165. return OverflowResult::MayOverflow;
  1166. APInt Min = getUnsignedMin(), Max = getUnsignedMax();
  1167. APInt OtherMin = Other.getUnsignedMin(), OtherMax = Other.getUnsignedMax();
  1168. bool Overflow;
  1169. (void) Min.umul_ov(OtherMin, Overflow);
  1170. if (Overflow)
  1171. return OverflowResult::AlwaysOverflowsHigh;
  1172. (void) Max.umul_ov(OtherMax, Overflow);
  1173. if (Overflow)
  1174. return OverflowResult::MayOverflow;
  1175. return OverflowResult::NeverOverflows;
  1176. }
  1177. void ConstantRange::print(raw_ostream &OS) const {
  1178. if (isFullSet())
  1179. OS << "full-set";
  1180. else if (isEmptySet())
  1181. OS << "empty-set";
  1182. else
  1183. OS << "[" << Lower << "," << Upper << ")";
  1184. }
  1185. #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
  1186. LLVM_DUMP_METHOD void ConstantRange::dump() const {
  1187. print(dbgs());
  1188. }
  1189. #endif
  1190. ConstantRange llvm::getConstantRangeFromMetadata(const MDNode &Ranges) {
  1191. const unsigned NumRanges = Ranges.getNumOperands() / 2;
  1192. assert(NumRanges >= 1 && "Must have at least one range!");
  1193. assert(Ranges.getNumOperands() % 2 == 0 && "Must be a sequence of pairs");
  1194. auto *FirstLow = mdconst::extract<ConstantInt>(Ranges.getOperand(0));
  1195. auto *FirstHigh = mdconst::extract<ConstantInt>(Ranges.getOperand(1));
  1196. ConstantRange CR(FirstLow->getValue(), FirstHigh->getValue());
  1197. for (unsigned i = 1; i < NumRanges; ++i) {
  1198. auto *Low = mdconst::extract<ConstantInt>(Ranges.getOperand(2 * i + 0));
  1199. auto *High = mdconst::extract<ConstantInt>(Ranges.getOperand(2 * i + 1));
  1200. // Note: unionWith will potentially create a range that contains values not
  1201. // contained in any of the original N ranges.
  1202. CR = CR.unionWith(ConstantRange(Low->getValue(), High->getValue()));
  1203. }
  1204. return CR;
  1205. }