5daa4d77671d17fba216e161b3050c72686d1071
[oota-llvm.git] / lib / Target / SystemZ / SystemZElimCompare.cpp
1 //===-- SystemZElimCompare.cpp - Eliminate comparison instructions --------===//
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:
11 // (1) tries to remove compares if CC already contains the required information
12 // (2) fuses compares and branches into COMPARE AND BRANCH instructions
13 //
14 //===----------------------------------------------------------------------===//
15
16 #include "SystemZTargetMachine.h"
17 #include "llvm/ADT/Statistic.h"
18 #include "llvm/CodeGen/MachineFunctionPass.h"
19 #include "llvm/CodeGen/MachineInstrBuilder.h"
20 #include "llvm/IR/Function.h"
21 #include "llvm/Support/CommandLine.h"
22 #include "llvm/Support/MathExtras.h"
23 #include "llvm/Target/TargetInstrInfo.h"
24 #include "llvm/Target/TargetMachine.h"
25 #include "llvm/Target/TargetRegisterInfo.h"
26
27 using namespace llvm;
28
29 #define DEBUG_TYPE "systemz-elim-compare"
30
31 STATISTIC(BranchOnCounts, "Number of branch-on-count instructions");
32 STATISTIC(EliminatedComparisons, "Number of eliminated comparisons");
33 STATISTIC(FusedComparisons, "Number of fused compare-and-branch instructions");
34
35 namespace {
36 // Represents the references to a particular register in one or more
37 // instructions.
38 struct Reference {
39   Reference()
40     : Def(false), Use(false) {}
41
42   Reference &operator|=(const Reference &Other) {
43     Def |= Other.Def;
44     Use |= Other.Use;
45     return *this;
46   }
47
48   explicit operator bool() const { return Def || Use; }
49
50   // True if the register is defined or used in some form, either directly or
51   // via a sub- or super-register.
52   bool Def;
53   bool Use;
54 };
55
56 class SystemZElimCompare : public MachineFunctionPass {
57 public:
58   static char ID;
59   SystemZElimCompare(const SystemZTargetMachine &tm)
60     : MachineFunctionPass(ID), TII(nullptr), TRI(nullptr) {}
61
62   const char *getPassName() const override {
63     return "SystemZ Comparison Elimination";
64   }
65
66   bool processBlock(MachineBasicBlock &MBB);
67   bool runOnMachineFunction(MachineFunction &F) override;
68
69 private:
70   Reference getRegReferences(MachineInstr *MI, unsigned Reg);
71   bool convertToBRCT(MachineInstr *MI, MachineInstr *Compare,
72                      SmallVectorImpl<MachineInstr *> &CCUsers);
73   bool convertToLoadAndTest(MachineInstr *MI);
74   bool adjustCCMasksForInstr(MachineInstr *MI, MachineInstr *Compare,
75                              SmallVectorImpl<MachineInstr *> &CCUsers);
76   bool optimizeCompareZero(MachineInstr *Compare,
77                            SmallVectorImpl<MachineInstr *> &CCUsers);
78   bool fuseCompareAndBranch(MachineInstr *Compare,
79                             SmallVectorImpl<MachineInstr *> &CCUsers);
80
81   const SystemZInstrInfo *TII;
82   const TargetRegisterInfo *TRI;
83 };
84
85 char SystemZElimCompare::ID = 0;
86 } // end anonymous namespace
87
88 FunctionPass *llvm::createSystemZElimComparePass(SystemZTargetMachine &TM) {
89   return new SystemZElimCompare(TM);
90 }
91
92 // Return true if CC is live out of MBB.
93 static bool isCCLiveOut(MachineBasicBlock &MBB) {
94   for (auto SI = MBB.succ_begin(), SE = MBB.succ_end(); SI != SE; ++SI)
95     if ((*SI)->isLiveIn(SystemZ::CC))
96       return true;
97   return false;
98 }
99
100 // Return true if any CC result of MI would reflect the value of Reg.
101 static bool resultTests(MachineInstr *MI, unsigned Reg) {
102   if (MI->getNumOperands() > 0 &&
103       MI->getOperand(0).isReg() &&
104       MI->getOperand(0).isDef() &&
105       MI->getOperand(0).getReg() == Reg)
106     return true;
107
108   switch (MI->getOpcode()) {
109   case SystemZ::LR:
110   case SystemZ::LGR:
111   case SystemZ::LGFR:
112   case SystemZ::LTR:
113   case SystemZ::LTGR:
114   case SystemZ::LTGFR:
115   case SystemZ::LER:
116   case SystemZ::LDR:
117   case SystemZ::LXR:
118   case SystemZ::LTEBR:
119   case SystemZ::LTDBR:
120   case SystemZ::LTXBR:
121     if (MI->getOperand(1).getReg() == Reg)
122       return true;
123   }
124
125   return false;
126 }
127
128 // Describe the references to Reg or any of its aliases in MI.
129 Reference SystemZElimCompare::getRegReferences(MachineInstr *MI, unsigned Reg) {
130   Reference Ref;
131   for (unsigned I = 0, E = MI->getNumOperands(); I != E; ++I) {
132     const MachineOperand &MO = MI->getOperand(I);
133     if (MO.isReg()) {
134       if (unsigned MOReg = MO.getReg()) {
135         if (TRI->regsOverlap(MOReg, Reg)) {
136           if (MO.isUse())
137             Ref.Use = true;
138           else if (MO.isDef())
139             Ref.Def = true;
140         }
141       }
142     }
143   }
144   return Ref;
145 }
146
147 // Return true if this is a load and test which can be optimized the
148 // same way as compare instruction.
149 static bool isLoadAndTestAsCmp(MachineInstr *MI) {
150   // If we during isel used a load-and-test as a compare with 0, the
151   // def operand is dead.
152   return ((MI->getOpcode() == SystemZ::LTEBR ||
153            MI->getOpcode() == SystemZ::LTDBR ||
154            MI->getOpcode() == SystemZ::LTXBR) &&
155           MI->getOperand(0).isDead());
156 }
157
158 // Return the source register of Compare, which is the unknown value
159 // being tested.
160 static unsigned getCompareSourceReg(MachineInstr *Compare) {
161   unsigned reg = 0;
162   if (Compare->isCompare())
163     reg = Compare->getOperand(0).getReg();
164   else if (isLoadAndTestAsCmp(Compare))
165     reg = Compare->getOperand(1).getReg();
166   assert (reg);
167
168   return reg;
169 }
170
171 // Compare compares the result of MI against zero.  If MI is an addition
172 // of -1 and if CCUsers is a single branch on nonzero, eliminate the addition
173 // and convert the branch to a BRCT(G).  Return true on success.
174 bool
175 SystemZElimCompare::convertToBRCT(MachineInstr *MI, MachineInstr *Compare,
176                                   SmallVectorImpl<MachineInstr *> &CCUsers) {
177   // Check whether we have an addition of -1.
178   unsigned Opcode = MI->getOpcode();
179   unsigned BRCT;
180   if (Opcode == SystemZ::AHI)
181     BRCT = SystemZ::BRCT;
182   else if (Opcode == SystemZ::AGHI)
183     BRCT = SystemZ::BRCTG;
184   else
185     return false;
186   if (MI->getOperand(2).getImm() != -1)
187     return false;
188
189   // Check whether we have a single JLH.
190   if (CCUsers.size() != 1)
191     return false;
192   MachineInstr *Branch = CCUsers[0];
193   if (Branch->getOpcode() != SystemZ::BRC ||
194       Branch->getOperand(0).getImm() != SystemZ::CCMASK_ICMP ||
195       Branch->getOperand(1).getImm() != SystemZ::CCMASK_CMP_NE)
196     return false;
197
198   // We already know that there are no references to the register between
199   // MI and Compare.  Make sure that there are also no references between
200   // Compare and Branch.
201   unsigned SrcReg = getCompareSourceReg(Compare);
202   MachineBasicBlock::iterator MBBI = Compare, MBBE = Branch;
203   for (++MBBI; MBBI != MBBE; ++MBBI)
204     if (getRegReferences(MBBI, SrcReg))
205       return false;
206
207   // The transformation is OK.  Rebuild Branch as a BRCT(G).
208   MachineOperand Target(Branch->getOperand(2));
209   Branch->RemoveOperand(2);
210   Branch->RemoveOperand(1);
211   Branch->RemoveOperand(0);
212   Branch->setDesc(TII->get(BRCT));
213   MachineInstrBuilder(*Branch->getParent()->getParent(), Branch)
214     .addOperand(MI->getOperand(0))
215     .addOperand(MI->getOperand(1))
216     .addOperand(Target)
217     .addReg(SystemZ::CC, RegState::ImplicitDefine);
218   MI->eraseFromParent();
219   return true;
220 }
221
222 // If MI is a load instruction, try to convert it into a LOAD AND TEST.
223 // Return true on success.
224 bool SystemZElimCompare::convertToLoadAndTest(MachineInstr *MI) {
225   unsigned Opcode = TII->getLoadAndTest(MI->getOpcode());
226   if (!Opcode)
227     return false;
228
229   MI->setDesc(TII->get(Opcode));
230   MachineInstrBuilder(*MI->getParent()->getParent(), MI)
231     .addReg(SystemZ::CC, RegState::ImplicitDefine);
232   return true;
233 }
234
235 // The CC users in CCUsers are testing the result of a comparison of some
236 // value X against zero and we know that any CC value produced by MI
237 // would also reflect the value of X.  Try to adjust CCUsers so that
238 // they test the result of MI directly, returning true on success.
239 // Leave everything unchanged on failure.
240 bool SystemZElimCompare::
241 adjustCCMasksForInstr(MachineInstr *MI, MachineInstr *Compare,
242                       SmallVectorImpl<MachineInstr *> &CCUsers) {
243   int Opcode = MI->getOpcode();
244   const MCInstrDesc &Desc = TII->get(Opcode);
245   unsigned MIFlags = Desc.TSFlags;
246
247   // See which compare-style condition codes are available.
248   unsigned ReusableCCMask = SystemZII::getCompareZeroCCMask(MIFlags);
249
250   // For unsigned comparisons with zero, only equality makes sense.
251   unsigned CompareFlags = Compare->getDesc().TSFlags;
252   if (CompareFlags & SystemZII::IsLogical)
253     ReusableCCMask &= SystemZ::CCMASK_CMP_EQ;
254
255   if (ReusableCCMask == 0)
256     return false;
257
258   unsigned CCValues = SystemZII::getCCValues(MIFlags);
259   assert((ReusableCCMask & ~CCValues) == 0 && "Invalid CCValues");
260
261   // Now check whether these flags are enough for all users.
262   SmallVector<MachineOperand *, 4> AlterMasks;
263   for (unsigned int I = 0, E = CCUsers.size(); I != E; ++I) {
264     MachineInstr *MI = CCUsers[I];
265
266     // Fail if this isn't a use of CC that we understand.
267     unsigned Flags = MI->getDesc().TSFlags;
268     unsigned FirstOpNum;
269     if (Flags & SystemZII::CCMaskFirst)
270       FirstOpNum = 0;
271     else if (Flags & SystemZII::CCMaskLast)
272       FirstOpNum = MI->getNumExplicitOperands() - 2;
273     else
274       return false;
275
276     // Check whether the instruction predicate treats all CC values
277     // outside of ReusableCCMask in the same way.  In that case it
278     // doesn't matter what those CC values mean.
279     unsigned CCValid = MI->getOperand(FirstOpNum).getImm();
280     unsigned CCMask = MI->getOperand(FirstOpNum + 1).getImm();
281     unsigned OutValid = ~ReusableCCMask & CCValid;
282     unsigned OutMask = ~ReusableCCMask & CCMask;
283     if (OutMask != 0 && OutMask != OutValid)
284       return false;
285
286     AlterMasks.push_back(&MI->getOperand(FirstOpNum));
287     AlterMasks.push_back(&MI->getOperand(FirstOpNum + 1));
288   }
289
290   // All users are OK.  Adjust the masks for MI.
291   for (unsigned I = 0, E = AlterMasks.size(); I != E; I += 2) {
292     AlterMasks[I]->setImm(CCValues);
293     unsigned CCMask = AlterMasks[I + 1]->getImm();
294     if (CCMask & ~ReusableCCMask)
295       AlterMasks[I + 1]->setImm((CCMask & ReusableCCMask) |
296                                 (CCValues & ~ReusableCCMask));
297   }
298
299   // CC is now live after MI.
300   int CCDef = MI->findRegisterDefOperandIdx(SystemZ::CC, false, true, TRI);
301   assert(CCDef >= 0 && "Couldn't find CC set");
302   MI->getOperand(CCDef).setIsDead(false);
303
304   // Clear any intervening kills of CC.
305   MachineBasicBlock::iterator MBBI = MI, MBBE = Compare;
306   for (++MBBI; MBBI != MBBE; ++MBBI)
307     MBBI->clearRegisterKills(SystemZ::CC, TRI);
308
309   return true;
310 }
311
312 // Return true if Compare is a comparison against zero.
313 static bool isCompareZero(MachineInstr *Compare) {
314   switch (Compare->getOpcode()) {
315   case SystemZ::LTEBRCompare:
316   case SystemZ::LTDBRCompare:
317   case SystemZ::LTXBRCompare:
318     return true;
319
320   default:
321
322     if (isLoadAndTestAsCmp(Compare))
323       return true;
324
325     return (Compare->getNumExplicitOperands() == 2 &&
326             Compare->getOperand(1).isImm() &&
327             Compare->getOperand(1).getImm() == 0);
328   }
329 }
330
331 // Try to optimize cases where comparison instruction Compare is testing
332 // a value against zero.  Return true on success and if Compare should be
333 // deleted as dead.  CCUsers is the list of instructions that use the CC
334 // value produced by Compare.
335 bool SystemZElimCompare::
336 optimizeCompareZero(MachineInstr *Compare,
337                     SmallVectorImpl<MachineInstr *> &CCUsers) {
338   if (!isCompareZero(Compare))
339     return false;
340
341   // Search back for CC results that are based on the first operand.
342   unsigned SrcReg = getCompareSourceReg(Compare);
343   MachineBasicBlock &MBB = *Compare->getParent();
344   MachineBasicBlock::iterator MBBI = Compare, MBBE = MBB.begin();
345   Reference CCRefs;
346   Reference SrcRefs;
347   while (MBBI != MBBE) {
348     --MBBI;
349     MachineInstr *MI = MBBI;
350     if (resultTests(MI, SrcReg)) {
351       // Try to remove both MI and Compare by converting a branch to BRCT(G).
352       // We don't care in this case whether CC is modified between MI and
353       // Compare.
354       if (!CCRefs.Use && !SrcRefs && convertToBRCT(MI, Compare, CCUsers)) {
355         BranchOnCounts += 1;
356         return true;
357       }
358       // Try to eliminate Compare by reusing a CC result from MI.
359       if ((!CCRefs && convertToLoadAndTest(MI)) ||
360           (!CCRefs.Def && adjustCCMasksForInstr(MI, Compare, CCUsers))) {
361         EliminatedComparisons += 1;
362         return true;
363       }
364     }
365     SrcRefs |= getRegReferences(MI, SrcReg);
366     if (SrcRefs.Def)
367       return false;
368     CCRefs |= getRegReferences(MI, SystemZ::CC);
369     if (CCRefs.Use && CCRefs.Def)
370       return false;
371   }
372   return false;
373 }
374
375 // Try to fuse comparison instruction Compare into a later branch.
376 // Return true on success and if Compare is therefore redundant.
377 bool SystemZElimCompare::
378 fuseCompareAndBranch(MachineInstr *Compare,
379                      SmallVectorImpl<MachineInstr *> &CCUsers) {
380   // See whether we have a comparison that can be fused.
381   unsigned FusedOpcode = TII->getCompareAndBranch(Compare->getOpcode(),
382                                                   Compare);
383   if (!FusedOpcode)
384     return false;
385
386   // See whether we have a single branch with which to fuse.
387   if (CCUsers.size() != 1)
388     return false;
389   MachineInstr *Branch = CCUsers[0];
390   if (Branch->getOpcode() != SystemZ::BRC)
391     return false;
392
393   // Make sure that the operands are available at the branch.
394   unsigned SrcReg = Compare->getOperand(0).getReg();
395   unsigned SrcReg2 = (Compare->getOperand(1).isReg() ?
396                       Compare->getOperand(1).getReg() : 0);
397   MachineBasicBlock::iterator MBBI = Compare, MBBE = Branch;
398   for (++MBBI; MBBI != MBBE; ++MBBI)
399     if (MBBI->modifiesRegister(SrcReg, TRI) ||
400         (SrcReg2 && MBBI->modifiesRegister(SrcReg2, TRI)))
401       return false;
402
403   // Read the branch mask and target.
404   MachineOperand CCMask(MBBI->getOperand(1));
405   MachineOperand Target(MBBI->getOperand(2));
406   assert((CCMask.getImm() & ~SystemZ::CCMASK_ICMP) == 0 &&
407          "Invalid condition-code mask for integer comparison");
408
409   // Clear out all current operands.
410   int CCUse = MBBI->findRegisterUseOperandIdx(SystemZ::CC, false, TRI);
411   assert(CCUse >= 0 && "BRC must use CC");
412   Branch->RemoveOperand(CCUse);
413   Branch->RemoveOperand(2);
414   Branch->RemoveOperand(1);
415   Branch->RemoveOperand(0);
416
417   // Rebuild Branch as a fused compare and branch.
418   Branch->setDesc(TII->get(FusedOpcode));
419   MachineInstrBuilder(*Branch->getParent()->getParent(), Branch)
420     .addOperand(Compare->getOperand(0))
421     .addOperand(Compare->getOperand(1))
422     .addOperand(CCMask)
423     .addOperand(Target)
424     .addReg(SystemZ::CC, RegState::ImplicitDefine);
425
426   // Clear any intervening kills of SrcReg and SrcReg2.
427   MBBI = Compare;
428   for (++MBBI; MBBI != MBBE; ++MBBI) {
429     MBBI->clearRegisterKills(SrcReg, TRI);
430     if (SrcReg2)
431       MBBI->clearRegisterKills(SrcReg2, TRI);
432   }
433   FusedComparisons += 1;
434   return true;
435 }
436
437 // Process all comparison instructions in MBB.  Return true if something
438 // changed.
439 bool SystemZElimCompare::processBlock(MachineBasicBlock &MBB) {
440   bool Changed = false;
441
442   // Walk backwards through the block looking for comparisons, recording
443   // all CC users as we go.  The subroutines can delete Compare and
444   // instructions before it.
445   bool CompleteCCUsers = !isCCLiveOut(MBB);
446   SmallVector<MachineInstr *, 4> CCUsers;
447   MachineBasicBlock::iterator MBBI = MBB.end();
448   while (MBBI != MBB.begin()) {
449     MachineInstr *MI = --MBBI;
450     if (CompleteCCUsers &&
451         (MI->isCompare() || isLoadAndTestAsCmp(MI)) &&
452         (optimizeCompareZero(MI, CCUsers) ||
453          fuseCompareAndBranch(MI, CCUsers))) {
454       ++MBBI;
455       MI->eraseFromParent();
456       Changed = true;
457       CCUsers.clear();
458       continue;
459     }
460
461     if (MI->definesRegister(SystemZ::CC)) {
462       CCUsers.clear();
463       CompleteCCUsers = true;
464     }
465     if (MI->readsRegister(SystemZ::CC) && CompleteCCUsers)
466       CCUsers.push_back(MI);
467   }
468   return Changed;
469 }
470
471 bool SystemZElimCompare::runOnMachineFunction(MachineFunction &F) {
472   TII = static_cast<const SystemZInstrInfo *>(F.getSubtarget().getInstrInfo());
473   TRI = &TII->getRegisterInfo();
474
475   bool Changed = false;
476   for (auto &MBB : F)
477     Changed |= processBlock(MBB);
478
479   return Changed;
480 }