f140676937152fd0bcf8cf5d1db57e69b0dd242b
[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/LevelChange.h"
10 #include "TransformInternals.h"
11 #include "llvm/Method.h"
12 #include "llvm/iOther.h"
13 #include "llvm/iMemory.h"
14 #include "llvm/ConstantVals.h"
15 #include "llvm/Optimizations/ConstantHandling.h"
16 #include "llvm/Optimizations/DCE.h"
17 #include "llvm/Optimizations/ConstantProp.h"
18 #include "llvm/Analysis/Expressions.h"
19 #include "Support/STLExtras.h"
20 #include <algorithm>
21
22 #include "llvm/Assembly/Writer.h"
23
24 //#define DEBUG_PEEPHOLE_INSTS 1
25
26 #ifdef DEBUG_PEEPHOLE_INSTS
27 #define PRINT_PEEPHOLE(ID, NUM, I)            \
28   cerr << "Inst P/H " << ID << "[" << NUM << "] " << I;
29 #else
30 #define PRINT_PEEPHOLE(ID, NUM, I)
31 #endif
32
33 #define PRINT_PEEPHOLE1(ID, I1) do { PRINT_PEEPHOLE(ID, 0, I1); } while (0)
34 #define PRINT_PEEPHOLE2(ID, I1, I2) \
35   do { PRINT_PEEPHOLE(ID, 0, I1); PRINT_PEEPHOLE(ID, 1, I2); } while (0)
36 #define PRINT_PEEPHOLE3(ID, I1, I2, I3) \
37   do { PRINT_PEEPHOLE(ID, 0, I1); PRINT_PEEPHOLE(ID, 1, I2); \
38        PRINT_PEEPHOLE(ID, 2, I3); } while (0)
39 #define PRINT_PEEPHOLE4(ID, I1, I2, I3, I4) \
40   do { PRINT_PEEPHOLE(ID, 0, I1); PRINT_PEEPHOLE(ID, 1, I2); \
41        PRINT_PEEPHOLE(ID, 2, I3); PRINT_PEEPHOLE(ID, 3, I4); } while (0)
42
43
44 // isReinterpretingCast - Return true if the cast instruction specified will
45 // cause the operand to be "reinterpreted".  A value is reinterpreted if the
46 // cast instruction would cause the underlying bits to change.
47 //
48 static inline bool isReinterpretingCast(const CastInst *CI) {
49   return!CI->getOperand(0)->getType()->isLosslesslyConvertableTo(CI->getType());
50 }
51
52
53
54 // Peephole optimize the following instructions:
55 // %t1 = cast ? to x *
56 // %t2 = add x * %SP, %t1              ;; Constant must be 2nd operand
57 //
58 // Into: %t3 = getelementptr {<...>} * %SP, <element indices>
59 //       %t2 = cast <eltype> * %t3 to {<...>}*
60 //
61 static bool HandleCastToPointer(BasicBlock::iterator BI,
62                                 const PointerType *DestPTy) {
63   CastInst *CI = cast<CastInst>(*BI);
64
65   // Scan all of the uses, looking for any uses that are not add
66   // instructions.  If we have non-adds, do not make this transformation.
67   //
68   for (Value::use_iterator I = CI->use_begin(), E = CI->use_end();
69        I != E; ++I) {
70     if (BinaryOperator *BO = dyn_cast<BinaryOperator>(*I)) {
71       if (BO->getOpcode() != Instruction::Add)
72         return false;
73     } else {
74       return false;
75     }
76   }
77
78   std::vector<Value*> Indices;
79   Value *Src = CI->getOperand(0);
80   const Type *Result = ConvertableToGEP(DestPTy, Src, Indices, &BI);
81   if (Result == 0) return false;  // Not convertable...
82
83   PRINT_PEEPHOLE2("cast-add-to-gep:in", Src, CI);
84
85   // If we have a getelementptr capability... transform all of the 
86   // add instruction uses into getelementptr's.
87   for (Value::use_iterator UI = CI->use_begin(), E = CI->use_end();
88        UI != E; ++UI) {
89     Instruction *I = cast<Instruction>(*UI);
90     assert(I->getOpcode() == Instruction::Add && I->getNumOperands() == 2 &&
91            "Use is not a valid add instruction!");
92     
93     // Get the value added to the cast result pointer...
94     Value *OtherPtr = I->getOperand((I->getOperand(0) == CI) ? 1 : 0);
95
96     BasicBlock *BB = I->getParent();
97     BasicBlock::iterator AddIt = find(BB->getInstList().begin(),
98                                       BB->getInstList().end(), I);
99
100     GetElementPtrInst *GEP = new GetElementPtrInst(OtherPtr, Indices);
101
102     PRINT_PEEPHOLE1("cast-add-to-gep:i", I);
103     
104     // Replace the old add instruction with the shiny new GEP inst
105     ReplaceInstWithInst(BB->getInstList(), AddIt, GEP);
106     PRINT_PEEPHOLE1("cast-add-to-gep:o", GEP);
107   }
108   return true;
109 }
110
111 // Peephole optimize the following instructions:
112 // %t1 = cast ulong <const int> to {<...>} *
113 // %t2 = add {<...>} * %SP, %t1              ;; Constant must be 2nd operand
114 //
115 //    or
116 // %t1 = cast {<...>}* %SP to int*
117 // %t5 = cast ulong <const int> to int*
118 // %t2 = add int* %t1, %t5                   ;; int is same size as field
119 //
120 // Into: %t3 = getelementptr {<...>} * %SP, <element indices>
121 //       %t2 = cast <eltype> * %t3 to {<...>}*
122 //
123 static bool PeepholeOptimizeAddCast(BasicBlock *BB, BasicBlock::iterator &BI,
124                                     Value *AddOp1, CastInst *AddOp2) {
125   const CompositeType *CompTy;
126   Value *OffsetVal = AddOp2->getOperand(0);
127   Value *SrcPtr;  // Of type pointer to struct...
128
129   if ((CompTy = getPointedToComposite(AddOp1->getType()))) {
130     SrcPtr = AddOp1;                      // Handle the first case...
131   } else if (CastInst *AddOp1c = dyn_cast<CastInst>(AddOp1)) {
132     SrcPtr = AddOp1c->getOperand(0);      // Handle the second case...
133     CompTy = getPointedToComposite(SrcPtr->getType());
134   }
135
136   // Only proceed if we have detected all of our conditions successfully...
137   if (!CompTy || !SrcPtr || !OffsetVal->getType()->isIntegral())
138     return false;
139
140   std::vector<Value*> Indices;
141   if (!ConvertableToGEP(SrcPtr->getType(), OffsetVal, Indices, &BI))
142     return false;  // Not convertable... perhaps next time
143
144   if (getPointedToComposite(AddOp1->getType())) {  // case 1
145     PRINT_PEEPHOLE2("add-to-gep1:in", AddOp2, *BI);
146   } else {
147     PRINT_PEEPHOLE3("add-to-gep2:in", AddOp1, AddOp2, *BI);
148   }
149
150   GetElementPtrInst *GEP = new GetElementPtrInst(SrcPtr, Indices,
151                                                  AddOp2->getName());
152   BI = BB->getInstList().insert(BI, GEP)+1;
153
154   Instruction *NCI = new CastInst(GEP, AddOp1->getType());
155   ReplaceInstWithInst(BB->getInstList(), BI, NCI);
156   PRINT_PEEPHOLE2("add-to-gep:out", GEP, NCI);
157   return true;
158 }
159
160 static bool PeepholeOptimize(BasicBlock *BB, BasicBlock::iterator &BI) {
161   Instruction *I = *BI;
162
163   if (CastInst *CI = dyn_cast<CastInst>(I)) {
164     Value       *Src    = CI->getOperand(0);
165     Instruction *SrcI   = dyn_cast<Instruction>(Src); // Nonnull if instr source
166     const Type  *DestTy = CI->getType();
167
168     // Peephole optimize the following instruction:
169     // %V2 = cast <ty> %V to <ty>
170     //
171     // Into: <nothing>
172     //
173     if (DestTy == Src->getType()) {   // Check for a cast to same type as src!!
174       PRINT_PEEPHOLE1("cast-of-self-ty", CI);
175       CI->replaceAllUsesWith(Src);
176       if (!Src->hasName() && CI->hasName()) {
177         std::string Name = CI->getName();
178         CI->setName("");
179         Src->setName(Name, BB->getParent()->getSymbolTable());
180       }
181       return true;
182     }
183
184     // Peephole optimize the following instructions:
185     // %tmp = cast <ty> %V to <ty2>
186     // %V   = cast <ty2> %tmp to <ty3>     ; Where ty & ty2 are same size
187     //
188     // Into: cast <ty> %V to <ty3>
189     //
190     if (SrcI)
191       if (CastInst *CSrc = dyn_cast<CastInst>(SrcI))
192         if (isReinterpretingCast(CI) + isReinterpretingCast(CSrc) < 2) {
193           // We can only do c-c elimination if, at most, one cast does a
194           // reinterpretation of the input data.
195           //
196           // If legal, make this cast refer the the original casts argument!
197           //
198           PRINT_PEEPHOLE2("cast-cast:in ", CI, CSrc);
199           CI->setOperand(0, CSrc->getOperand(0));
200           PRINT_PEEPHOLE1("cast-cast:out", CI);
201           return true;
202         }
203
204     // Check to see if it's a cast of an instruction that does not depend on the
205     // specific type of the operands to do it's job.
206     if (!isReinterpretingCast(CI)) {
207       ValueTypeCache ConvertedTypes;
208
209       // Check to see if we can convert the users of the cast value to match the
210       // source type of the cast...
211       //
212       ConvertedTypes[CI] = CI->getType();  // Make sure the cast doesn't change
213       if (ExpressionConvertableToType(Src, DestTy, ConvertedTypes)) {
214         PRINT_PEEPHOLE3("CAST-SRC-EXPR-CONV:in ", Src, CI, BB->getParent());
215           
216 #ifdef DEBUG_PEEPHOLE_INSTS
217         cerr << "\nCONVERTING SRC EXPR TYPE:\n";
218 #endif
219         ValueMapCache ValueMap;
220         Value *E = ConvertExpressionToType(Src, DestTy, ValueMap);
221         if (Constant *CPV = dyn_cast<Constant>(E))
222           CI->replaceAllUsesWith(CPV);
223
224         BI = BB->begin();  // Rescan basic block.  BI might be invalidated.
225         PRINT_PEEPHOLE1("CAST-SRC-EXPR-CONV:out", E);
226 #ifdef DEBUG_PEEPHOLE_INSTS
227         cerr << "DONE CONVERTING SRC EXPR TYPE: \n" << BB->getParent();
228 #endif
229         return true;
230       }
231
232       // Check to see if we can convert the source of the cast to match the
233       // destination type of the cast...
234       //
235       ConvertedTypes.clear();
236       if (ValueConvertableToType(CI, Src->getType(), ConvertedTypes)) {
237         PRINT_PEEPHOLE3("CAST-DEST-EXPR-CONV:in ", Src, CI, BB->getParent());
238
239 #ifdef DEBUG_PEEPHOLE_INSTS
240         cerr << "\nCONVERTING EXPR TYPE:\n";
241 #endif
242         ValueMapCache ValueMap;
243         ConvertValueToNewType(CI, Src, ValueMap);  // This will delete CI!
244
245         BI = BB->begin();  // Rescan basic block.  BI might be invalidated.
246         PRINT_PEEPHOLE1("CAST-DEST-EXPR-CONV:out", Src);
247 #ifdef DEBUG_PEEPHOLE_INSTS
248         cerr << "DONE CONVERTING EXPR TYPE: \n\n" << BB->getParent();
249 #endif
250         return true;
251       }
252     }
253
254     // Otherwise find out it this cast is a cast to a pointer type, which is
255     // then added to some other pointer, then loaded or stored through.  If
256     // so, convert the add into a getelementptr instruction...
257     //
258     if (const PointerType *DestPTy = dyn_cast<PointerType>(DestTy)) {
259       if (HandleCastToPointer(BI, DestPTy)) {
260         BI = BB->begin();  // Rescan basic block.  BI might be invalidated.
261         return true;
262       }
263     }
264
265     // Check to see if we are casting from a structure pointer to a pointer to
266     // the first element of the structure... to avoid munching other peepholes,
267     // we only let this happen if there are no add uses of the cast.
268     //
269     // Peephole optimize the following instructions:
270     // %t1 = cast {<...>} * %StructPtr to <ty> *
271     //
272     // Into: %t2 = getelementptr {<...>} * %StructPtr, <0, 0, 0, ...>
273     //       %t1 = cast <eltype> * %t1 to <ty> *
274     //
275 #if 1
276     if (const CompositeType *CTy = getPointedToComposite(Src->getType()))
277       if (const PointerType *DestPTy = dyn_cast<PointerType>(DestTy)) {
278
279         // Loop over uses of the cast, checking for add instructions.  If an add
280         // exists, this is probably a part of a more complex GEP, so we don't
281         // want to mess around with the cast.
282         //
283         bool HasAddUse = false;
284         for (Value::use_iterator I = CI->use_begin(), E = CI->use_end();
285              I != E; ++I)
286           if (isa<Instruction>(*I) &&
287               cast<Instruction>(*I)->getOpcode() == Instruction::Add) {
288             HasAddUse = true; break;
289           }
290
291         // If it doesn't have an add use, check to see if the dest type is
292         // losslessly convertable to one of the types in the start of the struct
293         // type.
294         //
295         if (!HasAddUse) {
296           const Type *DestPointedTy = DestPTy->getElementType();
297           unsigned Depth = 1;
298           const CompositeType *CurCTy = CTy;
299           const Type *ElTy = 0;
300
301           // Build the index vector, full of all zeros
302           std::vector<Value*> Indices;
303           Indices.push_back(ConstantUInt::get(Type::UIntTy, 0));
304           while (CurCTy && !isa<PointerType>(CurCTy)) {
305             if (const StructType *CurSTy = dyn_cast<StructType>(CurCTy)) {
306               // Check for a zero element struct type... if we have one, bail.
307               if (CurSTy->getElementTypes().size() == 0) break;
308             
309               // Grab the first element of the struct type, which must lie at
310               // offset zero in the struct.
311               //
312               ElTy = CurSTy->getElementTypes()[0];
313             } else {
314               ElTy = cast<ArrayType>(CurCTy)->getElementType();
315             }
316
317             // Insert a zero to index through this type...
318             Indices.push_back(ConstantUInt::get(CurCTy->getIndexType(), 0));
319
320             // Did we find what we're looking for?
321             if (ElTy->isLosslesslyConvertableTo(DestPointedTy)) break;
322             
323             // Nope, go a level deeper.
324             ++Depth;
325             CurCTy = dyn_cast<CompositeType>(ElTy);
326             ElTy = 0;
327           }
328           
329           // Did we find what we were looking for? If so, do the transformation
330           if (ElTy) {
331             PRINT_PEEPHOLE1("cast-for-first:in", CI);
332
333             // Insert the new T cast instruction... stealing old T's name
334             GetElementPtrInst *GEP = new GetElementPtrInst(Src, Indices,
335                                                            CI->getName());
336             CI->setName("");
337             BI = BB->getInstList().insert(BI, GEP)+1;
338
339             // Make the old cast instruction reference the new GEP instead of
340             // the old src value.
341             //
342             CI->setOperand(0, GEP);
343             
344             PRINT_PEEPHOLE2("cast-for-first:out", GEP, CI);
345             return true;
346           }
347         }
348       }
349 #endif
350
351 #if 1
352   } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
353     Value *Val     = SI->getOperand(0);
354     Value *Pointer = SI->getPointerOperand();
355     
356     // Peephole optimize the following instructions:
357     // %t = cast <T1>* %P to <T2> * ;; If T1 is losslessly convertable to T2
358     // store <T2> %V, <T2>* %t
359     //
360     // Into: 
361     // %t = cast <T2> %V to <T1>
362     // store <T1> %t2, <T1>* %P
363     //
364     // Note: This is not taken care of by expr conversion because there might
365     // not be a cast available for the store to convert the incoming value of.
366     // This code is basically here to make sure that pointers don't have casts
367     // if possible.
368     //
369     if (CastInst *CI = dyn_cast<CastInst>(Pointer))
370       if (Value *CastSrc = CI->getOperand(0)) // CSPT = CastSrcPointerType
371         if (PointerType *CSPT = dyn_cast<PointerType>(CastSrc->getType()))
372           // convertable types?
373           if (Val->getType()->isLosslesslyConvertableTo(CSPT->getElementType()) &&
374               !SI->hasIndices()) {      // No subscripts yet!
375             PRINT_PEEPHOLE3("st-src-cast:in ", Pointer, Val, SI);
376
377             // Insert the new T cast instruction... stealing old T's name
378             CastInst *NCI = new CastInst(Val, CSPT->getElementType(),
379                                          CI->getName());
380             CI->setName("");
381             BI = BB->getInstList().insert(BI, NCI)+1;
382
383             // Replace the old store with a new one!
384             ReplaceInstWithInst(BB->getInstList(), BI,
385                                 SI = new StoreInst(NCI, CastSrc));
386             PRINT_PEEPHOLE3("st-src-cast:out", NCI, CastSrc, SI);
387             return true;
388           }
389
390   } else if (I->getOpcode() == Instruction::Add &&
391              isa<CastInst>(I->getOperand(1))) {
392
393     if (PeepholeOptimizeAddCast(BB, BI, I->getOperand(0),
394                                 cast<CastInst>(I->getOperand(1))))
395       return true;
396
397 #endif
398   }
399
400   return false;
401 }
402
403
404
405
406 static bool DoRaisePass(Method *M) {
407   bool Changed = false;
408   for (Method::iterator MI = M->begin(), ME = M->end(); MI != ME; ++MI) {
409     BasicBlock *BB = *MI;
410     BasicBlock::InstListType &BIL = BB->getInstList();
411
412     for (BasicBlock::iterator BI = BB->begin(); BI != BB->end();) {
413 #if DEBUG_PEEPHOLE_INSTS
414       cerr << "Processing: " << *BI;
415 #endif
416       if (opt::DeadCodeElimination::dceInstruction(BIL, BI) ||
417           opt::ConstantPropogation::doConstantPropogation(BB, BI)) {
418         Changed = true; 
419 #ifdef DEBUG_PEEPHOLE_INSTS
420         cerr << "DeadCode Elinated!\n";
421 #endif
422       } else if (PeepholeOptimize(BB, BI))
423         Changed = true;
424       else
425         ++BI;
426     }
427   }
428   return Changed;
429 }
430
431
432
433
434 // RaisePointerReferences::doit - Raise a method representation to a higher
435 // level.
436 //
437 bool RaisePointerReferences::doit(Method *M) {
438   if (M->isExternal()) return false;
439
440 #ifdef DEBUG_PEEPHOLE_INSTS
441   cerr << "\n\n\nStarting to work on Method '" << M->getName() << "'\n";
442 #endif
443
444   // Insert casts for all incoming pointer pointer values that are treated as
445   // arrays...
446   //
447   bool Changed = false, LocalChange;
448   
449   do {
450 #ifdef DEBUG_PEEPHOLE_INSTS
451     cerr << "Looping: \n" << M;
452 #endif
453
454     // Iterate over the method, refining it, until it converges on a stable
455     // state
456     LocalChange = false;
457     while (DoRaisePass(M)) LocalChange = true;
458     Changed |= LocalChange;
459
460   } while (LocalChange);
461
462   return Changed;
463 }