LLVM 24.0.0git
SystemZElimCompare.cpp
Go to the documentation of this file.
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"
19#include "llvm/ADT/Statistic.h"
20#include "llvm/ADT/StringRef.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();
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(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(0).isReg() &&
113 MI.getOperand(0).isDef() && MI.getOperand(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(MOReg, 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.
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(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(0).getImm() != SystemZ::CCMASK_ICMP ||
168 Branch->getOperand(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(*MBBI, SrcReg, TRI))
178 return false;
179
180 // The transformation is OK. Rebuild Branch as a BRCT(G) or BRCTH.
181 MachineOperand Target(Branch->getOperand(2));
182 while (Branch->getNumOperands())
183 Branch->removeOperand(0);
184 Branch->setDesc(TII->get(BRCT));
185 MachineInstrBuilder MIB(*Branch->getParent()->getParent(), Branch);
186 MIB.add(MI.getOperand(0)).add(MI.getOperand(1)).add(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)
192 // The debug instr tracking for the counter now used by BRCT needs to be
193 // updated.
194 MI.getParent()->getParent()->substituteDebugValuesForInst(MI, *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.
204 const SystemZInstrInfo *TII,
205 const TargetRegisterInfo *TRI) {
206 unsigned LATOpcode = TII->getLoadAndTrap(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(0).getImm() != SystemZ::CCMASK_ICMP ||
216 Branch->getOperand(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(*MBBI, 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(0);
231 Branch->setDesc(TII->get(LATOpcode));
232 MachineInstrBuilder(*Branch->getParent()->getParent(), Branch)
233 .add(MI.getOperand(0))
234 .add(MI.getOperand(1))
235 .add(MI.getOperand(2))
236 .add(MI.getOperand(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(MI, *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.
269 unsigned ConvOpc, const SystemZInstrInfo *TII,
270 const TargetRegisterInfo *TRI) {
271 unsigned CompareFlags = Compare.getDesc().TSFlags;
272 unsigned CompareCCValues = SystemZII::getCCValues(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(MIFlags);
291 unsigned ReusableCCMask = CCValues;
292 // For unsigned comparisons with zero, only equality makes sense.
294 ReusableCCMask &= SystemZ::CCMASK_CMP_EQ;
295 unsigned OFImplies = 0;
296 bool LogicalMI = false;
297 bool MIEquivalentToCmp = false;
298 if (MI.getFlag(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(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(2).getImm();
314 if (SystemZ::GRX32BitRegClass.contains(MI.getOperand(0).getReg()) &&
315 RHS == INT32_MIN)
316 return false;
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(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.
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(FirstOpNum).getImm();
352 unsigned CCMask = CCUserMI->getOperand(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(&CCUserMI->getOperand(FirstOpNum));
361 AlterMasks.push_back(&CCUserMI->getOperand(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 ?
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(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(SystemZ::CC, 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.
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(MI.getOpcode());
414 if (!Opcode || !adjustCCMasksForInstr(MI, Compare, CCUsers, Opcode, TII, TRI))
415 return false;
416
417 // Rebuild to get the CC operand in the right place.
418 auto MIB = BuildMI(*MI.getParent(), MI, MI.getDebugLoc(), 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(MI, *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())
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.
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(ConvOpc));
477 MI.clearRegisterDeads(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.
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;
498 std::next(MachineBasicBlock::reverse_iterator(&Compare)),
499 MBBE = MBB.rend(); MBBI != MBBE;) {
500 MachineInstr &MI = *MBBI++;
501 if (resultTests(MI, 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, SrcReg, TRI);
525 if (SrcRefs.Def)
526 break;
527 CCRefs |= getRegReferences(MI, 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 std::next(MachineBasicBlock::iterator(&Compare)), MBB.end());
543 for (MachineInstr &MI : llvm::make_early_inc_range(MIRange)) {
544 if (preservesValueOf(MI, 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, SrcReg, TRI).Def)
552 return false;
553 if (getRegReferences(MI, 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.
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];
571 switch (Branch->getOpcode()) {
572 case SystemZ::BRC:
574 break;
575 case SystemZ::CondReturn:
577 break;
578 case SystemZ::CallBCR:
580 break;
581 case SystemZ::CondTrap:
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(Compare.getOpcode(), Type, &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(0).getReg();
599 Register SrcReg2 =
600 Compare.getOperand(1).isReg() ? Compare.getOperand(1).getReg() : Register();
601 MachineBasicBlock::iterator MBBI = Compare, MBBE = Branch;
602 for (++MBBI; MBBI != MBBE; ++MBBI)
603 if (MBBI->modifiesRegister(SrcReg, TRI) ||
604 (SrcReg2 && MBBI->modifiesRegister(SrcReg2, TRI)))
605 return false;
606
607 // Read the branch mask, target (if applicable), regmask (if applicable).
608 MachineOperand CCMask(MBBI->getOperand(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(
615 const uint32_t *RegMask;
617 RegMask = MBBI->getOperand(3).getRegMask();
618
619 // Clear out all current operands.
620 int CCUse = MBBI->findRegisterUseOperandIdx(SystemZ::CC, TRI, false);
621 assert(CCUse >= 0 && "BRC/BCR must use CC");
622 Branch->removeOperand(CCUse);
623 // Remove regmask (sibcall).
625 Branch->removeOperand(3);
626 // Remove target (branch or sibcall).
629 Branch->removeOperand(2);
630 Branch->removeOperand(1);
631 Branch->removeOperand(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(FusedOpcode));
640 MachineInstrBuilder MIB(*Branch->getParent()->getParent(), Branch);
641 for (unsigned I = 0; I < SrcNOps; I++)
642 MIB.add(Compare.getOperand(I));
643 MIB.add(CCMask);
644
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(Target).addReg(SystemZ::CC,
651 }
652
654 MIB.add(Target);
655 MIB.addRegMask(RegMask);
656 }
657
658 // Clear any intervening kills of SrcReg and SrcReg2.
659 MBBI = Compare;
660 for (++MBBI; MBBI != MBBE; ++MBBI) {
661 MBBI->clearRegisterKills(SrcReg, TRI);
662 if (SrcReg2)
663 MBBI->clearRegisterKills(SrcReg2, TRI);
664 }
665 FusedComparisons += 1;
666 return true;
667}
668
669// Process all comparison instructions in MBB. Return true if something
670// changed.
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.
679 LiveRegs.addLiveOuts(MBB);
680 bool CompleteCCUsers = LiveRegs.available(SystemZ::CC);
683 while (MBBI != MBB.begin()) {
684 MachineInstr &MI = *--MBBI;
685 if (CompleteCCUsers && (MI.isCompare() || TII->isLoadAndTestAsCmp(MI)) &&
686 (optimizeCompareZero(MI, CCUsers, TII, TRI) ||
687 fuseCompareOperations(MI, CCUsers, TII, TRI))) {
688 ++MBBI;
689 MI.eraseFromParent();
690 Changed = true;
691 CCUsers.clear();
692 continue;
693 }
694
695 if (MI.definesRegister(SystemZ::CC, /*TRI=*/nullptr)) {
696 CCUsers.clear();
697 CompleteCCUsers = true;
698 }
699 if (MI.readsRegister(SystemZ::CC, /*TRI=*/nullptr) && CompleteCCUsers)
700 CCUsers.push_back(&MI);
701 }
702 return Changed;
703}
704
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)
713
714 return Changed;
715}
716
719 return new SystemZElimCompareLegacy();
720}
721
722bool SystemZElimCompareLegacy::runOnMachineFunction(MachineFunction &MF) {
723 if (skipFunction(MF.getFunction()))
724 return false;
725 return runElimCompareOnMF(MF);
726}
727
728PreservedAnalyses
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
MachineBasicBlock & MBB
MachineBasicBlock MachineBasicBlock::iterator MBBI
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
#define DEBUG_TYPE
const HexagonInstrInfo * TII
IRTranslator LLVM IR MI
CompareFlags
CompareIO flag bitmask values.
A set of register units.
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
Register Reg
Register const TargetRegisterInfo * TRI
Promote Memory to Register
Definition Mem2Reg.cpp:110
#define INITIALIZE_PASS(passName, arg, name, cfg, analysis)
Definition PassSupport.h:56
static bool contains(SmallPtrSetImpl< ConstantExpr * > &Cache, ConstantExpr *Expr, Constant *C)
Definition Value.cpp:479
This file defines the SmallVector class.
This file defines the 'Statistic' class, which is designed to be an easy way to expose various metric...
#define STATISTIC(VARNAME, DESC)
Definition Statistic.h:171
static bool optimizeCompareZero(MachineInstr &Compare, SmallVectorImpl< MachineInstr * > &CCUsers, const SystemZInstrInfo *TII, const TargetRegisterInfo *TRI)
static bool convertToLoadAndTrap(MachineInstr &MI, MachineInstr &Compare, SmallVectorImpl< MachineInstr * > &CCUsers, const SystemZInstrInfo *TII, const TargetRegisterInfo *TRI)
static bool resultTests(MachineInstr &MI, unsigned Reg)
static bool runElimCompareOnMF(MachineFunction &F)
static bool convertToLoadAndTest(MachineInstr &MI, MachineInstr &Compare, SmallVectorImpl< MachineInstr * > &CCUsers, const SystemZInstrInfo *TII, const TargetRegisterInfo *TRI)
static bool convertToLogical(MachineInstr &MI, MachineInstr &Compare, SmallVectorImpl< MachineInstr * > &CCUsers, const SystemZInstrInfo *TII, const TargetRegisterInfo *TRI)
static Reference getRegReferences(MachineInstr &MI, unsigned Reg, const TargetRegisterInfo *TRI)
static bool adjustCCMasksForInstr(MachineInstr &MI, MachineInstr &Compare, SmallVectorImpl< MachineInstr * > &CCUsers, unsigned ConvOpc, const SystemZInstrInfo *TII, const TargetRegisterInfo *TRI)
static bool fuseCompareOperations(MachineInstr &Compare, SmallVectorImpl< MachineInstr * > &CCUsers, const SystemZInstrInfo *TII, const TargetRegisterInfo *TRI)
static bool convertToBRCT(MachineInstr &MI, MachineInstr &Compare, SmallVectorImpl< MachineInstr * > &CCUsers, const SystemZInstrInfo *TII, const TargetRegisterInfo *TRI)
static bool processBlock(MachineBasicBlock &MBB, const SystemZInstrInfo *TII, const TargetRegisterInfo *TRI)
static bool isAddWithImmediate(unsigned Opcode)
Value * RHS
LLVM_ABI void setPreservesCFG()
This function should be called by the pass, iff they do not:
Definition Pass.cpp:280
Represents analyses that only rely on functions' control flow.
Definition Analysis.h:73
FunctionPass class - This class is used to implement most global optimizations.
Definition Pass.h:312
A set of register units used to track register liveness.
Describe properties that are true of each instruction in the target description file.
MachineInstrBundleIterator< MachineInstr, true > reverse_iterator
MachineInstrBundleIterator< MachineInstr > iterator
MachineFunctionPass - This class adapts the FunctionPass interface to allow convenient creation of pa...
void getAnalysisUsage(AnalysisUsage &AU) const override
getAnalysisUsage - Subclasses that override getAnalysisUsage must call this.
Function & getFunction()
Return the LLVM function that this machine code represents.
const MachineInstrBuilder & addReg(Register RegNo, RegState Flags={}, unsigned SubReg=0) const
Add a new virtual register operand.
const MachineInstrBuilder & add(const MachineOperand &MO) const
const MachineInstrBuilder & addRegMask(const uint32_t *Mask) const
Representation of each machine instruction.
MachineOperand class - Representation of each machine instruction operand.
int64_t getImm() const
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Definition Analysis.h:118
PreservedAnalyses & preserveSet()
Mark an analysis set as preserved.
Definition Analysis.h:151
Wrapper class representing virtual and physical registers.
Definition Register.h:20
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
PreservedAnalyses run(MachineFunction &MF, MachineFunctionAnalysisManager &MFAM)
TargetRegisterInfo base class - We assume that the target defines a static array of TargetRegisterDes...
Target - Wrapper for Target specific information.
The instances of the Type class are immutable: once they are created, they are never changed.
Definition Type.h:46
A Use represents the edge between a Value definition and its users.
Definition Use.h:35
Pass manager infrastructure for declaring and invalidating analyses.
static unsigned getCCValues(unsigned int Flags)
static unsigned getCompareZeroCCMask(unsigned int Flags)
const unsigned CCMASK_LOGICAL_ZERO
Definition SystemZ.h:64
const unsigned CCMASK_CMP_GT
Definition SystemZ.h:43
const unsigned CCMASK_CMP_EQ
Definition SystemZ.h:41
const unsigned CCMASK_ICMP
Definition SystemZ.h:53
const unsigned CCMASK_ARITH_OVERFLOW
Definition SystemZ.h:60
const unsigned CCMASK_CMP_LT
Definition SystemZ.h:42
const unsigned CCMASK_CMP_NE
Definition SystemZ.h:44
const unsigned CCMASK_LOGICAL_NONZERO
Definition SystemZ.h:65
This is an optimization pass for GlobalISel generic memory operations.
MachineInstrBuilder BuildMI(MachineFunction &MF, const MIMetadata &MIMD, const MCInstrDesc &MCID)
Builder interface. Specify how to create the initial instruction itself.
@ Dead
Unused definition.
iterator_range< T > make_range(T x, T y)
Convenience function for iterating over sub-ranges.
iterator_range< early_inc_iterator_impl< detail::IterOfRange< RangeT > > > make_early_inc_range(RangeT &&Range)
Make a range that does early increment to allow mutation of the underlying range without disrupting i...
Definition STLExtras.h:649
AnalysisManager< MachineFunction > MachineFunctionAnalysisManager
Op::Description Desc
LLVM_ABI PreservedAnalyses getMachineFunctionPassPreservedAnalyses()
Returns the minimum set of Analyses that all machine function passes must preserve.
@ Ref
The access may reference the value stored in memory.
Definition ModRef.h:32
@ Other
Any other memory.
Definition ModRef.h:68
bool operator|=(SparseBitVector< ElementSize > &LHS, const SparseBitVector< ElementSize > *RHS)
FunctionPass * createSystemZElimCompareLegacyPass(SystemZTargetMachine &TM)