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