Reassociate.cpp 99 KB

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