1 //===------------- PPCExpandISEL.cpp - Expand ISEL instruction ------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // A pass that expands the ISEL instruction into an if-then-else sequence.
11 // This pass must be run post-RA since all operands must be physical registers.
12 //
13 //===----------------------------------------------------------------------===//
14 
15 #include "PPC.h"
16 #include "PPCInstrInfo.h"
17 #include "PPCSubtarget.h"
18 #include "llvm/ADT/DenseMap.h"
19 #include "llvm/ADT/Statistic.h"
20 #include "llvm/CodeGen/LivePhysRegs.h"
21 #include "llvm/CodeGen/MachineFunctionPass.h"
22 #include "llvm/CodeGen/MachineInstrBuilder.h"
23 #include "llvm/CodeGen/MachineRegisterInfo.h"
24 #include "llvm/Support/CommandLine.h"
25 #include "llvm/Support/Debug.h"
26 #include "llvm/Support/raw_ostream.h"
27 
28 using namespace llvm;
29 
30 #define DEBUG_TYPE "ppc-expand-isel"
31 
32 STATISTIC(NumExpanded, "Number of ISEL instructions expanded");
33 STATISTIC(NumRemoved, "Number of ISEL instructions removed");
34 STATISTIC(NumFolded, "Number of ISEL instructions folded");
35 
36 // If -ppc-gen-isel=false is set, we will disable generating the ISEL
37 // instruction on all PPC targets. Otherwise, if the user set option
38 // -misel or the platform supports ISEL by default, still generate the
39 // ISEL instruction, else expand it.
40 static cl::opt<bool>
41     GenerateISEL("ppc-gen-isel",
42                  cl::desc("Enable generating the ISEL instruction."),
43                  cl::init(true), cl::Hidden);
44 
45 namespace {
46 class PPCExpandISEL : public MachineFunctionPass {
47   DebugLoc dl;
48   MachineFunction *MF;
49   const TargetInstrInfo *TII;
50   bool IsTrueBlockRequired;
51   bool IsFalseBlockRequired;
52   MachineBasicBlock *TrueBlock;
53   MachineBasicBlock *FalseBlock;
54   MachineBasicBlock *NewSuccessor;
55   MachineBasicBlock::iterator TrueBlockI;
56   MachineBasicBlock::iterator FalseBlockI;
57 
58   typedef SmallVector<MachineInstr *, 4> BlockISELList;
59   typedef SmallDenseMap<int, BlockISELList> ISELInstructionList;
60 
61   // A map of MBB numbers to their lists of contained ISEL instructions.
62   ISELInstructionList ISELInstructions;
63 
64   /// Initialize the object.
65   void initialize(MachineFunction &MFParam);
66 
67   void handleSpecialCases(BlockISELList &BIL, MachineBasicBlock *MBB);
68   void reorganizeBlockLayout(BlockISELList &BIL, MachineBasicBlock *MBB);
69   void populateBlocks(BlockISELList &BIL);
70   void expandMergeableISELs(BlockISELList &BIL);
71   void expandAndMergeISELs();
72 
73   bool canMerge(MachineInstr *PrevPushedMI, MachineInstr *MI);
74 
75   ///  Is this instruction an ISEL or ISEL8?
76   static bool isISEL(const MachineInstr &MI) {
77     return (MI.getOpcode() == PPC::ISEL || MI.getOpcode() == PPC::ISEL8);
78   }
79 
80   ///  Is this instruction an ISEL8?
81   static bool isISEL8(const MachineInstr &MI) {
82     return (MI.getOpcode() == PPC::ISEL8);
83   }
84 
85   /// Are the two operands using the same register?
86   bool useSameRegister(const MachineOperand &Op1, const MachineOperand &Op2) {
87     return (Op1.getReg() == Op2.getReg());
88   }
89 
90   ///
91   ///  Collect all ISEL instructions from the current function.
92   ///
93   /// Walk the current function and collect all the ISEL instructions that are
94   /// found. The instructions are placed in the ISELInstructions vector.
95   ///
96   /// \return true if any ISEL instructions were found, false otherwise
97   ///
98   bool collectISELInstructions();
99 
100 public:
101   static char ID;
102   PPCExpandISEL() : MachineFunctionPass(ID) {
103     initializePPCExpandISELPass(*PassRegistry::getPassRegistry());
104   }
105 
106   ///
107   ///  Determine whether to generate the ISEL instruction or expand it.
108   ///
109   /// Expand ISEL instruction into if-then-else sequence when one of
110   /// the following two conditions hold:
111   /// (1) -ppc-gen-isel=false
112   /// (2) hasISEL() return false
113   /// Otherwise, still generate ISEL instruction.
114   /// The -ppc-gen-isel option is set to true by default. Which means the ISEL
115   /// instruction is still generated by default on targets that support them.
116   ///
117   /// \return true if ISEL should be expanded into if-then-else code sequence;
118   ///         false if ISEL instruction should be generated, i.e. not expaned.
119   ///
120   static bool isExpandISELEnabled(const MachineFunction &MF);
121 
122 #ifndef NDEBUG
123   void DumpISELInstructions() const;
124 #endif
125 
126   bool runOnMachineFunction(MachineFunction &MF) override {
127     if (!isExpandISELEnabled(MF))
128       return false;
129 
130     DEBUG(dbgs() << "Function: "; MF.dump(); dbgs() << "\n");
131     initialize(MF);
132 
133     if (!collectISELInstructions()) {
134       DEBUG(dbgs() << "No ISEL instructions in this function\n");
135       return false;
136     }
137 
138 #ifndef NDEBUG
139     DumpISELInstructions();
140 #endif
141 
142     expandAndMergeISELs();
143 
144     return true;
145   }
146 };
147 } // end anonymous namespace
148 
149 void PPCExpandISEL::initialize(MachineFunction &MFParam) {
150   MF = &MFParam;
151   TII = MF->getSubtarget().getInstrInfo();
152   ISELInstructions.clear();
153 }
154 
155 bool PPCExpandISEL::isExpandISELEnabled(const MachineFunction &MF) {
156   return !GenerateISEL || !MF.getSubtarget<PPCSubtarget>().hasISEL();
157 }
158 
159 bool PPCExpandISEL::collectISELInstructions() {
160   for (MachineBasicBlock &MBB : *MF) {
161     BlockISELList thisBlockISELs;
162     for (MachineInstr &MI : MBB)
163       if (isISEL(MI))
164         thisBlockISELs.push_back(&MI);
165     if (!thisBlockISELs.empty())
166       ISELInstructions.insert(std::make_pair(MBB.getNumber(), thisBlockISELs));
167   }
168   return !ISELInstructions.empty();
169 }
170 
171 #ifndef NDEBUG
172 void PPCExpandISEL::DumpISELInstructions() const {
173   for (const auto &I : ISELInstructions) {
174     DEBUG(dbgs() << printMBBReference(*MF->getBlockNumbered(I.first)) << ":\n");
175     for (const auto &VI : I.second)
176       DEBUG(dbgs() << "    "; VI->print(dbgs()));
177   }
178 }
179 #endif
180 
181 /// Contiguous ISELs that have the same condition can be merged.
182 bool PPCExpandISEL::canMerge(MachineInstr *PrevPushedMI, MachineInstr *MI) {
183   // Same Condition Register?
184   if (!useSameRegister(PrevPushedMI->getOperand(3), MI->getOperand(3)))
185     return false;
186 
187   MachineBasicBlock::iterator PrevPushedMBBI = *PrevPushedMI;
188   MachineBasicBlock::iterator MBBI = *MI;
189   return (std::prev(MBBI) == PrevPushedMBBI); // Contiguous ISELs?
190 }
191 
192 void PPCExpandISEL::expandAndMergeISELs() {
193   for (auto &BlockList : ISELInstructions) {
194 
195     DEBUG(dbgs() << printMBBReference(*MF->getBlockNumbered(BlockList.first))
196                  << ":\n");
197     DEBUG(dbgs() << "Expanding ISEL instructions in "
198                  << printMBBReference(*MF->getBlockNumbered(BlockList.first))
199                  << "\n");
200 
201     BlockISELList &CurrentISELList = BlockList.second;
202     auto I = CurrentISELList.begin();
203     auto E = CurrentISELList.end();
204 
205     while (I != E) {
206       BlockISELList SubISELList;
207 
208       SubISELList.push_back(*I++);
209 
210       // Collect the ISELs that can be merged together.
211       while (I != E && canMerge(SubISELList.back(), *I))
212         SubISELList.push_back(*I++);
213 
214       expandMergeableISELs(SubISELList);
215     }
216   }
217 }
218 
219 void PPCExpandISEL::handleSpecialCases(BlockISELList &BIL,
220                                        MachineBasicBlock *MBB) {
221   IsTrueBlockRequired = false;
222   IsFalseBlockRequired = false;
223 
224   auto MI = BIL.begin();
225   while (MI != BIL.end()) {
226     assert(isISEL(**MI) && "Expecting an ISEL instruction");
227     DEBUG(dbgs() << "ISEL: " << **MI << "\n");
228 
229     MachineOperand &Dest = (*MI)->getOperand(0);
230     MachineOperand &TrueValue = (*MI)->getOperand(1);
231     MachineOperand &FalseValue = (*MI)->getOperand(2);
232 
233     // If at least one of the ISEL instructions satisfy the following
234     // condition, we need the True Block:
235     // The Dest Register and True Value Register are not the same
236     // Similarly, if at least one of the ISEL instructions satisfy the
237     // following condition, we need the False Block:
238     // The Dest Register and False Value Register are not the same.
239 
240     bool IsADDIInstRequired = !useSameRegister(Dest, TrueValue);
241     bool IsORIInstRequired = !useSameRegister(Dest, FalseValue);
242 
243     // Special case 1, all registers used by ISEL are the same one.
244     if (!IsADDIInstRequired && !IsORIInstRequired) {
245       DEBUG(dbgs() << "Remove redudant ISEL instruction.");
246       NumRemoved++;
247       (*MI)->eraseFromParent();
248       // Setting MI to the erase result keeps the iterator valid and increased.
249       MI = BIL.erase(MI);
250       continue;
251     }
252 
253     // Special case 2, the two input registers used by ISEL are the same.
254     // Note 1: We favor merging ISEL expansions over folding a single one. If
255     // the passed list has multiple merge-able ISEL's, we won't fold any.
256     // Note 2: There is no need to test for PPC::R0/PPC::X0 because PPC::ZERO/
257     // PPC::ZERO8 will be used for the first operand if the value is meant to
258     // be zero. In this case, the useSameRegister method will return false,
259     // thereby preventing this ISEL from being folded.
260 
261     if (useSameRegister(TrueValue, FalseValue) && (BIL.size() == 1)) {
262       DEBUG(dbgs() << "Fold the ISEL instruction to an unconditonal copy.");
263       NumFolded++;
264       BuildMI(*MBB, (*MI), dl, TII->get(isISEL8(**MI) ? PPC::ADDI8 : PPC::ADDI))
265           .add(Dest)
266           .add(TrueValue)
267           .add(MachineOperand::CreateImm(0));
268       (*MI)->eraseFromParent();
269       // Setting MI to the erase result keeps the iterator valid and increased.
270       MI = BIL.erase(MI);
271       continue;
272     }
273 
274     IsTrueBlockRequired |= IsADDIInstRequired;
275     IsFalseBlockRequired |= IsORIInstRequired;
276     MI++;
277   }
278 }
279 
280 void PPCExpandISEL::reorganizeBlockLayout(BlockISELList &BIL,
281                                           MachineBasicBlock *MBB) {
282   if (BIL.empty())
283     return;
284 
285   assert((IsTrueBlockRequired || IsFalseBlockRequired) &&
286          "Should have been handled by special cases earlier!");
287 
288   MachineBasicBlock *Successor = nullptr;
289   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
290   MachineBasicBlock::iterator MBBI = (*BIL.back());
291   NewSuccessor = (MBBI != MBB->getLastNonDebugInstr() || !MBB->canFallThrough())
292                      // Another BB is needed to move the instructions that
293                      // follow this ISEL.  If the ISEL is the last instruction
294                      // in a block that can't fall through, we also need a block
295                      // to branch to.
296                      ? MF->CreateMachineBasicBlock(LLVM_BB)
297                      : nullptr;
298 
299   MachineFunction::iterator It = MBB->getIterator();
300   ++It; // Point to the successor block of MBB.
301 
302   // If NewSuccessor is NULL then the last ISEL in this group is the last
303   // non-debug instruction in this block. Find the fall-through successor
304   // of this block to use when updating the CFG below.
305   if (!NewSuccessor) {
306     for (auto &Succ : MBB->successors()) {
307       if (MBB->isLayoutSuccessor(Succ)) {
308         Successor = Succ;
309         break;
310       }
311     }
312   } else
313     Successor = NewSuccessor;
314 
315   // The FalseBlock and TrueBlock are inserted after the MBB block but before
316   // its successor.
317   // Note this need to be done *after* the above setting the Successor code.
318   if (IsFalseBlockRequired) {
319     FalseBlock = MF->CreateMachineBasicBlock(LLVM_BB);
320     MF->insert(It, FalseBlock);
321   }
322 
323   if (IsTrueBlockRequired) {
324     TrueBlock = MF->CreateMachineBasicBlock(LLVM_BB);
325     MF->insert(It, TrueBlock);
326   }
327 
328   if (NewSuccessor) {
329     MF->insert(It, NewSuccessor);
330 
331     // Transfer the rest of this block into the new successor block.
332     NewSuccessor->splice(NewSuccessor->end(), MBB,
333                          std::next(MachineBasicBlock::iterator(BIL.back())),
334                          MBB->end());
335     NewSuccessor->transferSuccessorsAndUpdatePHIs(MBB);
336 
337     // Copy the original liveIns of MBB to NewSuccessor.
338     for (auto &LI : MBB->liveins())
339       NewSuccessor->addLiveIn(LI);
340 
341     // After splitting the NewSuccessor block, Regs defined but not killed
342     // in MBB should be treated as liveins of NewSuccessor.
343     // Note: Cannot use stepBackward instead since we are using the Reg
344     // liveness state at the end of MBB (liveOut of MBB) as the liveIn for
345     // NewSuccessor. Otherwise, will cause cyclic dependence.
346     LivePhysRegs LPR(*MF->getSubtarget<PPCSubtarget>().getRegisterInfo());
347     SmallVector<std::pair<unsigned, const MachineOperand *>, 2> Clobbers;
348     for (MachineInstr &MI : *MBB)
349       LPR.stepForward(MI, Clobbers);
350     for (auto &LI : LPR)
351       NewSuccessor->addLiveIn(LI);
352   } else {
353     // Remove successor from MBB.
354     MBB->removeSuccessor(Successor);
355   }
356 
357   // Note that this needs to be done *after* transfering the successors from MBB
358   // to the NewSuccessor block, otherwise these blocks will also be transferred
359   // as successors!
360   MBB->addSuccessor(IsTrueBlockRequired ? TrueBlock : Successor);
361   MBB->addSuccessor(IsFalseBlockRequired ? FalseBlock : Successor);
362 
363   if (IsTrueBlockRequired) {
364     TrueBlockI = TrueBlock->begin();
365     TrueBlock->addSuccessor(Successor);
366   }
367 
368   if (IsFalseBlockRequired) {
369     FalseBlockI = FalseBlock->begin();
370     FalseBlock->addSuccessor(Successor);
371   }
372 
373   // Conditional branch to the TrueBlock or Successor
374   BuildMI(*MBB, BIL.back(), dl, TII->get(PPC::BC))
375       .add(BIL.back()->getOperand(3))
376       .addMBB(IsTrueBlockRequired ? TrueBlock : Successor);
377 
378   // Jump over the true block to the new successor if the condition is false.
379   BuildMI(*(IsFalseBlockRequired ? FalseBlock : MBB),
380           (IsFalseBlockRequired ? FalseBlockI : BIL.back()), dl,
381           TII->get(PPC::B))
382       .addMBB(Successor);
383 
384   if (IsFalseBlockRequired)
385     FalseBlockI = FalseBlock->begin(); // get the position of PPC::B
386 }
387 
388 void PPCExpandISEL::populateBlocks(BlockISELList &BIL) {
389   for (auto &MI : BIL) {
390     assert(isISEL(*MI) && "Expecting an ISEL instruction");
391 
392     MachineOperand &Dest = MI->getOperand(0);       // location to store to
393     MachineOperand &TrueValue = MI->getOperand(1);  // Value to store if
394                                                        // condition is true
395     MachineOperand &FalseValue = MI->getOperand(2); // Value to store if
396                                                        // condition is false
397     MachineOperand &ConditionRegister = MI->getOperand(3); // Condition
398 
399     DEBUG(dbgs() << "Dest: " << Dest << "\n");
400     DEBUG(dbgs() << "TrueValue: " << TrueValue << "\n");
401     DEBUG(dbgs() << "FalseValue: " << FalseValue << "\n");
402     DEBUG(dbgs() << "ConditionRegister: " << ConditionRegister << "\n");
403 
404 
405     // If the Dest Register and True Value Register are not the same one, we
406     // need the True Block.
407     bool IsADDIInstRequired = !useSameRegister(Dest, TrueValue);
408     bool IsORIInstRequired = !useSameRegister(Dest, FalseValue);
409 
410     if (IsADDIInstRequired) {
411       // Copy the result into the destination if the condition is true.
412       BuildMI(*TrueBlock, TrueBlockI, dl,
413               TII->get(isISEL8(*MI) ? PPC::ADDI8 : PPC::ADDI))
414           .add(Dest)
415           .add(TrueValue)
416           .add(MachineOperand::CreateImm(0));
417 
418       // Add the LiveIn registers required by true block.
419       TrueBlock->addLiveIn(TrueValue.getReg());
420     }
421 
422     if (IsORIInstRequired) {
423       // Add the LiveIn registers required by false block.
424       FalseBlock->addLiveIn(FalseValue.getReg());
425     }
426 
427     if (NewSuccessor) {
428       // Add the LiveIn registers required by NewSuccessor block.
429       NewSuccessor->addLiveIn(Dest.getReg());
430       NewSuccessor->addLiveIn(TrueValue.getReg());
431       NewSuccessor->addLiveIn(FalseValue.getReg());
432       NewSuccessor->addLiveIn(ConditionRegister.getReg());
433     }
434 
435     // Copy the value into the destination if the condition is false.
436     if (IsORIInstRequired)
437       BuildMI(*FalseBlock, FalseBlockI, dl,
438               TII->get(isISEL8(*MI) ? PPC::ORI8 : PPC::ORI))
439           .add(Dest)
440           .add(FalseValue)
441           .add(MachineOperand::CreateImm(0));
442 
443     MI->eraseFromParent(); // Remove the ISEL instruction.
444 
445     NumExpanded++;
446   }
447 }
448 
449 void PPCExpandISEL::expandMergeableISELs(BlockISELList &BIL) {
450   // At this stage all the ISELs of BIL are in the same MBB.
451   MachineBasicBlock *MBB = BIL.back()->getParent();
452 
453   handleSpecialCases(BIL, MBB);
454   reorganizeBlockLayout(BIL, MBB);
455   populateBlocks(BIL);
456 }
457 
458 INITIALIZE_PASS(PPCExpandISEL, DEBUG_TYPE, "PowerPC Expand ISEL Generation",
459                 false, false)
460 char PPCExpandISEL::ID = 0;
461 
462 FunctionPass *llvm::createPPCExpandISELPass() { return new PPCExpandISEL(); }
463