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