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