When a function takes a variable number of pointer arguments, with a zero
[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, it could be that we have something like this:
256     //     getelementptr [[sbyte] *] * %reg115, long %reg138    ; [sbyte]**
257     // and want to convert it into something like this:
258     //     getelemenptr [[int] *] * %reg115, long %reg138      ; [int]**
259     //
260     if (GEP->getNumOperands() == 2 &&
261         PTy->getElementType()->isSized() &&
262         TD.getTypeSize(PTy->getElementType()) ==
263         TD.getTypeSize(GEP->getType()->getElementType())) {
264       const PointerType *NewSrcTy = PointerType::get(PVTy);
265       if (!ExpressionConvertibleToType(I->getOperand(0), NewSrcTy, CTMap, TD))
266         return false;
267       break;
268     }
269
270     return false;   // No match, maybe next time.
271   }
272
273   case Instruction::Call: {
274     if (isa<Function>(I->getOperand(0)))
275       return false;  // Don't even try to change direct calls.
276
277     // If this is a function pointer, we can convert the return type if we can
278     // convert the source function pointer.
279     //
280     const PointerType *PT = cast<PointerType>(I->getOperand(0)->getType());
281     const FunctionType *FT = cast<FunctionType>(PT->getElementType());
282     std::vector<const Type *> ArgTys(FT->param_begin(), FT->param_end());
283     const FunctionType *NewTy =
284       FunctionType::get(Ty, ArgTys, FT->isVarArg());
285     if (!ExpressionConvertibleToType(I->getOperand(0),
286                                      PointerType::get(NewTy), CTMap, TD))
287       return false;
288     break;
289   }
290   default:
291     return false;
292   }
293
294   // Expressions are only convertible if all of the users of the expression can
295   // have this value converted.  This makes use of the map to avoid infinite
296   // recursion.
297   //
298   for (Value::use_iterator It = I->use_begin(), E = I->use_end(); It != E; ++It)
299     if (!OperandConvertibleToType(*It, I, Ty, CTMap, TD))
300       return false;
301
302   return true;
303 }
304
305
306 Value *llvm::ConvertExpressionToType(Value *V, const Type *Ty,
307                                      ValueMapCache &VMC, const TargetData &TD) {
308   if (V->getType() == Ty) return V;  // Already where we need to be?
309
310   ValueMapCache::ExprMapTy::iterator VMCI = VMC.ExprMap.find(V);
311   if (VMCI != VMC.ExprMap.end()) {
312     const Value *GV = VMCI->second;
313     const Type *GTy = VMCI->second->getType();
314     assert(VMCI->second->getType() == Ty);
315
316     if (Instruction *I = dyn_cast<Instruction>(V))
317       ValueHandle IHandle(VMC, I);  // Remove I if it is unused now!
318
319     return VMCI->second;
320   }
321
322   DEBUG(std::cerr << "CETT: " << (void*)V << " " << *V);
323
324   Instruction *I = dyn_cast<Instruction>(V);
325   if (I == 0) {
326     Constant *CPV = cast<Constant>(V);
327     // Constants are converted by constant folding the cast that is required.
328     // We assume here that all casts are implemented for constant prop.
329     Value *Result = ConstantExpr::getCast(CPV, Ty);
330     // Add the instruction to the expression map
331     //VMC.ExprMap[V] = Result;
332     return Result;
333   }
334
335
336   BasicBlock *BB = I->getParent();
337   std::string Name = I->getName();  if (!Name.empty()) I->setName("");
338   Instruction *Res;     // Result of conversion
339
340   ValueHandle IHandle(VMC, I);  // Prevent I from being removed!
341
342   Constant *Dummy = Constant::getNullValue(Ty);
343
344   switch (I->getOpcode()) {
345   case Instruction::Cast:
346     assert(VMC.NewCasts.count(ValueHandle(VMC, I)) == 0);
347     Res = new CastInst(I->getOperand(0), Ty, Name);
348     VMC.NewCasts.insert(ValueHandle(VMC, Res));
349     break;
350
351   case Instruction::Add:
352   case Instruction::Sub:
353     Res = BinaryOperator::create(cast<BinaryOperator>(I)->getOpcode(),
354                                  Dummy, Dummy, Name);
355     VMC.ExprMap[I] = Res;   // Add node to expression eagerly
356
357     Res->setOperand(0, ConvertExpressionToType(I->getOperand(0), Ty, VMC, TD));
358     Res->setOperand(1, ConvertExpressionToType(I->getOperand(1), Ty, VMC, TD));
359     break;
360
361   case Instruction::Shl:
362   case Instruction::Shr:
363     Res = new ShiftInst(cast<ShiftInst>(I)->getOpcode(), Dummy,
364                         I->getOperand(1), Name);
365     VMC.ExprMap[I] = Res;
366     Res->setOperand(0, ConvertExpressionToType(I->getOperand(0), Ty, VMC, TD));
367     break;
368
369   case Instruction::Load: {
370     LoadInst *LI = cast<LoadInst>(I);
371
372     Res = new LoadInst(Constant::getNullValue(PointerType::get(Ty)), Name);
373     VMC.ExprMap[I] = Res;
374     Res->setOperand(0, ConvertExpressionToType(LI->getPointerOperand(),
375                                                PointerType::get(Ty), VMC, TD));
376     assert(Res->getOperand(0)->getType() == PointerType::get(Ty));
377     assert(Ty == Res->getType());
378     assert(Res->getType()->isFirstClassType() && "Load of structure or array!");
379     break;
380   }
381
382   case Instruction::PHI: {
383     PHINode *OldPN = cast<PHINode>(I);
384     PHINode *NewPN = new PHINode(Ty, Name);
385
386     VMC.ExprMap[I] = NewPN;   // Add node to expression eagerly
387     while (OldPN->getNumOperands()) {
388       BasicBlock *BB = OldPN->getIncomingBlock(0);
389       Value *OldVal = OldPN->getIncomingValue(0);
390       ValueHandle OldValHandle(VMC, OldVal);
391       OldPN->removeIncomingValue(BB, false);
392       Value *V = ConvertExpressionToType(OldVal, Ty, VMC, TD);
393       NewPN->addIncoming(V, BB);
394     }
395     Res = NewPN;
396     break;
397   }
398
399   case Instruction::Malloc: {
400     Res = ConvertMallocToType(cast<MallocInst>(I), Ty, Name, VMC, TD);
401     break;
402   }
403
404   case Instruction::GetElementPtr: {
405     // GetElementPtr's are directly convertible to a pointer type if they have
406     // a number of zeros at the end.  Because removing these values does not
407     // change the logical offset of the GEP, it is okay and fair to remove them.
408     // This can change this:
409     //   %t1 = getelementptr %Hosp * %hosp, ubyte 4, ubyte 0  ; <%List **>
410     //   %t2 = cast %List * * %t1 to %List *
411     // into
412     //   %t2 = getelementptr %Hosp * %hosp, ubyte 4           ; <%List *>
413     //
414     GetElementPtrInst *GEP = cast<GetElementPtrInst>(I);
415
416     // Check to see if there are zero elements that we can remove from the
417     // index array.  If there are, check to see if removing them causes us to
418     // get to the right type...
419     //
420     std::vector<Value*> Indices(GEP->idx_begin(), GEP->idx_end());
421     const Type *BaseType = GEP->getPointerOperand()->getType();
422     const Type *PVTy = cast<PointerType>(Ty)->getElementType();
423     Res = 0;
424     while (!Indices.empty() &&
425            Indices.back() == Constant::getNullValue(Indices.back()->getType())){
426       Indices.pop_back();
427       if (GetElementPtrInst::getIndexedType(BaseType, Indices, true) == PVTy) {
428         if (Indices.size() == 0)
429           Res = new CastInst(GEP->getPointerOperand(), BaseType); // NOOP CAST
430         else
431           Res = new GetElementPtrInst(GEP->getPointerOperand(), Indices, Name);
432         break;
433       }
434     }
435
436     // Otherwise, it could be that we have something like this:
437     //     getelementptr [[sbyte] *] * %reg115, uint %reg138    ; [sbyte]**
438     // and want to convert it into something like this:
439     //     getelemenptr [[int] *] * %reg115, uint %reg138      ; [int]**
440     //
441     if (Res == 0) {
442       const PointerType *NewSrcTy = PointerType::get(PVTy);
443       std::vector<Value*> Indices(GEP->idx_begin(), GEP->idx_end());
444       Res = new GetElementPtrInst(Constant::getNullValue(NewSrcTy),
445                                   Indices, Name);
446       VMC.ExprMap[I] = Res;
447       Res->setOperand(0, ConvertExpressionToType(I->getOperand(0),
448                                                  NewSrcTy, VMC, TD));
449     }
450
451
452     assert(Res && "Didn't find match!");
453     break;
454   }
455
456   case Instruction::Call: {
457     assert(!isa<Function>(I->getOperand(0)));
458
459     // If this is a function pointer, we can convert the return type if we can
460     // convert the source function pointer.
461     //
462     const PointerType *PT = cast<PointerType>(I->getOperand(0)->getType());
463     const FunctionType *FT = cast<FunctionType>(PT->getElementType());
464     std::vector<const Type *> ArgTys(FT->param_begin(), FT->param_end());
465     const FunctionType *NewTy =
466       FunctionType::get(Ty, ArgTys, FT->isVarArg());
467     const PointerType *NewPTy = PointerType::get(NewTy);
468     if (Ty == Type::VoidTy)
469       Name = "";  // Make sure not to name calls that now return void!
470
471     Res = new CallInst(Constant::getNullValue(NewPTy),
472                        std::vector<Value*>(I->op_begin()+1, I->op_end()),
473                        Name);
474     if (cast<CallInst>(I)->isTailCall())
475       cast<CallInst>(Res)->setTailCall();
476     cast<CallInst>(Res)->setCallingConv(cast<CallInst>(I)->getCallingConv());
477     VMC.ExprMap[I] = Res;
478     Res->setOperand(0, ConvertExpressionToType(I->getOperand(0),NewPTy,VMC,TD));
479     break;
480   }
481   default:
482     assert(0 && "Expression convertible, but don't know how to convert?");
483     return 0;
484   }
485
486   assert(Res->getType() == Ty && "Didn't convert expr to correct type!");
487
488   BB->getInstList().insert(I, Res);
489
490   // Add the instruction to the expression map
491   VMC.ExprMap[I] = Res;
492
493
494   //// WTF is this code!  FIXME: remove this.
495   unsigned NumUses = I->getNumUses();
496   for (unsigned It = 0; It < NumUses; ) {
497     unsigned OldSize = NumUses;
498     Value::use_iterator UI = I->use_begin();
499     std::advance(UI, It);
500     ConvertOperandToType(*UI, I, Res, VMC, TD);
501     NumUses = I->getNumUses();
502     if (NumUses == OldSize) ++It;
503   }
504
505   DEBUG(std::cerr << "ExpIn: " << (void*)I << " " << *I
506                   << "ExpOut: " << (void*)Res << " " << *Res);
507
508   return Res;
509 }
510
511
512
513 // ValueConvertibleToType - Return true if it is possible
514 bool llvm::ValueConvertibleToType(Value *V, const Type *Ty,
515                                   ValueTypeCache &ConvertedTypes,
516                                   const TargetData &TD) {
517   ValueTypeCache::iterator I = ConvertedTypes.find(V);
518   if (I != ConvertedTypes.end()) return I->second == Ty;
519   ConvertedTypes[V] = Ty;
520
521   // It is safe to convert the specified value to the specified type IFF all of
522   // the uses of the value can be converted to accept the new typed value.
523   //
524   if (V->getType() != Ty) {
525     for (Value::use_iterator I = V->use_begin(), E = V->use_end(); I != E; ++I)
526       if (!OperandConvertibleToType(*I, V, Ty, ConvertedTypes, TD))
527         return false;
528   }
529
530   return true;
531 }
532
533
534
535
536
537 // OperandConvertibleToType - Return true if it is possible to convert operand
538 // V of User (instruction) U to the specified type.  This is true iff it is
539 // possible to change the specified instruction to accept this.  CTMap is a map
540 // of converted types, so that circular definitions will see the future type of
541 // the expression, not the static current type.
542 //
543 static bool OperandConvertibleToType(User *U, Value *V, const Type *Ty,
544                                      ValueTypeCache &CTMap,
545                                      const TargetData &TD) {
546   //  if (V->getType() == Ty) return true;   // Operand already the right type?
547
548   // Expression type must be holdable in a register.
549   if (!Ty->isFirstClassType())
550     return false;
551
552   Instruction *I = dyn_cast<Instruction>(U);
553   if (I == 0) return false;              // We can't convert!
554
555   switch (I->getOpcode()) {
556   case Instruction::Cast:
557     assert(I->getOperand(0) == V);
558     // We can convert the expr if the cast destination type is losslessly
559     // convertible to the requested type.
560     // Also, do not change a cast that is a noop cast.  For all intents and
561     // purposes it should be eliminated.
562     if (!Ty->isLosslesslyConvertibleTo(I->getOperand(0)->getType()) ||
563         I->getType() == I->getOperand(0)->getType())
564       return false;
565
566     // Do not allow a 'cast ushort %V to uint' to have it's first operand be
567     // converted to a 'short' type.  Doing so changes the way sign promotion
568     // happens, and breaks things.  Only allow the cast to take place if the
569     // signedness doesn't change... or if the current cast is not a lossy
570     // conversion.
571     //
572     if (!I->getType()->isLosslesslyConvertibleTo(I->getOperand(0)->getType()) &&
573         I->getOperand(0)->getType()->isSigned() != Ty->isSigned())
574       return false;
575
576     // We also do not allow conversion of a cast that casts from a ptr to array
577     // of X to a *X.  For example: cast [4 x %List *] * %val to %List * *
578     //
579     if (const PointerType *SPT =
580         dyn_cast<PointerType>(I->getOperand(0)->getType()))
581       if (const PointerType *DPT = dyn_cast<PointerType>(I->getType()))
582         if (const ArrayType *AT = dyn_cast<ArrayType>(SPT->getElementType()))
583           if (AT->getElementType() == DPT->getElementType())
584             return false;
585     return true;
586
587   case Instruction::Add:
588   case Instruction::Sub: {
589     if (!Ty->isInteger() && !Ty->isFloatingPoint()) return false;
590
591     Value *OtherOp = I->getOperand((V == I->getOperand(0)) ? 1 : 0);
592     return ValueConvertibleToType(I, Ty, CTMap, TD) &&
593            ExpressionConvertibleToType(OtherOp, Ty, CTMap, TD);
594   }
595   case Instruction::SetEQ:
596   case Instruction::SetNE: {
597     Value *OtherOp = I->getOperand((V == I->getOperand(0)) ? 1 : 0);
598     return ExpressionConvertibleToType(OtherOp, Ty, CTMap, TD);
599   }
600   case Instruction::Shr:
601     if (Ty->isSigned() != V->getType()->isSigned()) return false;
602     // FALL THROUGH
603   case Instruction::Shl:
604     if (I->getOperand(1) == V) return false;  // Cannot change shift amount type
605     if (!Ty->isInteger()) return false;
606     return ValueConvertibleToType(I, Ty, CTMap, TD);
607
608   case Instruction::Free:
609     assert(I->getOperand(0) == V);
610     return isa<PointerType>(Ty);    // Free can free any pointer type!
611
612   case Instruction::Load:
613     // Cannot convert the types of any subscripts...
614     if (I->getOperand(0) != V) return false;
615
616     if (const PointerType *PT = dyn_cast<PointerType>(Ty)) {
617       LoadInst *LI = cast<LoadInst>(I);
618
619       const Type *LoadedTy = PT->getElementType();
620
621       // They could be loading the first element of a composite type...
622       if (const CompositeType *CT = dyn_cast<CompositeType>(LoadedTy)) {
623         unsigned Offset = 0;     // No offset, get first leaf.
624         std::vector<Value*> Indices;  // Discarded...
625         LoadedTy = getStructOffsetType(CT, Offset, Indices, TD, false);
626         assert(Offset == 0 && "Offset changed from zero???");
627       }
628
629       if (!LoadedTy->isFirstClassType())
630         return false;
631
632       if (TD.getTypeSize(LoadedTy) != TD.getTypeSize(LI->getType()))
633         return false;
634
635       return ValueConvertibleToType(LI, LoadedTy, CTMap, TD);
636     }
637     return false;
638
639   case Instruction::Store: {
640     StoreInst *SI = cast<StoreInst>(I);
641
642     if (V == I->getOperand(0)) {
643       ValueTypeCache::iterator CTMI = CTMap.find(I->getOperand(1));
644       if (CTMI != CTMap.end()) {   // Operand #1 is in the table already?
645         // If so, check to see if it's Ty*, or, more importantly, if it is a
646         // pointer to a structure where the first element is a Ty... this code
647         // is necessary because we might be trying to change the source and
648         // destination type of the store (they might be related) and the dest
649         // pointer type might be a pointer to structure.  Below we allow pointer
650         // to structures where the 0th element is compatible with the value,
651         // now we have to support the symmetrical part of this.
652         //
653         const Type *ElTy = cast<PointerType>(CTMI->second)->getElementType();
654
655         // Already a pointer to what we want?  Trivially accept...
656         if (ElTy == Ty) return true;
657
658         // Tricky case now, if the destination is a pointer to structure,
659         // obviously the source is not allowed to be a structure (cannot copy
660         // a whole structure at a time), so the level raiser must be trying to
661         // store into the first field.  Check for this and allow it now:
662         //
663         if (const StructType *SElTy = dyn_cast<StructType>(ElTy)) {
664           unsigned Offset = 0;
665           std::vector<Value*> Indices;
666           ElTy = getStructOffsetType(ElTy, Offset, Indices, TD, false);
667           assert(Offset == 0 && "Offset changed!");
668           if (ElTy == 0)    // Element at offset zero in struct doesn't exist!
669             return false;   // Can only happen for {}*
670
671           if (ElTy == Ty)   // Looks like the 0th element of structure is
672             return true;    // compatible!  Accept now!
673
674           // Otherwise we know that we can't work, so just stop trying now.
675           return false;
676         }
677       }
678
679       // Can convert the store if we can convert the pointer operand to match
680       // the new  value type...
681       return ExpressionConvertibleToType(I->getOperand(1), PointerType::get(Ty),
682                                          CTMap, TD);
683     } else if (const PointerType *PT = dyn_cast<PointerType>(Ty)) {
684       const Type *ElTy = PT->getElementType();
685       assert(V == I->getOperand(1));
686
687       if (isa<StructType>(ElTy)) {
688         // We can change the destination pointer if we can store our first
689         // argument into the first element of the structure...
690         //
691         unsigned Offset = 0;
692         std::vector<Value*> Indices;
693         ElTy = getStructOffsetType(ElTy, Offset, Indices, TD, false);
694         assert(Offset == 0 && "Offset changed!");
695         if (ElTy == 0)    // Element at offset zero in struct doesn't exist!
696           return false;   // Can only happen for {}*
697       }
698
699       // Must move the same amount of data...
700       if (!ElTy->isSized() ||
701           TD.getTypeSize(ElTy) != TD.getTypeSize(I->getOperand(0)->getType()))
702         return false;
703
704       // Can convert store if the incoming value is convertible and if the
705       // result will preserve semantics...
706       const Type *Op0Ty = I->getOperand(0)->getType();
707       if (!(Op0Ty->isIntegral() ^ ElTy->isIntegral()) &&
708           !(Op0Ty->isFloatingPoint() ^ ElTy->isFloatingPoint()))
709         return ExpressionConvertibleToType(I->getOperand(0), ElTy, CTMap, TD);
710     }
711     return false;
712   }
713
714   case Instruction::PHI: {
715     PHINode *PN = cast<PHINode>(I);
716     // Be conservative if we find a giant PHI node.
717     if (PN->getNumIncomingValues() > 32) return false;
718
719     for (unsigned i = 0; i < PN->getNumIncomingValues(); ++i)
720       if (!ExpressionConvertibleToType(PN->getIncomingValue(i), Ty, CTMap, TD))
721         return false;
722     return ValueConvertibleToType(PN, Ty, CTMap, TD);
723   }
724
725   case Instruction::Call: {
726     User::op_iterator OI = std::find(I->op_begin(), I->op_end(), V);
727     assert (OI != I->op_end() && "Not using value!");
728     unsigned OpNum = OI - I->op_begin();
729
730     // Are we trying to change the function pointer value to a new type?
731     if (OpNum == 0) {
732       const PointerType *PTy = dyn_cast<PointerType>(Ty);
733       if (PTy == 0) return false;  // Can't convert to a non-pointer type...
734       const FunctionType *FTy = dyn_cast<FunctionType>(PTy->getElementType());
735       if (FTy == 0) return false;  // Can't convert to a non ptr to function...
736
737       // Do not allow converting to a call where all of the operands are ...'s
738       if (FTy->getNumParams() == 0 && FTy->isVarArg())
739         return false;              // Do not permit this conversion!
740
741       // Perform sanity checks to make sure that new function type has the
742       // correct number of arguments...
743       //
744       unsigned NumArgs = I->getNumOperands()-1;  // Don't include function ptr
745
746       // Cannot convert to a type that requires more fixed arguments than
747       // the call provides...
748       //
749       if (NumArgs < FTy->getNumParams()) return false;
750
751       // Unless this is a vararg function type, we cannot provide more arguments
752       // than are desired...
753       //
754       if (!FTy->isVarArg() && NumArgs > FTy->getNumParams())
755         return false;
756
757       // Okay, at this point, we know that the call and the function type match
758       // number of arguments.  Now we see if we can convert the arguments
759       // themselves.  Note that we do not require operands to be convertible,
760       // we can insert casts if they are convertible but not compatible.  The
761       // reason for this is that we prefer to have resolved functions but casted
762       // arguments if possible.
763       //
764       for (unsigned i = 0, NA = FTy->getNumParams(); i < NA; ++i)
765         if (!FTy->getParamType(i)->isLosslesslyConvertibleTo(I->getOperand(i+1)->getType()))
766           return false;   // Operands must have compatible types!
767
768       // Okay, at this point, we know that all of the arguments can be
769       // converted.  We succeed if we can change the return type if
770       // necessary...
771       //
772       return ValueConvertibleToType(I, FTy->getReturnType(), CTMap, TD);
773     }
774
775     const PointerType *MPtr = cast<PointerType>(I->getOperand(0)->getType());
776     const FunctionType *FTy = cast<FunctionType>(MPtr->getElementType());
777     if (!FTy->isVarArg()) return false;
778
779     if ((OpNum-1) < FTy->getNumParams())
780       return false;  // It's not in the varargs section...
781
782     // If we get this far, we know the value is in the varargs section of the
783     // function!  We can convert if we don't reinterpret the value...
784     //
785     return Ty->isLosslesslyConvertibleTo(V->getType());
786   }
787   }
788   return false;
789 }
790
791
792 void llvm::ConvertValueToNewType(Value *V, Value *NewVal, ValueMapCache &VMC,
793                                  const TargetData &TD) {
794   ValueHandle VH(VMC, V);
795
796   // FIXME: This is horrible!
797   unsigned NumUses = V->getNumUses();
798   for (unsigned It = 0; It < NumUses; ) {
799     unsigned OldSize = NumUses;
800     Value::use_iterator UI = V->use_begin();
801     std::advance(UI, It);
802     ConvertOperandToType(*UI, V, NewVal, VMC, TD);
803     NumUses = V->getNumUses();
804     if (NumUses == OldSize) ++It;
805   }
806 }
807
808
809
810 static void ConvertOperandToType(User *U, Value *OldVal, Value *NewVal,
811                                  ValueMapCache &VMC, const TargetData &TD) {
812   if (isa<ValueHandle>(U)) return;  // Valuehandles don't let go of operands...
813
814   if (VMC.OperandsMapped.count(U)) return;
815   VMC.OperandsMapped.insert(U);
816
817   ValueMapCache::ExprMapTy::iterator VMCI = VMC.ExprMap.find(U);
818   if (VMCI != VMC.ExprMap.end())
819     return;
820
821
822   Instruction *I = cast<Instruction>(U);  // Only Instructions convertible
823
824   BasicBlock *BB = I->getParent();
825   assert(BB != 0 && "Instruction not embedded in basic block!");
826   std::string Name = I->getName();
827   I->setName("");
828   Instruction *Res;     // Result of conversion
829
830   //std::cerr << endl << endl << "Type:\t" << Ty << "\nInst: " << I
831   //          << "BB Before: " << BB << endl;
832
833   // Prevent I from being removed...
834   ValueHandle IHandle(VMC, I);
835
836   const Type *NewTy = NewVal->getType();
837   Constant *Dummy = (NewTy != Type::VoidTy) ?
838                   Constant::getNullValue(NewTy) : 0;
839
840   switch (I->getOpcode()) {
841   case Instruction::Cast:
842     if (VMC.NewCasts.count(ValueHandle(VMC, I))) {
843       // This cast has already had it's value converted, causing a new cast to
844       // be created.  We don't want to create YET ANOTHER cast instruction
845       // representing the original one, so just modify the operand of this cast
846       // instruction, which we know is newly created.
847       I->setOperand(0, NewVal);
848       I->setName(Name);  // give I its name back
849       return;
850
851     } else {
852       Res = new CastInst(NewVal, I->getType(), Name);
853     }
854     break;
855
856   case Instruction::Add:
857   case Instruction::Sub:
858   case Instruction::SetEQ:
859   case Instruction::SetNE: {
860     Res = BinaryOperator::create(cast<BinaryOperator>(I)->getOpcode(),
861                                  Dummy, Dummy, Name);
862     VMC.ExprMap[I] = Res;   // Add node to expression eagerly
863
864     unsigned OtherIdx = (OldVal == I->getOperand(0)) ? 1 : 0;
865     Value *OtherOp    = I->getOperand(OtherIdx);
866     Res->setOperand(!OtherIdx, NewVal);
867     Value *NewOther   = ConvertExpressionToType(OtherOp, NewTy, VMC, TD);
868     Res->setOperand(OtherIdx, NewOther);
869     break;
870   }
871   case Instruction::Shl:
872   case Instruction::Shr:
873     assert(I->getOperand(0) == OldVal);
874     Res = new ShiftInst(cast<ShiftInst>(I)->getOpcode(), NewVal,
875                         I->getOperand(1), Name);
876     break;
877
878   case Instruction::Free:            // Free can free any pointer type!
879     assert(I->getOperand(0) == OldVal);
880     Res = new FreeInst(NewVal);
881     break;
882
883
884   case Instruction::Load: {
885     assert(I->getOperand(0) == OldVal && isa<PointerType>(NewVal->getType()));
886     const Type *LoadedTy =
887       cast<PointerType>(NewVal->getType())->getElementType();
888
889     Value *Src = NewVal;
890
891     if (const CompositeType *CT = dyn_cast<CompositeType>(LoadedTy)) {
892       std::vector<Value*> Indices;
893       Indices.push_back(Constant::getNullValue(Type::UIntTy));
894
895       unsigned Offset = 0;   // No offset, get first leaf.
896       LoadedTy = getStructOffsetType(CT, Offset, Indices, TD, false);
897       assert(LoadedTy->isFirstClassType());
898
899       if (Indices.size() != 1) {     // Do not generate load X, 0
900         // Insert the GEP instruction before this load.
901         Src = new GetElementPtrInst(Src, Indices, Name+".idx", I);
902       }
903     }
904
905     Res = new LoadInst(Src, Name);
906     assert(Res->getType()->isFirstClassType() && "Load of structure or array!");
907     break;
908   }
909
910   case Instruction::Store: {
911     if (I->getOperand(0) == OldVal) {  // Replace the source value
912       // Check to see if operand #1 has already been converted...
913       ValueMapCache::ExprMapTy::iterator VMCI =
914         VMC.ExprMap.find(I->getOperand(1));
915       if (VMCI != VMC.ExprMap.end()) {
916         // Comments describing this stuff are in the OperandConvertibleToType
917         // switch statement for Store...
918         //
919         const Type *ElTy =
920           cast<PointerType>(VMCI->second->getType())->getElementType();
921
922         Value *SrcPtr = VMCI->second;
923
924         if (ElTy != NewTy) {
925           // We check that this is a struct in the initial scan...
926           const StructType *SElTy = cast<StructType>(ElTy);
927
928           std::vector<Value*> Indices;
929           Indices.push_back(Constant::getNullValue(Type::UIntTy));
930
931           unsigned Offset = 0;
932           const Type *Ty = getStructOffsetType(ElTy, Offset, Indices, TD,false);
933           assert(Offset == 0 && "Offset changed!");
934           assert(NewTy == Ty && "Did not convert to correct type!");
935
936           // Insert the GEP instruction before this store.
937           SrcPtr = new GetElementPtrInst(SrcPtr, Indices,
938                                          SrcPtr->getName()+".idx", I);
939         }
940         Res = new StoreInst(NewVal, SrcPtr);
941
942         VMC.ExprMap[I] = Res;
943       } else {
944         // Otherwise, we haven't converted Operand #1 over yet...
945         const PointerType *NewPT = PointerType::get(NewTy);
946         Res = new StoreInst(NewVal, Constant::getNullValue(NewPT));
947         VMC.ExprMap[I] = Res;
948         Res->setOperand(1, ConvertExpressionToType(I->getOperand(1),
949                                                    NewPT, VMC, TD));
950       }
951     } else {                           // Replace the source pointer
952       const Type *ValTy = cast<PointerType>(NewTy)->getElementType();
953
954       Value *SrcPtr = NewVal;
955
956       if (isa<StructType>(ValTy)) {
957         std::vector<Value*> Indices;
958         Indices.push_back(Constant::getNullValue(Type::UIntTy));
959
960         unsigned Offset = 0;
961         ValTy = getStructOffsetType(ValTy, Offset, Indices, TD, false);
962
963         assert(Offset == 0 && ValTy);
964
965         // Insert the GEP instruction before this store.
966         SrcPtr = new GetElementPtrInst(SrcPtr, Indices,
967                                        SrcPtr->getName()+".idx", I);
968       }
969
970       Res = new StoreInst(Constant::getNullValue(ValTy), SrcPtr);
971       VMC.ExprMap[I] = Res;
972       Res->setOperand(0, ConvertExpressionToType(I->getOperand(0),
973                                                  ValTy, VMC, TD));
974     }
975     break;
976   }
977
978   case Instruction::PHI: {
979     PHINode *OldPN = cast<PHINode>(I);
980     PHINode *NewPN = new PHINode(NewTy, Name);
981     VMC.ExprMap[I] = NewPN;
982
983     while (OldPN->getNumOperands()) {
984       BasicBlock *BB = OldPN->getIncomingBlock(0);
985       Value *OldVal = OldPN->getIncomingValue(0);
986       ValueHandle OldValHandle(VMC, OldVal);
987       OldPN->removeIncomingValue(BB, false);
988       Value *V = ConvertExpressionToType(OldVal, NewTy, VMC, TD);
989       NewPN->addIncoming(V, BB);
990     }
991     Res = NewPN;
992     break;
993   }
994
995   case Instruction::Call: {
996     Value *Meth = I->getOperand(0);
997     std::vector<Value*> Params(I->op_begin()+1, I->op_end());
998
999     if (Meth == OldVal) {   // Changing the function pointer?
1000       const PointerType *NewPTy = cast<PointerType>(NewVal->getType());
1001       const FunctionType *NewTy = cast<FunctionType>(NewPTy->getElementType());
1002
1003       if (NewTy->getReturnType() == Type::VoidTy)
1004         Name = "";  // Make sure not to name a void call!
1005
1006       // Get an iterator to the call instruction so that we can insert casts for
1007       // operands if need be.  Note that we do not require operands to be
1008       // convertible, we can insert casts if they are convertible but not
1009       // compatible.  The reason for this is that we prefer to have resolved
1010       // functions but casted arguments if possible.
1011       //
1012       BasicBlock::iterator It = I;
1013
1014       // Convert over all of the call operands to their new types... but only
1015       // convert over the part that is not in the vararg section of the call.
1016       //
1017       for (unsigned i = 0; i != NewTy->getNumParams(); ++i)
1018         if (Params[i]->getType() != NewTy->getParamType(i)) {
1019           // Create a cast to convert it to the right type, we know that this
1020           // is a lossless cast...
1021           //
1022           Params[i] = new CastInst(Params[i], NewTy->getParamType(i),
1023                                    "callarg.cast." +
1024                                    Params[i]->getName(), It);
1025         }
1026       Meth = NewVal;  // Update call destination to new value
1027
1028     } else {                   // Changing an argument, must be in vararg area
1029       std::vector<Value*>::iterator OI =
1030         std::find(Params.begin(), Params.end(), OldVal);
1031       assert (OI != Params.end() && "Not using value!");
1032
1033       *OI = NewVal;
1034     }
1035
1036     Res = new CallInst(Meth, Params, Name);
1037     if (cast<CallInst>(I)->isTailCall())
1038       cast<CallInst>(Res)->setTailCall();
1039     cast<CallInst>(Res)->setCallingConv(cast<CallInst>(I)->getCallingConv());
1040     break;
1041   }
1042   default:
1043     assert(0 && "Expression convertible, but don't know how to convert?");
1044     return;
1045   }
1046
1047   // If the instruction was newly created, insert it into the instruction
1048   // stream.
1049   //
1050   BasicBlock::iterator It = I;
1051   assert(It != BB->end() && "Instruction not in own basic block??");
1052   BB->getInstList().insert(It, Res);   // Keep It pointing to old instruction
1053
1054   DEBUG(std::cerr << "COT CREATED: "  << (void*)Res << " " << *Res
1055                   << "In: " << (void*)I << " " << *I << "Out: " << (void*)Res
1056                   << " " << *Res);
1057
1058   // Add the instruction to the expression map
1059   VMC.ExprMap[I] = Res;
1060
1061   if (I->getType() != Res->getType())
1062     ConvertValueToNewType(I, Res, VMC, TD);
1063   else {
1064     for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
1065          UI != E; )
1066       if (isa<ValueHandle>(*UI)) {
1067         ++UI;
1068       } else {
1069         Use &U = UI.getUse();
1070         ++UI;  // Do not invalidate UI.
1071         U.set(Res);
1072       }
1073   }
1074 }
1075
1076
1077 ValueHandle::ValueHandle(ValueMapCache &VMC, Value *V)
1078   : Instruction(Type::VoidTy, UserOp1, &Op, 1, ""), Op(V, this), Cache(VMC) {
1079   //DEBUG(std::cerr << "VH AQUIRING: " << (void*)V << " " << V);
1080 }
1081
1082 ValueHandle::ValueHandle(const ValueHandle &VH)
1083   : Instruction(Type::VoidTy, UserOp1, &Op, 1, ""),
1084     Op(VH.Op, this), Cache(VH.Cache) {
1085   //DEBUG(std::cerr << "VH AQUIRING: " << (void*)V << " " << V);
1086 }
1087
1088 static void RecursiveDelete(ValueMapCache &Cache, Instruction *I) {
1089   if (!I || !I->use_empty()) return;
1090
1091   assert(I->getParent() && "Inst not in basic block!");
1092
1093   //DEBUG(std::cerr << "VH DELETING: " << (void*)I << " " << I);
1094
1095   for (User::op_iterator OI = I->op_begin(), OE = I->op_end();
1096        OI != OE; ++OI)
1097     if (Instruction *U = dyn_cast<Instruction>(OI)) {
1098       *OI = 0;
1099       RecursiveDelete(Cache, U);
1100     }
1101
1102   I->getParent()->getInstList().remove(I);
1103
1104   Cache.OperandsMapped.erase(I);
1105   Cache.ExprMap.erase(I);
1106   delete I;
1107 }
1108
1109 ValueHandle::~ValueHandle() {
1110   if (Op->hasOneUse()) {
1111     Value *V = Op;
1112     Op.set(0);   // Drop use!
1113
1114     // Now we just need to remove the old instruction so we don't get infinite
1115     // loops.  Note that we cannot use DCE because DCE won't remove a store
1116     // instruction, for example.
1117     //
1118     RecursiveDelete(Cache, dyn_cast<Instruction>(V));
1119   } else {
1120     //DEBUG(std::cerr << "VH RELEASING: " << (void*)Operands[0].get() << " "
1121     //                << Operands[0]->getNumUses() << " " << Operands[0]);
1122   }
1123 }
1124