PeepholeOptimizer.cpp 79 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130
  1. //===- PeepholeOptimizer.cpp - Peephole Optimizations ---------------------===//
  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. // Perform peephole optimizations on the machine code:
  10. //
  11. // - Optimize Extensions
  12. //
  13. // Optimization of sign / zero extension instructions. It may be extended to
  14. // handle other instructions with similar properties.
  15. //
  16. // On some targets, some instructions, e.g. X86 sign / zero extension, may
  17. // leave the source value in the lower part of the result. This optimization
  18. // will replace some uses of the pre-extension value with uses of the
  19. // sub-register of the results.
  20. //
  21. // - Optimize Comparisons
  22. //
  23. // Optimization of comparison instructions. For instance, in this code:
  24. //
  25. // sub r1, 1
  26. // cmp r1, 0
  27. // bz L1
  28. //
  29. // If the "sub" instruction all ready sets (or could be modified to set) the
  30. // same flag that the "cmp" instruction sets and that "bz" uses, then we can
  31. // eliminate the "cmp" instruction.
  32. //
  33. // Another instance, in this code:
  34. //
  35. // sub r1, r3 | sub r1, imm
  36. // cmp r3, r1 or cmp r1, r3 | cmp r1, imm
  37. // bge L1
  38. //
  39. // If the branch instruction can use flag from "sub", then we can replace
  40. // "sub" with "subs" and eliminate the "cmp" instruction.
  41. //
  42. // - Optimize Loads:
  43. //
  44. // Loads that can be folded into a later instruction. A load is foldable
  45. // if it loads to virtual registers and the virtual register defined has
  46. // a single use.
  47. //
  48. // - Optimize Copies and Bitcast (more generally, target specific copies):
  49. //
  50. // Rewrite copies and bitcasts to avoid cross register bank copies
  51. // when possible.
  52. // E.g., Consider the following example, where capital and lower
  53. // letters denote different register file:
  54. // b = copy A <-- cross-bank copy
  55. // C = copy b <-- cross-bank copy
  56. // =>
  57. // b = copy A <-- cross-bank copy
  58. // C = copy A <-- same-bank copy
  59. //
  60. // E.g., for bitcast:
  61. // b = bitcast A <-- cross-bank copy
  62. // C = bitcast b <-- cross-bank copy
  63. // =>
  64. // b = bitcast A <-- cross-bank copy
  65. // C = copy A <-- same-bank copy
  66. //===----------------------------------------------------------------------===//
  67. #include "llvm/ADT/DenseMap.h"
  68. #include "llvm/ADT/Optional.h"
  69. #include "llvm/ADT/SmallPtrSet.h"
  70. #include "llvm/ADT/SmallSet.h"
  71. #include "llvm/ADT/SmallVector.h"
  72. #include "llvm/ADT/Statistic.h"
  73. #include "llvm/CodeGen/MachineBasicBlock.h"
  74. #include "llvm/CodeGen/MachineDominators.h"
  75. #include "llvm/CodeGen/MachineFunction.h"
  76. #include "llvm/CodeGen/MachineFunctionPass.h"
  77. #include "llvm/CodeGen/MachineInstr.h"
  78. #include "llvm/CodeGen/MachineInstrBuilder.h"
  79. #include "llvm/CodeGen/MachineLoopInfo.h"
  80. #include "llvm/CodeGen/MachineOperand.h"
  81. #include "llvm/CodeGen/MachineRegisterInfo.h"
  82. #include "llvm/CodeGen/TargetInstrInfo.h"
  83. #include "llvm/CodeGen/TargetOpcodes.h"
  84. #include "llvm/CodeGen/TargetRegisterInfo.h"
  85. #include "llvm/CodeGen/TargetSubtargetInfo.h"
  86. #include "llvm/InitializePasses.h"
  87. #include "llvm/MC/LaneBitmask.h"
  88. #include "llvm/MC/MCInstrDesc.h"
  89. #include "llvm/Pass.h"
  90. #include "llvm/Support/CommandLine.h"
  91. #include "llvm/Support/Debug.h"
  92. #include "llvm/Support/ErrorHandling.h"
  93. #include "llvm/Support/raw_ostream.h"
  94. #include <cassert>
  95. #include <cstdint>
  96. #include <memory>
  97. #include <utility>
  98. using namespace llvm;
  99. using RegSubRegPair = TargetInstrInfo::RegSubRegPair;
  100. using RegSubRegPairAndIdx = TargetInstrInfo::RegSubRegPairAndIdx;
  101. #define DEBUG_TYPE "peephole-opt"
  102. // Optimize Extensions
  103. static cl::opt<bool>
  104. Aggressive("aggressive-ext-opt", cl::Hidden,
  105. cl::desc("Aggressive extension optimization"));
  106. static cl::opt<bool>
  107. DisablePeephole("disable-peephole", cl::Hidden, cl::init(false),
  108. cl::desc("Disable the peephole optimizer"));
  109. /// Specifiy whether or not the value tracking looks through
  110. /// complex instructions. When this is true, the value tracker
  111. /// bails on everything that is not a copy or a bitcast.
  112. static cl::opt<bool>
  113. DisableAdvCopyOpt("disable-adv-copy-opt", cl::Hidden, cl::init(false),
  114. cl::desc("Disable advanced copy optimization"));
  115. static cl::opt<bool> DisableNAPhysCopyOpt(
  116. "disable-non-allocatable-phys-copy-opt", cl::Hidden, cl::init(false),
  117. cl::desc("Disable non-allocatable physical register copy optimization"));
  118. // Limit the number of PHI instructions to process
  119. // in PeepholeOptimizer::getNextSource.
  120. static cl::opt<unsigned> RewritePHILimit(
  121. "rewrite-phi-limit", cl::Hidden, cl::init(10),
  122. cl::desc("Limit the length of PHI chains to lookup"));
  123. // Limit the length of recurrence chain when evaluating the benefit of
  124. // commuting operands.
  125. static cl::opt<unsigned> MaxRecurrenceChain(
  126. "recurrence-chain-limit", cl::Hidden, cl::init(3),
  127. cl::desc("Maximum length of recurrence chain when evaluating the benefit "
  128. "of commuting operands"));
  129. STATISTIC(NumReuse, "Number of extension results reused");
  130. STATISTIC(NumCmps, "Number of compares eliminated");
  131. STATISTIC(NumImmFold, "Number of move immediate folded");
  132. STATISTIC(NumLoadFold, "Number of loads folded");
  133. STATISTIC(NumSelects, "Number of selects optimized");
  134. STATISTIC(NumUncoalescableCopies, "Number of uncoalescable copies optimized");
  135. STATISTIC(NumRewrittenCopies, "Number of copies rewritten");
  136. STATISTIC(NumNAPhysCopies, "Number of non-allocatable physical copies removed");
  137. namespace {
  138. class ValueTrackerResult;
  139. class RecurrenceInstr;
  140. class PeepholeOptimizer : public MachineFunctionPass {
  141. const TargetInstrInfo *TII;
  142. const TargetRegisterInfo *TRI;
  143. MachineRegisterInfo *MRI;
  144. MachineDominatorTree *DT; // Machine dominator tree
  145. MachineLoopInfo *MLI;
  146. public:
  147. static char ID; // Pass identification
  148. PeepholeOptimizer() : MachineFunctionPass(ID) {
  149. initializePeepholeOptimizerPass(*PassRegistry::getPassRegistry());
  150. }
  151. bool runOnMachineFunction(MachineFunction &MF) override;
  152. void getAnalysisUsage(AnalysisUsage &AU) const override {
  153. AU.setPreservesCFG();
  154. MachineFunctionPass::getAnalysisUsage(AU);
  155. AU.addRequired<MachineLoopInfo>();
  156. AU.addPreserved<MachineLoopInfo>();
  157. if (Aggressive) {
  158. AU.addRequired<MachineDominatorTree>();
  159. AU.addPreserved<MachineDominatorTree>();
  160. }
  161. }
  162. MachineFunctionProperties getRequiredProperties() const override {
  163. return MachineFunctionProperties()
  164. .set(MachineFunctionProperties::Property::IsSSA);
  165. }
  166. /// Track Def -> Use info used for rewriting copies.
  167. using RewriteMapTy = SmallDenseMap<RegSubRegPair, ValueTrackerResult>;
  168. /// Sequence of instructions that formulate recurrence cycle.
  169. using RecurrenceCycle = SmallVector<RecurrenceInstr, 4>;
  170. private:
  171. bool optimizeCmpInstr(MachineInstr &MI);
  172. bool optimizeExtInstr(MachineInstr &MI, MachineBasicBlock &MBB,
  173. SmallPtrSetImpl<MachineInstr*> &LocalMIs);
  174. bool optimizeSelect(MachineInstr &MI,
  175. SmallPtrSetImpl<MachineInstr *> &LocalMIs);
  176. bool optimizeCondBranch(MachineInstr &MI);
  177. bool optimizeCoalescableCopy(MachineInstr &MI);
  178. bool optimizeUncoalescableCopy(MachineInstr &MI,
  179. SmallPtrSetImpl<MachineInstr *> &LocalMIs);
  180. bool optimizeRecurrence(MachineInstr &PHI);
  181. bool findNextSource(RegSubRegPair RegSubReg, RewriteMapTy &RewriteMap);
  182. bool isMoveImmediate(MachineInstr &MI, SmallSet<Register, 4> &ImmDefRegs,
  183. DenseMap<Register, MachineInstr *> &ImmDefMIs);
  184. bool foldImmediate(MachineInstr &MI, SmallSet<Register, 4> &ImmDefRegs,
  185. DenseMap<Register, MachineInstr *> &ImmDefMIs);
  186. /// Finds recurrence cycles, but only ones that formulated around
  187. /// a def operand and a use operand that are tied. If there is a use
  188. /// operand commutable with the tied use operand, find recurrence cycle
  189. /// along that operand as well.
  190. bool findTargetRecurrence(Register Reg,
  191. const SmallSet<Register, 2> &TargetReg,
  192. RecurrenceCycle &RC);
  193. /// If copy instruction \p MI is a virtual register copy, track it in
  194. /// the set \p CopyMIs. If this virtual register was previously seen as a
  195. /// copy, replace the uses of this copy with the previously seen copy's
  196. /// destination register.
  197. bool foldRedundantCopy(MachineInstr &MI,
  198. DenseMap<RegSubRegPair, MachineInstr *> &CopyMIs);
  199. /// Is the register \p Reg a non-allocatable physical register?
  200. bool isNAPhysCopy(Register Reg);
  201. /// If copy instruction \p MI is a non-allocatable virtual<->physical
  202. /// register copy, track it in the \p NAPhysToVirtMIs map. If this
  203. /// non-allocatable physical register was previously copied to a virtual
  204. /// registered and hasn't been clobbered, the virt->phys copy can be
  205. /// deleted.
  206. bool foldRedundantNAPhysCopy(
  207. MachineInstr &MI, DenseMap<Register, MachineInstr *> &NAPhysToVirtMIs);
  208. bool isLoadFoldable(MachineInstr &MI,
  209. SmallSet<Register, 16> &FoldAsLoadDefCandidates);
  210. /// Check whether \p MI is understood by the register coalescer
  211. /// but may require some rewriting.
  212. bool isCoalescableCopy(const MachineInstr &MI) {
  213. // SubregToRegs are not interesting, because they are already register
  214. // coalescer friendly.
  215. return MI.isCopy() || (!DisableAdvCopyOpt &&
  216. (MI.isRegSequence() || MI.isInsertSubreg() ||
  217. MI.isExtractSubreg()));
  218. }
  219. /// Check whether \p MI is a copy like instruction that is
  220. /// not recognized by the register coalescer.
  221. bool isUncoalescableCopy(const MachineInstr &MI) {
  222. return MI.isBitcast() ||
  223. (!DisableAdvCopyOpt &&
  224. (MI.isRegSequenceLike() || MI.isInsertSubregLike() ||
  225. MI.isExtractSubregLike()));
  226. }
  227. MachineInstr &rewriteSource(MachineInstr &CopyLike,
  228. RegSubRegPair Def, RewriteMapTy &RewriteMap);
  229. };
  230. /// Helper class to hold instructions that are inside recurrence cycles.
  231. /// The recurrence cycle is formulated around 1) a def operand and its
  232. /// tied use operand, or 2) a def operand and a use operand that is commutable
  233. /// with another use operand which is tied to the def operand. In the latter
  234. /// case, index of the tied use operand and the commutable use operand are
  235. /// maintained with CommutePair.
  236. class RecurrenceInstr {
  237. public:
  238. using IndexPair = std::pair<unsigned, unsigned>;
  239. RecurrenceInstr(MachineInstr *MI) : MI(MI) {}
  240. RecurrenceInstr(MachineInstr *MI, unsigned Idx1, unsigned Idx2)
  241. : MI(MI), CommutePair(std::make_pair(Idx1, Idx2)) {}
  242. MachineInstr *getMI() const { return MI; }
  243. Optional<IndexPair> getCommutePair() const { return CommutePair; }
  244. private:
  245. MachineInstr *MI;
  246. Optional<IndexPair> CommutePair;
  247. };
  248. /// Helper class to hold a reply for ValueTracker queries.
  249. /// Contains the returned sources for a given search and the instructions
  250. /// where the sources were tracked from.
  251. class ValueTrackerResult {
  252. private:
  253. /// Track all sources found by one ValueTracker query.
  254. SmallVector<RegSubRegPair, 2> RegSrcs;
  255. /// Instruction using the sources in 'RegSrcs'.
  256. const MachineInstr *Inst = nullptr;
  257. public:
  258. ValueTrackerResult() = default;
  259. ValueTrackerResult(Register Reg, unsigned SubReg) {
  260. addSource(Reg, SubReg);
  261. }
  262. bool isValid() const { return getNumSources() > 0; }
  263. void setInst(const MachineInstr *I) { Inst = I; }
  264. const MachineInstr *getInst() const { return Inst; }
  265. void clear() {
  266. RegSrcs.clear();
  267. Inst = nullptr;
  268. }
  269. void addSource(Register SrcReg, unsigned SrcSubReg) {
  270. RegSrcs.push_back(RegSubRegPair(SrcReg, SrcSubReg));
  271. }
  272. void setSource(int Idx, Register SrcReg, unsigned SrcSubReg) {
  273. assert(Idx < getNumSources() && "Reg pair source out of index");
  274. RegSrcs[Idx] = RegSubRegPair(SrcReg, SrcSubReg);
  275. }
  276. int getNumSources() const { return RegSrcs.size(); }
  277. RegSubRegPair getSrc(int Idx) const {
  278. return RegSrcs[Idx];
  279. }
  280. Register getSrcReg(int Idx) const {
  281. assert(Idx < getNumSources() && "Reg source out of index");
  282. return RegSrcs[Idx].Reg;
  283. }
  284. unsigned getSrcSubReg(int Idx) const {
  285. assert(Idx < getNumSources() && "SubReg source out of index");
  286. return RegSrcs[Idx].SubReg;
  287. }
  288. bool operator==(const ValueTrackerResult &Other) const {
  289. if (Other.getInst() != getInst())
  290. return false;
  291. if (Other.getNumSources() != getNumSources())
  292. return false;
  293. for (int i = 0, e = Other.getNumSources(); i != e; ++i)
  294. if (Other.getSrcReg(i) != getSrcReg(i) ||
  295. Other.getSrcSubReg(i) != getSrcSubReg(i))
  296. return false;
  297. return true;
  298. }
  299. };
  300. /// Helper class to track the possible sources of a value defined by
  301. /// a (chain of) copy related instructions.
  302. /// Given a definition (instruction and definition index), this class
  303. /// follows the use-def chain to find successive suitable sources.
  304. /// The given source can be used to rewrite the definition into
  305. /// def = COPY src.
  306. ///
  307. /// For instance, let us consider the following snippet:
  308. /// v0 =
  309. /// v2 = INSERT_SUBREG v1, v0, sub0
  310. /// def = COPY v2.sub0
  311. ///
  312. /// Using a ValueTracker for def = COPY v2.sub0 will give the following
  313. /// suitable sources:
  314. /// v2.sub0 and v0.
  315. /// Then, def can be rewritten into def = COPY v0.
  316. class ValueTracker {
  317. private:
  318. /// The current point into the use-def chain.
  319. const MachineInstr *Def = nullptr;
  320. /// The index of the definition in Def.
  321. unsigned DefIdx = 0;
  322. /// The sub register index of the definition.
  323. unsigned DefSubReg;
  324. /// The register where the value can be found.
  325. Register Reg;
  326. /// MachineRegisterInfo used to perform tracking.
  327. const MachineRegisterInfo &MRI;
  328. /// Optional TargetInstrInfo used to perform some complex tracking.
  329. const TargetInstrInfo *TII;
  330. /// Dispatcher to the right underlying implementation of getNextSource.
  331. ValueTrackerResult getNextSourceImpl();
  332. /// Specialized version of getNextSource for Copy instructions.
  333. ValueTrackerResult getNextSourceFromCopy();
  334. /// Specialized version of getNextSource for Bitcast instructions.
  335. ValueTrackerResult getNextSourceFromBitcast();
  336. /// Specialized version of getNextSource for RegSequence instructions.
  337. ValueTrackerResult getNextSourceFromRegSequence();
  338. /// Specialized version of getNextSource for InsertSubreg instructions.
  339. ValueTrackerResult getNextSourceFromInsertSubreg();
  340. /// Specialized version of getNextSource for ExtractSubreg instructions.
  341. ValueTrackerResult getNextSourceFromExtractSubreg();
  342. /// Specialized version of getNextSource for SubregToReg instructions.
  343. ValueTrackerResult getNextSourceFromSubregToReg();
  344. /// Specialized version of getNextSource for PHI instructions.
  345. ValueTrackerResult getNextSourceFromPHI();
  346. public:
  347. /// Create a ValueTracker instance for the value defined by \p Reg.
  348. /// \p DefSubReg represents the sub register index the value tracker will
  349. /// track. It does not need to match the sub register index used in the
  350. /// definition of \p Reg.
  351. /// If \p Reg is a physical register, a value tracker constructed with
  352. /// this constructor will not find any alternative source.
  353. /// Indeed, when \p Reg is a physical register that constructor does not
  354. /// know which definition of \p Reg it should track.
  355. /// Use the next constructor to track a physical register.
  356. ValueTracker(Register Reg, unsigned DefSubReg,
  357. const MachineRegisterInfo &MRI,
  358. const TargetInstrInfo *TII = nullptr)
  359. : DefSubReg(DefSubReg), Reg(Reg), MRI(MRI), TII(TII) {
  360. if (!Reg.isPhysical()) {
  361. Def = MRI.getVRegDef(Reg);
  362. DefIdx = MRI.def_begin(Reg).getOperandNo();
  363. }
  364. }
  365. /// Following the use-def chain, get the next available source
  366. /// for the tracked value.
  367. /// \return A ValueTrackerResult containing a set of registers
  368. /// and sub registers with tracked values. A ValueTrackerResult with
  369. /// an empty set of registers means no source was found.
  370. ValueTrackerResult getNextSource();
  371. };
  372. } // end anonymous namespace
  373. char PeepholeOptimizer::ID = 0;
  374. char &llvm::PeepholeOptimizerID = PeepholeOptimizer::ID;
  375. INITIALIZE_PASS_BEGIN(PeepholeOptimizer, DEBUG_TYPE,
  376. "Peephole Optimizations", false, false)
  377. INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree)
  378. INITIALIZE_PASS_DEPENDENCY(MachineLoopInfo)
  379. INITIALIZE_PASS_END(PeepholeOptimizer, DEBUG_TYPE,
  380. "Peephole Optimizations", false, false)
  381. /// If instruction is a copy-like instruction, i.e. it reads a single register
  382. /// and writes a single register and it does not modify the source, and if the
  383. /// source value is preserved as a sub-register of the result, then replace all
  384. /// reachable uses of the source with the subreg of the result.
  385. ///
  386. /// Do not generate an EXTRACT that is used only in a debug use, as this changes
  387. /// the code. Since this code does not currently share EXTRACTs, just ignore all
  388. /// debug uses.
  389. bool PeepholeOptimizer::
  390. optimizeExtInstr(MachineInstr &MI, MachineBasicBlock &MBB,
  391. SmallPtrSetImpl<MachineInstr*> &LocalMIs) {
  392. Register SrcReg, DstReg;
  393. unsigned SubIdx;
  394. if (!TII->isCoalescableExtInstr(MI, SrcReg, DstReg, SubIdx))
  395. return false;
  396. if (DstReg.isPhysical() || SrcReg.isPhysical())
  397. return false;
  398. if (MRI->hasOneNonDBGUse(SrcReg))
  399. // No other uses.
  400. return false;
  401. // Ensure DstReg can get a register class that actually supports
  402. // sub-registers. Don't change the class until we commit.
  403. const TargetRegisterClass *DstRC = MRI->getRegClass(DstReg);
  404. DstRC = TRI->getSubClassWithSubReg(DstRC, SubIdx);
  405. if (!DstRC)
  406. return false;
  407. // The ext instr may be operating on a sub-register of SrcReg as well.
  408. // PPC::EXTSW is a 32 -> 64-bit sign extension, but it reads a 64-bit
  409. // register.
  410. // If UseSrcSubIdx is Set, SubIdx also applies to SrcReg, and only uses of
  411. // SrcReg:SubIdx should be replaced.
  412. bool UseSrcSubIdx =
  413. TRI->getSubClassWithSubReg(MRI->getRegClass(SrcReg), SubIdx) != nullptr;
  414. // The source has other uses. See if we can replace the other uses with use of
  415. // the result of the extension.
  416. SmallPtrSet<MachineBasicBlock*, 4> ReachedBBs;
  417. for (MachineInstr &UI : MRI->use_nodbg_instructions(DstReg))
  418. ReachedBBs.insert(UI.getParent());
  419. // Uses that are in the same BB of uses of the result of the instruction.
  420. SmallVector<MachineOperand*, 8> Uses;
  421. // Uses that the result of the instruction can reach.
  422. SmallVector<MachineOperand*, 8> ExtendedUses;
  423. bool ExtendLife = true;
  424. for (MachineOperand &UseMO : MRI->use_nodbg_operands(SrcReg)) {
  425. MachineInstr *UseMI = UseMO.getParent();
  426. if (UseMI == &MI)
  427. continue;
  428. if (UseMI->isPHI()) {
  429. ExtendLife = false;
  430. continue;
  431. }
  432. // Only accept uses of SrcReg:SubIdx.
  433. if (UseSrcSubIdx && UseMO.getSubReg() != SubIdx)
  434. continue;
  435. // It's an error to translate this:
  436. //
  437. // %reg1025 = <sext> %reg1024
  438. // ...
  439. // %reg1026 = SUBREG_TO_REG 0, %reg1024, 4
  440. //
  441. // into this:
  442. //
  443. // %reg1025 = <sext> %reg1024
  444. // ...
  445. // %reg1027 = COPY %reg1025:4
  446. // %reg1026 = SUBREG_TO_REG 0, %reg1027, 4
  447. //
  448. // The problem here is that SUBREG_TO_REG is there to assert that an
  449. // implicit zext occurs. It doesn't insert a zext instruction. If we allow
  450. // the COPY here, it will give us the value after the <sext>, not the
  451. // original value of %reg1024 before <sext>.
  452. if (UseMI->getOpcode() == TargetOpcode::SUBREG_TO_REG)
  453. continue;
  454. MachineBasicBlock *UseMBB = UseMI->getParent();
  455. if (UseMBB == &MBB) {
  456. // Local uses that come after the extension.
  457. if (!LocalMIs.count(UseMI))
  458. Uses.push_back(&UseMO);
  459. } else if (ReachedBBs.count(UseMBB)) {
  460. // Non-local uses where the result of the extension is used. Always
  461. // replace these unless it's a PHI.
  462. Uses.push_back(&UseMO);
  463. } else if (Aggressive && DT->dominates(&MBB, UseMBB)) {
  464. // We may want to extend the live range of the extension result in order
  465. // to replace these uses.
  466. ExtendedUses.push_back(&UseMO);
  467. } else {
  468. // Both will be live out of the def MBB anyway. Don't extend live range of
  469. // the extension result.
  470. ExtendLife = false;
  471. break;
  472. }
  473. }
  474. if (ExtendLife && !ExtendedUses.empty())
  475. // Extend the liveness of the extension result.
  476. Uses.append(ExtendedUses.begin(), ExtendedUses.end());
  477. // Now replace all uses.
  478. bool Changed = false;
  479. if (!Uses.empty()) {
  480. SmallPtrSet<MachineBasicBlock*, 4> PHIBBs;
  481. // Look for PHI uses of the extended result, we don't want to extend the
  482. // liveness of a PHI input. It breaks all kinds of assumptions down
  483. // stream. A PHI use is expected to be the kill of its source values.
  484. for (MachineInstr &UI : MRI->use_nodbg_instructions(DstReg))
  485. if (UI.isPHI())
  486. PHIBBs.insert(UI.getParent());
  487. const TargetRegisterClass *RC = MRI->getRegClass(SrcReg);
  488. for (unsigned i = 0, e = Uses.size(); i != e; ++i) {
  489. MachineOperand *UseMO = Uses[i];
  490. MachineInstr *UseMI = UseMO->getParent();
  491. MachineBasicBlock *UseMBB = UseMI->getParent();
  492. if (PHIBBs.count(UseMBB))
  493. continue;
  494. // About to add uses of DstReg, clear DstReg's kill flags.
  495. if (!Changed) {
  496. MRI->clearKillFlags(DstReg);
  497. MRI->constrainRegClass(DstReg, DstRC);
  498. }
  499. // SubReg defs are illegal in machine SSA phase,
  500. // we should not generate SubReg defs.
  501. //
  502. // For example, for the instructions:
  503. //
  504. // %1:g8rc_and_g8rc_nox0 = EXTSW %0:g8rc
  505. // %3:gprc_and_gprc_nor0 = COPY %0.sub_32:g8rc
  506. //
  507. // We should generate:
  508. //
  509. // %1:g8rc_and_g8rc_nox0 = EXTSW %0:g8rc
  510. // %6:gprc_and_gprc_nor0 = COPY %1.sub_32:g8rc_and_g8rc_nox0
  511. // %3:gprc_and_gprc_nor0 = COPY %6:gprc_and_gprc_nor0
  512. //
  513. if (UseSrcSubIdx)
  514. RC = MRI->getRegClass(UseMI->getOperand(0).getReg());
  515. Register NewVR = MRI->createVirtualRegister(RC);
  516. BuildMI(*UseMBB, UseMI, UseMI->getDebugLoc(),
  517. TII->get(TargetOpcode::COPY), NewVR)
  518. .addReg(DstReg, 0, SubIdx);
  519. if (UseSrcSubIdx)
  520. UseMO->setSubReg(0);
  521. UseMO->setReg(NewVR);
  522. ++NumReuse;
  523. Changed = true;
  524. }
  525. }
  526. return Changed;
  527. }
  528. /// If the instruction is a compare and the previous instruction it's comparing
  529. /// against already sets (or could be modified to set) the same flag as the
  530. /// compare, then we can remove the comparison and use the flag from the
  531. /// previous instruction.
  532. bool PeepholeOptimizer::optimizeCmpInstr(MachineInstr &MI) {
  533. // If this instruction is a comparison against zero and isn't comparing a
  534. // physical register, we can try to optimize it.
  535. Register SrcReg, SrcReg2;
  536. int64_t CmpMask, CmpValue;
  537. if (!TII->analyzeCompare(MI, SrcReg, SrcReg2, CmpMask, CmpValue) ||
  538. SrcReg.isPhysical() || SrcReg2.isPhysical())
  539. return false;
  540. // Attempt to optimize the comparison instruction.
  541. LLVM_DEBUG(dbgs() << "Attempting to optimize compare: " << MI);
  542. if (TII->optimizeCompareInstr(MI, SrcReg, SrcReg2, CmpMask, CmpValue, MRI)) {
  543. LLVM_DEBUG(dbgs() << " -> Successfully optimized compare!\n");
  544. ++NumCmps;
  545. return true;
  546. }
  547. return false;
  548. }
  549. /// Optimize a select instruction.
  550. bool PeepholeOptimizer::optimizeSelect(MachineInstr &MI,
  551. SmallPtrSetImpl<MachineInstr *> &LocalMIs) {
  552. unsigned TrueOp = 0;
  553. unsigned FalseOp = 0;
  554. bool Optimizable = false;
  555. SmallVector<MachineOperand, 4> Cond;
  556. if (TII->analyzeSelect(MI, Cond, TrueOp, FalseOp, Optimizable))
  557. return false;
  558. if (!Optimizable)
  559. return false;
  560. if (!TII->optimizeSelect(MI, LocalMIs))
  561. return false;
  562. LLVM_DEBUG(dbgs() << "Deleting select: " << MI);
  563. MI.eraseFromParent();
  564. ++NumSelects;
  565. return true;
  566. }
  567. /// Check if a simpler conditional branch can be generated.
  568. bool PeepholeOptimizer::optimizeCondBranch(MachineInstr &MI) {
  569. return TII->optimizeCondBranch(MI);
  570. }
  571. /// Try to find the next source that share the same register file
  572. /// for the value defined by \p Reg and \p SubReg.
  573. /// When true is returned, the \p RewriteMap can be used by the client to
  574. /// retrieve all Def -> Use along the way up to the next source. Any found
  575. /// Use that is not itself a key for another entry, is the next source to
  576. /// use. During the search for the next source, multiple sources can be found
  577. /// given multiple incoming sources of a PHI instruction. In this case, we
  578. /// look in each PHI source for the next source; all found next sources must
  579. /// share the same register file as \p Reg and \p SubReg. The client should
  580. /// then be capable to rewrite all intermediate PHIs to get the next source.
  581. /// \return False if no alternative sources are available. True otherwise.
  582. bool PeepholeOptimizer::findNextSource(RegSubRegPair RegSubReg,
  583. RewriteMapTy &RewriteMap) {
  584. // Do not try to find a new source for a physical register.
  585. // So far we do not have any motivating example for doing that.
  586. // Thus, instead of maintaining untested code, we will revisit that if
  587. // that changes at some point.
  588. Register Reg = RegSubReg.Reg;
  589. if (Reg.isPhysical())
  590. return false;
  591. const TargetRegisterClass *DefRC = MRI->getRegClass(Reg);
  592. SmallVector<RegSubRegPair, 4> SrcToLook;
  593. RegSubRegPair CurSrcPair = RegSubReg;
  594. SrcToLook.push_back(CurSrcPair);
  595. unsigned PHICount = 0;
  596. do {
  597. CurSrcPair = SrcToLook.pop_back_val();
  598. // As explained above, do not handle physical registers
  599. if (Register::isPhysicalRegister(CurSrcPair.Reg))
  600. return false;
  601. ValueTracker ValTracker(CurSrcPair.Reg, CurSrcPair.SubReg, *MRI, TII);
  602. // Follow the chain of copies until we find a more suitable source, a phi
  603. // or have to abort.
  604. while (true) {
  605. ValueTrackerResult Res = ValTracker.getNextSource();
  606. // Abort at the end of a chain (without finding a suitable source).
  607. if (!Res.isValid())
  608. return false;
  609. // Insert the Def -> Use entry for the recently found source.
  610. ValueTrackerResult CurSrcRes = RewriteMap.lookup(CurSrcPair);
  611. if (CurSrcRes.isValid()) {
  612. assert(CurSrcRes == Res && "ValueTrackerResult found must match");
  613. // An existent entry with multiple sources is a PHI cycle we must avoid.
  614. // Otherwise it's an entry with a valid next source we already found.
  615. if (CurSrcRes.getNumSources() > 1) {
  616. LLVM_DEBUG(dbgs()
  617. << "findNextSource: found PHI cycle, aborting...\n");
  618. return false;
  619. }
  620. break;
  621. }
  622. RewriteMap.insert(std::make_pair(CurSrcPair, Res));
  623. // ValueTrackerResult usually have one source unless it's the result from
  624. // a PHI instruction. Add the found PHI edges to be looked up further.
  625. unsigned NumSrcs = Res.getNumSources();
  626. if (NumSrcs > 1) {
  627. PHICount++;
  628. if (PHICount >= RewritePHILimit) {
  629. LLVM_DEBUG(dbgs() << "findNextSource: PHI limit reached\n");
  630. return false;
  631. }
  632. for (unsigned i = 0; i < NumSrcs; ++i)
  633. SrcToLook.push_back(Res.getSrc(i));
  634. break;
  635. }
  636. CurSrcPair = Res.getSrc(0);
  637. // Do not extend the live-ranges of physical registers as they add
  638. // constraints to the register allocator. Moreover, if we want to extend
  639. // the live-range of a physical register, unlike SSA virtual register,
  640. // we will have to check that they aren't redefine before the related use.
  641. if (Register::isPhysicalRegister(CurSrcPair.Reg))
  642. return false;
  643. // Keep following the chain if the value isn't any better yet.
  644. const TargetRegisterClass *SrcRC = MRI->getRegClass(CurSrcPair.Reg);
  645. if (!TRI->shouldRewriteCopySrc(DefRC, RegSubReg.SubReg, SrcRC,
  646. CurSrcPair.SubReg))
  647. continue;
  648. // We currently cannot deal with subreg operands on PHI instructions
  649. // (see insertPHI()).
  650. if (PHICount > 0 && CurSrcPair.SubReg != 0)
  651. continue;
  652. // We found a suitable source, and are done with this chain.
  653. break;
  654. }
  655. } while (!SrcToLook.empty());
  656. // If we did not find a more suitable source, there is nothing to optimize.
  657. return CurSrcPair.Reg != Reg;
  658. }
  659. /// Insert a PHI instruction with incoming edges \p SrcRegs that are
  660. /// guaranteed to have the same register class. This is necessary whenever we
  661. /// successfully traverse a PHI instruction and find suitable sources coming
  662. /// from its edges. By inserting a new PHI, we provide a rewritten PHI def
  663. /// suitable to be used in a new COPY instruction.
  664. static MachineInstr &
  665. insertPHI(MachineRegisterInfo &MRI, const TargetInstrInfo &TII,
  666. const SmallVectorImpl<RegSubRegPair> &SrcRegs,
  667. MachineInstr &OrigPHI) {
  668. assert(!SrcRegs.empty() && "No sources to create a PHI instruction?");
  669. const TargetRegisterClass *NewRC = MRI.getRegClass(SrcRegs[0].Reg);
  670. // NewRC is only correct if no subregisters are involved. findNextSource()
  671. // should have rejected those cases already.
  672. assert(SrcRegs[0].SubReg == 0 && "should not have subreg operand");
  673. Register NewVR = MRI.createVirtualRegister(NewRC);
  674. MachineBasicBlock *MBB = OrigPHI.getParent();
  675. MachineInstrBuilder MIB = BuildMI(*MBB, &OrigPHI, OrigPHI.getDebugLoc(),
  676. TII.get(TargetOpcode::PHI), NewVR);
  677. unsigned MBBOpIdx = 2;
  678. for (const RegSubRegPair &RegPair : SrcRegs) {
  679. MIB.addReg(RegPair.Reg, 0, RegPair.SubReg);
  680. MIB.addMBB(OrigPHI.getOperand(MBBOpIdx).getMBB());
  681. // Since we're extended the lifetime of RegPair.Reg, clear the
  682. // kill flags to account for that and make RegPair.Reg reaches
  683. // the new PHI.
  684. MRI.clearKillFlags(RegPair.Reg);
  685. MBBOpIdx += 2;
  686. }
  687. return *MIB;
  688. }
  689. namespace {
  690. /// Interface to query instructions amenable to copy rewriting.
  691. class Rewriter {
  692. protected:
  693. MachineInstr &CopyLike;
  694. unsigned CurrentSrcIdx = 0; ///< The index of the source being rewritten.
  695. public:
  696. Rewriter(MachineInstr &CopyLike) : CopyLike(CopyLike) {}
  697. virtual ~Rewriter() {}
  698. /// Get the next rewritable source (SrcReg, SrcSubReg) and
  699. /// the related value that it affects (DstReg, DstSubReg).
  700. /// A source is considered rewritable if its register class and the
  701. /// register class of the related DstReg may not be register
  702. /// coalescer friendly. In other words, given a copy-like instruction
  703. /// not all the arguments may be returned at rewritable source, since
  704. /// some arguments are none to be register coalescer friendly.
  705. ///
  706. /// Each call of this method moves the current source to the next
  707. /// rewritable source.
  708. /// For instance, let CopyLike be the instruction to rewrite.
  709. /// CopyLike has one definition and one source:
  710. /// dst.dstSubIdx = CopyLike src.srcSubIdx.
  711. ///
  712. /// The first call will give the first rewritable source, i.e.,
  713. /// the only source this instruction has:
  714. /// (SrcReg, SrcSubReg) = (src, srcSubIdx).
  715. /// This source defines the whole definition, i.e.,
  716. /// (DstReg, DstSubReg) = (dst, dstSubIdx).
  717. ///
  718. /// The second and subsequent calls will return false, as there is only one
  719. /// rewritable source.
  720. ///
  721. /// \return True if a rewritable source has been found, false otherwise.
  722. /// The output arguments are valid if and only if true is returned.
  723. virtual bool getNextRewritableSource(RegSubRegPair &Src,
  724. RegSubRegPair &Dst) = 0;
  725. /// Rewrite the current source with \p NewReg and \p NewSubReg if possible.
  726. /// \return True if the rewriting was possible, false otherwise.
  727. virtual bool RewriteCurrentSource(Register NewReg, unsigned NewSubReg) = 0;
  728. };
  729. /// Rewriter for COPY instructions.
  730. class CopyRewriter : public Rewriter {
  731. public:
  732. CopyRewriter(MachineInstr &MI) : Rewriter(MI) {
  733. assert(MI.isCopy() && "Expected copy instruction");
  734. }
  735. virtual ~CopyRewriter() = default;
  736. bool getNextRewritableSource(RegSubRegPair &Src,
  737. RegSubRegPair &Dst) override {
  738. // CurrentSrcIdx > 0 means this function has already been called.
  739. if (CurrentSrcIdx > 0)
  740. return false;
  741. // This is the first call to getNextRewritableSource.
  742. // Move the CurrentSrcIdx to remember that we made that call.
  743. CurrentSrcIdx = 1;
  744. // The rewritable source is the argument.
  745. const MachineOperand &MOSrc = CopyLike.getOperand(1);
  746. Src = RegSubRegPair(MOSrc.getReg(), MOSrc.getSubReg());
  747. // What we track are the alternative sources of the definition.
  748. const MachineOperand &MODef = CopyLike.getOperand(0);
  749. Dst = RegSubRegPair(MODef.getReg(), MODef.getSubReg());
  750. return true;
  751. }
  752. bool RewriteCurrentSource(Register NewReg, unsigned NewSubReg) override {
  753. if (CurrentSrcIdx != 1)
  754. return false;
  755. MachineOperand &MOSrc = CopyLike.getOperand(CurrentSrcIdx);
  756. MOSrc.setReg(NewReg);
  757. MOSrc.setSubReg(NewSubReg);
  758. return true;
  759. }
  760. };
  761. /// Helper class to rewrite uncoalescable copy like instructions
  762. /// into new COPY (coalescable friendly) instructions.
  763. class UncoalescableRewriter : public Rewriter {
  764. unsigned NumDefs; ///< Number of defs in the bitcast.
  765. public:
  766. UncoalescableRewriter(MachineInstr &MI) : Rewriter(MI) {
  767. NumDefs = MI.getDesc().getNumDefs();
  768. }
  769. /// \see See Rewriter::getNextRewritableSource()
  770. /// All such sources need to be considered rewritable in order to
  771. /// rewrite a uncoalescable copy-like instruction. This method return
  772. /// each definition that must be checked if rewritable.
  773. bool getNextRewritableSource(RegSubRegPair &Src,
  774. RegSubRegPair &Dst) override {
  775. // Find the next non-dead definition and continue from there.
  776. if (CurrentSrcIdx == NumDefs)
  777. return false;
  778. while (CopyLike.getOperand(CurrentSrcIdx).isDead()) {
  779. ++CurrentSrcIdx;
  780. if (CurrentSrcIdx == NumDefs)
  781. return false;
  782. }
  783. // What we track are the alternative sources of the definition.
  784. Src = RegSubRegPair(0, 0);
  785. const MachineOperand &MODef = CopyLike.getOperand(CurrentSrcIdx);
  786. Dst = RegSubRegPair(MODef.getReg(), MODef.getSubReg());
  787. CurrentSrcIdx++;
  788. return true;
  789. }
  790. bool RewriteCurrentSource(Register NewReg, unsigned NewSubReg) override {
  791. return false;
  792. }
  793. };
  794. /// Specialized rewriter for INSERT_SUBREG instruction.
  795. class InsertSubregRewriter : public Rewriter {
  796. public:
  797. InsertSubregRewriter(MachineInstr &MI) : Rewriter(MI) {
  798. assert(MI.isInsertSubreg() && "Invalid instruction");
  799. }
  800. /// \see See Rewriter::getNextRewritableSource()
  801. /// Here CopyLike has the following form:
  802. /// dst = INSERT_SUBREG Src1, Src2.src2SubIdx, subIdx.
  803. /// Src1 has the same register class has dst, hence, there is
  804. /// nothing to rewrite.
  805. /// Src2.src2SubIdx, may not be register coalescer friendly.
  806. /// Therefore, the first call to this method returns:
  807. /// (SrcReg, SrcSubReg) = (Src2, src2SubIdx).
  808. /// (DstReg, DstSubReg) = (dst, subIdx).
  809. ///
  810. /// Subsequence calls will return false.
  811. bool getNextRewritableSource(RegSubRegPair &Src,
  812. RegSubRegPair &Dst) override {
  813. // If we already get the only source we can rewrite, return false.
  814. if (CurrentSrcIdx == 2)
  815. return false;
  816. // We are looking at v2 = INSERT_SUBREG v0, v1, sub0.
  817. CurrentSrcIdx = 2;
  818. const MachineOperand &MOInsertedReg = CopyLike.getOperand(2);
  819. Src = RegSubRegPair(MOInsertedReg.getReg(), MOInsertedReg.getSubReg());
  820. const MachineOperand &MODef = CopyLike.getOperand(0);
  821. // We want to track something that is compatible with the
  822. // partial definition.
  823. if (MODef.getSubReg())
  824. // Bail if we have to compose sub-register indices.
  825. return false;
  826. Dst = RegSubRegPair(MODef.getReg(),
  827. (unsigned)CopyLike.getOperand(3).getImm());
  828. return true;
  829. }
  830. bool RewriteCurrentSource(Register NewReg, unsigned NewSubReg) override {
  831. if (CurrentSrcIdx != 2)
  832. return false;
  833. // We are rewriting the inserted reg.
  834. MachineOperand &MO = CopyLike.getOperand(CurrentSrcIdx);
  835. MO.setReg(NewReg);
  836. MO.setSubReg(NewSubReg);
  837. return true;
  838. }
  839. };
  840. /// Specialized rewriter for EXTRACT_SUBREG instruction.
  841. class ExtractSubregRewriter : public Rewriter {
  842. const TargetInstrInfo &TII;
  843. public:
  844. ExtractSubregRewriter(MachineInstr &MI, const TargetInstrInfo &TII)
  845. : Rewriter(MI), TII(TII) {
  846. assert(MI.isExtractSubreg() && "Invalid instruction");
  847. }
  848. /// \see Rewriter::getNextRewritableSource()
  849. /// Here CopyLike has the following form:
  850. /// dst.dstSubIdx = EXTRACT_SUBREG Src, subIdx.
  851. /// There is only one rewritable source: Src.subIdx,
  852. /// which defines dst.dstSubIdx.
  853. bool getNextRewritableSource(RegSubRegPair &Src,
  854. RegSubRegPair &Dst) override {
  855. // If we already get the only source we can rewrite, return false.
  856. if (CurrentSrcIdx == 1)
  857. return false;
  858. // We are looking at v1 = EXTRACT_SUBREG v0, sub0.
  859. CurrentSrcIdx = 1;
  860. const MachineOperand &MOExtractedReg = CopyLike.getOperand(1);
  861. // If we have to compose sub-register indices, bail out.
  862. if (MOExtractedReg.getSubReg())
  863. return false;
  864. Src = RegSubRegPair(MOExtractedReg.getReg(),
  865. CopyLike.getOperand(2).getImm());
  866. // We want to track something that is compatible with the definition.
  867. const MachineOperand &MODef = CopyLike.getOperand(0);
  868. Dst = RegSubRegPair(MODef.getReg(), MODef.getSubReg());
  869. return true;
  870. }
  871. bool RewriteCurrentSource(Register NewReg, unsigned NewSubReg) override {
  872. // The only source we can rewrite is the input register.
  873. if (CurrentSrcIdx != 1)
  874. return false;
  875. CopyLike.getOperand(CurrentSrcIdx).setReg(NewReg);
  876. // If we find a source that does not require to extract something,
  877. // rewrite the operation with a copy.
  878. if (!NewSubReg) {
  879. // Move the current index to an invalid position.
  880. // We do not want another call to this method to be able
  881. // to do any change.
  882. CurrentSrcIdx = -1;
  883. // Rewrite the operation as a COPY.
  884. // Get rid of the sub-register index.
  885. CopyLike.RemoveOperand(2);
  886. // Morph the operation into a COPY.
  887. CopyLike.setDesc(TII.get(TargetOpcode::COPY));
  888. return true;
  889. }
  890. CopyLike.getOperand(CurrentSrcIdx + 1).setImm(NewSubReg);
  891. return true;
  892. }
  893. };
  894. /// Specialized rewriter for REG_SEQUENCE instruction.
  895. class RegSequenceRewriter : public Rewriter {
  896. public:
  897. RegSequenceRewriter(MachineInstr &MI) : Rewriter(MI) {
  898. assert(MI.isRegSequence() && "Invalid instruction");
  899. }
  900. /// \see Rewriter::getNextRewritableSource()
  901. /// Here CopyLike has the following form:
  902. /// dst = REG_SEQUENCE Src1.src1SubIdx, subIdx1, Src2.src2SubIdx, subIdx2.
  903. /// Each call will return a different source, walking all the available
  904. /// source.
  905. ///
  906. /// The first call returns:
  907. /// (SrcReg, SrcSubReg) = (Src1, src1SubIdx).
  908. /// (DstReg, DstSubReg) = (dst, subIdx1).
  909. ///
  910. /// The second call returns:
  911. /// (SrcReg, SrcSubReg) = (Src2, src2SubIdx).
  912. /// (DstReg, DstSubReg) = (dst, subIdx2).
  913. ///
  914. /// And so on, until all the sources have been traversed, then
  915. /// it returns false.
  916. bool getNextRewritableSource(RegSubRegPair &Src,
  917. RegSubRegPair &Dst) override {
  918. // We are looking at v0 = REG_SEQUENCE v1, sub1, v2, sub2, etc.
  919. // If this is the first call, move to the first argument.
  920. if (CurrentSrcIdx == 0) {
  921. CurrentSrcIdx = 1;
  922. } else {
  923. // Otherwise, move to the next argument and check that it is valid.
  924. CurrentSrcIdx += 2;
  925. if (CurrentSrcIdx >= CopyLike.getNumOperands())
  926. return false;
  927. }
  928. const MachineOperand &MOInsertedReg = CopyLike.getOperand(CurrentSrcIdx);
  929. Src.Reg = MOInsertedReg.getReg();
  930. // If we have to compose sub-register indices, bail out.
  931. if ((Src.SubReg = MOInsertedReg.getSubReg()))
  932. return false;
  933. // We want to track something that is compatible with the related
  934. // partial definition.
  935. Dst.SubReg = CopyLike.getOperand(CurrentSrcIdx + 1).getImm();
  936. const MachineOperand &MODef = CopyLike.getOperand(0);
  937. Dst.Reg = MODef.getReg();
  938. // If we have to compose sub-registers, bail.
  939. return MODef.getSubReg() == 0;
  940. }
  941. bool RewriteCurrentSource(Register NewReg, unsigned NewSubReg) override {
  942. // We cannot rewrite out of bound operands.
  943. // Moreover, rewritable sources are at odd positions.
  944. if ((CurrentSrcIdx & 1) != 1 || CurrentSrcIdx > CopyLike.getNumOperands())
  945. return false;
  946. MachineOperand &MO = CopyLike.getOperand(CurrentSrcIdx);
  947. MO.setReg(NewReg);
  948. MO.setSubReg(NewSubReg);
  949. return true;
  950. }
  951. };
  952. } // end anonymous namespace
  953. /// Get the appropriated Rewriter for \p MI.
  954. /// \return A pointer to a dynamically allocated Rewriter or nullptr if no
  955. /// rewriter works for \p MI.
  956. static Rewriter *getCopyRewriter(MachineInstr &MI, const TargetInstrInfo &TII) {
  957. // Handle uncoalescable copy-like instructions.
  958. if (MI.isBitcast() || MI.isRegSequenceLike() || MI.isInsertSubregLike() ||
  959. MI.isExtractSubregLike())
  960. return new UncoalescableRewriter(MI);
  961. switch (MI.getOpcode()) {
  962. default:
  963. return nullptr;
  964. case TargetOpcode::COPY:
  965. return new CopyRewriter(MI);
  966. case TargetOpcode::INSERT_SUBREG:
  967. return new InsertSubregRewriter(MI);
  968. case TargetOpcode::EXTRACT_SUBREG:
  969. return new ExtractSubregRewriter(MI, TII);
  970. case TargetOpcode::REG_SEQUENCE:
  971. return new RegSequenceRewriter(MI);
  972. }
  973. }
  974. /// Given a \p Def.Reg and Def.SubReg pair, use \p RewriteMap to find
  975. /// the new source to use for rewrite. If \p HandleMultipleSources is true and
  976. /// multiple sources for a given \p Def are found along the way, we found a
  977. /// PHI instructions that needs to be rewritten.
  978. /// TODO: HandleMultipleSources should be removed once we test PHI handling
  979. /// with coalescable copies.
  980. static RegSubRegPair
  981. getNewSource(MachineRegisterInfo *MRI, const TargetInstrInfo *TII,
  982. RegSubRegPair Def,
  983. const PeepholeOptimizer::RewriteMapTy &RewriteMap,
  984. bool HandleMultipleSources = true) {
  985. RegSubRegPair LookupSrc(Def.Reg, Def.SubReg);
  986. while (true) {
  987. ValueTrackerResult Res = RewriteMap.lookup(LookupSrc);
  988. // If there are no entries on the map, LookupSrc is the new source.
  989. if (!Res.isValid())
  990. return LookupSrc;
  991. // There's only one source for this definition, keep searching...
  992. unsigned NumSrcs = Res.getNumSources();
  993. if (NumSrcs == 1) {
  994. LookupSrc.Reg = Res.getSrcReg(0);
  995. LookupSrc.SubReg = Res.getSrcSubReg(0);
  996. continue;
  997. }
  998. // TODO: Remove once multiple srcs w/ coalescable copies are supported.
  999. if (!HandleMultipleSources)
  1000. break;
  1001. // Multiple sources, recurse into each source to find a new source
  1002. // for it. Then, rewrite the PHI accordingly to its new edges.
  1003. SmallVector<RegSubRegPair, 4> NewPHISrcs;
  1004. for (unsigned i = 0; i < NumSrcs; ++i) {
  1005. RegSubRegPair PHISrc(Res.getSrcReg(i), Res.getSrcSubReg(i));
  1006. NewPHISrcs.push_back(
  1007. getNewSource(MRI, TII, PHISrc, RewriteMap, HandleMultipleSources));
  1008. }
  1009. // Build the new PHI node and return its def register as the new source.
  1010. MachineInstr &OrigPHI = const_cast<MachineInstr &>(*Res.getInst());
  1011. MachineInstr &NewPHI = insertPHI(*MRI, *TII, NewPHISrcs, OrigPHI);
  1012. LLVM_DEBUG(dbgs() << "-- getNewSource\n");
  1013. LLVM_DEBUG(dbgs() << " Replacing: " << OrigPHI);
  1014. LLVM_DEBUG(dbgs() << " With: " << NewPHI);
  1015. const MachineOperand &MODef = NewPHI.getOperand(0);
  1016. return RegSubRegPair(MODef.getReg(), MODef.getSubReg());
  1017. }
  1018. return RegSubRegPair(0, 0);
  1019. }
  1020. /// Optimize generic copy instructions to avoid cross register bank copy.
  1021. /// The optimization looks through a chain of copies and tries to find a source
  1022. /// that has a compatible register class.
  1023. /// Two register classes are considered to be compatible if they share the same
  1024. /// register bank.
  1025. /// New copies issued by this optimization are register allocator
  1026. /// friendly. This optimization does not remove any copy as it may
  1027. /// overconstrain the register allocator, but replaces some operands
  1028. /// when possible.
  1029. /// \pre isCoalescableCopy(*MI) is true.
  1030. /// \return True, when \p MI has been rewritten. False otherwise.
  1031. bool PeepholeOptimizer::optimizeCoalescableCopy(MachineInstr &MI) {
  1032. assert(isCoalescableCopy(MI) && "Invalid argument");
  1033. assert(MI.getDesc().getNumDefs() == 1 &&
  1034. "Coalescer can understand multiple defs?!");
  1035. const MachineOperand &MODef = MI.getOperand(0);
  1036. // Do not rewrite physical definitions.
  1037. if (Register::isPhysicalRegister(MODef.getReg()))
  1038. return false;
  1039. bool Changed = false;
  1040. // Get the right rewriter for the current copy.
  1041. std::unique_ptr<Rewriter> CpyRewriter(getCopyRewriter(MI, *TII));
  1042. // If none exists, bail out.
  1043. if (!CpyRewriter)
  1044. return false;
  1045. // Rewrite each rewritable source.
  1046. RegSubRegPair Src;
  1047. RegSubRegPair TrackPair;
  1048. while (CpyRewriter->getNextRewritableSource(Src, TrackPair)) {
  1049. // Keep track of PHI nodes and its incoming edges when looking for sources.
  1050. RewriteMapTy RewriteMap;
  1051. // Try to find a more suitable source. If we failed to do so, or get the
  1052. // actual source, move to the next source.
  1053. if (!findNextSource(TrackPair, RewriteMap))
  1054. continue;
  1055. // Get the new source to rewrite. TODO: Only enable handling of multiple
  1056. // sources (PHIs) once we have a motivating example and testcases for it.
  1057. RegSubRegPair NewSrc = getNewSource(MRI, TII, TrackPair, RewriteMap,
  1058. /*HandleMultipleSources=*/false);
  1059. if (Src.Reg == NewSrc.Reg || NewSrc.Reg == 0)
  1060. continue;
  1061. // Rewrite source.
  1062. if (CpyRewriter->RewriteCurrentSource(NewSrc.Reg, NewSrc.SubReg)) {
  1063. // We may have extended the live-range of NewSrc, account for that.
  1064. MRI->clearKillFlags(NewSrc.Reg);
  1065. Changed = true;
  1066. }
  1067. }
  1068. // TODO: We could have a clean-up method to tidy the instruction.
  1069. // E.g., v0 = INSERT_SUBREG v1, v1.sub0, sub0
  1070. // => v0 = COPY v1
  1071. // Currently we haven't seen motivating example for that and we
  1072. // want to avoid untested code.
  1073. NumRewrittenCopies += Changed;
  1074. return Changed;
  1075. }
  1076. /// Rewrite the source found through \p Def, by using the \p RewriteMap
  1077. /// and create a new COPY instruction. More info about RewriteMap in
  1078. /// PeepholeOptimizer::findNextSource. Right now this is only used to handle
  1079. /// Uncoalescable copies, since they are copy like instructions that aren't
  1080. /// recognized by the register allocator.
  1081. MachineInstr &
  1082. PeepholeOptimizer::rewriteSource(MachineInstr &CopyLike,
  1083. RegSubRegPair Def, RewriteMapTy &RewriteMap) {
  1084. assert(!Register::isPhysicalRegister(Def.Reg) &&
  1085. "We do not rewrite physical registers");
  1086. // Find the new source to use in the COPY rewrite.
  1087. RegSubRegPair NewSrc = getNewSource(MRI, TII, Def, RewriteMap);
  1088. // Insert the COPY.
  1089. const TargetRegisterClass *DefRC = MRI->getRegClass(Def.Reg);
  1090. Register NewVReg = MRI->createVirtualRegister(DefRC);
  1091. MachineInstr *NewCopy =
  1092. BuildMI(*CopyLike.getParent(), &CopyLike, CopyLike.getDebugLoc(),
  1093. TII->get(TargetOpcode::COPY), NewVReg)
  1094. .addReg(NewSrc.Reg, 0, NewSrc.SubReg);
  1095. if (Def.SubReg) {
  1096. NewCopy->getOperand(0).setSubReg(Def.SubReg);
  1097. NewCopy->getOperand(0).setIsUndef();
  1098. }
  1099. LLVM_DEBUG(dbgs() << "-- RewriteSource\n");
  1100. LLVM_DEBUG(dbgs() << " Replacing: " << CopyLike);
  1101. LLVM_DEBUG(dbgs() << " With: " << *NewCopy);
  1102. MRI->replaceRegWith(Def.Reg, NewVReg);
  1103. MRI->clearKillFlags(NewVReg);
  1104. // We extended the lifetime of NewSrc.Reg, clear the kill flags to
  1105. // account for that.
  1106. MRI->clearKillFlags(NewSrc.Reg);
  1107. return *NewCopy;
  1108. }
  1109. /// Optimize copy-like instructions to create
  1110. /// register coalescer friendly instruction.
  1111. /// The optimization tries to kill-off the \p MI by looking
  1112. /// through a chain of copies to find a source that has a compatible
  1113. /// register class.
  1114. /// If such a source is found, it replace \p MI by a generic COPY
  1115. /// operation.
  1116. /// \pre isUncoalescableCopy(*MI) is true.
  1117. /// \return True, when \p MI has been optimized. In that case, \p MI has
  1118. /// been removed from its parent.
  1119. /// All COPY instructions created, are inserted in \p LocalMIs.
  1120. bool PeepholeOptimizer::optimizeUncoalescableCopy(
  1121. MachineInstr &MI, SmallPtrSetImpl<MachineInstr *> &LocalMIs) {
  1122. assert(isUncoalescableCopy(MI) && "Invalid argument");
  1123. UncoalescableRewriter CpyRewriter(MI);
  1124. // Rewrite each rewritable source by generating new COPYs. This works
  1125. // differently from optimizeCoalescableCopy since it first makes sure that all
  1126. // definitions can be rewritten.
  1127. RewriteMapTy RewriteMap;
  1128. RegSubRegPair Src;
  1129. RegSubRegPair Def;
  1130. SmallVector<RegSubRegPair, 4> RewritePairs;
  1131. while (CpyRewriter.getNextRewritableSource(Src, Def)) {
  1132. // If a physical register is here, this is probably for a good reason.
  1133. // Do not rewrite that.
  1134. if (Register::isPhysicalRegister(Def.Reg))
  1135. return false;
  1136. // If we do not know how to rewrite this definition, there is no point
  1137. // in trying to kill this instruction.
  1138. if (!findNextSource(Def, RewriteMap))
  1139. return false;
  1140. RewritePairs.push_back(Def);
  1141. }
  1142. // The change is possible for all defs, do it.
  1143. for (const RegSubRegPair &Def : RewritePairs) {
  1144. // Rewrite the "copy" in a way the register coalescer understands.
  1145. MachineInstr &NewCopy = rewriteSource(MI, Def, RewriteMap);
  1146. LocalMIs.insert(&NewCopy);
  1147. }
  1148. // MI is now dead.
  1149. LLVM_DEBUG(dbgs() << "Deleting uncoalescable copy: " << MI);
  1150. MI.eraseFromParent();
  1151. ++NumUncoalescableCopies;
  1152. return true;
  1153. }
  1154. /// Check whether MI is a candidate for folding into a later instruction.
  1155. /// We only fold loads to virtual registers and the virtual register defined
  1156. /// has a single user.
  1157. bool PeepholeOptimizer::isLoadFoldable(
  1158. MachineInstr &MI, SmallSet<Register, 16> &FoldAsLoadDefCandidates) {
  1159. if (!MI.canFoldAsLoad() || !MI.mayLoad())
  1160. return false;
  1161. const MCInstrDesc &MCID = MI.getDesc();
  1162. if (MCID.getNumDefs() != 1)
  1163. return false;
  1164. Register Reg = MI.getOperand(0).getReg();
  1165. // To reduce compilation time, we check MRI->hasOneNonDBGUser when inserting
  1166. // loads. It should be checked when processing uses of the load, since
  1167. // uses can be removed during peephole.
  1168. if (Reg.isVirtual() && !MI.getOperand(0).getSubReg() &&
  1169. MRI->hasOneNonDBGUser(Reg)) {
  1170. FoldAsLoadDefCandidates.insert(Reg);
  1171. return true;
  1172. }
  1173. return false;
  1174. }
  1175. bool PeepholeOptimizer::isMoveImmediate(
  1176. MachineInstr &MI, SmallSet<Register, 4> &ImmDefRegs,
  1177. DenseMap<Register, MachineInstr *> &ImmDefMIs) {
  1178. const MCInstrDesc &MCID = MI.getDesc();
  1179. if (!MI.isMoveImmediate())
  1180. return false;
  1181. if (MCID.getNumDefs() != 1)
  1182. return false;
  1183. Register Reg = MI.getOperand(0).getReg();
  1184. if (Reg.isVirtual()) {
  1185. ImmDefMIs.insert(std::make_pair(Reg, &MI));
  1186. ImmDefRegs.insert(Reg);
  1187. return true;
  1188. }
  1189. return false;
  1190. }
  1191. /// Try folding register operands that are defined by move immediate
  1192. /// instructions, i.e. a trivial constant folding optimization, if
  1193. /// and only if the def and use are in the same BB.
  1194. bool PeepholeOptimizer::foldImmediate(
  1195. MachineInstr &MI, SmallSet<Register, 4> &ImmDefRegs,
  1196. DenseMap<Register, MachineInstr *> &ImmDefMIs) {
  1197. for (unsigned i = 0, e = MI.getDesc().getNumOperands(); i != e; ++i) {
  1198. MachineOperand &MO = MI.getOperand(i);
  1199. if (!MO.isReg() || MO.isDef())
  1200. continue;
  1201. Register Reg = MO.getReg();
  1202. if (!Reg.isVirtual())
  1203. continue;
  1204. if (ImmDefRegs.count(Reg) == 0)
  1205. continue;
  1206. DenseMap<Register, MachineInstr *>::iterator II = ImmDefMIs.find(Reg);
  1207. assert(II != ImmDefMIs.end() && "couldn't find immediate definition");
  1208. if (TII->FoldImmediate(MI, *II->second, Reg, MRI)) {
  1209. ++NumImmFold;
  1210. return true;
  1211. }
  1212. }
  1213. return false;
  1214. }
  1215. // FIXME: This is very simple and misses some cases which should be handled when
  1216. // motivating examples are found.
  1217. //
  1218. // The copy rewriting logic should look at uses as well as defs and be able to
  1219. // eliminate copies across blocks.
  1220. //
  1221. // Later copies that are subregister extracts will also not be eliminated since
  1222. // only the first copy is considered.
  1223. //
  1224. // e.g.
  1225. // %1 = COPY %0
  1226. // %2 = COPY %0:sub1
  1227. //
  1228. // Should replace %2 uses with %1:sub1
  1229. bool PeepholeOptimizer::foldRedundantCopy(
  1230. MachineInstr &MI, DenseMap<RegSubRegPair, MachineInstr *> &CopyMIs) {
  1231. assert(MI.isCopy() && "expected a COPY machine instruction");
  1232. Register SrcReg = MI.getOperand(1).getReg();
  1233. unsigned SrcSubReg = MI.getOperand(1).getSubReg();
  1234. if (!SrcReg.isVirtual())
  1235. return false;
  1236. Register DstReg = MI.getOperand(0).getReg();
  1237. if (!DstReg.isVirtual())
  1238. return false;
  1239. RegSubRegPair SrcPair(SrcReg, SrcSubReg);
  1240. if (CopyMIs.insert(std::make_pair(SrcPair, &MI)).second) {
  1241. // First copy of this reg seen.
  1242. return false;
  1243. }
  1244. MachineInstr *PrevCopy = CopyMIs.find(SrcPair)->second;
  1245. assert(SrcSubReg == PrevCopy->getOperand(1).getSubReg() &&
  1246. "Unexpected mismatching subreg!");
  1247. Register PrevDstReg = PrevCopy->getOperand(0).getReg();
  1248. // Only replace if the copy register class is the same.
  1249. //
  1250. // TODO: If we have multiple copies to different register classes, we may want
  1251. // to track multiple copies of the same source register.
  1252. if (MRI->getRegClass(DstReg) != MRI->getRegClass(PrevDstReg))
  1253. return false;
  1254. MRI->replaceRegWith(DstReg, PrevDstReg);
  1255. // Lifetime of the previous copy has been extended.
  1256. MRI->clearKillFlags(PrevDstReg);
  1257. return true;
  1258. }
  1259. bool PeepholeOptimizer::isNAPhysCopy(Register Reg) {
  1260. return Reg.isPhysical() && !MRI->isAllocatable(Reg);
  1261. }
  1262. bool PeepholeOptimizer::foldRedundantNAPhysCopy(
  1263. MachineInstr &MI, DenseMap<Register, MachineInstr *> &NAPhysToVirtMIs) {
  1264. assert(MI.isCopy() && "expected a COPY machine instruction");
  1265. if (DisableNAPhysCopyOpt)
  1266. return false;
  1267. Register DstReg = MI.getOperand(0).getReg();
  1268. Register SrcReg = MI.getOperand(1).getReg();
  1269. if (isNAPhysCopy(SrcReg) && Register::isVirtualRegister(DstReg)) {
  1270. // %vreg = COPY $physreg
  1271. // Avoid using a datastructure which can track multiple live non-allocatable
  1272. // phys->virt copies since LLVM doesn't seem to do this.
  1273. NAPhysToVirtMIs.insert({SrcReg, &MI});
  1274. return false;
  1275. }
  1276. if (!(SrcReg.isVirtual() && isNAPhysCopy(DstReg)))
  1277. return false;
  1278. // $physreg = COPY %vreg
  1279. auto PrevCopy = NAPhysToVirtMIs.find(DstReg);
  1280. if (PrevCopy == NAPhysToVirtMIs.end()) {
  1281. // We can't remove the copy: there was an intervening clobber of the
  1282. // non-allocatable physical register after the copy to virtual.
  1283. LLVM_DEBUG(dbgs() << "NAPhysCopy: intervening clobber forbids erasing "
  1284. << MI);
  1285. return false;
  1286. }
  1287. Register PrevDstReg = PrevCopy->second->getOperand(0).getReg();
  1288. if (PrevDstReg == SrcReg) {
  1289. // Remove the virt->phys copy: we saw the virtual register definition, and
  1290. // the non-allocatable physical register's state hasn't changed since then.
  1291. LLVM_DEBUG(dbgs() << "NAPhysCopy: erasing " << MI);
  1292. ++NumNAPhysCopies;
  1293. return true;
  1294. }
  1295. // Potential missed optimization opportunity: we saw a different virtual
  1296. // register get a copy of the non-allocatable physical register, and we only
  1297. // track one such copy. Avoid getting confused by this new non-allocatable
  1298. // physical register definition, and remove it from the tracked copies.
  1299. LLVM_DEBUG(dbgs() << "NAPhysCopy: missed opportunity " << MI);
  1300. NAPhysToVirtMIs.erase(PrevCopy);
  1301. return false;
  1302. }
  1303. /// \bried Returns true if \p MO is a virtual register operand.
  1304. static bool isVirtualRegisterOperand(MachineOperand &MO) {
  1305. return MO.isReg() && MO.getReg().isVirtual();
  1306. }
  1307. bool PeepholeOptimizer::findTargetRecurrence(
  1308. Register Reg, const SmallSet<Register, 2> &TargetRegs,
  1309. RecurrenceCycle &RC) {
  1310. // Recurrence found if Reg is in TargetRegs.
  1311. if (TargetRegs.count(Reg))
  1312. return true;
  1313. // TODO: Curerntly, we only allow the last instruction of the recurrence
  1314. // cycle (the instruction that feeds the PHI instruction) to have more than
  1315. // one uses to guarantee that commuting operands does not tie registers
  1316. // with overlapping live range. Once we have actual live range info of
  1317. // each register, this constraint can be relaxed.
  1318. if (!MRI->hasOneNonDBGUse(Reg))
  1319. return false;
  1320. // Give up if the reccurrence chain length is longer than the limit.
  1321. if (RC.size() >= MaxRecurrenceChain)
  1322. return false;
  1323. MachineInstr &MI = *(MRI->use_instr_nodbg_begin(Reg));
  1324. unsigned Idx = MI.findRegisterUseOperandIdx(Reg);
  1325. // Only interested in recurrences whose instructions have only one def, which
  1326. // is a virtual register.
  1327. if (MI.getDesc().getNumDefs() != 1)
  1328. return false;
  1329. MachineOperand &DefOp = MI.getOperand(0);
  1330. if (!isVirtualRegisterOperand(DefOp))
  1331. return false;
  1332. // Check if def operand of MI is tied to any use operand. We are only
  1333. // interested in the case that all the instructions in the recurrence chain
  1334. // have there def operand tied with one of the use operand.
  1335. unsigned TiedUseIdx;
  1336. if (!MI.isRegTiedToUseOperand(0, &TiedUseIdx))
  1337. return false;
  1338. if (Idx == TiedUseIdx) {
  1339. RC.push_back(RecurrenceInstr(&MI));
  1340. return findTargetRecurrence(DefOp.getReg(), TargetRegs, RC);
  1341. } else {
  1342. // If Idx is not TiedUseIdx, check if Idx is commutable with TiedUseIdx.
  1343. unsigned CommIdx = TargetInstrInfo::CommuteAnyOperandIndex;
  1344. if (TII->findCommutedOpIndices(MI, Idx, CommIdx) && CommIdx == TiedUseIdx) {
  1345. RC.push_back(RecurrenceInstr(&MI, Idx, CommIdx));
  1346. return findTargetRecurrence(DefOp.getReg(), TargetRegs, RC);
  1347. }
  1348. }
  1349. return false;
  1350. }
  1351. /// Phi instructions will eventually be lowered to copy instructions.
  1352. /// If phi is in a loop header, a recurrence may formulated around the source
  1353. /// and destination of the phi. For such case commuting operands of the
  1354. /// instructions in the recurrence may enable coalescing of the copy instruction
  1355. /// generated from the phi. For example, if there is a recurrence of
  1356. ///
  1357. /// LoopHeader:
  1358. /// %1 = phi(%0, %100)
  1359. /// LoopLatch:
  1360. /// %0<def, tied1> = ADD %2<def, tied0>, %1
  1361. ///
  1362. /// , the fact that %0 and %2 are in the same tied operands set makes
  1363. /// the coalescing of copy instruction generated from the phi in
  1364. /// LoopHeader(i.e. %1 = COPY %0) impossible, because %1 and
  1365. /// %2 have overlapping live range. This introduces additional move
  1366. /// instruction to the final assembly. However, if we commute %2 and
  1367. /// %1 of ADD instruction, the redundant move instruction can be
  1368. /// avoided.
  1369. bool PeepholeOptimizer::optimizeRecurrence(MachineInstr &PHI) {
  1370. SmallSet<Register, 2> TargetRegs;
  1371. for (unsigned Idx = 1; Idx < PHI.getNumOperands(); Idx += 2) {
  1372. MachineOperand &MO = PHI.getOperand(Idx);
  1373. assert(isVirtualRegisterOperand(MO) && "Invalid PHI instruction");
  1374. TargetRegs.insert(MO.getReg());
  1375. }
  1376. bool Changed = false;
  1377. RecurrenceCycle RC;
  1378. if (findTargetRecurrence(PHI.getOperand(0).getReg(), TargetRegs, RC)) {
  1379. // Commutes operands of instructions in RC if necessary so that the copy to
  1380. // be generated from PHI can be coalesced.
  1381. LLVM_DEBUG(dbgs() << "Optimize recurrence chain from " << PHI);
  1382. for (auto &RI : RC) {
  1383. LLVM_DEBUG(dbgs() << "\tInst: " << *(RI.getMI()));
  1384. auto CP = RI.getCommutePair();
  1385. if (CP) {
  1386. Changed = true;
  1387. TII->commuteInstruction(*(RI.getMI()), false, (*CP).first,
  1388. (*CP).second);
  1389. LLVM_DEBUG(dbgs() << "\t\tCommuted: " << *(RI.getMI()));
  1390. }
  1391. }
  1392. }
  1393. return Changed;
  1394. }
  1395. bool PeepholeOptimizer::runOnMachineFunction(MachineFunction &MF) {
  1396. if (skipFunction(MF.getFunction()))
  1397. return false;
  1398. LLVM_DEBUG(dbgs() << "********** PEEPHOLE OPTIMIZER **********\n");
  1399. LLVM_DEBUG(dbgs() << "********** Function: " << MF.getName() << '\n');
  1400. if (DisablePeephole)
  1401. return false;
  1402. TII = MF.getSubtarget().getInstrInfo();
  1403. TRI = MF.getSubtarget().getRegisterInfo();
  1404. MRI = &MF.getRegInfo();
  1405. DT = Aggressive ? &getAnalysis<MachineDominatorTree>() : nullptr;
  1406. MLI = &getAnalysis<MachineLoopInfo>();
  1407. bool Changed = false;
  1408. for (MachineBasicBlock &MBB : MF) {
  1409. bool SeenMoveImm = false;
  1410. // During this forward scan, at some point it needs to answer the question
  1411. // "given a pointer to an MI in the current BB, is it located before or
  1412. // after the current instruction".
  1413. // To perform this, the following set keeps track of the MIs already seen
  1414. // during the scan, if a MI is not in the set, it is assumed to be located
  1415. // after. Newly created MIs have to be inserted in the set as well.
  1416. SmallPtrSet<MachineInstr*, 16> LocalMIs;
  1417. SmallSet<Register, 4> ImmDefRegs;
  1418. DenseMap<Register, MachineInstr *> ImmDefMIs;
  1419. SmallSet<Register, 16> FoldAsLoadDefCandidates;
  1420. // Track when a non-allocatable physical register is copied to a virtual
  1421. // register so that useless moves can be removed.
  1422. //
  1423. // $physreg is the map index; MI is the last valid `%vreg = COPY $physreg`
  1424. // without any intervening re-definition of $physreg.
  1425. DenseMap<Register, MachineInstr *> NAPhysToVirtMIs;
  1426. // Set of pairs of virtual registers and their subregs that are copied
  1427. // from.
  1428. DenseMap<RegSubRegPair, MachineInstr *> CopySrcMIs;
  1429. bool IsLoopHeader = MLI->isLoopHeader(&MBB);
  1430. for (MachineBasicBlock::iterator MII = MBB.begin(), MIE = MBB.end();
  1431. MII != MIE; ) {
  1432. MachineInstr *MI = &*MII;
  1433. // We may be erasing MI below, increment MII now.
  1434. ++MII;
  1435. LocalMIs.insert(MI);
  1436. // Skip debug instructions. They should not affect this peephole
  1437. // optimization.
  1438. if (MI->isDebugInstr())
  1439. continue;
  1440. if (MI->isPosition())
  1441. continue;
  1442. if (IsLoopHeader && MI->isPHI()) {
  1443. if (optimizeRecurrence(*MI)) {
  1444. Changed = true;
  1445. continue;
  1446. }
  1447. }
  1448. if (!MI->isCopy()) {
  1449. for (const MachineOperand &MO : MI->operands()) {
  1450. // Visit all operands: definitions can be implicit or explicit.
  1451. if (MO.isReg()) {
  1452. Register Reg = MO.getReg();
  1453. if (MO.isDef() && isNAPhysCopy(Reg)) {
  1454. const auto &Def = NAPhysToVirtMIs.find(Reg);
  1455. if (Def != NAPhysToVirtMIs.end()) {
  1456. // A new definition of the non-allocatable physical register
  1457. // invalidates previous copies.
  1458. LLVM_DEBUG(dbgs()
  1459. << "NAPhysCopy: invalidating because of " << *MI);
  1460. NAPhysToVirtMIs.erase(Def);
  1461. }
  1462. }
  1463. } else if (MO.isRegMask()) {
  1464. const uint32_t *RegMask = MO.getRegMask();
  1465. for (auto &RegMI : NAPhysToVirtMIs) {
  1466. Register Def = RegMI.first;
  1467. if (MachineOperand::clobbersPhysReg(RegMask, Def)) {
  1468. LLVM_DEBUG(dbgs()
  1469. << "NAPhysCopy: invalidating because of " << *MI);
  1470. NAPhysToVirtMIs.erase(Def);
  1471. }
  1472. }
  1473. }
  1474. }
  1475. }
  1476. if (MI->isImplicitDef() || MI->isKill())
  1477. continue;
  1478. if (MI->isInlineAsm() || MI->hasUnmodeledSideEffects()) {
  1479. // Blow away all non-allocatable physical registers knowledge since we
  1480. // don't know what's correct anymore.
  1481. //
  1482. // FIXME: handle explicit asm clobbers.
  1483. LLVM_DEBUG(dbgs() << "NAPhysCopy: blowing away all info due to "
  1484. << *MI);
  1485. NAPhysToVirtMIs.clear();
  1486. }
  1487. if ((isUncoalescableCopy(*MI) &&
  1488. optimizeUncoalescableCopy(*MI, LocalMIs)) ||
  1489. (MI->isCompare() && optimizeCmpInstr(*MI)) ||
  1490. (MI->isSelect() && optimizeSelect(*MI, LocalMIs))) {
  1491. // MI is deleted.
  1492. LocalMIs.erase(MI);
  1493. Changed = true;
  1494. continue;
  1495. }
  1496. if (MI->isConditionalBranch() && optimizeCondBranch(*MI)) {
  1497. Changed = true;
  1498. continue;
  1499. }
  1500. if (isCoalescableCopy(*MI) && optimizeCoalescableCopy(*MI)) {
  1501. // MI is just rewritten.
  1502. Changed = true;
  1503. continue;
  1504. }
  1505. if (MI->isCopy() && (foldRedundantCopy(*MI, CopySrcMIs) ||
  1506. foldRedundantNAPhysCopy(*MI, NAPhysToVirtMIs))) {
  1507. LocalMIs.erase(MI);
  1508. LLVM_DEBUG(dbgs() << "Deleting redundant copy: " << *MI << "\n");
  1509. MI->eraseFromParent();
  1510. Changed = true;
  1511. continue;
  1512. }
  1513. if (isMoveImmediate(*MI, ImmDefRegs, ImmDefMIs)) {
  1514. SeenMoveImm = true;
  1515. } else {
  1516. Changed |= optimizeExtInstr(*MI, MBB, LocalMIs);
  1517. // optimizeExtInstr might have created new instructions after MI
  1518. // and before the already incremented MII. Adjust MII so that the
  1519. // next iteration sees the new instructions.
  1520. MII = MI;
  1521. ++MII;
  1522. if (SeenMoveImm)
  1523. Changed |= foldImmediate(*MI, ImmDefRegs, ImmDefMIs);
  1524. }
  1525. // Check whether MI is a load candidate for folding into a later
  1526. // instruction. If MI is not a candidate, check whether we can fold an
  1527. // earlier load into MI.
  1528. if (!isLoadFoldable(*MI, FoldAsLoadDefCandidates) &&
  1529. !FoldAsLoadDefCandidates.empty()) {
  1530. // We visit each operand even after successfully folding a previous
  1531. // one. This allows us to fold multiple loads into a single
  1532. // instruction. We do assume that optimizeLoadInstr doesn't insert
  1533. // foldable uses earlier in the argument list. Since we don't restart
  1534. // iteration, we'd miss such cases.
  1535. const MCInstrDesc &MIDesc = MI->getDesc();
  1536. for (unsigned i = MIDesc.getNumDefs(); i != MI->getNumOperands();
  1537. ++i) {
  1538. const MachineOperand &MOp = MI->getOperand(i);
  1539. if (!MOp.isReg())
  1540. continue;
  1541. Register FoldAsLoadDefReg = MOp.getReg();
  1542. if (FoldAsLoadDefCandidates.count(FoldAsLoadDefReg)) {
  1543. // We need to fold load after optimizeCmpInstr, since
  1544. // optimizeCmpInstr can enable folding by converting SUB to CMP.
  1545. // Save FoldAsLoadDefReg because optimizeLoadInstr() resets it and
  1546. // we need it for markUsesInDebugValueAsUndef().
  1547. Register FoldedReg = FoldAsLoadDefReg;
  1548. MachineInstr *DefMI = nullptr;
  1549. if (MachineInstr *FoldMI =
  1550. TII->optimizeLoadInstr(*MI, MRI, FoldAsLoadDefReg, DefMI)) {
  1551. // Update LocalMIs since we replaced MI with FoldMI and deleted
  1552. // DefMI.
  1553. LLVM_DEBUG(dbgs() << "Replacing: " << *MI);
  1554. LLVM_DEBUG(dbgs() << " With: " << *FoldMI);
  1555. LocalMIs.erase(MI);
  1556. LocalMIs.erase(DefMI);
  1557. LocalMIs.insert(FoldMI);
  1558. // Update the call site info.
  1559. if (MI->shouldUpdateCallSiteInfo())
  1560. MI->getMF()->moveCallSiteInfo(MI, FoldMI);
  1561. MI->eraseFromParent();
  1562. DefMI->eraseFromParent();
  1563. MRI->markUsesInDebugValueAsUndef(FoldedReg);
  1564. FoldAsLoadDefCandidates.erase(FoldedReg);
  1565. ++NumLoadFold;
  1566. // MI is replaced with FoldMI so we can continue trying to fold
  1567. Changed = true;
  1568. MI = FoldMI;
  1569. }
  1570. }
  1571. }
  1572. }
  1573. // If we run into an instruction we can't fold across, discard
  1574. // the load candidates. Note: We might be able to fold *into* this
  1575. // instruction, so this needs to be after the folding logic.
  1576. if (MI->isLoadFoldBarrier()) {
  1577. LLVM_DEBUG(dbgs() << "Encountered load fold barrier on " << *MI);
  1578. FoldAsLoadDefCandidates.clear();
  1579. }
  1580. }
  1581. }
  1582. return Changed;
  1583. }
  1584. ValueTrackerResult ValueTracker::getNextSourceFromCopy() {
  1585. assert(Def->isCopy() && "Invalid definition");
  1586. // Copy instruction are supposed to be: Def = Src.
  1587. // If someone breaks this assumption, bad things will happen everywhere.
  1588. // There may be implicit uses preventing the copy to be moved across
  1589. // some target specific register definitions
  1590. assert(Def->getNumOperands() - Def->getNumImplicitOperands() == 2 &&
  1591. "Invalid number of operands");
  1592. assert(!Def->hasImplicitDef() && "Only implicit uses are allowed");
  1593. if (Def->getOperand(DefIdx).getSubReg() != DefSubReg)
  1594. // If we look for a different subreg, it means we want a subreg of src.
  1595. // Bails as we do not support composing subregs yet.
  1596. return ValueTrackerResult();
  1597. // Otherwise, we want the whole source.
  1598. const MachineOperand &Src = Def->getOperand(1);
  1599. if (Src.isUndef())
  1600. return ValueTrackerResult();
  1601. return ValueTrackerResult(Src.getReg(), Src.getSubReg());
  1602. }
  1603. ValueTrackerResult ValueTracker::getNextSourceFromBitcast() {
  1604. assert(Def->isBitcast() && "Invalid definition");
  1605. // Bail if there are effects that a plain copy will not expose.
  1606. if (Def->mayRaiseFPException() || Def->hasUnmodeledSideEffects())
  1607. return ValueTrackerResult();
  1608. // Bitcasts with more than one def are not supported.
  1609. if (Def->getDesc().getNumDefs() != 1)
  1610. return ValueTrackerResult();
  1611. const MachineOperand DefOp = Def->getOperand(DefIdx);
  1612. if (DefOp.getSubReg() != DefSubReg)
  1613. // If we look for a different subreg, it means we want a subreg of the src.
  1614. // Bails as we do not support composing subregs yet.
  1615. return ValueTrackerResult();
  1616. unsigned SrcIdx = Def->getNumOperands();
  1617. for (unsigned OpIdx = DefIdx + 1, EndOpIdx = SrcIdx; OpIdx != EndOpIdx;
  1618. ++OpIdx) {
  1619. const MachineOperand &MO = Def->getOperand(OpIdx);
  1620. if (!MO.isReg() || !MO.getReg())
  1621. continue;
  1622. // Ignore dead implicit defs.
  1623. if (MO.isImplicit() && MO.isDead())
  1624. continue;
  1625. assert(!MO.isDef() && "We should have skipped all the definitions by now");
  1626. if (SrcIdx != EndOpIdx)
  1627. // Multiple sources?
  1628. return ValueTrackerResult();
  1629. SrcIdx = OpIdx;
  1630. }
  1631. // In some rare case, Def has no input, SrcIdx is out of bound,
  1632. // getOperand(SrcIdx) will fail below.
  1633. if (SrcIdx >= Def->getNumOperands())
  1634. return ValueTrackerResult();
  1635. // Stop when any user of the bitcast is a SUBREG_TO_REG, replacing with a COPY
  1636. // will break the assumed guarantees for the upper bits.
  1637. for (const MachineInstr &UseMI : MRI.use_nodbg_instructions(DefOp.getReg())) {
  1638. if (UseMI.isSubregToReg())
  1639. return ValueTrackerResult();
  1640. }
  1641. const MachineOperand &Src = Def->getOperand(SrcIdx);
  1642. if (Src.isUndef())
  1643. return ValueTrackerResult();
  1644. return ValueTrackerResult(Src.getReg(), Src.getSubReg());
  1645. }
  1646. ValueTrackerResult ValueTracker::getNextSourceFromRegSequence() {
  1647. assert((Def->isRegSequence() || Def->isRegSequenceLike()) &&
  1648. "Invalid definition");
  1649. if (Def->getOperand(DefIdx).getSubReg())
  1650. // If we are composing subregs, bail out.
  1651. // The case we are checking is Def.<subreg> = REG_SEQUENCE.
  1652. // This should almost never happen as the SSA property is tracked at
  1653. // the register level (as opposed to the subreg level).
  1654. // I.e.,
  1655. // Def.sub0 =
  1656. // Def.sub1 =
  1657. // is a valid SSA representation for Def.sub0 and Def.sub1, but not for
  1658. // Def. Thus, it must not be generated.
  1659. // However, some code could theoretically generates a single
  1660. // Def.sub0 (i.e, not defining the other subregs) and we would
  1661. // have this case.
  1662. // If we can ascertain (or force) that this never happens, we could
  1663. // turn that into an assertion.
  1664. return ValueTrackerResult();
  1665. if (!TII)
  1666. // We could handle the REG_SEQUENCE here, but we do not want to
  1667. // duplicate the code from the generic TII.
  1668. return ValueTrackerResult();
  1669. SmallVector<RegSubRegPairAndIdx, 8> RegSeqInputRegs;
  1670. if (!TII->getRegSequenceInputs(*Def, DefIdx, RegSeqInputRegs))
  1671. return ValueTrackerResult();
  1672. // We are looking at:
  1673. // Def = REG_SEQUENCE v0, sub0, v1, sub1, ...
  1674. // Check if one of the operand defines the subreg we are interested in.
  1675. for (const RegSubRegPairAndIdx &RegSeqInput : RegSeqInputRegs) {
  1676. if (RegSeqInput.SubIdx == DefSubReg)
  1677. return ValueTrackerResult(RegSeqInput.Reg, RegSeqInput.SubReg);
  1678. }
  1679. // If the subreg we are tracking is super-defined by another subreg,
  1680. // we could follow this value. However, this would require to compose
  1681. // the subreg and we do not do that for now.
  1682. return ValueTrackerResult();
  1683. }
  1684. ValueTrackerResult ValueTracker::getNextSourceFromInsertSubreg() {
  1685. assert((Def->isInsertSubreg() || Def->isInsertSubregLike()) &&
  1686. "Invalid definition");
  1687. if (Def->getOperand(DefIdx).getSubReg())
  1688. // If we are composing subreg, bail out.
  1689. // Same remark as getNextSourceFromRegSequence.
  1690. // I.e., this may be turned into an assert.
  1691. return ValueTrackerResult();
  1692. if (!TII)
  1693. // We could handle the REG_SEQUENCE here, but we do not want to
  1694. // duplicate the code from the generic TII.
  1695. return ValueTrackerResult();
  1696. RegSubRegPair BaseReg;
  1697. RegSubRegPairAndIdx InsertedReg;
  1698. if (!TII->getInsertSubregInputs(*Def, DefIdx, BaseReg, InsertedReg))
  1699. return ValueTrackerResult();
  1700. // We are looking at:
  1701. // Def = INSERT_SUBREG v0, v1, sub1
  1702. // There are two cases:
  1703. // 1. DefSubReg == sub1, get v1.
  1704. // 2. DefSubReg != sub1, the value may be available through v0.
  1705. // #1 Check if the inserted register matches the required sub index.
  1706. if (InsertedReg.SubIdx == DefSubReg) {
  1707. return ValueTrackerResult(InsertedReg.Reg, InsertedReg.SubReg);
  1708. }
  1709. // #2 Otherwise, if the sub register we are looking for is not partial
  1710. // defined by the inserted element, we can look through the main
  1711. // register (v0).
  1712. const MachineOperand &MODef = Def->getOperand(DefIdx);
  1713. // If the result register (Def) and the base register (v0) do not
  1714. // have the same register class or if we have to compose
  1715. // subregisters, bail out.
  1716. if (MRI.getRegClass(MODef.getReg()) != MRI.getRegClass(BaseReg.Reg) ||
  1717. BaseReg.SubReg)
  1718. return ValueTrackerResult();
  1719. // Get the TRI and check if the inserted sub-register overlaps with the
  1720. // sub-register we are tracking.
  1721. const TargetRegisterInfo *TRI = MRI.getTargetRegisterInfo();
  1722. if (!TRI ||
  1723. !(TRI->getSubRegIndexLaneMask(DefSubReg) &
  1724. TRI->getSubRegIndexLaneMask(InsertedReg.SubIdx)).none())
  1725. return ValueTrackerResult();
  1726. // At this point, the value is available in v0 via the same subreg
  1727. // we used for Def.
  1728. return ValueTrackerResult(BaseReg.Reg, DefSubReg);
  1729. }
  1730. ValueTrackerResult ValueTracker::getNextSourceFromExtractSubreg() {
  1731. assert((Def->isExtractSubreg() ||
  1732. Def->isExtractSubregLike()) && "Invalid definition");
  1733. // We are looking at:
  1734. // Def = EXTRACT_SUBREG v0, sub0
  1735. // Bail if we have to compose sub registers.
  1736. // Indeed, if DefSubReg != 0, we would have to compose it with sub0.
  1737. if (DefSubReg)
  1738. return ValueTrackerResult();
  1739. if (!TII)
  1740. // We could handle the EXTRACT_SUBREG here, but we do not want to
  1741. // duplicate the code from the generic TII.
  1742. return ValueTrackerResult();
  1743. RegSubRegPairAndIdx ExtractSubregInputReg;
  1744. if (!TII->getExtractSubregInputs(*Def, DefIdx, ExtractSubregInputReg))
  1745. return ValueTrackerResult();
  1746. // Bail if we have to compose sub registers.
  1747. // Likewise, if v0.subreg != 0, we would have to compose v0.subreg with sub0.
  1748. if (ExtractSubregInputReg.SubReg)
  1749. return ValueTrackerResult();
  1750. // Otherwise, the value is available in the v0.sub0.
  1751. return ValueTrackerResult(ExtractSubregInputReg.Reg,
  1752. ExtractSubregInputReg.SubIdx);
  1753. }
  1754. ValueTrackerResult ValueTracker::getNextSourceFromSubregToReg() {
  1755. assert(Def->isSubregToReg() && "Invalid definition");
  1756. // We are looking at:
  1757. // Def = SUBREG_TO_REG Imm, v0, sub0
  1758. // Bail if we have to compose sub registers.
  1759. // If DefSubReg != sub0, we would have to check that all the bits
  1760. // we track are included in sub0 and if yes, we would have to
  1761. // determine the right subreg in v0.
  1762. if (DefSubReg != Def->getOperand(3).getImm())
  1763. return ValueTrackerResult();
  1764. // Bail if we have to compose sub registers.
  1765. // Likewise, if v0.subreg != 0, we would have to compose it with sub0.
  1766. if (Def->getOperand(2).getSubReg())
  1767. return ValueTrackerResult();
  1768. return ValueTrackerResult(Def->getOperand(2).getReg(),
  1769. Def->getOperand(3).getImm());
  1770. }
  1771. /// Explore each PHI incoming operand and return its sources.
  1772. ValueTrackerResult ValueTracker::getNextSourceFromPHI() {
  1773. assert(Def->isPHI() && "Invalid definition");
  1774. ValueTrackerResult Res;
  1775. // If we look for a different subreg, bail as we do not support composing
  1776. // subregs yet.
  1777. if (Def->getOperand(0).getSubReg() != DefSubReg)
  1778. return ValueTrackerResult();
  1779. // Return all register sources for PHI instructions.
  1780. for (unsigned i = 1, e = Def->getNumOperands(); i < e; i += 2) {
  1781. const MachineOperand &MO = Def->getOperand(i);
  1782. assert(MO.isReg() && "Invalid PHI instruction");
  1783. // We have no code to deal with undef operands. They shouldn't happen in
  1784. // normal programs anyway.
  1785. if (MO.isUndef())
  1786. return ValueTrackerResult();
  1787. Res.addSource(MO.getReg(), MO.getSubReg());
  1788. }
  1789. return Res;
  1790. }
  1791. ValueTrackerResult ValueTracker::getNextSourceImpl() {
  1792. assert(Def && "This method needs a valid definition");
  1793. assert(((Def->getOperand(DefIdx).isDef() &&
  1794. (DefIdx < Def->getDesc().getNumDefs() ||
  1795. Def->getDesc().isVariadic())) ||
  1796. Def->getOperand(DefIdx).isImplicit()) &&
  1797. "Invalid DefIdx");
  1798. if (Def->isCopy())
  1799. return getNextSourceFromCopy();
  1800. if (Def->isBitcast())
  1801. return getNextSourceFromBitcast();
  1802. // All the remaining cases involve "complex" instructions.
  1803. // Bail if we did not ask for the advanced tracking.
  1804. if (DisableAdvCopyOpt)
  1805. return ValueTrackerResult();
  1806. if (Def->isRegSequence() || Def->isRegSequenceLike())
  1807. return getNextSourceFromRegSequence();
  1808. if (Def->isInsertSubreg() || Def->isInsertSubregLike())
  1809. return getNextSourceFromInsertSubreg();
  1810. if (Def->isExtractSubreg() || Def->isExtractSubregLike())
  1811. return getNextSourceFromExtractSubreg();
  1812. if (Def->isSubregToReg())
  1813. return getNextSourceFromSubregToReg();
  1814. if (Def->isPHI())
  1815. return getNextSourceFromPHI();
  1816. return ValueTrackerResult();
  1817. }
  1818. ValueTrackerResult ValueTracker::getNextSource() {
  1819. // If we reach a point where we cannot move up in the use-def chain,
  1820. // there is nothing we can get.
  1821. if (!Def)
  1822. return ValueTrackerResult();
  1823. ValueTrackerResult Res = getNextSourceImpl();
  1824. if (Res.isValid()) {
  1825. // Update definition, definition index, and subregister for the
  1826. // next call of getNextSource.
  1827. // Update the current register.
  1828. bool OneRegSrc = Res.getNumSources() == 1;
  1829. if (OneRegSrc)
  1830. Reg = Res.getSrcReg(0);
  1831. // Update the result before moving up in the use-def chain
  1832. // with the instruction containing the last found sources.
  1833. Res.setInst(Def);
  1834. // If we can still move up in the use-def chain, move to the next
  1835. // definition.
  1836. if (!Register::isPhysicalRegister(Reg) && OneRegSrc) {
  1837. MachineRegisterInfo::def_iterator DI = MRI.def_begin(Reg);
  1838. if (DI != MRI.def_end()) {
  1839. Def = DI->getParent();
  1840. DefIdx = DI.getOperandNo();
  1841. DefSubReg = Res.getSrcSubReg(0);
  1842. } else {
  1843. Def = nullptr;
  1844. }
  1845. return Res;
  1846. }
  1847. }
  1848. // If we end up here, this means we will not be able to find another source
  1849. // for the next iteration. Make sure any new call to getNextSource bails out
  1850. // early by cutting the use-def chain.
  1851. Def = nullptr;
  1852. return Res;
  1853. }