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