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