PPCVSXSwapRemoval.cpp 38 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074
  1. //===----------- PPCVSXSwapRemoval.cpp - Remove VSX LE Swaps -------------===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===---------------------------------------------------------------------===//
  8. //
  9. // This pass analyzes vector computations and removes unnecessary
  10. // doubleword swaps (xxswapd instructions). This pass is performed
  11. // only for little-endian VSX code generation.
  12. //
  13. // For this specific case, loads and stores of v4i32, v4f32, v2i64,
  14. // and v2f64 vectors are inefficient. These are implemented using
  15. // the lxvd2x and stxvd2x instructions, which invert the order of
  16. // doublewords in a vector register. Thus code generation inserts
  17. // an xxswapd after each such load, and prior to each such store.
  18. //
  19. // The extra xxswapd instructions reduce performance. The purpose
  20. // of this pass is to reduce the number of xxswapd instructions
  21. // required for correctness.
  22. //
  23. // The primary insight is that much code that operates on vectors
  24. // does not care about the relative order of elements in a register,
  25. // so long as the correct memory order is preserved. If we have a
  26. // computation where all input values are provided by lxvd2x/xxswapd,
  27. // all outputs are stored using xxswapd/lxvd2x, and all intermediate
  28. // computations are lane-insensitive (independent of element order),
  29. // then all the xxswapd instructions associated with the loads and
  30. // stores may be removed without changing observable semantics.
  31. //
  32. // This pass uses standard equivalence class infrastructure to create
  33. // maximal webs of computations fitting the above description. Each
  34. // such web is then optimized by removing its unnecessary xxswapd
  35. // instructions.
  36. //
  37. // There are some lane-sensitive operations for which we can still
  38. // permit the optimization, provided we modify those operations
  39. // accordingly. Such operations are identified as using "special
  40. // handling" within this module.
  41. //
  42. //===---------------------------------------------------------------------===//
  43. #include "PPC.h"
  44. #include "PPCInstrBuilder.h"
  45. #include "PPCInstrInfo.h"
  46. #include "PPCTargetMachine.h"
  47. #include "llvm/ADT/DenseMap.h"
  48. #include "llvm/ADT/EquivalenceClasses.h"
  49. #include "llvm/CodeGen/MachineFunctionPass.h"
  50. #include "llvm/CodeGen/MachineInstrBuilder.h"
  51. #include "llvm/CodeGen/MachineRegisterInfo.h"
  52. #include "llvm/Config/llvm-config.h"
  53. #include "llvm/Support/Debug.h"
  54. #include "llvm/Support/Format.h"
  55. #include "llvm/Support/raw_ostream.h"
  56. using namespace llvm;
  57. #define DEBUG_TYPE "ppc-vsx-swaps"
  58. namespace {
  59. // A PPCVSXSwapEntry is created for each machine instruction that
  60. // is relevant to a vector computation.
  61. struct PPCVSXSwapEntry {
  62. // Pointer to the instruction.
  63. MachineInstr *VSEMI;
  64. // Unique ID (position in the swap vector).
  65. int VSEId;
  66. // Attributes of this node.
  67. unsigned int IsLoad : 1;
  68. unsigned int IsStore : 1;
  69. unsigned int IsSwap : 1;
  70. unsigned int MentionsPhysVR : 1;
  71. unsigned int IsSwappable : 1;
  72. unsigned int MentionsPartialVR : 1;
  73. unsigned int SpecialHandling : 3;
  74. unsigned int WebRejected : 1;
  75. unsigned int WillRemove : 1;
  76. };
  77. enum SHValues {
  78. SH_NONE = 0,
  79. SH_EXTRACT,
  80. SH_INSERT,
  81. SH_NOSWAP_LD,
  82. SH_NOSWAP_ST,
  83. SH_SPLAT,
  84. SH_XXPERMDI,
  85. SH_COPYWIDEN
  86. };
  87. struct PPCVSXSwapRemoval : public MachineFunctionPass {
  88. static char ID;
  89. const PPCInstrInfo *TII;
  90. MachineFunction *MF;
  91. MachineRegisterInfo *MRI;
  92. // Swap entries are allocated in a vector for better performance.
  93. std::vector<PPCVSXSwapEntry> SwapVector;
  94. // A mapping is maintained between machine instructions and
  95. // their swap entries. The key is the address of the MI.
  96. DenseMap<MachineInstr*, int> SwapMap;
  97. // Equivalence classes are used to gather webs of related computation.
  98. // Swap entries are represented by their VSEId fields.
  99. EquivalenceClasses<int> *EC;
  100. PPCVSXSwapRemoval() : MachineFunctionPass(ID) {
  101. initializePPCVSXSwapRemovalPass(*PassRegistry::getPassRegistry());
  102. }
  103. private:
  104. // Initialize data structures.
  105. void initialize(MachineFunction &MFParm);
  106. // Walk the machine instructions to gather vector usage information.
  107. // Return true iff vector mentions are present.
  108. bool gatherVectorInstructions();
  109. // Add an entry to the swap vector and swap map.
  110. int addSwapEntry(MachineInstr *MI, PPCVSXSwapEntry &SwapEntry);
  111. // Hunt backwards through COPY and SUBREG_TO_REG chains for a
  112. // source register. VecIdx indicates the swap vector entry to
  113. // mark as mentioning a physical register if the search leads
  114. // to one.
  115. unsigned lookThruCopyLike(unsigned SrcReg, unsigned VecIdx);
  116. // Generate equivalence classes for related computations (webs).
  117. void formWebs();
  118. // Analyze webs and determine those that cannot be optimized.
  119. void recordUnoptimizableWebs();
  120. // Record which swap instructions can be safely removed.
  121. void markSwapsForRemoval();
  122. // Remove swaps and update other instructions requiring special
  123. // handling. Return true iff any changes are made.
  124. bool removeSwaps();
  125. // Insert a swap instruction from SrcReg to DstReg at the given
  126. // InsertPoint.
  127. void insertSwap(MachineInstr *MI, MachineBasicBlock::iterator InsertPoint,
  128. unsigned DstReg, unsigned SrcReg);
  129. // Update instructions requiring special handling.
  130. void handleSpecialSwappables(int EntryIdx);
  131. // Dump a description of the entries in the swap vector.
  132. void dumpSwapVector();
  133. // Return true iff the given register is in the given class.
  134. bool isRegInClass(unsigned Reg, const TargetRegisterClass *RC) {
  135. if (Register::isVirtualRegister(Reg))
  136. return RC->hasSubClassEq(MRI->getRegClass(Reg));
  137. return RC->contains(Reg);
  138. }
  139. // Return true iff the given register is a full vector register.
  140. bool isVecReg(unsigned Reg) {
  141. return (isRegInClass(Reg, &PPC::VSRCRegClass) ||
  142. isRegInClass(Reg, &PPC::VRRCRegClass));
  143. }
  144. // Return true iff the given register is a partial vector register.
  145. bool isScalarVecReg(unsigned Reg) {
  146. return (isRegInClass(Reg, &PPC::VSFRCRegClass) ||
  147. isRegInClass(Reg, &PPC::VSSRCRegClass));
  148. }
  149. // Return true iff the given register mentions all or part of a
  150. // vector register. Also sets Partial to true if the mention
  151. // is for just the floating-point register overlap of the register.
  152. bool isAnyVecReg(unsigned Reg, bool &Partial) {
  153. if (isScalarVecReg(Reg))
  154. Partial = true;
  155. return isScalarVecReg(Reg) || isVecReg(Reg);
  156. }
  157. public:
  158. // Main entry point for this pass.
  159. bool runOnMachineFunction(MachineFunction &MF) override {
  160. if (skipFunction(MF.getFunction()))
  161. return false;
  162. // If we don't have VSX on the subtarget, don't do anything.
  163. // Also, on Power 9 the load and store ops preserve element order and so
  164. // the swaps are not required.
  165. const PPCSubtarget &STI = MF.getSubtarget<PPCSubtarget>();
  166. if (!STI.hasVSX() || !STI.needsSwapsForVSXMemOps())
  167. return false;
  168. bool Changed = false;
  169. initialize(MF);
  170. if (gatherVectorInstructions()) {
  171. formWebs();
  172. recordUnoptimizableWebs();
  173. markSwapsForRemoval();
  174. Changed = removeSwaps();
  175. }
  176. // FIXME: See the allocation of EC in initialize().
  177. delete EC;
  178. return Changed;
  179. }
  180. };
  181. // Initialize data structures for this pass. In particular, clear the
  182. // swap vector and allocate the equivalence class mapping before
  183. // processing each function.
  184. void PPCVSXSwapRemoval::initialize(MachineFunction &MFParm) {
  185. MF = &MFParm;
  186. MRI = &MF->getRegInfo();
  187. TII = MF->getSubtarget<PPCSubtarget>().getInstrInfo();
  188. // An initial vector size of 256 appears to work well in practice.
  189. // Small/medium functions with vector content tend not to incur a
  190. // reallocation at this size. Three of the vector tests in
  191. // projects/test-suite reallocate, which seems like a reasonable rate.
  192. const int InitialVectorSize(256);
  193. SwapVector.clear();
  194. SwapVector.reserve(InitialVectorSize);
  195. // FIXME: Currently we allocate EC each time because we don't have
  196. // access to the set representation on which to call clear(). Should
  197. // consider adding a clear() method to the EquivalenceClasses class.
  198. EC = new EquivalenceClasses<int>;
  199. }
  200. // Create an entry in the swap vector for each instruction that mentions
  201. // a full vector register, recording various characteristics of the
  202. // instructions there.
  203. bool PPCVSXSwapRemoval::gatherVectorInstructions() {
  204. bool RelevantFunction = false;
  205. for (MachineBasicBlock &MBB : *MF) {
  206. for (MachineInstr &MI : MBB) {
  207. if (MI.isDebugInstr())
  208. continue;
  209. bool RelevantInstr = false;
  210. bool Partial = false;
  211. for (const MachineOperand &MO : MI.operands()) {
  212. if (!MO.isReg())
  213. continue;
  214. Register Reg = MO.getReg();
  215. // All operands need to be checked because there are instructions that
  216. // operate on a partial register and produce a full register (such as
  217. // XXPERMDIs).
  218. if (isAnyVecReg(Reg, Partial))
  219. RelevantInstr = true;
  220. }
  221. if (!RelevantInstr)
  222. continue;
  223. RelevantFunction = true;
  224. // Create a SwapEntry initialized to zeros, then fill in the
  225. // instruction and ID fields before pushing it to the back
  226. // of the swap vector.
  227. PPCVSXSwapEntry SwapEntry{};
  228. int VecIdx = addSwapEntry(&MI, SwapEntry);
  229. switch(MI.getOpcode()) {
  230. default:
  231. // Unless noted otherwise, an instruction is considered
  232. // safe for the optimization. There are a large number of
  233. // such true-SIMD instructions (all vector math, logical,
  234. // select, compare, etc.). However, if the instruction
  235. // mentions a partial vector register and does not have
  236. // special handling defined, it is not swappable.
  237. if (Partial)
  238. SwapVector[VecIdx].MentionsPartialVR = 1;
  239. else
  240. SwapVector[VecIdx].IsSwappable = 1;
  241. break;
  242. case PPC::XXPERMDI: {
  243. // This is a swap if it is of the form XXPERMDI t, s, s, 2.
  244. // Unfortunately, MachineCSE ignores COPY and SUBREG_TO_REG, so we
  245. // can also see XXPERMDI t, SUBREG_TO_REG(s), SUBREG_TO_REG(s), 2,
  246. // for example. We have to look through chains of COPY and
  247. // SUBREG_TO_REG to find the real source value for comparison.
  248. // If the real source value is a physical register, then mark the
  249. // XXPERMDI as mentioning a physical register.
  250. int immed = MI.getOperand(3).getImm();
  251. if (immed == 2) {
  252. unsigned trueReg1 = lookThruCopyLike(MI.getOperand(1).getReg(),
  253. VecIdx);
  254. unsigned trueReg2 = lookThruCopyLike(MI.getOperand(2).getReg(),
  255. VecIdx);
  256. if (trueReg1 == trueReg2)
  257. SwapVector[VecIdx].IsSwap = 1;
  258. else {
  259. // We can still handle these if the two registers are not
  260. // identical, by adjusting the form of the XXPERMDI.
  261. SwapVector[VecIdx].IsSwappable = 1;
  262. SwapVector[VecIdx].SpecialHandling = SHValues::SH_XXPERMDI;
  263. }
  264. // This is a doubleword splat if it is of the form
  265. // XXPERMDI t, s, s, 0 or XXPERMDI t, s, s, 3. As above we
  266. // must look through chains of copy-likes to find the source
  267. // register. We turn off the marking for mention of a physical
  268. // register, because splatting it is safe; the optimization
  269. // will not swap the value in the physical register. Whether
  270. // or not the two input registers are identical, we can handle
  271. // these by adjusting the form of the XXPERMDI.
  272. } else if (immed == 0 || immed == 3) {
  273. SwapVector[VecIdx].IsSwappable = 1;
  274. SwapVector[VecIdx].SpecialHandling = SHValues::SH_XXPERMDI;
  275. unsigned trueReg1 = lookThruCopyLike(MI.getOperand(1).getReg(),
  276. VecIdx);
  277. unsigned trueReg2 = lookThruCopyLike(MI.getOperand(2).getReg(),
  278. VecIdx);
  279. if (trueReg1 == trueReg2)
  280. SwapVector[VecIdx].MentionsPhysVR = 0;
  281. } else {
  282. // We can still handle these by adjusting the form of the XXPERMDI.
  283. SwapVector[VecIdx].IsSwappable = 1;
  284. SwapVector[VecIdx].SpecialHandling = SHValues::SH_XXPERMDI;
  285. }
  286. break;
  287. }
  288. case PPC::LVX:
  289. // Non-permuting loads are currently unsafe. We can use special
  290. // handling for this in the future. By not marking these as
  291. // IsSwap, we ensure computations containing them will be rejected
  292. // for now.
  293. SwapVector[VecIdx].IsLoad = 1;
  294. break;
  295. case PPC::LXVD2X:
  296. case PPC::LXVW4X:
  297. // Permuting loads are marked as both load and swap, and are
  298. // safe for optimization.
  299. SwapVector[VecIdx].IsLoad = 1;
  300. SwapVector[VecIdx].IsSwap = 1;
  301. break;
  302. case PPC::LXSDX:
  303. case PPC::LXSSPX:
  304. case PPC::XFLOADf64:
  305. case PPC::XFLOADf32:
  306. // A load of a floating-point value into the high-order half of
  307. // a vector register is safe, provided that we introduce a swap
  308. // following the load, which will be done by the SUBREG_TO_REG
  309. // support. So just mark these as safe.
  310. SwapVector[VecIdx].IsLoad = 1;
  311. SwapVector[VecIdx].IsSwappable = 1;
  312. break;
  313. case PPC::STVX:
  314. // Non-permuting stores are currently unsafe. We can use special
  315. // handling for this in the future. By not marking these as
  316. // IsSwap, we ensure computations containing them will be rejected
  317. // for now.
  318. SwapVector[VecIdx].IsStore = 1;
  319. break;
  320. case PPC::STXVD2X:
  321. case PPC::STXVW4X:
  322. // Permuting stores are marked as both store and swap, and are
  323. // safe for optimization.
  324. SwapVector[VecIdx].IsStore = 1;
  325. SwapVector[VecIdx].IsSwap = 1;
  326. break;
  327. case PPC::COPY:
  328. // These are fine provided they are moving between full vector
  329. // register classes.
  330. if (isVecReg(MI.getOperand(0).getReg()) &&
  331. isVecReg(MI.getOperand(1).getReg()))
  332. SwapVector[VecIdx].IsSwappable = 1;
  333. // If we have a copy from one scalar floating-point register
  334. // to another, we can accept this even if it is a physical
  335. // register. The only way this gets involved is if it feeds
  336. // a SUBREG_TO_REG, which is handled by introducing a swap.
  337. else if (isScalarVecReg(MI.getOperand(0).getReg()) &&
  338. isScalarVecReg(MI.getOperand(1).getReg()))
  339. SwapVector[VecIdx].IsSwappable = 1;
  340. break;
  341. case PPC::SUBREG_TO_REG: {
  342. // These are fine provided they are moving between full vector
  343. // register classes. If they are moving from a scalar
  344. // floating-point class to a vector class, we can handle those
  345. // as well, provided we introduce a swap. It is generally the
  346. // case that we will introduce fewer swaps than we remove, but
  347. // (FIXME) a cost model could be used. However, introduced
  348. // swaps could potentially be CSEd, so this is not trivial.
  349. if (isVecReg(MI.getOperand(0).getReg()) &&
  350. isVecReg(MI.getOperand(2).getReg()))
  351. SwapVector[VecIdx].IsSwappable = 1;
  352. else if (isVecReg(MI.getOperand(0).getReg()) &&
  353. isScalarVecReg(MI.getOperand(2).getReg())) {
  354. SwapVector[VecIdx].IsSwappable = 1;
  355. SwapVector[VecIdx].SpecialHandling = SHValues::SH_COPYWIDEN;
  356. }
  357. break;
  358. }
  359. case PPC::VSPLTB:
  360. case PPC::VSPLTH:
  361. case PPC::VSPLTW:
  362. case PPC::XXSPLTW:
  363. // Splats are lane-sensitive, but we can use special handling
  364. // to adjust the source lane for the splat.
  365. SwapVector[VecIdx].IsSwappable = 1;
  366. SwapVector[VecIdx].SpecialHandling = SHValues::SH_SPLAT;
  367. break;
  368. // The presence of the following lane-sensitive operations in a
  369. // web will kill the optimization, at least for now. For these
  370. // we do nothing, causing the optimization to fail.
  371. // FIXME: Some of these could be permitted with special handling,
  372. // and will be phased in as time permits.
  373. // FIXME: There is no simple and maintainable way to express a set
  374. // of opcodes having a common attribute in TableGen. Should this
  375. // change, this is a prime candidate to use such a mechanism.
  376. case PPC::INLINEASM:
  377. case PPC::INLINEASM_BR:
  378. case PPC::EXTRACT_SUBREG:
  379. case PPC::INSERT_SUBREG:
  380. case PPC::COPY_TO_REGCLASS:
  381. case PPC::LVEBX:
  382. case PPC::LVEHX:
  383. case PPC::LVEWX:
  384. case PPC::LVSL:
  385. case PPC::LVSR:
  386. case PPC::LVXL:
  387. case PPC::STVEBX:
  388. case PPC::STVEHX:
  389. case PPC::STVEWX:
  390. case PPC::STVXL:
  391. // We can handle STXSDX and STXSSPX similarly to LXSDX and LXSSPX,
  392. // by adding special handling for narrowing copies as well as
  393. // widening ones. However, I've experimented with this, and in
  394. // practice we currently do not appear to use STXSDX fed by
  395. // a narrowing copy from a full vector register. Since I can't
  396. // generate any useful test cases, I've left this alone for now.
  397. case PPC::STXSDX:
  398. case PPC::STXSSPX:
  399. case PPC::VCIPHER:
  400. case PPC::VCIPHERLAST:
  401. case PPC::VMRGHB:
  402. case PPC::VMRGHH:
  403. case PPC::VMRGHW:
  404. case PPC::VMRGLB:
  405. case PPC::VMRGLH:
  406. case PPC::VMRGLW:
  407. case PPC::VMULESB:
  408. case PPC::VMULESH:
  409. case PPC::VMULESW:
  410. case PPC::VMULEUB:
  411. case PPC::VMULEUH:
  412. case PPC::VMULEUW:
  413. case PPC::VMULOSB:
  414. case PPC::VMULOSH:
  415. case PPC::VMULOSW:
  416. case PPC::VMULOUB:
  417. case PPC::VMULOUH:
  418. case PPC::VMULOUW:
  419. case PPC::VNCIPHER:
  420. case PPC::VNCIPHERLAST:
  421. case PPC::VPERM:
  422. case PPC::VPERMXOR:
  423. case PPC::VPKPX:
  424. case PPC::VPKSHSS:
  425. case PPC::VPKSHUS:
  426. case PPC::VPKSDSS:
  427. case PPC::VPKSDUS:
  428. case PPC::VPKSWSS:
  429. case PPC::VPKSWUS:
  430. case PPC::VPKUDUM:
  431. case PPC::VPKUDUS:
  432. case PPC::VPKUHUM:
  433. case PPC::VPKUHUS:
  434. case PPC::VPKUWUM:
  435. case PPC::VPKUWUS:
  436. case PPC::VPMSUMB:
  437. case PPC::VPMSUMD:
  438. case PPC::VPMSUMH:
  439. case PPC::VPMSUMW:
  440. case PPC::VRLB:
  441. case PPC::VRLD:
  442. case PPC::VRLH:
  443. case PPC::VRLW:
  444. case PPC::VSBOX:
  445. case PPC::VSHASIGMAD:
  446. case PPC::VSHASIGMAW:
  447. case PPC::VSL:
  448. case PPC::VSLDOI:
  449. case PPC::VSLO:
  450. case PPC::VSR:
  451. case PPC::VSRO:
  452. case PPC::VSUM2SWS:
  453. case PPC::VSUM4SBS:
  454. case PPC::VSUM4SHS:
  455. case PPC::VSUM4UBS:
  456. case PPC::VSUMSWS:
  457. case PPC::VUPKHPX:
  458. case PPC::VUPKHSB:
  459. case PPC::VUPKHSH:
  460. case PPC::VUPKHSW:
  461. case PPC::VUPKLPX:
  462. case PPC::VUPKLSB:
  463. case PPC::VUPKLSH:
  464. case PPC::VUPKLSW:
  465. case PPC::XXMRGHW:
  466. case PPC::XXMRGLW:
  467. // XXSLDWI could be replaced by a general permute with one of three
  468. // permute control vectors (for shift values 1, 2, 3). However,
  469. // VPERM has a more restrictive register class.
  470. case PPC::XXSLDWI:
  471. case PPC::XSCVDPSPN:
  472. case PPC::XSCVSPDPN:
  473. case PPC::MTVSCR:
  474. case PPC::MFVSCR:
  475. break;
  476. }
  477. }
  478. }
  479. if (RelevantFunction) {
  480. LLVM_DEBUG(dbgs() << "Swap vector when first built\n\n");
  481. LLVM_DEBUG(dumpSwapVector());
  482. }
  483. return RelevantFunction;
  484. }
  485. // Add an entry to the swap vector and swap map, and make a
  486. // singleton equivalence class for the entry.
  487. int PPCVSXSwapRemoval::addSwapEntry(MachineInstr *MI,
  488. PPCVSXSwapEntry& SwapEntry) {
  489. SwapEntry.VSEMI = MI;
  490. SwapEntry.VSEId = SwapVector.size();
  491. SwapVector.push_back(SwapEntry);
  492. EC->insert(SwapEntry.VSEId);
  493. SwapMap[MI] = SwapEntry.VSEId;
  494. return SwapEntry.VSEId;
  495. }
  496. // This is used to find the "true" source register for an
  497. // XXPERMDI instruction, since MachineCSE does not handle the
  498. // "copy-like" operations (Copy and SubregToReg). Returns
  499. // the original SrcReg unless it is the target of a copy-like
  500. // operation, in which case we chain backwards through all
  501. // such operations to the ultimate source register. If a
  502. // physical register is encountered, we stop the search and
  503. // flag the swap entry indicated by VecIdx (the original
  504. // XXPERMDI) as mentioning a physical register.
  505. unsigned PPCVSXSwapRemoval::lookThruCopyLike(unsigned SrcReg,
  506. unsigned VecIdx) {
  507. MachineInstr *MI = MRI->getVRegDef(SrcReg);
  508. if (!MI->isCopyLike())
  509. return SrcReg;
  510. unsigned CopySrcReg;
  511. if (MI->isCopy())
  512. CopySrcReg = MI->getOperand(1).getReg();
  513. else {
  514. assert(MI->isSubregToReg() && "bad opcode for lookThruCopyLike");
  515. CopySrcReg = MI->getOperand(2).getReg();
  516. }
  517. if (!Register::isVirtualRegister(CopySrcReg)) {
  518. if (!isScalarVecReg(CopySrcReg))
  519. SwapVector[VecIdx].MentionsPhysVR = 1;
  520. return CopySrcReg;
  521. }
  522. return lookThruCopyLike(CopySrcReg, VecIdx);
  523. }
  524. // Generate equivalence classes for related computations (webs) by
  525. // def-use relationships of virtual registers. Mention of a physical
  526. // register terminates the generation of equivalence classes as this
  527. // indicates a use of a parameter, definition of a return value, use
  528. // of a value returned from a call, or definition of a parameter to a
  529. // call. Computations with physical register mentions are flagged
  530. // as such so their containing webs will not be optimized.
  531. void PPCVSXSwapRemoval::formWebs() {
  532. LLVM_DEBUG(dbgs() << "\n*** Forming webs for swap removal ***\n\n");
  533. for (unsigned EntryIdx = 0; EntryIdx < SwapVector.size(); ++EntryIdx) {
  534. MachineInstr *MI = SwapVector[EntryIdx].VSEMI;
  535. LLVM_DEBUG(dbgs() << "\n" << SwapVector[EntryIdx].VSEId << " ");
  536. LLVM_DEBUG(MI->dump());
  537. // It's sufficient to walk vector uses and join them to their unique
  538. // definitions. In addition, check full vector register operands
  539. // for physical regs. We exclude partial-vector register operands
  540. // because we can handle them if copied to a full vector.
  541. for (const MachineOperand &MO : MI->operands()) {
  542. if (!MO.isReg())
  543. continue;
  544. Register Reg = MO.getReg();
  545. if (!isVecReg(Reg) && !isScalarVecReg(Reg))
  546. continue;
  547. if (!Reg.isVirtual()) {
  548. if (!(MI->isCopy() && isScalarVecReg(Reg)))
  549. SwapVector[EntryIdx].MentionsPhysVR = 1;
  550. continue;
  551. }
  552. if (!MO.isUse())
  553. continue;
  554. MachineInstr* DefMI = MRI->getVRegDef(Reg);
  555. assert(SwapMap.find(DefMI) != SwapMap.end() &&
  556. "Inconsistency: def of vector reg not found in swap map!");
  557. int DefIdx = SwapMap[DefMI];
  558. (void)EC->unionSets(SwapVector[DefIdx].VSEId,
  559. SwapVector[EntryIdx].VSEId);
  560. LLVM_DEBUG(dbgs() << format("Unioning %d with %d\n",
  561. SwapVector[DefIdx].VSEId,
  562. SwapVector[EntryIdx].VSEId));
  563. LLVM_DEBUG(dbgs() << " Def: ");
  564. LLVM_DEBUG(DefMI->dump());
  565. }
  566. }
  567. }
  568. // Walk the swap vector entries looking for conditions that prevent their
  569. // containing computations from being optimized. When such conditions are
  570. // found, mark the representative of the computation's equivalence class
  571. // as rejected.
  572. void PPCVSXSwapRemoval::recordUnoptimizableWebs() {
  573. LLVM_DEBUG(dbgs() << "\n*** Rejecting webs for swap removal ***\n\n");
  574. for (unsigned EntryIdx = 0; EntryIdx < SwapVector.size(); ++EntryIdx) {
  575. int Repr = EC->getLeaderValue(SwapVector[EntryIdx].VSEId);
  576. // If representative is already rejected, don't waste further time.
  577. if (SwapVector[Repr].WebRejected)
  578. continue;
  579. // Reject webs containing mentions of physical or partial registers, or
  580. // containing operations that we don't know how to handle in a lane-
  581. // permuted region.
  582. if (SwapVector[EntryIdx].MentionsPhysVR ||
  583. SwapVector[EntryIdx].MentionsPartialVR ||
  584. !(SwapVector[EntryIdx].IsSwappable || SwapVector[EntryIdx].IsSwap)) {
  585. SwapVector[Repr].WebRejected = 1;
  586. LLVM_DEBUG(
  587. dbgs() << format("Web %d rejected for physreg, partial reg, or not "
  588. "swap[pable]\n",
  589. Repr));
  590. LLVM_DEBUG(dbgs() << " in " << EntryIdx << ": ");
  591. LLVM_DEBUG(SwapVector[EntryIdx].VSEMI->dump());
  592. LLVM_DEBUG(dbgs() << "\n");
  593. }
  594. // Reject webs than contain swapping loads that feed something other
  595. // than a swap instruction.
  596. else if (SwapVector[EntryIdx].IsLoad && SwapVector[EntryIdx].IsSwap) {
  597. MachineInstr *MI = SwapVector[EntryIdx].VSEMI;
  598. Register DefReg = MI->getOperand(0).getReg();
  599. // We skip debug instructions in the analysis. (Note that debug
  600. // location information is still maintained by this optimization
  601. // because it remains on the LXVD2X and STXVD2X instructions after
  602. // the XXPERMDIs are removed.)
  603. for (MachineInstr &UseMI : MRI->use_nodbg_instructions(DefReg)) {
  604. int UseIdx = SwapMap[&UseMI];
  605. if (!SwapVector[UseIdx].IsSwap || SwapVector[UseIdx].IsLoad ||
  606. SwapVector[UseIdx].IsStore) {
  607. SwapVector[Repr].WebRejected = 1;
  608. LLVM_DEBUG(dbgs() << format(
  609. "Web %d rejected for load not feeding swap\n", Repr));
  610. LLVM_DEBUG(dbgs() << " def " << EntryIdx << ": ");
  611. LLVM_DEBUG(MI->dump());
  612. LLVM_DEBUG(dbgs() << " use " << UseIdx << ": ");
  613. LLVM_DEBUG(UseMI.dump());
  614. LLVM_DEBUG(dbgs() << "\n");
  615. }
  616. // It is possible that the load feeds a swap and that swap feeds a
  617. // store. In such a case, the code is actually trying to store a swapped
  618. // vector. We must reject such webs.
  619. if (SwapVector[UseIdx].IsSwap && !SwapVector[UseIdx].IsLoad &&
  620. !SwapVector[UseIdx].IsStore) {
  621. Register SwapDefReg = UseMI.getOperand(0).getReg();
  622. for (MachineInstr &UseOfUseMI :
  623. MRI->use_nodbg_instructions(SwapDefReg)) {
  624. int UseOfUseIdx = SwapMap[&UseOfUseMI];
  625. if (SwapVector[UseOfUseIdx].IsStore) {
  626. SwapVector[Repr].WebRejected = 1;
  627. LLVM_DEBUG(
  628. dbgs() << format(
  629. "Web %d rejected for load/swap feeding a store\n", Repr));
  630. LLVM_DEBUG(dbgs() << " def " << EntryIdx << ": ");
  631. LLVM_DEBUG(MI->dump());
  632. LLVM_DEBUG(dbgs() << " use " << UseIdx << ": ");
  633. LLVM_DEBUG(UseMI.dump());
  634. LLVM_DEBUG(dbgs() << "\n");
  635. }
  636. }
  637. }
  638. }
  639. // Reject webs that contain swapping stores that are fed by something
  640. // other than a swap instruction.
  641. } else if (SwapVector[EntryIdx].IsStore && SwapVector[EntryIdx].IsSwap) {
  642. MachineInstr *MI = SwapVector[EntryIdx].VSEMI;
  643. Register UseReg = MI->getOperand(0).getReg();
  644. MachineInstr *DefMI = MRI->getVRegDef(UseReg);
  645. Register DefReg = DefMI->getOperand(0).getReg();
  646. int DefIdx = SwapMap[DefMI];
  647. if (!SwapVector[DefIdx].IsSwap || SwapVector[DefIdx].IsLoad ||
  648. SwapVector[DefIdx].IsStore) {
  649. SwapVector[Repr].WebRejected = 1;
  650. LLVM_DEBUG(dbgs() << format(
  651. "Web %d rejected for store not fed by swap\n", Repr));
  652. LLVM_DEBUG(dbgs() << " def " << DefIdx << ": ");
  653. LLVM_DEBUG(DefMI->dump());
  654. LLVM_DEBUG(dbgs() << " use " << EntryIdx << ": ");
  655. LLVM_DEBUG(MI->dump());
  656. LLVM_DEBUG(dbgs() << "\n");
  657. }
  658. // Ensure all uses of the register defined by DefMI feed store
  659. // instructions
  660. for (MachineInstr &UseMI : MRI->use_nodbg_instructions(DefReg)) {
  661. int UseIdx = SwapMap[&UseMI];
  662. if (SwapVector[UseIdx].VSEMI->getOpcode() != MI->getOpcode()) {
  663. SwapVector[Repr].WebRejected = 1;
  664. LLVM_DEBUG(
  665. dbgs() << format(
  666. "Web %d rejected for swap not feeding only stores\n", Repr));
  667. LLVM_DEBUG(dbgs() << " def "
  668. << " : ");
  669. LLVM_DEBUG(DefMI->dump());
  670. LLVM_DEBUG(dbgs() << " use " << UseIdx << ": ");
  671. LLVM_DEBUG(SwapVector[UseIdx].VSEMI->dump());
  672. LLVM_DEBUG(dbgs() << "\n");
  673. }
  674. }
  675. }
  676. }
  677. LLVM_DEBUG(dbgs() << "Swap vector after web analysis:\n\n");
  678. LLVM_DEBUG(dumpSwapVector());
  679. }
  680. // Walk the swap vector entries looking for swaps fed by permuting loads
  681. // and swaps that feed permuting stores. If the containing computation
  682. // has not been marked rejected, mark each such swap for removal.
  683. // (Removal is delayed in case optimization has disturbed the pattern,
  684. // such that multiple loads feed the same swap, etc.)
  685. void PPCVSXSwapRemoval::markSwapsForRemoval() {
  686. LLVM_DEBUG(dbgs() << "\n*** Marking swaps for removal ***\n\n");
  687. for (unsigned EntryIdx = 0; EntryIdx < SwapVector.size(); ++EntryIdx) {
  688. if (SwapVector[EntryIdx].IsLoad && SwapVector[EntryIdx].IsSwap) {
  689. int Repr = EC->getLeaderValue(SwapVector[EntryIdx].VSEId);
  690. if (!SwapVector[Repr].WebRejected) {
  691. MachineInstr *MI = SwapVector[EntryIdx].VSEMI;
  692. Register DefReg = MI->getOperand(0).getReg();
  693. for (MachineInstr &UseMI : MRI->use_nodbg_instructions(DefReg)) {
  694. int UseIdx = SwapMap[&UseMI];
  695. SwapVector[UseIdx].WillRemove = 1;
  696. LLVM_DEBUG(dbgs() << "Marking swap fed by load for removal: ");
  697. LLVM_DEBUG(UseMI.dump());
  698. }
  699. }
  700. } else if (SwapVector[EntryIdx].IsStore && SwapVector[EntryIdx].IsSwap) {
  701. int Repr = EC->getLeaderValue(SwapVector[EntryIdx].VSEId);
  702. if (!SwapVector[Repr].WebRejected) {
  703. MachineInstr *MI = SwapVector[EntryIdx].VSEMI;
  704. Register UseReg = MI->getOperand(0).getReg();
  705. MachineInstr *DefMI = MRI->getVRegDef(UseReg);
  706. int DefIdx = SwapMap[DefMI];
  707. SwapVector[DefIdx].WillRemove = 1;
  708. LLVM_DEBUG(dbgs() << "Marking swap feeding store for removal: ");
  709. LLVM_DEBUG(DefMI->dump());
  710. }
  711. } else if (SwapVector[EntryIdx].IsSwappable &&
  712. SwapVector[EntryIdx].SpecialHandling != 0) {
  713. int Repr = EC->getLeaderValue(SwapVector[EntryIdx].VSEId);
  714. if (!SwapVector[Repr].WebRejected)
  715. handleSpecialSwappables(EntryIdx);
  716. }
  717. }
  718. }
  719. // Create an xxswapd instruction and insert it prior to the given point.
  720. // MI is used to determine basic block and debug loc information.
  721. // FIXME: When inserting a swap, we should check whether SrcReg is
  722. // defined by another swap: SrcReg = XXPERMDI Reg, Reg, 2; If so,
  723. // then instead we should generate a copy from Reg to DstReg.
  724. void PPCVSXSwapRemoval::insertSwap(MachineInstr *MI,
  725. MachineBasicBlock::iterator InsertPoint,
  726. unsigned DstReg, unsigned SrcReg) {
  727. BuildMI(*MI->getParent(), InsertPoint, MI->getDebugLoc(),
  728. TII->get(PPC::XXPERMDI), DstReg)
  729. .addReg(SrcReg)
  730. .addReg(SrcReg)
  731. .addImm(2);
  732. }
  733. // The identified swap entry requires special handling to allow its
  734. // containing computation to be optimized. Perform that handling
  735. // here.
  736. // FIXME: Additional opportunities will be phased in with subsequent
  737. // patches.
  738. void PPCVSXSwapRemoval::handleSpecialSwappables(int EntryIdx) {
  739. switch (SwapVector[EntryIdx].SpecialHandling) {
  740. default:
  741. llvm_unreachable("Unexpected special handling type");
  742. // For splats based on an index into a vector, add N/2 modulo N
  743. // to the index, where N is the number of vector elements.
  744. case SHValues::SH_SPLAT: {
  745. MachineInstr *MI = SwapVector[EntryIdx].VSEMI;
  746. unsigned NElts;
  747. LLVM_DEBUG(dbgs() << "Changing splat: ");
  748. LLVM_DEBUG(MI->dump());
  749. switch (MI->getOpcode()) {
  750. default:
  751. llvm_unreachable("Unexpected splat opcode");
  752. case PPC::VSPLTB: NElts = 16; break;
  753. case PPC::VSPLTH: NElts = 8; break;
  754. case PPC::VSPLTW:
  755. case PPC::XXSPLTW: NElts = 4; break;
  756. }
  757. unsigned EltNo;
  758. if (MI->getOpcode() == PPC::XXSPLTW)
  759. EltNo = MI->getOperand(2).getImm();
  760. else
  761. EltNo = MI->getOperand(1).getImm();
  762. EltNo = (EltNo + NElts / 2) % NElts;
  763. if (MI->getOpcode() == PPC::XXSPLTW)
  764. MI->getOperand(2).setImm(EltNo);
  765. else
  766. MI->getOperand(1).setImm(EltNo);
  767. LLVM_DEBUG(dbgs() << " Into: ");
  768. LLVM_DEBUG(MI->dump());
  769. break;
  770. }
  771. // For an XXPERMDI that isn't handled otherwise, we need to
  772. // reverse the order of the operands. If the selector operand
  773. // has a value of 0 or 3, we need to change it to 3 or 0,
  774. // respectively. Otherwise we should leave it alone. (This
  775. // is equivalent to reversing the two bits of the selector
  776. // operand and complementing the result.)
  777. case SHValues::SH_XXPERMDI: {
  778. MachineInstr *MI = SwapVector[EntryIdx].VSEMI;
  779. LLVM_DEBUG(dbgs() << "Changing XXPERMDI: ");
  780. LLVM_DEBUG(MI->dump());
  781. unsigned Selector = MI->getOperand(3).getImm();
  782. if (Selector == 0 || Selector == 3)
  783. Selector = 3 - Selector;
  784. MI->getOperand(3).setImm(Selector);
  785. Register Reg1 = MI->getOperand(1).getReg();
  786. Register Reg2 = MI->getOperand(2).getReg();
  787. MI->getOperand(1).setReg(Reg2);
  788. MI->getOperand(2).setReg(Reg1);
  789. // We also need to swap kill flag associated with the register.
  790. bool IsKill1 = MI->getOperand(1).isKill();
  791. bool IsKill2 = MI->getOperand(2).isKill();
  792. MI->getOperand(1).setIsKill(IsKill2);
  793. MI->getOperand(2).setIsKill(IsKill1);
  794. LLVM_DEBUG(dbgs() << " Into: ");
  795. LLVM_DEBUG(MI->dump());
  796. break;
  797. }
  798. // For a copy from a scalar floating-point register to a vector
  799. // register, removing swaps will leave the copied value in the
  800. // wrong lane. Insert a swap following the copy to fix this.
  801. case SHValues::SH_COPYWIDEN: {
  802. MachineInstr *MI = SwapVector[EntryIdx].VSEMI;
  803. LLVM_DEBUG(dbgs() << "Changing SUBREG_TO_REG: ");
  804. LLVM_DEBUG(MI->dump());
  805. Register DstReg = MI->getOperand(0).getReg();
  806. const TargetRegisterClass *DstRC = MRI->getRegClass(DstReg);
  807. Register NewVReg = MRI->createVirtualRegister(DstRC);
  808. MI->getOperand(0).setReg(NewVReg);
  809. LLVM_DEBUG(dbgs() << " Into: ");
  810. LLVM_DEBUG(MI->dump());
  811. auto InsertPoint = ++MachineBasicBlock::iterator(MI);
  812. // Note that an XXPERMDI requires a VSRC, so if the SUBREG_TO_REG
  813. // is copying to a VRRC, we need to be careful to avoid a register
  814. // assignment problem. In this case we must copy from VRRC to VSRC
  815. // prior to the swap, and from VSRC to VRRC following the swap.
  816. // Coalescing will usually remove all this mess.
  817. if (DstRC == &PPC::VRRCRegClass) {
  818. Register VSRCTmp1 = MRI->createVirtualRegister(&PPC::VSRCRegClass);
  819. Register VSRCTmp2 = MRI->createVirtualRegister(&PPC::VSRCRegClass);
  820. BuildMI(*MI->getParent(), InsertPoint, MI->getDebugLoc(),
  821. TII->get(PPC::COPY), VSRCTmp1)
  822. .addReg(NewVReg);
  823. LLVM_DEBUG(std::prev(InsertPoint)->dump());
  824. insertSwap(MI, InsertPoint, VSRCTmp2, VSRCTmp1);
  825. LLVM_DEBUG(std::prev(InsertPoint)->dump());
  826. BuildMI(*MI->getParent(), InsertPoint, MI->getDebugLoc(),
  827. TII->get(PPC::COPY), DstReg)
  828. .addReg(VSRCTmp2);
  829. LLVM_DEBUG(std::prev(InsertPoint)->dump());
  830. } else {
  831. insertSwap(MI, InsertPoint, DstReg, NewVReg);
  832. LLVM_DEBUG(std::prev(InsertPoint)->dump());
  833. }
  834. break;
  835. }
  836. }
  837. }
  838. // Walk the swap vector and replace each entry marked for removal with
  839. // a copy operation.
  840. bool PPCVSXSwapRemoval::removeSwaps() {
  841. LLVM_DEBUG(dbgs() << "\n*** Removing swaps ***\n\n");
  842. bool Changed = false;
  843. for (unsigned EntryIdx = 0; EntryIdx < SwapVector.size(); ++EntryIdx) {
  844. if (SwapVector[EntryIdx].WillRemove) {
  845. Changed = true;
  846. MachineInstr *MI = SwapVector[EntryIdx].VSEMI;
  847. MachineBasicBlock *MBB = MI->getParent();
  848. BuildMI(*MBB, MI, MI->getDebugLoc(), TII->get(TargetOpcode::COPY),
  849. MI->getOperand(0).getReg())
  850. .add(MI->getOperand(1));
  851. LLVM_DEBUG(dbgs() << format("Replaced %d with copy: ",
  852. SwapVector[EntryIdx].VSEId));
  853. LLVM_DEBUG(MI->dump());
  854. MI->eraseFromParent();
  855. }
  856. }
  857. return Changed;
  858. }
  859. #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
  860. // For debug purposes, dump the contents of the swap vector.
  861. LLVM_DUMP_METHOD void PPCVSXSwapRemoval::dumpSwapVector() {
  862. for (unsigned EntryIdx = 0; EntryIdx < SwapVector.size(); ++EntryIdx) {
  863. MachineInstr *MI = SwapVector[EntryIdx].VSEMI;
  864. int ID = SwapVector[EntryIdx].VSEId;
  865. dbgs() << format("%6d", ID);
  866. dbgs() << format("%6d", EC->getLeaderValue(ID));
  867. dbgs() << format(" %bb.%3d", MI->getParent()->getNumber());
  868. dbgs() << format(" %14s ", TII->getName(MI->getOpcode()).str().c_str());
  869. if (SwapVector[EntryIdx].IsLoad)
  870. dbgs() << "load ";
  871. if (SwapVector[EntryIdx].IsStore)
  872. dbgs() << "store ";
  873. if (SwapVector[EntryIdx].IsSwap)
  874. dbgs() << "swap ";
  875. if (SwapVector[EntryIdx].MentionsPhysVR)
  876. dbgs() << "physreg ";
  877. if (SwapVector[EntryIdx].MentionsPartialVR)
  878. dbgs() << "partialreg ";
  879. if (SwapVector[EntryIdx].IsSwappable) {
  880. dbgs() << "swappable ";
  881. switch(SwapVector[EntryIdx].SpecialHandling) {
  882. default:
  883. dbgs() << "special:**unknown**";
  884. break;
  885. case SH_NONE:
  886. break;
  887. case SH_EXTRACT:
  888. dbgs() << "special:extract ";
  889. break;
  890. case SH_INSERT:
  891. dbgs() << "special:insert ";
  892. break;
  893. case SH_NOSWAP_LD:
  894. dbgs() << "special:load ";
  895. break;
  896. case SH_NOSWAP_ST:
  897. dbgs() << "special:store ";
  898. break;
  899. case SH_SPLAT:
  900. dbgs() << "special:splat ";
  901. break;
  902. case SH_XXPERMDI:
  903. dbgs() << "special:xxpermdi ";
  904. break;
  905. case SH_COPYWIDEN:
  906. dbgs() << "special:copywiden ";
  907. break;
  908. }
  909. }
  910. if (SwapVector[EntryIdx].WebRejected)
  911. dbgs() << "rejected ";
  912. if (SwapVector[EntryIdx].WillRemove)
  913. dbgs() << "remove ";
  914. dbgs() << "\n";
  915. // For no-asserts builds.
  916. (void)MI;
  917. (void)ID;
  918. }
  919. dbgs() << "\n";
  920. }
  921. #endif
  922. } // end default namespace
  923. INITIALIZE_PASS_BEGIN(PPCVSXSwapRemoval, DEBUG_TYPE,
  924. "PowerPC VSX Swap Removal", false, false)
  925. INITIALIZE_PASS_END(PPCVSXSwapRemoval, DEBUG_TYPE,
  926. "PowerPC VSX Swap Removal", false, false)
  927. char PPCVSXSwapRemoval::ID = 0;
  928. FunctionPass*
  929. llvm::createPPCVSXSwapRemovalPass() { return new PPCVSXSwapRemoval(); }