Implement conversion of method pointer parameter in Call instruction
[oota-llvm.git] / lib / Transforms / ExprTypeConvert.cpp
1 //===- ExprTypeConvert.cpp - Code to change an LLVM Expr Type ---------------=//
2 //
3 // This file implements the part of level raising that checks to see if it is
4 // possible to coerce an entire expression tree into a different type.  If
5 // convertable, other routines from this file will do the conversion.
6 //
7 //===----------------------------------------------------------------------===//
8
9 #include "TransformInternals.h"
10 #include "llvm/Method.h"
11 #include "llvm/iOther.h"
12 #include "llvm/iPHINode.h"
13 #include "llvm/iMemory.h"
14 #include "llvm/ConstantVals.h"
15 #include "llvm/Transforms/Scalar/ConstantHandling.h"
16 #include "llvm/Transforms/Scalar/DCE.h"
17 #include "llvm/Analysis/Expressions.h"
18 #include "Support/STLExtras.h"
19 #include <map>
20 #include <algorithm>
21 #include <iostream>
22 using std::cerr;
23
24 #include "llvm/Assembly/Writer.h"
25
26 //#define DEBUG_EXPR_CONVERT 1
27
28 static bool OperandConvertableToType(User *U, Value *V, const Type *Ty,
29                                      ValueTypeCache &ConvertedTypes);
30
31 static void ConvertOperandToType(User *U, Value *OldVal, Value *NewVal,
32                                  ValueMapCache &VMC);
33
34 // AllIndicesZero - Return true if all of the indices of the specified memory
35 // access instruction are zero, indicating an effectively nil offset to the 
36 // pointer value.
37 //
38 static bool AllIndicesZero(const MemAccessInst *MAI) {
39   for (User::const_op_iterator S = MAI->idx_begin(), E = MAI->idx_end();
40        S != E; ++S)
41     if (!isa<Constant>(*S) || !cast<Constant>(*S)->isNullValue())
42       return false;
43   return true;
44 }
45
46
47 // Peephole Malloc instructions: we take a look at the use chain of the
48 // malloc instruction, and try to find out if the following conditions hold:
49 //   1. The malloc is of the form: 'malloc [sbyte], uint <constant>'
50 //   2. The only users of the malloc are cast & add instructions
51 //   3. Of the cast instructions, there is only one destination pointer type
52 //      [RTy] where the size of the pointed to object is equal to the number
53 //      of bytes allocated.
54 //
55 // If these conditions hold, we convert the malloc to allocate an [RTy]
56 // element.  TODO: This comment is out of date WRT arrays
57 //
58 static bool MallocConvertableToType(MallocInst *MI, const Type *Ty,
59                                     ValueTypeCache &CTMap) {
60   if (!MI->isArrayAllocation() ||            // No array allocation?
61       !isa<PointerType>(Ty)) return false;   // Malloc always returns pointers
62
63   // Deal with the type to allocate, not the pointer type...
64   Ty = cast<PointerType>(Ty)->getElementType();
65   if (!Ty->isSized()) return false;      // Can only alloc something with a size
66
67   // Analyze the number of bytes allocated...
68   analysis::ExprType Expr = analysis::ClassifyExpression(MI->getArraySize());
69
70   // Get information about the base datatype being allocated, before & after
71   unsigned ReqTypeSize = TD.getTypeSize(Ty);
72   unsigned OldTypeSize = TD.getTypeSize(MI->getType()->getElementType());
73
74   // Must have a scale or offset to analyze it...
75   if (!Expr.Offset && !Expr.Scale) return false;
76
77   // Get the offset and scale of the allocation...
78   int OffsetVal = Expr.Offset ? getConstantValue(Expr.Offset) : 0;
79   int ScaleVal = Expr.Scale ? getConstantValue(Expr.Scale) : (Expr.Var ? 1 : 0);
80   if (ScaleVal < 0 || OffsetVal < 0) {
81     cerr << "malloc of a negative number???\n";
82     return false;
83   }
84
85   // The old type might not be of unit size, take old size into consideration
86   // here...
87   unsigned Offset = (unsigned)OffsetVal * OldTypeSize;
88   unsigned Scale  = (unsigned)ScaleVal  * OldTypeSize;
89   
90   // In order to be successful, both the scale and the offset must be a multiple
91   // of the requested data type's size.
92   //
93   if (Offset/ReqTypeSize*ReqTypeSize != Offset ||
94       Scale/ReqTypeSize*ReqTypeSize != Scale)
95     return false;   // Nope.
96
97   return true;
98 }
99
100 static Instruction *ConvertMallocToType(MallocInst *MI, const Type *Ty,
101                                         const std::string &Name,
102                                         ValueMapCache &VMC){
103   BasicBlock *BB = MI->getParent();
104   BasicBlock::iterator It = BB->end();
105
106   // Analyze the number of bytes allocated...
107   analysis::ExprType Expr = analysis::ClassifyExpression(MI->getArraySize());
108
109   const PointerType *AllocTy = cast<PointerType>(Ty);
110   const Type *ElType = AllocTy->getElementType();
111
112   unsigned DataSize = TD.getTypeSize(ElType);
113   unsigned OldTypeSize = TD.getTypeSize(MI->getType()->getElementType());
114
115   // Get the offset and scale coefficients that we are allocating...
116   int OffsetVal = (Expr.Offset ? getConstantValue(Expr.Offset) : 0);
117   int ScaleVal = Expr.Scale ? getConstantValue(Expr.Scale) : (Expr.Var ? 1 : 0);
118
119   // The old type might not be of unit size, take old size into consideration
120   // here...
121   unsigned Offset = (unsigned)OffsetVal * OldTypeSize / DataSize;
122   unsigned Scale  = (unsigned)ScaleVal  * OldTypeSize / DataSize;
123
124   // Locate the malloc instruction, because we may be inserting instructions
125   It = find(BB->getInstList().begin(), BB->getInstList().end(), MI);
126
127   // If we have a scale, apply it first...
128   if (Expr.Var) {
129     // Expr.Var is not neccesarily unsigned right now, insert a cast now.
130     if (Expr.Var->getType() != Type::UIntTy) {
131       Instruction *CI = new CastInst(Expr.Var, Type::UIntTy);
132       if (Expr.Var->hasName()) CI->setName(Expr.Var->getName()+"-uint");
133       It = BB->getInstList().insert(It, CI)+1;
134       Expr.Var = CI;
135     }
136
137     if (Scale != 1) {
138       Instruction *ScI =
139         BinaryOperator::create(Instruction::Mul, Expr.Var,
140                                ConstantUInt::get(Type::UIntTy, Scale));
141       if (Expr.Var->hasName()) ScI->setName(Expr.Var->getName()+"-scl");
142       It = BB->getInstList().insert(It, ScI)+1;
143       Expr.Var = ScI;
144     }
145
146   } else {
147     // If we are not scaling anything, just make the offset be the "var"...
148     Expr.Var = ConstantUInt::get(Type::UIntTy, Offset);
149     Offset = 0; Scale = 1;
150   }
151
152   // If we have an offset now, add it in...
153   if (Offset != 0) {
154     assert(Expr.Var && "Var must be nonnull by now!");
155
156     Instruction *AddI =
157       BinaryOperator::create(Instruction::Add, Expr.Var,
158                              ConstantUInt::get(Type::UIntTy, Offset));
159     if (Expr.Var->hasName()) AddI->setName(Expr.Var->getName()+"-off");
160     It = BB->getInstList().insert(It, AddI)+1;
161     Expr.Var = AddI;
162   }
163
164   Instruction *NewI = new MallocInst(AllocTy, Expr.Var, Name);
165
166   assert(AllocTy == Ty);
167   return NewI;
168 }
169
170
171 // ExpressionConvertableToType - Return true if it is possible
172 bool ExpressionConvertableToType(Value *V, const Type *Ty,
173                                  ValueTypeCache &CTMap) {
174   if (V->getType() == Ty) return true;  // Expression already correct type!
175
176   // Expression type must be holdable in a register.
177   if (!Ty->isFirstClassType())
178     return false;
179   
180   ValueTypeCache::iterator CTMI = CTMap.find(V);
181   if (CTMI != CTMap.end()) return CTMI->second == Ty;
182
183   CTMap[V] = Ty;
184
185   Instruction *I = dyn_cast<Instruction>(V);
186   if (I == 0) {
187     // It's not an instruction, check to see if it's a constant... all constants
188     // can be converted to an equivalent value (except pointers, they can't be
189     // const prop'd in general).  We just ask the constant propogator to see if
190     // it can convert the value...
191     //
192     if (Constant *CPV = dyn_cast<Constant>(V))
193       if (ConstantFoldCastInstruction(CPV, Ty))
194         return true;  // Don't worry about deallocating, it's a constant.
195
196     return false;              // Otherwise, we can't convert!
197   }
198
199   switch (I->getOpcode()) {
200   case Instruction::Cast:
201     // We can convert the expr if the cast destination type is losslessly
202     // convertable to the requested type.
203     if (!Ty->isLosslesslyConvertableTo(I->getType())) return false;
204 #if 1
205     // We also do not allow conversion of a cast that casts from a ptr to array
206     // of X to a *X.  For example: cast [4 x %List *] * %val to %List * *
207     //
208     if (PointerType *SPT = dyn_cast<PointerType>(I->getOperand(0)->getType()))
209       if (PointerType *DPT = dyn_cast<PointerType>(I->getType()))
210         if (ArrayType *AT = dyn_cast<ArrayType>(SPT->getElementType()))
211           if (AT->getElementType() == DPT->getElementType())
212             return false;
213 #endif
214     break;
215
216   case Instruction::Add:
217   case Instruction::Sub:
218     if (!ExpressionConvertableToType(I->getOperand(0), Ty, CTMap) ||
219         !ExpressionConvertableToType(I->getOperand(1), Ty, CTMap))
220       return false;
221     break;
222   case Instruction::Shr:
223     if (Ty->isSigned() != V->getType()->isSigned()) return false;
224     // FALL THROUGH
225   case Instruction::Shl:
226     if (!ExpressionConvertableToType(I->getOperand(0), Ty, CTMap))
227       return false;
228     break;
229
230   case Instruction::Load: {
231     LoadInst *LI = cast<LoadInst>(I);
232     if (LI->hasIndices() && !AllIndicesZero(LI)) {
233       // We can't convert a load expression if it has indices... unless they are
234       // all zero.
235       return false;
236     }
237
238     if (!ExpressionConvertableToType(LI->getPointerOperand(),
239                                      PointerType::get(Ty), CTMap))
240       return false;
241     break;                                     
242   }
243   case Instruction::PHINode: {
244     PHINode *PN = cast<PHINode>(I);
245     for (unsigned i = 0; i < PN->getNumIncomingValues(); ++i)
246       if (!ExpressionConvertableToType(PN->getIncomingValue(i), Ty, CTMap))
247         return false;
248     break;
249   }
250
251   case Instruction::Malloc:
252     if (!MallocConvertableToType(cast<MallocInst>(I), Ty, CTMap))
253       return false;
254     break;
255
256 #if 1
257   case Instruction::GetElementPtr: {
258     // GetElementPtr's are directly convertable to a pointer type if they have
259     // a number of zeros at the end.  Because removing these values does not
260     // change the logical offset of the GEP, it is okay and fair to remove them.
261     // This can change this:
262     //   %t1 = getelementptr %Hosp * %hosp, ubyte 4, ubyte 0  ; <%List **>
263     //   %t2 = cast %List * * %t1 to %List *
264     // into
265     //   %t2 = getelementptr %Hosp * %hosp, ubyte 4           ; <%List *>
266     // 
267     GetElementPtrInst *GEP = cast<GetElementPtrInst>(I);
268     const PointerType *PTy = dyn_cast<PointerType>(Ty);
269     if (!PTy) return false;  // GEP must always return a pointer...
270     const Type *PVTy = PTy->getElementType();
271
272     // Check to see if there are zero elements that we can remove from the
273     // index array.  If there are, check to see if removing them causes us to
274     // get to the right type...
275     //
276     std::vector<Value*> Indices = GEP->copyIndices();
277     const Type *BaseType = GEP->getPointerOperand()->getType();
278     const Type *ElTy = 0;
279
280     while (!Indices.empty() && isa<ConstantUInt>(Indices.back()) &&
281            cast<ConstantUInt>(Indices.back())->getValue() == 0) {
282       Indices.pop_back();
283       ElTy = GetElementPtrInst::getIndexedType(BaseType, Indices, true);
284       if (ElTy == PVTy)
285         break;  // Found a match!!
286       ElTy = 0;
287     }
288
289     if (ElTy) break;   // Found a number of zeros we can strip off!
290
291     // Otherwise, we can convert a GEP from one form to the other iff the
292     // current gep is of the form 'getelementptr sbyte*, unsigned N
293     // and we could convert this to an appropriate GEP for the new type.
294     //
295     if (GEP->getNumOperands() == 2 &&
296         GEP->getOperand(1)->getType() == Type::UIntTy &&
297         GEP->getType() == PointerType::get(Type::SByteTy)) {
298
299       // Do not Check to see if our incoming pointer can be converted
300       // to be a ptr to an array of the right type... because in more cases than
301       // not, it is simply not analyzable because of pointer/array
302       // discrepencies.  To fix this, we will insert a cast before the GEP.
303       //
304
305       // Check to see if 'N' is an expression that can be converted to
306       // the appropriate size... if so, allow it.
307       //
308       std::vector<Value*> Indices;
309       const Type *ElTy = ConvertableToGEP(PTy, I->getOperand(1), Indices);
310       if (ElTy) {
311         assert(ElTy == PVTy && "Internal error, setup wrong!");
312         if (!ExpressionConvertableToType(I->getOperand(0),
313                                          PointerType::get(ElTy), CTMap))
314           return false;  // Can't continue, ExConToTy might have polluted set!
315         break;
316       }
317     }
318
319     // Otherwise, it could be that we have something like this:
320     //     getelementptr [[sbyte] *] * %reg115, uint %reg138    ; [sbyte]**
321     // and want to convert it into something like this:
322     //     getelemenptr [[int] *] * %reg115, uint %reg138      ; [int]**
323     //
324     if (GEP->getNumOperands() == 2 && 
325         GEP->getOperand(1)->getType() == Type::UIntTy &&
326         TD.getTypeSize(PTy->getElementType()) == 
327         TD.getTypeSize(GEP->getType()->getElementType())) {
328       const PointerType *NewSrcTy = PointerType::get(PVTy);
329       if (!ExpressionConvertableToType(I->getOperand(0), NewSrcTy, CTMap))
330         return false;
331       break;
332     }
333
334     return false;   // No match, maybe next time.
335   }
336 #endif
337
338   default:
339     return false;
340   }
341
342   // Expressions are only convertable if all of the users of the expression can
343   // have this value converted.  This makes use of the map to avoid infinite
344   // recursion.
345   //
346   for (Value::use_iterator It = I->use_begin(), E = I->use_end(); It != E; ++It)
347     if (!OperandConvertableToType(*It, I, Ty, CTMap))
348       return false;
349
350   return true;
351 }
352
353
354 Value *ConvertExpressionToType(Value *V, const Type *Ty, ValueMapCache &VMC) {
355   if (V->getType() == Ty) return V;  // Already where we need to be?
356
357   ValueMapCache::ExprMapTy::iterator VMCI = VMC.ExprMap.find(V);
358   if (VMCI != VMC.ExprMap.end()) {
359     assert(VMCI->second->getType() == Ty);
360
361     if (Instruction *I = dyn_cast<Instruction>(V))
362       ValueHandle IHandle(VMC, I);  // Remove I if it is unused now!
363
364     return VMCI->second;
365   }
366
367 #ifdef DEBUG_EXPR_CONVERT
368   cerr << "CETT: " << (void*)V << " " << V;
369 #endif
370
371   Instruction *I = dyn_cast<Instruction>(V);
372   if (I == 0)
373     if (Constant *CPV = cast<Constant>(V)) {
374       // Constants are converted by constant folding the cast that is required.
375       // We assume here that all casts are implemented for constant prop.
376       Value *Result = ConstantFoldCastInstruction(CPV, Ty);
377       assert(Result && "ConstantFoldCastInstruction Failed!!!");
378       assert(Result->getType() == Ty && "Const prop of cast failed!");
379
380       // Add the instruction to the expression map
381       VMC.ExprMap[V] = Result;
382       return Result;
383     }
384
385
386   BasicBlock *BB = I->getParent();
387   BasicBlock::InstListType &BIL = BB->getInstList();
388   std::string Name = I->getName();  if (!Name.empty()) I->setName("");
389   Instruction *Res;     // Result of conversion
390
391   ValueHandle IHandle(VMC, I);  // Prevent I from being removed!
392   
393   Constant *Dummy = Constant::getNullConstant(Ty);
394
395   switch (I->getOpcode()) {
396   case Instruction::Cast:
397     Res = new CastInst(I->getOperand(0), Ty, Name);
398     break;
399     
400   case Instruction::Add:
401   case Instruction::Sub:
402     Res = BinaryOperator::create(cast<BinaryOperator>(I)->getOpcode(),
403                                  Dummy, Dummy, Name);
404     VMC.ExprMap[I] = Res;   // Add node to expression eagerly
405
406     Res->setOperand(0, ConvertExpressionToType(I->getOperand(0), Ty, VMC));
407     Res->setOperand(1, ConvertExpressionToType(I->getOperand(1), Ty, VMC));
408     break;
409
410   case Instruction::Shl:
411   case Instruction::Shr:
412     Res = new ShiftInst(cast<ShiftInst>(I)->getOpcode(), Dummy,
413                         I->getOperand(1), Name);
414     VMC.ExprMap[I] = Res;
415     Res->setOperand(0, ConvertExpressionToType(I->getOperand(0), Ty, VMC));
416     break;
417
418   case Instruction::Load: {
419     LoadInst *LI = cast<LoadInst>(I);
420     assert(!LI->hasIndices() || AllIndicesZero(LI));
421
422     Res = new LoadInst(Constant::getNullConstant(PointerType::get(Ty)), Name);
423     VMC.ExprMap[I] = Res;
424     Res->setOperand(0, ConvertExpressionToType(LI->getPointerOperand(),
425                                                PointerType::get(Ty), VMC));
426     assert(Res->getOperand(0)->getType() == PointerType::get(Ty));
427     assert(Ty == Res->getType());
428     assert(Res->getType()->isFirstClassType() && "Load of structure or array!");
429     break;
430   }
431
432   case Instruction::PHINode: {
433     PHINode *OldPN = cast<PHINode>(I);
434     PHINode *NewPN = new PHINode(Ty, Name);
435
436     VMC.ExprMap[I] = NewPN;   // Add node to expression eagerly
437     while (OldPN->getNumOperands()) {
438       BasicBlock *BB = OldPN->getIncomingBlock(0);
439       Value *OldVal = OldPN->getIncomingValue(0);
440       ValueHandle OldValHandle(VMC, OldVal);
441       OldPN->removeIncomingValue(BB);
442       Value *V = ConvertExpressionToType(OldVal, Ty, VMC);
443       NewPN->addIncoming(V, BB);
444     }
445     Res = NewPN;
446     break;
447   }
448
449   case Instruction::Malloc: {
450     Res = ConvertMallocToType(cast<MallocInst>(I), Ty, Name, VMC);
451     break;
452   }
453
454   case Instruction::GetElementPtr: {
455     // GetElementPtr's are directly convertable to a pointer type if they have
456     // a number of zeros at the end.  Because removing these values does not
457     // change the logical offset of the GEP, it is okay and fair to remove them.
458     // This can change this:
459     //   %t1 = getelementptr %Hosp * %hosp, ubyte 4, ubyte 0  ; <%List **>
460     //   %t2 = cast %List * * %t1 to %List *
461     // into
462     //   %t2 = getelementptr %Hosp * %hosp, ubyte 4           ; <%List *>
463     // 
464     GetElementPtrInst *GEP = cast<GetElementPtrInst>(I);
465
466     // Check to see if there are zero elements that we can remove from the
467     // index array.  If there are, check to see if removing them causes us to
468     // get to the right type...
469     //
470     std::vector<Value*> Indices = GEP->copyIndices();
471     const Type *BaseType = GEP->getPointerOperand()->getType();
472     const Type *PVTy = cast<PointerType>(Ty)->getElementType();
473     Res = 0;
474     while (!Indices.empty() && isa<ConstantUInt>(Indices.back()) &&
475            cast<ConstantUInt>(Indices.back())->getValue() == 0) {
476       Indices.pop_back();
477       if (GetElementPtrInst::getIndexedType(BaseType, Indices, true) == PVTy) {
478         if (Indices.size() == 0) {
479           Res = new CastInst(GEP->getPointerOperand(), BaseType); // NOOP
480         } else {
481           Res = new GetElementPtrInst(GEP->getPointerOperand(), Indices, Name);
482         }
483         break;
484       }
485     }
486
487     if (Res == 0 && GEP->getNumOperands() == 2 &&
488         GEP->getOperand(1)->getType() == Type::UIntTy &&
489         GEP->getType() == PointerType::get(Type::SByteTy)) {
490       
491       // Otherwise, we can convert a GEP from one form to the other iff the
492       // current gep is of the form 'getelementptr [sbyte]*, unsigned N
493       // and we could convert this to an appropriate GEP for the new type.
494       //
495       const PointerType *NewSrcTy = PointerType::get(PVTy);
496       BasicBlock::iterator It = find(BIL.begin(), BIL.end(), I);
497
498       // Check to see if 'N' is an expression that can be converted to
499       // the appropriate size... if so, allow it.
500       //
501       std::vector<Value*> Indices;
502       const Type *ElTy = ConvertableToGEP(NewSrcTy, I->getOperand(1),
503                                           Indices, &It);
504       if (ElTy) {        
505         assert(ElTy == PVTy && "Internal error, setup wrong!");
506         Res = new GetElementPtrInst(Constant::getNullConstant(NewSrcTy),
507                                     Indices, Name);
508         VMC.ExprMap[I] = Res;
509         Res->setOperand(0, ConvertExpressionToType(I->getOperand(0),
510                                                    NewSrcTy, VMC));
511       }
512     }
513
514     // Otherwise, it could be that we have something like this:
515     //     getelementptr [[sbyte] *] * %reg115, uint %reg138    ; [sbyte]**
516     // and want to convert it into something like this:
517     //     getelemenptr [[int] *] * %reg115, uint %reg138      ; [int]**
518     //
519     if (Res == 0) {
520       const PointerType *NewSrcTy = PointerType::get(PVTy);
521       Res = new GetElementPtrInst(Constant::getNullConstant(NewSrcTy),
522                                   GEP->copyIndices(), Name);
523       VMC.ExprMap[I] = Res;
524       Res->setOperand(0, ConvertExpressionToType(I->getOperand(0),
525                                                  NewSrcTy, VMC));
526     }
527
528
529     assert(Res && "Didn't find match!");
530     break;   // No match, maybe next time.
531   }
532
533   default:
534     assert(0 && "Expression convertable, but don't know how to convert?");
535     return 0;
536   }
537
538   assert(Res->getType() == Ty && "Didn't convert expr to correct type!");
539
540   BasicBlock::iterator It = find(BIL.begin(), BIL.end(), I);
541   assert(It != BIL.end() && "Instruction not in own basic block??");
542   BIL.insert(It, Res);
543
544   // Add the instruction to the expression map
545   VMC.ExprMap[I] = Res;
546
547   // Expressions are only convertable if all of the users of the expression can
548   // have this value converted.  This makes use of the map to avoid infinite
549   // recursion.
550   //
551   unsigned NumUses = I->use_size();
552   for (unsigned It = 0; It < NumUses; ) {
553     unsigned OldSize = NumUses;
554     ConvertOperandToType(*(I->use_begin()+It), I, Res, VMC);
555     NumUses = I->use_size();
556     if (NumUses == OldSize) ++It;
557   }
558
559 #ifdef DEBUG_EXPR_CONVERT
560   cerr << "ExpIn: " << (void*)I << " " << I
561        << "ExpOut: " << (void*)Res << " " << Res;
562 #endif
563
564   if (I->use_empty()) {
565 #ifdef DEBUG_EXPR_CONVERT
566     cerr << "EXPR DELETING: " << (void*)I << " " << I;
567 #endif
568     BIL.remove(I);
569     VMC.OperandsMapped.erase(I);
570     VMC.ExprMap.erase(I);
571     delete I;
572   }
573
574   return Res;
575 }
576
577
578
579 // ValueConvertableToType - Return true if it is possible
580 bool ValueConvertableToType(Value *V, const Type *Ty,
581                              ValueTypeCache &ConvertedTypes) {
582   ValueTypeCache::iterator I = ConvertedTypes.find(V);
583   if (I != ConvertedTypes.end()) return I->second == Ty;
584   ConvertedTypes[V] = Ty;
585
586   // It is safe to convert the specified value to the specified type IFF all of
587   // the uses of the value can be converted to accept the new typed value.
588   //
589   if (V->getType() != Ty) {
590     for (Value::use_iterator I = V->use_begin(), E = V->use_end(); I != E; ++I)
591       if (!OperandConvertableToType(*I, V, Ty, ConvertedTypes))
592         return false;
593   }
594
595   return true;
596 }
597
598
599
600
601
602 // OperandConvertableToType - Return true if it is possible to convert operand
603 // V of User (instruction) U to the specified type.  This is true iff it is
604 // possible to change the specified instruction to accept this.  CTMap is a map
605 // of converted types, so that circular definitions will see the future type of
606 // the expression, not the static current type.
607 //
608 static bool OperandConvertableToType(User *U, Value *V, const Type *Ty,
609                                      ValueTypeCache &CTMap) {
610   //  if (V->getType() == Ty) return true;   // Operand already the right type?
611
612   // Expression type must be holdable in a register.
613   if (!Ty->isFirstClassType())
614     return false;
615
616   Instruction *I = dyn_cast<Instruction>(U);
617   if (I == 0) return false;              // We can't convert!
618
619   switch (I->getOpcode()) {
620   case Instruction::Cast:
621     assert(I->getOperand(0) == V);
622     // We can convert the expr if the cast destination type is losslessly
623     // convertable to the requested type.
624     // Also, do not change a cast that is a noop cast.  For all intents and
625     // purposes it should be eliminated.
626     if (!Ty->isLosslesslyConvertableTo(I->getOperand(0)->getType()) ||
627         I->getType() == I->getOperand(0)->getType())
628       return false;
629
630
631 #if 1
632     // We also do not allow conversion of a cast that casts from a ptr to array
633     // of X to a *X.  For example: cast [4 x %List *] * %val to %List * *
634     //
635     if (PointerType *SPT = dyn_cast<PointerType>(I->getOperand(0)->getType()))
636       if (PointerType *DPT = dyn_cast<PointerType>(I->getType()))
637         if (ArrayType *AT = dyn_cast<ArrayType>(SPT->getElementType()))
638           if (AT->getElementType() == DPT->getElementType())
639             return false;
640 #endif
641     return true;
642
643   case Instruction::Add:
644     if (isa<PointerType>(Ty)) {
645       Value *IndexVal = I->getOperand(V == I->getOperand(0) ? 1 : 0);
646       std::vector<Value*> Indices;
647       if (const Type *ETy = ConvertableToGEP(Ty, IndexVal, Indices)) {
648         const Type *RetTy = PointerType::get(ETy);
649
650         // Only successful if we can convert this type to the required type
651         if (ValueConvertableToType(I, RetTy, CTMap)) {
652           CTMap[I] = RetTy;
653           return true;
654         }
655         // We have to return failure here because ValueConvertableToType could 
656         // have polluted our map
657         return false;
658       }
659     }
660     // FALLTHROUGH
661   case Instruction::Sub: {
662     Value *OtherOp = I->getOperand((V == I->getOperand(0)) ? 1 : 0);
663     return ValueConvertableToType(I, Ty, CTMap) &&
664            ExpressionConvertableToType(OtherOp, Ty, CTMap);
665   }
666   case Instruction::SetEQ:
667   case Instruction::SetNE: {
668     Value *OtherOp = I->getOperand((V == I->getOperand(0)) ? 1 : 0);
669     return ExpressionConvertableToType(OtherOp, Ty, CTMap);
670   }
671   case Instruction::Shr:
672     if (Ty->isSigned() != V->getType()->isSigned()) return false;
673     // FALL THROUGH
674   case Instruction::Shl:
675     assert(I->getOperand(0) == V);
676     return ValueConvertableToType(I, Ty, CTMap);
677
678   case Instruction::Free:
679     assert(I->getOperand(0) == V);
680     return isa<PointerType>(Ty);    // Free can free any pointer type!
681
682   case Instruction::Load:
683     // Cannot convert the types of any subscripts...
684     if (I->getOperand(0) != V) return false;
685
686     if (const PointerType *PT = dyn_cast<PointerType>(Ty)) {
687       LoadInst *LI = cast<LoadInst>(I);
688       
689       if (LI->hasIndices() && !AllIndicesZero(LI))
690         return false;
691
692       const Type *LoadedTy = PT->getElementType();
693
694       // They could be loading the first element of a composite type...
695       if (const CompositeType *CT = dyn_cast<CompositeType>(LoadedTy)) {
696         unsigned Offset = 0;     // No offset, get first leaf.
697         std::vector<Value*> Indices;  // Discarded...
698         LoadedTy = getStructOffsetType(CT, Offset, Indices, false);
699         assert(Offset == 0 && "Offset changed from zero???");
700       }
701
702       if (!LoadedTy->isFirstClassType())
703         return false;
704
705       if (TD.getTypeSize(LoadedTy) != TD.getTypeSize(LI->getType()))
706         return false;
707
708       return ValueConvertableToType(LI, LoadedTy, CTMap);
709     }
710     return false;
711
712   case Instruction::Store: {
713     StoreInst *SI = cast<StoreInst>(I);
714     if (SI->hasIndices()) return false;
715
716     if (V == I->getOperand(0)) {
717       // Can convert the store if we can convert the pointer operand to match
718       // the new  value type...
719       return ExpressionConvertableToType(I->getOperand(1), PointerType::get(Ty),
720                                          CTMap);
721     } else if (const PointerType *PT = dyn_cast<PointerType>(Ty)) {
722       const Type *ElTy = PT->getElementType();
723       assert(V == I->getOperand(1));
724
725       // Must move the same amount of data...
726       if (TD.getTypeSize(ElTy) != TD.getTypeSize(I->getOperand(0)->getType()))
727         return false;
728
729       // Can convert store if the incoming value is convertable...
730       return ExpressionConvertableToType(I->getOperand(0), ElTy, CTMap);
731     }
732     return false;
733   }
734
735   case Instruction::GetElementPtr:
736     if (V != I->getOperand(0) || !isa<PointerType>(Ty)) return false;
737
738     // If we have a two operand form of getelementptr, this is really little
739     // more than a simple addition.  As with addition, check to see if the
740     // getelementptr instruction can be changed to index into the new type.
741     //
742     if (I->getNumOperands() == 2) {
743       const Type *OldElTy = cast<PointerType>(I->getType())->getElementType();
744       unsigned DataSize = TD.getTypeSize(OldElTy);
745       Value *Index = I->getOperand(1);
746       Instruction *TempScale = 0;
747
748       // If the old data element is not unit sized, we have to create a scale
749       // instruction so that ConvertableToGEP will know the REAL amount we are
750       // indexing by.  Note that this is never inserted into the instruction
751       // stream, so we have to delete it when we're done.
752       //
753       if (DataSize != 1) {
754         TempScale = BinaryOperator::create(Instruction::Mul, Index,
755                                            ConstantUInt::get(Type::UIntTy,
756                                                              DataSize));
757         Index = TempScale;
758       }
759
760       // Check to see if the second argument is an expression that can
761       // be converted to the appropriate size... if so, allow it.
762       //
763       std::vector<Value*> Indices;
764       const Type *ElTy = ConvertableToGEP(Ty, Index, Indices);
765       delete TempScale;   // Free our temporary multiply if we made it
766
767       if (ElTy == 0) return false;  // Cannot make conversion...
768       return ValueConvertableToType(I, PointerType::get(ElTy), CTMap);
769     }
770     return false;
771
772   case Instruction::PHINode: {
773     PHINode *PN = cast<PHINode>(I);
774     for (unsigned i = 0; i < PN->getNumIncomingValues(); ++i)
775       if (!ExpressionConvertableToType(PN->getIncomingValue(i), Ty, CTMap))
776         return false;
777     return ValueConvertableToType(PN, Ty, CTMap);
778   }
779
780   case Instruction::Call: {
781     User::op_iterator OI = find(I->op_begin(), I->op_end(), V);
782     assert (OI != I->op_end() && "Not using value!");
783     unsigned OpNum = OI - I->op_begin();
784
785     // Are we trying to change the method pointer value to a new type?
786     if (OpNum == 0) {
787       PointerType *PTy = dyn_cast<PointerType>(Ty);
788       if (PTy == 0) return false;  // Can't convert to a non-pointer type...
789       MethodType *MTy = dyn_cast_or_null<MethodType>(PTy->getElementType());
790       if (MTy == 0) return false;  // Can't convert to a non ptr to method...
791
792       // Perform sanity checks to make sure that new method type has the
793       // correct number of arguments...
794       //
795       unsigned NumArgs = I->getNumOperands()-1;  // Don't include method ptr
796
797       // Cannot convert to a type that requires more fixed arguments than
798       // the call provides...
799       //
800       if (NumArgs < MTy->getParamTypes().size()) return false;
801       
802       // Unless this is a vararg method type, we cannot provide more arguments
803       // than are desired...
804       //
805       if (!MTy->isVarArg() && NumArgs > MTy->getParamTypes().size())
806         return false;
807
808       // Okay, at this point, we know that the call and the method type match
809       // number of arguments.  Now we see if we can convert the arguments
810       // themselves.
811       //
812       const MethodType::ParamTypes &PTs = MTy->getParamTypes();
813       for (unsigned i = 0, NA = PTs.size(); i < NA; ++i)
814         if (!PTs[i]->isLosslesslyConvertableTo(I->getOperand(i+1)->getType()))
815           return false;   // Operands must have compatible types!
816
817       // Okay, at this point, we know that all of the arguments can be
818       // converted.  We succeed if we can change the return type if
819       // neccesary...
820       //
821       return ValueConvertableToType(I, MTy->getReturnType(), CTMap);
822     }
823     
824     const PointerType *MPtr = cast<PointerType>(I->getOperand(0)->getType());
825     const MethodType *MTy = cast<MethodType>(MPtr->getElementType());
826     if (!MTy->isVarArg()) return false;
827
828     if ((OpNum-1) < MTy->getParamTypes().size())
829       return false;  // It's not in the varargs section...
830
831     // If we get this far, we know the value is in the varargs section of the
832     // method!  We can convert if we don't reinterpret the value...
833     //
834     return Ty->isLosslesslyConvertableTo(V->getType());
835   }
836   }
837   return false;
838 }
839
840
841 void ConvertValueToNewType(Value *V, Value *NewVal, ValueMapCache &VMC) {
842   ValueHandle VH(VMC, V);
843
844   unsigned NumUses = V->use_size();
845   for (unsigned It = 0; It < NumUses; ) {
846     unsigned OldSize = NumUses;
847     ConvertOperandToType(*(V->use_begin()+It), V, NewVal, VMC);
848     NumUses = V->use_size();
849     if (NumUses == OldSize) ++It;
850   }
851 }
852
853
854
855 static void ConvertOperandToType(User *U, Value *OldVal, Value *NewVal,
856                                  ValueMapCache &VMC) {
857   if (isa<ValueHandle>(U)) return;  // Valuehandles don't let go of operands...
858
859   if (VMC.OperandsMapped.count(U)) return;
860   VMC.OperandsMapped.insert(U);
861
862   ValueMapCache::ExprMapTy::iterator VMCI = VMC.ExprMap.find(U);
863   if (VMCI != VMC.ExprMap.end())
864     return;
865
866
867   Instruction *I = cast<Instruction>(U);  // Only Instructions convertable
868
869   BasicBlock *BB = I->getParent();
870   BasicBlock::InstListType &BIL = BB->getInstList();
871   std::string Name = I->getName();  if (!Name.empty()) I->setName("");
872   Instruction *Res;     // Result of conversion
873
874   //cerr << endl << endl << "Type:\t" << Ty << "\nInst: " << I << "BB Before: " << BB << endl;
875
876   // Prevent I from being removed...
877   ValueHandle IHandle(VMC, I);
878
879   const Type *NewTy = NewVal->getType();
880   Constant *Dummy = (NewTy != Type::VoidTy) ? 
881                   Constant::getNullConstant(NewTy) : 0;
882
883   switch (I->getOpcode()) {
884   case Instruction::Cast:
885     assert(I->getOperand(0) == OldVal);
886     Res = new CastInst(NewVal, I->getType(), Name);
887     break;
888
889   case Instruction::Add:
890     if (isa<PointerType>(NewTy)) {
891       Value *IndexVal = I->getOperand(OldVal == I->getOperand(0) ? 1 : 0);
892       std::vector<Value*> Indices;
893       BasicBlock::iterator It = find(BIL.begin(), BIL.end(), I);
894
895       if (const Type *ETy = ConvertableToGEP(NewTy, IndexVal, Indices, &It)) {
896         // If successful, convert the add to a GEP
897         //const Type *RetTy = PointerType::get(ETy);
898         // First operand is actually the given pointer...
899         Res = new GetElementPtrInst(NewVal, Indices, Name);
900         assert(cast<PointerType>(Res->getType())->getElementType() == ETy &&
901                "ConvertableToGEP broken!");
902         break;
903       }
904     }
905     // FALLTHROUGH
906
907   case Instruction::Sub:
908   case Instruction::SetEQ:
909   case Instruction::SetNE: {
910     Res = BinaryOperator::create(cast<BinaryOperator>(I)->getOpcode(),
911                                  Dummy, Dummy, Name);
912     VMC.ExprMap[I] = Res;   // Add node to expression eagerly
913
914     unsigned OtherIdx = (OldVal == I->getOperand(0)) ? 1 : 0;
915     Value *OtherOp    = I->getOperand(OtherIdx);
916     Value *NewOther   = ConvertExpressionToType(OtherOp, NewTy, VMC);
917
918     Res->setOperand(OtherIdx, NewOther);
919     Res->setOperand(!OtherIdx, NewVal);
920     break;
921   }
922   case Instruction::Shl:
923   case Instruction::Shr:
924     assert(I->getOperand(0) == OldVal);
925     Res = new ShiftInst(cast<ShiftInst>(I)->getOpcode(), NewVal,
926                         I->getOperand(1), Name);
927     break;
928
929   case Instruction::Free:            // Free can free any pointer type!
930     assert(I->getOperand(0) == OldVal);
931     Res = new FreeInst(NewVal);
932     break;
933
934
935   case Instruction::Load: {
936     assert(I->getOperand(0) == OldVal && isa<PointerType>(NewVal->getType()));
937     const Type *LoadedTy =
938       cast<PointerType>(NewVal->getType())->getElementType();
939
940     std::vector<Value*> Indices;
941     Indices.push_back(ConstantUInt::get(Type::UIntTy, 0));
942
943     if (const CompositeType *CT = dyn_cast<CompositeType>(LoadedTy)) {
944       unsigned Offset = 0;   // No offset, get first leaf.
945       LoadedTy = getStructOffsetType(CT, Offset, Indices, false);
946     }
947     assert(LoadedTy->isFirstClassType());
948
949     Res = new LoadInst(NewVal, Indices, Name);
950     assert(Res->getType()->isFirstClassType() && "Load of structure or array!");
951     break;
952   }
953
954   case Instruction::Store: {
955     if (I->getOperand(0) == OldVal) {  // Replace the source value
956       const PointerType *NewPT = PointerType::get(NewTy);
957       Res = new StoreInst(NewVal, Constant::getNullConstant(NewPT));
958       VMC.ExprMap[I] = Res;
959       Res->setOperand(1, ConvertExpressionToType(I->getOperand(1), NewPT, VMC));
960     } else {                           // Replace the source pointer
961       const Type *ValTy = cast<PointerType>(NewTy)->getElementType();
962       std::vector<Value*> Indices;
963 #if 0
964       Indices.push_back(ConstantUInt::get(Type::UIntTy, 0));
965       while (ArrayType *AT = dyn_cast<ArrayType>(ValTy)) {
966         Indices.push_back(ConstantUInt::get(Type::UIntTy, 0));
967         ValTy = AT->getElementType();
968       }
969 #endif
970       Res = new StoreInst(Constant::getNullConstant(ValTy), NewVal, Indices);
971       VMC.ExprMap[I] = Res;
972       Res->setOperand(0, ConvertExpressionToType(I->getOperand(0), ValTy, VMC));
973     }
974     break;
975   }
976
977
978   case Instruction::GetElementPtr: {
979     // Convert a one index getelementptr into just about anything that is
980     // desired.
981     //
982     BasicBlock::iterator It = find(BIL.begin(), BIL.end(), I);
983     const Type *OldElTy = cast<PointerType>(I->getType())->getElementType();
984     unsigned DataSize = TD.getTypeSize(OldElTy);
985     Value *Index = I->getOperand(1);
986
987     if (DataSize != 1) {
988       // Insert a multiply of the old element type is not a unit size...
989       Index = BinaryOperator::create(Instruction::Mul, Index,
990                                      ConstantUInt::get(Type::UIntTy, DataSize));
991       It = BIL.insert(It, cast<Instruction>(Index))+1;
992     }
993
994     // Perform the conversion now...
995     //
996     std::vector<Value*> Indices;
997     const Type *ElTy = ConvertableToGEP(NewVal->getType(), Index, Indices, &It);
998     assert(ElTy != 0 && "GEP Conversion Failure!");
999     Res = new GetElementPtrInst(NewVal, Indices, Name);
1000     assert(Res->getType() == PointerType::get(ElTy) &&
1001            "ConvertableToGet failed!");
1002   }
1003 #if 0
1004     if (I->getType() == PointerType::get(Type::SByteTy)) {
1005       // Convert a getelementptr sbyte * %reg111, uint 16 freely back to
1006       // anything that is a pointer type...
1007       //
1008       BasicBlock::iterator It = find(BIL.begin(), BIL.end(), I);
1009     
1010       // Check to see if the second argument is an expression that can
1011       // be converted to the appropriate size... if so, allow it.
1012       //
1013       std::vector<Value*> Indices;
1014       const Type *ElTy = ConvertableToGEP(NewVal->getType(), I->getOperand(1),
1015                                           Indices, &It);
1016       assert(ElTy != 0 && "GEP Conversion Failure!");
1017       
1018       Res = new GetElementPtrInst(NewVal, Indices, Name);
1019     } else {
1020       // Convert a getelementptr ulong * %reg123, uint %N
1021       // to        getelementptr  long * %reg123, uint %N
1022       // ... where the type must simply stay the same size...
1023       //
1024       Res = new GetElementPtrInst(NewVal,
1025                                   cast<GetElementPtrInst>(I)->copyIndices(),
1026                                   Name);
1027     }
1028 #endif
1029     break;
1030
1031   case Instruction::PHINode: {
1032     PHINode *OldPN = cast<PHINode>(I);
1033     PHINode *NewPN = new PHINode(NewTy, Name);
1034     VMC.ExprMap[I] = NewPN;
1035
1036     while (OldPN->getNumOperands()) {
1037       BasicBlock *BB = OldPN->getIncomingBlock(0);
1038       Value *OldVal = OldPN->getIncomingValue(0);
1039       OldPN->removeIncomingValue(BB);
1040       Value *V = ConvertExpressionToType(OldVal, NewTy, VMC);
1041       NewPN->addIncoming(V, BB);
1042     }
1043     Res = NewPN;
1044     break;
1045   }
1046
1047   case Instruction::Call: {
1048     Value *Meth = I->getOperand(0);
1049     std::vector<Value*> Params(I->op_begin()+1, I->op_end());
1050
1051     if (Meth == OldVal) {   // Changing the method pointer?
1052       PointerType *NewPTy = cast<PointerType>(NewVal->getType());
1053       MethodType *NewTy = cast<MethodType>(NewPTy->getElementType());
1054       const MethodType::ParamTypes &PTs = NewTy->getParamTypes();
1055
1056       // Convert over all of the call operands to their new types... but only
1057       // convert over the part that is not in the vararg section of the call.
1058       //
1059       for (unsigned i = 0; i < PTs.size(); ++i)
1060         Params[i] = ConvertExpressionToType(Params[i], PTs[i], VMC);
1061       Meth = NewVal;  // Update call destination to new value
1062
1063     } else {                   // Changing an argument, must be in vararg area
1064       std::vector<Value*>::iterator OI =
1065         find(Params.begin(), Params.end(), OldVal);
1066       assert (OI != Params.end() && "Not using value!");
1067
1068       *OI = NewVal;
1069     }
1070
1071     Res = new CallInst(Meth, Params, Name);
1072     break;
1073   }
1074   default:
1075     assert(0 && "Expression convertable, but don't know how to convert?");
1076     return;
1077   }
1078
1079   // If the instruction was newly created, insert it into the instruction
1080   // stream.
1081   //
1082   BasicBlock::iterator It = find(BIL.begin(), BIL.end(), I);
1083   assert(It != BIL.end() && "Instruction not in own basic block??");
1084   BIL.insert(It, Res);   // Keep It pointing to old instruction
1085
1086 #ifdef DEBUG_EXPR_CONVERT
1087   cerr << "COT CREATED: "  << (void*)Res << " " << Res;
1088   cerr << "In: " << (void*)I << " " << I << "Out: " << (void*)Res << " " << Res;
1089 #endif
1090
1091   // Add the instruction to the expression map
1092   VMC.ExprMap[I] = Res;
1093
1094   if (I->getType() != Res->getType())
1095     ConvertValueToNewType(I, Res, VMC);
1096   else {
1097     for (unsigned It = 0; It < I->use_size(); ) {
1098       User *Use = *(I->use_begin()+It);
1099       if (isa<ValueHandle>(Use))            // Don't remove ValueHandles!
1100         ++It;
1101       else
1102         Use->replaceUsesOfWith(I, Res);
1103     }
1104
1105     if (I->use_empty()) {
1106       // Now we just need to remove the old instruction so we don't get infinite
1107       // loops.  Note that we cannot use DCE because DCE won't remove a store
1108       // instruction, for example.
1109       //
1110 #ifdef DEBUG_EXPR_CONVERT
1111       cerr << "DELETING: " << (void*)I << " " << I;
1112 #endif
1113       BIL.remove(I);
1114       VMC.OperandsMapped.erase(I);
1115       VMC.ExprMap.erase(I);
1116       delete I;
1117     } else {
1118       for (Value::use_iterator UI = I->use_begin(), UE = I->use_end();
1119            UI != UE; ++UI)
1120         assert(isa<ValueHandle>((Value*)*UI) &&"Uses of Instruction remain!!!");
1121     }
1122   }
1123 }
1124
1125
1126 ValueHandle::ValueHandle(ValueMapCache &VMC, Value *V)
1127   : Instruction(Type::VoidTy, UserOp1, ""), Cache(VMC) {
1128 #ifdef DEBUG_EXPR_CONVERT
1129   //cerr << "VH AQUIRING: " << (void*)V << " " << V;
1130 #endif
1131   Operands.push_back(Use(V, this));
1132 }
1133
1134 static void RecursiveDelete(ValueMapCache &Cache, Instruction *I) {
1135   if (!I || !I->use_empty()) return;
1136
1137   assert(I->getParent() && "Inst not in basic block!");
1138
1139 #ifdef DEBUG_EXPR_CONVERT
1140   //cerr << "VH DELETING: " << (void*)I << " " << I;
1141 #endif
1142
1143   for (User::op_iterator OI = I->op_begin(), OE = I->op_end(); 
1144        OI != OE; ++OI)
1145     if (Instruction *U = dyn_cast<Instruction>(*OI)) {
1146       *OI = 0;
1147       RecursiveDelete(Cache, U);
1148     }
1149
1150   I->getParent()->getInstList().remove(I);
1151
1152   Cache.OperandsMapped.erase(I);
1153   Cache.ExprMap.erase(I);
1154   delete I;
1155 }
1156
1157 ValueHandle::~ValueHandle() {
1158   if (Operands[0]->use_size() == 1) {
1159     Value *V = Operands[0];
1160     Operands[0] = 0;   // Drop use!
1161
1162     // Now we just need to remove the old instruction so we don't get infinite
1163     // loops.  Note that we cannot use DCE because DCE won't remove a store
1164     // instruction, for example.
1165     //
1166     RecursiveDelete(Cache, dyn_cast<Instruction>(V));
1167   } else {
1168 #ifdef DEBUG_EXPR_CONVERT
1169     //cerr << "VH RELEASING: " << (void*)Operands[0].get() << " " << Operands[0]->use_size() << " " << Operands[0];
1170 #endif
1171   }
1172 }