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