HexagonHardwareLoops.cpp 53 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547
  1. //===-- HexagonHardwareLoops.cpp - Identify and generate hardware loops ---===//
  2. //
  3. // The LLVM Compiler Infrastructure
  4. //
  5. // This file is distributed under the University of Illinois Open Source
  6. // License. See LICENSE.TXT for details.
  7. //
  8. //===----------------------------------------------------------------------===//
  9. //
  10. // This pass identifies loops where we can generate the Hexagon hardware
  11. // loop instruction. The hardware loop can perform loop branches with a
  12. // zero-cycle overhead.
  13. //
  14. // The pattern that defines the induction variable can changed depending on
  15. // prior optimizations. For example, the IndVarSimplify phase run by 'opt'
  16. // normalizes induction variables, and the Loop Strength Reduction pass
  17. // run by 'llc' may also make changes to the induction variable.
  18. // The pattern detected by this phase is due to running Strength Reduction.
  19. //
  20. // Criteria for hardware loops:
  21. // - Countable loops (w/ ind. var for a trip count)
  22. // - Assumes loops are normalized by IndVarSimplify
  23. // - Try inner-most loops first
  24. // - No nested hardware loops.
  25. // - No function calls in loops.
  26. //
  27. //===----------------------------------------------------------------------===//
  28. #define DEBUG_TYPE "hwloops"
  29. #include "llvm/ADT/SmallSet.h"
  30. #include "Hexagon.h"
  31. #include "HexagonTargetMachine.h"
  32. #include "llvm/ADT/Statistic.h"
  33. #include "llvm/CodeGen/MachineDominators.h"
  34. #include "llvm/CodeGen/MachineFunction.h"
  35. #include "llvm/CodeGen/MachineFunctionPass.h"
  36. #include "llvm/CodeGen/MachineInstrBuilder.h"
  37. #include "llvm/CodeGen/MachineLoopInfo.h"
  38. #include "llvm/CodeGen/MachineRegisterInfo.h"
  39. #include "llvm/PassSupport.h"
  40. #include "llvm/Support/CommandLine.h"
  41. #include "llvm/Support/Debug.h"
  42. #include "llvm/Support/raw_ostream.h"
  43. #include "llvm/Target/TargetInstrInfo.h"
  44. #include <algorithm>
  45. #include <vector>
  46. using namespace llvm;
  47. #ifndef NDEBUG
  48. static cl::opt<int> HWLoopLimit("max-hwloop", cl::Hidden, cl::init(-1));
  49. #endif
  50. STATISTIC(NumHWLoops, "Number of loops converted to hardware loops");
  51. namespace llvm {
  52. void initializeHexagonHardwareLoopsPass(PassRegistry&);
  53. }
  54. namespace {
  55. class CountValue;
  56. struct HexagonHardwareLoops : public MachineFunctionPass {
  57. MachineLoopInfo *MLI;
  58. MachineRegisterInfo *MRI;
  59. MachineDominatorTree *MDT;
  60. const HexagonTargetMachine *TM;
  61. const HexagonInstrInfo *TII;
  62. const HexagonRegisterInfo *TRI;
  63. #ifndef NDEBUG
  64. static int Counter;
  65. #endif
  66. public:
  67. static char ID;
  68. HexagonHardwareLoops() : MachineFunctionPass(ID) {
  69. initializeHexagonHardwareLoopsPass(*PassRegistry::getPassRegistry());
  70. }
  71. virtual bool runOnMachineFunction(MachineFunction &MF);
  72. const char *getPassName() const { return "Hexagon Hardware Loops"; }
  73. virtual void getAnalysisUsage(AnalysisUsage &AU) const {
  74. AU.addRequired<MachineDominatorTree>();
  75. AU.addRequired<MachineLoopInfo>();
  76. MachineFunctionPass::getAnalysisUsage(AU);
  77. }
  78. private:
  79. /// Kinds of comparisons in the compare instructions.
  80. struct Comparison {
  81. enum Kind {
  82. EQ = 0x01,
  83. NE = 0x02,
  84. L = 0x04, // Less-than property.
  85. G = 0x08, // Greater-than property.
  86. U = 0x40, // Unsigned property.
  87. LTs = L,
  88. LEs = L | EQ,
  89. GTs = G,
  90. GEs = G | EQ,
  91. LTu = L | U,
  92. LEu = L | EQ | U,
  93. GTu = G | U,
  94. GEu = G | EQ | U
  95. };
  96. static Kind getSwappedComparison(Kind Cmp) {
  97. assert ((!((Cmp & L) && (Cmp & G))) && "Malformed comparison operator");
  98. if ((Cmp & L) || (Cmp & G))
  99. return (Kind)(Cmp ^ (L|G));
  100. return Cmp;
  101. }
  102. };
  103. /// \brief Find the register that contains the loop controlling
  104. /// induction variable.
  105. /// If successful, it will return true and set the \p Reg, \p IVBump
  106. /// and \p IVOp arguments. Otherwise it will return false.
  107. /// The returned induction register is the register R that follows the
  108. /// following induction pattern:
  109. /// loop:
  110. /// R = phi ..., [ R.next, LatchBlock ]
  111. /// R.next = R + #bump
  112. /// if (R.next < #N) goto loop
  113. /// IVBump is the immediate value added to R, and IVOp is the instruction
  114. /// "R.next = R + #bump".
  115. bool findInductionRegister(MachineLoop *L, unsigned &Reg,
  116. int64_t &IVBump, MachineInstr *&IVOp) const;
  117. /// \brief Analyze the statements in a loop to determine if the loop
  118. /// has a computable trip count and, if so, return a value that represents
  119. /// the trip count expression.
  120. CountValue *getLoopTripCount(MachineLoop *L,
  121. SmallVectorImpl<MachineInstr *> &OldInsts);
  122. /// \brief Return the expression that represents the number of times
  123. /// a loop iterates. The function takes the operands that represent the
  124. /// loop start value, loop end value, and induction value. Based upon
  125. /// these operands, the function attempts to compute the trip count.
  126. /// If the trip count is not directly available (as an immediate value,
  127. /// or a register), the function will attempt to insert computation of it
  128. /// to the loop's preheader.
  129. CountValue *computeCount(MachineLoop *Loop,
  130. const MachineOperand *Start,
  131. const MachineOperand *End,
  132. unsigned IVReg,
  133. int64_t IVBump,
  134. Comparison::Kind Cmp) const;
  135. /// \brief Return true if the instruction is not valid within a hardware
  136. /// loop.
  137. bool isInvalidLoopOperation(const MachineInstr *MI) const;
  138. /// \brief Return true if the loop contains an instruction that inhibits
  139. /// using the hardware loop.
  140. bool containsInvalidInstruction(MachineLoop *L) const;
  141. /// \brief Given a loop, check if we can convert it to a hardware loop.
  142. /// If so, then perform the conversion and return true.
  143. bool convertToHardwareLoop(MachineLoop *L);
  144. /// \brief Return true if the instruction is now dead.
  145. bool isDead(const MachineInstr *MI,
  146. SmallVectorImpl<MachineInstr *> &DeadPhis) const;
  147. /// \brief Remove the instruction if it is now dead.
  148. void removeIfDead(MachineInstr *MI);
  149. /// \brief Make sure that the "bump" instruction executes before the
  150. /// compare. We need that for the IV fixup, so that the compare
  151. /// instruction would not use a bumped value that has not yet been
  152. /// defined. If the instructions are out of order, try to reorder them.
  153. bool orderBumpCompare(MachineInstr *BumpI, MachineInstr *CmpI);
  154. /// \brief Get the instruction that loads an immediate value into \p R,
  155. /// or 0 if such an instruction does not exist.
  156. MachineInstr *defWithImmediate(unsigned R);
  157. /// \brief Get the immediate value referenced to by \p MO, either for
  158. /// immediate operands, or for register operands, where the register
  159. /// was defined with an immediate value.
  160. int64_t getImmediate(MachineOperand &MO);
  161. /// \brief Reset the given machine operand to now refer to a new immediate
  162. /// value. Assumes that the operand was already referencing an immediate
  163. /// value, either directly, or via a register.
  164. void setImmediate(MachineOperand &MO, int64_t Val);
  165. /// \brief Fix the data flow of the induction varible.
  166. /// The desired flow is: phi ---> bump -+-> comparison-in-latch.
  167. /// |
  168. /// +-> back to phi
  169. /// where "bump" is the increment of the induction variable:
  170. /// iv = iv + #const.
  171. /// Due to some prior code transformations, the actual flow may look
  172. /// like this:
  173. /// phi -+-> bump ---> back to phi
  174. /// |
  175. /// +-> comparison-in-latch (against upper_bound-bump),
  176. /// i.e. the comparison that controls the loop execution may be using
  177. /// the value of the induction variable from before the increment.
  178. ///
  179. /// Return true if the loop's flow is the desired one (i.e. it's
  180. /// either been fixed, or no fixing was necessary).
  181. /// Otherwise, return false. This can happen if the induction variable
  182. /// couldn't be identified, or if the value in the latch's comparison
  183. /// cannot be adjusted to reflect the post-bump value.
  184. bool fixupInductionVariable(MachineLoop *L);
  185. /// \brief Given a loop, if it does not have a preheader, create one.
  186. /// Return the block that is the preheader.
  187. MachineBasicBlock *createPreheaderForLoop(MachineLoop *L);
  188. };
  189. char HexagonHardwareLoops::ID = 0;
  190. #ifndef NDEBUG
  191. int HexagonHardwareLoops::Counter = 0;
  192. #endif
  193. /// \brief Abstraction for a trip count of a loop. A smaller vesrsion
  194. /// of the MachineOperand class without the concerns of changing the
  195. /// operand representation.
  196. class CountValue {
  197. public:
  198. enum CountValueType {
  199. CV_Register,
  200. CV_Immediate
  201. };
  202. private:
  203. CountValueType Kind;
  204. union Values {
  205. struct {
  206. unsigned Reg;
  207. unsigned Sub;
  208. } R;
  209. unsigned ImmVal;
  210. } Contents;
  211. public:
  212. explicit CountValue(CountValueType t, unsigned v, unsigned u = 0) {
  213. Kind = t;
  214. if (Kind == CV_Register) {
  215. Contents.R.Reg = v;
  216. Contents.R.Sub = u;
  217. } else {
  218. Contents.ImmVal = v;
  219. }
  220. }
  221. bool isReg() const { return Kind == CV_Register; }
  222. bool isImm() const { return Kind == CV_Immediate; }
  223. unsigned getReg() const {
  224. assert(isReg() && "Wrong CountValue accessor");
  225. return Contents.R.Reg;
  226. }
  227. unsigned getSubReg() const {
  228. assert(isReg() && "Wrong CountValue accessor");
  229. return Contents.R.Sub;
  230. }
  231. unsigned getImm() const {
  232. assert(isImm() && "Wrong CountValue accessor");
  233. return Contents.ImmVal;
  234. }
  235. void print(raw_ostream &OS, const TargetMachine *TM = 0) const {
  236. const TargetRegisterInfo *TRI = TM ? TM->getRegisterInfo() : 0;
  237. if (isReg()) { OS << PrintReg(Contents.R.Reg, TRI, Contents.R.Sub); }
  238. if (isImm()) { OS << Contents.ImmVal; }
  239. }
  240. };
  241. } // end anonymous namespace
  242. INITIALIZE_PASS_BEGIN(HexagonHardwareLoops, "hwloops",
  243. "Hexagon Hardware Loops", false, false)
  244. INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree)
  245. INITIALIZE_PASS_DEPENDENCY(MachineLoopInfo)
  246. INITIALIZE_PASS_END(HexagonHardwareLoops, "hwloops",
  247. "Hexagon Hardware Loops", false, false)
  248. /// \brief Returns true if the instruction is a hardware loop instruction.
  249. static bool isHardwareLoop(const MachineInstr *MI) {
  250. return MI->getOpcode() == Hexagon::LOOP0_r ||
  251. MI->getOpcode() == Hexagon::LOOP0_i;
  252. }
  253. FunctionPass *llvm::createHexagonHardwareLoops() {
  254. return new HexagonHardwareLoops();
  255. }
  256. bool HexagonHardwareLoops::runOnMachineFunction(MachineFunction &MF) {
  257. DEBUG(dbgs() << "********* Hexagon Hardware Loops *********\n");
  258. bool Changed = false;
  259. MLI = &getAnalysis<MachineLoopInfo>();
  260. MRI = &MF.getRegInfo();
  261. MDT = &getAnalysis<MachineDominatorTree>();
  262. TM = static_cast<const HexagonTargetMachine*>(&MF.getTarget());
  263. TII = static_cast<const HexagonInstrInfo*>(TM->getInstrInfo());
  264. TRI = static_cast<const HexagonRegisterInfo*>(TM->getRegisterInfo());
  265. for (MachineLoopInfo::iterator I = MLI->begin(), E = MLI->end();
  266. I != E; ++I) {
  267. MachineLoop *L = *I;
  268. if (!L->getParentLoop())
  269. Changed |= convertToHardwareLoop(L);
  270. }
  271. return Changed;
  272. }
  273. bool HexagonHardwareLoops::findInductionRegister(MachineLoop *L,
  274. unsigned &Reg,
  275. int64_t &IVBump,
  276. MachineInstr *&IVOp
  277. ) const {
  278. MachineBasicBlock *Header = L->getHeader();
  279. MachineBasicBlock *Preheader = L->getLoopPreheader();
  280. MachineBasicBlock *Latch = L->getLoopLatch();
  281. if (!Header || !Preheader || !Latch)
  282. return false;
  283. // This pair represents an induction register together with an immediate
  284. // value that will be added to it in each loop iteration.
  285. typedef std::pair<unsigned,int64_t> RegisterBump;
  286. // Mapping: R.next -> (R, bump), where R, R.next and bump are derived
  287. // from an induction operation
  288. // R.next = R + bump
  289. // where bump is an immediate value.
  290. typedef std::map<unsigned,RegisterBump> InductionMap;
  291. InductionMap IndMap;
  292. typedef MachineBasicBlock::instr_iterator instr_iterator;
  293. for (instr_iterator I = Header->instr_begin(), E = Header->instr_end();
  294. I != E && I->isPHI(); ++I) {
  295. MachineInstr *Phi = &*I;
  296. // Have a PHI instruction. Get the operand that corresponds to the
  297. // latch block, and see if is a result of an addition of form "reg+imm",
  298. // where the "reg" is defined by the PHI node we are looking at.
  299. for (unsigned i = 1, n = Phi->getNumOperands(); i < n; i += 2) {
  300. if (Phi->getOperand(i+1).getMBB() != Latch)
  301. continue;
  302. unsigned PhiOpReg = Phi->getOperand(i).getReg();
  303. MachineInstr *DI = MRI->getVRegDef(PhiOpReg);
  304. unsigned UpdOpc = DI->getOpcode();
  305. bool isAdd = (UpdOpc == Hexagon::ADD_ri);
  306. if (isAdd) {
  307. // If the register operand to the add is the PHI we're
  308. // looking at, this meets the induction pattern.
  309. unsigned IndReg = DI->getOperand(1).getReg();
  310. if (MRI->getVRegDef(IndReg) == Phi) {
  311. unsigned UpdReg = DI->getOperand(0).getReg();
  312. int64_t V = DI->getOperand(2).getImm();
  313. IndMap.insert(std::make_pair(UpdReg, std::make_pair(IndReg, V)));
  314. }
  315. }
  316. } // for (i)
  317. } // for (instr)
  318. SmallVector<MachineOperand,2> Cond;
  319. MachineBasicBlock *TB = 0, *FB = 0;
  320. bool NotAnalyzed = TII->AnalyzeBranch(*Latch, TB, FB, Cond, false);
  321. if (NotAnalyzed)
  322. return false;
  323. unsigned CSz = Cond.size();
  324. assert (CSz == 1 || CSz == 2);
  325. unsigned PredR = Cond[CSz-1].getReg();
  326. MachineInstr *PredI = MRI->getVRegDef(PredR);
  327. if (!PredI->isCompare())
  328. return false;
  329. unsigned CmpReg1 = 0, CmpReg2 = 0;
  330. int CmpImm = 0, CmpMask = 0;
  331. bool CmpAnalyzed = TII->analyzeCompare(PredI, CmpReg1, CmpReg2,
  332. CmpMask, CmpImm);
  333. // Fail if the compare was not analyzed, or it's not comparing a register
  334. // with an immediate value. Not checking the mask here, since we handle
  335. // the individual compare opcodes (including CMPb) later on.
  336. if (!CmpAnalyzed)
  337. return false;
  338. // Exactly one of the input registers to the comparison should be among
  339. // the induction registers.
  340. InductionMap::iterator IndMapEnd = IndMap.end();
  341. InductionMap::iterator F = IndMapEnd;
  342. if (CmpReg1 != 0) {
  343. InductionMap::iterator F1 = IndMap.find(CmpReg1);
  344. if (F1 != IndMapEnd)
  345. F = F1;
  346. }
  347. if (CmpReg2 != 0) {
  348. InductionMap::iterator F2 = IndMap.find(CmpReg2);
  349. if (F2 != IndMapEnd) {
  350. if (F != IndMapEnd)
  351. return false;
  352. F = F2;
  353. }
  354. }
  355. if (F == IndMapEnd)
  356. return false;
  357. Reg = F->second.first;
  358. IVBump = F->second.second;
  359. IVOp = MRI->getVRegDef(F->first);
  360. return true;
  361. }
  362. /// \brief Analyze the statements in a loop to determine if the loop has
  363. /// a computable trip count and, if so, return a value that represents
  364. /// the trip count expression.
  365. ///
  366. /// This function iterates over the phi nodes in the loop to check for
  367. /// induction variable patterns that are used in the calculation for
  368. /// the number of time the loop is executed.
  369. CountValue *HexagonHardwareLoops::getLoopTripCount(MachineLoop *L,
  370. SmallVectorImpl<MachineInstr *> &OldInsts) {
  371. MachineBasicBlock *TopMBB = L->getTopBlock();
  372. MachineBasicBlock::pred_iterator PI = TopMBB->pred_begin();
  373. assert(PI != TopMBB->pred_end() &&
  374. "Loop must have more than one incoming edge!");
  375. MachineBasicBlock *Backedge = *PI++;
  376. if (PI == TopMBB->pred_end()) // dead loop?
  377. return 0;
  378. MachineBasicBlock *Incoming = *PI++;
  379. if (PI != TopMBB->pred_end()) // multiple backedges?
  380. return 0;
  381. // Make sure there is one incoming and one backedge and determine which
  382. // is which.
  383. if (L->contains(Incoming)) {
  384. if (L->contains(Backedge))
  385. return 0;
  386. std::swap(Incoming, Backedge);
  387. } else if (!L->contains(Backedge))
  388. return 0;
  389. // Look for the cmp instruction to determine if we can get a useful trip
  390. // count. The trip count can be either a register or an immediate. The
  391. // location of the value depends upon the type (reg or imm).
  392. MachineBasicBlock *Latch = L->getLoopLatch();
  393. if (!Latch)
  394. return 0;
  395. unsigned IVReg = 0;
  396. int64_t IVBump = 0;
  397. MachineInstr *IVOp;
  398. bool FoundIV = findInductionRegister(L, IVReg, IVBump, IVOp);
  399. if (!FoundIV)
  400. return 0;
  401. MachineBasicBlock *Preheader = L->getLoopPreheader();
  402. MachineOperand *InitialValue = 0;
  403. MachineInstr *IV_Phi = MRI->getVRegDef(IVReg);
  404. for (unsigned i = 1, n = IV_Phi->getNumOperands(); i < n; i += 2) {
  405. MachineBasicBlock *MBB = IV_Phi->getOperand(i+1).getMBB();
  406. if (MBB == Preheader)
  407. InitialValue = &IV_Phi->getOperand(i);
  408. else if (MBB == Latch)
  409. IVReg = IV_Phi->getOperand(i).getReg(); // Want IV reg after bump.
  410. }
  411. if (!InitialValue)
  412. return 0;
  413. SmallVector<MachineOperand,2> Cond;
  414. MachineBasicBlock *TB = 0, *FB = 0;
  415. bool NotAnalyzed = TII->AnalyzeBranch(*Latch, TB, FB, Cond, false);
  416. if (NotAnalyzed)
  417. return 0;
  418. MachineBasicBlock *Header = L->getHeader();
  419. // TB must be non-null. If FB is also non-null, one of them must be
  420. // the header. Otherwise, branch to TB could be exiting the loop, and
  421. // the fall through can go to the header.
  422. assert (TB && "Latch block without a branch?");
  423. assert ((!FB || TB == Header || FB == Header) && "Branches not to header?");
  424. if (!TB || (FB && TB != Header && FB != Header))
  425. return 0;
  426. // Branches of form "if (!P) ..." cause HexagonInstrInfo::AnalyzeBranch
  427. // to put imm(0), followed by P in the vector Cond.
  428. // If TB is not the header, it means that the "not-taken" path must lead
  429. // to the header.
  430. bool Negated = (Cond.size() > 1) ^ (TB != Header);
  431. unsigned PredReg = Cond[Cond.size()-1].getReg();
  432. MachineInstr *CondI = MRI->getVRegDef(PredReg);
  433. unsigned CondOpc = CondI->getOpcode();
  434. unsigned CmpReg1 = 0, CmpReg2 = 0;
  435. int Mask = 0, ImmValue = 0;
  436. bool AnalyzedCmp = TII->analyzeCompare(CondI, CmpReg1, CmpReg2,
  437. Mask, ImmValue);
  438. if (!AnalyzedCmp)
  439. return 0;
  440. // The comparison operator type determines how we compute the loop
  441. // trip count.
  442. OldInsts.push_back(CondI);
  443. OldInsts.push_back(IVOp);
  444. // Sadly, the following code gets information based on the position
  445. // of the operands in the compare instruction. This has to be done
  446. // this way, because the comparisons check for a specific relationship
  447. // between the operands (e.g. is-less-than), rather than to find out
  448. // what relationship the operands are in (as on PPC).
  449. Comparison::Kind Cmp;
  450. bool isSwapped = false;
  451. const MachineOperand &Op1 = CondI->getOperand(1);
  452. const MachineOperand &Op2 = CondI->getOperand(2);
  453. const MachineOperand *EndValue = 0;
  454. if (Op1.isReg()) {
  455. if (Op2.isImm() || Op1.getReg() == IVReg)
  456. EndValue = &Op2;
  457. else {
  458. EndValue = &Op1;
  459. isSwapped = true;
  460. }
  461. }
  462. if (!EndValue)
  463. return 0;
  464. switch (CondOpc) {
  465. case Hexagon::CMPEQri:
  466. case Hexagon::CMPEQrr:
  467. Cmp = !Negated ? Comparison::EQ : Comparison::NE;
  468. break;
  469. case Hexagon::CMPGTUri:
  470. case Hexagon::CMPGTUrr:
  471. Cmp = !Negated ? Comparison::GTu : Comparison::LEu;
  472. break;
  473. case Hexagon::CMPGTri:
  474. case Hexagon::CMPGTrr:
  475. Cmp = !Negated ? Comparison::GTs : Comparison::LEs;
  476. break;
  477. // Very limited support for byte/halfword compares.
  478. case Hexagon::CMPbEQri_V4:
  479. case Hexagon::CMPhEQri_V4: {
  480. if (IVBump != 1)
  481. return 0;
  482. int64_t InitV, EndV;
  483. // Since the comparisons are "ri", the EndValue should be an
  484. // immediate. Check it just in case.
  485. assert(EndValue->isImm() && "Unrecognized latch comparison");
  486. EndV = EndValue->getImm();
  487. // Allow InitialValue to be a register defined with an immediate.
  488. if (InitialValue->isReg()) {
  489. if (!defWithImmediate(InitialValue->getReg()))
  490. return 0;
  491. InitV = getImmediate(*InitialValue);
  492. } else {
  493. assert(InitialValue->isImm());
  494. InitV = InitialValue->getImm();
  495. }
  496. if (InitV >= EndV)
  497. return 0;
  498. if (CondOpc == Hexagon::CMPbEQri_V4) {
  499. if (!isInt<8>(InitV) || !isInt<8>(EndV))
  500. return 0;
  501. } else { // Hexagon::CMPhEQri_V4
  502. if (!isInt<16>(InitV) || !isInt<16>(EndV))
  503. return 0;
  504. }
  505. Cmp = !Negated ? Comparison::EQ : Comparison::NE;
  506. break;
  507. }
  508. default:
  509. return 0;
  510. }
  511. if (isSwapped)
  512. Cmp = Comparison::getSwappedComparison(Cmp);
  513. if (InitialValue->isReg()) {
  514. unsigned R = InitialValue->getReg();
  515. MachineBasicBlock *DefBB = MRI->getVRegDef(R)->getParent();
  516. if (!MDT->properlyDominates(DefBB, Header))
  517. return 0;
  518. OldInsts.push_back(MRI->getVRegDef(R));
  519. }
  520. if (EndValue->isReg()) {
  521. unsigned R = EndValue->getReg();
  522. MachineBasicBlock *DefBB = MRI->getVRegDef(R)->getParent();
  523. if (!MDT->properlyDominates(DefBB, Header))
  524. return 0;
  525. }
  526. return computeCount(L, InitialValue, EndValue, IVReg, IVBump, Cmp);
  527. }
  528. /// \brief Helper function that returns the expression that represents the
  529. /// number of times a loop iterates. The function takes the operands that
  530. /// represent the loop start value, loop end value, and induction value.
  531. /// Based upon these operands, the function attempts to compute the trip count.
  532. CountValue *HexagonHardwareLoops::computeCount(MachineLoop *Loop,
  533. const MachineOperand *Start,
  534. const MachineOperand *End,
  535. unsigned IVReg,
  536. int64_t IVBump,
  537. Comparison::Kind Cmp) const {
  538. // Cannot handle comparison EQ, i.e. while (A == B).
  539. if (Cmp == Comparison::EQ)
  540. return 0;
  541. // Check if either the start or end values are an assignment of an immediate.
  542. // If so, use the immediate value rather than the register.
  543. if (Start->isReg()) {
  544. const MachineInstr *StartValInstr = MRI->getVRegDef(Start->getReg());
  545. if (StartValInstr && StartValInstr->getOpcode() == Hexagon::TFRI)
  546. Start = &StartValInstr->getOperand(1);
  547. }
  548. if (End->isReg()) {
  549. const MachineInstr *EndValInstr = MRI->getVRegDef(End->getReg());
  550. if (EndValInstr && EndValInstr->getOpcode() == Hexagon::TFRI)
  551. End = &EndValInstr->getOperand(1);
  552. }
  553. assert (Start->isReg() || Start->isImm());
  554. assert (End->isReg() || End->isImm());
  555. bool CmpLess = Cmp & Comparison::L;
  556. bool CmpGreater = Cmp & Comparison::G;
  557. bool CmpHasEqual = Cmp & Comparison::EQ;
  558. // Avoid certain wrap-arounds. This doesn't detect all wrap-arounds.
  559. // If loop executes while iv is "less" with the iv value going down, then
  560. // the iv must wrap.
  561. if (CmpLess && IVBump < 0)
  562. return 0;
  563. // If loop executes while iv is "greater" with the iv value going up, then
  564. // the iv must wrap.
  565. if (CmpGreater && IVBump > 0)
  566. return 0;
  567. if (Start->isImm() && End->isImm()) {
  568. // Both, start and end are immediates.
  569. int64_t StartV = Start->getImm();
  570. int64_t EndV = End->getImm();
  571. int64_t Dist = EndV - StartV;
  572. if (Dist == 0)
  573. return 0;
  574. bool Exact = (Dist % IVBump) == 0;
  575. if (Cmp == Comparison::NE) {
  576. if (!Exact)
  577. return 0;
  578. if ((Dist < 0) ^ (IVBump < 0))
  579. return 0;
  580. }
  581. // For comparisons that include the final value (i.e. include equality
  582. // with the final value), we need to increase the distance by 1.
  583. if (CmpHasEqual)
  584. Dist = Dist > 0 ? Dist+1 : Dist-1;
  585. // assert (CmpLess => Dist > 0);
  586. assert ((!CmpLess || Dist > 0) && "Loop should never iterate!");
  587. // assert (CmpGreater => Dist < 0);
  588. assert ((!CmpGreater || Dist < 0) && "Loop should never iterate!");
  589. // "Normalized" distance, i.e. with the bump set to +-1.
  590. int64_t Dist1 = (IVBump > 0) ? (Dist + (IVBump-1)) / IVBump
  591. : (-Dist + (-IVBump-1)) / (-IVBump);
  592. assert (Dist1 > 0 && "Fishy thing. Both operands have the same sign.");
  593. uint64_t Count = Dist1;
  594. if (Count > 0xFFFFFFFFULL)
  595. return 0;
  596. return new CountValue(CountValue::CV_Immediate, Count);
  597. }
  598. // A general case: Start and End are some values, but the actual
  599. // iteration count may not be available. If it is not, insert
  600. // a computation of it into the preheader.
  601. // If the induction variable bump is not a power of 2, quit.
  602. // Othwerise we'd need a general integer division.
  603. if (!isPowerOf2_64(abs64(IVBump)))
  604. return 0;
  605. MachineBasicBlock *PH = Loop->getLoopPreheader();
  606. assert (PH && "Should have a preheader by now");
  607. MachineBasicBlock::iterator InsertPos = PH->getFirstTerminator();
  608. DebugLoc DL = (InsertPos != PH->end()) ? InsertPos->getDebugLoc()
  609. : DebugLoc();
  610. // If Start is an immediate and End is a register, the trip count
  611. // will be "reg - imm". Hexagon's "subtract immediate" instruction
  612. // is actually "reg + -imm".
  613. // If the loop IV is going downwards, i.e. if the bump is negative,
  614. // then the iteration count (computed as End-Start) will need to be
  615. // negated. To avoid the negation, just swap Start and End.
  616. if (IVBump < 0) {
  617. std::swap(Start, End);
  618. IVBump = -IVBump;
  619. }
  620. // Cmp may now have a wrong direction, e.g. LEs may now be GEs.
  621. // Signedness, and "including equality" are preserved.
  622. bool RegToImm = Start->isReg() && End->isImm(); // for (reg..imm)
  623. bool RegToReg = Start->isReg() && End->isReg(); // for (reg..reg)
  624. int64_t StartV = 0, EndV = 0;
  625. if (Start->isImm())
  626. StartV = Start->getImm();
  627. if (End->isImm())
  628. EndV = End->getImm();
  629. int64_t AdjV = 0;
  630. // To compute the iteration count, we would need this computation:
  631. // Count = (End - Start + (IVBump-1)) / IVBump
  632. // or, when CmpHasEqual:
  633. // Count = (End - Start + (IVBump-1)+1) / IVBump
  634. // The "IVBump-1" part is the adjustment (AdjV). We can avoid
  635. // generating an instruction specifically to add it if we can adjust
  636. // the immediate values for Start or End.
  637. if (CmpHasEqual) {
  638. // Need to add 1 to the total iteration count.
  639. if (Start->isImm())
  640. StartV--;
  641. else if (End->isImm())
  642. EndV++;
  643. else
  644. AdjV += 1;
  645. }
  646. if (Cmp != Comparison::NE) {
  647. if (Start->isImm())
  648. StartV -= (IVBump-1);
  649. else if (End->isImm())
  650. EndV += (IVBump-1);
  651. else
  652. AdjV += (IVBump-1);
  653. }
  654. unsigned R = 0, SR = 0;
  655. if (Start->isReg()) {
  656. R = Start->getReg();
  657. SR = Start->getSubReg();
  658. } else {
  659. R = End->getReg();
  660. SR = End->getSubReg();
  661. }
  662. const TargetRegisterClass *RC = MRI->getRegClass(R);
  663. // Hardware loops cannot handle 64-bit registers. If it's a double
  664. // register, it has to have a subregister.
  665. if (!SR && RC == &Hexagon::DoubleRegsRegClass)
  666. return 0;
  667. const TargetRegisterClass *IntRC = &Hexagon::IntRegsRegClass;
  668. // Compute DistR (register with the distance between Start and End).
  669. unsigned DistR, DistSR;
  670. // Avoid special case, where the start value is an imm(0).
  671. if (Start->isImm() && StartV == 0) {
  672. DistR = End->getReg();
  673. DistSR = End->getSubReg();
  674. } else {
  675. const MCInstrDesc &SubD = RegToReg ? TII->get(Hexagon::SUB_rr) :
  676. (RegToImm ? TII->get(Hexagon::SUB_ri) :
  677. TII->get(Hexagon::ADD_ri));
  678. unsigned SubR = MRI->createVirtualRegister(IntRC);
  679. MachineInstrBuilder SubIB =
  680. BuildMI(*PH, InsertPos, DL, SubD, SubR);
  681. if (RegToReg) {
  682. SubIB.addReg(End->getReg(), 0, End->getSubReg())
  683. .addReg(Start->getReg(), 0, Start->getSubReg());
  684. } else if (RegToImm) {
  685. SubIB.addImm(EndV)
  686. .addReg(Start->getReg(), 0, Start->getSubReg());
  687. } else { // ImmToReg
  688. SubIB.addReg(End->getReg(), 0, End->getSubReg())
  689. .addImm(-StartV);
  690. }
  691. DistR = SubR;
  692. DistSR = 0;
  693. }
  694. // From DistR, compute AdjR (register with the adjusted distance).
  695. unsigned AdjR, AdjSR;
  696. if (AdjV == 0) {
  697. AdjR = DistR;
  698. AdjSR = DistSR;
  699. } else {
  700. // Generate CountR = ADD DistR, AdjVal
  701. unsigned AddR = MRI->createVirtualRegister(IntRC);
  702. const MCInstrDesc &AddD = TII->get(Hexagon::ADD_ri);
  703. BuildMI(*PH, InsertPos, DL, AddD, AddR)
  704. .addReg(DistR, 0, DistSR)
  705. .addImm(AdjV);
  706. AdjR = AddR;
  707. AdjSR = 0;
  708. }
  709. // From AdjR, compute CountR (register with the final count).
  710. unsigned CountR, CountSR;
  711. if (IVBump == 1) {
  712. CountR = AdjR;
  713. CountSR = AdjSR;
  714. } else {
  715. // The IV bump is a power of two. Log_2(IV bump) is the shift amount.
  716. unsigned Shift = Log2_32(IVBump);
  717. // Generate NormR = LSR DistR, Shift.
  718. unsigned LsrR = MRI->createVirtualRegister(IntRC);
  719. const MCInstrDesc &LsrD = TII->get(Hexagon::LSR_ri);
  720. BuildMI(*PH, InsertPos, DL, LsrD, LsrR)
  721. .addReg(AdjR, 0, AdjSR)
  722. .addImm(Shift);
  723. CountR = LsrR;
  724. CountSR = 0;
  725. }
  726. return new CountValue(CountValue::CV_Register, CountR, CountSR);
  727. }
  728. /// \brief Return true if the operation is invalid within hardware loop.
  729. bool HexagonHardwareLoops::isInvalidLoopOperation(
  730. const MachineInstr *MI) const {
  731. // call is not allowed because the callee may use a hardware loop
  732. if (MI->getDesc().isCall())
  733. return true;
  734. // do not allow nested hardware loops
  735. if (isHardwareLoop(MI))
  736. return true;
  737. // check if the instruction defines a hardware loop register
  738. for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
  739. const MachineOperand &MO = MI->getOperand(i);
  740. if (!MO.isReg() || !MO.isDef())
  741. continue;
  742. unsigned R = MO.getReg();
  743. if (R == Hexagon::LC0 || R == Hexagon::LC1 ||
  744. R == Hexagon::SA0 || R == Hexagon::SA1)
  745. return true;
  746. }
  747. return false;
  748. }
  749. /// \brief - Return true if the loop contains an instruction that inhibits
  750. /// the use of the hardware loop function.
  751. bool HexagonHardwareLoops::containsInvalidInstruction(MachineLoop *L) const {
  752. const std::vector<MachineBasicBlock *> &Blocks = L->getBlocks();
  753. for (unsigned i = 0, e = Blocks.size(); i != e; ++i) {
  754. MachineBasicBlock *MBB = Blocks[i];
  755. for (MachineBasicBlock::iterator
  756. MII = MBB->begin(), E = MBB->end(); MII != E; ++MII) {
  757. const MachineInstr *MI = &*MII;
  758. if (isInvalidLoopOperation(MI))
  759. return true;
  760. }
  761. }
  762. return false;
  763. }
  764. /// \brief Returns true if the instruction is dead. This was essentially
  765. /// copied from DeadMachineInstructionElim::isDead, but with special cases
  766. /// for inline asm, physical registers and instructions with side effects
  767. /// removed.
  768. bool HexagonHardwareLoops::isDead(const MachineInstr *MI,
  769. SmallVectorImpl<MachineInstr *> &DeadPhis) const {
  770. // Examine each operand.
  771. for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
  772. const MachineOperand &MO = MI->getOperand(i);
  773. if (!MO.isReg() || !MO.isDef())
  774. continue;
  775. unsigned Reg = MO.getReg();
  776. if (MRI->use_nodbg_empty(Reg))
  777. continue;
  778. typedef MachineRegisterInfo::use_nodbg_iterator use_nodbg_iterator;
  779. // This instruction has users, but if the only user is the phi node for the
  780. // parent block, and the only use of that phi node is this instruction, then
  781. // this instruction is dead: both it (and the phi node) can be removed.
  782. use_nodbg_iterator I = MRI->use_nodbg_begin(Reg);
  783. use_nodbg_iterator End = MRI->use_nodbg_end();
  784. if (std::next(I) != End || !I.getOperand().getParent()->isPHI())
  785. return false;
  786. MachineInstr *OnePhi = I.getOperand().getParent();
  787. for (unsigned j = 0, f = OnePhi->getNumOperands(); j != f; ++j) {
  788. const MachineOperand &OPO = OnePhi->getOperand(j);
  789. if (!OPO.isReg() || !OPO.isDef())
  790. continue;
  791. unsigned OPReg = OPO.getReg();
  792. use_nodbg_iterator nextJ;
  793. for (use_nodbg_iterator J = MRI->use_nodbg_begin(OPReg);
  794. J != End; J = nextJ) {
  795. nextJ = std::next(J);
  796. MachineOperand &Use = J.getOperand();
  797. MachineInstr *UseMI = Use.getParent();
  798. // If the phi node has a user that is not MI, bail...
  799. if (MI != UseMI)
  800. return false;
  801. }
  802. }
  803. DeadPhis.push_back(OnePhi);
  804. }
  805. // If there are no defs with uses, the instruction is dead.
  806. return true;
  807. }
  808. void HexagonHardwareLoops::removeIfDead(MachineInstr *MI) {
  809. // This procedure was essentially copied from DeadMachineInstructionElim.
  810. SmallVector<MachineInstr*, 1> DeadPhis;
  811. if (isDead(MI, DeadPhis)) {
  812. DEBUG(dbgs() << "HW looping will remove: " << *MI);
  813. // It is possible that some DBG_VALUE instructions refer to this
  814. // instruction. Examine each def operand for such references;
  815. // if found, mark the DBG_VALUE as undef (but don't delete it).
  816. for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
  817. const MachineOperand &MO = MI->getOperand(i);
  818. if (!MO.isReg() || !MO.isDef())
  819. continue;
  820. unsigned Reg = MO.getReg();
  821. MachineRegisterInfo::use_iterator nextI;
  822. for (MachineRegisterInfo::use_iterator I = MRI->use_begin(Reg),
  823. E = MRI->use_end(); I != E; I = nextI) {
  824. nextI = std::next(I); // I is invalidated by the setReg
  825. MachineOperand &Use = I.getOperand();
  826. MachineInstr *UseMI = Use.getParent();
  827. if (UseMI == MI)
  828. continue;
  829. if (Use.isDebug())
  830. UseMI->getOperand(0).setReg(0U);
  831. // This may also be a "instr -> phi -> instr" case which can
  832. // be removed too.
  833. }
  834. }
  835. MI->eraseFromParent();
  836. for (unsigned i = 0; i < DeadPhis.size(); ++i)
  837. DeadPhis[i]->eraseFromParent();
  838. }
  839. }
  840. /// \brief Check if the loop is a candidate for converting to a hardware
  841. /// loop. If so, then perform the transformation.
  842. ///
  843. /// This function works on innermost loops first. A loop can be converted
  844. /// if it is a counting loop; either a register value or an immediate.
  845. ///
  846. /// The code makes several assumptions about the representation of the loop
  847. /// in llvm.
  848. bool HexagonHardwareLoops::convertToHardwareLoop(MachineLoop *L) {
  849. // This is just for sanity.
  850. assert(L->getHeader() && "Loop without a header?");
  851. bool Changed = false;
  852. // Process nested loops first.
  853. for (MachineLoop::iterator I = L->begin(), E = L->end(); I != E; ++I)
  854. Changed |= convertToHardwareLoop(*I);
  855. // If a nested loop has been converted, then we can't convert this loop.
  856. if (Changed)
  857. return Changed;
  858. #ifndef NDEBUG
  859. // Stop trying after reaching the limit (if any).
  860. int Limit = HWLoopLimit;
  861. if (Limit >= 0) {
  862. if (Counter >= HWLoopLimit)
  863. return false;
  864. Counter++;
  865. }
  866. #endif
  867. // Does the loop contain any invalid instructions?
  868. if (containsInvalidInstruction(L))
  869. return false;
  870. // Is the induction variable bump feeding the latch condition?
  871. if (!fixupInductionVariable(L))
  872. return false;
  873. MachineBasicBlock *LastMBB = L->getExitingBlock();
  874. // Don't generate hw loop if the loop has more than one exit.
  875. if (LastMBB == 0)
  876. return false;
  877. MachineBasicBlock::iterator LastI = LastMBB->getFirstTerminator();
  878. if (LastI == LastMBB->end())
  879. return false;
  880. // Ensure the loop has a preheader: the loop instruction will be
  881. // placed there.
  882. bool NewPreheader = false;
  883. MachineBasicBlock *Preheader = L->getLoopPreheader();
  884. if (!Preheader) {
  885. Preheader = createPreheaderForLoop(L);
  886. if (!Preheader)
  887. return false;
  888. NewPreheader = true;
  889. }
  890. MachineBasicBlock::iterator InsertPos = Preheader->getFirstTerminator();
  891. SmallVector<MachineInstr*, 2> OldInsts;
  892. // Are we able to determine the trip count for the loop?
  893. CountValue *TripCount = getLoopTripCount(L, OldInsts);
  894. if (TripCount == 0)
  895. return false;
  896. // Is the trip count available in the preheader?
  897. if (TripCount->isReg()) {
  898. // There will be a use of the register inserted into the preheader,
  899. // so make sure that the register is actually defined at that point.
  900. MachineInstr *TCDef = MRI->getVRegDef(TripCount->getReg());
  901. MachineBasicBlock *BBDef = TCDef->getParent();
  902. if (!NewPreheader) {
  903. if (!MDT->dominates(BBDef, Preheader))
  904. return false;
  905. } else {
  906. // If we have just created a preheader, the dominator tree won't be
  907. // aware of it. Check if the definition of the register dominates
  908. // the header, but is not the header itself.
  909. if (!MDT->properlyDominates(BBDef, L->getHeader()))
  910. return false;
  911. }
  912. }
  913. // Determine the loop start.
  914. MachineBasicBlock *LoopStart = L->getTopBlock();
  915. if (L->getLoopLatch() != LastMBB) {
  916. // When the exit and latch are not the same, use the latch block as the
  917. // start.
  918. // The loop start address is used only after the 1st iteration, and the
  919. // loop latch may contains instrs. that need to be executed after the
  920. // first iteration.
  921. LoopStart = L->getLoopLatch();
  922. // Make sure the latch is a successor of the exit, otherwise it won't work.
  923. if (!LastMBB->isSuccessor(LoopStart))
  924. return false;
  925. }
  926. // Convert the loop to a hardware loop.
  927. DEBUG(dbgs() << "Change to hardware loop at "; L->dump());
  928. DebugLoc DL;
  929. if (InsertPos != Preheader->end())
  930. DL = InsertPos->getDebugLoc();
  931. if (TripCount->isReg()) {
  932. // Create a copy of the loop count register.
  933. unsigned CountReg = MRI->createVirtualRegister(&Hexagon::IntRegsRegClass);
  934. BuildMI(*Preheader, InsertPos, DL, TII->get(TargetOpcode::COPY), CountReg)
  935. .addReg(TripCount->getReg(), 0, TripCount->getSubReg());
  936. // Add the Loop instruction to the beginning of the loop.
  937. BuildMI(*Preheader, InsertPos, DL, TII->get(Hexagon::LOOP0_r))
  938. .addMBB(LoopStart)
  939. .addReg(CountReg);
  940. } else {
  941. assert(TripCount->isImm() && "Expecting immediate value for trip count");
  942. // Add the Loop immediate instruction to the beginning of the loop,
  943. // if the immediate fits in the instructions. Otherwise, we need to
  944. // create a new virtual register.
  945. int64_t CountImm = TripCount->getImm();
  946. if (!TII->isValidOffset(Hexagon::LOOP0_i, CountImm)) {
  947. unsigned CountReg = MRI->createVirtualRegister(&Hexagon::IntRegsRegClass);
  948. BuildMI(*Preheader, InsertPos, DL, TII->get(Hexagon::TFRI), CountReg)
  949. .addImm(CountImm);
  950. BuildMI(*Preheader, InsertPos, DL, TII->get(Hexagon::LOOP0_r))
  951. .addMBB(LoopStart).addReg(CountReg);
  952. } else
  953. BuildMI(*Preheader, InsertPos, DL, TII->get(Hexagon::LOOP0_i))
  954. .addMBB(LoopStart).addImm(CountImm);
  955. }
  956. // Make sure the loop start always has a reference in the CFG. We need
  957. // to create a BlockAddress operand to get this mechanism to work both the
  958. // MachineBasicBlock and BasicBlock objects need the flag set.
  959. LoopStart->setHasAddressTaken();
  960. // This line is needed to set the hasAddressTaken flag on the BasicBlock
  961. // object.
  962. BlockAddress::get(const_cast<BasicBlock *>(LoopStart->getBasicBlock()));
  963. // Replace the loop branch with an endloop instruction.
  964. DebugLoc LastIDL = LastI->getDebugLoc();
  965. BuildMI(*LastMBB, LastI, LastIDL,
  966. TII->get(Hexagon::ENDLOOP0)).addMBB(LoopStart);
  967. // The loop ends with either:
  968. // - a conditional branch followed by an unconditional branch, or
  969. // - a conditional branch to the loop start.
  970. if (LastI->getOpcode() == Hexagon::JMP_t ||
  971. LastI->getOpcode() == Hexagon::JMP_f) {
  972. // Delete one and change/add an uncond. branch to out of the loop.
  973. MachineBasicBlock *BranchTarget = LastI->getOperand(1).getMBB();
  974. LastI = LastMBB->erase(LastI);
  975. if (!L->contains(BranchTarget)) {
  976. if (LastI != LastMBB->end())
  977. LastI = LastMBB->erase(LastI);
  978. SmallVector<MachineOperand, 0> Cond;
  979. TII->InsertBranch(*LastMBB, BranchTarget, 0, Cond, LastIDL);
  980. }
  981. } else {
  982. // Conditional branch to loop start; just delete it.
  983. LastMBB->erase(LastI);
  984. }
  985. delete TripCount;
  986. // The induction operation and the comparison may now be
  987. // unneeded. If these are unneeded, then remove them.
  988. for (unsigned i = 0; i < OldInsts.size(); ++i)
  989. removeIfDead(OldInsts[i]);
  990. ++NumHWLoops;
  991. return true;
  992. }
  993. bool HexagonHardwareLoops::orderBumpCompare(MachineInstr *BumpI,
  994. MachineInstr *CmpI) {
  995. assert (BumpI != CmpI && "Bump and compare in the same instruction?");
  996. MachineBasicBlock *BB = BumpI->getParent();
  997. if (CmpI->getParent() != BB)
  998. return false;
  999. typedef MachineBasicBlock::instr_iterator instr_iterator;
  1000. // Check if things are in order to begin with.
  1001. for (instr_iterator I = BumpI, E = BB->instr_end(); I != E; ++I)
  1002. if (&*I == CmpI)
  1003. return true;
  1004. // Out of order.
  1005. unsigned PredR = CmpI->getOperand(0).getReg();
  1006. bool FoundBump = false;
  1007. instr_iterator CmpIt = CmpI, NextIt = std::next(CmpIt);
  1008. for (instr_iterator I = NextIt, E = BB->instr_end(); I != E; ++I) {
  1009. MachineInstr *In = &*I;
  1010. for (unsigned i = 0, n = In->getNumOperands(); i < n; ++i) {
  1011. MachineOperand &MO = In->getOperand(i);
  1012. if (MO.isReg() && MO.isUse()) {
  1013. if (MO.getReg() == PredR) // Found an intervening use of PredR.
  1014. return false;
  1015. }
  1016. }
  1017. if (In == BumpI) {
  1018. instr_iterator After = BumpI;
  1019. instr_iterator From = CmpI;
  1020. BB->splice(std::next(After), BB, From);
  1021. FoundBump = true;
  1022. break;
  1023. }
  1024. }
  1025. assert (FoundBump && "Cannot determine instruction order");
  1026. return FoundBump;
  1027. }
  1028. MachineInstr *HexagonHardwareLoops::defWithImmediate(unsigned R) {
  1029. MachineInstr *DI = MRI->getVRegDef(R);
  1030. unsigned DOpc = DI->getOpcode();
  1031. switch (DOpc) {
  1032. case Hexagon::TFRI:
  1033. case Hexagon::TFRI64:
  1034. case Hexagon::CONST32_Int_Real:
  1035. case Hexagon::CONST64_Int_Real:
  1036. return DI;
  1037. }
  1038. return 0;
  1039. }
  1040. int64_t HexagonHardwareLoops::getImmediate(MachineOperand &MO) {
  1041. if (MO.isImm())
  1042. return MO.getImm();
  1043. assert(MO.isReg());
  1044. unsigned R = MO.getReg();
  1045. MachineInstr *DI = defWithImmediate(R);
  1046. assert(DI && "Need an immediate operand");
  1047. // All currently supported "define-with-immediate" instructions have the
  1048. // actual immediate value in the operand(1).
  1049. int64_t v = DI->getOperand(1).getImm();
  1050. return v;
  1051. }
  1052. void HexagonHardwareLoops::setImmediate(MachineOperand &MO, int64_t Val) {
  1053. if (MO.isImm()) {
  1054. MO.setImm(Val);
  1055. return;
  1056. }
  1057. assert(MO.isReg());
  1058. unsigned R = MO.getReg();
  1059. MachineInstr *DI = defWithImmediate(R);
  1060. if (MRI->hasOneNonDBGUse(R)) {
  1061. // If R has only one use, then just change its defining instruction to
  1062. // the new immediate value.
  1063. DI->getOperand(1).setImm(Val);
  1064. return;
  1065. }
  1066. const TargetRegisterClass *RC = MRI->getRegClass(R);
  1067. unsigned NewR = MRI->createVirtualRegister(RC);
  1068. MachineBasicBlock &B = *DI->getParent();
  1069. DebugLoc DL = DI->getDebugLoc();
  1070. BuildMI(B, DI, DL, TII->get(DI->getOpcode()), NewR)
  1071. .addImm(Val);
  1072. MO.setReg(NewR);
  1073. }
  1074. bool HexagonHardwareLoops::fixupInductionVariable(MachineLoop *L) {
  1075. MachineBasicBlock *Header = L->getHeader();
  1076. MachineBasicBlock *Preheader = L->getLoopPreheader();
  1077. MachineBasicBlock *Latch = L->getLoopLatch();
  1078. if (!Header || !Preheader || !Latch)
  1079. return false;
  1080. // These data structures follow the same concept as the corresponding
  1081. // ones in findInductionRegister (where some comments are).
  1082. typedef std::pair<unsigned,int64_t> RegisterBump;
  1083. typedef std::pair<unsigned,RegisterBump> RegisterInduction;
  1084. typedef std::set<RegisterInduction> RegisterInductionSet;
  1085. // Register candidates for induction variables, with their associated bumps.
  1086. RegisterInductionSet IndRegs;
  1087. // Look for induction patterns:
  1088. // vreg1 = PHI ..., [ latch, vreg2 ]
  1089. // vreg2 = ADD vreg1, imm
  1090. typedef MachineBasicBlock::instr_iterator instr_iterator;
  1091. for (instr_iterator I = Header->instr_begin(), E = Header->instr_end();
  1092. I != E && I->isPHI(); ++I) {
  1093. MachineInstr *Phi = &*I;
  1094. // Have a PHI instruction.
  1095. for (unsigned i = 1, n = Phi->getNumOperands(); i < n; i += 2) {
  1096. if (Phi->getOperand(i+1).getMBB() != Latch)
  1097. continue;
  1098. unsigned PhiReg = Phi->getOperand(i).getReg();
  1099. MachineInstr *DI = MRI->getVRegDef(PhiReg);
  1100. unsigned UpdOpc = DI->getOpcode();
  1101. bool isAdd = (UpdOpc == Hexagon::ADD_ri);
  1102. if (isAdd) {
  1103. // If the register operand to the add/sub is the PHI we are looking
  1104. // at, this meets the induction pattern.
  1105. unsigned IndReg = DI->getOperand(1).getReg();
  1106. if (MRI->getVRegDef(IndReg) == Phi) {
  1107. unsigned UpdReg = DI->getOperand(0).getReg();
  1108. int64_t V = DI->getOperand(2).getImm();
  1109. IndRegs.insert(std::make_pair(UpdReg, std::make_pair(IndReg, V)));
  1110. }
  1111. }
  1112. } // for (i)
  1113. } // for (instr)
  1114. if (IndRegs.empty())
  1115. return false;
  1116. MachineBasicBlock *TB = 0, *FB = 0;
  1117. SmallVector<MachineOperand,2> Cond;
  1118. // AnalyzeBranch returns true if it fails to analyze branch.
  1119. bool NotAnalyzed = TII->AnalyzeBranch(*Latch, TB, FB, Cond, false);
  1120. if (NotAnalyzed)
  1121. return false;
  1122. // Check if the latch branch is unconditional.
  1123. if (Cond.empty())
  1124. return false;
  1125. if (TB != Header && FB != Header)
  1126. // The latch does not go back to the header. Not a latch we know and love.
  1127. return false;
  1128. // Expecting a predicate register as a condition. It won't be a hardware
  1129. // predicate register at this point yet, just a vreg.
  1130. // HexagonInstrInfo::AnalyzeBranch for negated branches inserts imm(0)
  1131. // into Cond, followed by the predicate register. For non-negated branches
  1132. // it's just the register.
  1133. unsigned CSz = Cond.size();
  1134. if (CSz != 1 && CSz != 2)
  1135. return false;
  1136. unsigned P = Cond[CSz-1].getReg();
  1137. MachineInstr *PredDef = MRI->getVRegDef(P);
  1138. if (!PredDef->isCompare())
  1139. return false;
  1140. SmallSet<unsigned,2> CmpRegs;
  1141. MachineOperand *CmpImmOp = 0;
  1142. // Go over all operands to the compare and look for immediate and register
  1143. // operands. Assume that if the compare has a single register use and a
  1144. // single immediate operand, then the register is being compared with the
  1145. // immediate value.
  1146. for (unsigned i = 0, n = PredDef->getNumOperands(); i < n; ++i) {
  1147. MachineOperand &MO = PredDef->getOperand(i);
  1148. if (MO.isReg()) {
  1149. // Skip all implicit references. In one case there was:
  1150. // %vreg140<def> = FCMPUGT32_rr %vreg138, %vreg139, %USR<imp-use>
  1151. if (MO.isImplicit())
  1152. continue;
  1153. if (MO.isUse()) {
  1154. unsigned R = MO.getReg();
  1155. if (!defWithImmediate(R)) {
  1156. CmpRegs.insert(MO.getReg());
  1157. continue;
  1158. }
  1159. // Consider the register to be the "immediate" operand.
  1160. if (CmpImmOp)
  1161. return false;
  1162. CmpImmOp = &MO;
  1163. }
  1164. } else if (MO.isImm()) {
  1165. if (CmpImmOp) // A second immediate argument? Confusing. Bail out.
  1166. return false;
  1167. CmpImmOp = &MO;
  1168. }
  1169. }
  1170. if (CmpRegs.empty())
  1171. return false;
  1172. // Check if the compared register follows the order we want. Fix if needed.
  1173. for (RegisterInductionSet::iterator I = IndRegs.begin(), E = IndRegs.end();
  1174. I != E; ++I) {
  1175. // This is a success. If the register used in the comparison is one that
  1176. // we have identified as a bumped (updated) induction register, there is
  1177. // nothing to do.
  1178. if (CmpRegs.count(I->first))
  1179. return true;
  1180. // Otherwise, if the register being compared comes out of a PHI node,
  1181. // and has been recognized as following the induction pattern, and is
  1182. // compared against an immediate, we can fix it.
  1183. const RegisterBump &RB = I->second;
  1184. if (CmpRegs.count(RB.first)) {
  1185. if (!CmpImmOp)
  1186. return false;
  1187. int64_t CmpImm = getImmediate(*CmpImmOp);
  1188. int64_t V = RB.second;
  1189. if (V > 0 && CmpImm+V < CmpImm) // Overflow (64-bit).
  1190. return false;
  1191. if (V < 0 && CmpImm+V > CmpImm) // Overflow (64-bit).
  1192. return false;
  1193. CmpImm += V;
  1194. // Some forms of cmp-immediate allow u9 and s10. Assume the worst case
  1195. // scenario, i.e. an 8-bit value.
  1196. if (CmpImmOp->isImm() && !isInt<8>(CmpImm))
  1197. return false;
  1198. // Make sure that the compare happens after the bump. Otherwise,
  1199. // after the fixup, the compare would use a yet-undefined register.
  1200. MachineInstr *BumpI = MRI->getVRegDef(I->first);
  1201. bool Order = orderBumpCompare(BumpI, PredDef);
  1202. if (!Order)
  1203. return false;
  1204. // Finally, fix the compare instruction.
  1205. setImmediate(*CmpImmOp, CmpImm);
  1206. for (unsigned i = 0, n = PredDef->getNumOperands(); i < n; ++i) {
  1207. MachineOperand &MO = PredDef->getOperand(i);
  1208. if (MO.isReg() && MO.getReg() == RB.first) {
  1209. MO.setReg(I->first);
  1210. return true;
  1211. }
  1212. }
  1213. }
  1214. }
  1215. return false;
  1216. }
  1217. /// \brief Create a preheader for a given loop.
  1218. MachineBasicBlock *HexagonHardwareLoops::createPreheaderForLoop(
  1219. MachineLoop *L) {
  1220. if (MachineBasicBlock *TmpPH = L->getLoopPreheader())
  1221. return TmpPH;
  1222. MachineBasicBlock *Header = L->getHeader();
  1223. MachineBasicBlock *Latch = L->getLoopLatch();
  1224. MachineFunction *MF = Header->getParent();
  1225. DebugLoc DL;
  1226. if (!Latch || Header->hasAddressTaken())
  1227. return 0;
  1228. typedef MachineBasicBlock::instr_iterator instr_iterator;
  1229. // Verify that all existing predecessors have analyzable branches
  1230. // (or no branches at all).
  1231. typedef std::vector<MachineBasicBlock*> MBBVector;
  1232. MBBVector Preds(Header->pred_begin(), Header->pred_end());
  1233. SmallVector<MachineOperand,2> Tmp1;
  1234. MachineBasicBlock *TB = 0, *FB = 0;
  1235. if (TII->AnalyzeBranch(*Latch, TB, FB, Tmp1, false))
  1236. return 0;
  1237. for (MBBVector::iterator I = Preds.begin(), E = Preds.end(); I != E; ++I) {
  1238. MachineBasicBlock *PB = *I;
  1239. if (PB != Latch) {
  1240. bool NotAnalyzed = TII->AnalyzeBranch(*PB, TB, FB, Tmp1, false);
  1241. if (NotAnalyzed)
  1242. return 0;
  1243. }
  1244. }
  1245. MachineBasicBlock *NewPH = MF->CreateMachineBasicBlock();
  1246. MF->insert(Header, NewPH);
  1247. if (Header->pred_size() > 2) {
  1248. // Ensure that the header has only two predecessors: the preheader and
  1249. // the loop latch. Any additional predecessors of the header should
  1250. // join at the newly created preheader. Inspect all PHI nodes from the
  1251. // header and create appropriate corresponding PHI nodes in the preheader.
  1252. for (instr_iterator I = Header->instr_begin(), E = Header->instr_end();
  1253. I != E && I->isPHI(); ++I) {
  1254. MachineInstr *PN = &*I;
  1255. const MCInstrDesc &PD = TII->get(TargetOpcode::PHI);
  1256. MachineInstr *NewPN = MF->CreateMachineInstr(PD, DL);
  1257. NewPH->insert(NewPH->end(), NewPN);
  1258. unsigned PR = PN->getOperand(0).getReg();
  1259. const TargetRegisterClass *RC = MRI->getRegClass(PR);
  1260. unsigned NewPR = MRI->createVirtualRegister(RC);
  1261. NewPN->addOperand(MachineOperand::CreateReg(NewPR, true));
  1262. // Copy all non-latch operands of a header's PHI node to the newly
  1263. // created PHI node in the preheader.
  1264. for (unsigned i = 1, n = PN->getNumOperands(); i < n; i += 2) {
  1265. unsigned PredR = PN->getOperand(i).getReg();
  1266. MachineBasicBlock *PredB = PN->getOperand(i+1).getMBB();
  1267. if (PredB == Latch)
  1268. continue;
  1269. NewPN->addOperand(MachineOperand::CreateReg(PredR, false));
  1270. NewPN->addOperand(MachineOperand::CreateMBB(PredB));
  1271. }
  1272. // Remove copied operands from the old PHI node and add the value
  1273. // coming from the preheader's PHI.
  1274. for (int i = PN->getNumOperands()-2; i > 0; i -= 2) {
  1275. MachineBasicBlock *PredB = PN->getOperand(i+1).getMBB();
  1276. if (PredB != Latch) {
  1277. PN->RemoveOperand(i+1);
  1278. PN->RemoveOperand(i);
  1279. }
  1280. }
  1281. PN->addOperand(MachineOperand::CreateReg(NewPR, false));
  1282. PN->addOperand(MachineOperand::CreateMBB(NewPH));
  1283. }
  1284. } else {
  1285. assert(Header->pred_size() == 2);
  1286. // The header has only two predecessors, but the non-latch predecessor
  1287. // is not a preheader (e.g. it has other successors, etc.)
  1288. // In such a case we don't need any extra PHI nodes in the new preheader,
  1289. // all we need is to adjust existing PHIs in the header to now refer to
  1290. // the new preheader.
  1291. for (instr_iterator I = Header->instr_begin(), E = Header->instr_end();
  1292. I != E && I->isPHI(); ++I) {
  1293. MachineInstr *PN = &*I;
  1294. for (unsigned i = 1, n = PN->getNumOperands(); i < n; i += 2) {
  1295. MachineOperand &MO = PN->getOperand(i+1);
  1296. if (MO.getMBB() != Latch)
  1297. MO.setMBB(NewPH);
  1298. }
  1299. }
  1300. }
  1301. // "Reroute" the CFG edges to link in the new preheader.
  1302. // If any of the predecessors falls through to the header, insert a branch
  1303. // to the new preheader in that place.
  1304. SmallVector<MachineOperand,1> Tmp2;
  1305. SmallVector<MachineOperand,1> EmptyCond;
  1306. TB = FB = 0;
  1307. for (MBBVector::iterator I = Preds.begin(), E = Preds.end(); I != E; ++I) {
  1308. MachineBasicBlock *PB = *I;
  1309. if (PB != Latch) {
  1310. Tmp2.clear();
  1311. bool NotAnalyzed = TII->AnalyzeBranch(*PB, TB, FB, Tmp2, false);
  1312. (void)NotAnalyzed; // suppress compiler warning
  1313. assert (!NotAnalyzed && "Should be analyzable!");
  1314. if (TB != Header && (Tmp2.empty() || FB != Header))
  1315. TII->InsertBranch(*PB, NewPH, 0, EmptyCond, DL);
  1316. PB->ReplaceUsesOfBlockWith(Header, NewPH);
  1317. }
  1318. }
  1319. // It can happen that the latch block will fall through into the header.
  1320. // Insert an unconditional branch to the header.
  1321. TB = FB = 0;
  1322. bool LatchNotAnalyzed = TII->AnalyzeBranch(*Latch, TB, FB, Tmp2, false);
  1323. (void)LatchNotAnalyzed; // suppress compiler warning
  1324. assert (!LatchNotAnalyzed && "Should be analyzable!");
  1325. if (!TB && !FB)
  1326. TII->InsertBranch(*Latch, Header, 0, EmptyCond, DL);
  1327. // Finally, the branch from the preheader to the header.
  1328. TII->InsertBranch(*NewPH, Header, 0, EmptyCond, DL);
  1329. NewPH->addSuccessor(Header);
  1330. return NewPH;
  1331. }