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