ValueTracking.cpp 135 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449
  1. //===- ValueTracking.cpp - Walk computations to compute properties --------===//
  2. //
  3. // The LLVM Compiler Infrastructure
  4. //
  5. // This file is distributed under the University of Illinois Open Source
  6. // License. See LICENSE.TXT for details.
  7. //
  8. //===----------------------------------------------------------------------===//
  9. //
  10. // This file contains routines that help analyze properties that chains of
  11. // computations have.
  12. //
  13. //===----------------------------------------------------------------------===//
  14. #include "llvm/Analysis/ValueTracking.h"
  15. #include "llvm/ADT/SmallPtrSet.h"
  16. #include "llvm/Analysis/AssumptionCache.h"
  17. #include "llvm/Analysis/InstructionSimplify.h"
  18. #include "llvm/Analysis/MemoryBuiltins.h"
  19. #include "llvm/Analysis/LoopInfo.h"
  20. #include "llvm/IR/CallSite.h"
  21. #include "llvm/IR/ConstantRange.h"
  22. #include "llvm/IR/Constants.h"
  23. #include "llvm/IR/DataLayout.h"
  24. #include "llvm/IR/Dominators.h"
  25. #include "llvm/IR/GetElementPtrTypeIterator.h"
  26. #include "llvm/IR/GlobalAlias.h"
  27. #include "llvm/IR/GlobalVariable.h"
  28. #include "llvm/IR/Instructions.h"
  29. #include "llvm/IR/IntrinsicInst.h"
  30. #include "llvm/IR/LLVMContext.h"
  31. #include "llvm/IR/Metadata.h"
  32. #include "llvm/IR/Operator.h"
  33. #include "llvm/IR/PatternMatch.h"
  34. #include "llvm/IR/Statepoint.h"
  35. #include "llvm/Support/Debug.h"
  36. #include "llvm/Support/MathExtras.h"
  37. #include <cstring>
  38. using namespace llvm;
  39. using namespace llvm::PatternMatch;
  40. const unsigned MaxDepth = 6;
  41. /// Enable an experimental feature to leverage information about dominating
  42. /// conditions to compute known bits. The individual options below control how
  43. /// hard we search. The defaults are choosen to be fairly aggressive. If you
  44. /// run into compile time problems when testing, scale them back and report
  45. /// your findings.
  46. static cl::opt<bool> EnableDomConditions("value-tracking-dom-conditions",
  47. cl::Hidden, cl::init(false));
  48. // This is expensive, so we only do it for the top level query value.
  49. // (TODO: evaluate cost vs profit, consider higher thresholds)
  50. static cl::opt<unsigned> DomConditionsMaxDepth("dom-conditions-max-depth",
  51. cl::Hidden, cl::init(1));
  52. /// How many dominating blocks should be scanned looking for dominating
  53. /// conditions?
  54. static cl::opt<unsigned> DomConditionsMaxDomBlocks("dom-conditions-dom-blocks",
  55. cl::Hidden,
  56. cl::init(20000));
  57. // Controls the number of uses of the value searched for possible
  58. // dominating comparisons.
  59. static cl::opt<unsigned> DomConditionsMaxUses("dom-conditions-max-uses",
  60. cl::Hidden, cl::init(2000));
  61. // If true, don't consider only compares whose only use is a branch.
  62. static cl::opt<bool> DomConditionsSingleCmpUse("dom-conditions-single-cmp-use",
  63. cl::Hidden, cl::init(false));
  64. /// Returns the bitwidth of the given scalar or pointer type (if unknown returns
  65. /// 0). For vector types, returns the element type's bitwidth.
  66. static unsigned getBitWidth(Type *Ty, const DataLayout &DL) {
  67. if (unsigned BitWidth = Ty->getScalarSizeInBits())
  68. return BitWidth;
  69. return DL.getPointerTypeSizeInBits(Ty);
  70. }
  71. // Many of these functions have internal versions that take an assumption
  72. // exclusion set. This is because of the potential for mutual recursion to
  73. // cause computeKnownBits to repeatedly visit the same assume intrinsic. The
  74. // classic case of this is assume(x = y), which will attempt to determine
  75. // bits in x from bits in y, which will attempt to determine bits in y from
  76. // bits in x, etc. Regarding the mutual recursion, computeKnownBits can call
  77. // isKnownNonZero, which calls computeKnownBits and ComputeSignBit and
  78. // isKnownToBeAPowerOfTwo (all of which can call computeKnownBits), and so on.
  79. typedef SmallPtrSet<const Value *, 8> ExclInvsSet;
  80. namespace {
  81. // Simplifying using an assume can only be done in a particular control-flow
  82. // context (the context instruction provides that context). If an assume and
  83. // the context instruction are not in the same block then the DT helps in
  84. // figuring out if we can use it.
  85. struct Query {
  86. ExclInvsSet ExclInvs;
  87. AssumptionCache *AC;
  88. const Instruction *CxtI;
  89. const DominatorTree *DT;
  90. Query(AssumptionCache *AC = nullptr, const Instruction *CxtI = nullptr,
  91. const DominatorTree *DT = nullptr)
  92. : AC(AC), CxtI(CxtI), DT(DT) {}
  93. Query(const Query &Q, const Value *NewExcl)
  94. : ExclInvs(Q.ExclInvs), AC(Q.AC), CxtI(Q.CxtI), DT(Q.DT) {
  95. ExclInvs.insert(NewExcl);
  96. }
  97. };
  98. } // end anonymous namespace
  99. // Given the provided Value and, potentially, a context instruction, return
  100. // the preferred context instruction (if any).
  101. static const Instruction *safeCxtI(const Value *V, const Instruction *CxtI) {
  102. // If we've been provided with a context instruction, then use that (provided
  103. // it has been inserted).
  104. if (CxtI && CxtI->getParent())
  105. return CxtI;
  106. // If the value is really an already-inserted instruction, then use that.
  107. CxtI = dyn_cast<Instruction>(V);
  108. if (CxtI && CxtI->getParent())
  109. return CxtI;
  110. return nullptr;
  111. }
  112. static void computeKnownBits(Value *V, APInt &KnownZero, APInt &KnownOne,
  113. const DataLayout &DL, unsigned Depth,
  114. const Query &Q);
  115. void llvm::computeKnownBits(Value *V, APInt &KnownZero, APInt &KnownOne,
  116. const DataLayout &DL, unsigned Depth,
  117. AssumptionCache *AC, const Instruction *CxtI,
  118. const DominatorTree *DT) {
  119. ::computeKnownBits(V, KnownZero, KnownOne, DL, Depth,
  120. Query(AC, safeCxtI(V, CxtI), DT));
  121. }
  122. bool llvm::haveNoCommonBitsSet(Value *LHS, Value *RHS, const DataLayout &DL,
  123. AssumptionCache *AC, const Instruction *CxtI,
  124. const DominatorTree *DT) {
  125. assert(LHS->getType() == RHS->getType() &&
  126. "LHS and RHS should have the same type");
  127. assert(LHS->getType()->isIntOrIntVectorTy() &&
  128. "LHS and RHS should be integers");
  129. IntegerType *IT = cast<IntegerType>(LHS->getType()->getScalarType());
  130. APInt LHSKnownZero(IT->getBitWidth(), 0), LHSKnownOne(IT->getBitWidth(), 0);
  131. APInt RHSKnownZero(IT->getBitWidth(), 0), RHSKnownOne(IT->getBitWidth(), 0);
  132. computeKnownBits(LHS, LHSKnownZero, LHSKnownOne, DL, 0, AC, CxtI, DT);
  133. computeKnownBits(RHS, RHSKnownZero, RHSKnownOne, DL, 0, AC, CxtI, DT);
  134. return (LHSKnownZero | RHSKnownZero).isAllOnesValue();
  135. }
  136. static void ComputeSignBit(Value *V, bool &KnownZero, bool &KnownOne,
  137. const DataLayout &DL, unsigned Depth,
  138. const Query &Q);
  139. void llvm::ComputeSignBit(Value *V, bool &KnownZero, bool &KnownOne,
  140. const DataLayout &DL, unsigned Depth,
  141. AssumptionCache *AC, const Instruction *CxtI,
  142. const DominatorTree *DT) {
  143. ::ComputeSignBit(V, KnownZero, KnownOne, DL, Depth,
  144. Query(AC, safeCxtI(V, CxtI), DT));
  145. }
  146. static bool isKnownToBeAPowerOfTwo(Value *V, bool OrZero, unsigned Depth,
  147. const Query &Q, const DataLayout &DL);
  148. bool llvm::isKnownToBeAPowerOfTwo(Value *V, const DataLayout &DL, bool OrZero,
  149. unsigned Depth, AssumptionCache *AC,
  150. const Instruction *CxtI,
  151. const DominatorTree *DT) {
  152. return ::isKnownToBeAPowerOfTwo(V, OrZero, Depth,
  153. Query(AC, safeCxtI(V, CxtI), DT), DL);
  154. }
  155. static bool isKnownNonZero(Value *V, const DataLayout &DL, unsigned Depth,
  156. const Query &Q);
  157. bool llvm::isKnownNonZero(Value *V, const DataLayout &DL, unsigned Depth,
  158. AssumptionCache *AC, const Instruction *CxtI,
  159. const DominatorTree *DT) {
  160. return ::isKnownNonZero(V, DL, Depth, Query(AC, safeCxtI(V, CxtI), DT));
  161. }
  162. static bool MaskedValueIsZero(Value *V, const APInt &Mask, const DataLayout &DL,
  163. unsigned Depth, const Query &Q);
  164. bool llvm::MaskedValueIsZero(Value *V, const APInt &Mask, const DataLayout &DL,
  165. unsigned Depth, AssumptionCache *AC,
  166. const Instruction *CxtI, const DominatorTree *DT) {
  167. return ::MaskedValueIsZero(V, Mask, DL, Depth,
  168. Query(AC, safeCxtI(V, CxtI), DT));
  169. }
  170. static unsigned ComputeNumSignBits(Value *V, const DataLayout &DL,
  171. unsigned Depth, const Query &Q);
  172. unsigned llvm::ComputeNumSignBits(Value *V, const DataLayout &DL,
  173. unsigned Depth, AssumptionCache *AC,
  174. const Instruction *CxtI,
  175. const DominatorTree *DT) {
  176. return ::ComputeNumSignBits(V, DL, Depth, Query(AC, safeCxtI(V, CxtI), DT));
  177. }
  178. static void computeKnownBitsAddSub(bool Add, Value *Op0, Value *Op1, bool NSW,
  179. APInt &KnownZero, APInt &KnownOne,
  180. APInt &KnownZero2, APInt &KnownOne2,
  181. const DataLayout &DL, unsigned Depth,
  182. const Query &Q) {
  183. if (!Add) {
  184. if (ConstantInt *CLHS = dyn_cast<ConstantInt>(Op0)) {
  185. // We know that the top bits of C-X are clear if X contains less bits
  186. // than C (i.e. no wrap-around can happen). For example, 20-X is
  187. // positive if we can prove that X is >= 0 and < 16.
  188. if (!CLHS->getValue().isNegative()) {
  189. unsigned BitWidth = KnownZero.getBitWidth();
  190. unsigned NLZ = (CLHS->getValue()+1).countLeadingZeros();
  191. // NLZ can't be BitWidth with no sign bit
  192. APInt MaskV = APInt::getHighBitsSet(BitWidth, NLZ+1);
  193. computeKnownBits(Op1, KnownZero2, KnownOne2, DL, Depth + 1, Q);
  194. // If all of the MaskV bits are known to be zero, then we know the
  195. // output top bits are zero, because we now know that the output is
  196. // from [0-C].
  197. if ((KnownZero2 & MaskV) == MaskV) {
  198. unsigned NLZ2 = CLHS->getValue().countLeadingZeros();
  199. // Top bits known zero.
  200. KnownZero = APInt::getHighBitsSet(BitWidth, NLZ2);
  201. }
  202. }
  203. }
  204. }
  205. unsigned BitWidth = KnownZero.getBitWidth();
  206. // If an initial sequence of bits in the result is not needed, the
  207. // corresponding bits in the operands are not needed.
  208. APInt LHSKnownZero(BitWidth, 0), LHSKnownOne(BitWidth, 0);
  209. computeKnownBits(Op0, LHSKnownZero, LHSKnownOne, DL, Depth + 1, Q);
  210. computeKnownBits(Op1, KnownZero2, KnownOne2, DL, Depth + 1, Q);
  211. // Carry in a 1 for a subtract, rather than a 0.
  212. APInt CarryIn(BitWidth, 0);
  213. if (!Add) {
  214. // Sum = LHS + ~RHS + 1
  215. std::swap(KnownZero2, KnownOne2);
  216. CarryIn.setBit(0);
  217. }
  218. APInt PossibleSumZero = ~LHSKnownZero + ~KnownZero2 + CarryIn;
  219. APInt PossibleSumOne = LHSKnownOne + KnownOne2 + CarryIn;
  220. // Compute known bits of the carry.
  221. APInt CarryKnownZero = ~(PossibleSumZero ^ LHSKnownZero ^ KnownZero2);
  222. APInt CarryKnownOne = PossibleSumOne ^ LHSKnownOne ^ KnownOne2;
  223. // Compute set of known bits (where all three relevant bits are known).
  224. APInt LHSKnown = LHSKnownZero | LHSKnownOne;
  225. APInt RHSKnown = KnownZero2 | KnownOne2;
  226. APInt CarryKnown = CarryKnownZero | CarryKnownOne;
  227. APInt Known = LHSKnown & RHSKnown & CarryKnown;
  228. assert((PossibleSumZero & Known) == (PossibleSumOne & Known) &&
  229. "known bits of sum differ");
  230. // Compute known bits of the result.
  231. KnownZero = ~PossibleSumOne & Known;
  232. KnownOne = PossibleSumOne & Known;
  233. // Are we still trying to solve for the sign bit?
  234. if (!Known.isNegative()) {
  235. if (NSW) {
  236. // Adding two non-negative numbers, or subtracting a negative number from
  237. // a non-negative one, can't wrap into negative.
  238. if (LHSKnownZero.isNegative() && KnownZero2.isNegative())
  239. KnownZero |= APInt::getSignBit(BitWidth);
  240. // Adding two negative numbers, or subtracting a non-negative number from
  241. // a negative one, can't wrap into non-negative.
  242. else if (LHSKnownOne.isNegative() && KnownOne2.isNegative())
  243. KnownOne |= APInt::getSignBit(BitWidth);
  244. }
  245. }
  246. }
  247. static void computeKnownBitsMul(Value *Op0, Value *Op1, bool NSW,
  248. APInt &KnownZero, APInt &KnownOne,
  249. APInt &KnownZero2, APInt &KnownOne2,
  250. const DataLayout &DL, unsigned Depth,
  251. const Query &Q) {
  252. unsigned BitWidth = KnownZero.getBitWidth();
  253. computeKnownBits(Op1, KnownZero, KnownOne, DL, Depth + 1, Q);
  254. computeKnownBits(Op0, KnownZero2, KnownOne2, DL, Depth + 1, Q);
  255. bool isKnownNegative = false;
  256. bool isKnownNonNegative = false;
  257. // If the multiplication is known not to overflow, compute the sign bit.
  258. if (NSW) {
  259. if (Op0 == Op1) {
  260. // The product of a number with itself is non-negative.
  261. isKnownNonNegative = true;
  262. } else {
  263. bool isKnownNonNegativeOp1 = KnownZero.isNegative();
  264. bool isKnownNonNegativeOp0 = KnownZero2.isNegative();
  265. bool isKnownNegativeOp1 = KnownOne.isNegative();
  266. bool isKnownNegativeOp0 = KnownOne2.isNegative();
  267. // The product of two numbers with the same sign is non-negative.
  268. isKnownNonNegative = (isKnownNegativeOp1 && isKnownNegativeOp0) ||
  269. (isKnownNonNegativeOp1 && isKnownNonNegativeOp0);
  270. // The product of a negative number and a non-negative number is either
  271. // negative or zero.
  272. if (!isKnownNonNegative)
  273. isKnownNegative = (isKnownNegativeOp1 && isKnownNonNegativeOp0 &&
  274. isKnownNonZero(Op0, DL, Depth, Q)) ||
  275. (isKnownNegativeOp0 && isKnownNonNegativeOp1 &&
  276. isKnownNonZero(Op1, DL, Depth, Q));
  277. }
  278. }
  279. // If low bits are zero in either operand, output low known-0 bits.
  280. // Also compute a conserative estimate for high known-0 bits.
  281. // More trickiness is possible, but this is sufficient for the
  282. // interesting case of alignment computation.
  283. KnownOne.clearAllBits();
  284. unsigned TrailZ = KnownZero.countTrailingOnes() +
  285. KnownZero2.countTrailingOnes();
  286. unsigned LeadZ = std::max(KnownZero.countLeadingOnes() +
  287. KnownZero2.countLeadingOnes(),
  288. BitWidth) - BitWidth;
  289. TrailZ = std::min(TrailZ, BitWidth);
  290. LeadZ = std::min(LeadZ, BitWidth);
  291. KnownZero = APInt::getLowBitsSet(BitWidth, TrailZ) |
  292. APInt::getHighBitsSet(BitWidth, LeadZ);
  293. // Only make use of no-wrap flags if we failed to compute the sign bit
  294. // directly. This matters if the multiplication always overflows, in
  295. // which case we prefer to follow the result of the direct computation,
  296. // though as the program is invoking undefined behaviour we can choose
  297. // whatever we like here.
  298. if (isKnownNonNegative && !KnownOne.isNegative())
  299. KnownZero.setBit(BitWidth - 1);
  300. else if (isKnownNegative && !KnownZero.isNegative())
  301. KnownOne.setBit(BitWidth - 1);
  302. }
  303. void llvm::computeKnownBitsFromRangeMetadata(const MDNode &Ranges,
  304. APInt &KnownZero) {
  305. unsigned BitWidth = KnownZero.getBitWidth();
  306. unsigned NumRanges = Ranges.getNumOperands() / 2;
  307. assert(NumRanges >= 1);
  308. // Use the high end of the ranges to find leading zeros.
  309. unsigned MinLeadingZeros = BitWidth;
  310. for (unsigned i = 0; i < NumRanges; ++i) {
  311. ConstantInt *Lower =
  312. mdconst::extract<ConstantInt>(Ranges.getOperand(2 * i + 0));
  313. ConstantInt *Upper =
  314. mdconst::extract<ConstantInt>(Ranges.getOperand(2 * i + 1));
  315. ConstantRange Range(Lower->getValue(), Upper->getValue());
  316. if (Range.isWrappedSet())
  317. MinLeadingZeros = 0; // -1 has no zeros
  318. unsigned LeadingZeros = (Upper->getValue() - 1).countLeadingZeros();
  319. MinLeadingZeros = std::min(LeadingZeros, MinLeadingZeros);
  320. }
  321. KnownZero = APInt::getHighBitsSet(BitWidth, MinLeadingZeros);
  322. }
  323. static bool isEphemeralValueOf(Instruction *I, const Value *E) {
  324. SmallVector<const Value *, 16> WorkSet(1, I);
  325. SmallPtrSet<const Value *, 32> Visited;
  326. SmallPtrSet<const Value *, 16> EphValues;
  327. while (!WorkSet.empty()) {
  328. const Value *V = WorkSet.pop_back_val();
  329. if (!Visited.insert(V).second)
  330. continue;
  331. // If all uses of this value are ephemeral, then so is this value.
  332. bool FoundNEUse = false;
  333. for (const User *I : V->users())
  334. if (!EphValues.count(I)) {
  335. FoundNEUse = true;
  336. break;
  337. }
  338. if (!FoundNEUse) {
  339. if (V == E)
  340. return true;
  341. EphValues.insert(V);
  342. if (const User *U = dyn_cast<User>(V))
  343. for (User::const_op_iterator J = U->op_begin(), JE = U->op_end();
  344. J != JE; ++J) {
  345. if (isSafeToSpeculativelyExecute(*J))
  346. WorkSet.push_back(*J);
  347. }
  348. }
  349. }
  350. return false;
  351. }
  352. // Is this an intrinsic that cannot be speculated but also cannot trap?
  353. static bool isAssumeLikeIntrinsic(const Instruction *I) {
  354. if (const CallInst *CI = dyn_cast<CallInst>(I))
  355. if (Function *F = CI->getCalledFunction())
  356. switch (F->getIntrinsicID()) {
  357. default: break;
  358. // FIXME: This list is repeated from NoTTI::getIntrinsicCost.
  359. case Intrinsic::assume:
  360. case Intrinsic::dbg_declare:
  361. case Intrinsic::dbg_value:
  362. case Intrinsic::invariant_start:
  363. case Intrinsic::invariant_end:
  364. case Intrinsic::lifetime_start:
  365. case Intrinsic::lifetime_end:
  366. case Intrinsic::objectsize:
  367. case Intrinsic::ptr_annotation:
  368. case Intrinsic::var_annotation:
  369. return true;
  370. }
  371. return false;
  372. }
  373. static bool isValidAssumeForContext(Value *V, const Query &Q) {
  374. Instruction *Inv = cast<Instruction>(V);
  375. // There are two restrictions on the use of an assume:
  376. // 1. The assume must dominate the context (or the control flow must
  377. // reach the assume whenever it reaches the context).
  378. // 2. The context must not be in the assume's set of ephemeral values
  379. // (otherwise we will use the assume to prove that the condition
  380. // feeding the assume is trivially true, thus causing the removal of
  381. // the assume).
  382. if (Q.DT) {
  383. if (Q.DT->dominates(Inv, Q.CxtI)) {
  384. return true;
  385. } else if (Inv->getParent() == Q.CxtI->getParent()) {
  386. // The context comes first, but they're both in the same block. Make sure
  387. // there is nothing in between that might interrupt the control flow.
  388. for (BasicBlock::const_iterator I =
  389. std::next(BasicBlock::const_iterator(Q.CxtI)),
  390. IE(Inv); I != IE; ++I)
  391. if (!isSafeToSpeculativelyExecute(I) && !isAssumeLikeIntrinsic(I))
  392. return false;
  393. return !isEphemeralValueOf(Inv, Q.CxtI);
  394. }
  395. return false;
  396. }
  397. // When we don't have a DT, we do a limited search...
  398. if (Inv->getParent() == Q.CxtI->getParent()->getSinglePredecessor()) {
  399. return true;
  400. } else if (Inv->getParent() == Q.CxtI->getParent()) {
  401. // Search forward from the assume until we reach the context (or the end
  402. // of the block); the common case is that the assume will come first.
  403. for (BasicBlock::iterator I = std::next(BasicBlock::iterator(Inv)),
  404. IE = Inv->getParent()->end(); I != IE; ++I)
  405. if (I == Q.CxtI)
  406. return true;
  407. // The context must come first...
  408. for (BasicBlock::const_iterator I =
  409. std::next(BasicBlock::const_iterator(Q.CxtI)),
  410. IE(Inv); I != IE; ++I)
  411. if (!isSafeToSpeculativelyExecute(I) && !isAssumeLikeIntrinsic(I))
  412. return false;
  413. return !isEphemeralValueOf(Inv, Q.CxtI);
  414. }
  415. return false;
  416. }
  417. bool llvm::isValidAssumeForContext(const Instruction *I,
  418. const Instruction *CxtI,
  419. const DominatorTree *DT) {
  420. return ::isValidAssumeForContext(const_cast<Instruction *>(I),
  421. Query(nullptr, CxtI, DT));
  422. }
  423. template<typename LHS, typename RHS>
  424. inline match_combine_or<CmpClass_match<LHS, RHS, ICmpInst, ICmpInst::Predicate>,
  425. CmpClass_match<RHS, LHS, ICmpInst, ICmpInst::Predicate>>
  426. m_c_ICmp(ICmpInst::Predicate &Pred, const LHS &L, const RHS &R) {
  427. return m_CombineOr(m_ICmp(Pred, L, R), m_ICmp(Pred, R, L));
  428. }
  429. template<typename LHS, typename RHS>
  430. inline match_combine_or<BinaryOp_match<LHS, RHS, Instruction::And>,
  431. BinaryOp_match<RHS, LHS, Instruction::And>>
  432. m_c_And(const LHS &L, const RHS &R) {
  433. return m_CombineOr(m_And(L, R), m_And(R, L));
  434. }
  435. template<typename LHS, typename RHS>
  436. inline match_combine_or<BinaryOp_match<LHS, RHS, Instruction::Or>,
  437. BinaryOp_match<RHS, LHS, Instruction::Or>>
  438. m_c_Or(const LHS &L, const RHS &R) {
  439. return m_CombineOr(m_Or(L, R), m_Or(R, L));
  440. }
  441. template<typename LHS, typename RHS>
  442. inline match_combine_or<BinaryOp_match<LHS, RHS, Instruction::Xor>,
  443. BinaryOp_match<RHS, LHS, Instruction::Xor>>
  444. m_c_Xor(const LHS &L, const RHS &R) {
  445. return m_CombineOr(m_Xor(L, R), m_Xor(R, L));
  446. }
  447. /// Compute known bits in 'V' under the assumption that the condition 'Cmp' is
  448. /// true (at the context instruction.) This is mostly a utility function for
  449. /// the prototype dominating conditions reasoning below.
  450. static void computeKnownBitsFromTrueCondition(Value *V, ICmpInst *Cmp,
  451. APInt &KnownZero,
  452. APInt &KnownOne,
  453. const DataLayout &DL,
  454. unsigned Depth, const Query &Q) {
  455. Value *LHS = Cmp->getOperand(0);
  456. Value *RHS = Cmp->getOperand(1);
  457. // TODO: We could potentially be more aggressive here. This would be worth
  458. // evaluating. If we can, explore commoning this code with the assume
  459. // handling logic.
  460. if (LHS != V && RHS != V)
  461. return;
  462. const unsigned BitWidth = KnownZero.getBitWidth();
  463. switch (Cmp->getPredicate()) {
  464. default:
  465. // We know nothing from this condition
  466. break;
  467. // TODO: implement unsigned bound from below (known one bits)
  468. // TODO: common condition check implementations with assumes
  469. // TODO: implement other patterns from assume (e.g. V & B == A)
  470. case ICmpInst::ICMP_SGT:
  471. if (LHS == V) {
  472. APInt KnownZeroTemp(BitWidth, 0), KnownOneTemp(BitWidth, 0);
  473. computeKnownBits(RHS, KnownZeroTemp, KnownOneTemp, DL, Depth + 1, Q);
  474. if (KnownOneTemp.isAllOnesValue() || KnownZeroTemp.isNegative()) {
  475. // We know that the sign bit is zero.
  476. KnownZero |= APInt::getSignBit(BitWidth);
  477. }
  478. }
  479. break;
  480. case ICmpInst::ICMP_EQ:
  481. {
  482. APInt KnownZeroTemp(BitWidth, 0), KnownOneTemp(BitWidth, 0);
  483. if (LHS == V)
  484. computeKnownBits(RHS, KnownZeroTemp, KnownOneTemp, DL, Depth + 1, Q);
  485. else if (RHS == V)
  486. computeKnownBits(LHS, KnownZeroTemp, KnownOneTemp, DL, Depth + 1, Q);
  487. else
  488. llvm_unreachable("missing use?");
  489. KnownZero |= KnownZeroTemp;
  490. KnownOne |= KnownOneTemp;
  491. }
  492. break;
  493. case ICmpInst::ICMP_ULE:
  494. if (LHS == V) {
  495. APInt KnownZeroTemp(BitWidth, 0), KnownOneTemp(BitWidth, 0);
  496. computeKnownBits(RHS, KnownZeroTemp, KnownOneTemp, DL, Depth + 1, Q);
  497. // The known zero bits carry over
  498. unsigned SignBits = KnownZeroTemp.countLeadingOnes();
  499. KnownZero |= APInt::getHighBitsSet(BitWidth, SignBits);
  500. }
  501. break;
  502. case ICmpInst::ICMP_ULT:
  503. if (LHS == V) {
  504. APInt KnownZeroTemp(BitWidth, 0), KnownOneTemp(BitWidth, 0);
  505. computeKnownBits(RHS, KnownZeroTemp, KnownOneTemp, DL, Depth + 1, Q);
  506. // Whatever high bits in rhs are zero are known to be zero (if rhs is a
  507. // power of 2, then one more).
  508. unsigned SignBits = KnownZeroTemp.countLeadingOnes();
  509. if (isKnownToBeAPowerOfTwo(RHS, false, Depth + 1, Query(Q, Cmp), DL))
  510. SignBits++;
  511. KnownZero |= APInt::getHighBitsSet(BitWidth, SignBits);
  512. }
  513. break;
  514. };
  515. }
  516. /// Compute known bits in 'V' from conditions which are known to be true along
  517. /// all paths leading to the context instruction. In particular, look for
  518. /// cases where one branch of an interesting condition dominates the context
  519. /// instruction. This does not do general dataflow.
  520. /// NOTE: This code is EXPERIMENTAL and currently off by default.
  521. static void computeKnownBitsFromDominatingCondition(Value *V, APInt &KnownZero,
  522. APInt &KnownOne,
  523. const DataLayout &DL,
  524. unsigned Depth,
  525. const Query &Q) {
  526. // Need both the dominator tree and the query location to do anything useful
  527. if (!Q.DT || !Q.CxtI)
  528. return;
  529. Instruction *Cxt = const_cast<Instruction *>(Q.CxtI);
  530. // Avoid useless work
  531. if (auto VI = dyn_cast<Instruction>(V))
  532. if (VI->getParent() == Cxt->getParent())
  533. return;
  534. // Note: We currently implement two options. It's not clear which of these
  535. // will survive long term, we need data for that.
  536. // Option 1 - Try walking the dominator tree looking for conditions which
  537. // might apply. This works well for local conditions (loop guards, etc..),
  538. // but not as well for things far from the context instruction (presuming a
  539. // low max blocks explored). If we can set an high enough limit, this would
  540. // be all we need.
  541. // Option 2 - We restrict out search to those conditions which are uses of
  542. // the value we're interested in. This is independent of dom structure,
  543. // but is slightly less powerful without looking through lots of use chains.
  544. // It does handle conditions far from the context instruction (e.g. early
  545. // function exits on entry) really well though.
  546. // Option 1 - Search the dom tree
  547. unsigned NumBlocksExplored = 0;
  548. BasicBlock *Current = Cxt->getParent();
  549. while (true) {
  550. // Stop searching if we've gone too far up the chain
  551. if (NumBlocksExplored >= DomConditionsMaxDomBlocks)
  552. break;
  553. NumBlocksExplored++;
  554. if (!Q.DT->getNode(Current)->getIDom())
  555. break;
  556. Current = Q.DT->getNode(Current)->getIDom()->getBlock();
  557. if (!Current)
  558. // found function entry
  559. break;
  560. BranchInst *BI = dyn_cast<BranchInst>(Current->getTerminator());
  561. if (!BI || BI->isUnconditional())
  562. continue;
  563. ICmpInst *Cmp = dyn_cast<ICmpInst>(BI->getCondition());
  564. if (!Cmp)
  565. continue;
  566. // We're looking for conditions that are guaranteed to hold at the context
  567. // instruction. Finding a condition where one path dominates the context
  568. // isn't enough because both the true and false cases could merge before
  569. // the context instruction we're actually interested in. Instead, we need
  570. // to ensure that the taken *edge* dominates the context instruction.
  571. BasicBlock *BB0 = BI->getSuccessor(0);
  572. BasicBlockEdge Edge(BI->getParent(), BB0);
  573. if (!Edge.isSingleEdge() || !Q.DT->dominates(Edge, Q.CxtI->getParent()))
  574. continue;
  575. computeKnownBitsFromTrueCondition(V, Cmp, KnownZero, KnownOne, DL, Depth,
  576. Q);
  577. }
  578. // Option 2 - Search the other uses of V
  579. unsigned NumUsesExplored = 0;
  580. for (auto U : V->users()) {
  581. // Avoid massive lists
  582. if (NumUsesExplored >= DomConditionsMaxUses)
  583. break;
  584. NumUsesExplored++;
  585. // Consider only compare instructions uniquely controlling a branch
  586. ICmpInst *Cmp = dyn_cast<ICmpInst>(U);
  587. if (!Cmp)
  588. continue;
  589. if (DomConditionsSingleCmpUse && !Cmp->hasOneUse())
  590. continue;
  591. for (auto *CmpU : Cmp->users()) {
  592. BranchInst *BI = dyn_cast<BranchInst>(CmpU);
  593. if (!BI || BI->isUnconditional())
  594. continue;
  595. // We're looking for conditions that are guaranteed to hold at the
  596. // context instruction. Finding a condition where one path dominates
  597. // the context isn't enough because both the true and false cases could
  598. // merge before the context instruction we're actually interested in.
  599. // Instead, we need to ensure that the taken *edge* dominates the context
  600. // instruction.
  601. BasicBlock *BB0 = BI->getSuccessor(0);
  602. BasicBlockEdge Edge(BI->getParent(), BB0);
  603. if (!Edge.isSingleEdge() || !Q.DT->dominates(Edge, Q.CxtI->getParent()))
  604. continue;
  605. computeKnownBitsFromTrueCondition(V, Cmp, KnownZero, KnownOne, DL, Depth,
  606. Q);
  607. }
  608. }
  609. }
  610. static void computeKnownBitsFromAssume(Value *V, APInt &KnownZero,
  611. APInt &KnownOne, const DataLayout &DL,
  612. unsigned Depth, const Query &Q) {
  613. // Use of assumptions is context-sensitive. If we don't have a context, we
  614. // cannot use them!
  615. if (!Q.AC || !Q.CxtI)
  616. return;
  617. unsigned BitWidth = KnownZero.getBitWidth();
  618. for (auto &AssumeVH : Q.AC->assumptions()) {
  619. if (!AssumeVH)
  620. continue;
  621. CallInst *I = cast<CallInst>(AssumeVH);
  622. assert(I->getParent()->getParent() == Q.CxtI->getParent()->getParent() &&
  623. "Got assumption for the wrong function!");
  624. if (Q.ExclInvs.count(I))
  625. continue;
  626. // Warning: This loop can end up being somewhat performance sensetive.
  627. // We're running this loop for once for each value queried resulting in a
  628. // runtime of ~O(#assumes * #values).
  629. assert(I->getCalledFunction()->getIntrinsicID() == Intrinsic::assume &&
  630. "must be an assume intrinsic");
  631. Value *Arg = I->getArgOperand(0);
  632. if (Arg == V && isValidAssumeForContext(I, Q)) {
  633. assert(BitWidth == 1 && "assume operand is not i1?");
  634. KnownZero.clearAllBits();
  635. KnownOne.setAllBits();
  636. return;
  637. }
  638. // The remaining tests are all recursive, so bail out if we hit the limit.
  639. if (Depth == MaxDepth)
  640. continue;
  641. Value *A, *B;
  642. auto m_V = m_CombineOr(m_Specific(V),
  643. m_CombineOr(m_PtrToInt(m_Specific(V)),
  644. m_BitCast(m_Specific(V))));
  645. CmpInst::Predicate Pred;
  646. ConstantInt *C;
  647. // assume(v = a)
  648. if (match(Arg, m_c_ICmp(Pred, m_V, m_Value(A))) &&
  649. Pred == ICmpInst::ICMP_EQ && isValidAssumeForContext(I, Q)) {
  650. APInt RHSKnownZero(BitWidth, 0), RHSKnownOne(BitWidth, 0);
  651. computeKnownBits(A, RHSKnownZero, RHSKnownOne, DL, Depth+1, Query(Q, I));
  652. KnownZero |= RHSKnownZero;
  653. KnownOne |= RHSKnownOne;
  654. // assume(v & b = a)
  655. } else if (match(Arg,
  656. m_c_ICmp(Pred, m_c_And(m_V, m_Value(B)), m_Value(A))) &&
  657. Pred == ICmpInst::ICMP_EQ && isValidAssumeForContext(I, Q)) {
  658. APInt RHSKnownZero(BitWidth, 0), RHSKnownOne(BitWidth, 0);
  659. computeKnownBits(A, RHSKnownZero, RHSKnownOne, DL, Depth+1, Query(Q, I));
  660. APInt MaskKnownZero(BitWidth, 0), MaskKnownOne(BitWidth, 0);
  661. computeKnownBits(B, MaskKnownZero, MaskKnownOne, DL, Depth+1, Query(Q, I));
  662. // For those bits in the mask that are known to be one, we can propagate
  663. // known bits from the RHS to V.
  664. KnownZero |= RHSKnownZero & MaskKnownOne;
  665. KnownOne |= RHSKnownOne & MaskKnownOne;
  666. // assume(~(v & b) = a)
  667. } else if (match(Arg, m_c_ICmp(Pred, m_Not(m_c_And(m_V, m_Value(B))),
  668. m_Value(A))) &&
  669. Pred == ICmpInst::ICMP_EQ && isValidAssumeForContext(I, Q)) {
  670. APInt RHSKnownZero(BitWidth, 0), RHSKnownOne(BitWidth, 0);
  671. computeKnownBits(A, RHSKnownZero, RHSKnownOne, DL, Depth+1, Query(Q, I));
  672. APInt MaskKnownZero(BitWidth, 0), MaskKnownOne(BitWidth, 0);
  673. computeKnownBits(B, MaskKnownZero, MaskKnownOne, DL, Depth+1, Query(Q, I));
  674. // For those bits in the mask that are known to be one, we can propagate
  675. // inverted known bits from the RHS to V.
  676. KnownZero |= RHSKnownOne & MaskKnownOne;
  677. KnownOne |= RHSKnownZero & MaskKnownOne;
  678. // assume(v | b = a)
  679. } else if (match(Arg,
  680. m_c_ICmp(Pred, m_c_Or(m_V, m_Value(B)), m_Value(A))) &&
  681. Pred == ICmpInst::ICMP_EQ && isValidAssumeForContext(I, Q)) {
  682. APInt RHSKnownZero(BitWidth, 0), RHSKnownOne(BitWidth, 0);
  683. computeKnownBits(A, RHSKnownZero, RHSKnownOne, DL, Depth+1, Query(Q, I));
  684. APInt BKnownZero(BitWidth, 0), BKnownOne(BitWidth, 0);
  685. computeKnownBits(B, BKnownZero, BKnownOne, DL, Depth+1, Query(Q, I));
  686. // For those bits in B that are known to be zero, we can propagate known
  687. // bits from the RHS to V.
  688. KnownZero |= RHSKnownZero & BKnownZero;
  689. KnownOne |= RHSKnownOne & BKnownZero;
  690. // assume(~(v | b) = a)
  691. } else if (match(Arg, m_c_ICmp(Pred, m_Not(m_c_Or(m_V, m_Value(B))),
  692. m_Value(A))) &&
  693. Pred == ICmpInst::ICMP_EQ && isValidAssumeForContext(I, Q)) {
  694. APInt RHSKnownZero(BitWidth, 0), RHSKnownOne(BitWidth, 0);
  695. computeKnownBits(A, RHSKnownZero, RHSKnownOne, DL, Depth+1, Query(Q, I));
  696. APInt BKnownZero(BitWidth, 0), BKnownOne(BitWidth, 0);
  697. computeKnownBits(B, BKnownZero, BKnownOne, DL, Depth+1, Query(Q, I));
  698. // For those bits in B that are known to be zero, we can propagate
  699. // inverted known bits from the RHS to V.
  700. KnownZero |= RHSKnownOne & BKnownZero;
  701. KnownOne |= RHSKnownZero & BKnownZero;
  702. // assume(v ^ b = a)
  703. } else if (match(Arg,
  704. m_c_ICmp(Pred, m_c_Xor(m_V, m_Value(B)), m_Value(A))) &&
  705. Pred == ICmpInst::ICMP_EQ && isValidAssumeForContext(I, Q)) {
  706. APInt RHSKnownZero(BitWidth, 0), RHSKnownOne(BitWidth, 0);
  707. computeKnownBits(A, RHSKnownZero, RHSKnownOne, DL, Depth+1, Query(Q, I));
  708. APInt BKnownZero(BitWidth, 0), BKnownOne(BitWidth, 0);
  709. computeKnownBits(B, BKnownZero, BKnownOne, DL, Depth+1, Query(Q, I));
  710. // For those bits in B that are known to be zero, we can propagate known
  711. // bits from the RHS to V. For those bits in B that are known to be one,
  712. // we can propagate inverted known bits from the RHS to V.
  713. KnownZero |= RHSKnownZero & BKnownZero;
  714. KnownOne |= RHSKnownOne & BKnownZero;
  715. KnownZero |= RHSKnownOne & BKnownOne;
  716. KnownOne |= RHSKnownZero & BKnownOne;
  717. // assume(~(v ^ b) = a)
  718. } else if (match(Arg, m_c_ICmp(Pred, m_Not(m_c_Xor(m_V, m_Value(B))),
  719. m_Value(A))) &&
  720. Pred == ICmpInst::ICMP_EQ && isValidAssumeForContext(I, Q)) {
  721. APInt RHSKnownZero(BitWidth, 0), RHSKnownOne(BitWidth, 0);
  722. computeKnownBits(A, RHSKnownZero, RHSKnownOne, DL, Depth+1, Query(Q, I));
  723. APInt BKnownZero(BitWidth, 0), BKnownOne(BitWidth, 0);
  724. computeKnownBits(B, BKnownZero, BKnownOne, DL, Depth+1, Query(Q, I));
  725. // For those bits in B that are known to be zero, we can propagate
  726. // inverted known bits from the RHS to V. For those bits in B that are
  727. // known to be one, we can propagate known bits from the RHS to V.
  728. KnownZero |= RHSKnownOne & BKnownZero;
  729. KnownOne |= RHSKnownZero & BKnownZero;
  730. KnownZero |= RHSKnownZero & BKnownOne;
  731. KnownOne |= RHSKnownOne & BKnownOne;
  732. // assume(v << c = a)
  733. } else if (match(Arg, m_c_ICmp(Pred, m_Shl(m_V, m_ConstantInt(C)),
  734. m_Value(A))) &&
  735. Pred == ICmpInst::ICMP_EQ && isValidAssumeForContext(I, Q)) {
  736. APInt RHSKnownZero(BitWidth, 0), RHSKnownOne(BitWidth, 0);
  737. computeKnownBits(A, RHSKnownZero, RHSKnownOne, DL, Depth+1, Query(Q, I));
  738. // For those bits in RHS that are known, we can propagate them to known
  739. // bits in V shifted to the right by C.
  740. KnownZero |= RHSKnownZero.lshr(C->getZExtValue());
  741. KnownOne |= RHSKnownOne.lshr(C->getZExtValue());
  742. // assume(~(v << c) = a)
  743. } else if (match(Arg, m_c_ICmp(Pred, m_Not(m_Shl(m_V, m_ConstantInt(C))),
  744. m_Value(A))) &&
  745. Pred == ICmpInst::ICMP_EQ && isValidAssumeForContext(I, Q)) {
  746. APInt RHSKnownZero(BitWidth, 0), RHSKnownOne(BitWidth, 0);
  747. computeKnownBits(A, RHSKnownZero, RHSKnownOne, DL, Depth+1, Query(Q, I));
  748. // For those bits in RHS that are known, we can propagate them inverted
  749. // to known bits in V shifted to the right by C.
  750. KnownZero |= RHSKnownOne.lshr(C->getZExtValue());
  751. KnownOne |= RHSKnownZero.lshr(C->getZExtValue());
  752. // assume(v >> c = a)
  753. } else if (match(Arg,
  754. m_c_ICmp(Pred, m_CombineOr(m_LShr(m_V, m_ConstantInt(C)),
  755. m_AShr(m_V, m_ConstantInt(C))),
  756. m_Value(A))) &&
  757. Pred == ICmpInst::ICMP_EQ && isValidAssumeForContext(I, Q)) {
  758. APInt RHSKnownZero(BitWidth, 0), RHSKnownOne(BitWidth, 0);
  759. computeKnownBits(A, RHSKnownZero, RHSKnownOne, DL, Depth+1, Query(Q, I));
  760. // For those bits in RHS that are known, we can propagate them to known
  761. // bits in V shifted to the right by C.
  762. KnownZero |= RHSKnownZero << C->getZExtValue();
  763. KnownOne |= RHSKnownOne << C->getZExtValue();
  764. // assume(~(v >> c) = a)
  765. } else if (match(Arg, m_c_ICmp(Pred, m_Not(m_CombineOr(
  766. m_LShr(m_V, m_ConstantInt(C)),
  767. m_AShr(m_V, m_ConstantInt(C)))),
  768. m_Value(A))) &&
  769. Pred == ICmpInst::ICMP_EQ && isValidAssumeForContext(I, Q)) {
  770. APInt RHSKnownZero(BitWidth, 0), RHSKnownOne(BitWidth, 0);
  771. computeKnownBits(A, RHSKnownZero, RHSKnownOne, DL, Depth+1, Query(Q, I));
  772. // For those bits in RHS that are known, we can propagate them inverted
  773. // to known bits in V shifted to the right by C.
  774. KnownZero |= RHSKnownOne << C->getZExtValue();
  775. KnownOne |= RHSKnownZero << C->getZExtValue();
  776. // assume(v >=_s c) where c is non-negative
  777. } else if (match(Arg, m_ICmp(Pred, m_V, m_Value(A))) &&
  778. Pred == ICmpInst::ICMP_SGE && isValidAssumeForContext(I, Q)) {
  779. APInt RHSKnownZero(BitWidth, 0), RHSKnownOne(BitWidth, 0);
  780. computeKnownBits(A, RHSKnownZero, RHSKnownOne, DL, Depth+1, Query(Q, I));
  781. if (RHSKnownZero.isNegative()) {
  782. // We know that the sign bit is zero.
  783. KnownZero |= APInt::getSignBit(BitWidth);
  784. }
  785. // assume(v >_s c) where c is at least -1.
  786. } else if (match(Arg, m_ICmp(Pred, m_V, m_Value(A))) &&
  787. Pred == ICmpInst::ICMP_SGT && isValidAssumeForContext(I, Q)) {
  788. APInt RHSKnownZero(BitWidth, 0), RHSKnownOne(BitWidth, 0);
  789. computeKnownBits(A, RHSKnownZero, RHSKnownOne, DL, Depth+1, Query(Q, I));
  790. if (RHSKnownOne.isAllOnesValue() || RHSKnownZero.isNegative()) {
  791. // We know that the sign bit is zero.
  792. KnownZero |= APInt::getSignBit(BitWidth);
  793. }
  794. // assume(v <=_s c) where c is negative
  795. } else if (match(Arg, m_ICmp(Pred, m_V, m_Value(A))) &&
  796. Pred == ICmpInst::ICMP_SLE && isValidAssumeForContext(I, Q)) {
  797. APInt RHSKnownZero(BitWidth, 0), RHSKnownOne(BitWidth, 0);
  798. computeKnownBits(A, RHSKnownZero, RHSKnownOne, DL, Depth+1, Query(Q, I));
  799. if (RHSKnownOne.isNegative()) {
  800. // We know that the sign bit is one.
  801. KnownOne |= APInt::getSignBit(BitWidth);
  802. }
  803. // assume(v <_s c) where c is non-positive
  804. } else if (match(Arg, m_ICmp(Pred, m_V, m_Value(A))) &&
  805. Pred == ICmpInst::ICMP_SLT && isValidAssumeForContext(I, Q)) {
  806. APInt RHSKnownZero(BitWidth, 0), RHSKnownOne(BitWidth, 0);
  807. computeKnownBits(A, RHSKnownZero, RHSKnownOne, DL, Depth+1, Query(Q, I));
  808. if (RHSKnownZero.isAllOnesValue() || RHSKnownOne.isNegative()) {
  809. // We know that the sign bit is one.
  810. KnownOne |= APInt::getSignBit(BitWidth);
  811. }
  812. // assume(v <=_u c)
  813. } else if (match(Arg, m_ICmp(Pred, m_V, m_Value(A))) &&
  814. Pred == ICmpInst::ICMP_ULE && isValidAssumeForContext(I, Q)) {
  815. APInt RHSKnownZero(BitWidth, 0), RHSKnownOne(BitWidth, 0);
  816. computeKnownBits(A, RHSKnownZero, RHSKnownOne, DL, Depth+1, Query(Q, I));
  817. // Whatever high bits in c are zero are known to be zero.
  818. KnownZero |=
  819. APInt::getHighBitsSet(BitWidth, RHSKnownZero.countLeadingOnes());
  820. // assume(v <_u c)
  821. } else if (match(Arg, m_ICmp(Pred, m_V, m_Value(A))) &&
  822. Pred == ICmpInst::ICMP_ULT && isValidAssumeForContext(I, Q)) {
  823. APInt RHSKnownZero(BitWidth, 0), RHSKnownOne(BitWidth, 0);
  824. computeKnownBits(A, RHSKnownZero, RHSKnownOne, DL, Depth+1, Query(Q, I));
  825. // Whatever high bits in c are zero are known to be zero (if c is a power
  826. // of 2, then one more).
  827. if (isKnownToBeAPowerOfTwo(A, false, Depth + 1, Query(Q, I), DL))
  828. KnownZero |=
  829. APInt::getHighBitsSet(BitWidth, RHSKnownZero.countLeadingOnes()+1);
  830. else
  831. KnownZero |=
  832. APInt::getHighBitsSet(BitWidth, RHSKnownZero.countLeadingOnes());
  833. }
  834. }
  835. }
  836. static void computeKnownBitsFromOperator(Operator *I, APInt &KnownZero,
  837. APInt &KnownOne, const DataLayout &DL,
  838. unsigned Depth, const Query &Q) {
  839. unsigned BitWidth = KnownZero.getBitWidth();
  840. APInt KnownZero2(KnownZero), KnownOne2(KnownOne);
  841. switch (I->getOpcode()) {
  842. default: break;
  843. case Instruction::Load:
  844. if (MDNode *MD = cast<LoadInst>(I)->getMetadata(LLVMContext::MD_range))
  845. computeKnownBitsFromRangeMetadata(*MD, KnownZero);
  846. break;
  847. case Instruction::And: {
  848. // If either the LHS or the RHS are Zero, the result is zero.
  849. computeKnownBits(I->getOperand(1), KnownZero, KnownOne, DL, Depth + 1, Q);
  850. computeKnownBits(I->getOperand(0), KnownZero2, KnownOne2, DL, Depth + 1, Q);
  851. // Output known-1 bits are only known if set in both the LHS & RHS.
  852. KnownOne &= KnownOne2;
  853. // Output known-0 are known to be clear if zero in either the LHS | RHS.
  854. KnownZero |= KnownZero2;
  855. break;
  856. }
  857. case Instruction::Or: {
  858. computeKnownBits(I->getOperand(1), KnownZero, KnownOne, DL, Depth + 1, Q);
  859. computeKnownBits(I->getOperand(0), KnownZero2, KnownOne2, DL, Depth + 1, Q);
  860. // Output known-0 bits are only known if clear in both the LHS & RHS.
  861. KnownZero &= KnownZero2;
  862. // Output known-1 are known to be set if set in either the LHS | RHS.
  863. KnownOne |= KnownOne2;
  864. break;
  865. }
  866. case Instruction::Xor: {
  867. computeKnownBits(I->getOperand(1), KnownZero, KnownOne, DL, Depth + 1, Q);
  868. computeKnownBits(I->getOperand(0), KnownZero2, KnownOne2, DL, Depth + 1, Q);
  869. // Output known-0 bits are known if clear or set in both the LHS & RHS.
  870. APInt KnownZeroOut = (KnownZero & KnownZero2) | (KnownOne & KnownOne2);
  871. // Output known-1 are known to be set if set in only one of the LHS, RHS.
  872. KnownOne = (KnownZero & KnownOne2) | (KnownOne & KnownZero2);
  873. KnownZero = KnownZeroOut;
  874. break;
  875. }
  876. case Instruction::Mul: {
  877. bool NSW = cast<OverflowingBinaryOperator>(I)->hasNoSignedWrap();
  878. computeKnownBitsMul(I->getOperand(0), I->getOperand(1), NSW, KnownZero,
  879. KnownOne, KnownZero2, KnownOne2, DL, Depth, Q);
  880. break;
  881. }
  882. case Instruction::UDiv: {
  883. // For the purposes of computing leading zeros we can conservatively
  884. // treat a udiv as a logical right shift by the power of 2 known to
  885. // be less than the denominator.
  886. computeKnownBits(I->getOperand(0), KnownZero2, KnownOne2, DL, Depth + 1, Q);
  887. unsigned LeadZ = KnownZero2.countLeadingOnes();
  888. KnownOne2.clearAllBits();
  889. KnownZero2.clearAllBits();
  890. computeKnownBits(I->getOperand(1), KnownZero2, KnownOne2, DL, Depth + 1, Q);
  891. unsigned RHSUnknownLeadingOnes = KnownOne2.countLeadingZeros();
  892. if (RHSUnknownLeadingOnes != BitWidth)
  893. LeadZ = std::min(BitWidth,
  894. LeadZ + BitWidth - RHSUnknownLeadingOnes - 1);
  895. KnownZero = APInt::getHighBitsSet(BitWidth, LeadZ);
  896. break;
  897. }
  898. case Instruction::Select:
  899. computeKnownBits(I->getOperand(2), KnownZero, KnownOne, DL, Depth + 1, Q);
  900. computeKnownBits(I->getOperand(1), KnownZero2, KnownOne2, DL, Depth + 1, Q);
  901. // Only known if known in both the LHS and RHS.
  902. KnownOne &= KnownOne2;
  903. KnownZero &= KnownZero2;
  904. break;
  905. case Instruction::FPTrunc:
  906. case Instruction::FPExt:
  907. case Instruction::FPToUI:
  908. case Instruction::FPToSI:
  909. case Instruction::SIToFP:
  910. case Instruction::UIToFP:
  911. break; // Can't work with floating point.
  912. case Instruction::PtrToInt:
  913. case Instruction::IntToPtr:
  914. case Instruction::AddrSpaceCast: // Pointers could be different sizes.
  915. // FALL THROUGH and handle them the same as zext/trunc.
  916. case Instruction::ZExt:
  917. case Instruction::Trunc: {
  918. Type *SrcTy = I->getOperand(0)->getType();
  919. unsigned SrcBitWidth;
  920. // Note that we handle pointer operands here because of inttoptr/ptrtoint
  921. // which fall through here.
  922. SrcBitWidth = DL.getTypeSizeInBits(SrcTy->getScalarType());
  923. assert(SrcBitWidth && "SrcBitWidth can't be zero");
  924. KnownZero = KnownZero.zextOrTrunc(SrcBitWidth);
  925. KnownOne = KnownOne.zextOrTrunc(SrcBitWidth);
  926. computeKnownBits(I->getOperand(0), KnownZero, KnownOne, DL, Depth + 1, Q);
  927. KnownZero = KnownZero.zextOrTrunc(BitWidth);
  928. KnownOne = KnownOne.zextOrTrunc(BitWidth);
  929. // Any top bits are known to be zero.
  930. if (BitWidth > SrcBitWidth)
  931. KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
  932. break;
  933. }
  934. case Instruction::BitCast: {
  935. Type *SrcTy = I->getOperand(0)->getType();
  936. if ((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
  937. // TODO: For now, not handling conversions like:
  938. // (bitcast i64 %x to <2 x i32>)
  939. !I->getType()->isVectorTy()) {
  940. computeKnownBits(I->getOperand(0), KnownZero, KnownOne, DL, Depth + 1, Q);
  941. break;
  942. }
  943. break;
  944. }
  945. case Instruction::SExt: {
  946. // Compute the bits in the result that are not present in the input.
  947. unsigned SrcBitWidth = I->getOperand(0)->getType()->getScalarSizeInBits();
  948. KnownZero = KnownZero.trunc(SrcBitWidth);
  949. KnownOne = KnownOne.trunc(SrcBitWidth);
  950. computeKnownBits(I->getOperand(0), KnownZero, KnownOne, DL, Depth + 1, Q);
  951. KnownZero = KnownZero.zext(BitWidth);
  952. KnownOne = KnownOne.zext(BitWidth);
  953. // If the sign bit of the input is known set or clear, then we know the
  954. // top bits of the result.
  955. if (KnownZero[SrcBitWidth-1]) // Input sign bit known zero
  956. KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
  957. else if (KnownOne[SrcBitWidth-1]) // Input sign bit known set
  958. KnownOne |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
  959. break;
  960. }
  961. case Instruction::Shl:
  962. // (shl X, C1) & C2 == 0 iff (X & C2 >>u C1) == 0
  963. if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
  964. uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
  965. computeKnownBits(I->getOperand(0), KnownZero, KnownOne, DL, Depth + 1, Q);
  966. KnownZero <<= ShiftAmt;
  967. KnownOne <<= ShiftAmt;
  968. KnownZero |= APInt::getLowBitsSet(BitWidth, ShiftAmt); // low bits known 0
  969. }
  970. break;
  971. case Instruction::LShr:
  972. // (ushr X, C1) & C2 == 0 iff (-1 >> C1) & C2 == 0
  973. if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
  974. // Compute the new bits that are at the top now.
  975. uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
  976. // Unsigned shift right.
  977. computeKnownBits(I->getOperand(0), KnownZero, KnownOne, DL, Depth + 1, Q);
  978. KnownZero = APIntOps::lshr(KnownZero, ShiftAmt);
  979. KnownOne = APIntOps::lshr(KnownOne, ShiftAmt);
  980. // high bits known zero.
  981. KnownZero |= APInt::getHighBitsSet(BitWidth, ShiftAmt);
  982. }
  983. break;
  984. case Instruction::AShr:
  985. // (ashr X, C1) & C2 == 0 iff (-1 >> C1) & C2 == 0
  986. if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
  987. // Compute the new bits that are at the top now.
  988. uint64_t ShiftAmt = SA->getLimitedValue(BitWidth-1);
  989. // Signed shift right.
  990. computeKnownBits(I->getOperand(0), KnownZero, KnownOne, DL, Depth + 1, Q);
  991. KnownZero = APIntOps::lshr(KnownZero, ShiftAmt);
  992. KnownOne = APIntOps::lshr(KnownOne, ShiftAmt);
  993. APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
  994. if (KnownZero[BitWidth-ShiftAmt-1]) // New bits are known zero.
  995. KnownZero |= HighBits;
  996. else if (KnownOne[BitWidth-ShiftAmt-1]) // New bits are known one.
  997. KnownOne |= HighBits;
  998. }
  999. break;
  1000. case Instruction::Sub: {
  1001. bool NSW = cast<OverflowingBinaryOperator>(I)->hasNoSignedWrap();
  1002. computeKnownBitsAddSub(false, I->getOperand(0), I->getOperand(1), NSW,
  1003. KnownZero, KnownOne, KnownZero2, KnownOne2, DL,
  1004. Depth, Q);
  1005. break;
  1006. }
  1007. case Instruction::Add: {
  1008. bool NSW = cast<OverflowingBinaryOperator>(I)->hasNoSignedWrap();
  1009. computeKnownBitsAddSub(true, I->getOperand(0), I->getOperand(1), NSW,
  1010. KnownZero, KnownOne, KnownZero2, KnownOne2, DL,
  1011. Depth, Q);
  1012. break;
  1013. }
  1014. case Instruction::SRem:
  1015. if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
  1016. APInt RA = Rem->getValue().abs();
  1017. if (RA.isPowerOf2()) {
  1018. APInt LowBits = RA - 1;
  1019. computeKnownBits(I->getOperand(0), KnownZero2, KnownOne2, DL, Depth + 1,
  1020. Q);
  1021. // The low bits of the first operand are unchanged by the srem.
  1022. KnownZero = KnownZero2 & LowBits;
  1023. KnownOne = KnownOne2 & LowBits;
  1024. // If the first operand is non-negative or has all low bits zero, then
  1025. // the upper bits are all zero.
  1026. if (KnownZero2[BitWidth-1] || ((KnownZero2 & LowBits) == LowBits))
  1027. KnownZero |= ~LowBits;
  1028. // If the first operand is negative and not all low bits are zero, then
  1029. // the upper bits are all one.
  1030. if (KnownOne2[BitWidth-1] && ((KnownOne2 & LowBits) != 0))
  1031. KnownOne |= ~LowBits;
  1032. assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
  1033. }
  1034. }
  1035. // The sign bit is the LHS's sign bit, except when the result of the
  1036. // remainder is zero.
  1037. if (KnownZero.isNonNegative()) {
  1038. APInt LHSKnownZero(BitWidth, 0), LHSKnownOne(BitWidth, 0);
  1039. computeKnownBits(I->getOperand(0), LHSKnownZero, LHSKnownOne, DL,
  1040. Depth + 1, Q);
  1041. // If it's known zero, our sign bit is also zero.
  1042. if (LHSKnownZero.isNegative())
  1043. KnownZero.setBit(BitWidth - 1);
  1044. }
  1045. break;
  1046. case Instruction::URem: {
  1047. if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
  1048. APInt RA = Rem->getValue();
  1049. if (RA.isPowerOf2()) {
  1050. APInt LowBits = (RA - 1);
  1051. computeKnownBits(I->getOperand(0), KnownZero, KnownOne, DL, Depth + 1,
  1052. Q);
  1053. KnownZero |= ~LowBits;
  1054. KnownOne &= LowBits;
  1055. break;
  1056. }
  1057. }
  1058. // Since the result is less than or equal to either operand, any leading
  1059. // zero bits in either operand must also exist in the result.
  1060. computeKnownBits(I->getOperand(0), KnownZero, KnownOne, DL, Depth + 1, Q);
  1061. computeKnownBits(I->getOperand(1), KnownZero2, KnownOne2, DL, Depth + 1, Q);
  1062. unsigned Leaders = std::max(KnownZero.countLeadingOnes(),
  1063. KnownZero2.countLeadingOnes());
  1064. KnownOne.clearAllBits();
  1065. KnownZero = APInt::getHighBitsSet(BitWidth, Leaders);
  1066. break;
  1067. }
  1068. case Instruction::Alloca: {
  1069. AllocaInst *AI = cast<AllocaInst>(I);
  1070. unsigned Align = AI->getAlignment();
  1071. if (Align == 0)
  1072. Align = DL.getABITypeAlignment(AI->getType()->getElementType());
  1073. if (Align > 0)
  1074. KnownZero = APInt::getLowBitsSet(BitWidth, countTrailingZeros(Align));
  1075. break;
  1076. }
  1077. case Instruction::GetElementPtr: {
  1078. // Analyze all of the subscripts of this getelementptr instruction
  1079. // to determine if we can prove known low zero bits.
  1080. APInt LocalKnownZero(BitWidth, 0), LocalKnownOne(BitWidth, 0);
  1081. computeKnownBits(I->getOperand(0), LocalKnownZero, LocalKnownOne, DL,
  1082. Depth + 1, Q);
  1083. unsigned TrailZ = LocalKnownZero.countTrailingOnes();
  1084. gep_type_iterator GTI = gep_type_begin(I);
  1085. for (unsigned i = 1, e = I->getNumOperands(); i != e; ++i, ++GTI) {
  1086. Value *Index = I->getOperand(i);
  1087. if (StructType *STy = dyn_cast<StructType>(*GTI)) {
  1088. // Handle struct member offset arithmetic.
  1089. // Handle case when index is vector zeroinitializer
  1090. Constant *CIndex = cast<Constant>(Index);
  1091. if (CIndex->isZeroValue())
  1092. continue;
  1093. if (CIndex->getType()->isVectorTy())
  1094. Index = CIndex->getSplatValue();
  1095. unsigned Idx = cast<ConstantInt>(Index)->getZExtValue();
  1096. const StructLayout *SL = DL.getStructLayout(STy);
  1097. uint64_t Offset = SL->getElementOffset(Idx);
  1098. TrailZ = std::min<unsigned>(TrailZ,
  1099. countTrailingZeros(Offset));
  1100. } else {
  1101. // Handle array index arithmetic.
  1102. Type *IndexedTy = GTI.getIndexedType();
  1103. if (!IndexedTy->isSized()) {
  1104. TrailZ = 0;
  1105. break;
  1106. }
  1107. unsigned GEPOpiBits = Index->getType()->getScalarSizeInBits();
  1108. uint64_t TypeSize = DL.getTypeAllocSize(IndexedTy);
  1109. LocalKnownZero = LocalKnownOne = APInt(GEPOpiBits, 0);
  1110. computeKnownBits(Index, LocalKnownZero, LocalKnownOne, DL, Depth + 1,
  1111. Q);
  1112. TrailZ = std::min(TrailZ,
  1113. unsigned(countTrailingZeros(TypeSize) +
  1114. LocalKnownZero.countTrailingOnes()));
  1115. }
  1116. }
  1117. KnownZero = APInt::getLowBitsSet(BitWidth, TrailZ);
  1118. break;
  1119. }
  1120. case Instruction::PHI: {
  1121. PHINode *P = cast<PHINode>(I);
  1122. // Handle the case of a simple two-predecessor recurrence PHI.
  1123. // There's a lot more that could theoretically be done here, but
  1124. // this is sufficient to catch some interesting cases.
  1125. if (P->getNumIncomingValues() == 2) {
  1126. for (unsigned i = 0; i != 2; ++i) {
  1127. Value *L = P->getIncomingValue(i);
  1128. Value *R = P->getIncomingValue(!i);
  1129. Operator *LU = dyn_cast<Operator>(L);
  1130. if (!LU)
  1131. continue;
  1132. unsigned Opcode = LU->getOpcode();
  1133. // Check for operations that have the property that if
  1134. // both their operands have low zero bits, the result
  1135. // will have low zero bits.
  1136. if (Opcode == Instruction::Add ||
  1137. Opcode == Instruction::Sub ||
  1138. Opcode == Instruction::And ||
  1139. Opcode == Instruction::Or ||
  1140. Opcode == Instruction::Mul) {
  1141. Value *LL = LU->getOperand(0);
  1142. Value *LR = LU->getOperand(1);
  1143. // Find a recurrence.
  1144. if (LL == I)
  1145. L = LR;
  1146. else if (LR == I)
  1147. L = LL;
  1148. else
  1149. break;
  1150. // Ok, we have a PHI of the form L op= R. Check for low
  1151. // zero bits.
  1152. computeKnownBits(R, KnownZero2, KnownOne2, DL, Depth + 1, Q);
  1153. // We need to take the minimum number of known bits
  1154. APInt KnownZero3(KnownZero), KnownOne3(KnownOne);
  1155. computeKnownBits(L, KnownZero3, KnownOne3, DL, Depth + 1, Q);
  1156. KnownZero = APInt::getLowBitsSet(BitWidth,
  1157. std::min(KnownZero2.countTrailingOnes(),
  1158. KnownZero3.countTrailingOnes()));
  1159. break;
  1160. }
  1161. }
  1162. }
  1163. // Unreachable blocks may have zero-operand PHI nodes.
  1164. if (P->getNumIncomingValues() == 0)
  1165. break;
  1166. // Otherwise take the unions of the known bit sets of the operands,
  1167. // taking conservative care to avoid excessive recursion.
  1168. if (Depth < MaxDepth - 1 && !KnownZero && !KnownOne) {
  1169. // Skip if every incoming value references to ourself.
  1170. if (dyn_cast_or_null<UndefValue>(P->hasConstantValue()))
  1171. break;
  1172. KnownZero = APInt::getAllOnesValue(BitWidth);
  1173. KnownOne = APInt::getAllOnesValue(BitWidth);
  1174. for (Value *IncValue : P->incoming_values()) {
  1175. // Skip direct self references.
  1176. if (IncValue == P) continue;
  1177. KnownZero2 = APInt(BitWidth, 0);
  1178. KnownOne2 = APInt(BitWidth, 0);
  1179. // Recurse, but cap the recursion to one level, because we don't
  1180. // want to waste time spinning around in loops.
  1181. computeKnownBits(IncValue, KnownZero2, KnownOne2, DL,
  1182. MaxDepth - 1, Q);
  1183. KnownZero &= KnownZero2;
  1184. KnownOne &= KnownOne2;
  1185. // If all bits have been ruled out, there's no need to check
  1186. // more operands.
  1187. if (!KnownZero && !KnownOne)
  1188. break;
  1189. }
  1190. }
  1191. break;
  1192. }
  1193. case Instruction::Call:
  1194. case Instruction::Invoke:
  1195. if (MDNode *MD = cast<Instruction>(I)->getMetadata(LLVMContext::MD_range))
  1196. computeKnownBitsFromRangeMetadata(*MD, KnownZero);
  1197. // If a range metadata is attached to this IntrinsicInst, intersect the
  1198. // explicit range specified by the metadata and the implicit range of
  1199. // the intrinsic.
  1200. if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
  1201. switch (II->getIntrinsicID()) {
  1202. default: break;
  1203. case Intrinsic::ctlz:
  1204. case Intrinsic::cttz: {
  1205. unsigned LowBits = Log2_32(BitWidth)+1;
  1206. // If this call is undefined for 0, the result will be less than 2^n.
  1207. if (II->getArgOperand(1) == ConstantInt::getTrue(II->getContext()))
  1208. LowBits -= 1;
  1209. KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - LowBits);
  1210. break;
  1211. }
  1212. case Intrinsic::ctpop: {
  1213. unsigned LowBits = Log2_32(BitWidth)+1;
  1214. KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - LowBits);
  1215. break;
  1216. }
  1217. #if 0 // HLSL Change - remove platform intrinsics
  1218. case Intrinsic::x86_sse42_crc32_64_64:
  1219. KnownZero |= APInt::getHighBitsSet(64, 32);
  1220. break;
  1221. #endif // HLSL Change - remove platform intrinsics
  1222. }
  1223. }
  1224. break;
  1225. case Instruction::ExtractValue:
  1226. if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I->getOperand(0))) {
  1227. ExtractValueInst *EVI = cast<ExtractValueInst>(I);
  1228. if (EVI->getNumIndices() != 1) break;
  1229. if (EVI->getIndices()[0] == 0) {
  1230. switch (II->getIntrinsicID()) {
  1231. default: break;
  1232. case Intrinsic::uadd_with_overflow:
  1233. case Intrinsic::sadd_with_overflow:
  1234. computeKnownBitsAddSub(true, II->getArgOperand(0),
  1235. II->getArgOperand(1), false, KnownZero,
  1236. KnownOne, KnownZero2, KnownOne2, DL, Depth, Q);
  1237. break;
  1238. case Intrinsic::usub_with_overflow:
  1239. case Intrinsic::ssub_with_overflow:
  1240. computeKnownBitsAddSub(false, II->getArgOperand(0),
  1241. II->getArgOperand(1), false, KnownZero,
  1242. KnownOne, KnownZero2, KnownOne2, DL, Depth, Q);
  1243. break;
  1244. case Intrinsic::umul_with_overflow:
  1245. case Intrinsic::smul_with_overflow:
  1246. computeKnownBitsMul(II->getArgOperand(0), II->getArgOperand(1), false,
  1247. KnownZero, KnownOne, KnownZero2, KnownOne2, DL,
  1248. Depth, Q);
  1249. break;
  1250. }
  1251. }
  1252. }
  1253. }
  1254. }
  1255. /// Determine which bits of V are known to be either zero or one and return
  1256. /// them in the KnownZero/KnownOne bit sets.
  1257. ///
  1258. /// NOTE: we cannot consider 'undef' to be "IsZero" here. The problem is that
  1259. /// we cannot optimize based on the assumption that it is zero without changing
  1260. /// it to be an explicit zero. If we don't change it to zero, other code could
  1261. /// optimized based on the contradictory assumption that it is non-zero.
  1262. /// Because instcombine aggressively folds operations with undef args anyway,
  1263. /// this won't lose us code quality.
  1264. ///
  1265. /// This function is defined on values with integer type, values with pointer
  1266. /// type, and vectors of integers. In the case
  1267. /// where V is a vector, known zero, and known one values are the
  1268. /// same width as the vector element, and the bit is set only if it is true
  1269. /// for all of the elements in the vector.
  1270. void computeKnownBits(Value *V, APInt &KnownZero, APInt &KnownOne,
  1271. const DataLayout &DL, unsigned Depth, const Query &Q) {
  1272. assert(V && "No Value?");
  1273. assert(Depth <= MaxDepth && "Limit Search Depth");
  1274. unsigned BitWidth = KnownZero.getBitWidth();
  1275. assert((V->getType()->isIntOrIntVectorTy() ||
  1276. V->getType()->getScalarType()->isPointerTy()) &&
  1277. "Not integer or pointer type!");
  1278. assert((DL.getTypeSizeInBits(V->getType()->getScalarType()) == BitWidth) &&
  1279. (!V->getType()->isIntOrIntVectorTy() ||
  1280. V->getType()->getScalarSizeInBits() == BitWidth) &&
  1281. KnownZero.getBitWidth() == BitWidth &&
  1282. KnownOne.getBitWidth() == BitWidth &&
  1283. "V, KnownOne and KnownZero should have same BitWidth");
  1284. if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
  1285. // We know all of the bits for a constant!
  1286. KnownOne = CI->getValue();
  1287. KnownZero = ~KnownOne;
  1288. return;
  1289. }
  1290. // Null and aggregate-zero are all-zeros.
  1291. if (isa<ConstantPointerNull>(V) ||
  1292. isa<ConstantAggregateZero>(V)) {
  1293. KnownOne.clearAllBits();
  1294. KnownZero = APInt::getAllOnesValue(BitWidth);
  1295. return;
  1296. }
  1297. // Handle a constant vector by taking the intersection of the known bits of
  1298. // each element. There is no real need to handle ConstantVector here, because
  1299. // we don't handle undef in any particularly useful way.
  1300. if (ConstantDataSequential *CDS = dyn_cast<ConstantDataSequential>(V)) {
  1301. // We know that CDS must be a vector of integers. Take the intersection of
  1302. // each element.
  1303. KnownZero.setAllBits(); KnownOne.setAllBits();
  1304. APInt Elt(KnownZero.getBitWidth(), 0);
  1305. for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
  1306. Elt = CDS->getElementAsInteger(i);
  1307. KnownZero &= ~Elt;
  1308. KnownOne &= Elt;
  1309. }
  1310. return;
  1311. }
  1312. // The address of an aligned GlobalValue has trailing zeros.
  1313. if (auto *GO = dyn_cast<GlobalObject>(V)) {
  1314. unsigned Align = GO->getAlignment();
  1315. if (Align == 0) {
  1316. if (auto *GVar = dyn_cast<GlobalVariable>(GO)) {
  1317. Type *ObjectType = GVar->getType()->getElementType();
  1318. if (ObjectType->isSized()) {
  1319. // If the object is defined in the current Module, we'll be giving
  1320. // it the preferred alignment. Otherwise, we have to assume that it
  1321. // may only have the minimum ABI alignment.
  1322. if (GVar->isStrongDefinitionForLinker())
  1323. Align = DL.getPreferredAlignment(GVar);
  1324. else
  1325. Align = DL.getABITypeAlignment(ObjectType);
  1326. }
  1327. }
  1328. }
  1329. if (Align > 0)
  1330. KnownZero = APInt::getLowBitsSet(BitWidth,
  1331. countTrailingZeros(Align));
  1332. else
  1333. KnownZero.clearAllBits();
  1334. KnownOne.clearAllBits();
  1335. return;
  1336. }
  1337. if (Argument *A = dyn_cast<Argument>(V)) {
  1338. unsigned Align = A->getType()->isPointerTy() ? A->getParamAlignment() : 0;
  1339. if (!Align && A->hasStructRetAttr()) {
  1340. // An sret parameter has at least the ABI alignment of the return type.
  1341. Type *EltTy = cast<PointerType>(A->getType())->getElementType();
  1342. if (EltTy->isSized())
  1343. Align = DL.getABITypeAlignment(EltTy);
  1344. }
  1345. if (Align)
  1346. KnownZero = APInt::getLowBitsSet(BitWidth, countTrailingZeros(Align));
  1347. else
  1348. KnownZero.clearAllBits();
  1349. KnownOne.clearAllBits();
  1350. // Don't give up yet... there might be an assumption that provides more
  1351. // information...
  1352. computeKnownBitsFromAssume(V, KnownZero, KnownOne, DL, Depth, Q);
  1353. // Or a dominating condition for that matter
  1354. if (EnableDomConditions && Depth <= DomConditionsMaxDepth)
  1355. computeKnownBitsFromDominatingCondition(V, KnownZero, KnownOne, DL,
  1356. Depth, Q);
  1357. return;
  1358. }
  1359. // Start out not knowing anything.
  1360. KnownZero.clearAllBits(); KnownOne.clearAllBits();
  1361. // Limit search depth.
  1362. // All recursive calls that increase depth must come after this.
  1363. if (Depth == MaxDepth)
  1364. return;
  1365. // A weak GlobalAlias is totally unknown. A non-weak GlobalAlias has
  1366. // the bits of its aliasee.
  1367. if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) {
  1368. if (!GA->mayBeOverridden())
  1369. computeKnownBits(GA->getAliasee(), KnownZero, KnownOne, DL, Depth + 1, Q);
  1370. return;
  1371. }
  1372. if (Operator *I = dyn_cast<Operator>(V))
  1373. computeKnownBitsFromOperator(I, KnownZero, KnownOne, DL, Depth, Q);
  1374. // computeKnownBitsFromAssume and computeKnownBitsFromDominatingCondition
  1375. // strictly refines KnownZero and KnownOne. Therefore, we run them after
  1376. // computeKnownBitsFromOperator.
  1377. // Check whether a nearby assume intrinsic can determine some known bits.
  1378. computeKnownBitsFromAssume(V, KnownZero, KnownOne, DL, Depth, Q);
  1379. // Check whether there's a dominating condition which implies something about
  1380. // this value at the given context.
  1381. if (EnableDomConditions && Depth <= DomConditionsMaxDepth)
  1382. computeKnownBitsFromDominatingCondition(V, KnownZero, KnownOne, DL, Depth,
  1383. Q);
  1384. assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
  1385. }
  1386. /// Determine whether the sign bit is known to be zero or one.
  1387. /// Convenience wrapper around computeKnownBits.
  1388. void ComputeSignBit(Value *V, bool &KnownZero, bool &KnownOne,
  1389. const DataLayout &DL, unsigned Depth, const Query &Q) {
  1390. unsigned BitWidth = getBitWidth(V->getType(), DL);
  1391. if (!BitWidth) {
  1392. KnownZero = false;
  1393. KnownOne = false;
  1394. return;
  1395. }
  1396. APInt ZeroBits(BitWidth, 0);
  1397. APInt OneBits(BitWidth, 0);
  1398. computeKnownBits(V, ZeroBits, OneBits, DL, Depth, Q);
  1399. KnownOne = OneBits[BitWidth - 1];
  1400. KnownZero = ZeroBits[BitWidth - 1];
  1401. }
  1402. /// Return true if the given value is known to have exactly one
  1403. /// bit set when defined. For vectors return true if every element is known to
  1404. /// be a power of two when defined. Supports values with integer or pointer
  1405. /// types and vectors of integers.
  1406. bool isKnownToBeAPowerOfTwo(Value *V, bool OrZero, unsigned Depth,
  1407. const Query &Q, const DataLayout &DL) {
  1408. if (Constant *C = dyn_cast<Constant>(V)) {
  1409. if (C->isNullValue())
  1410. return OrZero;
  1411. if (ConstantInt *CI = dyn_cast<ConstantInt>(C))
  1412. return CI->getValue().isPowerOf2();
  1413. // TODO: Handle vector constants.
  1414. }
  1415. // 1 << X is clearly a power of two if the one is not shifted off the end. If
  1416. // it is shifted off the end then the result is undefined.
  1417. if (match(V, m_Shl(m_One(), m_Value())))
  1418. return true;
  1419. // (signbit) >>l X is clearly a power of two if the one is not shifted off the
  1420. // bottom. If it is shifted off the bottom then the result is undefined.
  1421. if (match(V, m_LShr(m_SignBit(), m_Value())))
  1422. return true;
  1423. // The remaining tests are all recursive, so bail out if we hit the limit.
  1424. if (Depth++ == MaxDepth)
  1425. return false;
  1426. Value *X = nullptr, *Y = nullptr;
  1427. // A shift of a power of two is a power of two or zero.
  1428. if (OrZero && (match(V, m_Shl(m_Value(X), m_Value())) ||
  1429. match(V, m_Shr(m_Value(X), m_Value()))))
  1430. return isKnownToBeAPowerOfTwo(X, /*OrZero*/ true, Depth, Q, DL);
  1431. if (ZExtInst *ZI = dyn_cast<ZExtInst>(V))
  1432. return isKnownToBeAPowerOfTwo(ZI->getOperand(0), OrZero, Depth, Q, DL);
  1433. if (SelectInst *SI = dyn_cast<SelectInst>(V))
  1434. return isKnownToBeAPowerOfTwo(SI->getTrueValue(), OrZero, Depth, Q, DL) &&
  1435. isKnownToBeAPowerOfTwo(SI->getFalseValue(), OrZero, Depth, Q, DL);
  1436. if (OrZero && match(V, m_And(m_Value(X), m_Value(Y)))) {
  1437. // A power of two and'd with anything is a power of two or zero.
  1438. if (isKnownToBeAPowerOfTwo(X, /*OrZero*/ true, Depth, Q, DL) ||
  1439. isKnownToBeAPowerOfTwo(Y, /*OrZero*/ true, Depth, Q, DL))
  1440. return true;
  1441. // X & (-X) is always a power of two or zero.
  1442. if (match(X, m_Neg(m_Specific(Y))) || match(Y, m_Neg(m_Specific(X))))
  1443. return true;
  1444. return false;
  1445. }
  1446. // Adding a power-of-two or zero to the same power-of-two or zero yields
  1447. // either the original power-of-two, a larger power-of-two or zero.
  1448. if (match(V, m_Add(m_Value(X), m_Value(Y)))) {
  1449. OverflowingBinaryOperator *VOBO = cast<OverflowingBinaryOperator>(V);
  1450. if (OrZero || VOBO->hasNoUnsignedWrap() || VOBO->hasNoSignedWrap()) {
  1451. if (match(X, m_And(m_Specific(Y), m_Value())) ||
  1452. match(X, m_And(m_Value(), m_Specific(Y))))
  1453. if (isKnownToBeAPowerOfTwo(Y, OrZero, Depth, Q, DL))
  1454. return true;
  1455. if (match(Y, m_And(m_Specific(X), m_Value())) ||
  1456. match(Y, m_And(m_Value(), m_Specific(X))))
  1457. if (isKnownToBeAPowerOfTwo(X, OrZero, Depth, Q, DL))
  1458. return true;
  1459. unsigned BitWidth = V->getType()->getScalarSizeInBits();
  1460. APInt LHSZeroBits(BitWidth, 0), LHSOneBits(BitWidth, 0);
  1461. computeKnownBits(X, LHSZeroBits, LHSOneBits, DL, Depth, Q);
  1462. APInt RHSZeroBits(BitWidth, 0), RHSOneBits(BitWidth, 0);
  1463. computeKnownBits(Y, RHSZeroBits, RHSOneBits, DL, Depth, Q);
  1464. // If i8 V is a power of two or zero:
  1465. // ZeroBits: 1 1 1 0 1 1 1 1
  1466. // ~ZeroBits: 0 0 0 1 0 0 0 0
  1467. if ((~(LHSZeroBits & RHSZeroBits)).isPowerOf2())
  1468. // If OrZero isn't set, we cannot give back a zero result.
  1469. // Make sure either the LHS or RHS has a bit set.
  1470. if (OrZero || RHSOneBits.getBoolValue() || LHSOneBits.getBoolValue())
  1471. return true;
  1472. }
  1473. }
  1474. // An exact divide or right shift can only shift off zero bits, so the result
  1475. // is a power of two only if the first operand is a power of two and not
  1476. // copying a sign bit (sdiv int_min, 2).
  1477. if (match(V, m_Exact(m_LShr(m_Value(), m_Value()))) ||
  1478. match(V, m_Exact(m_UDiv(m_Value(), m_Value())))) {
  1479. return isKnownToBeAPowerOfTwo(cast<Operator>(V)->getOperand(0), OrZero,
  1480. Depth, Q, DL);
  1481. }
  1482. return false;
  1483. }
  1484. /// \brief Test whether a GEP's result is known to be non-null.
  1485. ///
  1486. /// Uses properties inherent in a GEP to try to determine whether it is known
  1487. /// to be non-null.
  1488. ///
  1489. /// Currently this routine does not support vector GEPs.
  1490. static bool isGEPKnownNonNull(GEPOperator *GEP, const DataLayout &DL,
  1491. unsigned Depth, const Query &Q) {
  1492. if (!GEP->isInBounds() || GEP->getPointerAddressSpace() != 0)
  1493. return false;
  1494. // FIXME: Support vector-GEPs.
  1495. assert(GEP->getType()->isPointerTy() && "We only support plain pointer GEP");
  1496. // If the base pointer is non-null, we cannot walk to a null address with an
  1497. // inbounds GEP in address space zero.
  1498. if (isKnownNonZero(GEP->getPointerOperand(), DL, Depth, Q))
  1499. return true;
  1500. // Walk the GEP operands and see if any operand introduces a non-zero offset.
  1501. // If so, then the GEP cannot produce a null pointer, as doing so would
  1502. // inherently violate the inbounds contract within address space zero.
  1503. for (gep_type_iterator GTI = gep_type_begin(GEP), GTE = gep_type_end(GEP);
  1504. GTI != GTE; ++GTI) {
  1505. // Struct types are easy -- they must always be indexed by a constant.
  1506. if (StructType *STy = dyn_cast<StructType>(*GTI)) {
  1507. ConstantInt *OpC = cast<ConstantInt>(GTI.getOperand());
  1508. unsigned ElementIdx = OpC->getZExtValue();
  1509. const StructLayout *SL = DL.getStructLayout(STy);
  1510. uint64_t ElementOffset = SL->getElementOffset(ElementIdx);
  1511. if (ElementOffset > 0)
  1512. return true;
  1513. continue;
  1514. }
  1515. // If we have a zero-sized type, the index doesn't matter. Keep looping.
  1516. if (DL.getTypeAllocSize(GTI.getIndexedType()) == 0)
  1517. continue;
  1518. // Fast path the constant operand case both for efficiency and so we don't
  1519. // increment Depth when just zipping down an all-constant GEP.
  1520. if (ConstantInt *OpC = dyn_cast<ConstantInt>(GTI.getOperand())) {
  1521. if (!OpC->isZero())
  1522. return true;
  1523. continue;
  1524. }
  1525. // We post-increment Depth here because while isKnownNonZero increments it
  1526. // as well, when we pop back up that increment won't persist. We don't want
  1527. // to recurse 10k times just because we have 10k GEP operands. We don't
  1528. // bail completely out because we want to handle constant GEPs regardless
  1529. // of depth.
  1530. if (Depth++ >= MaxDepth)
  1531. continue;
  1532. if (isKnownNonZero(GTI.getOperand(), DL, Depth, Q))
  1533. return true;
  1534. }
  1535. return false;
  1536. }
  1537. /// Does the 'Range' metadata (which must be a valid MD_range operand list)
  1538. /// ensure that the value it's attached to is never Value? 'RangeType' is
  1539. /// is the type of the value described by the range.
  1540. static bool rangeMetadataExcludesValue(MDNode* Ranges,
  1541. const APInt& Value) {
  1542. const unsigned NumRanges = Ranges->getNumOperands() / 2;
  1543. assert(NumRanges >= 1);
  1544. for (unsigned i = 0; i < NumRanges; ++i) {
  1545. ConstantInt *Lower =
  1546. mdconst::extract<ConstantInt>(Ranges->getOperand(2 * i + 0));
  1547. ConstantInt *Upper =
  1548. mdconst::extract<ConstantInt>(Ranges->getOperand(2 * i + 1));
  1549. ConstantRange Range(Lower->getValue(), Upper->getValue());
  1550. if (Range.contains(Value))
  1551. return false;
  1552. }
  1553. return true;
  1554. }
  1555. /// Return true if the given value is known to be non-zero when defined.
  1556. /// For vectors return true if every element is known to be non-zero when
  1557. /// defined. Supports values with integer or pointer type and vectors of
  1558. /// integers.
  1559. bool isKnownNonZero(Value *V, const DataLayout &DL, unsigned Depth,
  1560. const Query &Q) {
  1561. if (Constant *C = dyn_cast<Constant>(V)) {
  1562. if (C->isNullValue())
  1563. return false;
  1564. if (isa<ConstantInt>(C))
  1565. // Must be non-zero due to null test above.
  1566. return true;
  1567. // TODO: Handle vectors
  1568. return false;
  1569. }
  1570. if (Instruction* I = dyn_cast<Instruction>(V)) {
  1571. if (MDNode *Ranges = I->getMetadata(LLVMContext::MD_range)) {
  1572. // If the possible ranges don't contain zero, then the value is
  1573. // definitely non-zero.
  1574. if (IntegerType* Ty = dyn_cast<IntegerType>(V->getType())) {
  1575. const APInt ZeroValue(Ty->getBitWidth(), 0);
  1576. if (rangeMetadataExcludesValue(Ranges, ZeroValue))
  1577. return true;
  1578. }
  1579. }
  1580. }
  1581. // The remaining tests are all recursive, so bail out if we hit the limit.
  1582. if (Depth++ >= MaxDepth)
  1583. return false;
  1584. // Check for pointer simplifications.
  1585. if (V->getType()->isPointerTy()) {
  1586. if (isKnownNonNull(V))
  1587. return true;
  1588. if (GEPOperator *GEP = dyn_cast<GEPOperator>(V))
  1589. if (isGEPKnownNonNull(GEP, DL, Depth, Q))
  1590. return true;
  1591. }
  1592. unsigned BitWidth = getBitWidth(V->getType()->getScalarType(), DL);
  1593. // X | Y != 0 if X != 0 or Y != 0.
  1594. Value *X = nullptr, *Y = nullptr;
  1595. if (match(V, m_Or(m_Value(X), m_Value(Y))))
  1596. return isKnownNonZero(X, DL, Depth, Q) || isKnownNonZero(Y, DL, Depth, Q);
  1597. // ext X != 0 if X != 0.
  1598. if (isa<SExtInst>(V) || isa<ZExtInst>(V))
  1599. return isKnownNonZero(cast<Instruction>(V)->getOperand(0), DL, Depth, Q);
  1600. // shl X, Y != 0 if X is odd. Note that the value of the shift is undefined
  1601. // if the lowest bit is shifted off the end.
  1602. if (BitWidth && match(V, m_Shl(m_Value(X), m_Value(Y)))) {
  1603. // shl nuw can't remove any non-zero bits.
  1604. OverflowingBinaryOperator *BO = cast<OverflowingBinaryOperator>(V);
  1605. if (BO->hasNoUnsignedWrap())
  1606. return isKnownNonZero(X, DL, Depth, Q);
  1607. APInt KnownZero(BitWidth, 0);
  1608. APInt KnownOne(BitWidth, 0);
  1609. computeKnownBits(X, KnownZero, KnownOne, DL, Depth, Q);
  1610. if (KnownOne[0])
  1611. return true;
  1612. }
  1613. // shr X, Y != 0 if X is negative. Note that the value of the shift is not
  1614. // defined if the sign bit is shifted off the end.
  1615. else if (match(V, m_Shr(m_Value(X), m_Value(Y)))) {
  1616. // shr exact can only shift out zero bits.
  1617. PossiblyExactOperator *BO = cast<PossiblyExactOperator>(V);
  1618. if (BO->isExact())
  1619. return isKnownNonZero(X, DL, Depth, Q);
  1620. bool XKnownNonNegative, XKnownNegative;
  1621. ComputeSignBit(X, XKnownNonNegative, XKnownNegative, DL, Depth, Q);
  1622. if (XKnownNegative)
  1623. return true;
  1624. }
  1625. // div exact can only produce a zero if the dividend is zero.
  1626. else if (match(V, m_Exact(m_IDiv(m_Value(X), m_Value())))) {
  1627. return isKnownNonZero(X, DL, Depth, Q);
  1628. }
  1629. // X + Y.
  1630. else if (match(V, m_Add(m_Value(X), m_Value(Y)))) {
  1631. bool XKnownNonNegative, XKnownNegative;
  1632. bool YKnownNonNegative, YKnownNegative;
  1633. ComputeSignBit(X, XKnownNonNegative, XKnownNegative, DL, Depth, Q);
  1634. ComputeSignBit(Y, YKnownNonNegative, YKnownNegative, DL, Depth, Q);
  1635. // If X and Y are both non-negative (as signed values) then their sum is not
  1636. // zero unless both X and Y are zero.
  1637. if (XKnownNonNegative && YKnownNonNegative)
  1638. if (isKnownNonZero(X, DL, Depth, Q) || isKnownNonZero(Y, DL, Depth, Q))
  1639. return true;
  1640. // If X and Y are both negative (as signed values) then their sum is not
  1641. // zero unless both X and Y equal INT_MIN.
  1642. if (BitWidth && XKnownNegative && YKnownNegative) {
  1643. APInt KnownZero(BitWidth, 0);
  1644. APInt KnownOne(BitWidth, 0);
  1645. APInt Mask = APInt::getSignedMaxValue(BitWidth);
  1646. // The sign bit of X is set. If some other bit is set then X is not equal
  1647. // to INT_MIN.
  1648. computeKnownBits(X, KnownZero, KnownOne, DL, Depth, Q);
  1649. if ((KnownOne & Mask) != 0)
  1650. return true;
  1651. // The sign bit of Y is set. If some other bit is set then Y is not equal
  1652. // to INT_MIN.
  1653. computeKnownBits(Y, KnownZero, KnownOne, DL, Depth, Q);
  1654. if ((KnownOne & Mask) != 0)
  1655. return true;
  1656. }
  1657. // The sum of a non-negative number and a power of two is not zero.
  1658. if (XKnownNonNegative &&
  1659. isKnownToBeAPowerOfTwo(Y, /*OrZero*/ false, Depth, Q, DL))
  1660. return true;
  1661. if (YKnownNonNegative &&
  1662. isKnownToBeAPowerOfTwo(X, /*OrZero*/ false, Depth, Q, DL))
  1663. return true;
  1664. }
  1665. // X * Y.
  1666. else if (match(V, m_Mul(m_Value(X), m_Value(Y)))) {
  1667. OverflowingBinaryOperator *BO = cast<OverflowingBinaryOperator>(V);
  1668. // If X and Y are non-zero then so is X * Y as long as the multiplication
  1669. // does not overflow.
  1670. if ((BO->hasNoSignedWrap() || BO->hasNoUnsignedWrap()) &&
  1671. isKnownNonZero(X, DL, Depth, Q) && isKnownNonZero(Y, DL, Depth, Q))
  1672. return true;
  1673. }
  1674. // (C ? X : Y) != 0 if X != 0 and Y != 0.
  1675. else if (SelectInst *SI = dyn_cast<SelectInst>(V)) {
  1676. if (isKnownNonZero(SI->getTrueValue(), DL, Depth, Q) &&
  1677. isKnownNonZero(SI->getFalseValue(), DL, Depth, Q))
  1678. return true;
  1679. }
  1680. if (!BitWidth) return false;
  1681. APInt KnownZero(BitWidth, 0);
  1682. APInt KnownOne(BitWidth, 0);
  1683. computeKnownBits(V, KnownZero, KnownOne, DL, Depth, Q);
  1684. return KnownOne != 0;
  1685. }
  1686. /// Return true if 'V & Mask' is known to be zero. We use this predicate to
  1687. /// simplify operations downstream. Mask is known to be zero for bits that V
  1688. /// cannot have.
  1689. ///
  1690. /// This function is defined on values with integer type, values with pointer
  1691. /// type, and vectors of integers. In the case
  1692. /// where V is a vector, the mask, known zero, and known one values are the
  1693. /// same width as the vector element, and the bit is set only if it is true
  1694. /// for all of the elements in the vector.
  1695. bool MaskedValueIsZero(Value *V, const APInt &Mask, const DataLayout &DL,
  1696. unsigned Depth, const Query &Q) {
  1697. APInt KnownZero(Mask.getBitWidth(), 0), KnownOne(Mask.getBitWidth(), 0);
  1698. computeKnownBits(V, KnownZero, KnownOne, DL, Depth, Q);
  1699. return (KnownZero & Mask) == Mask;
  1700. }
  1701. /// Return the number of times the sign bit of the register is replicated into
  1702. /// the other bits. We know that at least 1 bit is always equal to the sign bit
  1703. /// (itself), but other cases can give us information. For example, immediately
  1704. /// after an "ashr X, 2", we know that the top 3 bits are all equal to each
  1705. /// other, so we return 3.
  1706. ///
  1707. /// 'Op' must have a scalar integer type.
  1708. ///
  1709. unsigned ComputeNumSignBits(Value *V, const DataLayout &DL, unsigned Depth,
  1710. const Query &Q) {
  1711. unsigned TyBits = DL.getTypeSizeInBits(V->getType()->getScalarType());
  1712. unsigned Tmp, Tmp2;
  1713. unsigned FirstAnswer = 1;
  1714. // Note that ConstantInt is handled by the general computeKnownBits case
  1715. // below.
  1716. if (Depth == 6)
  1717. return 1; // Limit search depth.
  1718. Operator *U = dyn_cast<Operator>(V);
  1719. switch (Operator::getOpcode(V)) {
  1720. default: break;
  1721. case Instruction::SExt:
  1722. Tmp = TyBits - U->getOperand(0)->getType()->getScalarSizeInBits();
  1723. return ComputeNumSignBits(U->getOperand(0), DL, Depth + 1, Q) + Tmp;
  1724. case Instruction::SDiv: {
  1725. const APInt *Denominator;
  1726. // sdiv X, C -> adds log(C) sign bits.
  1727. if (match(U->getOperand(1), m_APInt(Denominator))) {
  1728. // Ignore non-positive denominator.
  1729. if (!Denominator->isStrictlyPositive())
  1730. break;
  1731. // Calculate the incoming numerator bits.
  1732. unsigned NumBits = ComputeNumSignBits(U->getOperand(0), DL, Depth + 1, Q);
  1733. // Add floor(log(C)) bits to the numerator bits.
  1734. return std::min(TyBits, NumBits + Denominator->logBase2());
  1735. }
  1736. break;
  1737. }
  1738. case Instruction::SRem: {
  1739. const APInt *Denominator;
  1740. // srem X, C -> we know that the result is within [-C+1,C) when C is a
  1741. // positive constant. This let us put a lower bound on the number of sign
  1742. // bits.
  1743. if (match(U->getOperand(1), m_APInt(Denominator))) {
  1744. // Ignore non-positive denominator.
  1745. if (!Denominator->isStrictlyPositive())
  1746. break;
  1747. // Calculate the incoming numerator bits. SRem by a positive constant
  1748. // can't lower the number of sign bits.
  1749. unsigned NumrBits =
  1750. ComputeNumSignBits(U->getOperand(0), DL, Depth + 1, Q);
  1751. // Calculate the leading sign bit constraints by examining the
  1752. // denominator. Given that the denominator is positive, there are two
  1753. // cases:
  1754. //
  1755. // 1. the numerator is positive. The result range is [0,C) and [0,C) u<
  1756. // (1 << ceilLogBase2(C)).
  1757. //
  1758. // 2. the numerator is negative. Then the result range is (-C,0] and
  1759. // integers in (-C,0] are either 0 or >u (-1 << ceilLogBase2(C)).
  1760. //
  1761. // Thus a lower bound on the number of sign bits is `TyBits -
  1762. // ceilLogBase2(C)`.
  1763. unsigned ResBits = TyBits - Denominator->ceilLogBase2();
  1764. return std::max(NumrBits, ResBits);
  1765. }
  1766. break;
  1767. }
  1768. case Instruction::AShr: {
  1769. Tmp = ComputeNumSignBits(U->getOperand(0), DL, Depth + 1, Q);
  1770. // ashr X, C -> adds C sign bits. Vectors too.
  1771. const APInt *ShAmt;
  1772. if (match(U->getOperand(1), m_APInt(ShAmt))) {
  1773. Tmp += ShAmt->getZExtValue();
  1774. if (Tmp > TyBits) Tmp = TyBits;
  1775. }
  1776. return Tmp;
  1777. }
  1778. case Instruction::Shl: {
  1779. const APInt *ShAmt;
  1780. if (match(U->getOperand(1), m_APInt(ShAmt))) {
  1781. // shl destroys sign bits.
  1782. Tmp = ComputeNumSignBits(U->getOperand(0), DL, Depth + 1, Q);
  1783. Tmp2 = ShAmt->getZExtValue();
  1784. if (Tmp2 >= TyBits || // Bad shift.
  1785. Tmp2 >= Tmp) break; // Shifted all sign bits out.
  1786. return Tmp - Tmp2;
  1787. }
  1788. break;
  1789. }
  1790. case Instruction::And:
  1791. case Instruction::Or:
  1792. case Instruction::Xor: // NOT is handled here.
  1793. // Logical binary ops preserve the number of sign bits at the worst.
  1794. Tmp = ComputeNumSignBits(U->getOperand(0), DL, Depth + 1, Q);
  1795. if (Tmp != 1) {
  1796. Tmp2 = ComputeNumSignBits(U->getOperand(1), DL, Depth + 1, Q);
  1797. FirstAnswer = std::min(Tmp, Tmp2);
  1798. // We computed what we know about the sign bits as our first
  1799. // answer. Now proceed to the generic code that uses
  1800. // computeKnownBits, and pick whichever answer is better.
  1801. }
  1802. break;
  1803. case Instruction::Select:
  1804. Tmp = ComputeNumSignBits(U->getOperand(1), DL, Depth + 1, Q);
  1805. if (Tmp == 1) return 1; // Early out.
  1806. Tmp2 = ComputeNumSignBits(U->getOperand(2), DL, Depth + 1, Q);
  1807. return std::min(Tmp, Tmp2);
  1808. case Instruction::Add:
  1809. // Add can have at most one carry bit. Thus we know that the output
  1810. // is, at worst, one more bit than the inputs.
  1811. Tmp = ComputeNumSignBits(U->getOperand(0), DL, Depth + 1, Q);
  1812. if (Tmp == 1) return 1; // Early out.
  1813. // Special case decrementing a value (ADD X, -1):
  1814. if (const auto *CRHS = dyn_cast<Constant>(U->getOperand(1)))
  1815. if (CRHS->isAllOnesValue()) {
  1816. APInt KnownZero(TyBits, 0), KnownOne(TyBits, 0);
  1817. computeKnownBits(U->getOperand(0), KnownZero, KnownOne, DL, Depth + 1,
  1818. Q);
  1819. // If the input is known to be 0 or 1, the output is 0/-1, which is all
  1820. // sign bits set.
  1821. if ((KnownZero | APInt(TyBits, 1)).isAllOnesValue())
  1822. return TyBits;
  1823. // If we are subtracting one from a positive number, there is no carry
  1824. // out of the result.
  1825. if (KnownZero.isNegative())
  1826. return Tmp;
  1827. }
  1828. Tmp2 = ComputeNumSignBits(U->getOperand(1), DL, Depth + 1, Q);
  1829. if (Tmp2 == 1) return 1;
  1830. return std::min(Tmp, Tmp2)-1;
  1831. case Instruction::Sub:
  1832. Tmp2 = ComputeNumSignBits(U->getOperand(1), DL, Depth + 1, Q);
  1833. if (Tmp2 == 1) return 1;
  1834. // Handle NEG.
  1835. if (const auto *CLHS = dyn_cast<Constant>(U->getOperand(0)))
  1836. if (CLHS->isNullValue()) {
  1837. APInt KnownZero(TyBits, 0), KnownOne(TyBits, 0);
  1838. computeKnownBits(U->getOperand(1), KnownZero, KnownOne, DL, Depth + 1,
  1839. Q);
  1840. // If the input is known to be 0 or 1, the output is 0/-1, which is all
  1841. // sign bits set.
  1842. if ((KnownZero | APInt(TyBits, 1)).isAllOnesValue())
  1843. return TyBits;
  1844. // If the input is known to be positive (the sign bit is known clear),
  1845. // the output of the NEG has the same number of sign bits as the input.
  1846. if (KnownZero.isNegative())
  1847. return Tmp2;
  1848. // Otherwise, we treat this like a SUB.
  1849. }
  1850. // Sub can have at most one carry bit. Thus we know that the output
  1851. // is, at worst, one more bit than the inputs.
  1852. Tmp = ComputeNumSignBits(U->getOperand(0), DL, Depth + 1, Q);
  1853. if (Tmp == 1) return 1; // Early out.
  1854. return std::min(Tmp, Tmp2)-1;
  1855. case Instruction::PHI: {
  1856. PHINode *PN = cast<PHINode>(U);
  1857. unsigned NumIncomingValues = PN->getNumIncomingValues();
  1858. // Don't analyze large in-degree PHIs.
  1859. if (NumIncomingValues > 4) break;
  1860. // Unreachable blocks may have zero-operand PHI nodes.
  1861. if (NumIncomingValues == 0) break;
  1862. // Take the minimum of all incoming values. This can't infinitely loop
  1863. // because of our depth threshold.
  1864. Tmp = ComputeNumSignBits(PN->getIncomingValue(0), DL, Depth + 1, Q);
  1865. for (unsigned i = 1, e = NumIncomingValues; i != e; ++i) {
  1866. if (Tmp == 1) return Tmp;
  1867. Tmp = std::min(
  1868. Tmp, ComputeNumSignBits(PN->getIncomingValue(i), DL, Depth + 1, Q));
  1869. }
  1870. return Tmp;
  1871. }
  1872. case Instruction::Trunc:
  1873. // FIXME: it's tricky to do anything useful for this, but it is an important
  1874. // case for targets like X86.
  1875. break;
  1876. }
  1877. // Finally, if we can prove that the top bits of the result are 0's or 1's,
  1878. // use this information.
  1879. APInt KnownZero(TyBits, 0), KnownOne(TyBits, 0);
  1880. APInt Mask;
  1881. computeKnownBits(V, KnownZero, KnownOne, DL, Depth, Q);
  1882. if (KnownZero.isNegative()) { // sign bit is 0
  1883. Mask = KnownZero;
  1884. } else if (KnownOne.isNegative()) { // sign bit is 1;
  1885. Mask = KnownOne;
  1886. } else {
  1887. // Nothing known.
  1888. return FirstAnswer;
  1889. }
  1890. // Okay, we know that the sign bit in Mask is set. Use CLZ to determine
  1891. // the number of identical bits in the top of the input value.
  1892. Mask = ~Mask;
  1893. Mask <<= Mask.getBitWidth()-TyBits;
  1894. // Return # leading zeros. We use 'min' here in case Val was zero before
  1895. // shifting. We don't want to return '64' as for an i32 "0".
  1896. return std::max(FirstAnswer, std::min(TyBits, Mask.countLeadingZeros()));
  1897. }
  1898. /// This function computes the integer multiple of Base that equals V.
  1899. /// If successful, it returns true and returns the multiple in
  1900. /// Multiple. If unsuccessful, it returns false. It looks
  1901. /// through SExt instructions only if LookThroughSExt is true.
  1902. bool llvm::ComputeMultiple(Value *V, unsigned Base, Value *&Multiple,
  1903. bool LookThroughSExt, unsigned Depth) {
  1904. const unsigned MaxDepth = 6;
  1905. assert(V && "No Value?");
  1906. assert(Depth <= MaxDepth && "Limit Search Depth");
  1907. assert(V->getType()->isIntegerTy() && "Not integer or pointer type!");
  1908. Type *T = V->getType();
  1909. ConstantInt *CI = dyn_cast<ConstantInt>(V);
  1910. if (Base == 0)
  1911. return false;
  1912. if (Base == 1) {
  1913. Multiple = V;
  1914. return true;
  1915. }
  1916. ConstantExpr *CO = dyn_cast<ConstantExpr>(V);
  1917. Constant *BaseVal = ConstantInt::get(T, Base);
  1918. if (CO && CO == BaseVal) {
  1919. // Multiple is 1.
  1920. Multiple = ConstantInt::get(T, 1);
  1921. return true;
  1922. }
  1923. if (CI && CI->getZExtValue() % Base == 0) {
  1924. Multiple = ConstantInt::get(T, CI->getZExtValue() / Base);
  1925. return true;
  1926. }
  1927. if (Depth == MaxDepth) return false; // Limit search depth.
  1928. Operator *I = dyn_cast<Operator>(V);
  1929. if (!I) return false;
  1930. switch (I->getOpcode()) {
  1931. default: break;
  1932. case Instruction::SExt:
  1933. if (!LookThroughSExt) return false;
  1934. // otherwise fall through to ZExt
  1935. case Instruction::ZExt:
  1936. return ComputeMultiple(I->getOperand(0), Base, Multiple,
  1937. LookThroughSExt, Depth+1);
  1938. case Instruction::Shl:
  1939. case Instruction::Mul: {
  1940. Value *Op0 = I->getOperand(0);
  1941. Value *Op1 = I->getOperand(1);
  1942. if (I->getOpcode() == Instruction::Shl) {
  1943. ConstantInt *Op1CI = dyn_cast<ConstantInt>(Op1);
  1944. if (!Op1CI) return false;
  1945. // Turn Op0 << Op1 into Op0 * 2^Op1
  1946. APInt Op1Int = Op1CI->getValue();
  1947. uint64_t BitToSet = Op1Int.getLimitedValue(Op1Int.getBitWidth() - 1);
  1948. APInt API(Op1Int.getBitWidth(), 0);
  1949. API.setBit(BitToSet);
  1950. Op1 = ConstantInt::get(V->getContext(), API);
  1951. }
  1952. Value *Mul0 = nullptr;
  1953. if (ComputeMultiple(Op0, Base, Mul0, LookThroughSExt, Depth+1)) {
  1954. if (Constant *Op1C = dyn_cast<Constant>(Op1))
  1955. if (Constant *MulC = dyn_cast<Constant>(Mul0)) {
  1956. if (Op1C->getType()->getPrimitiveSizeInBits() <
  1957. MulC->getType()->getPrimitiveSizeInBits())
  1958. Op1C = ConstantExpr::getZExt(Op1C, MulC->getType());
  1959. if (Op1C->getType()->getPrimitiveSizeInBits() >
  1960. MulC->getType()->getPrimitiveSizeInBits())
  1961. MulC = ConstantExpr::getZExt(MulC, Op1C->getType());
  1962. // V == Base * (Mul0 * Op1), so return (Mul0 * Op1)
  1963. Multiple = ConstantExpr::getMul(MulC, Op1C);
  1964. return true;
  1965. }
  1966. if (ConstantInt *Mul0CI = dyn_cast<ConstantInt>(Mul0))
  1967. if (Mul0CI->getValue() == 1) {
  1968. // V == Base * Op1, so return Op1
  1969. Multiple = Op1;
  1970. return true;
  1971. }
  1972. }
  1973. Value *Mul1 = nullptr;
  1974. if (ComputeMultiple(Op1, Base, Mul1, LookThroughSExt, Depth+1)) {
  1975. if (Constant *Op0C = dyn_cast<Constant>(Op0))
  1976. if (Constant *MulC = dyn_cast<Constant>(Mul1)) {
  1977. if (Op0C->getType()->getPrimitiveSizeInBits() <
  1978. MulC->getType()->getPrimitiveSizeInBits())
  1979. Op0C = ConstantExpr::getZExt(Op0C, MulC->getType());
  1980. if (Op0C->getType()->getPrimitiveSizeInBits() >
  1981. MulC->getType()->getPrimitiveSizeInBits())
  1982. MulC = ConstantExpr::getZExt(MulC, Op0C->getType());
  1983. // V == Base * (Mul1 * Op0), so return (Mul1 * Op0)
  1984. Multiple = ConstantExpr::getMul(MulC, Op0C);
  1985. return true;
  1986. }
  1987. if (ConstantInt *Mul1CI = dyn_cast<ConstantInt>(Mul1))
  1988. if (Mul1CI->getValue() == 1) {
  1989. // V == Base * Op0, so return Op0
  1990. Multiple = Op0;
  1991. return true;
  1992. }
  1993. }
  1994. }
  1995. }
  1996. // We could not determine if V is a multiple of Base.
  1997. return false;
  1998. }
  1999. /// Return true if we can prove that the specified FP value is never equal to
  2000. /// -0.0.
  2001. ///
  2002. /// NOTE: this function will need to be revisited when we support non-default
  2003. /// rounding modes!
  2004. ///
  2005. bool llvm::CannotBeNegativeZero(const Value *V, unsigned Depth) {
  2006. if (const ConstantFP *CFP = dyn_cast<ConstantFP>(V))
  2007. return !CFP->getValueAPF().isNegZero();
  2008. // FIXME: Magic number! At the least, this should be given a name because it's
  2009. // used similarly in CannotBeOrderedLessThanZero(). A better fix may be to
  2010. // expose it as a parameter, so it can be used for testing / experimenting.
  2011. if (Depth == 6)
  2012. return false; // Limit search depth.
  2013. const Operator *I = dyn_cast<Operator>(V);
  2014. if (!I) return false;
  2015. // Check if the nsz fast-math flag is set
  2016. if (const FPMathOperator *FPOp = dyn_cast<FPMathOperator>(I)) // HLSL Change - FPO -> FPOp (macro collision)
  2017. if (FPOp->hasNoSignedZeros()) // HLSL Change - FPO -> FPOp (macro collision)
  2018. return true;
  2019. // (add x, 0.0) is guaranteed to return +0.0, not -0.0.
  2020. if (I->getOpcode() == Instruction::FAdd)
  2021. if (ConstantFP *CFP = dyn_cast<ConstantFP>(I->getOperand(1)))
  2022. if (CFP->isNullValue())
  2023. return true;
  2024. // sitofp and uitofp turn into +0.0 for zero.
  2025. if (isa<SIToFPInst>(I) || isa<UIToFPInst>(I))
  2026. return true;
  2027. if (const IntrinsicInst *II = dyn_cast<IntrinsicInst>(I))
  2028. // sqrt(-0.0) = -0.0, no other negative results are possible.
  2029. if (II->getIntrinsicID() == Intrinsic::sqrt)
  2030. return CannotBeNegativeZero(II->getArgOperand(0), Depth+1);
  2031. if (const CallInst *CI = dyn_cast<CallInst>(I))
  2032. if (const Function *F = CI->getCalledFunction()) {
  2033. if (F->isDeclaration()) {
  2034. // abs(x) != -0.0
  2035. if (F->getName() == "abs") return true;
  2036. // fabs[lf](x) != -0.0
  2037. if (F->getName() == "fabs") return true;
  2038. if (F->getName() == "fabsf") return true;
  2039. if (F->getName() == "fabsl") return true;
  2040. if (F->getName() == "sqrt" || F->getName() == "sqrtf" ||
  2041. F->getName() == "sqrtl")
  2042. return CannotBeNegativeZero(CI->getArgOperand(0), Depth+1);
  2043. }
  2044. }
  2045. return false;
  2046. }
  2047. bool llvm::CannotBeOrderedLessThanZero(const Value *V, unsigned Depth) {
  2048. if (const ConstantFP *CFP = dyn_cast<ConstantFP>(V))
  2049. return !CFP->getValueAPF().isNegative() || CFP->getValueAPF().isZero();
  2050. // FIXME: Magic number! At the least, this should be given a name because it's
  2051. // used similarly in CannotBeNegativeZero(). A better fix may be to
  2052. // expose it as a parameter, so it can be used for testing / experimenting.
  2053. if (Depth == 6)
  2054. return false; // Limit search depth.
  2055. const Operator *I = dyn_cast<Operator>(V);
  2056. if (!I) return false;
  2057. switch (I->getOpcode()) {
  2058. default: break;
  2059. case Instruction::FMul:
  2060. // x*x is always non-negative or a NaN.
  2061. if (I->getOperand(0) == I->getOperand(1))
  2062. return true;
  2063. // Fall through
  2064. case Instruction::FAdd:
  2065. case Instruction::FDiv:
  2066. case Instruction::FRem:
  2067. return CannotBeOrderedLessThanZero(I->getOperand(0), Depth+1) &&
  2068. CannotBeOrderedLessThanZero(I->getOperand(1), Depth+1);
  2069. case Instruction::FPExt:
  2070. case Instruction::FPTrunc:
  2071. // Widening/narrowing never change sign.
  2072. return CannotBeOrderedLessThanZero(I->getOperand(0), Depth+1);
  2073. case Instruction::Call:
  2074. if (const IntrinsicInst *II = dyn_cast<IntrinsicInst>(I))
  2075. switch (II->getIntrinsicID()) {
  2076. default: break;
  2077. case Intrinsic::exp:
  2078. case Intrinsic::exp2:
  2079. case Intrinsic::fabs:
  2080. case Intrinsic::sqrt:
  2081. return true;
  2082. case Intrinsic::powi:
  2083. if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
  2084. // powi(x,n) is non-negative if n is even.
  2085. if (CI->getBitWidth() <= 64 && CI->getSExtValue() % 2u == 0)
  2086. return true;
  2087. }
  2088. return CannotBeOrderedLessThanZero(I->getOperand(0), Depth+1);
  2089. case Intrinsic::fma:
  2090. case Intrinsic::fmuladd:
  2091. // x*x+y is non-negative if y is non-negative.
  2092. return I->getOperand(0) == I->getOperand(1) &&
  2093. CannotBeOrderedLessThanZero(I->getOperand(2), Depth+1);
  2094. }
  2095. break;
  2096. }
  2097. return false;
  2098. }
  2099. /// If the specified value can be set by repeating the same byte in memory,
  2100. /// return the i8 value that it is represented with. This is
  2101. /// true for all i8 values obviously, but is also true for i32 0, i32 -1,
  2102. /// i16 0xF0F0, double 0.0 etc. If the value can't be handled with a repeated
  2103. /// byte store (e.g. i16 0x1234), return null.
  2104. Value *llvm::isBytewiseValue(Value *V) {
  2105. // All byte-wide stores are splatable, even of arbitrary variables.
  2106. if (V->getType()->isIntegerTy(8)) return V;
  2107. // Handle 'null' ConstantArrayZero etc.
  2108. if (Constant *C = dyn_cast<Constant>(V))
  2109. if (C->isNullValue())
  2110. return Constant::getNullValue(Type::getInt8Ty(V->getContext()));
  2111. // Constant float and double values can be handled as integer values if the
  2112. // corresponding integer value is "byteable". An important case is 0.0.
  2113. if (ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
  2114. if (CFP->getType()->isFloatTy())
  2115. V = ConstantExpr::getBitCast(CFP, Type::getInt32Ty(V->getContext()));
  2116. if (CFP->getType()->isDoubleTy())
  2117. V = ConstantExpr::getBitCast(CFP, Type::getInt64Ty(V->getContext()));
  2118. // Don't handle long double formats, which have strange constraints.
  2119. }
  2120. // We can handle constant integers that are multiple of 8 bits.
  2121. if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
  2122. if (CI->getBitWidth() % 8 == 0) {
  2123. assert(CI->getBitWidth() > 8 && "8 bits should be handled above!");
  2124. if (!CI->getValue().isSplat(8))
  2125. return nullptr;
  2126. return ConstantInt::get(V->getContext(), CI->getValue().trunc(8));
  2127. }
  2128. }
  2129. // A ConstantDataArray/Vector is splatable if all its members are equal and
  2130. // also splatable.
  2131. if (ConstantDataSequential *CA = dyn_cast<ConstantDataSequential>(V)) {
  2132. Value *Elt = CA->getElementAsConstant(0);
  2133. Value *Val = isBytewiseValue(Elt);
  2134. if (!Val)
  2135. return nullptr;
  2136. for (unsigned I = 1, E = CA->getNumElements(); I != E; ++I)
  2137. if (CA->getElementAsConstant(I) != Elt)
  2138. return nullptr;
  2139. return Val;
  2140. }
  2141. // Conceptually, we could handle things like:
  2142. // %a = zext i8 %X to i16
  2143. // %b = shl i16 %a, 8
  2144. // %c = or i16 %a, %b
  2145. // but until there is an example that actually needs this, it doesn't seem
  2146. // worth worrying about.
  2147. return nullptr;
  2148. }
  2149. // This is the recursive version of BuildSubAggregate. It takes a few different
  2150. // arguments. Idxs is the index within the nested struct From that we are
  2151. // looking at now (which is of type IndexedType). IdxSkip is the number of
  2152. // indices from Idxs that should be left out when inserting into the resulting
  2153. // struct. To is the result struct built so far, new insertvalue instructions
  2154. // build on that.
  2155. static Value *BuildSubAggregate(Value *From, Value* To, Type *IndexedType,
  2156. SmallVectorImpl<unsigned> &Idxs,
  2157. unsigned IdxSkip,
  2158. Instruction *InsertBefore) {
  2159. llvm::StructType *STy = dyn_cast<llvm::StructType>(IndexedType);
  2160. if (STy) {
  2161. // Save the original To argument so we can modify it
  2162. Value *OrigTo = To;
  2163. // General case, the type indexed by Idxs is a struct
  2164. for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
  2165. // Process each struct element recursively
  2166. Idxs.push_back(i);
  2167. Value *PrevTo = To;
  2168. To = BuildSubAggregate(From, To, STy->getElementType(i), Idxs, IdxSkip,
  2169. InsertBefore);
  2170. Idxs.pop_back();
  2171. if (!To) {
  2172. // Couldn't find any inserted value for this index? Cleanup
  2173. while (PrevTo != OrigTo) {
  2174. InsertValueInst* Del = cast<InsertValueInst>(PrevTo);
  2175. PrevTo = Del->getAggregateOperand();
  2176. Del->eraseFromParent();
  2177. }
  2178. // Stop processing elements
  2179. break;
  2180. }
  2181. }
  2182. // If we successfully found a value for each of our subaggregates
  2183. if (To)
  2184. return To;
  2185. }
  2186. // Base case, the type indexed by SourceIdxs is not a struct, or not all of
  2187. // the struct's elements had a value that was inserted directly. In the latter
  2188. // case, perhaps we can't determine each of the subelements individually, but
  2189. // we might be able to find the complete struct somewhere.
  2190. // Find the value that is at that particular spot
  2191. Value *V = FindInsertedValue(From, Idxs);
  2192. if (!V)
  2193. return nullptr;
  2194. // Insert the value in the new (sub) aggregrate
  2195. return llvm::InsertValueInst::Create(To, V, makeArrayRef(Idxs).slice(IdxSkip),
  2196. "tmp", InsertBefore);
  2197. }
  2198. // This helper takes a nested struct and extracts a part of it (which is again a
  2199. // struct) into a new value. For example, given the struct:
  2200. // { a, { b, { c, d }, e } }
  2201. // and the indices "1, 1" this returns
  2202. // { c, d }.
  2203. //
  2204. // It does this by inserting an insertvalue for each element in the resulting
  2205. // struct, as opposed to just inserting a single struct. This will only work if
  2206. // each of the elements of the substruct are known (ie, inserted into From by an
  2207. // insertvalue instruction somewhere).
  2208. //
  2209. // All inserted insertvalue instructions are inserted before InsertBefore
  2210. static Value *BuildSubAggregate(Value *From, ArrayRef<unsigned> idx_range,
  2211. Instruction *InsertBefore) {
  2212. assert(InsertBefore && "Must have someplace to insert!");
  2213. Type *IndexedType = ExtractValueInst::getIndexedType(From->getType(),
  2214. idx_range);
  2215. Value *To = UndefValue::get(IndexedType);
  2216. SmallVector<unsigned, 10> Idxs(idx_range.begin(), idx_range.end());
  2217. unsigned IdxSkip = Idxs.size();
  2218. return BuildSubAggregate(From, To, IndexedType, Idxs, IdxSkip, InsertBefore);
  2219. }
  2220. /// Given an aggregrate and an sequence of indices, see if
  2221. /// the scalar value indexed is already around as a register, for example if it
  2222. /// were inserted directly into the aggregrate.
  2223. ///
  2224. /// If InsertBefore is not null, this function will duplicate (modified)
  2225. /// insertvalues when a part of a nested struct is extracted.
  2226. Value *llvm::FindInsertedValue(Value *V, ArrayRef<unsigned> idx_range,
  2227. Instruction *InsertBefore) {
  2228. // Nothing to index? Just return V then (this is useful at the end of our
  2229. // recursion).
  2230. if (idx_range.empty())
  2231. return V;
  2232. // We have indices, so V should have an indexable type.
  2233. assert((V->getType()->isStructTy() || V->getType()->isArrayTy()) &&
  2234. "Not looking at a struct or array?");
  2235. assert(ExtractValueInst::getIndexedType(V->getType(), idx_range) &&
  2236. "Invalid indices for type?");
  2237. if (Constant *C = dyn_cast<Constant>(V)) {
  2238. C = C->getAggregateElement(idx_range[0]);
  2239. if (!C) return nullptr;
  2240. return FindInsertedValue(C, idx_range.slice(1), InsertBefore);
  2241. }
  2242. if (InsertValueInst *I = dyn_cast<InsertValueInst>(V)) {
  2243. // Loop the indices for the insertvalue instruction in parallel with the
  2244. // requested indices
  2245. const unsigned *req_idx = idx_range.begin();
  2246. for (const unsigned *i = I->idx_begin(), *e = I->idx_end();
  2247. i != e; ++i, ++req_idx) {
  2248. if (req_idx == idx_range.end()) {
  2249. // We can't handle this without inserting insertvalues
  2250. if (!InsertBefore)
  2251. return nullptr;
  2252. // The requested index identifies a part of a nested aggregate. Handle
  2253. // this specially. For example,
  2254. // %A = insertvalue { i32, {i32, i32 } } undef, i32 10, 1, 0
  2255. // %B = insertvalue { i32, {i32, i32 } } %A, i32 11, 1, 1
  2256. // %C = extractvalue {i32, { i32, i32 } } %B, 1
  2257. // This can be changed into
  2258. // %A = insertvalue {i32, i32 } undef, i32 10, 0
  2259. // %C = insertvalue {i32, i32 } %A, i32 11, 1
  2260. // which allows the unused 0,0 element from the nested struct to be
  2261. // removed.
  2262. return BuildSubAggregate(V, makeArrayRef(idx_range.begin(), req_idx),
  2263. InsertBefore);
  2264. }
  2265. // This insert value inserts something else than what we are looking for.
  2266. // See if the (aggregrate) value inserted into has the value we are
  2267. // looking for, then.
  2268. if (*req_idx != *i)
  2269. return FindInsertedValue(I->getAggregateOperand(), idx_range,
  2270. InsertBefore);
  2271. }
  2272. // If we end up here, the indices of the insertvalue match with those
  2273. // requested (though possibly only partially). Now we recursively look at
  2274. // the inserted value, passing any remaining indices.
  2275. return FindInsertedValue(I->getInsertedValueOperand(),
  2276. makeArrayRef(req_idx, idx_range.end()),
  2277. InsertBefore);
  2278. }
  2279. if (ExtractValueInst *I = dyn_cast<ExtractValueInst>(V)) {
  2280. // If we're extracting a value from an aggregrate that was extracted from
  2281. // something else, we can extract from that something else directly instead.
  2282. // However, we will need to chain I's indices with the requested indices.
  2283. // Calculate the number of indices required
  2284. unsigned size = I->getNumIndices() + idx_range.size();
  2285. // Allocate some space to put the new indices in
  2286. SmallVector<unsigned, 5> Idxs;
  2287. Idxs.reserve(size);
  2288. // Add indices from the extract value instruction
  2289. Idxs.append(I->idx_begin(), I->idx_end());
  2290. // Add requested indices
  2291. Idxs.append(idx_range.begin(), idx_range.end());
  2292. assert(Idxs.size() == size
  2293. && "Number of indices added not correct?");
  2294. return FindInsertedValue(I->getAggregateOperand(), Idxs, InsertBefore);
  2295. }
  2296. // Otherwise, we don't know (such as, extracting from a function return value
  2297. // or load instruction)
  2298. return nullptr;
  2299. }
  2300. /// Analyze the specified pointer to see if it can be expressed as a base
  2301. /// pointer plus a constant offset. Return the base and offset to the caller.
  2302. Value *llvm::GetPointerBaseWithConstantOffset(Value *Ptr, int64_t &Offset,
  2303. const DataLayout &DL) {
  2304. unsigned BitWidth = DL.getPointerTypeSizeInBits(Ptr->getType());
  2305. APInt ByteOffset(BitWidth, 0);
  2306. while (1) {
  2307. if (Ptr->getType()->isVectorTy())
  2308. break;
  2309. if (GEPOperator *GEP = dyn_cast<GEPOperator>(Ptr)) {
  2310. APInt GEPOffset(BitWidth, 0);
  2311. if (!GEP->accumulateConstantOffset(DL, GEPOffset))
  2312. break;
  2313. ByteOffset += GEPOffset;
  2314. Ptr = GEP->getPointerOperand();
  2315. } else if (Operator::getOpcode(Ptr) == Instruction::BitCast ||
  2316. Operator::getOpcode(Ptr) == Instruction::AddrSpaceCast) {
  2317. Ptr = cast<Operator>(Ptr)->getOperand(0);
  2318. } else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(Ptr)) {
  2319. if (GA->mayBeOverridden())
  2320. break;
  2321. Ptr = GA->getAliasee();
  2322. } else {
  2323. break;
  2324. }
  2325. }
  2326. Offset = ByteOffset.getSExtValue();
  2327. return Ptr;
  2328. }
  2329. /// This function computes the length of a null-terminated C string pointed to
  2330. /// by V. If successful, it returns true and returns the string in Str.
  2331. /// If unsuccessful, it returns false.
  2332. bool llvm::getConstantStringInfo(const Value *V, StringRef &Str,
  2333. uint64_t Offset, bool TrimAtNul) {
  2334. assert(V);
  2335. // Look through bitcast instructions and geps.
  2336. V = V->stripPointerCasts();
  2337. // If the value is a GEP instruction or constant expression, treat it as an
  2338. // offset.
  2339. if (const GEPOperator *GEP = dyn_cast<GEPOperator>(V)) {
  2340. // Make sure the GEP has exactly three arguments.
  2341. if (GEP->getNumOperands() != 3)
  2342. return false;
  2343. // Make sure the index-ee is a pointer to array of i8.
  2344. PointerType *PT = cast<PointerType>(GEP->getOperand(0)->getType());
  2345. ArrayType *AT = dyn_cast<ArrayType>(PT->getElementType());
  2346. if (!AT || !AT->getElementType()->isIntegerTy(8))
  2347. return false;
  2348. // Check to make sure that the first operand of the GEP is an integer and
  2349. // has value 0 so that we are sure we're indexing into the initializer.
  2350. const ConstantInt *FirstIdx = dyn_cast<ConstantInt>(GEP->getOperand(1));
  2351. if (!FirstIdx || !FirstIdx->isZero())
  2352. return false;
  2353. // If the second index isn't a ConstantInt, then this is a variable index
  2354. // into the array. If this occurs, we can't say anything meaningful about
  2355. // the string.
  2356. uint64_t StartIdx = 0;
  2357. if (const ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(2)))
  2358. StartIdx = CI->getZExtValue();
  2359. else
  2360. return false;
  2361. return getConstantStringInfo(GEP->getOperand(0), Str, StartIdx + Offset,
  2362. TrimAtNul);
  2363. }
  2364. // The GEP instruction, constant or instruction, must reference a global
  2365. // variable that is a constant and is initialized. The referenced constant
  2366. // initializer is the array that we'll use for optimization.
  2367. const GlobalVariable *GV = dyn_cast<GlobalVariable>(V);
  2368. if (!GV || !GV->isConstant() || !GV->hasDefinitiveInitializer())
  2369. return false;
  2370. // Handle the all-zeros case
  2371. if (GV->getInitializer()->isNullValue()) {
  2372. // This is a degenerate case. The initializer is constant zero so the
  2373. // length of the string must be zero.
  2374. Str = "";
  2375. return true;
  2376. }
  2377. // Must be a Constant Array
  2378. const ConstantDataArray *Array =
  2379. dyn_cast<ConstantDataArray>(GV->getInitializer());
  2380. if (!Array || !Array->isString())
  2381. return false;
  2382. // Get the number of elements in the array
  2383. uint64_t NumElts = Array->getType()->getArrayNumElements();
  2384. // Start out with the entire array in the StringRef.
  2385. Str = Array->getAsString();
  2386. if (Offset > NumElts)
  2387. return false;
  2388. // Skip over 'offset' bytes.
  2389. Str = Str.substr(Offset);
  2390. if (TrimAtNul) {
  2391. // Trim off the \0 and anything after it. If the array is not nul
  2392. // terminated, we just return the whole end of string. The client may know
  2393. // some other way that the string is length-bound.
  2394. Str = Str.substr(0, Str.find('\0'));
  2395. }
  2396. return true;
  2397. }
  2398. // These next two are very similar to the above, but also look through PHI
  2399. // nodes.
  2400. // TODO: See if we can integrate these two together.
  2401. /// If we can compute the length of the string pointed to by
  2402. /// the specified pointer, return 'len+1'. If we can't, return 0.
  2403. static uint64_t GetStringLengthH(Value *V, SmallPtrSetImpl<PHINode*> &PHIs) {
  2404. // Look through noop bitcast instructions.
  2405. V = V->stripPointerCasts();
  2406. // If this is a PHI node, there are two cases: either we have already seen it
  2407. // or we haven't.
  2408. if (PHINode *PN = dyn_cast<PHINode>(V)) {
  2409. if (!PHIs.insert(PN).second)
  2410. return ~0ULL; // already in the set.
  2411. // If it was new, see if all the input strings are the same length.
  2412. uint64_t LenSoFar = ~0ULL;
  2413. for (Value *IncValue : PN->incoming_values()) {
  2414. uint64_t Len = GetStringLengthH(IncValue, PHIs);
  2415. if (Len == 0) return 0; // Unknown length -> unknown.
  2416. if (Len == ~0ULL) continue;
  2417. if (Len != LenSoFar && LenSoFar != ~0ULL)
  2418. return 0; // Disagree -> unknown.
  2419. LenSoFar = Len;
  2420. }
  2421. // Success, all agree.
  2422. return LenSoFar;
  2423. }
  2424. // strlen(select(c,x,y)) -> strlen(x) ^ strlen(y)
  2425. if (SelectInst *SI = dyn_cast<SelectInst>(V)) {
  2426. uint64_t Len1 = GetStringLengthH(SI->getTrueValue(), PHIs);
  2427. if (Len1 == 0) return 0;
  2428. uint64_t Len2 = GetStringLengthH(SI->getFalseValue(), PHIs);
  2429. if (Len2 == 0) return 0;
  2430. if (Len1 == ~0ULL) return Len2;
  2431. if (Len2 == ~0ULL) return Len1;
  2432. if (Len1 != Len2) return 0;
  2433. return Len1;
  2434. }
  2435. // Otherwise, see if we can read the string.
  2436. StringRef StrData;
  2437. if (!getConstantStringInfo(V, StrData))
  2438. return 0;
  2439. return StrData.size()+1;
  2440. }
  2441. /// If we can compute the length of the string pointed to by
  2442. /// the specified pointer, return 'len+1'. If we can't, return 0.
  2443. uint64_t llvm::GetStringLength(Value *V) {
  2444. if (!V->getType()->isPointerTy()) return 0;
  2445. SmallPtrSet<PHINode*, 32> PHIs;
  2446. uint64_t Len = GetStringLengthH(V, PHIs);
  2447. // If Len is ~0ULL, we had an infinite phi cycle: this is dead code, so return
  2448. // an empty string as a length.
  2449. return Len == ~0ULL ? 1 : Len;
  2450. }
  2451. /// \brief \p PN defines a loop-variant pointer to an object. Check if the
  2452. /// previous iteration of the loop was referring to the same object as \p PN.
  2453. static bool isSameUnderlyingObjectInLoop(PHINode *PN, LoopInfo *LI) {
  2454. // Find the loop-defined value.
  2455. Loop *L = LI->getLoopFor(PN->getParent());
  2456. if (PN->getNumIncomingValues() != 2)
  2457. return true;
  2458. // Find the value from previous iteration.
  2459. auto *PrevValue = dyn_cast<Instruction>(PN->getIncomingValue(0));
  2460. if (!PrevValue || LI->getLoopFor(PrevValue->getParent()) != L)
  2461. PrevValue = dyn_cast<Instruction>(PN->getIncomingValue(1));
  2462. if (!PrevValue || LI->getLoopFor(PrevValue->getParent()) != L)
  2463. return true;
  2464. // If a new pointer is loaded in the loop, the pointer references a different
  2465. // object in every iteration. E.g.:
  2466. // for (i)
  2467. // int *p = a[i];
  2468. // ...
  2469. if (auto *Load = dyn_cast<LoadInst>(PrevValue))
  2470. if (!L->isLoopInvariant(Load->getPointerOperand()))
  2471. return false;
  2472. return true;
  2473. }
  2474. Value *llvm::GetUnderlyingObject(Value *V, const DataLayout &DL,
  2475. unsigned MaxLookup) {
  2476. if (!V->getType()->isPointerTy())
  2477. return V;
  2478. for (unsigned Count = 0; MaxLookup == 0 || Count < MaxLookup; ++Count) {
  2479. if (GEPOperator *GEP = dyn_cast<GEPOperator>(V)) {
  2480. V = GEP->getPointerOperand();
  2481. } else if (Operator::getOpcode(V) == Instruction::BitCast ||
  2482. Operator::getOpcode(V) == Instruction::AddrSpaceCast) {
  2483. V = cast<Operator>(V)->getOperand(0);
  2484. } else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) {
  2485. if (GA->mayBeOverridden())
  2486. return V;
  2487. V = GA->getAliasee();
  2488. } else {
  2489. // See if InstructionSimplify knows any relevant tricks.
  2490. if (Instruction *I = dyn_cast<Instruction>(V))
  2491. // TODO: Acquire a DominatorTree and AssumptionCache and use them.
  2492. if (Value *Simplified = SimplifyInstruction(I, DL, nullptr)) {
  2493. V = Simplified;
  2494. continue;
  2495. }
  2496. return V;
  2497. }
  2498. assert(V->getType()->isPointerTy() && "Unexpected operand type!");
  2499. }
  2500. return V;
  2501. }
  2502. void llvm::GetUnderlyingObjects(Value *V, SmallVectorImpl<Value *> &Objects,
  2503. const DataLayout &DL, LoopInfo *LI,
  2504. unsigned MaxLookup) {
  2505. SmallPtrSet<Value *, 4> Visited;
  2506. SmallVector<Value *, 4> Worklist;
  2507. Worklist.push_back(V);
  2508. do {
  2509. Value *P = Worklist.pop_back_val();
  2510. P = GetUnderlyingObject(P, DL, MaxLookup);
  2511. if (!Visited.insert(P).second)
  2512. continue;
  2513. if (SelectInst *SI = dyn_cast<SelectInst>(P)) {
  2514. Worklist.push_back(SI->getTrueValue());
  2515. Worklist.push_back(SI->getFalseValue());
  2516. continue;
  2517. }
  2518. if (PHINode *PN = dyn_cast<PHINode>(P)) {
  2519. // If this PHI changes the underlying object in every iteration of the
  2520. // loop, don't look through it. Consider:
  2521. // int **A;
  2522. // for (i) {
  2523. // Prev = Curr; // Prev = PHI (Prev_0, Curr)
  2524. // Curr = A[i];
  2525. // *Prev, *Curr;
  2526. //
  2527. // Prev is tracking Curr one iteration behind so they refer to different
  2528. // underlying objects.
  2529. if (!LI || !LI->isLoopHeader(PN->getParent()) ||
  2530. isSameUnderlyingObjectInLoop(PN, LI))
  2531. for (Value *IncValue : PN->incoming_values())
  2532. Worklist.push_back(IncValue);
  2533. continue;
  2534. }
  2535. Objects.push_back(P);
  2536. } while (!Worklist.empty());
  2537. }
  2538. /// Return true if the only users of this pointer are lifetime markers.
  2539. bool llvm::onlyUsedByLifetimeMarkers(const Value *V) {
  2540. for (const User *U : V->users()) {
  2541. const IntrinsicInst *II = dyn_cast<IntrinsicInst>(U);
  2542. if (!II) return false;
  2543. if (II->getIntrinsicID() != Intrinsic::lifetime_start &&
  2544. II->getIntrinsicID() != Intrinsic::lifetime_end)
  2545. return false;
  2546. }
  2547. return true;
  2548. }
  2549. static bool isDereferenceableFromAttribute(const Value *BV, APInt Offset,
  2550. Type *Ty, const DataLayout &DL,
  2551. const Instruction *CtxI,
  2552. const DominatorTree *DT,
  2553. const TargetLibraryInfo *TLI) {
  2554. assert(Offset.isNonNegative() && "offset can't be negative");
  2555. assert(Ty->isSized() && "must be sized");
  2556. APInt DerefBytes(Offset.getBitWidth(), 0);
  2557. bool CheckForNonNull = false;
  2558. if (const Argument *A = dyn_cast<Argument>(BV)) {
  2559. DerefBytes = A->getDereferenceableBytes();
  2560. if (!DerefBytes.getBoolValue()) {
  2561. DerefBytes = A->getDereferenceableOrNullBytes();
  2562. CheckForNonNull = true;
  2563. }
  2564. } else if (auto CS = ImmutableCallSite(BV)) {
  2565. DerefBytes = CS.getDereferenceableBytes(0);
  2566. if (!DerefBytes.getBoolValue()) {
  2567. DerefBytes = CS.getDereferenceableOrNullBytes(0);
  2568. CheckForNonNull = true;
  2569. }
  2570. } else if (const LoadInst *LI = dyn_cast<LoadInst>(BV)) {
  2571. if (MDNode *MD = LI->getMetadata(LLVMContext::MD_dereferenceable)) {
  2572. ConstantInt *CI = mdconst::extract<ConstantInt>(MD->getOperand(0));
  2573. DerefBytes = CI->getLimitedValue();
  2574. }
  2575. if (!DerefBytes.getBoolValue()) {
  2576. if (MDNode *MD =
  2577. LI->getMetadata(LLVMContext::MD_dereferenceable_or_null)) {
  2578. ConstantInt *CI = mdconst::extract<ConstantInt>(MD->getOperand(0));
  2579. DerefBytes = CI->getLimitedValue();
  2580. }
  2581. CheckForNonNull = true;
  2582. }
  2583. }
  2584. if (DerefBytes.getBoolValue())
  2585. if (DerefBytes.uge(Offset + DL.getTypeStoreSize(Ty)))
  2586. if (!CheckForNonNull || isKnownNonNullAt(BV, CtxI, DT, TLI))
  2587. return true;
  2588. return false;
  2589. }
  2590. static bool isDereferenceableFromAttribute(const Value *V, const DataLayout &DL,
  2591. const Instruction *CtxI,
  2592. const DominatorTree *DT,
  2593. const TargetLibraryInfo *TLI) {
  2594. Type *VTy = V->getType();
  2595. Type *Ty = VTy->getPointerElementType();
  2596. if (!Ty->isSized())
  2597. return false;
  2598. APInt Offset(DL.getTypeStoreSizeInBits(VTy), 0);
  2599. return isDereferenceableFromAttribute(V, Offset, Ty, DL, CtxI, DT, TLI);
  2600. }
  2601. /// Return true if Value is always a dereferenceable pointer.
  2602. ///
  2603. /// Test if V is always a pointer to allocated and suitably aligned memory for
  2604. /// a simple load or store.
  2605. static bool isDereferenceablePointer(const Value *V, const DataLayout &DL,
  2606. const Instruction *CtxI,
  2607. const DominatorTree *DT,
  2608. const TargetLibraryInfo *TLI,
  2609. SmallPtrSetImpl<const Value *> &Visited) {
  2610. // Note that it is not safe to speculate into a malloc'd region because
  2611. // malloc may return null.
  2612. // These are obviously ok.
  2613. if (isa<AllocaInst>(V)) return true;
  2614. // It's not always safe to follow a bitcast, for example:
  2615. // bitcast i8* (alloca i8) to i32*
  2616. // would result in a 4-byte load from a 1-byte alloca. However,
  2617. // if we're casting from a pointer from a type of larger size
  2618. // to a type of smaller size (or the same size), and the alignment
  2619. // is at least as large as for the resulting pointer type, then
  2620. // we can look through the bitcast.
  2621. if (const BitCastOperator *BC = dyn_cast<BitCastOperator>(V)) {
  2622. Type *STy = BC->getSrcTy()->getPointerElementType(),
  2623. *DTy = BC->getDestTy()->getPointerElementType();
  2624. if (STy->isSized() && DTy->isSized() &&
  2625. (DL.getTypeStoreSize(STy) >= DL.getTypeStoreSize(DTy)) &&
  2626. (DL.getABITypeAlignment(STy) >= DL.getABITypeAlignment(DTy)))
  2627. return isDereferenceablePointer(BC->getOperand(0), DL, CtxI,
  2628. DT, TLI, Visited);
  2629. }
  2630. // Global variables which can't collapse to null are ok.
  2631. if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(V))
  2632. return !GV->hasExternalWeakLinkage();
  2633. // byval arguments are okay.
  2634. if (const Argument *A = dyn_cast<Argument>(V))
  2635. if (A->hasByValAttr())
  2636. return true;
  2637. if (isDereferenceableFromAttribute(V, DL, CtxI, DT, TLI))
  2638. return true;
  2639. // For GEPs, determine if the indexing lands within the allocated object.
  2640. if (const GEPOperator *GEP = dyn_cast<GEPOperator>(V)) {
  2641. Type *VTy = GEP->getType();
  2642. Type *Ty = VTy->getPointerElementType();
  2643. const Value *Base = GEP->getPointerOperand();
  2644. // Conservatively require that the base pointer be fully dereferenceable.
  2645. if (!Visited.insert(Base).second)
  2646. return false;
  2647. if (!isDereferenceablePointer(Base, DL, CtxI,
  2648. DT, TLI, Visited))
  2649. return false;
  2650. APInt Offset(DL.getPointerTypeSizeInBits(VTy), 0);
  2651. if (!GEP->accumulateConstantOffset(DL, Offset))
  2652. return false;
  2653. // Check if the load is within the bounds of the underlying object.
  2654. uint64_t LoadSize = DL.getTypeStoreSize(Ty);
  2655. Type *BaseType = Base->getType()->getPointerElementType();
  2656. return (Offset + LoadSize).ule(DL.getTypeAllocSize(BaseType));
  2657. }
  2658. // For gc.relocate, look through relocations
  2659. if (const IntrinsicInst *I = dyn_cast<IntrinsicInst>(V))
  2660. if (I->getIntrinsicID() == Intrinsic::experimental_gc_relocate) {
  2661. GCRelocateOperands RelocateInst(I);
  2662. return isDereferenceablePointer(RelocateInst.getDerivedPtr(), DL, CtxI,
  2663. DT, TLI, Visited);
  2664. }
  2665. if (const AddrSpaceCastInst *ASC = dyn_cast<AddrSpaceCastInst>(V))
  2666. return isDereferenceablePointer(ASC->getOperand(0), DL, CtxI,
  2667. DT, TLI, Visited);
  2668. // If we don't know, assume the worst.
  2669. return false;
  2670. }
  2671. bool llvm::isDereferenceablePointer(const Value *V, const DataLayout &DL,
  2672. const Instruction *CtxI,
  2673. const DominatorTree *DT,
  2674. const TargetLibraryInfo *TLI) {
  2675. // When dereferenceability information is provided by a dereferenceable
  2676. // attribute, we know exactly how many bytes are dereferenceable. If we can
  2677. // determine the exact offset to the attributed variable, we can use that
  2678. // information here.
  2679. Type *VTy = V->getType();
  2680. Type *Ty = VTy->getPointerElementType();
  2681. if (Ty->isSized()) {
  2682. APInt Offset(DL.getTypeStoreSizeInBits(VTy), 0);
  2683. const Value *BV = V->stripAndAccumulateInBoundsConstantOffsets(DL, Offset);
  2684. if (Offset.isNonNegative())
  2685. if (isDereferenceableFromAttribute(BV, Offset, Ty, DL,
  2686. CtxI, DT, TLI))
  2687. return true;
  2688. }
  2689. SmallPtrSet<const Value *, 32> Visited;
  2690. return ::isDereferenceablePointer(V, DL, CtxI, DT, TLI, Visited);
  2691. }
  2692. bool llvm::isSafeToSpeculativelyExecute(const Value *V,
  2693. const Instruction *CtxI,
  2694. const DominatorTree *DT,
  2695. const TargetLibraryInfo *TLI) {
  2696. const Operator *Inst = dyn_cast<Operator>(V);
  2697. if (!Inst)
  2698. return false;
  2699. for (unsigned i = 0, e = Inst->getNumOperands(); i != e; ++i)
  2700. if (Constant *C = dyn_cast<Constant>(Inst->getOperand(i)))
  2701. if (C->canTrap())
  2702. return false;
  2703. switch (Inst->getOpcode()) {
  2704. default:
  2705. return true;
  2706. case Instruction::UDiv:
  2707. case Instruction::URem: {
  2708. // x / y is undefined if y == 0.
  2709. const APInt *V;
  2710. if (match(Inst->getOperand(1), m_APInt(V)))
  2711. return *V != 0;
  2712. return false;
  2713. }
  2714. case Instruction::SDiv:
  2715. case Instruction::SRem: {
  2716. // x / y is undefined if y == 0 or x == INT_MIN and y == -1
  2717. const APInt *Numerator, *Denominator;
  2718. if (!match(Inst->getOperand(1), m_APInt(Denominator)))
  2719. return false;
  2720. // We cannot hoist this division if the denominator is 0.
  2721. if (*Denominator == 0)
  2722. return false;
  2723. // It's safe to hoist if the denominator is not 0 or -1.
  2724. if (*Denominator != -1)
  2725. return true;
  2726. // At this point we know that the denominator is -1. It is safe to hoist as
  2727. // long we know that the numerator is not INT_MIN.
  2728. if (match(Inst->getOperand(0), m_APInt(Numerator)))
  2729. return !Numerator->isMinSignedValue();
  2730. // The numerator *might* be MinSignedValue.
  2731. return false;
  2732. }
  2733. case Instruction::Load: {
  2734. const LoadInst *LI = cast<LoadInst>(Inst);
  2735. if (!LI->isUnordered() ||
  2736. // Speculative load may create a race that did not exist in the source.
  2737. LI->getParent()->getParent()->hasFnAttribute(Attribute::SanitizeThread))
  2738. return false;
  2739. const DataLayout &DL = LI->getModule()->getDataLayout();
  2740. return isDereferenceablePointer(LI->getPointerOperand(), DL, CtxI, DT, TLI);
  2741. }
  2742. case Instruction::Call: {
  2743. if (const IntrinsicInst *II = dyn_cast<IntrinsicInst>(Inst)) {
  2744. switch (II->getIntrinsicID()) {
  2745. // These synthetic intrinsics have no side-effects and just mark
  2746. // information about their operands.
  2747. // FIXME: There are other no-op synthetic instructions that potentially
  2748. // should be considered at least *safe* to speculate...
  2749. case Intrinsic::dbg_declare:
  2750. case Intrinsic::dbg_value:
  2751. return true;
  2752. case Intrinsic::bswap:
  2753. case Intrinsic::ctlz:
  2754. case Intrinsic::ctpop:
  2755. case Intrinsic::cttz:
  2756. case Intrinsic::objectsize:
  2757. case Intrinsic::sadd_with_overflow:
  2758. case Intrinsic::smul_with_overflow:
  2759. case Intrinsic::ssub_with_overflow:
  2760. case Intrinsic::uadd_with_overflow:
  2761. case Intrinsic::umul_with_overflow:
  2762. case Intrinsic::usub_with_overflow:
  2763. return true;
  2764. // Sqrt should be OK, since the llvm sqrt intrinsic isn't defined to set
  2765. // errno like libm sqrt would.
  2766. case Intrinsic::sqrt:
  2767. case Intrinsic::fma:
  2768. case Intrinsic::fmuladd:
  2769. case Intrinsic::fabs:
  2770. case Intrinsic::minnum:
  2771. case Intrinsic::maxnum:
  2772. return true;
  2773. // TODO: some fp intrinsics are marked as having the same error handling
  2774. // as libm. They're safe to speculate when they won't error.
  2775. // TODO: are convert_{from,to}_fp16 safe?
  2776. // TODO: can we list target-specific intrinsics here?
  2777. default: break;
  2778. }
  2779. }
  2780. return false; // The called function could have undefined behavior or
  2781. // side-effects, even if marked readnone nounwind.
  2782. }
  2783. case Instruction::VAArg:
  2784. case Instruction::Alloca:
  2785. case Instruction::Invoke:
  2786. case Instruction::PHI:
  2787. case Instruction::Store:
  2788. case Instruction::Ret:
  2789. case Instruction::Br:
  2790. case Instruction::IndirectBr:
  2791. case Instruction::Switch:
  2792. case Instruction::Unreachable:
  2793. case Instruction::Fence:
  2794. case Instruction::LandingPad:
  2795. case Instruction::AtomicRMW:
  2796. case Instruction::AtomicCmpXchg:
  2797. case Instruction::Resume:
  2798. return false; // Misc instructions which have effects
  2799. }
  2800. }
  2801. /// Return true if we know that the specified value is never null.
  2802. bool llvm::isKnownNonNull(const Value *V, const TargetLibraryInfo *TLI) {
  2803. // Alloca never returns null, malloc might.
  2804. if (isa<AllocaInst>(V)) return true;
  2805. // A byval, inalloca, or nonnull argument is never null.
  2806. if (const Argument *A = dyn_cast<Argument>(V))
  2807. return A->hasByValOrInAllocaAttr() || A->hasNonNullAttr();
  2808. // Global values are not null unless extern weak.
  2809. if (const GlobalValue *GV = dyn_cast<GlobalValue>(V))
  2810. return !GV->hasExternalWeakLinkage();
  2811. // A Load tagged w/nonnull metadata is never null.
  2812. if (const LoadInst *LI = dyn_cast<LoadInst>(V))
  2813. return LI->getMetadata(LLVMContext::MD_nonnull);
  2814. if (auto CS = ImmutableCallSite(V))
  2815. if (CS.isReturnNonNull())
  2816. return true;
  2817. // operator new never returns null.
  2818. if (isOperatorNewLikeFn(V, TLI, /*LookThroughBitCast=*/true))
  2819. return true;
  2820. return false;
  2821. }
  2822. static bool isKnownNonNullFromDominatingCondition(const Value *V,
  2823. const Instruction *CtxI,
  2824. const DominatorTree *DT) {
  2825. unsigned NumUsesExplored = 0;
  2826. for (auto U : V->users()) {
  2827. // Avoid massive lists
  2828. if (NumUsesExplored >= DomConditionsMaxUses)
  2829. break;
  2830. NumUsesExplored++;
  2831. // Consider only compare instructions uniquely controlling a branch
  2832. const ICmpInst *Cmp = dyn_cast<ICmpInst>(U);
  2833. if (!Cmp)
  2834. continue;
  2835. if (DomConditionsSingleCmpUse && !Cmp->hasOneUse())
  2836. continue;
  2837. for (auto *CmpU : Cmp->users()) {
  2838. const BranchInst *BI = dyn_cast<BranchInst>(CmpU);
  2839. if (!BI)
  2840. continue;
  2841. assert(BI->isConditional() && "uses a comparison!");
  2842. BasicBlock *NonNullSuccessor = nullptr;
  2843. CmpInst::Predicate Pred;
  2844. if (match(const_cast<ICmpInst*>(Cmp),
  2845. m_c_ICmp(Pred, m_Specific(V), m_Zero()))) {
  2846. if (Pred == ICmpInst::ICMP_EQ)
  2847. NonNullSuccessor = BI->getSuccessor(1);
  2848. else if (Pred == ICmpInst::ICMP_NE)
  2849. NonNullSuccessor = BI->getSuccessor(0);
  2850. }
  2851. if (NonNullSuccessor) {
  2852. BasicBlockEdge Edge(BI->getParent(), NonNullSuccessor);
  2853. if (Edge.isSingleEdge() && DT->dominates(Edge, CtxI->getParent()))
  2854. return true;
  2855. }
  2856. }
  2857. }
  2858. return false;
  2859. }
  2860. bool llvm::isKnownNonNullAt(const Value *V, const Instruction *CtxI,
  2861. const DominatorTree *DT, const TargetLibraryInfo *TLI) {
  2862. if (isKnownNonNull(V, TLI))
  2863. return true;
  2864. return CtxI ? ::isKnownNonNullFromDominatingCondition(V, CtxI, DT) : false;
  2865. }
  2866. OverflowResult llvm::computeOverflowForUnsignedMul(Value *LHS, Value *RHS,
  2867. const DataLayout &DL,
  2868. AssumptionCache *AC,
  2869. const Instruction *CxtI,
  2870. const DominatorTree *DT) {
  2871. // Multiplying n * m significant bits yields a result of n + m significant
  2872. // bits. If the total number of significant bits does not exceed the
  2873. // result bit width (minus 1), there is no overflow.
  2874. // This means if we have enough leading zero bits in the operands
  2875. // we can guarantee that the result does not overflow.
  2876. // Ref: "Hacker's Delight" by Henry Warren
  2877. unsigned BitWidth = LHS->getType()->getScalarSizeInBits();
  2878. APInt LHSKnownZero(BitWidth, 0);
  2879. APInt LHSKnownOne(BitWidth, 0);
  2880. APInt RHSKnownZero(BitWidth, 0);
  2881. APInt RHSKnownOne(BitWidth, 0);
  2882. computeKnownBits(LHS, LHSKnownZero, LHSKnownOne, DL, /*Depth=*/0, AC, CxtI,
  2883. DT);
  2884. computeKnownBits(RHS, RHSKnownZero, RHSKnownOne, DL, /*Depth=*/0, AC, CxtI,
  2885. DT);
  2886. // Note that underestimating the number of zero bits gives a more
  2887. // conservative answer.
  2888. unsigned ZeroBits = LHSKnownZero.countLeadingOnes() +
  2889. RHSKnownZero.countLeadingOnes();
  2890. // First handle the easy case: if we have enough zero bits there's
  2891. // definitely no overflow.
  2892. if (ZeroBits >= BitWidth)
  2893. return OverflowResult::NeverOverflows;
  2894. // Get the largest possible values for each operand.
  2895. APInt LHSMax = ~LHSKnownZero;
  2896. APInt RHSMax = ~RHSKnownZero;
  2897. // We know the multiply operation doesn't overflow if the maximum values for
  2898. // each operand will not overflow after we multiply them together.
  2899. bool MaxOverflow;
  2900. LHSMax.umul_ov(RHSMax, MaxOverflow);
  2901. if (!MaxOverflow)
  2902. return OverflowResult::NeverOverflows;
  2903. // We know it always overflows if multiplying the smallest possible values for
  2904. // the operands also results in overflow.
  2905. bool MinOverflow;
  2906. LHSKnownOne.umul_ov(RHSKnownOne, MinOverflow);
  2907. if (MinOverflow)
  2908. return OverflowResult::AlwaysOverflows;
  2909. return OverflowResult::MayOverflow;
  2910. }
  2911. OverflowResult llvm::computeOverflowForUnsignedAdd(Value *LHS, Value *RHS,
  2912. const DataLayout &DL,
  2913. AssumptionCache *AC,
  2914. const Instruction *CxtI,
  2915. const DominatorTree *DT) {
  2916. bool LHSKnownNonNegative, LHSKnownNegative;
  2917. ComputeSignBit(LHS, LHSKnownNonNegative, LHSKnownNegative, DL, /*Depth=*/0,
  2918. AC, CxtI, DT);
  2919. if (LHSKnownNonNegative || LHSKnownNegative) {
  2920. bool RHSKnownNonNegative, RHSKnownNegative;
  2921. ComputeSignBit(RHS, RHSKnownNonNegative, RHSKnownNegative, DL, /*Depth=*/0,
  2922. AC, CxtI, DT);
  2923. if (LHSKnownNegative && RHSKnownNegative) {
  2924. // The sign bit is set in both cases: this MUST overflow.
  2925. // Create a simple add instruction, and insert it into the struct.
  2926. return OverflowResult::AlwaysOverflows;
  2927. }
  2928. if (LHSKnownNonNegative && RHSKnownNonNegative) {
  2929. // The sign bit is clear in both cases: this CANNOT overflow.
  2930. // Create a simple add instruction, and insert it into the struct.
  2931. return OverflowResult::NeverOverflows;
  2932. }
  2933. }
  2934. return OverflowResult::MayOverflow;
  2935. }
  2936. static SelectPatternFlavor matchSelectPattern(ICmpInst::Predicate Pred,
  2937. Value *CmpLHS, Value *CmpRHS,
  2938. Value *TrueVal, Value *FalseVal,
  2939. Value *&LHS, Value *&RHS) {
  2940. LHS = CmpLHS;
  2941. RHS = CmpRHS;
  2942. // (icmp X, Y) ? X : Y
  2943. if (TrueVal == CmpLHS && FalseVal == CmpRHS) {
  2944. switch (Pred) {
  2945. default: return SPF_UNKNOWN; // Equality.
  2946. case ICmpInst::ICMP_UGT:
  2947. case ICmpInst::ICMP_UGE: return SPF_UMAX;
  2948. case ICmpInst::ICMP_SGT:
  2949. case ICmpInst::ICMP_SGE: return SPF_SMAX;
  2950. case ICmpInst::ICMP_ULT:
  2951. case ICmpInst::ICMP_ULE: return SPF_UMIN;
  2952. case ICmpInst::ICMP_SLT:
  2953. case ICmpInst::ICMP_SLE: return SPF_SMIN;
  2954. }
  2955. }
  2956. // (icmp X, Y) ? Y : X
  2957. if (TrueVal == CmpRHS && FalseVal == CmpLHS) {
  2958. switch (Pred) {
  2959. default: return SPF_UNKNOWN; // Equality.
  2960. case ICmpInst::ICMP_UGT:
  2961. case ICmpInst::ICMP_UGE: return SPF_UMIN;
  2962. case ICmpInst::ICMP_SGT:
  2963. case ICmpInst::ICMP_SGE: return SPF_SMIN;
  2964. case ICmpInst::ICMP_ULT:
  2965. case ICmpInst::ICMP_ULE: return SPF_UMAX;
  2966. case ICmpInst::ICMP_SLT:
  2967. case ICmpInst::ICMP_SLE: return SPF_SMAX;
  2968. }
  2969. }
  2970. if (ConstantInt *C1 = dyn_cast<ConstantInt>(CmpRHS)) {
  2971. if ((CmpLHS == TrueVal && match(FalseVal, m_Neg(m_Specific(CmpLHS)))) ||
  2972. (CmpLHS == FalseVal && match(TrueVal, m_Neg(m_Specific(CmpLHS))))) {
  2973. // ABS(X) ==> (X >s 0) ? X : -X and (X >s -1) ? X : -X
  2974. // NABS(X) ==> (X >s 0) ? -X : X and (X >s -1) ? -X : X
  2975. if (Pred == ICmpInst::ICMP_SGT && (C1->isZero() || C1->isMinusOne())) {
  2976. return (CmpLHS == TrueVal) ? SPF_ABS : SPF_NABS;
  2977. }
  2978. // ABS(X) ==> (X <s 0) ? -X : X and (X <s 1) ? -X : X
  2979. // NABS(X) ==> (X <s 0) ? X : -X and (X <s 1) ? X : -X
  2980. if (Pred == ICmpInst::ICMP_SLT && (C1->isZero() || C1->isOne())) {
  2981. return (CmpLHS == FalseVal) ? SPF_ABS : SPF_NABS;
  2982. }
  2983. }
  2984. // Y >s C ? ~Y : ~C == ~Y <s ~C ? ~Y : ~C = SMIN(~Y, ~C)
  2985. if (const auto *C2 = dyn_cast<ConstantInt>(FalseVal)) {
  2986. if (C1->getType() == C2->getType() && ~C1->getValue() == C2->getValue() &&
  2987. (match(TrueVal, m_Not(m_Specific(CmpLHS))) ||
  2988. match(CmpLHS, m_Not(m_Specific(TrueVal))))) {
  2989. LHS = TrueVal;
  2990. RHS = FalseVal;
  2991. return SPF_SMIN;
  2992. }
  2993. }
  2994. }
  2995. // TODO: (X > 4) ? X : 5 --> (X >= 5) ? X : 5 --> MAX(X, 5)
  2996. return SPF_UNKNOWN;
  2997. }
  2998. static Constant *lookThroughCast(ICmpInst *CmpI, Value *V1, Value *V2,
  2999. Instruction::CastOps *CastOp) {
  3000. CastInst *CI = dyn_cast<CastInst>(V1);
  3001. Constant *C = dyn_cast<Constant>(V2);
  3002. if (!CI || !C)
  3003. return nullptr;
  3004. *CastOp = CI->getOpcode();
  3005. if (isa<SExtInst>(CI) && CmpI->isSigned()) {
  3006. Constant *T = ConstantExpr::getTrunc(C, CI->getSrcTy());
  3007. // This is only valid if the truncated value can be sign-extended
  3008. // back to the original value.
  3009. if (ConstantExpr::getSExt(T, C->getType()) == C)
  3010. return T;
  3011. return nullptr;
  3012. }
  3013. if (isa<ZExtInst>(CI) && CmpI->isUnsigned())
  3014. return ConstantExpr::getTrunc(C, CI->getSrcTy());
  3015. if (isa<TruncInst>(CI))
  3016. return ConstantExpr::getIntegerCast(C, CI->getSrcTy(), CmpI->isSigned());
  3017. return nullptr;
  3018. }
  3019. SelectPatternFlavor llvm::matchSelectPattern(Value *V,
  3020. Value *&LHS, Value *&RHS,
  3021. Instruction::CastOps *CastOp) {
  3022. SelectInst *SI = dyn_cast<SelectInst>(V);
  3023. if (!SI) return SPF_UNKNOWN;
  3024. ICmpInst *CmpI = dyn_cast<ICmpInst>(SI->getCondition());
  3025. if (!CmpI) return SPF_UNKNOWN;
  3026. ICmpInst::Predicate Pred = CmpI->getPredicate();
  3027. Value *CmpLHS = CmpI->getOperand(0);
  3028. Value *CmpRHS = CmpI->getOperand(1);
  3029. Value *TrueVal = SI->getTrueValue();
  3030. Value *FalseVal = SI->getFalseValue();
  3031. // Bail out early.
  3032. if (CmpI->isEquality())
  3033. return SPF_UNKNOWN;
  3034. // Deal with type mismatches.
  3035. if (CastOp && CmpLHS->getType() != TrueVal->getType()) {
  3036. if (Constant *C = lookThroughCast(CmpI, TrueVal, FalseVal, CastOp))
  3037. return ::matchSelectPattern(Pred, CmpLHS, CmpRHS,
  3038. cast<CastInst>(TrueVal)->getOperand(0), C,
  3039. LHS, RHS);
  3040. if (Constant *C = lookThroughCast(CmpI, FalseVal, TrueVal, CastOp))
  3041. return ::matchSelectPattern(Pred, CmpLHS, CmpRHS,
  3042. C, cast<CastInst>(FalseVal)->getOperand(0),
  3043. LHS, RHS);
  3044. }
  3045. return ::matchSelectPattern(Pred, CmpLHS, CmpRHS, TrueVal, FalseVal,
  3046. LHS, RHS);
  3047. }