Reassociate.cpp 100 KB

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