ARMLoadStoreOptimizer.cpp 73 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123
  1. //===-- ARMLoadStoreOptimizer.cpp - ARM load / store opt. pass ------------===//
  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 file contains a pass that performs load / store related peephole
  11. // optimizations. This pass should be run after register allocation.
  12. //
  13. //===----------------------------------------------------------------------===//
  14. #include "ARM.h"
  15. #include "ARMBaseInstrInfo.h"
  16. #include "ARMBaseRegisterInfo.h"
  17. #include "ARMISelLowering.h"
  18. #include "ARMMachineFunctionInfo.h"
  19. #include "ARMSubtarget.h"
  20. #include "MCTargetDesc/ARMAddressingModes.h"
  21. #include "Thumb1RegisterInfo.h"
  22. #include "llvm/ADT/DenseMap.h"
  23. #include "llvm/ADT/STLExtras.h"
  24. #include "llvm/ADT/SmallPtrSet.h"
  25. #include "llvm/ADT/SmallSet.h"
  26. #include "llvm/ADT/SmallVector.h"
  27. #include "llvm/ADT/Statistic.h"
  28. #include "llvm/CodeGen/MachineBasicBlock.h"
  29. #include "llvm/CodeGen/MachineFunctionPass.h"
  30. #include "llvm/CodeGen/MachineInstr.h"
  31. #include "llvm/CodeGen/MachineInstrBuilder.h"
  32. #include "llvm/CodeGen/MachineRegisterInfo.h"
  33. #include "llvm/CodeGen/RegisterScavenging.h"
  34. #include "llvm/CodeGen/SelectionDAGNodes.h"
  35. #include "llvm/IR/DataLayout.h"
  36. #include "llvm/IR/DerivedTypes.h"
  37. #include "llvm/IR/Function.h"
  38. #include "llvm/Support/Debug.h"
  39. #include "llvm/Support/ErrorHandling.h"
  40. #include "llvm/Target/TargetInstrInfo.h"
  41. #include "llvm/Target/TargetMachine.h"
  42. #include "llvm/Target/TargetRegisterInfo.h"
  43. using namespace llvm;
  44. #define DEBUG_TYPE "arm-ldst-opt"
  45. STATISTIC(NumLDMGened , "Number of ldm instructions generated");
  46. STATISTIC(NumSTMGened , "Number of stm instructions generated");
  47. STATISTIC(NumVLDMGened, "Number of vldm instructions generated");
  48. STATISTIC(NumVSTMGened, "Number of vstm instructions generated");
  49. STATISTIC(NumLdStMoved, "Number of load / store instructions moved");
  50. STATISTIC(NumLDRDFormed,"Number of ldrd created before allocation");
  51. STATISTIC(NumSTRDFormed,"Number of strd created before allocation");
  52. STATISTIC(NumLDRD2LDM, "Number of ldrd instructions turned back into ldm");
  53. STATISTIC(NumSTRD2STM, "Number of strd instructions turned back into stm");
  54. STATISTIC(NumLDRD2LDR, "Number of ldrd instructions turned back into ldr's");
  55. STATISTIC(NumSTRD2STR, "Number of strd instructions turned back into str's");
  56. /// ARMAllocLoadStoreOpt - Post- register allocation pass the combine
  57. /// load / store instructions to form ldm / stm instructions.
  58. namespace {
  59. struct ARMLoadStoreOpt : public MachineFunctionPass {
  60. static char ID;
  61. ARMLoadStoreOpt() : MachineFunctionPass(ID) {}
  62. const TargetInstrInfo *TII;
  63. const TargetRegisterInfo *TRI;
  64. const ARMSubtarget *STI;
  65. const TargetLowering *TL;
  66. ARMFunctionInfo *AFI;
  67. RegScavenger *RS;
  68. bool isThumb1, isThumb2;
  69. bool runOnMachineFunction(MachineFunction &Fn) override;
  70. const char *getPassName() const override {
  71. return "ARM load / store optimization pass";
  72. }
  73. private:
  74. struct MemOpQueueEntry {
  75. int Offset;
  76. unsigned Reg;
  77. bool isKill;
  78. unsigned Position;
  79. MachineBasicBlock::iterator MBBI;
  80. bool Merged;
  81. MemOpQueueEntry(int o, unsigned r, bool k, unsigned p,
  82. MachineBasicBlock::iterator i)
  83. : Offset(o), Reg(r), isKill(k), Position(p), MBBI(i), Merged(false) {}
  84. };
  85. typedef SmallVector<MemOpQueueEntry,8> MemOpQueue;
  86. typedef MemOpQueue::iterator MemOpQueueIter;
  87. void findUsesOfImpDef(SmallVectorImpl<MachineOperand *> &UsesOfImpDefs,
  88. const MemOpQueue &MemOps, unsigned DefReg,
  89. unsigned RangeBegin, unsigned RangeEnd);
  90. bool MergeOps(MachineBasicBlock &MBB, MachineBasicBlock::iterator MBBI,
  91. int Offset, unsigned Base, bool BaseKill, int Opcode,
  92. ARMCC::CondCodes Pred, unsigned PredReg, unsigned Scratch,
  93. DebugLoc dl,
  94. ArrayRef<std::pair<unsigned, bool> > Regs,
  95. ArrayRef<unsigned> ImpDefs);
  96. void MergeOpsUpdate(MachineBasicBlock &MBB,
  97. MemOpQueue &MemOps,
  98. unsigned memOpsBegin,
  99. unsigned memOpsEnd,
  100. unsigned insertAfter,
  101. int Offset,
  102. unsigned Base,
  103. bool BaseKill,
  104. int Opcode,
  105. ARMCC::CondCodes Pred,
  106. unsigned PredReg,
  107. unsigned Scratch,
  108. DebugLoc dl,
  109. SmallVectorImpl<MachineBasicBlock::iterator> &Merges);
  110. void MergeLDR_STR(MachineBasicBlock &MBB, unsigned SIndex, unsigned Base,
  111. int Opcode, unsigned Size,
  112. ARMCC::CondCodes Pred, unsigned PredReg,
  113. unsigned Scratch, MemOpQueue &MemOps,
  114. SmallVectorImpl<MachineBasicBlock::iterator> &Merges);
  115. void AdvanceRS(MachineBasicBlock &MBB, MemOpQueue &MemOps);
  116. bool FixInvalidRegPairOp(MachineBasicBlock &MBB,
  117. MachineBasicBlock::iterator &MBBI);
  118. bool MergeBaseUpdateLoadStore(MachineBasicBlock &MBB,
  119. MachineBasicBlock::iterator MBBI,
  120. const TargetInstrInfo *TII,
  121. bool &Advance,
  122. MachineBasicBlock::iterator &I);
  123. bool MergeBaseUpdateLSMultiple(MachineBasicBlock &MBB,
  124. MachineBasicBlock::iterator MBBI,
  125. bool &Advance,
  126. MachineBasicBlock::iterator &I);
  127. bool LoadStoreMultipleOpti(MachineBasicBlock &MBB);
  128. bool MergeReturnIntoLDM(MachineBasicBlock &MBB);
  129. };
  130. char ARMLoadStoreOpt::ID = 0;
  131. }
  132. static int getLoadStoreMultipleOpcode(int Opcode, ARM_AM::AMSubMode Mode) {
  133. switch (Opcode) {
  134. default: llvm_unreachable("Unhandled opcode!");
  135. case ARM::LDRi12:
  136. ++NumLDMGened;
  137. switch (Mode) {
  138. default: llvm_unreachable("Unhandled submode!");
  139. case ARM_AM::ia: return ARM::LDMIA;
  140. case ARM_AM::da: return ARM::LDMDA;
  141. case ARM_AM::db: return ARM::LDMDB;
  142. case ARM_AM::ib: return ARM::LDMIB;
  143. }
  144. case ARM::STRi12:
  145. ++NumSTMGened;
  146. switch (Mode) {
  147. default: llvm_unreachable("Unhandled submode!");
  148. case ARM_AM::ia: return ARM::STMIA;
  149. case ARM_AM::da: return ARM::STMDA;
  150. case ARM_AM::db: return ARM::STMDB;
  151. case ARM_AM::ib: return ARM::STMIB;
  152. }
  153. case ARM::tLDRi:
  154. // tLDMIA is writeback-only - unless the base register is in the input
  155. // reglist.
  156. ++NumLDMGened;
  157. switch (Mode) {
  158. default: llvm_unreachable("Unhandled submode!");
  159. case ARM_AM::ia: return ARM::tLDMIA;
  160. }
  161. case ARM::tSTRi:
  162. // There is no non-writeback tSTMIA either.
  163. ++NumSTMGened;
  164. switch (Mode) {
  165. default: llvm_unreachable("Unhandled submode!");
  166. case ARM_AM::ia: return ARM::tSTMIA_UPD;
  167. }
  168. case ARM::t2LDRi8:
  169. case ARM::t2LDRi12:
  170. ++NumLDMGened;
  171. switch (Mode) {
  172. default: llvm_unreachable("Unhandled submode!");
  173. case ARM_AM::ia: return ARM::t2LDMIA;
  174. case ARM_AM::db: return ARM::t2LDMDB;
  175. }
  176. case ARM::t2STRi8:
  177. case ARM::t2STRi12:
  178. ++NumSTMGened;
  179. switch (Mode) {
  180. default: llvm_unreachable("Unhandled submode!");
  181. case ARM_AM::ia: return ARM::t2STMIA;
  182. case ARM_AM::db: return ARM::t2STMDB;
  183. }
  184. case ARM::VLDRS:
  185. ++NumVLDMGened;
  186. switch (Mode) {
  187. default: llvm_unreachable("Unhandled submode!");
  188. case ARM_AM::ia: return ARM::VLDMSIA;
  189. case ARM_AM::db: return 0; // Only VLDMSDB_UPD exists.
  190. }
  191. case ARM::VSTRS:
  192. ++NumVSTMGened;
  193. switch (Mode) {
  194. default: llvm_unreachable("Unhandled submode!");
  195. case ARM_AM::ia: return ARM::VSTMSIA;
  196. case ARM_AM::db: return 0; // Only VSTMSDB_UPD exists.
  197. }
  198. case ARM::VLDRD:
  199. ++NumVLDMGened;
  200. switch (Mode) {
  201. default: llvm_unreachable("Unhandled submode!");
  202. case ARM_AM::ia: return ARM::VLDMDIA;
  203. case ARM_AM::db: return 0; // Only VLDMDDB_UPD exists.
  204. }
  205. case ARM::VSTRD:
  206. ++NumVSTMGened;
  207. switch (Mode) {
  208. default: llvm_unreachable("Unhandled submode!");
  209. case ARM_AM::ia: return ARM::VSTMDIA;
  210. case ARM_AM::db: return 0; // Only VSTMDDB_UPD exists.
  211. }
  212. }
  213. }
  214. namespace llvm {
  215. namespace ARM_AM {
  216. AMSubMode getLoadStoreMultipleSubMode(int Opcode) {
  217. switch (Opcode) {
  218. default: llvm_unreachable("Unhandled opcode!");
  219. case ARM::LDMIA_RET:
  220. case ARM::LDMIA:
  221. case ARM::LDMIA_UPD:
  222. case ARM::STMIA:
  223. case ARM::STMIA_UPD:
  224. case ARM::tLDMIA:
  225. case ARM::tLDMIA_UPD:
  226. case ARM::tSTMIA_UPD:
  227. case ARM::t2LDMIA_RET:
  228. case ARM::t2LDMIA:
  229. case ARM::t2LDMIA_UPD:
  230. case ARM::t2STMIA:
  231. case ARM::t2STMIA_UPD:
  232. case ARM::VLDMSIA:
  233. case ARM::VLDMSIA_UPD:
  234. case ARM::VSTMSIA:
  235. case ARM::VSTMSIA_UPD:
  236. case ARM::VLDMDIA:
  237. case ARM::VLDMDIA_UPD:
  238. case ARM::VSTMDIA:
  239. case ARM::VSTMDIA_UPD:
  240. return ARM_AM::ia;
  241. case ARM::LDMDA:
  242. case ARM::LDMDA_UPD:
  243. case ARM::STMDA:
  244. case ARM::STMDA_UPD:
  245. return ARM_AM::da;
  246. case ARM::LDMDB:
  247. case ARM::LDMDB_UPD:
  248. case ARM::STMDB:
  249. case ARM::STMDB_UPD:
  250. case ARM::t2LDMDB:
  251. case ARM::t2LDMDB_UPD:
  252. case ARM::t2STMDB:
  253. case ARM::t2STMDB_UPD:
  254. case ARM::VLDMSDB_UPD:
  255. case ARM::VSTMSDB_UPD:
  256. case ARM::VLDMDDB_UPD:
  257. case ARM::VSTMDDB_UPD:
  258. return ARM_AM::db;
  259. case ARM::LDMIB:
  260. case ARM::LDMIB_UPD:
  261. case ARM::STMIB:
  262. case ARM::STMIB_UPD:
  263. return ARM_AM::ib;
  264. }
  265. }
  266. } // end namespace ARM_AM
  267. } // end namespace llvm
  268. static bool isT1i32Load(unsigned Opc) {
  269. return Opc == ARM::tLDRi;
  270. }
  271. static bool isT2i32Load(unsigned Opc) {
  272. return Opc == ARM::t2LDRi12 || Opc == ARM::t2LDRi8;
  273. }
  274. static bool isi32Load(unsigned Opc) {
  275. return Opc == ARM::LDRi12 || isT1i32Load(Opc) || isT2i32Load(Opc) ;
  276. }
  277. static bool isT1i32Store(unsigned Opc) {
  278. return Opc == ARM::tSTRi;
  279. }
  280. static bool isT2i32Store(unsigned Opc) {
  281. return Opc == ARM::t2STRi12 || Opc == ARM::t2STRi8;
  282. }
  283. static bool isi32Store(unsigned Opc) {
  284. return Opc == ARM::STRi12 || isT1i32Store(Opc) || isT2i32Store(Opc);
  285. }
  286. /// MergeOps - Create and insert a LDM or STM with Base as base register and
  287. /// registers in Regs as the register operands that would be loaded / stored.
  288. /// It returns true if the transformation is done.
  289. bool
  290. ARMLoadStoreOpt::MergeOps(MachineBasicBlock &MBB,
  291. MachineBasicBlock::iterator MBBI,
  292. int Offset, unsigned Base, bool BaseKill,
  293. int Opcode, ARMCC::CondCodes Pred,
  294. unsigned PredReg, unsigned Scratch, DebugLoc dl,
  295. ArrayRef<std::pair<unsigned, bool> > Regs,
  296. ArrayRef<unsigned> ImpDefs) {
  297. // Only a single register to load / store. Don't bother.
  298. unsigned NumRegs = Regs.size();
  299. if (NumRegs <= 1)
  300. return false;
  301. ARM_AM::AMSubMode Mode = ARM_AM::ia;
  302. // VFP and Thumb2 do not support IB or DA modes. Thumb1 only supports IA.
  303. bool isNotVFP = isi32Load(Opcode) || isi32Store(Opcode);
  304. bool haveIBAndDA = isNotVFP && !isThumb2 && !isThumb1;
  305. if (Offset == 4 && haveIBAndDA) {
  306. Mode = ARM_AM::ib;
  307. } else if (Offset == -4 * (int)NumRegs + 4 && haveIBAndDA) {
  308. Mode = ARM_AM::da;
  309. } else if (Offset == -4 * (int)NumRegs && isNotVFP && !isThumb1) {
  310. // VLDM/VSTM do not support DB mode without also updating the base reg.
  311. Mode = ARM_AM::db;
  312. } else if (Offset != 0) {
  313. // Check if this is a supported opcode before inserting instructions to
  314. // calculate a new base register.
  315. if (!getLoadStoreMultipleOpcode(Opcode, Mode)) return false;
  316. // If starting offset isn't zero, insert a MI to materialize a new base.
  317. // But only do so if it is cost effective, i.e. merging more than two
  318. // loads / stores.
  319. if (NumRegs <= 2)
  320. return false;
  321. unsigned NewBase;
  322. if (isi32Load(Opcode)) {
  323. // If it is a load, then just use one of the destination register to
  324. // use as the new base.
  325. NewBase = Regs[NumRegs-1].first;
  326. } else {
  327. // Use the scratch register to use as a new base.
  328. NewBase = Scratch;
  329. if (NewBase == 0)
  330. return false;
  331. }
  332. int BaseOpc =
  333. isThumb2 ? ARM::t2ADDri :
  334. isThumb1 ? ARM::tADDi8 : ARM::ADDri;
  335. if (Offset < 0) {
  336. BaseOpc =
  337. isThumb2 ? ARM::t2SUBri :
  338. isThumb1 ? ARM::tSUBi8 : ARM::SUBri;
  339. Offset = - Offset;
  340. }
  341. if (!TL->isLegalAddImmediate(Offset))
  342. // FIXME: Try add with register operand?
  343. return false; // Probably not worth it then.
  344. if (isThumb1) {
  345. if (Base != NewBase) {
  346. // Need to insert a MOV to the new base first.
  347. // FIXME: If the immediate fits in 3 bits, use ADD instead.
  348. BuildMI(MBB, MBBI, dl, TII->get(ARM::tMOVr), NewBase)
  349. .addReg(Base, getKillRegState(BaseKill))
  350. .addImm(Pred).addReg(PredReg);
  351. }
  352. AddDefaultT1CC(BuildMI(MBB, MBBI, dl, TII->get(BaseOpc), NewBase))
  353. .addReg(NewBase, getKillRegState(true)).addImm(Offset)
  354. .addImm(Pred).addReg(PredReg);
  355. } else {
  356. BuildMI(MBB, MBBI, dl, TII->get(BaseOpc), NewBase)
  357. .addReg(Base, getKillRegState(BaseKill)).addImm(Offset)
  358. .addImm(Pred).addReg(PredReg).addReg(0);
  359. }
  360. Base = NewBase;
  361. BaseKill = true; // New base is always killed straight away.
  362. }
  363. bool isDef = (isi32Load(Opcode) || Opcode == ARM::VLDRS ||
  364. Opcode == ARM::VLDRD);
  365. // Get LS multiple opcode. Note that for Thumb1 this might be an opcode with
  366. // base register writeback.
  367. Opcode = getLoadStoreMultipleOpcode(Opcode, Mode);
  368. if (!Opcode) return false;
  369. bool Writeback = isThumb1; // Thumb1 LDM/STM have base reg writeback.
  370. // Exception: If the base register is in the input reglist, Thumb1 LDM is
  371. // non-writeback. Check for this.
  372. if (Opcode == ARM::tLDMIA && isThumb1)
  373. for (unsigned I = 0; I < NumRegs; ++I)
  374. if (Base == Regs[I].first) {
  375. Writeback = false;
  376. break;
  377. }
  378. // If the merged instruction has writeback and the base register is not killed
  379. // it's not safe to do the merge on Thumb1. This is because resetting the base
  380. // register writeback by inserting a SUBS sets the condition flags.
  381. // FIXME: Try something clever here to see if resetting the base register can
  382. // be avoided, e.g. by updating a later ADD/SUB of the base register with the
  383. // writeback.
  384. if (isThumb1 && Writeback && !BaseKill) return false;
  385. MachineInstrBuilder MIB;
  386. if (Writeback) {
  387. if (Opcode == ARM::tLDMIA)
  388. // Update tLDMIA with writeback if necessary.
  389. Opcode = ARM::tLDMIA_UPD;
  390. MIB = BuildMI(MBB, MBBI, dl, TII->get(Opcode));
  391. // Thumb1: we might need to set base writeback when building the MI.
  392. MIB.addReg(Base, getDefRegState(true))
  393. .addReg(Base, getKillRegState(BaseKill));
  394. } else {
  395. // No writeback, simply build the MachineInstr.
  396. MIB = BuildMI(MBB, MBBI, dl, TII->get(Opcode));
  397. MIB.addReg(Base, getKillRegState(BaseKill));
  398. }
  399. MIB.addImm(Pred).addReg(PredReg);
  400. for (unsigned i = 0; i != NumRegs; ++i)
  401. MIB = MIB.addReg(Regs[i].first, getDefRegState(isDef)
  402. | getKillRegState(Regs[i].second));
  403. // Add implicit defs for super-registers.
  404. for (unsigned i = 0, e = ImpDefs.size(); i != e; ++i)
  405. MIB.addReg(ImpDefs[i], RegState::ImplicitDefine);
  406. return true;
  407. }
  408. /// \brief Find all instructions using a given imp-def within a range.
  409. ///
  410. /// We are trying to combine a range of instructions, one of which (located at
  411. /// position RangeBegin) implicitly defines a register. The final LDM/STM will
  412. /// be placed at RangeEnd, and so any uses of this definition between RangeStart
  413. /// and RangeEnd must be modified to use an undefined value.
  414. ///
  415. /// The live range continues until we find a second definition or one of the
  416. /// uses we find is a kill. Unfortunately MemOps is not sorted by Position, so
  417. /// we must consider all uses and decide which are relevant in a second pass.
  418. void ARMLoadStoreOpt::findUsesOfImpDef(
  419. SmallVectorImpl<MachineOperand *> &UsesOfImpDefs, const MemOpQueue &MemOps,
  420. unsigned DefReg, unsigned RangeBegin, unsigned RangeEnd) {
  421. std::map<unsigned, MachineOperand *> Uses;
  422. unsigned LastLivePos = RangeEnd;
  423. // First we find all uses of this register with Position between RangeBegin
  424. // and RangeEnd, any or all of these could be uses of a definition at
  425. // RangeBegin. We also record the latest position a definition at RangeBegin
  426. // would be considered live.
  427. for (unsigned i = 0; i < MemOps.size(); ++i) {
  428. MachineInstr &MI = *MemOps[i].MBBI;
  429. unsigned MIPosition = MemOps[i].Position;
  430. if (MIPosition <= RangeBegin || MIPosition > RangeEnd)
  431. continue;
  432. // If this instruction defines the register, then any later use will be of
  433. // that definition rather than ours.
  434. if (MI.definesRegister(DefReg))
  435. LastLivePos = std::min(LastLivePos, MIPosition);
  436. MachineOperand *UseOp = MI.findRegisterUseOperand(DefReg);
  437. if (!UseOp)
  438. continue;
  439. // If this instruction kills the register then (assuming liveness is
  440. // correct when we start) we don't need to think about anything after here.
  441. if (UseOp->isKill())
  442. LastLivePos = std::min(LastLivePos, MIPosition);
  443. Uses[MIPosition] = UseOp;
  444. }
  445. // Now we traverse the list of all uses, and append the ones that actually use
  446. // our definition to the requested list.
  447. for (std::map<unsigned, MachineOperand *>::iterator I = Uses.begin(),
  448. E = Uses.end();
  449. I != E; ++I) {
  450. // List is sorted by position so once we've found one out of range there
  451. // will be no more to consider.
  452. if (I->first > LastLivePos)
  453. break;
  454. UsesOfImpDefs.push_back(I->second);
  455. }
  456. }
  457. // MergeOpsUpdate - call MergeOps and update MemOps and merges accordingly on
  458. // success.
  459. void ARMLoadStoreOpt::MergeOpsUpdate(MachineBasicBlock &MBB,
  460. MemOpQueue &memOps,
  461. unsigned memOpsBegin, unsigned memOpsEnd,
  462. unsigned insertAfter, int Offset,
  463. unsigned Base, bool BaseKill,
  464. int Opcode,
  465. ARMCC::CondCodes Pred, unsigned PredReg,
  466. unsigned Scratch,
  467. DebugLoc dl,
  468. SmallVectorImpl<MachineBasicBlock::iterator> &Merges) {
  469. // First calculate which of the registers should be killed by the merged
  470. // instruction.
  471. const unsigned insertPos = memOps[insertAfter].Position;
  472. SmallSet<unsigned, 4> KilledRegs;
  473. DenseMap<unsigned, unsigned> Killer;
  474. for (unsigned i = 0, e = memOps.size(); i != e; ++i) {
  475. if (i == memOpsBegin) {
  476. i = memOpsEnd;
  477. if (i == e)
  478. break;
  479. }
  480. if (memOps[i].Position < insertPos && memOps[i].isKill) {
  481. unsigned Reg = memOps[i].Reg;
  482. KilledRegs.insert(Reg);
  483. Killer[Reg] = i;
  484. }
  485. }
  486. SmallVector<std::pair<unsigned, bool>, 8> Regs;
  487. SmallVector<unsigned, 8> ImpDefs;
  488. SmallVector<MachineOperand *, 8> UsesOfImpDefs;
  489. for (unsigned i = memOpsBegin; i < memOpsEnd; ++i) {
  490. unsigned Reg = memOps[i].Reg;
  491. // If we are inserting the merged operation after an operation that
  492. // uses the same register, make sure to transfer any kill flag.
  493. bool isKill = memOps[i].isKill || KilledRegs.count(Reg);
  494. Regs.push_back(std::make_pair(Reg, isKill));
  495. // Collect any implicit defs of super-registers. They must be preserved.
  496. for (MIOperands MO(memOps[i].MBBI); MO.isValid(); ++MO) {
  497. if (!MO->isReg() || !MO->isDef() || !MO->isImplicit() || MO->isDead())
  498. continue;
  499. unsigned DefReg = MO->getReg();
  500. if (std::find(ImpDefs.begin(), ImpDefs.end(), DefReg) == ImpDefs.end())
  501. ImpDefs.push_back(DefReg);
  502. // There may be other uses of the definition between this instruction and
  503. // the eventual LDM/STM position. These should be marked undef if the
  504. // merge takes place.
  505. findUsesOfImpDef(UsesOfImpDefs, memOps, DefReg, memOps[i].Position,
  506. insertPos);
  507. }
  508. }
  509. // Try to do the merge.
  510. MachineBasicBlock::iterator Loc = memOps[insertAfter].MBBI;
  511. ++Loc;
  512. if (!MergeOps(MBB, Loc, Offset, Base, BaseKill, Opcode,
  513. Pred, PredReg, Scratch, dl, Regs, ImpDefs))
  514. return;
  515. // Merge succeeded, update records.
  516. Merges.push_back(std::prev(Loc));
  517. // In gathering loads together, we may have moved the imp-def of a register
  518. // past one of its uses. This is OK, since we know better than the rest of
  519. // LLVM what's OK with ARM loads and stores; but we still have to adjust the
  520. // affected uses.
  521. for (SmallVectorImpl<MachineOperand *>::iterator I = UsesOfImpDefs.begin(),
  522. E = UsesOfImpDefs.end();
  523. I != E; ++I)
  524. (*I)->setIsUndef();
  525. for (unsigned i = memOpsBegin; i < memOpsEnd; ++i) {
  526. // Remove kill flags from any memops that come before insertPos.
  527. if (Regs[i-memOpsBegin].second) {
  528. unsigned Reg = Regs[i-memOpsBegin].first;
  529. if (KilledRegs.count(Reg)) {
  530. unsigned j = Killer[Reg];
  531. int Idx = memOps[j].MBBI->findRegisterUseOperandIdx(Reg, true);
  532. assert(Idx >= 0 && "Cannot find killing operand");
  533. memOps[j].MBBI->getOperand(Idx).setIsKill(false);
  534. memOps[j].isKill = false;
  535. }
  536. memOps[i].isKill = true;
  537. }
  538. MBB.erase(memOps[i].MBBI);
  539. // Update this memop to refer to the merged instruction.
  540. // We may need to move kill flags again.
  541. memOps[i].Merged = true;
  542. memOps[i].MBBI = Merges.back();
  543. memOps[i].Position = insertPos;
  544. }
  545. }
  546. /// MergeLDR_STR - Merge a number of load / store instructions into one or more
  547. /// load / store multiple instructions.
  548. void
  549. ARMLoadStoreOpt::MergeLDR_STR(MachineBasicBlock &MBB, unsigned SIndex,
  550. unsigned Base, int Opcode, unsigned Size,
  551. ARMCC::CondCodes Pred, unsigned PredReg,
  552. unsigned Scratch, MemOpQueue &MemOps,
  553. SmallVectorImpl<MachineBasicBlock::iterator> &Merges) {
  554. bool isNotVFP = isi32Load(Opcode) || isi32Store(Opcode);
  555. int Offset = MemOps[SIndex].Offset;
  556. int SOffset = Offset;
  557. unsigned insertAfter = SIndex;
  558. MachineBasicBlock::iterator Loc = MemOps[SIndex].MBBI;
  559. DebugLoc dl = Loc->getDebugLoc();
  560. const MachineOperand &PMO = Loc->getOperand(0);
  561. unsigned PReg = PMO.getReg();
  562. unsigned PRegNum = PMO.isUndef() ? UINT_MAX : TRI->getEncodingValue(PReg);
  563. unsigned Count = 1;
  564. unsigned Limit = ~0U;
  565. bool BaseKill = false;
  566. // vldm / vstm limit are 32 for S variants, 16 for D variants.
  567. switch (Opcode) {
  568. default: break;
  569. case ARM::VSTRS:
  570. Limit = 32;
  571. break;
  572. case ARM::VSTRD:
  573. Limit = 16;
  574. break;
  575. case ARM::VLDRD:
  576. Limit = 16;
  577. break;
  578. case ARM::VLDRS:
  579. Limit = 32;
  580. break;
  581. }
  582. for (unsigned i = SIndex+1, e = MemOps.size(); i != e; ++i) {
  583. int NewOffset = MemOps[i].Offset;
  584. const MachineOperand &MO = MemOps[i].MBBI->getOperand(0);
  585. unsigned Reg = MO.getReg();
  586. unsigned RegNum = MO.isUndef() ? UINT_MAX : TRI->getEncodingValue(Reg);
  587. // Register numbers must be in ascending order. For VFP / NEON load and
  588. // store multiples, the registers must also be consecutive and within the
  589. // limit on the number of registers per instruction.
  590. if (Reg != ARM::SP &&
  591. NewOffset == Offset + (int)Size &&
  592. ((isNotVFP && RegNum > PRegNum) ||
  593. ((Count < Limit) && RegNum == PRegNum+1)) &&
  594. // On Swift we don't want vldm/vstm to start with a odd register num
  595. // because Q register unaligned vldm/vstm need more uops.
  596. (!STI->isSwift() || isNotVFP || Count != 1 || !(PRegNum & 0x1))) {
  597. Offset += Size;
  598. PRegNum = RegNum;
  599. ++Count;
  600. } else {
  601. // Can't merge this in. Try merge the earlier ones first.
  602. // We need to compute BaseKill here because the MemOps may have been
  603. // reordered.
  604. BaseKill = Loc->killsRegister(Base);
  605. MergeOpsUpdate(MBB, MemOps, SIndex, i, insertAfter, SOffset, Base,
  606. BaseKill, Opcode, Pred, PredReg, Scratch, dl, Merges);
  607. MergeLDR_STR(MBB, i, Base, Opcode, Size, Pred, PredReg, Scratch,
  608. MemOps, Merges);
  609. return;
  610. }
  611. if (MemOps[i].Position > MemOps[insertAfter].Position) {
  612. insertAfter = i;
  613. Loc = MemOps[i].MBBI;
  614. }
  615. }
  616. BaseKill = Loc->killsRegister(Base);
  617. MergeOpsUpdate(MBB, MemOps, SIndex, MemOps.size(), insertAfter, SOffset,
  618. Base, BaseKill, Opcode, Pred, PredReg, Scratch, dl, Merges);
  619. }
  620. static bool definesCPSR(MachineInstr *MI) {
  621. for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
  622. const MachineOperand &MO = MI->getOperand(i);
  623. if (!MO.isReg())
  624. continue;
  625. if (MO.isDef() && MO.getReg() == ARM::CPSR && !MO.isDead())
  626. // If the instruction has live CPSR def, then it's not safe to fold it
  627. // into load / store.
  628. return true;
  629. }
  630. return false;
  631. }
  632. static bool isMatchingDecrement(MachineInstr *MI, unsigned Base,
  633. unsigned Bytes, unsigned Limit,
  634. ARMCC::CondCodes Pred, unsigned PredReg) {
  635. unsigned MyPredReg = 0;
  636. if (!MI)
  637. return false;
  638. bool CheckCPSRDef = false;
  639. switch (MI->getOpcode()) {
  640. default: return false;
  641. case ARM::tSUBi8:
  642. case ARM::t2SUBri:
  643. case ARM::SUBri:
  644. CheckCPSRDef = true;
  645. // fallthrough
  646. case ARM::tSUBspi:
  647. break;
  648. }
  649. // Make sure the offset fits in 8 bits.
  650. if (Bytes == 0 || (Limit && Bytes >= Limit))
  651. return false;
  652. unsigned Scale = (MI->getOpcode() == ARM::tSUBspi ||
  653. MI->getOpcode() == ARM::tSUBi8) ? 4 : 1; // FIXME
  654. if (!(MI->getOperand(0).getReg() == Base &&
  655. MI->getOperand(1).getReg() == Base &&
  656. (MI->getOperand(2).getImm() * Scale) == Bytes &&
  657. getInstrPredicate(MI, MyPredReg) == Pred &&
  658. MyPredReg == PredReg))
  659. return false;
  660. return CheckCPSRDef ? !definesCPSR(MI) : true;
  661. }
  662. static bool isMatchingIncrement(MachineInstr *MI, unsigned Base,
  663. unsigned Bytes, unsigned Limit,
  664. ARMCC::CondCodes Pred, unsigned PredReg) {
  665. unsigned MyPredReg = 0;
  666. if (!MI)
  667. return false;
  668. bool CheckCPSRDef = false;
  669. switch (MI->getOpcode()) {
  670. default: return false;
  671. case ARM::tADDi8:
  672. case ARM::t2ADDri:
  673. case ARM::ADDri:
  674. CheckCPSRDef = true;
  675. // fallthrough
  676. case ARM::tADDspi:
  677. break;
  678. }
  679. if (Bytes == 0 || (Limit && Bytes >= Limit))
  680. // Make sure the offset fits in 8 bits.
  681. return false;
  682. unsigned Scale = (MI->getOpcode() == ARM::tADDspi ||
  683. MI->getOpcode() == ARM::tADDi8) ? 4 : 1; // FIXME
  684. if (!(MI->getOperand(0).getReg() == Base &&
  685. MI->getOperand(1).getReg() == Base &&
  686. (MI->getOperand(2).getImm() * Scale) == Bytes &&
  687. getInstrPredicate(MI, MyPredReg) == Pred &&
  688. MyPredReg == PredReg))
  689. return false;
  690. return CheckCPSRDef ? !definesCPSR(MI) : true;
  691. }
  692. static inline unsigned getLSMultipleTransferSize(MachineInstr *MI) {
  693. switch (MI->getOpcode()) {
  694. default: return 0;
  695. case ARM::LDRi12:
  696. case ARM::STRi12:
  697. case ARM::tLDRi:
  698. case ARM::tSTRi:
  699. case ARM::t2LDRi8:
  700. case ARM::t2LDRi12:
  701. case ARM::t2STRi8:
  702. case ARM::t2STRi12:
  703. case ARM::VLDRS:
  704. case ARM::VSTRS:
  705. return 4;
  706. case ARM::VLDRD:
  707. case ARM::VSTRD:
  708. return 8;
  709. case ARM::LDMIA:
  710. case ARM::LDMDA:
  711. case ARM::LDMDB:
  712. case ARM::LDMIB:
  713. case ARM::STMIA:
  714. case ARM::STMDA:
  715. case ARM::STMDB:
  716. case ARM::STMIB:
  717. case ARM::tLDMIA:
  718. case ARM::tLDMIA_UPD:
  719. case ARM::tSTMIA_UPD:
  720. case ARM::t2LDMIA:
  721. case ARM::t2LDMDB:
  722. case ARM::t2STMIA:
  723. case ARM::t2STMDB:
  724. case ARM::VLDMSIA:
  725. case ARM::VSTMSIA:
  726. return (MI->getNumOperands() - MI->getDesc().getNumOperands() + 1) * 4;
  727. case ARM::VLDMDIA:
  728. case ARM::VSTMDIA:
  729. return (MI->getNumOperands() - MI->getDesc().getNumOperands() + 1) * 8;
  730. }
  731. }
  732. static unsigned getUpdatingLSMultipleOpcode(unsigned Opc,
  733. ARM_AM::AMSubMode Mode) {
  734. switch (Opc) {
  735. default: llvm_unreachable("Unhandled opcode!");
  736. case ARM::LDMIA:
  737. case ARM::LDMDA:
  738. case ARM::LDMDB:
  739. case ARM::LDMIB:
  740. switch (Mode) {
  741. default: llvm_unreachable("Unhandled submode!");
  742. case ARM_AM::ia: return ARM::LDMIA_UPD;
  743. case ARM_AM::ib: return ARM::LDMIB_UPD;
  744. case ARM_AM::da: return ARM::LDMDA_UPD;
  745. case ARM_AM::db: return ARM::LDMDB_UPD;
  746. }
  747. case ARM::STMIA:
  748. case ARM::STMDA:
  749. case ARM::STMDB:
  750. case ARM::STMIB:
  751. switch (Mode) {
  752. default: llvm_unreachable("Unhandled submode!");
  753. case ARM_AM::ia: return ARM::STMIA_UPD;
  754. case ARM_AM::ib: return ARM::STMIB_UPD;
  755. case ARM_AM::da: return ARM::STMDA_UPD;
  756. case ARM_AM::db: return ARM::STMDB_UPD;
  757. }
  758. case ARM::t2LDMIA:
  759. case ARM::t2LDMDB:
  760. switch (Mode) {
  761. default: llvm_unreachable("Unhandled submode!");
  762. case ARM_AM::ia: return ARM::t2LDMIA_UPD;
  763. case ARM_AM::db: return ARM::t2LDMDB_UPD;
  764. }
  765. case ARM::t2STMIA:
  766. case ARM::t2STMDB:
  767. switch (Mode) {
  768. default: llvm_unreachable("Unhandled submode!");
  769. case ARM_AM::ia: return ARM::t2STMIA_UPD;
  770. case ARM_AM::db: return ARM::t2STMDB_UPD;
  771. }
  772. case ARM::VLDMSIA:
  773. switch (Mode) {
  774. default: llvm_unreachable("Unhandled submode!");
  775. case ARM_AM::ia: return ARM::VLDMSIA_UPD;
  776. case ARM_AM::db: return ARM::VLDMSDB_UPD;
  777. }
  778. case ARM::VLDMDIA:
  779. switch (Mode) {
  780. default: llvm_unreachable("Unhandled submode!");
  781. case ARM_AM::ia: return ARM::VLDMDIA_UPD;
  782. case ARM_AM::db: return ARM::VLDMDDB_UPD;
  783. }
  784. case ARM::VSTMSIA:
  785. switch (Mode) {
  786. default: llvm_unreachable("Unhandled submode!");
  787. case ARM_AM::ia: return ARM::VSTMSIA_UPD;
  788. case ARM_AM::db: return ARM::VSTMSDB_UPD;
  789. }
  790. case ARM::VSTMDIA:
  791. switch (Mode) {
  792. default: llvm_unreachable("Unhandled submode!");
  793. case ARM_AM::ia: return ARM::VSTMDIA_UPD;
  794. case ARM_AM::db: return ARM::VSTMDDB_UPD;
  795. }
  796. }
  797. }
  798. /// MergeBaseUpdateLSMultiple - Fold proceeding/trailing inc/dec of base
  799. /// register into the LDM/STM/VLDM{D|S}/VSTM{D|S} op when possible:
  800. ///
  801. /// stmia rn, <ra, rb, rc>
  802. /// rn := rn + 4 * 3;
  803. /// =>
  804. /// stmia rn!, <ra, rb, rc>
  805. ///
  806. /// rn := rn - 4 * 3;
  807. /// ldmia rn, <ra, rb, rc>
  808. /// =>
  809. /// ldmdb rn!, <ra, rb, rc>
  810. bool ARMLoadStoreOpt::MergeBaseUpdateLSMultiple(MachineBasicBlock &MBB,
  811. MachineBasicBlock::iterator MBBI,
  812. bool &Advance,
  813. MachineBasicBlock::iterator &I) {
  814. // Thumb1 is already using updating loads/stores.
  815. if (isThumb1) return false;
  816. MachineInstr *MI = MBBI;
  817. unsigned Base = MI->getOperand(0).getReg();
  818. bool BaseKill = MI->getOperand(0).isKill();
  819. unsigned Bytes = getLSMultipleTransferSize(MI);
  820. unsigned PredReg = 0;
  821. ARMCC::CondCodes Pred = getInstrPredicate(MI, PredReg);
  822. int Opcode = MI->getOpcode();
  823. DebugLoc dl = MI->getDebugLoc();
  824. // Can't use an updating ld/st if the base register is also a dest
  825. // register. e.g. ldmdb r0!, {r0, r1, r2}. The behavior is undefined.
  826. for (unsigned i = 2, e = MI->getNumOperands(); i != e; ++i)
  827. if (MI->getOperand(i).getReg() == Base)
  828. return false;
  829. bool DoMerge = false;
  830. ARM_AM::AMSubMode Mode = ARM_AM::getLoadStoreMultipleSubMode(Opcode);
  831. // Try merging with the previous instruction.
  832. MachineBasicBlock::iterator BeginMBBI = MBB.begin();
  833. if (MBBI != BeginMBBI) {
  834. MachineBasicBlock::iterator PrevMBBI = std::prev(MBBI);
  835. while (PrevMBBI != BeginMBBI && PrevMBBI->isDebugValue())
  836. --PrevMBBI;
  837. if (Mode == ARM_AM::ia &&
  838. isMatchingDecrement(PrevMBBI, Base, Bytes, 0, Pred, PredReg)) {
  839. Mode = ARM_AM::db;
  840. DoMerge = true;
  841. } else if (Mode == ARM_AM::ib &&
  842. isMatchingDecrement(PrevMBBI, Base, Bytes, 0, Pred, PredReg)) {
  843. Mode = ARM_AM::da;
  844. DoMerge = true;
  845. }
  846. if (DoMerge)
  847. MBB.erase(PrevMBBI);
  848. }
  849. // Try merging with the next instruction.
  850. MachineBasicBlock::iterator EndMBBI = MBB.end();
  851. if (!DoMerge && MBBI != EndMBBI) {
  852. MachineBasicBlock::iterator NextMBBI = std::next(MBBI);
  853. while (NextMBBI != EndMBBI && NextMBBI->isDebugValue())
  854. ++NextMBBI;
  855. if ((Mode == ARM_AM::ia || Mode == ARM_AM::ib) &&
  856. isMatchingIncrement(NextMBBI, Base, Bytes, 0, Pred, PredReg)) {
  857. DoMerge = true;
  858. } else if ((Mode == ARM_AM::da || Mode == ARM_AM::db) &&
  859. isMatchingDecrement(NextMBBI, Base, Bytes, 0, Pred, PredReg)) {
  860. DoMerge = true;
  861. }
  862. if (DoMerge) {
  863. if (NextMBBI == I) {
  864. Advance = true;
  865. ++I;
  866. }
  867. MBB.erase(NextMBBI);
  868. }
  869. }
  870. if (!DoMerge)
  871. return false;
  872. unsigned NewOpc = getUpdatingLSMultipleOpcode(Opcode, Mode);
  873. MachineInstrBuilder MIB = BuildMI(MBB, MBBI, dl, TII->get(NewOpc))
  874. .addReg(Base, getDefRegState(true)) // WB base register
  875. .addReg(Base, getKillRegState(BaseKill))
  876. .addImm(Pred).addReg(PredReg);
  877. // Transfer the rest of operands.
  878. for (unsigned OpNum = 3, e = MI->getNumOperands(); OpNum != e; ++OpNum)
  879. MIB.addOperand(MI->getOperand(OpNum));
  880. // Transfer memoperands.
  881. MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
  882. MBB.erase(MBBI);
  883. return true;
  884. }
  885. static unsigned getPreIndexedLoadStoreOpcode(unsigned Opc,
  886. ARM_AM::AddrOpc Mode) {
  887. switch (Opc) {
  888. case ARM::LDRi12:
  889. return ARM::LDR_PRE_IMM;
  890. case ARM::STRi12:
  891. return ARM::STR_PRE_IMM;
  892. case ARM::VLDRS:
  893. return Mode == ARM_AM::add ? ARM::VLDMSIA_UPD : ARM::VLDMSDB_UPD;
  894. case ARM::VLDRD:
  895. return Mode == ARM_AM::add ? ARM::VLDMDIA_UPD : ARM::VLDMDDB_UPD;
  896. case ARM::VSTRS:
  897. return Mode == ARM_AM::add ? ARM::VSTMSIA_UPD : ARM::VSTMSDB_UPD;
  898. case ARM::VSTRD:
  899. return Mode == ARM_AM::add ? ARM::VSTMDIA_UPD : ARM::VSTMDDB_UPD;
  900. case ARM::t2LDRi8:
  901. case ARM::t2LDRi12:
  902. return ARM::t2LDR_PRE;
  903. case ARM::t2STRi8:
  904. case ARM::t2STRi12:
  905. return ARM::t2STR_PRE;
  906. default: llvm_unreachable("Unhandled opcode!");
  907. }
  908. }
  909. static unsigned getPostIndexedLoadStoreOpcode(unsigned Opc,
  910. ARM_AM::AddrOpc Mode) {
  911. switch (Opc) {
  912. case ARM::LDRi12:
  913. return ARM::LDR_POST_IMM;
  914. case ARM::STRi12:
  915. return ARM::STR_POST_IMM;
  916. case ARM::VLDRS:
  917. return Mode == ARM_AM::add ? ARM::VLDMSIA_UPD : ARM::VLDMSDB_UPD;
  918. case ARM::VLDRD:
  919. return Mode == ARM_AM::add ? ARM::VLDMDIA_UPD : ARM::VLDMDDB_UPD;
  920. case ARM::VSTRS:
  921. return Mode == ARM_AM::add ? ARM::VSTMSIA_UPD : ARM::VSTMSDB_UPD;
  922. case ARM::VSTRD:
  923. return Mode == ARM_AM::add ? ARM::VSTMDIA_UPD : ARM::VSTMDDB_UPD;
  924. case ARM::t2LDRi8:
  925. case ARM::t2LDRi12:
  926. return ARM::t2LDR_POST;
  927. case ARM::t2STRi8:
  928. case ARM::t2STRi12:
  929. return ARM::t2STR_POST;
  930. default: llvm_unreachable("Unhandled opcode!");
  931. }
  932. }
  933. /// MergeBaseUpdateLoadStore - Fold proceeding/trailing inc/dec of base
  934. /// register into the LDR/STR/FLD{D|S}/FST{D|S} op when possible:
  935. bool ARMLoadStoreOpt::MergeBaseUpdateLoadStore(MachineBasicBlock &MBB,
  936. MachineBasicBlock::iterator MBBI,
  937. const TargetInstrInfo *TII,
  938. bool &Advance,
  939. MachineBasicBlock::iterator &I) {
  940. // Thumb1 doesn't have updating LDR/STR.
  941. // FIXME: Use LDM/STM with single register instead.
  942. if (isThumb1) return false;
  943. MachineInstr *MI = MBBI;
  944. unsigned Base = MI->getOperand(1).getReg();
  945. bool BaseKill = MI->getOperand(1).isKill();
  946. unsigned Bytes = getLSMultipleTransferSize(MI);
  947. int Opcode = MI->getOpcode();
  948. DebugLoc dl = MI->getDebugLoc();
  949. bool isAM5 = (Opcode == ARM::VLDRD || Opcode == ARM::VLDRS ||
  950. Opcode == ARM::VSTRD || Opcode == ARM::VSTRS);
  951. bool isAM2 = (Opcode == ARM::LDRi12 || Opcode == ARM::STRi12);
  952. if (isi32Load(Opcode) || isi32Store(Opcode))
  953. if (MI->getOperand(2).getImm() != 0)
  954. return false;
  955. if (isAM5 && ARM_AM::getAM5Offset(MI->getOperand(2).getImm()) != 0)
  956. return false;
  957. bool isLd = isi32Load(Opcode) || Opcode == ARM::VLDRS || Opcode == ARM::VLDRD;
  958. // Can't do the merge if the destination register is the same as the would-be
  959. // writeback register.
  960. if (MI->getOperand(0).getReg() == Base)
  961. return false;
  962. unsigned PredReg = 0;
  963. ARMCC::CondCodes Pred = getInstrPredicate(MI, PredReg);
  964. bool DoMerge = false;
  965. ARM_AM::AddrOpc AddSub = ARM_AM::add;
  966. unsigned NewOpc = 0;
  967. // AM2 - 12 bits, thumb2 - 8 bits.
  968. unsigned Limit = isAM5 ? 0 : (isAM2 ? 0x1000 : 0x100);
  969. // Try merging with the previous instruction.
  970. MachineBasicBlock::iterator BeginMBBI = MBB.begin();
  971. if (MBBI != BeginMBBI) {
  972. MachineBasicBlock::iterator PrevMBBI = std::prev(MBBI);
  973. while (PrevMBBI != BeginMBBI && PrevMBBI->isDebugValue())
  974. --PrevMBBI;
  975. if (isMatchingDecrement(PrevMBBI, Base, Bytes, Limit, Pred, PredReg)) {
  976. DoMerge = true;
  977. AddSub = ARM_AM::sub;
  978. } else if (!isAM5 &&
  979. isMatchingIncrement(PrevMBBI, Base, Bytes, Limit,Pred,PredReg)) {
  980. DoMerge = true;
  981. }
  982. if (DoMerge) {
  983. NewOpc = getPreIndexedLoadStoreOpcode(Opcode, AddSub);
  984. MBB.erase(PrevMBBI);
  985. }
  986. }
  987. // Try merging with the next instruction.
  988. MachineBasicBlock::iterator EndMBBI = MBB.end();
  989. if (!DoMerge && MBBI != EndMBBI) {
  990. MachineBasicBlock::iterator NextMBBI = std::next(MBBI);
  991. while (NextMBBI != EndMBBI && NextMBBI->isDebugValue())
  992. ++NextMBBI;
  993. if (!isAM5 &&
  994. isMatchingDecrement(NextMBBI, Base, Bytes, Limit, Pred, PredReg)) {
  995. DoMerge = true;
  996. AddSub = ARM_AM::sub;
  997. } else if (isMatchingIncrement(NextMBBI, Base, Bytes, Limit,Pred,PredReg)) {
  998. DoMerge = true;
  999. }
  1000. if (DoMerge) {
  1001. NewOpc = getPostIndexedLoadStoreOpcode(Opcode, AddSub);
  1002. if (NextMBBI == I) {
  1003. Advance = true;
  1004. ++I;
  1005. }
  1006. MBB.erase(NextMBBI);
  1007. }
  1008. }
  1009. if (!DoMerge)
  1010. return false;
  1011. if (isAM5) {
  1012. // VLDM[SD]_UPD, VSTM[SD]_UPD
  1013. // (There are no base-updating versions of VLDR/VSTR instructions, but the
  1014. // updating load/store-multiple instructions can be used with only one
  1015. // register.)
  1016. MachineOperand &MO = MI->getOperand(0);
  1017. BuildMI(MBB, MBBI, dl, TII->get(NewOpc))
  1018. .addReg(Base, getDefRegState(true)) // WB base register
  1019. .addReg(Base, getKillRegState(isLd ? BaseKill : false))
  1020. .addImm(Pred).addReg(PredReg)
  1021. .addReg(MO.getReg(), (isLd ? getDefRegState(true) :
  1022. getKillRegState(MO.isKill())));
  1023. } else if (isLd) {
  1024. if (isAM2) {
  1025. // LDR_PRE, LDR_POST
  1026. if (NewOpc == ARM::LDR_PRE_IMM || NewOpc == ARM::LDRB_PRE_IMM) {
  1027. int Offset = AddSub == ARM_AM::sub ? -Bytes : Bytes;
  1028. BuildMI(MBB, MBBI, dl, TII->get(NewOpc), MI->getOperand(0).getReg())
  1029. .addReg(Base, RegState::Define)
  1030. .addReg(Base).addImm(Offset).addImm(Pred).addReg(PredReg);
  1031. } else {
  1032. int Offset = ARM_AM::getAM2Opc(AddSub, Bytes, ARM_AM::no_shift);
  1033. BuildMI(MBB, MBBI, dl, TII->get(NewOpc), MI->getOperand(0).getReg())
  1034. .addReg(Base, RegState::Define)
  1035. .addReg(Base).addReg(0).addImm(Offset).addImm(Pred).addReg(PredReg);
  1036. }
  1037. } else {
  1038. int Offset = AddSub == ARM_AM::sub ? -Bytes : Bytes;
  1039. // t2LDR_PRE, t2LDR_POST
  1040. BuildMI(MBB, MBBI, dl, TII->get(NewOpc), MI->getOperand(0).getReg())
  1041. .addReg(Base, RegState::Define)
  1042. .addReg(Base).addImm(Offset).addImm(Pred).addReg(PredReg);
  1043. }
  1044. } else {
  1045. MachineOperand &MO = MI->getOperand(0);
  1046. // FIXME: post-indexed stores use am2offset_imm, which still encodes
  1047. // the vestigal zero-reg offset register. When that's fixed, this clause
  1048. // can be removed entirely.
  1049. if (isAM2 && NewOpc == ARM::STR_POST_IMM) {
  1050. int Offset = ARM_AM::getAM2Opc(AddSub, Bytes, ARM_AM::no_shift);
  1051. // STR_PRE, STR_POST
  1052. BuildMI(MBB, MBBI, dl, TII->get(NewOpc), Base)
  1053. .addReg(MO.getReg(), getKillRegState(MO.isKill()))
  1054. .addReg(Base).addReg(0).addImm(Offset).addImm(Pred).addReg(PredReg);
  1055. } else {
  1056. int Offset = AddSub == ARM_AM::sub ? -Bytes : Bytes;
  1057. // t2STR_PRE, t2STR_POST
  1058. BuildMI(MBB, MBBI, dl, TII->get(NewOpc), Base)
  1059. .addReg(MO.getReg(), getKillRegState(MO.isKill()))
  1060. .addReg(Base).addImm(Offset).addImm(Pred).addReg(PredReg);
  1061. }
  1062. }
  1063. MBB.erase(MBBI);
  1064. return true;
  1065. }
  1066. /// isMemoryOp - Returns true if instruction is a memory operation that this
  1067. /// pass is capable of operating on.
  1068. static bool isMemoryOp(const MachineInstr *MI) {
  1069. // When no memory operands are present, conservatively assume unaligned,
  1070. // volatile, unfoldable.
  1071. if (!MI->hasOneMemOperand())
  1072. return false;
  1073. const MachineMemOperand *MMO = *MI->memoperands_begin();
  1074. // Don't touch volatile memory accesses - we may be changing their order.
  1075. if (MMO->isVolatile())
  1076. return false;
  1077. // Unaligned ldr/str is emulated by some kernels, but unaligned ldm/stm is
  1078. // not.
  1079. if (MMO->getAlignment() < 4)
  1080. return false;
  1081. // str <undef> could probably be eliminated entirely, but for now we just want
  1082. // to avoid making a mess of it.
  1083. // FIXME: Use str <undef> as a wildcard to enable better stm folding.
  1084. if (MI->getNumOperands() > 0 && MI->getOperand(0).isReg() &&
  1085. MI->getOperand(0).isUndef())
  1086. return false;
  1087. // Likewise don't mess with references to undefined addresses.
  1088. if (MI->getNumOperands() > 1 && MI->getOperand(1).isReg() &&
  1089. MI->getOperand(1).isUndef())
  1090. return false;
  1091. int Opcode = MI->getOpcode();
  1092. switch (Opcode) {
  1093. default: break;
  1094. case ARM::VLDRS:
  1095. case ARM::VSTRS:
  1096. return MI->getOperand(1).isReg();
  1097. case ARM::VLDRD:
  1098. case ARM::VSTRD:
  1099. return MI->getOperand(1).isReg();
  1100. case ARM::LDRi12:
  1101. case ARM::STRi12:
  1102. case ARM::tLDRi:
  1103. case ARM::tSTRi:
  1104. case ARM::t2LDRi8:
  1105. case ARM::t2LDRi12:
  1106. case ARM::t2STRi8:
  1107. case ARM::t2STRi12:
  1108. return MI->getOperand(1).isReg();
  1109. }
  1110. return false;
  1111. }
  1112. /// AdvanceRS - Advance register scavenger to just before the earliest memory
  1113. /// op that is being merged.
  1114. void ARMLoadStoreOpt::AdvanceRS(MachineBasicBlock &MBB, MemOpQueue &MemOps) {
  1115. MachineBasicBlock::iterator Loc = MemOps[0].MBBI;
  1116. unsigned Position = MemOps[0].Position;
  1117. for (unsigned i = 1, e = MemOps.size(); i != e; ++i) {
  1118. if (MemOps[i].Position < Position) {
  1119. Position = MemOps[i].Position;
  1120. Loc = MemOps[i].MBBI;
  1121. }
  1122. }
  1123. if (Loc != MBB.begin())
  1124. RS->forward(std::prev(Loc));
  1125. }
  1126. static int getMemoryOpOffset(const MachineInstr *MI) {
  1127. int Opcode = MI->getOpcode();
  1128. bool isAM3 = Opcode == ARM::LDRD || Opcode == ARM::STRD;
  1129. unsigned NumOperands = MI->getDesc().getNumOperands();
  1130. unsigned OffField = MI->getOperand(NumOperands-3).getImm();
  1131. if (Opcode == ARM::t2LDRi12 || Opcode == ARM::t2LDRi8 ||
  1132. Opcode == ARM::t2STRi12 || Opcode == ARM::t2STRi8 ||
  1133. Opcode == ARM::t2LDRDi8 || Opcode == ARM::t2STRDi8 ||
  1134. Opcode == ARM::LDRi12 || Opcode == ARM::STRi12)
  1135. return OffField;
  1136. // Thumb1 immediate offsets are scaled by 4
  1137. if (Opcode == ARM::tLDRi || Opcode == ARM::tSTRi)
  1138. return OffField * 4;
  1139. int Offset = isAM3 ? ARM_AM::getAM3Offset(OffField)
  1140. : ARM_AM::getAM5Offset(OffField) * 4;
  1141. if (isAM3) {
  1142. if (ARM_AM::getAM3Op(OffField) == ARM_AM::sub)
  1143. Offset = -Offset;
  1144. } else {
  1145. if (ARM_AM::getAM5Op(OffField) == ARM_AM::sub)
  1146. Offset = -Offset;
  1147. }
  1148. return Offset;
  1149. }
  1150. static void InsertLDR_STR(MachineBasicBlock &MBB,
  1151. MachineBasicBlock::iterator &MBBI,
  1152. int Offset, bool isDef,
  1153. DebugLoc dl, unsigned NewOpc,
  1154. unsigned Reg, bool RegDeadKill, bool RegUndef,
  1155. unsigned BaseReg, bool BaseKill, bool BaseUndef,
  1156. bool OffKill, bool OffUndef,
  1157. ARMCC::CondCodes Pred, unsigned PredReg,
  1158. const TargetInstrInfo *TII, bool isT2) {
  1159. if (isDef) {
  1160. MachineInstrBuilder MIB = BuildMI(MBB, MBBI, MBBI->getDebugLoc(),
  1161. TII->get(NewOpc))
  1162. .addReg(Reg, getDefRegState(true) | getDeadRegState(RegDeadKill))
  1163. .addReg(BaseReg, getKillRegState(BaseKill)|getUndefRegState(BaseUndef));
  1164. MIB.addImm(Offset).addImm(Pred).addReg(PredReg);
  1165. } else {
  1166. MachineInstrBuilder MIB = BuildMI(MBB, MBBI, MBBI->getDebugLoc(),
  1167. TII->get(NewOpc))
  1168. .addReg(Reg, getKillRegState(RegDeadKill) | getUndefRegState(RegUndef))
  1169. .addReg(BaseReg, getKillRegState(BaseKill)|getUndefRegState(BaseUndef));
  1170. MIB.addImm(Offset).addImm(Pred).addReg(PredReg);
  1171. }
  1172. }
  1173. bool ARMLoadStoreOpt::FixInvalidRegPairOp(MachineBasicBlock &MBB,
  1174. MachineBasicBlock::iterator &MBBI) {
  1175. MachineInstr *MI = &*MBBI;
  1176. unsigned Opcode = MI->getOpcode();
  1177. if (Opcode == ARM::LDRD || Opcode == ARM::STRD ||
  1178. Opcode == ARM::t2LDRDi8 || Opcode == ARM::t2STRDi8) {
  1179. const MachineOperand &BaseOp = MI->getOperand(2);
  1180. unsigned BaseReg = BaseOp.getReg();
  1181. unsigned EvenReg = MI->getOperand(0).getReg();
  1182. unsigned OddReg = MI->getOperand(1).getReg();
  1183. unsigned EvenRegNum = TRI->getDwarfRegNum(EvenReg, false);
  1184. unsigned OddRegNum = TRI->getDwarfRegNum(OddReg, false);
  1185. // ARM errata 602117: LDRD with base in list may result in incorrect base
  1186. // register when interrupted or faulted.
  1187. bool Errata602117 = EvenReg == BaseReg && STI->isCortexM3();
  1188. if (!Errata602117 &&
  1189. ((EvenRegNum & 1) == 0 && (EvenRegNum + 1) == OddRegNum))
  1190. return false;
  1191. MachineBasicBlock::iterator NewBBI = MBBI;
  1192. bool isT2 = Opcode == ARM::t2LDRDi8 || Opcode == ARM::t2STRDi8;
  1193. bool isLd = Opcode == ARM::LDRD || Opcode == ARM::t2LDRDi8;
  1194. bool EvenDeadKill = isLd ?
  1195. MI->getOperand(0).isDead() : MI->getOperand(0).isKill();
  1196. bool EvenUndef = MI->getOperand(0).isUndef();
  1197. bool OddDeadKill = isLd ?
  1198. MI->getOperand(1).isDead() : MI->getOperand(1).isKill();
  1199. bool OddUndef = MI->getOperand(1).isUndef();
  1200. bool BaseKill = BaseOp.isKill();
  1201. bool BaseUndef = BaseOp.isUndef();
  1202. bool OffKill = isT2 ? false : MI->getOperand(3).isKill();
  1203. bool OffUndef = isT2 ? false : MI->getOperand(3).isUndef();
  1204. int OffImm = getMemoryOpOffset(MI);
  1205. unsigned PredReg = 0;
  1206. ARMCC::CondCodes Pred = getInstrPredicate(MI, PredReg);
  1207. if (OddRegNum > EvenRegNum && OffImm == 0) {
  1208. // Ascending register numbers and no offset. It's safe to change it to a
  1209. // ldm or stm.
  1210. unsigned NewOpc = (isLd)
  1211. ? (isT2 ? ARM::t2LDMIA : ARM::LDMIA)
  1212. : (isT2 ? ARM::t2STMIA : ARM::STMIA);
  1213. if (isLd) {
  1214. BuildMI(MBB, MBBI, MBBI->getDebugLoc(), TII->get(NewOpc))
  1215. .addReg(BaseReg, getKillRegState(BaseKill))
  1216. .addImm(Pred).addReg(PredReg)
  1217. .addReg(EvenReg, getDefRegState(isLd) | getDeadRegState(EvenDeadKill))
  1218. .addReg(OddReg, getDefRegState(isLd) | getDeadRegState(OddDeadKill));
  1219. ++NumLDRD2LDM;
  1220. } else {
  1221. BuildMI(MBB, MBBI, MBBI->getDebugLoc(), TII->get(NewOpc))
  1222. .addReg(BaseReg, getKillRegState(BaseKill))
  1223. .addImm(Pred).addReg(PredReg)
  1224. .addReg(EvenReg,
  1225. getKillRegState(EvenDeadKill) | getUndefRegState(EvenUndef))
  1226. .addReg(OddReg,
  1227. getKillRegState(OddDeadKill) | getUndefRegState(OddUndef));
  1228. ++NumSTRD2STM;
  1229. }
  1230. NewBBI = std::prev(MBBI);
  1231. } else {
  1232. // Split into two instructions.
  1233. unsigned NewOpc = (isLd)
  1234. ? (isT2 ? (OffImm < 0 ? ARM::t2LDRi8 : ARM::t2LDRi12) : ARM::LDRi12)
  1235. : (isT2 ? (OffImm < 0 ? ARM::t2STRi8 : ARM::t2STRi12) : ARM::STRi12);
  1236. // Be extra careful for thumb2. t2LDRi8 can't reference a zero offset,
  1237. // so adjust and use t2LDRi12 here for that.
  1238. unsigned NewOpc2 = (isLd)
  1239. ? (isT2 ? (OffImm+4 < 0 ? ARM::t2LDRi8 : ARM::t2LDRi12) : ARM::LDRi12)
  1240. : (isT2 ? (OffImm+4 < 0 ? ARM::t2STRi8 : ARM::t2STRi12) : ARM::STRi12);
  1241. DebugLoc dl = MBBI->getDebugLoc();
  1242. // If this is a load and base register is killed, it may have been
  1243. // re-defed by the load, make sure the first load does not clobber it.
  1244. if (isLd &&
  1245. (BaseKill || OffKill) &&
  1246. (TRI->regsOverlap(EvenReg, BaseReg))) {
  1247. assert(!TRI->regsOverlap(OddReg, BaseReg));
  1248. InsertLDR_STR(MBB, MBBI, OffImm+4, isLd, dl, NewOpc2,
  1249. OddReg, OddDeadKill, false,
  1250. BaseReg, false, BaseUndef, false, OffUndef,
  1251. Pred, PredReg, TII, isT2);
  1252. NewBBI = std::prev(MBBI);
  1253. InsertLDR_STR(MBB, MBBI, OffImm, isLd, dl, NewOpc,
  1254. EvenReg, EvenDeadKill, false,
  1255. BaseReg, BaseKill, BaseUndef, OffKill, OffUndef,
  1256. Pred, PredReg, TII, isT2);
  1257. } else {
  1258. if (OddReg == EvenReg && EvenDeadKill) {
  1259. // If the two source operands are the same, the kill marker is
  1260. // probably on the first one. e.g.
  1261. // t2STRDi8 %R5<kill>, %R5, %R9<kill>, 0, 14, %reg0
  1262. EvenDeadKill = false;
  1263. OddDeadKill = true;
  1264. }
  1265. // Never kill the base register in the first instruction.
  1266. if (EvenReg == BaseReg)
  1267. EvenDeadKill = false;
  1268. InsertLDR_STR(MBB, MBBI, OffImm, isLd, dl, NewOpc,
  1269. EvenReg, EvenDeadKill, EvenUndef,
  1270. BaseReg, false, BaseUndef, false, OffUndef,
  1271. Pred, PredReg, TII, isT2);
  1272. NewBBI = std::prev(MBBI);
  1273. InsertLDR_STR(MBB, MBBI, OffImm+4, isLd, dl, NewOpc2,
  1274. OddReg, OddDeadKill, OddUndef,
  1275. BaseReg, BaseKill, BaseUndef, OffKill, OffUndef,
  1276. Pred, PredReg, TII, isT2);
  1277. }
  1278. if (isLd)
  1279. ++NumLDRD2LDR;
  1280. else
  1281. ++NumSTRD2STR;
  1282. }
  1283. MBB.erase(MI);
  1284. MBBI = NewBBI;
  1285. return true;
  1286. }
  1287. return false;
  1288. }
  1289. /// LoadStoreMultipleOpti - An optimization pass to turn multiple LDR / STR
  1290. /// ops of the same base and incrementing offset into LDM / STM ops.
  1291. bool ARMLoadStoreOpt::LoadStoreMultipleOpti(MachineBasicBlock &MBB) {
  1292. unsigned NumMerges = 0;
  1293. unsigned NumMemOps = 0;
  1294. MemOpQueue MemOps;
  1295. unsigned CurrBase = 0;
  1296. int CurrOpc = -1;
  1297. unsigned CurrSize = 0;
  1298. ARMCC::CondCodes CurrPred = ARMCC::AL;
  1299. unsigned CurrPredReg = 0;
  1300. unsigned Position = 0;
  1301. SmallVector<MachineBasicBlock::iterator,4> Merges;
  1302. RS->enterBasicBlock(&MBB);
  1303. MachineBasicBlock::iterator MBBI = MBB.begin(), E = MBB.end();
  1304. while (MBBI != E) {
  1305. if (FixInvalidRegPairOp(MBB, MBBI))
  1306. continue;
  1307. bool Advance = false;
  1308. bool TryMerge = false;
  1309. bool Clobber = false;
  1310. bool isMemOp = isMemoryOp(MBBI);
  1311. if (isMemOp) {
  1312. int Opcode = MBBI->getOpcode();
  1313. unsigned Size = getLSMultipleTransferSize(MBBI);
  1314. const MachineOperand &MO = MBBI->getOperand(0);
  1315. unsigned Reg = MO.getReg();
  1316. bool isKill = MO.isDef() ? false : MO.isKill();
  1317. unsigned Base = MBBI->getOperand(1).getReg();
  1318. unsigned PredReg = 0;
  1319. ARMCC::CondCodes Pred = getInstrPredicate(MBBI, PredReg);
  1320. int Offset = getMemoryOpOffset(MBBI);
  1321. // Watch out for:
  1322. // r4 := ldr [r5]
  1323. // r5 := ldr [r5, #4]
  1324. // r6 := ldr [r5, #8]
  1325. //
  1326. // The second ldr has effectively broken the chain even though it
  1327. // looks like the later ldr(s) use the same base register. Try to
  1328. // merge the ldr's so far, including this one. But don't try to
  1329. // combine the following ldr(s).
  1330. Clobber = (isi32Load(Opcode) && Base == MBBI->getOperand(0).getReg());
  1331. // Watch out for:
  1332. // r4 := ldr [r0, #8]
  1333. // r4 := ldr [r0, #4]
  1334. //
  1335. // The optimization may reorder the second ldr in front of the first
  1336. // ldr, which violates write after write(WAW) dependence. The same as
  1337. // str. Try to merge inst(s) already in MemOps.
  1338. bool Overlap = false;
  1339. for (MemOpQueueIter I = MemOps.begin(), E = MemOps.end(); I != E; ++I) {
  1340. if (TRI->regsOverlap(Reg, I->MBBI->getOperand(0).getReg())) {
  1341. Overlap = true;
  1342. break;
  1343. }
  1344. }
  1345. if (CurrBase == 0 && !Clobber) {
  1346. // Start of a new chain.
  1347. CurrBase = Base;
  1348. CurrOpc = Opcode;
  1349. CurrSize = Size;
  1350. CurrPred = Pred;
  1351. CurrPredReg = PredReg;
  1352. MemOps.push_back(MemOpQueueEntry(Offset, Reg, isKill, Position, MBBI));
  1353. ++NumMemOps;
  1354. Advance = true;
  1355. } else if (!Overlap) {
  1356. if (Clobber) {
  1357. TryMerge = true;
  1358. Advance = true;
  1359. }
  1360. if (CurrOpc == Opcode && CurrBase == Base && CurrPred == Pred) {
  1361. // No need to match PredReg.
  1362. // Continue adding to the queue.
  1363. if (Offset > MemOps.back().Offset) {
  1364. MemOps.push_back(MemOpQueueEntry(Offset, Reg, isKill,
  1365. Position, MBBI));
  1366. ++NumMemOps;
  1367. Advance = true;
  1368. } else {
  1369. for (MemOpQueueIter I = MemOps.begin(), E = MemOps.end();
  1370. I != E; ++I) {
  1371. if (Offset < I->Offset) {
  1372. MemOps.insert(I, MemOpQueueEntry(Offset, Reg, isKill,
  1373. Position, MBBI));
  1374. ++NumMemOps;
  1375. Advance = true;
  1376. break;
  1377. } else if (Offset == I->Offset) {
  1378. // Collision! This can't be merged!
  1379. break;
  1380. }
  1381. }
  1382. }
  1383. }
  1384. }
  1385. }
  1386. if (MBBI->isDebugValue()) {
  1387. ++MBBI;
  1388. if (MBBI == E)
  1389. // Reach the end of the block, try merging the memory instructions.
  1390. TryMerge = true;
  1391. } else if (Advance) {
  1392. ++Position;
  1393. ++MBBI;
  1394. if (MBBI == E)
  1395. // Reach the end of the block, try merging the memory instructions.
  1396. TryMerge = true;
  1397. } else {
  1398. TryMerge = true;
  1399. }
  1400. if (TryMerge) {
  1401. if (NumMemOps > 1) {
  1402. // Try to find a free register to use as a new base in case it's needed.
  1403. // First advance to the instruction just before the start of the chain.
  1404. AdvanceRS(MBB, MemOps);
  1405. // Find a scratch register.
  1406. unsigned Scratch =
  1407. RS->FindUnusedReg(isThumb1 ? &ARM::tGPRRegClass : &ARM::GPRRegClass);
  1408. // Process the load / store instructions.
  1409. RS->forward(std::prev(MBBI));
  1410. // Merge ops.
  1411. Merges.clear();
  1412. MergeLDR_STR(MBB, 0, CurrBase, CurrOpc, CurrSize,
  1413. CurrPred, CurrPredReg, Scratch, MemOps, Merges);
  1414. // Try folding preceding/trailing base inc/dec into the generated
  1415. // LDM/STM ops.
  1416. for (unsigned i = 0, e = Merges.size(); i < e; ++i)
  1417. if (MergeBaseUpdateLSMultiple(MBB, Merges[i], Advance, MBBI))
  1418. ++NumMerges;
  1419. NumMerges += Merges.size();
  1420. // Try folding preceding/trailing base inc/dec into those load/store
  1421. // that were not merged to form LDM/STM ops.
  1422. for (unsigned i = 0; i != NumMemOps; ++i)
  1423. if (!MemOps[i].Merged)
  1424. if (MergeBaseUpdateLoadStore(MBB, MemOps[i].MBBI, TII,Advance,MBBI))
  1425. ++NumMerges;
  1426. // RS may be pointing to an instruction that's deleted.
  1427. RS->skipTo(std::prev(MBBI));
  1428. } else if (NumMemOps == 1) {
  1429. // Try folding preceding/trailing base inc/dec into the single
  1430. // load/store.
  1431. if (MergeBaseUpdateLoadStore(MBB, MemOps[0].MBBI, TII, Advance, MBBI)) {
  1432. ++NumMerges;
  1433. RS->forward(std::prev(MBBI));
  1434. }
  1435. }
  1436. CurrBase = 0;
  1437. CurrOpc = -1;
  1438. CurrSize = 0;
  1439. CurrPred = ARMCC::AL;
  1440. CurrPredReg = 0;
  1441. if (NumMemOps) {
  1442. MemOps.clear();
  1443. NumMemOps = 0;
  1444. }
  1445. // If iterator hasn't been advanced and this is not a memory op, skip it.
  1446. // It can't start a new chain anyway.
  1447. if (!Advance && !isMemOp && MBBI != E) {
  1448. ++Position;
  1449. ++MBBI;
  1450. }
  1451. }
  1452. }
  1453. return NumMerges > 0;
  1454. }
  1455. /// MergeReturnIntoLDM - If this is a exit BB, try merging the return ops
  1456. /// ("bx lr" and "mov pc, lr") into the preceding stack restore so it
  1457. /// directly restore the value of LR into pc.
  1458. /// ldmfd sp!, {..., lr}
  1459. /// bx lr
  1460. /// or
  1461. /// ldmfd sp!, {..., lr}
  1462. /// mov pc, lr
  1463. /// =>
  1464. /// ldmfd sp!, {..., pc}
  1465. bool ARMLoadStoreOpt::MergeReturnIntoLDM(MachineBasicBlock &MBB) {
  1466. // Thumb1 LDM doesn't allow high registers.
  1467. if (isThumb1) return false;
  1468. if (MBB.empty()) return false;
  1469. MachineBasicBlock::iterator MBBI = MBB.getLastNonDebugInstr();
  1470. if (MBBI != MBB.begin() &&
  1471. (MBBI->getOpcode() == ARM::BX_RET ||
  1472. MBBI->getOpcode() == ARM::tBX_RET ||
  1473. MBBI->getOpcode() == ARM::MOVPCLR)) {
  1474. MachineInstr *PrevMI = std::prev(MBBI);
  1475. unsigned Opcode = PrevMI->getOpcode();
  1476. if (Opcode == ARM::LDMIA_UPD || Opcode == ARM::LDMDA_UPD ||
  1477. Opcode == ARM::LDMDB_UPD || Opcode == ARM::LDMIB_UPD ||
  1478. Opcode == ARM::t2LDMIA_UPD || Opcode == ARM::t2LDMDB_UPD) {
  1479. MachineOperand &MO = PrevMI->getOperand(PrevMI->getNumOperands()-1);
  1480. if (MO.getReg() != ARM::LR)
  1481. return false;
  1482. unsigned NewOpc = (isThumb2 ? ARM::t2LDMIA_RET : ARM::LDMIA_RET);
  1483. assert(((isThumb2 && Opcode == ARM::t2LDMIA_UPD) ||
  1484. Opcode == ARM::LDMIA_UPD) && "Unsupported multiple load-return!");
  1485. PrevMI->setDesc(TII->get(NewOpc));
  1486. MO.setReg(ARM::PC);
  1487. PrevMI->copyImplicitOps(*MBB.getParent(), &*MBBI);
  1488. MBB.erase(MBBI);
  1489. return true;
  1490. }
  1491. }
  1492. return false;
  1493. }
  1494. bool ARMLoadStoreOpt::runOnMachineFunction(MachineFunction &Fn) {
  1495. const TargetMachine &TM = Fn.getTarget();
  1496. TL = TM.getSubtargetImpl()->getTargetLowering();
  1497. AFI = Fn.getInfo<ARMFunctionInfo>();
  1498. TII = TM.getSubtargetImpl()->getInstrInfo();
  1499. TRI = TM.getSubtargetImpl()->getRegisterInfo();
  1500. STI = &TM.getSubtarget<ARMSubtarget>();
  1501. RS = new RegScavenger();
  1502. isThumb2 = AFI->isThumb2Function();
  1503. isThumb1 = AFI->isThumbFunction() && !isThumb2;
  1504. bool Modified = false;
  1505. for (MachineFunction::iterator MFI = Fn.begin(), E = Fn.end(); MFI != E;
  1506. ++MFI) {
  1507. MachineBasicBlock &MBB = *MFI;
  1508. Modified |= LoadStoreMultipleOpti(MBB);
  1509. if (TM.getSubtarget<ARMSubtarget>().hasV5TOps())
  1510. Modified |= MergeReturnIntoLDM(MBB);
  1511. }
  1512. delete RS;
  1513. return Modified;
  1514. }
  1515. /// ARMPreAllocLoadStoreOpt - Pre- register allocation pass that move
  1516. /// load / stores from consecutive locations close to make it more
  1517. /// likely they will be combined later.
  1518. namespace {
  1519. struct ARMPreAllocLoadStoreOpt : public MachineFunctionPass{
  1520. static char ID;
  1521. ARMPreAllocLoadStoreOpt() : MachineFunctionPass(ID) {}
  1522. const DataLayout *TD;
  1523. const TargetInstrInfo *TII;
  1524. const TargetRegisterInfo *TRI;
  1525. const ARMSubtarget *STI;
  1526. MachineRegisterInfo *MRI;
  1527. MachineFunction *MF;
  1528. bool runOnMachineFunction(MachineFunction &Fn) override;
  1529. const char *getPassName() const override {
  1530. return "ARM pre- register allocation load / store optimization pass";
  1531. }
  1532. private:
  1533. bool CanFormLdStDWord(MachineInstr *Op0, MachineInstr *Op1, DebugLoc &dl,
  1534. unsigned &NewOpc, unsigned &EvenReg,
  1535. unsigned &OddReg, unsigned &BaseReg,
  1536. int &Offset,
  1537. unsigned &PredReg, ARMCC::CondCodes &Pred,
  1538. bool &isT2);
  1539. bool RescheduleOps(MachineBasicBlock *MBB,
  1540. SmallVectorImpl<MachineInstr *> &Ops,
  1541. unsigned Base, bool isLd,
  1542. DenseMap<MachineInstr*, unsigned> &MI2LocMap);
  1543. bool RescheduleLoadStoreInstrs(MachineBasicBlock *MBB);
  1544. };
  1545. char ARMPreAllocLoadStoreOpt::ID = 0;
  1546. }
  1547. bool ARMPreAllocLoadStoreOpt::runOnMachineFunction(MachineFunction &Fn) {
  1548. TD = Fn.getSubtarget().getDataLayout();
  1549. TII = Fn.getSubtarget().getInstrInfo();
  1550. TRI = Fn.getSubtarget().getRegisterInfo();
  1551. STI = &Fn.getTarget().getSubtarget<ARMSubtarget>();
  1552. MRI = &Fn.getRegInfo();
  1553. MF = &Fn;
  1554. bool Modified = false;
  1555. for (MachineFunction::iterator MFI = Fn.begin(), E = Fn.end(); MFI != E;
  1556. ++MFI)
  1557. Modified |= RescheduleLoadStoreInstrs(MFI);
  1558. return Modified;
  1559. }
  1560. static bool IsSafeAndProfitableToMove(bool isLd, unsigned Base,
  1561. MachineBasicBlock::iterator I,
  1562. MachineBasicBlock::iterator E,
  1563. SmallPtrSetImpl<MachineInstr*> &MemOps,
  1564. SmallSet<unsigned, 4> &MemRegs,
  1565. const TargetRegisterInfo *TRI) {
  1566. // Are there stores / loads / calls between them?
  1567. // FIXME: This is overly conservative. We should make use of alias information
  1568. // some day.
  1569. SmallSet<unsigned, 4> AddedRegPressure;
  1570. while (++I != E) {
  1571. if (I->isDebugValue() || MemOps.count(&*I))
  1572. continue;
  1573. if (I->isCall() || I->isTerminator() || I->hasUnmodeledSideEffects())
  1574. return false;
  1575. if (isLd && I->mayStore())
  1576. return false;
  1577. if (!isLd) {
  1578. if (I->mayLoad())
  1579. return false;
  1580. // It's not safe to move the first 'str' down.
  1581. // str r1, [r0]
  1582. // strh r5, [r0]
  1583. // str r4, [r0, #+4]
  1584. if (I->mayStore())
  1585. return false;
  1586. }
  1587. for (unsigned j = 0, NumOps = I->getNumOperands(); j != NumOps; ++j) {
  1588. MachineOperand &MO = I->getOperand(j);
  1589. if (!MO.isReg())
  1590. continue;
  1591. unsigned Reg = MO.getReg();
  1592. if (MO.isDef() && TRI->regsOverlap(Reg, Base))
  1593. return false;
  1594. if (Reg != Base && !MemRegs.count(Reg))
  1595. AddedRegPressure.insert(Reg);
  1596. }
  1597. }
  1598. // Estimate register pressure increase due to the transformation.
  1599. if (MemRegs.size() <= 4)
  1600. // Ok if we are moving small number of instructions.
  1601. return true;
  1602. return AddedRegPressure.size() <= MemRegs.size() * 2;
  1603. }
  1604. /// Copy Op0 and Op1 operands into a new array assigned to MI.
  1605. static void concatenateMemOperands(MachineInstr *MI, MachineInstr *Op0,
  1606. MachineInstr *Op1) {
  1607. assert(MI->memoperands_empty() && "expected a new machineinstr");
  1608. size_t numMemRefs = (Op0->memoperands_end() - Op0->memoperands_begin())
  1609. + (Op1->memoperands_end() - Op1->memoperands_begin());
  1610. MachineFunction *MF = MI->getParent()->getParent();
  1611. MachineSDNode::mmo_iterator MemBegin = MF->allocateMemRefsArray(numMemRefs);
  1612. MachineSDNode::mmo_iterator MemEnd =
  1613. std::copy(Op0->memoperands_begin(), Op0->memoperands_end(), MemBegin);
  1614. MemEnd =
  1615. std::copy(Op1->memoperands_begin(), Op1->memoperands_end(), MemEnd);
  1616. MI->setMemRefs(MemBegin, MemEnd);
  1617. }
  1618. bool
  1619. ARMPreAllocLoadStoreOpt::CanFormLdStDWord(MachineInstr *Op0, MachineInstr *Op1,
  1620. DebugLoc &dl,
  1621. unsigned &NewOpc, unsigned &EvenReg,
  1622. unsigned &OddReg, unsigned &BaseReg,
  1623. int &Offset, unsigned &PredReg,
  1624. ARMCC::CondCodes &Pred,
  1625. bool &isT2) {
  1626. // Make sure we're allowed to generate LDRD/STRD.
  1627. if (!STI->hasV5TEOps())
  1628. return false;
  1629. // FIXME: VLDRS / VSTRS -> VLDRD / VSTRD
  1630. unsigned Scale = 1;
  1631. unsigned Opcode = Op0->getOpcode();
  1632. if (Opcode == ARM::LDRi12) {
  1633. NewOpc = ARM::LDRD;
  1634. } else if (Opcode == ARM::STRi12) {
  1635. NewOpc = ARM::STRD;
  1636. } else if (Opcode == ARM::t2LDRi8 || Opcode == ARM::t2LDRi12) {
  1637. NewOpc = ARM::t2LDRDi8;
  1638. Scale = 4;
  1639. isT2 = true;
  1640. } else if (Opcode == ARM::t2STRi8 || Opcode == ARM::t2STRi12) {
  1641. NewOpc = ARM::t2STRDi8;
  1642. Scale = 4;
  1643. isT2 = true;
  1644. } else {
  1645. return false;
  1646. }
  1647. // Make sure the base address satisfies i64 ld / st alignment requirement.
  1648. // At the moment, we ignore the memoryoperand's value.
  1649. // If we want to use AliasAnalysis, we should check it accordingly.
  1650. if (!Op0->hasOneMemOperand() ||
  1651. (*Op0->memoperands_begin())->isVolatile())
  1652. return false;
  1653. unsigned Align = (*Op0->memoperands_begin())->getAlignment();
  1654. const Function *Func = MF->getFunction();
  1655. unsigned ReqAlign = STI->hasV6Ops()
  1656. ? TD->getABITypeAlignment(Type::getInt64Ty(Func->getContext()))
  1657. : 8; // Pre-v6 need 8-byte align
  1658. if (Align < ReqAlign)
  1659. return false;
  1660. // Then make sure the immediate offset fits.
  1661. int OffImm = getMemoryOpOffset(Op0);
  1662. if (isT2) {
  1663. int Limit = (1 << 8) * Scale;
  1664. if (OffImm >= Limit || (OffImm <= -Limit) || (OffImm & (Scale-1)))
  1665. return false;
  1666. Offset = OffImm;
  1667. } else {
  1668. ARM_AM::AddrOpc AddSub = ARM_AM::add;
  1669. if (OffImm < 0) {
  1670. AddSub = ARM_AM::sub;
  1671. OffImm = - OffImm;
  1672. }
  1673. int Limit = (1 << 8) * Scale;
  1674. if (OffImm >= Limit || (OffImm & (Scale-1)))
  1675. return false;
  1676. Offset = ARM_AM::getAM3Opc(AddSub, OffImm);
  1677. }
  1678. EvenReg = Op0->getOperand(0).getReg();
  1679. OddReg = Op1->getOperand(0).getReg();
  1680. if (EvenReg == OddReg)
  1681. return false;
  1682. BaseReg = Op0->getOperand(1).getReg();
  1683. Pred = getInstrPredicate(Op0, PredReg);
  1684. dl = Op0->getDebugLoc();
  1685. return true;
  1686. }
  1687. bool ARMPreAllocLoadStoreOpt::RescheduleOps(MachineBasicBlock *MBB,
  1688. SmallVectorImpl<MachineInstr *> &Ops,
  1689. unsigned Base, bool isLd,
  1690. DenseMap<MachineInstr*, unsigned> &MI2LocMap) {
  1691. bool RetVal = false;
  1692. // Sort by offset (in reverse order).
  1693. std::sort(Ops.begin(), Ops.end(),
  1694. [](const MachineInstr *LHS, const MachineInstr *RHS) {
  1695. int LOffset = getMemoryOpOffset(LHS);
  1696. int ROffset = getMemoryOpOffset(RHS);
  1697. assert(LHS == RHS || LOffset != ROffset);
  1698. return LOffset > ROffset;
  1699. });
  1700. // The loads / stores of the same base are in order. Scan them from first to
  1701. // last and check for the following:
  1702. // 1. Any def of base.
  1703. // 2. Any gaps.
  1704. while (Ops.size() > 1) {
  1705. unsigned FirstLoc = ~0U;
  1706. unsigned LastLoc = 0;
  1707. MachineInstr *FirstOp = nullptr;
  1708. MachineInstr *LastOp = nullptr;
  1709. int LastOffset = 0;
  1710. unsigned LastOpcode = 0;
  1711. unsigned LastBytes = 0;
  1712. unsigned NumMove = 0;
  1713. for (int i = Ops.size() - 1; i >= 0; --i) {
  1714. MachineInstr *Op = Ops[i];
  1715. unsigned Loc = MI2LocMap[Op];
  1716. if (Loc <= FirstLoc) {
  1717. FirstLoc = Loc;
  1718. FirstOp = Op;
  1719. }
  1720. if (Loc >= LastLoc) {
  1721. LastLoc = Loc;
  1722. LastOp = Op;
  1723. }
  1724. unsigned LSMOpcode
  1725. = getLoadStoreMultipleOpcode(Op->getOpcode(), ARM_AM::ia);
  1726. if (LastOpcode && LSMOpcode != LastOpcode)
  1727. break;
  1728. int Offset = getMemoryOpOffset(Op);
  1729. unsigned Bytes = getLSMultipleTransferSize(Op);
  1730. if (LastBytes) {
  1731. if (Bytes != LastBytes || Offset != (LastOffset + (int)Bytes))
  1732. break;
  1733. }
  1734. LastOffset = Offset;
  1735. LastBytes = Bytes;
  1736. LastOpcode = LSMOpcode;
  1737. if (++NumMove == 8) // FIXME: Tune this limit.
  1738. break;
  1739. }
  1740. if (NumMove <= 1)
  1741. Ops.pop_back();
  1742. else {
  1743. SmallPtrSet<MachineInstr*, 4> MemOps;
  1744. SmallSet<unsigned, 4> MemRegs;
  1745. for (int i = NumMove-1; i >= 0; --i) {
  1746. MemOps.insert(Ops[i]);
  1747. MemRegs.insert(Ops[i]->getOperand(0).getReg());
  1748. }
  1749. // Be conservative, if the instructions are too far apart, don't
  1750. // move them. We want to limit the increase of register pressure.
  1751. bool DoMove = (LastLoc - FirstLoc) <= NumMove*4; // FIXME: Tune this.
  1752. if (DoMove)
  1753. DoMove = IsSafeAndProfitableToMove(isLd, Base, FirstOp, LastOp,
  1754. MemOps, MemRegs, TRI);
  1755. if (!DoMove) {
  1756. for (unsigned i = 0; i != NumMove; ++i)
  1757. Ops.pop_back();
  1758. } else {
  1759. // This is the new location for the loads / stores.
  1760. MachineBasicBlock::iterator InsertPos = isLd ? FirstOp : LastOp;
  1761. while (InsertPos != MBB->end()
  1762. && (MemOps.count(InsertPos) || InsertPos->isDebugValue()))
  1763. ++InsertPos;
  1764. // If we are moving a pair of loads / stores, see if it makes sense
  1765. // to try to allocate a pair of registers that can form register pairs.
  1766. MachineInstr *Op0 = Ops.back();
  1767. MachineInstr *Op1 = Ops[Ops.size()-2];
  1768. unsigned EvenReg = 0, OddReg = 0;
  1769. unsigned BaseReg = 0, PredReg = 0;
  1770. ARMCC::CondCodes Pred = ARMCC::AL;
  1771. bool isT2 = false;
  1772. unsigned NewOpc = 0;
  1773. int Offset = 0;
  1774. DebugLoc dl;
  1775. if (NumMove == 2 && CanFormLdStDWord(Op0, Op1, dl, NewOpc,
  1776. EvenReg, OddReg, BaseReg,
  1777. Offset, PredReg, Pred, isT2)) {
  1778. Ops.pop_back();
  1779. Ops.pop_back();
  1780. const MCInstrDesc &MCID = TII->get(NewOpc);
  1781. const TargetRegisterClass *TRC = TII->getRegClass(MCID, 0, TRI, *MF);
  1782. MRI->constrainRegClass(EvenReg, TRC);
  1783. MRI->constrainRegClass(OddReg, TRC);
  1784. // Form the pair instruction.
  1785. if (isLd) {
  1786. MachineInstrBuilder MIB = BuildMI(*MBB, InsertPos, dl, MCID)
  1787. .addReg(EvenReg, RegState::Define)
  1788. .addReg(OddReg, RegState::Define)
  1789. .addReg(BaseReg);
  1790. // FIXME: We're converting from LDRi12 to an insn that still
  1791. // uses addrmode2, so we need an explicit offset reg. It should
  1792. // always by reg0 since we're transforming LDRi12s.
  1793. if (!isT2)
  1794. MIB.addReg(0);
  1795. MIB.addImm(Offset).addImm(Pred).addReg(PredReg);
  1796. concatenateMemOperands(MIB, Op0, Op1);
  1797. DEBUG(dbgs() << "Formed " << *MIB << "\n");
  1798. ++NumLDRDFormed;
  1799. } else {
  1800. MachineInstrBuilder MIB = BuildMI(*MBB, InsertPos, dl, MCID)
  1801. .addReg(EvenReg)
  1802. .addReg(OddReg)
  1803. .addReg(BaseReg);
  1804. // FIXME: We're converting from LDRi12 to an insn that still
  1805. // uses addrmode2, so we need an explicit offset reg. It should
  1806. // always by reg0 since we're transforming STRi12s.
  1807. if (!isT2)
  1808. MIB.addReg(0);
  1809. MIB.addImm(Offset).addImm(Pred).addReg(PredReg);
  1810. concatenateMemOperands(MIB, Op0, Op1);
  1811. DEBUG(dbgs() << "Formed " << *MIB << "\n");
  1812. ++NumSTRDFormed;
  1813. }
  1814. MBB->erase(Op0);
  1815. MBB->erase(Op1);
  1816. // Add register allocation hints to form register pairs.
  1817. MRI->setRegAllocationHint(EvenReg, ARMRI::RegPairEven, OddReg);
  1818. MRI->setRegAllocationHint(OddReg, ARMRI::RegPairOdd, EvenReg);
  1819. } else {
  1820. for (unsigned i = 0; i != NumMove; ++i) {
  1821. MachineInstr *Op = Ops.back();
  1822. Ops.pop_back();
  1823. MBB->splice(InsertPos, MBB, Op);
  1824. }
  1825. }
  1826. NumLdStMoved += NumMove;
  1827. RetVal = true;
  1828. }
  1829. }
  1830. }
  1831. return RetVal;
  1832. }
  1833. bool
  1834. ARMPreAllocLoadStoreOpt::RescheduleLoadStoreInstrs(MachineBasicBlock *MBB) {
  1835. bool RetVal = false;
  1836. DenseMap<MachineInstr*, unsigned> MI2LocMap;
  1837. DenseMap<unsigned, SmallVector<MachineInstr*, 4> > Base2LdsMap;
  1838. DenseMap<unsigned, SmallVector<MachineInstr*, 4> > Base2StsMap;
  1839. SmallVector<unsigned, 4> LdBases;
  1840. SmallVector<unsigned, 4> StBases;
  1841. unsigned Loc = 0;
  1842. MachineBasicBlock::iterator MBBI = MBB->begin();
  1843. MachineBasicBlock::iterator E = MBB->end();
  1844. while (MBBI != E) {
  1845. for (; MBBI != E; ++MBBI) {
  1846. MachineInstr *MI = MBBI;
  1847. if (MI->isCall() || MI->isTerminator()) {
  1848. // Stop at barriers.
  1849. ++MBBI;
  1850. break;
  1851. }
  1852. if (!MI->isDebugValue())
  1853. MI2LocMap[MI] = ++Loc;
  1854. if (!isMemoryOp(MI))
  1855. continue;
  1856. unsigned PredReg = 0;
  1857. if (getInstrPredicate(MI, PredReg) != ARMCC::AL)
  1858. continue;
  1859. int Opc = MI->getOpcode();
  1860. bool isLd = isi32Load(Opc) || Opc == ARM::VLDRS || Opc == ARM::VLDRD;
  1861. unsigned Base = MI->getOperand(1).getReg();
  1862. int Offset = getMemoryOpOffset(MI);
  1863. bool StopHere = false;
  1864. if (isLd) {
  1865. DenseMap<unsigned, SmallVector<MachineInstr*, 4> >::iterator BI =
  1866. Base2LdsMap.find(Base);
  1867. if (BI != Base2LdsMap.end()) {
  1868. for (unsigned i = 0, e = BI->second.size(); i != e; ++i) {
  1869. if (Offset == getMemoryOpOffset(BI->second[i])) {
  1870. StopHere = true;
  1871. break;
  1872. }
  1873. }
  1874. if (!StopHere)
  1875. BI->second.push_back(MI);
  1876. } else {
  1877. Base2LdsMap[Base].push_back(MI);
  1878. LdBases.push_back(Base);
  1879. }
  1880. } else {
  1881. DenseMap<unsigned, SmallVector<MachineInstr*, 4> >::iterator BI =
  1882. Base2StsMap.find(Base);
  1883. if (BI != Base2StsMap.end()) {
  1884. for (unsigned i = 0, e = BI->second.size(); i != e; ++i) {
  1885. if (Offset == getMemoryOpOffset(BI->second[i])) {
  1886. StopHere = true;
  1887. break;
  1888. }
  1889. }
  1890. if (!StopHere)
  1891. BI->second.push_back(MI);
  1892. } else {
  1893. Base2StsMap[Base].push_back(MI);
  1894. StBases.push_back(Base);
  1895. }
  1896. }
  1897. if (StopHere) {
  1898. // Found a duplicate (a base+offset combination that's seen earlier).
  1899. // Backtrack.
  1900. --Loc;
  1901. break;
  1902. }
  1903. }
  1904. // Re-schedule loads.
  1905. for (unsigned i = 0, e = LdBases.size(); i != e; ++i) {
  1906. unsigned Base = LdBases[i];
  1907. SmallVectorImpl<MachineInstr *> &Lds = Base2LdsMap[Base];
  1908. if (Lds.size() > 1)
  1909. RetVal |= RescheduleOps(MBB, Lds, Base, true, MI2LocMap);
  1910. }
  1911. // Re-schedule stores.
  1912. for (unsigned i = 0, e = StBases.size(); i != e; ++i) {
  1913. unsigned Base = StBases[i];
  1914. SmallVectorImpl<MachineInstr *> &Sts = Base2StsMap[Base];
  1915. if (Sts.size() > 1)
  1916. RetVal |= RescheduleOps(MBB, Sts, Base, false, MI2LocMap);
  1917. }
  1918. if (MBBI != E) {
  1919. Base2LdsMap.clear();
  1920. Base2StsMap.clear();
  1921. LdBases.clear();
  1922. StBases.clear();
  1923. }
  1924. }
  1925. return RetVal;
  1926. }
  1927. /// createARMLoadStoreOptimizationPass - returns an instance of the load / store
  1928. /// optimization pass.
  1929. FunctionPass *llvm::createARMLoadStoreOptimizationPass(bool PreAlloc) {
  1930. if (PreAlloc)
  1931. return new ARMPreAllocLoadStoreOpt();
  1932. return new ARMLoadStoreOpt();
  1933. }