Better heuristics for handling arrays
[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.  Note that it is good to run DCE after doing this transformation.
6 //
7 //  Eliminate silly things in the source that do not effect the level, but do
8 //  clean up the code:
9 //    * Casts of casts
10 //    - getelementptr/load & getelementptr/store are folded into a direct
11 //      load or store
12 //    - Convert this code (for both alloca and malloc):
13 //          %reg110 = shl uint %n, ubyte 2          ;;<uint>
14 //          %reg108 = alloca ubyte, uint %reg110            ;;<ubyte*>
15 //          %cast76 = cast ubyte* %reg108 to uint*          ;;<uint*>
16 //      To: %cast76 = alloca uint, uint %n
17 //   Convert explicit addressing to use getelementptr instruction where possible
18 //      - ...
19 //
20 //   Convert explicit addressing on pointers to use getelementptr instruction.
21 //    - If a pointer is used by arithmetic operation, insert an array casted
22 //      version into the source program, only for the following pointer types:
23 //        * Method argument pointers
24 //        - Pointers returned by alloca or malloc
25 //        - Pointers returned by function calls
26 //    - If a pointer is indexed with a value scaled by a constant size equal
27 //      to the element size of the array, the expression is replaced with a
28 //      getelementptr instruction.
29 //
30 //===----------------------------------------------------------------------===//
31
32 #include "llvm/Transforms/LevelChange.h"
33 #include "TransformInternals.h"
34 #include "llvm/Method.h"
35 #include "llvm/Support/STLExtras.h"
36 #include "llvm/iOther.h"
37 #include "llvm/iMemory.h"
38 #include "llvm/ConstPoolVals.h"
39 #include "llvm/Optimizations/ConstantHandling.h"
40 #include "llvm/Optimizations/DCE.h"
41 #include "llvm/Analysis/Expressions.h"
42 #include <algorithm>
43
44 #include "llvm/Assembly/Writer.h"
45
46 //#define DEBUG_PEEPHOLE_INSTS 1
47
48 #ifdef DEBUG_PEEPHOLE_INSTS
49 #define PRINT_PEEPHOLE(ID, NUM, I)            \
50   cerr << "Inst P/H " << ID << "[" << NUM << "] " << I;
51 #else
52 #define PRINT_PEEPHOLE(ID, NUM, I)
53 #endif
54
55 #define PRINT_PEEPHOLE1(ID, I1) do { PRINT_PEEPHOLE(ID, 0, I1); } while (0)
56 #define PRINT_PEEPHOLE2(ID, I1, I2) \
57   do { PRINT_PEEPHOLE(ID, 0, I1); PRINT_PEEPHOLE(ID, 1, I2); } while (0)
58 #define PRINT_PEEPHOLE3(ID, I1, I2, I3) \
59   do { PRINT_PEEPHOLE(ID, 0, I1); PRINT_PEEPHOLE(ID, 1, I2); \
60        PRINT_PEEPHOLE(ID, 2, I3); } while (0)
61 #define PRINT_PEEPHOLE4(ID, I1, I2, I3, I4) \
62   do { PRINT_PEEPHOLE(ID, 0, I1); PRINT_PEEPHOLE(ID, 1, I2); \
63        PRINT_PEEPHOLE(ID, 2, I3); PRINT_PEEPHOLE(ID, 3, I4); } while (0)
64
65
66 // isReinterpretingCast - Return true if the cast instruction specified will
67 // cause the operand to be "reinterpreted".  A value is reinterpreted if the
68 // cast instruction would cause the underlying bits to change.
69 //
70 static inline bool isReinterpretingCast(const CastInst *CI) {
71   return !losslessCastableTypes(CI->getOperand(0)->getType(), CI->getType());
72 }
73
74
75
76
77 // DoInsertArrayCast - If the argument value has a pointer type, and if the
78 // argument value is used as an array, insert a cast before the specified 
79 // basic block iterator that casts the value to an array pointer.  Return the
80 // new cast instruction (in the CastResult var), or null if no cast is inserted.
81 //
82 static bool DoInsertArrayCast(Method *CurMeth, Value *V, BasicBlock *BB,
83                               BasicBlock::iterator &InsertBefore,
84                               CastInst *&CastResult) {
85   const PointerType *ThePtrType = dyn_cast<PointerType>(V->getType());
86   if (!ThePtrType) return false;
87   bool InsertCast = false;
88
89   for (Value::use_iterator I = V->use_begin(), E = V->use_end(); I != E; ++I) {
90     Instruction *Inst = cast<Instruction>(*I);
91     switch (Inst->getOpcode()) {
92     default: break;                  // Not an interesting use...
93     case Instruction::Add:           // It's being used as an array index!
94   //case Instruction::Sub:
95       InsertCast = true;
96       break;
97     case Instruction::Cast:          // There is already a cast instruction!
98       if (const PointerType *PT = dyn_cast<const PointerType>(Inst->getType()))
99         if (const ArrayType *AT = dyn_cast<const ArrayType>(PT->getValueType()))
100           if (AT->getElementType() == ThePtrType->getValueType()) {
101             // Cast already exists! Return the existing one!
102             CastResult = cast<CastInst>(Inst);
103             return false;       // No changes made to program though...
104           }
105       break;
106     }
107   }
108
109   if (!InsertCast) return false;  // There is no reason to insert a cast!
110
111   // Insert a cast!
112   const Type *ElTy = ThePtrType->getValueType();
113   const PointerType *DestTy = PointerType::get(ArrayType::get(ElTy));
114
115   CastResult = new CastInst(V, DestTy);
116   BB->getInstList().insert(InsertBefore, CastResult);
117   //cerr << "Inserted cast: " << CastResult;
118   return true;            // Made a change!
119 }
120
121
122 // DoInsertArrayCasts - Loop over all "incoming" values in the specified method,
123 // inserting a cast for pointer values that are used as arrays. For our
124 // purposes, an incoming value is considered to be either a value that is 
125 // either a method parameter, a value created by alloca or malloc, or a value
126 // returned from a function call.  All casts are kept attached to their original
127 // values through the PtrCasts map.
128 //
129 static bool DoInsertArrayCasts(Method *M, map<Value*, CastInst*> &PtrCasts) {
130   assert(!M->isExternal() && "Can't handle external methods!");
131
132   // Insert casts for all arguments to the function...
133   bool Changed = false;
134   BasicBlock *CurBB = M->front();
135   BasicBlock::iterator It = CurBB->begin();
136   for (Method::ArgumentListType::iterator AI = M->getArgumentList().begin(), 
137          AE = M->getArgumentList().end(); AI != AE; ++AI) {
138     CastInst *TheCast = 0;
139     if (DoInsertArrayCast(M, *AI, CurBB, It, TheCast)) {
140       It = CurBB->begin();      // We might have just invalidated the iterator!
141       Changed = true;           // Yes we made a change
142       ++It;                     // Insert next cast AFTER this one...
143     }
144
145     if (TheCast)                // Is there a cast associated with this value?
146       PtrCasts[*AI] = TheCast;  // Yes, add it to the map...
147   }
148
149   // TODO: insert casts for alloca, malloc, and function call results.  Also, 
150   // look for pointers that already have casts, to add to the map.
151
152   return Changed;
153 }
154
155
156
157
158 // DoElminatePointerArithmetic - Loop over each incoming pointer variable,
159 // replacing indexing arithmetic with getelementptr calls.
160 //
161 static bool DoEliminatePointerArithmetic(const pair<Value*, CastInst*> &Val) {
162   Value    *V  = Val.first;   // The original pointer
163   CastInst *CV = Val.second;  // The array casted version of the pointer...
164
165   for (Value::use_iterator I = V->use_begin(), E = V->use_end(); I != E; ++I) {
166     Instruction *Inst = cast<Instruction>(*I);
167     if (Inst->getOpcode() != Instruction::Add) 
168       continue;   // We only care about add instructions
169
170     BinaryOperator *Add = cast<BinaryOperator>(Inst);
171
172     // Make sure the array is the first operand of the add expression...
173     if (Add->getOperand(0) != V)
174       Add->swapOperands();
175
176     // Get the amount added to the pointer value...
177     Value *AddAmount = Add->getOperand(1);
178
179     
180   }
181   return false;
182 }
183
184
185 // Peephole Malloc instructions: we take a look at the use chain of the
186 // malloc instruction, and try to find out if the following conditions hold:
187 //   1. The malloc is of the form: 'malloc [sbyte], uint <constant>'
188 //   2. The only users of the malloc are cast & add instructions
189 //   3. Of the cast instructions, there is only one destination pointer type
190 //      [RTy] where the size of the pointed to object is equal to the number
191 //      of bytes allocated.
192 //
193 // If these conditions hold, we convert the malloc to allocate an [RTy]
194 // element.  This should be extended in the future to handle arrays. TODO
195 //
196 static bool PeepholeMallocInst(BasicBlock *BB, BasicBlock::iterator &BI) {
197   MallocInst *MI = cast<MallocInst>(*BI);
198   if (!MI->isArrayAllocation()) return false;    // No array allocation?
199
200   ConstPoolUInt *Amt = dyn_cast<ConstPoolUInt>(MI->getArraySize());
201   if (Amt == 0 || MI->getAllocatedType() != ArrayType::get(Type::SByteTy))
202     return false;
203
204   // Get the number of bytes allocated...
205   unsigned Size = Amt->getValue();
206   const Type *ResultTy = 0;
207
208   // Loop over all of the uses of the malloc instruction, inspecting casts.
209   for (Value::use_iterator I = MI->use_begin(), E = MI->use_end();
210        I != E; ++I) {
211     if (CastInst *CI = dyn_cast<CastInst>(*I)) {
212         //cerr << "\t" << CI;
213     
214       // We only work on casts to pointer types for sure, be conservative
215       if (!isa<PointerType>(CI->getType())) {
216         cerr << "Found cast of malloc value to non pointer type:\n" << CI;
217         return false;
218       }
219
220       const Type *DestTy = cast<PointerType>(CI->getType())->getValueType();
221       if (isa<ArrayType>(DestTy)) {
222         cerr << "Avoided malloc conversion because of type: " << DestTy
223              << " TODO.\n";
224         return false;
225       }
226       if (TD.getTypeSize(DestTy) == Size && DestTy != ResultTy) {
227         // Does the size of the allocated type match the number of bytes
228         // allocated?
229         //
230         if (ResultTy == 0) {
231           ResultTy = DestTy;   // Keep note of this for future uses...
232         } else {
233           // It's overdefined!  We don't know which type to convert to!
234           return false;
235         }
236       }
237     }
238   }
239
240   // If we get this far, we have either found, or not, a type that is cast to
241   // that is of the same size as the malloc instruction.
242   if (!ResultTy) return false;
243
244   // Now we check to see if we can convert the return value of malloc to the
245   // specified pointer type.  All this is moot if we can't.
246   //
247   ValueTypeCache ConvertedTypes;
248   if (RetValConvertableToType(MI, PointerType::get(ResultTy), ConvertedTypes)) {
249     // Yup, it's convertable, do the transformation now!
250     PRINT_PEEPHOLE1("mall-refine:in ", MI);
251
252     // Create a new malloc instruction, and insert it into the method...
253     MallocInst *NewMI = new MallocInst(PointerType::get(ResultTy));
254     NewMI->setName(MI->getName());
255     MI->setName("");
256     BI = BB->getInstList().insert(BI, NewMI)+1;
257
258     // Create a new cast instruction to cast it to the old type...
259     CastInst *NewCI = new CastInst(NewMI, MI->getType());
260     BB->getInstList().insert(BI, NewCI);
261
262     // Move all users of the old malloc instruction over to use the new cast...
263     MI->replaceAllUsesWith(NewCI);
264
265     ValueMapCache ValueMap;
266     ConvertUsersType(NewCI, NewMI, ValueMap);  // This will delete MI!
267         
268     BI = BB->begin();  // Rescan basic block.  BI might be invalidated.
269     PRINT_PEEPHOLE1("mall-refine:out", NewMI);
270     return true;
271   }
272   return false;
273 }
274
275
276
277 // Peephole optimize the following instructions:
278 // %t1 = cast ulong <const int> to {<...>} *
279 // %t2 = add {<...>} * %SP, %t1              ;; Constant must be 2nd operand
280 //
281 //    or
282 // %t1 = cast {<...>}* %SP to int*
283 // %t5 = cast ulong <const int> to int*
284 // %t2 = add int* %t1, %t5                   ;; int is same size as field
285 //
286 // Into: %t3 = getelementptr {<...>} * %SP, <element indices>
287 //       %t2 = cast <eltype> * %t3 to {<...>}*
288 //
289 static bool PeepholeOptimizeAddCast(BasicBlock *BB, BasicBlock::iterator &BI,
290                                     Value *AddOp1, CastInst *AddOp2) {
291   Value            *OffsetVal = AddOp2->getOperand(0);
292   Value            *SrcPtr;  // Of type pointer to struct...
293   const StructType *StructTy;
294
295   if ((StructTy = getPointedToStruct(AddOp1->getType()))) {
296     SrcPtr = AddOp1;                      // Handle the first case...
297   } else if (CastInst *AddOp1c = dyn_cast<CastInst>(AddOp1)) {
298     SrcPtr = AddOp1c->getOperand(0);      // Handle the second case...
299     StructTy = getPointedToStruct(SrcPtr->getType());
300   }
301
302   // Only proceed if we have detected all of our conditions successfully...
303   if (!StructTy || !SrcPtr || !OffsetVal->getType()->isIntegral())
304     return false;
305
306   // See if the cast is of an integer expression that is either a constant,
307   // or a value scaled by some amount with a possible offset.
308   //
309   analysis::ExprType Expr = analysis::ClassifyExpression(OffsetVal);
310   unsigned         Offset = 0, Scale = 1;
311
312   // The expression must either be a constant, or a scaled index to be useful
313   if (!Expr.Offset && !Expr.Scale)
314     return false;
315
316   // Get the offset value if it exists...
317   if (Expr.Offset) {
318     if (ConstPoolSInt *CPSI = dyn_cast<ConstPoolSInt>(Expr.Offset))
319       Offset = (unsigned)CPSI->getValue();
320     else {
321       ConstPoolUInt *CPUI = cast<ConstPoolUInt>(Expr.Offset);
322       Offset = (unsigned)CPUI->getValue();
323     }
324     assert(Offset != 0 && "Expression analysis failure!");
325   }
326
327   // Get the scale value if it exists...
328   if (Expr.Scale) {
329     if (ConstPoolSInt *CPSI = dyn_cast<ConstPoolSInt>(Expr.Scale))
330       Scale = (unsigned)CPSI->getValue();
331     else {
332       ConstPoolUInt *CPUI = cast<ConstPoolUInt>(Expr.Scale);
333       Scale = (unsigned)CPUI->getValue();
334     }
335     assert(Scale != 1 && "Expression analysis failure!");
336   }
337   
338   // Check to make sure the offset is not negative or really large, outside the
339   // scope of this structure...
340   //
341   if (Offset >= TD.getTypeSize(StructTy))
342     return false;
343
344   const StructLayout *SL = TD.getStructLayout(StructTy);
345   vector<ConstPoolVal*> Offsets;
346   unsigned ActualOffset = Offset;
347   const Type *ElTy = getStructOffsetType(StructTy, ActualOffset, Offsets);
348   
349   if (getPointedToStruct(AddOp1->getType())) {  // case 1
350     PRINT_PEEPHOLE2("add-to-gep1:in", AddOp2, *BI);
351   } else {
352     PRINT_PEEPHOLE3("add-to-gep2:in", AddOp1, AddOp2, *BI);
353   }
354
355   GetElementPtrInst *GEP = new GetElementPtrInst(SrcPtr, Offsets);
356   //AddOp2->getName());
357   BI = BB->getInstList().insert(BI, GEP)+1;
358   
359   Instruction *AddrSrc = GEP;
360   
361   if (const ArrayType *AT = dyn_cast<ArrayType>(ElTy)) {
362     assert((Scale == 1 || Offset == ActualOffset) &&
363            "Cannot handle scaled expression and unused offset in the same "
364            "instruction until after GEP array works!");
365
366     // Check to see if we have bottomed out INSIDE of an array reference..
367     //
368     if (Offset != ActualOffset) {
369       // Insert a cast of the "rest" of the offset to the appropriate
370       // pointer type.
371       CastInst *OffInst =
372         new CastInst(ConstPoolUInt::get(Type::ULongTy, 
373                                         Offset-ActualOffset),
374                      GEP->getType());
375       BI = BB->getInstList().insert(BI, OffInst)+1;
376       
377       // Now insert an ADD to actually adjust the pointer...
378       Instruction *AddInst =
379         BinaryOperator::create(Instruction::Add, GEP, OffInst);
380       BI = BB->getInstList().insert(BI, AddInst)+1;
381
382       PRINT_PEEPHOLE2("add-to-gep:out1", OffInst, AddInst);
383       
384       AddrSrc = AddInst;
385     } else if (Scale != 1) {
386       // If the scale factor occurs, then this means that there is an index into
387       // this element of the array.  Check to make sure the scale factor is the
388       // same as the size of the datatype that we are dealing with.
389       //
390       assert(Scale == TD.getTypeSize(AT->getElementType()) && 
391              "Scaling by something other than the array element size!!");
392       
393       // TODO: In the future, we will not want to cast the index and scale to
394       // pointer types first.  We will want to create a GEP directly here.
395
396       // Now we must actually perform the scaling operation to get an
397       // appropriate value to add in... but the scale has to be done in the
398       // appropriate destination pointer type, so cast the index value now.
399       //
400       // Cast the base index pointer
401       CastInst *IdxValue = new CastInst(Expr.Var, GEP->getType());
402       BI = BB->getInstList().insert(BI, IdxValue)+1;
403
404       // Case the scale amount as well...
405       CastInst *ScaleAmt =
406         new CastInst(ConstPoolUInt::get(Type::ULongTy, Scale), GEP->getType());
407       BI = BB->getInstList().insert(BI, ScaleAmt)+1;
408
409       // Insert the multiply now.  Make sure to make the constant the second arg
410       Instruction *ScaledVal =
411         BinaryOperator::create(Instruction::Mul, IdxValue, ScaleAmt);
412       BI = BB->getInstList().insert(BI, ScaledVal)+1;
413
414       // Now insert an ADD to actually adjust the pointer...
415       Instruction *AddInst =
416         BinaryOperator::create(Instruction::Add, GEP, ScaledVal);
417       BI = BB->getInstList().insert(BI, AddInst)+1;
418
419       PRINT_PEEPHOLE4("add-to-gep:out1", IdxValue, ScaleAmt, ScaledVal, 
420                       AddInst);
421       AddrSrc = AddInst;
422     }
423     
424     // Insert a cast of the pointer to array of X to be a pointer to the
425     // element of the array.
426     //
427     // Insert a cast of the "rest" of the offset to the appropriate
428     // pointer type.
429     CastInst *ACI = new CastInst(AddrSrc, AT->getElementType());
430     BI = BB->getInstList().insert(BI, ACI)+1;
431     AddrSrc = ACI;
432     
433   } else {
434     assert(Offset == ActualOffset && "GEP to middle of non array!");
435     assert(Scale == 1 && "Scale factor for expr that is not an array idx!");
436   }
437   
438   Instruction *NCI = new CastInst(AddrSrc, AddOp1->getType());
439   ReplaceInstWithInst(BB->getInstList(), BI, NCI);
440   PRINT_PEEPHOLE2("add-to-gep:out", GEP, NCI);
441   return true;
442 }
443
444 // Peephole optimize the following instructions:
445 //   %t1 = cast int (uint) * %reg111 to uint (...) *
446 //   %t2 = call uint (...) * %cast111( uint %key )
447 //
448 // Into: %t3 = call int (uint) * %reg111( uint %key )
449 //       %t2 = cast int %t3 to uint
450 //
451 static bool PeepholeCallInst(BasicBlock *BB, BasicBlock::iterator &BI) {
452   CallInst *CI = cast<CallInst>(*BI);
453   return false;
454 }
455
456
457 static bool PeepholeOptimize(BasicBlock *BB, BasicBlock::iterator &BI) {
458   Instruction *I = *BI;
459
460   if (CastInst *CI = dyn_cast<CastInst>(I)) {
461     Value       *Src    = CI->getOperand(0);
462     Instruction *SrcI   = dyn_cast<Instruction>(Src); // Nonnull if instr source
463     const Type  *DestTy = CI->getType();
464
465     // Peephole optimize the following instruction:
466     // %V2 = cast <ty> %V to <ty>
467     //
468     // Into: <nothing>
469     //
470     if (DestTy == Src->getType()) {   // Check for a cast to same type as src!!
471       PRINT_PEEPHOLE1("cast-of-self-ty", CI);
472       CI->replaceAllUsesWith(Src);
473       if (!Src->hasName() && CI->hasName()) {
474         string Name = CI->getName();
475         CI->setName("");
476         Src->setName(Name, BB->getParent()->getSymbolTable());
477       }
478       return true;
479     }
480
481     // Peephole optimize the following instructions:
482     // %tmp = cast <ty> %V to <ty2>
483     // %V  = cast <ty2> %tmp to <ty3>     ; Where ty & ty2 are same size
484     //
485     // Into: cast <ty> %V to <ty3>
486     //
487     if (SrcI)
488       if (CastInst *CSrc = dyn_cast<CastInst>(SrcI))
489         if (isReinterpretingCast(CI) + isReinterpretingCast(CSrc) < 2) {
490           // We can only do c-c elimination if, at most, one cast does a
491           // reinterpretation of the input data.
492           //
493           // If legal, make this cast refer the the original casts argument!
494           //
495           PRINT_PEEPHOLE2("cast-cast:in ", CI, CSrc);
496           CI->setOperand(0, CSrc->getOperand(0));
497           PRINT_PEEPHOLE1("cast-cast:out", CI);
498           return true;
499         }
500
501     // Check to see if it's a cast of an instruction that does not depend on the
502     // specific type of the operands to do it's job.
503     if (!isReinterpretingCast(CI)) {
504       ValueTypeCache ConvertedTypes;
505       if (RetValConvertableToType(CI, Src->getType(), ConvertedTypes)) {
506         PRINT_PEEPHOLE2("CAST-DEST-EXPR-CONV:in ", CI, Src);
507
508 #ifdef DEBUG_PEEPHOLE_INSTS
509         cerr << "\nCONVERTING EXPR TYPE:\n";
510 #endif
511         ValueMapCache ValueMap;
512         ConvertUsersType(CI, Src, ValueMap);  // This will delete CI!
513
514         BI = BB->begin();  // Rescan basic block.  BI might be invalidated.
515         PRINT_PEEPHOLE1("CAST-DEST-EXPR-CONV:out", Src);
516 #ifdef DEBUG_PEEPHOLE_INSTS
517         cerr << "DONE CONVERTING EXPR TYPE: \n\n";// << BB->getParent();
518 #endif
519         return true;
520       } else {
521         ConvertedTypes.clear();
522         if (ExpressionConvertableToType(Src, DestTy, ConvertedTypes)) {
523           PRINT_PEEPHOLE2("CAST-SRC-EXPR-CONV:in ", CI, Src);
524           
525 #ifdef DEBUG_PEEPHOLE_INSTS
526           cerr << "\nCONVERTING SRC EXPR TYPE:\n";
527 #endif
528           ValueMapCache ValueMap;
529           Value *E = ConvertExpressionToType(Src, DestTy, ValueMap);
530           if (ConstPoolVal *CPV = dyn_cast<ConstPoolVal>(E))
531             CI->replaceAllUsesWith(CPV);
532
533           BI = BB->begin();  // Rescan basic block.  BI might be invalidated.
534           PRINT_PEEPHOLE1("CAST-SRC-EXPR-CONV:out", E);
535 #ifdef DEBUG_PEEPHOLE_INSTS
536           cerr << "DONE CONVERTING SRC EXPR TYPE: \n\n";// << BB->getParent();
537 #endif
538           return true;
539         }
540       }
541       
542     }
543
544     // Check to see if we are casting from a structure pointer to a pointer to
545     // the first element of the structure... to avoid munching other peepholes,
546     // we only let this happen if there are no add uses of the cast.
547     //
548     // Peephole optimize the following instructions:
549     // %t1 = cast {<...>} * %StructPtr to <ty> *
550     //
551     // Into: %t2 = getelementptr {<...>} * %StructPtr, <0, 0, 0, ...>
552     //       %t1 = cast <eltype> * %t1 to <ty> *
553     //
554 #if 1
555     if (const StructType *STy = getPointedToStruct(Src->getType()))
556       if (const PointerType *DestPTy = dyn_cast<PointerType>(DestTy)) {
557
558         // Loop over uses of the cast, checking for add instructions.  If an add
559         // exists, this is probably a part of a more complex GEP, so we don't
560         // want to mess around with the cast.
561         //
562         bool HasAddUse = false;
563         for (Value::use_iterator I = CI->use_begin(), E = CI->use_end();
564              I != E; ++I)
565           if (isa<Instruction>(*I) &&
566               cast<Instruction>(*I)->getOpcode() == Instruction::Add) {
567             HasAddUse = true; break;
568           }
569
570         // If it doesn't have an add use, check to see if the dest type is
571         // losslessly convertable to one of the types in the start of the struct
572         // type.
573         //
574         if (!HasAddUse) {
575           const Type *DestPointedTy = DestPTy->getValueType();
576           unsigned Depth = 1;
577           const StructType *CurSTy = STy;
578           const Type *ElTy = 0;
579           while (CurSTy) {
580             
581             // Check for a zero element struct type... if we have one, bail.
582             if (CurSTy->getElementTypes().size() == 0) break;
583             
584             // Grab the first element of the struct type, which must lie at
585             // offset zero in the struct.
586             //
587             ElTy = CurSTy->getElementTypes()[0];
588
589             // Did we find what we're looking for?
590             if (losslessCastableTypes(ElTy, DestPointedTy)) break;
591             
592             // Nope, go a level deeper.
593             ++Depth;
594             CurSTy = dyn_cast<StructType>(ElTy);
595             ElTy = 0;
596           }
597           
598           // Did we find what we were looking for? If so, do the transformation
599           if (ElTy) {
600             PRINT_PEEPHOLE1("cast-for-first:in", CI);
601
602             // Build the index vector, full of all zeros
603             vector<ConstPoolVal *> Indices(Depth,
604                                            ConstPoolUInt::get(Type::UByteTy,0));
605
606             // Insert the new T cast instruction... stealing old T's name
607             GetElementPtrInst *GEP = new GetElementPtrInst(Src, Indices,
608                                                            CI->getName());
609             CI->setName("");
610             BI = BB->getInstList().insert(BI, GEP)+1;
611
612             // Make the old cast instruction reference the new GEP instead of
613             // the old src value.
614             //
615             CI->setOperand(0, GEP);
616             
617             PRINT_PEEPHOLE2("cast-for-first:out", GEP, CI);
618             return true;
619           }
620         }
621       }
622 #endif
623
624 #if 1
625   } else if (MallocInst *MI = dyn_cast<MallocInst>(I)) {
626     if (PeepholeMallocInst(BB, BI)) return true;
627
628   } else if (CallInst *CI = dyn_cast<CallInst>(I)) {
629     if (PeepholeCallInst(BB, BI)) return true;
630
631   } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
632     Value *Val     = SI->getOperand(0);
633     Value *Pointer = SI->getPtrOperand();
634     
635     // Peephole optimize the following instructions:
636     // %t1 = getelementptr {<...>} * %StructPtr, <element indices>
637     // store <elementty> %v, <elementty> * %t1
638     //
639     // Into: store <elementty> %v, {<...>} * %StructPtr, <element indices>
640     //
641     if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Pointer)) {
642       // Append any indices that the store instruction has onto the end of the
643       // ones that the GEP is carrying...
644       //
645       vector<ConstPoolVal*> Indices(GEP->getIndices());
646       Indices.insert(Indices.end(), SI->getIndices().begin(),
647                      SI->getIndices().end());
648
649       PRINT_PEEPHOLE2("gep-store:in", GEP, SI);
650       ReplaceInstWithInst(BB->getInstList(), BI,
651                           SI = new StoreInst(Val, GEP->getPtrOperand(),
652                                              Indices));
653       PRINT_PEEPHOLE1("gep-store:out", SI);
654       return true;
655     }
656     
657     // Peephole optimize the following instructions:
658     // %t = cast <T1>* %P to <T2> * ;; If T1 is losslessly convertable to T2
659     // store <T2> %V, <T2>* %t
660     //
661     // Into: 
662     // %t = cast <T2> %V to <T1>
663     // store <T1> %t2, <T1>* %P
664     //
665     if (CastInst *CI = dyn_cast<CastInst>(Pointer))
666       if (Value *CastSrc = CI->getOperand(0)) // CSPT = CastSrcPointerType
667         if (PointerType *CSPT = dyn_cast<PointerType>(CastSrc->getType()))
668           if (losslessCastableTypes(Val->getType(), // convertable types!
669                                     CSPT->getValueType()) &&
670               !SI->hasIndices()) {      // No subscripts yet!
671             PRINT_PEEPHOLE3("st-src-cast:in ", Pointer, Val, SI);
672
673             // Insert the new T cast instruction... stealing old T's name
674             CastInst *NCI = new CastInst(Val, CSPT->getValueType(),
675                                          CI->getName());
676             CI->setName("");
677             BI = BB->getInstList().insert(BI, NCI)+1;
678
679             // Replace the old store with a new one!
680             ReplaceInstWithInst(BB->getInstList(), BI,
681                                 SI = new StoreInst(NCI, CastSrc));
682             PRINT_PEEPHOLE3("st-src-cast:out", NCI, CastSrc, SI);
683             return true;
684           }
685
686
687   } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
688     Value *Pointer = LI->getPtrOperand();
689     
690     // Peephole optimize the following instructions:
691     // %t1 = getelementptr {<...>} * %StructPtr, <element indices>
692     // %V  = load <elementty> * %t1
693     //
694     // Into: load {<...>} * %StructPtr, <element indices>
695     //
696     if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Pointer)) {
697       // Append any indices that the load instruction has onto the end of the
698       // ones that the GEP is carrying...
699       //
700       vector<ConstPoolVal*> Indices(GEP->getIndices());
701       Indices.insert(Indices.end(), LI->getIndices().begin(),
702                      LI->getIndices().end());
703
704       PRINT_PEEPHOLE2("gep-load:in", GEP, LI);
705       ReplaceInstWithInst(BB->getInstList(), BI,
706                           LI = new LoadInst(GEP->getPtrOperand(),
707                                             Indices));
708       PRINT_PEEPHOLE1("gep-load:out", LI);
709       return true;
710     }
711
712
713     // Peephole optimize the following instructions:
714     // %t1 = cast <ty> * %t0 to <ty2> *
715     // %V  = load <ty2> * %t1
716     //
717     // Into: %t1 = load <ty> * %t0
718     //       %V  = cast <ty> %t1 to <ty2>
719     //
720     // The idea behind this transformation is that if the expression type
721     // conversion engine could not convert the cast into some other nice form,
722     // that there is something fundementally wrong with the current shape of
723     // the program.  Move the cast through the load and try again.  This will
724     // leave the original cast instruction, to presumably become dead.
725     //
726     if (CastInst *CI = dyn_cast<CastInst>(Pointer)) {
727       Value *SrcVal = CI->getOperand(0);
728       const PointerType *SrcTy = dyn_cast<PointerType>(SrcVal->getType());
729       const Type *ElTy = SrcTy ? SrcTy->getValueType() : 0;
730
731       // Make sure that nothing will be lost in the new cast...
732       if (SrcTy && losslessCastableTypes(ElTy, LI->getType())) {
733         PRINT_PEEPHOLE2("CL-LoadCast:in ", CI, LI);
734
735         string CName = CI->getName(); CI->setName("");
736         LoadInst *NLI = new LoadInst(SrcVal, LI->getName());
737         LI->setName("");  // Take over the old load's name
738
739         // Insert the load before the old load
740         BI = BB->getInstList().insert(BI, NLI)+1;
741
742         // Replace the old load with a new cast...
743         ReplaceInstWithInst(BB->getInstList(), BI, 
744                             CI = new CastInst(NLI, LI->getType(), CName));
745         PRINT_PEEPHOLE2("CL-LoadCast:out", NLI, CI);
746
747         return true;
748       }
749     }
750   } else if (I->getOpcode() == Instruction::Add &&
751              isa<CastInst>(I->getOperand(1))) {
752
753     if (PeepholeOptimizeAddCast(BB, BI, I->getOperand(0),
754                                 cast<CastInst>(I->getOperand(1))))
755       return true;
756
757 #endif
758   }
759
760   return false;
761 }
762
763
764
765
766 static bool DoRaisePass(Method *M) {
767   bool Changed = false;
768   for (Method::iterator MI = M->begin(), ME = M->end(); MI != ME; ++MI) {
769     BasicBlock *BB = *MI;
770     BasicBlock::InstListType &BIL = BB->getInstList();
771
772     for (BasicBlock::iterator BI = BB->begin(); BI != BB->end();) {
773       if (opt::DeadCodeElimination::dceInstruction(BIL, BI)) {
774         Changed = true; 
775 #ifdef DEBUG_PEEPHOLE_INSTS
776         cerr << "DeadCode Elinated!\n";
777 #endif
778       } else if (PeepholeOptimize(BB, BI))
779         Changed = true;
780       else
781         ++BI;
782     }
783   }
784   return Changed;
785 }
786
787
788 // RaisePointerReferences::doit - Raise a method representation to a higher
789 // level.
790 //
791 bool RaisePointerReferences::doit(Method *M) {
792   if (M->isExternal()) return false;
793   bool Changed = false;
794
795 #ifdef DEBUG_PEEPHOLE_INSTS
796   cerr << "\n\n\nStarting to work on Method '" << M->getName() << "'\n";
797 #endif
798
799   while (DoRaisePass(M)) Changed = true;
800
801 #if 0
802   // PtrCasts - Keep a mapping between the pointer values (the key of the 
803   // map), and the cast to array pointer (the value) in this map.  This is
804   // used when converting pointer math into array addressing.
805   // 
806   map<Value*, CastInst*> PtrCasts;
807
808   // Insert casts for all incoming pointer values.  Keep track of those casts
809   // and the identified incoming values in the PtrCasts map.
810   //
811   Changed |= DoInsertArrayCasts(M, PtrCasts);
812
813   // Loop over each incoming pointer variable, replacing indexing arithmetic
814   // with getelementptr calls.
815   //
816   Changed |= reduce_apply_bool(PtrCasts.begin(), PtrCasts.end(), 
817                                ptr_fun(DoEliminatePointerArithmetic));
818 #endif
819
820   return Changed;
821 }