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