InstCombineAddSub.cpp 67 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984
  1. //===- InstCombineAddSub.cpp ------------------------------------*- C++ -*-===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. //
  9. // This file implements the visit functions for add, fadd, sub, and fsub.
  10. //
  11. //===----------------------------------------------------------------------===//
  12. #include "InstCombineInternal.h"
  13. #include "llvm/ADT/APFloat.h"
  14. #include "llvm/ADT/APInt.h"
  15. #include "llvm/ADT/STLExtras.h"
  16. #include "llvm/ADT/SmallVector.h"
  17. #include "llvm/Analysis/InstructionSimplify.h"
  18. #include "llvm/Analysis/ValueTracking.h"
  19. #include "llvm/IR/Constant.h"
  20. #include "llvm/IR/Constants.h"
  21. #include "llvm/IR/InstrTypes.h"
  22. #include "llvm/IR/Instruction.h"
  23. #include "llvm/IR/Instructions.h"
  24. #include "llvm/IR/Operator.h"
  25. #include "llvm/IR/PatternMatch.h"
  26. #include "llvm/IR/Type.h"
  27. #include "llvm/IR/Value.h"
  28. #include "llvm/Support/AlignOf.h"
  29. #include "llvm/Support/Casting.h"
  30. #include "llvm/Support/KnownBits.h"
  31. #include <cassert>
  32. #include <utility>
  33. using namespace llvm;
  34. using namespace PatternMatch;
  35. #define DEBUG_TYPE "instcombine"
  36. namespace {
  37. /// Class representing coefficient of floating-point addend.
  38. /// This class needs to be highly efficient, which is especially true for
  39. /// the constructor. As of I write this comment, the cost of the default
  40. /// constructor is merely 4-byte-store-zero (Assuming compiler is able to
  41. /// perform write-merging).
  42. ///
  43. class FAddendCoef {
  44. public:
  45. // The constructor has to initialize a APFloat, which is unnecessary for
  46. // most addends which have coefficient either 1 or -1. So, the constructor
  47. // is expensive. In order to avoid the cost of the constructor, we should
  48. // reuse some instances whenever possible. The pre-created instances
  49. // FAddCombine::Add[0-5] embodies this idea.
  50. FAddendCoef() = default;
  51. ~FAddendCoef();
  52. // If possible, don't define operator+/operator- etc because these
  53. // operators inevitably call FAddendCoef's constructor which is not cheap.
  54. void operator=(const FAddendCoef &A);
  55. void operator+=(const FAddendCoef &A);
  56. void operator*=(const FAddendCoef &S);
  57. void set(short C) {
  58. assert(!insaneIntVal(C) && "Insane coefficient");
  59. IsFp = false; IntVal = C;
  60. }
  61. void set(const APFloat& C);
  62. void negate();
  63. bool isZero() const { return isInt() ? !IntVal : getFpVal().isZero(); }
  64. Value *getValue(Type *) const;
  65. bool isOne() const { return isInt() && IntVal == 1; }
  66. bool isTwo() const { return isInt() && IntVal == 2; }
  67. bool isMinusOne() const { return isInt() && IntVal == -1; }
  68. bool isMinusTwo() const { return isInt() && IntVal == -2; }
  69. private:
  70. bool insaneIntVal(int V) { return V > 4 || V < -4; }
  71. APFloat *getFpValPtr()
  72. { return reinterpret_cast<APFloat *>(&FpValBuf.buffer[0]); }
  73. const APFloat *getFpValPtr() const
  74. { return reinterpret_cast<const APFloat *>(&FpValBuf.buffer[0]); }
  75. const APFloat &getFpVal() const {
  76. assert(IsFp && BufHasFpVal && "Incorret state");
  77. return *getFpValPtr();
  78. }
  79. APFloat &getFpVal() {
  80. assert(IsFp && BufHasFpVal && "Incorret state");
  81. return *getFpValPtr();
  82. }
  83. bool isInt() const { return !IsFp; }
  84. // If the coefficient is represented by an integer, promote it to a
  85. // floating point.
  86. void convertToFpType(const fltSemantics &Sem);
  87. // Construct an APFloat from a signed integer.
  88. // TODO: We should get rid of this function when APFloat can be constructed
  89. // from an *SIGNED* integer.
  90. APFloat createAPFloatFromInt(const fltSemantics &Sem, int Val);
  91. bool IsFp = false;
  92. // True iff FpValBuf contains an instance of APFloat.
  93. bool BufHasFpVal = false;
  94. // The integer coefficient of an individual addend is either 1 or -1,
  95. // and we try to simplify at most 4 addends from neighboring at most
  96. // two instructions. So the range of <IntVal> falls in [-4, 4]. APInt
  97. // is overkill of this end.
  98. short IntVal = 0;
  99. AlignedCharArrayUnion<APFloat> FpValBuf;
  100. };
  101. /// FAddend is used to represent floating-point addend. An addend is
  102. /// represented as <C, V>, where the V is a symbolic value, and C is a
  103. /// constant coefficient. A constant addend is represented as <C, 0>.
  104. class FAddend {
  105. public:
  106. FAddend() = default;
  107. void operator+=(const FAddend &T) {
  108. assert((Val == T.Val) && "Symbolic-values disagree");
  109. Coeff += T.Coeff;
  110. }
  111. Value *getSymVal() const { return Val; }
  112. const FAddendCoef &getCoef() const { return Coeff; }
  113. bool isConstant() const { return Val == nullptr; }
  114. bool isZero() const { return Coeff.isZero(); }
  115. void set(short Coefficient, Value *V) {
  116. Coeff.set(Coefficient);
  117. Val = V;
  118. }
  119. void set(const APFloat &Coefficient, Value *V) {
  120. Coeff.set(Coefficient);
  121. Val = V;
  122. }
  123. void set(const ConstantFP *Coefficient, Value *V) {
  124. Coeff.set(Coefficient->getValueAPF());
  125. Val = V;
  126. }
  127. void negate() { Coeff.negate(); }
  128. /// Drill down the U-D chain one step to find the definition of V, and
  129. /// try to break the definition into one or two addends.
  130. static unsigned drillValueDownOneStep(Value* V, FAddend &A0, FAddend &A1);
  131. /// Similar to FAddend::drillDownOneStep() except that the value being
  132. /// splitted is the addend itself.
  133. unsigned drillAddendDownOneStep(FAddend &Addend0, FAddend &Addend1) const;
  134. private:
  135. void Scale(const FAddendCoef& ScaleAmt) { Coeff *= ScaleAmt; }
  136. // This addend has the value of "Coeff * Val".
  137. Value *Val = nullptr;
  138. FAddendCoef Coeff;
  139. };
  140. /// FAddCombine is the class for optimizing an unsafe fadd/fsub along
  141. /// with its neighboring at most two instructions.
  142. ///
  143. class FAddCombine {
  144. public:
  145. FAddCombine(InstCombiner::BuilderTy &B) : Builder(B) {}
  146. Value *simplify(Instruction *FAdd);
  147. private:
  148. using AddendVect = SmallVector<const FAddend *, 4>;
  149. Value *simplifyFAdd(AddendVect& V, unsigned InstrQuota);
  150. /// Convert given addend to a Value
  151. Value *createAddendVal(const FAddend &A, bool& NeedNeg);
  152. /// Return the number of instructions needed to emit the N-ary addition.
  153. unsigned calcInstrNumber(const AddendVect& Vect);
  154. Value *createFSub(Value *Opnd0, Value *Opnd1);
  155. Value *createFAdd(Value *Opnd0, Value *Opnd1);
  156. Value *createFMul(Value *Opnd0, Value *Opnd1);
  157. Value *createFNeg(Value *V);
  158. Value *createNaryFAdd(const AddendVect& Opnds, unsigned InstrQuota);
  159. void createInstPostProc(Instruction *NewInst, bool NoNumber = false);
  160. // Debugging stuff are clustered here.
  161. #ifndef NDEBUG
  162. unsigned CreateInstrNum;
  163. void initCreateInstNum() { CreateInstrNum = 0; }
  164. void incCreateInstNum() { CreateInstrNum++; }
  165. #else
  166. void initCreateInstNum() {}
  167. void incCreateInstNum() {}
  168. #endif
  169. InstCombiner::BuilderTy &Builder;
  170. Instruction *Instr = nullptr;
  171. };
  172. } // end anonymous namespace
  173. //===----------------------------------------------------------------------===//
  174. //
  175. // Implementation of
  176. // {FAddendCoef, FAddend, FAddition, FAddCombine}.
  177. //
  178. //===----------------------------------------------------------------------===//
  179. FAddendCoef::~FAddendCoef() {
  180. if (BufHasFpVal)
  181. getFpValPtr()->~APFloat();
  182. }
  183. void FAddendCoef::set(const APFloat& C) {
  184. APFloat *P = getFpValPtr();
  185. if (isInt()) {
  186. // As the buffer is meanless byte stream, we cannot call
  187. // APFloat::operator=().
  188. new(P) APFloat(C);
  189. } else
  190. *P = C;
  191. IsFp = BufHasFpVal = true;
  192. }
  193. void FAddendCoef::convertToFpType(const fltSemantics &Sem) {
  194. if (!isInt())
  195. return;
  196. APFloat *P = getFpValPtr();
  197. if (IntVal > 0)
  198. new(P) APFloat(Sem, IntVal);
  199. else {
  200. new(P) APFloat(Sem, 0 - IntVal);
  201. P->changeSign();
  202. }
  203. IsFp = BufHasFpVal = true;
  204. }
  205. APFloat FAddendCoef::createAPFloatFromInt(const fltSemantics &Sem, int Val) {
  206. if (Val >= 0)
  207. return APFloat(Sem, Val);
  208. APFloat T(Sem, 0 - Val);
  209. T.changeSign();
  210. return T;
  211. }
  212. void FAddendCoef::operator=(const FAddendCoef &That) {
  213. if (That.isInt())
  214. set(That.IntVal);
  215. else
  216. set(That.getFpVal());
  217. }
  218. void FAddendCoef::operator+=(const FAddendCoef &That) {
  219. enum APFloat::roundingMode RndMode = APFloat::rmNearestTiesToEven;
  220. if (isInt() == That.isInt()) {
  221. if (isInt())
  222. IntVal += That.IntVal;
  223. else
  224. getFpVal().add(That.getFpVal(), RndMode);
  225. return;
  226. }
  227. if (isInt()) {
  228. const APFloat &T = That.getFpVal();
  229. convertToFpType(T.getSemantics());
  230. getFpVal().add(T, RndMode);
  231. return;
  232. }
  233. APFloat &T = getFpVal();
  234. T.add(createAPFloatFromInt(T.getSemantics(), That.IntVal), RndMode);
  235. }
  236. void FAddendCoef::operator*=(const FAddendCoef &That) {
  237. if (That.isOne())
  238. return;
  239. if (That.isMinusOne()) {
  240. negate();
  241. return;
  242. }
  243. if (isInt() && That.isInt()) {
  244. int Res = IntVal * (int)That.IntVal;
  245. assert(!insaneIntVal(Res) && "Insane int value");
  246. IntVal = Res;
  247. return;
  248. }
  249. const fltSemantics &Semantic =
  250. isInt() ? That.getFpVal().getSemantics() : getFpVal().getSemantics();
  251. if (isInt())
  252. convertToFpType(Semantic);
  253. APFloat &F0 = getFpVal();
  254. if (That.isInt())
  255. F0.multiply(createAPFloatFromInt(Semantic, That.IntVal),
  256. APFloat::rmNearestTiesToEven);
  257. else
  258. F0.multiply(That.getFpVal(), APFloat::rmNearestTiesToEven);
  259. }
  260. void FAddendCoef::negate() {
  261. if (isInt())
  262. IntVal = 0 - IntVal;
  263. else
  264. getFpVal().changeSign();
  265. }
  266. Value *FAddendCoef::getValue(Type *Ty) const {
  267. return isInt() ?
  268. ConstantFP::get(Ty, float(IntVal)) :
  269. ConstantFP::get(Ty->getContext(), getFpVal());
  270. }
  271. // The definition of <Val> Addends
  272. // =========================================
  273. // A + B <1, A>, <1,B>
  274. // A - B <1, A>, <1,B>
  275. // 0 - B <-1, B>
  276. // C * A, <C, A>
  277. // A + C <1, A> <C, NULL>
  278. // 0 +/- 0 <0, NULL> (corner case)
  279. //
  280. // Legend: A and B are not constant, C is constant
  281. unsigned FAddend::drillValueDownOneStep
  282. (Value *Val, FAddend &Addend0, FAddend &Addend1) {
  283. Instruction *I = nullptr;
  284. if (!Val || !(I = dyn_cast<Instruction>(Val)))
  285. return 0;
  286. unsigned Opcode = I->getOpcode();
  287. if (Opcode == Instruction::FAdd || Opcode == Instruction::FSub) {
  288. ConstantFP *C0, *C1;
  289. Value *Opnd0 = I->getOperand(0);
  290. Value *Opnd1 = I->getOperand(1);
  291. if ((C0 = dyn_cast<ConstantFP>(Opnd0)) && C0->isZero())
  292. Opnd0 = nullptr;
  293. if ((C1 = dyn_cast<ConstantFP>(Opnd1)) && C1->isZero())
  294. Opnd1 = nullptr;
  295. if (Opnd0) {
  296. if (!C0)
  297. Addend0.set(1, Opnd0);
  298. else
  299. Addend0.set(C0, nullptr);
  300. }
  301. if (Opnd1) {
  302. FAddend &Addend = Opnd0 ? Addend1 : Addend0;
  303. if (!C1)
  304. Addend.set(1, Opnd1);
  305. else
  306. Addend.set(C1, nullptr);
  307. if (Opcode == Instruction::FSub)
  308. Addend.negate();
  309. }
  310. if (Opnd0 || Opnd1)
  311. return Opnd0 && Opnd1 ? 2 : 1;
  312. // Both operands are zero. Weird!
  313. Addend0.set(APFloat(C0->getValueAPF().getSemantics()), nullptr);
  314. return 1;
  315. }
  316. if (I->getOpcode() == Instruction::FMul) {
  317. Value *V0 = I->getOperand(0);
  318. Value *V1 = I->getOperand(1);
  319. if (ConstantFP *C = dyn_cast<ConstantFP>(V0)) {
  320. Addend0.set(C, V1);
  321. return 1;
  322. }
  323. if (ConstantFP *C = dyn_cast<ConstantFP>(V1)) {
  324. Addend0.set(C, V0);
  325. return 1;
  326. }
  327. }
  328. return 0;
  329. }
  330. // Try to break *this* addend into two addends. e.g. Suppose this addend is
  331. // <2.3, V>, and V = X + Y, by calling this function, we obtain two addends,
  332. // i.e. <2.3, X> and <2.3, Y>.
  333. unsigned FAddend::drillAddendDownOneStep
  334. (FAddend &Addend0, FAddend &Addend1) const {
  335. if (isConstant())
  336. return 0;
  337. unsigned BreakNum = FAddend::drillValueDownOneStep(Val, Addend0, Addend1);
  338. if (!BreakNum || Coeff.isOne())
  339. return BreakNum;
  340. Addend0.Scale(Coeff);
  341. if (BreakNum == 2)
  342. Addend1.Scale(Coeff);
  343. return BreakNum;
  344. }
  345. Value *FAddCombine::simplify(Instruction *I) {
  346. assert(I->hasAllowReassoc() && I->hasNoSignedZeros() &&
  347. "Expected 'reassoc'+'nsz' instruction");
  348. // Currently we are not able to handle vector type.
  349. if (I->getType()->isVectorTy())
  350. return nullptr;
  351. assert((I->getOpcode() == Instruction::FAdd ||
  352. I->getOpcode() == Instruction::FSub) && "Expect add/sub");
  353. // Save the instruction before calling other member-functions.
  354. Instr = I;
  355. FAddend Opnd0, Opnd1, Opnd0_0, Opnd0_1, Opnd1_0, Opnd1_1;
  356. unsigned OpndNum = FAddend::drillValueDownOneStep(I, Opnd0, Opnd1);
  357. // Step 1: Expand the 1st addend into Opnd0_0 and Opnd0_1.
  358. unsigned Opnd0_ExpNum = 0;
  359. unsigned Opnd1_ExpNum = 0;
  360. if (!Opnd0.isConstant())
  361. Opnd0_ExpNum = Opnd0.drillAddendDownOneStep(Opnd0_0, Opnd0_1);
  362. // Step 2: Expand the 2nd addend into Opnd1_0 and Opnd1_1.
  363. if (OpndNum == 2 && !Opnd1.isConstant())
  364. Opnd1_ExpNum = Opnd1.drillAddendDownOneStep(Opnd1_0, Opnd1_1);
  365. // Step 3: Try to optimize Opnd0_0 + Opnd0_1 + Opnd1_0 + Opnd1_1
  366. if (Opnd0_ExpNum && Opnd1_ExpNum) {
  367. AddendVect AllOpnds;
  368. AllOpnds.push_back(&Opnd0_0);
  369. AllOpnds.push_back(&Opnd1_0);
  370. if (Opnd0_ExpNum == 2)
  371. AllOpnds.push_back(&Opnd0_1);
  372. if (Opnd1_ExpNum == 2)
  373. AllOpnds.push_back(&Opnd1_1);
  374. // Compute instruction quota. We should save at least one instruction.
  375. unsigned InstQuota = 0;
  376. Value *V0 = I->getOperand(0);
  377. Value *V1 = I->getOperand(1);
  378. InstQuota = ((!isa<Constant>(V0) && V0->hasOneUse()) &&
  379. (!isa<Constant>(V1) && V1->hasOneUse())) ? 2 : 1;
  380. if (Value *R = simplifyFAdd(AllOpnds, InstQuota))
  381. return R;
  382. }
  383. if (OpndNum != 2) {
  384. // The input instruction is : "I=0.0 +/- V". If the "V" were able to be
  385. // splitted into two addends, say "V = X - Y", the instruction would have
  386. // been optimized into "I = Y - X" in the previous steps.
  387. //
  388. const FAddendCoef &CE = Opnd0.getCoef();
  389. return CE.isOne() ? Opnd0.getSymVal() : nullptr;
  390. }
  391. // step 4: Try to optimize Opnd0 + Opnd1_0 [+ Opnd1_1]
  392. if (Opnd1_ExpNum) {
  393. AddendVect AllOpnds;
  394. AllOpnds.push_back(&Opnd0);
  395. AllOpnds.push_back(&Opnd1_0);
  396. if (Opnd1_ExpNum == 2)
  397. AllOpnds.push_back(&Opnd1_1);
  398. if (Value *R = simplifyFAdd(AllOpnds, 1))
  399. return R;
  400. }
  401. // step 5: Try to optimize Opnd1 + Opnd0_0 [+ Opnd0_1]
  402. if (Opnd0_ExpNum) {
  403. AddendVect AllOpnds;
  404. AllOpnds.push_back(&Opnd1);
  405. AllOpnds.push_back(&Opnd0_0);
  406. if (Opnd0_ExpNum == 2)
  407. AllOpnds.push_back(&Opnd0_1);
  408. if (Value *R = simplifyFAdd(AllOpnds, 1))
  409. return R;
  410. }
  411. return nullptr;
  412. }
  413. Value *FAddCombine::simplifyFAdd(AddendVect& Addends, unsigned InstrQuota) {
  414. unsigned AddendNum = Addends.size();
  415. assert(AddendNum <= 4 && "Too many addends");
  416. // For saving intermediate results;
  417. unsigned NextTmpIdx = 0;
  418. FAddend TmpResult[3];
  419. // Points to the constant addend of the resulting simplified expression.
  420. // If the resulting expr has constant-addend, this constant-addend is
  421. // desirable to reside at the top of the resulting expression tree. Placing
  422. // constant close to supper-expr(s) will potentially reveal some optimization
  423. // opportunities in super-expr(s).
  424. const FAddend *ConstAdd = nullptr;
  425. // Simplified addends are placed <SimpVect>.
  426. AddendVect SimpVect;
  427. // The outer loop works on one symbolic-value at a time. Suppose the input
  428. // addends are : <a1, x>, <b1, y>, <a2, x>, <c1, z>, <b2, y>, ...
  429. // The symbolic-values will be processed in this order: x, y, z.
  430. for (unsigned SymIdx = 0; SymIdx < AddendNum; SymIdx++) {
  431. const FAddend *ThisAddend = Addends[SymIdx];
  432. if (!ThisAddend) {
  433. // This addend was processed before.
  434. continue;
  435. }
  436. Value *Val = ThisAddend->getSymVal();
  437. unsigned StartIdx = SimpVect.size();
  438. SimpVect.push_back(ThisAddend);
  439. // The inner loop collects addends sharing same symbolic-value, and these
  440. // addends will be later on folded into a single addend. Following above
  441. // example, if the symbolic value "y" is being processed, the inner loop
  442. // will collect two addends "<b1,y>" and "<b2,Y>". These two addends will
  443. // be later on folded into "<b1+b2, y>".
  444. for (unsigned SameSymIdx = SymIdx + 1;
  445. SameSymIdx < AddendNum; SameSymIdx++) {
  446. const FAddend *T = Addends[SameSymIdx];
  447. if (T && T->getSymVal() == Val) {
  448. // Set null such that next iteration of the outer loop will not process
  449. // this addend again.
  450. Addends[SameSymIdx] = nullptr;
  451. SimpVect.push_back(T);
  452. }
  453. }
  454. // If multiple addends share same symbolic value, fold them together.
  455. if (StartIdx + 1 != SimpVect.size()) {
  456. FAddend &R = TmpResult[NextTmpIdx ++];
  457. R = *SimpVect[StartIdx];
  458. for (unsigned Idx = StartIdx + 1; Idx < SimpVect.size(); Idx++)
  459. R += *SimpVect[Idx];
  460. // Pop all addends being folded and push the resulting folded addend.
  461. SimpVect.resize(StartIdx);
  462. if (Val) {
  463. if (!R.isZero()) {
  464. SimpVect.push_back(&R);
  465. }
  466. } else {
  467. // Don't push constant addend at this time. It will be the last element
  468. // of <SimpVect>.
  469. ConstAdd = &R;
  470. }
  471. }
  472. }
  473. assert((NextTmpIdx <= array_lengthof(TmpResult) + 1) &&
  474. "out-of-bound access");
  475. if (ConstAdd)
  476. SimpVect.push_back(ConstAdd);
  477. Value *Result;
  478. if (!SimpVect.empty())
  479. Result = createNaryFAdd(SimpVect, InstrQuota);
  480. else {
  481. // The addition is folded to 0.0.
  482. Result = ConstantFP::get(Instr->getType(), 0.0);
  483. }
  484. return Result;
  485. }
  486. Value *FAddCombine::createNaryFAdd
  487. (const AddendVect &Opnds, unsigned InstrQuota) {
  488. assert(!Opnds.empty() && "Expect at least one addend");
  489. // Step 1: Check if the # of instructions needed exceeds the quota.
  490. unsigned InstrNeeded = calcInstrNumber(Opnds);
  491. if (InstrNeeded > InstrQuota)
  492. return nullptr;
  493. initCreateInstNum();
  494. // step 2: Emit the N-ary addition.
  495. // Note that at most three instructions are involved in Fadd-InstCombine: the
  496. // addition in question, and at most two neighboring instructions.
  497. // The resulting optimized addition should have at least one less instruction
  498. // than the original addition expression tree. This implies that the resulting
  499. // N-ary addition has at most two instructions, and we don't need to worry
  500. // about tree-height when constructing the N-ary addition.
  501. Value *LastVal = nullptr;
  502. bool LastValNeedNeg = false;
  503. // Iterate the addends, creating fadd/fsub using adjacent two addends.
  504. for (const FAddend *Opnd : Opnds) {
  505. bool NeedNeg;
  506. Value *V = createAddendVal(*Opnd, NeedNeg);
  507. if (!LastVal) {
  508. LastVal = V;
  509. LastValNeedNeg = NeedNeg;
  510. continue;
  511. }
  512. if (LastValNeedNeg == NeedNeg) {
  513. LastVal = createFAdd(LastVal, V);
  514. continue;
  515. }
  516. if (LastValNeedNeg)
  517. LastVal = createFSub(V, LastVal);
  518. else
  519. LastVal = createFSub(LastVal, V);
  520. LastValNeedNeg = false;
  521. }
  522. if (LastValNeedNeg) {
  523. LastVal = createFNeg(LastVal);
  524. }
  525. #ifndef NDEBUG
  526. assert(CreateInstrNum == InstrNeeded &&
  527. "Inconsistent in instruction numbers");
  528. #endif
  529. return LastVal;
  530. }
  531. Value *FAddCombine::createFSub(Value *Opnd0, Value *Opnd1) {
  532. Value *V = Builder.CreateFSub(Opnd0, Opnd1);
  533. if (Instruction *I = dyn_cast<Instruction>(V))
  534. createInstPostProc(I);
  535. return V;
  536. }
  537. Value *FAddCombine::createFNeg(Value *V) {
  538. Value *Zero = cast<Value>(ConstantFP::getZeroValueForNegation(V->getType()));
  539. Value *NewV = createFSub(Zero, V);
  540. if (Instruction *I = dyn_cast<Instruction>(NewV))
  541. createInstPostProc(I, true); // fneg's don't receive instruction numbers.
  542. return NewV;
  543. }
  544. Value *FAddCombine::createFAdd(Value *Opnd0, Value *Opnd1) {
  545. Value *V = Builder.CreateFAdd(Opnd0, Opnd1);
  546. if (Instruction *I = dyn_cast<Instruction>(V))
  547. createInstPostProc(I);
  548. return V;
  549. }
  550. Value *FAddCombine::createFMul(Value *Opnd0, Value *Opnd1) {
  551. Value *V = Builder.CreateFMul(Opnd0, Opnd1);
  552. if (Instruction *I = dyn_cast<Instruction>(V))
  553. createInstPostProc(I);
  554. return V;
  555. }
  556. void FAddCombine::createInstPostProc(Instruction *NewInstr, bool NoNumber) {
  557. NewInstr->setDebugLoc(Instr->getDebugLoc());
  558. // Keep track of the number of instruction created.
  559. if (!NoNumber)
  560. incCreateInstNum();
  561. // Propagate fast-math flags
  562. NewInstr->setFastMathFlags(Instr->getFastMathFlags());
  563. }
  564. // Return the number of instruction needed to emit the N-ary addition.
  565. // NOTE: Keep this function in sync with createAddendVal().
  566. unsigned FAddCombine::calcInstrNumber(const AddendVect &Opnds) {
  567. unsigned OpndNum = Opnds.size();
  568. unsigned InstrNeeded = OpndNum - 1;
  569. // The number of addends in the form of "(-1)*x".
  570. unsigned NegOpndNum = 0;
  571. // Adjust the number of instructions needed to emit the N-ary add.
  572. for (const FAddend *Opnd : Opnds) {
  573. if (Opnd->isConstant())
  574. continue;
  575. // The constant check above is really for a few special constant
  576. // coefficients.
  577. if (isa<UndefValue>(Opnd->getSymVal()))
  578. continue;
  579. const FAddendCoef &CE = Opnd->getCoef();
  580. if (CE.isMinusOne() || CE.isMinusTwo())
  581. NegOpndNum++;
  582. // Let the addend be "c * x". If "c == +/-1", the value of the addend
  583. // is immediately available; otherwise, it needs exactly one instruction
  584. // to evaluate the value.
  585. if (!CE.isMinusOne() && !CE.isOne())
  586. InstrNeeded++;
  587. }
  588. if (NegOpndNum == OpndNum)
  589. InstrNeeded++;
  590. return InstrNeeded;
  591. }
  592. // Input Addend Value NeedNeg(output)
  593. // ================================================================
  594. // Constant C C false
  595. // <+/-1, V> V coefficient is -1
  596. // <2/-2, V> "fadd V, V" coefficient is -2
  597. // <C, V> "fmul V, C" false
  598. //
  599. // NOTE: Keep this function in sync with FAddCombine::calcInstrNumber.
  600. Value *FAddCombine::createAddendVal(const FAddend &Opnd, bool &NeedNeg) {
  601. const FAddendCoef &Coeff = Opnd.getCoef();
  602. if (Opnd.isConstant()) {
  603. NeedNeg = false;
  604. return Coeff.getValue(Instr->getType());
  605. }
  606. Value *OpndVal = Opnd.getSymVal();
  607. if (Coeff.isMinusOne() || Coeff.isOne()) {
  608. NeedNeg = Coeff.isMinusOne();
  609. return OpndVal;
  610. }
  611. if (Coeff.isTwo() || Coeff.isMinusTwo()) {
  612. NeedNeg = Coeff.isMinusTwo();
  613. return createFAdd(OpndVal, OpndVal);
  614. }
  615. NeedNeg = false;
  616. return createFMul(OpndVal, Coeff.getValue(Instr->getType()));
  617. }
  618. // Checks if any operand is negative and we can convert add to sub.
  619. // This function checks for following negative patterns
  620. // ADD(XOR(OR(Z, NOT(C)), C)), 1) == NEG(AND(Z, C))
  621. // ADD(XOR(AND(Z, C), C), 1) == NEG(OR(Z, ~C))
  622. // XOR(AND(Z, C), (C + 1)) == NEG(OR(Z, ~C)) if C is even
  623. static Value *checkForNegativeOperand(BinaryOperator &I,
  624. InstCombiner::BuilderTy &Builder) {
  625. Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
  626. // This function creates 2 instructions to replace ADD, we need at least one
  627. // of LHS or RHS to have one use to ensure benefit in transform.
  628. if (!LHS->hasOneUse() && !RHS->hasOneUse())
  629. return nullptr;
  630. Value *X = nullptr, *Y = nullptr, *Z = nullptr;
  631. const APInt *C1 = nullptr, *C2 = nullptr;
  632. // if ONE is on other side, swap
  633. if (match(RHS, m_Add(m_Value(X), m_One())))
  634. std::swap(LHS, RHS);
  635. if (match(LHS, m_Add(m_Value(X), m_One()))) {
  636. // if XOR on other side, swap
  637. if (match(RHS, m_Xor(m_Value(Y), m_APInt(C1))))
  638. std::swap(X, RHS);
  639. if (match(X, m_Xor(m_Value(Y), m_APInt(C1)))) {
  640. // X = XOR(Y, C1), Y = OR(Z, C2), C2 = NOT(C1) ==> X == NOT(AND(Z, C1))
  641. // ADD(ADD(X, 1), RHS) == ADD(X, ADD(RHS, 1)) == SUB(RHS, AND(Z, C1))
  642. if (match(Y, m_Or(m_Value(Z), m_APInt(C2))) && (*C2 == ~(*C1))) {
  643. Value *NewAnd = Builder.CreateAnd(Z, *C1);
  644. return Builder.CreateSub(RHS, NewAnd, "sub");
  645. } else if (match(Y, m_And(m_Value(Z), m_APInt(C2))) && (*C1 == *C2)) {
  646. // X = XOR(Y, C1), Y = AND(Z, C2), C2 == C1 ==> X == NOT(OR(Z, ~C1))
  647. // ADD(ADD(X, 1), RHS) == ADD(X, ADD(RHS, 1)) == SUB(RHS, OR(Z, ~C1))
  648. Value *NewOr = Builder.CreateOr(Z, ~(*C1));
  649. return Builder.CreateSub(RHS, NewOr, "sub");
  650. }
  651. }
  652. }
  653. // Restore LHS and RHS
  654. LHS = I.getOperand(0);
  655. RHS = I.getOperand(1);
  656. // if XOR is on other side, swap
  657. if (match(RHS, m_Xor(m_Value(Y), m_APInt(C1))))
  658. std::swap(LHS, RHS);
  659. // C2 is ODD
  660. // LHS = XOR(Y, C1), Y = AND(Z, C2), C1 == (C2 + 1) => LHS == NEG(OR(Z, ~C2))
  661. // ADD(LHS, RHS) == SUB(RHS, OR(Z, ~C2))
  662. if (match(LHS, m_Xor(m_Value(Y), m_APInt(C1))))
  663. if (C1->countTrailingZeros() == 0)
  664. if (match(Y, m_And(m_Value(Z), m_APInt(C2))) && *C1 == (*C2 + 1)) {
  665. Value *NewOr = Builder.CreateOr(Z, ~(*C2));
  666. return Builder.CreateSub(RHS, NewOr, "sub");
  667. }
  668. return nullptr;
  669. }
  670. /// Wrapping flags may allow combining constants separated by an extend.
  671. static Instruction *foldNoWrapAdd(BinaryOperator &Add,
  672. InstCombiner::BuilderTy &Builder) {
  673. Value *Op0 = Add.getOperand(0), *Op1 = Add.getOperand(1);
  674. Type *Ty = Add.getType();
  675. Constant *Op1C;
  676. if (!match(Op1, m_Constant(Op1C)))
  677. return nullptr;
  678. // Try this match first because it results in an add in the narrow type.
  679. // (zext (X +nuw C2)) + C1 --> zext (X + (C2 + trunc(C1)))
  680. Value *X;
  681. const APInt *C1, *C2;
  682. if (match(Op1, m_APInt(C1)) &&
  683. match(Op0, m_OneUse(m_ZExt(m_NUWAdd(m_Value(X), m_APInt(C2))))) &&
  684. C1->isNegative() && C1->sge(-C2->sext(C1->getBitWidth()))) {
  685. Constant *NewC =
  686. ConstantInt::get(X->getType(), *C2 + C1->trunc(C2->getBitWidth()));
  687. return new ZExtInst(Builder.CreateNUWAdd(X, NewC), Ty);
  688. }
  689. // More general combining of constants in the wide type.
  690. // (sext (X +nsw NarrowC)) + C --> (sext X) + (sext(NarrowC) + C)
  691. Constant *NarrowC;
  692. if (match(Op0, m_OneUse(m_SExt(m_NSWAdd(m_Value(X), m_Constant(NarrowC)))))) {
  693. Constant *WideC = ConstantExpr::getSExt(NarrowC, Ty);
  694. Constant *NewC = ConstantExpr::getAdd(WideC, Op1C);
  695. Value *WideX = Builder.CreateSExt(X, Ty);
  696. return BinaryOperator::CreateAdd(WideX, NewC);
  697. }
  698. // (zext (X +nuw NarrowC)) + C --> (zext X) + (zext(NarrowC) + C)
  699. if (match(Op0, m_OneUse(m_ZExt(m_NUWAdd(m_Value(X), m_Constant(NarrowC)))))) {
  700. Constant *WideC = ConstantExpr::getZExt(NarrowC, Ty);
  701. Constant *NewC = ConstantExpr::getAdd(WideC, Op1C);
  702. Value *WideX = Builder.CreateZExt(X, Ty);
  703. return BinaryOperator::CreateAdd(WideX, NewC);
  704. }
  705. return nullptr;
  706. }
  707. Instruction *InstCombiner::foldAddWithConstant(BinaryOperator &Add) {
  708. Value *Op0 = Add.getOperand(0), *Op1 = Add.getOperand(1);
  709. Constant *Op1C;
  710. if (!match(Op1, m_Constant(Op1C)))
  711. return nullptr;
  712. if (Instruction *NV = foldBinOpIntoSelectOrPhi(Add))
  713. return NV;
  714. Value *X;
  715. Constant *Op00C;
  716. // add (sub C1, X), C2 --> sub (add C1, C2), X
  717. if (match(Op0, m_Sub(m_Constant(Op00C), m_Value(X))))
  718. return BinaryOperator::CreateSub(ConstantExpr::getAdd(Op00C, Op1C), X);
  719. Value *Y;
  720. // add (sub X, Y), -1 --> add (not Y), X
  721. if (match(Op0, m_OneUse(m_Sub(m_Value(X), m_Value(Y)))) &&
  722. match(Op1, m_AllOnes()))
  723. return BinaryOperator::CreateAdd(Builder.CreateNot(Y), X);
  724. // zext(bool) + C -> bool ? C + 1 : C
  725. if (match(Op0, m_ZExt(m_Value(X))) &&
  726. X->getType()->getScalarSizeInBits() == 1)
  727. return SelectInst::Create(X, AddOne(Op1C), Op1);
  728. // ~X + C --> (C-1) - X
  729. if (match(Op0, m_Not(m_Value(X))))
  730. return BinaryOperator::CreateSub(SubOne(Op1C), X);
  731. const APInt *C;
  732. if (!match(Op1, m_APInt(C)))
  733. return nullptr;
  734. // (X | C2) + C --> (X | C2) ^ C2 iff (C2 == -C)
  735. const APInt *C2;
  736. if (match(Op0, m_Or(m_Value(), m_APInt(C2))) && *C2 == -*C)
  737. return BinaryOperator::CreateXor(Op0, ConstantInt::get(Add.getType(), *C2));
  738. if (C->isSignMask()) {
  739. // If wrapping is not allowed, then the addition must set the sign bit:
  740. // X + (signmask) --> X | signmask
  741. if (Add.hasNoSignedWrap() || Add.hasNoUnsignedWrap())
  742. return BinaryOperator::CreateOr(Op0, Op1);
  743. // If wrapping is allowed, then the addition flips the sign bit of LHS:
  744. // X + (signmask) --> X ^ signmask
  745. return BinaryOperator::CreateXor(Op0, Op1);
  746. }
  747. // Is this add the last step in a convoluted sext?
  748. // add(zext(xor i16 X, -32768), -32768) --> sext X
  749. Type *Ty = Add.getType();
  750. if (match(Op0, m_ZExt(m_Xor(m_Value(X), m_APInt(C2)))) &&
  751. C2->isMinSignedValue() && C2->sext(Ty->getScalarSizeInBits()) == *C)
  752. return CastInst::Create(Instruction::SExt, X, Ty);
  753. if (C->isOneValue() && Op0->hasOneUse()) {
  754. // add (sext i1 X), 1 --> zext (not X)
  755. // TODO: The smallest IR representation is (select X, 0, 1), and that would
  756. // not require the one-use check. But we need to remove a transform in
  757. // visitSelect and make sure that IR value tracking for select is equal or
  758. // better than for these ops.
  759. if (match(Op0, m_SExt(m_Value(X))) &&
  760. X->getType()->getScalarSizeInBits() == 1)
  761. return new ZExtInst(Builder.CreateNot(X), Ty);
  762. // Shifts and add used to flip and mask off the low bit:
  763. // add (ashr (shl i32 X, 31), 31), 1 --> and (not X), 1
  764. const APInt *C3;
  765. if (match(Op0, m_AShr(m_Shl(m_Value(X), m_APInt(C2)), m_APInt(C3))) &&
  766. C2 == C3 && *C2 == Ty->getScalarSizeInBits() - 1) {
  767. Value *NotX = Builder.CreateNot(X);
  768. return BinaryOperator::CreateAnd(NotX, ConstantInt::get(Ty, 1));
  769. }
  770. }
  771. return nullptr;
  772. }
  773. // Matches multiplication expression Op * C where C is a constant. Returns the
  774. // constant value in C and the other operand in Op. Returns true if such a
  775. // match is found.
  776. static bool MatchMul(Value *E, Value *&Op, APInt &C) {
  777. const APInt *AI;
  778. if (match(E, m_Mul(m_Value(Op), m_APInt(AI)))) {
  779. C = *AI;
  780. return true;
  781. }
  782. if (match(E, m_Shl(m_Value(Op), m_APInt(AI)))) {
  783. C = APInt(AI->getBitWidth(), 1);
  784. C <<= *AI;
  785. return true;
  786. }
  787. return false;
  788. }
  789. // Matches remainder expression Op % C where C is a constant. Returns the
  790. // constant value in C and the other operand in Op. Returns the signedness of
  791. // the remainder operation in IsSigned. Returns true if such a match is
  792. // found.
  793. static bool MatchRem(Value *E, Value *&Op, APInt &C, bool &IsSigned) {
  794. const APInt *AI;
  795. IsSigned = false;
  796. if (match(E, m_SRem(m_Value(Op), m_APInt(AI)))) {
  797. IsSigned = true;
  798. C = *AI;
  799. return true;
  800. }
  801. if (match(E, m_URem(m_Value(Op), m_APInt(AI)))) {
  802. C = *AI;
  803. return true;
  804. }
  805. if (match(E, m_And(m_Value(Op), m_APInt(AI))) && (*AI + 1).isPowerOf2()) {
  806. C = *AI + 1;
  807. return true;
  808. }
  809. return false;
  810. }
  811. // Matches division expression Op / C with the given signedness as indicated
  812. // by IsSigned, where C is a constant. Returns the constant value in C and the
  813. // other operand in Op. Returns true if such a match is found.
  814. static bool MatchDiv(Value *E, Value *&Op, APInt &C, bool IsSigned) {
  815. const APInt *AI;
  816. if (IsSigned && match(E, m_SDiv(m_Value(Op), m_APInt(AI)))) {
  817. C = *AI;
  818. return true;
  819. }
  820. if (!IsSigned) {
  821. if (match(E, m_UDiv(m_Value(Op), m_APInt(AI)))) {
  822. C = *AI;
  823. return true;
  824. }
  825. if (match(E, m_LShr(m_Value(Op), m_APInt(AI)))) {
  826. C = APInt(AI->getBitWidth(), 1);
  827. C <<= *AI;
  828. return true;
  829. }
  830. }
  831. return false;
  832. }
  833. // Returns whether C0 * C1 with the given signedness overflows.
  834. static bool MulWillOverflow(APInt &C0, APInt &C1, bool IsSigned) {
  835. bool overflow;
  836. if (IsSigned)
  837. (void)C0.smul_ov(C1, overflow);
  838. else
  839. (void)C0.umul_ov(C1, overflow);
  840. return overflow;
  841. }
  842. // Simplifies X % C0 + (( X / C0 ) % C1) * C0 to X % (C0 * C1), where (C0 * C1)
  843. // does not overflow.
  844. Value *InstCombiner::SimplifyAddWithRemainder(BinaryOperator &I) {
  845. Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
  846. Value *X, *MulOpV;
  847. APInt C0, MulOpC;
  848. bool IsSigned;
  849. // Match I = X % C0 + MulOpV * C0
  850. if (((MatchRem(LHS, X, C0, IsSigned) && MatchMul(RHS, MulOpV, MulOpC)) ||
  851. (MatchRem(RHS, X, C0, IsSigned) && MatchMul(LHS, MulOpV, MulOpC))) &&
  852. C0 == MulOpC) {
  853. Value *RemOpV;
  854. APInt C1;
  855. bool Rem2IsSigned;
  856. // Match MulOpC = RemOpV % C1
  857. if (MatchRem(MulOpV, RemOpV, C1, Rem2IsSigned) &&
  858. IsSigned == Rem2IsSigned) {
  859. Value *DivOpV;
  860. APInt DivOpC;
  861. // Match RemOpV = X / C0
  862. if (MatchDiv(RemOpV, DivOpV, DivOpC, IsSigned) && X == DivOpV &&
  863. C0 == DivOpC && !MulWillOverflow(C0, C1, IsSigned)) {
  864. Value *NewDivisor =
  865. ConstantInt::get(X->getType()->getContext(), C0 * C1);
  866. return IsSigned ? Builder.CreateSRem(X, NewDivisor, "srem")
  867. : Builder.CreateURem(X, NewDivisor, "urem");
  868. }
  869. }
  870. }
  871. return nullptr;
  872. }
  873. /// Fold
  874. /// (1 << NBits) - 1
  875. /// Into:
  876. /// ~(-(1 << NBits))
  877. /// Because a 'not' is better for bit-tracking analysis and other transforms
  878. /// than an 'add'. The new shl is always nsw, and is nuw if old `and` was.
  879. static Instruction *canonicalizeLowbitMask(BinaryOperator &I,
  880. InstCombiner::BuilderTy &Builder) {
  881. Value *NBits;
  882. if (!match(&I, m_Add(m_OneUse(m_Shl(m_One(), m_Value(NBits))), m_AllOnes())))
  883. return nullptr;
  884. Constant *MinusOne = Constant::getAllOnesValue(NBits->getType());
  885. Value *NotMask = Builder.CreateShl(MinusOne, NBits, "notmask");
  886. // Be wary of constant folding.
  887. if (auto *BOp = dyn_cast<BinaryOperator>(NotMask)) {
  888. // Always NSW. But NUW propagates from `add`.
  889. BOp->setHasNoSignedWrap();
  890. BOp->setHasNoUnsignedWrap(I.hasNoUnsignedWrap());
  891. }
  892. return BinaryOperator::CreateNot(NotMask, I.getName());
  893. }
  894. static Instruction *foldToUnsignedSaturatedAdd(BinaryOperator &I) {
  895. assert(I.getOpcode() == Instruction::Add && "Expecting add instruction");
  896. Type *Ty = I.getType();
  897. auto getUAddSat = [&]() {
  898. return Intrinsic::getDeclaration(I.getModule(), Intrinsic::uadd_sat, Ty);
  899. };
  900. // add (umin X, ~Y), Y --> uaddsat X, Y
  901. Value *X, *Y;
  902. if (match(&I, m_c_Add(m_c_UMin(m_Value(X), m_Not(m_Value(Y))),
  903. m_Deferred(Y))))
  904. return CallInst::Create(getUAddSat(), { X, Y });
  905. // add (umin X, ~C), C --> uaddsat X, C
  906. const APInt *C, *NotC;
  907. if (match(&I, m_Add(m_UMin(m_Value(X), m_APInt(NotC)), m_APInt(C))) &&
  908. *C == ~*NotC)
  909. return CallInst::Create(getUAddSat(), { X, ConstantInt::get(Ty, *C) });
  910. return nullptr;
  911. }
  912. Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
  913. if (Value *V = SimplifyAddInst(I.getOperand(0), I.getOperand(1),
  914. I.hasNoSignedWrap(), I.hasNoUnsignedWrap(),
  915. SQ.getWithInstruction(&I)))
  916. return replaceInstUsesWith(I, V);
  917. if (SimplifyAssociativeOrCommutative(I))
  918. return &I;
  919. if (Instruction *X = foldVectorBinop(I))
  920. return X;
  921. // (A*B)+(A*C) -> A*(B+C) etc
  922. if (Value *V = SimplifyUsingDistributiveLaws(I))
  923. return replaceInstUsesWith(I, V);
  924. if (Instruction *X = foldAddWithConstant(I))
  925. return X;
  926. if (Instruction *X = foldNoWrapAdd(I, Builder))
  927. return X;
  928. // FIXME: This should be moved into the above helper function to allow these
  929. // transforms for general constant or constant splat vectors.
  930. Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
  931. Type *Ty = I.getType();
  932. if (ConstantInt *CI = dyn_cast<ConstantInt>(RHS)) {
  933. Value *XorLHS = nullptr; ConstantInt *XorRHS = nullptr;
  934. if (match(LHS, m_Xor(m_Value(XorLHS), m_ConstantInt(XorRHS)))) {
  935. unsigned TySizeBits = Ty->getScalarSizeInBits();
  936. const APInt &RHSVal = CI->getValue();
  937. unsigned ExtendAmt = 0;
  938. // If we have ADD(XOR(AND(X, 0xFF), 0x80), 0xF..F80), it's a sext.
  939. // If we have ADD(XOR(AND(X, 0xFF), 0xF..F80), 0x80), it's a sext.
  940. if (XorRHS->getValue() == -RHSVal) {
  941. if (RHSVal.isPowerOf2())
  942. ExtendAmt = TySizeBits - RHSVal.logBase2() - 1;
  943. else if (XorRHS->getValue().isPowerOf2())
  944. ExtendAmt = TySizeBits - XorRHS->getValue().logBase2() - 1;
  945. }
  946. if (ExtendAmt) {
  947. APInt Mask = APInt::getHighBitsSet(TySizeBits, ExtendAmt);
  948. if (!MaskedValueIsZero(XorLHS, Mask, 0, &I))
  949. ExtendAmt = 0;
  950. }
  951. if (ExtendAmt) {
  952. Constant *ShAmt = ConstantInt::get(Ty, ExtendAmt);
  953. Value *NewShl = Builder.CreateShl(XorLHS, ShAmt, "sext");
  954. return BinaryOperator::CreateAShr(NewShl, ShAmt);
  955. }
  956. // If this is a xor that was canonicalized from a sub, turn it back into
  957. // a sub and fuse this add with it.
  958. if (LHS->hasOneUse() && (XorRHS->getValue()+1).isPowerOf2()) {
  959. KnownBits LHSKnown = computeKnownBits(XorLHS, 0, &I);
  960. if ((XorRHS->getValue() | LHSKnown.Zero).isAllOnesValue())
  961. return BinaryOperator::CreateSub(ConstantExpr::getAdd(XorRHS, CI),
  962. XorLHS);
  963. }
  964. // (X + signmask) + C could have gotten canonicalized to (X^signmask) + C,
  965. // transform them into (X + (signmask ^ C))
  966. if (XorRHS->getValue().isSignMask())
  967. return BinaryOperator::CreateAdd(XorLHS,
  968. ConstantExpr::getXor(XorRHS, CI));
  969. }
  970. }
  971. if (Ty->isIntOrIntVectorTy(1))
  972. return BinaryOperator::CreateXor(LHS, RHS);
  973. // X + X --> X << 1
  974. if (LHS == RHS) {
  975. auto *Shl = BinaryOperator::CreateShl(LHS, ConstantInt::get(Ty, 1));
  976. Shl->setHasNoSignedWrap(I.hasNoSignedWrap());
  977. Shl->setHasNoUnsignedWrap(I.hasNoUnsignedWrap());
  978. return Shl;
  979. }
  980. Value *A, *B;
  981. if (match(LHS, m_Neg(m_Value(A)))) {
  982. // -A + -B --> -(A + B)
  983. if (match(RHS, m_Neg(m_Value(B))))
  984. return BinaryOperator::CreateNeg(Builder.CreateAdd(A, B));
  985. // -A + B --> B - A
  986. return BinaryOperator::CreateSub(RHS, A);
  987. }
  988. // Canonicalize sext to zext for better value tracking potential.
  989. // add A, sext(B) --> sub A, zext(B)
  990. if (match(&I, m_c_Add(m_Value(A), m_OneUse(m_SExt(m_Value(B))))) &&
  991. B->getType()->isIntOrIntVectorTy(1))
  992. return BinaryOperator::CreateSub(A, Builder.CreateZExt(B, Ty));
  993. // A + -B --> A - B
  994. if (match(RHS, m_Neg(m_Value(B))))
  995. return BinaryOperator::CreateSub(LHS, B);
  996. if (Value *V = checkForNegativeOperand(I, Builder))
  997. return replaceInstUsesWith(I, V);
  998. // (A + 1) + ~B --> A - B
  999. // ~B + (A + 1) --> A - B
  1000. // (~B + A) + 1 --> A - B
  1001. // (A + ~B) + 1 --> A - B
  1002. if (match(&I, m_c_BinOp(m_Add(m_Value(A), m_One()), m_Not(m_Value(B)))) ||
  1003. match(&I, m_BinOp(m_c_Add(m_Not(m_Value(B)), m_Value(A)), m_One())))
  1004. return BinaryOperator::CreateSub(A, B);
  1005. // X % C0 + (( X / C0 ) % C1) * C0 => X % (C0 * C1)
  1006. if (Value *V = SimplifyAddWithRemainder(I)) return replaceInstUsesWith(I, V);
  1007. // A+B --> A|B iff A and B have no bits set in common.
  1008. if (haveNoCommonBitsSet(LHS, RHS, DL, &AC, &I, &DT))
  1009. return BinaryOperator::CreateOr(LHS, RHS);
  1010. // FIXME: We already did a check for ConstantInt RHS above this.
  1011. // FIXME: Is this pattern covered by another fold? No regression tests fail on
  1012. // removal.
  1013. if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
  1014. // (X & FF00) + xx00 -> (X+xx00) & FF00
  1015. Value *X;
  1016. ConstantInt *C2;
  1017. if (LHS->hasOneUse() &&
  1018. match(LHS, m_And(m_Value(X), m_ConstantInt(C2))) &&
  1019. CRHS->getValue() == (CRHS->getValue() & C2->getValue())) {
  1020. // See if all bits from the first bit set in the Add RHS up are included
  1021. // in the mask. First, get the rightmost bit.
  1022. const APInt &AddRHSV = CRHS->getValue();
  1023. // Form a mask of all bits from the lowest bit added through the top.
  1024. APInt AddRHSHighBits(~((AddRHSV & -AddRHSV)-1));
  1025. // See if the and mask includes all of these bits.
  1026. APInt AddRHSHighBitsAnd(AddRHSHighBits & C2->getValue());
  1027. if (AddRHSHighBits == AddRHSHighBitsAnd) {
  1028. // Okay, the xform is safe. Insert the new add pronto.
  1029. Value *NewAdd = Builder.CreateAdd(X, CRHS, LHS->getName());
  1030. return BinaryOperator::CreateAnd(NewAdd, C2);
  1031. }
  1032. }
  1033. }
  1034. // add (select X 0 (sub n A)) A --> select X A n
  1035. {
  1036. SelectInst *SI = dyn_cast<SelectInst>(LHS);
  1037. Value *A = RHS;
  1038. if (!SI) {
  1039. SI = dyn_cast<SelectInst>(RHS);
  1040. A = LHS;
  1041. }
  1042. if (SI && SI->hasOneUse()) {
  1043. Value *TV = SI->getTrueValue();
  1044. Value *FV = SI->getFalseValue();
  1045. Value *N;
  1046. // Can we fold the add into the argument of the select?
  1047. // We check both true and false select arguments for a matching subtract.
  1048. if (match(FV, m_Zero()) && match(TV, m_Sub(m_Value(N), m_Specific(A))))
  1049. // Fold the add into the true select value.
  1050. return SelectInst::Create(SI->getCondition(), N, A);
  1051. if (match(TV, m_Zero()) && match(FV, m_Sub(m_Value(N), m_Specific(A))))
  1052. // Fold the add into the false select value.
  1053. return SelectInst::Create(SI->getCondition(), A, N);
  1054. }
  1055. }
  1056. if (Instruction *Ext = narrowMathIfNoOverflow(I))
  1057. return Ext;
  1058. // (add (xor A, B) (and A, B)) --> (or A, B)
  1059. // (add (and A, B) (xor A, B)) --> (or A, B)
  1060. if (match(&I, m_c_BinOp(m_Xor(m_Value(A), m_Value(B)),
  1061. m_c_And(m_Deferred(A), m_Deferred(B)))))
  1062. return BinaryOperator::CreateOr(A, B);
  1063. // (add (or A, B) (and A, B)) --> (add A, B)
  1064. // (add (and A, B) (or A, B)) --> (add A, B)
  1065. if (match(&I, m_c_BinOp(m_Or(m_Value(A), m_Value(B)),
  1066. m_c_And(m_Deferred(A), m_Deferred(B))))) {
  1067. I.setOperand(0, A);
  1068. I.setOperand(1, B);
  1069. return &I;
  1070. }
  1071. // TODO(jingyue): Consider willNotOverflowSignedAdd and
  1072. // willNotOverflowUnsignedAdd to reduce the number of invocations of
  1073. // computeKnownBits.
  1074. bool Changed = false;
  1075. if (!I.hasNoSignedWrap() && willNotOverflowSignedAdd(LHS, RHS, I)) {
  1076. Changed = true;
  1077. I.setHasNoSignedWrap(true);
  1078. }
  1079. if (!I.hasNoUnsignedWrap() && willNotOverflowUnsignedAdd(LHS, RHS, I)) {
  1080. Changed = true;
  1081. I.setHasNoUnsignedWrap(true);
  1082. }
  1083. if (Instruction *V = canonicalizeLowbitMask(I, Builder))
  1084. return V;
  1085. if (Instruction *SatAdd = foldToUnsignedSaturatedAdd(I))
  1086. return SatAdd;
  1087. return Changed ? &I : nullptr;
  1088. }
  1089. /// Factor a common operand out of fadd/fsub of fmul/fdiv.
  1090. static Instruction *factorizeFAddFSub(BinaryOperator &I,
  1091. InstCombiner::BuilderTy &Builder) {
  1092. assert((I.getOpcode() == Instruction::FAdd ||
  1093. I.getOpcode() == Instruction::FSub) && "Expecting fadd/fsub");
  1094. assert(I.hasAllowReassoc() && I.hasNoSignedZeros() &&
  1095. "FP factorization requires FMF");
  1096. Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
  1097. Value *X, *Y, *Z;
  1098. bool IsFMul;
  1099. if ((match(Op0, m_OneUse(m_FMul(m_Value(X), m_Value(Z)))) &&
  1100. match(Op1, m_OneUse(m_c_FMul(m_Value(Y), m_Specific(Z))))) ||
  1101. (match(Op0, m_OneUse(m_FMul(m_Value(Z), m_Value(X)))) &&
  1102. match(Op1, m_OneUse(m_c_FMul(m_Value(Y), m_Specific(Z))))))
  1103. IsFMul = true;
  1104. else if (match(Op0, m_OneUse(m_FDiv(m_Value(X), m_Value(Z)))) &&
  1105. match(Op1, m_OneUse(m_FDiv(m_Value(Y), m_Specific(Z)))))
  1106. IsFMul = false;
  1107. else
  1108. return nullptr;
  1109. // (X * Z) + (Y * Z) --> (X + Y) * Z
  1110. // (X * Z) - (Y * Z) --> (X - Y) * Z
  1111. // (X / Z) + (Y / Z) --> (X + Y) / Z
  1112. // (X / Z) - (Y / Z) --> (X - Y) / Z
  1113. bool IsFAdd = I.getOpcode() == Instruction::FAdd;
  1114. Value *XY = IsFAdd ? Builder.CreateFAddFMF(X, Y, &I)
  1115. : Builder.CreateFSubFMF(X, Y, &I);
  1116. // Bail out if we just created a denormal constant.
  1117. // TODO: This is copied from a previous implementation. Is it necessary?
  1118. const APFloat *C;
  1119. if (match(XY, m_APFloat(C)) && !C->isNormal())
  1120. return nullptr;
  1121. return IsFMul ? BinaryOperator::CreateFMulFMF(XY, Z, &I)
  1122. : BinaryOperator::CreateFDivFMF(XY, Z, &I);
  1123. }
  1124. Instruction *InstCombiner::visitFAdd(BinaryOperator &I) {
  1125. if (Value *V = SimplifyFAddInst(I.getOperand(0), I.getOperand(1),
  1126. I.getFastMathFlags(),
  1127. SQ.getWithInstruction(&I)))
  1128. return replaceInstUsesWith(I, V);
  1129. if (SimplifyAssociativeOrCommutative(I))
  1130. return &I;
  1131. if (Instruction *X = foldVectorBinop(I))
  1132. return X;
  1133. if (Instruction *FoldedFAdd = foldBinOpIntoSelectOrPhi(I))
  1134. return FoldedFAdd;
  1135. Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
  1136. Value *X;
  1137. // (-X) + Y --> Y - X
  1138. if (match(LHS, m_FNeg(m_Value(X))))
  1139. return BinaryOperator::CreateFSubFMF(RHS, X, &I);
  1140. // Y + (-X) --> Y - X
  1141. if (match(RHS, m_FNeg(m_Value(X))))
  1142. return BinaryOperator::CreateFSubFMF(LHS, X, &I);
  1143. // Check for (fadd double (sitofp x), y), see if we can merge this into an
  1144. // integer add followed by a promotion.
  1145. if (SIToFPInst *LHSConv = dyn_cast<SIToFPInst>(LHS)) {
  1146. Value *LHSIntVal = LHSConv->getOperand(0);
  1147. Type *FPType = LHSConv->getType();
  1148. // TODO: This check is overly conservative. In many cases known bits
  1149. // analysis can tell us that the result of the addition has less significant
  1150. // bits than the integer type can hold.
  1151. auto IsValidPromotion = [](Type *FTy, Type *ITy) {
  1152. Type *FScalarTy = FTy->getScalarType();
  1153. Type *IScalarTy = ITy->getScalarType();
  1154. // Do we have enough bits in the significand to represent the result of
  1155. // the integer addition?
  1156. unsigned MaxRepresentableBits =
  1157. APFloat::semanticsPrecision(FScalarTy->getFltSemantics());
  1158. return IScalarTy->getIntegerBitWidth() <= MaxRepresentableBits;
  1159. };
  1160. // (fadd double (sitofp x), fpcst) --> (sitofp (add int x, intcst))
  1161. // ... if the constant fits in the integer value. This is useful for things
  1162. // like (double)(x & 1234) + 4.0 -> (double)((X & 1234)+4) which no longer
  1163. // requires a constant pool load, and generally allows the add to be better
  1164. // instcombined.
  1165. if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS))
  1166. if (IsValidPromotion(FPType, LHSIntVal->getType())) {
  1167. Constant *CI =
  1168. ConstantExpr::getFPToSI(CFP, LHSIntVal->getType());
  1169. if (LHSConv->hasOneUse() &&
  1170. ConstantExpr::getSIToFP(CI, I.getType()) == CFP &&
  1171. willNotOverflowSignedAdd(LHSIntVal, CI, I)) {
  1172. // Insert the new integer add.
  1173. Value *NewAdd = Builder.CreateNSWAdd(LHSIntVal, CI, "addconv");
  1174. return new SIToFPInst(NewAdd, I.getType());
  1175. }
  1176. }
  1177. // (fadd double (sitofp x), (sitofp y)) --> (sitofp (add int x, y))
  1178. if (SIToFPInst *RHSConv = dyn_cast<SIToFPInst>(RHS)) {
  1179. Value *RHSIntVal = RHSConv->getOperand(0);
  1180. // It's enough to check LHS types only because we require int types to
  1181. // be the same for this transform.
  1182. if (IsValidPromotion(FPType, LHSIntVal->getType())) {
  1183. // Only do this if x/y have the same type, if at least one of them has a
  1184. // single use (so we don't increase the number of int->fp conversions),
  1185. // and if the integer add will not overflow.
  1186. if (LHSIntVal->getType() == RHSIntVal->getType() &&
  1187. (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
  1188. willNotOverflowSignedAdd(LHSIntVal, RHSIntVal, I)) {
  1189. // Insert the new integer add.
  1190. Value *NewAdd = Builder.CreateNSWAdd(LHSIntVal, RHSIntVal, "addconv");
  1191. return new SIToFPInst(NewAdd, I.getType());
  1192. }
  1193. }
  1194. }
  1195. }
  1196. // Handle specials cases for FAdd with selects feeding the operation
  1197. if (Value *V = SimplifySelectsFeedingBinaryOp(I, LHS, RHS))
  1198. return replaceInstUsesWith(I, V);
  1199. if (I.hasAllowReassoc() && I.hasNoSignedZeros()) {
  1200. if (Instruction *F = factorizeFAddFSub(I, Builder))
  1201. return F;
  1202. if (Value *V = FAddCombine(Builder).simplify(&I))
  1203. return replaceInstUsesWith(I, V);
  1204. }
  1205. return nullptr;
  1206. }
  1207. /// Optimize pointer differences into the same array into a size. Consider:
  1208. /// &A[10] - &A[0]: we should compile this to "10". LHS/RHS are the pointer
  1209. /// operands to the ptrtoint instructions for the LHS/RHS of the subtract.
  1210. Value *InstCombiner::OptimizePointerDifference(Value *LHS, Value *RHS,
  1211. Type *Ty) {
  1212. // If LHS is a gep based on RHS or RHS is a gep based on LHS, we can optimize
  1213. // this.
  1214. bool Swapped = false;
  1215. GEPOperator *GEP1 = nullptr, *GEP2 = nullptr;
  1216. // For now we require one side to be the base pointer "A" or a constant
  1217. // GEP derived from it.
  1218. if (GEPOperator *LHSGEP = dyn_cast<GEPOperator>(LHS)) {
  1219. // (gep X, ...) - X
  1220. if (LHSGEP->getOperand(0) == RHS) {
  1221. GEP1 = LHSGEP;
  1222. Swapped = false;
  1223. } else if (GEPOperator *RHSGEP = dyn_cast<GEPOperator>(RHS)) {
  1224. // (gep X, ...) - (gep X, ...)
  1225. if (LHSGEP->getOperand(0)->stripPointerCasts() ==
  1226. RHSGEP->getOperand(0)->stripPointerCasts()) {
  1227. GEP2 = RHSGEP;
  1228. GEP1 = LHSGEP;
  1229. Swapped = false;
  1230. }
  1231. }
  1232. }
  1233. if (GEPOperator *RHSGEP = dyn_cast<GEPOperator>(RHS)) {
  1234. // X - (gep X, ...)
  1235. if (RHSGEP->getOperand(0) == LHS) {
  1236. GEP1 = RHSGEP;
  1237. Swapped = true;
  1238. } else if (GEPOperator *LHSGEP = dyn_cast<GEPOperator>(LHS)) {
  1239. // (gep X, ...) - (gep X, ...)
  1240. if (RHSGEP->getOperand(0)->stripPointerCasts() ==
  1241. LHSGEP->getOperand(0)->stripPointerCasts()) {
  1242. GEP2 = LHSGEP;
  1243. GEP1 = RHSGEP;
  1244. Swapped = true;
  1245. }
  1246. }
  1247. }
  1248. if (!GEP1)
  1249. // No GEP found.
  1250. return nullptr;
  1251. if (GEP2) {
  1252. // (gep X, ...) - (gep X, ...)
  1253. //
  1254. // Avoid duplicating the arithmetic if there are more than one non-constant
  1255. // indices between the two GEPs and either GEP has a non-constant index and
  1256. // multiple users. If zero non-constant index, the result is a constant and
  1257. // there is no duplication. If one non-constant index, the result is an add
  1258. // or sub with a constant, which is no larger than the original code, and
  1259. // there's no duplicated arithmetic, even if either GEP has multiple
  1260. // users. If more than one non-constant indices combined, as long as the GEP
  1261. // with at least one non-constant index doesn't have multiple users, there
  1262. // is no duplication.
  1263. unsigned NumNonConstantIndices1 = GEP1->countNonConstantIndices();
  1264. unsigned NumNonConstantIndices2 = GEP2->countNonConstantIndices();
  1265. if (NumNonConstantIndices1 + NumNonConstantIndices2 > 1 &&
  1266. ((NumNonConstantIndices1 > 0 && !GEP1->hasOneUse()) ||
  1267. (NumNonConstantIndices2 > 0 && !GEP2->hasOneUse()))) {
  1268. return nullptr;
  1269. }
  1270. }
  1271. // Emit the offset of the GEP and an intptr_t.
  1272. Value *Result = EmitGEPOffset(GEP1);
  1273. // If we had a constant expression GEP on the other side offsetting the
  1274. // pointer, subtract it from the offset we have.
  1275. if (GEP2) {
  1276. Value *Offset = EmitGEPOffset(GEP2);
  1277. Result = Builder.CreateSub(Result, Offset);
  1278. }
  1279. // If we have p - gep(p, ...) then we have to negate the result.
  1280. if (Swapped)
  1281. Result = Builder.CreateNeg(Result, "diff.neg");
  1282. return Builder.CreateIntCast(Result, Ty, true);
  1283. }
  1284. Instruction *InstCombiner::visitSub(BinaryOperator &I) {
  1285. if (Value *V = SimplifySubInst(I.getOperand(0), I.getOperand(1),
  1286. I.hasNoSignedWrap(), I.hasNoUnsignedWrap(),
  1287. SQ.getWithInstruction(&I)))
  1288. return replaceInstUsesWith(I, V);
  1289. if (Instruction *X = foldVectorBinop(I))
  1290. return X;
  1291. // (A*B)-(A*C) -> A*(B-C) etc
  1292. if (Value *V = SimplifyUsingDistributiveLaws(I))
  1293. return replaceInstUsesWith(I, V);
  1294. // If this is a 'B = x-(-A)', change to B = x+A.
  1295. Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
  1296. if (Value *V = dyn_castNegVal(Op1)) {
  1297. BinaryOperator *Res = BinaryOperator::CreateAdd(Op0, V);
  1298. if (const auto *BO = dyn_cast<BinaryOperator>(Op1)) {
  1299. assert(BO->getOpcode() == Instruction::Sub &&
  1300. "Expected a subtraction operator!");
  1301. if (BO->hasNoSignedWrap() && I.hasNoSignedWrap())
  1302. Res->setHasNoSignedWrap(true);
  1303. } else {
  1304. if (cast<Constant>(Op1)->isNotMinSignedValue() && I.hasNoSignedWrap())
  1305. Res->setHasNoSignedWrap(true);
  1306. }
  1307. return Res;
  1308. }
  1309. if (I.getType()->isIntOrIntVectorTy(1))
  1310. return BinaryOperator::CreateXor(Op0, Op1);
  1311. // Replace (-1 - A) with (~A).
  1312. if (match(Op0, m_AllOnes()))
  1313. return BinaryOperator::CreateNot(Op1);
  1314. // (~X) - (~Y) --> Y - X
  1315. Value *X, *Y;
  1316. if (match(Op0, m_Not(m_Value(X))) && match(Op1, m_Not(m_Value(Y))))
  1317. return BinaryOperator::CreateSub(Y, X);
  1318. // (X + -1) - Y --> ~Y + X
  1319. if (match(Op0, m_OneUse(m_Add(m_Value(X), m_AllOnes()))))
  1320. return BinaryOperator::CreateAdd(Builder.CreateNot(Op1), X);
  1321. // Y - (X + 1) --> ~X + Y
  1322. if (match(Op1, m_OneUse(m_Add(m_Value(X), m_One()))))
  1323. return BinaryOperator::CreateAdd(Builder.CreateNot(X), Op0);
  1324. // Y - ~X --> (X + 1) + Y
  1325. if (match(Op1, m_OneUse(m_Not(m_Value(X))))) {
  1326. return BinaryOperator::CreateAdd(
  1327. Builder.CreateAdd(Op0, ConstantInt::get(I.getType(), 1)), X);
  1328. }
  1329. if (Constant *C = dyn_cast<Constant>(Op0)) {
  1330. bool IsNegate = match(C, m_ZeroInt());
  1331. Value *X;
  1332. if (match(Op1, m_ZExt(m_Value(X))) && X->getType()->isIntOrIntVectorTy(1)) {
  1333. // 0 - (zext bool) --> sext bool
  1334. // C - (zext bool) --> bool ? C - 1 : C
  1335. if (IsNegate)
  1336. return CastInst::CreateSExtOrBitCast(X, I.getType());
  1337. return SelectInst::Create(X, SubOne(C), C);
  1338. }
  1339. if (match(Op1, m_SExt(m_Value(X))) && X->getType()->isIntOrIntVectorTy(1)) {
  1340. // 0 - (sext bool) --> zext bool
  1341. // C - (sext bool) --> bool ? C + 1 : C
  1342. if (IsNegate)
  1343. return CastInst::CreateZExtOrBitCast(X, I.getType());
  1344. return SelectInst::Create(X, AddOne(C), C);
  1345. }
  1346. // C - ~X == X + (1+C)
  1347. if (match(Op1, m_Not(m_Value(X))))
  1348. return BinaryOperator::CreateAdd(X, AddOne(C));
  1349. // Try to fold constant sub into select arguments.
  1350. if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
  1351. if (Instruction *R = FoldOpIntoSelect(I, SI))
  1352. return R;
  1353. // Try to fold constant sub into PHI values.
  1354. if (PHINode *PN = dyn_cast<PHINode>(Op1))
  1355. if (Instruction *R = foldOpIntoPhi(I, PN))
  1356. return R;
  1357. Constant *C2;
  1358. // C-(C2-X) --> X+(C-C2)
  1359. if (match(Op1, m_Sub(m_Constant(C2), m_Value(X))))
  1360. return BinaryOperator::CreateAdd(X, ConstantExpr::getSub(C, C2));
  1361. // C-(X+C2) --> (C-C2)-X
  1362. if (match(Op1, m_Add(m_Value(X), m_Constant(C2))))
  1363. return BinaryOperator::CreateSub(ConstantExpr::getSub(C, C2), X);
  1364. }
  1365. const APInt *Op0C;
  1366. if (match(Op0, m_APInt(Op0C))) {
  1367. unsigned BitWidth = I.getType()->getScalarSizeInBits();
  1368. // -(X >>u 31) -> (X >>s 31)
  1369. // -(X >>s 31) -> (X >>u 31)
  1370. if (Op0C->isNullValue()) {
  1371. Value *X;
  1372. const APInt *ShAmt;
  1373. if (match(Op1, m_LShr(m_Value(X), m_APInt(ShAmt))) &&
  1374. *ShAmt == BitWidth - 1) {
  1375. Value *ShAmtOp = cast<Instruction>(Op1)->getOperand(1);
  1376. return BinaryOperator::CreateAShr(X, ShAmtOp);
  1377. }
  1378. if (match(Op1, m_AShr(m_Value(X), m_APInt(ShAmt))) &&
  1379. *ShAmt == BitWidth - 1) {
  1380. Value *ShAmtOp = cast<Instruction>(Op1)->getOperand(1);
  1381. return BinaryOperator::CreateLShr(X, ShAmtOp);
  1382. }
  1383. if (Op1->hasOneUse()) {
  1384. Value *LHS, *RHS;
  1385. SelectPatternFlavor SPF = matchSelectPattern(Op1, LHS, RHS).Flavor;
  1386. if (SPF == SPF_ABS || SPF == SPF_NABS) {
  1387. // This is a negate of an ABS/NABS pattern. Just swap the operands
  1388. // of the select.
  1389. SelectInst *SI = cast<SelectInst>(Op1);
  1390. Value *TrueVal = SI->getTrueValue();
  1391. Value *FalseVal = SI->getFalseValue();
  1392. SI->setTrueValue(FalseVal);
  1393. SI->setFalseValue(TrueVal);
  1394. // Don't swap prof metadata, we didn't change the branch behavior.
  1395. return replaceInstUsesWith(I, SI);
  1396. }
  1397. }
  1398. }
  1399. // Turn this into a xor if LHS is 2^n-1 and the remaining bits are known
  1400. // zero.
  1401. if (Op0C->isMask()) {
  1402. KnownBits RHSKnown = computeKnownBits(Op1, 0, &I);
  1403. if ((*Op0C | RHSKnown.Zero).isAllOnesValue())
  1404. return BinaryOperator::CreateXor(Op1, Op0);
  1405. }
  1406. }
  1407. {
  1408. Value *Y;
  1409. // X-(X+Y) == -Y X-(Y+X) == -Y
  1410. if (match(Op1, m_c_Add(m_Specific(Op0), m_Value(Y))))
  1411. return BinaryOperator::CreateNeg(Y);
  1412. // (X-Y)-X == -Y
  1413. if (match(Op0, m_Sub(m_Specific(Op1), m_Value(Y))))
  1414. return BinaryOperator::CreateNeg(Y);
  1415. }
  1416. // (sub (or A, B), (xor A, B)) --> (and A, B)
  1417. {
  1418. Value *A, *B;
  1419. if (match(Op1, m_Xor(m_Value(A), m_Value(B))) &&
  1420. match(Op0, m_c_Or(m_Specific(A), m_Specific(B))))
  1421. return BinaryOperator::CreateAnd(A, B);
  1422. }
  1423. {
  1424. Value *Y;
  1425. // ((X | Y) - X) --> (~X & Y)
  1426. if (match(Op0, m_OneUse(m_c_Or(m_Value(Y), m_Specific(Op1)))))
  1427. return BinaryOperator::CreateAnd(
  1428. Y, Builder.CreateNot(Op1, Op1->getName() + ".not"));
  1429. }
  1430. if (Op1->hasOneUse()) {
  1431. Value *X = nullptr, *Y = nullptr, *Z = nullptr;
  1432. Constant *C = nullptr;
  1433. // (X - (Y - Z)) --> (X + (Z - Y)).
  1434. if (match(Op1, m_Sub(m_Value(Y), m_Value(Z))))
  1435. return BinaryOperator::CreateAdd(Op0,
  1436. Builder.CreateSub(Z, Y, Op1->getName()));
  1437. // (X - (X & Y)) --> (X & ~Y)
  1438. if (match(Op1, m_c_And(m_Value(Y), m_Specific(Op0))))
  1439. return BinaryOperator::CreateAnd(Op0,
  1440. Builder.CreateNot(Y, Y->getName() + ".not"));
  1441. // 0 - (X sdiv C) -> (X sdiv -C) provided the negation doesn't overflow.
  1442. // TODO: This could be extended to match arbitrary vector constants.
  1443. const APInt *DivC;
  1444. if (match(Op0, m_Zero()) && match(Op1, m_SDiv(m_Value(X), m_APInt(DivC))) &&
  1445. !DivC->isMinSignedValue() && *DivC != 1) {
  1446. Constant *NegDivC = ConstantInt::get(I.getType(), -(*DivC));
  1447. Instruction *BO = BinaryOperator::CreateSDiv(X, NegDivC);
  1448. BO->setIsExact(cast<BinaryOperator>(Op1)->isExact());
  1449. return BO;
  1450. }
  1451. // 0 - (X << Y) -> (-X << Y) when X is freely negatable.
  1452. if (match(Op1, m_Shl(m_Value(X), m_Value(Y))) && match(Op0, m_Zero()))
  1453. if (Value *XNeg = dyn_castNegVal(X))
  1454. return BinaryOperator::CreateShl(XNeg, Y);
  1455. // Subtracting -1/0 is the same as adding 1/0:
  1456. // sub [nsw] Op0, sext(bool Y) -> add [nsw] Op0, zext(bool Y)
  1457. // 'nuw' is dropped in favor of the canonical form.
  1458. if (match(Op1, m_SExt(m_Value(Y))) &&
  1459. Y->getType()->getScalarSizeInBits() == 1) {
  1460. Value *Zext = Builder.CreateZExt(Y, I.getType());
  1461. BinaryOperator *Add = BinaryOperator::CreateAdd(Op0, Zext);
  1462. Add->setHasNoSignedWrap(I.hasNoSignedWrap());
  1463. return Add;
  1464. }
  1465. // X - A*-B -> X + A*B
  1466. // X - -A*B -> X + A*B
  1467. Value *A, *B;
  1468. if (match(Op1, m_c_Mul(m_Value(A), m_Neg(m_Value(B)))))
  1469. return BinaryOperator::CreateAdd(Op0, Builder.CreateMul(A, B));
  1470. // X - A*C -> X + A*-C
  1471. // No need to handle commuted multiply because multiply handling will
  1472. // ensure constant will be move to the right hand side.
  1473. if (match(Op1, m_Mul(m_Value(A), m_Constant(C))) && !isa<ConstantExpr>(C)) {
  1474. Value *NewMul = Builder.CreateMul(A, ConstantExpr::getNeg(C));
  1475. return BinaryOperator::CreateAdd(Op0, NewMul);
  1476. }
  1477. }
  1478. {
  1479. // ~A - Min/Max(~A, O) -> Max/Min(A, ~O) - A
  1480. // ~A - Min/Max(O, ~A) -> Max/Min(A, ~O) - A
  1481. // Min/Max(~A, O) - ~A -> A - Max/Min(A, ~O)
  1482. // Min/Max(O, ~A) - ~A -> A - Max/Min(A, ~O)
  1483. // So long as O here is freely invertible, this will be neutral or a win.
  1484. Value *LHS, *RHS, *A;
  1485. Value *NotA = Op0, *MinMax = Op1;
  1486. SelectPatternFlavor SPF = matchSelectPattern(MinMax, LHS, RHS).Flavor;
  1487. if (!SelectPatternResult::isMinOrMax(SPF)) {
  1488. NotA = Op1;
  1489. MinMax = Op0;
  1490. SPF = matchSelectPattern(MinMax, LHS, RHS).Flavor;
  1491. }
  1492. if (SelectPatternResult::isMinOrMax(SPF) &&
  1493. match(NotA, m_Not(m_Value(A))) && (NotA == LHS || NotA == RHS)) {
  1494. if (NotA == LHS)
  1495. std::swap(LHS, RHS);
  1496. // LHS is now O above and expected to have at least 2 uses (the min/max)
  1497. // NotA is epected to have 2 uses from the min/max and 1 from the sub.
  1498. if (IsFreeToInvert(LHS, !LHS->hasNUsesOrMore(3)) &&
  1499. !NotA->hasNUsesOrMore(4)) {
  1500. // Note: We don't generate the inverse max/min, just create the not of
  1501. // it and let other folds do the rest.
  1502. Value *Not = Builder.CreateNot(MinMax);
  1503. if (NotA == Op0)
  1504. return BinaryOperator::CreateSub(Not, A);
  1505. else
  1506. return BinaryOperator::CreateSub(A, Not);
  1507. }
  1508. }
  1509. }
  1510. // Optimize pointer differences into the same array into a size. Consider:
  1511. // &A[10] - &A[0]: we should compile this to "10".
  1512. Value *LHSOp, *RHSOp;
  1513. if (match(Op0, m_PtrToInt(m_Value(LHSOp))) &&
  1514. match(Op1, m_PtrToInt(m_Value(RHSOp))))
  1515. if (Value *Res = OptimizePointerDifference(LHSOp, RHSOp, I.getType()))
  1516. return replaceInstUsesWith(I, Res);
  1517. // trunc(p)-trunc(q) -> trunc(p-q)
  1518. if (match(Op0, m_Trunc(m_PtrToInt(m_Value(LHSOp)))) &&
  1519. match(Op1, m_Trunc(m_PtrToInt(m_Value(RHSOp)))))
  1520. if (Value *Res = OptimizePointerDifference(LHSOp, RHSOp, I.getType()))
  1521. return replaceInstUsesWith(I, Res);
  1522. // Canonicalize a shifty way to code absolute value to the common pattern.
  1523. // There are 2 potential commuted variants.
  1524. // We're relying on the fact that we only do this transform when the shift has
  1525. // exactly 2 uses and the xor has exactly 1 use (otherwise, we might increase
  1526. // instructions).
  1527. Value *A;
  1528. const APInt *ShAmt;
  1529. Type *Ty = I.getType();
  1530. if (match(Op1, m_AShr(m_Value(A), m_APInt(ShAmt))) &&
  1531. Op1->hasNUses(2) && *ShAmt == Ty->getScalarSizeInBits() - 1 &&
  1532. match(Op0, m_OneUse(m_c_Xor(m_Specific(A), m_Specific(Op1))))) {
  1533. // B = ashr i32 A, 31 ; smear the sign bit
  1534. // sub (xor A, B), B ; flip bits if negative and subtract -1 (add 1)
  1535. // --> (A < 0) ? -A : A
  1536. Value *Cmp = Builder.CreateICmpSLT(A, ConstantInt::getNullValue(Ty));
  1537. // Copy the nuw/nsw flags from the sub to the negate.
  1538. Value *Neg = Builder.CreateNeg(A, "", I.hasNoUnsignedWrap(),
  1539. I.hasNoSignedWrap());
  1540. return SelectInst::Create(Cmp, Neg, A);
  1541. }
  1542. if (Instruction *Ext = narrowMathIfNoOverflow(I))
  1543. return Ext;
  1544. bool Changed = false;
  1545. if (!I.hasNoSignedWrap() && willNotOverflowSignedSub(Op0, Op1, I)) {
  1546. Changed = true;
  1547. I.setHasNoSignedWrap(true);
  1548. }
  1549. if (!I.hasNoUnsignedWrap() && willNotOverflowUnsignedSub(Op0, Op1, I)) {
  1550. Changed = true;
  1551. I.setHasNoUnsignedWrap(true);
  1552. }
  1553. return Changed ? &I : nullptr;
  1554. }
  1555. /// This eliminates floating-point negation in either 'fneg(X)' or
  1556. /// 'fsub(-0.0, X)' form by combining into a constant operand.
  1557. static Instruction *foldFNegIntoConstant(Instruction &I) {
  1558. Value *X;
  1559. Constant *C;
  1560. // Fold negation into constant operand. This is limited with one-use because
  1561. // fneg is assumed better for analysis and cheaper in codegen than fmul/fdiv.
  1562. // -(X * C) --> X * (-C)
  1563. // FIXME: It's arguable whether these should be m_OneUse or not. The current
  1564. // belief is that the FNeg allows for better reassociation opportunities.
  1565. if (match(&I, m_FNeg(m_OneUse(m_FMul(m_Value(X), m_Constant(C))))))
  1566. return BinaryOperator::CreateFMulFMF(X, ConstantExpr::getFNeg(C), &I);
  1567. // -(X / C) --> X / (-C)
  1568. if (match(&I, m_FNeg(m_OneUse(m_FDiv(m_Value(X), m_Constant(C))))))
  1569. return BinaryOperator::CreateFDivFMF(X, ConstantExpr::getFNeg(C), &I);
  1570. // -(C / X) --> (-C) / X
  1571. if (match(&I, m_FNeg(m_OneUse(m_FDiv(m_Constant(C), m_Value(X))))))
  1572. return BinaryOperator::CreateFDivFMF(ConstantExpr::getFNeg(C), X, &I);
  1573. return nullptr;
  1574. }
  1575. Instruction *InstCombiner::visitFNeg(UnaryOperator &I) {
  1576. Value *Op = I.getOperand(0);
  1577. if (Value *V = SimplifyFNegInst(Op, I.getFastMathFlags(),
  1578. SQ.getWithInstruction(&I)))
  1579. return replaceInstUsesWith(I, V);
  1580. if (Instruction *X = foldFNegIntoConstant(I))
  1581. return X;
  1582. Value *X, *Y;
  1583. // If we can ignore the sign of zeros: -(X - Y) --> (Y - X)
  1584. if (I.hasNoSignedZeros() &&
  1585. match(Op, m_OneUse(m_FSub(m_Value(X), m_Value(Y)))))
  1586. return BinaryOperator::CreateFSubFMF(Y, X, &I);
  1587. return nullptr;
  1588. }
  1589. Instruction *InstCombiner::visitFSub(BinaryOperator &I) {
  1590. if (Value *V = SimplifyFSubInst(I.getOperand(0), I.getOperand(1),
  1591. I.getFastMathFlags(),
  1592. SQ.getWithInstruction(&I)))
  1593. return replaceInstUsesWith(I, V);
  1594. if (Instruction *X = foldVectorBinop(I))
  1595. return X;
  1596. // Subtraction from -0.0 is the canonical form of fneg.
  1597. // fsub nsz 0, X ==> fsub nsz -0.0, X
  1598. Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
  1599. if (I.hasNoSignedZeros() && match(Op0, m_PosZeroFP()))
  1600. return BinaryOperator::CreateFNegFMF(Op1, &I);
  1601. if (Instruction *X = foldFNegIntoConstant(I))
  1602. return X;
  1603. Value *X, *Y;
  1604. Constant *C;
  1605. // If Op0 is not -0.0 or we can ignore -0.0: Z - (X - Y) --> Z + (Y - X)
  1606. // Canonicalize to fadd to make analysis easier.
  1607. // This can also help codegen because fadd is commutative.
  1608. // Note that if this fsub was really an fneg, the fadd with -0.0 will get
  1609. // killed later. We still limit that particular transform with 'hasOneUse'
  1610. // because an fneg is assumed better/cheaper than a generic fsub.
  1611. if (I.hasNoSignedZeros() || CannotBeNegativeZero(Op0, SQ.TLI)) {
  1612. if (match(Op1, m_OneUse(m_FSub(m_Value(X), m_Value(Y))))) {
  1613. Value *NewSub = Builder.CreateFSubFMF(Y, X, &I);
  1614. return BinaryOperator::CreateFAddFMF(Op0, NewSub, &I);
  1615. }
  1616. }
  1617. if (isa<Constant>(Op0))
  1618. if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
  1619. if (Instruction *NV = FoldOpIntoSelect(I, SI))
  1620. return NV;
  1621. // X - C --> X + (-C)
  1622. // But don't transform constant expressions because there's an inverse fold
  1623. // for X + (-Y) --> X - Y.
  1624. if (match(Op1, m_Constant(C)) && !isa<ConstantExpr>(Op1))
  1625. return BinaryOperator::CreateFAddFMF(Op0, ConstantExpr::getFNeg(C), &I);
  1626. // X - (-Y) --> X + Y
  1627. if (match(Op1, m_FNeg(m_Value(Y))))
  1628. return BinaryOperator::CreateFAddFMF(Op0, Y, &I);
  1629. // Similar to above, but look through a cast of the negated value:
  1630. // X - (fptrunc(-Y)) --> X + fptrunc(Y)
  1631. Type *Ty = I.getType();
  1632. if (match(Op1, m_OneUse(m_FPTrunc(m_FNeg(m_Value(Y))))))
  1633. return BinaryOperator::CreateFAddFMF(Op0, Builder.CreateFPTrunc(Y, Ty), &I);
  1634. // X - (fpext(-Y)) --> X + fpext(Y)
  1635. if (match(Op1, m_OneUse(m_FPExt(m_FNeg(m_Value(Y))))))
  1636. return BinaryOperator::CreateFAddFMF(Op0, Builder.CreateFPExt(Y, Ty), &I);
  1637. // Handle special cases for FSub with selects feeding the operation
  1638. if (Value *V = SimplifySelectsFeedingBinaryOp(I, Op0, Op1))
  1639. return replaceInstUsesWith(I, V);
  1640. if (I.hasAllowReassoc() && I.hasNoSignedZeros()) {
  1641. // (Y - X) - Y --> -X
  1642. if (match(Op0, m_FSub(m_Specific(Op1), m_Value(X))))
  1643. return BinaryOperator::CreateFNegFMF(X, &I);
  1644. // Y - (X + Y) --> -X
  1645. // Y - (Y + X) --> -X
  1646. if (match(Op1, m_c_FAdd(m_Specific(Op0), m_Value(X))))
  1647. return BinaryOperator::CreateFNegFMF(X, &I);
  1648. // (X * C) - X --> X * (C - 1.0)
  1649. if (match(Op0, m_FMul(m_Specific(Op1), m_Constant(C)))) {
  1650. Constant *CSubOne = ConstantExpr::getFSub(C, ConstantFP::get(Ty, 1.0));
  1651. return BinaryOperator::CreateFMulFMF(Op1, CSubOne, &I);
  1652. }
  1653. // X - (X * C) --> X * (1.0 - C)
  1654. if (match(Op1, m_FMul(m_Specific(Op0), m_Constant(C)))) {
  1655. Constant *OneSubC = ConstantExpr::getFSub(ConstantFP::get(Ty, 1.0), C);
  1656. return BinaryOperator::CreateFMulFMF(Op0, OneSubC, &I);
  1657. }
  1658. if (Instruction *F = factorizeFAddFSub(I, Builder))
  1659. return F;
  1660. // TODO: This performs reassociative folds for FP ops. Some fraction of the
  1661. // functionality has been subsumed by simple pattern matching here and in
  1662. // InstSimplify. We should let a dedicated reassociation pass handle more
  1663. // complex pattern matching and remove this from InstCombine.
  1664. if (Value *V = FAddCombine(Builder).simplify(&I))
  1665. return replaceInstUsesWith(I, V);
  1666. }
  1667. return nullptr;
  1668. }