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