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 "SystemZ.h"
17 #include "SystemZInstrInfo.h"
18 #include "SystemZTargetMachine.h"
19 #include "llvm/ADT/SmallVector.h"
20 #include "llvm/ADT/Statistic.h"
21 #include "llvm/ADT/StringRef.h"
22 #include "llvm/CodeGen/MachineBasicBlock.h"
23 #include "llvm/CodeGen/MachineFunction.h"
24 #include "llvm/CodeGen/MachineFunctionPass.h"
25 #include "llvm/CodeGen/MachineInstr.h"
26 #include "llvm/CodeGen/MachineInstrBuilder.h"
27 #include "llvm/CodeGen/MachineOperand.h"
28 #include "llvm/CodeGen/TargetRegisterInfo.h"
29 #include "llvm/CodeGen/TargetSubtargetInfo.h"
30 #include "llvm/MC/MCInstrDesc.h"
31 #include <cassert>
32 #include <cstdint>
33 
34 using namespace llvm;
35 
36 #define DEBUG_TYPE "systemz-elim-compare"
37 
38 STATISTIC(BranchOnCounts, "Number of branch-on-count instructions");
39 STATISTIC(LoadAndTraps, "Number of load-and-trap instructions");
40 STATISTIC(EliminatedComparisons, "Number of eliminated comparisons");
41 STATISTIC(FusedComparisons, "Number of fused compare-and-branch instructions");
42 
43 namespace {
44 
45 // Represents the references to a particular register in one or more
46 // instructions.
47 struct Reference {
48   Reference() = default;
49 
50   Reference &operator|=(const Reference &Other) {
51     Def |= Other.Def;
52     Use |= Other.Use;
53     return *this;
54   }
55 
56   explicit operator bool() const { return Def || Use; }
57 
58   // True if the register is defined or used in some form, either directly or
59   // via a sub- or super-register.
60   bool Def = false;
61   bool Use = false;
62 };
63 
64 class SystemZElimCompare : public MachineFunctionPass {
65 public:
66   static char ID;
67 
68   SystemZElimCompare(const SystemZTargetMachine &tm)
69     : MachineFunctionPass(ID) {}
70 
71   StringRef getPassName() const override {
72     return "SystemZ Comparison Elimination";
73   }
74 
75   bool processBlock(MachineBasicBlock &MBB);
76   bool runOnMachineFunction(MachineFunction &F) override;
77 
78   MachineFunctionProperties getRequiredProperties() const override {
79     return MachineFunctionProperties().set(
80         MachineFunctionProperties::Property::NoVRegs);
81   }
82 
83 private:
84   Reference getRegReferences(MachineInstr &MI, unsigned Reg);
85   bool convertToBRCT(MachineInstr &MI, MachineInstr &Compare,
86                      SmallVectorImpl<MachineInstr *> &CCUsers);
87   bool convertToLoadAndTrap(MachineInstr &MI, MachineInstr &Compare,
88                             SmallVectorImpl<MachineInstr *> &CCUsers);
89   bool convertToLoadAndTest(MachineInstr &MI, MachineInstr &Compare,
90                             SmallVectorImpl<MachineInstr *> &CCUsers);
91   bool adjustCCMasksForInstr(MachineInstr &MI, MachineInstr &Compare,
92                              SmallVectorImpl<MachineInstr *> &CCUsers,
93                              unsigned ConvOpc = 0);
94   bool optimizeCompareZero(MachineInstr &Compare,
95                            SmallVectorImpl<MachineInstr *> &CCUsers);
96   bool fuseCompareOperations(MachineInstr &Compare,
97                              SmallVectorImpl<MachineInstr *> &CCUsers);
98 
99   const SystemZInstrInfo *TII = nullptr;
100   const TargetRegisterInfo *TRI = nullptr;
101 };
102 
103 char SystemZElimCompare::ID = 0;
104 
105 } // end anonymous namespace
106 
107 // Return true if CC is live out of MBB.
108 static bool isCCLiveOut(MachineBasicBlock &MBB) {
109   for (auto SI = MBB.succ_begin(), SE = MBB.succ_end(); SI != SE; ++SI)
110     if ((*SI)->isLiveIn(SystemZ::CC))
111       return true;
112   return false;
113 }
114 
115 // Returns true if MI is an instruction whose output equals the value in Reg.
116 static bool preservesValueOf(MachineInstr &MI, unsigned Reg) {
117   switch (MI.getOpcode()) {
118   case SystemZ::LR:
119   case SystemZ::LGR:
120   case SystemZ::LGFR:
121   case SystemZ::LTR:
122   case SystemZ::LTGR:
123   case SystemZ::LTGFR:
124   case SystemZ::LER:
125   case SystemZ::LDR:
126   case SystemZ::LXR:
127   case SystemZ::LTEBR:
128   case SystemZ::LTDBR:
129   case SystemZ::LTXBR:
130     if (MI.getOperand(1).getReg() == Reg)
131       return true;
132   }
133 
134   return false;
135 }
136 
137 // Return true if any CC result of MI would (perhaps after conversion)
138 // reflect the value of Reg.
139 static bool resultTests(MachineInstr &MI, unsigned Reg) {
140   if (MI.getNumOperands() > 0 && MI.getOperand(0).isReg() &&
141       MI.getOperand(0).isDef() && MI.getOperand(0).getReg() == Reg)
142     return true;
143 
144   return (preservesValueOf(MI, Reg));
145 }
146 
147 // Describe the references to Reg or any of its aliases in MI.
148 Reference SystemZElimCompare::getRegReferences(MachineInstr &MI, unsigned Reg) {
149   Reference Ref;
150   for (unsigned I = 0, E = MI.getNumOperands(); I != E; ++I) {
151     const MachineOperand &MO = MI.getOperand(I);
152     if (MO.isReg()) {
153       if (unsigned MOReg = MO.getReg()) {
154         if (TRI->regsOverlap(MOReg, Reg)) {
155           if (MO.isUse())
156             Ref.Use = true;
157           else if (MO.isDef())
158             Ref.Def = true;
159         }
160       }
161     }
162   }
163   return Ref;
164 }
165 
166 // Return true if this is a load and test which can be optimized the
167 // same way as compare instruction.
168 static bool isLoadAndTestAsCmp(MachineInstr &MI) {
169   // If we during isel used a load-and-test as a compare with 0, the
170   // def operand is dead.
171   return (MI.getOpcode() == SystemZ::LTEBR ||
172           MI.getOpcode() == SystemZ::LTDBR ||
173           MI.getOpcode() == SystemZ::LTXBR) &&
174          MI.getOperand(0).isDead();
175 }
176 
177 // Return the source register of Compare, which is the unknown value
178 // being tested.
179 static unsigned getCompareSourceReg(MachineInstr &Compare) {
180   unsigned reg = 0;
181   if (Compare.isCompare())
182     reg = Compare.getOperand(0).getReg();
183   else if (isLoadAndTestAsCmp(Compare))
184     reg = Compare.getOperand(1).getReg();
185   assert(reg);
186 
187   return reg;
188 }
189 
190 // Compare compares the result of MI against zero.  If MI is an addition
191 // of -1 and if CCUsers is a single branch on nonzero, eliminate the addition
192 // and convert the branch to a BRCT(G) or BRCTH.  Return true on success.
193 bool SystemZElimCompare::convertToBRCT(
194     MachineInstr &MI, MachineInstr &Compare,
195     SmallVectorImpl<MachineInstr *> &CCUsers) {
196   // Check whether we have an addition of -1.
197   unsigned Opcode = MI.getOpcode();
198   unsigned BRCT;
199   if (Opcode == SystemZ::AHI)
200     BRCT = SystemZ::BRCT;
201   else if (Opcode == SystemZ::AGHI)
202     BRCT = SystemZ::BRCTG;
203   else if (Opcode == SystemZ::AIH)
204     BRCT = SystemZ::BRCTH;
205   else
206     return false;
207   if (MI.getOperand(2).getImm() != -1)
208     return false;
209 
210   // Check whether we have a single JLH.
211   if (CCUsers.size() != 1)
212     return false;
213   MachineInstr *Branch = CCUsers[0];
214   if (Branch->getOpcode() != SystemZ::BRC ||
215       Branch->getOperand(0).getImm() != SystemZ::CCMASK_ICMP ||
216       Branch->getOperand(1).getImm() != SystemZ::CCMASK_CMP_NE)
217     return false;
218 
219   // We already know that there are no references to the register between
220   // MI and Compare.  Make sure that there are also no references between
221   // Compare and Branch.
222   unsigned SrcReg = getCompareSourceReg(Compare);
223   MachineBasicBlock::iterator MBBI = Compare, MBBE = Branch;
224   for (++MBBI; MBBI != MBBE; ++MBBI)
225     if (getRegReferences(*MBBI, SrcReg))
226       return false;
227 
228   // The transformation is OK.  Rebuild Branch as a BRCT(G) or BRCTH.
229   MachineOperand Target(Branch->getOperand(2));
230   while (Branch->getNumOperands())
231     Branch->RemoveOperand(0);
232   Branch->setDesc(TII->get(BRCT));
233   MachineInstrBuilder MIB(*Branch->getParent()->getParent(), Branch);
234   MIB.add(MI.getOperand(0)).add(MI.getOperand(1)).add(Target);
235   // Add a CC def to BRCT(G), since we may have to split them again if the
236   // branch displacement overflows.  BRCTH has a 32-bit displacement, so
237   // this is not necessary there.
238   if (BRCT != SystemZ::BRCTH)
239     MIB.addReg(SystemZ::CC, RegState::ImplicitDefine | RegState::Dead);
240   MI.eraseFromParent();
241   return true;
242 }
243 
244 // Compare compares the result of MI against zero.  If MI is a suitable load
245 // instruction and if CCUsers is a single conditional trap on zero, eliminate
246 // the load and convert the branch to a load-and-trap.  Return true on success.
247 bool SystemZElimCompare::convertToLoadAndTrap(
248     MachineInstr &MI, MachineInstr &Compare,
249     SmallVectorImpl<MachineInstr *> &CCUsers) {
250   unsigned LATOpcode = TII->getLoadAndTrap(MI.getOpcode());
251   if (!LATOpcode)
252     return false;
253 
254   // Check whether we have a single CondTrap that traps on zero.
255   if (CCUsers.size() != 1)
256     return false;
257   MachineInstr *Branch = CCUsers[0];
258   if (Branch->getOpcode() != SystemZ::CondTrap ||
259       Branch->getOperand(0).getImm() != SystemZ::CCMASK_ICMP ||
260       Branch->getOperand(1).getImm() != SystemZ::CCMASK_CMP_EQ)
261     return false;
262 
263   // We already know that there are no references to the register between
264   // MI and Compare.  Make sure that there are also no references between
265   // Compare and Branch.
266   unsigned SrcReg = getCompareSourceReg(Compare);
267   MachineBasicBlock::iterator MBBI = Compare, MBBE = Branch;
268   for (++MBBI; MBBI != MBBE; ++MBBI)
269     if (getRegReferences(*MBBI, SrcReg))
270       return false;
271 
272   // The transformation is OK.  Rebuild Branch as a load-and-trap.
273   while (Branch->getNumOperands())
274     Branch->RemoveOperand(0);
275   Branch->setDesc(TII->get(LATOpcode));
276   MachineInstrBuilder(*Branch->getParent()->getParent(), Branch)
277       .add(MI.getOperand(0))
278       .add(MI.getOperand(1))
279       .add(MI.getOperand(2))
280       .add(MI.getOperand(3));
281   MI.eraseFromParent();
282   return true;
283 }
284 
285 // If MI is a load instruction, try to convert it into a LOAD AND TEST.
286 // Return true on success.
287 bool SystemZElimCompare::convertToLoadAndTest(
288     MachineInstr &MI, MachineInstr &Compare,
289     SmallVectorImpl<MachineInstr *> &CCUsers) {
290 
291   // Try to adjust CC masks for a LOAD AND TEST opcode that could replace MI.
292   unsigned Opcode = TII->getLoadAndTest(MI.getOpcode());
293   if (!Opcode || !adjustCCMasksForInstr(MI, Compare, CCUsers, Opcode))
294     return false;
295 
296   MI.setDesc(TII->get(Opcode));
297   MachineInstrBuilder(*MI.getParent()->getParent(), MI)
298       .addReg(SystemZ::CC, RegState::ImplicitDefine);
299   return true;
300 }
301 
302 // The CC users in CCUsers are testing the result of a comparison of some
303 // value X against zero and we know that any CC value produced by MI would
304 // also reflect the value of X.  ConvOpc may be used to pass the transfomed
305 // opcode MI will have if this succeeds.  Try to adjust CCUsers so that they
306 // test the result of MI directly, returning true on success.  Leave
307 // everything unchanged on failure.
308 bool SystemZElimCompare::adjustCCMasksForInstr(
309     MachineInstr &MI, MachineInstr &Compare,
310     SmallVectorImpl<MachineInstr *> &CCUsers,
311     unsigned ConvOpc) {
312   int Opcode = (ConvOpc ? ConvOpc : MI.getOpcode());
313   const MCInstrDesc &Desc = TII->get(Opcode);
314   unsigned MIFlags = Desc.TSFlags;
315 
316   // See which compare-style condition codes are available.
317   unsigned ReusableCCMask = SystemZII::getCompareZeroCCMask(MIFlags);
318 
319   // For unsigned comparisons with zero, only equality makes sense.
320   unsigned CompareFlags = Compare.getDesc().TSFlags;
321   if (CompareFlags & SystemZII::IsLogical)
322     ReusableCCMask &= SystemZ::CCMASK_CMP_EQ;
323 
324   if (ReusableCCMask == 0)
325     return false;
326 
327   unsigned CCValues = SystemZII::getCCValues(MIFlags);
328   assert((ReusableCCMask & ~CCValues) == 0 && "Invalid CCValues");
329 
330   // Now check whether these flags are enough for all users.
331   SmallVector<MachineOperand *, 4> AlterMasks;
332   for (unsigned int I = 0, E = CCUsers.size(); I != E; ++I) {
333     MachineInstr *MI = CCUsers[I];
334 
335     // Fail if this isn't a use of CC that we understand.
336     unsigned Flags = MI->getDesc().TSFlags;
337     unsigned FirstOpNum;
338     if (Flags & SystemZII::CCMaskFirst)
339       FirstOpNum = 0;
340     else if (Flags & SystemZII::CCMaskLast)
341       FirstOpNum = MI->getNumExplicitOperands() - 2;
342     else
343       return false;
344 
345     // Check whether the instruction predicate treats all CC values
346     // outside of ReusableCCMask in the same way.  In that case it
347     // doesn't matter what those CC values mean.
348     unsigned CCValid = MI->getOperand(FirstOpNum).getImm();
349     unsigned CCMask = MI->getOperand(FirstOpNum + 1).getImm();
350     unsigned OutValid = ~ReusableCCMask & CCValid;
351     unsigned OutMask = ~ReusableCCMask & CCMask;
352     if (OutMask != 0 && OutMask != OutValid)
353       return false;
354 
355     AlterMasks.push_back(&MI->getOperand(FirstOpNum));
356     AlterMasks.push_back(&MI->getOperand(FirstOpNum + 1));
357   }
358 
359   // All users are OK.  Adjust the masks for MI.
360   for (unsigned I = 0, E = AlterMasks.size(); I != E; I += 2) {
361     AlterMasks[I]->setImm(CCValues);
362     unsigned CCMask = AlterMasks[I + 1]->getImm();
363     if (CCMask & ~ReusableCCMask)
364       AlterMasks[I + 1]->setImm((CCMask & ReusableCCMask) |
365                                 (CCValues & ~ReusableCCMask));
366   }
367 
368   // CC is now live after MI.
369   if (!ConvOpc) {
370     int CCDef = MI.findRegisterDefOperandIdx(SystemZ::CC, false, true, TRI);
371     assert(CCDef >= 0 && "Couldn't find CC set");
372     MI.getOperand(CCDef).setIsDead(false);
373   }
374 
375   // Clear any intervening kills of CC.
376   MachineBasicBlock::iterator MBBI = MI, MBBE = Compare;
377   for (++MBBI; MBBI != MBBE; ++MBBI)
378     MBBI->clearRegisterKills(SystemZ::CC, TRI);
379 
380   return true;
381 }
382 
383 // Return true if Compare is a comparison against zero.
384 static bool isCompareZero(MachineInstr &Compare) {
385   switch (Compare.getOpcode()) {
386   case SystemZ::LTEBRCompare:
387   case SystemZ::LTDBRCompare:
388   case SystemZ::LTXBRCompare:
389     return true;
390 
391   default:
392     if (isLoadAndTestAsCmp(Compare))
393       return true;
394     return Compare.getNumExplicitOperands() == 2 &&
395            Compare.getOperand(1).isImm() && Compare.getOperand(1).getImm() == 0;
396   }
397 }
398 
399 // Try to optimize cases where comparison instruction Compare is testing
400 // a value against zero.  Return true on success and if Compare should be
401 // deleted as dead.  CCUsers is the list of instructions that use the CC
402 // value produced by Compare.
403 bool SystemZElimCompare::optimizeCompareZero(
404     MachineInstr &Compare, SmallVectorImpl<MachineInstr *> &CCUsers) {
405   if (!isCompareZero(Compare))
406     return false;
407 
408   // Search back for CC results that are based on the first operand.
409   unsigned SrcReg = getCompareSourceReg(Compare);
410   MachineBasicBlock &MBB = *Compare.getParent();
411   MachineBasicBlock::iterator MBBI = Compare, MBBE = MBB.begin();
412   Reference CCRefs;
413   Reference SrcRefs;
414   while (MBBI != MBBE) {
415     --MBBI;
416     MachineInstr &MI = *MBBI;
417     if (resultTests(MI, SrcReg)) {
418       // Try to remove both MI and Compare by converting a branch to BRCT(G).
419       // or a load-and-trap instruction.  We don't care in this case whether
420       // CC is modified between MI and Compare.
421       if (!CCRefs.Use && !SrcRefs) {
422         if (convertToBRCT(MI, Compare, CCUsers)) {
423           BranchOnCounts += 1;
424           return true;
425         }
426         if (convertToLoadAndTrap(MI, Compare, CCUsers)) {
427           LoadAndTraps += 1;
428           return true;
429         }
430       }
431       // Try to eliminate Compare by reusing a CC result from MI.
432       if ((!CCRefs && convertToLoadAndTest(MI, Compare, CCUsers)) ||
433           (!CCRefs.Def && adjustCCMasksForInstr(MI, Compare, CCUsers))) {
434         EliminatedComparisons += 1;
435         return true;
436       }
437     }
438     SrcRefs |= getRegReferences(MI, SrcReg);
439     if (SrcRefs.Def)
440       break;
441     CCRefs |= getRegReferences(MI, SystemZ::CC);
442     if (CCRefs.Use && CCRefs.Def)
443       break;
444   }
445 
446   // Also do a forward search to handle cases where an instruction after the
447   // compare can be converted, like
448   // LTEBRCompare %f0s, %f0s; %f2s = LER %f0s  =>  LTEBRCompare %f2s, %f0s
449   MBBI = Compare, MBBE = MBB.end();
450   while (++MBBI != MBBE) {
451     MachineInstr &MI = *MBBI;
452     if (preservesValueOf(MI, SrcReg)) {
453       // Try to eliminate Compare by reusing a CC result from MI.
454       if (convertToLoadAndTest(MI, Compare, CCUsers)) {
455         EliminatedComparisons += 1;
456         return true;
457       }
458     }
459     if (getRegReferences(MI, SrcReg).Def)
460       return false;
461     if (getRegReferences(MI, SystemZ::CC))
462       return false;
463   }
464 
465   return false;
466 }
467 
468 // Try to fuse comparison instruction Compare into a later branch.
469 // Return true on success and if Compare is therefore redundant.
470 bool SystemZElimCompare::fuseCompareOperations(
471     MachineInstr &Compare, SmallVectorImpl<MachineInstr *> &CCUsers) {
472   // See whether we have a single branch with which to fuse.
473   if (CCUsers.size() != 1)
474     return false;
475   MachineInstr *Branch = CCUsers[0];
476   SystemZII::FusedCompareType Type;
477   switch (Branch->getOpcode()) {
478   case SystemZ::BRC:
479     Type = SystemZII::CompareAndBranch;
480     break;
481   case SystemZ::CondReturn:
482     Type = SystemZII::CompareAndReturn;
483     break;
484   case SystemZ::CallBCR:
485     Type = SystemZII::CompareAndSibcall;
486     break;
487   case SystemZ::CondTrap:
488     Type = SystemZII::CompareAndTrap;
489     break;
490   default:
491     return false;
492   }
493 
494   // See whether we have a comparison that can be fused.
495   unsigned FusedOpcode =
496       TII->getFusedCompare(Compare.getOpcode(), Type, &Compare);
497   if (!FusedOpcode)
498     return false;
499 
500   // Make sure that the operands are available at the branch.
501   // SrcReg2 is the register if the source operand is a register,
502   // 0 if the source operand is immediate, and the base register
503   // if the source operand is memory (index is not supported).
504   unsigned SrcReg = Compare.getOperand(0).getReg();
505   unsigned SrcReg2 =
506       Compare.getOperand(1).isReg() ? Compare.getOperand(1).getReg() : 0;
507   MachineBasicBlock::iterator MBBI = Compare, MBBE = Branch;
508   for (++MBBI; MBBI != MBBE; ++MBBI)
509     if (MBBI->modifiesRegister(SrcReg, TRI) ||
510         (SrcReg2 && MBBI->modifiesRegister(SrcReg2, TRI)))
511       return false;
512 
513   // Read the branch mask, target (if applicable), regmask (if applicable).
514   MachineOperand CCMask(MBBI->getOperand(1));
515   assert((CCMask.getImm() & ~SystemZ::CCMASK_ICMP) == 0 &&
516          "Invalid condition-code mask for integer comparison");
517   // This is only valid for CompareAndBranch.
518   MachineOperand Target(MBBI->getOperand(
519     Type == SystemZII::CompareAndBranch ? 2 : 0));
520   const uint32_t *RegMask;
521   if (Type == SystemZII::CompareAndSibcall)
522     RegMask = MBBI->getOperand(2).getRegMask();
523 
524   // Clear out all current operands.
525   int CCUse = MBBI->findRegisterUseOperandIdx(SystemZ::CC, false, TRI);
526   assert(CCUse >= 0 && "BRC/BCR must use CC");
527   Branch->RemoveOperand(CCUse);
528   // Remove target (branch) or regmask (sibcall).
529   if (Type == SystemZII::CompareAndBranch ||
530       Type == SystemZII::CompareAndSibcall)
531     Branch->RemoveOperand(2);
532   Branch->RemoveOperand(1);
533   Branch->RemoveOperand(0);
534 
535   // Rebuild Branch as a fused compare and branch.
536   // SrcNOps is the number of MI operands of the compare instruction
537   // that we need to copy over.
538   unsigned SrcNOps = 2;
539   if (FusedOpcode == SystemZ::CLT || FusedOpcode == SystemZ::CLGT)
540     SrcNOps = 3;
541   Branch->setDesc(TII->get(FusedOpcode));
542   MachineInstrBuilder MIB(*Branch->getParent()->getParent(), Branch);
543   for (unsigned I = 0; I < SrcNOps; I++)
544     MIB.add(Compare.getOperand(I));
545   MIB.add(CCMask);
546 
547   if (Type == SystemZII::CompareAndBranch) {
548     // Only conditional branches define CC, as they may be converted back
549     // to a non-fused branch because of a long displacement.  Conditional
550     // returns don't have that problem.
551     MIB.add(Target).addReg(SystemZ::CC,
552                            RegState::ImplicitDefine | RegState::Dead);
553   }
554 
555   if (Type == SystemZII::CompareAndSibcall)
556     MIB.addRegMask(RegMask);
557 
558   // Clear any intervening kills of SrcReg and SrcReg2.
559   MBBI = Compare;
560   for (++MBBI; MBBI != MBBE; ++MBBI) {
561     MBBI->clearRegisterKills(SrcReg, TRI);
562     if (SrcReg2)
563       MBBI->clearRegisterKills(SrcReg2, TRI);
564   }
565   FusedComparisons += 1;
566   return true;
567 }
568 
569 // Process all comparison instructions in MBB.  Return true if something
570 // changed.
571 bool SystemZElimCompare::processBlock(MachineBasicBlock &MBB) {
572   bool Changed = false;
573 
574   // Walk backwards through the block looking for comparisons, recording
575   // all CC users as we go.  The subroutines can delete Compare and
576   // instructions before it.
577   bool CompleteCCUsers = !isCCLiveOut(MBB);
578   SmallVector<MachineInstr *, 4> CCUsers;
579   MachineBasicBlock::iterator MBBI = MBB.end();
580   while (MBBI != MBB.begin()) {
581     MachineInstr &MI = *--MBBI;
582     if (CompleteCCUsers && (MI.isCompare() || isLoadAndTestAsCmp(MI)) &&
583         (optimizeCompareZero(MI, CCUsers) ||
584          fuseCompareOperations(MI, CCUsers))) {
585       ++MBBI;
586       MI.eraseFromParent();
587       Changed = true;
588       CCUsers.clear();
589       continue;
590     }
591 
592     if (MI.definesRegister(SystemZ::CC)) {
593       CCUsers.clear();
594       CompleteCCUsers = true;
595     }
596     if (MI.readsRegister(SystemZ::CC) && CompleteCCUsers)
597       CCUsers.push_back(&MI);
598   }
599   return Changed;
600 }
601 
602 bool SystemZElimCompare::runOnMachineFunction(MachineFunction &F) {
603   if (skipFunction(F.getFunction()))
604     return false;
605 
606   TII = static_cast<const SystemZInstrInfo *>(F.getSubtarget().getInstrInfo());
607   TRI = &TII->getRegisterInfo();
608 
609   bool Changed = false;
610   for (auto &MBB : F)
611     Changed |= processBlock(MBB);
612 
613   return Changed;
614 }
615 
616 FunctionPass *llvm::createSystemZElimComparePass(SystemZTargetMachine &TM) {
617   return new SystemZElimCompare(TM);
618 }
619