ConstantRange.cpp 61 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797
  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/Intrinsics.h"
  29. #include "llvm/IR/Metadata.h"
  30. #include "llvm/IR/Operator.h"
  31. #include "llvm/Support/Compiler.h"
  32. #include "llvm/Support/Debug.h"
  33. #include "llvm/Support/ErrorHandling.h"
  34. #include "llvm/Support/KnownBits.h"
  35. #include "llvm/Support/raw_ostream.h"
  36. #include <algorithm>
  37. #include <cassert>
  38. #include <cstdint>
  39. using namespace llvm;
  40. ConstantRange::ConstantRange(uint32_t BitWidth, bool Full)
  41. : Lower(Full ? APInt::getMaxValue(BitWidth) : APInt::getMinValue(BitWidth)),
  42. Upper(Lower) {}
  43. ConstantRange::ConstantRange(APInt V)
  44. : Lower(std::move(V)), Upper(Lower + 1) {}
  45. ConstantRange::ConstantRange(APInt L, APInt U)
  46. : Lower(std::move(L)), Upper(std::move(U)) {
  47. assert(Lower.getBitWidth() == Upper.getBitWidth() &&
  48. "ConstantRange with unequal bit widths");
  49. assert((Lower != Upper || (Lower.isMaxValue() || Lower.isMinValue())) &&
  50. "Lower == Upper, but they aren't min or max value!");
  51. }
  52. ConstantRange ConstantRange::fromKnownBits(const KnownBits &Known,
  53. bool IsSigned) {
  54. assert(!Known.hasConflict() && "Expected valid KnownBits");
  55. if (Known.isUnknown())
  56. return getFull(Known.getBitWidth());
  57. // For unsigned ranges, or signed ranges with known sign bit, create a simple
  58. // range between the smallest and largest possible value.
  59. if (!IsSigned || Known.isNegative() || Known.isNonNegative())
  60. return ConstantRange(Known.getMinValue(), Known.getMaxValue() + 1);
  61. // If we don't know the sign bit, pick the lower bound as a negative number
  62. // and the upper bound as a non-negative one.
  63. APInt Lower = Known.getMinValue(), Upper = Known.getMaxValue();
  64. Lower.setSignBit();
  65. Upper.clearSignBit();
  66. return ConstantRange(Lower, Upper + 1);
  67. }
  68. ConstantRange ConstantRange::makeAllowedICmpRegion(CmpInst::Predicate Pred,
  69. const ConstantRange &CR) {
  70. if (CR.isEmptySet())
  71. return CR;
  72. uint32_t W = CR.getBitWidth();
  73. switch (Pred) {
  74. default:
  75. llvm_unreachable("Invalid ICmp predicate to makeAllowedICmpRegion()");
  76. case CmpInst::ICMP_EQ:
  77. return CR;
  78. case CmpInst::ICMP_NE:
  79. if (CR.isSingleElement())
  80. return ConstantRange(CR.getUpper(), CR.getLower());
  81. return getFull(W);
  82. case CmpInst::ICMP_ULT: {
  83. APInt UMax(CR.getUnsignedMax());
  84. if (UMax.isMinValue())
  85. return getEmpty(W);
  86. return ConstantRange(APInt::getMinValue(W), std::move(UMax));
  87. }
  88. case CmpInst::ICMP_SLT: {
  89. APInt SMax(CR.getSignedMax());
  90. if (SMax.isMinSignedValue())
  91. return getEmpty(W);
  92. return ConstantRange(APInt::getSignedMinValue(W), std::move(SMax));
  93. }
  94. case CmpInst::ICMP_ULE:
  95. return getNonEmpty(APInt::getMinValue(W), CR.getUnsignedMax() + 1);
  96. case CmpInst::ICMP_SLE:
  97. return getNonEmpty(APInt::getSignedMinValue(W), CR.getSignedMax() + 1);
  98. case CmpInst::ICMP_UGT: {
  99. APInt UMin(CR.getUnsignedMin());
  100. if (UMin.isMaxValue())
  101. return getEmpty(W);
  102. return ConstantRange(std::move(UMin) + 1, APInt::getZero(W));
  103. }
  104. case CmpInst::ICMP_SGT: {
  105. APInt SMin(CR.getSignedMin());
  106. if (SMin.isMaxSignedValue())
  107. return getEmpty(W);
  108. return ConstantRange(std::move(SMin) + 1, APInt::getSignedMinValue(W));
  109. }
  110. case CmpInst::ICMP_UGE:
  111. return getNonEmpty(CR.getUnsignedMin(), APInt::getZero(W));
  112. case CmpInst::ICMP_SGE:
  113. return getNonEmpty(CR.getSignedMin(), APInt::getSignedMinValue(W));
  114. }
  115. }
  116. ConstantRange ConstantRange::makeSatisfyingICmpRegion(CmpInst::Predicate Pred,
  117. const ConstantRange &CR) {
  118. // Follows from De-Morgan's laws:
  119. //
  120. // ~(~A union ~B) == A intersect B.
  121. //
  122. return makeAllowedICmpRegion(CmpInst::getInversePredicate(Pred), CR)
  123. .inverse();
  124. }
  125. ConstantRange ConstantRange::makeExactICmpRegion(CmpInst::Predicate Pred,
  126. const APInt &C) {
  127. // Computes the exact range that is equal to both the constant ranges returned
  128. // by makeAllowedICmpRegion and makeSatisfyingICmpRegion. This is always true
  129. // when RHS is a singleton such as an APInt and so the assert is valid.
  130. // However for non-singleton RHS, for example ult [2,5) makeAllowedICmpRegion
  131. // returns [0,4) but makeSatisfyICmpRegion returns [0,2).
  132. //
  133. assert(makeAllowedICmpRegion(Pred, C) == makeSatisfyingICmpRegion(Pred, C));
  134. return makeAllowedICmpRegion(Pred, C);
  135. }
  136. bool ConstantRange::areInsensitiveToSignednessOfICmpPredicate(
  137. const ConstantRange &CR1, const ConstantRange &CR2) {
  138. if (CR1.isEmptySet() || CR2.isEmptySet())
  139. return true;
  140. return (CR1.isAllNonNegative() && CR2.isAllNonNegative()) ||
  141. (CR1.isAllNegative() && CR2.isAllNegative());
  142. }
  143. bool ConstantRange::areInsensitiveToSignednessOfInvertedICmpPredicate(
  144. const ConstantRange &CR1, const ConstantRange &CR2) {
  145. if (CR1.isEmptySet() || CR2.isEmptySet())
  146. return true;
  147. return (CR1.isAllNonNegative() && CR2.isAllNegative()) ||
  148. (CR1.isAllNegative() && CR2.isAllNonNegative());
  149. }
  150. CmpInst::Predicate ConstantRange::getEquivalentPredWithFlippedSignedness(
  151. CmpInst::Predicate Pred, const ConstantRange &CR1,
  152. const ConstantRange &CR2) {
  153. assert(CmpInst::isIntPredicate(Pred) && CmpInst::isRelational(Pred) &&
  154. "Only for relational integer predicates!");
  155. CmpInst::Predicate FlippedSignednessPred =
  156. CmpInst::getFlippedSignednessPredicate(Pred);
  157. if (areInsensitiveToSignednessOfICmpPredicate(CR1, CR2))
  158. return FlippedSignednessPred;
  159. if (areInsensitiveToSignednessOfInvertedICmpPredicate(CR1, CR2))
  160. return CmpInst::getInversePredicate(FlippedSignednessPred);
  161. return CmpInst::Predicate::BAD_ICMP_PREDICATE;
  162. }
  163. void ConstantRange::getEquivalentICmp(CmpInst::Predicate &Pred,
  164. APInt &RHS, APInt &Offset) const {
  165. Offset = APInt(getBitWidth(), 0);
  166. if (isFullSet() || isEmptySet()) {
  167. Pred = isEmptySet() ? CmpInst::ICMP_ULT : CmpInst::ICMP_UGE;
  168. RHS = APInt(getBitWidth(), 0);
  169. } else if (auto *OnlyElt = getSingleElement()) {
  170. Pred = CmpInst::ICMP_EQ;
  171. RHS = *OnlyElt;
  172. } else if (auto *OnlyMissingElt = getSingleMissingElement()) {
  173. Pred = CmpInst::ICMP_NE;
  174. RHS = *OnlyMissingElt;
  175. } else if (getLower().isMinSignedValue() || getLower().isMinValue()) {
  176. Pred =
  177. getLower().isMinSignedValue() ? CmpInst::ICMP_SLT : CmpInst::ICMP_ULT;
  178. RHS = getUpper();
  179. } else if (getUpper().isMinSignedValue() || getUpper().isMinValue()) {
  180. Pred =
  181. getUpper().isMinSignedValue() ? CmpInst::ICMP_SGE : CmpInst::ICMP_UGE;
  182. RHS = getLower();
  183. } else {
  184. Pred = CmpInst::ICMP_ULT;
  185. RHS = getUpper() - getLower();
  186. Offset = -getLower();
  187. }
  188. assert(ConstantRange::makeExactICmpRegion(Pred, RHS) == add(Offset) &&
  189. "Bad result!");
  190. }
  191. bool ConstantRange::getEquivalentICmp(CmpInst::Predicate &Pred,
  192. APInt &RHS) const {
  193. APInt Offset;
  194. getEquivalentICmp(Pred, RHS, Offset);
  195. return Offset.isZero();
  196. }
  197. bool ConstantRange::icmp(CmpInst::Predicate Pred,
  198. const ConstantRange &Other) const {
  199. return makeSatisfyingICmpRegion(Pred, Other).contains(*this);
  200. }
  201. /// Exact mul nuw region for single element RHS.
  202. static ConstantRange makeExactMulNUWRegion(const APInt &V) {
  203. unsigned BitWidth = V.getBitWidth();
  204. if (V == 0)
  205. return ConstantRange::getFull(V.getBitWidth());
  206. return ConstantRange::getNonEmpty(
  207. APIntOps::RoundingUDiv(APInt::getMinValue(BitWidth), V,
  208. APInt::Rounding::UP),
  209. APIntOps::RoundingUDiv(APInt::getMaxValue(BitWidth), V,
  210. APInt::Rounding::DOWN) + 1);
  211. }
  212. /// Exact mul nsw region for single element RHS.
  213. static ConstantRange makeExactMulNSWRegion(const APInt &V) {
  214. // Handle special case for 0, -1 and 1. See the last for reason why we
  215. // specialize -1 and 1.
  216. unsigned BitWidth = V.getBitWidth();
  217. if (V == 0 || V.isOne())
  218. return ConstantRange::getFull(BitWidth);
  219. APInt MinValue = APInt::getSignedMinValue(BitWidth);
  220. APInt MaxValue = APInt::getSignedMaxValue(BitWidth);
  221. // e.g. Returning [-127, 127], represented as [-127, -128).
  222. if (V.isAllOnes())
  223. return ConstantRange(-MaxValue, MinValue);
  224. APInt Lower, Upper;
  225. if (V.isNegative()) {
  226. Lower = APIntOps::RoundingSDiv(MaxValue, V, APInt::Rounding::UP);
  227. Upper = APIntOps::RoundingSDiv(MinValue, V, APInt::Rounding::DOWN);
  228. } else {
  229. Lower = APIntOps::RoundingSDiv(MinValue, V, APInt::Rounding::UP);
  230. Upper = APIntOps::RoundingSDiv(MaxValue, V, APInt::Rounding::DOWN);
  231. }
  232. // ConstantRange ctor take a half inclusive interval [Lower, Upper + 1).
  233. // Upper + 1 is guaranteed not to overflow, because |divisor| > 1. 0, -1,
  234. // and 1 are already handled as special cases.
  235. return ConstantRange(Lower, Upper + 1);
  236. }
  237. ConstantRange
  238. ConstantRange::makeGuaranteedNoWrapRegion(Instruction::BinaryOps BinOp,
  239. const ConstantRange &Other,
  240. unsigned NoWrapKind) {
  241. using OBO = OverflowingBinaryOperator;
  242. assert(Instruction::isBinaryOp(BinOp) && "Binary operators only!");
  243. assert((NoWrapKind == OBO::NoSignedWrap ||
  244. NoWrapKind == OBO::NoUnsignedWrap) &&
  245. "NoWrapKind invalid!");
  246. bool Unsigned = NoWrapKind == OBO::NoUnsignedWrap;
  247. unsigned BitWidth = Other.getBitWidth();
  248. switch (BinOp) {
  249. default:
  250. llvm_unreachable("Unsupported binary op");
  251. case Instruction::Add: {
  252. if (Unsigned)
  253. return getNonEmpty(APInt::getZero(BitWidth), -Other.getUnsignedMax());
  254. APInt SignedMinVal = APInt::getSignedMinValue(BitWidth);
  255. APInt SMin = Other.getSignedMin(), SMax = Other.getSignedMax();
  256. return getNonEmpty(
  257. SMin.isNegative() ? SignedMinVal - SMin : SignedMinVal,
  258. SMax.isStrictlyPositive() ? SignedMinVal - SMax : SignedMinVal);
  259. }
  260. case Instruction::Sub: {
  261. if (Unsigned)
  262. return getNonEmpty(Other.getUnsignedMax(), APInt::getMinValue(BitWidth));
  263. APInt SignedMinVal = APInt::getSignedMinValue(BitWidth);
  264. APInt SMin = Other.getSignedMin(), SMax = Other.getSignedMax();
  265. return getNonEmpty(
  266. SMax.isStrictlyPositive() ? SignedMinVal + SMax : SignedMinVal,
  267. SMin.isNegative() ? SignedMinVal + SMin : SignedMinVal);
  268. }
  269. case Instruction::Mul:
  270. if (Unsigned)
  271. return makeExactMulNUWRegion(Other.getUnsignedMax());
  272. return makeExactMulNSWRegion(Other.getSignedMin())
  273. .intersectWith(makeExactMulNSWRegion(Other.getSignedMax()));
  274. case Instruction::Shl: {
  275. // For given range of shift amounts, if we ignore all illegal shift amounts
  276. // (that always produce poison), what shift amount range is left?
  277. ConstantRange ShAmt = Other.intersectWith(
  278. ConstantRange(APInt(BitWidth, 0), APInt(BitWidth, (BitWidth - 1) + 1)));
  279. if (ShAmt.isEmptySet()) {
  280. // If the entire range of shift amounts is already poison-producing,
  281. // then we can freely add more poison-producing flags ontop of that.
  282. return getFull(BitWidth);
  283. }
  284. // There are some legal shift amounts, we can compute conservatively-correct
  285. // range of no-wrap inputs. Note that by now we have clamped the ShAmtUMax
  286. // to be at most bitwidth-1, which results in most conservative range.
  287. APInt ShAmtUMax = ShAmt.getUnsignedMax();
  288. if (Unsigned)
  289. return getNonEmpty(APInt::getZero(BitWidth),
  290. APInt::getMaxValue(BitWidth).lshr(ShAmtUMax) + 1);
  291. return getNonEmpty(APInt::getSignedMinValue(BitWidth).ashr(ShAmtUMax),
  292. APInt::getSignedMaxValue(BitWidth).ashr(ShAmtUMax) + 1);
  293. }
  294. }
  295. }
  296. ConstantRange ConstantRange::makeExactNoWrapRegion(Instruction::BinaryOps BinOp,
  297. const APInt &Other,
  298. unsigned NoWrapKind) {
  299. // makeGuaranteedNoWrapRegion() is exact for single-element ranges, as
  300. // "for all" and "for any" coincide in this case.
  301. return makeGuaranteedNoWrapRegion(BinOp, ConstantRange(Other), NoWrapKind);
  302. }
  303. bool ConstantRange::isFullSet() const {
  304. return Lower == Upper && Lower.isMaxValue();
  305. }
  306. bool ConstantRange::isEmptySet() const {
  307. return Lower == Upper && Lower.isMinValue();
  308. }
  309. bool ConstantRange::isWrappedSet() const {
  310. return Lower.ugt(Upper) && !Upper.isZero();
  311. }
  312. bool ConstantRange::isUpperWrapped() const {
  313. return Lower.ugt(Upper);
  314. }
  315. bool ConstantRange::isSignWrappedSet() const {
  316. return Lower.sgt(Upper) && !Upper.isMinSignedValue();
  317. }
  318. bool ConstantRange::isUpperSignWrapped() const {
  319. return Lower.sgt(Upper);
  320. }
  321. bool
  322. ConstantRange::isSizeStrictlySmallerThan(const ConstantRange &Other) const {
  323. assert(getBitWidth() == Other.getBitWidth());
  324. if (isFullSet())
  325. return false;
  326. if (Other.isFullSet())
  327. return true;
  328. return (Upper - Lower).ult(Other.Upper - Other.Lower);
  329. }
  330. bool
  331. ConstantRange::isSizeLargerThan(uint64_t MaxSize) const {
  332. // If this a full set, we need special handling to avoid needing an extra bit
  333. // to represent the size.
  334. if (isFullSet())
  335. return MaxSize == 0 || APInt::getMaxValue(getBitWidth()).ugt(MaxSize - 1);
  336. return (Upper - Lower).ugt(MaxSize);
  337. }
  338. bool ConstantRange::isAllNegative() const {
  339. // Empty set is all negative, full set is not.
  340. if (isEmptySet())
  341. return true;
  342. if (isFullSet())
  343. return false;
  344. return !isUpperSignWrapped() && !Upper.isStrictlyPositive();
  345. }
  346. bool ConstantRange::isAllNonNegative() const {
  347. // Empty and full set are automatically treated correctly.
  348. return !isSignWrappedSet() && Lower.isNonNegative();
  349. }
  350. APInt ConstantRange::getUnsignedMax() const {
  351. if (isFullSet() || isUpperWrapped())
  352. return APInt::getMaxValue(getBitWidth());
  353. return getUpper() - 1;
  354. }
  355. APInt ConstantRange::getUnsignedMin() const {
  356. if (isFullSet() || isWrappedSet())
  357. return APInt::getMinValue(getBitWidth());
  358. return getLower();
  359. }
  360. APInt ConstantRange::getSignedMax() const {
  361. if (isFullSet() || isUpperSignWrapped())
  362. return APInt::getSignedMaxValue(getBitWidth());
  363. return getUpper() - 1;
  364. }
  365. APInt ConstantRange::getSignedMin() const {
  366. if (isFullSet() || isSignWrappedSet())
  367. return APInt::getSignedMinValue(getBitWidth());
  368. return getLower();
  369. }
  370. bool ConstantRange::contains(const APInt &V) const {
  371. if (Lower == Upper)
  372. return isFullSet();
  373. if (!isUpperWrapped())
  374. return Lower.ule(V) && V.ult(Upper);
  375. return Lower.ule(V) || V.ult(Upper);
  376. }
  377. bool ConstantRange::contains(const ConstantRange &Other) const {
  378. if (isFullSet() || Other.isEmptySet()) return true;
  379. if (isEmptySet() || Other.isFullSet()) return false;
  380. if (!isUpperWrapped()) {
  381. if (Other.isUpperWrapped())
  382. return false;
  383. return Lower.ule(Other.getLower()) && Other.getUpper().ule(Upper);
  384. }
  385. if (!Other.isUpperWrapped())
  386. return Other.getUpper().ule(Upper) ||
  387. Lower.ule(Other.getLower());
  388. return Other.getUpper().ule(Upper) && Lower.ule(Other.getLower());
  389. }
  390. unsigned ConstantRange::getActiveBits() const {
  391. if (isEmptySet())
  392. return 0;
  393. return getUnsignedMax().getActiveBits();
  394. }
  395. unsigned ConstantRange::getMinSignedBits() const {
  396. if (isEmptySet())
  397. return 0;
  398. return std::max(getSignedMin().getMinSignedBits(),
  399. getSignedMax().getMinSignedBits());
  400. }
  401. ConstantRange ConstantRange::subtract(const APInt &Val) const {
  402. assert(Val.getBitWidth() == getBitWidth() && "Wrong bit width");
  403. // If the set is empty or full, don't modify the endpoints.
  404. if (Lower == Upper)
  405. return *this;
  406. return ConstantRange(Lower - Val, Upper - Val);
  407. }
  408. ConstantRange ConstantRange::difference(const ConstantRange &CR) const {
  409. return intersectWith(CR.inverse());
  410. }
  411. static ConstantRange getPreferredRange(
  412. const ConstantRange &CR1, const ConstantRange &CR2,
  413. ConstantRange::PreferredRangeType Type) {
  414. if (Type == ConstantRange::Unsigned) {
  415. if (!CR1.isWrappedSet() && CR2.isWrappedSet())
  416. return CR1;
  417. if (CR1.isWrappedSet() && !CR2.isWrappedSet())
  418. return CR2;
  419. } else if (Type == ConstantRange::Signed) {
  420. if (!CR1.isSignWrappedSet() && CR2.isSignWrappedSet())
  421. return CR1;
  422. if (CR1.isSignWrappedSet() && !CR2.isSignWrappedSet())
  423. return CR2;
  424. }
  425. if (CR1.isSizeStrictlySmallerThan(CR2))
  426. return CR1;
  427. return CR2;
  428. }
  429. ConstantRange ConstantRange::intersectWith(const ConstantRange &CR,
  430. PreferredRangeType Type) const {
  431. assert(getBitWidth() == CR.getBitWidth() &&
  432. "ConstantRange types don't agree!");
  433. // Handle common cases.
  434. if ( isEmptySet() || CR.isFullSet()) return *this;
  435. if (CR.isEmptySet() || isFullSet()) return CR;
  436. if (!isUpperWrapped() && CR.isUpperWrapped())
  437. return CR.intersectWith(*this, Type);
  438. if (!isUpperWrapped() && !CR.isUpperWrapped()) {
  439. if (Lower.ult(CR.Lower)) {
  440. // L---U : this
  441. // L---U : CR
  442. if (Upper.ule(CR.Lower))
  443. return getEmpty();
  444. // L---U : this
  445. // L---U : CR
  446. if (Upper.ult(CR.Upper))
  447. return ConstantRange(CR.Lower, Upper);
  448. // L-------U : this
  449. // L---U : CR
  450. return CR;
  451. }
  452. // L---U : this
  453. // L-------U : CR
  454. if (Upper.ult(CR.Upper))
  455. return *this;
  456. // L-----U : this
  457. // L-----U : CR
  458. if (Lower.ult(CR.Upper))
  459. return ConstantRange(Lower, CR.Upper);
  460. // L---U : this
  461. // L---U : CR
  462. return getEmpty();
  463. }
  464. if (isUpperWrapped() && !CR.isUpperWrapped()) {
  465. if (CR.Lower.ult(Upper)) {
  466. // ------U L--- : this
  467. // L--U : CR
  468. if (CR.Upper.ult(Upper))
  469. return CR;
  470. // ------U L--- : this
  471. // L------U : CR
  472. if (CR.Upper.ule(Lower))
  473. return ConstantRange(CR.Lower, Upper);
  474. // ------U L--- : this
  475. // L----------U : CR
  476. return getPreferredRange(*this, CR, Type);
  477. }
  478. if (CR.Lower.ult(Lower)) {
  479. // --U L---- : this
  480. // L--U : CR
  481. if (CR.Upper.ule(Lower))
  482. return getEmpty();
  483. // --U L---- : this
  484. // L------U : CR
  485. return ConstantRange(Lower, CR.Upper);
  486. }
  487. // --U L------ : this
  488. // L--U : CR
  489. return CR;
  490. }
  491. if (CR.Upper.ult(Upper)) {
  492. // ------U L-- : this
  493. // --U L------ : CR
  494. if (CR.Lower.ult(Upper))
  495. return getPreferredRange(*this, CR, Type);
  496. // ----U L-- : this
  497. // --U L---- : CR
  498. if (CR.Lower.ult(Lower))
  499. return ConstantRange(Lower, CR.Upper);
  500. // ----U L---- : this
  501. // --U L-- : CR
  502. return CR;
  503. }
  504. if (CR.Upper.ule(Lower)) {
  505. // --U L-- : this
  506. // ----U L---- : CR
  507. if (CR.Lower.ult(Lower))
  508. return *this;
  509. // --U L---- : this
  510. // ----U L-- : CR
  511. return ConstantRange(CR.Lower, Upper);
  512. }
  513. // --U L------ : this
  514. // ------U L-- : CR
  515. return getPreferredRange(*this, CR, Type);
  516. }
  517. ConstantRange ConstantRange::unionWith(const ConstantRange &CR,
  518. PreferredRangeType Type) const {
  519. assert(getBitWidth() == CR.getBitWidth() &&
  520. "ConstantRange types don't agree!");
  521. if ( isFullSet() || CR.isEmptySet()) return *this;
  522. if (CR.isFullSet() || isEmptySet()) return CR;
  523. if (!isUpperWrapped() && CR.isUpperWrapped())
  524. return CR.unionWith(*this, Type);
  525. if (!isUpperWrapped() && !CR.isUpperWrapped()) {
  526. // L---U and L---U : this
  527. // L---U L---U : CR
  528. // result in one of
  529. // L---------U
  530. // -----U L-----
  531. if (CR.Upper.ult(Lower) || Upper.ult(CR.Lower))
  532. return getPreferredRange(
  533. ConstantRange(Lower, CR.Upper), ConstantRange(CR.Lower, Upper), Type);
  534. APInt L = CR.Lower.ult(Lower) ? CR.Lower : Lower;
  535. APInt U = (CR.Upper - 1).ugt(Upper - 1) ? CR.Upper : Upper;
  536. if (L.isZero() && U.isZero())
  537. return getFull();
  538. return ConstantRange(std::move(L), std::move(U));
  539. }
  540. if (!CR.isUpperWrapped()) {
  541. // ------U L----- and ------U L----- : this
  542. // L--U L--U : CR
  543. if (CR.Upper.ule(Upper) || CR.Lower.uge(Lower))
  544. return *this;
  545. // ------U L----- : this
  546. // L---------U : CR
  547. if (CR.Lower.ule(Upper) && Lower.ule(CR.Upper))
  548. return getFull();
  549. // ----U L---- : this
  550. // L---U : CR
  551. // results in one of
  552. // ----------U L----
  553. // ----U L----------
  554. if (Upper.ult(CR.Lower) && CR.Upper.ult(Lower))
  555. return getPreferredRange(
  556. ConstantRange(Lower, CR.Upper), ConstantRange(CR.Lower, Upper), Type);
  557. // ----U L----- : this
  558. // L----U : CR
  559. if (Upper.ult(CR.Lower) && Lower.ule(CR.Upper))
  560. return ConstantRange(CR.Lower, Upper);
  561. // ------U L---- : this
  562. // L-----U : CR
  563. assert(CR.Lower.ule(Upper) && CR.Upper.ult(Lower) &&
  564. "ConstantRange::unionWith missed a case with one range wrapped");
  565. return ConstantRange(Lower, CR.Upper);
  566. }
  567. // ------U L---- and ------U L---- : this
  568. // -U L----------- and ------------U L : CR
  569. if (CR.Lower.ule(Upper) || Lower.ule(CR.Upper))
  570. return getFull();
  571. APInt L = CR.Lower.ult(Lower) ? CR.Lower : Lower;
  572. APInt U = CR.Upper.ugt(Upper) ? CR.Upper : Upper;
  573. return ConstantRange(std::move(L), std::move(U));
  574. }
  575. Optional<ConstantRange>
  576. ConstantRange::exactIntersectWith(const ConstantRange &CR) const {
  577. // TODO: This can be implemented more efficiently.
  578. ConstantRange Result = intersectWith(CR);
  579. if (Result == inverse().unionWith(CR.inverse()).inverse())
  580. return Result;
  581. return None;
  582. }
  583. Optional<ConstantRange>
  584. ConstantRange::exactUnionWith(const ConstantRange &CR) const {
  585. // TODO: This can be implemented more efficiently.
  586. ConstantRange Result = unionWith(CR);
  587. if (Result == inverse().intersectWith(CR.inverse()).inverse())
  588. return Result;
  589. return None;
  590. }
  591. ConstantRange ConstantRange::castOp(Instruction::CastOps CastOp,
  592. uint32_t ResultBitWidth) const {
  593. switch (CastOp) {
  594. default:
  595. llvm_unreachable("unsupported cast type");
  596. case Instruction::Trunc:
  597. return truncate(ResultBitWidth);
  598. case Instruction::SExt:
  599. return signExtend(ResultBitWidth);
  600. case Instruction::ZExt:
  601. return zeroExtend(ResultBitWidth);
  602. case Instruction::BitCast:
  603. return *this;
  604. case Instruction::FPToUI:
  605. case Instruction::FPToSI:
  606. if (getBitWidth() == ResultBitWidth)
  607. return *this;
  608. else
  609. return getFull(ResultBitWidth);
  610. case Instruction::UIToFP: {
  611. // TODO: use input range if available
  612. auto BW = getBitWidth();
  613. APInt Min = APInt::getMinValue(BW).zextOrSelf(ResultBitWidth);
  614. APInt Max = APInt::getMaxValue(BW).zextOrSelf(ResultBitWidth);
  615. return ConstantRange(std::move(Min), std::move(Max));
  616. }
  617. case Instruction::SIToFP: {
  618. // TODO: use input range if available
  619. auto BW = getBitWidth();
  620. APInt SMin = APInt::getSignedMinValue(BW).sextOrSelf(ResultBitWidth);
  621. APInt SMax = APInt::getSignedMaxValue(BW).sextOrSelf(ResultBitWidth);
  622. return ConstantRange(std::move(SMin), std::move(SMax));
  623. }
  624. case Instruction::FPTrunc:
  625. case Instruction::FPExt:
  626. case Instruction::IntToPtr:
  627. case Instruction::PtrToInt:
  628. case Instruction::AddrSpaceCast:
  629. // Conservatively return getFull set.
  630. return getFull(ResultBitWidth);
  631. };
  632. }
  633. ConstantRange ConstantRange::zeroExtend(uint32_t DstTySize) const {
  634. if (isEmptySet()) return getEmpty(DstTySize);
  635. unsigned SrcTySize = getBitWidth();
  636. assert(SrcTySize < DstTySize && "Not a value extension");
  637. if (isFullSet() || isUpperWrapped()) {
  638. // Change into [0, 1 << src bit width)
  639. APInt LowerExt(DstTySize, 0);
  640. if (!Upper) // special case: [X, 0) -- not really wrapping around
  641. LowerExt = Lower.zext(DstTySize);
  642. return ConstantRange(std::move(LowerExt),
  643. APInt::getOneBitSet(DstTySize, SrcTySize));
  644. }
  645. return ConstantRange(Lower.zext(DstTySize), Upper.zext(DstTySize));
  646. }
  647. ConstantRange ConstantRange::signExtend(uint32_t DstTySize) const {
  648. if (isEmptySet()) return getEmpty(DstTySize);
  649. unsigned SrcTySize = getBitWidth();
  650. assert(SrcTySize < DstTySize && "Not a value extension");
  651. // special case: [X, INT_MIN) -- not really wrapping around
  652. if (Upper.isMinSignedValue())
  653. return ConstantRange(Lower.sext(DstTySize), Upper.zext(DstTySize));
  654. if (isFullSet() || isSignWrappedSet()) {
  655. return ConstantRange(APInt::getHighBitsSet(DstTySize,DstTySize-SrcTySize+1),
  656. APInt::getLowBitsSet(DstTySize, SrcTySize-1) + 1);
  657. }
  658. return ConstantRange(Lower.sext(DstTySize), Upper.sext(DstTySize));
  659. }
  660. ConstantRange ConstantRange::truncate(uint32_t DstTySize) const {
  661. assert(getBitWidth() > DstTySize && "Not a value truncation");
  662. if (isEmptySet())
  663. return getEmpty(DstTySize);
  664. if (isFullSet())
  665. return getFull(DstTySize);
  666. APInt LowerDiv(Lower), UpperDiv(Upper);
  667. ConstantRange Union(DstTySize, /*isFullSet=*/false);
  668. // Analyze wrapped sets in their two parts: [0, Upper) \/ [Lower, MaxValue]
  669. // We use the non-wrapped set code to analyze the [Lower, MaxValue) part, and
  670. // then we do the union with [MaxValue, Upper)
  671. if (isUpperWrapped()) {
  672. // If Upper is greater than or equal to MaxValue(DstTy), it covers the whole
  673. // truncated range.
  674. if (Upper.getActiveBits() > DstTySize ||
  675. Upper.countTrailingOnes() == DstTySize)
  676. return getFull(DstTySize);
  677. Union = ConstantRange(APInt::getMaxValue(DstTySize),Upper.trunc(DstTySize));
  678. UpperDiv.setAllBits();
  679. // Union covers the MaxValue case, so return if the remaining range is just
  680. // MaxValue(DstTy).
  681. if (LowerDiv == UpperDiv)
  682. return Union;
  683. }
  684. // Chop off the most significant bits that are past the destination bitwidth.
  685. if (LowerDiv.getActiveBits() > DstTySize) {
  686. // Mask to just the signficant bits and subtract from LowerDiv/UpperDiv.
  687. APInt Adjust = LowerDiv & APInt::getBitsSetFrom(getBitWidth(), DstTySize);
  688. LowerDiv -= Adjust;
  689. UpperDiv -= Adjust;
  690. }
  691. unsigned UpperDivWidth = UpperDiv.getActiveBits();
  692. if (UpperDivWidth <= DstTySize)
  693. return ConstantRange(LowerDiv.trunc(DstTySize),
  694. UpperDiv.trunc(DstTySize)).unionWith(Union);
  695. // The truncated value wraps around. Check if we can do better than fullset.
  696. if (UpperDivWidth == DstTySize + 1) {
  697. // Clear the MSB so that UpperDiv wraps around.
  698. UpperDiv.clearBit(DstTySize);
  699. if (UpperDiv.ult(LowerDiv))
  700. return ConstantRange(LowerDiv.trunc(DstTySize),
  701. UpperDiv.trunc(DstTySize)).unionWith(Union);
  702. }
  703. return getFull(DstTySize);
  704. }
  705. ConstantRange ConstantRange::zextOrTrunc(uint32_t DstTySize) const {
  706. unsigned SrcTySize = getBitWidth();
  707. if (SrcTySize > DstTySize)
  708. return truncate(DstTySize);
  709. if (SrcTySize < DstTySize)
  710. return zeroExtend(DstTySize);
  711. return *this;
  712. }
  713. ConstantRange ConstantRange::sextOrTrunc(uint32_t DstTySize) const {
  714. unsigned SrcTySize = getBitWidth();
  715. if (SrcTySize > DstTySize)
  716. return truncate(DstTySize);
  717. if (SrcTySize < DstTySize)
  718. return signExtend(DstTySize);
  719. return *this;
  720. }
  721. ConstantRange ConstantRange::binaryOp(Instruction::BinaryOps BinOp,
  722. const ConstantRange &Other) const {
  723. assert(Instruction::isBinaryOp(BinOp) && "Binary operators only!");
  724. switch (BinOp) {
  725. case Instruction::Add:
  726. return add(Other);
  727. case Instruction::Sub:
  728. return sub(Other);
  729. case Instruction::Mul:
  730. return multiply(Other);
  731. case Instruction::UDiv:
  732. return udiv(Other);
  733. case Instruction::SDiv:
  734. return sdiv(Other);
  735. case Instruction::URem:
  736. return urem(Other);
  737. case Instruction::SRem:
  738. return srem(Other);
  739. case Instruction::Shl:
  740. return shl(Other);
  741. case Instruction::LShr:
  742. return lshr(Other);
  743. case Instruction::AShr:
  744. return ashr(Other);
  745. case Instruction::And:
  746. return binaryAnd(Other);
  747. case Instruction::Or:
  748. return binaryOr(Other);
  749. case Instruction::Xor:
  750. return binaryXor(Other);
  751. // Note: floating point operations applied to abstract ranges are just
  752. // ideal integer operations with a lossy representation
  753. case Instruction::FAdd:
  754. return add(Other);
  755. case Instruction::FSub:
  756. return sub(Other);
  757. case Instruction::FMul:
  758. return multiply(Other);
  759. default:
  760. // Conservatively return getFull set.
  761. return getFull();
  762. }
  763. }
  764. ConstantRange ConstantRange::overflowingBinaryOp(Instruction::BinaryOps BinOp,
  765. const ConstantRange &Other,
  766. unsigned NoWrapKind) const {
  767. assert(Instruction::isBinaryOp(BinOp) && "Binary operators only!");
  768. switch (BinOp) {
  769. case Instruction::Add:
  770. return addWithNoWrap(Other, NoWrapKind);
  771. case Instruction::Sub:
  772. return subWithNoWrap(Other, NoWrapKind);
  773. default:
  774. // Don't know about this Overflowing Binary Operation.
  775. // Conservatively fallback to plain binop handling.
  776. return binaryOp(BinOp, Other);
  777. }
  778. }
  779. bool ConstantRange::isIntrinsicSupported(Intrinsic::ID IntrinsicID) {
  780. switch (IntrinsicID) {
  781. case Intrinsic::uadd_sat:
  782. case Intrinsic::usub_sat:
  783. case Intrinsic::sadd_sat:
  784. case Intrinsic::ssub_sat:
  785. case Intrinsic::umin:
  786. case Intrinsic::umax:
  787. case Intrinsic::smin:
  788. case Intrinsic::smax:
  789. case Intrinsic::abs:
  790. return true;
  791. default:
  792. return false;
  793. }
  794. }
  795. ConstantRange ConstantRange::intrinsic(Intrinsic::ID IntrinsicID,
  796. ArrayRef<ConstantRange> Ops) {
  797. switch (IntrinsicID) {
  798. case Intrinsic::uadd_sat:
  799. return Ops[0].uadd_sat(Ops[1]);
  800. case Intrinsic::usub_sat:
  801. return Ops[0].usub_sat(Ops[1]);
  802. case Intrinsic::sadd_sat:
  803. return Ops[0].sadd_sat(Ops[1]);
  804. case Intrinsic::ssub_sat:
  805. return Ops[0].ssub_sat(Ops[1]);
  806. case Intrinsic::umin:
  807. return Ops[0].umin(Ops[1]);
  808. case Intrinsic::umax:
  809. return Ops[0].umax(Ops[1]);
  810. case Intrinsic::smin:
  811. return Ops[0].smin(Ops[1]);
  812. case Intrinsic::smax:
  813. return Ops[0].smax(Ops[1]);
  814. case Intrinsic::abs: {
  815. const APInt *IntMinIsPoison = Ops[1].getSingleElement();
  816. assert(IntMinIsPoison && "Must be known (immarg)");
  817. assert(IntMinIsPoison->getBitWidth() == 1 && "Must be boolean");
  818. return Ops[0].abs(IntMinIsPoison->getBoolValue());
  819. }
  820. default:
  821. assert(!isIntrinsicSupported(IntrinsicID) && "Shouldn't be supported");
  822. llvm_unreachable("Unsupported intrinsic");
  823. }
  824. }
  825. ConstantRange
  826. ConstantRange::add(const ConstantRange &Other) const {
  827. if (isEmptySet() || Other.isEmptySet())
  828. return getEmpty();
  829. if (isFullSet() || Other.isFullSet())
  830. return getFull();
  831. APInt NewLower = getLower() + Other.getLower();
  832. APInt NewUpper = getUpper() + Other.getUpper() - 1;
  833. if (NewLower == NewUpper)
  834. return getFull();
  835. ConstantRange X = ConstantRange(std::move(NewLower), std::move(NewUpper));
  836. if (X.isSizeStrictlySmallerThan(*this) ||
  837. X.isSizeStrictlySmallerThan(Other))
  838. // We've wrapped, therefore, full set.
  839. return getFull();
  840. return X;
  841. }
  842. ConstantRange ConstantRange::addWithNoWrap(const ConstantRange &Other,
  843. unsigned NoWrapKind,
  844. PreferredRangeType RangeType) const {
  845. // Calculate the range for "X + Y" which is guaranteed not to wrap(overflow).
  846. // (X is from this, and Y is from Other)
  847. if (isEmptySet() || Other.isEmptySet())
  848. return getEmpty();
  849. if (isFullSet() && Other.isFullSet())
  850. return getFull();
  851. using OBO = OverflowingBinaryOperator;
  852. ConstantRange Result = add(Other);
  853. // If an overflow happens for every value pair in these two constant ranges,
  854. // we must return Empty set. In this case, we get that for free, because we
  855. // get lucky that intersection of add() with uadd_sat()/sadd_sat() results
  856. // in an empty set.
  857. if (NoWrapKind & OBO::NoSignedWrap)
  858. Result = Result.intersectWith(sadd_sat(Other), RangeType);
  859. if (NoWrapKind & OBO::NoUnsignedWrap)
  860. Result = Result.intersectWith(uadd_sat(Other), RangeType);
  861. return Result;
  862. }
  863. ConstantRange
  864. ConstantRange::sub(const ConstantRange &Other) const {
  865. if (isEmptySet() || Other.isEmptySet())
  866. return getEmpty();
  867. if (isFullSet() || Other.isFullSet())
  868. return getFull();
  869. APInt NewLower = getLower() - Other.getUpper() + 1;
  870. APInt NewUpper = getUpper() - Other.getLower();
  871. if (NewLower == NewUpper)
  872. return getFull();
  873. ConstantRange X = ConstantRange(std::move(NewLower), std::move(NewUpper));
  874. if (X.isSizeStrictlySmallerThan(*this) ||
  875. X.isSizeStrictlySmallerThan(Other))
  876. // We've wrapped, therefore, full set.
  877. return getFull();
  878. return X;
  879. }
  880. ConstantRange ConstantRange::subWithNoWrap(const ConstantRange &Other,
  881. unsigned NoWrapKind,
  882. PreferredRangeType RangeType) const {
  883. // Calculate the range for "X - Y" which is guaranteed not to wrap(overflow).
  884. // (X is from this, and Y is from Other)
  885. if (isEmptySet() || Other.isEmptySet())
  886. return getEmpty();
  887. if (isFullSet() && Other.isFullSet())
  888. return getFull();
  889. using OBO = OverflowingBinaryOperator;
  890. ConstantRange Result = sub(Other);
  891. // If an overflow happens for every value pair in these two constant ranges,
  892. // we must return Empty set. In signed case, we get that for free, because we
  893. // get lucky that intersection of sub() with ssub_sat() results in an
  894. // empty set. But for unsigned we must perform the overflow check manually.
  895. if (NoWrapKind & OBO::NoSignedWrap)
  896. Result = Result.intersectWith(ssub_sat(Other), RangeType);
  897. if (NoWrapKind & OBO::NoUnsignedWrap) {
  898. if (getUnsignedMax().ult(Other.getUnsignedMin()))
  899. return getEmpty(); // Always overflows.
  900. Result = Result.intersectWith(usub_sat(Other), RangeType);
  901. }
  902. return Result;
  903. }
  904. ConstantRange
  905. ConstantRange::multiply(const ConstantRange &Other) const {
  906. // TODO: If either operand is a single element and the multiply is known to
  907. // be non-wrapping, round the result min and max value to the appropriate
  908. // multiple of that element. If wrapping is possible, at least adjust the
  909. // range according to the greatest power-of-two factor of the single element.
  910. if (isEmptySet() || Other.isEmptySet())
  911. return getEmpty();
  912. // Multiplication is signedness-independent. However different ranges can be
  913. // obtained depending on how the input ranges are treated. These different
  914. // ranges are all conservatively correct, but one might be better than the
  915. // other. We calculate two ranges; one treating the inputs as unsigned
  916. // and the other signed, then return the smallest of these ranges.
  917. // Unsigned range first.
  918. APInt this_min = getUnsignedMin().zext(getBitWidth() * 2);
  919. APInt this_max = getUnsignedMax().zext(getBitWidth() * 2);
  920. APInt Other_min = Other.getUnsignedMin().zext(getBitWidth() * 2);
  921. APInt Other_max = Other.getUnsignedMax().zext(getBitWidth() * 2);
  922. ConstantRange Result_zext = ConstantRange(this_min * Other_min,
  923. this_max * Other_max + 1);
  924. ConstantRange UR = Result_zext.truncate(getBitWidth());
  925. // If the unsigned range doesn't wrap, and isn't negative then it's a range
  926. // from one positive number to another which is as good as we can generate.
  927. // In this case, skip the extra work of generating signed ranges which aren't
  928. // going to be better than this range.
  929. if (!UR.isUpperWrapped() &&
  930. (UR.getUpper().isNonNegative() || UR.getUpper().isMinSignedValue()))
  931. return UR;
  932. // Now the signed range. Because we could be dealing with negative numbers
  933. // here, the lower bound is the smallest of the cartesian product of the
  934. // lower and upper ranges; for example:
  935. // [-1,4) * [-2,3) = min(-1*-2, -1*2, 3*-2, 3*2) = -6.
  936. // Similarly for the upper bound, swapping min for max.
  937. this_min = getSignedMin().sext(getBitWidth() * 2);
  938. this_max = getSignedMax().sext(getBitWidth() * 2);
  939. Other_min = Other.getSignedMin().sext(getBitWidth() * 2);
  940. Other_max = Other.getSignedMax().sext(getBitWidth() * 2);
  941. auto L = {this_min * Other_min, this_min * Other_max,
  942. this_max * Other_min, this_max * Other_max};
  943. auto Compare = [](const APInt &A, const APInt &B) { return A.slt(B); };
  944. ConstantRange Result_sext(std::min(L, Compare), std::max(L, Compare) + 1);
  945. ConstantRange SR = Result_sext.truncate(getBitWidth());
  946. return UR.isSizeStrictlySmallerThan(SR) ? UR : SR;
  947. }
  948. ConstantRange ConstantRange::smul_fast(const ConstantRange &Other) const {
  949. if (isEmptySet() || Other.isEmptySet())
  950. return getEmpty();
  951. APInt Min = getSignedMin();
  952. APInt Max = getSignedMax();
  953. APInt OtherMin = Other.getSignedMin();
  954. APInt OtherMax = Other.getSignedMax();
  955. bool O1, O2, O3, O4;
  956. auto Muls = {Min.smul_ov(OtherMin, O1), Min.smul_ov(OtherMax, O2),
  957. Max.smul_ov(OtherMin, O3), Max.smul_ov(OtherMax, O4)};
  958. if (O1 || O2 || O3 || O4)
  959. return getFull();
  960. auto Compare = [](const APInt &A, const APInt &B) { return A.slt(B); };
  961. return getNonEmpty(std::min(Muls, Compare), std::max(Muls, Compare) + 1);
  962. }
  963. ConstantRange
  964. ConstantRange::smax(const ConstantRange &Other) const {
  965. // X smax Y is: range(smax(X_smin, Y_smin),
  966. // smax(X_smax, Y_smax))
  967. if (isEmptySet() || Other.isEmptySet())
  968. return getEmpty();
  969. APInt NewL = APIntOps::smax(getSignedMin(), Other.getSignedMin());
  970. APInt NewU = APIntOps::smax(getSignedMax(), Other.getSignedMax()) + 1;
  971. ConstantRange Res = getNonEmpty(std::move(NewL), std::move(NewU));
  972. if (isSignWrappedSet() || Other.isSignWrappedSet())
  973. return Res.intersectWith(unionWith(Other, Signed), Signed);
  974. return Res;
  975. }
  976. ConstantRange
  977. ConstantRange::umax(const ConstantRange &Other) const {
  978. // X umax Y is: range(umax(X_umin, Y_umin),
  979. // umax(X_umax, Y_umax))
  980. if (isEmptySet() || Other.isEmptySet())
  981. return getEmpty();
  982. APInt NewL = APIntOps::umax(getUnsignedMin(), Other.getUnsignedMin());
  983. APInt NewU = APIntOps::umax(getUnsignedMax(), Other.getUnsignedMax()) + 1;
  984. ConstantRange Res = getNonEmpty(std::move(NewL), std::move(NewU));
  985. if (isWrappedSet() || Other.isWrappedSet())
  986. return Res.intersectWith(unionWith(Other, Unsigned), Unsigned);
  987. return Res;
  988. }
  989. ConstantRange
  990. ConstantRange::smin(const ConstantRange &Other) const {
  991. // X smin Y is: range(smin(X_smin, Y_smin),
  992. // smin(X_smax, Y_smax))
  993. if (isEmptySet() || Other.isEmptySet())
  994. return getEmpty();
  995. APInt NewL = APIntOps::smin(getSignedMin(), Other.getSignedMin());
  996. APInt NewU = APIntOps::smin(getSignedMax(), Other.getSignedMax()) + 1;
  997. ConstantRange Res = getNonEmpty(std::move(NewL), std::move(NewU));
  998. if (isSignWrappedSet() || Other.isSignWrappedSet())
  999. return Res.intersectWith(unionWith(Other, Signed), Signed);
  1000. return Res;
  1001. }
  1002. ConstantRange
  1003. ConstantRange::umin(const ConstantRange &Other) const {
  1004. // X umin Y is: range(umin(X_umin, Y_umin),
  1005. // umin(X_umax, Y_umax))
  1006. if (isEmptySet() || Other.isEmptySet())
  1007. return getEmpty();
  1008. APInt NewL = APIntOps::umin(getUnsignedMin(), Other.getUnsignedMin());
  1009. APInt NewU = APIntOps::umin(getUnsignedMax(), Other.getUnsignedMax()) + 1;
  1010. ConstantRange Res = getNonEmpty(std::move(NewL), std::move(NewU));
  1011. if (isWrappedSet() || Other.isWrappedSet())
  1012. return Res.intersectWith(unionWith(Other, Unsigned), Unsigned);
  1013. return Res;
  1014. }
  1015. ConstantRange
  1016. ConstantRange::udiv(const ConstantRange &RHS) const {
  1017. if (isEmptySet() || RHS.isEmptySet() || RHS.getUnsignedMax().isZero())
  1018. return getEmpty();
  1019. APInt Lower = getUnsignedMin().udiv(RHS.getUnsignedMax());
  1020. APInt RHS_umin = RHS.getUnsignedMin();
  1021. if (RHS_umin.isZero()) {
  1022. // We want the lowest value in RHS excluding zero. Usually that would be 1
  1023. // except for a range in the form of [X, 1) in which case it would be X.
  1024. if (RHS.getUpper() == 1)
  1025. RHS_umin = RHS.getLower();
  1026. else
  1027. RHS_umin = 1;
  1028. }
  1029. APInt Upper = getUnsignedMax().udiv(RHS_umin) + 1;
  1030. return getNonEmpty(std::move(Lower), std::move(Upper));
  1031. }
  1032. ConstantRange ConstantRange::sdiv(const ConstantRange &RHS) const {
  1033. // We split up the LHS and RHS into positive and negative components
  1034. // and then also compute the positive and negative components of the result
  1035. // separately by combining division results with the appropriate signs.
  1036. APInt Zero = APInt::getZero(getBitWidth());
  1037. APInt SignedMin = APInt::getSignedMinValue(getBitWidth());
  1038. ConstantRange PosFilter(APInt(getBitWidth(), 1), SignedMin);
  1039. ConstantRange NegFilter(SignedMin, Zero);
  1040. ConstantRange PosL = intersectWith(PosFilter);
  1041. ConstantRange NegL = intersectWith(NegFilter);
  1042. ConstantRange PosR = RHS.intersectWith(PosFilter);
  1043. ConstantRange NegR = RHS.intersectWith(NegFilter);
  1044. ConstantRange PosRes = getEmpty();
  1045. if (!PosL.isEmptySet() && !PosR.isEmptySet())
  1046. // pos / pos = pos.
  1047. PosRes = ConstantRange(PosL.Lower.sdiv(PosR.Upper - 1),
  1048. (PosL.Upper - 1).sdiv(PosR.Lower) + 1);
  1049. if (!NegL.isEmptySet() && !NegR.isEmptySet()) {
  1050. // neg / neg = pos.
  1051. //
  1052. // We need to deal with one tricky case here: SignedMin / -1 is UB on the
  1053. // IR level, so we'll want to exclude this case when calculating bounds.
  1054. // (For APInts the operation is well-defined and yields SignedMin.) We
  1055. // handle this by dropping either SignedMin from the LHS or -1 from the RHS.
  1056. APInt Lo = (NegL.Upper - 1).sdiv(NegR.Lower);
  1057. if (NegL.Lower.isMinSignedValue() && NegR.Upper.isZero()) {
  1058. // Remove -1 from the LHS. Skip if it's the only element, as this would
  1059. // leave us with an empty set.
  1060. if (!NegR.Lower.isAllOnes()) {
  1061. APInt AdjNegRUpper;
  1062. if (RHS.Lower.isAllOnes())
  1063. // Negative part of [-1, X] without -1 is [SignedMin, X].
  1064. AdjNegRUpper = RHS.Upper;
  1065. else
  1066. // [X, -1] without -1 is [X, -2].
  1067. AdjNegRUpper = NegR.Upper - 1;
  1068. PosRes = PosRes.unionWith(
  1069. ConstantRange(Lo, NegL.Lower.sdiv(AdjNegRUpper - 1) + 1));
  1070. }
  1071. // Remove SignedMin from the RHS. Skip if it's the only element, as this
  1072. // would leave us with an empty set.
  1073. if (NegL.Upper != SignedMin + 1) {
  1074. APInt AdjNegLLower;
  1075. if (Upper == SignedMin + 1)
  1076. // Negative part of [X, SignedMin] without SignedMin is [X, -1].
  1077. AdjNegLLower = Lower;
  1078. else
  1079. // [SignedMin, X] without SignedMin is [SignedMin + 1, X].
  1080. AdjNegLLower = NegL.Lower + 1;
  1081. PosRes = PosRes.unionWith(
  1082. ConstantRange(std::move(Lo),
  1083. AdjNegLLower.sdiv(NegR.Upper - 1) + 1));
  1084. }
  1085. } else {
  1086. PosRes = PosRes.unionWith(
  1087. ConstantRange(std::move(Lo), NegL.Lower.sdiv(NegR.Upper - 1) + 1));
  1088. }
  1089. }
  1090. ConstantRange NegRes = getEmpty();
  1091. if (!PosL.isEmptySet() && !NegR.isEmptySet())
  1092. // pos / neg = neg.
  1093. NegRes = ConstantRange((PosL.Upper - 1).sdiv(NegR.Upper - 1),
  1094. PosL.Lower.sdiv(NegR.Lower) + 1);
  1095. if (!NegL.isEmptySet() && !PosR.isEmptySet())
  1096. // neg / pos = neg.
  1097. NegRes = NegRes.unionWith(
  1098. ConstantRange(NegL.Lower.sdiv(PosR.Lower),
  1099. (NegL.Upper - 1).sdiv(PosR.Upper - 1) + 1));
  1100. // Prefer a non-wrapping signed range here.
  1101. ConstantRange Res = NegRes.unionWith(PosRes, PreferredRangeType::Signed);
  1102. // Preserve the zero that we dropped when splitting the LHS by sign.
  1103. if (contains(Zero) && (!PosR.isEmptySet() || !NegR.isEmptySet()))
  1104. Res = Res.unionWith(ConstantRange(Zero));
  1105. return Res;
  1106. }
  1107. ConstantRange ConstantRange::urem(const ConstantRange &RHS) const {
  1108. if (isEmptySet() || RHS.isEmptySet() || RHS.getUnsignedMax().isZero())
  1109. return getEmpty();
  1110. if (const APInt *RHSInt = RHS.getSingleElement()) {
  1111. // UREM by null is UB.
  1112. if (RHSInt->isZero())
  1113. return getEmpty();
  1114. // Use APInt's implementation of UREM for single element ranges.
  1115. if (const APInt *LHSInt = getSingleElement())
  1116. return {LHSInt->urem(*RHSInt)};
  1117. }
  1118. // L % R for L < R is L.
  1119. if (getUnsignedMax().ult(RHS.getUnsignedMin()))
  1120. return *this;
  1121. // L % R is <= L and < R.
  1122. APInt Upper = APIntOps::umin(getUnsignedMax(), RHS.getUnsignedMax() - 1) + 1;
  1123. return getNonEmpty(APInt::getZero(getBitWidth()), std::move(Upper));
  1124. }
  1125. ConstantRange ConstantRange::srem(const ConstantRange &RHS) const {
  1126. if (isEmptySet() || RHS.isEmptySet())
  1127. return getEmpty();
  1128. if (const APInt *RHSInt = RHS.getSingleElement()) {
  1129. // SREM by null is UB.
  1130. if (RHSInt->isZero())
  1131. return getEmpty();
  1132. // Use APInt's implementation of SREM for single element ranges.
  1133. if (const APInt *LHSInt = getSingleElement())
  1134. return {LHSInt->srem(*RHSInt)};
  1135. }
  1136. ConstantRange AbsRHS = RHS.abs();
  1137. APInt MinAbsRHS = AbsRHS.getUnsignedMin();
  1138. APInt MaxAbsRHS = AbsRHS.getUnsignedMax();
  1139. // Modulus by zero is UB.
  1140. if (MaxAbsRHS.isZero())
  1141. return getEmpty();
  1142. if (MinAbsRHS.isZero())
  1143. ++MinAbsRHS;
  1144. APInt MinLHS = getSignedMin(), MaxLHS = getSignedMax();
  1145. if (MinLHS.isNonNegative()) {
  1146. // L % R for L < R is L.
  1147. if (MaxLHS.ult(MinAbsRHS))
  1148. return *this;
  1149. // L % R is <= L and < R.
  1150. APInt Upper = APIntOps::umin(MaxLHS, MaxAbsRHS - 1) + 1;
  1151. return ConstantRange(APInt::getZero(getBitWidth()), std::move(Upper));
  1152. }
  1153. // Same basic logic as above, but the result is negative.
  1154. if (MaxLHS.isNegative()) {
  1155. if (MinLHS.ugt(-MinAbsRHS))
  1156. return *this;
  1157. APInt Lower = APIntOps::umax(MinLHS, -MaxAbsRHS + 1);
  1158. return ConstantRange(std::move(Lower), APInt(getBitWidth(), 1));
  1159. }
  1160. // LHS range crosses zero.
  1161. APInt Lower = APIntOps::umax(MinLHS, -MaxAbsRHS + 1);
  1162. APInt Upper = APIntOps::umin(MaxLHS, MaxAbsRHS - 1) + 1;
  1163. return ConstantRange(std::move(Lower), std::move(Upper));
  1164. }
  1165. ConstantRange ConstantRange::binaryNot() const {
  1166. return ConstantRange(APInt::getAllOnes(getBitWidth())).sub(*this);
  1167. }
  1168. ConstantRange
  1169. ConstantRange::binaryAnd(const ConstantRange &Other) const {
  1170. if (isEmptySet() || Other.isEmptySet())
  1171. return getEmpty();
  1172. // Use APInt's implementation of AND for single element ranges.
  1173. if (isSingleElement() && Other.isSingleElement())
  1174. return {*getSingleElement() & *Other.getSingleElement()};
  1175. // TODO: replace this with something less conservative
  1176. APInt umin = APIntOps::umin(Other.getUnsignedMax(), getUnsignedMax());
  1177. return getNonEmpty(APInt::getZero(getBitWidth()), std::move(umin) + 1);
  1178. }
  1179. ConstantRange
  1180. ConstantRange::binaryOr(const ConstantRange &Other) const {
  1181. if (isEmptySet() || Other.isEmptySet())
  1182. return getEmpty();
  1183. // Use APInt's implementation of OR for single element ranges.
  1184. if (isSingleElement() && Other.isSingleElement())
  1185. return {*getSingleElement() | *Other.getSingleElement()};
  1186. // TODO: replace this with something less conservative
  1187. APInt umax = APIntOps::umax(getUnsignedMin(), Other.getUnsignedMin());
  1188. return getNonEmpty(std::move(umax), APInt::getZero(getBitWidth()));
  1189. }
  1190. ConstantRange ConstantRange::binaryXor(const ConstantRange &Other) const {
  1191. if (isEmptySet() || Other.isEmptySet())
  1192. return getEmpty();
  1193. // Use APInt's implementation of XOR for single element ranges.
  1194. if (isSingleElement() && Other.isSingleElement())
  1195. return {*getSingleElement() ^ *Other.getSingleElement()};
  1196. // Special-case binary complement, since we can give a precise answer.
  1197. if (Other.isSingleElement() && Other.getSingleElement()->isAllOnes())
  1198. return binaryNot();
  1199. if (isSingleElement() && getSingleElement()->isAllOnes())
  1200. return Other.binaryNot();
  1201. // TODO: replace this with something less conservative
  1202. return getFull();
  1203. }
  1204. ConstantRange
  1205. ConstantRange::shl(const ConstantRange &Other) const {
  1206. if (isEmptySet() || Other.isEmptySet())
  1207. return getEmpty();
  1208. APInt Min = getUnsignedMin();
  1209. APInt Max = getUnsignedMax();
  1210. if (const APInt *RHS = Other.getSingleElement()) {
  1211. unsigned BW = getBitWidth();
  1212. if (RHS->uge(BW))
  1213. return getEmpty();
  1214. unsigned EqualLeadingBits = (Min ^ Max).countLeadingZeros();
  1215. if (RHS->ule(EqualLeadingBits))
  1216. return getNonEmpty(Min << *RHS, (Max << *RHS) + 1);
  1217. return getNonEmpty(APInt::getZero(BW),
  1218. APInt::getBitsSetFrom(BW, RHS->getZExtValue()) + 1);
  1219. }
  1220. APInt OtherMax = Other.getUnsignedMax();
  1221. // There's overflow!
  1222. if (OtherMax.ugt(Max.countLeadingZeros()))
  1223. return getFull();
  1224. // FIXME: implement the other tricky cases
  1225. Min <<= Other.getUnsignedMin();
  1226. Max <<= OtherMax;
  1227. return ConstantRange::getNonEmpty(std::move(Min), std::move(Max) + 1);
  1228. }
  1229. ConstantRange
  1230. ConstantRange::lshr(const ConstantRange &Other) const {
  1231. if (isEmptySet() || Other.isEmptySet())
  1232. return getEmpty();
  1233. APInt max = getUnsignedMax().lshr(Other.getUnsignedMin()) + 1;
  1234. APInt min = getUnsignedMin().lshr(Other.getUnsignedMax());
  1235. return getNonEmpty(std::move(min), std::move(max));
  1236. }
  1237. ConstantRange
  1238. ConstantRange::ashr(const ConstantRange &Other) const {
  1239. if (isEmptySet() || Other.isEmptySet())
  1240. return getEmpty();
  1241. // May straddle zero, so handle both positive and negative cases.
  1242. // 'PosMax' is the upper bound of the result of the ashr
  1243. // operation, when Upper of the LHS of ashr is a non-negative.
  1244. // number. Since ashr of a non-negative number will result in a
  1245. // smaller number, the Upper value of LHS is shifted right with
  1246. // the minimum value of 'Other' instead of the maximum value.
  1247. APInt PosMax = getSignedMax().ashr(Other.getUnsignedMin()) + 1;
  1248. // 'PosMin' is the lower bound of the result of the ashr
  1249. // operation, when Lower of the LHS is a non-negative number.
  1250. // Since ashr of a non-negative number will result in a smaller
  1251. // number, the Lower value of LHS is shifted right with the
  1252. // maximum value of 'Other'.
  1253. APInt PosMin = getSignedMin().ashr(Other.getUnsignedMax());
  1254. // 'NegMax' is the upper bound of the result of the ashr
  1255. // operation, when Upper of the LHS of ashr is a negative number.
  1256. // Since 'ashr' of a negative number will result in a bigger
  1257. // number, the Upper value of LHS is shifted right with the
  1258. // maximum value of 'Other'.
  1259. APInt NegMax = getSignedMax().ashr(Other.getUnsignedMax()) + 1;
  1260. // 'NegMin' is the lower bound of the result of the ashr
  1261. // operation, when Lower of the LHS of ashr is a negative number.
  1262. // Since 'ashr' of a negative number will result in a bigger
  1263. // number, the Lower value of LHS is shifted right with the
  1264. // minimum value of 'Other'.
  1265. APInt NegMin = getSignedMin().ashr(Other.getUnsignedMin());
  1266. APInt max, min;
  1267. if (getSignedMin().isNonNegative()) {
  1268. // Upper and Lower of LHS are non-negative.
  1269. min = PosMin;
  1270. max = PosMax;
  1271. } else if (getSignedMax().isNegative()) {
  1272. // Upper and Lower of LHS are negative.
  1273. min = NegMin;
  1274. max = NegMax;
  1275. } else {
  1276. // Upper is non-negative and Lower is negative.
  1277. min = NegMin;
  1278. max = PosMax;
  1279. }
  1280. return getNonEmpty(std::move(min), std::move(max));
  1281. }
  1282. ConstantRange ConstantRange::uadd_sat(const ConstantRange &Other) const {
  1283. if (isEmptySet() || Other.isEmptySet())
  1284. return getEmpty();
  1285. APInt NewL = getUnsignedMin().uadd_sat(Other.getUnsignedMin());
  1286. APInt NewU = getUnsignedMax().uadd_sat(Other.getUnsignedMax()) + 1;
  1287. return getNonEmpty(std::move(NewL), std::move(NewU));
  1288. }
  1289. ConstantRange ConstantRange::sadd_sat(const ConstantRange &Other) const {
  1290. if (isEmptySet() || Other.isEmptySet())
  1291. return getEmpty();
  1292. APInt NewL = getSignedMin().sadd_sat(Other.getSignedMin());
  1293. APInt NewU = getSignedMax().sadd_sat(Other.getSignedMax()) + 1;
  1294. return getNonEmpty(std::move(NewL), std::move(NewU));
  1295. }
  1296. ConstantRange ConstantRange::usub_sat(const ConstantRange &Other) const {
  1297. if (isEmptySet() || Other.isEmptySet())
  1298. return getEmpty();
  1299. APInt NewL = getUnsignedMin().usub_sat(Other.getUnsignedMax());
  1300. APInt NewU = getUnsignedMax().usub_sat(Other.getUnsignedMin()) + 1;
  1301. return getNonEmpty(std::move(NewL), std::move(NewU));
  1302. }
  1303. ConstantRange ConstantRange::ssub_sat(const ConstantRange &Other) const {
  1304. if (isEmptySet() || Other.isEmptySet())
  1305. return getEmpty();
  1306. APInt NewL = getSignedMin().ssub_sat(Other.getSignedMax());
  1307. APInt NewU = getSignedMax().ssub_sat(Other.getSignedMin()) + 1;
  1308. return getNonEmpty(std::move(NewL), std::move(NewU));
  1309. }
  1310. ConstantRange ConstantRange::umul_sat(const ConstantRange &Other) const {
  1311. if (isEmptySet() || Other.isEmptySet())
  1312. return getEmpty();
  1313. APInt NewL = getUnsignedMin().umul_sat(Other.getUnsignedMin());
  1314. APInt NewU = getUnsignedMax().umul_sat(Other.getUnsignedMax()) + 1;
  1315. return getNonEmpty(std::move(NewL), std::move(NewU));
  1316. }
  1317. ConstantRange ConstantRange::smul_sat(const ConstantRange &Other) const {
  1318. if (isEmptySet() || Other.isEmptySet())
  1319. return getEmpty();
  1320. // Because we could be dealing with negative numbers here, the lower bound is
  1321. // the smallest of the cartesian product of the lower and upper ranges;
  1322. // for example:
  1323. // [-1,4) * [-2,3) = min(-1*-2, -1*2, 3*-2, 3*2) = -6.
  1324. // Similarly for the upper bound, swapping min for max.
  1325. APInt Min = getSignedMin();
  1326. APInt Max = getSignedMax();
  1327. APInt OtherMin = Other.getSignedMin();
  1328. APInt OtherMax = Other.getSignedMax();
  1329. auto L = {Min.smul_sat(OtherMin), Min.smul_sat(OtherMax),
  1330. Max.smul_sat(OtherMin), Max.smul_sat(OtherMax)};
  1331. auto Compare = [](const APInt &A, const APInt &B) { return A.slt(B); };
  1332. return getNonEmpty(std::min(L, Compare), std::max(L, Compare) + 1);
  1333. }
  1334. ConstantRange ConstantRange::ushl_sat(const ConstantRange &Other) const {
  1335. if (isEmptySet() || Other.isEmptySet())
  1336. return getEmpty();
  1337. APInt NewL = getUnsignedMin().ushl_sat(Other.getUnsignedMin());
  1338. APInt NewU = getUnsignedMax().ushl_sat(Other.getUnsignedMax()) + 1;
  1339. return getNonEmpty(std::move(NewL), std::move(NewU));
  1340. }
  1341. ConstantRange ConstantRange::sshl_sat(const ConstantRange &Other) const {
  1342. if (isEmptySet() || Other.isEmptySet())
  1343. return getEmpty();
  1344. APInt Min = getSignedMin(), Max = getSignedMax();
  1345. APInt ShAmtMin = Other.getUnsignedMin(), ShAmtMax = Other.getUnsignedMax();
  1346. APInt NewL = Min.sshl_sat(Min.isNonNegative() ? ShAmtMin : ShAmtMax);
  1347. APInt NewU = Max.sshl_sat(Max.isNegative() ? ShAmtMin : ShAmtMax) + 1;
  1348. return getNonEmpty(std::move(NewL), std::move(NewU));
  1349. }
  1350. ConstantRange ConstantRange::inverse() const {
  1351. if (isFullSet())
  1352. return getEmpty();
  1353. if (isEmptySet())
  1354. return getFull();
  1355. return ConstantRange(Upper, Lower);
  1356. }
  1357. ConstantRange ConstantRange::abs(bool IntMinIsPoison) const {
  1358. if (isEmptySet())
  1359. return getEmpty();
  1360. if (isSignWrappedSet()) {
  1361. APInt Lo;
  1362. // Check whether the range crosses zero.
  1363. if (Upper.isStrictlyPositive() || !Lower.isStrictlyPositive())
  1364. Lo = APInt::getZero(getBitWidth());
  1365. else
  1366. Lo = APIntOps::umin(Lower, -Upper + 1);
  1367. // If SignedMin is not poison, then it is included in the result range.
  1368. if (IntMinIsPoison)
  1369. return ConstantRange(Lo, APInt::getSignedMinValue(getBitWidth()));
  1370. else
  1371. return ConstantRange(Lo, APInt::getSignedMinValue(getBitWidth()) + 1);
  1372. }
  1373. APInt SMin = getSignedMin(), SMax = getSignedMax();
  1374. // Skip SignedMin if it is poison.
  1375. if (IntMinIsPoison && SMin.isMinSignedValue()) {
  1376. // The range may become empty if it *only* contains SignedMin.
  1377. if (SMax.isMinSignedValue())
  1378. return getEmpty();
  1379. ++SMin;
  1380. }
  1381. // All non-negative.
  1382. if (SMin.isNonNegative())
  1383. return *this;
  1384. // All negative.
  1385. if (SMax.isNegative())
  1386. return ConstantRange(-SMax, -SMin + 1);
  1387. // Range crosses zero.
  1388. return ConstantRange(APInt::getZero(getBitWidth()),
  1389. APIntOps::umax(-SMin, SMax) + 1);
  1390. }
  1391. ConstantRange::OverflowResult ConstantRange::unsignedAddMayOverflow(
  1392. const ConstantRange &Other) const {
  1393. if (isEmptySet() || Other.isEmptySet())
  1394. return OverflowResult::MayOverflow;
  1395. APInt Min = getUnsignedMin(), Max = getUnsignedMax();
  1396. APInt OtherMin = Other.getUnsignedMin(), OtherMax = Other.getUnsignedMax();
  1397. // a u+ b overflows high iff a u> ~b.
  1398. if (Min.ugt(~OtherMin))
  1399. return OverflowResult::AlwaysOverflowsHigh;
  1400. if (Max.ugt(~OtherMax))
  1401. return OverflowResult::MayOverflow;
  1402. return OverflowResult::NeverOverflows;
  1403. }
  1404. ConstantRange::OverflowResult ConstantRange::signedAddMayOverflow(
  1405. const ConstantRange &Other) const {
  1406. if (isEmptySet() || Other.isEmptySet())
  1407. return OverflowResult::MayOverflow;
  1408. APInt Min = getSignedMin(), Max = getSignedMax();
  1409. APInt OtherMin = Other.getSignedMin(), OtherMax = Other.getSignedMax();
  1410. APInt SignedMin = APInt::getSignedMinValue(getBitWidth());
  1411. APInt SignedMax = APInt::getSignedMaxValue(getBitWidth());
  1412. // a s+ b overflows high iff a s>=0 && b s>= 0 && a s> smax - b.
  1413. // a s+ b overflows low iff a s< 0 && b s< 0 && a s< smin - b.
  1414. if (Min.isNonNegative() && OtherMin.isNonNegative() &&
  1415. Min.sgt(SignedMax - OtherMin))
  1416. return OverflowResult::AlwaysOverflowsHigh;
  1417. if (Max.isNegative() && OtherMax.isNegative() &&
  1418. Max.slt(SignedMin - OtherMax))
  1419. return OverflowResult::AlwaysOverflowsLow;
  1420. if (Max.isNonNegative() && OtherMax.isNonNegative() &&
  1421. Max.sgt(SignedMax - OtherMax))
  1422. return OverflowResult::MayOverflow;
  1423. if (Min.isNegative() && OtherMin.isNegative() &&
  1424. Min.slt(SignedMin - OtherMin))
  1425. return OverflowResult::MayOverflow;
  1426. return OverflowResult::NeverOverflows;
  1427. }
  1428. ConstantRange::OverflowResult ConstantRange::unsignedSubMayOverflow(
  1429. const ConstantRange &Other) const {
  1430. if (isEmptySet() || Other.isEmptySet())
  1431. return OverflowResult::MayOverflow;
  1432. APInt Min = getUnsignedMin(), Max = getUnsignedMax();
  1433. APInt OtherMin = Other.getUnsignedMin(), OtherMax = Other.getUnsignedMax();
  1434. // a u- b overflows low iff a u< b.
  1435. if (Max.ult(OtherMin))
  1436. return OverflowResult::AlwaysOverflowsLow;
  1437. if (Min.ult(OtherMax))
  1438. return OverflowResult::MayOverflow;
  1439. return OverflowResult::NeverOverflows;
  1440. }
  1441. ConstantRange::OverflowResult ConstantRange::signedSubMayOverflow(
  1442. const ConstantRange &Other) const {
  1443. if (isEmptySet() || Other.isEmptySet())
  1444. return OverflowResult::MayOverflow;
  1445. APInt Min = getSignedMin(), Max = getSignedMax();
  1446. APInt OtherMin = Other.getSignedMin(), OtherMax = Other.getSignedMax();
  1447. APInt SignedMin = APInt::getSignedMinValue(getBitWidth());
  1448. APInt SignedMax = APInt::getSignedMaxValue(getBitWidth());
  1449. // a s- b overflows high iff a s>=0 && b s< 0 && a s> smax + b.
  1450. // a s- b overflows low iff a s< 0 && b s>= 0 && a s< smin + b.
  1451. if (Min.isNonNegative() && OtherMax.isNegative() &&
  1452. Min.sgt(SignedMax + OtherMax))
  1453. return OverflowResult::AlwaysOverflowsHigh;
  1454. if (Max.isNegative() && OtherMin.isNonNegative() &&
  1455. Max.slt(SignedMin + OtherMin))
  1456. return OverflowResult::AlwaysOverflowsLow;
  1457. if (Max.isNonNegative() && OtherMin.isNegative() &&
  1458. Max.sgt(SignedMax + OtherMin))
  1459. return OverflowResult::MayOverflow;
  1460. if (Min.isNegative() && OtherMax.isNonNegative() &&
  1461. Min.slt(SignedMin + OtherMax))
  1462. return OverflowResult::MayOverflow;
  1463. return OverflowResult::NeverOverflows;
  1464. }
  1465. ConstantRange::OverflowResult ConstantRange::unsignedMulMayOverflow(
  1466. const ConstantRange &Other) const {
  1467. if (isEmptySet() || Other.isEmptySet())
  1468. return OverflowResult::MayOverflow;
  1469. APInt Min = getUnsignedMin(), Max = getUnsignedMax();
  1470. APInt OtherMin = Other.getUnsignedMin(), OtherMax = Other.getUnsignedMax();
  1471. bool Overflow;
  1472. (void) Min.umul_ov(OtherMin, Overflow);
  1473. if (Overflow)
  1474. return OverflowResult::AlwaysOverflowsHigh;
  1475. (void) Max.umul_ov(OtherMax, Overflow);
  1476. if (Overflow)
  1477. return OverflowResult::MayOverflow;
  1478. return OverflowResult::NeverOverflows;
  1479. }
  1480. void ConstantRange::print(raw_ostream &OS) const {
  1481. if (isFullSet())
  1482. OS << "full-set";
  1483. else if (isEmptySet())
  1484. OS << "empty-set";
  1485. else
  1486. OS << "[" << Lower << "," << Upper << ")";
  1487. }
  1488. #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
  1489. LLVM_DUMP_METHOD void ConstantRange::dump() const {
  1490. print(dbgs());
  1491. }
  1492. #endif
  1493. ConstantRange llvm::getConstantRangeFromMetadata(const MDNode &Ranges) {
  1494. const unsigned NumRanges = Ranges.getNumOperands() / 2;
  1495. assert(NumRanges >= 1 && "Must have at least one range!");
  1496. assert(Ranges.getNumOperands() % 2 == 0 && "Must be a sequence of pairs");
  1497. auto *FirstLow = mdconst::extract<ConstantInt>(Ranges.getOperand(0));
  1498. auto *FirstHigh = mdconst::extract<ConstantInt>(Ranges.getOperand(1));
  1499. ConstantRange CR(FirstLow->getValue(), FirstHigh->getValue());
  1500. for (unsigned i = 1; i < NumRanges; ++i) {
  1501. auto *Low = mdconst::extract<ConstantInt>(Ranges.getOperand(2 * i + 0));
  1502. auto *High = mdconst::extract<ConstantInt>(Ranges.getOperand(2 * i + 1));
  1503. // Note: unionWith will potentially create a range that contains values not
  1504. // contained in any of the original N ranges.
  1505. CR = CR.unionWith(ConstantRange(Low->getValue(), High->getValue()));
  1506. }
  1507. return CR;
  1508. }