1 //===-- SystemZElimCompare.cpp - Eliminate comparison instructions --------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
11 // (1) tries to remove compares if CC already contains the required information
12 // (2) fuses compares and branches into COMPARE AND BRANCH instructions
14 //===----------------------------------------------------------------------===//
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"
36 #define DEBUG_TYPE "systemz-elim-compare"
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");
45 // Represents the references to a particular register in one or more
48 Reference() = default;
50 Reference &operator|=(const Reference &Other) {
56 explicit operator bool() const { return Def || Use; }
58 // True if the register is defined or used in some form, either directly or
59 // via a sub- or super-register.
64 class SystemZElimCompare : public MachineFunctionPass {
68 SystemZElimCompare(const SystemZTargetMachine &tm)
69 : MachineFunctionPass(ID) {}
71 StringRef getPassName() const override {
72 return "SystemZ Comparison Elimination";
75 bool processBlock(MachineBasicBlock &MBB);
76 bool runOnMachineFunction(MachineFunction &F) override;
78 MachineFunctionProperties getRequiredProperties() const override {
79 return MachineFunctionProperties().set(
80 MachineFunctionProperties::Property::NoVRegs);
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);
99 const SystemZInstrInfo *TII = nullptr;
100 const TargetRegisterInfo *TRI = nullptr;
103 char SystemZElimCompare::ID = 0;
105 } // end anonymous namespace
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))
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()) {
130 if (MI.getOperand(1).getReg() == Reg)
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)
144 return (preservesValueOf(MI, Reg));
147 // Describe the references to Reg or any of its aliases in MI.
148 Reference SystemZElimCompare::getRegReferences(MachineInstr &MI, unsigned Reg) {
150 for (unsigned I = 0, E = MI.getNumOperands(); I != E; ++I) {
151 const MachineOperand &MO = MI.getOperand(I);
153 if (unsigned MOReg = MO.getReg()) {
154 if (TRI->regsOverlap(MOReg, Reg)) {
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();
177 // Return the source register of Compare, which is the unknown value
179 static unsigned getCompareSourceReg(MachineInstr &Compare) {
181 if (Compare.isCompare())
182 reg = Compare.getOperand(0).getReg();
183 else if (isLoadAndTestAsCmp(Compare))
184 reg = Compare.getOperand(1).getReg();
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();
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;
207 if (MI.getOperand(2).getImm() != -1)
210 // Check whether we have a single JLH.
211 if (CCUsers.size() != 1)
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)
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))
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();
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());
254 // Check whether we have a single CondTrap that traps on zero.
255 if (CCUsers.size() != 1)
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)
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))
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();
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) {
291 // Try to adjust CC masks for the LOAD AND TEST opcode that could replace MI.
292 unsigned Opcode = TII->getLoadAndTest(MI.getOpcode());
293 if (!Opcode || !adjustCCMasksForInstr(MI, Compare, CCUsers, Opcode))
296 // Rebuild to get the CC operand in the right place.
297 auto MIB = BuildMI(*MI.getParent(), MI, MI.getDebugLoc(), TII->get(Opcode));
298 for (const auto &MO : MI.operands())
300 MIB.setMemRefs(MI.memoperands());
301 MI.eraseFromParent();
306 // The CC users in CCUsers are testing the result of a comparison of some
307 // value X against zero and we know that any CC value produced by MI would
308 // also reflect the value of X. ConvOpc may be used to pass the transfomed
309 // opcode MI will have if this succeeds. Try to adjust CCUsers so that they
310 // test the result of MI directly, returning true on success. Leave
311 // everything unchanged on failure.
312 bool SystemZElimCompare::adjustCCMasksForInstr(
313 MachineInstr &MI, MachineInstr &Compare,
314 SmallVectorImpl<MachineInstr *> &CCUsers,
316 int Opcode = (ConvOpc ? ConvOpc : MI.getOpcode());
317 const MCInstrDesc &Desc = TII->get(Opcode);
318 unsigned MIFlags = Desc.TSFlags;
320 // See which compare-style condition codes are available.
321 unsigned ReusableCCMask = SystemZII::getCompareZeroCCMask(MIFlags);
323 // For unsigned comparisons with zero, only equality makes sense.
324 unsigned CompareFlags = Compare.getDesc().TSFlags;
325 if (CompareFlags & SystemZII::IsLogical)
326 ReusableCCMask &= SystemZ::CCMASK_CMP_EQ;
328 if (ReusableCCMask == 0)
331 unsigned CCValues = SystemZII::getCCValues(MIFlags);
332 assert((ReusableCCMask & ~CCValues) == 0 && "Invalid CCValues");
334 bool MIEquivalentToCmp =
335 (ReusableCCMask == CCValues &&
336 CCValues == SystemZII::getCCValues(CompareFlags));
338 if (!MIEquivalentToCmp) {
339 // Now check whether these flags are enough for all users.
340 SmallVector<MachineOperand *, 4> AlterMasks;
341 for (unsigned int I = 0, E = CCUsers.size(); I != E; ++I) {
342 MachineInstr *MI = CCUsers[I];
344 // Fail if this isn't a use of CC that we understand.
345 unsigned Flags = MI->getDesc().TSFlags;
347 if (Flags & SystemZII::CCMaskFirst)
349 else if (Flags & SystemZII::CCMaskLast)
350 FirstOpNum = MI->getNumExplicitOperands() - 2;
354 // Check whether the instruction predicate treats all CC values
355 // outside of ReusableCCMask in the same way. In that case it
356 // doesn't matter what those CC values mean.
357 unsigned CCValid = MI->getOperand(FirstOpNum).getImm();
358 unsigned CCMask = MI->getOperand(FirstOpNum + 1).getImm();
359 unsigned OutValid = ~ReusableCCMask & CCValid;
360 unsigned OutMask = ~ReusableCCMask & CCMask;
361 if (OutMask != 0 && OutMask != OutValid)
364 AlterMasks.push_back(&MI->getOperand(FirstOpNum));
365 AlterMasks.push_back(&MI->getOperand(FirstOpNum + 1));
368 // All users are OK. Adjust the masks for MI.
369 for (unsigned I = 0, E = AlterMasks.size(); I != E; I += 2) {
370 AlterMasks[I]->setImm(CCValues);
371 unsigned CCMask = AlterMasks[I + 1]->getImm();
372 if (CCMask & ~ReusableCCMask)
373 AlterMasks[I + 1]->setImm((CCMask & ReusableCCMask) |
374 (CCValues & ~ReusableCCMask));
378 // CC is now live after MI.
380 int CCDef = MI.findRegisterDefOperandIdx(SystemZ::CC, false, true, TRI);
381 assert(CCDef >= 0 && "Couldn't find CC set");
382 MI.getOperand(CCDef).setIsDead(false);
385 // Check if MI lies before Compare.
386 bool BeforeCmp = false;
387 MachineBasicBlock::iterator MBBI = MI, MBBE = MI.getParent()->end();
388 for (++MBBI; MBBI != MBBE; ++MBBI)
389 if (MBBI == Compare) {
394 // Clear any intervening kills of CC.
396 MachineBasicBlock::iterator MBBI = MI, MBBE = Compare;
397 for (++MBBI; MBBI != MBBE; ++MBBI)
398 MBBI->clearRegisterKills(SystemZ::CC, TRI);
404 // Return true if Compare is a comparison against zero.
405 static bool isCompareZero(MachineInstr &Compare) {
406 switch (Compare.getOpcode()) {
407 case SystemZ::LTEBRCompare:
408 case SystemZ::LTDBRCompare:
409 case SystemZ::LTXBRCompare:
413 if (isLoadAndTestAsCmp(Compare))
415 return Compare.getNumExplicitOperands() == 2 &&
416 Compare.getOperand(1).isImm() && Compare.getOperand(1).getImm() == 0;
420 // Try to optimize cases where comparison instruction Compare is testing
421 // a value against zero. Return true on success and if Compare should be
422 // deleted as dead. CCUsers is the list of instructions that use the CC
423 // value produced by Compare.
424 bool SystemZElimCompare::optimizeCompareZero(
425 MachineInstr &Compare, SmallVectorImpl<MachineInstr *> &CCUsers) {
426 if (!isCompareZero(Compare))
429 // Search back for CC results that are based on the first operand.
430 unsigned SrcReg = getCompareSourceReg(Compare);
431 MachineBasicBlock &MBB = *Compare.getParent();
434 for (MachineBasicBlock::reverse_iterator MBBI =
435 std::next(MachineBasicBlock::reverse_iterator(&Compare)),
436 MBBE = MBB.rend(); MBBI != MBBE;) {
437 MachineInstr &MI = *MBBI++;
438 if (resultTests(MI, SrcReg)) {
439 // Try to remove both MI and Compare by converting a branch to BRCT(G).
440 // or a load-and-trap instruction. We don't care in this case whether
441 // CC is modified between MI and Compare.
442 if (!CCRefs.Use && !SrcRefs) {
443 if (convertToBRCT(MI, Compare, CCUsers)) {
447 if (convertToLoadAndTrap(MI, Compare, CCUsers)) {
452 // Try to eliminate Compare by reusing a CC result from MI.
453 if ((!CCRefs && convertToLoadAndTest(MI, Compare, CCUsers)) ||
454 (!CCRefs.Def && adjustCCMasksForInstr(MI, Compare, CCUsers))) {
455 EliminatedComparisons += 1;
459 SrcRefs |= getRegReferences(MI, SrcReg);
462 CCRefs |= getRegReferences(MI, SystemZ::CC);
463 if (CCRefs.Use && CCRefs.Def)
467 // Also do a forward search to handle cases where an instruction after the
468 // compare can be converted, like
469 // LTEBRCompare %f0s, %f0s; %f2s = LER %f0s => LTEBRCompare %f2s, %f0s
470 for (MachineBasicBlock::iterator MBBI =
471 std::next(MachineBasicBlock::iterator(&Compare)), MBBE = MBB.end();
473 MachineInstr &MI = *MBBI++;
474 if (preservesValueOf(MI, SrcReg)) {
475 // Try to eliminate Compare by reusing a CC result from MI.
476 if (convertToLoadAndTest(MI, Compare, CCUsers)) {
477 EliminatedComparisons += 1;
481 if (getRegReferences(MI, SrcReg).Def)
483 if (getRegReferences(MI, SystemZ::CC))
490 // Try to fuse comparison instruction Compare into a later branch.
491 // Return true on success and if Compare is therefore redundant.
492 bool SystemZElimCompare::fuseCompareOperations(
493 MachineInstr &Compare, SmallVectorImpl<MachineInstr *> &CCUsers) {
494 // See whether we have a single branch with which to fuse.
495 if (CCUsers.size() != 1)
497 MachineInstr *Branch = CCUsers[0];
498 SystemZII::FusedCompareType Type;
499 switch (Branch->getOpcode()) {
501 Type = SystemZII::CompareAndBranch;
503 case SystemZ::CondReturn:
504 Type = SystemZII::CompareAndReturn;
506 case SystemZ::CallBCR:
507 Type = SystemZII::CompareAndSibcall;
509 case SystemZ::CondTrap:
510 Type = SystemZII::CompareAndTrap;
516 // See whether we have a comparison that can be fused.
517 unsigned FusedOpcode =
518 TII->getFusedCompare(Compare.getOpcode(), Type, &Compare);
522 // Make sure that the operands are available at the branch.
523 // SrcReg2 is the register if the source operand is a register,
524 // 0 if the source operand is immediate, and the base register
525 // if the source operand is memory (index is not supported).
526 unsigned SrcReg = Compare.getOperand(0).getReg();
528 Compare.getOperand(1).isReg() ? Compare.getOperand(1).getReg() : 0;
529 MachineBasicBlock::iterator MBBI = Compare, MBBE = Branch;
530 for (++MBBI; MBBI != MBBE; ++MBBI)
531 if (MBBI->modifiesRegister(SrcReg, TRI) ||
532 (SrcReg2 && MBBI->modifiesRegister(SrcReg2, TRI)))
535 // Read the branch mask, target (if applicable), regmask (if applicable).
536 MachineOperand CCMask(MBBI->getOperand(1));
537 assert((CCMask.getImm() & ~SystemZ::CCMASK_ICMP) == 0 &&
538 "Invalid condition-code mask for integer comparison");
539 // This is only valid for CompareAndBranch.
540 MachineOperand Target(MBBI->getOperand(
541 Type == SystemZII::CompareAndBranch ? 2 : 0));
542 const uint32_t *RegMask;
543 if (Type == SystemZII::CompareAndSibcall)
544 RegMask = MBBI->getOperand(2).getRegMask();
546 // Clear out all current operands.
547 int CCUse = MBBI->findRegisterUseOperandIdx(SystemZ::CC, false, TRI);
548 assert(CCUse >= 0 && "BRC/BCR must use CC");
549 Branch->RemoveOperand(CCUse);
550 // Remove target (branch) or regmask (sibcall).
551 if (Type == SystemZII::CompareAndBranch ||
552 Type == SystemZII::CompareAndSibcall)
553 Branch->RemoveOperand(2);
554 Branch->RemoveOperand(1);
555 Branch->RemoveOperand(0);
557 // Rebuild Branch as a fused compare and branch.
558 // SrcNOps is the number of MI operands of the compare instruction
559 // that we need to copy over.
560 unsigned SrcNOps = 2;
561 if (FusedOpcode == SystemZ::CLT || FusedOpcode == SystemZ::CLGT)
563 Branch->setDesc(TII->get(FusedOpcode));
564 MachineInstrBuilder MIB(*Branch->getParent()->getParent(), Branch);
565 for (unsigned I = 0; I < SrcNOps; I++)
566 MIB.add(Compare.getOperand(I));
569 if (Type == SystemZII::CompareAndBranch) {
570 // Only conditional branches define CC, as they may be converted back
571 // to a non-fused branch because of a long displacement. Conditional
572 // returns don't have that problem.
573 MIB.add(Target).addReg(SystemZ::CC,
574 RegState::ImplicitDefine | RegState::Dead);
577 if (Type == SystemZII::CompareAndSibcall)
578 MIB.addRegMask(RegMask);
580 // Clear any intervening kills of SrcReg and SrcReg2.
582 for (++MBBI; MBBI != MBBE; ++MBBI) {
583 MBBI->clearRegisterKills(SrcReg, TRI);
585 MBBI->clearRegisterKills(SrcReg2, TRI);
587 FusedComparisons += 1;
591 // Process all comparison instructions in MBB. Return true if something
593 bool SystemZElimCompare::processBlock(MachineBasicBlock &MBB) {
594 bool Changed = false;
596 // Walk backwards through the block looking for comparisons, recording
597 // all CC users as we go. The subroutines can delete Compare and
598 // instructions before it.
599 bool CompleteCCUsers = !isCCLiveOut(MBB);
600 SmallVector<MachineInstr *, 4> CCUsers;
601 MachineBasicBlock::iterator MBBI = MBB.end();
602 while (MBBI != MBB.begin()) {
603 MachineInstr &MI = *--MBBI;
604 if (CompleteCCUsers && (MI.isCompare() || isLoadAndTestAsCmp(MI)) &&
605 (optimizeCompareZero(MI, CCUsers) ||
606 fuseCompareOperations(MI, CCUsers))) {
608 MI.eraseFromParent();
614 if (MI.definesRegister(SystemZ::CC)) {
616 CompleteCCUsers = true;
618 if (MI.readsRegister(SystemZ::CC) && CompleteCCUsers)
619 CCUsers.push_back(&MI);
624 bool SystemZElimCompare::runOnMachineFunction(MachineFunction &F) {
625 if (skipFunction(F.getFunction()))
628 TII = static_cast<const SystemZInstrInfo *>(F.getSubtarget().getInstrInfo());
629 TRI = &TII->getRegisterInfo();
631 bool Changed = false;
633 Changed |= processBlock(MBB);
638 FunctionPass *llvm::createSystemZElimComparePass(SystemZTargetMachine &TM) {
639 return new SystemZElimCompare(TM);