Removed #include <iostream> and used the llvm_cerr/DOUT streams instead.
[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/ADT/STLExtras.h"
20 #include "llvm/Support/Debug.h"
21 #include <algorithm>
22 using namespace llvm;
23
24 static bool OperandConvertibleToType(User *U, Value *V, const Type *Ty,
25                                      ValueTypeCache &ConvertedTypes,
26                                      const TargetData &TD);
27
28 static void ConvertOperandToType(User *U, Value *OldVal, Value *NewVal,
29                                  ValueMapCache &VMC, const TargetData &TD);
30
31
32 // ExpressionConvertibleToType - Return true if it is possible
33 bool llvm::ExpressionConvertibleToType(Value *V, const Type *Ty,
34                                  ValueTypeCache &CTMap, const TargetData &TD) {
35   // Expression type must be holdable in a register.
36   if (!Ty->isFirstClassType())
37     return false;
38
39   ValueTypeCache::iterator CTMI = CTMap.find(V);
40   if (CTMI != CTMap.end()) return CTMI->second == Ty;
41
42   // If it's a constant... all constants can be converted to a different
43   // type.
44   //
45   if (isa<Constant>(V) && !isa<GlobalValue>(V))
46     return true;
47
48   CTMap[V] = Ty;
49   if (V->getType() == Ty) return true;  // Expression already correct type!
50
51   Instruction *I = dyn_cast<Instruction>(V);
52   if (I == 0) return false;              // Otherwise, we can't convert!
53
54   switch (I->getOpcode()) {
55   case Instruction::Cast:
56     // We can convert the expr if the cast destination type is losslessly
57     // convertible to the requested type.
58     if (!Ty->isLosslesslyConvertibleTo(I->getType())) return false;
59
60     // We also do not allow conversion of a cast that casts from a ptr to array
61     // of X to a *X.  For example: cast [4 x %List *] * %val to %List * *
62     //
63     if (const PointerType *SPT =
64         dyn_cast<PointerType>(I->getOperand(0)->getType()))
65       if (const PointerType *DPT = dyn_cast<PointerType>(I->getType()))
66         if (const ArrayType *AT = dyn_cast<ArrayType>(SPT->getElementType()))
67           if (AT->getElementType() == DPT->getElementType())
68             return false;
69     break;
70
71   case Instruction::Add:
72   case Instruction::Sub:
73     if (!Ty->isInteger() && !Ty->isFloatingPoint()) return false;
74     if (!ExpressionConvertibleToType(I->getOperand(0), Ty, CTMap, TD) ||
75         !ExpressionConvertibleToType(I->getOperand(1), Ty, CTMap, TD))
76       return false;
77     break;
78   case Instruction::LShr:
79   case Instruction::AShr:
80     if (!Ty->isInteger()) return false;
81     if (!ExpressionConvertibleToType(I->getOperand(0), Ty, CTMap, TD))
82       return false;
83     break;
84   case Instruction::Shl:
85     if (!Ty->isInteger()) return false;
86     if (!ExpressionConvertibleToType(I->getOperand(0), Ty, CTMap, TD))
87       return false;
88     break;
89
90   case Instruction::Load: {
91     LoadInst *LI = cast<LoadInst>(I);
92     if (!ExpressionConvertibleToType(LI->getPointerOperand(),
93                                      PointerType::get(Ty), CTMap, TD))
94       return false;
95     break;
96   }
97   case Instruction::PHI: {
98     PHINode *PN = cast<PHINode>(I);
99     // Be conservative if we find a giant PHI node.
100     if (PN->getNumIncomingValues() > 32) return false;
101
102     for (unsigned i = 0; i < PN->getNumIncomingValues(); ++i)
103       if (!ExpressionConvertibleToType(PN->getIncomingValue(i), Ty, CTMap, TD))
104         return false;
105     break;
106   }
107
108   case Instruction::GetElementPtr: {
109     // GetElementPtr's are directly convertible to a pointer type if they have
110     // a number of zeros at the end.  Because removing these values does not
111     // change the logical offset of the GEP, it is okay and fair to remove them.
112     // This can change this:
113     //   %t1 = getelementptr %Hosp * %hosp, ubyte 4, ubyte 0  ; <%List **>
114     //   %t2 = cast %List * * %t1 to %List *
115     // into
116     //   %t2 = getelementptr %Hosp * %hosp, ubyte 4           ; <%List *>
117     //
118     GetElementPtrInst *GEP = cast<GetElementPtrInst>(I);
119     const PointerType *PTy = dyn_cast<PointerType>(Ty);
120     if (!PTy) return false;  // GEP must always return a pointer...
121     const Type *PVTy = PTy->getElementType();
122
123     // Check to see if there are zero elements that we can remove from the
124     // index array.  If there are, check to see if removing them causes us to
125     // get to the right type...
126     //
127     std::vector<Value*> Indices(GEP->idx_begin(), GEP->idx_end());
128     const Type *BaseType = GEP->getPointerOperand()->getType();
129     const Type *ElTy = 0;
130
131     while (!Indices.empty() &&
132            Indices.back() == Constant::getNullValue(Indices.back()->getType())){
133       Indices.pop_back();
134       ElTy = GetElementPtrInst::getIndexedType(BaseType, Indices, true);
135       if (ElTy == PVTy)
136         break;  // Found a match!!
137       ElTy = 0;
138     }
139
140     if (ElTy) break;   // Found a number of zeros we can strip off!
141
142     // Otherwise, it could be that we have something like this:
143     //     getelementptr [[sbyte] *] * %reg115, long %reg138    ; [sbyte]**
144     // and want to convert it into something like this:
145     //     getelemenptr [[int] *] * %reg115, long %reg138      ; [int]**
146     //
147     if (GEP->getNumOperands() == 2 &&
148         PTy->getElementType()->isSized() &&
149         TD.getTypeSize(PTy->getElementType()) ==
150         TD.getTypeSize(GEP->getType()->getElementType())) {
151       const PointerType *NewSrcTy = PointerType::get(PVTy);
152       if (!ExpressionConvertibleToType(I->getOperand(0), NewSrcTy, CTMap, TD))
153         return false;
154       break;
155     }
156
157     return false;   // No match, maybe next time.
158   }
159
160   case Instruction::Call: {
161     if (isa<Function>(I->getOperand(0)))
162       return false;  // Don't even try to change direct calls.
163
164     // If this is a function pointer, we can convert the return type if we can
165     // convert the source function pointer.
166     //
167     const PointerType *PT = cast<PointerType>(I->getOperand(0)->getType());
168     const FunctionType *FT = cast<FunctionType>(PT->getElementType());
169     std::vector<const Type *> ArgTys(FT->param_begin(), FT->param_end());
170     const FunctionType *NewTy =
171       FunctionType::get(Ty, ArgTys, FT->isVarArg());
172     if (!ExpressionConvertibleToType(I->getOperand(0),
173                                      PointerType::get(NewTy), CTMap, TD))
174       return false;
175     break;
176   }
177   default:
178     return false;
179   }
180
181   // Expressions are only convertible if all of the users of the expression can
182   // have this value converted.  This makes use of the map to avoid infinite
183   // recursion.
184   //
185   for (Value::use_iterator It = I->use_begin(), E = I->use_end(); It != E; ++It)
186     if (!OperandConvertibleToType(*It, I, Ty, CTMap, TD))
187       return false;
188
189   return true;
190 }
191
192
193 Value *llvm::ConvertExpressionToType(Value *V, const Type *Ty,
194                                      ValueMapCache &VMC, const TargetData &TD) {
195   if (V->getType() == Ty) return V;  // Already where we need to be?
196
197   ValueMapCache::ExprMapTy::iterator VMCI = VMC.ExprMap.find(V);
198   if (VMCI != VMC.ExprMap.end()) {
199     assert(VMCI->second->getType() == Ty);
200
201     if (Instruction *I = dyn_cast<Instruction>(V))
202       ValueHandle IHandle(VMC, I);  // Remove I if it is unused now!
203
204     return VMCI->second;
205   }
206
207   DOUT << "CETT: " << (void*)V << " " << *V;
208
209   Instruction *I = dyn_cast<Instruction>(V);
210   if (I == 0) {
211     Constant *CPV = cast<Constant>(V);
212     // Constants are converted by constant folding the cast that is required.
213     // We assume here that all casts are implemented for constant prop.
214     Value *Result = ConstantExpr::getCast(CPV, Ty);
215     // Add the instruction to the expression map
216     //VMC.ExprMap[V] = Result;
217     return Result;
218   }
219
220
221   BasicBlock *BB = I->getParent();
222   std::string Name = I->getName();  if (!Name.empty()) I->setName("");
223   Instruction *Res;     // Result of conversion
224
225   ValueHandle IHandle(VMC, I);  // Prevent I from being removed!
226
227   Constant *Dummy = Constant::getNullValue(Ty);
228
229   switch (I->getOpcode()) {
230   case Instruction::Cast:
231     assert(VMC.NewCasts.count(ValueHandle(VMC, I)) == 0);
232     Res = new CastInst(I->getOperand(0), Ty, Name);
233     VMC.NewCasts.insert(ValueHandle(VMC, Res));
234     break;
235
236   case Instruction::Add:
237   case Instruction::Sub:
238     Res = BinaryOperator::create(cast<BinaryOperator>(I)->getOpcode(),
239                                  Dummy, Dummy, Name);
240     VMC.ExprMap[I] = Res;   // Add node to expression eagerly
241
242     Res->setOperand(0, ConvertExpressionToType(I->getOperand(0), Ty, VMC, TD));
243     Res->setOperand(1, ConvertExpressionToType(I->getOperand(1), Ty, VMC, TD));
244     break;
245
246   case Instruction::Shl:
247   case Instruction::LShr:
248   case Instruction::AShr:
249     Res = new ShiftInst(cast<ShiftInst>(I)->getOpcode(), Dummy,
250                         I->getOperand(1), Name);
251     VMC.ExprMap[I] = Res;
252     Res->setOperand(0, ConvertExpressionToType(I->getOperand(0), Ty, VMC, TD));
253     break;
254
255   case Instruction::Load: {
256     LoadInst *LI = cast<LoadInst>(I);
257
258     Res = new LoadInst(Constant::getNullValue(PointerType::get(Ty)), Name);
259     VMC.ExprMap[I] = Res;
260     Res->setOperand(0, ConvertExpressionToType(LI->getPointerOperand(),
261                                                PointerType::get(Ty), VMC, TD));
262     assert(Res->getOperand(0)->getType() == PointerType::get(Ty));
263     assert(Ty == Res->getType());
264     assert(Res->getType()->isFirstClassType() && "Load of structure or array!");
265     break;
266   }
267
268   case Instruction::PHI: {
269     PHINode *OldPN = cast<PHINode>(I);
270     PHINode *NewPN = new PHINode(Ty, Name);
271
272     VMC.ExprMap[I] = NewPN;   // Add node to expression eagerly
273     while (OldPN->getNumOperands()) {
274       BasicBlock *BB = OldPN->getIncomingBlock(0);
275       Value *OldVal = OldPN->getIncomingValue(0);
276       ValueHandle OldValHandle(VMC, OldVal);
277       OldPN->removeIncomingValue(BB, false);
278       Value *V = ConvertExpressionToType(OldVal, Ty, VMC, TD);
279       NewPN->addIncoming(V, BB);
280     }
281     Res = NewPN;
282     break;
283   }
284
285   case Instruction::GetElementPtr: {
286     // GetElementPtr's are directly convertible to a pointer type if they have
287     // a number of zeros at the end.  Because removing these values does not
288     // change the logical offset of the GEP, it is okay and fair to remove them.
289     // This can change this:
290     //   %t1 = getelementptr %Hosp * %hosp, ubyte 4, ubyte 0  ; <%List **>
291     //   %t2 = cast %List * * %t1 to %List *
292     // into
293     //   %t2 = getelementptr %Hosp * %hosp, ubyte 4           ; <%List *>
294     //
295     GetElementPtrInst *GEP = cast<GetElementPtrInst>(I);
296
297     // Check to see if there are zero elements that we can remove from the
298     // index array.  If there are, check to see if removing them causes us to
299     // get to the right type...
300     //
301     std::vector<Value*> Indices(GEP->idx_begin(), GEP->idx_end());
302     const Type *BaseType = GEP->getPointerOperand()->getType();
303     const Type *PVTy = cast<PointerType>(Ty)->getElementType();
304     Res = 0;
305     while (!Indices.empty() &&
306            Indices.back() == Constant::getNullValue(Indices.back()->getType())){
307       Indices.pop_back();
308       if (GetElementPtrInst::getIndexedType(BaseType, Indices, true) == PVTy) {
309         if (Indices.size() == 0)
310           Res = new CastInst(GEP->getPointerOperand(), BaseType); // NOOP CAST
311         else
312           Res = new GetElementPtrInst(GEP->getPointerOperand(), Indices, Name);
313         break;
314       }
315     }
316
317     // Otherwise, it could be that we have something like this:
318     //     getelementptr [[sbyte] *] * %reg115, uint %reg138    ; [sbyte]**
319     // and want to convert it into something like this:
320     //     getelemenptr [[int] *] * %reg115, uint %reg138      ; [int]**
321     //
322     if (Res == 0) {
323       const PointerType *NewSrcTy = PointerType::get(PVTy);
324       std::vector<Value*> Indices(GEP->idx_begin(), GEP->idx_end());
325       Res = new GetElementPtrInst(Constant::getNullValue(NewSrcTy),
326                                   Indices, Name);
327       VMC.ExprMap[I] = Res;
328       Res->setOperand(0, ConvertExpressionToType(I->getOperand(0),
329                                                  NewSrcTy, VMC, TD));
330     }
331
332
333     assert(Res && "Didn't find match!");
334     break;
335   }
336
337   case Instruction::Call: {
338     assert(!isa<Function>(I->getOperand(0)));
339
340     // If this is a function pointer, we can convert the return type if we can
341     // convert the source function pointer.
342     //
343     const PointerType *PT = cast<PointerType>(I->getOperand(0)->getType());
344     const FunctionType *FT = cast<FunctionType>(PT->getElementType());
345     std::vector<const Type *> ArgTys(FT->param_begin(), FT->param_end());
346     const FunctionType *NewTy =
347       FunctionType::get(Ty, ArgTys, FT->isVarArg());
348     const PointerType *NewPTy = PointerType::get(NewTy);
349     if (Ty == Type::VoidTy)
350       Name = "";  // Make sure not to name calls that now return void!
351
352     Res = new CallInst(Constant::getNullValue(NewPTy),
353                        std::vector<Value*>(I->op_begin()+1, I->op_end()),
354                        Name);
355     if (cast<CallInst>(I)->isTailCall())
356       cast<CallInst>(Res)->setTailCall();
357     cast<CallInst>(Res)->setCallingConv(cast<CallInst>(I)->getCallingConv());
358     VMC.ExprMap[I] = Res;
359     Res->setOperand(0, ConvertExpressionToType(I->getOperand(0),NewPTy,VMC,TD));
360     break;
361   }
362   default:
363     assert(0 && "Expression convertible, but don't know how to convert?");
364     return 0;
365   }
366
367   assert(Res->getType() == Ty && "Didn't convert expr to correct type!");
368
369   BB->getInstList().insert(I, Res);
370
371   // Add the instruction to the expression map
372   VMC.ExprMap[I] = Res;
373
374
375   //// WTF is this code!  FIXME: remove this.
376   unsigned NumUses = I->getNumUses();
377   for (unsigned It = 0; It < NumUses; ) {
378     unsigned OldSize = NumUses;
379     Value::use_iterator UI = I->use_begin();
380     std::advance(UI, It);
381     ConvertOperandToType(*UI, I, Res, VMC, TD);
382     NumUses = I->getNumUses();
383     if (NumUses == OldSize) ++It;
384   }
385
386   DOUT << "ExpIn: " << (void*)I << " " << *I
387        << "ExpOut: " << (void*)Res << " " << *Res;
388
389   return Res;
390 }
391
392
393
394 // ValueConvertibleToType - Return true if it is possible
395 bool llvm::ValueConvertibleToType(Value *V, const Type *Ty,
396                                   ValueTypeCache &ConvertedTypes,
397                                   const TargetData &TD) {
398   ValueTypeCache::iterator I = ConvertedTypes.find(V);
399   if (I != ConvertedTypes.end()) return I->second == Ty;
400   ConvertedTypes[V] = Ty;
401
402   // It is safe to convert the specified value to the specified type IFF all of
403   // the uses of the value can be converted to accept the new typed value.
404   //
405   if (V->getType() != Ty) {
406     for (Value::use_iterator I = V->use_begin(), E = V->use_end(); I != E; ++I)
407       if (!OperandConvertibleToType(*I, V, Ty, ConvertedTypes, TD))
408         return false;
409   }
410
411   return true;
412 }
413
414
415
416
417
418 // OperandConvertibleToType - Return true if it is possible to convert operand
419 // V of User (instruction) U to the specified type.  This is true iff it is
420 // possible to change the specified instruction to accept this.  CTMap is a map
421 // of converted types, so that circular definitions will see the future type of
422 // the expression, not the static current type.
423 //
424 static bool OperandConvertibleToType(User *U, Value *V, const Type *Ty,
425                                      ValueTypeCache &CTMap,
426                                      const TargetData &TD) {
427   //  if (V->getType() == Ty) return true;   // Operand already the right type?
428
429   // Expression type must be holdable in a register.
430   if (!Ty->isFirstClassType())
431     return false;
432
433   Instruction *I = dyn_cast<Instruction>(U);
434   if (I == 0) return false;              // We can't convert!
435
436   switch (I->getOpcode()) {
437   case Instruction::Cast:
438     assert(I->getOperand(0) == V);
439     // We can convert the expr if the cast destination type is losslessly
440     // convertible to the requested type.
441     // Also, do not change a cast that is a noop cast.  For all intents and
442     // purposes it should be eliminated.
443     if (!Ty->isLosslesslyConvertibleTo(I->getOperand(0)->getType()) ||
444         I->getType() == I->getOperand(0)->getType())
445       return false;
446
447     // Do not allow a 'cast ushort %V to uint' to have it's first operand be
448     // converted to a 'short' type.  Doing so changes the way sign promotion
449     // happens, and breaks things.  Only allow the cast to take place if the
450     // signedness doesn't change... or if the current cast is not a lossy
451     // conversion.
452     //
453     if (!I->getType()->isLosslesslyConvertibleTo(I->getOperand(0)->getType()) &&
454         I->getOperand(0)->getType()->isSigned() != Ty->isSigned())
455       return false;
456
457     // We also do not allow conversion of a cast that casts from a ptr to array
458     // of X to a *X.  For example: cast [4 x %List *] * %val to %List * *
459     //
460     if (const PointerType *SPT =
461         dyn_cast<PointerType>(I->getOperand(0)->getType()))
462       if (const PointerType *DPT = dyn_cast<PointerType>(I->getType()))
463         if (const ArrayType *AT = dyn_cast<ArrayType>(SPT->getElementType()))
464           if (AT->getElementType() == DPT->getElementType())
465             return false;
466     return true;
467
468   case Instruction::Add:
469   case Instruction::Sub: {
470     if (!Ty->isInteger() && !Ty->isFloatingPoint()) return false;
471
472     Value *OtherOp = I->getOperand((V == I->getOperand(0)) ? 1 : 0);
473     return ValueConvertibleToType(I, Ty, CTMap, TD) &&
474            ExpressionConvertibleToType(OtherOp, Ty, CTMap, TD);
475   }
476   case Instruction::SetEQ:
477   case Instruction::SetNE: {
478     Value *OtherOp = I->getOperand((V == I->getOperand(0)) ? 1 : 0);
479     return ExpressionConvertibleToType(OtherOp, Ty, CTMap, TD);
480   }
481   case Instruction::LShr:
482   case Instruction::AShr:
483     if (Ty->isSigned() != V->getType()->isSigned()) return false;
484     // FALL THROUGH
485   case Instruction::Shl:
486     if (I->getOperand(1) == V) return false;  // Cannot change shift amount type
487     if (!Ty->isInteger()) return false;
488     return ValueConvertibleToType(I, Ty, CTMap, TD);
489
490   case Instruction::Free:
491     assert(I->getOperand(0) == V);
492     return isa<PointerType>(Ty);    // Free can free any pointer type!
493
494   case Instruction::Load:
495     // Cannot convert the types of any subscripts...
496     if (I->getOperand(0) != V) return false;
497
498     if (const PointerType *PT = dyn_cast<PointerType>(Ty)) {
499       LoadInst *LI = cast<LoadInst>(I);
500
501       const Type *LoadedTy = PT->getElementType();
502
503       // They could be loading the first element of a composite type...
504       if (const CompositeType *CT = dyn_cast<CompositeType>(LoadedTy)) {
505         unsigned Offset = 0;     // No offset, get first leaf.
506         std::vector<Value*> Indices;  // Discarded...
507         LoadedTy = getStructOffsetType(CT, Offset, Indices, TD, false);
508         assert(Offset == 0 && "Offset changed from zero???");
509       }
510
511       if (!LoadedTy->isFirstClassType())
512         return false;
513
514       if (TD.getTypeSize(LoadedTy) != TD.getTypeSize(LI->getType()))
515         return false;
516
517       return ValueConvertibleToType(LI, LoadedTy, CTMap, TD);
518     }
519     return false;
520
521   case Instruction::Store: {
522     if (V == I->getOperand(0)) {
523       ValueTypeCache::iterator CTMI = CTMap.find(I->getOperand(1));
524       if (CTMI != CTMap.end()) {   // Operand #1 is in the table already?
525         // If so, check to see if it's Ty*, or, more importantly, if it is a
526         // pointer to a structure where the first element is a Ty... this code
527         // is necessary because we might be trying to change the source and
528         // destination type of the store (they might be related) and the dest
529         // pointer type might be a pointer to structure.  Below we allow pointer
530         // to structures where the 0th element is compatible with the value,
531         // now we have to support the symmetrical part of this.
532         //
533         const Type *ElTy = cast<PointerType>(CTMI->second)->getElementType();
534
535         // Already a pointer to what we want?  Trivially accept...
536         if (ElTy == Ty) return true;
537
538         // Tricky case now, if the destination is a pointer to structure,
539         // obviously the source is not allowed to be a structure (cannot copy
540         // a whole structure at a time), so the level raiser must be trying to
541         // store into the first field.  Check for this and allow it now:
542         //
543         if (isa<StructType>(ElTy)) {
544           unsigned Offset = 0;
545           std::vector<Value*> Indices;
546           ElTy = getStructOffsetType(ElTy, Offset, Indices, TD, false);
547           assert(Offset == 0 && "Offset changed!");
548           if (ElTy == 0)    // Element at offset zero in struct doesn't exist!
549             return false;   // Can only happen for {}*
550
551           if (ElTy == Ty)   // Looks like the 0th element of structure is
552             return true;    // compatible!  Accept now!
553
554           // Otherwise we know that we can't work, so just stop trying now.
555           return false;
556         }
557       }
558
559       // Can convert the store if we can convert the pointer operand to match
560       // the new  value type...
561       return ExpressionConvertibleToType(I->getOperand(1), PointerType::get(Ty),
562                                          CTMap, TD);
563     } else if (const PointerType *PT = dyn_cast<PointerType>(Ty)) {
564       const Type *ElTy = PT->getElementType();
565       assert(V == I->getOperand(1));
566
567       if (isa<StructType>(ElTy)) {
568         // We can change the destination pointer if we can store our first
569         // argument into the first element of the structure...
570         //
571         unsigned Offset = 0;
572         std::vector<Value*> Indices;
573         ElTy = getStructOffsetType(ElTy, Offset, Indices, TD, false);
574         assert(Offset == 0 && "Offset changed!");
575         if (ElTy == 0)    // Element at offset zero in struct doesn't exist!
576           return false;   // Can only happen for {}*
577       }
578
579       // Must move the same amount of data...
580       if (!ElTy->isSized() ||
581           TD.getTypeSize(ElTy) != TD.getTypeSize(I->getOperand(0)->getType()))
582         return false;
583
584       // Can convert store if the incoming value is convertible and if the
585       // result will preserve semantics...
586       const Type *Op0Ty = I->getOperand(0)->getType();
587       if (!(Op0Ty->isIntegral() ^ ElTy->isIntegral()) &&
588           !(Op0Ty->isFloatingPoint() ^ ElTy->isFloatingPoint()))
589         return ExpressionConvertibleToType(I->getOperand(0), ElTy, CTMap, TD);
590     }
591     return false;
592   }
593
594   case Instruction::PHI: {
595     PHINode *PN = cast<PHINode>(I);
596     // Be conservative if we find a giant PHI node.
597     if (PN->getNumIncomingValues() > 32) return false;
598
599     for (unsigned i = 0; i < PN->getNumIncomingValues(); ++i)
600       if (!ExpressionConvertibleToType(PN->getIncomingValue(i), Ty, CTMap, TD))
601         return false;
602     return ValueConvertibleToType(PN, Ty, CTMap, TD);
603   }
604
605   case Instruction::Call: {
606     User::op_iterator OI = std::find(I->op_begin(), I->op_end(), V);
607     assert (OI != I->op_end() && "Not using value!");
608     unsigned OpNum = OI - I->op_begin();
609
610     // Are we trying to change the function pointer value to a new type?
611     if (OpNum == 0) {
612       const PointerType *PTy = dyn_cast<PointerType>(Ty);
613       if (PTy == 0) return false;  // Can't convert to a non-pointer type...
614       const FunctionType *FTy = dyn_cast<FunctionType>(PTy->getElementType());
615       if (FTy == 0) return false;  // Can't convert to a non ptr to function...
616
617       // Do not allow converting to a call where all of the operands are ...'s
618       if (FTy->getNumParams() == 0 && FTy->isVarArg())
619         return false;              // Do not permit this conversion!
620
621       // Perform sanity checks to make sure that new function type has the
622       // correct number of arguments...
623       //
624       unsigned NumArgs = I->getNumOperands()-1;  // Don't include function ptr
625
626       // Cannot convert to a type that requires more fixed arguments than
627       // the call provides...
628       //
629       if (NumArgs < FTy->getNumParams()) return false;
630
631       // Unless this is a vararg function type, we cannot provide more arguments
632       // than are desired...
633       //
634       if (!FTy->isVarArg() && NumArgs > FTy->getNumParams())
635         return false;
636
637       // Okay, at this point, we know that the call and the function type match
638       // number of arguments.  Now we see if we can convert the arguments
639       // themselves.  Note that we do not require operands to be convertible,
640       // we can insert casts if they are convertible but not compatible.  The
641       // reason for this is that we prefer to have resolved functions but casted
642       // arguments if possible.
643       //
644       for (unsigned i = 0, NA = FTy->getNumParams(); i < NA; ++i)
645         if (!FTy->getParamType(i)->isLosslesslyConvertibleTo(I->getOperand(i+1)->getType()))
646           return false;   // Operands must have compatible types!
647
648       // Okay, at this point, we know that all of the arguments can be
649       // converted.  We succeed if we can change the return type if
650       // necessary...
651       //
652       return ValueConvertibleToType(I, FTy->getReturnType(), CTMap, TD);
653     }
654
655     const PointerType *MPtr = cast<PointerType>(I->getOperand(0)->getType());
656     const FunctionType *FTy = cast<FunctionType>(MPtr->getElementType());
657     if (!FTy->isVarArg()) return false;
658
659     if ((OpNum-1) < FTy->getNumParams())
660       return false;  // It's not in the varargs section...
661
662     // If we get this far, we know the value is in the varargs section of the
663     // function!  We can convert if we don't reinterpret the value...
664     //
665     return Ty->isLosslesslyConvertibleTo(V->getType());
666   }
667   }
668   return false;
669 }
670
671
672 void llvm::ConvertValueToNewType(Value *V, Value *NewVal, ValueMapCache &VMC,
673                                  const TargetData &TD) {
674   ValueHandle VH(VMC, V);
675
676   // FIXME: This is horrible!
677   unsigned NumUses = V->getNumUses();
678   for (unsigned It = 0; It < NumUses; ) {
679     unsigned OldSize = NumUses;
680     Value::use_iterator UI = V->use_begin();
681     std::advance(UI, It);
682     ConvertOperandToType(*UI, V, NewVal, VMC, TD);
683     NumUses = V->getNumUses();
684     if (NumUses == OldSize) ++It;
685   }
686 }
687
688
689
690 static void ConvertOperandToType(User *U, Value *OldVal, Value *NewVal,
691                                  ValueMapCache &VMC, const TargetData &TD) {
692   if (isa<ValueHandle>(U)) return;  // Valuehandles don't let go of operands...
693
694   if (VMC.OperandsMapped.count(U)) return;
695   VMC.OperandsMapped.insert(U);
696
697   ValueMapCache::ExprMapTy::iterator VMCI = VMC.ExprMap.find(U);
698   if (VMCI != VMC.ExprMap.end())
699     return;
700
701
702   Instruction *I = cast<Instruction>(U);  // Only Instructions convertible
703
704   BasicBlock *BB = I->getParent();
705   assert(BB != 0 && "Instruction not embedded in basic block!");
706   std::string Name = I->getName();
707   I->setName("");
708   Instruction *Res;     // Result of conversion
709
710   //llvm_cerr << endl << endl << "Type:\t" << Ty << "\nInst: " << I
711   //          << "BB Before: " << BB << endl;
712
713   // Prevent I from being removed...
714   ValueHandle IHandle(VMC, I);
715
716   const Type *NewTy = NewVal->getType();
717   Constant *Dummy = (NewTy != Type::VoidTy) ?
718                   Constant::getNullValue(NewTy) : 0;
719
720   switch (I->getOpcode()) {
721   case Instruction::Cast:
722     if (VMC.NewCasts.count(ValueHandle(VMC, I))) {
723       // This cast has already had it's value converted, causing a new cast to
724       // be created.  We don't want to create YET ANOTHER cast instruction
725       // representing the original one, so just modify the operand of this cast
726       // instruction, which we know is newly created.
727       I->setOperand(0, NewVal);
728       I->setName(Name);  // give I its name back
729       return;
730
731     } else {
732       Res = new CastInst(NewVal, I->getType(), Name);
733     }
734     break;
735
736   case Instruction::Add:
737   case Instruction::Sub:
738   case Instruction::SetEQ:
739   case Instruction::SetNE: {
740     Res = BinaryOperator::create(cast<BinaryOperator>(I)->getOpcode(),
741                                  Dummy, Dummy, Name);
742     VMC.ExprMap[I] = Res;   // Add node to expression eagerly
743
744     unsigned OtherIdx = (OldVal == I->getOperand(0)) ? 1 : 0;
745     Value *OtherOp    = I->getOperand(OtherIdx);
746     Res->setOperand(!OtherIdx, NewVal);
747     Value *NewOther   = ConvertExpressionToType(OtherOp, NewTy, VMC, TD);
748     Res->setOperand(OtherIdx, NewOther);
749     break;
750   }
751   case Instruction::Shl:
752   case Instruction::LShr:
753   case Instruction::AShr:
754     assert(I->getOperand(0) == OldVal);
755     Res = new ShiftInst(cast<ShiftInst>(I)->getOpcode(), NewVal,
756                         I->getOperand(1), Name);
757     break;
758
759   case Instruction::Free:            // Free can free any pointer type!
760     assert(I->getOperand(0) == OldVal);
761     Res = new FreeInst(NewVal);
762     break;
763
764
765   case Instruction::Load: {
766     assert(I->getOperand(0) == OldVal && isa<PointerType>(NewVal->getType()));
767     const Type *LoadedTy =
768       cast<PointerType>(NewVal->getType())->getElementType();
769
770     Value *Src = NewVal;
771
772     if (const CompositeType *CT = dyn_cast<CompositeType>(LoadedTy)) {
773       std::vector<Value*> Indices;
774       Indices.push_back(Constant::getNullValue(Type::UIntTy));
775
776       unsigned Offset = 0;   // No offset, get first leaf.
777       LoadedTy = getStructOffsetType(CT, Offset, Indices, TD, false);
778       assert(LoadedTy->isFirstClassType());
779
780       if (Indices.size() != 1) {     // Do not generate load X, 0
781         // Insert the GEP instruction before this load.
782         Src = new GetElementPtrInst(Src, Indices, Name+".idx", I);
783       }
784     }
785
786     Res = new LoadInst(Src, Name);
787     assert(Res->getType()->isFirstClassType() && "Load of structure or array!");
788     break;
789   }
790
791   case Instruction::Store: {
792     if (I->getOperand(0) == OldVal) {  // Replace the source value
793       // Check to see if operand #1 has already been converted...
794       ValueMapCache::ExprMapTy::iterator VMCI =
795         VMC.ExprMap.find(I->getOperand(1));
796       if (VMCI != VMC.ExprMap.end()) {
797         // Comments describing this stuff are in the OperandConvertibleToType
798         // switch statement for Store...
799         //
800         const Type *ElTy =
801           cast<PointerType>(VMCI->second->getType())->getElementType();
802
803         Value *SrcPtr = VMCI->second;
804
805         if (ElTy != NewTy) {
806           std::vector<Value*> Indices;
807           Indices.push_back(Constant::getNullValue(Type::UIntTy));
808
809           unsigned Offset = 0;
810           const Type *Ty = getStructOffsetType(ElTy, Offset, Indices, TD,false);
811           assert(Offset == 0 && "Offset changed!");
812           assert(NewTy == Ty && "Did not convert to correct type!");
813
814           // Insert the GEP instruction before this store.
815           SrcPtr = new GetElementPtrInst(SrcPtr, Indices,
816                                          SrcPtr->getName()+".idx", I);
817         }
818         Res = new StoreInst(NewVal, SrcPtr);
819
820         VMC.ExprMap[I] = Res;
821       } else {
822         // Otherwise, we haven't converted Operand #1 over yet...
823         const PointerType *NewPT = PointerType::get(NewTy);
824         Res = new StoreInst(NewVal, Constant::getNullValue(NewPT));
825         VMC.ExprMap[I] = Res;
826         Res->setOperand(1, ConvertExpressionToType(I->getOperand(1),
827                                                    NewPT, VMC, TD));
828       }
829     } else {                           // Replace the source pointer
830       const Type *ValTy = cast<PointerType>(NewTy)->getElementType();
831
832       Value *SrcPtr = NewVal;
833
834       if (isa<StructType>(ValTy)) {
835         std::vector<Value*> Indices;
836         Indices.push_back(Constant::getNullValue(Type::UIntTy));
837
838         unsigned Offset = 0;
839         ValTy = getStructOffsetType(ValTy, Offset, Indices, TD, false);
840
841         assert(Offset == 0 && ValTy);
842
843         // Insert the GEP instruction before this store.
844         SrcPtr = new GetElementPtrInst(SrcPtr, Indices,
845                                        SrcPtr->getName()+".idx", I);
846       }
847
848       Res = new StoreInst(Constant::getNullValue(ValTy), SrcPtr);
849       VMC.ExprMap[I] = Res;
850       Res->setOperand(0, ConvertExpressionToType(I->getOperand(0),
851                                                  ValTy, VMC, TD));
852     }
853     break;
854   }
855
856   case Instruction::PHI: {
857     PHINode *OldPN = cast<PHINode>(I);
858     PHINode *NewPN = new PHINode(NewTy, Name);
859     VMC.ExprMap[I] = NewPN;
860
861     while (OldPN->getNumOperands()) {
862       BasicBlock *BB = OldPN->getIncomingBlock(0);
863       Value *OldVal = OldPN->getIncomingValue(0);
864       ValueHandle OldValHandle(VMC, OldVal);
865       OldPN->removeIncomingValue(BB, false);
866       Value *V = ConvertExpressionToType(OldVal, NewTy, VMC, TD);
867       NewPN->addIncoming(V, BB);
868     }
869     Res = NewPN;
870     break;
871   }
872
873   case Instruction::Call: {
874     Value *Meth = I->getOperand(0);
875     std::vector<Value*> Params(I->op_begin()+1, I->op_end());
876
877     if (Meth == OldVal) {   // Changing the function pointer?
878       const PointerType *NewPTy = cast<PointerType>(NewVal->getType());
879       const FunctionType *NewTy = cast<FunctionType>(NewPTy->getElementType());
880
881       if (NewTy->getReturnType() == Type::VoidTy)
882         Name = "";  // Make sure not to name a void call!
883
884       // Get an iterator to the call instruction so that we can insert casts for
885       // operands if need be.  Note that we do not require operands to be
886       // convertible, we can insert casts if they are convertible but not
887       // compatible.  The reason for this is that we prefer to have resolved
888       // functions but casted arguments if possible.
889       //
890       BasicBlock::iterator It = I;
891
892       // Convert over all of the call operands to their new types... but only
893       // convert over the part that is not in the vararg section of the call.
894       //
895       for (unsigned i = 0; i != NewTy->getNumParams(); ++i)
896         if (Params[i]->getType() != NewTy->getParamType(i)) {
897           // Create a cast to convert it to the right type, we know that this
898           // is a lossless cast...
899           //
900           Params[i] = new CastInst(Params[i], NewTy->getParamType(i),
901                                    "callarg.cast." +
902                                    Params[i]->getName(), It);
903         }
904       Meth = NewVal;  // Update call destination to new value
905
906     } else {                   // Changing an argument, must be in vararg area
907       std::vector<Value*>::iterator OI =
908         std::find(Params.begin(), Params.end(), OldVal);
909       assert (OI != Params.end() && "Not using value!");
910
911       *OI = NewVal;
912     }
913
914     Res = new CallInst(Meth, Params, Name);
915     if (cast<CallInst>(I)->isTailCall())
916       cast<CallInst>(Res)->setTailCall();
917     cast<CallInst>(Res)->setCallingConv(cast<CallInst>(I)->getCallingConv());
918     break;
919   }
920   default:
921     assert(0 && "Expression convertible, but don't know how to convert?");
922     return;
923   }
924
925   // If the instruction was newly created, insert it into the instruction
926   // stream.
927   //
928   BasicBlock::iterator It = I;
929   assert(It != BB->end() && "Instruction not in own basic block??");
930   BB->getInstList().insert(It, Res);   // Keep It pointing to old instruction
931
932   DOUT << "COT CREATED: "  << (void*)Res << " " << *Res
933        << "In: " << (void*)I << " " << *I << "Out: " << (void*)Res
934        << " " << *Res;
935
936   // Add the instruction to the expression map
937   VMC.ExprMap[I] = Res;
938
939   if (I->getType() != Res->getType())
940     ConvertValueToNewType(I, Res, VMC, TD);
941   else {
942     for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
943          UI != E; )
944       if (isa<ValueHandle>(*UI)) {
945         ++UI;
946       } else {
947         Use &U = UI.getUse();
948         ++UI;  // Do not invalidate UI.
949         U.set(Res);
950       }
951   }
952 }
953
954
955 ValueHandle::ValueHandle(ValueMapCache &VMC, Value *V)
956   : Instruction(Type::VoidTy, UserOp1, &Op, 1, ""), Op(V, this), Cache(VMC) {
957   //DOUT << "VH AQUIRING: " << (void*)V << " " << V;
958 }
959
960 ValueHandle::ValueHandle(const ValueHandle &VH)
961   : Instruction(Type::VoidTy, UserOp1, &Op, 1, ""),
962     Op(VH.Op, this), Cache(VH.Cache) {
963   //DOUT << "VH AQUIRING: " << (void*)V << " " << V;
964 }
965
966 static void RecursiveDelete(ValueMapCache &Cache, Instruction *I) {
967   if (!I || !I->use_empty()) return;
968
969   assert(I->getParent() && "Inst not in basic block!");
970
971   //DOUT << "VH DELETING: " << (void*)I << " " << I;
972
973   for (User::op_iterator OI = I->op_begin(), OE = I->op_end();
974        OI != OE; ++OI)
975     if (Instruction *U = dyn_cast<Instruction>(OI)) {
976       *OI = 0;
977       RecursiveDelete(Cache, U);
978     }
979
980   I->getParent()->getInstList().remove(I);
981
982   Cache.OperandsMapped.erase(I);
983   Cache.ExprMap.erase(I);
984   delete I;
985 }
986
987 ValueHandle::~ValueHandle() {
988   if (Op->hasOneUse()) {
989     Value *V = Op;
990     Op.set(0);   // Drop use!
991
992     // Now we just need to remove the old instruction so we don't get infinite
993     // loops.  Note that we cannot use DCE because DCE won't remove a store
994     // instruction, for example.
995     //
996     RecursiveDelete(Cache, dyn_cast<Instruction>(V));
997   } else {
998     //DOUT << "VH RELEASING: " << (void*)Operands[0].get() << " "
999     //     << Operands[0]->getNumUses() << " " << Operands[0];
1000   }
1001 }