Reassociate.cpp 85 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276
  1. //===- Reassociate.cpp - Reassociate binary expressions -------------------===//
  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 pass reassociates commutative expressions in an order that is designed
  11. // to promote better constant propagation, GCSE, LICM, PRE, etc.
  12. //
  13. // For example: 4 + (x + 5) -> x + (4 + 5)
  14. //
  15. // In the implementation of this algorithm, constants are assigned rank = 0,
  16. // function arguments are rank = 1, and other values are assigned ranks
  17. // corresponding to the reverse post order traversal of current function
  18. // (starting at 2), which effectively gives values in deep loops higher rank
  19. // than values not in loops.
  20. //
  21. //===----------------------------------------------------------------------===//
  22. #include "llvm/Transforms/Scalar.h"
  23. #include "llvm/ADT/DenseMap.h"
  24. #include "llvm/ADT/PostOrderIterator.h"
  25. #include "llvm/ADT/STLExtras.h"
  26. #include "llvm/ADT/SetVector.h"
  27. #include "llvm/ADT/Statistic.h"
  28. #include "llvm/IR/CFG.h"
  29. #include "llvm/IR/Constants.h"
  30. #include "llvm/IR/DerivedTypes.h"
  31. #include "llvm/IR/Function.h"
  32. #include "llvm/IR/IRBuilder.h"
  33. #include "llvm/IR/Instructions.h"
  34. #include "llvm/IR/IntrinsicInst.h"
  35. #include "llvm/IR/ValueHandle.h"
  36. #include "llvm/Pass.h"
  37. #include "llvm/Support/Debug.h"
  38. #include "llvm/Support/raw_ostream.h"
  39. #include "llvm/Transforms/Utils/Local.h"
  40. #include <algorithm>
  41. using namespace llvm;
  42. #define DEBUG_TYPE "reassociate"
  43. STATISTIC(NumChanged, "Number of insts reassociated");
  44. STATISTIC(NumAnnihil, "Number of expr tree annihilated");
  45. STATISTIC(NumFactor , "Number of multiplies factored");
  46. namespace {
  47. struct ValueEntry {
  48. unsigned Rank;
  49. Value *Op;
  50. ValueEntry(unsigned R, Value *O) : Rank(R), Op(O) {}
  51. };
  52. inline bool operator<(const ValueEntry &LHS, const ValueEntry &RHS) {
  53. return LHS.Rank > RHS.Rank; // Sort so that highest rank goes to start.
  54. }
  55. }
  56. #ifndef NDEBUG
  57. /// Print out the expression identified in the Ops list.
  58. ///
  59. static void PrintOps(Instruction *I, const SmallVectorImpl<ValueEntry> &Ops) {
  60. Module *M = I->getParent()->getParent()->getParent();
  61. dbgs() << Instruction::getOpcodeName(I->getOpcode()) << " "
  62. << *Ops[0].Op->getType() << '\t';
  63. for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
  64. dbgs() << "[ ";
  65. Ops[i].Op->printAsOperand(dbgs(), false, M);
  66. dbgs() << ", #" << Ops[i].Rank << "] ";
  67. }
  68. }
  69. #endif
  70. namespace {
  71. /// \brief Utility class representing a base and exponent pair which form one
  72. /// factor of some product.
  73. struct Factor {
  74. Value *Base;
  75. unsigned Power;
  76. Factor(Value *Base, unsigned Power) : Base(Base), Power(Power) {}
  77. /// \brief Sort factors by their Base.
  78. struct BaseSorter {
  79. bool operator()(const Factor &LHS, const Factor &RHS) {
  80. return LHS.Base < RHS.Base;
  81. }
  82. };
  83. /// \brief Compare factors for equal bases.
  84. struct BaseEqual {
  85. bool operator()(const Factor &LHS, const Factor &RHS) {
  86. return LHS.Base == RHS.Base;
  87. }
  88. };
  89. /// \brief Sort factors in descending order by their power.
  90. struct PowerDescendingSorter {
  91. bool operator()(const Factor &LHS, const Factor &RHS) {
  92. return LHS.Power > RHS.Power;
  93. }
  94. };
  95. /// \brief Compare factors for equal powers.
  96. struct PowerEqual {
  97. bool operator()(const Factor &LHS, const Factor &RHS) {
  98. return LHS.Power == RHS.Power;
  99. }
  100. };
  101. };
  102. /// Utility class representing a non-constant Xor-operand. We classify
  103. /// non-constant Xor-Operands into two categories:
  104. /// C1) The operand is in the form "X & C", where C is a constant and C != ~0
  105. /// C2)
  106. /// C2.1) The operand is in the form of "X | C", where C is a non-zero
  107. /// constant.
  108. /// C2.2) Any operand E which doesn't fall into C1 and C2.1, we view this
  109. /// operand as "E | 0"
  110. class XorOpnd {
  111. public:
  112. XorOpnd(Value *V);
  113. bool isInvalid() const { return SymbolicPart == nullptr; }
  114. bool isOrExpr() const { return isOr; }
  115. Value *getValue() const { return OrigVal; }
  116. Value *getSymbolicPart() const { return SymbolicPart; }
  117. unsigned getSymbolicRank() const { return SymbolicRank; }
  118. const APInt &getConstPart() const { return ConstPart; }
  119. void Invalidate() { SymbolicPart = OrigVal = nullptr; }
  120. void setSymbolicRank(unsigned R) { SymbolicRank = R; }
  121. // Sort the XorOpnd-Pointer in ascending order of symbolic-value-rank.
  122. // The purpose is twofold:
  123. // 1) Cluster together the operands sharing the same symbolic-value.
  124. // 2) Operand having smaller symbolic-value-rank is permuted earlier, which
  125. // could potentially shorten crital path, and expose more loop-invariants.
  126. // Note that values' rank are basically defined in RPO order (FIXME).
  127. // So, if Rank(X) < Rank(Y) < Rank(Z), it means X is defined earlier
  128. // than Y which is defined earlier than Z. Permute "x | 1", "Y & 2",
  129. // "z" in the order of X-Y-Z is better than any other orders.
  130. struct PtrSortFunctor {
  131. bool operator()(XorOpnd * const &LHS, XorOpnd * const &RHS) {
  132. return LHS->getSymbolicRank() < RHS->getSymbolicRank();
  133. }
  134. };
  135. private:
  136. Value *OrigVal;
  137. Value *SymbolicPart;
  138. APInt ConstPart;
  139. unsigned SymbolicRank;
  140. bool isOr;
  141. };
  142. }
  143. namespace {
  144. class Reassociate : public FunctionPass {
  145. DenseMap<BasicBlock*, unsigned> RankMap;
  146. DenseMap<AssertingVH<Value>, unsigned> ValueRankMap;
  147. SetVector<AssertingVH<Instruction> > RedoInsts;
  148. bool MadeChange;
  149. public:
  150. static char ID; // Pass identification, replacement for typeid
  151. Reassociate() : FunctionPass(ID) {
  152. initializeReassociatePass(*PassRegistry::getPassRegistry());
  153. }
  154. bool runOnFunction(Function &F) override;
  155. void getAnalysisUsage(AnalysisUsage &AU) const override {
  156. AU.setPreservesCFG();
  157. }
  158. private:
  159. void BuildRankMap(Function &F);
  160. unsigned getRank(Value *V);
  161. void canonicalizeOperands(Instruction *I);
  162. void ReassociateExpression(BinaryOperator *I);
  163. void RewriteExprTree(BinaryOperator *I, SmallVectorImpl<ValueEntry> &Ops);
  164. Value *OptimizeExpression(BinaryOperator *I,
  165. SmallVectorImpl<ValueEntry> &Ops);
  166. Value *OptimizeAdd(Instruction *I, SmallVectorImpl<ValueEntry> &Ops);
  167. Value *OptimizeXor(Instruction *I, SmallVectorImpl<ValueEntry> &Ops);
  168. bool CombineXorOpnd(Instruction *I, XorOpnd *Opnd1, APInt &ConstOpnd,
  169. Value *&Res);
  170. bool CombineXorOpnd(Instruction *I, XorOpnd *Opnd1, XorOpnd *Opnd2,
  171. APInt &ConstOpnd, Value *&Res);
  172. bool collectMultiplyFactors(SmallVectorImpl<ValueEntry> &Ops,
  173. SmallVectorImpl<Factor> &Factors);
  174. Value *buildMinimalMultiplyDAG(IRBuilder<> &Builder,
  175. SmallVectorImpl<Factor> &Factors);
  176. Value *OptimizeMul(BinaryOperator *I, SmallVectorImpl<ValueEntry> &Ops);
  177. Value *RemoveFactorFromExpression(Value *V, Value *Factor);
  178. void EraseInst(Instruction *I);
  179. void OptimizeInst(Instruction *I);
  180. Instruction *canonicalizeNegConstExpr(Instruction *I);
  181. };
  182. }
  183. XorOpnd::XorOpnd(Value *V) {
  184. assert(!isa<ConstantInt>(V) && "No ConstantInt");
  185. OrigVal = V;
  186. Instruction *I = dyn_cast<Instruction>(V);
  187. SymbolicRank = 0;
  188. if (I && (I->getOpcode() == Instruction::Or ||
  189. I->getOpcode() == Instruction::And)) {
  190. Value *V0 = I->getOperand(0);
  191. Value *V1 = I->getOperand(1);
  192. if (isa<ConstantInt>(V0))
  193. std::swap(V0, V1);
  194. if (ConstantInt *C = dyn_cast<ConstantInt>(V1)) {
  195. ConstPart = C->getValue();
  196. SymbolicPart = V0;
  197. isOr = (I->getOpcode() == Instruction::Or);
  198. return;
  199. }
  200. }
  201. // view the operand as "V | 0"
  202. SymbolicPart = V;
  203. ConstPart = APInt::getNullValue(V->getType()->getIntegerBitWidth());
  204. isOr = true;
  205. }
  206. char Reassociate::ID = 0;
  207. INITIALIZE_PASS(Reassociate, "reassociate",
  208. "Reassociate expressions", false, false)
  209. // Public interface to the Reassociate pass
  210. FunctionPass *llvm::createReassociatePass() { return new Reassociate(); }
  211. /// Return true if V is an instruction of the specified opcode and if it
  212. /// only has one use.
  213. static BinaryOperator *isReassociableOp(Value *V, unsigned Opcode) {
  214. if (V->hasOneUse() && isa<Instruction>(V) &&
  215. cast<Instruction>(V)->getOpcode() == Opcode &&
  216. (!isa<FPMathOperator>(V) ||
  217. cast<Instruction>(V)->hasUnsafeAlgebra()))
  218. return cast<BinaryOperator>(V);
  219. return nullptr;
  220. }
  221. static BinaryOperator *isReassociableOp(Value *V, unsigned Opcode1,
  222. unsigned Opcode2) {
  223. if (V->hasOneUse() && isa<Instruction>(V) &&
  224. (cast<Instruction>(V)->getOpcode() == Opcode1 ||
  225. cast<Instruction>(V)->getOpcode() == Opcode2) &&
  226. (!isa<FPMathOperator>(V) ||
  227. cast<Instruction>(V)->hasUnsafeAlgebra()))
  228. return cast<BinaryOperator>(V);
  229. return nullptr;
  230. }
  231. static bool isUnmovableInstruction(Instruction *I) {
  232. switch (I->getOpcode()) {
  233. case Instruction::PHI:
  234. case Instruction::LandingPad:
  235. case Instruction::Alloca:
  236. case Instruction::Load:
  237. case Instruction::Invoke:
  238. case Instruction::UDiv:
  239. case Instruction::SDiv:
  240. case Instruction::FDiv:
  241. case Instruction::URem:
  242. case Instruction::SRem:
  243. case Instruction::FRem:
  244. return true;
  245. case Instruction::Call:
  246. return !isa<DbgInfoIntrinsic>(I);
  247. default:
  248. return false;
  249. }
  250. }
  251. void Reassociate::BuildRankMap(Function &F) {
  252. unsigned i = 2;
  253. // Assign distinct ranks to function arguments.
  254. for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end(); I != E; ++I) {
  255. ValueRankMap[&*I] = ++i;
  256. DEBUG(dbgs() << "Calculated Rank[" << I->getName() << "] = " << i << "\n");
  257. }
  258. ReversePostOrderTraversal<Function*> RPOT(&F);
  259. for (ReversePostOrderTraversal<Function*>::rpo_iterator I = RPOT.begin(),
  260. E = RPOT.end(); I != E; ++I) {
  261. BasicBlock *BB = *I;
  262. unsigned BBRank = RankMap[BB] = ++i << 16;
  263. // Walk the basic block, adding precomputed ranks for any instructions that
  264. // we cannot move. This ensures that the ranks for these instructions are
  265. // all different in the block.
  266. for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
  267. if (isUnmovableInstruction(I))
  268. ValueRankMap[&*I] = ++BBRank;
  269. }
  270. }
  271. unsigned Reassociate::getRank(Value *V) {
  272. Instruction *I = dyn_cast<Instruction>(V);
  273. if (!I) {
  274. if (isa<Argument>(V)) return ValueRankMap[V]; // Function argument.
  275. return 0; // Otherwise it's a global or constant, rank 0.
  276. }
  277. if (unsigned Rank = ValueRankMap[I])
  278. return Rank; // Rank already known?
  279. // If this is an expression, return the 1+MAX(rank(LHS), rank(RHS)) so that
  280. // we can reassociate expressions for code motion! Since we do not recurse
  281. // for PHI nodes, we cannot have infinite recursion here, because there
  282. // cannot be loops in the value graph that do not go through PHI nodes.
  283. unsigned Rank = 0, MaxRank = RankMap[I->getParent()];
  284. for (unsigned i = 0, e = I->getNumOperands();
  285. i != e && Rank != MaxRank; ++i)
  286. Rank = std::max(Rank, getRank(I->getOperand(i)));
  287. // If this is a not or neg instruction, do not count it for rank. This
  288. // assures us that X and ~X will have the same rank.
  289. if (!BinaryOperator::isNot(I) && !BinaryOperator::isNeg(I) &&
  290. !BinaryOperator::isFNeg(I))
  291. ++Rank;
  292. DEBUG(dbgs() << "Calculated Rank[" << V->getName() << "] = " << Rank << "\n");
  293. return ValueRankMap[I] = Rank;
  294. }
  295. // Canonicalize constants to RHS. Otherwise, sort the operands by rank.
  296. void Reassociate::canonicalizeOperands(Instruction *I) {
  297. assert(isa<BinaryOperator>(I) && "Expected binary operator.");
  298. assert(I->isCommutative() && "Expected commutative operator.");
  299. Value *LHS = I->getOperand(0);
  300. Value *RHS = I->getOperand(1);
  301. unsigned LHSRank = getRank(LHS);
  302. unsigned RHSRank = getRank(RHS);
  303. if (isa<Constant>(RHS))
  304. return;
  305. if (isa<Constant>(LHS) || RHSRank < LHSRank)
  306. cast<BinaryOperator>(I)->swapOperands();
  307. }
  308. static BinaryOperator *CreateAdd(Value *S1, Value *S2, const Twine &Name,
  309. Instruction *InsertBefore, Value *FlagsOp) {
  310. if (S1->getType()->isIntOrIntVectorTy())
  311. return BinaryOperator::CreateAdd(S1, S2, Name, InsertBefore);
  312. else {
  313. BinaryOperator *Res =
  314. BinaryOperator::CreateFAdd(S1, S2, Name, InsertBefore);
  315. Res->setFastMathFlags(cast<FPMathOperator>(FlagsOp)->getFastMathFlags());
  316. return Res;
  317. }
  318. }
  319. static BinaryOperator *CreateMul(Value *S1, Value *S2, const Twine &Name,
  320. Instruction *InsertBefore, Value *FlagsOp) {
  321. if (S1->getType()->isIntOrIntVectorTy())
  322. return BinaryOperator::CreateMul(S1, S2, Name, InsertBefore);
  323. else {
  324. BinaryOperator *Res =
  325. BinaryOperator::CreateFMul(S1, S2, Name, InsertBefore);
  326. Res->setFastMathFlags(cast<FPMathOperator>(FlagsOp)->getFastMathFlags());
  327. return Res;
  328. }
  329. }
  330. static BinaryOperator *CreateNeg(Value *S1, const Twine &Name,
  331. Instruction *InsertBefore, Value *FlagsOp) {
  332. if (S1->getType()->isIntOrIntVectorTy())
  333. return BinaryOperator::CreateNeg(S1, Name, InsertBefore);
  334. else {
  335. BinaryOperator *Res = BinaryOperator::CreateFNeg(S1, Name, InsertBefore);
  336. Res->setFastMathFlags(cast<FPMathOperator>(FlagsOp)->getFastMathFlags());
  337. return Res;
  338. }
  339. }
  340. /// Replace 0-X with X*-1.
  341. static BinaryOperator *LowerNegateToMultiply(Instruction *Neg) {
  342. Type *Ty = Neg->getType();
  343. Constant *NegOne = Ty->isIntOrIntVectorTy() ?
  344. ConstantInt::getAllOnesValue(Ty) : ConstantFP::get(Ty, -1.0);
  345. BinaryOperator *Res = CreateMul(Neg->getOperand(1), NegOne, "", Neg, Neg);
  346. Neg->setOperand(1, Constant::getNullValue(Ty)); // Drop use of op.
  347. Res->takeName(Neg);
  348. Neg->replaceAllUsesWith(Res);
  349. Res->setDebugLoc(Neg->getDebugLoc());
  350. return Res;
  351. }
  352. /// Returns k such that lambda(2^Bitwidth) = 2^k, where lambda is the Carmichael
  353. /// function. This means that x^(2^k) === 1 mod 2^Bitwidth for
  354. /// every odd x, i.e. x^(2^k) = 1 for every odd x in Bitwidth-bit arithmetic.
  355. /// Note that 0 <= k < Bitwidth, and if Bitwidth > 3 then x^(2^k) = 0 for every
  356. /// even x in Bitwidth-bit arithmetic.
  357. static unsigned CarmichaelShift(unsigned Bitwidth) {
  358. if (Bitwidth < 3)
  359. return Bitwidth - 1;
  360. return Bitwidth - 2;
  361. }
  362. /// Add the extra weight 'RHS' to the existing weight 'LHS',
  363. /// reducing the combined weight using any special properties of the operation.
  364. /// The existing weight LHS represents the computation X op X op ... op X where
  365. /// X occurs LHS times. The combined weight represents X op X op ... op X with
  366. /// X occurring LHS + RHS times. If op is "Xor" for example then the combined
  367. /// operation is equivalent to X if LHS + RHS is odd, or 0 if LHS + RHS is even;
  368. /// the routine returns 1 in LHS in the first case, and 0 in LHS in the second.
  369. static void IncorporateWeight(APInt &LHS, const APInt &RHS, unsigned Opcode) {
  370. // If we were working with infinite precision arithmetic then the combined
  371. // weight would be LHS + RHS. But we are using finite precision arithmetic,
  372. // and the APInt sum LHS + RHS may not be correct if it wraps (it is correct
  373. // for nilpotent operations and addition, but not for idempotent operations
  374. // and multiplication), so it is important to correctly reduce the combined
  375. // weight back into range if wrapping would be wrong.
  376. // If RHS is zero then the weight didn't change.
  377. if (RHS.isMinValue())
  378. return;
  379. // If LHS is zero then the combined weight is RHS.
  380. if (LHS.isMinValue()) {
  381. LHS = RHS;
  382. return;
  383. }
  384. // From this point on we know that neither LHS nor RHS is zero.
  385. if (Instruction::isIdempotent(Opcode)) {
  386. // Idempotent means X op X === X, so any non-zero weight is equivalent to a
  387. // weight of 1. Keeping weights at zero or one also means that wrapping is
  388. // not a problem.
  389. assert(LHS == 1 && RHS == 1 && "Weights not reduced!");
  390. return; // Return a weight of 1.
  391. }
  392. if (Instruction::isNilpotent(Opcode)) {
  393. // Nilpotent means X op X === 0, so reduce weights modulo 2.
  394. assert(LHS == 1 && RHS == 1 && "Weights not reduced!");
  395. LHS = 0; // 1 + 1 === 0 modulo 2.
  396. return;
  397. }
  398. if (Opcode == Instruction::Add || Opcode == Instruction::FAdd) {
  399. // TODO: Reduce the weight by exploiting nsw/nuw?
  400. LHS += RHS;
  401. return;
  402. }
  403. assert((Opcode == Instruction::Mul || Opcode == Instruction::FMul) &&
  404. "Unknown associative operation!");
  405. unsigned Bitwidth = LHS.getBitWidth();
  406. // If CM is the Carmichael number then a weight W satisfying W >= CM+Bitwidth
  407. // can be replaced with W-CM. That's because x^W=x^(W-CM) for every Bitwidth
  408. // bit number x, since either x is odd in which case x^CM = 1, or x is even in
  409. // which case both x^W and x^(W - CM) are zero. By subtracting off multiples
  410. // of CM like this weights can always be reduced to the range [0, CM+Bitwidth)
  411. // which by a happy accident means that they can always be represented using
  412. // Bitwidth bits.
  413. // TODO: Reduce the weight by exploiting nsw/nuw? (Could do much better than
  414. // the Carmichael number).
  415. if (Bitwidth > 3) {
  416. /// CM - The value of Carmichael's lambda function.
  417. APInt CM = APInt::getOneBitSet(Bitwidth, CarmichaelShift(Bitwidth));
  418. // Any weight W >= Threshold can be replaced with W - CM.
  419. APInt Threshold = CM + Bitwidth;
  420. assert(LHS.ult(Threshold) && RHS.ult(Threshold) && "Weights not reduced!");
  421. // For Bitwidth 4 or more the following sum does not overflow.
  422. LHS += RHS;
  423. while (LHS.uge(Threshold))
  424. LHS -= CM;
  425. } else {
  426. // To avoid problems with overflow do everything the same as above but using
  427. // a larger type.
  428. unsigned CM = 1U << CarmichaelShift(Bitwidth);
  429. unsigned Threshold = CM + Bitwidth;
  430. assert(LHS.getZExtValue() < Threshold && RHS.getZExtValue() < Threshold &&
  431. "Weights not reduced!");
  432. unsigned Total = LHS.getZExtValue() + RHS.getZExtValue();
  433. while (Total >= Threshold)
  434. Total -= CM;
  435. LHS = Total;
  436. }
  437. }
  438. typedef std::pair<Value*, APInt> RepeatedValue;
  439. /// Given an associative binary expression, return the leaf
  440. /// nodes in Ops along with their weights (how many times the leaf occurs). The
  441. /// original expression is the same as
  442. /// (Ops[0].first op Ops[0].first op ... Ops[0].first) <- Ops[0].second times
  443. /// op
  444. /// (Ops[1].first op Ops[1].first op ... Ops[1].first) <- Ops[1].second times
  445. /// op
  446. /// ...
  447. /// op
  448. /// (Ops[N].first op Ops[N].first op ... Ops[N].first) <- Ops[N].second times
  449. ///
  450. /// Note that the values Ops[0].first, ..., Ops[N].first are all distinct.
  451. ///
  452. /// This routine may modify the function, in which case it returns 'true'. The
  453. /// changes it makes may well be destructive, changing the value computed by 'I'
  454. /// to something completely different. Thus if the routine returns 'true' then
  455. /// you MUST either replace I with a new expression computed from the Ops array,
  456. /// or use RewriteExprTree to put the values back in.
  457. ///
  458. /// A leaf node is either not a binary operation of the same kind as the root
  459. /// node 'I' (i.e. is not a binary operator at all, or is, but with a different
  460. /// opcode), or is the same kind of binary operator but has a use which either
  461. /// does not belong to the expression, or does belong to the expression but is
  462. /// a leaf node. Every leaf node has at least one use that is a non-leaf node
  463. /// of the expression, while for non-leaf nodes (except for the root 'I') every
  464. /// use is a non-leaf node of the expression.
  465. ///
  466. /// For example:
  467. /// expression graph node names
  468. ///
  469. /// + | I
  470. /// / \ |
  471. /// + + | A, B
  472. /// / \ / \ |
  473. /// * + * | C, D, E
  474. /// / \ / \ / \ |
  475. /// + * | F, G
  476. ///
  477. /// The leaf nodes are C, E, F and G. The Ops array will contain (maybe not in
  478. /// that order) (C, 1), (E, 1), (F, 2), (G, 2).
  479. ///
  480. /// The expression is maximal: if some instruction is a binary operator of the
  481. /// same kind as 'I', and all of its uses are non-leaf nodes of the expression,
  482. /// then the instruction also belongs to the expression, is not a leaf node of
  483. /// it, and its operands also belong to the expression (but may be leaf nodes).
  484. ///
  485. /// NOTE: This routine will set operands of non-leaf non-root nodes to undef in
  486. /// order to ensure that every non-root node in the expression has *exactly one*
  487. /// use by a non-leaf node of the expression. This destruction means that the
  488. /// caller MUST either replace 'I' with a new expression or use something like
  489. /// RewriteExprTree to put the values back in if the routine indicates that it
  490. /// made a change by returning 'true'.
  491. ///
  492. /// In the above example either the right operand of A or the left operand of B
  493. /// will be replaced by undef. If it is B's operand then this gives:
  494. ///
  495. /// + | I
  496. /// / \ |
  497. /// + + | A, B - operand of B replaced with undef
  498. /// / \ \ |
  499. /// * + * | C, D, E
  500. /// / \ / \ / \ |
  501. /// + * | F, G
  502. ///
  503. /// Note that such undef operands can only be reached by passing through 'I'.
  504. /// For example, if you visit operands recursively starting from a leaf node
  505. /// then you will never see such an undef operand unless you get back to 'I',
  506. /// which requires passing through a phi node.
  507. ///
  508. /// Note that this routine may also mutate binary operators of the wrong type
  509. /// that have all uses inside the expression (i.e. only used by non-leaf nodes
  510. /// of the expression) if it can turn them into binary operators of the right
  511. /// type and thus make the expression bigger.
  512. static bool LinearizeExprTree(BinaryOperator *I,
  513. SmallVectorImpl<RepeatedValue> &Ops) {
  514. DEBUG(dbgs() << "LINEARIZE: " << *I << '\n');
  515. unsigned Bitwidth = I->getType()->getScalarType()->getPrimitiveSizeInBits();
  516. unsigned Opcode = I->getOpcode();
  517. assert(I->isAssociative() && I->isCommutative() &&
  518. "Expected an associative and commutative operation!");
  519. // Visit all operands of the expression, keeping track of their weight (the
  520. // number of paths from the expression root to the operand, or if you like
  521. // the number of times that operand occurs in the linearized expression).
  522. // For example, if I = X + A, where X = A + B, then I, X and B have weight 1
  523. // while A has weight two.
  524. // Worklist of non-leaf nodes (their operands are in the expression too) along
  525. // with their weights, representing a certain number of paths to the operator.
  526. // If an operator occurs in the worklist multiple times then we found multiple
  527. // ways to get to it.
  528. SmallVector<std::pair<BinaryOperator*, APInt>, 8> Worklist; // (Op, Weight)
  529. Worklist.push_back(std::make_pair(I, APInt(Bitwidth, 1)));
  530. bool Changed = false;
  531. // Leaves of the expression are values that either aren't the right kind of
  532. // operation (eg: a constant, or a multiply in an add tree), or are, but have
  533. // some uses that are not inside the expression. For example, in I = X + X,
  534. // X = A + B, the value X has two uses (by I) that are in the expression. If
  535. // X has any other uses, for example in a return instruction, then we consider
  536. // X to be a leaf, and won't analyze it further. When we first visit a value,
  537. // if it has more than one use then at first we conservatively consider it to
  538. // be a leaf. Later, as the expression is explored, we may discover some more
  539. // uses of the value from inside the expression. If all uses turn out to be
  540. // from within the expression (and the value is a binary operator of the right
  541. // kind) then the value is no longer considered to be a leaf, and its operands
  542. // are explored.
  543. // Leaves - Keeps track of the set of putative leaves as well as the number of
  544. // paths to each leaf seen so far.
  545. typedef DenseMap<Value*, APInt> LeafMap;
  546. LeafMap Leaves; // Leaf -> Total weight so far.
  547. SmallVector<Value*, 8> LeafOrder; // Ensure deterministic leaf output order.
  548. #ifndef NDEBUG
  549. SmallPtrSet<Value*, 8> Visited; // For sanity checking the iteration scheme.
  550. #endif
  551. while (!Worklist.empty()) {
  552. std::pair<BinaryOperator*, APInt> P = Worklist.pop_back_val();
  553. I = P.first; // We examine the operands of this binary operator.
  554. for (unsigned OpIdx = 0; OpIdx < 2; ++OpIdx) { // Visit operands.
  555. Value *Op = I->getOperand(OpIdx);
  556. APInt Weight = P.second; // Number of paths to this operand.
  557. DEBUG(dbgs() << "OPERAND: " << *Op << " (" << Weight << ")\n");
  558. assert(!Op->use_empty() && "No uses, so how did we get to it?!");
  559. // If this is a binary operation of the right kind with only one use then
  560. // add its operands to the expression.
  561. if (BinaryOperator *BO = isReassociableOp(Op, Opcode)) {
  562. assert(Visited.insert(Op).second && "Not first visit!");
  563. DEBUG(dbgs() << "DIRECT ADD: " << *Op << " (" << Weight << ")\n");
  564. Worklist.push_back(std::make_pair(BO, Weight));
  565. continue;
  566. }
  567. // Appears to be a leaf. Is the operand already in the set of leaves?
  568. LeafMap::iterator It = Leaves.find(Op);
  569. if (It == Leaves.end()) {
  570. // Not in the leaf map. Must be the first time we saw this operand.
  571. assert(Visited.insert(Op).second && "Not first visit!");
  572. if (!Op->hasOneUse()) {
  573. // This value has uses not accounted for by the expression, so it is
  574. // not safe to modify. Mark it as being a leaf.
  575. DEBUG(dbgs() << "ADD USES LEAF: " << *Op << " (" << Weight << ")\n");
  576. LeafOrder.push_back(Op);
  577. Leaves[Op] = Weight;
  578. continue;
  579. }
  580. // No uses outside the expression, try morphing it.
  581. } else if (It != Leaves.end()) {
  582. // Already in the leaf map.
  583. assert(Visited.count(Op) && "In leaf map but not visited!");
  584. // Update the number of paths to the leaf.
  585. IncorporateWeight(It->second, Weight, Opcode);
  586. #if 0 // TODO: Re-enable once PR13021 is fixed.
  587. // The leaf already has one use from inside the expression. As we want
  588. // exactly one such use, drop this new use of the leaf.
  589. assert(!Op->hasOneUse() && "Only one use, but we got here twice!");
  590. I->setOperand(OpIdx, UndefValue::get(I->getType()));
  591. Changed = true;
  592. // If the leaf is a binary operation of the right kind and we now see
  593. // that its multiple original uses were in fact all by nodes belonging
  594. // to the expression, then no longer consider it to be a leaf and add
  595. // its operands to the expression.
  596. if (BinaryOperator *BO = isReassociableOp(Op, Opcode)) {
  597. DEBUG(dbgs() << "UNLEAF: " << *Op << " (" << It->second << ")\n");
  598. Worklist.push_back(std::make_pair(BO, It->second));
  599. Leaves.erase(It);
  600. continue;
  601. }
  602. #endif
  603. // If we still have uses that are not accounted for by the expression
  604. // then it is not safe to modify the value.
  605. if (!Op->hasOneUse())
  606. continue;
  607. // No uses outside the expression, try morphing it.
  608. Weight = It->second;
  609. Leaves.erase(It); // Since the value may be morphed below.
  610. }
  611. // At this point we have a value which, first of all, is not a binary
  612. // expression of the right kind, and secondly, is only used inside the
  613. // expression. This means that it can safely be modified. See if we
  614. // can usefully morph it into an expression of the right kind.
  615. assert((!isa<Instruction>(Op) ||
  616. cast<Instruction>(Op)->getOpcode() != Opcode
  617. || (isa<FPMathOperator>(Op) &&
  618. !cast<Instruction>(Op)->hasUnsafeAlgebra())) &&
  619. "Should have been handled above!");
  620. assert(Op->hasOneUse() && "Has uses outside the expression tree!");
  621. // If this is a multiply expression, turn any internal negations into
  622. // multiplies by -1 so they can be reassociated.
  623. if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op))
  624. if ((Opcode == Instruction::Mul && BinaryOperator::isNeg(BO)) ||
  625. (Opcode == Instruction::FMul && BinaryOperator::isFNeg(BO))) {
  626. DEBUG(dbgs() << "MORPH LEAF: " << *Op << " (" << Weight << ") TO ");
  627. BO = LowerNegateToMultiply(BO);
  628. DEBUG(dbgs() << *BO << '\n');
  629. Worklist.push_back(std::make_pair(BO, Weight));
  630. Changed = true;
  631. continue;
  632. }
  633. // Failed to morph into an expression of the right type. This really is
  634. // a leaf.
  635. DEBUG(dbgs() << "ADD LEAF: " << *Op << " (" << Weight << ")\n");
  636. assert(!isReassociableOp(Op, Opcode) && "Value was morphed?");
  637. LeafOrder.push_back(Op);
  638. Leaves[Op] = Weight;
  639. }
  640. }
  641. // The leaves, repeated according to their weights, represent the linearized
  642. // form of the expression.
  643. for (unsigned i = 0, e = LeafOrder.size(); i != e; ++i) {
  644. Value *V = LeafOrder[i];
  645. LeafMap::iterator It = Leaves.find(V);
  646. if (It == Leaves.end())
  647. // Node initially thought to be a leaf wasn't.
  648. continue;
  649. assert(!isReassociableOp(V, Opcode) && "Shouldn't be a leaf!");
  650. APInt Weight = It->second;
  651. if (Weight.isMinValue())
  652. // Leaf already output or weight reduction eliminated it.
  653. continue;
  654. // Ensure the leaf is only output once.
  655. It->second = 0;
  656. Ops.push_back(std::make_pair(V, Weight));
  657. }
  658. // For nilpotent operations or addition there may be no operands, for example
  659. // because the expression was "X xor X" or consisted of 2^Bitwidth additions:
  660. // in both cases the weight reduces to 0 causing the value to be skipped.
  661. if (Ops.empty()) {
  662. Constant *Identity = ConstantExpr::getBinOpIdentity(Opcode, I->getType());
  663. assert(Identity && "Associative operation without identity!");
  664. Ops.emplace_back(Identity, APInt(Bitwidth, 1));
  665. }
  666. return Changed;
  667. }
  668. /// Now that the operands for this expression tree are
  669. /// linearized and optimized, emit them in-order.
  670. void Reassociate::RewriteExprTree(BinaryOperator *I,
  671. SmallVectorImpl<ValueEntry> &Ops) {
  672. assert(Ops.size() > 1 && "Single values should be used directly!");
  673. // Since our optimizations should never increase the number of operations, the
  674. // new expression can usually be written reusing the existing binary operators
  675. // from the original expression tree, without creating any new instructions,
  676. // though the rewritten expression may have a completely different topology.
  677. // We take care to not change anything if the new expression will be the same
  678. // as the original. If more than trivial changes (like commuting operands)
  679. // were made then we are obliged to clear out any optional subclass data like
  680. // nsw flags.
  681. /// NodesToRewrite - Nodes from the original expression available for writing
  682. /// the new expression into.
  683. SmallVector<BinaryOperator*, 8> NodesToRewrite;
  684. unsigned Opcode = I->getOpcode();
  685. BinaryOperator *Op = I;
  686. /// NotRewritable - The operands being written will be the leaves of the new
  687. /// expression and must not be used as inner nodes (via NodesToRewrite) by
  688. /// mistake. Inner nodes are always reassociable, and usually leaves are not
  689. /// (if they were they would have been incorporated into the expression and so
  690. /// would not be leaves), so most of the time there is no danger of this. But
  691. /// in rare cases a leaf may become reassociable if an optimization kills uses
  692. /// of it, or it may momentarily become reassociable during rewriting (below)
  693. /// due it being removed as an operand of one of its uses. Ensure that misuse
  694. /// of leaf nodes as inner nodes cannot occur by remembering all of the future
  695. /// leaves and refusing to reuse any of them as inner nodes.
  696. SmallPtrSet<Value*, 8> NotRewritable;
  697. for (unsigned i = 0, e = Ops.size(); i != e; ++i)
  698. NotRewritable.insert(Ops[i].Op);
  699. // ExpressionChanged - Non-null if the rewritten expression differs from the
  700. // original in some non-trivial way, requiring the clearing of optional flags.
  701. // Flags are cleared from the operator in ExpressionChanged up to I inclusive.
  702. BinaryOperator *ExpressionChanged = nullptr;
  703. for (unsigned i = 0; ; ++i) {
  704. // The last operation (which comes earliest in the IR) is special as both
  705. // operands will come from Ops, rather than just one with the other being
  706. // a subexpression.
  707. if (i+2 == Ops.size()) {
  708. Value *NewLHS = Ops[i].Op;
  709. Value *NewRHS = Ops[i+1].Op;
  710. Value *OldLHS = Op->getOperand(0);
  711. Value *OldRHS = Op->getOperand(1);
  712. if (NewLHS == OldLHS && NewRHS == OldRHS)
  713. // Nothing changed, leave it alone.
  714. break;
  715. if (NewLHS == OldRHS && NewRHS == OldLHS) {
  716. // The order of the operands was reversed. Swap them.
  717. DEBUG(dbgs() << "RA: " << *Op << '\n');
  718. Op->swapOperands();
  719. DEBUG(dbgs() << "TO: " << *Op << '\n');
  720. MadeChange = true;
  721. ++NumChanged;
  722. break;
  723. }
  724. // The new operation differs non-trivially from the original. Overwrite
  725. // the old operands with the new ones.
  726. DEBUG(dbgs() << "RA: " << *Op << '\n');
  727. if (NewLHS != OldLHS) {
  728. BinaryOperator *BO = isReassociableOp(OldLHS, Opcode);
  729. if (BO && !NotRewritable.count(BO))
  730. NodesToRewrite.push_back(BO);
  731. Op->setOperand(0, NewLHS);
  732. }
  733. if (NewRHS != OldRHS) {
  734. BinaryOperator *BO = isReassociableOp(OldRHS, Opcode);
  735. if (BO && !NotRewritable.count(BO))
  736. NodesToRewrite.push_back(BO);
  737. Op->setOperand(1, NewRHS);
  738. }
  739. DEBUG(dbgs() << "TO: " << *Op << '\n');
  740. ExpressionChanged = Op;
  741. MadeChange = true;
  742. ++NumChanged;
  743. break;
  744. }
  745. // Not the last operation. The left-hand side will be a sub-expression
  746. // while the right-hand side will be the current element of Ops.
  747. Value *NewRHS = Ops[i].Op;
  748. if (NewRHS != Op->getOperand(1)) {
  749. DEBUG(dbgs() << "RA: " << *Op << '\n');
  750. if (NewRHS == Op->getOperand(0)) {
  751. // The new right-hand side was already present as the left operand. If
  752. // we are lucky then swapping the operands will sort out both of them.
  753. Op->swapOperands();
  754. } else {
  755. // Overwrite with the new right-hand side.
  756. BinaryOperator *BO = isReassociableOp(Op->getOperand(1), Opcode);
  757. if (BO && !NotRewritable.count(BO))
  758. NodesToRewrite.push_back(BO);
  759. Op->setOperand(1, NewRHS);
  760. ExpressionChanged = Op;
  761. }
  762. DEBUG(dbgs() << "TO: " << *Op << '\n');
  763. MadeChange = true;
  764. ++NumChanged;
  765. }
  766. // Now deal with the left-hand side. If this is already an operation node
  767. // from the original expression then just rewrite the rest of the expression
  768. // into it.
  769. BinaryOperator *BO = isReassociableOp(Op->getOperand(0), Opcode);
  770. if (BO && !NotRewritable.count(BO)) {
  771. Op = BO;
  772. continue;
  773. }
  774. // Otherwise, grab a spare node from the original expression and use that as
  775. // the left-hand side. If there are no nodes left then the optimizers made
  776. // an expression with more nodes than the original! This usually means that
  777. // they did something stupid but it might mean that the problem was just too
  778. // hard (finding the mimimal number of multiplications needed to realize a
  779. // multiplication expression is NP-complete). Whatever the reason, smart or
  780. // stupid, create a new node if there are none left.
  781. BinaryOperator *NewOp;
  782. if (NodesToRewrite.empty()) {
  783. Constant *Undef = UndefValue::get(I->getType());
  784. NewOp = BinaryOperator::Create(Instruction::BinaryOps(Opcode),
  785. Undef, Undef, "", I);
  786. if (NewOp->getType()->isFPOrFPVectorTy())
  787. NewOp->setFastMathFlags(I->getFastMathFlags());
  788. } else {
  789. NewOp = NodesToRewrite.pop_back_val();
  790. }
  791. DEBUG(dbgs() << "RA: " << *Op << '\n');
  792. Op->setOperand(0, NewOp);
  793. DEBUG(dbgs() << "TO: " << *Op << '\n');
  794. ExpressionChanged = Op;
  795. MadeChange = true;
  796. ++NumChanged;
  797. Op = NewOp;
  798. }
  799. // If the expression changed non-trivially then clear out all subclass data
  800. // starting from the operator specified in ExpressionChanged, and compactify
  801. // the operators to just before the expression root to guarantee that the
  802. // expression tree is dominated by all of Ops.
  803. if (ExpressionChanged)
  804. do {
  805. // Preserve FastMathFlags.
  806. if (isa<FPMathOperator>(I)) {
  807. FastMathFlags Flags = I->getFastMathFlags();
  808. ExpressionChanged->clearSubclassOptionalData();
  809. ExpressionChanged->setFastMathFlags(Flags);
  810. } else
  811. ExpressionChanged->clearSubclassOptionalData();
  812. if (ExpressionChanged == I)
  813. break;
  814. ExpressionChanged->moveBefore(I);
  815. ExpressionChanged = cast<BinaryOperator>(*ExpressionChanged->user_begin());
  816. } while (1);
  817. // Throw away any left over nodes from the original expression.
  818. for (unsigned i = 0, e = NodesToRewrite.size(); i != e; ++i)
  819. RedoInsts.insert(NodesToRewrite[i]);
  820. }
  821. /// Insert instructions before the instruction pointed to by BI,
  822. /// that computes the negative version of the value specified. The negative
  823. /// version of the value is returned, and BI is left pointing at the instruction
  824. /// that should be processed next by the reassociation pass.
  825. static Value *NegateValue(Value *V, Instruction *BI) {
  826. if (Constant *C = dyn_cast<Constant>(V)) {
  827. if (C->getType()->isFPOrFPVectorTy()) {
  828. return ConstantExpr::getFNeg(C);
  829. }
  830. return ConstantExpr::getNeg(C);
  831. }
  832. // We are trying to expose opportunity for reassociation. One of the things
  833. // that we want to do to achieve this is to push a negation as deep into an
  834. // expression chain as possible, to expose the add instructions. In practice,
  835. // this means that we turn this:
  836. // X = -(A+12+C+D) into X = -A + -12 + -C + -D = -12 + -A + -C + -D
  837. // so that later, a: Y = 12+X could get reassociated with the -12 to eliminate
  838. // the constants. We assume that instcombine will clean up the mess later if
  839. // we introduce tons of unnecessary negation instructions.
  840. //
  841. if (BinaryOperator *I =
  842. isReassociableOp(V, Instruction::Add, Instruction::FAdd)) {
  843. // Push the negates through the add.
  844. I->setOperand(0, NegateValue(I->getOperand(0), BI));
  845. I->setOperand(1, NegateValue(I->getOperand(1), BI));
  846. if (I->getOpcode() == Instruction::Add) {
  847. I->setHasNoUnsignedWrap(false);
  848. I->setHasNoSignedWrap(false);
  849. }
  850. // We must move the add instruction here, because the neg instructions do
  851. // not dominate the old add instruction in general. By moving it, we are
  852. // assured that the neg instructions we just inserted dominate the
  853. // instruction we are about to insert after them.
  854. //
  855. I->moveBefore(BI);
  856. I->setName(I->getName()+".neg");
  857. return I;
  858. }
  859. // Okay, we need to materialize a negated version of V with an instruction.
  860. // Scan the use lists of V to see if we have one already.
  861. for (User *U : V->users()) {
  862. if (!BinaryOperator::isNeg(U) && !BinaryOperator::isFNeg(U))
  863. continue;
  864. // We found one! Now we have to make sure that the definition dominates
  865. // this use. We do this by moving it to the entry block (if it is a
  866. // non-instruction value) or right after the definition. These negates will
  867. // be zapped by reassociate later, so we don't need much finesse here.
  868. BinaryOperator *TheNeg = cast<BinaryOperator>(U);
  869. // Verify that the negate is in this function, V might be a constant expr.
  870. if (TheNeg->getParent()->getParent() != BI->getParent()->getParent())
  871. continue;
  872. BasicBlock::iterator InsertPt;
  873. if (Instruction *InstInput = dyn_cast<Instruction>(V)) {
  874. if (InvokeInst *II = dyn_cast<InvokeInst>(InstInput)) {
  875. InsertPt = II->getNormalDest()->begin();
  876. } else {
  877. InsertPt = InstInput;
  878. ++InsertPt;
  879. }
  880. while (isa<PHINode>(InsertPt)) ++InsertPt;
  881. } else {
  882. InsertPt = TheNeg->getParent()->getParent()->getEntryBlock().begin();
  883. }
  884. TheNeg->moveBefore(InsertPt);
  885. if (TheNeg->getOpcode() == Instruction::Sub) {
  886. TheNeg->setHasNoUnsignedWrap(false);
  887. TheNeg->setHasNoSignedWrap(false);
  888. } else {
  889. TheNeg->andIRFlags(BI);
  890. }
  891. return TheNeg;
  892. }
  893. // Insert a 'neg' instruction that subtracts the value from zero to get the
  894. // negation.
  895. return CreateNeg(V, V->getName() + ".neg", BI, BI);
  896. }
  897. /// Return true if we should break up this subtract of X-Y into (X + -Y).
  898. static bool ShouldBreakUpSubtract(Instruction *Sub) {
  899. // If this is a negation, we can't split it up!
  900. if (BinaryOperator::isNeg(Sub) || BinaryOperator::isFNeg(Sub))
  901. return false;
  902. // Don't breakup X - undef.
  903. if (isa<UndefValue>(Sub->getOperand(1)))
  904. return false;
  905. // Don't bother to break this up unless either the LHS is an associable add or
  906. // subtract or if this is only used by one.
  907. Value *V0 = Sub->getOperand(0);
  908. if (isReassociableOp(V0, Instruction::Add, Instruction::FAdd) ||
  909. isReassociableOp(V0, Instruction::Sub, Instruction::FSub))
  910. return true;
  911. Value *V1 = Sub->getOperand(1);
  912. if (isReassociableOp(V1, Instruction::Add, Instruction::FAdd) ||
  913. isReassociableOp(V1, Instruction::Sub, Instruction::FSub))
  914. return true;
  915. Value *VB = Sub->user_back();
  916. if (Sub->hasOneUse() &&
  917. (isReassociableOp(VB, Instruction::Add, Instruction::FAdd) ||
  918. isReassociableOp(VB, Instruction::Sub, Instruction::FSub)))
  919. return true;
  920. return false;
  921. }
  922. /// If we have (X-Y), and if either X is an add, or if this is only used by an
  923. /// add, transform this into (X+(0-Y)) to promote better reassociation.
  924. static BinaryOperator *BreakUpSubtract(Instruction *Sub) {
  925. // Convert a subtract into an add and a neg instruction. This allows sub
  926. // instructions to be commuted with other add instructions.
  927. //
  928. // Calculate the negative value of Operand 1 of the sub instruction,
  929. // and set it as the RHS of the add instruction we just made.
  930. //
  931. Value *NegVal = NegateValue(Sub->getOperand(1), Sub);
  932. BinaryOperator *New = CreateAdd(Sub->getOperand(0), NegVal, "", Sub, Sub);
  933. Sub->setOperand(0, Constant::getNullValue(Sub->getType())); // Drop use of op.
  934. Sub->setOperand(1, Constant::getNullValue(Sub->getType())); // Drop use of op.
  935. New->takeName(Sub);
  936. // Everyone now refers to the add instruction.
  937. Sub->replaceAllUsesWith(New);
  938. New->setDebugLoc(Sub->getDebugLoc());
  939. DEBUG(dbgs() << "Negated: " << *New << '\n');
  940. return New;
  941. }
  942. /// If this is a shift of a reassociable multiply or is used by one, change
  943. /// this into a multiply by a constant to assist with further reassociation.
  944. static BinaryOperator *ConvertShiftToMul(Instruction *Shl) {
  945. Constant *MulCst = ConstantInt::get(Shl->getType(), 1);
  946. MulCst = ConstantExpr::getShl(MulCst, cast<Constant>(Shl->getOperand(1)));
  947. BinaryOperator *Mul =
  948. BinaryOperator::CreateMul(Shl->getOperand(0), MulCst, "", Shl);
  949. Shl->setOperand(0, UndefValue::get(Shl->getType())); // Drop use of op.
  950. Mul->takeName(Shl);
  951. // Everyone now refers to the mul instruction.
  952. Shl->replaceAllUsesWith(Mul);
  953. Mul->setDebugLoc(Shl->getDebugLoc());
  954. // We can safely preserve the nuw flag in all cases. It's also safe to turn a
  955. // nuw nsw shl into a nuw nsw mul. However, nsw in isolation requires special
  956. // handling.
  957. bool NSW = cast<BinaryOperator>(Shl)->hasNoSignedWrap();
  958. bool NUW = cast<BinaryOperator>(Shl)->hasNoUnsignedWrap();
  959. if (NSW && NUW)
  960. Mul->setHasNoSignedWrap(true);
  961. Mul->setHasNoUnsignedWrap(NUW);
  962. return Mul;
  963. }
  964. /// Scan backwards and forwards among values with the same rank as element i
  965. /// to see if X exists. If X does not exist, return i. This is useful when
  966. /// scanning for 'x' when we see '-x' because they both get the same rank.
  967. static unsigned FindInOperandList(SmallVectorImpl<ValueEntry> &Ops, unsigned i,
  968. Value *X) {
  969. unsigned XRank = Ops[i].Rank;
  970. unsigned e = Ops.size();
  971. for (unsigned j = i+1; j != e && Ops[j].Rank == XRank; ++j) {
  972. if (Ops[j].Op == X)
  973. return j;
  974. if (Instruction *I1 = dyn_cast<Instruction>(Ops[j].Op))
  975. if (Instruction *I2 = dyn_cast<Instruction>(X))
  976. if (I1->isIdenticalTo(I2))
  977. return j;
  978. }
  979. // Scan backwards.
  980. for (unsigned j = i-1; j != ~0U && Ops[j].Rank == XRank; --j) {
  981. if (Ops[j].Op == X)
  982. return j;
  983. if (Instruction *I1 = dyn_cast<Instruction>(Ops[j].Op))
  984. if (Instruction *I2 = dyn_cast<Instruction>(X))
  985. if (I1->isIdenticalTo(I2))
  986. return j;
  987. }
  988. return i;
  989. }
  990. /// Emit a tree of add instructions, summing Ops together
  991. /// and returning the result. Insert the tree before I.
  992. static Value *EmitAddTreeOfValues(Instruction *I,
  993. SmallVectorImpl<WeakVH> &Ops){
  994. if (Ops.size() == 1) return Ops.back();
  995. Value *V1 = Ops.back();
  996. Ops.pop_back();
  997. Value *V2 = EmitAddTreeOfValues(I, Ops);
  998. return CreateAdd(V2, V1, "tmp", I, I);
  999. }
  1000. /// If V is an expression tree that is a multiplication sequence,
  1001. /// and if this sequence contains a multiply by Factor,
  1002. /// remove Factor from the tree and return the new tree.
  1003. Value *Reassociate::RemoveFactorFromExpression(Value *V, Value *Factor) {
  1004. BinaryOperator *BO = isReassociableOp(V, Instruction::Mul, Instruction::FMul);
  1005. if (!BO)
  1006. return nullptr;
  1007. SmallVector<RepeatedValue, 8> Tree;
  1008. MadeChange |= LinearizeExprTree(BO, Tree);
  1009. SmallVector<ValueEntry, 8> Factors;
  1010. Factors.reserve(Tree.size());
  1011. for (unsigned i = 0, e = Tree.size(); i != e; ++i) {
  1012. RepeatedValue E = Tree[i];
  1013. Factors.append(E.second.getZExtValue(),
  1014. ValueEntry(getRank(E.first), E.first));
  1015. }
  1016. bool FoundFactor = false;
  1017. bool NeedsNegate = false;
  1018. for (unsigned i = 0, e = Factors.size(); i != e; ++i) {
  1019. if (Factors[i].Op == Factor) {
  1020. FoundFactor = true;
  1021. Factors.erase(Factors.begin()+i);
  1022. break;
  1023. }
  1024. // If this is a negative version of this factor, remove it.
  1025. if (ConstantInt *FC1 = dyn_cast<ConstantInt>(Factor)) {
  1026. if (ConstantInt *FC2 = dyn_cast<ConstantInt>(Factors[i].Op))
  1027. if (FC1->getValue() == -FC2->getValue()) {
  1028. FoundFactor = NeedsNegate = true;
  1029. Factors.erase(Factors.begin()+i);
  1030. break;
  1031. }
  1032. } else if (ConstantFP *FC1 = dyn_cast<ConstantFP>(Factor)) {
  1033. if (ConstantFP *FC2 = dyn_cast<ConstantFP>(Factors[i].Op)) {
  1034. APFloat F1(FC1->getValueAPF());
  1035. APFloat F2(FC2->getValueAPF());
  1036. F2.changeSign();
  1037. if (F1.compare(F2) == APFloat::cmpEqual) {
  1038. FoundFactor = NeedsNegate = true;
  1039. Factors.erase(Factors.begin() + i);
  1040. break;
  1041. }
  1042. }
  1043. }
  1044. }
  1045. if (!FoundFactor) {
  1046. // Make sure to restore the operands to the expression tree.
  1047. RewriteExprTree(BO, Factors);
  1048. return nullptr;
  1049. }
  1050. BasicBlock::iterator InsertPt = BO; ++InsertPt;
  1051. // If this was just a single multiply, remove the multiply and return the only
  1052. // remaining operand.
  1053. if (Factors.size() == 1) {
  1054. RedoInsts.insert(BO);
  1055. V = Factors[0].Op;
  1056. } else {
  1057. RewriteExprTree(BO, Factors);
  1058. V = BO;
  1059. }
  1060. if (NeedsNegate)
  1061. V = CreateNeg(V, "neg", InsertPt, BO);
  1062. return V;
  1063. }
  1064. /// If V is a single-use multiply, recursively add its operands as factors,
  1065. /// otherwise add V to the list of factors.
  1066. ///
  1067. /// Ops is the top-level list of add operands we're trying to factor.
  1068. static void FindSingleUseMultiplyFactors(Value *V,
  1069. SmallVectorImpl<Value*> &Factors,
  1070. const SmallVectorImpl<ValueEntry> &Ops) {
  1071. BinaryOperator *BO = isReassociableOp(V, Instruction::Mul, Instruction::FMul);
  1072. if (!BO) {
  1073. Factors.push_back(V);
  1074. return;
  1075. }
  1076. // Otherwise, add the LHS and RHS to the list of factors.
  1077. FindSingleUseMultiplyFactors(BO->getOperand(1), Factors, Ops);
  1078. FindSingleUseMultiplyFactors(BO->getOperand(0), Factors, Ops);
  1079. }
  1080. /// Optimize a series of operands to an 'and', 'or', or 'xor' instruction.
  1081. /// This optimizes based on identities. If it can be reduced to a single Value,
  1082. /// it is returned, otherwise the Ops list is mutated as necessary.
  1083. static Value *OptimizeAndOrXor(unsigned Opcode,
  1084. SmallVectorImpl<ValueEntry> &Ops) {
  1085. // Scan the operand lists looking for X and ~X pairs, along with X,X pairs.
  1086. // If we find any, we can simplify the expression. X&~X == 0, X|~X == -1.
  1087. for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
  1088. // First, check for X and ~X in the operand list.
  1089. assert(i < Ops.size());
  1090. if (BinaryOperator::isNot(Ops[i].Op)) { // Cannot occur for ^.
  1091. Value *X = BinaryOperator::getNotArgument(Ops[i].Op);
  1092. unsigned FoundX = FindInOperandList(Ops, i, X);
  1093. if (FoundX != i) {
  1094. if (Opcode == Instruction::And) // ...&X&~X = 0
  1095. return Constant::getNullValue(X->getType());
  1096. if (Opcode == Instruction::Or) // ...|X|~X = -1
  1097. return Constant::getAllOnesValue(X->getType());
  1098. }
  1099. }
  1100. // Next, check for duplicate pairs of values, which we assume are next to
  1101. // each other, due to our sorting criteria.
  1102. assert(i < Ops.size());
  1103. if (i+1 != Ops.size() && Ops[i+1].Op == Ops[i].Op) {
  1104. if (Opcode == Instruction::And || Opcode == Instruction::Or) {
  1105. // Drop duplicate values for And and Or.
  1106. Ops.erase(Ops.begin()+i);
  1107. --i; --e;
  1108. ++NumAnnihil;
  1109. continue;
  1110. }
  1111. // Drop pairs of values for Xor.
  1112. assert(Opcode == Instruction::Xor);
  1113. if (e == 2)
  1114. return Constant::getNullValue(Ops[0].Op->getType());
  1115. // Y ^ X^X -> Y
  1116. Ops.erase(Ops.begin()+i, Ops.begin()+i+2);
  1117. i -= 1; e -= 2;
  1118. ++NumAnnihil;
  1119. }
  1120. }
  1121. return nullptr;
  1122. }
  1123. /// Helper funciton of CombineXorOpnd(). It creates a bitwise-and
  1124. /// instruction with the given two operands, and return the resulting
  1125. /// instruction. There are two special cases: 1) if the constant operand is 0,
  1126. /// it will return NULL. 2) if the constant is ~0, the symbolic operand will
  1127. /// be returned.
  1128. static Value *createAndInstr(Instruction *InsertBefore, Value *Opnd,
  1129. const APInt &ConstOpnd) {
  1130. if (ConstOpnd != 0) {
  1131. if (!ConstOpnd.isAllOnesValue()) {
  1132. LLVMContext &Ctx = Opnd->getType()->getContext();
  1133. Instruction *I;
  1134. I = BinaryOperator::CreateAnd(Opnd, ConstantInt::get(Ctx, ConstOpnd),
  1135. "and.ra", InsertBefore);
  1136. I->setDebugLoc(InsertBefore->getDebugLoc());
  1137. return I;
  1138. }
  1139. return Opnd;
  1140. }
  1141. return nullptr;
  1142. }
  1143. // Helper function of OptimizeXor(). It tries to simplify "Opnd1 ^ ConstOpnd"
  1144. // into "R ^ C", where C would be 0, and R is a symbolic value.
  1145. //
  1146. // If it was successful, true is returned, and the "R" and "C" is returned
  1147. // via "Res" and "ConstOpnd", respectively; otherwise, false is returned,
  1148. // and both "Res" and "ConstOpnd" remain unchanged.
  1149. //
  1150. bool Reassociate::CombineXorOpnd(Instruction *I, XorOpnd *Opnd1,
  1151. APInt &ConstOpnd, Value *&Res) {
  1152. // Xor-Rule 1: (x | c1) ^ c2 = (x | c1) ^ (c1 ^ c1) ^ c2
  1153. // = ((x | c1) ^ c1) ^ (c1 ^ c2)
  1154. // = (x & ~c1) ^ (c1 ^ c2)
  1155. // It is useful only when c1 == c2.
  1156. if (Opnd1->isOrExpr() && Opnd1->getConstPart() != 0) {
  1157. if (!Opnd1->getValue()->hasOneUse())
  1158. return false;
  1159. const APInt &C1 = Opnd1->getConstPart();
  1160. if (C1 != ConstOpnd)
  1161. return false;
  1162. Value *X = Opnd1->getSymbolicPart();
  1163. Res = createAndInstr(I, X, ~C1);
  1164. // ConstOpnd was C2, now C1 ^ C2.
  1165. ConstOpnd ^= C1;
  1166. if (Instruction *T = dyn_cast<Instruction>(Opnd1->getValue()))
  1167. RedoInsts.insert(T);
  1168. return true;
  1169. }
  1170. return false;
  1171. }
  1172. // Helper function of OptimizeXor(). It tries to simplify
  1173. // "Opnd1 ^ Opnd2 ^ ConstOpnd" into "R ^ C", where C would be 0, and R is a
  1174. // symbolic value.
  1175. //
  1176. // If it was successful, true is returned, and the "R" and "C" is returned
  1177. // via "Res" and "ConstOpnd", respectively (If the entire expression is
  1178. // evaluated to a constant, the Res is set to NULL); otherwise, false is
  1179. // returned, and both "Res" and "ConstOpnd" remain unchanged.
  1180. bool Reassociate::CombineXorOpnd(Instruction *I, XorOpnd *Opnd1, XorOpnd *Opnd2,
  1181. APInt &ConstOpnd, Value *&Res) {
  1182. Value *X = Opnd1->getSymbolicPart();
  1183. if (X != Opnd2->getSymbolicPart())
  1184. return false;
  1185. // This many instruction become dead.(At least "Opnd1 ^ Opnd2" will die.)
  1186. int DeadInstNum = 1;
  1187. if (Opnd1->getValue()->hasOneUse())
  1188. DeadInstNum++;
  1189. if (Opnd2->getValue()->hasOneUse())
  1190. DeadInstNum++;
  1191. // Xor-Rule 2:
  1192. // (x | c1) ^ (x & c2)
  1193. // = (x|c1) ^ (x&c2) ^ (c1 ^ c1) = ((x|c1) ^ c1) ^ (x & c2) ^ c1
  1194. // = (x & ~c1) ^ (x & c2) ^ c1 // Xor-Rule 1
  1195. // = (x & c3) ^ c1, where c3 = ~c1 ^ c2 // Xor-rule 3
  1196. //
  1197. if (Opnd1->isOrExpr() != Opnd2->isOrExpr()) {
  1198. if (Opnd2->isOrExpr())
  1199. std::swap(Opnd1, Opnd2);
  1200. const APInt &C1 = Opnd1->getConstPart();
  1201. const APInt &C2 = Opnd2->getConstPart();
  1202. APInt C3((~C1) ^ C2);
  1203. // Do not increase code size!
  1204. if (C3 != 0 && !C3.isAllOnesValue()) {
  1205. int NewInstNum = ConstOpnd != 0 ? 1 : 2;
  1206. if (NewInstNum > DeadInstNum)
  1207. return false;
  1208. }
  1209. Res = createAndInstr(I, X, C3);
  1210. ConstOpnd ^= C1;
  1211. } else if (Opnd1->isOrExpr()) {
  1212. // Xor-Rule 3: (x | c1) ^ (x | c2) = (x & c3) ^ c3 where c3 = c1 ^ c2
  1213. //
  1214. const APInt &C1 = Opnd1->getConstPart();
  1215. const APInt &C2 = Opnd2->getConstPart();
  1216. APInt C3 = C1 ^ C2;
  1217. // Do not increase code size
  1218. if (C3 != 0 && !C3.isAllOnesValue()) {
  1219. int NewInstNum = ConstOpnd != 0 ? 1 : 2;
  1220. if (NewInstNum > DeadInstNum)
  1221. return false;
  1222. }
  1223. Res = createAndInstr(I, X, C3);
  1224. ConstOpnd ^= C3;
  1225. } else {
  1226. // Xor-Rule 4: (x & c1) ^ (x & c2) = (x & (c1^c2))
  1227. //
  1228. const APInt &C1 = Opnd1->getConstPart();
  1229. const APInt &C2 = Opnd2->getConstPart();
  1230. APInt C3 = C1 ^ C2;
  1231. Res = createAndInstr(I, X, C3);
  1232. }
  1233. // Put the original operands in the Redo list; hope they will be deleted
  1234. // as dead code.
  1235. if (Instruction *T = dyn_cast<Instruction>(Opnd1->getValue()))
  1236. RedoInsts.insert(T);
  1237. if (Instruction *T = dyn_cast<Instruction>(Opnd2->getValue()))
  1238. RedoInsts.insert(T);
  1239. return true;
  1240. }
  1241. /// Optimize a series of operands to an 'xor' instruction. If it can be reduced
  1242. /// to a single Value, it is returned, otherwise the Ops list is mutated as
  1243. /// necessary.
  1244. Value *Reassociate::OptimizeXor(Instruction *I,
  1245. SmallVectorImpl<ValueEntry> &Ops) {
  1246. if (Value *V = OptimizeAndOrXor(Instruction::Xor, Ops))
  1247. return V;
  1248. if (Ops.size() == 1)
  1249. return nullptr;
  1250. SmallVector<XorOpnd, 8> Opnds;
  1251. SmallVector<XorOpnd*, 8> OpndPtrs;
  1252. Type *Ty = Ops[0].Op->getType();
  1253. APInt ConstOpnd(Ty->getIntegerBitWidth(), 0);
  1254. // Step 1: Convert ValueEntry to XorOpnd
  1255. for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
  1256. Value *V = Ops[i].Op;
  1257. if (!isa<ConstantInt>(V)) {
  1258. XorOpnd O(V);
  1259. O.setSymbolicRank(getRank(O.getSymbolicPart()));
  1260. Opnds.push_back(O);
  1261. } else
  1262. ConstOpnd ^= cast<ConstantInt>(V)->getValue();
  1263. }
  1264. // NOTE: From this point on, do *NOT* add/delete element to/from "Opnds".
  1265. // It would otherwise invalidate the "Opnds"'s iterator, and hence invalidate
  1266. // the "OpndPtrs" as well. For the similar reason, do not fuse this loop
  1267. // with the previous loop --- the iterator of the "Opnds" may be invalidated
  1268. // when new elements are added to the vector.
  1269. for (unsigned i = 0, e = Opnds.size(); i != e; ++i)
  1270. OpndPtrs.push_back(&Opnds[i]);
  1271. // Step 2: Sort the Xor-Operands in a way such that the operands containing
  1272. // the same symbolic value cluster together. For instance, the input operand
  1273. // sequence ("x | 123", "y & 456", "x & 789") will be sorted into:
  1274. // ("x | 123", "x & 789", "y & 456").
  1275. std::stable_sort(OpndPtrs.begin(), OpndPtrs.end(), XorOpnd::PtrSortFunctor());
  1276. // Step 3: Combine adjacent operands
  1277. XorOpnd *PrevOpnd = nullptr;
  1278. bool Changed = false;
  1279. for (unsigned i = 0, e = Opnds.size(); i < e; i++) {
  1280. XorOpnd *CurrOpnd = OpndPtrs[i];
  1281. // The combined value
  1282. Value *CV;
  1283. // Step 3.1: Try simplifying "CurrOpnd ^ ConstOpnd"
  1284. if (ConstOpnd != 0 && CombineXorOpnd(I, CurrOpnd, ConstOpnd, CV)) {
  1285. Changed = true;
  1286. if (CV)
  1287. *CurrOpnd = XorOpnd(CV);
  1288. else {
  1289. CurrOpnd->Invalidate();
  1290. continue;
  1291. }
  1292. }
  1293. if (!PrevOpnd || CurrOpnd->getSymbolicPart() != PrevOpnd->getSymbolicPart()) {
  1294. PrevOpnd = CurrOpnd;
  1295. continue;
  1296. }
  1297. // step 3.2: When previous and current operands share the same symbolic
  1298. // value, try to simplify "PrevOpnd ^ CurrOpnd ^ ConstOpnd"
  1299. //
  1300. if (CombineXorOpnd(I, CurrOpnd, PrevOpnd, ConstOpnd, CV)) {
  1301. // Remove previous operand
  1302. PrevOpnd->Invalidate();
  1303. if (CV) {
  1304. *CurrOpnd = XorOpnd(CV);
  1305. PrevOpnd = CurrOpnd;
  1306. } else {
  1307. CurrOpnd->Invalidate();
  1308. PrevOpnd = nullptr;
  1309. }
  1310. Changed = true;
  1311. }
  1312. }
  1313. // Step 4: Reassemble the Ops
  1314. if (Changed) {
  1315. Ops.clear();
  1316. for (unsigned int i = 0, e = Opnds.size(); i < e; i++) {
  1317. XorOpnd &O = Opnds[i];
  1318. if (O.isInvalid())
  1319. continue;
  1320. ValueEntry VE(getRank(O.getValue()), O.getValue());
  1321. Ops.push_back(VE);
  1322. }
  1323. if (ConstOpnd != 0) {
  1324. Value *C = ConstantInt::get(Ty->getContext(), ConstOpnd);
  1325. ValueEntry VE(getRank(C), C);
  1326. Ops.push_back(VE);
  1327. }
  1328. int Sz = Ops.size();
  1329. if (Sz == 1)
  1330. return Ops.back().Op;
  1331. else if (Sz == 0) {
  1332. assert(ConstOpnd == 0);
  1333. return ConstantInt::get(Ty->getContext(), ConstOpnd);
  1334. }
  1335. }
  1336. return nullptr;
  1337. }
  1338. /// Optimize a series of operands to an 'add' instruction. This
  1339. /// optimizes based on identities. If it can be reduced to a single Value, it
  1340. /// is returned, otherwise the Ops list is mutated as necessary.
  1341. Value *Reassociate::OptimizeAdd(Instruction *I,
  1342. SmallVectorImpl<ValueEntry> &Ops) {
  1343. // Scan the operand lists looking for X and -X pairs. If we find any, we
  1344. // can simplify expressions like X+-X == 0 and X+~X ==-1. While we're at it,
  1345. // scan for any
  1346. // duplicates. We want to canonicalize Y+Y+Y+Z -> 3*Y+Z.
  1347. for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
  1348. Value *TheOp = Ops[i].Op;
  1349. // Check to see if we've seen this operand before. If so, we factor all
  1350. // instances of the operand together. Due to our sorting criteria, we know
  1351. // that these need to be next to each other in the vector.
  1352. if (i+1 != Ops.size() && Ops[i+1].Op == TheOp) {
  1353. // Rescan the list, remove all instances of this operand from the expr.
  1354. unsigned NumFound = 0;
  1355. do {
  1356. Ops.erase(Ops.begin()+i);
  1357. ++NumFound;
  1358. } while (i != Ops.size() && Ops[i].Op == TheOp);
  1359. DEBUG(dbgs() << "\nFACTORING [" << NumFound << "]: " << *TheOp << '\n');
  1360. ++NumFactor;
  1361. // Insert a new multiply.
  1362. Type *Ty = TheOp->getType();
  1363. Constant *C = Ty->isIntOrIntVectorTy() ?
  1364. ConstantInt::get(Ty, NumFound) : ConstantFP::get(Ty, NumFound);
  1365. Instruction *Mul = CreateMul(TheOp, C, "factor", I, I);
  1366. // Now that we have inserted a multiply, optimize it. This allows us to
  1367. // handle cases that require multiple factoring steps, such as this:
  1368. // (X*2) + (X*2) + (X*2) -> (X*2)*3 -> X*6
  1369. RedoInsts.insert(Mul);
  1370. // If every add operand was a duplicate, return the multiply.
  1371. if (Ops.empty())
  1372. return Mul;
  1373. // Otherwise, we had some input that didn't have the dupe, such as
  1374. // "A + A + B" -> "A*2 + B". Add the new multiply to the list of
  1375. // things being added by this operation.
  1376. Ops.insert(Ops.begin(), ValueEntry(getRank(Mul), Mul));
  1377. --i;
  1378. e = Ops.size();
  1379. continue;
  1380. }
  1381. // Check for X and -X or X and ~X in the operand list.
  1382. if (!BinaryOperator::isNeg(TheOp) && !BinaryOperator::isFNeg(TheOp) &&
  1383. !BinaryOperator::isNot(TheOp))
  1384. continue;
  1385. Value *X = nullptr;
  1386. if (BinaryOperator::isNeg(TheOp) || BinaryOperator::isFNeg(TheOp))
  1387. X = BinaryOperator::getNegArgument(TheOp);
  1388. else if (BinaryOperator::isNot(TheOp))
  1389. X = BinaryOperator::getNotArgument(TheOp);
  1390. unsigned FoundX = FindInOperandList(Ops, i, X);
  1391. if (FoundX == i)
  1392. continue;
  1393. // Remove X and -X from the operand list.
  1394. if (Ops.size() == 2 &&
  1395. (BinaryOperator::isNeg(TheOp) || BinaryOperator::isFNeg(TheOp)))
  1396. return Constant::getNullValue(X->getType());
  1397. // Remove X and ~X from the operand list.
  1398. if (Ops.size() == 2 && BinaryOperator::isNot(TheOp))
  1399. return Constant::getAllOnesValue(X->getType());
  1400. Ops.erase(Ops.begin()+i);
  1401. if (i < FoundX)
  1402. --FoundX;
  1403. else
  1404. --i; // Need to back up an extra one.
  1405. Ops.erase(Ops.begin()+FoundX);
  1406. ++NumAnnihil;
  1407. --i; // Revisit element.
  1408. e -= 2; // Removed two elements.
  1409. // if X and ~X we append -1 to the operand list.
  1410. if (BinaryOperator::isNot(TheOp)) {
  1411. Value *V = Constant::getAllOnesValue(X->getType());
  1412. Ops.insert(Ops.end(), ValueEntry(getRank(V), V));
  1413. e += 1;
  1414. }
  1415. }
  1416. // Scan the operand list, checking to see if there are any common factors
  1417. // between operands. Consider something like A*A+A*B*C+D. We would like to
  1418. // reassociate this to A*(A+B*C)+D, which reduces the number of multiplies.
  1419. // To efficiently find this, we count the number of times a factor occurs
  1420. // for any ADD operands that are MULs.
  1421. DenseMap<Value*, unsigned> FactorOccurrences;
  1422. // Keep track of each multiply we see, to avoid triggering on (X*4)+(X*4)
  1423. // where they are actually the same multiply.
  1424. unsigned MaxOcc = 0;
  1425. Value *MaxOccVal = nullptr;
  1426. for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
  1427. BinaryOperator *BOp =
  1428. isReassociableOp(Ops[i].Op, Instruction::Mul, Instruction::FMul);
  1429. if (!BOp)
  1430. continue;
  1431. // Compute all of the factors of this added value.
  1432. SmallVector<Value*, 8> Factors;
  1433. FindSingleUseMultiplyFactors(BOp, Factors, Ops);
  1434. assert(Factors.size() > 1 && "Bad linearize!");
  1435. // Add one to FactorOccurrences for each unique factor in this op.
  1436. SmallPtrSet<Value*, 8> Duplicates;
  1437. for (unsigned i = 0, e = Factors.size(); i != e; ++i) {
  1438. Value *Factor = Factors[i];
  1439. if (!Duplicates.insert(Factor).second)
  1440. continue;
  1441. unsigned Occ = ++FactorOccurrences[Factor];
  1442. if (Occ > MaxOcc) {
  1443. MaxOcc = Occ;
  1444. MaxOccVal = Factor;
  1445. }
  1446. // If Factor is a negative constant, add the negated value as a factor
  1447. // because we can percolate the negate out. Watch for minint, which
  1448. // cannot be positivified.
  1449. if (ConstantInt *CI = dyn_cast<ConstantInt>(Factor)) {
  1450. if (CI->isNegative() && !CI->isMinValue(true)) {
  1451. Factor = ConstantInt::get(CI->getContext(), -CI->getValue());
  1452. assert(!Duplicates.count(Factor) &&
  1453. "Shouldn't have two constant factors, missed a canonicalize");
  1454. unsigned Occ = ++FactorOccurrences[Factor];
  1455. if (Occ > MaxOcc) {
  1456. MaxOcc = Occ;
  1457. MaxOccVal = Factor;
  1458. }
  1459. }
  1460. } else if (ConstantFP *CF = dyn_cast<ConstantFP>(Factor)) {
  1461. if (CF->isNegative()) {
  1462. APFloat F(CF->getValueAPF());
  1463. F.changeSign();
  1464. Factor = ConstantFP::get(CF->getContext(), F);
  1465. assert(!Duplicates.count(Factor) &&
  1466. "Shouldn't have two constant factors, missed a canonicalize");
  1467. unsigned Occ = ++FactorOccurrences[Factor];
  1468. if (Occ > MaxOcc) {
  1469. MaxOcc = Occ;
  1470. MaxOccVal = Factor;
  1471. }
  1472. }
  1473. }
  1474. }
  1475. }
  1476. // If any factor occurred more than one time, we can pull it out.
  1477. if (MaxOcc > 1) {
  1478. DEBUG(dbgs() << "\nFACTORING [" << MaxOcc << "]: " << *MaxOccVal << '\n');
  1479. ++NumFactor;
  1480. // Create a new instruction that uses the MaxOccVal twice. If we don't do
  1481. // this, we could otherwise run into situations where removing a factor
  1482. // from an expression will drop a use of maxocc, and this can cause
  1483. // RemoveFactorFromExpression on successive values to behave differently.
  1484. Instruction *DummyInst =
  1485. I->getType()->isIntOrIntVectorTy()
  1486. ? BinaryOperator::CreateAdd(MaxOccVal, MaxOccVal)
  1487. : BinaryOperator::CreateFAdd(MaxOccVal, MaxOccVal);
  1488. SmallVector<WeakVH, 4> NewMulOps;
  1489. for (unsigned i = 0; i != Ops.size(); ++i) {
  1490. // Only try to remove factors from expressions we're allowed to.
  1491. BinaryOperator *BOp =
  1492. isReassociableOp(Ops[i].Op, Instruction::Mul, Instruction::FMul);
  1493. if (!BOp)
  1494. continue;
  1495. if (Value *V = RemoveFactorFromExpression(Ops[i].Op, MaxOccVal)) {
  1496. // The factorized operand may occur several times. Convert them all in
  1497. // one fell swoop.
  1498. for (unsigned j = Ops.size(); j != i;) {
  1499. --j;
  1500. if (Ops[j].Op == Ops[i].Op) {
  1501. NewMulOps.push_back(V);
  1502. Ops.erase(Ops.begin()+j);
  1503. }
  1504. }
  1505. --i;
  1506. }
  1507. }
  1508. // No need for extra uses anymore.
  1509. delete DummyInst;
  1510. unsigned NumAddedValues = NewMulOps.size();
  1511. Value *V = EmitAddTreeOfValues(I, NewMulOps);
  1512. // Now that we have inserted the add tree, optimize it. This allows us to
  1513. // handle cases that require multiple factoring steps, such as this:
  1514. // A*A*B + A*A*C --> A*(A*B+A*C) --> A*(A*(B+C))
  1515. assert(NumAddedValues > 1 && "Each occurrence should contribute a value");
  1516. (void)NumAddedValues;
  1517. if (Instruction *VI = dyn_cast<Instruction>(V))
  1518. RedoInsts.insert(VI);
  1519. // Create the multiply.
  1520. Instruction *V2 = CreateMul(V, MaxOccVal, "tmp", I, I);
  1521. // Rerun associate on the multiply in case the inner expression turned into
  1522. // a multiply. We want to make sure that we keep things in canonical form.
  1523. RedoInsts.insert(V2);
  1524. // If every add operand included the factor (e.g. "A*B + A*C"), then the
  1525. // entire result expression is just the multiply "A*(B+C)".
  1526. if (Ops.empty())
  1527. return V2;
  1528. // Otherwise, we had some input that didn't have the factor, such as
  1529. // "A*B + A*C + D" -> "A*(B+C) + D". Add the new multiply to the list of
  1530. // things being added by this operation.
  1531. Ops.insert(Ops.begin(), ValueEntry(getRank(V2), V2));
  1532. }
  1533. return nullptr;
  1534. }
  1535. /// \brief Build up a vector of value/power pairs factoring a product.
  1536. ///
  1537. /// Given a series of multiplication operands, build a vector of factors and
  1538. /// the powers each is raised to when forming the final product. Sort them in
  1539. /// the order of descending power.
  1540. ///
  1541. /// (x*x) -> [(x, 2)]
  1542. /// ((x*x)*x) -> [(x, 3)]
  1543. /// ((((x*y)*x)*y)*x) -> [(x, 3), (y, 2)]
  1544. ///
  1545. /// \returns Whether any factors have a power greater than one.
  1546. bool Reassociate::collectMultiplyFactors(SmallVectorImpl<ValueEntry> &Ops,
  1547. SmallVectorImpl<Factor> &Factors) {
  1548. // FIXME: Have Ops be (ValueEntry, Multiplicity) pairs, simplifying this.
  1549. // Compute the sum of powers of simplifiable factors.
  1550. unsigned FactorPowerSum = 0;
  1551. for (unsigned Idx = 1, Size = Ops.size(); Idx < Size; ++Idx) {
  1552. Value *Op = Ops[Idx-1].Op;
  1553. // Count the number of occurrences of this value.
  1554. unsigned Count = 1;
  1555. for (; Idx < Size && Ops[Idx].Op == Op; ++Idx)
  1556. ++Count;
  1557. // Track for simplification all factors which occur 2 or more times.
  1558. if (Count > 1)
  1559. FactorPowerSum += Count;
  1560. }
  1561. // We can only simplify factors if the sum of the powers of our simplifiable
  1562. // factors is 4 or higher. When that is the case, we will *always* have
  1563. // a simplification. This is an important invariant to prevent cyclicly
  1564. // trying to simplify already minimal formations.
  1565. if (FactorPowerSum < 4)
  1566. return false;
  1567. // Now gather the simplifiable factors, removing them from Ops.
  1568. FactorPowerSum = 0;
  1569. for (unsigned Idx = 1; Idx < Ops.size(); ++Idx) {
  1570. Value *Op = Ops[Idx-1].Op;
  1571. // Count the number of occurrences of this value.
  1572. unsigned Count = 1;
  1573. for (; Idx < Ops.size() && Ops[Idx].Op == Op; ++Idx)
  1574. ++Count;
  1575. if (Count == 1)
  1576. continue;
  1577. // Move an even number of occurrences to Factors.
  1578. Count &= ~1U;
  1579. Idx -= Count;
  1580. FactorPowerSum += Count;
  1581. Factors.push_back(Factor(Op, Count));
  1582. Ops.erase(Ops.begin()+Idx, Ops.begin()+Idx+Count);
  1583. }
  1584. // None of the adjustments above should have reduced the sum of factor powers
  1585. // below our mininum of '4'.
  1586. assert(FactorPowerSum >= 4);
  1587. std::stable_sort(Factors.begin(), Factors.end(), Factor::PowerDescendingSorter());
  1588. return true;
  1589. }
  1590. /// \brief Build a tree of multiplies, computing the product of Ops.
  1591. static Value *buildMultiplyTree(IRBuilder<> &Builder,
  1592. SmallVectorImpl<Value*> &Ops) {
  1593. if (Ops.size() == 1)
  1594. return Ops.back();
  1595. Value *LHS = Ops.pop_back_val();
  1596. do {
  1597. if (LHS->getType()->isIntOrIntVectorTy())
  1598. LHS = Builder.CreateMul(LHS, Ops.pop_back_val());
  1599. else
  1600. LHS = Builder.CreateFMul(LHS, Ops.pop_back_val());
  1601. } while (!Ops.empty());
  1602. return LHS;
  1603. }
  1604. /// \brief Build a minimal multiplication DAG for (a^x)*(b^y)*(c^z)*...
  1605. ///
  1606. /// Given a vector of values raised to various powers, where no two values are
  1607. /// equal and the powers are sorted in decreasing order, compute the minimal
  1608. /// DAG of multiplies to compute the final product, and return that product
  1609. /// value.
  1610. Value *Reassociate::buildMinimalMultiplyDAG(IRBuilder<> &Builder,
  1611. SmallVectorImpl<Factor> &Factors) {
  1612. assert(Factors[0].Power);
  1613. SmallVector<Value *, 4> OuterProduct;
  1614. for (unsigned LastIdx = 0, Idx = 1, Size = Factors.size();
  1615. Idx < Size && Factors[Idx].Power > 0; ++Idx) {
  1616. if (Factors[Idx].Power != Factors[LastIdx].Power) {
  1617. LastIdx = Idx;
  1618. continue;
  1619. }
  1620. // We want to multiply across all the factors with the same power so that
  1621. // we can raise them to that power as a single entity. Build a mini tree
  1622. // for that.
  1623. SmallVector<Value *, 4> InnerProduct;
  1624. InnerProduct.push_back(Factors[LastIdx].Base);
  1625. do {
  1626. InnerProduct.push_back(Factors[Idx].Base);
  1627. ++Idx;
  1628. } while (Idx < Size && Factors[Idx].Power == Factors[LastIdx].Power);
  1629. // Reset the base value of the first factor to the new expression tree.
  1630. // We'll remove all the factors with the same power in a second pass.
  1631. Value *M = Factors[LastIdx].Base = buildMultiplyTree(Builder, InnerProduct);
  1632. if (Instruction *MI = dyn_cast<Instruction>(M))
  1633. RedoInsts.insert(MI);
  1634. LastIdx = Idx;
  1635. }
  1636. // Unique factors with equal powers -- we've folded them into the first one's
  1637. // base.
  1638. Factors.erase(std::unique(Factors.begin(), Factors.end(),
  1639. Factor::PowerEqual()),
  1640. Factors.end());
  1641. // Iteratively collect the base of each factor with an add power into the
  1642. // outer product, and halve each power in preparation for squaring the
  1643. // expression.
  1644. for (unsigned Idx = 0, Size = Factors.size(); Idx != Size; ++Idx) {
  1645. if (Factors[Idx].Power & 1)
  1646. OuterProduct.push_back(Factors[Idx].Base);
  1647. Factors[Idx].Power >>= 1;
  1648. }
  1649. if (Factors[0].Power) {
  1650. Value *SquareRoot = buildMinimalMultiplyDAG(Builder, Factors);
  1651. OuterProduct.push_back(SquareRoot);
  1652. OuterProduct.push_back(SquareRoot);
  1653. }
  1654. if (OuterProduct.size() == 1)
  1655. return OuterProduct.front();
  1656. Value *V = buildMultiplyTree(Builder, OuterProduct);
  1657. return V;
  1658. }
  1659. Value *Reassociate::OptimizeMul(BinaryOperator *I,
  1660. SmallVectorImpl<ValueEntry> &Ops) {
  1661. // We can only optimize the multiplies when there is a chain of more than
  1662. // three, such that a balanced tree might require fewer total multiplies.
  1663. if (Ops.size() < 4)
  1664. return nullptr;
  1665. // Try to turn linear trees of multiplies without other uses of the
  1666. // intermediate stages into minimal multiply DAGs with perfect sub-expression
  1667. // re-use.
  1668. SmallVector<Factor, 4> Factors;
  1669. if (!collectMultiplyFactors(Ops, Factors))
  1670. return nullptr; // All distinct factors, so nothing left for us to do.
  1671. IRBuilder<> Builder(I);
  1672. Value *V = buildMinimalMultiplyDAG(Builder, Factors);
  1673. if (Ops.empty())
  1674. return V;
  1675. ValueEntry NewEntry = ValueEntry(getRank(V), V);
  1676. Ops.insert(std::lower_bound(Ops.begin(), Ops.end(), NewEntry), NewEntry);
  1677. return nullptr;
  1678. }
  1679. Value *Reassociate::OptimizeExpression(BinaryOperator *I,
  1680. SmallVectorImpl<ValueEntry> &Ops) {
  1681. // Now that we have the linearized expression tree, try to optimize it.
  1682. // Start by folding any constants that we found.
  1683. Constant *Cst = nullptr;
  1684. unsigned Opcode = I->getOpcode();
  1685. while (!Ops.empty() && isa<Constant>(Ops.back().Op)) {
  1686. Constant *C = cast<Constant>(Ops.pop_back_val().Op);
  1687. Cst = Cst ? ConstantExpr::get(Opcode, C, Cst) : C;
  1688. }
  1689. // If there was nothing but constants then we are done.
  1690. if (Ops.empty())
  1691. return Cst;
  1692. // Put the combined constant back at the end of the operand list, except if
  1693. // there is no point. For example, an add of 0 gets dropped here, while a
  1694. // multiplication by zero turns the whole expression into zero.
  1695. if (Cst && Cst != ConstantExpr::getBinOpIdentity(Opcode, I->getType())) {
  1696. if (Cst == ConstantExpr::getBinOpAbsorber(Opcode, I->getType()))
  1697. return Cst;
  1698. Ops.push_back(ValueEntry(0, Cst));
  1699. }
  1700. if (Ops.size() == 1) return Ops[0].Op;
  1701. // Handle destructive annihilation due to identities between elements in the
  1702. // argument list here.
  1703. unsigned NumOps = Ops.size();
  1704. switch (Opcode) {
  1705. default: break;
  1706. case Instruction::And:
  1707. case Instruction::Or:
  1708. if (Value *Result = OptimizeAndOrXor(Opcode, Ops))
  1709. return Result;
  1710. break;
  1711. case Instruction::Xor:
  1712. if (Value *Result = OptimizeXor(I, Ops))
  1713. return Result;
  1714. break;
  1715. case Instruction::Add:
  1716. case Instruction::FAdd:
  1717. if (Value *Result = OptimizeAdd(I, Ops))
  1718. return Result;
  1719. break;
  1720. case Instruction::Mul:
  1721. case Instruction::FMul:
  1722. if (Value *Result = OptimizeMul(I, Ops))
  1723. return Result;
  1724. break;
  1725. }
  1726. if (Ops.size() != NumOps)
  1727. return OptimizeExpression(I, Ops);
  1728. return nullptr;
  1729. }
  1730. /// Zap the given instruction, adding interesting operands to the work list.
  1731. void Reassociate::EraseInst(Instruction *I) {
  1732. assert(isInstructionTriviallyDead(I) && "Trivially dead instructions only!");
  1733. SmallVector<Value*, 8> Ops(I->op_begin(), I->op_end());
  1734. // Erase the dead instruction.
  1735. ValueRankMap.erase(I);
  1736. RedoInsts.remove(I);
  1737. I->eraseFromParent();
  1738. // Optimize its operands.
  1739. SmallPtrSet<Instruction *, 8> Visited; // Detect self-referential nodes.
  1740. for (unsigned i = 0, e = Ops.size(); i != e; ++i)
  1741. if (Instruction *Op = dyn_cast<Instruction>(Ops[i])) {
  1742. // If this is a node in an expression tree, climb to the expression root
  1743. // and add that since that's where optimization actually happens.
  1744. unsigned Opcode = Op->getOpcode();
  1745. while (Op->hasOneUse() && Op->user_back()->getOpcode() == Opcode &&
  1746. Visited.insert(Op).second)
  1747. Op = Op->user_back();
  1748. RedoInsts.insert(Op);
  1749. }
  1750. }
  1751. // Canonicalize expressions of the following form:
  1752. // x + (-Constant * y) -> x - (Constant * y)
  1753. // x - (-Constant * y) -> x + (Constant * y)
  1754. Instruction *Reassociate::canonicalizeNegConstExpr(Instruction *I) {
  1755. if (!I->hasOneUse() || I->getType()->isVectorTy())
  1756. return nullptr;
  1757. // Must be a fmul or fdiv instruction.
  1758. unsigned Opcode = I->getOpcode();
  1759. if (Opcode != Instruction::FMul && Opcode != Instruction::FDiv)
  1760. return nullptr;
  1761. auto *C0 = dyn_cast<ConstantFP>(I->getOperand(0));
  1762. auto *C1 = dyn_cast<ConstantFP>(I->getOperand(1));
  1763. // Both operands are constant, let it get constant folded away.
  1764. if (C0 && C1)
  1765. return nullptr;
  1766. ConstantFP *CF = C0 ? C0 : C1;
  1767. // Must have one constant operand.
  1768. if (!CF)
  1769. return nullptr;
  1770. // Must be a negative ConstantFP.
  1771. if (!CF->isNegative())
  1772. return nullptr;
  1773. // User must be a binary operator with one or more uses.
  1774. Instruction *User = I->user_back();
  1775. if (!isa<BinaryOperator>(User) || !User->hasNUsesOrMore(1))
  1776. return nullptr;
  1777. unsigned UserOpcode = User->getOpcode();
  1778. if (UserOpcode != Instruction::FAdd && UserOpcode != Instruction::FSub)
  1779. return nullptr;
  1780. // Subtraction is not commutative. Explicitly, the following transform is
  1781. // not valid: (-Constant * y) - x -> x + (Constant * y)
  1782. if (!User->isCommutative() && User->getOperand(1) != I)
  1783. return nullptr;
  1784. // Change the sign of the constant.
  1785. APFloat Val = CF->getValueAPF();
  1786. Val.changeSign();
  1787. I->setOperand(C0 ? 0 : 1, ConstantFP::get(CF->getContext(), Val));
  1788. // Canonicalize I to RHS to simplify the next bit of logic. E.g.,
  1789. // ((-Const*y) + x) -> (x + (-Const*y)).
  1790. if (User->getOperand(0) == I && User->isCommutative())
  1791. cast<BinaryOperator>(User)->swapOperands();
  1792. Value *Op0 = User->getOperand(0);
  1793. Value *Op1 = User->getOperand(1);
  1794. BinaryOperator *NI;
  1795. switch (UserOpcode) {
  1796. default:
  1797. llvm_unreachable("Unexpected Opcode!");
  1798. case Instruction::FAdd:
  1799. NI = BinaryOperator::CreateFSub(Op0, Op1);
  1800. NI->setFastMathFlags(cast<FPMathOperator>(User)->getFastMathFlags());
  1801. break;
  1802. case Instruction::FSub:
  1803. NI = BinaryOperator::CreateFAdd(Op0, Op1);
  1804. NI->setFastMathFlags(cast<FPMathOperator>(User)->getFastMathFlags());
  1805. break;
  1806. }
  1807. NI->insertBefore(User);
  1808. NI->setName(User->getName());
  1809. User->replaceAllUsesWith(NI);
  1810. NI->setDebugLoc(I->getDebugLoc());
  1811. RedoInsts.insert(I);
  1812. MadeChange = true;
  1813. return NI;
  1814. }
  1815. /// Inspect and optimize the given instruction. Note that erasing
  1816. /// instructions is not allowed.
  1817. void Reassociate::OptimizeInst(Instruction *I) {
  1818. // Only consider operations that we understand.
  1819. if (!isa<BinaryOperator>(I))
  1820. return;
  1821. if (I->getOpcode() == Instruction::Shl && isa<ConstantInt>(I->getOperand(1)))
  1822. // If an operand of this shift is a reassociable multiply, or if the shift
  1823. // is used by a reassociable multiply or add, turn into a multiply.
  1824. if (isReassociableOp(I->getOperand(0), Instruction::Mul) ||
  1825. (I->hasOneUse() &&
  1826. (isReassociableOp(I->user_back(), Instruction::Mul) ||
  1827. isReassociableOp(I->user_back(), Instruction::Add)))) {
  1828. Instruction *NI = ConvertShiftToMul(I);
  1829. RedoInsts.insert(I);
  1830. MadeChange = true;
  1831. I = NI;
  1832. }
  1833. // Canonicalize negative constants out of expressions.
  1834. if (Instruction *Res = canonicalizeNegConstExpr(I))
  1835. I = Res;
  1836. // Commute binary operators, to canonicalize the order of their operands.
  1837. // This can potentially expose more CSE opportunities, and makes writing other
  1838. // transformations simpler.
  1839. if (I->isCommutative())
  1840. canonicalizeOperands(I);
  1841. // TODO: We should optimize vector Xor instructions, but they are
  1842. // currently unsupported.
  1843. if (I->getType()->isVectorTy() && I->getOpcode() == Instruction::Xor)
  1844. return;
  1845. // Don't optimize floating point instructions that don't have unsafe algebra.
  1846. if (I->getType()->isFloatingPointTy() && !I->hasUnsafeAlgebra())
  1847. return;
  1848. // Do not reassociate boolean (i1) expressions. We want to preserve the
  1849. // original order of evaluation for short-circuited comparisons that
  1850. // SimplifyCFG has folded to AND/OR expressions. If the expression
  1851. // is not further optimized, it is likely to be transformed back to a
  1852. // short-circuited form for code gen, and the source order may have been
  1853. // optimized for the most likely conditions.
  1854. if (I->getType()->isIntegerTy(1))
  1855. return;
  1856. // If this is a subtract instruction which is not already in negate form,
  1857. // see if we can convert it to X+-Y.
  1858. if (I->getOpcode() == Instruction::Sub) {
  1859. if (ShouldBreakUpSubtract(I)) {
  1860. Instruction *NI = BreakUpSubtract(I);
  1861. RedoInsts.insert(I);
  1862. MadeChange = true;
  1863. I = NI;
  1864. } else if (BinaryOperator::isNeg(I)) {
  1865. // Otherwise, this is a negation. See if the operand is a multiply tree
  1866. // and if this is not an inner node of a multiply tree.
  1867. if (isReassociableOp(I->getOperand(1), Instruction::Mul) &&
  1868. (!I->hasOneUse() ||
  1869. !isReassociableOp(I->user_back(), Instruction::Mul))) {
  1870. Instruction *NI = LowerNegateToMultiply(I);
  1871. RedoInsts.insert(I);
  1872. MadeChange = true;
  1873. I = NI;
  1874. }
  1875. }
  1876. } else if (I->getOpcode() == Instruction::FSub) {
  1877. if (ShouldBreakUpSubtract(I)) {
  1878. Instruction *NI = BreakUpSubtract(I);
  1879. RedoInsts.insert(I);
  1880. MadeChange = true;
  1881. I = NI;
  1882. } else if (BinaryOperator::isFNeg(I)) {
  1883. // Otherwise, this is a negation. See if the operand is a multiply tree
  1884. // and if this is not an inner node of a multiply tree.
  1885. if (isReassociableOp(I->getOperand(1), Instruction::FMul) &&
  1886. (!I->hasOneUse() ||
  1887. !isReassociableOp(I->user_back(), Instruction::FMul))) {
  1888. Instruction *NI = LowerNegateToMultiply(I);
  1889. RedoInsts.insert(I);
  1890. MadeChange = true;
  1891. I = NI;
  1892. }
  1893. }
  1894. }
  1895. // If this instruction is an associative binary operator, process it.
  1896. if (!I->isAssociative()) return;
  1897. BinaryOperator *BO = cast<BinaryOperator>(I);
  1898. // If this is an interior node of a reassociable tree, ignore it until we
  1899. // get to the root of the tree, to avoid N^2 analysis.
  1900. unsigned Opcode = BO->getOpcode();
  1901. if (BO->hasOneUse() && BO->user_back()->getOpcode() == Opcode)
  1902. return;
  1903. // If this is an add tree that is used by a sub instruction, ignore it
  1904. // until we process the subtract.
  1905. if (BO->hasOneUse() && BO->getOpcode() == Instruction::Add &&
  1906. cast<Instruction>(BO->user_back())->getOpcode() == Instruction::Sub)
  1907. return;
  1908. if (BO->hasOneUse() && BO->getOpcode() == Instruction::FAdd &&
  1909. cast<Instruction>(BO->user_back())->getOpcode() == Instruction::FSub)
  1910. return;
  1911. ReassociateExpression(BO);
  1912. }
  1913. void Reassociate::ReassociateExpression(BinaryOperator *I) {
  1914. // First, walk the expression tree, linearizing the tree, collecting the
  1915. // operand information.
  1916. SmallVector<RepeatedValue, 8> Tree;
  1917. MadeChange |= LinearizeExprTree(I, Tree);
  1918. SmallVector<ValueEntry, 8> Ops;
  1919. Ops.reserve(Tree.size());
  1920. for (unsigned i = 0, e = Tree.size(); i != e; ++i) {
  1921. RepeatedValue E = Tree[i];
  1922. Ops.append(E.second.getZExtValue(),
  1923. ValueEntry(getRank(E.first), E.first));
  1924. }
  1925. DEBUG(dbgs() << "RAIn:\t"; PrintOps(I, Ops); dbgs() << '\n');
  1926. // Now that we have linearized the tree to a list and have gathered all of
  1927. // the operands and their ranks, sort the operands by their rank. Use a
  1928. // stable_sort so that values with equal ranks will have their relative
  1929. // positions maintained (and so the compiler is deterministic). Note that
  1930. // this sorts so that the highest ranking values end up at the beginning of
  1931. // the vector.
  1932. std::stable_sort(Ops.begin(), Ops.end());
  1933. // Now that we have the expression tree in a convenient
  1934. // sorted form, optimize it globally if possible.
  1935. if (Value *V = OptimizeExpression(I, Ops)) {
  1936. if (V == I)
  1937. // Self-referential expression in unreachable code.
  1938. return;
  1939. // This expression tree simplified to something that isn't a tree,
  1940. // eliminate it.
  1941. DEBUG(dbgs() << "Reassoc to scalar: " << *V << '\n');
  1942. I->replaceAllUsesWith(V);
  1943. if (Instruction *VI = dyn_cast<Instruction>(V))
  1944. VI->setDebugLoc(I->getDebugLoc());
  1945. RedoInsts.insert(I);
  1946. ++NumAnnihil;
  1947. return;
  1948. }
  1949. // We want to sink immediates as deeply as possible except in the case where
  1950. // this is a multiply tree used only by an add, and the immediate is a -1.
  1951. // In this case we reassociate to put the negation on the outside so that we
  1952. // can fold the negation into the add: (-X)*Y + Z -> Z-X*Y
  1953. if (I->hasOneUse()) {
  1954. if (I->getOpcode() == Instruction::Mul &&
  1955. cast<Instruction>(I->user_back())->getOpcode() == Instruction::Add &&
  1956. isa<ConstantInt>(Ops.back().Op) &&
  1957. cast<ConstantInt>(Ops.back().Op)->isAllOnesValue()) {
  1958. ValueEntry Tmp = Ops.pop_back_val();
  1959. Ops.insert(Ops.begin(), Tmp);
  1960. } else if (I->getOpcode() == Instruction::FMul &&
  1961. cast<Instruction>(I->user_back())->getOpcode() ==
  1962. Instruction::FAdd &&
  1963. isa<ConstantFP>(Ops.back().Op) &&
  1964. cast<ConstantFP>(Ops.back().Op)->isExactlyValue(-1.0)) {
  1965. ValueEntry Tmp = Ops.pop_back_val();
  1966. Ops.insert(Ops.begin(), Tmp);
  1967. }
  1968. }
  1969. DEBUG(dbgs() << "RAOut:\t"; PrintOps(I, Ops); dbgs() << '\n');
  1970. if (Ops.size() == 1) {
  1971. if (Ops[0].Op == I)
  1972. // Self-referential expression in unreachable code.
  1973. return;
  1974. // This expression tree simplified to something that isn't a tree,
  1975. // eliminate it.
  1976. I->replaceAllUsesWith(Ops[0].Op);
  1977. if (Instruction *OI = dyn_cast<Instruction>(Ops[0].Op))
  1978. OI->setDebugLoc(I->getDebugLoc());
  1979. RedoInsts.insert(I);
  1980. return;
  1981. }
  1982. // Now that we ordered and optimized the expressions, splat them back into
  1983. // the expression tree, removing any unneeded nodes.
  1984. RewriteExprTree(I, Ops);
  1985. }
  1986. bool Reassociate::runOnFunction(Function &F) {
  1987. if (skipOptnoneFunction(F))
  1988. return false;
  1989. // Calculate the rank map for F
  1990. BuildRankMap(F);
  1991. MadeChange = false;
  1992. for (Function::iterator BI = F.begin(), BE = F.end(); BI != BE; ++BI) {
  1993. // Optimize every instruction in the basic block.
  1994. for (BasicBlock::iterator II = BI->begin(), IE = BI->end(); II != IE; )
  1995. if (isInstructionTriviallyDead(II)) {
  1996. EraseInst(II++);
  1997. } else {
  1998. OptimizeInst(II);
  1999. assert(II->getParent() == BI && "Moved to a different block!");
  2000. ++II;
  2001. }
  2002. // If this produced extra instructions to optimize, handle them now.
  2003. while (!RedoInsts.empty()) {
  2004. Instruction *I = RedoInsts.pop_back_val();
  2005. if (isInstructionTriviallyDead(I))
  2006. EraseInst(I);
  2007. else
  2008. OptimizeInst(I);
  2009. }
  2010. }
  2011. // We are done with the rank map.
  2012. RankMap.clear();
  2013. ValueRankMap.clear();
  2014. return MadeChange;
  2015. }