* Implement expression type conversion for constant values
[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 "llvm/Method.h"
34 #include "llvm/Support/STLExtras.h"
35 #include "llvm/iOther.h"
36 #include "llvm/iMemory.h"
37 #include "llvm/ConstPoolVals.h"
38 #include "llvm/Target/TargetData.h"
39 #include "llvm/Optimizations/ConstantHandling.h"
40 #include <map>
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 // TargetData Hack: Eventually we will have annotations given to us by the
63 // backend so that we know stuff about type size and alignments.  For now
64 // though, just use this, because it happens to match the model that GCC uses.
65 //
66 const TargetData TD("LevelRaise: Should be GCC though!");
67
68
69 // losslessCastableTypes - Return true if the types are bitwise equivalent.
70 // This predicate returns true if it is possible to cast from one type to
71 // another without gaining or losing precision, or altering the bits in any way.
72 //
73 static bool losslessCastableTypes(const Type *T1, const Type *T2) {
74   if (!T1->isPrimitiveType() && !isa<PointerType>(T1)) return false;
75   if (!T2->isPrimitiveType() && !isa<PointerType>(T2)) return false;
76
77   if (T1->getPrimitiveID() == T2->getPrimitiveID())
78     return true;  // Handles identity cast, and cast of differing pointer types
79
80   // Now we know that they are two differing primitive or pointer types
81   switch (T1->getPrimitiveID()) {
82   case Type::UByteTyID:   return T2 == Type::SByteTy;
83   case Type::SByteTyID:   return T2 == Type::UByteTy;
84   case Type::UShortTyID:  return T2 == Type::ShortTy;
85   case Type::ShortTyID:   return T2 == Type::UShortTy;
86   case Type::UIntTyID:    return T2 == Type::IntTy;
87   case Type::IntTyID:     return T2 == Type::UIntTy;
88   case Type::ULongTyID:
89   case Type::LongTyID:
90   case Type::PointerTyID:
91     return T2 == Type::ULongTy || T2 == Type::LongTy ||
92            T2->getPrimitiveID() == Type::PointerTyID;
93   default:
94     return false;  // Other types have no identity values
95   }
96 }
97
98
99 // isReinterpretingCast - Return true if the cast instruction specified will
100 // cause the operand to be "reinterpreted".  A value is reinterpreted if the
101 // cast instruction would cause the underlying bits to change.
102 //
103 static inline bool isReinterpretingCast(const CastInst *CI) {
104   return !losslessCastableTypes(CI->getOperand(0)->getType(), CI->getType());
105 }
106
107
108 // getPointedToStruct - If the argument is a pointer type, and the pointed to
109 // value is a struct type, return the struct type, else return null.
110 //
111 static const StructType *getPointedToStruct(const Type *Ty) {
112   const PointerType *PT = dyn_cast<PointerType>(Ty);
113   return PT ? dyn_cast<StructType>(PT->getValueType()) : 0;
114 }
115
116
117 // getStructOffsetType - Return a vector of offsets that are to be used to index
118 // into the specified struct type to get as close as possible to index as we
119 // can.  Note that it is possible that we cannot get exactly to Offset, in which
120 // case we update offset to be the offset we actually obtained.  The resultant
121 // leaf type is returned.
122 //
123 static const Type *getStructOffsetType(const Type *Ty, unsigned &Offset,
124                                        vector<ConstPoolVal*> &Offsets) {
125   if (!isa<StructType>(Ty)) {
126     Offset = 0;   // Return the offset that we were able to acheive
127     return Ty;    // Return the leaf type
128   }
129
130   assert(Offset < TD.getTypeSize(Ty) && "Offset not in struct!");
131   const StructType *STy = cast<StructType>(Ty);
132   const StructLayout *SL = TD.getStructLayout(STy);
133
134   // This loop terminates always on a 0 <= i < MemberOffsets.size()
135   unsigned i;
136   for (i = 0; i < SL->MemberOffsets.size()-1; ++i)
137     if (Offset >= SL->MemberOffsets[i] && Offset <  SL->MemberOffsets[i+1])
138       break;
139   
140   assert(Offset >= SL->MemberOffsets[i] && Offset <  SL->MemberOffsets[i+1]);
141
142   // Make sure to save the current index...
143   Offsets.push_back(ConstPoolUInt::get(Type::UByteTy, i));
144
145   unsigned SubOffs = Offset - SL->MemberOffsets[i];
146   const Type *LeafTy = getStructOffsetType(STy->getElementTypes()[i], SubOffs,
147                                            Offsets);
148   Offset = SL->MemberOffsets[i] + SubOffs;
149   return LeafTy;
150 }
151
152
153
154 // ReplaceInstWithValue - Replace all uses of an instruction (specified by BI)
155 // with a value, then remove and delete the original instruction.
156 //
157 static void ReplaceInstWithValue(BasicBlock::InstListType &BIL,
158                                  BasicBlock::iterator &BI, Value *V) {
159   Instruction *I = *BI;
160   // Replaces all of the uses of the instruction with uses of the value
161   I->replaceAllUsesWith(V);
162
163   // Remove the unneccesary instruction now...
164   BIL.remove(BI);
165
166   // Make sure to propogate a name if there is one already...
167   if (I->hasName() && !V->hasName())
168     V->setName(I->getName(), BIL.getParent()->getSymbolTable());
169
170   // Remove the dead instruction now...
171   delete I;
172 }
173
174
175 // ReplaceInstWithInst - Replace the instruction specified by BI with the
176 // instruction specified by I.  The original instruction is deleted and BI is
177 // updated to point to the new instruction.
178 //
179 static void ReplaceInstWithInst(BasicBlock::InstListType &BIL,
180                                 BasicBlock::iterator &BI, Instruction *I) {
181   assert(I->getParent() == 0 &&
182          "ReplaceInstWithInst: Instruction already inserted into basic block!");
183
184   // Insert the new instruction into the basic block...
185   BI = BIL.insert(BI, I)+1;
186
187   // Replace all uses of the old instruction, and delete it.
188   ReplaceInstWithValue(BIL, BI, I);
189
190   // Reexamine the instruction just inserted next time around the cleanup pass
191   // loop.
192   --BI;
193 }
194
195
196 // ExpressionConvertableToType - Return true if it is possible
197 static bool ExpressionConvertableToType(Value *V, const Type *Ty) {
198   Instruction *I = dyn_cast<Instruction>(V);
199   if (I == 0) {
200     // It's not an instruction, check to see if it's a constant... all constants
201     // can be converted to an equivalent value (except pointers, they can't be
202     // const prop'd in general).
203     //
204     if (isa<ConstPoolVal>(V) &&
205         !isa<PointerType>(V->getType()) && !isa<PointerType>(Ty)) return true;
206
207     return false;              // Otherwise, we can't convert!
208   }
209   if (I->getType() == Ty) return false;  // Expression already correct type!
210
211   switch (I->getOpcode()) {
212   case Instruction::Cast:
213     // We can convert the expr if the cast destination type is losslessly
214     // convertable to the requested type.
215     return losslessCastableTypes(Ty, I->getType());
216
217   case Instruction::Add:
218   case Instruction::Sub:
219     return ExpressionConvertableToType(I->getOperand(0), Ty) &&
220            ExpressionConvertableToType(I->getOperand(1), Ty);
221   case Instruction::Shl:
222   case Instruction::Shr:
223     return ExpressionConvertableToType(I->getOperand(0), Ty);
224   }
225   return false;
226 }
227
228
229 static Value *ConvertExpressionToType(Value *V, const Type *Ty) {
230   assert(ExpressionConvertableToType(V, Ty) && "Value is not convertable!");
231   Instruction *I = dyn_cast<Instruction>(V);
232   if (I == 0)
233     if (ConstPoolVal *CPV = cast<ConstPoolVal>(V)) {
234       // Constants are converted by constant folding the cast that is required.
235       // We assume here that all casts are implemented for constant prop.
236       Value *Result = opt::ConstantFoldCastInstruction(CPV, Ty);
237       if (!Result) cerr << "Couldn't fold " << CPV << " to " << Ty << endl;
238       assert(Result && "ConstantFoldCastInstruction Failed!!!");
239       return Result;
240     }
241
242
243   BasicBlock *BB = I->getParent();
244   BasicBlock::InstListType &BIL = BB->getInstList();
245   string Name = I->getName();  if (!Name.empty()) I->setName("");
246   Instruction *Res;     // Result of conversion
247
248   //cerr << endl << endl << "Type:\t" << Ty << "\nInst: " << I << "BB Before: " << BB << endl;
249
250   switch (I->getOpcode()) {
251   case Instruction::Cast:
252     Res = new CastInst(I->getOperand(0), Ty, Name);
253     break;
254     
255   case Instruction::Add:
256   case Instruction::Sub:
257     Res = BinaryOperator::create(cast<BinaryOperator>(I)->getOpcode(),
258                                  ConvertExpressionToType(I->getOperand(0), Ty),
259                                  ConvertExpressionToType(I->getOperand(1), Ty),
260                                  Name);
261     break;
262
263   case Instruction::Shl:
264   case Instruction::Shr:
265     Res = new ShiftInst(cast<ShiftInst>(I)->getOpcode(),
266                         ConvertExpressionToType(I->getOperand(0), Ty),
267                         I->getOperand(1), Name);
268     break;
269
270   default:
271     assert(0 && "Expression convertable, but don't know how to convert?");
272     return 0;
273   }
274
275   BasicBlock::iterator It = find(BIL.begin(), BIL.end(), I);
276   assert(It != BIL.end() && "Instruction not in own basic block??");
277   BIL.insert(It, Res);
278
279   //cerr << "RInst: " << Res << "BB After: " << BB << endl << endl;
280
281   return Res;
282 }
283
284
285
286 // DoInsertArrayCast - If the argument value has a pointer type, and if the
287 // argument value is used as an array, insert a cast before the specified 
288 // basic block iterator that casts the value to an array pointer.  Return the
289 // new cast instruction (in the CastResult var), or null if no cast is inserted.
290 //
291 static bool DoInsertArrayCast(Method *CurMeth, Value *V, BasicBlock *BB,
292                               BasicBlock::iterator &InsertBefore,
293                               CastInst *&CastResult) {
294   const PointerType *ThePtrType = dyn_cast<PointerType>(V->getType());
295   if (!ThePtrType) return false;
296   bool InsertCast = false;
297
298   for (Value::use_iterator I = V->use_begin(), E = V->use_end(); I != E; ++I) {
299     Instruction *Inst = cast<Instruction>(*I);
300     switch (Inst->getOpcode()) {
301     default: break;                  // Not an interesting use...
302     case Instruction::Add:           // It's being used as an array index!
303   //case Instruction::Sub:
304       InsertCast = true;
305       break;
306     case Instruction::Cast:          // There is already a cast instruction!
307       if (const PointerType *PT = dyn_cast<const PointerType>(Inst->getType()))
308         if (const ArrayType *AT = dyn_cast<const ArrayType>(PT->getValueType()))
309           if (AT->getElementType() == ThePtrType->getValueType()) {
310             // Cast already exists! Return the existing one!
311             CastResult = cast<CastInst>(Inst);
312             return false;       // No changes made to program though...
313           }
314       break;
315     }
316   }
317
318   if (!InsertCast) return false;  // There is no reason to insert a cast!
319
320   // Insert a cast!
321   const Type *ElTy = ThePtrType->getValueType();
322   const PointerType *DestTy = PointerType::get(ArrayType::get(ElTy));
323
324   CastResult = new CastInst(V, DestTy);
325   BB->getInstList().insert(InsertBefore, CastResult);
326   //cerr << "Inserted cast: " << CastResult;
327   return true;            // Made a change!
328 }
329
330
331 // DoInsertArrayCasts - Loop over all "incoming" values in the specified method,
332 // inserting a cast for pointer values that are used as arrays. For our
333 // purposes, an incoming value is considered to be either a value that is 
334 // either a method parameter, a value created by alloca or malloc, or a value
335 // returned from a function call.  All casts are kept attached to their original
336 // values through the PtrCasts map.
337 //
338 static bool DoInsertArrayCasts(Method *M, map<Value*, CastInst*> &PtrCasts) {
339   assert(!M->isExternal() && "Can't handle external methods!");
340
341   // Insert casts for all arguments to the function...
342   bool Changed = false;
343   BasicBlock *CurBB = M->front();
344   BasicBlock::iterator It = CurBB->begin();
345   for (Method::ArgumentListType::iterator AI = M->getArgumentList().begin(), 
346          AE = M->getArgumentList().end(); AI != AE; ++AI) {
347     CastInst *TheCast = 0;
348     if (DoInsertArrayCast(M, *AI, CurBB, It, TheCast)) {
349       It = CurBB->begin();      // We might have just invalidated the iterator!
350       Changed = true;           // Yes we made a change
351       ++It;                     // Insert next cast AFTER this one...
352     }
353
354     if (TheCast)                // Is there a cast associated with this value?
355       PtrCasts[*AI] = TheCast;  // Yes, add it to the map...
356   }
357
358   // TODO: insert casts for alloca, malloc, and function call results.  Also, 
359   // look for pointers that already have casts, to add to the map.
360
361   return Changed;
362 }
363
364
365
366
367 // DoElminatePointerArithmetic - Loop over each incoming pointer variable,
368 // replacing indexing arithmetic with getelementptr calls.
369 //
370 static bool DoEliminatePointerArithmetic(const pair<Value*, CastInst*> &Val) {
371   Value    *V  = Val.first;   // The original pointer
372   CastInst *CV = Val.second;  // The array casted version of the pointer...
373
374   for (Value::use_iterator I = V->use_begin(), E = V->use_end(); I != E; ++I) {
375     Instruction *Inst = cast<Instruction>(*I);
376     if (Inst->getOpcode() != Instruction::Add) 
377       continue;   // We only care about add instructions
378
379     BinaryOperator *Add = cast<BinaryOperator>(Inst);
380
381     // Make sure the array is the first operand of the add expression...
382     if (Add->getOperand(0) != V)
383       Add->swapOperands();
384
385     // Get the amount added to the pointer value...
386     Value *AddAmount = Add->getOperand(1);
387
388     
389   }
390   return false;
391 }
392
393
394 // Peephole Malloc instructions: we take a look at the use chain of the
395 // malloc instruction, and try to find out if the following conditions hold:
396 //   1. The malloc is of the form: 'malloc [sbyte], uint <constant>'
397 //   2. The only users of the malloc are cast instructions
398 //   3. Of the cast instructions, there is only one destination pointer type
399 //      [RTy] where the size of the pointed to object is equal to the number
400 //      of bytes allocated.
401 //
402 // If these conditions hold, we convert the malloc to allocate an [RTy]
403 // element.  This should be extended in the future to handle arrays. TODO
404 //
405 static bool PeepholeMallocInst(BasicBlock *BB, BasicBlock::iterator &BI) {
406   MallocInst *MI = cast<MallocInst>(*BI);
407   if (!MI->isArrayAllocation()) return false;    // No array allocation?
408
409   ConstPoolUInt *Amt = dyn_cast<ConstPoolUInt>(MI->getArraySize());
410   if (Amt == 0 || MI->getAllocatedType() != ArrayType::get(Type::SByteTy))
411     return false;
412
413   // Get the number of bytes allocated...
414   unsigned Size = Amt->getValue();
415   const Type *ResultTy = 0;
416
417   // Loop over all of the uses of the malloc instruction, inspecting casts.
418   for (Value::use_iterator I = MI->use_begin(), E = MI->use_end();
419        I != E; ++I) {
420     if (!isa<CastInst>(*I)) {
421       //cerr << "\tnon" << *I;
422       return false;  // A non cast user?
423     }
424     CastInst *CI = cast<CastInst>(*I);
425     //cerr << "\t" << CI;
426     
427     // We only work on casts to pointer types for sure, be conservative
428     if (!isa<PointerType>(CI->getType())) {
429       cerr << "Found cast of malloc value to non pointer type:\n" << CI;
430       return false;
431     }
432
433     const Type *DestTy = cast<PointerType>(CI->getType())->getValueType();
434     if (TD.getTypeSize(DestTy) == Size && DestTy != ResultTy) {
435       // Does the size of the allocated type match the number of bytes
436       // allocated?
437       //
438       if (ResultTy == 0) {
439         ResultTy = DestTy;   // Keep note of this for future uses...
440       } else {
441         // It's overdefined!  We don't know which type to convert to!
442         return false;
443       }
444     }
445   }
446
447   // If we get this far, we have either found, or not, a type that is cast to
448   // that is of the same size as the malloc instruction.
449   if (!ResultTy) return false;
450
451   PRINT_PEEPHOLE1("mall-refine:in ", MI);
452   ReplaceInstWithInst(BB->getInstList(), BI, 
453                       MI = new MallocInst(PointerType::get(ResultTy)));
454   PRINT_PEEPHOLE1("mall-refine:out", MI);
455   return true;
456 }
457
458
459
460 static bool PeepholeOptimize(BasicBlock *BB, BasicBlock::iterator &BI) {
461   Instruction *I = *BI;
462   // TODO: replace this with a DCE call
463   if (I->use_size() == 0 && I->getType() != Type::VoidTy) return false;
464
465   if (CastInst *CI = dyn_cast<CastInst>(I)) {
466     Value       *Src    = CI->getOperand(0);
467     Instruction *SrcI   = dyn_cast<Instruction>(Src); // Nonnull if instr source
468     const Type  *DestTy = CI->getType();
469
470     // Check for a cast of the same type as the destination!
471     if (DestTy == Src->getType()) {
472       PRINT_PEEPHOLE1("cast-of-self-ty", CI);
473       CI->replaceAllUsesWith(Src);
474       if (!Src->hasName() && CI->hasName()) {
475         string Name = CI->getName();
476         CI->setName(""); Src->setName(Name, 
477                                       BB->getParent()->getSymbolTable());
478       }
479       return true;
480     }
481
482     // Check for a cast of cast, where no size information is lost...
483     if (SrcI)
484       if (CastInst *CSrc = dyn_cast<CastInst>(SrcI))
485         if (isReinterpretingCast(CI) + isReinterpretingCast(CSrc) < 2) {
486           // We can only do c-c elimination if, at most, one cast does a
487           // reinterpretation of the input data.
488           //
489           // If legal, make this cast refer the the original casts argument!
490           //
491           PRINT_PEEPHOLE2("cast-cast:in ", CI, CSrc);
492           CI->setOperand(0, CSrc->getOperand(0));
493           PRINT_PEEPHOLE1("cast-cast:out", CI);
494           return true;
495         }
496
497     // Check to see if it's a cast of an instruction that does not depend on the
498     // specific type of the operands to do it's job.
499     if (!isReinterpretingCast(CI) && 
500         ExpressionConvertableToType(Src, DestTy)) {
501       PRINT_PEEPHOLE2("EXPR-CONV:in ", CI, Src);
502       CI->setOperand(0, ConvertExpressionToType(Src, DestTy));
503       BI = BB->begin();  // Rescan basic block.  BI might be invalidated.
504       PRINT_PEEPHOLE2("EXPR-CONV:out", CI, CI->getOperand(0));
505       return true;
506     }
507
508   } else if (MallocInst *MI = dyn_cast<MallocInst>(I)) {
509     if (PeepholeMallocInst(BB, BI)) return true;
510
511   } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
512     Value *Val     = SI->getOperand(0);
513     Value *Pointer = SI->getPtrOperand();
514     
515     // Peephole optimize the following instructions:
516     // %t1 = getelementptr {<...>} * %StructPtr, <element indices>
517     // store <elementty> %v, <elementty> * %t1
518     //
519     // Into: store <elementty> %v, {<...>} * %StructPtr, <element indices>
520     //
521     if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Pointer)) {
522       PRINT_PEEPHOLE2("gep-store:in", GEP, SI);
523       ReplaceInstWithInst(BB->getInstList(), BI,
524                           SI = new StoreInst(Val, GEP->getPtrOperand(),
525                                              GEP->getIndexVec()));
526       PRINT_PEEPHOLE1("gep-store:out", SI);
527       return true;
528     }
529     
530     // Peephole optimize the following instructions:
531     // %t = cast <T1>* %P to <T2> * ;; If T1 is losslessly convertable to T2
532     // store <T2> %V, <T2>* %t
533     //
534     // Into: 
535     // %t = cast <T2> %V to <T1>
536     // store <T1> %t2, <T1>* %P
537     //
538     if (CastInst *CI = dyn_cast<CastInst>(Pointer))
539       if (Value *CastSrc = CI->getOperand(0)) // CSPT = CastSrcPointerType
540         if (PointerType *CSPT = dyn_cast<PointerType>(CastSrc->getType()))
541           if (losslessCastableTypes(Val->getType(), // convertable types!
542                                     CSPT->getValueType()) &&
543               !SI->hasIndices()) {      // No subscripts yet!
544             PRINT_PEEPHOLE3("st-src-cast:in ", Pointer, Val, SI);
545
546             // Insert the new T cast instruction... stealing old T's name
547             CastInst *NCI = new CastInst(Val, CSPT->getValueType(),
548                                          CI->getName());
549             CI->setName("");
550             BI = BB->getInstList().insert(BI, NCI)+1;
551
552             // Replace the old store with a new one!
553             ReplaceInstWithInst(BB->getInstList(), BI,
554                                 SI = new StoreInst(NCI, CastSrc));
555             PRINT_PEEPHOLE3("st-src-cast:out", NCI, CastSrc, SI);
556             return true;
557           }
558
559
560   } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
561     Value *Pointer = LI->getPtrOperand();
562     
563     // Peephole optimize the following instructions:
564     // %t1 = getelementptr {<...>} * %StructPtr, <element indices>
565     // %V  = load <elementty> * %t1
566     //
567     // Into: load {<...>} * %StructPtr, <element indices>
568     //
569     if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Pointer)) {
570       PRINT_PEEPHOLE2("gep-load:in", GEP, LI);
571       ReplaceInstWithInst(BB->getInstList(), BI,
572                           LI = new LoadInst(GEP->getPtrOperand(),
573                                             GEP->getIndexVec()));
574       PRINT_PEEPHOLE1("gep-load:out", LI);
575       return true;
576     }
577   } else if (I->getOpcode() == Instruction::Add &&
578              isa<CastInst>(I->getOperand(1))) {
579
580     // Peephole optimize the following instructions:
581     // %t1 = cast ulong <const int> to {<...>} *
582     // %t2 = add {<...>} * %SP, %t1              ;; Constant must be 2nd operand
583     //
584     //    or
585     // %t1 = cast {<...>}* %SP to int*
586     // %t5 = cast ulong <const int> to int*
587     // %t2 = add int* %t1, %t5                   ;; int is same size as field
588     //
589     // Into: %t3 = getelementptr {<...>} * %SP, <element indices>
590     //       %t2 = cast <eltype> * %t3 to {<...>}*
591     //
592     Value            *AddOp1  = I->getOperand(0);
593     CastInst         *AddOp2  = cast<CastInst>(I->getOperand(1));
594     ConstPoolUInt    *OffsetV = dyn_cast<ConstPoolUInt>(AddOp2->getOperand(0));
595     unsigned          Offset  = OffsetV ? OffsetV->getValue() : 0;
596     Value            *SrcPtr;  // Of type pointer to struct...
597     const StructType *StructTy;
598
599     if ((StructTy = getPointedToStruct(AddOp1->getType()))) {
600       SrcPtr = AddOp1;                      // Handle the first case...
601     } else if (CastInst *AddOp1c = dyn_cast<CastInst>(AddOp1)) {
602       SrcPtr = AddOp1c->getOperand(0);      // Handle the second case...
603       StructTy = getPointedToStruct(SrcPtr->getType());
604     }
605     
606     // Only proceed if we have detected all of our conditions successfully...
607     if (Offset && StructTy && SrcPtr && Offset < TD.getTypeSize(StructTy)) {
608       const StructLayout *SL = TD.getStructLayout(StructTy);
609       vector<ConstPoolVal*> Offsets;
610       unsigned ActualOffset = Offset;
611       const Type *ElTy = getStructOffsetType(StructTy, ActualOffset, Offsets);
612
613       if (getPointedToStruct(AddOp1->getType())) {  // case 1
614         PRINT_PEEPHOLE2("add-to-gep1:in", AddOp2, I);
615       } else {
616         PRINT_PEEPHOLE3("add-to-gep2:in", AddOp1, AddOp2, I);
617       }
618
619       GetElementPtrInst *GEP = new GetElementPtrInst(SrcPtr, Offsets);
620       BI = BB->getInstList().insert(BI, GEP)+1;
621
622       assert(Offset-ActualOffset == 0  &&
623              "GEP to middle of element not implemented yet!");
624
625       ReplaceInstWithInst(BB->getInstList(), BI, 
626                           I = new CastInst(GEP, I->getType()));
627       PRINT_PEEPHOLE2("add-to-gep:out", GEP, I);
628       return true;
629     }
630   }
631
632   return false;
633 }
634
635
636
637
638 static bool DoRaisePass(Method *M) {
639   bool Changed = false;
640   for (Method::iterator MI = M->begin(), ME = M->end(); MI != ME; ++MI) {
641     BasicBlock *BB = *MI;
642     BasicBlock::InstListType &BIL = BB->getInstList();
643
644     for (BasicBlock::iterator BI = BB->begin(); BI != BB->end();) {
645       if (PeepholeOptimize(BB, BI))
646         Changed = true;
647       else
648         ++BI;
649     }
650   }
651   return Changed;
652 }
653
654
655 // RaisePointerReferences::doit - Raise a method representation to a higher
656 // level.
657 //
658 bool RaisePointerReferences::doit(Method *M) {
659   if (M->isExternal()) return false;
660   bool Changed = false;
661
662   while (DoRaisePass(M)) Changed = true;
663
664   // PtrCasts - Keep a mapping between the pointer values (the key of the 
665   // map), and the cast to array pointer (the value) in this map.  This is
666   // used when converting pointer math into array addressing.
667   // 
668   map<Value*, CastInst*> PtrCasts;
669
670   // Insert casts for all incoming pointer values.  Keep track of those casts
671   // and the identified incoming values in the PtrCasts map.
672   //
673   Changed |= DoInsertArrayCasts(M, PtrCasts);
674
675   // Loop over each incoming pointer variable, replacing indexing arithmetic
676   // with getelementptr calls.
677   //
678   Changed |= reduce_apply_bool(PtrCasts.begin(), PtrCasts.end(), 
679                                ptr_fun(DoEliminatePointerArithmetic));
680
681   return Changed;
682 }