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