LLVM 24.0.0git
PPCReduceCRLogicals.cpp
Go to the documentation of this file.
1//===---- PPCReduceCRLogicals.cpp - Reduce CR Bit Logical operations ------===//
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 aims to reduce the number of logical operations on bits in the CR
10// register. These instructions have a fairly high latency and only a single
11// pipeline at their disposal in modern PPC cores. Furthermore, they have a
12// tendency to occur in fairly small blocks where there's little opportunity
13// to hide the latency between the CR logical operation and its user.
14//
15//===---------------------------------------------------------------------===//
16
17#include "PPC.h"
18#include "PPCInstrInfo.h"
19#include "PPCTargetMachine.h"
20#include "llvm/ADT/Statistic.h"
28#include "llvm/Config/llvm-config.h"
30#include "llvm/Support/Debug.h"
31
32using namespace llvm;
33
34#define DEBUG_TYPE "ppc-reduce-cr-ops"
35
36STATISTIC(NumContainedSingleUseBinOps,
37 "Number of single-use binary CR logical ops contained in a block");
38STATISTIC(NumToSplitBlocks,
39 "Number of binary CR logical ops that can be used to split blocks");
40STATISTIC(TotalCRLogicals, "Number of CR logical ops.");
41STATISTIC(TotalNullaryCRLogicals,
42 "Number of nullary CR logical ops (CRSET/CRUNSET).");
43STATISTIC(TotalUnaryCRLogicals, "Number of unary CR logical ops.");
44STATISTIC(TotalBinaryCRLogicals, "Number of CR logical ops.");
45STATISTIC(NumBlocksSplitOnBinaryCROp,
46 "Number of blocks split on CR binary logical ops.");
47STATISTIC(NumNotSplitIdenticalOperands,
48 "Number of blocks not split due to operands being identical.");
49STATISTIC(NumNotSplitChainCopies,
50 "Number of blocks not split due to operands being chained copies.");
51STATISTIC(NumNotSplitWrongOpcode,
52 "Number of blocks not split due to the wrong opcode.");
53
54/// Given a basic block \p Successor that potentially contains PHIs, this
55/// function will look for any incoming values in the PHIs that are supposed to
56/// be coming from \p OrigMBB but whose definition is actually in \p NewMBB.
57/// Any such PHIs will be updated to reflect reality.
60 for (auto &MI : Successor->instrs()) {
61 if (!MI.isPHI())
62 continue;
63 // This is a really ugly-looking loop, but it was pillaged directly from
64 // MachineBasicBlock::transferSuccessorsAndUpdatePHIs().
65 for (unsigned i = 2, e = MI.getNumOperands() + 1; i != e; i += 2) {
66 MachineOperand &MO = MI.getOperand(i);
67 if (MO.getMBB() == OrigMBB) {
68 // Check if the instruction is actually defined in NewMBB.
69 if (MI.getOperand(i - 1).isReg()) {
70 MachineInstr *DefMI = MRI->getVRegDef(MI.getOperand(i - 1).getReg());
71 if (DefMI->getParent() == NewMBB ||
72 !OrigMBB->isSuccessor(Successor)) {
73 MO.setMBB(NewMBB);
74 break;
75 }
76 }
77 }
78 }
79 }
80}
81
82/// Given a basic block \p Successor that potentially contains PHIs, this
83/// function will look for PHIs that have an incoming value from \p OrigMBB
84/// and will add the same incoming value from \p NewMBB.
85/// NOTE: This should only be used if \p NewMBB is an immediate dominator of
86/// \p OrigMBB.
88 MachineBasicBlock *OrigMBB,
89 MachineBasicBlock *NewMBB,
91 assert(OrigMBB->isSuccessor(NewMBB) &&
92 "NewMBB must be a successor of OrigMBB");
93 for (auto &MI : Successor->instrs()) {
94 if (!MI.isPHI())
95 continue;
96 // This is a really ugly-looking loop, but it was pillaged directly from
97 // MachineBasicBlock::transferSuccessorsAndUpdatePHIs().
98 for (unsigned i = 2, e = MI.getNumOperands() + 1; i != e; i += 2) {
99 MachineOperand &MO = MI.getOperand(i);
100 if (MO.getMBB() == OrigMBB) {
101 MachineInstrBuilder MIB(*MI.getParent()->getParent(), &MI);
102 MIB.addReg(MI.getOperand(i - 1).getReg()).addMBB(NewMBB);
103 break;
104 }
105 }
106 }
107}
108
109namespace {
110struct BlockSplitInfo {
111 MachineInstr *OrigBranch;
112 MachineInstr *SplitBefore;
113 MachineInstr *SplitCond;
114 unsigned OrigSubreg;
115 unsigned SplitCondSubreg;
116 bool InvertNewBranch;
117 bool InvertOrigBranch;
118 bool BranchToFallThrough;
119 const MachineBranchProbabilityInfo *MBPI;
120 MachineInstr *MIToDelete;
121 MachineInstr *NewCond;
122 bool allInstrsInSameMBB() {
123 if (!OrigBranch || !SplitBefore || !SplitCond)
124 return false;
125 MachineBasicBlock *MBB = OrigBranch->getParent();
126 if (SplitBefore->getParent() != MBB || SplitCond->getParent() != MBB)
127 return false;
128 if (MIToDelete && MIToDelete->getParent() != MBB)
129 return false;
130 if (NewCond && NewCond->getParent() != MBB)
131 return false;
132 return true;
133 }
134};
135} // end anonymous namespace
136
137/// Splits a MachineBasicBlock to branch before \p SplitBefore. The original
138/// branch is \p OrigBranch. The target of the new branch can either be the same
139/// as the target of the original branch or the fallthrough successor of the
140/// original block as determined by \p BranchToFallThrough. The branch
141/// conditions will be inverted according to \p InvertNewBranch and
142/// \p InvertOrigBranch. If an instruction that previously fed the branch is to
143/// be deleted, it is provided in \p MIToDelete and \p NewCond will be used as
144/// the branch condition. The branch probabilities will be set if the
145/// MachineBranchProbabilityInfo isn't null.
146static bool splitMBB(BlockSplitInfo &BSI) {
147 assert(BSI.allInstrsInSameMBB() &&
148 "All instructions must be in the same block.");
149
150 MachineBasicBlock *ThisMBB = BSI.OrigBranch->getParent();
151 MachineFunction *MF = ThisMBB->getParent();
153 assert(MRI->isSSA() && "Can only do this while the function is in SSA form.");
154 if (ThisMBB->succ_size() != 2) {
156 dbgs() << "Don't know how to handle blocks that don't have exactly"
157 << " two successors.\n");
158 return false;
159 }
160
161 const PPCInstrInfo *TII = MF->getSubtarget<PPCSubtarget>().getInstrInfo();
162 unsigned OrigBROpcode = BSI.OrigBranch->getOpcode();
163 unsigned InvertedOpcode =
164 OrigBROpcode == PPC::BC
165 ? PPC::BCn
166 : OrigBROpcode == PPC::BCn
167 ? PPC::BC
168 : OrigBROpcode == PPC::BCLR ? PPC::BCLRn : PPC::BCLR;
169 unsigned NewBROpcode = BSI.InvertNewBranch ? InvertedOpcode : OrigBROpcode;
170 MachineBasicBlock *OrigTarget = BSI.OrigBranch->getOperand(1).getMBB();
171 MachineBasicBlock *OrigFallThrough = OrigTarget == *ThisMBB->succ_begin()
172 ? *ThisMBB->succ_rbegin()
173 : *ThisMBB->succ_begin();
174 MachineBasicBlock *NewBRTarget =
175 BSI.BranchToFallThrough ? OrigFallThrough : OrigTarget;
176
177 // It's impossible to know the precise branch probability after the split.
178 // But it still needs to be reasonable, the whole probability to original
179 // targets should not be changed.
180 // After split NewBRTarget will get two incoming edges. Assume P0 is the
181 // original branch probability to NewBRTarget, P1 and P2 are new branch
182 // probabilies to NewBRTarget after split. If the two edge frequencies are
183 // same, then
184 // F * P1 = F * P0 / 2 ==> P1 = P0 / 2
185 // F * (1 - P1) * P2 = F * P1 ==> P2 = P1 / (1 - P1)
186 BranchProbability ProbToNewTarget, ProbFallThrough; // Prob for new Br.
187 BranchProbability ProbOrigTarget, ProbOrigFallThrough; // Prob for orig Br.
188 ProbToNewTarget = ProbFallThrough = BranchProbability::getUnknown();
189 ProbOrigTarget = ProbOrigFallThrough = BranchProbability::getUnknown();
190 if (BSI.MBPI) {
191 if (BSI.BranchToFallThrough) {
192 ProbToNewTarget = BSI.MBPI->getEdgeProbability(ThisMBB, OrigFallThrough) / 2;
193 ProbFallThrough = ProbToNewTarget.getCompl();
194 ProbOrigFallThrough = ProbToNewTarget / ProbToNewTarget.getCompl();
195 ProbOrigTarget = ProbOrigFallThrough.getCompl();
196 } else {
197 ProbToNewTarget = BSI.MBPI->getEdgeProbability(ThisMBB, OrigTarget) / 2;
198 ProbFallThrough = ProbToNewTarget.getCompl();
199 ProbOrigTarget = ProbToNewTarget / ProbToNewTarget.getCompl();
200 ProbOrigFallThrough = ProbOrigTarget.getCompl();
201 }
202 }
203
204 // Create a new basic block.
206 const BasicBlock *LLVM_BB = ThisMBB->getBasicBlock();
208 MachineBasicBlock *NewMBB = MF->CreateMachineBasicBlock(LLVM_BB);
209 MF->insert(++It, NewMBB);
210
211 // Move everything after SplitBefore into the new block.
212 NewMBB->splice(NewMBB->end(), ThisMBB, InsertPoint, ThisMBB->end());
213 NewMBB->transferSuccessors(ThisMBB);
214 if (!ProbOrigTarget.isUnknown()) {
215 auto MBBI = find(NewMBB->successors(), OrigTarget);
216 NewMBB->setSuccProbability(MBBI, ProbOrigTarget);
217 MBBI = find(NewMBB->successors(), OrigFallThrough);
218 NewMBB->setSuccProbability(MBBI, ProbOrigFallThrough);
219 }
220
221 // Add the two successors to ThisMBB.
222 ThisMBB->addSuccessor(NewBRTarget, ProbToNewTarget);
223 ThisMBB->addSuccessor(NewMBB, ProbFallThrough);
224
225 // Add the branches to ThisMBB.
226 BuildMI(*ThisMBB, ThisMBB->end(), BSI.SplitBefore->getDebugLoc(),
227 TII->get(NewBROpcode))
228 .addReg(BSI.SplitCond->getOperand(0).getReg(), {}, BSI.SplitCondSubreg)
229 .addMBB(NewBRTarget);
230 BuildMI(*ThisMBB, ThisMBB->end(), BSI.SplitBefore->getDebugLoc(),
231 TII->get(PPC::B))
232 .addMBB(NewMBB);
233 if (BSI.MIToDelete)
234 BSI.MIToDelete->eraseFromParent();
235
236 // Change the condition on the original branch and invert it if requested.
237 auto FirstTerminator = NewMBB->getFirstTerminator();
238 if (BSI.NewCond) {
239 assert(FirstTerminator->getOperand(0).isReg() &&
240 "Can't update condition of unconditional branch.");
241 FirstTerminator->getOperand(0).setReg(BSI.NewCond->getOperand(0).getReg());
242 FirstTerminator->getOperand(0).setSubReg(BSI.OrigSubreg);
243 }
244 if (BSI.InvertOrigBranch)
245 FirstTerminator->setDesc(TII->get(InvertedOpcode));
246
247 // If any of the PHIs in the successors of NewMBB reference values that
248 // now come from NewMBB, they need to be updated.
249 for (auto *Succ : NewMBB->successors()) {
250 updatePHIs(Succ, ThisMBB, NewMBB, MRI);
251 }
252 addIncomingValuesToPHIs(NewBRTarget, ThisMBB, NewMBB, MRI);
253
254 // Physical registers (e.g. the carry bit) may be live across the split
255 // point, so NewMBB needs a live-in list.
258
259 // Set the call frame size on ThisMBB to the new basic blocks.
260 // See https://reviews.llvm.org/D156113.
261 NewMBB->setCallFrameSize(TII->getCallFrameSizeAt(ThisMBB->back()));
262
263 LLVM_DEBUG(dbgs() << "After splitting, ThisMBB:\n"; ThisMBB->dump());
264 LLVM_DEBUG(dbgs() << "NewMBB:\n"; NewMBB->dump());
265 LLVM_DEBUG(dbgs() << "New branch-to block:\n"; NewBRTarget->dump());
266 return true;
267}
268
269static bool isBinary(MachineInstr &MI) {
270 return MI.getNumOperands() == 3;
271}
272
273static bool isNullary(MachineInstr &MI) {
274 return MI.getNumOperands() == 1;
275}
276
277/// Given a CR logical operation \p CROp, branch opcode \p BROp as well as
278/// a flag to indicate if the first operand of \p CROp is used as the
279/// SplitBefore operand, determines whether either of the branches are to be
280/// inverted as well as whether the new target should be the original
281/// fall-through block.
282static void
283computeBranchTargetAndInversion(unsigned CROp, unsigned BROp, bool UsingDef1,
284 bool &InvertNewBranch, bool &InvertOrigBranch,
285 bool &TargetIsFallThrough) {
286 // The conditions under which each of the output operands should be [un]set
287 // can certainly be written much more concisely with just 3 if statements or
288 // ternary expressions. However, this provides a much clearer overview to the
289 // reader as to what is set for each <CROp, BROp, OpUsed> combination.
290 if (BROp == PPC::BC || BROp == PPC::BCLR) {
291 // Regular branches.
292 switch (CROp) {
293 default:
294 llvm_unreachable("Don't know how to handle this CR logical.");
295 case PPC::CROR:
296 InvertNewBranch = false;
297 InvertOrigBranch = false;
298 TargetIsFallThrough = false;
299 return;
300 case PPC::CRAND:
301 InvertNewBranch = true;
302 InvertOrigBranch = false;
303 TargetIsFallThrough = true;
304 return;
305 case PPC::CRNAND:
306 InvertNewBranch = true;
307 InvertOrigBranch = true;
308 TargetIsFallThrough = false;
309 return;
310 case PPC::CRNOR:
311 InvertNewBranch = false;
312 InvertOrigBranch = true;
313 TargetIsFallThrough = true;
314 return;
315 case PPC::CRORC:
316 InvertNewBranch = UsingDef1;
317 InvertOrigBranch = !UsingDef1;
318 TargetIsFallThrough = false;
319 return;
320 case PPC::CRANDC:
321 InvertNewBranch = !UsingDef1;
322 InvertOrigBranch = !UsingDef1;
323 TargetIsFallThrough = true;
324 return;
325 }
326 } else if (BROp == PPC::BCn || BROp == PPC::BCLRn) {
327 // Negated branches.
328 switch (CROp) {
329 default:
330 llvm_unreachable("Don't know how to handle this CR logical.");
331 case PPC::CROR:
332 InvertNewBranch = true;
333 InvertOrigBranch = false;
334 TargetIsFallThrough = true;
335 return;
336 case PPC::CRAND:
337 InvertNewBranch = false;
338 InvertOrigBranch = false;
339 TargetIsFallThrough = false;
340 return;
341 case PPC::CRNAND:
342 InvertNewBranch = false;
343 InvertOrigBranch = true;
344 TargetIsFallThrough = true;
345 return;
346 case PPC::CRNOR:
347 InvertNewBranch = true;
348 InvertOrigBranch = true;
349 TargetIsFallThrough = false;
350 return;
351 case PPC::CRORC:
352 InvertNewBranch = !UsingDef1;
353 InvertOrigBranch = !UsingDef1;
354 TargetIsFallThrough = true;
355 return;
356 case PPC::CRANDC:
357 InvertNewBranch = UsingDef1;
358 InvertOrigBranch = !UsingDef1;
359 TargetIsFallThrough = false;
360 return;
361 }
362 } else
363 llvm_unreachable("Don't know how to handle this branch.");
364}
365
366namespace {
367
368class PPCReduceCRLogicals : public MachineFunctionPass {
369public:
370 static char ID;
371 struct CRLogicalOpInfo {
372 MachineInstr *MI;
373 // FIXME: If chains of copies are to be handled, this should be a vector.
374 std::pair<MachineInstr*, MachineInstr*> CopyDefs;
375 std::pair<MachineInstr*, MachineInstr*> TrueDefs;
376 unsigned IsBinary : 1;
377 unsigned IsNullary : 1;
378 unsigned ContainedInBlock : 1;
379 unsigned FeedsISEL : 1;
380 unsigned FeedsBR : 1;
381 unsigned FeedsLogical : 1;
382 unsigned SingleUse : 1;
383 unsigned DefsSingleUse : 1;
384 unsigned SubregDef1;
385 unsigned SubregDef2;
386 CRLogicalOpInfo() : MI(nullptr), IsBinary(0), IsNullary(0),
387 ContainedInBlock(0), FeedsISEL(0), FeedsBR(0),
388 FeedsLogical(0), SingleUse(0), DefsSingleUse(1),
389 SubregDef1(0), SubregDef2(0) { }
390 void dump();
391 };
392
393private:
394 const PPCInstrInfo *TII = nullptr;
395 MachineFunction *MF = nullptr;
396 MachineRegisterInfo *MRI = nullptr;
397 const MachineBranchProbabilityInfo *MBPI = nullptr;
398
399 // A vector to contain all the CR logical operations
400 SmallVector<CRLogicalOpInfo, 16> AllCRLogicalOps;
401 void initialize(MachineFunction &MFParm);
402 void collectCRLogicals();
403 bool handleCROp(unsigned Idx);
404 bool splitBlockOnBinaryCROp(CRLogicalOpInfo &CRI);
405 static bool isCRLogical(MachineInstr &MI) {
406 unsigned Opc = MI.getOpcode();
407 return Opc == PPC::CRAND || Opc == PPC::CRNAND || Opc == PPC::CROR ||
408 Opc == PPC::CRXOR || Opc == PPC::CRNOR || Opc == PPC::CRNOT ||
409 Opc == PPC::CREQV || Opc == PPC::CRANDC || Opc == PPC::CRORC ||
410 Opc == PPC::CRSET || Opc == PPC::CRUNSET || Opc == PPC::CR6SET ||
411 Opc == PPC::CR6UNSET;
412 }
413 bool simplifyCode() {
414 bool Changed = false;
415 // Not using a range-based for loop here as the vector may grow while being
416 // operated on.
417 for (unsigned i = 0; i < AllCRLogicalOps.size(); i++)
418 Changed |= handleCROp(i);
419 return Changed;
420 }
421
422public:
423 PPCReduceCRLogicals() : MachineFunctionPass(ID) {}
424
425 MachineInstr *lookThroughCRCopy(unsigned Reg, unsigned &Subreg,
426 MachineInstr *&CpDef);
427 bool runOnMachineFunction(MachineFunction &MF) override {
428 if (skipFunction(MF.getFunction()))
429 return false;
430
431 // If the subtarget doesn't use CR bits, there's nothing to do.
432 const PPCSubtarget &STI = MF.getSubtarget<PPCSubtarget>();
433 if (!STI.useCRBits())
434 return false;
435
436 initialize(MF);
437 collectCRLogicals();
438 return simplifyCode();
439 }
440 CRLogicalOpInfo createCRLogicalOpInfo(MachineInstr &MI);
441 void getAnalysisUsage(AnalysisUsage &AU) const override {
442 AU.addRequired<MachineBranchProbabilityInfoWrapperPass>();
443 AU.addPreserved<MachineRegisterClassInfoWrapperPass>();
445 }
446};
447} // end anonymous namespace
448
449#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
450LLVM_DUMP_METHOD void PPCReduceCRLogicals::CRLogicalOpInfo::dump() {
451 dbgs() << "CRLogicalOpMI: ";
452 MI->dump();
453 dbgs() << "IsBinary: " << IsBinary << ", FeedsISEL: " << FeedsISEL;
454 dbgs() << ", FeedsBR: " << FeedsBR << ", FeedsLogical: ";
455 dbgs() << FeedsLogical << ", SingleUse: " << SingleUse;
456 dbgs() << ", DefsSingleUse: " << DefsSingleUse;
457 dbgs() << ", SubregDef1: " << SubregDef1 << ", SubregDef2: ";
458 dbgs() << SubregDef2 << ", ContainedInBlock: " << ContainedInBlock;
459 if (!IsNullary) {
460 dbgs() << "\nDefs:\n";
461 TrueDefs.first->dump();
462 }
463 if (IsBinary)
464 TrueDefs.second->dump();
465 dbgs() << "\n";
466 if (CopyDefs.first) {
467 dbgs() << "CopyDef1: ";
468 CopyDefs.first->dump();
469 }
470 if (CopyDefs.second) {
471 dbgs() << "CopyDef2: ";
472 CopyDefs.second->dump();
473 }
474}
475#endif
476
477PPCReduceCRLogicals::CRLogicalOpInfo
478PPCReduceCRLogicals::createCRLogicalOpInfo(MachineInstr &MIParam) {
479 CRLogicalOpInfo Ret;
480 Ret.MI = &MIParam;
481 // Get the defs
482 if (isNullary(MIParam)) {
483 Ret.IsNullary = 1;
484 Ret.TrueDefs = std::make_pair(nullptr, nullptr);
485 Ret.CopyDefs = std::make_pair(nullptr, nullptr);
486 } else {
487 MachineInstr *Def1 = lookThroughCRCopy(MIParam.getOperand(1).getReg(),
488 Ret.SubregDef1, Ret.CopyDefs.first);
489 Ret.SubregDef1 = MIParam.getOperand(1).getSubReg();
490 assert(Def1 && "Must be able to find a definition of operand 1.");
491 Ret.DefsSingleUse &=
493 Ret.DefsSingleUse &=
494 MRI->hasOneNonDBGUse(Ret.CopyDefs.first->getOperand(0).getReg());
495 if (isBinary(MIParam)) {
496 Ret.IsBinary = 1;
497 MachineInstr *Def2 = lookThroughCRCopy(MIParam.getOperand(2).getReg(),
498 Ret.SubregDef2,
499 Ret.CopyDefs.second);
500 Ret.SubregDef2 = MIParam.getOperand(2).getSubReg();
501 assert(Def2 && "Must be able to find a definition of operand 2.");
502 Ret.DefsSingleUse &=
504 Ret.DefsSingleUse &=
505 MRI->hasOneNonDBGUse(Ret.CopyDefs.second->getOperand(0).getReg());
506 Ret.TrueDefs = std::make_pair(Def1, Def2);
507 } else {
508 Ret.TrueDefs = std::make_pair(Def1, nullptr);
509 Ret.CopyDefs.second = nullptr;
510 }
511 }
512
513 Ret.ContainedInBlock = 1;
514 // Get the uses
515 for (MachineInstr &UseMI :
517 unsigned Opc = UseMI.getOpcode();
518 if (Opc == PPC::ISEL || Opc == PPC::ISEL8)
519 Ret.FeedsISEL = 1;
520 if (Opc == PPC::BC || Opc == PPC::BCn || Opc == PPC::BCLR ||
521 Opc == PPC::BCLRn)
522 Ret.FeedsBR = 1;
523 Ret.FeedsLogical = isCRLogical(UseMI);
524 if (UseMI.getParent() != MIParam.getParent())
525 Ret.ContainedInBlock = 0;
526 }
527 Ret.SingleUse = MRI->hasOneNonDBGUse(MIParam.getOperand(0).getReg()) ? 1 : 0;
528
529 // We now know whether all the uses of the CR logical are in the same block.
530 if (!Ret.IsNullary) {
531 Ret.ContainedInBlock &=
532 (MIParam.getParent() == Ret.TrueDefs.first->getParent());
533 if (Ret.IsBinary)
534 Ret.ContainedInBlock &=
535 (MIParam.getParent() == Ret.TrueDefs.second->getParent());
536 }
537 LLVM_DEBUG(Ret.dump());
538 if (Ret.IsBinary && Ret.ContainedInBlock && Ret.SingleUse) {
539 NumContainedSingleUseBinOps++;
540 if (Ret.FeedsBR && Ret.DefsSingleUse)
541 NumToSplitBlocks++;
542 }
543 return Ret;
544}
545
546/// Looks through a COPY instruction to the actual definition of the CR-bit
547/// register and returns the instruction that defines it.
548/// FIXME: This currently handles what is by-far the most common case:
549/// an instruction that defines a CR field followed by a single copy of a bit
550/// from that field into a virtual register. If chains of copies need to be
551/// handled, this should have a loop until a non-copy instruction is found.
552MachineInstr *PPCReduceCRLogicals::lookThroughCRCopy(unsigned Reg,
553 unsigned &Subreg,
554 MachineInstr *&CpDef) {
555 if (!Register::isVirtualRegister(Reg))
556 return nullptr;
557 MachineInstr *Copy = MRI->getVRegDef(Reg);
558 CpDef = Copy;
559 if (!Copy->isCopy())
560 return Copy;
561 Register CopySrc = Copy->getOperand(1).getReg();
562 if (!CopySrc.isVirtual()) {
563 const TargetRegisterInfo *TRI = &TII->getRegisterInfo();
564 // Loop backwards and return the first MI that modifies the physical CR Reg.
565 MachineBasicBlock::iterator Me = Copy, B = Copy->getParent()->begin();
566 while (Me != B)
567 if ((--Me)->modifiesRegister(CopySrc, TRI))
568 return &*Me;
569 return nullptr;
570 }
571 return MRI->getVRegDef(CopySrc);
572}
573
574void PPCReduceCRLogicals::initialize(MachineFunction &MFParam) {
575 MF = &MFParam;
576 MRI = &MF->getRegInfo();
577 TII = MF->getSubtarget<PPCSubtarget>().getInstrInfo();
578 MBPI = &getAnalysis<MachineBranchProbabilityInfoWrapperPass>().getMBPI();
579
580 AllCRLogicalOps.clear();
581}
582
583/// Contains all the implemented transformations on CR logical operations.
584/// For example, a binary CR logical can be used to split a block on its inputs,
585/// a unary CR logical might be used to change the condition code on a
586/// comparison feeding it. A nullary CR logical might simply be removable
587/// if the user of the bit it [un]sets can be transformed.
588bool PPCReduceCRLogicals::handleCROp(unsigned Idx) {
589 // We can definitely split a block on the inputs to a binary CR operation
590 // whose defs and (single) use are within the same block.
591 bool Changed = false;
592 CRLogicalOpInfo CRI = AllCRLogicalOps[Idx];
593 if (CRI.IsBinary && CRI.ContainedInBlock && CRI.SingleUse && CRI.FeedsBR &&
594 CRI.DefsSingleUse) {
595 Changed = splitBlockOnBinaryCROp(CRI);
596 if (Changed)
597 NumBlocksSplitOnBinaryCROp++;
598 }
599 return Changed;
600}
601
602/// Splits a block that contains a CR-logical operation that feeds a branch
603/// and whose operands are produced within the block.
604/// Example:
605/// %vr5<def> = CMPDI %vr2, 0; CRRC:%vr5 G8RC:%vr2
606/// %vr6<def> = COPY %vr5:sub_eq; CRBITRC:%vr6 CRRC:%vr5
607/// %vr7<def> = CMPDI %vr3, 0; CRRC:%vr7 G8RC:%vr3
608/// %vr8<def> = COPY %vr7:sub_eq; CRBITRC:%vr8 CRRC:%vr7
609/// %vr9<def> = CROR %vr6<kill>, %vr8<kill>; CRBITRC:%vr9,%vr6,%vr8
610/// BC %vr9<kill>, <BB#2>; CRBITRC:%vr9
611/// Becomes:
612/// %vr5<def> = CMPDI %vr2, 0; CRRC:%vr5 G8RC:%vr2
613/// %vr6<def> = COPY %vr5:sub_eq; CRBITRC:%vr6 CRRC:%vr5
614/// BC %vr6<kill>, <BB#2>; CRBITRC:%vr6
615///
616/// %vr7<def> = CMPDI %vr3, 0; CRRC:%vr7 G8RC:%vr3
617/// %vr8<def> = COPY %vr7:sub_eq; CRBITRC:%vr8 CRRC:%vr7
618/// BC %vr9<kill>, <BB#2>; CRBITRC:%vr9
619bool PPCReduceCRLogicals::splitBlockOnBinaryCROp(CRLogicalOpInfo &CRI) {
620 if (CRI.CopyDefs.first == CRI.CopyDefs.second) {
621 LLVM_DEBUG(dbgs() << "Unable to split as the two operands are the same\n");
622 NumNotSplitIdenticalOperands++;
623 return false;
624 }
625 if (CRI.TrueDefs.first->isCopy() || CRI.TrueDefs.second->isCopy() ||
626 CRI.TrueDefs.first->isPHI() || CRI.TrueDefs.second->isPHI()) {
628 dbgs() << "Unable to split because one of the operands is a PHI or "
629 "chain of copies.\n");
630 NumNotSplitChainCopies++;
631 return false;
632 }
633 // Note: keep in sync with computeBranchTargetAndInversion().
634 if (CRI.MI->getOpcode() != PPC::CROR &&
635 CRI.MI->getOpcode() != PPC::CRAND &&
636 CRI.MI->getOpcode() != PPC::CRNOR &&
637 CRI.MI->getOpcode() != PPC::CRNAND &&
638 CRI.MI->getOpcode() != PPC::CRORC &&
639 CRI.MI->getOpcode() != PPC::CRANDC) {
640 LLVM_DEBUG(dbgs() << "Unable to split blocks on this opcode.\n");
641 NumNotSplitWrongOpcode++;
642 return false;
643 }
644 LLVM_DEBUG(dbgs() << "Splitting the following CR op:\n"; CRI.dump());
645 MachineBasicBlock::iterator Def1It = CRI.TrueDefs.first;
646 MachineBasicBlock::iterator Def2It = CRI.TrueDefs.second;
647
648 bool UsingDef1 = false;
649 MachineInstr *SplitBefore = &*Def2It;
650 for (auto E = CRI.MI->getParent()->end(); Def2It != E; ++Def2It) {
651 if (Def1It == Def2It) { // Def2 comes before Def1.
652 SplitBefore = &*Def1It;
653 UsingDef1 = true;
654 break;
655 }
656 }
657
658 LLVM_DEBUG(dbgs() << "We will split the following block:\n";);
659 LLVM_DEBUG(CRI.MI->getParent()->dump());
660 LLVM_DEBUG(dbgs() << "Before instruction:\n"; SplitBefore->dump());
661
662 // Get the branch instruction.
663 MachineInstr *Branch =
664 &*MRI->use_instr_nodbg_begin(CRI.MI->getOperand(0).getReg());
665
666 // We want the new block to have no code in it other than the definition
667 // of the input to the CR logical and the CR logical itself. So we move
668 // those to the bottom of the block (just before the branch). Then we
669 // will split before the CR logical.
670 MachineBasicBlock *MBB = SplitBefore->getParent();
671 auto FirstTerminator = MBB->getFirstTerminator();
672 MachineBasicBlock::iterator FirstInstrToMove =
673 UsingDef1 ? CRI.TrueDefs.first : CRI.TrueDefs.second;
674 MachineBasicBlock::iterator SecondInstrToMove =
675 UsingDef1 ? CRI.CopyDefs.first : CRI.CopyDefs.second;
676
677 // The instructions that need to be moved are not guaranteed to be
678 // contiguous. Move them individually.
679 // FIXME: If one of the operands is a chain of (single use) copies, they
680 // can all be moved and we can still split.
681 MBB->splice(FirstTerminator, MBB, FirstInstrToMove);
682 if (FirstInstrToMove != SecondInstrToMove)
683 MBB->splice(FirstTerminator, MBB, SecondInstrToMove);
684 MBB->splice(FirstTerminator, MBB, CRI.MI);
685
686 unsigned Opc = CRI.MI->getOpcode();
687 bool InvertOrigBranch, InvertNewBranch, TargetIsFallThrough;
688 computeBranchTargetAndInversion(Opc, Branch->getOpcode(), UsingDef1,
689 InvertNewBranch, InvertOrigBranch,
690 TargetIsFallThrough);
691 MachineInstr *NewCond = CRI.CopyDefs.first;
692 MachineInstr *SplitCond = CRI.CopyDefs.second;
693 if (!UsingDef1) {
694 std::swap(NewCond, SplitCond);
695 std::swap(CRI.SubregDef1, CRI.SubregDef2);
696 }
697 LLVM_DEBUG(dbgs() << "We will " << (InvertNewBranch ? "invert" : "copy"));
698 LLVM_DEBUG(dbgs() << " the original branch and the target is the "
699 << (TargetIsFallThrough ? "fallthrough block\n"
700 : "orig. target block\n"));
701 LLVM_DEBUG(dbgs() << "Original branch instruction: "; Branch->dump());
702 BlockSplitInfo BSI{
703 Branch, SplitBefore, SplitCond, CRI.SubregDef1,
704 CRI.SubregDef2, InvertNewBranch, InvertOrigBranch, TargetIsFallThrough,
705 MBPI, CRI.MI, NewCond};
706 bool Changed = splitMBB(BSI);
707 // If we've split on a CR logical that is fed by a CR logical,
708 // recompute the source CR logical as it may be usable for splitting.
709 if (Changed) {
710 bool Input1CRlogical =
711 CRI.TrueDefs.first && isCRLogical(*CRI.TrueDefs.first);
712 bool Input2CRlogical =
713 CRI.TrueDefs.second && isCRLogical(*CRI.TrueDefs.second);
714 if (Input1CRlogical)
715 AllCRLogicalOps.push_back(createCRLogicalOpInfo(*CRI.TrueDefs.first));
716 if (Input2CRlogical)
717 AllCRLogicalOps.push_back(createCRLogicalOpInfo(*CRI.TrueDefs.second));
718 }
719 return Changed;
720}
721
722void PPCReduceCRLogicals::collectCRLogicals() {
723 for (MachineBasicBlock &MBB : *MF) {
724 for (MachineInstr &MI : MBB) {
725 if (isCRLogical(MI)) {
726 AllCRLogicalOps.push_back(createCRLogicalOpInfo(MI));
727 TotalCRLogicals++;
728 if (AllCRLogicalOps.back().IsNullary)
729 TotalNullaryCRLogicals++;
730 else if (AllCRLogicalOps.back().IsBinary)
731 TotalBinaryCRLogicals++;
732 else
733 TotalUnaryCRLogicals++;
734 }
735 }
736 }
737}
738
740 "PowerPC Reduce CR logical Operation", false, false)
742INITIALIZE_PASS_END(PPCReduceCRLogicals, DEBUG_TYPE,
743 "PowerPC Reduce CR logical Operation", false, false)
744
745char PPCReduceCRLogicals::ID = 0;
747llvm::createPPCReduceCRLogicalsPass() { return new PPCReduceCRLogicals(); }
MachineInstrBuilder & UseMI
MachineInstrBuilder MachineInstrBuilder & DefMI
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
MachineBasicBlock & MBB
MachineBasicBlock MachineBasicBlock::iterator MBBI
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
#define LLVM_DUMP_METHOD
Mark debug helper function definitions like dump() that should not be stripped from debug builds.
Definition Compiler.h:702
#define DEBUG_TYPE
const HexagonInstrInfo * TII
IRTranslator LLVM IR MI
This file implements the LivePhysRegs utility for tracking liveness of physical registers.
unsigned Opc
Register Reg
Register const TargetRegisterInfo * TRI
Promote Memory to Register
Definition Mem2Reg.cpp:110
static bool isBinary(MachineInstr &MI)
static bool isNullary(MachineInstr &MI)
static bool splitMBB(BlockSplitInfo &BSI)
Splits a MachineBasicBlock to branch before SplitBefore.
static void computeBranchTargetAndInversion(unsigned CROp, unsigned BROp, bool UsingDef1, bool &InvertNewBranch, bool &InvertOrigBranch, bool &TargetIsFallThrough)
Given a CR logical operation CROp, branch opcode BROp as well as a flag to indicate if the first oper...
static void addIncomingValuesToPHIs(MachineBasicBlock *Successor, MachineBasicBlock *OrigMBB, MachineBasicBlock *NewMBB, MachineRegisterInfo *MRI)
Given a basic block Successor that potentially contains PHIs, this function will look for PHIs that h...
static void updatePHIs(MachineBasicBlock *Successor, MachineBasicBlock *OrigMBB, MachineBasicBlock *NewMBB, MachineRegisterInfo *MRI)
Given a basic block Successor that potentially contains PHIs, this function will look for any incomin...
#define INITIALIZE_PASS_DEPENDENCY(depName)
Definition PassSupport.h:42
#define INITIALIZE_PASS_END(passName, arg, name, cfg, analysis)
Definition PassSupport.h:44
#define INITIALIZE_PASS_BEGIN(passName, arg, name, cfg, analysis)
Definition PassSupport.h:39
MachineRegisterInfo & MRI
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:170
#define LLVM_DEBUG(...)
Definition Debug.h:119
static void initialize(TargetLibraryInfoImpl &TLI, const Triple &T, const llvm::StringTable &StandardNames, VectorLibrary VecLib)
Initialize the set of available library functions based on the specified target triple.
AnalysisUsage & addRequired()
AnalysisUsage & addPreserved()
Add the specified Pass class to the set of analyses preserved by this pass.
LLVM Basic Block Representation.
Definition BasicBlock.h:61
static constexpr BranchProbability getUnknown()
BranchProbability getCompl() const
FunctionPass class - This class is used to implement most global optimizations.
Definition Pass.h:312
const HexagonRegisterInfo & getRegisterInfo() const
A set of physical registers with utility functions to track liveness when walking backward/forward th...
LLVM_ABI void transferSuccessors(MachineBasicBlock *FromMBB)
Transfers all the successors from MBB to this machine basic block (i.e., copies all the successors Fr...
void setCallFrameSize(unsigned N)
Set the call frame size on entry to this basic block.
const BasicBlock * getBasicBlock() const
Return the LLVM basic block that this instance corresponded to originally.
LLVM_ABI void setSuccProbability(succ_iterator I, BranchProbability Prob)
Set successor probability of a given iterator.
LLVM_ABI iterator getFirstTerminator()
Returns an iterator to the first terminator instruction of this basic block.
LLVM_ABI void dump() const
LLVM_ABI void addSuccessor(MachineBasicBlock *Succ, BranchProbability Prob=BranchProbability::getUnknown())
Add Succ as a successor of this MachineBasicBlock.
succ_reverse_iterator succ_rbegin()
const MachineFunction * getParent() const
Return the MachineFunction containing this basic block.
iterator_range< succ_iterator > successors()
LLVM_ABI bool isSuccessor(const MachineBasicBlock *MBB) const
Return true if the specified MBB is a successor of this block.
void splice(iterator Where, MachineBasicBlock *Other, iterator From)
Take an instruction from MBB 'Other' at the position From, and insert it into this MBB right before '...
MachineInstrBundleIterator< MachineInstr > iterator
LLVM_ABI BranchProbability getEdgeProbability(const MachineBasicBlock *Src, const MachineBasicBlock *Dst) const
Analysis pass which computes a MachineDominatorTree.
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.
const TargetSubtargetInfo & getSubtarget() const
getSubtarget - Return the subtarget for which this machine code is being compiled.
MachineRegisterInfo & getRegInfo()
getRegInfo - Return information about the registers currently in use.
BasicBlockListType::iterator iterator
MachineBasicBlock * CreateMachineBasicBlock(const BasicBlock *BB=nullptr, std::optional< UniqueBBID > BBID=std::nullopt)
CreateMachineInstr - Allocate a new MachineInstr.
void insert(iterator MBBI, MachineBasicBlock *MBB)
const MachineInstrBuilder & addReg(Register RegNo, RegState Flags={}, unsigned SubReg=0) const
Add a new virtual register operand.
const MachineInstrBuilder & addMBB(MachineBasicBlock *MBB, unsigned TargetFlags=0) const
Representation of each machine instruction.
unsigned getOpcode() const
Returns the opcode of this MachineInstr.
const MachineBasicBlock * getParent() const
const DebugLoc & getDebugLoc() const
Returns the debug location id of this MachineInstr.
LLVM_ABI void dump() const
const MachineOperand & getOperand(unsigned i) const
LLVM_ABI MachineInstrBundleIterator< MachineInstr > eraseFromParent()
Unlink 'this' from the containing basic block and delete it.
MachineOperand class - Representation of each machine instruction operand.
unsigned getSubReg() const
MachineBasicBlock * getMBB() const
void setMBB(MachineBasicBlock *MBB)
Register getReg() const
getReg - Returns the register number.
MachineRegisterInfo - Keep track of information for virtual and physical registers,...
LLVM_ABI bool hasOneNonDBGUse(Register RegNo) const
hasOneNonDBGUse - Return true if there is exactly one non-Debug use of the specified register.
LLVM_ABI LLVM_READONLY MachineInstr * getVRegDef(Register Reg) const
getVRegDef - Return the machine instr that defines the specified virtual register or null if none is ...
use_instr_nodbg_iterator use_instr_nodbg_begin(Register RegNo) const
iterator_range< use_instr_nodbg_iterator > use_nodbg_instructions(Register Reg) const
constexpr bool isVirtual() const
Return true if the specified register number is in the virtual register namespace.
Definition Register.h:79
void push_back(const T &Elt)
self_iterator getIterator()
Definition ilist_node.h:123
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
This is an optimization pass for GlobalISel generic memory operations.
void dump(const SparseBitVector< ElementSize > &LHS, raw_ostream &out)
auto find(R &&Range, const T &Val)
Provide wrappers to std::find which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1781
MachineInstrBuilder BuildMI(MachineFunction &MF, const MIMetadata &MIMD, const MCInstrDesc &MCID)
Builder interface. Specify how to create the initial instruction itself.
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:209
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
FunctionPass * createPPCReduceCRLogicalsPass()
LLVM_ABI void computeAndAddLiveIns(LivePhysRegs &LiveRegs, MachineBasicBlock &MBB)
Convenience function combining computeLiveIns() and addLiveIns().
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
Definition BitVector.h:881