Be gcc 3.4 clean
[oota-llvm.git] / lib / Transforms / LevelRaise.cpp
1 //===- LevelRaise.cpp - Code to change LLVM to higher level ---------------===//
2 // 
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source License. See LICENSE.TXT for details.
7 // 
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements the 'raising' part of the LevelChange API.  This is
11 // useful because, in general, it makes the LLVM code terser and easier to
12 // analyze.
13 //
14 //===----------------------------------------------------------------------===//
15
16 #include "llvm/Transforms/Scalar.h"
17 #include "llvm/Transforms/Utils/Local.h"
18 #include "TransformInternals.h"
19 #include "llvm/iOther.h"
20 #include "llvm/iMemory.h"
21 #include "llvm/Pass.h"
22 #include "llvm/ConstantHandling.h"
23 #include "llvm/Analysis/Expressions.h"
24 #include "llvm/Analysis/Verifier.h"
25 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
26 #include "Support/CommandLine.h"
27 #include "Support/Debug.h"
28 #include "Support/Statistic.h"
29 #include "Support/STLExtras.h"
30 #include <algorithm>
31
32 // StartInst - This enables the -raise-start-inst=foo option to cause the level
33 // raising pass to start at instruction "foo", which is immensely useful for
34 // debugging!
35 //
36 static cl::opt<std::string>
37 StartInst("raise-start-inst", cl::Hidden, cl::value_desc("inst name"),
38        cl::desc("Start raise pass at the instruction with the specified name"));
39
40 static Statistic<>
41 NumLoadStorePeepholes("raise", "Number of load/store peepholes");
42
43 static Statistic<> 
44 NumGEPInstFormed("raise", "Number of other getelementptr's formed");
45
46 static Statistic<>
47 NumExprTreesConv("raise", "Number of expression trees converted");
48
49 static Statistic<>
50 NumCastOfCast("raise", "Number of cast-of-self removed");
51
52 static Statistic<>
53 NumDCEorCP("raise", "Number of insts DCEd or constprop'd");
54
55 static Statistic<>
56 NumVarargCallChanges("raise", "Number of vararg call peepholes");
57
58
59 #define PRINT_PEEPHOLE(ID, NUM, I)            \
60   DEBUG(std::cerr << "Inst P/H " << ID << "[" << NUM << "] " << I)
61
62 #define PRINT_PEEPHOLE1(ID, I1) do { PRINT_PEEPHOLE(ID, 0, I1); } while (0)
63 #define PRINT_PEEPHOLE2(ID, I1, I2) \
64   do { PRINT_PEEPHOLE(ID, 0, I1); PRINT_PEEPHOLE(ID, 1, I2); } while (0)
65 #define PRINT_PEEPHOLE3(ID, I1, I2, I3) \
66   do { PRINT_PEEPHOLE(ID, 0, I1); PRINT_PEEPHOLE(ID, 1, I2); \
67        PRINT_PEEPHOLE(ID, 2, I3); } while (0)
68 #define PRINT_PEEPHOLE4(ID, I1, I2, I3, I4) \
69   do { PRINT_PEEPHOLE(ID, 0, I1); PRINT_PEEPHOLE(ID, 1, I2); \
70        PRINT_PEEPHOLE(ID, 2, I3); PRINT_PEEPHOLE(ID, 3, I4); } while (0)
71
72 namespace {
73   struct RPR : public FunctionPass {
74     virtual bool runOnFunction(Function &F);
75
76     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
77       AU.setPreservesCFG();
78       AU.addRequired<TargetData>();
79     }
80
81   private:
82     bool DoRaisePass(Function &F);
83     bool PeepholeOptimize(BasicBlock *BB, BasicBlock::iterator &BI);
84   };
85
86   RegisterOpt<RPR> X("raise", "Raise Pointer References");
87 }
88
89 Pass *createRaisePointerReferencesPass() {
90   return new RPR();
91 }
92
93
94
95 // isReinterpretingCast - Return true if the cast instruction specified will
96 // cause the operand to be "reinterpreted".  A value is reinterpreted if the
97 // cast instruction would cause the underlying bits to change.
98 //
99 static inline bool isReinterpretingCast(const CastInst *CI) {
100   return!CI->getOperand(0)->getType()->isLosslesslyConvertibleTo(CI->getType());
101 }
102
103
104 // Peephole optimize the following instructions:
105 // %t1 = cast ? to x *
106 // %t2 = add x * %SP, %t1              ;; Constant must be 2nd operand
107 //
108 // Into: %t3 = getelementptr {<...>} * %SP, <element indices>
109 //       %t2 = cast <eltype> * %t3 to {<...>}*
110 //
111 static bool HandleCastToPointer(BasicBlock::iterator BI,
112                                 const PointerType *DestPTy,
113                                 const TargetData &TD) {
114   CastInst &CI = cast<CastInst>(*BI);
115   if (CI.use_empty()) return false;
116
117   // Scan all of the uses, looking for any uses that are not add or sub
118   // instructions.  If we have non-adds, do not make this transformation.
119   //
120   bool HasSubUse = false;  // Keep track of any subtracts...
121   for (Value::use_iterator I = CI.use_begin(), E = CI.use_end();
122        I != E; ++I)
123     if (BinaryOperator *BO = dyn_cast<BinaryOperator>(*I)) {
124       if ((BO->getOpcode() != Instruction::Add &&
125            BO->getOpcode() != Instruction::Sub) ||
126           // Avoid add sbyte* %X, %X cases...
127           BO->getOperand(0) == BO->getOperand(1))
128         return false;
129       else
130         HasSubUse |= BO->getOpcode() == Instruction::Sub;
131     } else {
132       return false;
133     }
134
135   std::vector<Value*> Indices;
136   Value *Src = CI.getOperand(0);
137   const Type *Result = ConvertibleToGEP(DestPTy, Src, Indices, TD, &BI);
138   if (Result == 0) return false;  // Not convertible...
139
140   // Cannot handle subtracts if there is more than one index required...
141   if (HasSubUse && Indices.size() != 1) return false;
142
143   PRINT_PEEPHOLE2("cast-add-to-gep:in", Src, CI);
144
145   // If we have a getelementptr capability... transform all of the 
146   // add instruction uses into getelementptr's.
147   while (!CI.use_empty()) {
148     BinaryOperator *I = cast<BinaryOperator>(*CI.use_begin());
149     assert((I->getOpcode() == Instruction::Add ||
150             I->getOpcode() == Instruction::Sub) && 
151            "Use is not a valid add instruction!");
152     
153     // Get the value added to the cast result pointer...
154     Value *OtherPtr = I->getOperand((I->getOperand(0) == &CI) ? 1 : 0);
155
156     Instruction *GEP = new GetElementPtrInst(OtherPtr, Indices, I->getName());
157     PRINT_PEEPHOLE1("cast-add-to-gep:i", I);
158
159     // If the instruction is actually a subtract, we are guaranteed to only have
160     // one index (from code above), so we just need to negate the pointer index
161     // long value.
162     if (I->getOpcode() == Instruction::Sub) {
163       Instruction *Neg = BinaryOperator::createNeg(GEP->getOperand(1), 
164                                        GEP->getOperand(1)->getName()+".neg", I);
165       GEP->setOperand(1, Neg);
166     }
167
168     if (GEP->getType() == I->getType()) {
169       // Replace the old add instruction with the shiny new GEP inst
170       ReplaceInstWithInst(I, GEP);
171     } else {
172       // If the type produced by the gep instruction differs from the original
173       // add instruction type, insert a cast now.
174       //
175
176       // Insert the GEP instruction before the old add instruction...
177       I->getParent()->getInstList().insert(I, GEP);
178
179       PRINT_PEEPHOLE1("cast-add-to-gep:o", GEP);
180       GEP = new CastInst(GEP, I->getType());
181
182       // Replace the old add instruction with the shiny new GEP inst
183       ReplaceInstWithInst(I, GEP);
184     }
185
186     PRINT_PEEPHOLE1("cast-add-to-gep:o", GEP);
187   }
188   return true;
189 }
190
191 // Peephole optimize the following instructions:
192 // %t1 = cast ulong <const int> to {<...>} *
193 // %t2 = add {<...>} * %SP, %t1              ;; Constant must be 2nd operand
194 //
195 //    or
196 // %t1 = cast {<...>}* %SP to int*
197 // %t5 = cast ulong <const int> to int*
198 // %t2 = add int* %t1, %t5                   ;; int is same size as field
199 //
200 // Into: %t3 = getelementptr {<...>} * %SP, <element indices>
201 //       %t2 = cast <eltype> * %t3 to {<...>}*
202 //
203 static bool PeepholeOptimizeAddCast(BasicBlock *BB, BasicBlock::iterator &BI,
204                                     Value *AddOp1, CastInst *AddOp2,
205                                     const TargetData &TD) {
206   const CompositeType *CompTy;
207   Value *OffsetVal = AddOp2->getOperand(0);
208   Value *SrcPtr = 0;  // Of type pointer to struct...
209
210   if ((CompTy = getPointedToComposite(AddOp1->getType()))) {
211     SrcPtr = AddOp1;                      // Handle the first case...
212   } else if (CastInst *AddOp1c = dyn_cast<CastInst>(AddOp1)) {
213     SrcPtr = AddOp1c->getOperand(0);      // Handle the second case...
214     CompTy = getPointedToComposite(SrcPtr->getType());
215   }
216
217   // Only proceed if we have detected all of our conditions successfully...
218   if (!CompTy || !SrcPtr || !OffsetVal->getType()->isInteger())
219     return false;
220
221   std::vector<Value*> Indices;
222   if (!ConvertibleToGEP(SrcPtr->getType(), OffsetVal, Indices, TD, &BI))
223     return false;  // Not convertible... perhaps next time
224
225   if (getPointedToComposite(AddOp1->getType())) {  // case 1
226     PRINT_PEEPHOLE2("add-to-gep1:in", AddOp2, *BI);
227   } else {
228     PRINT_PEEPHOLE3("add-to-gep2:in", AddOp1, AddOp2, *BI);
229   }
230
231   GetElementPtrInst *GEP = new GetElementPtrInst(SrcPtr, Indices,
232                                                  AddOp2->getName(), BI);
233
234   Instruction *NCI = new CastInst(GEP, AddOp1->getType());
235   ReplaceInstWithInst(BB->getInstList(), BI, NCI);
236   PRINT_PEEPHOLE2("add-to-gep:out", GEP, NCI);
237   return true;
238 }
239
240 bool RPR::PeepholeOptimize(BasicBlock *BB, BasicBlock::iterator &BI) {
241   Instruction *I = BI;
242   const TargetData &TD = getAnalysis<TargetData>();
243
244   if (CastInst *CI = dyn_cast<CastInst>(I)) {
245     Value       *Src    = CI->getOperand(0);
246     Instruction *SrcI   = dyn_cast<Instruction>(Src); // Nonnull if instr source
247     const Type  *DestTy = CI->getType();
248
249     // Peephole optimize the following instruction:
250     // %V2 = cast <ty> %V to <ty>
251     //
252     // Into: <nothing>
253     //
254     if (DestTy == Src->getType()) {   // Check for a cast to same type as src!!
255       PRINT_PEEPHOLE1("cast-of-self-ty", CI);
256       CI->replaceAllUsesWith(Src);
257       if (!Src->hasName() && CI->hasName()) {
258         std::string Name = CI->getName();
259         CI->setName("");
260         Src->setName(Name, &BB->getParent()->getSymbolTable());
261       }
262
263       // DCE the instruction now, to avoid having the iterative version of DCE
264       // have to worry about it.
265       //
266       BI = BB->getInstList().erase(BI);
267
268       ++NumCastOfCast;
269       return true;
270     }
271
272     // Check to see if it's a cast of an instruction that does not depend on the
273     // specific type of the operands to do it's job.
274     if (!isReinterpretingCast(CI)) {
275       ValueTypeCache ConvertedTypes;
276
277       // Check to see if we can convert the source of the cast to match the
278       // destination type of the cast...
279       //
280       ConvertedTypes[CI] = CI->getType();  // Make sure the cast doesn't change
281       if (ExpressionConvertibleToType(Src, DestTy, ConvertedTypes, TD)) {
282         PRINT_PEEPHOLE3("CAST-SRC-EXPR-CONV:in ", Src, CI, BB->getParent());
283           
284         DEBUG(std::cerr << "\nCONVERTING SRC EXPR TYPE:\n");
285         { // ValueMap must be destroyed before function verified!
286           ValueMapCache ValueMap;
287           Value *E = ConvertExpressionToType(Src, DestTy, ValueMap, TD);
288
289           if (Constant *CPV = dyn_cast<Constant>(E))
290             CI->replaceAllUsesWith(CPV);
291           
292           PRINT_PEEPHOLE1("CAST-SRC-EXPR-CONV:out", E);
293           DEBUG(std::cerr << "DONE CONVERTING SRC EXPR TYPE: \n"
294                           << BB->getParent());
295         }
296
297         DEBUG(assert(verifyFunction(*BB->getParent()) == false &&
298                      "Function broken!"));
299         BI = BB->begin();  // Rescan basic block.  BI might be invalidated.
300         ++NumExprTreesConv;
301         return true;
302       }
303
304       // Check to see if we can convert the users of the cast value to match the
305       // source type of the cast...
306       //
307       ConvertedTypes.clear();
308       // Make sure the source doesn't change type
309       ConvertedTypes[Src] = Src->getType();
310       if (ValueConvertibleToType(CI, Src->getType(), ConvertedTypes, TD)) {
311         PRINT_PEEPHOLE3("CAST-DEST-EXPR-CONV:in ", Src, CI, BB->getParent());
312
313         DEBUG(std::cerr << "\nCONVERTING EXPR TYPE:\n");
314         { // ValueMap must be destroyed before function verified!
315           ValueMapCache ValueMap;
316           ConvertValueToNewType(CI, Src, ValueMap, TD);  // This will delete CI!
317         }
318
319         PRINT_PEEPHOLE1("CAST-DEST-EXPR-CONV:out", Src);
320         DEBUG(std::cerr << "DONE CONVERTING EXPR TYPE: \n\n" << BB->getParent());
321
322         DEBUG(assert(verifyFunction(*BB->getParent()) == false &&
323                      "Function broken!"));
324         BI = BB->begin();  // Rescan basic block.  BI might be invalidated.
325         ++NumExprTreesConv;
326         return true;
327       }
328     }
329
330     // Otherwise find out it this cast is a cast to a pointer type, which is
331     // then added to some other pointer, then loaded or stored through.  If
332     // so, convert the add into a getelementptr instruction...
333     //
334     if (const PointerType *DestPTy = dyn_cast<PointerType>(DestTy)) {
335       if (HandleCastToPointer(BI, DestPTy, TD)) {
336         BI = BB->begin();  // Rescan basic block.  BI might be invalidated.
337         ++NumGEPInstFormed;
338         return true;
339       }
340     }
341
342     // Check to see if we are casting from a structure pointer to a pointer to
343     // the first element of the structure... to avoid munching other peepholes,
344     // we only let this happen if there are no add uses of the cast.
345     //
346     // Peephole optimize the following instructions:
347     // %t1 = cast {<...>} * %StructPtr to <ty> *
348     //
349     // Into: %t2 = getelementptr {<...>} * %StructPtr, <0, 0, 0, ...>
350     //       %t1 = cast <eltype> * %t1 to <ty> *
351     //
352     if (const CompositeType *CTy = getPointedToComposite(Src->getType()))
353       if (const PointerType *DestPTy = dyn_cast<PointerType>(DestTy)) {
354
355         // Loop over uses of the cast, checking for add instructions.  If an add
356         // exists, this is probably a part of a more complex GEP, so we don't
357         // want to mess around with the cast.
358         //
359         bool HasAddUse = false;
360         for (Value::use_iterator I = CI->use_begin(), E = CI->use_end();
361              I != E; ++I)
362           if (isa<Instruction>(*I) &&
363               cast<Instruction>(*I)->getOpcode() == Instruction::Add) {
364             HasAddUse = true; break;
365           }
366
367         // If it doesn't have an add use, check to see if the dest type is
368         // losslessly convertible to one of the types in the start of the struct
369         // type.
370         //
371         if (!HasAddUse) {
372           const Type *DestPointedTy = DestPTy->getElementType();
373           unsigned Depth = 1;
374           const CompositeType *CurCTy = CTy;
375           const Type *ElTy = 0;
376
377           // Build the index vector, full of all zeros
378           std::vector<Value*> Indices;
379           Indices.push_back(ConstantSInt::get(Type::LongTy, 0));
380           while (CurCTy && !isa<PointerType>(CurCTy)) {
381             if (const StructType *CurSTy = dyn_cast<StructType>(CurCTy)) {
382               // Check for a zero element struct type... if we have one, bail.
383               if (CurSTy->getElementTypes().size() == 0) break;
384             
385               // Grab the first element of the struct type, which must lie at
386               // offset zero in the struct.
387               //
388               ElTy = CurSTy->getElementTypes()[0];
389             } else {
390               ElTy = cast<ArrayType>(CurCTy)->getElementType();
391             }
392
393             // Insert a zero to index through this type...
394             Indices.push_back(Constant::getNullValue(CurCTy->getIndexType()));
395
396             // Did we find what we're looking for?
397             if (ElTy->isLosslesslyConvertibleTo(DestPointedTy)) break;
398             
399             // Nope, go a level deeper.
400             ++Depth;
401             CurCTy = dyn_cast<CompositeType>(ElTy);
402             ElTy = 0;
403           }
404           
405           // Did we find what we were looking for? If so, do the transformation
406           if (ElTy) {
407             PRINT_PEEPHOLE1("cast-for-first:in", CI);
408
409             std::string Name = CI->getName(); CI->setName("");
410
411             // Insert the new T cast instruction... stealing old T's name
412             GetElementPtrInst *GEP = new GetElementPtrInst(Src, Indices,
413                                                            Name, BI);
414
415             // Make the old cast instruction reference the new GEP instead of
416             // the old src value.
417             //
418             CI->setOperand(0, GEP);
419             
420             PRINT_PEEPHOLE2("cast-for-first:out", GEP, CI);
421             ++NumGEPInstFormed;
422             return true;
423           }
424         }
425       }
426
427   } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
428     Value *Val     = SI->getOperand(0);
429     Value *Pointer = SI->getPointerOperand();
430     
431     // Peephole optimize the following instructions:
432     // %t = cast <T1>* %P to <T2> * ;; If T1 is losslessly convertible to T2
433     // store <T2> %V, <T2>* %t
434     //
435     // Into: 
436     // %t = cast <T2> %V to <T1>
437     // store <T1> %t2, <T1>* %P
438     //
439     // Note: This is not taken care of by expr conversion because there might
440     // not be a cast available for the store to convert the incoming value of.
441     // This code is basically here to make sure that pointers don't have casts
442     // if possible.
443     //
444     if (CastInst *CI = dyn_cast<CastInst>(Pointer))
445       if (Value *CastSrc = CI->getOperand(0)) // CSPT = CastSrcPointerType
446         if (const PointerType *CSPT = dyn_cast<PointerType>(CastSrc->getType()))
447           // convertible types?
448           if (Val->getType()->isLosslesslyConvertibleTo(CSPT->getElementType())) {
449             PRINT_PEEPHOLE3("st-src-cast:in ", Pointer, Val, SI);
450
451             // Insert the new T cast instruction... stealing old T's name
452             std::string Name(CI->getName()); CI->setName("");
453             CastInst *NCI = new CastInst(Val, CSPT->getElementType(),
454                                          Name, BI);
455
456             // Replace the old store with a new one!
457             ReplaceInstWithInst(BB->getInstList(), BI,
458                                 SI = new StoreInst(NCI, CastSrc));
459             PRINT_PEEPHOLE3("st-src-cast:out", NCI, CastSrc, SI);
460             ++NumLoadStorePeepholes;
461             return true;
462           }
463
464   } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
465     Value *Pointer = LI->getOperand(0);
466     const Type *PtrElType =
467       cast<PointerType>(Pointer->getType())->getElementType();
468     
469     // Peephole optimize the following instructions:
470     // %Val = cast <T1>* to <T2>*    ;; If T1 is losslessly convertible to T2
471     // %t = load <T2>* %P
472     //
473     // Into: 
474     // %t = load <T1>* %P
475     // %Val = cast <T1> to <T2>
476     //
477     // Note: This is not taken care of by expr conversion because there might
478     // not be a cast available for the store to convert the incoming value of.
479     // This code is basically here to make sure that pointers don't have casts
480     // if possible.
481     //
482     if (CastInst *CI = dyn_cast<CastInst>(Pointer))
483       if (Value *CastSrc = CI->getOperand(0)) // CSPT = CastSrcPointerType
484         if (const PointerType *CSPT = dyn_cast<PointerType>(CastSrc->getType()))
485           // convertible types?
486           if (PtrElType->isLosslesslyConvertibleTo(CSPT->getElementType())) {
487             PRINT_PEEPHOLE2("load-src-cast:in ", Pointer, LI);
488
489             // Create the new load instruction... loading the pre-casted value
490             LoadInst *NewLI = new LoadInst(CastSrc, LI->getName(), BI);
491             
492             // Insert the new T cast instruction... stealing old T's name
493             CastInst *NCI = new CastInst(NewLI, LI->getType(), CI->getName());
494
495             // Replace the old store with a new one!
496             ReplaceInstWithInst(BB->getInstList(), BI, NCI);
497             PRINT_PEEPHOLE3("load-src-cast:out", NCI, CastSrc, NewLI);
498             ++NumLoadStorePeepholes;
499             return true;
500           }
501
502   } else if (I->getOpcode() == Instruction::Add &&
503              isa<CastInst>(I->getOperand(1))) {
504
505     if (PeepholeOptimizeAddCast(BB, BI, I->getOperand(0),
506                                 cast<CastInst>(I->getOperand(1)), TD)) {
507       ++NumGEPInstFormed;
508       return true;
509     }
510   } else if (CallInst *CI = dyn_cast<CallInst>(I)) {
511     // If we have a call with all varargs arguments, convert the call to use the
512     // actual argument types present...
513     //
514     const PointerType *PTy = cast<PointerType>(CI->getCalledValue()->getType());
515     const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
516
517     // Is the call to a vararg variable with no real parameters?
518     if (FTy->isVarArg() && FTy->getNumParams() == 0 &&
519         !CI->getCalledFunction()) {
520       // If so, insert a new cast instruction, casting it to a function type
521       // that matches the current arguments...
522       //
523       std::vector<const Type *> Params;  // Parameter types...
524       for (unsigned i = 1, e = CI->getNumOperands(); i != e; ++i)
525         Params.push_back(CI->getOperand(i)->getType());
526
527       FunctionType *NewFT = FunctionType::get(FTy->getReturnType(),
528                                               Params, false);
529       PointerType *NewPFunTy = PointerType::get(NewFT);
530
531       // Create a new cast, inserting it right before the function call...
532       Value *NewCast;
533       Constant *ConstantCallSrc = 0;
534       if (Constant *CS = dyn_cast<Constant>(CI->getCalledValue()))
535         ConstantCallSrc = CS;
536       else if (GlobalValue *GV = dyn_cast<GlobalValue>(CI->getCalledValue()))
537         ConstantCallSrc = ConstantPointerRef::get(GV);
538
539       if (ConstantCallSrc)
540         NewCast = ConstantExpr::getCast(ConstantCallSrc, NewPFunTy);
541       else
542         NewCast = new CastInst(CI->getCalledValue(), NewPFunTy,
543                                CI->getCalledValue()->getName()+"_c",CI);
544
545       // Create a new call instruction...
546       CallInst *NewCall = new CallInst(NewCast,
547                            std::vector<Value*>(CI->op_begin()+1, CI->op_end()));
548       ++BI;
549       ReplaceInstWithInst(CI, NewCall);
550       
551       ++NumVarargCallChanges;
552       return true;
553     }
554
555   }
556
557   return false;
558 }
559
560
561
562
563 bool RPR::DoRaisePass(Function &F) {
564   bool Changed = false;
565   for (Function::iterator BB = F.begin(), BBE = F.end(); BB != BBE; ++BB)
566     for (BasicBlock::iterator BI = BB->begin(); BI != BB->end();) {
567       DEBUG(std::cerr << "Processing: " << *BI);
568       if (dceInstruction(BI) || doConstantPropagation(BI)) {
569         Changed = true; 
570         ++NumDCEorCP;
571         DEBUG(std::cerr << "***\t\t^^-- Dead code eliminated!\n");
572       } else if (PeepholeOptimize(BB, BI)) {
573         Changed = true;
574       } else {
575         ++BI;
576       }
577     }
578
579   return Changed;
580 }
581
582
583 // runOnFunction - Raise a function representation to a higher level.
584 bool RPR::runOnFunction(Function &F) {
585   DEBUG(std::cerr << "\n\n\nStarting to work on Function '" << F.getName()
586                   << "'\n");
587
588   // Insert casts for all incoming pointer pointer values that are treated as
589   // arrays...
590   //
591   bool Changed = false, LocalChange;
592
593   // If the StartInst option was specified, then Peephole optimize that
594   // instruction first if it occurs in this function.
595   //
596   if (!StartInst.empty()) {
597     for (Function::iterator BB = F.begin(), BBE = F.end(); BB != BBE; ++BB)
598       for (BasicBlock::iterator BI = BB->begin(); BI != BB->end(); ++BI)
599         if (BI->getName() == StartInst) {
600           bool SavedDebug = DebugFlag;  // Save the DEBUG() controlling flag.
601           DebugFlag = true;             // Turn on DEBUG's
602           Changed |= PeepholeOptimize(BB, BI);
603           DebugFlag = SavedDebug;       // Restore DebugFlag to previous state
604         }
605   }
606
607   do {
608     DEBUG(std::cerr << "Looping: \n" << F);
609
610     // Iterate over the function, refining it, until it converges on a stable
611     // state
612     LocalChange = false;
613     while (DoRaisePass(F)) LocalChange = true;
614     Changed |= LocalChange;
615
616   } while (LocalChange);
617
618   return Changed;
619 }