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