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