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