LLVM 24.0.0git
PPCMIPeephole.cpp
Go to the documentation of this file.
1//===-------------- PPCMIPeephole.cpp - MI Peephole Cleanups -------------===//
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 performs peephole optimizations to clean up ugly code
10// sequences at the MachineInstruction layer. It runs at the end of
11// the SSA phases, following VSX swap removal. A pass of dead code
12// elimination follows this one for quick clean-up of any dead
13// instructions introduced here. Although we could do this as callbacks
14// from the generic peephole pass, this would have a couple of bad
15// effects: it might remove optimization opportunities for VSX swap
16// removal, and it would miss cleanups made possible following VSX
17// swap removal.
18//
19// NOTE: We run the verifier after this pass in Asserts/Debug builds so it
20// is important to keep the code valid after transformations.
21// Common causes of errors stem from violating the contract specified
22// by kill flags. Whenever a transformation changes the live range of
23// a register, that register should be added to the work list using
24// addRegToUpdate(RegsToUpdate, <Reg>). Furthermore, if a transformation
25// is changing the definition of a register (i.e. removing the single
26// definition of the original vreg), it needs to provide a dummy
27// definition of that register using addDummyDef(<MBB>, <Reg>).
28//===---------------------------------------------------------------------===//
29
32#include "PPC.h"
33#include "PPCInstrInfo.h"
35#include "PPCTargetMachine.h"
36#include "llvm/ADT/Statistic.h"
47#include "llvm/Support/Debug.h"
49
50using namespace llvm;
51
52#define DEBUG_TYPE "ppc-mi-peepholes"
53
54STATISTIC(RemoveTOCSave, "Number of TOC saves removed");
55STATISTIC(MultiTOCSaves,
56 "Number of functions with multiple TOC saves that must be kept");
57STATISTIC(NumTOCSavesInPrologue, "Number of TOC saves placed in the prologue");
58STATISTIC(NumEliminatedSExt, "Number of eliminated sign-extensions");
59STATISTIC(NumEliminatedZExt, "Number of eliminated zero-extensions");
60STATISTIC(NumOptADDLIs, "Number of optimized ADD instruction fed by LI");
61STATISTIC(NumConvertedToImmediateForm,
62 "Number of instructions converted to their immediate form");
63STATISTIC(NumFunctionsEnteredInMIPeephole,
64 "Number of functions entered in PPC MI Peepholes");
65STATISTIC(NumFixedPointIterations,
66 "Number of fixed-point iterations converting reg-reg instructions "
67 "to reg-imm ones");
68STATISTIC(NumRotatesCollapsed,
69 "Number of pairs of rotate left, clear left/right collapsed");
70STATISTIC(NumEXTSWAndSLDICombined,
71 "Number of pairs of EXTSW and SLDI combined as EXTSWSLI");
72STATISTIC(NumLoadImmZeroFoldedAndRemoved,
73 "Number of LI(8) reg, 0 that are folded to r0 and removed");
74
75static cl::opt<bool>
76FixedPointRegToImm("ppc-reg-to-imm-fixed-point", cl::Hidden, cl::init(true),
77 cl::desc("Iterate to a fixed point when attempting to "
78 "convert reg-reg instructions to reg-imm"));
79
80static cl::opt<bool>
81ConvertRegReg("ppc-convert-rr-to-ri", cl::Hidden, cl::init(true),
82 cl::desc("Convert eligible reg+reg instructions to reg+imm"));
83
84static cl::opt<bool>
85 EnableSExtElimination("ppc-eliminate-signext",
86 cl::desc("enable elimination of sign-extensions"),
87 cl::init(true), cl::Hidden);
88
89static cl::opt<bool>
90 EnableZExtElimination("ppc-eliminate-zeroext",
91 cl::desc("enable elimination of zero-extensions"),
92 cl::init(true), cl::Hidden);
93
94static cl::opt<bool>
95 EnableTrapOptimization("ppc-opt-conditional-trap",
96 cl::desc("enable optimization of conditional traps"),
97 cl::init(false), cl::Hidden);
98
100 PeepholeXToICounter, "ppc-xtoi-peephole",
101 "Controls whether PPC reg+reg to reg+imm peephole is performed on a MI");
102
103DEBUG_COUNTER(PeepholePerOpCounter, "ppc-per-op-peephole",
104 "Controls whether PPC per opcode peephole is performed on a MI");
105
106namespace {
107
108struct PPCMIPeephole : public MachineFunctionPass {
109
110 static char ID;
111 const PPCInstrInfo *TII;
112 MachineFunction *MF;
114
115 PPCMIPeephole() : MachineFunctionPass(ID) {}
116
117private:
118 MachineDominatorTree *MDT;
119 MachinePostDominatorTree *MPDT;
120 MachineBlockFrequencyInfo *MBFI;
121 BlockFrequency EntryFreq;
122 SmallSet<Register, 16> RegsToUpdate;
123
124 // Initialize class variables.
125 void initialize(MachineFunction &MFParm);
126
127 // Perform peepholes.
128 bool simplifyCode();
129
130 // Perform peepholes.
131 bool eliminateRedundantCompare();
132 bool eliminateRedundantTOCSaves(std::map<MachineInstr *, bool> &TOCSaves);
133 bool combineSEXTAndSHL(MachineInstr &MI, MachineInstr *&ToErase);
134 bool emitRLDICWhenLoweringJumpTables(MachineInstr &MI,
135 MachineInstr *&ToErase);
136 void UpdateTOCSaves(std::map<MachineInstr *, bool> &TOCSaves,
137 MachineInstr *MI);
138
139 // A number of transformations will eliminate the definition of a register
140 // as all of its uses will be removed. However, this can leave a register
141 // used with no reaching definition until DCE removes the dead uses. Such
142 // transformations should use this function to provide a dummy definition of
143 // the register that will simply be removed by DCE.
144 void addDummyDef(MachineBasicBlock &MBB, MachineInstr *At, Register Reg) {
145 BuildMI(MBB, At, At->getDebugLoc(), TII->get(PPC::IMPLICIT_DEF), Reg);
146 }
147 void addRegToUpdateWithLine(Register Reg, int Line);
148 void convertUnprimedAccPHIs(const PPCInstrInfo *TII, MachineRegisterInfo *MRI,
149 SmallVectorImpl<MachineInstr *> &PHIs,
150 Register Dst);
151
152public:
153 void getAnalysisUsage(AnalysisUsage &AU) const override {
154 AU.addRequired<MachineDominatorTreeWrapperPass>();
155 AU.addRequired<MachinePostDominatorTreeWrapperPass>();
156 AU.addRequired<MachineBlockFrequencyInfoWrapperPass>();
157 AU.addPreserved<MachineDominatorTreeWrapperPass>();
158 AU.addPreserved<MachinePostDominatorTreeWrapperPass>();
159 AU.addPreserved<MachineBlockFrequencyInfoWrapperPass>();
160 AU.addPreserved<MachineRegisterClassInfoWrapperPass>();
162 }
163
164 // Main entry point for this pass.
165 bool runOnMachineFunction(MachineFunction &MF) override {
166 initialize(MF);
167 // At this point, TOC pointer should not be used in a function that uses
168 // PC-Relative addressing.
169 assert((MF.getRegInfo().use_empty(PPC::X2) ||
170 !MF.getSubtarget<PPCSubtarget>().isUsingPCRelativeCalls()) &&
171 "TOC pointer used in a function using PC-Relative addressing!");
172 if (skipFunction(MF.getFunction()))
173 return false;
174 return simplifyCode();
175 }
176};
177
178#define addRegToUpdate(R) addRegToUpdateWithLine(R, __LINE__)
179void PPCMIPeephole::addRegToUpdateWithLine(Register Reg, int Line) {
180 if (!Reg.isVirtual())
181 return;
182 if (RegsToUpdate.insert(Reg).second)
183 LLVM_DEBUG(dbgs() << "Adding register: " << printReg(Reg) << " on line "
184 << Line << " for re-computation of kill flags\n");
185}
186
187// Initialize class variables.
188void PPCMIPeephole::initialize(MachineFunction &MFParm) {
189 MF = &MFParm;
190 MRI = &MF->getRegInfo();
191 MDT = &getAnalysis<MachineDominatorTreeWrapperPass>().getDomTree();
192 MPDT = &getAnalysis<MachinePostDominatorTreeWrapperPass>().getPostDomTree();
193 MBFI = &getAnalysis<MachineBlockFrequencyInfoWrapperPass>().getMBFI();
194 EntryFreq = MBFI->getEntryFreq();
195 TII = MF->getSubtarget<PPCSubtarget>().getInstrInfo();
196 RegsToUpdate.clear();
197 LLVM_DEBUG(dbgs() << "*** PowerPC MI peephole pass ***\n\n");
198 LLVM_DEBUG(MF->dump());
199}
200
201static MachineInstr *getVRegDefOrNull(MachineOperand *Op,
202 MachineRegisterInfo *MRI) {
203 assert(Op && "Invalid Operand!");
204 if (!Op->isReg())
205 return nullptr;
206
207 Register Reg = Op->getReg();
208 if (!Reg.isVirtual())
209 return nullptr;
210
211 return MRI->getVRegDef(Reg);
212}
213
214// This function returns number of known zero bits in output of MI
215// starting from the most significant bit.
216static unsigned getKnownLeadingZeroCount(const unsigned Reg,
217 const PPCInstrInfo *TII,
218 const MachineRegisterInfo *MRI) {
219 MachineInstr *MI = MRI->getVRegDef(Reg);
220 unsigned Opcode = MI->getOpcode();
221 if (Opcode == PPC::RLDICL || Opcode == PPC::RLDICL_rec ||
222 Opcode == PPC::RLDCL || Opcode == PPC::RLDCL_rec)
223 return MI->getOperand(3).getImm();
224
225 if ((Opcode == PPC::RLDIC || Opcode == PPC::RLDIC_rec) &&
226 MI->getOperand(3).getImm() <= 63 - MI->getOperand(2).getImm())
227 return MI->getOperand(3).getImm();
228
229 if ((Opcode == PPC::RLWINM || Opcode == PPC::RLWINM_rec ||
230 Opcode == PPC::RLWNM || Opcode == PPC::RLWNM_rec ||
231 Opcode == PPC::RLWINM8 || Opcode == PPC::RLWNM8) &&
232 MI->getOperand(3).getImm() <= MI->getOperand(4).getImm())
233 return 32 + MI->getOperand(3).getImm();
234
235 if (Opcode == PPC::ANDI_rec) {
236 uint16_t Imm = MI->getOperand(2).getImm();
237 return 48 + llvm::countl_zero(Imm);
238 }
239
240 if (Opcode == PPC::CNTLZW || Opcode == PPC::CNTLZW_rec ||
241 Opcode == PPC::CNTTZW || Opcode == PPC::CNTTZW_rec ||
242 Opcode == PPC::CNTLZW8 || Opcode == PPC::CNTTZW8)
243 // The result ranges from 0 to 32.
244 return 58;
245
246 if (Opcode == PPC::CNTLZD || Opcode == PPC::CNTLZD_rec ||
247 Opcode == PPC::CNTTZD || Opcode == PPC::CNTTZD_rec)
248 // The result ranges from 0 to 64.
249 return 57;
250
251 if (Opcode == PPC::LHZ || Opcode == PPC::LHZX ||
252 Opcode == PPC::LHZ8 || Opcode == PPC::LHZX8 ||
253 Opcode == PPC::LHZU || Opcode == PPC::LHZUX ||
254 Opcode == PPC::LHZU8 || Opcode == PPC::LHZUX8)
255 return 48;
256
257 if (Opcode == PPC::LBZ || Opcode == PPC::LBZX ||
258 Opcode == PPC::LBZ8 || Opcode == PPC::LBZX8 ||
259 Opcode == PPC::LBZU || Opcode == PPC::LBZUX ||
260 Opcode == PPC::LBZU8 || Opcode == PPC::LBZUX8)
261 return 56;
262
263 if (Opcode == PPC::AND || Opcode == PPC::AND8 || Opcode == PPC::AND_rec ||
264 Opcode == PPC::AND8_rec)
265 return std::max(
266 getKnownLeadingZeroCount(MI->getOperand(1).getReg(), TII, MRI),
267 getKnownLeadingZeroCount(MI->getOperand(2).getReg(), TII, MRI));
268
269 if (Opcode == PPC::OR || Opcode == PPC::OR8 || Opcode == PPC::XOR ||
270 Opcode == PPC::XOR8 || Opcode == PPC::OR_rec ||
271 Opcode == PPC::OR8_rec || Opcode == PPC::XOR_rec ||
272 Opcode == PPC::XOR8_rec)
273 return std::min(
274 getKnownLeadingZeroCount(MI->getOperand(1).getReg(), TII, MRI),
275 getKnownLeadingZeroCount(MI->getOperand(2).getReg(), TII, MRI));
276
277 if (TII->isZeroExtended(Reg, MRI))
278 return 32;
279
280 return 0;
281}
282
283// This function maintains a map for the pairs <TOC Save Instr, Keep>
284// Each time a new TOC save is encountered, it checks if any of the existing
285// ones are dominated by the new one. If so, it marks the existing one as
286// redundant by setting it's entry in the map as false. It then adds the new
287// instruction to the map with either true or false depending on if any
288// existing instructions dominated the new one.
289void PPCMIPeephole::UpdateTOCSaves(
290 std::map<MachineInstr *, bool> &TOCSaves, MachineInstr *MI) {
291 assert(TII->isTOCSaveMI(*MI) && "Expecting a TOC save instruction here");
292 // FIXME: Saving TOC in prologue hasn't been implemented well in AIX ABI part,
293 // here only support it under ELFv2.
294 if (MF->getSubtarget<PPCSubtarget>().isELFv2ABI()) {
295 PPCFunctionInfo *FI = MF->getInfo<PPCFunctionInfo>();
296
297 MachineBasicBlock *Entry = &MF->front();
298 BlockFrequency CurrBlockFreq = MBFI->getBlockFreq(MI->getParent());
299
300 // If the block in which the TOC save resides is in a block that
301 // post-dominates Entry, or a block that is hotter than entry (keep in mind
302 // that early MachineLICM has already run so the TOC save won't be hoisted)
303 // we can just do the save in the prologue.
304 if (CurrBlockFreq > EntryFreq || MPDT->dominates(MI->getParent(), Entry))
305 FI->setMustSaveTOC(true);
306
307 // If we are saving the TOC in the prologue, all the TOC saves can be
308 // removed from the code.
309 if (FI->mustSaveTOC()) {
310 for (auto &TOCSave : TOCSaves)
311 TOCSave.second = false;
312 // Add new instruction to map.
313 TOCSaves[MI] = false;
314 return;
315 }
316 }
317
318 bool Keep = true;
319 for (auto &I : TOCSaves) {
320 MachineInstr *CurrInst = I.first;
321 // If new instruction dominates an existing one, mark existing one as
322 // redundant.
323 if (I.second && MDT->dominates(MI, CurrInst))
324 I.second = false;
325 // Check if the new instruction is redundant.
326 if (MDT->dominates(CurrInst, MI)) {
327 Keep = false;
328 break;
329 }
330 }
331 // Add new instruction to map.
332 TOCSaves[MI] = Keep;
333}
334
335// This function returns a list of all PHI nodes in the tree starting from
336// the RootPHI node. We perform a BFS traversal to get an ordered list of nodes.
337// The list initially only contains the root PHI. When we visit a PHI node, we
338// add it to the list. We continue to look for other PHI node operands while
339// there are nodes to visit in the list. The function returns false if the
340// optimization cannot be applied on this tree.
341static bool collectUnprimedAccPHIs(MachineRegisterInfo *MRI,
342 MachineInstr *RootPHI,
343 SmallVectorImpl<MachineInstr *> &PHIs) {
344 PHIs.push_back(RootPHI);
345 unsigned VisitedIndex = 0;
346 while (VisitedIndex < PHIs.size()) {
347 MachineInstr *VisitedPHI = PHIs[VisitedIndex];
348 for (unsigned PHIOp = 1, NumOps = VisitedPHI->getNumOperands();
349 PHIOp != NumOps; PHIOp += 2) {
350 Register RegOp = VisitedPHI->getOperand(PHIOp).getReg();
351 if (!RegOp.isVirtual())
352 return false;
353 MachineInstr *Instr = MRI->getVRegDef(RegOp);
354 // While collecting the PHI nodes, we check if they can be converted (i.e.
355 // all the operands are either copies, implicit defs or PHI nodes).
356 unsigned Opcode = Instr->getOpcode();
357 if (Opcode == PPC::COPY) {
358 Register Reg = Instr->getOperand(1).getReg();
359 if (!Reg.isVirtual() || MRI->getRegClass(Reg) != &PPC::ACCRCRegClass)
360 return false;
361 } else if (Opcode != PPC::IMPLICIT_DEF && Opcode != PPC::PHI)
362 return false;
363 // If we detect a cycle in the PHI nodes, we exit. It would be
364 // possible to change cycles as well, but that would add a lot
365 // of complexity for a case that is unlikely to occur with MMA
366 // code.
367 if (Opcode != PPC::PHI)
368 continue;
369 if (llvm::is_contained(PHIs, Instr))
370 return false;
371 PHIs.push_back(Instr);
372 }
373 VisitedIndex++;
374 }
375 return true;
376}
377
378// This function changes the unprimed accumulator PHI nodes in the PHIs list to
379// primed accumulator PHI nodes. The list is traversed in reverse order to
380// change all the PHI operands of a PHI node before changing the node itself.
381// We keep a map to associate each changed PHI node to its non-changed form.
382void PPCMIPeephole::convertUnprimedAccPHIs(
383 const PPCInstrInfo *TII, MachineRegisterInfo *MRI,
384 SmallVectorImpl<MachineInstr *> &PHIs, Register Dst) {
385 DenseMap<MachineInstr *, MachineInstr *> ChangedPHIMap;
386 for (MachineInstr *PHI : llvm::reverse(PHIs)) {
388 // We check if the current PHI node can be changed by looking at its
389 // operands. If all the operands are either copies from primed
390 // accumulators, implicit definitions or other unprimed accumulator
391 // PHI nodes, we change it.
392 for (unsigned PHIOp = 1, NumOps = PHI->getNumOperands(); PHIOp != NumOps;
393 PHIOp += 2) {
394 Register RegOp = PHI->getOperand(PHIOp).getReg();
395 MachineInstr *PHIInput = MRI->getVRegDef(RegOp);
396 unsigned Opcode = PHIInput->getOpcode();
397 assert((Opcode == PPC::COPY || Opcode == PPC::IMPLICIT_DEF ||
398 Opcode == PPC::PHI) &&
399 "Unexpected instruction");
400 if (Opcode == PPC::COPY) {
401 assert(MRI->getRegClass(PHIInput->getOperand(1).getReg()) ==
402 &PPC::ACCRCRegClass &&
403 "Unexpected register class");
404 PHIOps.push_back({PHIInput->getOperand(1), PHI->getOperand(PHIOp + 1)});
405 } else if (Opcode == PPC::IMPLICIT_DEF) {
406 Register AccReg = MRI->createVirtualRegister(&PPC::ACCRCRegClass);
407 BuildMI(*PHIInput->getParent(), PHIInput, PHIInput->getDebugLoc(),
408 TII->get(PPC::IMPLICIT_DEF), AccReg);
409 PHIOps.push_back({MachineOperand::CreateReg(AccReg, false),
410 PHI->getOperand(PHIOp + 1)});
411 } else if (Opcode == PPC::PHI) {
412 // We found a PHI operand. At this point we know this operand
413 // has already been changed so we get its associated changed form
414 // from the map.
415 assert(ChangedPHIMap.count(PHIInput) == 1 &&
416 "This PHI node should have already been changed.");
417 MachineInstr *PrimedAccPHI = ChangedPHIMap.lookup(PHIInput);
419 PrimedAccPHI->getOperand(0).getReg(), false),
420 PHI->getOperand(PHIOp + 1)});
421 }
422 }
423 Register AccReg = Dst;
424 // If the PHI node we are changing is the root node, the register it defines
425 // will be the destination register of the original copy (of the PHI def).
426 // For all other PHI's in the list, we need to create another primed
427 // accumulator virtual register as the PHI will no longer define the
428 // unprimed accumulator.
429 if (PHI != PHIs[0])
430 AccReg = MRI->createVirtualRegister(&PPC::ACCRCRegClass);
431 MachineInstrBuilder NewPHI = BuildMI(
432 *PHI->getParent(), PHI, PHI->getDebugLoc(), TII->get(PPC::PHI), AccReg);
433 for (auto RegMBB : PHIOps) {
434 NewPHI.add(RegMBB.first).add(RegMBB.second);
435 if (MRI->isSSA())
436 addRegToUpdate(RegMBB.first.getReg());
437 }
438 // The liveness of old PHI and new PHI have to be updated.
439 addRegToUpdate(PHI->getOperand(0).getReg());
440 addRegToUpdate(AccReg);
441 ChangedPHIMap[PHI] = NewPHI.getInstr();
442 LLVM_DEBUG(dbgs() << "Converting PHI: ");
443 LLVM_DEBUG(PHI->dump());
444 LLVM_DEBUG(dbgs() << "To: ");
445 LLVM_DEBUG(NewPHI.getInstr()->dump());
446 }
447}
448
449// Perform peephole optimizations.
450bool PPCMIPeephole::simplifyCode() {
451 bool Simplified = false;
452 bool TrapOpt = false;
453 MachineInstr* ToErase = nullptr;
454 std::map<MachineInstr *, bool> TOCSaves;
455 const TargetRegisterInfo *TRI = &TII->getRegisterInfo();
456 NumFunctionsEnteredInMIPeephole++;
457 if (ConvertRegReg) {
458 // Fixed-point conversion of reg/reg instructions fed by load-immediate
459 // into reg/imm instructions. FIXME: This is expensive, control it with
460 // an option.
461 bool SomethingChanged = false;
462 do {
463 NumFixedPointIterations++;
464 SomethingChanged = false;
465 for (MachineBasicBlock &MBB : *MF) {
466 for (MachineInstr &MI : MBB) {
467 if (MI.isDebugInstr())
468 continue;
469
470 if (!DebugCounter::shouldExecute(PeepholeXToICounter))
471 continue;
472
473 SmallSet<Register, 4> RRToRIRegsToUpdate;
474 if (!TII->convertToImmediateForm(MI, RRToRIRegsToUpdate))
475 continue;
476 for (Register R : RRToRIRegsToUpdate)
478 // The updated instruction may now have new register operands.
479 // Conservatively add them to recompute the flags as well.
480 for (const MachineOperand &MO : MI.operands())
481 if (MO.isReg())
482 addRegToUpdate(MO.getReg());
483 // We don't erase anything in case the def has other uses. Let DCE
484 // remove it if it can be removed.
485 LLVM_DEBUG(dbgs() << "Converted instruction to imm form: ");
486 LLVM_DEBUG(MI.dump());
487 NumConvertedToImmediateForm++;
488 SomethingChanged = true;
489 Simplified = true;
490 }
491 }
492 } while (SomethingChanged && FixedPointRegToImm);
493 }
494
495 // Since we are deleting this instruction, clear the kill flags on any of its
496 // definitions that are marked as needing an update: the transforms only ever
497 // invalidate kill flags by removing uses (turning a non-last use into the
498 // last one), so a conservative clear is sufficient.
499 auto clearKillsForDyingInstr = [&]() {
500 if (RegsToUpdate.empty())
501 return;
502 for (MachineOperand &MO : ToErase->operands()) {
503 if (!MO.isReg() || !MO.isDef() || !RegsToUpdate.count(MO.getReg()))
504 continue;
505 Register RegToUpdate = MO.getReg();
506 RegsToUpdate.erase(RegToUpdate);
507 // If some transformation has introduced an additional definition of
508 // this register (breaking SSA), we can safely convert this def to
509 // a def of an invalid register as the instruction is going away.
510 if (!MRI->getUniqueVRegDef(RegToUpdate))
511 MO.setReg(PPC::NoRegister);
512 MRI->clearKillFlags(RegToUpdate);
513 for (MachineOperand &Def : MRI->def_operands(RegToUpdate))
514 Def.setIsDead(false);
515 }
516 };
517
518 for (MachineBasicBlock &MBB : *MF) {
519 for (MachineInstr &MI : MBB) {
520
521 // If the previous instruction was marked for elimination,
522 // remove it now.
523 if (ToErase) {
524 LLVM_DEBUG(dbgs() << "Deleting instruction: ");
525 LLVM_DEBUG(ToErase->dump());
526 clearKillsForDyingInstr();
527 ToErase->eraseFromParent();
528 ToErase = nullptr;
529 }
530 // If a conditional trap instruction got optimized to an
531 // unconditional trap, eliminate all the instructions after
532 // the trap.
533 if (EnableTrapOptimization && TrapOpt) {
534 ToErase = &MI;
535 continue;
536 }
537
538 // Ignore debug instructions.
539 if (MI.isDebugInstr())
540 continue;
541
542 if (!DebugCounter::shouldExecute(PeepholePerOpCounter))
543 continue;
544
545 // Per-opcode peepholes.
546 switch (MI.getOpcode()) {
547
548 default:
549 break;
550 case PPC::COPY: {
551 Register Src = MI.getOperand(1).getReg();
552 Register Dst = MI.getOperand(0).getReg();
553 if (!Src.isVirtual() || !Dst.isVirtual())
554 break;
555 if (MRI->getRegClass(Src) != &PPC::UACCRCRegClass ||
556 MRI->getRegClass(Dst) != &PPC::ACCRCRegClass)
557 break;
558
559 // We are copying an unprimed accumulator to a primed accumulator.
560 // If the input to the copy is a PHI that is fed only by (i) copies in
561 // the other direction (ii) implicitly defined unprimed accumulators or
562 // (iii) other PHI nodes satisfying (i) and (ii), we can change
563 // the PHI to a PHI on primed accumulators (as long as we also change
564 // its operands). To detect and change such copies, we first get a list
565 // of all the PHI nodes starting from the root PHI node in BFS order.
566 // We then visit all these PHI nodes to check if they can be changed to
567 // primed accumulator PHI nodes and if so, we change them.
568 MachineInstr *RootPHI = MRI->getVRegDef(Src);
569 if (RootPHI->getOpcode() != PPC::PHI)
570 break;
571
572 SmallVector<MachineInstr *, 4> PHIs;
573 if (!collectUnprimedAccPHIs(MRI, RootPHI, PHIs))
574 break;
575
576 convertUnprimedAccPHIs(TII, MRI, PHIs, Dst);
577
578 ToErase = &MI;
579 break;
580 }
581 case PPC::LI:
582 case PPC::LI8: {
583 // If we are materializing a zero, look for any use operands for which
584 // zero means immediate zero. All such operands can be replaced with
585 // PPC::ZERO.
586 if (!MI.getOperand(1).isImm() || MI.getOperand(1).getImm() != 0)
587 break;
588 Register MIDestReg = MI.getOperand(0).getReg();
589 bool Folded = false;
590 for (MachineInstr& UseMI : MRI->use_instructions(MIDestReg))
591 Folded |= TII->onlyFoldImmediate(UseMI, MI, MIDestReg);
592 if (MRI->use_nodbg_empty(MIDestReg)) {
593 ++NumLoadImmZeroFoldedAndRemoved;
594 ToErase = &MI;
595 }
596 if (Folded)
597 addRegToUpdate(MIDestReg);
598 Simplified |= Folded;
599 break;
600 }
601 case PPC::STW:
602 case PPC::STD: {
603 MachineFrameInfo &MFI = MF->getFrameInfo();
604 if (MFI.hasVarSizedObjects() ||
605 (!MF->getSubtarget<PPCSubtarget>().isELFv2ABI() &&
606 !MF->getSubtarget<PPCSubtarget>().isAIXABI()))
607 break;
608 // When encountering a TOC save instruction, call UpdateTOCSaves
609 // to add it to the TOCSaves map and mark any existing TOC saves
610 // it dominates as redundant.
611 if (TII->isTOCSaveMI(MI))
612 UpdateTOCSaves(TOCSaves, &MI);
613 break;
614 }
615 case PPC::XXPERMDI: {
616 // Perform simplifications of 2x64 vector swaps and splats.
617 // A swap is identified by an immediate value of 2, and a splat
618 // is identified by an immediate value of 0 or 3.
619 int Immed = MI.getOperand(3).getImm();
620
621 if (Immed == 1)
622 break;
623
624 // For each of these simplifications, we need the two source
625 // regs to match. Unfortunately, MachineCSE ignores COPY and
626 // SUBREG_TO_REG, so for example we can see
627 // XXPERMDI t, SUBREG_TO_REG(s), SUBREG_TO_REG(s), immed.
628 // We have to look through chains of COPY and SUBREG_TO_REG
629 // to find the real source values for comparison.
630 Register TrueReg1 =
631 TRI->lookThruCopyLike(MI.getOperand(1).getReg(), MRI);
632 Register TrueReg2 =
633 TRI->lookThruCopyLike(MI.getOperand(2).getReg(), MRI);
634
635 if (!(TrueReg1 == TrueReg2 && TrueReg1.isVirtual()))
636 break;
637
638 MachineInstr *DefMI = MRI->getVRegDef(TrueReg1);
639
640 if (!DefMI)
641 break;
642
643 unsigned DefOpc = DefMI->getOpcode();
644
645 // If this is a splat fed by a splatting load, the splat is
646 // redundant. Replace with a copy. This doesn't happen directly due
647 // to code in PPCDAGToDAGISel.cpp, but it can happen when converting
648 // a load of a double to a vector of 64-bit integers.
649 auto isConversionOfLoadAndSplat = [=]() -> bool {
650 if (DefOpc != PPC::XVCVDPSXDS && DefOpc != PPC::XVCVDPUXDS)
651 return false;
652 Register FeedReg1 =
653 TRI->lookThruCopyLike(DefMI->getOperand(1).getReg(), MRI);
654 if (FeedReg1.isVirtual()) {
655 MachineInstr *LoadMI = MRI->getVRegDef(FeedReg1);
656 if (LoadMI && LoadMI->getOpcode() == PPC::LXVDSX)
657 return true;
658 }
659 return false;
660 };
661 if ((Immed == 0 || Immed == 3) &&
662 (DefOpc == PPC::LXVDSX || isConversionOfLoadAndSplat())) {
663 LLVM_DEBUG(dbgs() << "Optimizing load-and-splat/splat "
664 "to load-and-splat/copy: ");
665 LLVM_DEBUG(MI.dump());
666 BuildMI(MBB, &MI, MI.getDebugLoc(), TII->get(PPC::COPY),
667 MI.getOperand(0).getReg())
668 .add(MI.getOperand(1));
669 addRegToUpdate(MI.getOperand(1).getReg());
670 ToErase = &MI;
671 Simplified = true;
672 }
673
674 // If this is a splat or a swap fed by another splat, we
675 // can replace it with a copy.
676 if (DefOpc == PPC::XXPERMDI) {
677 Register DefReg1 = DefMI->getOperand(1).getReg();
678 Register DefReg2 = DefMI->getOperand(2).getReg();
679 unsigned DefImmed = DefMI->getOperand(3).getImm();
680
681 // If the two inputs are not the same register, check to see if
682 // they originate from the same virtual register after only
683 // copy-like instructions.
684 if (DefReg1 != DefReg2) {
685 Register FeedReg1 = TRI->lookThruCopyLike(DefReg1, MRI);
686 Register FeedReg2 = TRI->lookThruCopyLike(DefReg2, MRI);
687
688 if (!(FeedReg1 == FeedReg2 && FeedReg1.isVirtual()))
689 break;
690 }
691
692 if (DefImmed == 0 || DefImmed == 3) {
693 LLVM_DEBUG(dbgs() << "Optimizing splat/swap or splat/splat "
694 "to splat/copy: ");
695 LLVM_DEBUG(MI.dump());
696 BuildMI(MBB, &MI, MI.getDebugLoc(), TII->get(PPC::COPY),
697 MI.getOperand(0).getReg())
698 .add(MI.getOperand(1));
699 addRegToUpdate(MI.getOperand(1).getReg());
700 ToErase = &MI;
701 Simplified = true;
702 }
703
704 // If this is a splat fed by a swap, we can simplify modify
705 // the splat to splat the other value from the swap's input
706 // parameter.
707 else if ((Immed == 0 || Immed == 3) && DefImmed == 2) {
708 LLVM_DEBUG(dbgs() << "Optimizing swap/splat => splat: ");
709 LLVM_DEBUG(MI.dump());
710 addRegToUpdate(MI.getOperand(1).getReg());
711 addRegToUpdate(MI.getOperand(2).getReg());
712 MI.getOperand(1).setReg(DefReg1);
713 MI.getOperand(2).setReg(DefReg2);
714 MI.getOperand(3).setImm(3 - Immed);
715 addRegToUpdate(DefReg1);
716 addRegToUpdate(DefReg2);
717 Simplified = true;
718 }
719
720 // If this is a swap fed by a swap, we can replace it
721 // with a copy from the first swap's input.
722 else if (Immed == 2 && DefImmed == 2) {
723 LLVM_DEBUG(dbgs() << "Optimizing swap/swap => copy: ");
724 LLVM_DEBUG(MI.dump());
725 addRegToUpdate(MI.getOperand(1).getReg());
726
727 BuildMI(MBB, &MI, MI.getDebugLoc(), TII->get(PPC::COPY),
728 MI.getOperand(0).getReg())
729 .add(DefMI->getOperand(1));
732 ToErase = &MI;
733 Simplified = true;
734 }
735 } else if ((Immed == 0 || Immed == 3 || Immed == 2) &&
736 DefOpc == PPC::XXPERMDIs &&
737 (DefMI->getOperand(2).getImm() == 0 ||
738 DefMI->getOperand(2).getImm() == 3)) {
739
740 if (!MRI->hasOneNonDBGUser(DefMI->getOperand(0).getReg()))
741 break;
742 Simplified = true;
743 // Swap of a splat, convert to copy.
744 if (Immed == 2) {
745 LLVM_DEBUG(dbgs() << "Optimizing swap(splat) => copy(splat): ");
746 LLVM_DEBUG(MI.dump());
747 BuildMI(MBB, &MI, MI.getDebugLoc(), TII->get(PPC::COPY),
748 MI.getOperand(0).getReg())
749 .add(MI.getOperand(1));
750 addRegToUpdate(MI.getOperand(1).getReg());
751 ToErase = &MI;
752 break;
753 }
754 // Splat fed by another splat - switch the output of the first
755 // and remove the second.
756 ToErase = &MI;
757 DefMI->getOperand(0).setReg(MI.getOperand(0).getReg());
758 LLVM_DEBUG(dbgs() << "Removing redundant splat: ");
759 LLVM_DEBUG(MI.dump());
760 } else if (Immed == 2 &&
761 (DefOpc == PPC::VSPLTB || DefOpc == PPC::VSPLTH ||
762 DefOpc == PPC::VSPLTW || DefOpc == PPC::XXSPLTW ||
763 DefOpc == PPC::VSPLTISB || DefOpc == PPC::VSPLTISH ||
764 DefOpc == PPC::VSPLTISW)) {
765 // Swap of various vector splats, convert to copy.
766 ToErase = &MI;
767 Simplified = true;
768 LLVM_DEBUG(dbgs() << "Optimizing swap(vsplt(is)?[b|h|w]|xxspltw) => "
769 "copy(vsplt(is)?[b|h|w]|xxspltw): ");
770 LLVM_DEBUG(MI.dump());
771 BuildMI(MBB, &MI, MI.getDebugLoc(), TII->get(PPC::COPY),
772 MI.getOperand(0).getReg())
773 .add(MI.getOperand(1));
774 addRegToUpdate(MI.getOperand(1).getReg());
775 } else if ((Immed == 0 || Immed == 3 || Immed == 2) &&
776 TII->isLoadFromConstantPool(DefMI)) {
777 const Constant *C = TII->getConstantFromConstantPool(DefMI);
778 if (C && C->getType()->isVectorTy() && C->getSplatValue()) {
779 ToErase = &MI;
780 Simplified = true;
782 << "Optimizing swap(splat pattern from constant-pool) "
783 "=> copy(splat pattern from constant-pool): ");
784 LLVM_DEBUG(MI.dump());
785 BuildMI(MBB, &MI, MI.getDebugLoc(), TII->get(PPC::COPY),
786 MI.getOperand(0).getReg())
787 .add(MI.getOperand(1));
788 addRegToUpdate(MI.getOperand(1).getReg());
789 }
790 }
791 break;
792 }
793 case PPC::VSPLTB:
794 case PPC::VSPLTH:
795 case PPC::XXSPLTW: {
796 unsigned MyOpcode = MI.getOpcode();
797 // The operand number of the source register in the splat instruction.
798 unsigned OpNo = MyOpcode == PPC::XXSPLTW ? 1 : 2;
799 Register TrueReg =
800 TRI->lookThruCopyLike(MI.getOperand(OpNo).getReg(), MRI);
801 if (!TrueReg.isVirtual())
802 break;
803 MachineInstr *DefMI = MRI->getVRegDef(TrueReg);
804 if (!DefMI)
805 break;
806 unsigned DefOpcode = DefMI->getOpcode();
807 auto isConvertOfSplat = [=]() -> bool {
808 if (DefOpcode != PPC::XVCVSPSXWS && DefOpcode != PPC::XVCVSPUXWS)
809 return false;
810 Register ConvReg = DefMI->getOperand(1).getReg();
811 if (!ConvReg.isVirtual())
812 return false;
813 MachineInstr *Splt = MRI->getVRegDef(ConvReg);
814 return Splt && (Splt->getOpcode() == PPC::LXVWSX ||
815 Splt->getOpcode() == PPC::XXSPLTW);
816 };
817 bool AlreadySplat = (MyOpcode == DefOpcode) ||
818 (MyOpcode == PPC::VSPLTB && DefOpcode == PPC::VSPLTBs) ||
819 (MyOpcode == PPC::VSPLTH && DefOpcode == PPC::VSPLTHs) ||
820 (MyOpcode == PPC::XXSPLTW && DefOpcode == PPC::XXSPLTWs) ||
821 (MyOpcode == PPC::XXSPLTW && DefOpcode == PPC::LXVWSX) ||
822 (MyOpcode == PPC::XXSPLTW && DefOpcode == PPC::MTVSRWS)||
823 (MyOpcode == PPC::XXSPLTW && isConvertOfSplat());
824
825 // If the instruction[s] that feed this splat have already splat
826 // the value, this splat is redundant.
827 if (AlreadySplat) {
828 LLVM_DEBUG(dbgs() << "Changing redundant splat to a copy: ");
829 LLVM_DEBUG(MI.dump());
830 BuildMI(MBB, &MI, MI.getDebugLoc(), TII->get(PPC::COPY),
831 MI.getOperand(0).getReg())
832 .add(MI.getOperand(OpNo));
833 addRegToUpdate(MI.getOperand(OpNo).getReg());
834 ToErase = &MI;
835 Simplified = true;
836 }
837
838 // Splat fed by a shift. Usually when we align value to splat into
839 // vector element zero.
840 if (DefOpcode == PPC::XXSLDWI) {
841 Register ShiftOp1 = DefMI->getOperand(1).getReg();
842
843 if (ShiftOp1 == DefMI->getOperand(2).getReg()) {
844 // For example, We can erase XXSLDWI from in following:
845 // %2:vrrc = XXSLDWI killed %1:vrrc, %1:vrrc, 1
846 // %6:vrrc = VSPLTB 15, killed %2:vrrc
847 // %7:vsrc = XXLAND killed %6:vrrc, killed %1:vrrc
848 //
849 // --->
850 //
851 // %6:vrrc = VSPLTB 3, killed %1:vrrc
852 // %7:vsrc = XXLAND killed %6:vrrc, killed %1:vrrc
853
854 if (MRI->hasOneNonDBGUse(DefMI->getOperand(0).getReg())) {
855 LLVM_DEBUG(dbgs() << "Removing redundant shift: ");
857 ToErase = DefMI;
858 }
859 Simplified = true;
860 unsigned ShiftImm = DefMI->getOperand(3).getImm();
861 // The operand number of the splat Imm in the instruction.
862 unsigned SplatImmNo = MyOpcode == PPC::XXSPLTW ? 2 : 1;
863 unsigned SplatImm = MI.getOperand(SplatImmNo).getImm();
864
865 // Calculate the new splat-element immediate. We need to convert the
866 // element index into the proper unit (byte for VSPLTB, halfword for
867 // VSPLTH, word for VSPLTW) because PPC::XXSLDWI interprets its
868 // ShiftImm in 32-bit word units.
869 auto CalculateNewElementIdx = [&](unsigned Opcode) {
870 if (Opcode == PPC::VSPLTB)
871 return (SplatImm + ShiftImm * 4) & 0xF;
872 else if (Opcode == PPC::VSPLTH)
873 return (SplatImm + ShiftImm * 2) & 0x7;
874 else
875 return (SplatImm + ShiftImm) & 0x3;
876 };
877
878 unsigned NewElem = CalculateNewElementIdx(MyOpcode);
879
880 LLVM_DEBUG(dbgs() << "Changing splat immediate from " << SplatImm
881 << " to " << NewElem << " in instruction: ");
882 LLVM_DEBUG(MI.dump());
883 if (!MRI->constrainRegClass(ShiftOp1, &PPC::VRRCRegClass))
884 llvm_unreachable("Can't fail because vrrc is subset of vsrc");
885 addRegToUpdate(MI.getOperand(OpNo).getReg());
886 addRegToUpdate(ShiftOp1);
887 MI.getOperand(OpNo).setReg(ShiftOp1);
888 MI.getOperand(SplatImmNo).setImm(NewElem);
889 }
890 }
891 break;
892 }
893 case PPC::XVCVDPSP: {
894 // If this is a DP->SP conversion fed by an FRSP, the FRSP is redundant.
895 Register TrueReg =
896 TRI->lookThruCopyLike(MI.getOperand(1).getReg(), MRI);
897 if (!TrueReg.isVirtual())
898 break;
899 MachineInstr *DefMI = MRI->getVRegDef(TrueReg);
900
901 // This can occur when building a vector of single precision or integer
902 // values.
903 if (DefMI && DefMI->getOpcode() == PPC::XXPERMDI) {
904 Register DefsReg1 =
905 TRI->lookThruCopyLike(DefMI->getOperand(1).getReg(), MRI);
906 Register DefsReg2 =
907 TRI->lookThruCopyLike(DefMI->getOperand(2).getReg(), MRI);
908 if (!DefsReg1.isVirtual() || !DefsReg2.isVirtual())
909 break;
910 MachineInstr *P1 = MRI->getVRegDef(DefsReg1);
911 MachineInstr *P2 = MRI->getVRegDef(DefsReg2);
912
913 if (!P1 || !P2)
914 break;
915
916 // Remove the passed FRSP/XSRSP instruction if it only feeds this MI
917 // and set any uses of that FRSP/XSRSP (in this MI) to the source of
918 // the FRSP/XSRSP.
919 auto removeFRSPIfPossible = [&](MachineInstr *RoundInstr) {
920 unsigned Opc = RoundInstr->getOpcode();
921 if ((Opc == PPC::FRSP || Opc == PPC::XSRSP) &&
922 MRI->hasOneNonDBGUse(RoundInstr->getOperand(0).getReg())) {
923 Simplified = true;
924 Register ConvReg1 = RoundInstr->getOperand(1).getReg();
925 Register FRSPDefines = RoundInstr->getOperand(0).getReg();
926 MachineInstr &Use = *(MRI->use_instr_nodbg_begin(FRSPDefines));
927 for (int i = 0, e = Use.getNumOperands(); i < e; ++i)
928 if (Use.getOperand(i).isReg() &&
929 Use.getOperand(i).getReg() == FRSPDefines)
930 Use.getOperand(i).setReg(ConvReg1);
931 LLVM_DEBUG(dbgs() << "Removing redundant FRSP/XSRSP:\n");
932 LLVM_DEBUG(RoundInstr->dump());
933 LLVM_DEBUG(dbgs() << "As it feeds instruction:\n");
934 LLVM_DEBUG(MI.dump());
935 LLVM_DEBUG(dbgs() << "Through instruction:\n");
937 addRegToUpdate(ConvReg1);
938 addRegToUpdate(FRSPDefines);
939 ToErase = RoundInstr;
940 }
941 };
942
943 // If the input to XVCVDPSP is a vector that was built (even
944 // partially) out of FRSP's, the FRSP(s) can safely be removed
945 // since this instruction performs the same operation.
946 if (P1 != P2) {
947 removeFRSPIfPossible(P1);
948 removeFRSPIfPossible(P2);
949 break;
950 }
951 removeFRSPIfPossible(P1);
952 }
953 break;
954 }
955 case PPC::EXTSH:
956 case PPC::EXTSH8:
957 case PPC::EXTSH8_32_64: {
958 if (!EnableSExtElimination) break;
959 Register NarrowReg = MI.getOperand(1).getReg();
960 if (!NarrowReg.isVirtual())
961 break;
962
963 MachineInstr *SrcMI = MRI->getVRegDef(NarrowReg);
964 unsigned SrcOpcode = SrcMI->getOpcode();
965 // If we've used a zero-extending load that we will sign-extend,
966 // just do a sign-extending load.
967 if (SrcOpcode == PPC::LHZ || SrcOpcode == PPC::LHZX) {
968 if (!MRI->hasOneNonDBGUse(SrcMI->getOperand(0).getReg()))
969 break;
970 // Determine the new opcode. We need to make sure that if the original
971 // instruction has a 64 bit opcode we keep using a 64 bit opcode.
972 // Likewise if the source is X-Form the new opcode should also be
973 // X-Form.
974 unsigned Opc = PPC::LHA;
975 bool SourceIsXForm = SrcOpcode == PPC::LHZX;
976 bool MIIs64Bit = MI.getOpcode() == PPC::EXTSH8 ||
977 MI.getOpcode() == PPC::EXTSH8_32_64;
978
979 if (SourceIsXForm && MIIs64Bit)
980 Opc = PPC::LHAX8;
981 else if (SourceIsXForm && !MIIs64Bit)
982 Opc = PPC::LHAX;
983 else if (MIIs64Bit)
984 Opc = PPC::LHA8;
985
986 addRegToUpdate(NarrowReg);
987 addRegToUpdate(MI.getOperand(0).getReg());
988
989 // We are removing a definition of NarrowReg which will cause
990 // problems in AliveBlocks. Add an implicit def that will be
991 // removed so that AliveBlocks are updated correctly.
992 addDummyDef(MBB, &MI, NarrowReg);
993 LLVM_DEBUG(dbgs() << "Zero-extending load\n");
994 LLVM_DEBUG(SrcMI->dump());
995 LLVM_DEBUG(dbgs() << "and sign-extension\n");
996 LLVM_DEBUG(MI.dump());
997 LLVM_DEBUG(dbgs() << "are merged into sign-extending load\n");
998 SrcMI->setDesc(TII->get(Opc));
999 SrcMI->getOperand(0).setReg(MI.getOperand(0).getReg());
1000 ToErase = &MI;
1001 Simplified = true;
1002 NumEliminatedSExt++;
1003 }
1004 break;
1005 }
1006 case PPC::EXTSW:
1007 case PPC::EXTSW_32:
1008 case PPC::EXTSW_32_64: {
1009 if (!EnableSExtElimination) break;
1010 Register NarrowReg = MI.getOperand(1).getReg();
1011 if (!NarrowReg.isVirtual())
1012 break;
1013
1014 MachineInstr *SrcMI = MRI->getVRegDef(NarrowReg);
1015 unsigned SrcOpcode = SrcMI->getOpcode();
1016 // If we've used a zero-extending load that we will sign-extend,
1017 // just do a sign-extending load. The source may be a 32-bit gprc load
1018 // consumed directly, or a 64-bit g8rc load consumed through its sub_32
1019 // subregister.
1020 bool SrcIsGPRCWordZextLoad =
1021 SrcOpcode == PPC::LWZ || SrcOpcode == PPC::LWZX;
1022 bool SrcIsG8RCWordZextLoad =
1023 SrcOpcode == PPC::LWZ8 || SrcOpcode == PPC::LWZX8;
1024 unsigned NarrowSubReg = MI.getOperand(1).getSubReg();
1025
1026 if ((!NarrowSubReg && SrcIsGPRCWordZextLoad) ||
1027 (NarrowSubReg == PPC::sub_32 && SrcIsG8RCWordZextLoad)) {
1028 if (!MRI->hasOneNonDBGUse(SrcMI->getOperand(0).getReg()))
1029 break;
1030
1031 // The transformation from a zero-extending load to a sign-extending
1032 // load is only legal when the displacement is a multiple of 4.
1033 // If the displacement is not at least 4 byte aligned, don't perform
1034 // the transformation.
1035 bool IsWordAligned = false;
1036 if (SrcMI->getOperand(1).isGlobal()) {
1037 const GlobalVariable *GV =
1039 if (GV && GV->getAlign() && *GV->getAlign() >= 4 &&
1040 (SrcMI->getOperand(1).getOffset() % 4 == 0))
1041 IsWordAligned = true;
1042 } else if (SrcMI->getOperand(1).isImm()) {
1043 int64_t Value = SrcMI->getOperand(1).getImm();
1044 if (Value % 4 == 0)
1045 IsWordAligned = true;
1046 }
1047
1048 // Determine the new opcode. We need to make sure that if the original
1049 // instruction has a 64 bit opcode we keep using a 64 bit opcode.
1050 // Likewise if the source is X-Form the new opcode should also be
1051 // X-Form.
1052 unsigned Opc = PPC::LWA_32;
1053 bool SourceIsXForm =
1054 SrcOpcode == PPC::LWZX || SrcOpcode == PPC::LWZX8;
1055 bool MIIs64Bit = MI.getOpcode() == PPC::EXTSW ||
1056 MI.getOpcode() == PPC::EXTSW_32_64;
1057
1058 if (SourceIsXForm && MIIs64Bit)
1059 Opc = PPC::LWAX;
1060 else if (SourceIsXForm && !MIIs64Bit)
1061 Opc = PPC::LWAX_32;
1062 else if (MIIs64Bit)
1063 Opc = PPC::LWA;
1064
1065 if (!IsWordAligned && (Opc == PPC::LWA || Opc == PPC::LWA_32))
1066 break;
1067
1068 addRegToUpdate(NarrowReg);
1069 addRegToUpdate(MI.getOperand(0).getReg());
1070
1071 // We are removing a definition of NarrowReg which will cause
1072 // problems in AliveBlocks. Add an implicit def that will be
1073 // removed so that AliveBlocks are updated correctly.
1074 addDummyDef(MBB, &MI, NarrowReg);
1075 LLVM_DEBUG(dbgs() << "Zero-extending load\n");
1076 LLVM_DEBUG(SrcMI->dump());
1077 LLVM_DEBUG(dbgs() << "and sign-extension\n");
1078 LLVM_DEBUG(MI.dump());
1079 LLVM_DEBUG(dbgs() << "are merged into sign-extending load\n");
1080 SrcMI->setDesc(TII->get(Opc));
1081 SrcMI->getOperand(0).setReg(MI.getOperand(0).getReg());
1082 ToErase = &MI;
1083 Simplified = true;
1084 NumEliminatedSExt++;
1085 } else if (MI.getOpcode() == PPC::EXTSW_32_64 &&
1086 TII->isSignExtended(NarrowReg, MRI)) {
1087 // We can eliminate EXTSW if the input is known to be already
1088 // sign-extended. However, we are not sure whether a spill will occur
1089 // during register allocation. If there is no promotion, it will use
1090 // 'stw' instead of 'std', and 'lwz' instead of 'ld' when spilling,
1091 // since the register class is 32-bits. Consequently, the high 32-bit
1092 // information will be lost. Therefore, all these instructions in the
1093 // chain used to deduce sign extension to eliminate the 'extsw' will
1094 // need to be promoted to 64-bit pseudo instructions when the 'extsw'
1095 // is eliminated.
1096 TII->promoteInstr32To64ForElimEXTSW(NarrowReg, MRI, 0);
1097
1098 LLVM_DEBUG(dbgs() << "Removing redundant sign-extension\n");
1099
1100 unsigned NarrowSubReg = MI.getOperand(1).getSubReg();
1101 if (NarrowSubReg) {
1102 // The input reads a subregister of a wider register which we can
1103 // use directly by dropping the subreg.
1104 assert(NarrowSubReg == PPC::sub_32 &&
1105 "EXTSW_32_64 input must read the sub_32 subregister");
1106 BuildMI(MBB, &MI, MI.getDebugLoc(), TII->get(PPC::COPY),
1107 MI.getOperand(0).getReg())
1108 .addReg(NarrowReg);
1109 } else {
1110 Register TmpReg =
1111 MF->getRegInfo().createVirtualRegister(&PPC::G8RCRegClass);
1112 BuildMI(MBB, &MI, MI.getDebugLoc(), TII->get(PPC::IMPLICIT_DEF),
1113 TmpReg);
1114 BuildMI(MBB, &MI, MI.getDebugLoc(), TII->get(PPC::INSERT_SUBREG),
1115 MI.getOperand(0).getReg())
1116 .addReg(TmpReg)
1117 .addReg(NarrowReg)
1118 .addImm(PPC::sub_32);
1119 addRegToUpdate(NarrowReg);
1120 }
1121 ToErase = &MI;
1122 Simplified = true;
1123 NumEliminatedSExt++;
1124 }
1125 break;
1126 }
1127 case PPC::RLDICL: {
1128 // We can eliminate RLDICL (e.g. for zero-extension)
1129 // if all bits to clear are already zero in the input.
1130 // This code assume following code sequence for zero-extension.
1131 // %6 = COPY %5:sub_32; (optional)
1132 // %8 = IMPLICIT_DEF;
1133 // %7<def,tied1> = INSERT_SUBREG %8<tied0>, %6, sub_32;
1134 if (!EnableZExtElimination) break;
1135
1136 if (MI.getOperand(2).getImm() != 0)
1137 break;
1138
1139 Register SrcReg = MI.getOperand(1).getReg();
1140 if (!SrcReg.isVirtual())
1141 break;
1142
1143 MachineInstr *SrcMI = MRI->getVRegDef(SrcReg);
1144 if (!(SrcMI && SrcMI->getOpcode() == PPC::INSERT_SUBREG &&
1145 SrcMI->getOperand(0).isReg() && SrcMI->getOperand(1).isReg()))
1146 break;
1147
1148 MachineInstr *ImpDefMI, *SubRegMI;
1149 ImpDefMI = MRI->getVRegDef(SrcMI->getOperand(1).getReg());
1150 SubRegMI = MRI->getVRegDef(SrcMI->getOperand(2).getReg());
1151 if (ImpDefMI->getOpcode() != PPC::IMPLICIT_DEF) break;
1152
1153 SrcMI = SubRegMI;
1154 if (SubRegMI->getOpcode() == PPC::COPY) {
1155 Register CopyReg = SubRegMI->getOperand(1).getReg();
1156 if (CopyReg.isVirtual())
1157 SrcMI = MRI->getVRegDef(CopyReg);
1158 }
1159 if (!SrcMI->getOperand(0).isReg())
1160 break;
1161
1162 unsigned KnownZeroCount =
1163 getKnownLeadingZeroCount(SrcMI->getOperand(0).getReg(), TII, MRI);
1164 if (MI.getOperand(3).getImm() <= KnownZeroCount) {
1165 LLVM_DEBUG(dbgs() << "Removing redundant zero-extension\n");
1166 BuildMI(MBB, &MI, MI.getDebugLoc(), TII->get(PPC::COPY),
1167 MI.getOperand(0).getReg())
1168 .addReg(SrcReg);
1169 addRegToUpdate(SrcReg);
1170 ToErase = &MI;
1171 Simplified = true;
1172 NumEliminatedZExt++;
1173 }
1174 break;
1175 }
1176
1177 // TODO: Any instruction that has an immediate form fed only by a PHI
1178 // whose operands are all load immediate can be folded away. We currently
1179 // do this for ADD instructions, but should expand it to arithmetic and
1180 // binary instructions with immediate forms in the future.
1181 case PPC::ADD4:
1182 case PPC::ADD8: {
1183 auto isSingleUsePHI = [&](MachineOperand *PhiOp) {
1184 assert(PhiOp && "Invalid Operand!");
1185 MachineInstr *DefPhiMI = getVRegDefOrNull(PhiOp, MRI);
1186
1187 return DefPhiMI && (DefPhiMI->getOpcode() == PPC::PHI) &&
1188 MRI->hasOneNonDBGUse(DefPhiMI->getOperand(0).getReg());
1189 };
1190
1191 auto dominatesAllSingleUseLIs = [&](MachineOperand *DominatorOp,
1192 MachineOperand *PhiOp) {
1193 assert(PhiOp && "Invalid Operand!");
1194 assert(DominatorOp && "Invalid Operand!");
1195 MachineInstr *DefPhiMI = getVRegDefOrNull(PhiOp, MRI);
1196 MachineInstr *DefDomMI = getVRegDefOrNull(DominatorOp, MRI);
1197
1198 // Note: the vregs only show up at odd indices position of PHI Node,
1199 // the even indices position save the BB info.
1200 for (unsigned i = 1; i < DefPhiMI->getNumOperands(); i += 2) {
1201 MachineInstr *LiMI =
1202 getVRegDefOrNull(&DefPhiMI->getOperand(i), MRI);
1203 if (!LiMI ||
1204 (LiMI->getOpcode() != PPC::LI && LiMI->getOpcode() != PPC::LI8)
1205 || !MRI->hasOneNonDBGUse(LiMI->getOperand(0).getReg()) ||
1206 !MDT->dominates(DefDomMI, LiMI))
1207 return false;
1208 }
1209
1210 return true;
1211 };
1212
1213 MachineOperand Op1 = MI.getOperand(1);
1214 MachineOperand Op2 = MI.getOperand(2);
1215 if (isSingleUsePHI(&Op2) && dominatesAllSingleUseLIs(&Op1, &Op2))
1216 std::swap(Op1, Op2);
1217 else if (!isSingleUsePHI(&Op1) || !dominatesAllSingleUseLIs(&Op2, &Op1))
1218 break; // We don't have an ADD fed by LI's that can be transformed
1219
1220 // Now we know that Op1 is the PHI node and Op2 is the dominator
1221 Register DominatorReg = Op2.getReg();
1222
1223 const TargetRegisterClass *TRC = MI.getOpcode() == PPC::ADD8
1224 ? &PPC::G8RC_and_G8RC_NOX0RegClass
1225 : &PPC::GPRC_and_GPRC_NOR0RegClass;
1226 MRI->setRegClass(DominatorReg, TRC);
1227
1228 // replace LIs with ADDIs
1229 MachineInstr *DefPhiMI = getVRegDefOrNull(&Op1, MRI);
1230 for (unsigned i = 1; i < DefPhiMI->getNumOperands(); i += 2) {
1231 MachineInstr *LiMI = getVRegDefOrNull(&DefPhiMI->getOperand(i), MRI);
1232 LLVM_DEBUG(dbgs() << "Optimizing LI to ADDI: ");
1233 LLVM_DEBUG(LiMI->dump());
1234
1235 // There could be repeated registers in the PHI, e.g: %1 =
1236 // PHI %6, <%bb.2>, %8, <%bb.3>, %8, <%bb.6>; So if we've
1237 // already replaced the def instruction, skip.
1238 if (LiMI->getOpcode() == PPC::ADDI || LiMI->getOpcode() == PPC::ADDI8)
1239 continue;
1240
1241 assert((LiMI->getOpcode() == PPC::LI ||
1242 LiMI->getOpcode() == PPC::LI8) &&
1243 "Invalid Opcode!");
1244 auto LiImm = LiMI->getOperand(1).getImm(); // save the imm of LI
1245 LiMI->removeOperand(1); // remove the imm of LI
1246 LiMI->setDesc(TII->get(LiMI->getOpcode() == PPC::LI ? PPC::ADDI
1247 : PPC::ADDI8));
1248 MachineInstrBuilder(*LiMI->getParent()->getParent(), *LiMI)
1249 .addReg(DominatorReg)
1250 .addImm(LiImm); // restore the imm of LI
1251 LLVM_DEBUG(LiMI->dump());
1252 }
1253
1254 // Replace ADD with COPY
1255 LLVM_DEBUG(dbgs() << "Optimizing ADD to COPY: ");
1256 LLVM_DEBUG(MI.dump());
1257 BuildMI(MBB, &MI, MI.getDebugLoc(), TII->get(PPC::COPY),
1258 MI.getOperand(0).getReg())
1259 .add(Op1);
1260 addRegToUpdate(Op1.getReg());
1261 addRegToUpdate(Op2.getReg());
1262 ToErase = &MI;
1263 Simplified = true;
1264 NumOptADDLIs++;
1265 break;
1266 }
1267 case PPC::RLDICR: {
1268 Simplified |= emitRLDICWhenLoweringJumpTables(MI, ToErase) ||
1269 combineSEXTAndSHL(MI, ToErase);
1270 break;
1271 }
1272 case PPC::ANDI_rec:
1273 case PPC::ANDI8_rec:
1274 case PPC::ANDIS_rec:
1275 case PPC::ANDIS8_rec: {
1276 Register TrueReg =
1277 TRI->lookThruCopyLike(MI.getOperand(1).getReg(), MRI);
1278 if (!TrueReg.isVirtual() || !MRI->hasOneNonDBGUse(TrueReg))
1279 break;
1280
1281 MachineInstr *SrcMI = MRI->getVRegDef(TrueReg);
1282 if (!SrcMI)
1283 break;
1284
1285 unsigned SrcOpCode = SrcMI->getOpcode();
1286 if (SrcOpCode != PPC::RLDICL && SrcOpCode != PPC::RLDICR)
1287 break;
1288
1289 Register SrcReg, DstReg;
1290 SrcReg = SrcMI->getOperand(1).getReg();
1291 DstReg = MI.getOperand(1).getReg();
1292 const TargetRegisterClass *SrcRC = MRI->getRegClassOrNull(SrcReg);
1293 const TargetRegisterClass *DstRC = MRI->getRegClassOrNull(DstReg);
1294 if (DstRC != SrcRC)
1295 break;
1296
1297 uint64_t AndImm = MI.getOperand(2).getImm();
1298 if (MI.getOpcode() == PPC::ANDIS_rec ||
1299 MI.getOpcode() == PPC::ANDIS8_rec)
1300 AndImm <<= 16;
1301 uint64_t LZeroAndImm = llvm::countl_zero<uint64_t>(AndImm);
1302 uint64_t RZeroAndImm = llvm::countr_zero<uint64_t>(AndImm);
1303 uint64_t ImmSrc = SrcMI->getOperand(3).getImm();
1304
1305 // We can transfer `RLDICL/RLDICR + ANDI_rec/ANDIS_rec` to `ANDI_rec 0`
1306 // if all bits to AND are already zero in the input.
1307 bool PatternResultZero =
1308 (SrcOpCode == PPC::RLDICL && (RZeroAndImm + ImmSrc > 63)) ||
1309 (SrcOpCode == PPC::RLDICR && LZeroAndImm > ImmSrc);
1310
1311 // We can eliminate RLDICL/RLDICR if it's used to clear bits and all
1312 // bits cleared will be ANDed with 0 by ANDI_rec/ANDIS_rec.
1313 bool PatternRemoveRotate =
1314 SrcMI->getOperand(2).getImm() == 0 &&
1315 ((SrcOpCode == PPC::RLDICL && LZeroAndImm >= ImmSrc) ||
1316 (SrcOpCode == PPC::RLDICR && (RZeroAndImm + ImmSrc > 63)));
1317
1318 if (!PatternResultZero && !PatternRemoveRotate)
1319 break;
1320
1321 LLVM_DEBUG(dbgs() << "Combining pair: ");
1322 LLVM_DEBUG(SrcMI->dump());
1323 LLVM_DEBUG(MI.dump());
1324 if (PatternResultZero)
1325 MI.getOperand(2).setImm(0);
1326 MI.getOperand(1).setReg(SrcMI->getOperand(1).getReg());
1327 LLVM_DEBUG(dbgs() << "To: ");
1328 LLVM_DEBUG(MI.dump());
1329 addRegToUpdate(MI.getOperand(1).getReg());
1330 addRegToUpdate(SrcMI->getOperand(0).getReg());
1331 Simplified = true;
1332 break;
1333 }
1334 case PPC::RLWINM:
1335 case PPC::RLWINM_rec:
1336 case PPC::RLWINM8:
1337 case PPC::RLWINM8_rec: {
1338 // We might replace operand 1 of the instruction which will
1339 // require we recompute kill flags for it.
1340 Register OrigOp1Reg = MI.getOperand(1).isReg()
1341 ? MI.getOperand(1).getReg()
1342 : PPC::NoRegister;
1343 Simplified = TII->combineRLWINM(MI, &ToErase);
1344 if (Simplified) {
1345 addRegToUpdate(OrigOp1Reg);
1346 if (MI.getOperand(1).isReg())
1347 addRegToUpdate(MI.getOperand(1).getReg());
1348 if (ToErase && ToErase->getOperand(1).isReg())
1349 for (auto UseReg : ToErase->explicit_uses())
1350 if (UseReg.isReg())
1351 addRegToUpdate(UseReg.getReg());
1352 ++NumRotatesCollapsed;
1353 }
1354 break;
1355 }
1356 // We will replace TD/TW/TDI/TWI with an unconditional trap if it will
1357 // always trap, we will delete the node if it will never trap.
1358 case PPC::TDI:
1359 case PPC::TWI:
1360 case PPC::TD:
1361 case PPC::TW: {
1362 if (!EnableTrapOptimization) break;
1363 MachineInstr *LiMI1 = getVRegDefOrNull(&MI.getOperand(1), MRI);
1364 MachineInstr *LiMI2 = getVRegDefOrNull(&MI.getOperand(2), MRI);
1365 bool IsOperand2Immediate = MI.getOperand(2).isImm();
1366 // We can only do the optimization if we can get immediates
1367 // from both operands
1368 if (!(LiMI1 && (LiMI1->getOpcode() == PPC::LI ||
1369 LiMI1->getOpcode() == PPC::LI8)))
1370 break;
1371 if (!IsOperand2Immediate &&
1372 !(LiMI2 && (LiMI2->getOpcode() == PPC::LI ||
1373 LiMI2->getOpcode() == PPC::LI8)))
1374 break;
1375
1376 auto ImmOperand0 = MI.getOperand(0).getImm();
1377 auto ImmOperand1 = LiMI1->getOperand(1).getImm();
1378 auto ImmOperand2 = IsOperand2Immediate ? MI.getOperand(2).getImm()
1379 : LiMI2->getOperand(1).getImm();
1380
1381 // We will replace the MI with an unconditional trap if it will always
1382 // trap.
1383 if ((ImmOperand0 == 31) ||
1384 ((ImmOperand0 & 0x10) &&
1385 ((int64_t)ImmOperand1 < (int64_t)ImmOperand2)) ||
1386 ((ImmOperand0 & 0x8) &&
1387 ((int64_t)ImmOperand1 > (int64_t)ImmOperand2)) ||
1388 ((ImmOperand0 & 0x2) &&
1389 ((uint64_t)ImmOperand1 < (uint64_t)ImmOperand2)) ||
1390 ((ImmOperand0 & 0x1) &&
1391 ((uint64_t)ImmOperand1 > (uint64_t)ImmOperand2)) ||
1392 ((ImmOperand0 & 0x4) && (ImmOperand1 == ImmOperand2))) {
1393 BuildMI(MBB, &MI, MI.getDebugLoc(), TII->get(PPC::TRAP));
1394 TrapOpt = true;
1395 }
1396 // We will delete the MI if it will never trap.
1397 ToErase = &MI;
1398 Simplified = true;
1399 break;
1400 }
1401 }
1402 }
1403
1404 // If the last instruction was marked for elimination,
1405 // remove it now.
1406 if (ToErase) {
1407 clearKillsForDyingInstr();
1408 ToErase->eraseFromParent();
1409 ToErase = nullptr;
1410 }
1411 // Reset TrapOpt to false at the end of the basic block.
1413 TrapOpt = false;
1414 }
1415
1416 // Eliminate all the TOC save instructions which are redundant.
1417 Simplified |= eliminateRedundantTOCSaves(TOCSaves);
1418 PPCFunctionInfo *FI = MF->getInfo<PPCFunctionInfo>();
1419 if (FI->mustSaveTOC())
1420 NumTOCSavesInPrologue++;
1421
1422 // We try to eliminate redundant compare instruction.
1423 Simplified |= eliminateRedundantCompare();
1424
1425 // If we have made any modifications and added any registers to the set of
1426 // registers whose liveness flags may now be stale, clear those flags. A
1427 // transform may remove a use (leaving a stale kill on an earlier use) or add
1428 // a use of a previously dead def (leaving a stale dead flag), so clear both
1429 // kinds conservatively.
1430 for (Register Reg : RegsToUpdate) {
1431 if (MRI->reg_empty(Reg))
1432 continue;
1433 MRI->clearKillFlags(Reg);
1434 for (MachineOperand &Def : MRI->def_operands(Reg))
1435 Def.setIsDead(false);
1436 }
1437 return Simplified;
1438}
1439
1440// helper functions for eliminateRedundantCompare
1441static bool isEqOrNe(MachineInstr *BI) {
1443 unsigned PredCond = PPC::getPredicateCondition(Pred);
1444 return (PredCond == PPC::PRED_EQ || PredCond == PPC::PRED_NE);
1445}
1446
1447static bool isSupportedCmpOp(unsigned opCode) {
1448 return (opCode == PPC::CMPLD || opCode == PPC::CMPD ||
1449 opCode == PPC::CMPLW || opCode == PPC::CMPW ||
1450 opCode == PPC::CMPLDI || opCode == PPC::CMPDI ||
1451 opCode == PPC::CMPLWI || opCode == PPC::CMPWI);
1452}
1453
1454static bool is64bitCmpOp(unsigned opCode) {
1455 return (opCode == PPC::CMPLD || opCode == PPC::CMPD ||
1456 opCode == PPC::CMPLDI || opCode == PPC::CMPDI);
1457}
1458
1459static bool isSignedCmpOp(unsigned opCode) {
1460 return (opCode == PPC::CMPD || opCode == PPC::CMPW ||
1461 opCode == PPC::CMPDI || opCode == PPC::CMPWI);
1462}
1463
1464static unsigned getSignedCmpOpCode(unsigned opCode) {
1465 if (opCode == PPC::CMPLD) return PPC::CMPD;
1466 if (opCode == PPC::CMPLW) return PPC::CMPW;
1467 if (opCode == PPC::CMPLDI) return PPC::CMPDI;
1468 if (opCode == PPC::CMPLWI) return PPC::CMPWI;
1469 return opCode;
1470}
1471
1472// We can decrement immediate x in (GE x) by changing it to (GT x-1) or
1473// (LT x) to (LE x-1)
1474static unsigned getPredicateToDecImm(MachineInstr *BI, MachineInstr *CMPI) {
1475 uint64_t Imm = CMPI->getOperand(2).getImm();
1476 bool SignedCmp = isSignedCmpOp(CMPI->getOpcode());
1477 if ((!SignedCmp && Imm == 0) || (SignedCmp && Imm == 0x8000))
1478 return 0;
1479
1481 unsigned PredCond = PPC::getPredicateCondition(Pred);
1482 unsigned PredHint = PPC::getPredicateHint(Pred);
1483 if (PredCond == PPC::PRED_GE)
1484 return PPC::getPredicate(PPC::PRED_GT, PredHint);
1485 if (PredCond == PPC::PRED_LT)
1486 return PPC::getPredicate(PPC::PRED_LE, PredHint);
1487
1488 return 0;
1489}
1490
1491// We can increment immediate x in (GT x) by changing it to (GE x+1) or
1492// (LE x) to (LT x+1)
1493static unsigned getPredicateToIncImm(MachineInstr *BI, MachineInstr *CMPI) {
1494 uint64_t Imm = CMPI->getOperand(2).getImm();
1495 bool SignedCmp = isSignedCmpOp(CMPI->getOpcode());
1496 if ((!SignedCmp && Imm == 0xFFFF) || (SignedCmp && Imm == 0x7FFF))
1497 return 0;
1498
1500 unsigned PredCond = PPC::getPredicateCondition(Pred);
1501 unsigned PredHint = PPC::getPredicateHint(Pred);
1502 if (PredCond == PPC::PRED_GT)
1503 return PPC::getPredicate(PPC::PRED_GE, PredHint);
1504 if (PredCond == PPC::PRED_LE)
1505 return PPC::getPredicate(PPC::PRED_LT, PredHint);
1506
1507 return 0;
1508}
1509
1510// This takes a Phi node and returns a register value for the specified BB.
1511static unsigned getIncomingRegForBlock(MachineInstr *Phi,
1512 MachineBasicBlock *MBB) {
1513 for (unsigned I = 2, E = Phi->getNumOperands() + 1; I != E; I += 2) {
1514 MachineOperand &MO = Phi->getOperand(I);
1515 if (MO.getMBB() == MBB)
1516 return Phi->getOperand(I-1).getReg();
1517 }
1518 llvm_unreachable("invalid src basic block for this Phi node\n");
1519 return 0;
1520}
1521
1522// This function tracks the source of the register through register copy.
1523// If BB1 and BB2 are non-NULL, we also track PHI instruction in BB2
1524// assuming that the control comes from BB1 into BB2.
1525static unsigned getSrcVReg(unsigned Reg, MachineBasicBlock *BB1,
1526 MachineBasicBlock *BB2, MachineRegisterInfo *MRI) {
1527 unsigned SrcReg = Reg;
1528 while (true) {
1529 unsigned NextReg = SrcReg;
1530 MachineInstr *Inst = MRI->getVRegDef(SrcReg);
1531 if (BB1 && Inst->getOpcode() == PPC::PHI && Inst->getParent() == BB2) {
1532 NextReg = getIncomingRegForBlock(Inst, BB1);
1533 // We track through PHI only once to avoid infinite loop.
1534 BB1 = nullptr;
1535 }
1536 else if (Inst->isFullCopy())
1537 NextReg = Inst->getOperand(1).getReg();
1538 if (NextReg == SrcReg || !Register::isVirtualRegister(NextReg))
1539 break;
1540 SrcReg = NextReg;
1541 }
1542 return SrcReg;
1543}
1544
1545static bool eligibleForCompareElimination(MachineBasicBlock &MBB,
1546 MachineBasicBlock *&PredMBB,
1547 MachineBasicBlock *&MBBtoMoveCmp,
1548 MachineRegisterInfo *MRI) {
1549
1550 auto isEligibleBB = [&](MachineBasicBlock &BB) {
1551 auto BII = BB.getFirstInstrTerminator();
1552 // We optimize BBs ending with a conditional branch.
1553 // We check only for BCC here, not BCCLR, because BCCLR
1554 // will be formed only later in the pipeline.
1555 if (BB.succ_size() == 2 &&
1556 BII != BB.instr_end() &&
1557 (*BII).getOpcode() == PPC::BCC &&
1558 (*BII).getOperand(1).isReg()) {
1559 // We optimize only if the condition code is used only by one BCC.
1560 Register CndReg = (*BII).getOperand(1).getReg();
1561 if (!CndReg.isVirtual() || !MRI->hasOneNonDBGUse(CndReg))
1562 return false;
1563
1564 MachineInstr *CMPI = MRI->getVRegDef(CndReg);
1565 // We assume compare and branch are in the same BB for ease of analysis.
1566 if (CMPI->getParent() != &BB)
1567 return false;
1568
1569 // We skip this BB if a physical register is used in comparison.
1570 for (MachineOperand &MO : CMPI->operands())
1571 if (MO.isReg() && !MO.getReg().isVirtual())
1572 return false;
1573
1574 return true;
1575 }
1576 return false;
1577 };
1578
1579 // If this BB has more than one successor, we can create a new BB and
1580 // move the compare instruction in the new BB.
1581 // So far, we do not move compare instruction to a BB having multiple
1582 // successors to avoid potentially increasing code size.
1583 auto isEligibleForMoveCmp = [](MachineBasicBlock &BB) {
1584 return BB.succ_size() == 1;
1585 };
1586
1587 if (!isEligibleBB(MBB))
1588 return false;
1589
1590 unsigned NumPredBBs = MBB.pred_size();
1591 if (NumPredBBs == 1) {
1592 MachineBasicBlock *TmpMBB = *MBB.pred_begin();
1593 if (isEligibleBB(*TmpMBB)) {
1594 PredMBB = TmpMBB;
1595 MBBtoMoveCmp = nullptr;
1596 return true;
1597 }
1598 }
1599 else if (NumPredBBs == 2) {
1600 // We check for partially redundant case.
1601 // So far, we support cases with only two predecessors
1602 // to avoid increasing the number of instructions.
1604 MachineBasicBlock *Pred1MBB = *PI;
1605 MachineBasicBlock *Pred2MBB = *(PI+1);
1606
1607 if (isEligibleBB(*Pred1MBB) && isEligibleForMoveCmp(*Pred2MBB)) {
1608 // We assume Pred1MBB is the BB containing the compare to be merged and
1609 // Pred2MBB is the BB to which we will append a compare instruction.
1610 // Proceed as is if Pred1MBB is different from MBB.
1611 }
1612 else if (isEligibleBB(*Pred2MBB) && isEligibleForMoveCmp(*Pred1MBB)) {
1613 // We need to swap Pred1MBB and Pred2MBB to canonicalize.
1614 std::swap(Pred1MBB, Pred2MBB);
1615 }
1616 else return false;
1617
1618 if (Pred1MBB == &MBB)
1619 return false;
1620
1621 // Here, Pred2MBB is the BB to which we need to append a compare inst.
1622 // We cannot move the compare instruction if operands are not available
1623 // in Pred2MBB (i.e. defined in MBB by an instruction other than PHI).
1624 MachineInstr *BI = &*MBB.getFirstInstrTerminator();
1625 MachineInstr *CMPI = MRI->getVRegDef(BI->getOperand(1).getReg());
1626 for (int I = 1; I <= 2; I++)
1627 if (CMPI->getOperand(I).isReg()) {
1628 MachineInstr *Inst = MRI->getVRegDef(CMPI->getOperand(I).getReg());
1629 if (Inst->getParent() == &MBB && Inst->getOpcode() != PPC::PHI)
1630 return false;
1631 }
1632
1633 PredMBB = Pred1MBB;
1634 MBBtoMoveCmp = Pred2MBB;
1635 return true;
1636 }
1637
1638 return false;
1639}
1640
1641// This function will iterate over the input map containing a pair of TOC save
1642// instruction and a flag. The flag will be set to false if the TOC save is
1643// proven redundant. This function will erase from the basic block all the TOC
1644// saves marked as redundant.
1645bool PPCMIPeephole::eliminateRedundantTOCSaves(
1646 std::map<MachineInstr *, bool> &TOCSaves) {
1647 bool Simplified = false;
1648 int NumKept = 0;
1649 for (auto TOCSave : TOCSaves) {
1650 if (!TOCSave.second) {
1651 TOCSave.first->eraseFromParent();
1652 RemoveTOCSave++;
1653 Simplified = true;
1654 } else {
1655 NumKept++;
1656 }
1657 }
1658
1659 if (NumKept > 1)
1660 MultiTOCSaves++;
1661
1662 return Simplified;
1663}
1664
1665// If multiple conditional branches are executed based on the (essentially)
1666// same comparison, we merge compare instructions into one and make multiple
1667// conditional branches on this comparison.
1668// For example,
1669// if (a == 0) { ... }
1670// else if (a < 0) { ... }
1671// can be executed by one compare and two conditional branches instead of
1672// two pairs of a compare and a conditional branch.
1673//
1674// This method merges two compare instructions in two MBBs and modifies the
1675// compare and conditional branch instructions if needed.
1676// For the above example, the input for this pass looks like:
1677// cmplwi r3, 0
1678// beq 0, .LBB0_3
1679// cmpwi r3, -1
1680// bgt 0, .LBB0_4
1681// So, before merging two compares, we need to modify these instructions as
1682// cmpwi r3, 0 ; cmplwi and cmpwi yield same result for beq
1683// beq 0, .LBB0_3
1684// cmpwi r3, 0 ; greather than -1 means greater or equal to 0
1685// bge 0, .LBB0_4
1686
1687bool PPCMIPeephole::eliminateRedundantCompare() {
1688 bool Simplified = false;
1689
1690 for (MachineBasicBlock &MBB2 : *MF) {
1691 MachineBasicBlock *MBB1 = nullptr, *MBBtoMoveCmp = nullptr;
1692
1693 // For fully redundant case, we select two basic blocks MBB1 and MBB2
1694 // as an optimization target if
1695 // - both MBBs end with a conditional branch,
1696 // - MBB1 is the only predecessor of MBB2, and
1697 // - compare does not take a physical register as a operand in both MBBs.
1698 // In this case, eligibleForCompareElimination sets MBBtoMoveCmp nullptr.
1699 //
1700 // As partially redundant case, we additionally handle if MBB2 has one
1701 // additional predecessor, which has only one successor (MBB2).
1702 // In this case, we move the compare instruction originally in MBB2 into
1703 // MBBtoMoveCmp. This partially redundant case is typically appear by
1704 // compiling a while loop; here, MBBtoMoveCmp is the loop preheader.
1705 //
1706 // Overview of CFG of related basic blocks
1707 // Fully redundant case Partially redundant case
1708 // -------- ---------------- --------
1709 // | MBB1 | (w/ 2 succ) | MBBtoMoveCmp | | MBB1 | (w/ 2 succ)
1710 // -------- ---------------- --------
1711 // | \ (w/ 1 succ) \ | \
1712 // | \ \ | \
1713 // | \ |
1714 // -------- --------
1715 // | MBB2 | (w/ 1 pred | MBB2 | (w/ 2 pred
1716 // -------- and 2 succ) -------- and 2 succ)
1717 // | \ | \
1718 // | \ | \
1719 //
1720 if (!eligibleForCompareElimination(MBB2, MBB1, MBBtoMoveCmp, MRI))
1721 continue;
1722
1723 MachineInstr *BI1 = &*MBB1->getFirstInstrTerminator();
1724 MachineInstr *CMPI1 = MRI->getVRegDef(BI1->getOperand(1).getReg());
1725
1726 MachineInstr *BI2 = &*MBB2.getFirstInstrTerminator();
1727 MachineInstr *CMPI2 = MRI->getVRegDef(BI2->getOperand(1).getReg());
1728 bool IsPartiallyRedundant = (MBBtoMoveCmp != nullptr);
1729
1730 // We cannot optimize an unsupported compare opcode or
1731 // a mix of 32-bit and 64-bit comparisons
1732 if (!isSupportedCmpOp(CMPI1->getOpcode()) ||
1733 !isSupportedCmpOp(CMPI2->getOpcode()) ||
1734 is64bitCmpOp(CMPI1->getOpcode()) != is64bitCmpOp(CMPI2->getOpcode()))
1735 continue;
1736
1737 unsigned NewOpCode = 0;
1738 unsigned NewPredicate1 = 0, NewPredicate2 = 0;
1739 int16_t Imm1 = 0, NewImm1 = 0, Imm2 = 0, NewImm2 = 0;
1740 bool SwapOperands = false;
1741
1742 if (CMPI1->getOpcode() != CMPI2->getOpcode()) {
1743 // Typically, unsigned comparison is used for equality check, but
1744 // we replace it with a signed comparison if the comparison
1745 // to be merged is a signed comparison.
1746 // In other cases of opcode mismatch, we cannot optimize this.
1747
1748 // We cannot change opcode when comparing against an immediate
1749 // if the most significant bit of the immediate is one
1750 // due to the difference in sign extension.
1751 auto CmpAgainstImmWithSignBit = [](MachineInstr *I) {
1752 if (!I->getOperand(2).isImm())
1753 return false;
1754 int16_t Imm = (int16_t)I->getOperand(2).getImm();
1755 return Imm < 0;
1756 };
1757
1758 if (isEqOrNe(BI2) && !CmpAgainstImmWithSignBit(CMPI2) &&
1759 CMPI1->getOpcode() == getSignedCmpOpCode(CMPI2->getOpcode()))
1760 NewOpCode = CMPI1->getOpcode();
1761 else if (isEqOrNe(BI1) && !CmpAgainstImmWithSignBit(CMPI1) &&
1762 getSignedCmpOpCode(CMPI1->getOpcode()) == CMPI2->getOpcode())
1763 NewOpCode = CMPI2->getOpcode();
1764 else continue;
1765 }
1766
1767 if (CMPI1->getOperand(2).isReg() && CMPI2->getOperand(2).isReg()) {
1768 // In case of comparisons between two registers, these two registers
1769 // must be same to merge two comparisons.
1770 unsigned Cmp1Operand1 = getSrcVReg(CMPI1->getOperand(1).getReg(),
1771 nullptr, nullptr, MRI);
1772 unsigned Cmp1Operand2 = getSrcVReg(CMPI1->getOperand(2).getReg(),
1773 nullptr, nullptr, MRI);
1774 unsigned Cmp2Operand1 = getSrcVReg(CMPI2->getOperand(1).getReg(),
1775 MBB1, &MBB2, MRI);
1776 unsigned Cmp2Operand2 = getSrcVReg(CMPI2->getOperand(2).getReg(),
1777 MBB1, &MBB2, MRI);
1778
1779 if (Cmp1Operand1 == Cmp2Operand1 && Cmp1Operand2 == Cmp2Operand2) {
1780 // Same pair of registers in the same order; ready to merge as is.
1781 }
1782 else if (Cmp1Operand1 == Cmp2Operand2 && Cmp1Operand2 == Cmp2Operand1) {
1783 // Same pair of registers in different order.
1784 // We reverse the predicate to merge compare instructions.
1786 NewPredicate2 = (unsigned)PPC::getSwappedPredicate(Pred);
1787 // In case of partial redundancy, we need to swap operands
1788 // in another compare instruction.
1789 SwapOperands = true;
1790 }
1791 else continue;
1792 }
1793 else if (CMPI1->getOperand(2).isImm() && CMPI2->getOperand(2).isImm()) {
1794 // In case of comparisons between a register and an immediate,
1795 // the operand register must be same for two compare instructions.
1796 unsigned Cmp1Operand1 = getSrcVReg(CMPI1->getOperand(1).getReg(),
1797 nullptr, nullptr, MRI);
1798 unsigned Cmp2Operand1 = getSrcVReg(CMPI2->getOperand(1).getReg(),
1799 MBB1, &MBB2, MRI);
1800 if (Cmp1Operand1 != Cmp2Operand1)
1801 continue;
1802
1803 NewImm1 = Imm1 = (int16_t)CMPI1->getOperand(2).getImm();
1804 NewImm2 = Imm2 = (int16_t)CMPI2->getOperand(2).getImm();
1805
1806 // If immediate are not same, we try to adjust by changing predicate;
1807 // e.g. GT imm means GE (imm+1).
1808 if (Imm1 != Imm2 && (!isEqOrNe(BI2) || !isEqOrNe(BI1))) {
1809 int Diff = Imm1 - Imm2;
1810 if (Diff < -2 || Diff > 2)
1811 continue;
1812
1813 unsigned PredToInc1 = getPredicateToIncImm(BI1, CMPI1);
1814 unsigned PredToDec1 = getPredicateToDecImm(BI1, CMPI1);
1815 unsigned PredToInc2 = getPredicateToIncImm(BI2, CMPI2);
1816 unsigned PredToDec2 = getPredicateToDecImm(BI2, CMPI2);
1817 if (Diff == 2) {
1818 if (PredToInc2 && PredToDec1) {
1819 NewPredicate2 = PredToInc2;
1820 NewPredicate1 = PredToDec1;
1821 NewImm2++;
1822 NewImm1--;
1823 }
1824 }
1825 else if (Diff == 1) {
1826 if (PredToInc2) {
1827 NewImm2++;
1828 NewPredicate2 = PredToInc2;
1829 }
1830 else if (PredToDec1) {
1831 NewImm1--;
1832 NewPredicate1 = PredToDec1;
1833 }
1834 }
1835 else if (Diff == -1) {
1836 if (PredToDec2) {
1837 NewImm2--;
1838 NewPredicate2 = PredToDec2;
1839 }
1840 else if (PredToInc1) {
1841 NewImm1++;
1842 NewPredicate1 = PredToInc1;
1843 }
1844 }
1845 else if (Diff == -2) {
1846 if (PredToDec2 && PredToInc1) {
1847 NewPredicate2 = PredToDec2;
1848 NewPredicate1 = PredToInc1;
1849 NewImm2--;
1850 NewImm1++;
1851 }
1852 }
1853 }
1854
1855 // We cannot merge two compares if the immediates are not same.
1856 if (NewImm2 != NewImm1)
1857 continue;
1858 }
1859
1860 LLVM_DEBUG(dbgs() << "Optimize two pairs of compare and branch:\n");
1861 LLVM_DEBUG(CMPI1->dump());
1862 LLVM_DEBUG(BI1->dump());
1863 LLVM_DEBUG(CMPI2->dump());
1864 LLVM_DEBUG(BI2->dump());
1865 for (const MachineOperand &MO : CMPI1->operands())
1866 if (MO.isReg())
1867 addRegToUpdate(MO.getReg());
1868 for (const MachineOperand &MO : CMPI2->operands())
1869 if (MO.isReg())
1870 addRegToUpdate(MO.getReg());
1871
1872 // We adjust opcode, predicates and immediate as we determined above.
1873 if (NewOpCode != 0 && NewOpCode != CMPI1->getOpcode()) {
1874 CMPI1->setDesc(TII->get(NewOpCode));
1875 }
1876 if (NewPredicate1) {
1877 BI1->getOperand(0).setImm(NewPredicate1);
1878 }
1879 if (NewPredicate2) {
1880 BI2->getOperand(0).setImm(NewPredicate2);
1881 }
1882 if (NewImm1 != Imm1) {
1883 CMPI1->getOperand(2).setImm(NewImm1);
1884 }
1885
1886 if (IsPartiallyRedundant) {
1887 // We touch up the compare instruction in MBB2 and move it to
1888 // a previous BB to handle partially redundant case.
1889 if (SwapOperands) {
1890 Register Op1 = CMPI2->getOperand(1).getReg();
1891 Register Op2 = CMPI2->getOperand(2).getReg();
1892 CMPI2->getOperand(1).setReg(Op2);
1893 CMPI2->getOperand(2).setReg(Op1);
1894 }
1895 if (NewImm2 != Imm2)
1896 CMPI2->getOperand(2).setImm(NewImm2);
1897
1898 for (int I = 1; I <= 2; I++) {
1899 if (CMPI2->getOperand(I).isReg()) {
1900 MachineInstr *Inst = MRI->getVRegDef(CMPI2->getOperand(I).getReg());
1901 if (Inst->getParent() != &MBB2)
1902 continue;
1903
1904 assert(Inst->getOpcode() == PPC::PHI &&
1905 "We cannot support if an operand comes from this BB.");
1906 unsigned SrcReg = getIncomingRegForBlock(Inst, MBBtoMoveCmp);
1907 CMPI2->getOperand(I).setReg(SrcReg);
1908 addRegToUpdate(SrcReg);
1909 }
1910 }
1911 auto I = MachineBasicBlock::iterator(MBBtoMoveCmp->getFirstTerminator());
1912 MBBtoMoveCmp->splice(I, &MBB2, MachineBasicBlock::iterator(CMPI2));
1913
1914 DebugLoc DL = CMPI2->getDebugLoc();
1915 Register NewVReg = MRI->createVirtualRegister(&PPC::CRRCRegClass);
1916 BuildMI(MBB2, MBB2.begin(), DL,
1917 TII->get(PPC::PHI), NewVReg)
1918 .addReg(BI1->getOperand(1).getReg()).addMBB(MBB1)
1919 .addReg(BI2->getOperand(1).getReg()).addMBB(MBBtoMoveCmp);
1920 BI2->getOperand(1).setReg(NewVReg);
1921 addRegToUpdate(NewVReg);
1922 }
1923 else {
1924 // We finally eliminate compare instruction in MBB2.
1925 // We do not need to treat CMPI2 specially here in terms of re-computing
1926 // live variables even though it is being deleted because:
1927 // - It defines a register that has a single use (already checked in
1928 // eligibleForCompareElimination())
1929 // - The only user (BI2) is no longer using it so the register is dead (no
1930 // def, no uses)
1931 // - We do not attempt to recompute live variables for dead registers
1932 BI2->getOperand(1).setReg(BI1->getOperand(1).getReg());
1933 CMPI2->eraseFromParent();
1934 }
1935
1936 LLVM_DEBUG(dbgs() << "into a compare and two branches:\n");
1937 LLVM_DEBUG(CMPI1->dump());
1938 LLVM_DEBUG(BI1->dump());
1939 LLVM_DEBUG(BI2->dump());
1940 if (IsPartiallyRedundant) {
1941 LLVM_DEBUG(dbgs() << "The following compare is moved into "
1942 << printMBBReference(*MBBtoMoveCmp)
1943 << " to handle partial redundancy.\n");
1944 LLVM_DEBUG(CMPI2->dump());
1945 }
1946 Simplified = true;
1947 }
1948
1949 return Simplified;
1950}
1951
1952// We miss the opportunity to emit an RLDIC when lowering jump tables
1953// since ISEL sees only a single basic block. When selecting, the clear
1954// and shift left will be in different blocks.
1955bool PPCMIPeephole::emitRLDICWhenLoweringJumpTables(MachineInstr &MI,
1956 MachineInstr *&ToErase) {
1957 if (MI.getOpcode() != PPC::RLDICR)
1958 return false;
1959
1960 Register SrcReg = MI.getOperand(1).getReg();
1961 if (!SrcReg.isVirtual())
1962 return false;
1963
1964 MachineInstr *SrcMI = MRI->getVRegDef(SrcReg);
1965 if (SrcMI->getOpcode() != PPC::RLDICL)
1966 return false;
1967
1968 MachineOperand MOpSHSrc = SrcMI->getOperand(2);
1969 MachineOperand MOpMBSrc = SrcMI->getOperand(3);
1970 MachineOperand MOpSHMI = MI.getOperand(2);
1971 MachineOperand MOpMEMI = MI.getOperand(3);
1972 if (!(MOpSHSrc.isImm() && MOpMBSrc.isImm() && MOpSHMI.isImm() &&
1973 MOpMEMI.isImm()))
1974 return false;
1975
1976 uint64_t SHSrc = MOpSHSrc.getImm();
1977 uint64_t MBSrc = MOpMBSrc.getImm();
1978 uint64_t SHMI = MOpSHMI.getImm();
1979 uint64_t MEMI = MOpMEMI.getImm();
1980 uint64_t NewSH = SHSrc + SHMI;
1981 uint64_t NewMB = MBSrc - SHMI;
1982 if (NewMB > 63 || NewSH > 63)
1983 return false;
1984
1985 // The bits cleared with RLDICL are [0, MBSrc).
1986 // The bits cleared with RLDICR are (MEMI, 63].
1987 // After the sequence, the bits cleared are:
1988 // [0, MBSrc-SHMI) and (MEMI, 63).
1989 //
1990 // The bits cleared with RLDIC are [0, NewMB) and (63-NewSH, 63].
1991 if ((63 - NewSH) != MEMI)
1992 return false;
1993
1994 LLVM_DEBUG(dbgs() << "Converting pair: ");
1995 LLVM_DEBUG(SrcMI->dump());
1996 LLVM_DEBUG(MI.dump());
1997
1998 MI.setDesc(TII->get(PPC::RLDIC));
1999 MI.getOperand(1).setReg(SrcMI->getOperand(1).getReg());
2000 MI.getOperand(2).setImm(NewSH);
2001 MI.getOperand(3).setImm(NewMB);
2002 addRegToUpdate(MI.getOperand(1).getReg());
2003 addRegToUpdate(SrcMI->getOperand(0).getReg());
2004
2005 LLVM_DEBUG(dbgs() << "To: ");
2006 LLVM_DEBUG(MI.dump());
2007 NumRotatesCollapsed++;
2008 // If SrcReg has no non-debug use it's safe to delete its def SrcMI.
2009 if (MRI->use_nodbg_empty(SrcReg)) {
2010 assert(!SrcMI->hasImplicitDef() &&
2011 "Not expecting an implicit def with this instr.");
2012 ToErase = SrcMI;
2013 }
2014 return true;
2015}
2016
2017// For case in LLVM IR
2018// entry:
2019// %iconv = sext i32 %index to i64
2020// br i1 undef label %true, label %false
2021// true:
2022// %ptr = getelementptr inbounds i32, i32* null, i64 %iconv
2023// ...
2024// PPCISelLowering::combineSHL fails to combine, because sext and shl are in
2025// different BBs when conducting instruction selection. We can do a peephole
2026// optimization to combine these two instructions into extswsli after
2027// instruction selection.
2028bool PPCMIPeephole::combineSEXTAndSHL(MachineInstr &MI,
2029 MachineInstr *&ToErase) {
2030 if (MI.getOpcode() != PPC::RLDICR)
2031 return false;
2032
2033 if (!MF->getSubtarget<PPCSubtarget>().isISA3_0())
2034 return false;
2035
2036 assert(MI.getNumOperands() == 4 && "RLDICR should have 4 operands");
2037
2038 MachineOperand MOpSHMI = MI.getOperand(2);
2039 MachineOperand MOpMEMI = MI.getOperand(3);
2040 if (!(MOpSHMI.isImm() && MOpMEMI.isImm()))
2041 return false;
2042
2043 uint64_t SHMI = MOpSHMI.getImm();
2044 uint64_t MEMI = MOpMEMI.getImm();
2045 if (SHMI + MEMI != 63)
2046 return false;
2047
2048 Register SrcReg = MI.getOperand(1).getReg();
2049 if (!SrcReg.isVirtual())
2050 return false;
2051
2052 MachineInstr *SrcMI = MRI->getVRegDef(SrcReg);
2053 if (SrcMI->getOpcode() != PPC::EXTSW &&
2054 SrcMI->getOpcode() != PPC::EXTSW_32_64)
2055 return false;
2056
2057 // If the register defined by extsw has more than one use, combination is not
2058 // needed.
2059 if (!MRI->hasOneNonDBGUse(SrcReg))
2060 return false;
2061
2062 assert(SrcMI->getNumOperands() == 2 && "EXTSW should have 2 operands");
2063 assert(SrcMI->getOperand(1).isReg() &&
2064 "EXTSW's second operand should be a register");
2065 if (!SrcMI->getOperand(1).getReg().isVirtual())
2066 return false;
2067
2068 LLVM_DEBUG(dbgs() << "Combining pair: ");
2069 LLVM_DEBUG(SrcMI->dump());
2070 LLVM_DEBUG(MI.dump());
2071
2072 MachineInstr *NewInstr =
2073 BuildMI(*MI.getParent(), &MI, MI.getDebugLoc(),
2074 SrcMI->getOpcode() == PPC::EXTSW ? TII->get(PPC::EXTSWSLI)
2075 : TII->get(PPC::EXTSWSLI_32_64),
2076 MI.getOperand(0).getReg())
2077 .add(SrcMI->getOperand(1))
2078 .add(MOpSHMI);
2079 (void)NewInstr;
2080
2081 LLVM_DEBUG(dbgs() << "TO: ");
2082 LLVM_DEBUG(NewInstr->dump());
2083 ++NumEXTSWAndSLDICombined;
2084 ToErase = &MI;
2085 // SrcMI, which is extsw, is of no use now, but we don't erase it here so we
2086 // can recompute its kill flags. We run DCE immediately after this pass
2087 // to clean up dead instructions such as this.
2088 addRegToUpdate(NewInstr->getOperand(1).getReg());
2089 addRegToUpdate(SrcMI->getOperand(0).getReg());
2090 return true;
2091}
2092
2093} // end default namespace
2094
2096 "PowerPC MI Peephole Optimization", false, false)
2101 "PowerPC MI Peephole Optimization", false, false)
2102
2103char PPCMIPeephole::ID = 0;
2105llvm::createPPCMIPeepholePass() { return new PPCMIPeephole(); }
MachineInstrBuilder & UseMI
MachineInstrBuilder MachineInstrBuilder & DefMI
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
uint64_t uint64_t
uint64_t Imm
Rewrite undef for PHI
MachineBasicBlock & MBB
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
static GCRegistry::Add< ShadowStackGC > C("shadow-stack", "Very portable GC for uncooperative code generators")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
This file provides an implementation of debug counters.
#define DEBUG_COUNTER(VARNAME, COUNTERNAME, DESC)
#define DEBUG_TYPE
static Register UseReg(const MachineOperand &MO)
const HexagonInstrInfo * TII
IRTranslator LLVM IR MI
const size_t AbstractManglingParser< Derived, Alloc >::NumOps
#define I(x, y, z)
Definition MD5.cpp:57
Register Reg
Register const TargetRegisterInfo * TRI
Promote Memory to Register
Definition Mem2Reg.cpp:110
#define addRegToUpdate(R)
static cl::opt< bool > EnableZExtElimination("ppc-eliminate-zeroext", cl::desc("enable elimination of zero-extensions"), cl::init(true), cl::Hidden)
static cl::opt< bool > FixedPointRegToImm("ppc-reg-to-imm-fixed-point", cl::Hidden, cl::init(true), cl::desc("Iterate to a fixed point when attempting to " "convert reg-reg instructions to reg-imm"))
static cl::opt< bool > EnableTrapOptimization("ppc-opt-conditional-trap", cl::desc("enable optimization of conditional traps"), cl::init(false), cl::Hidden)
static cl::opt< bool > ConvertRegReg("ppc-convert-rr-to-ri", cl::Hidden, cl::init(true), cl::desc("Convert eligible reg+reg instructions to reg+imm"))
static cl::opt< bool > EnableSExtElimination("ppc-eliminate-signext", cl::desc("enable elimination of sign-extensions"), cl::init(true), cl::Hidden)
#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
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
#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.
static bool shouldExecute(CounterInfo &Counter)
size_type count(const_arg_type_t< KeyT > Val) const
Return 1 if the specified key is in the map, 0 otherwise.
Definition DenseMap.h:762
ValueT lookup(const_arg_type_t< KeyT > Val) const
Return the entry for the specified key, or a default constructed value if no such entry exists.
Definition DenseMap.h:793
bool dominates(const DomTreeNodeBase< NodeT > *A, const DomTreeNodeBase< NodeT > *B) const
dominates - Returns true iff A dominates B.
FunctionPass class - This class is used to implement most global optimizations.
Definition Pass.h:312
MaybeAlign getAlign() const
Returns the alignment of the given variable.
const HexagonRegisterInfo & getRegisterInfo() const
static MDTuple * get(LLVMContext &Context, ArrayRef< Metadata * > MDs)
Definition Metadata.h:1579
LLVM_ABI iterator getFirstTerminator()
Returns an iterator to the first terminator instruction of this basic block.
SmallVectorImpl< MachineBasicBlock * >::iterator pred_iterator
const MachineFunction * getParent() const
Return the MachineFunction containing this basic block.
LLVM_ABI instr_iterator getFirstInstrTerminator()
Same getFirstTerminator but it ignores bundles and return an instr_iterator instead.
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 BlockFrequency getBlockFreq(const MachineBasicBlock *MBB) const
getblockFreq - Return block frequency.
LLVM_ABI BlockFrequency getEntryFreq() const
Divide a block's BlockFrequency::getFrequency() value by this value to obtain the entry block - relat...
Analysis pass which computes a MachineDominatorTree.
bool dominates(const MachineInstr *A, const MachineInstr *B) const
bool hasVarSizedObjects() const
This method may be called any time after instruction selection is complete to determine if the stack ...
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.
void dump() const
dump - Print the current MachineFunction to cerr, useful for debugger use.
MachineRegisterInfo & getRegInfo()
getRegInfo - Return information about the registers currently in use.
Ty * getInfo()
getInfo - Keep track of various per-function pieces of information for backends that would like to do...
const MachineBasicBlock & front() const
const MachineInstrBuilder & addReg(Register RegNo, RegState Flags={}, unsigned SubReg=0) const
Add a new virtual register operand.
const MachineInstrBuilder & addImm(int64_t Val) const
Add a new immediate operand.
const MachineInstrBuilder & add(const MachineOperand &MO) const
const MachineInstrBuilder & addMBB(MachineBasicBlock *MBB, unsigned TargetFlags=0) const
MachineInstr * getInstr() const
If conversion operators fail, use this method to get the MachineInstr explicitly.
unsigned getOpcode() const
Returns the opcode of this MachineInstr.
const MachineBasicBlock * getParent() const
unsigned getNumOperands() const
Retuns the total number of operands.
bool hasImplicitDef() const
Returns true if the instruction has implicit definition.
bool isFullCopy() const
mop_range operands()
mop_range explicit_uses()
LLVM_ABI void setDesc(const MCInstrDesc &TID)
Replace the instruction descriptor (thus opcode) of the current instruction with a new one.
const DebugLoc & getDebugLoc() const
Returns the debug location id of this MachineInstr.
LLVM_ABI void removeOperand(unsigned OpNo)
Erase an operand from an instruction, leaving it with one fewer operand than it started with.
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.
const GlobalValue * getGlobal() const
void setImm(int64_t immVal)
int64_t getImm() const
bool isReg() const
isReg - Tests if this is a MO_Register operand.
MachineBasicBlock * getMBB() const
LLVM_ABI void setReg(Register Reg)
Change the register this operand corresponds to.
bool isImm() const
isImm - Tests if this is a MO_Immediate operand.
bool isGlobal() const
isGlobal - Tests if this is a MO_GlobalAddress operand.
Register getReg() const
getReg - Returns the register number.
static MachineOperand CreateReg(Register Reg, bool isDef, bool isImp=false, bool isKill=false, bool isDead=false, bool isUndef=false, bool isEarlyClobber=false, unsigned SubReg=0, bool isDebug=false, bool isInternalRead=false, bool isRenamable=false)
int64_t getOffset() const
Return the offset from the symbol in this operand.
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.
const TargetRegisterClass * getRegClass(Register Reg) const
Return the register class of the specified virtual register.
LLVM_ABI void clearKillFlags(Register Reg) const
clearKillFlags - Iterate over all the uses of the given register and clear the kill flag from the Mac...
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 ...
bool use_nodbg_empty(Register RegNo) const
use_nodbg_empty - Return true if there are no non-Debug instructions using the specified register.
LLVM_ABI Register createVirtualRegister(const TargetRegisterClass *RegClass, StringRef Name="")
createVirtualRegister - Create and return a new virtual register in the function with the specified r...
use_instr_nodbg_iterator use_instr_nodbg_begin(Register RegNo) const
LLVM_ABI bool hasOneNonDBGUser(Register RegNo) const
hasOneNonDBGUse - Return true if there is exactly one non-Debug instruction using the specified regis...
iterator_range< def_iterator > def_operands(Register Reg) const
LLVM_ABI void setRegClass(Register Reg, const TargetRegisterClass *RC)
setRegClass - Set the register class of the specified virtual register.
const TargetRegisterClass * getRegClassOrNull(Register Reg) const
Return the register class of Reg, or null if Reg has not been assigned a register class yet.
iterator_range< use_instr_iterator > use_instructions(Register Reg) const
LLVM_ABI const TargetRegisterClass * constrainRegClass(Register Reg, const TargetRegisterClass *RC, unsigned MinNumRegs=0)
constrainRegClass - Constrain the register class of the specified virtual register to be a common sub...
bool reg_empty(Register RegNo) const
reg_empty - Return true if there are no instructions using or defining the specified register (it may...
LLVM_ABI LLVM_READONLY MachineInstr * getUniqueVRegDef(Register Reg) const
getUniqueVRegDef - Return the unique machine instr that defines the specified virtual register or nul...
Wrapper class representing virtual and physical registers.
Definition Register.h:20
constexpr bool isVirtual() const
Return true if the specified register number is in the virtual register namespace.
Definition Register.h:79
size_type count(const T &V) const
count - Return 1 if the element is in the set, 0 otherwise.
Definition SmallSet.h:176
bool empty() const
Definition SmallSet.h:169
bool erase(const T &V)
Definition SmallSet.h:200
std::pair< const_iterator, bool > insert(const T &V)
insert - Insert an element into the set if it isn't already there.
Definition SmallSet.h:184
void push_back(const T &Elt)
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
@ Entry
Definition COFF.h:862
Predicate getSwappedPredicate(Predicate Opcode)
Assume the condition register is set by MI(a,b), return the predicate if we modify the instructions s...
Predicate
Predicate - These are "(BI << 5) | BO" for various predicates.
unsigned getPredicateCondition(Predicate Opcode)
Return the condition without hint bits.
Predicate getPredicate(unsigned Condition, unsigned Hint)
Return predicate consisting of specified condition and hint bits.
unsigned getPredicateHint(Predicate Opcode)
Return the hint bits of the predicate.
initializer< Ty > init(const Ty &Val)
NodeAddr< DefNode * > Def
Definition RDFGraph.h:384
NodeAddr< InstrNode * > Instr
Definition RDFGraph.h:389
NodeAddr< PhiNode * > Phi
Definition RDFGraph.h:390
NodeAddr< UseNode * > Use
Definition RDFGraph.h:385
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.
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Value
Definition InstrProf.h:143
int countr_zero(T Val)
Count number of 0's from the least significant bit to the most stopping at the first 1.
Definition bit.h:204
int countl_zero(T Val)
Count number of 0's from the most significant bit to the least stopping at the first 1.
Definition bit.h:263
auto reverse(ContainerTy &&C)
Definition STLExtras.h:408
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...
DWARFExpression::Operation Op
bool is_contained(R &&Range, const E &Element)
Returns true if Element is found in Range.
Definition STLExtras.h:1963
LLVM_ABI Printable printReg(Register Reg, const TargetRegisterInfo *TRI=nullptr, unsigned SubIdx=0, const MachineRegisterInfo *MRI=nullptr)
Prints virtual and physical registers with or without a TRI instance.
@ Keep
No function return thunk.
Definition CodeGen.h:317
LLVM_ABI Printable printMBBReference(const MachineBasicBlock &MBB)
Prints a machine basic block reference.
FunctionPass * createPPCMIPeepholePass()
MCRegisterClass TargetRegisterClass
Definition FastISel.h:58
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
Definition BitVector.h:880