51658011a9d69a1ba00f8e6768066098ee1a8f0c
[oota-llvm.git] / lib / Target / PowerPC / PPCCTRLoops.cpp
1 //===-- PPCCTRLoops.cpp - Identify and generate CTR loops -----------------===//
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 // This pass identifies loops where we can generate the PPC branch instructions
11 // that decrement and test the count register (CTR) (bdnz and friends).
12 // This pass is based on the HexagonHardwareLoops pass.
13 //
14 // The pattern that defines the induction variable can changed depending on
15 // prior optimizations.  For example, the IndVarSimplify phase run by 'opt'
16 // normalizes induction variables, and the Loop Strength Reduction pass
17 // run by 'llc' may also make changes to the induction variable.
18 // The pattern detected by this phase is due to running Strength Reduction.
19 //
20 // Criteria for CTR loops:
21 //  - Countable loops (w/ ind. var for a trip count)
22 //  - Assumes loops are normalized by IndVarSimplify
23 //  - Try inner-most loops first
24 //  - No nested CTR loops.
25 //  - No function calls in loops.
26 //
27 //  Note: As with unconverted loops, PPCBranchSelector must be run after this
28 //  pass in order to convert long-displacement jumps into jump pairs.
29 //
30 //===----------------------------------------------------------------------===//
31
32 #define DEBUG_TYPE "ctrloops"
33 #include "PPC.h"
34 #include "MCTargetDesc/PPCPredicates.h"
35 #include "PPCTargetMachine.h"
36 #include "llvm/ADT/DenseMap.h"
37 #include "llvm/ADT/Statistic.h"
38 #include "llvm/CodeGen/MachineDominators.h"
39 #include "llvm/CodeGen/MachineFunction.h"
40 #include "llvm/CodeGen/MachineFunctionPass.h"
41 #include "llvm/CodeGen/MachineInstrBuilder.h"
42 #include "llvm/CodeGen/MachineLoopInfo.h"
43 #include "llvm/CodeGen/MachineRegisterInfo.h"
44 #include "llvm/CodeGen/Passes.h"
45 #include "llvm/CodeGen/RegisterScavenging.h"
46 #include "llvm/IR/Constants.h"
47 #include "llvm/PassSupport.h"
48 #include "llvm/Support/Debug.h"
49 #include "llvm/Support/raw_ostream.h"
50 #include "llvm/Target/TargetInstrInfo.h"
51 #include <algorithm>
52
53 using namespace llvm;
54
55 STATISTIC(NumCTRLoops, "Number of loops converted to CTR loops");
56
57 namespace llvm {
58   void initializePPCCTRLoopsPass(PassRegistry&);
59 }
60
61 namespace {
62   class CountValue;
63   struct PPCCTRLoops : public MachineFunctionPass {
64     MachineLoopInfo       *MLI;
65     MachineRegisterInfo   *MRI;
66     const TargetInstrInfo *TII;
67
68   public:
69     static char ID;   // Pass identification, replacement for typeid
70
71     PPCCTRLoops() : MachineFunctionPass(ID) {
72       initializePPCCTRLoopsPass(*PassRegistry::getPassRegistry());
73     }
74
75     virtual bool runOnMachineFunction(MachineFunction &MF);
76
77     const char *getPassName() const { return "PPC CTR Loops"; }
78
79     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
80       AU.setPreservesCFG();
81       AU.addRequired<MachineDominatorTree>();
82       AU.addPreserved<MachineDominatorTree>();
83       AU.addRequired<MachineLoopInfo>();
84       AU.addPreserved<MachineLoopInfo>();
85       MachineFunctionPass::getAnalysisUsage(AU);
86     }
87
88   private:
89     /// getCanonicalInductionVariable - Check to see if the loop has a canonical
90     /// induction variable.
91     /// Should be defined in MachineLoop. Based upon version in class Loop.
92     void getCanonicalInductionVariable(MachineLoop *L,
93                               SmallVector<MachineInstr *, 4> &IVars,
94                               SmallVector<MachineInstr *, 4> &IOps) const;
95
96     /// getTripCount - Return a loop-invariant LLVM register indicating the
97     /// number of times the loop will be executed.  If the trip-count cannot
98     /// be determined, this return null.
99     CountValue *getTripCount(MachineLoop *L,
100                              SmallVector<MachineInstr *, 2> &OldInsts) const;
101
102     /// isInductionOperation - Return true if the instruction matches the
103     /// pattern for an opertion that defines an induction variable.
104     bool isInductionOperation(const MachineInstr *MI, unsigned IVReg) const;
105
106     /// isInvalidOperation - Return true if the instruction is not valid within
107     /// a CTR loop.
108     bool isInvalidLoopOperation(const MachineInstr *MI) const;
109
110     /// containsInavlidInstruction - Return true if the loop contains an
111     /// instruction that inhibits using the CTR loop.
112     bool containsInvalidInstruction(MachineLoop *L) const;
113
114     /// converToCTRLoop - Given a loop, check if we can convert it to a
115     /// CTR loop.  If so, then perform the conversion and return true.
116     bool convertToCTRLoop(MachineLoop *L);
117
118     /// isDead - Return true if the instruction is now dead.
119     bool isDead(const MachineInstr *MI,
120                 SmallVector<MachineInstr *, 1> &DeadPhis) const;
121
122     /// removeIfDead - Remove the instruction if it is now dead.
123     void removeIfDead(MachineInstr *MI);
124   };
125
126   char PPCCTRLoops::ID = 0;
127
128
129   // CountValue class - Abstraction for a trip count of a loop. A
130   // smaller vesrsion of the MachineOperand class without the concerns
131   // of changing the operand representation.
132   class CountValue {
133   public:
134     enum CountValueType {
135       CV_Register,
136       CV_Immediate
137     };
138   private:
139     CountValueType Kind;
140     union Values {
141       unsigned RegNum;
142       int64_t ImmVal;
143       Values(unsigned r) : RegNum(r) {}
144       Values(int64_t i) : ImmVal(i) {}
145     } Contents;
146     bool isNegative;
147
148   public:
149     CountValue(unsigned r, bool neg) : Kind(CV_Register), Contents(r),
150                                        isNegative(neg) {}
151     explicit CountValue(int64_t i) : Kind(CV_Immediate), Contents(i),
152                                      isNegative(i < 0) {}
153     CountValueType getType() const { return Kind; }
154     bool isReg() const { return Kind == CV_Register; }
155     bool isImm() const { return Kind == CV_Immediate; }
156     bool isNeg() const { return isNegative; }
157
158     unsigned getReg() const {
159       assert(isReg() && "Wrong CountValue accessor");
160       return Contents.RegNum;
161     }
162     void setReg(unsigned Val) {
163       Contents.RegNum = Val;
164     }
165     int64_t getImm() const {
166       assert(isImm() && "Wrong CountValue accessor");
167       if (isNegative) {
168         return -Contents.ImmVal;
169       }
170       return Contents.ImmVal;
171     }
172     void setImm(int64_t Val) {
173       Contents.ImmVal = Val;
174     }
175
176     void print(raw_ostream &OS, const TargetMachine *TM = 0) const {
177       if (isReg()) { OS << PrintReg(getReg()); }
178       if (isImm()) { OS << getImm(); }
179     }
180   };
181 } // end anonymous namespace
182
183 INITIALIZE_PASS_BEGIN(PPCCTRLoops, "ppc-ctr-loops", "PowerPC CTR Loops",
184                       false, false)
185 INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree)
186 INITIALIZE_PASS_DEPENDENCY(MachineLoopInfo)
187 INITIALIZE_PASS_END(PPCCTRLoops, "ppc-ctr-loops", "PowerPC CTR Loops",
188                     false, false)
189
190 /// isCompareEquals - Returns true if the instruction is a compare equals
191 /// instruction with an immediate operand.
192 static bool isCompareEqualsImm(const MachineInstr *MI, bool &SignedCmp) {
193   if (MI->getOpcode() == PPC::CMPWI || MI->getOpcode() == PPC::CMPDI) {
194     SignedCmp = true;
195     return true;
196   } else if (MI->getOpcode() == PPC::CMPLWI || MI->getOpcode() == PPC::CMPLDI) {
197     SignedCmp = false;
198     return true;
199   }
200
201   return false;
202 }
203
204
205 /// createPPCCTRLoops - Factory for creating
206 /// the CTR loop phase.
207 FunctionPass *llvm::createPPCCTRLoops() {
208   return new PPCCTRLoops();
209 }
210
211
212 bool PPCCTRLoops::runOnMachineFunction(MachineFunction &MF) {
213   DEBUG(dbgs() << "********* PPC CTR Loops *********\n");
214
215   bool Changed = false;
216
217   // get the loop information
218   MLI = &getAnalysis<MachineLoopInfo>();
219   // get the register information
220   MRI = &MF.getRegInfo();
221   // the target specific instructio info.
222   TII = MF.getTarget().getInstrInfo();
223
224   for (MachineLoopInfo::iterator I = MLI->begin(), E = MLI->end();
225        I != E; ++I) {
226     MachineLoop *L = *I;
227     if (!L->getParentLoop()) {
228       Changed |= convertToCTRLoop(L);
229     }
230   }
231
232   return Changed;
233 }
234
235 /// getCanonicalInductionVariable - Check to see if the loop has a canonical
236 /// induction variable. We check for a simple recurrence pattern - an
237 /// integer recurrence that decrements by one each time through the loop and
238 /// ends at zero.  If so, return the phi node that corresponds to it.
239 ///
240 /// Based upon the similar code in LoopInfo except this code is specific to
241 /// the machine.
242 /// This method assumes that the IndVarSimplify pass has been run by 'opt'.
243 ///
244 void
245 PPCCTRLoops::getCanonicalInductionVariable(MachineLoop *L,
246                                   SmallVector<MachineInstr *, 4> &IVars,
247                                   SmallVector<MachineInstr *, 4> &IOps) const {
248   MachineBasicBlock *TopMBB = L->getTopBlock();
249   MachineBasicBlock::pred_iterator PI = TopMBB->pred_begin();
250   assert(PI != TopMBB->pred_end() &&
251          "Loop must have more than one incoming edge!");
252   MachineBasicBlock *Backedge = *PI++;
253   if (PI == TopMBB->pred_end()) return;  // dead loop
254   MachineBasicBlock *Incoming = *PI++;
255   if (PI != TopMBB->pred_end()) return;  // multiple backedges?
256
257   // make sure there is one incoming and one backedge and determine which
258   // is which.
259   if (L->contains(Incoming)) {
260     if (L->contains(Backedge))
261       return;
262     std::swap(Incoming, Backedge);
263   } else if (!L->contains(Backedge))
264     return;
265
266   // Loop over all of the PHI nodes, looking for a canonical induction variable:
267   //   - The PHI node is "reg1 = PHI reg2, BB1, reg3, BB2".
268   //   - The recurrence comes from the backedge.
269   //   - the definition is an induction operatio.n
270   for (MachineBasicBlock::iterator I = TopMBB->begin(), E = TopMBB->end();
271        I != E && I->isPHI(); ++I) {
272     MachineInstr *MPhi = &*I;
273     unsigned DefReg = MPhi->getOperand(0).getReg();
274     for (unsigned i = 1; i != MPhi->getNumOperands(); i += 2) {
275       // Check each operand for the value from the backedge.
276       MachineBasicBlock *MBB = MPhi->getOperand(i+1).getMBB();
277       if (L->contains(MBB)) { // operands comes from the backedge
278         // Check if the definition is an induction operation.
279         MachineInstr *DI = MRI->getVRegDef(MPhi->getOperand(i).getReg());
280         if (isInductionOperation(DI, DefReg)) {
281           IOps.push_back(DI);
282           IVars.push_back(MPhi);
283         }
284       }
285     }
286   }
287   return;
288 }
289
290 /// getTripCount - Return a loop-invariant LLVM value indicating the
291 /// number of times the loop will be executed.  The trip count can
292 /// be either a register or a constant value.  If the trip-count
293 /// cannot be determined, this returns null.
294 ///
295 /// We find the trip count from the phi instruction that defines the
296 /// induction variable.  We follow the links to the CMP instruction
297 /// to get the trip count.
298 ///
299 /// Based upon getTripCount in LoopInfo.
300 ///
301 CountValue *PPCCTRLoops::getTripCount(MachineLoop *L,
302                            SmallVector<MachineInstr *, 2> &OldInsts) const {
303   MachineBasicBlock *LastMBB = L->getExitingBlock();
304   // Don't generate a CTR loop if the loop has more than one exit.
305   if (LastMBB == 0)
306     return 0;
307
308   MachineBasicBlock::iterator LastI = LastMBB->getFirstTerminator();
309   if (LastI->getOpcode() != PPC::BCC)
310     return 0;
311
312   // We need to make sure that this compare is defining the condition
313   // register actually used by the terminating branch.
314
315   unsigned PredReg = LastI->getOperand(1).getReg();
316   DEBUG(dbgs() << "Examining loop with first terminator: " << *LastI);
317
318   unsigned PredCond = LastI->getOperand(0).getImm();
319   if (PredCond != PPC::PRED_EQ && PredCond != PPC::PRED_NE)
320     return 0;
321
322   // Check that the loop has a induction variable.
323   SmallVector<MachineInstr *, 4> IVars, IOps;
324   getCanonicalInductionVariable(L, IVars, IOps);
325   for (unsigned i = 0; i < IVars.size(); ++i) {
326     MachineInstr *IOp = IOps[i];
327     MachineInstr *IV_Inst = IVars[i];
328
329     // Canonical loops will end with a 'cmpwi/cmpdi cr, IV, Imm',
330     //  if Imm is 0, get the count from the PHI opnd
331     //  if Imm is -M, than M is the count
332     //  Otherwise, Imm is the count
333     MachineOperand *IV_Opnd;
334     const MachineOperand *InitialValue;
335     if (!L->contains(IV_Inst->getOperand(2).getMBB())) {
336       InitialValue = &IV_Inst->getOperand(1);
337       IV_Opnd = &IV_Inst->getOperand(3);
338     } else {
339       InitialValue = &IV_Inst->getOperand(3);
340       IV_Opnd = &IV_Inst->getOperand(1);
341     }
342
343     DEBUG(dbgs() << "Considering:\n");
344     DEBUG(dbgs() << "  induction operation: " << *IOp);
345     DEBUG(dbgs() << "  induction variable: " << *IV_Inst);
346     DEBUG(dbgs() << "  initial value: " << *InitialValue << "\n");
347   
348     // Look for the cmp instruction to determine if we
349     // can get a useful trip count.  The trip count can
350     // be either a register or an immediate.  The location
351     // of the value depends upon the type (reg or imm).
352     for (MachineRegisterInfo::reg_iterator
353          RI = MRI->reg_begin(IV_Opnd->getReg()), RE = MRI->reg_end();
354          RI != RE; ++RI) {
355       IV_Opnd = &RI.getOperand();
356       bool SignedCmp;
357       MachineInstr *MI = IV_Opnd->getParent();
358       if (L->contains(MI) && isCompareEqualsImm(MI, SignedCmp) &&
359           MI->getOperand(0).getReg() == PredReg) {
360
361         OldInsts.push_back(MI);
362         OldInsts.push_back(IOp);
363  
364         DEBUG(dbgs() << "  compare: " << *MI);
365  
366         const MachineOperand &MO = MI->getOperand(2);
367         assert(MO.isImm() && "IV Cmp Operand should be an immediate");
368
369         int64_t ImmVal;
370         if (SignedCmp)
371           ImmVal = (short) MO.getImm();
372         else
373           ImmVal = MO.getImm();
374   
375         const MachineInstr *IV_DefInstr = MRI->getVRegDef(IV_Opnd->getReg());
376         assert(L->contains(IV_DefInstr->getParent()) &&
377                "IV definition should occurs in loop");
378         int64_t iv_value = (short) IV_DefInstr->getOperand(2).getImm();
379   
380         assert(InitialValue->isReg() && "Expecting register for init value");
381         unsigned InitialValueReg = InitialValue->getReg();
382   
383         MachineInstr *DefInstr = MRI->getVRegDef(InitialValueReg);
384   
385         // Here we need to look for an immediate load (an li or lis/ori pair).
386         if (DefInstr && (DefInstr->getOpcode() == PPC::ORI8 ||
387                          DefInstr->getOpcode() == PPC::ORI)) {
388           int64_t start = (short) DefInstr->getOperand(2).getImm();
389           MachineInstr *DefInstr2 =
390             MRI->getVRegDef(DefInstr->getOperand(0).getReg());
391           if (DefInstr2 && (DefInstr2->getOpcode() == PPC::LIS8 ||
392                             DefInstr2->getOpcode() == PPC::LIS)) {
393             DEBUG(dbgs() << "  initial constant: " << *DefInstr);
394             DEBUG(dbgs() << "  initial constant: " << *DefInstr2);
395
396             start |= int64_t(short(DefInstr2->getOperand(1).getImm())) << 16;
397   
398             int64_t count = ImmVal - start;
399             if ((count % iv_value) != 0) {
400               return 0;
401             }
402
403             OldInsts.push_back(DefInstr);
404             OldInsts.push_back(DefInstr2);
405
406             return new CountValue(count/iv_value);
407           }
408         } else if (DefInstr && (DefInstr->getOpcode() == PPC::LI8 ||
409                                 DefInstr->getOpcode() == PPC::LI)) {
410           DEBUG(dbgs() << "  initial constant: " << *DefInstr);
411
412           int64_t count = ImmVal - int64_t(short(DefInstr->getOperand(1).getImm()));
413           if ((count % iv_value) != 0) {
414             return 0;
415           }
416
417           OldInsts.push_back(DefInstr);
418
419           return new CountValue(count/iv_value);
420         } else if (iv_value == 1 || iv_value == -1) {
421           // We can't determine a constant starting value.
422           if (ImmVal == 0) {
423             return new CountValue(InitialValueReg, iv_value > 0);
424           }
425           // FIXME: handle non-zero end value.
426         }
427         // FIXME: handle non-unit increments (we might not want to introduce division
428         // but we can handle some 2^n cases with shifts).
429   
430       }
431     }
432   }
433   return 0;
434 }
435
436 /// isInductionOperation - return true if the operation is matches the
437 /// pattern that defines an induction variable:
438 ///    addi iv, c
439 ///
440 bool
441 PPCCTRLoops::isInductionOperation(const MachineInstr *MI,
442                                            unsigned IVReg) const {
443   return ((MI->getOpcode() == PPC::ADDI || MI->getOpcode() == PPC::ADDI8) &&
444           MI->getOperand(1).isReg() && // could be a frame index instead
445           MI->getOperand(1).getReg() == IVReg);
446 }
447
448 /// isInvalidOperation - Return true if the operation is invalid within
449 /// CTR loop.
450 bool
451 PPCCTRLoops::isInvalidLoopOperation(const MachineInstr *MI) const {
452
453   // call is not allowed because the callee may use a CTR loop
454   if (MI->getDesc().isCall()) {
455     return true;
456   }
457   // check if the instruction defines a CTR loop register
458   // (this will also catch nested CTR loops)
459   for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
460     const MachineOperand &MO = MI->getOperand(i);
461     if (MO.isReg() && MO.isDef() &&
462         (MO.getReg() == PPC::CTR || MO.getReg() == PPC::CTR8)) {
463       return true;
464     }
465   }
466   return false;
467 }
468
469 /// containsInvalidInstruction - Return true if the loop contains
470 /// an instruction that inhibits the use of the CTR loop function.
471 ///
472 bool PPCCTRLoops::containsInvalidInstruction(MachineLoop *L) const {
473   const std::vector<MachineBasicBlock*> Blocks = L->getBlocks();
474   for (unsigned i = 0, e = Blocks.size(); i != e; ++i) {
475     MachineBasicBlock *MBB = Blocks[i];
476     for (MachineBasicBlock::iterator
477            MII = MBB->begin(), E = MBB->end(); MII != E; ++MII) {
478       const MachineInstr *MI = &*MII;
479       if (isInvalidLoopOperation(MI)) {
480         return true;
481       }
482     }
483   }
484   return false;
485 }
486
487 /// isDead returns true if the instruction is dead
488 /// (this was essentially copied from DeadMachineInstructionElim::isDead, but
489 /// with special cases for inline asm, physical registers and instructions with
490 /// side effects removed)
491 bool PPCCTRLoops::isDead(const MachineInstr *MI,
492                          SmallVector<MachineInstr *, 1> &DeadPhis) const {
493   // Examine each operand.
494   for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
495     const MachineOperand &MO = MI->getOperand(i);
496     if (MO.isReg() && MO.isDef()) {
497       unsigned Reg = MO.getReg();
498       if (!MRI->use_nodbg_empty(Reg)) {
499         // This instruction has users, but if the only user is the phi node for the
500         // parent block, and the only use of that phi node is this instruction, then
501         // this instruction is dead: both it (and the phi node) can be removed.
502         MachineRegisterInfo::use_iterator I = MRI->use_begin(Reg);
503         if (llvm::next(I) == MRI->use_end() &&
504             I.getOperand().getParent()->isPHI()) {
505           MachineInstr *OnePhi = I.getOperand().getParent();
506
507           for (unsigned j = 0, f = OnePhi->getNumOperands(); j != f; ++j) {
508             const MachineOperand &OPO = OnePhi->getOperand(j);
509             if (OPO.isReg() && OPO.isDef()) {
510               unsigned OPReg = OPO.getReg();
511
512               MachineRegisterInfo::use_iterator nextJ;
513               for (MachineRegisterInfo::use_iterator J = MRI->use_begin(OPReg),
514                    E = MRI->use_end(); J!=E; J=nextJ) {
515                 nextJ = llvm::next(J);
516                 MachineOperand& Use = J.getOperand();
517                 MachineInstr *UseMI = Use.getParent();
518
519                 if (MI != UseMI) {
520                   // The phi node has a user that is not MI, bail...
521                   return false;
522                 }
523               }
524             }
525           }
526
527           DeadPhis.push_back(OnePhi);
528         } else {
529           // This def has a non-debug use. Don't delete the instruction!
530           return false;
531         }
532       }
533     }
534   }
535
536   // If there are no defs with uses, the instruction is dead.
537   return true;
538 }
539
540 void PPCCTRLoops::removeIfDead(MachineInstr *MI) {
541   // This procedure was essentially copied from DeadMachineInstructionElim
542
543   SmallVector<MachineInstr *, 1> DeadPhis;
544   if (isDead(MI, DeadPhis)) {
545     DEBUG(dbgs() << "CTR looping will remove: " << *MI);
546
547     // It is possible that some DBG_VALUE instructions refer to this
548     // instruction.  Examine each def operand for such references;
549     // if found, mark the DBG_VALUE as undef (but don't delete it).
550     for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
551       const MachineOperand &MO = MI->getOperand(i);
552       if (!MO.isReg() || !MO.isDef())
553         continue;
554       unsigned Reg = MO.getReg();
555       MachineRegisterInfo::use_iterator nextI;
556       for (MachineRegisterInfo::use_iterator I = MRI->use_begin(Reg),
557            E = MRI->use_end(); I!=E; I=nextI) {
558         nextI = llvm::next(I);  // I is invalidated by the setReg
559         MachineOperand& Use = I.getOperand();
560         MachineInstr *UseMI = Use.getParent();
561         if (UseMI==MI)
562           continue;
563         if (Use.isDebug()) // this might also be a instr -> phi -> instr case
564                            // which can also be removed.
565           UseMI->getOperand(0).setReg(0U);
566       }
567     }
568
569     MI->eraseFromParent();
570     for (unsigned i = 0; i < DeadPhis.size(); ++i) {
571       DeadPhis[i]->eraseFromParent();
572     }
573   }
574 }
575
576 /// converToCTRLoop - check if the loop is a candidate for
577 /// converting to a CTR loop.  If so, then perform the
578 /// transformation.
579 ///
580 /// This function works on innermost loops first.  A loop can
581 /// be converted if it is a counting loop; either a register
582 /// value or an immediate.
583 ///
584 /// The code makes several assumptions about the representation
585 /// of the loop in llvm.
586 bool PPCCTRLoops::convertToCTRLoop(MachineLoop *L) {
587   bool Changed = false;
588   // Process nested loops first.
589   for (MachineLoop::iterator I = L->begin(), E = L->end(); I != E; ++I) {
590     Changed |= convertToCTRLoop(*I);
591   }
592   // If a nested loop has been converted, then we can't convert this loop.
593   if (Changed) {
594     return Changed;
595   }
596
597   SmallVector<MachineInstr *, 2> OldInsts;
598   // Are we able to determine the trip count for the loop?
599   CountValue *TripCount = getTripCount(L, OldInsts);
600   if (TripCount == 0) {
601     DEBUG(dbgs() << "failed to get trip count!\n");
602     return false;
603   }
604   // Does the loop contain any invalid instructions?
605   if (containsInvalidInstruction(L)) {
606     return false;
607   }
608   MachineBasicBlock *Preheader = L->getLoopPreheader();
609   // No preheader means there's not place for the loop instr.
610   if (Preheader == 0) {
611     return false;
612   }
613   MachineBasicBlock::iterator InsertPos = Preheader->getFirstTerminator();
614
615   DebugLoc dl;
616   if (InsertPos != Preheader->end())
617     dl = InsertPos->getDebugLoc();
618
619   MachineBasicBlock *LastMBB = L->getExitingBlock();
620   // Don't generate CTR loop if the loop has more than one exit.
621   if (LastMBB == 0) {
622     return false;
623   }
624   MachineBasicBlock::iterator LastI = LastMBB->getFirstTerminator();
625
626   // Determine the loop start.
627   MachineBasicBlock *LoopStart = L->getTopBlock();
628   if (L->getLoopLatch() != LastMBB) {
629     // When the exit and latch are not the same, use the latch block as the
630     // start.
631     // The loop start address is used only after the 1st iteration, and the loop
632     // latch may contains instrs. that need to be executed after the 1st iter.
633     LoopStart = L->getLoopLatch();
634     // Make sure the latch is a successor of the exit, otherwise it won't work.
635     if (!LastMBB->isSuccessor(LoopStart)) {
636       return false;
637     }
638   }
639
640   // Convert the loop to a CTR loop
641   DEBUG(dbgs() << "Change to CTR loop at "; L->dump());
642
643   MachineFunction *MF = LastMBB->getParent();
644   const PPCSubtarget &Subtarget = MF->getTarget().getSubtarget<PPCSubtarget>();
645   bool isPPC64 = Subtarget.isPPC64();
646
647   const TargetRegisterClass *GPRC = &PPC::GPRCRegClass;
648   const TargetRegisterClass *G8RC = &PPC::G8RCRegClass;
649   const TargetRegisterClass *RC = isPPC64 ? G8RC : GPRC;
650
651   unsigned CountReg;
652   if (TripCount->isReg()) {
653     // Create a copy of the loop count register.
654     const TargetRegisterClass *SrcRC =
655       MF->getRegInfo().getRegClass(TripCount->getReg());
656     CountReg = MF->getRegInfo().createVirtualRegister(RC);
657     unsigned CopyOp = (isPPC64 && SrcRC == GPRC) ?
658                         (unsigned) PPC::EXTSW_32_64 :
659                         (unsigned) TargetOpcode::COPY;
660     BuildMI(*Preheader, InsertPos, dl,
661             TII->get(CopyOp), CountReg).addReg(TripCount->getReg());
662     if (TripCount->isNeg()) {
663       unsigned CountReg1 = CountReg;
664       CountReg = MF->getRegInfo().createVirtualRegister(RC);
665       BuildMI(*Preheader, InsertPos, dl,
666               TII->get(isPPC64 ? PPC::NEG8 : PPC::NEG),
667                        CountReg).addReg(CountReg1);
668     }
669   } else {
670     assert(TripCount->isImm() && "Expecting immedate vaule for trip count");
671     // Put the trip count in a register for transfer into the count register.
672
673     int64_t CountImm = TripCount->getImm();
674     assert(!TripCount->isNeg() && "Constant trip count must be positive");
675
676     CountReg = MF->getRegInfo().createVirtualRegister(RC);
677     if (CountImm > 0xFFFF) {
678       BuildMI(*Preheader, InsertPos, dl,
679               TII->get(isPPC64 ? PPC::LIS8 : PPC::LIS),
680               CountReg).addImm(CountImm >> 16);
681       unsigned CountReg1 = CountReg;
682       CountReg = MF->getRegInfo().createVirtualRegister(RC);
683       BuildMI(*Preheader, InsertPos, dl,
684               TII->get(isPPC64 ? PPC::ORI8 : PPC::ORI),
685               CountReg).addReg(CountReg1).addImm(CountImm & 0xFFFF);
686     } else {
687       BuildMI(*Preheader, InsertPos, dl,
688               TII->get(isPPC64 ? PPC::LI8 : PPC::LI),
689               CountReg).addImm(CountImm);
690     }
691   }
692
693   // Add the mtctr instruction to the beginning of the loop.
694   BuildMI(*Preheader, InsertPos, dl,
695           TII->get(isPPC64 ? PPC::MTCTR8 : PPC::MTCTR)).addReg(CountReg,
696             TripCount->isImm() ? RegState::Kill : 0);
697
698   // Make sure the loop start always has a reference in the CFG.  We need to
699   // create a BlockAddress operand to get this mechanism to work both the
700   // MachineBasicBlock and BasicBlock objects need the flag set.
701   LoopStart->setHasAddressTaken();
702   // This line is needed to set the hasAddressTaken flag on the BasicBlock
703   // object
704   BlockAddress::get(const_cast<BasicBlock *>(LoopStart->getBasicBlock()));
705
706   // Replace the loop branch with a bdnz instruction.
707   dl = LastI->getDebugLoc();
708   const std::vector<MachineBasicBlock*> Blocks = L->getBlocks();
709   for (unsigned i = 0, e = Blocks.size(); i != e; ++i) {
710     MachineBasicBlock *MBB = Blocks[i];
711     if (MBB != Preheader)
712       MBB->addLiveIn(isPPC64 ? PPC::CTR8 : PPC::CTR);
713   }
714
715   // The loop ends with either:
716   //  - a conditional branch followed by an unconditional branch, or
717   //  - a conditional branch to the loop start.
718   assert(LastI->getOpcode() == PPC::BCC &&
719          "loop end must start with a BCC instruction");
720   // Either the BCC branches to the beginning of the loop, or it
721   // branches out of the loop and there is an unconditional branch
722   // to the start of the loop.
723   MachineBasicBlock *BranchTarget = LastI->getOperand(2).getMBB();
724   BuildMI(*LastMBB, LastI, dl,
725         TII->get((BranchTarget == LoopStart) ?
726                  (isPPC64 ? PPC::BDNZ8 : PPC::BDNZ) :
727                  (isPPC64 ? PPC::BDZ8 : PPC::BDZ))).addMBB(BranchTarget);
728
729   // Conditional branch; just delete it.
730   DEBUG(dbgs() << "Removing old branch: " << *LastI);
731   LastMBB->erase(LastI);
732
733   delete TripCount;
734
735   // The induction operation (add) and the comparison (cmpwi) may now be
736   // unneeded. If these are unneeded, then remove them.
737   for (unsigned i = 0; i < OldInsts.size(); ++i)
738     removeIfDead(OldInsts[i]);
739
740   ++NumCTRLoops;
741   return true;
742 }
743