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