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