PPCVSXSwapRemoval.cpp 38 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072
  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. break;
  474. }
  475. }
  476. }
  477. if (RelevantFunction) {
  478. LLVM_DEBUG(dbgs() << "Swap vector when first built\n\n");
  479. LLVM_DEBUG(dumpSwapVector());
  480. }
  481. return RelevantFunction;
  482. }
  483. // Add an entry to the swap vector and swap map, and make a
  484. // singleton equivalence class for the entry.
  485. int PPCVSXSwapRemoval::addSwapEntry(MachineInstr *MI,
  486. PPCVSXSwapEntry& SwapEntry) {
  487. SwapEntry.VSEMI = MI;
  488. SwapEntry.VSEId = SwapVector.size();
  489. SwapVector.push_back(SwapEntry);
  490. EC->insert(SwapEntry.VSEId);
  491. SwapMap[MI] = SwapEntry.VSEId;
  492. return SwapEntry.VSEId;
  493. }
  494. // This is used to find the "true" source register for an
  495. // XXPERMDI instruction, since MachineCSE does not handle the
  496. // "copy-like" operations (Copy and SubregToReg). Returns
  497. // the original SrcReg unless it is the target of a copy-like
  498. // operation, in which case we chain backwards through all
  499. // such operations to the ultimate source register. If a
  500. // physical register is encountered, we stop the search and
  501. // flag the swap entry indicated by VecIdx (the original
  502. // XXPERMDI) as mentioning a physical register.
  503. unsigned PPCVSXSwapRemoval::lookThruCopyLike(unsigned SrcReg,
  504. unsigned VecIdx) {
  505. MachineInstr *MI = MRI->getVRegDef(SrcReg);
  506. if (!MI->isCopyLike())
  507. return SrcReg;
  508. unsigned CopySrcReg;
  509. if (MI->isCopy())
  510. CopySrcReg = MI->getOperand(1).getReg();
  511. else {
  512. assert(MI->isSubregToReg() && "bad opcode for lookThruCopyLike");
  513. CopySrcReg = MI->getOperand(2).getReg();
  514. }
  515. if (!Register::isVirtualRegister(CopySrcReg)) {
  516. if (!isScalarVecReg(CopySrcReg))
  517. SwapVector[VecIdx].MentionsPhysVR = 1;
  518. return CopySrcReg;
  519. }
  520. return lookThruCopyLike(CopySrcReg, VecIdx);
  521. }
  522. // Generate equivalence classes for related computations (webs) by
  523. // def-use relationships of virtual registers. Mention of a physical
  524. // register terminates the generation of equivalence classes as this
  525. // indicates a use of a parameter, definition of a return value, use
  526. // of a value returned from a call, or definition of a parameter to a
  527. // call. Computations with physical register mentions are flagged
  528. // as such so their containing webs will not be optimized.
  529. void PPCVSXSwapRemoval::formWebs() {
  530. LLVM_DEBUG(dbgs() << "\n*** Forming webs for swap removal ***\n\n");
  531. for (unsigned EntryIdx = 0; EntryIdx < SwapVector.size(); ++EntryIdx) {
  532. MachineInstr *MI = SwapVector[EntryIdx].VSEMI;
  533. LLVM_DEBUG(dbgs() << "\n" << SwapVector[EntryIdx].VSEId << " ");
  534. LLVM_DEBUG(MI->dump());
  535. // It's sufficient to walk vector uses and join them to their unique
  536. // definitions. In addition, check full vector register operands
  537. // for physical regs. We exclude partial-vector register operands
  538. // because we can handle them if copied to a full vector.
  539. for (const MachineOperand &MO : MI->operands()) {
  540. if (!MO.isReg())
  541. continue;
  542. Register Reg = MO.getReg();
  543. if (!isVecReg(Reg) && !isScalarVecReg(Reg))
  544. continue;
  545. if (!Register::isVirtualRegister(Reg)) {
  546. if (!(MI->isCopy() && isScalarVecReg(Reg)))
  547. SwapVector[EntryIdx].MentionsPhysVR = 1;
  548. continue;
  549. }
  550. if (!MO.isUse())
  551. continue;
  552. MachineInstr* DefMI = MRI->getVRegDef(Reg);
  553. assert(SwapMap.find(DefMI) != SwapMap.end() &&
  554. "Inconsistency: def of vector reg not found in swap map!");
  555. int DefIdx = SwapMap[DefMI];
  556. (void)EC->unionSets(SwapVector[DefIdx].VSEId,
  557. SwapVector[EntryIdx].VSEId);
  558. LLVM_DEBUG(dbgs() << format("Unioning %d with %d\n",
  559. SwapVector[DefIdx].VSEId,
  560. SwapVector[EntryIdx].VSEId));
  561. LLVM_DEBUG(dbgs() << " Def: ");
  562. LLVM_DEBUG(DefMI->dump());
  563. }
  564. }
  565. }
  566. // Walk the swap vector entries looking for conditions that prevent their
  567. // containing computations from being optimized. When such conditions are
  568. // found, mark the representative of the computation's equivalence class
  569. // as rejected.
  570. void PPCVSXSwapRemoval::recordUnoptimizableWebs() {
  571. LLVM_DEBUG(dbgs() << "\n*** Rejecting webs for swap removal ***\n\n");
  572. for (unsigned EntryIdx = 0; EntryIdx < SwapVector.size(); ++EntryIdx) {
  573. int Repr = EC->getLeaderValue(SwapVector[EntryIdx].VSEId);
  574. // If representative is already rejected, don't waste further time.
  575. if (SwapVector[Repr].WebRejected)
  576. continue;
  577. // Reject webs containing mentions of physical or partial registers, or
  578. // containing operations that we don't know how to handle in a lane-
  579. // permuted region.
  580. if (SwapVector[EntryIdx].MentionsPhysVR ||
  581. SwapVector[EntryIdx].MentionsPartialVR ||
  582. !(SwapVector[EntryIdx].IsSwappable || SwapVector[EntryIdx].IsSwap)) {
  583. SwapVector[Repr].WebRejected = 1;
  584. LLVM_DEBUG(
  585. dbgs() << format("Web %d rejected for physreg, partial reg, or not "
  586. "swap[pable]\n",
  587. Repr));
  588. LLVM_DEBUG(dbgs() << " in " << EntryIdx << ": ");
  589. LLVM_DEBUG(SwapVector[EntryIdx].VSEMI->dump());
  590. LLVM_DEBUG(dbgs() << "\n");
  591. }
  592. // Reject webs than contain swapping loads that feed something other
  593. // than a swap instruction.
  594. else if (SwapVector[EntryIdx].IsLoad && SwapVector[EntryIdx].IsSwap) {
  595. MachineInstr *MI = SwapVector[EntryIdx].VSEMI;
  596. Register DefReg = MI->getOperand(0).getReg();
  597. // We skip debug instructions in the analysis. (Note that debug
  598. // location information is still maintained by this optimization
  599. // because it remains on the LXVD2X and STXVD2X instructions after
  600. // the XXPERMDIs are removed.)
  601. for (MachineInstr &UseMI : MRI->use_nodbg_instructions(DefReg)) {
  602. int UseIdx = SwapMap[&UseMI];
  603. if (!SwapVector[UseIdx].IsSwap || SwapVector[UseIdx].IsLoad ||
  604. SwapVector[UseIdx].IsStore) {
  605. SwapVector[Repr].WebRejected = 1;
  606. LLVM_DEBUG(dbgs() << format(
  607. "Web %d rejected for load not feeding swap\n", Repr));
  608. LLVM_DEBUG(dbgs() << " def " << EntryIdx << ": ");
  609. LLVM_DEBUG(MI->dump());
  610. LLVM_DEBUG(dbgs() << " use " << UseIdx << ": ");
  611. LLVM_DEBUG(UseMI.dump());
  612. LLVM_DEBUG(dbgs() << "\n");
  613. }
  614. // It is possible that the load feeds a swap and that swap feeds a
  615. // store. In such a case, the code is actually trying to store a swapped
  616. // vector. We must reject such webs.
  617. if (SwapVector[UseIdx].IsSwap && !SwapVector[UseIdx].IsLoad &&
  618. !SwapVector[UseIdx].IsStore) {
  619. Register SwapDefReg = UseMI.getOperand(0).getReg();
  620. for (MachineInstr &UseOfUseMI :
  621. MRI->use_nodbg_instructions(SwapDefReg)) {
  622. int UseOfUseIdx = SwapMap[&UseOfUseMI];
  623. if (SwapVector[UseOfUseIdx].IsStore) {
  624. SwapVector[Repr].WebRejected = 1;
  625. LLVM_DEBUG(
  626. dbgs() << format(
  627. "Web %d rejected for load/swap feeding a store\n", Repr));
  628. LLVM_DEBUG(dbgs() << " def " << EntryIdx << ": ");
  629. LLVM_DEBUG(MI->dump());
  630. LLVM_DEBUG(dbgs() << " use " << UseIdx << ": ");
  631. LLVM_DEBUG(UseMI.dump());
  632. LLVM_DEBUG(dbgs() << "\n");
  633. }
  634. }
  635. }
  636. }
  637. // Reject webs that contain swapping stores that are fed by something
  638. // other than a swap instruction.
  639. } else if (SwapVector[EntryIdx].IsStore && SwapVector[EntryIdx].IsSwap) {
  640. MachineInstr *MI = SwapVector[EntryIdx].VSEMI;
  641. Register UseReg = MI->getOperand(0).getReg();
  642. MachineInstr *DefMI = MRI->getVRegDef(UseReg);
  643. Register DefReg = DefMI->getOperand(0).getReg();
  644. int DefIdx = SwapMap[DefMI];
  645. if (!SwapVector[DefIdx].IsSwap || SwapVector[DefIdx].IsLoad ||
  646. SwapVector[DefIdx].IsStore) {
  647. SwapVector[Repr].WebRejected = 1;
  648. LLVM_DEBUG(dbgs() << format(
  649. "Web %d rejected for store not fed by swap\n", Repr));
  650. LLVM_DEBUG(dbgs() << " def " << DefIdx << ": ");
  651. LLVM_DEBUG(DefMI->dump());
  652. LLVM_DEBUG(dbgs() << " use " << EntryIdx << ": ");
  653. LLVM_DEBUG(MI->dump());
  654. LLVM_DEBUG(dbgs() << "\n");
  655. }
  656. // Ensure all uses of the register defined by DefMI feed store
  657. // instructions
  658. for (MachineInstr &UseMI : MRI->use_nodbg_instructions(DefReg)) {
  659. int UseIdx = SwapMap[&UseMI];
  660. if (SwapVector[UseIdx].VSEMI->getOpcode() != MI->getOpcode()) {
  661. SwapVector[Repr].WebRejected = 1;
  662. LLVM_DEBUG(
  663. dbgs() << format(
  664. "Web %d rejected for swap not feeding only stores\n", Repr));
  665. LLVM_DEBUG(dbgs() << " def "
  666. << " : ");
  667. LLVM_DEBUG(DefMI->dump());
  668. LLVM_DEBUG(dbgs() << " use " << UseIdx << ": ");
  669. LLVM_DEBUG(SwapVector[UseIdx].VSEMI->dump());
  670. LLVM_DEBUG(dbgs() << "\n");
  671. }
  672. }
  673. }
  674. }
  675. LLVM_DEBUG(dbgs() << "Swap vector after web analysis:\n\n");
  676. LLVM_DEBUG(dumpSwapVector());
  677. }
  678. // Walk the swap vector entries looking for swaps fed by permuting loads
  679. // and swaps that feed permuting stores. If the containing computation
  680. // has not been marked rejected, mark each such swap for removal.
  681. // (Removal is delayed in case optimization has disturbed the pattern,
  682. // such that multiple loads feed the same swap, etc.)
  683. void PPCVSXSwapRemoval::markSwapsForRemoval() {
  684. LLVM_DEBUG(dbgs() << "\n*** Marking swaps for removal ***\n\n");
  685. for (unsigned EntryIdx = 0; EntryIdx < SwapVector.size(); ++EntryIdx) {
  686. if (SwapVector[EntryIdx].IsLoad && SwapVector[EntryIdx].IsSwap) {
  687. int Repr = EC->getLeaderValue(SwapVector[EntryIdx].VSEId);
  688. if (!SwapVector[Repr].WebRejected) {
  689. MachineInstr *MI = SwapVector[EntryIdx].VSEMI;
  690. Register DefReg = MI->getOperand(0).getReg();
  691. for (MachineInstr &UseMI : MRI->use_nodbg_instructions(DefReg)) {
  692. int UseIdx = SwapMap[&UseMI];
  693. SwapVector[UseIdx].WillRemove = 1;
  694. LLVM_DEBUG(dbgs() << "Marking swap fed by load for removal: ");
  695. LLVM_DEBUG(UseMI.dump());
  696. }
  697. }
  698. } else if (SwapVector[EntryIdx].IsStore && SwapVector[EntryIdx].IsSwap) {
  699. int Repr = EC->getLeaderValue(SwapVector[EntryIdx].VSEId);
  700. if (!SwapVector[Repr].WebRejected) {
  701. MachineInstr *MI = SwapVector[EntryIdx].VSEMI;
  702. Register UseReg = MI->getOperand(0).getReg();
  703. MachineInstr *DefMI = MRI->getVRegDef(UseReg);
  704. int DefIdx = SwapMap[DefMI];
  705. SwapVector[DefIdx].WillRemove = 1;
  706. LLVM_DEBUG(dbgs() << "Marking swap feeding store for removal: ");
  707. LLVM_DEBUG(DefMI->dump());
  708. }
  709. } else if (SwapVector[EntryIdx].IsSwappable &&
  710. SwapVector[EntryIdx].SpecialHandling != 0) {
  711. int Repr = EC->getLeaderValue(SwapVector[EntryIdx].VSEId);
  712. if (!SwapVector[Repr].WebRejected)
  713. handleSpecialSwappables(EntryIdx);
  714. }
  715. }
  716. }
  717. // Create an xxswapd instruction and insert it prior to the given point.
  718. // MI is used to determine basic block and debug loc information.
  719. // FIXME: When inserting a swap, we should check whether SrcReg is
  720. // defined by another swap: SrcReg = XXPERMDI Reg, Reg, 2; If so,
  721. // then instead we should generate a copy from Reg to DstReg.
  722. void PPCVSXSwapRemoval::insertSwap(MachineInstr *MI,
  723. MachineBasicBlock::iterator InsertPoint,
  724. unsigned DstReg, unsigned SrcReg) {
  725. BuildMI(*MI->getParent(), InsertPoint, MI->getDebugLoc(),
  726. TII->get(PPC::XXPERMDI), DstReg)
  727. .addReg(SrcReg)
  728. .addReg(SrcReg)
  729. .addImm(2);
  730. }
  731. // The identified swap entry requires special handling to allow its
  732. // containing computation to be optimized. Perform that handling
  733. // here.
  734. // FIXME: Additional opportunities will be phased in with subsequent
  735. // patches.
  736. void PPCVSXSwapRemoval::handleSpecialSwappables(int EntryIdx) {
  737. switch (SwapVector[EntryIdx].SpecialHandling) {
  738. default:
  739. llvm_unreachable("Unexpected special handling type");
  740. // For splats based on an index into a vector, add N/2 modulo N
  741. // to the index, where N is the number of vector elements.
  742. case SHValues::SH_SPLAT: {
  743. MachineInstr *MI = SwapVector[EntryIdx].VSEMI;
  744. unsigned NElts;
  745. LLVM_DEBUG(dbgs() << "Changing splat: ");
  746. LLVM_DEBUG(MI->dump());
  747. switch (MI->getOpcode()) {
  748. default:
  749. llvm_unreachable("Unexpected splat opcode");
  750. case PPC::VSPLTB: NElts = 16; break;
  751. case PPC::VSPLTH: NElts = 8; break;
  752. case PPC::VSPLTW:
  753. case PPC::XXSPLTW: NElts = 4; break;
  754. }
  755. unsigned EltNo;
  756. if (MI->getOpcode() == PPC::XXSPLTW)
  757. EltNo = MI->getOperand(2).getImm();
  758. else
  759. EltNo = MI->getOperand(1).getImm();
  760. EltNo = (EltNo + NElts / 2) % NElts;
  761. if (MI->getOpcode() == PPC::XXSPLTW)
  762. MI->getOperand(2).setImm(EltNo);
  763. else
  764. MI->getOperand(1).setImm(EltNo);
  765. LLVM_DEBUG(dbgs() << " Into: ");
  766. LLVM_DEBUG(MI->dump());
  767. break;
  768. }
  769. // For an XXPERMDI that isn't handled otherwise, we need to
  770. // reverse the order of the operands. If the selector operand
  771. // has a value of 0 or 3, we need to change it to 3 or 0,
  772. // respectively. Otherwise we should leave it alone. (This
  773. // is equivalent to reversing the two bits of the selector
  774. // operand and complementing the result.)
  775. case SHValues::SH_XXPERMDI: {
  776. MachineInstr *MI = SwapVector[EntryIdx].VSEMI;
  777. LLVM_DEBUG(dbgs() << "Changing XXPERMDI: ");
  778. LLVM_DEBUG(MI->dump());
  779. unsigned Selector = MI->getOperand(3).getImm();
  780. if (Selector == 0 || Selector == 3)
  781. Selector = 3 - Selector;
  782. MI->getOperand(3).setImm(Selector);
  783. Register Reg1 = MI->getOperand(1).getReg();
  784. Register Reg2 = MI->getOperand(2).getReg();
  785. MI->getOperand(1).setReg(Reg2);
  786. MI->getOperand(2).setReg(Reg1);
  787. // We also need to swap kill flag associated with the register.
  788. bool IsKill1 = MI->getOperand(1).isKill();
  789. bool IsKill2 = MI->getOperand(2).isKill();
  790. MI->getOperand(1).setIsKill(IsKill2);
  791. MI->getOperand(2).setIsKill(IsKill1);
  792. LLVM_DEBUG(dbgs() << " Into: ");
  793. LLVM_DEBUG(MI->dump());
  794. break;
  795. }
  796. // For a copy from a scalar floating-point register to a vector
  797. // register, removing swaps will leave the copied value in the
  798. // wrong lane. Insert a swap following the copy to fix this.
  799. case SHValues::SH_COPYWIDEN: {
  800. MachineInstr *MI = SwapVector[EntryIdx].VSEMI;
  801. LLVM_DEBUG(dbgs() << "Changing SUBREG_TO_REG: ");
  802. LLVM_DEBUG(MI->dump());
  803. Register DstReg = MI->getOperand(0).getReg();
  804. const TargetRegisterClass *DstRC = MRI->getRegClass(DstReg);
  805. Register NewVReg = MRI->createVirtualRegister(DstRC);
  806. MI->getOperand(0).setReg(NewVReg);
  807. LLVM_DEBUG(dbgs() << " Into: ");
  808. LLVM_DEBUG(MI->dump());
  809. auto InsertPoint = ++MachineBasicBlock::iterator(MI);
  810. // Note that an XXPERMDI requires a VSRC, so if the SUBREG_TO_REG
  811. // is copying to a VRRC, we need to be careful to avoid a register
  812. // assignment problem. In this case we must copy from VRRC to VSRC
  813. // prior to the swap, and from VSRC to VRRC following the swap.
  814. // Coalescing will usually remove all this mess.
  815. if (DstRC == &PPC::VRRCRegClass) {
  816. Register VSRCTmp1 = MRI->createVirtualRegister(&PPC::VSRCRegClass);
  817. Register VSRCTmp2 = MRI->createVirtualRegister(&PPC::VSRCRegClass);
  818. BuildMI(*MI->getParent(), InsertPoint, MI->getDebugLoc(),
  819. TII->get(PPC::COPY), VSRCTmp1)
  820. .addReg(NewVReg);
  821. LLVM_DEBUG(std::prev(InsertPoint)->dump());
  822. insertSwap(MI, InsertPoint, VSRCTmp2, VSRCTmp1);
  823. LLVM_DEBUG(std::prev(InsertPoint)->dump());
  824. BuildMI(*MI->getParent(), InsertPoint, MI->getDebugLoc(),
  825. TII->get(PPC::COPY), DstReg)
  826. .addReg(VSRCTmp2);
  827. LLVM_DEBUG(std::prev(InsertPoint)->dump());
  828. } else {
  829. insertSwap(MI, InsertPoint, DstReg, NewVReg);
  830. LLVM_DEBUG(std::prev(InsertPoint)->dump());
  831. }
  832. break;
  833. }
  834. }
  835. }
  836. // Walk the swap vector and replace each entry marked for removal with
  837. // a copy operation.
  838. bool PPCVSXSwapRemoval::removeSwaps() {
  839. LLVM_DEBUG(dbgs() << "\n*** Removing swaps ***\n\n");
  840. bool Changed = false;
  841. for (unsigned EntryIdx = 0; EntryIdx < SwapVector.size(); ++EntryIdx) {
  842. if (SwapVector[EntryIdx].WillRemove) {
  843. Changed = true;
  844. MachineInstr *MI = SwapVector[EntryIdx].VSEMI;
  845. MachineBasicBlock *MBB = MI->getParent();
  846. BuildMI(*MBB, MI, MI->getDebugLoc(), TII->get(TargetOpcode::COPY),
  847. MI->getOperand(0).getReg())
  848. .add(MI->getOperand(1));
  849. LLVM_DEBUG(dbgs() << format("Replaced %d with copy: ",
  850. SwapVector[EntryIdx].VSEId));
  851. LLVM_DEBUG(MI->dump());
  852. MI->eraseFromParent();
  853. }
  854. }
  855. return Changed;
  856. }
  857. #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
  858. // For debug purposes, dump the contents of the swap vector.
  859. LLVM_DUMP_METHOD void PPCVSXSwapRemoval::dumpSwapVector() {
  860. for (unsigned EntryIdx = 0; EntryIdx < SwapVector.size(); ++EntryIdx) {
  861. MachineInstr *MI = SwapVector[EntryIdx].VSEMI;
  862. int ID = SwapVector[EntryIdx].VSEId;
  863. dbgs() << format("%6d", ID);
  864. dbgs() << format("%6d", EC->getLeaderValue(ID));
  865. dbgs() << format(" %bb.%3d", MI->getParent()->getNumber());
  866. dbgs() << format(" %14s ", TII->getName(MI->getOpcode()).str().c_str());
  867. if (SwapVector[EntryIdx].IsLoad)
  868. dbgs() << "load ";
  869. if (SwapVector[EntryIdx].IsStore)
  870. dbgs() << "store ";
  871. if (SwapVector[EntryIdx].IsSwap)
  872. dbgs() << "swap ";
  873. if (SwapVector[EntryIdx].MentionsPhysVR)
  874. dbgs() << "physreg ";
  875. if (SwapVector[EntryIdx].MentionsPartialVR)
  876. dbgs() << "partialreg ";
  877. if (SwapVector[EntryIdx].IsSwappable) {
  878. dbgs() << "swappable ";
  879. switch(SwapVector[EntryIdx].SpecialHandling) {
  880. default:
  881. dbgs() << "special:**unknown**";
  882. break;
  883. case SH_NONE:
  884. break;
  885. case SH_EXTRACT:
  886. dbgs() << "special:extract ";
  887. break;
  888. case SH_INSERT:
  889. dbgs() << "special:insert ";
  890. break;
  891. case SH_NOSWAP_LD:
  892. dbgs() << "special:load ";
  893. break;
  894. case SH_NOSWAP_ST:
  895. dbgs() << "special:store ";
  896. break;
  897. case SH_SPLAT:
  898. dbgs() << "special:splat ";
  899. break;
  900. case SH_XXPERMDI:
  901. dbgs() << "special:xxpermdi ";
  902. break;
  903. case SH_COPYWIDEN:
  904. dbgs() << "special:copywiden ";
  905. break;
  906. }
  907. }
  908. if (SwapVector[EntryIdx].WebRejected)
  909. dbgs() << "rejected ";
  910. if (SwapVector[EntryIdx].WillRemove)
  911. dbgs() << "remove ";
  912. dbgs() << "\n";
  913. // For no-asserts builds.
  914. (void)MI;
  915. (void)ID;
  916. }
  917. dbgs() << "\n";
  918. }
  919. #endif
  920. } // end default namespace
  921. INITIALIZE_PASS_BEGIN(PPCVSXSwapRemoval, DEBUG_TYPE,
  922. "PowerPC VSX Swap Removal", false, false)
  923. INITIALIZE_PASS_END(PPCVSXSwapRemoval, DEBUG_TYPE,
  924. "PowerPC VSX Swap Removal", false, false)
  925. char PPCVSXSwapRemoval::ID = 0;
  926. FunctionPass*
  927. llvm::createPPCVSXSwapRemovalPass() { return new PPCVSXSwapRemoval(); }