1//===-- SystemZElimCompare.cpp - Eliminate comparison instructions --------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This pass:
10// (1) tries to remove compares if CC already contains the required information
11// (2) fuses compares and branches into COMPARE AND BRANCH instructions
12//
13//===----------------------------------------------------------------------===//
14
15#include "SystemZ.h"
16#include "SystemZInstrInfo.h"
17#include "SystemZTargetMachine.h"
18#include "llvm/ADT/SmallVector.h"
19#include "llvm/ADT/Statistic.h"
20#include "llvm/ADT/StringRef.h"
21#include "llvm/CodeGen/LiveRegUnits.h"
22#include "llvm/CodeGen/MachineBasicBlock.h"
23#include "llvm/CodeGen/MachineFunction.h"
24#include "llvm/CodeGen/MachineFunctionAnalysisManager.h"
25#include "llvm/CodeGen/MachineFunctionPass.h"
26#include "llvm/CodeGen/MachineInstr.h"
27#include "llvm/CodeGen/MachineInstrBuilder.h"
28#include "llvm/CodeGen/MachineOperand.h"
29#include "llvm/CodeGen/MachinePassManager.h"
30#include "llvm/CodeGen/TargetRegisterInfo.h"
31#include "llvm/CodeGen/TargetSubtargetInfo.h"
32#include "llvm/IR/Analysis.h"
33#include "llvm/MC/MCInstrDesc.h"
34#include "llvm/Pass.h"
35#include <cassert>
36#include <cstdint>
37
38using namespace llvm;
39
40#define DEBUG_TYPE "systemz-elim-compare"
41
42STATISTIC(BranchOnCounts, "Number of branch-on-count instructions");
43STATISTIC(LoadAndTraps, "Number of load-and-trap instructions");
44STATISTIC(EliminatedComparisons, "Number of eliminated comparisons");
45STATISTIC(FusedComparisons, "Number of fused compare-and-branch instructions");
46
47namespace {
48
49// Represents the references to a particular register in one or more
50// instructions.
51struct Reference {
52 Reference() = default;
53
54 Reference &operator|=(const Reference &Other) {
55 Def |= Other.Def;
56 Use |= Other.Use;
57 return *this;
58 }
59
60 explicit operator bool() const { return Def || Use; }
61
62 // True if the register is defined or used in some form, either directly or
63 // via a sub- or super-register.
64 bool Def = false;
65 bool Use = false;
66};
67
68class SystemZElimCompareLegacy : public MachineFunctionPass {
69public:
70 static char ID;
71
72 SystemZElimCompareLegacy() : MachineFunctionPass(ID) {}
73
74 bool runOnMachineFunction(MachineFunction &F) override;
75
76 MachineFunctionProperties getRequiredProperties() const override {
77 return MachineFunctionProperties().setNoVRegs();
78 }
79
80 void getAnalysisUsage(AnalysisUsage &AU) const override {
81 AU.setPreservesCFG();
82 return MachineFunctionPass::getAnalysisUsage(AU);
83 }
84};
85
86char SystemZElimCompareLegacy::ID = 0;
87
88} // end anonymous namespace
89
90INITIALIZE_PASS(SystemZElimCompareLegacy, DEBUG_TYPE,
91 "SystemZ Comparison Elimination", false, false)
92
93// Returns true if MI is an instruction whose output equals the value in Reg.
94static bool preservesValueOf(MachineInstr &MI, unsigned Reg) {
95 switch (MI.getOpcode()) {
96 case SystemZ::LR:
97 case SystemZ::LGR:
98 case SystemZ::LGFR:
99 case SystemZ::LTR:
100 case SystemZ::LTGR:
101 case SystemZ::LTGFR:
102 if (MI.getOperand(i: 1).getReg() == Reg)
103 return true;
104 }
105
106 return false;
107}
108
109// Return true if any CC result of MI would (perhaps after conversion)
110// reflect the value of Reg.
111static bool resultTests(MachineInstr &MI, unsigned Reg) {
112 if (MI.getNumOperands() > 0 && MI.getOperand(i: 0).isReg() &&
113 MI.getOperand(i: 0).isDef() && MI.getOperand(i: 0).getReg() == Reg)
114 return true;
115
116 return (preservesValueOf(MI, Reg));
117}
118
119// Describe the references to Reg or any of its aliases in MI.
120static Reference getRegReferences(MachineInstr &MI, unsigned Reg,
121 const TargetRegisterInfo *TRI) {
122 Reference Ref;
123 if (MI.isDebugInstr())
124 return Ref;
125
126 for (const MachineOperand &MO : MI.operands()) {
127 if (MO.isReg()) {
128 if (Register MOReg = MO.getReg()) {
129 if (TRI->regsOverlap(RegA: MOReg, RegB: Reg)) {
130 if (MO.isUse())
131 Ref.Use = true;
132 else if (MO.isDef())
133 Ref.Def = true;
134 }
135 }
136 }
137 }
138 return Ref;
139}
140
141// Compare compares the result of MI against zero. If MI is an addition
142// of -1 and if CCUsers is a single branch on nonzero, eliminate the addition
143// and convert the branch to a BRCT(G) or BRCTH. Return true on success.
144static bool convertToBRCT(MachineInstr &MI, MachineInstr &Compare,
145 SmallVectorImpl<MachineInstr *> &CCUsers,
146 const SystemZInstrInfo *TII,
147 const TargetRegisterInfo *TRI) {
148 // Check whether we have an addition of -1.
149 unsigned Opcode = MI.getOpcode();
150 unsigned BRCT;
151 if (Opcode == SystemZ::AHI)
152 BRCT = SystemZ::BRCT;
153 else if (Opcode == SystemZ::AGHI)
154 BRCT = SystemZ::BRCTG;
155 else if (Opcode == SystemZ::AIH)
156 BRCT = SystemZ::BRCTH;
157 else
158 return false;
159 if (MI.getOperand(i: 2).getImm() != -1)
160 return false;
161
162 // Check whether we have a single JLH.
163 if (CCUsers.size() != 1)
164 return false;
165 MachineInstr *Branch = CCUsers[0];
166 if (Branch->getOpcode() != SystemZ::BRC ||
167 Branch->getOperand(i: 0).getImm() != SystemZ::CCMASK_ICMP ||
168 Branch->getOperand(i: 1).getImm() != SystemZ::CCMASK_CMP_NE)
169 return false;
170
171 // We already know that there are no references to the register between
172 // MI and Compare. Make sure that there are also no references between
173 // Compare and Branch.
174 unsigned SrcReg = TII->getCompareSourceReg(Compare);
175 MachineBasicBlock::iterator MBBI = Compare, MBBE = Branch;
176 for (++MBBI; MBBI != MBBE; ++MBBI)
177 if (getRegReferences(MI&: *MBBI, Reg: SrcReg, TRI))
178 return false;
179
180 // The transformation is OK. Rebuild Branch as a BRCT(G) or BRCTH.
181 MachineOperand Target(Branch->getOperand(i: 2));
182 while (Branch->getNumOperands())
183 Branch->removeOperand(OpNo: 0);
184 Branch->setDesc(TII->get(Opcode: BRCT));
185 MachineInstrBuilder MIB(*Branch->getParent()->getParent(), Branch);
186 MIB.add(MO: MI.getOperand(i: 0)).add(MO: MI.getOperand(i: 1)).add(MO: Target);
187 // Add a CC def to BRCT(G), since we may have to split them again if the
188 // branch displacement overflows. BRCTH has a 32-bit displacement, so
189 // this is not necessary there.
190 if (BRCT != SystemZ::BRCTH)
191 MIB.addReg(RegNo: SystemZ::CC, Flags: RegState::ImplicitDefine | RegState::Dead);
192 // The debug instr tracking for the counter now used by BRCT needs to be
193 // updated.
194 MI.getParent()->getParent()->substituteDebugValuesForInst(Old: MI, New&: *MIB);
195 MI.eraseFromParent();
196 return true;
197}
198
199// Compare compares the result of MI against zero. If MI is a suitable load
200// instruction and if CCUsers is a single conditional trap on zero, eliminate
201// the load and convert the branch to a load-and-trap. Return true on success.
202static bool convertToLoadAndTrap(MachineInstr &MI, MachineInstr &Compare,
203 SmallVectorImpl<MachineInstr *> &CCUsers,
204 const SystemZInstrInfo *TII,
205 const TargetRegisterInfo *TRI) {
206 unsigned LATOpcode = TII->getLoadAndTrap(Opcode: MI.getOpcode());
207 if (!LATOpcode)
208 return false;
209
210 // Check whether we have a single CondTrap that traps on zero.
211 if (CCUsers.size() != 1)
212 return false;
213 MachineInstr *Branch = CCUsers[0];
214 if (Branch->getOpcode() != SystemZ::CondTrap ||
215 Branch->getOperand(i: 0).getImm() != SystemZ::CCMASK_ICMP ||
216 Branch->getOperand(i: 1).getImm() != SystemZ::CCMASK_CMP_EQ)
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 = TII->getCompareSourceReg(Compare);
223 MachineBasicBlock::iterator MBBI = Compare, MBBE = Branch;
224 for (++MBBI; MBBI != MBBE; ++MBBI)
225 if (getRegReferences(MI&: *MBBI, Reg: SrcReg, TRI))
226 return false;
227
228 // The transformation is OK. Rebuild Branch as a load-and-trap.
229 while (Branch->getNumOperands())
230 Branch->removeOperand(OpNo: 0);
231 Branch->setDesc(TII->get(Opcode: LATOpcode));
232 MachineInstrBuilder(*Branch->getParent()->getParent(), Branch)
233 .add(MO: MI.getOperand(i: 0))
234 .add(MO: MI.getOperand(i: 1))
235 .add(MO: MI.getOperand(i: 2))
236 .add(MO: MI.getOperand(i: 3));
237 // The debug instr tracking for the load target now used by the load-and-trap
238 // needs to be updated.
239 MI.getParent()->getParent()->substituteDebugValuesForInst(Old: MI, New&: *Branch);
240 MI.eraseFromParent();
241 return true;
242}
243
244#ifndef NDEBUG
245static bool isAddWithImmediate(unsigned Opcode) {
246 switch(Opcode) {
247 case SystemZ::AHI:
248 case SystemZ::AHIK:
249 case SystemZ::AGHI:
250 case SystemZ::AGHIK:
251 case SystemZ::AFI:
252 case SystemZ::AIH:
253 case SystemZ::AGFI:
254 return true;
255 default: break;
256 }
257 return false;
258}
259#endif
260
261// The CC users in CCUsers are testing the result of a comparison of some
262// value X against zero and we know that any CC value produced by MI would
263// also reflect the value of X. ConvOpc may be used to pass the transfomed
264// opcode MI will have if this succeeds. Try to adjust CCUsers so that they
265// test the result of MI directly, returning true on success. Leave
266// everything unchanged on failure.
267static bool adjustCCMasksForInstr(MachineInstr &MI, MachineInstr &Compare,
268 SmallVectorImpl<MachineInstr *> &CCUsers,
269 unsigned ConvOpc, const SystemZInstrInfo *TII,
270 const TargetRegisterInfo *TRI) {
271 unsigned CompareFlags = Compare.getDesc().TSFlags;
272 unsigned CompareCCValues = SystemZII::getCCValues(Flags: CompareFlags);
273 int Opcode = (ConvOpc ? ConvOpc : MI.getOpcode());
274 const MCInstrDesc &Desc = TII->get(Opcode);
275 unsigned MIFlags = Desc.TSFlags;
276
277 // If Compare may raise an FP exception, we can only eliminate it
278 // if MI itself would have already raised the exception.
279 if (Compare.mayRaiseFPException()) {
280 // If the caller will change MI to use ConvOpc, only test whether
281 // ConvOpc is suitable; it is on the caller to set the MI flag.
282 if (ConvOpc && !Desc.mayRaiseFPException())
283 return false;
284 // If the caller will not change MI, we test the MI flag here.
285 if (!ConvOpc && !MI.mayRaiseFPException())
286 return false;
287 }
288
289 // See which compare-style condition codes are available.
290 unsigned CCValues = SystemZII::getCCValues(Flags: MIFlags);
291 unsigned ReusableCCMask = CCValues;
292 // For unsigned comparisons with zero, only equality makes sense.
293 if (CompareFlags & SystemZII::IsLogical)
294 ReusableCCMask &= SystemZ::CCMASK_CMP_EQ;
295 unsigned OFImplies = 0;
296 bool LogicalMI = false;
297 bool MIEquivalentToCmp = false;
298 if (MI.getFlag(Flag: MachineInstr::NoSWrap) &&
299 (MIFlags & SystemZII::CCIfNoSignedWrap)) {
300 // If MI has the NSW flag set in combination with the
301 // SystemZII::CCIfNoSignedWrap flag, all CCValues are valid.
302 }
303 else if ((MIFlags & SystemZII::CCIfNoSignedWrap) &&
304 MI.getOperand(i: 2).isImm()) {
305 // Signed addition of immediate. If adding a positive immediate
306 // overflows, the result must be less than zero. If adding a negative
307 // immediate overflows, the result must be larger than zero (except in
308 // the special case of adding the minimum value of the result range, in
309 // which case we cannot predict whether the result is larger than or
310 // equal to zero).
311 assert(isAddWithImmediate(Opcode) && "Expected an add with immediate.");
312 assert(!MI.mayLoadOrStore() && "Expected an immediate term.");
313 int64_t RHS = MI.getOperand(i: 2).getImm();
314 if (SystemZ::GRX32BitRegClass.contains(Reg: MI.getOperand(i: 0).getReg()) &&
315 RHS == INT32_MIN)
316 return false;
317 OFImplies = (RHS > 0 ? SystemZ::CCMASK_CMP_LT : SystemZ::CCMASK_CMP_GT);
318 }
319 else if ((MIFlags & SystemZII::IsLogical) && CCValues) {
320 // Use CCMASK_CMP_EQ to match with CCUsers. On success CCMask:s will be
321 // converted to CCMASK_LOGICAL_ZERO or CCMASK_LOGICAL_NONZERO.
322 LogicalMI = true;
323 ReusableCCMask = SystemZ::CCMASK_CMP_EQ;
324 }
325 else {
326 ReusableCCMask &= SystemZII::getCompareZeroCCMask(Flags: MIFlags);
327 assert((ReusableCCMask & ~CCValues) == 0 && "Invalid CCValues");
328 MIEquivalentToCmp =
329 ReusableCCMask == CCValues && CCValues == CompareCCValues;
330 }
331 if (ReusableCCMask == 0)
332 return false;
333
334 if (!MIEquivalentToCmp) {
335 // Now check whether these flags are enough for all users.
336 SmallVector<MachineOperand *, 4> AlterMasks;
337 for (MachineInstr *CCUserMI : CCUsers) {
338 // Fail if this isn't a use of CC that we understand.
339 unsigned Flags = CCUserMI->getDesc().TSFlags;
340 unsigned FirstOpNum;
341 if (Flags & SystemZII::CCMaskFirst)
342 FirstOpNum = 0;
343 else if (Flags & SystemZII::CCMaskLast)
344 FirstOpNum = CCUserMI->getNumExplicitOperands() - 2;
345 else
346 return false;
347
348 // Check whether the instruction predicate treats all CC values
349 // outside of ReusableCCMask in the same way. In that case it
350 // doesn't matter what those CC values mean.
351 unsigned CCValid = CCUserMI->getOperand(i: FirstOpNum).getImm();
352 unsigned CCMask = CCUserMI->getOperand(i: FirstOpNum + 1).getImm();
353 assert(CCValid == CompareCCValues && (CCMask & ~CCValid) == 0 &&
354 "Corrupt CC operands of CCUser.");
355 unsigned OutValid = ~ReusableCCMask & CCValid;
356 unsigned OutMask = ~ReusableCCMask & CCMask;
357 if (OutMask != 0 && OutMask != OutValid)
358 return false;
359
360 AlterMasks.push_back(Elt: &CCUserMI->getOperand(i: FirstOpNum));
361 AlterMasks.push_back(Elt: &CCUserMI->getOperand(i: FirstOpNum + 1));
362 }
363
364 // All users are OK. Adjust the masks for MI.
365 for (unsigned I = 0, E = AlterMasks.size(); I != E; I += 2) {
366 AlterMasks[I]->setImm(CCValues);
367 unsigned CCMask = AlterMasks[I + 1]->getImm();
368 if (LogicalMI) {
369 // Translate the CCMask into its "logical" value.
370 CCMask = (CCMask == SystemZ::CCMASK_CMP_EQ ?
371 SystemZ::CCMASK_LOGICAL_ZERO : SystemZ::CCMASK_LOGICAL_NONZERO);
372 CCMask &= CCValues; // Logical subtracts never set CC=0.
373 } else {
374 if (CCMask & ~ReusableCCMask)
375 CCMask = (CCMask & ReusableCCMask) | (CCValues & ~ReusableCCMask);
376 CCMask |= (CCMask & OFImplies) ? SystemZ::CCMASK_ARITH_OVERFLOW : 0;
377 }
378 AlterMasks[I + 1]->setImm(CCMask);
379 }
380 }
381
382 // CC is now live after MI.
383 if (!ConvOpc)
384 MI.clearRegisterDeads(Reg: SystemZ::CC);
385
386 // Check if MI lies before Compare.
387 bool BeforeCmp = false;
388 MachineBasicBlock::iterator MBBI = MI, MBBE = MI.getParent()->end();
389 for (++MBBI; MBBI != MBBE; ++MBBI)
390 if (MBBI == Compare) {
391 BeforeCmp = true;
392 break;
393 }
394
395 // Clear any intervening kills of CC.
396 if (BeforeCmp) {
397 MachineBasicBlock::iterator MBBI = MI, MBBE = Compare;
398 for (++MBBI; MBBI != MBBE; ++MBBI)
399 MBBI->clearRegisterKills(Reg: SystemZ::CC, RegInfo: TRI);
400 }
401
402 return true;
403}
404
405// If MI is a load instruction, try to convert it into a LOAD AND TEST.
406// Return true on success.
407static bool convertToLoadAndTest(MachineInstr &MI, MachineInstr &Compare,
408 SmallVectorImpl<MachineInstr *> &CCUsers,
409 const SystemZInstrInfo *TII,
410 const TargetRegisterInfo *TRI) {
411
412 // Try to adjust CC masks for the LOAD AND TEST opcode that could replace MI.
413 unsigned Opcode = TII->getLoadAndTest(Opcode: MI.getOpcode());
414 if (!Opcode || !adjustCCMasksForInstr(MI, Compare, CCUsers, ConvOpc: Opcode, TII, TRI))
415 return false;
416
417 // Rebuild to get the CC operand in the right place.
418 auto MIB = BuildMI(BB&: *MI.getParent(), I&: MI, MIMD: MI.getDebugLoc(), MCID: TII->get(Opcode));
419 for (const auto &MO : MI.operands())
420 MIB.add(MO);
421 MIB.setMemRefs(MI.memoperands());
422 // The debug instr tracking for the load target now needs to be updated
423 // because the load has moved to a new instruction
424 MI.getParent()->getParent()->substituteDebugValuesForInst(Old: MI, New&: *MIB);
425 MI.eraseFromParent();
426
427 // Mark instruction as not raising an FP exception if applicable. We already
428 // verified earlier that this move is valid.
429 if (!Compare.mayRaiseFPException())
430 MIB.setMIFlag(MachineInstr::MIFlag::NoFPExcept);
431
432 return true;
433}
434
435// See if MI is an instruction with an equivalent "logical" opcode that can
436// be used and replace MI. This is useful for EQ/NE comparisons where the
437// "nsw" flag is missing since the "logical" opcode always sets CC to reflect
438// the result being zero or non-zero.
439static bool convertToLogical(MachineInstr &MI, MachineInstr &Compare,
440 SmallVectorImpl<MachineInstr *> &CCUsers,
441 const SystemZInstrInfo *TII,
442 const TargetRegisterInfo *TRI) {
443
444 unsigned ConvOpc = 0;
445 switch (MI.getOpcode()) {
446 case SystemZ::AR:
447 ConvOpc = SystemZ::ALR;
448 break;
449 case SystemZ::ARK:
450 ConvOpc = SystemZ::ALRK;
451 break;
452 case SystemZ::AGR:
453 ConvOpc = SystemZ::ALGR;
454 break;
455 case SystemZ::AGRK:
456 ConvOpc = SystemZ::ALGRK;
457 break;
458 case SystemZ::A:
459 ConvOpc = SystemZ::AL;
460 break;
461 case SystemZ::AY:
462 ConvOpc = SystemZ::ALY;
463 break;
464 case SystemZ::AG:
465 ConvOpc = SystemZ::ALG;
466 break;
467 default:
468 break;
469 }
470 if (!ConvOpc ||
471 !adjustCCMasksForInstr(MI, Compare, CCUsers, ConvOpc, TII, TRI))
472 return false;
473
474 // Operands should be identical, so just change the opcode and remove the
475 // dead flag on CC.
476 MI.setDesc(TII->get(Opcode: ConvOpc));
477 MI.clearRegisterDeads(Reg: SystemZ::CC);
478 return true;
479}
480
481// Try to optimize cases where comparison instruction Compare is testing
482// a value against zero. Return true on success and if Compare should be
483// deleted as dead. CCUsers is the list of instructions that use the CC
484// value produced by Compare.
485static bool optimizeCompareZero(MachineInstr &Compare,
486 SmallVectorImpl<MachineInstr *> &CCUsers,
487 const SystemZInstrInfo *TII,
488 const TargetRegisterInfo *TRI) {
489 if (!TII->isCompareZero(Compare))
490 return false;
491
492 // Search back for CC results that are based on the first operand.
493 unsigned SrcReg = TII->getCompareSourceReg(Compare);
494 MachineBasicBlock &MBB = *Compare.getParent();
495 Reference CCRefs;
496 Reference SrcRefs;
497 for (MachineBasicBlock::reverse_iterator MBBI =
498 std::next(x: MachineBasicBlock::reverse_iterator(&Compare)),
499 MBBE = MBB.rend(); MBBI != MBBE;) {
500 MachineInstr &MI = *MBBI++;
501 if (resultTests(MI, Reg: SrcReg)) {
502 // Try to remove both MI and Compare by converting a branch to BRCT(G).
503 // or a load-and-trap instruction. We don't care in this case whether
504 // CC is modified between MI and Compare.
505 if (!CCRefs.Use && !SrcRefs) {
506 if (convertToBRCT(MI, Compare, CCUsers, TII, TRI)) {
507 BranchOnCounts += 1;
508 return true;
509 }
510 if (convertToLoadAndTrap(MI, Compare, CCUsers, TII, TRI)) {
511 LoadAndTraps += 1;
512 return true;
513 }
514 }
515 // Try to eliminate Compare by reusing a CC result from MI.
516 if ((!CCRefs && convertToLoadAndTest(MI, Compare, CCUsers, TII, TRI)) ||
517 (!CCRefs.Def && (adjustCCMasksForInstr(MI, Compare, CCUsers,
518 /*ConvOpc=*/0, TII, TRI) ||
519 convertToLogical(MI, Compare, CCUsers, TII, TRI)))) {
520 EliminatedComparisons += 1;
521 return true;
522 }
523 }
524 SrcRefs |= getRegReferences(MI, Reg: SrcReg, TRI);
525 if (SrcRefs.Def)
526 break;
527 CCRefs |= getRegReferences(MI, Reg: SystemZ::CC, TRI);
528 if (CCRefs.Use && CCRefs.Def)
529 break;
530 // Eliminating a Compare that may raise an FP exception will move
531 // raising the exception to some earlier MI. We cannot do this if
532 // there is anything in between that might change exception flags.
533 if (Compare.mayRaiseFPException() &&
534 (MI.isCall() || MI.hasUnmodeledSideEffects()))
535 break;
536 }
537
538 // Also do a forward search to handle cases where an instruction after the
539 // compare can be converted, like
540 // CGHI %r0d, 0; %r1d = LGR %r0d => LTGR %r1d, %r0d
541 auto MIRange = llvm::make_range(
542 x: std::next(x: MachineBasicBlock::iterator(&Compare)), y: MBB.end());
543 for (MachineInstr &MI : llvm::make_early_inc_range(Range&: MIRange)) {
544 if (preservesValueOf(MI, Reg: SrcReg)) {
545 // Try to eliminate Compare by reusing a CC result from MI.
546 if (convertToLoadAndTest(MI, Compare, CCUsers, TII, TRI)) {
547 EliminatedComparisons += 1;
548 return true;
549 }
550 }
551 if (getRegReferences(MI, Reg: SrcReg, TRI).Def)
552 return false;
553 if (getRegReferences(MI, Reg: SystemZ::CC, TRI))
554 return false;
555 }
556
557 return false;
558}
559
560// Try to fuse comparison instruction Compare into a later branch.
561// Return true on success and if Compare is therefore redundant.
562static bool fuseCompareOperations(MachineInstr &Compare,
563 SmallVectorImpl<MachineInstr *> &CCUsers,
564 const SystemZInstrInfo *TII,
565 const TargetRegisterInfo *TRI) {
566 // See whether we have a single branch with which to fuse.
567 if (CCUsers.size() != 1)
568 return false;
569 MachineInstr *Branch = CCUsers[0];
570 SystemZII::FusedCompareType Type;
571 switch (Branch->getOpcode()) {
572 case SystemZ::BRC:
573 Type = SystemZII::CompareAndBranch;
574 break;
575 case SystemZ::CondReturn:
576 Type = SystemZII::CompareAndReturn;
577 break;
578 case SystemZ::CallBCR:
579 Type = SystemZII::CompareAndSibcall;
580 break;
581 case SystemZ::CondTrap:
582 Type = SystemZII::CompareAndTrap;
583 break;
584 default:
585 return false;
586 }
587
588 // See whether we have a comparison that can be fused.
589 unsigned FusedOpcode =
590 TII->getFusedCompare(Opcode: Compare.getOpcode(), Type, MI: &Compare);
591 if (!FusedOpcode)
592 return false;
593
594 // Make sure that the operands are available at the branch.
595 // SrcReg2 is the register if the source operand is a register,
596 // 0 if the source operand is immediate, and the base register
597 // if the source operand is memory (index is not supported).
598 Register SrcReg = Compare.getOperand(i: 0).getReg();
599 Register SrcReg2 =
600 Compare.getOperand(i: 1).isReg() ? Compare.getOperand(i: 1).getReg() : Register();
601 MachineBasicBlock::iterator MBBI = Compare, MBBE = Branch;
602 for (++MBBI; MBBI != MBBE; ++MBBI)
603 if (MBBI->modifiesRegister(Reg: SrcReg, TRI) ||
604 (SrcReg2 && MBBI->modifiesRegister(Reg: SrcReg2, TRI)))
605 return false;
606
607 // Read the branch mask, target (if applicable), regmask (if applicable).
608 MachineOperand CCMask(MBBI->getOperand(i: 1));
609 assert((CCMask.getImm() & ~SystemZ::CCMASK_ICMP) == 0 &&
610 "Invalid condition-code mask for integer comparison");
611 // This is only valid for CompareAndBranch and CompareAndSibcall.
612 MachineOperand Target(MBBI->getOperand(
613 i: (Type == SystemZII::CompareAndBranch ||
614 Type == SystemZII::CompareAndSibcall) ? 2 : 0));
615 const uint32_t *RegMask;
616 if (Type == SystemZII::CompareAndSibcall)
617 RegMask = MBBI->getOperand(i: 3).getRegMask();
618
619 // Clear out all current operands.
620 int CCUse = MBBI->findRegisterUseOperandIdx(Reg: SystemZ::CC, TRI, isKill: false);
621 assert(CCUse >= 0 && "BRC/BCR must use CC");
622 Branch->removeOperand(OpNo: CCUse);
623 // Remove regmask (sibcall).
624 if (Type == SystemZII::CompareAndSibcall)
625 Branch->removeOperand(OpNo: 3);
626 // Remove target (branch or sibcall).
627 if (Type == SystemZII::CompareAndBranch ||
628 Type == SystemZII::CompareAndSibcall)
629 Branch->removeOperand(OpNo: 2);
630 Branch->removeOperand(OpNo: 1);
631 Branch->removeOperand(OpNo: 0);
632
633 // Rebuild Branch as a fused compare and branch.
634 // SrcNOps is the number of MI operands of the compare instruction
635 // that we need to copy over.
636 unsigned SrcNOps = 2;
637 if (FusedOpcode == SystemZ::CLT || FusedOpcode == SystemZ::CLGT)
638 SrcNOps = 3;
639 Branch->setDesc(TII->get(Opcode: FusedOpcode));
640 MachineInstrBuilder MIB(*Branch->getParent()->getParent(), Branch);
641 for (unsigned I = 0; I < SrcNOps; I++)
642 MIB.add(MO: Compare.getOperand(i: I));
643 MIB.add(MO: CCMask);
644
645 if (Type == SystemZII::CompareAndBranch) {
646 // Only conditional branches define CC, as they may be converted back
647 // to a non-fused branch because of a long displacement. Conditional
648 // returns don't have that problem.
649 MIB.add(MO: Target).addReg(RegNo: SystemZ::CC,
650 Flags: RegState::ImplicitDefine | RegState::Dead);
651 }
652
653 if (Type == SystemZII::CompareAndSibcall) {
654 MIB.add(MO: Target);
655 MIB.addRegMask(Mask: RegMask);
656 }
657
658 // Clear any intervening kills of SrcReg and SrcReg2.
659 MBBI = Compare;
660 for (++MBBI; MBBI != MBBE; ++MBBI) {
661 MBBI->clearRegisterKills(Reg: SrcReg, RegInfo: TRI);
662 if (SrcReg2)
663 MBBI->clearRegisterKills(Reg: SrcReg2, RegInfo: TRI);
664 }
665 FusedComparisons += 1;
666 return true;
667}
668
669// Process all comparison instructions in MBB. Return true if something
670// changed.
671static bool processBlock(MachineBasicBlock &MBB, const SystemZInstrInfo *TII,
672 const TargetRegisterInfo *TRI) {
673 bool Changed = false;
674
675 // Walk backwards through the block looking for comparisons, recording
676 // all CC users as we go. The subroutines can delete Compare and
677 // instructions before it.
678 LiveRegUnits LiveRegs(*TRI);
679 LiveRegs.addLiveOuts(MBB);
680 bool CompleteCCUsers = LiveRegs.available(Reg: SystemZ::CC);
681 SmallVector<MachineInstr *, 4> CCUsers;
682 MachineBasicBlock::iterator MBBI = MBB.end();
683 while (MBBI != MBB.begin()) {
684 MachineInstr &MI = *--MBBI;
685 if (CompleteCCUsers && (MI.isCompare() || TII->isLoadAndTestAsCmp(MI)) &&
686 (optimizeCompareZero(Compare&: MI, CCUsers, TII, TRI) ||
687 fuseCompareOperations(Compare&: MI, CCUsers, TII, TRI))) {
688 ++MBBI;
689 MI.eraseFromParent();
690 Changed = true;
691 CCUsers.clear();
692 continue;
693 }
694
695 if (MI.definesRegister(Reg: SystemZ::CC, /*TRI=*/nullptr)) {
696 CCUsers.clear();
697 CompleteCCUsers = true;
698 }
699 if (MI.readsRegister(Reg: SystemZ::CC, /*TRI=*/nullptr) && CompleteCCUsers)
700 CCUsers.push_back(Elt: &MI);
701 }
702 return Changed;
703}
704
705static bool runElimCompareOnMF(MachineFunction &F) {
706 const SystemZInstrInfo *TII =
707 F.getSubtarget<SystemZSubtarget>().getInstrInfo();
708 const TargetRegisterInfo *TRI = &TII->getRegisterInfo();
709
710 bool Changed = false;
711 for (auto &MBB : F)
712 Changed |= processBlock(MBB, TII, TRI);
713
714 return Changed;
715}
716
717FunctionPass *
718llvm::createSystemZElimCompareLegacyPass(SystemZTargetMachine &TM) {
719 return new SystemZElimCompareLegacy();
720}
721
722bool SystemZElimCompareLegacy::runOnMachineFunction(MachineFunction &MF) {
723 if (skipFunction(F: MF.getFunction()))
724 return false;
725 return runElimCompareOnMF(F&: MF);
726}
727
728PreservedAnalyses
729SystemZElimComparePass::run(MachineFunction &MF,
730 MachineFunctionAnalysisManager &MFAM) {
731 return runElimCompareOnMF(F&: MF) ? getMachineFunctionPassPreservedAnalyses()
732 .preserveSet<CFGAnalyses>()
733 : PreservedAnalyses::all();
734}
735