forked from llvm/llvm-project
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathPPCMIPeephole.cpp
1739 lines (1566 loc) · 67.5 KB
/
PPCMIPeephole.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//===-------------- PPCMIPeephole.cpp - MI Peephole Cleanups -------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===---------------------------------------------------------------------===//
//
// This pass performs peephole optimizations to clean up ugly code
// sequences at the MachineInstruction layer. It runs at the end of
// the SSA phases, following VSX swap removal. A pass of dead code
// elimination follows this one for quick clean-up of any dead
// instructions introduced here. Although we could do this as callbacks
// from the generic peephole pass, this would have a couple of bad
// effects: it might remove optimization opportunities for VSX swap
// removal, and it would miss cleanups made possible following VSX
// swap removal.
//
//===---------------------------------------------------------------------===//
#include "MCTargetDesc/PPCMCTargetDesc.h"
#include "MCTargetDesc/PPCPredicates.h"
#include "PPC.h"
#include "PPCInstrBuilder.h"
#include "PPCInstrInfo.h"
#include "PPCMachineFunctionInfo.h"
#include "PPCTargetMachine.h"
#include "llvm/ADT/Statistic.h"
#include "llvm/CodeGen/MachineBlockFrequencyInfo.h"
#include "llvm/CodeGen/MachineDominators.h"
#include "llvm/CodeGen/MachineFunctionPass.h"
#include "llvm/CodeGen/MachineInstrBuilder.h"
#include "llvm/CodeGen/MachinePostDominators.h"
#include "llvm/CodeGen/MachineRegisterInfo.h"
#include "llvm/InitializePasses.h"
#include "llvm/Support/Debug.h"
using namespace llvm;
#define DEBUG_TYPE "ppc-mi-peepholes"
STATISTIC(RemoveTOCSave, "Number of TOC saves removed");
STATISTIC(MultiTOCSaves,
"Number of functions with multiple TOC saves that must be kept");
STATISTIC(NumTOCSavesInPrologue, "Number of TOC saves placed in the prologue");
STATISTIC(NumEliminatedSExt, "Number of eliminated sign-extensions");
STATISTIC(NumEliminatedZExt, "Number of eliminated zero-extensions");
STATISTIC(NumOptADDLIs, "Number of optimized ADD instruction fed by LI");
STATISTIC(NumConvertedToImmediateForm,
"Number of instructions converted to their immediate form");
STATISTIC(NumFunctionsEnteredInMIPeephole,
"Number of functions entered in PPC MI Peepholes");
STATISTIC(NumFixedPointIterations,
"Number of fixed-point iterations converting reg-reg instructions "
"to reg-imm ones");
STATISTIC(NumRotatesCollapsed,
"Number of pairs of rotate left, clear left/right collapsed");
STATISTIC(NumEXTSWAndSLDICombined,
"Number of pairs of EXTSW and SLDI combined as EXTSWSLI");
STATISTIC(NumLoadImmZeroFoldedAndRemoved,
"Number of LI(8) reg, 0 that are folded to r0 and removed");
static cl::opt<bool>
FixedPointRegToImm("ppc-reg-to-imm-fixed-point", cl::Hidden, cl::init(true),
cl::desc("Iterate to a fixed point when attempting to "
"convert reg-reg instructions to reg-imm"));
static cl::opt<bool>
ConvertRegReg("ppc-convert-rr-to-ri", cl::Hidden, cl::init(true),
cl::desc("Convert eligible reg+reg instructions to reg+imm"));
static cl::opt<bool>
EnableSExtElimination("ppc-eliminate-signext",
cl::desc("enable elimination of sign-extensions"),
cl::init(false), cl::Hidden);
static cl::opt<bool>
EnableZExtElimination("ppc-eliminate-zeroext",
cl::desc("enable elimination of zero-extensions"),
cl::init(false), cl::Hidden);
static cl::opt<bool>
EnableTrapOptimization("ppc-opt-conditional-trap",
cl::desc("enable optimization of conditional traps"),
cl::init(false), cl::Hidden);
namespace {
struct PPCMIPeephole : public MachineFunctionPass {
static char ID;
const PPCInstrInfo *TII;
MachineFunction *MF;
MachineRegisterInfo *MRI;
PPCMIPeephole() : MachineFunctionPass(ID) {
initializePPCMIPeepholePass(*PassRegistry::getPassRegistry());
}
private:
MachineDominatorTree *MDT;
MachinePostDominatorTree *MPDT;
MachineBlockFrequencyInfo *MBFI;
uint64_t EntryFreq;
// Initialize class variables.
void initialize(MachineFunction &MFParm);
// Perform peepholes.
bool simplifyCode();
// Perform peepholes.
bool eliminateRedundantCompare();
bool eliminateRedundantTOCSaves(std::map<MachineInstr *, bool> &TOCSaves);
bool combineSEXTAndSHL(MachineInstr &MI, MachineInstr *&ToErase);
bool emitRLDICWhenLoweringJumpTables(MachineInstr &MI);
void UpdateTOCSaves(std::map<MachineInstr *, bool> &TOCSaves,
MachineInstr *MI);
public:
void getAnalysisUsage(AnalysisUsage &AU) const override {
AU.addRequired<MachineDominatorTree>();
AU.addRequired<MachinePostDominatorTree>();
AU.addRequired<MachineBlockFrequencyInfo>();
AU.addPreserved<MachineDominatorTree>();
AU.addPreserved<MachinePostDominatorTree>();
AU.addPreserved<MachineBlockFrequencyInfo>();
MachineFunctionPass::getAnalysisUsage(AU);
}
// Main entry point for this pass.
bool runOnMachineFunction(MachineFunction &MF) override {
initialize(MF);
// At this point, TOC pointer should not be used in a function that uses
// PC-Relative addressing.
assert((MF.getRegInfo().use_empty(PPC::X2) ||
!MF.getSubtarget<PPCSubtarget>().isUsingPCRelativeCalls()) &&
"TOC pointer used in a function using PC-Relative addressing!");
if (skipFunction(MF.getFunction()))
return false;
return simplifyCode();
}
};
// Initialize class variables.
void PPCMIPeephole::initialize(MachineFunction &MFParm) {
MF = &MFParm;
MRI = &MF->getRegInfo();
MDT = &getAnalysis<MachineDominatorTree>();
MPDT = &getAnalysis<MachinePostDominatorTree>();
MBFI = &getAnalysis<MachineBlockFrequencyInfo>();
EntryFreq = MBFI->getEntryFreq();
TII = MF->getSubtarget<PPCSubtarget>().getInstrInfo();
LLVM_DEBUG(dbgs() << "*** PowerPC MI peephole pass ***\n\n");
LLVM_DEBUG(MF->dump());
}
static MachineInstr *getVRegDefOrNull(MachineOperand *Op,
MachineRegisterInfo *MRI) {
assert(Op && "Invalid Operand!");
if (!Op->isReg())
return nullptr;
Register Reg = Op->getReg();
if (!Register::isVirtualRegister(Reg))
return nullptr;
return MRI->getVRegDef(Reg);
}
// This function returns number of known zero bits in output of MI
// starting from the most significant bit.
static unsigned
getKnownLeadingZeroCount(MachineInstr *MI, const PPCInstrInfo *TII) {
unsigned Opcode = MI->getOpcode();
if (Opcode == PPC::RLDICL || Opcode == PPC::RLDICL_rec ||
Opcode == PPC::RLDCL || Opcode == PPC::RLDCL_rec)
return MI->getOperand(3).getImm();
if ((Opcode == PPC::RLDIC || Opcode == PPC::RLDIC_rec) &&
MI->getOperand(3).getImm() <= 63 - MI->getOperand(2).getImm())
return MI->getOperand(3).getImm();
if ((Opcode == PPC::RLWINM || Opcode == PPC::RLWINM_rec ||
Opcode == PPC::RLWNM || Opcode == PPC::RLWNM_rec ||
Opcode == PPC::RLWINM8 || Opcode == PPC::RLWNM8) &&
MI->getOperand(3).getImm() <= MI->getOperand(4).getImm())
return 32 + MI->getOperand(3).getImm();
if (Opcode == PPC::ANDI_rec) {
uint16_t Imm = MI->getOperand(2).getImm();
return 48 + countLeadingZeros(Imm);
}
if (Opcode == PPC::CNTLZW || Opcode == PPC::CNTLZW_rec ||
Opcode == PPC::CNTTZW || Opcode == PPC::CNTTZW_rec ||
Opcode == PPC::CNTLZW8 || Opcode == PPC::CNTTZW8)
// The result ranges from 0 to 32.
return 58;
if (Opcode == PPC::CNTLZD || Opcode == PPC::CNTLZD_rec ||
Opcode == PPC::CNTTZD || Opcode == PPC::CNTTZD_rec)
// The result ranges from 0 to 64.
return 57;
if (Opcode == PPC::LHZ || Opcode == PPC::LHZX ||
Opcode == PPC::LHZ8 || Opcode == PPC::LHZX8 ||
Opcode == PPC::LHZU || Opcode == PPC::LHZUX ||
Opcode == PPC::LHZU8 || Opcode == PPC::LHZUX8)
return 48;
if (Opcode == PPC::LBZ || Opcode == PPC::LBZX ||
Opcode == PPC::LBZ8 || Opcode == PPC::LBZX8 ||
Opcode == PPC::LBZU || Opcode == PPC::LBZUX ||
Opcode == PPC::LBZU8 || Opcode == PPC::LBZUX8)
return 56;
if (TII->isZeroExtended(*MI))
return 32;
return 0;
}
// This function maintains a map for the pairs <TOC Save Instr, Keep>
// Each time a new TOC save is encountered, it checks if any of the existing
// ones are dominated by the new one. If so, it marks the existing one as
// redundant by setting it's entry in the map as false. It then adds the new
// instruction to the map with either true or false depending on if any
// existing instructions dominated the new one.
void PPCMIPeephole::UpdateTOCSaves(
std::map<MachineInstr *, bool> &TOCSaves, MachineInstr *MI) {
assert(TII->isTOCSaveMI(*MI) && "Expecting a TOC save instruction here");
// FIXME: Saving TOC in prologue hasn't been implemented well in AIX ABI part,
// here only support it under ELFv2.
if (MF->getSubtarget<PPCSubtarget>().isELFv2ABI()) {
PPCFunctionInfo *FI = MF->getInfo<PPCFunctionInfo>();
MachineBasicBlock *Entry = &MF->front();
uint64_t CurrBlockFreq = MBFI->getBlockFreq(MI->getParent()).getFrequency();
// If the block in which the TOC save resides is in a block that
// post-dominates Entry, or a block that is hotter than entry (keep in mind
// that early MachineLICM has already run so the TOC save won't be hoisted)
// we can just do the save in the prologue.
if (CurrBlockFreq > EntryFreq || MPDT->dominates(MI->getParent(), Entry))
FI->setMustSaveTOC(true);
// If we are saving the TOC in the prologue, all the TOC saves can be
// removed from the code.
if (FI->mustSaveTOC()) {
for (auto &TOCSave : TOCSaves)
TOCSave.second = false;
// Add new instruction to map.
TOCSaves[MI] = false;
return;
}
}
bool Keep = true;
for (auto &I : TOCSaves) {
MachineInstr *CurrInst = I.first;
// If new instruction dominates an existing one, mark existing one as
// redundant.
if (I.second && MDT->dominates(MI, CurrInst))
I.second = false;
// Check if the new instruction is redundant.
if (MDT->dominates(CurrInst, MI)) {
Keep = false;
break;
}
}
// Add new instruction to map.
TOCSaves[MI] = Keep;
}
// This function returns a list of all PHI nodes in the tree starting from
// the RootPHI node. We perform a BFS traversal to get an ordered list of nodes.
// The list initially only contains the root PHI. When we visit a PHI node, we
// add it to the list. We continue to look for other PHI node operands while
// there are nodes to visit in the list. The function returns false if the
// optimization cannot be applied on this tree.
static bool collectUnprimedAccPHIs(MachineRegisterInfo *MRI,
MachineInstr *RootPHI,
SmallVectorImpl<MachineInstr *> &PHIs) {
PHIs.push_back(RootPHI);
unsigned VisitedIndex = 0;
while (VisitedIndex < PHIs.size()) {
MachineInstr *VisitedPHI = PHIs[VisitedIndex];
for (unsigned PHIOp = 1, NumOps = VisitedPHI->getNumOperands();
PHIOp != NumOps; PHIOp += 2) {
Register RegOp = VisitedPHI->getOperand(PHIOp).getReg();
if (!Register::isVirtualRegister(RegOp))
return false;
MachineInstr *Instr = MRI->getVRegDef(RegOp);
// While collecting the PHI nodes, we check if they can be converted (i.e.
// all the operands are either copies, implicit defs or PHI nodes).
unsigned Opcode = Instr->getOpcode();
if (Opcode == PPC::COPY) {
Register Reg = Instr->getOperand(1).getReg();
if (!Register::isVirtualRegister(Reg) ||
MRI->getRegClass(Reg) != &PPC::ACCRCRegClass)
return false;
} else if (Opcode != PPC::IMPLICIT_DEF && Opcode != PPC::PHI)
return false;
// If we detect a cycle in the PHI nodes, we exit. It would be
// possible to change cycles as well, but that would add a lot
// of complexity for a case that is unlikely to occur with MMA
// code.
if (Opcode != PPC::PHI)
continue;
if (llvm::is_contained(PHIs, Instr))
return false;
PHIs.push_back(Instr);
}
VisitedIndex++;
}
return true;
}
// This function changes the unprimed accumulator PHI nodes in the PHIs list to
// primed accumulator PHI nodes. The list is traversed in reverse order to
// change all the PHI operands of a PHI node before changing the node itself.
// We keep a map to associate each changed PHI node to its non-changed form.
static void convertUnprimedAccPHIs(const PPCInstrInfo *TII,
MachineRegisterInfo *MRI,
SmallVectorImpl<MachineInstr *> &PHIs,
Register Dst) {
DenseMap<MachineInstr *, MachineInstr *> ChangedPHIMap;
for (MachineInstr *PHI : llvm::reverse(PHIs)) {
SmallVector<std::pair<MachineOperand, MachineOperand>, 4> PHIOps;
// We check if the current PHI node can be changed by looking at its
// operands. If all the operands are either copies from primed
// accumulators, implicit definitions or other unprimed accumulator
// PHI nodes, we change it.
for (unsigned PHIOp = 1, NumOps = PHI->getNumOperands(); PHIOp != NumOps;
PHIOp += 2) {
Register RegOp = PHI->getOperand(PHIOp).getReg();
MachineInstr *PHIInput = MRI->getVRegDef(RegOp);
unsigned Opcode = PHIInput->getOpcode();
assert((Opcode == PPC::COPY || Opcode == PPC::IMPLICIT_DEF ||
Opcode == PPC::PHI) &&
"Unexpected instruction");
if (Opcode == PPC::COPY) {
assert(MRI->getRegClass(PHIInput->getOperand(1).getReg()) ==
&PPC::ACCRCRegClass &&
"Unexpected register class");
PHIOps.push_back({PHIInput->getOperand(1), PHI->getOperand(PHIOp + 1)});
} else if (Opcode == PPC::IMPLICIT_DEF) {
Register AccReg = MRI->createVirtualRegister(&PPC::ACCRCRegClass);
BuildMI(*PHIInput->getParent(), PHIInput, PHIInput->getDebugLoc(),
TII->get(PPC::IMPLICIT_DEF), AccReg);
PHIOps.push_back({MachineOperand::CreateReg(AccReg, false),
PHI->getOperand(PHIOp + 1)});
} else if (Opcode == PPC::PHI) {
// We found a PHI operand. At this point we know this operand
// has already been changed so we get its associated changed form
// from the map.
assert(ChangedPHIMap.count(PHIInput) == 1 &&
"This PHI node should have already been changed.");
MachineInstr *PrimedAccPHI = ChangedPHIMap.lookup(PHIInput);
PHIOps.push_back({MachineOperand::CreateReg(
PrimedAccPHI->getOperand(0).getReg(), false),
PHI->getOperand(PHIOp + 1)});
}
}
Register AccReg = Dst;
// If the PHI node we are changing is the root node, the register it defines
// will be the destination register of the original copy (of the PHI def).
// For all other PHI's in the list, we need to create another primed
// accumulator virtual register as the PHI will no longer define the
// unprimed accumulator.
if (PHI != PHIs[0])
AccReg = MRI->createVirtualRegister(&PPC::ACCRCRegClass);
MachineInstrBuilder NewPHI = BuildMI(
*PHI->getParent(), PHI, PHI->getDebugLoc(), TII->get(PPC::PHI), AccReg);
for (auto RegMBB : PHIOps)
NewPHI.add(RegMBB.first).add(RegMBB.second);
ChangedPHIMap[PHI] = NewPHI.getInstr();
}
}
// Perform peephole optimizations.
bool PPCMIPeephole::simplifyCode() {
bool Simplified = false;
bool TrapOpt = false;
MachineInstr* ToErase = nullptr;
std::map<MachineInstr *, bool> TOCSaves;
const TargetRegisterInfo *TRI = &TII->getRegisterInfo();
NumFunctionsEnteredInMIPeephole++;
if (ConvertRegReg) {
// Fixed-point conversion of reg/reg instructions fed by load-immediate
// into reg/imm instructions. FIXME: This is expensive, control it with
// an option.
bool SomethingChanged = false;
do {
NumFixedPointIterations++;
SomethingChanged = false;
for (MachineBasicBlock &MBB : *MF) {
for (MachineInstr &MI : MBB) {
if (MI.isDebugInstr())
continue;
if (TII->convertToImmediateForm(MI)) {
// We don't erase anything in case the def has other uses. Let DCE
// remove it if it can be removed.
LLVM_DEBUG(dbgs() << "Converted instruction to imm form: ");
LLVM_DEBUG(MI.dump());
NumConvertedToImmediateForm++;
SomethingChanged = true;
Simplified = true;
continue;
}
}
}
} while (SomethingChanged && FixedPointRegToImm);
}
for (MachineBasicBlock &MBB : *MF) {
for (MachineInstr &MI : MBB) {
// If the previous instruction was marked for elimination,
// remove it now.
if (ToErase) {
ToErase->eraseFromParent();
ToErase = nullptr;
}
// If a conditional trap instruction got optimized to an
// unconditional trap, eliminate all the instructions after
// the trap.
if (EnableTrapOptimization && TrapOpt) {
ToErase = &MI;
continue;
}
// Ignore debug instructions.
if (MI.isDebugInstr())
continue;
// Per-opcode peepholes.
switch (MI.getOpcode()) {
default:
break;
case PPC::COPY: {
Register Src = MI.getOperand(1).getReg();
Register Dst = MI.getOperand(0).getReg();
if (!Register::isVirtualRegister(Src) ||
!Register::isVirtualRegister(Dst))
break;
if (MRI->getRegClass(Src) != &PPC::UACCRCRegClass ||
MRI->getRegClass(Dst) != &PPC::ACCRCRegClass)
break;
// We are copying an unprimed accumulator to a primed accumulator.
// If the input to the copy is a PHI that is fed only by (i) copies in
// the other direction (ii) implicitly defined unprimed accumulators or
// (iii) other PHI nodes satisfying (i) and (ii), we can change
// the PHI to a PHI on primed accumulators (as long as we also change
// its operands). To detect and change such copies, we first get a list
// of all the PHI nodes starting from the root PHI node in BFS order.
// We then visit all these PHI nodes to check if they can be changed to
// primed accumulator PHI nodes and if so, we change them.
MachineInstr *RootPHI = MRI->getVRegDef(Src);
if (RootPHI->getOpcode() != PPC::PHI)
break;
SmallVector<MachineInstr *, 4> PHIs;
if (!collectUnprimedAccPHIs(MRI, RootPHI, PHIs))
break;
convertUnprimedAccPHIs(TII, MRI, PHIs, Dst);
ToErase = &MI;
break;
}
case PPC::LI:
case PPC::LI8: {
// If we are materializing a zero, look for any use operands for which
// zero means immediate zero. All such operands can be replaced with
// PPC::ZERO.
if (!MI.getOperand(1).isImm() || MI.getOperand(1).getImm() != 0)
break;
Register MIDestReg = MI.getOperand(0).getReg();
for (MachineInstr& UseMI : MRI->use_instructions(MIDestReg))
Simplified |= TII->onlyFoldImmediate(UseMI, MI, MIDestReg);
if (MRI->use_nodbg_empty(MIDestReg)) {
++NumLoadImmZeroFoldedAndRemoved;
ToErase = &MI;
}
break;
}
case PPC::STW:
case PPC::STD: {
MachineFrameInfo &MFI = MF->getFrameInfo();
if (MFI.hasVarSizedObjects() ||
(!MF->getSubtarget<PPCSubtarget>().isELFv2ABI() &&
!MF->getSubtarget<PPCSubtarget>().isAIXABI()))
break;
// When encountering a TOC save instruction, call UpdateTOCSaves
// to add it to the TOCSaves map and mark any existing TOC saves
// it dominates as redundant.
if (TII->isTOCSaveMI(MI))
UpdateTOCSaves(TOCSaves, &MI);
break;
}
case PPC::XXPERMDI: {
// Perform simplifications of 2x64 vector swaps and splats.
// A swap is identified by an immediate value of 2, and a splat
// is identified by an immediate value of 0 or 3.
int Immed = MI.getOperand(3).getImm();
if (Immed == 1)
break;
// For each of these simplifications, we need the two source
// regs to match. Unfortunately, MachineCSE ignores COPY and
// SUBREG_TO_REG, so for example we can see
// XXPERMDI t, SUBREG_TO_REG(s), SUBREG_TO_REG(s), immed.
// We have to look through chains of COPY and SUBREG_TO_REG
// to find the real source values for comparison.
Register TrueReg1 =
TRI->lookThruCopyLike(MI.getOperand(1).getReg(), MRI);
Register TrueReg2 =
TRI->lookThruCopyLike(MI.getOperand(2).getReg(), MRI);
if (!(TrueReg1 == TrueReg2 && Register::isVirtualRegister(TrueReg1)))
break;
MachineInstr *DefMI = MRI->getVRegDef(TrueReg1);
if (!DefMI)
break;
unsigned DefOpc = DefMI->getOpcode();
// If this is a splat fed by a splatting load, the splat is
// redundant. Replace with a copy. This doesn't happen directly due
// to code in PPCDAGToDAGISel.cpp, but it can happen when converting
// a load of a double to a vector of 64-bit integers.
auto isConversionOfLoadAndSplat = [=]() -> bool {
if (DefOpc != PPC::XVCVDPSXDS && DefOpc != PPC::XVCVDPUXDS)
return false;
Register FeedReg1 =
TRI->lookThruCopyLike(DefMI->getOperand(1).getReg(), MRI);
if (Register::isVirtualRegister(FeedReg1)) {
MachineInstr *LoadMI = MRI->getVRegDef(FeedReg1);
if (LoadMI && LoadMI->getOpcode() == PPC::LXVDSX)
return true;
}
return false;
};
if ((Immed == 0 || Immed == 3) &&
(DefOpc == PPC::LXVDSX || isConversionOfLoadAndSplat())) {
LLVM_DEBUG(dbgs() << "Optimizing load-and-splat/splat "
"to load-and-splat/copy: ");
LLVM_DEBUG(MI.dump());
BuildMI(MBB, &MI, MI.getDebugLoc(), TII->get(PPC::COPY),
MI.getOperand(0).getReg())
.add(MI.getOperand(1));
ToErase = &MI;
Simplified = true;
}
// If this is a splat or a swap fed by another splat, we
// can replace it with a copy.
if (DefOpc == PPC::XXPERMDI) {
Register DefReg1 = DefMI->getOperand(1).getReg();
Register DefReg2 = DefMI->getOperand(2).getReg();
unsigned DefImmed = DefMI->getOperand(3).getImm();
// If the two inputs are not the same register, check to see if
// they originate from the same virtual register after only
// copy-like instructions.
if (DefReg1 != DefReg2) {
Register FeedReg1 = TRI->lookThruCopyLike(DefReg1, MRI);
Register FeedReg2 = TRI->lookThruCopyLike(DefReg2, MRI);
if (!(FeedReg1 == FeedReg2 &&
Register::isVirtualRegister(FeedReg1)))
break;
}
if (DefImmed == 0 || DefImmed == 3) {
LLVM_DEBUG(dbgs() << "Optimizing splat/swap or splat/splat "
"to splat/copy: ");
LLVM_DEBUG(MI.dump());
BuildMI(MBB, &MI, MI.getDebugLoc(), TII->get(PPC::COPY),
MI.getOperand(0).getReg())
.add(MI.getOperand(1));
ToErase = &MI;
Simplified = true;
}
// If this is a splat fed by a swap, we can simplify modify
// the splat to splat the other value from the swap's input
// parameter.
else if ((Immed == 0 || Immed == 3) && DefImmed == 2) {
LLVM_DEBUG(dbgs() << "Optimizing swap/splat => splat: ");
LLVM_DEBUG(MI.dump());
MI.getOperand(1).setReg(DefReg1);
MI.getOperand(2).setReg(DefReg2);
MI.getOperand(3).setImm(3 - Immed);
Simplified = true;
}
// If this is a swap fed by a swap, we can replace it
// with a copy from the first swap's input.
else if (Immed == 2 && DefImmed == 2) {
LLVM_DEBUG(dbgs() << "Optimizing swap/swap => copy: ");
LLVM_DEBUG(MI.dump());
BuildMI(MBB, &MI, MI.getDebugLoc(), TII->get(PPC::COPY),
MI.getOperand(0).getReg())
.add(DefMI->getOperand(1));
ToErase = &MI;
Simplified = true;
}
} else if ((Immed == 0 || Immed == 3 || Immed == 2) &&
DefOpc == PPC::XXPERMDIs &&
(DefMI->getOperand(2).getImm() == 0 ||
DefMI->getOperand(2).getImm() == 3)) {
ToErase = &MI;
Simplified = true;
// Swap of a splat, convert to copy.
if (Immed == 2) {
LLVM_DEBUG(dbgs() << "Optimizing swap(splat) => copy(splat): ");
LLVM_DEBUG(MI.dump());
BuildMI(MBB, &MI, MI.getDebugLoc(), TII->get(PPC::COPY),
MI.getOperand(0).getReg())
.add(MI.getOperand(1));
break;
}
// Splat fed by another splat - switch the output of the first
// and remove the second.
DefMI->getOperand(0).setReg(MI.getOperand(0).getReg());
LLVM_DEBUG(dbgs() << "Removing redundant splat: ");
LLVM_DEBUG(MI.dump());
}
break;
}
case PPC::VSPLTB:
case PPC::VSPLTH:
case PPC::XXSPLTW: {
unsigned MyOpcode = MI.getOpcode();
unsigned OpNo = MyOpcode == PPC::XXSPLTW ? 1 : 2;
Register TrueReg =
TRI->lookThruCopyLike(MI.getOperand(OpNo).getReg(), MRI);
if (!Register::isVirtualRegister(TrueReg))
break;
MachineInstr *DefMI = MRI->getVRegDef(TrueReg);
if (!DefMI)
break;
unsigned DefOpcode = DefMI->getOpcode();
auto isConvertOfSplat = [=]() -> bool {
if (DefOpcode != PPC::XVCVSPSXWS && DefOpcode != PPC::XVCVSPUXWS)
return false;
Register ConvReg = DefMI->getOperand(1).getReg();
if (!Register::isVirtualRegister(ConvReg))
return false;
MachineInstr *Splt = MRI->getVRegDef(ConvReg);
return Splt && (Splt->getOpcode() == PPC::LXVWSX ||
Splt->getOpcode() == PPC::XXSPLTW);
};
bool AlreadySplat = (MyOpcode == DefOpcode) ||
(MyOpcode == PPC::VSPLTB && DefOpcode == PPC::VSPLTBs) ||
(MyOpcode == PPC::VSPLTH && DefOpcode == PPC::VSPLTHs) ||
(MyOpcode == PPC::XXSPLTW && DefOpcode == PPC::XXSPLTWs) ||
(MyOpcode == PPC::XXSPLTW && DefOpcode == PPC::LXVWSX) ||
(MyOpcode == PPC::XXSPLTW && DefOpcode == PPC::MTVSRWS)||
(MyOpcode == PPC::XXSPLTW && isConvertOfSplat());
// If the instruction[s] that feed this splat have already splat
// the value, this splat is redundant.
if (AlreadySplat) {
LLVM_DEBUG(dbgs() << "Changing redundant splat to a copy: ");
LLVM_DEBUG(MI.dump());
BuildMI(MBB, &MI, MI.getDebugLoc(), TII->get(PPC::COPY),
MI.getOperand(0).getReg())
.add(MI.getOperand(OpNo));
ToErase = &MI;
Simplified = true;
}
// Splat fed by a shift. Usually when we align value to splat into
// vector element zero.
if (DefOpcode == PPC::XXSLDWI) {
Register ShiftRes = DefMI->getOperand(0).getReg();
Register ShiftOp1 = DefMI->getOperand(1).getReg();
Register ShiftOp2 = DefMI->getOperand(2).getReg();
unsigned ShiftImm = DefMI->getOperand(3).getImm();
unsigned SplatImm =
MI.getOperand(MyOpcode == PPC::XXSPLTW ? 2 : 1).getImm();
if (ShiftOp1 == ShiftOp2) {
unsigned NewElem = (SplatImm + ShiftImm) & 0x3;
if (MRI->hasOneNonDBGUse(ShiftRes)) {
LLVM_DEBUG(dbgs() << "Removing redundant shift: ");
LLVM_DEBUG(DefMI->dump());
ToErase = DefMI;
}
Simplified = true;
LLVM_DEBUG(dbgs() << "Changing splat immediate from " << SplatImm
<< " to " << NewElem << " in instruction: ");
LLVM_DEBUG(MI.dump());
MI.getOperand(1).setReg(ShiftOp1);
MI.getOperand(2).setImm(NewElem);
}
}
break;
}
case PPC::XVCVDPSP: {
// If this is a DP->SP conversion fed by an FRSP, the FRSP is redundant.
Register TrueReg =
TRI->lookThruCopyLike(MI.getOperand(1).getReg(), MRI);
if (!Register::isVirtualRegister(TrueReg))
break;
MachineInstr *DefMI = MRI->getVRegDef(TrueReg);
// This can occur when building a vector of single precision or integer
// values.
if (DefMI && DefMI->getOpcode() == PPC::XXPERMDI) {
Register DefsReg1 =
TRI->lookThruCopyLike(DefMI->getOperand(1).getReg(), MRI);
Register DefsReg2 =
TRI->lookThruCopyLike(DefMI->getOperand(2).getReg(), MRI);
if (!Register::isVirtualRegister(DefsReg1) ||
!Register::isVirtualRegister(DefsReg2))
break;
MachineInstr *P1 = MRI->getVRegDef(DefsReg1);
MachineInstr *P2 = MRI->getVRegDef(DefsReg2);
if (!P1 || !P2)
break;
// Remove the passed FRSP/XSRSP instruction if it only feeds this MI
// and set any uses of that FRSP/XSRSP (in this MI) to the source of
// the FRSP/XSRSP.
auto removeFRSPIfPossible = [&](MachineInstr *RoundInstr) {
unsigned Opc = RoundInstr->getOpcode();
if ((Opc == PPC::FRSP || Opc == PPC::XSRSP) &&
MRI->hasOneNonDBGUse(RoundInstr->getOperand(0).getReg())) {
Simplified = true;
Register ConvReg1 = RoundInstr->getOperand(1).getReg();
Register FRSPDefines = RoundInstr->getOperand(0).getReg();
MachineInstr &Use = *(MRI->use_instr_nodbg_begin(FRSPDefines));
for (int i = 0, e = Use.getNumOperands(); i < e; ++i)
if (Use.getOperand(i).isReg() &&
Use.getOperand(i).getReg() == FRSPDefines)
Use.getOperand(i).setReg(ConvReg1);
LLVM_DEBUG(dbgs() << "Removing redundant FRSP/XSRSP:\n");
LLVM_DEBUG(RoundInstr->dump());
LLVM_DEBUG(dbgs() << "As it feeds instruction:\n");
LLVM_DEBUG(MI.dump());
LLVM_DEBUG(dbgs() << "Through instruction:\n");
LLVM_DEBUG(DefMI->dump());
RoundInstr->eraseFromParent();
}
};
// If the input to XVCVDPSP is a vector that was built (even
// partially) out of FRSP's, the FRSP(s) can safely be removed
// since this instruction performs the same operation.
if (P1 != P2) {
removeFRSPIfPossible(P1);
removeFRSPIfPossible(P2);
break;
}
removeFRSPIfPossible(P1);
}
break;
}
case PPC::EXTSH:
case PPC::EXTSH8:
case PPC::EXTSH8_32_64: {
if (!EnableSExtElimination) break;
Register NarrowReg = MI.getOperand(1).getReg();
if (!Register::isVirtualRegister(NarrowReg))
break;
MachineInstr *SrcMI = MRI->getVRegDef(NarrowReg);
// If we've used a zero-extending load that we will sign-extend,
// just do a sign-extending load.
if (SrcMI->getOpcode() == PPC::LHZ ||
SrcMI->getOpcode() == PPC::LHZX) {
if (!MRI->hasOneNonDBGUse(SrcMI->getOperand(0).getReg()))
break;
auto is64Bit = [] (unsigned Opcode) {
return Opcode == PPC::EXTSH8;
};
auto isXForm = [] (unsigned Opcode) {
return Opcode == PPC::LHZX;
};
auto getSextLoadOp = [] (bool is64Bit, bool isXForm) {
if (is64Bit)
if (isXForm) return PPC::LHAX8;
else return PPC::LHA8;
else
if (isXForm) return PPC::LHAX;
else return PPC::LHA;
};
unsigned Opc = getSextLoadOp(is64Bit(MI.getOpcode()),
isXForm(SrcMI->getOpcode()));
LLVM_DEBUG(dbgs() << "Zero-extending load\n");
LLVM_DEBUG(SrcMI->dump());
LLVM_DEBUG(dbgs() << "and sign-extension\n");
LLVM_DEBUG(MI.dump());
LLVM_DEBUG(dbgs() << "are merged into sign-extending load\n");
SrcMI->setDesc(TII->get(Opc));
SrcMI->getOperand(0).setReg(MI.getOperand(0).getReg());
ToErase = &MI;
Simplified = true;
NumEliminatedSExt++;
}
break;
}
case PPC::EXTSW:
case PPC::EXTSW_32:
case PPC::EXTSW_32_64: {
if (!EnableSExtElimination) break;
Register NarrowReg = MI.getOperand(1).getReg();
if (!Register::isVirtualRegister(NarrowReg))
break;
MachineInstr *SrcMI = MRI->getVRegDef(NarrowReg);
// If we've used a zero-extending load that we will sign-extend,
// just do a sign-extending load.
if (SrcMI->getOpcode() == PPC::LWZ ||
SrcMI->getOpcode() == PPC::LWZX) {
if (!MRI->hasOneNonDBGUse(SrcMI->getOperand(0).getReg()))
break;
auto is64Bit = [] (unsigned Opcode) {
return Opcode == PPC::EXTSW || Opcode == PPC::EXTSW_32_64;
};
auto isXForm = [] (unsigned Opcode) {
return Opcode == PPC::LWZX;
};
auto getSextLoadOp = [] (bool is64Bit, bool isXForm) {
if (is64Bit)
if (isXForm) return PPC::LWAX;
else return PPC::LWA;
else
if (isXForm) return PPC::LWAX_32;
else return PPC::LWA_32;
};
unsigned Opc = getSextLoadOp(is64Bit(MI.getOpcode()),
isXForm(SrcMI->getOpcode()));
LLVM_DEBUG(dbgs() << "Zero-extending load\n");
LLVM_DEBUG(SrcMI->dump());
LLVM_DEBUG(dbgs() << "and sign-extension\n");
LLVM_DEBUG(MI.dump());
LLVM_DEBUG(dbgs() << "are merged into sign-extending load\n");
SrcMI->setDesc(TII->get(Opc));
SrcMI->getOperand(0).setReg(MI.getOperand(0).getReg());
ToErase = &MI;
Simplified = true;
NumEliminatedSExt++;
} else if (MI.getOpcode() == PPC::EXTSW_32_64 &&
TII->isSignExtended(*SrcMI)) {
// We can eliminate EXTSW if the input is known to be already
// sign-extended.
LLVM_DEBUG(dbgs() << "Removing redundant sign-extension\n");
Register TmpReg =
MF->getRegInfo().createVirtualRegister(&PPC::G8RCRegClass);
BuildMI(MBB, &MI, MI.getDebugLoc(), TII->get(PPC::IMPLICIT_DEF),
TmpReg);
BuildMI(MBB, &MI, MI.getDebugLoc(), TII->get(PPC::INSERT_SUBREG),
MI.getOperand(0).getReg())
.addReg(TmpReg)
.addReg(NarrowReg)
.addImm(PPC::sub_32);
ToErase = &MI;
Simplified = true;
NumEliminatedSExt++;
}
break;
}
case PPC::RLDICL: {
// We can eliminate RLDICL (e.g. for zero-extension)
// if all bits to clear are already zero in the input.
// This code assume following code sequence for zero-extension.
// %6 = COPY %5:sub_32; (optional)
// %8 = IMPLICIT_DEF;
// %7<def,tied1> = INSERT_SUBREG %8<tied0>, %6, sub_32;
if (!EnableZExtElimination) break;
if (MI.getOperand(2).getImm() != 0)
break;
Register SrcReg = MI.getOperand(1).getReg();
if (!Register::isVirtualRegister(SrcReg))
break;
MachineInstr *SrcMI = MRI->getVRegDef(SrcReg);
if (!(SrcMI && SrcMI->getOpcode() == PPC::INSERT_SUBREG &&
SrcMI->getOperand(0).isReg() && SrcMI->getOperand(1).isReg()))
break;
MachineInstr *ImpDefMI, *SubRegMI;
ImpDefMI = MRI->getVRegDef(SrcMI->getOperand(1).getReg());
SubRegMI = MRI->getVRegDef(SrcMI->getOperand(2).getReg());
if (ImpDefMI->getOpcode() != PPC::IMPLICIT_DEF) break;
SrcMI = SubRegMI;
if (SubRegMI->getOpcode() == PPC::COPY) {
Register CopyReg = SubRegMI->getOperand(1).getReg();
if (Register::isVirtualRegister(CopyReg))
SrcMI = MRI->getVRegDef(CopyReg);
}
unsigned KnownZeroCount = getKnownLeadingZeroCount(SrcMI, TII);
if (MI.getOperand(3).getImm() <= KnownZeroCount) {
LLVM_DEBUG(dbgs() << "Removing redundant zero-extension\n");
BuildMI(MBB, &MI, MI.getDebugLoc(), TII->get(PPC::COPY),
MI.getOperand(0).getReg())
.addReg(SrcReg);
ToErase = &MI;
Simplified = true;
NumEliminatedZExt++;
}
break;
}
// TODO: Any instruction that has an immediate form fed only by a PHI
// whose operands are all load immediate can be folded away. We currently
// do this for ADD instructions, but should expand it to arithmetic and
// binary instructions with immediate forms in the future.
case PPC::ADD4:
case PPC::ADD8: {
auto isSingleUsePHI = [&](MachineOperand *PhiOp) {
assert(PhiOp && "Invalid Operand!");
MachineInstr *DefPhiMI = getVRegDefOrNull(PhiOp, MRI);
return DefPhiMI && (DefPhiMI->getOpcode() == PPC::PHI) &&
MRI->hasOneNonDBGUse(DefPhiMI->getOperand(0).getReg());
};
auto dominatesAllSingleUseLIs = [&](MachineOperand *DominatorOp,
MachineOperand *PhiOp) {
assert(PhiOp && "Invalid Operand!");
assert(DominatorOp && "Invalid Operand!");
MachineInstr *DefPhiMI = getVRegDefOrNull(PhiOp, MRI);
MachineInstr *DefDomMI = getVRegDefOrNull(DominatorOp, MRI);
// Note: the vregs only show up at odd indices position of PHI Node,
// the even indices position save the BB info.
for (unsigned i = 1; i < DefPhiMI->getNumOperands(); i += 2) {
MachineInstr *LiMI =
getVRegDefOrNull(&DefPhiMI->getOperand(i), MRI);
if (!LiMI ||
(LiMI->getOpcode() != PPC::LI && LiMI->getOpcode() != PPC::LI8)
|| !MRI->hasOneNonDBGUse(LiMI->getOperand(0).getReg()) ||
!MDT->dominates(DefDomMI, LiMI))
return false;
}
return true;
};
MachineOperand Op1 = MI.getOperand(1);
MachineOperand Op2 = MI.getOperand(2);
if (isSingleUsePHI(&Op2) && dominatesAllSingleUseLIs(&Op1, &Op2))
std::swap(Op1, Op2);
else if (!isSingleUsePHI(&Op1) || !dominatesAllSingleUseLIs(&Op2, &Op1))
break; // We don't have an ADD fed by LI's that can be transformed
// Now we know that Op1 is the PHI node and Op2 is the dominator
Register DominatorReg = Op2.getReg();
const TargetRegisterClass *TRC = MI.getOpcode() == PPC::ADD8
? &PPC::G8RC_and_G8RC_NOX0RegClass
: &PPC::GPRC_and_GPRC_NOR0RegClass;
MRI->setRegClass(DominatorReg, TRC);
// replace LIs with ADDIs
MachineInstr *DefPhiMI = getVRegDefOrNull(&Op1, MRI);
for (unsigned i = 1; i < DefPhiMI->getNumOperands(); i += 2) {
MachineInstr *LiMI = getVRegDefOrNull(&DefPhiMI->getOperand(i), MRI);
LLVM_DEBUG(dbgs() << "Optimizing LI to ADDI: ");
LLVM_DEBUG(LiMI->dump());
// There could be repeated registers in the PHI, e.g: %1 =
// PHI %6, <%bb.2>, %8, <%bb.3>, %8, <%bb.6>; So if we've
// already replaced the def instruction, skip.
if (LiMI->getOpcode() == PPC::ADDI || LiMI->getOpcode() == PPC::ADDI8)
continue;
assert((LiMI->getOpcode() == PPC::LI ||
LiMI->getOpcode() == PPC::LI8) &&
"Invalid Opcode!");
auto LiImm = LiMI->getOperand(1).getImm(); // save the imm of LI
LiMI->RemoveOperand(1); // remove the imm of LI
LiMI->setDesc(TII->get(LiMI->getOpcode() == PPC::LI ? PPC::ADDI
: PPC::ADDI8));
MachineInstrBuilder(*LiMI->getParent()->getParent(), *LiMI)
.addReg(DominatorReg)
.addImm(LiImm); // restore the imm of LI
LLVM_DEBUG(LiMI->dump());
}
// Replace ADD with COPY
LLVM_DEBUG(dbgs() << "Optimizing ADD to COPY: ");
LLVM_DEBUG(MI.dump());
BuildMI(MBB, &MI, MI.getDebugLoc(), TII->get(PPC::COPY),