5c94f8c729bd8b721e30314a65b8ff5d642561c9
[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/Method.h"
11 #include "llvm/Support/STLExtras.h"
12 #include "llvm/iOther.h"
13 #include "llvm/iMemory.h"
14 #include "llvm/ConstPoolVals.h"
15 #include "llvm/Optimizations/ConstantHandling.h"
16 #include "llvm/Optimizations/DCE.h"
17 #include <map>
18 #include <algorithm>
19
20 #include "llvm/Assembly/Writer.h"
21
22 //#define DEBUG_EXPR_CONVERT 1
23
24 static inline const Type *getTy(const Value *V, ValueTypeCache &CT) {
25   ValueTypeCache::iterator I = CT.find(V);
26   if (I == CT.end()) return V->getType();
27   return I->second;
28 }
29
30
31 static bool OperandConvertableToType(User *U, Value *V, const Type *Ty,
32                                      ValueTypeCache &ConvertedTypes);
33
34 static void ConvertOperandToType(User *U, Value *OldVal, Value *NewVal,
35                                  ValueMapCache &VMC);
36
37
38 // ExpressionConvertableToType - Return true if it is possible
39 static bool ExpressionConvertableToType(Value *V, const Type *Ty,
40                                         ValueTypeCache &CTMap) {
41   ValueTypeCache::iterator CTMI = CTMap.find(V);
42   if (CTMI != CTMap.end()) return CTMI->second == Ty;
43   CTMap[V] = Ty;
44
45   // Expressions are only convertable if all of the users of the expression can
46   // have this value converted.  This makes use of the map to avoid infinite
47   // recursion.
48   //
49   for (Value::use_iterator I = V->use_begin(), E = V->use_end(); I != E; ++I)
50     if (!OperandConvertableToType(*I, V, Ty, CTMap))
51       return false;
52
53   Instruction *I = dyn_cast<Instruction>(V);
54   if (I == 0) {
55     // It's not an instruction, check to see if it's a constant... all constants
56     // can be converted to an equivalent value (except pointers, they can't be
57     // const prop'd in general).
58     //
59     if (isa<ConstPoolVal>(V) &&
60         !isa<PointerType>(V->getType()) && !isa<PointerType>(Ty)) return true;
61
62     return false;              // Otherwise, we can't convert!
63   }
64   if (I->getType() == Ty) return false;  // Expression already correct type!
65
66   switch (I->getOpcode()) {
67   case Instruction::Cast:
68     // We can convert the expr if the cast destination type is losslessly
69     // convertable to the requested type.
70     return losslessCastableTypes(Ty, I->getType());
71
72   case Instruction::Add:
73   case Instruction::Sub:
74     return ExpressionConvertableToType(I->getOperand(0), Ty, CTMap) &&
75            ExpressionConvertableToType(I->getOperand(1), Ty, CTMap);
76   case Instruction::Shr:
77     if (Ty->isSigned() != V->getType()->isSigned()) return false;
78     // FALL THROUGH
79   case Instruction::Shl:
80     return ExpressionConvertableToType(I->getOperand(0), Ty, CTMap);
81
82   case Instruction::Load: {
83     LoadInst *LI = cast<LoadInst>(I);
84     if (LI->hasIndices()) return false;
85     return ExpressionConvertableToType(LI->getPtrOperand(),
86                                        PointerType::get(Ty), CTMap);
87   }
88   case Instruction::GetElementPtr: {
89     // GetElementPtr's are directly convertable to a pointer type if they have
90     // a number of zeros at the end.  Because removing these values does not
91     // change the logical offset of the GEP, it is okay and fair to remove them.
92     // This can change this:
93     //   %t1 = getelementptr %Hosp * %hosp, ubyte 4, ubyte 0  ; <%List **>
94     //   %t2 = cast %List * * %t1 to %List *
95     // into
96     //   %t2 = getelementptr %Hosp * %hosp, ubyte 4           ; <%List *>
97     // 
98     GetElementPtrInst *GEP = cast<GetElementPtrInst>(I);
99     const PointerType *PTy = dyn_cast<PointerType>(Ty);
100     if (!PTy) return false;
101
102     // Check to see if there are zero elements that we can remove from the
103     // index array.  If there are, check to see if removing them causes us to
104     // get to the right type...
105     //
106     vector<ConstPoolVal*> Indices = GEP->getIndices();
107     const Type *BaseType = GEP->getPtrOperand()->getType();
108
109     while (Indices.size() &&
110            cast<ConstPoolUInt>(Indices.back())->getValue() == 0) {
111       Indices.pop_back();
112       const Type *ElTy = GetElementPtrInst::getIndexedType(BaseType, Indices,
113                                                            true);
114       if (ElTy == PTy->getValueType())
115         return true;  // Found a match!!
116     }
117     break;   // No match, maybe next time.
118   }
119   }
120   return false;
121 }
122
123
124
125
126 static Value *ConvertExpressionToType(Value *V, const Type *Ty,
127                                       ValueMapCache &VMC) {
128   ValueMapCache::ExprMapTy::iterator VMCI = VMC.ExprMap.find(V);
129   if (VMCI != VMC.ExprMap.end())
130     return VMCI->second;
131
132   Instruction *I = dyn_cast<Instruction>(V);
133   if (I == 0)
134     if (ConstPoolVal *CPV = cast<ConstPoolVal>(V)) {
135       // Constants are converted by constant folding the cast that is required.
136       // We assume here that all casts are implemented for constant prop.
137       Value *Result = opt::ConstantFoldCastInstruction(CPV, Ty);
138       if (!Result) cerr << "Couldn't fold " << CPV << " to " << Ty << endl;
139       assert(Result && "ConstantFoldCastInstruction Failed!!!");
140
141       // Add the instruction to the expression map
142       VMC.ExprMap[V] = Result;
143       return Result;
144     }
145
146
147   BasicBlock *BB = I->getParent();
148   BasicBlock::InstListType &BIL = BB->getInstList();
149   string Name = I->getName();  if (!Name.empty()) I->setName("");
150   Instruction *Res;     // Result of conversion
151
152   //cerr << endl << endl << "Type:\t" << Ty << "\nInst: " << I << "BB Before: " << BB << endl;
153
154   switch (I->getOpcode()) {
155   case Instruction::Cast:
156     Res = new CastInst(I->getOperand(0), Ty, Name);
157     break;
158     
159   case Instruction::Add:
160   case Instruction::Sub:
161     Res = BinaryOperator::create(cast<BinaryOperator>(I)->getOpcode(),
162                              ConvertExpressionToType(I->getOperand(0), Ty, VMC),
163                              ConvertExpressionToType(I->getOperand(1), Ty, VMC),
164                                  Name);
165     break;
166
167   case Instruction::Shl:
168   case Instruction::Shr:
169     Res = new ShiftInst(cast<ShiftInst>(I)->getOpcode(),
170                         ConvertExpressionToType(I->getOperand(0), Ty, VMC),
171                         I->getOperand(1), Name);
172     break;
173
174   case Instruction::Load: {
175     LoadInst *LI = cast<LoadInst>(I);
176     assert(!LI->hasIndices());
177     Res = new LoadInst(ConvertExpressionToType(LI->getPtrOperand(),
178                                                PointerType::get(Ty), VMC),
179                        Name);
180     break;
181   }
182
183   case Instruction::GetElementPtr: {
184     // GetElementPtr's are directly convertable to a pointer type if they have
185     // a number of zeros at the end.  Because removing these values does not
186     // change the logical offset of the GEP, it is okay and fair to remove them.
187     // This can change this:
188     //   %t1 = getelementptr %Hosp * %hosp, ubyte 4, ubyte 0  ; <%List **>
189     //   %t2 = cast %List * * %t1 to %List *
190     // into
191     //   %t2 = getelementptr %Hosp * %hosp, ubyte 4           ; <%List *>
192     // 
193     GetElementPtrInst *GEP = cast<GetElementPtrInst>(I);
194
195     // Check to see if there are zero elements that we can remove from the
196     // index array.  If there are, check to see if removing them causes us to
197     // get to the right type...
198     //
199     vector<ConstPoolVal*> Indices = GEP->getIndices();
200     const Type *BaseType = GEP->getPtrOperand()->getType();
201     const Type *PVTy = cast<PointerType>(Ty)->getValueType();
202     Res = 0;
203     while (Indices.size() &&
204            cast<ConstPoolUInt>(Indices.back())->getValue() == 0) {
205       Indices.pop_back();
206       if (GetElementPtrInst::getIndexedType(BaseType, Indices, true) == PVTy) {
207         if (Indices.size() == 0) {
208           Res = new CastInst(GEP->getPtrOperand(), BaseType); // NOOP
209         } else {
210           Res = new GetElementPtrInst(GEP->getPtrOperand(), Indices, Name);
211         }
212         break;
213       }
214     }
215     assert(Res && "Didn't find match!");
216     break;   // No match, maybe next time.
217   }
218
219   default:
220     assert(0 && "Expression convertable, but don't know how to convert?");
221     return 0;
222   }
223
224   BasicBlock::iterator It = find(BIL.begin(), BIL.end(), I);
225   assert(It != BIL.end() && "Instruction not in own basic block??");
226   BIL.insert(It, Res);
227
228   // Add the instruction to the expression map
229   VMC.ExprMap[I] = Res;
230
231   // Expressions are only convertable if all of the users of the expression can
232   // have this value converted.  This makes use of the map to avoid infinite
233   // recursion.
234   //
235   unsigned NumUses = I->use_size();
236   for (unsigned It = 0; It < NumUses; ) {
237     unsigned OldSize = NumUses;
238     ConvertOperandToType(*(I->use_begin()+It), I, Res, VMC);
239     NumUses = I->use_size();
240     if (NumUses == OldSize) ++It;
241   }
242
243 #ifdef DEBUG_EXPR_CONVERT
244   cerr << "ExpIn: " << I << "ExpOut: " << Res;
245 #endif
246
247   return Res;
248 }
249
250
251
252 // RetValConvertableToType - Return true if it is possible
253 bool RetValConvertableToType(Value *V, const Type *Ty,
254                              ValueTypeCache &ConvertedTypes) {
255   ValueTypeCache::iterator I = ConvertedTypes.find(V);
256   if (I != ConvertedTypes.end()) return I->second == Ty;
257   ConvertedTypes[V] = Ty;
258
259   // It is safe to convert the specified value to the specified type IFF all of
260   // the uses of the value can be converted to accept the new typed value.
261   //
262   for (Value::use_iterator I = V->use_begin(), E = V->use_end(); I != E; ++I)
263     if (!OperandConvertableToType(*I, V, Ty, ConvertedTypes))
264       return false;
265
266   return true;
267 }
268
269
270
271
272
273
274
275 // OperandConvertableToType - Return true if it is possible to convert operand
276 // V of User (instruction) U to the specified type.  This is true iff it is
277 // possible to change the specified instruction to accept this.  CTMap is a map
278 // of converted types, so that circular definitions will see the future type of
279 // the expression, not the static current type.
280 //
281 static bool OperandConvertableToType(User *U, Value *V, const Type *Ty,
282                                      ValueTypeCache &CTMap) {
283   assert(V->getType() != Ty &&
284          "OperandConvertableToType: Operand is already right type!");
285   Instruction *I = dyn_cast<Instruction>(U);
286   if (I == 0) return false;              // We can't convert!
287
288   switch (I->getOpcode()) {
289   case Instruction::Cast:
290     assert(I->getOperand(0) == V);
291     // We can convert the expr if the cast destination type is losslessly
292     // convertable to the requested type.
293     return losslessCastableTypes(Ty, I->getOperand(0)->getType());
294
295   case Instruction::Add:
296   case Instruction::Sub: {
297     Value *OtherOp = I->getOperand((V == I->getOperand(0)) ? 1 : 0);
298     return RetValConvertableToType(I, Ty, CTMap) &&
299            ExpressionConvertableToType(OtherOp, Ty, CTMap);
300   }
301   case Instruction::SetEQ:
302   case Instruction::SetNE: {
303     Value *OtherOp = I->getOperand((V == I->getOperand(0)) ? 1 : 0);
304     return ExpressionConvertableToType(OtherOp, Ty, CTMap);
305   }
306   case Instruction::Shr:
307     if (Ty->isSigned() != V->getType()->isSigned()) return false;
308     // FALL THROUGH
309   case Instruction::Shl:
310     assert(I->getOperand(0) == V);
311     return RetValConvertableToType(I, Ty, CTMap);
312
313   case Instruction::Load:
314     assert(I->getOperand(0) == V);
315     if (const PointerType *PT = dyn_cast<PointerType>(Ty)) {
316       LoadInst *LI = cast<LoadInst>(I);
317       if (LI->hasIndices() || 
318           TD.getTypeSize(PT->getValueType()) != TD.getTypeSize(LI->getType()))
319         return false;
320
321       return RetValConvertableToType(LI, PT->getValueType(), CTMap);
322     }
323     return false;
324
325   case Instruction::Store: {
326     StoreInst *SI = cast<StoreInst>(I);
327     if (SI->hasIndices()) return false;
328
329     if (V == I->getOperand(0)) {
330       // Can convert the store if we can convert the pointer operand to match
331       // the new  value type...
332       return ExpressionConvertableToType(I->getOperand(1), PointerType::get(Ty),
333                                          CTMap);
334     } else if (const PointerType *PT = dyn_cast<PointerType>(Ty)) {
335       if (isa<ArrayType>(PT->getValueType()))
336         return false;  // Avoid getDataSize on unsized array type!
337       assert(V == I->getOperand(1));
338
339       // Must move the same amount of data...
340       if (TD.getTypeSize(PT->getValueType()) != 
341           TD.getTypeSize(I->getOperand(0)->getType())) return false;
342
343       // Can convert store if the incoming value is convertable...
344       return ExpressionConvertableToType(I->getOperand(0), PT->getValueType(),
345                                          CTMap);
346     }
347     return false;
348   }
349
350
351 #if 0
352   case Instruction::GetElementPtr: {
353     // GetElementPtr's are directly convertable to a pointer type if they have
354     // a number of zeros at the end.  Because removing these values does not
355     // change the logical offset of the GEP, it is okay and fair to remove them.
356     // This can change this:
357     //   %t1 = getelementptr %Hosp * %hosp, ubyte 4, ubyte 0  ; <%List **>
358     //   %t2 = cast %List * * %t1 to %List *
359     // into
360     //   %t2 = getelementptr %Hosp * %hosp, ubyte 4           ; <%List *>
361     // 
362     GetElementPtrInst *GEP = cast<GetElementPtrInst>(I);
363     const PointerType *PTy = dyn_cast<PointerType>(Ty);
364     if (!PTy) return false;
365
366     // Check to see if there are zero elements that we can remove from the
367     // index array.  If there are, check to see if removing them causes us to
368     // get to the right type...
369     //
370     vector<ConstPoolVal*> Indices = GEP->getIndices();
371     const Type *BaseType = GEP->getPtrOperand()->getType();
372
373     while (Indices.size() &&
374            cast<ConstPoolUInt>(Indices.back())->getValue() == 0) {
375       Indices.pop_back();
376       const Type *ElTy = GetElementPtrInst::getIndexedType(BaseType, Indices,
377                                                            true);
378       if (ElTy == PTy->getValueType())
379         return true;  // Found a match!!
380     }
381     break;   // No match, maybe next time.
382   }
383 #endif
384   }
385   return false;
386 }
387
388
389 void ConvertUsersType(Value *V, Value *NewVal, ValueMapCache &VMC) {
390   unsigned NumUses = V->use_size();
391   for (unsigned It = 0; It < NumUses; ) {
392     unsigned OldSize = NumUses;
393     ConvertOperandToType(*(V->use_begin()+It), V, NewVal, VMC);
394     NumUses = V->use_size();
395     if (NumUses == OldSize) ++It;
396   }
397
398   if (NumUses == 0)
399     if (Instruction *I = dyn_cast<Instruction>(V)) {
400       BasicBlock *BB = I->getParent();
401
402       // Now we just need to remove the old instruction so we don't get infinite
403       // loops.  Note that we cannot use DCE because DCE won't remove a store
404       // instruction, for example.
405       //
406       BasicBlock::iterator It = find(BB->begin(), BB->end(), I);
407       assert(It != BB->end() && "Instruction no longer in basic block??");
408 #ifdef DEBUG_EXPR_CONVERT
409       cerr << "DELETING: " << (void*)I << " " << I;
410 #endif
411       delete BB->getInstList().remove(It);
412     }
413 }
414
415
416
417 static void ConvertOperandToType(User *U, Value *OldVal, Value *NewVal,
418                                  ValueMapCache &VMC) {
419   if (isa<ValueHandle>(U)) return;  // Valuehandles don't let go of operands...
420
421   if (VMC.OperandsMapped.count(make_pair(U, OldVal))) return;
422
423   VMC.OperandsMapped.insert(make_pair(U, OldVal));
424
425   Instruction *I = cast<Instruction>(U);  // Only Instructions convertable
426
427   BasicBlock *BB = I->getParent();
428   BasicBlock::InstListType &BIL = BB->getInstList();
429   string Name = I->getName();  if (!Name.empty()) I->setName("");
430   Instruction *Res;     // Result of conversion
431
432   //cerr << endl << endl << "Type:\t" << Ty << "\nInst: " << I << "BB Before: " << BB << endl;
433
434   // Prevent I from being removed...
435   ValueHandle IHandle(I);
436 #ifdef DEBUG_EXPR_CONVERT
437   cerr << "VH AQUIRING: " << I;
438 #endif
439
440   switch (I->getOpcode()) {
441   case Instruction::Cast:
442     assert(I->getOperand(0) == OldVal);
443     Res = new CastInst(NewVal, I->getType(), Name);
444     break;
445
446   case Instruction::Add:
447   case Instruction::Sub:
448   case Instruction::SetEQ:
449   case Instruction::SetNE: {
450     unsigned OtherIdx = (OldVal == I->getOperand(0)) ? 1 : 0;
451     Value *OtherOp    = I->getOperand(OtherIdx);
452     Value *NewOther   = ConvertExpressionToType(OtherOp, NewVal->getType(),VMC);
453
454     Res = BinaryOperator::create(cast<BinaryOperator>(I)->getOpcode(),
455                                  OtherIdx == 0 ? NewOther : NewVal,
456                                  OtherIdx == 1 ? NewOther : NewVal,
457                                  Name);
458     break;
459   }
460   case Instruction::Shl:
461   case Instruction::Shr:
462     assert(I->getOperand(0) == OldVal);
463     Res = new ShiftInst(cast<ShiftInst>(I)->getOpcode(), NewVal,
464                         I->getOperand(1), Name);
465     break;
466
467   case Instruction::Load:
468     assert(I->getOperand(0) == OldVal);
469     Res = new LoadInst(NewVal, Name);
470     break;
471
472   case Instruction::Store: {
473     if (I->getOperand(0) == OldVal) {  // Replace the source value
474       Value *NewPtr =
475         ConvertExpressionToType(I->getOperand(1),
476                                 PointerType::get(NewVal->getType()), VMC);
477       Res = new StoreInst(NewVal, NewPtr);
478     } else {                           // Replace the source pointer
479       const Type *ValType =cast<PointerType>(NewVal->getType())->getValueType();
480       Value *NewV = ConvertExpressionToType(I->getOperand(0), ValType, VMC);
481       Res = new StoreInst(NewV, NewVal);
482     }
483     break;
484   }
485
486 #if 0
487   case Instruction::GetElementPtr: {
488     // GetElementPtr's are directly convertable to a pointer type if they have
489     // a number of zeros at the end.  Because removing these values does not
490     // change the logical offset of the GEP, it is okay and fair to remove them.
491     // This can change this:
492     //   %t1 = getelementptr %Hosp * %hosp, ubyte 4, ubyte 0  ; <%List **>
493     //   %t2 = cast %List * * %t1 to %List *
494     // into
495     //   %t2 = getelementptr %Hosp * %hosp, ubyte 4           ; <%List *>
496     // 
497     GetElementPtrInst *GEP = cast<GetElementPtrInst>(I);
498
499     // Check to see if there are zero elements that we can remove from the
500     // index array.  If there are, check to see if removing them causes us to
501     // get to the right type...
502     //
503     vector<ConstPoolVal*> Indices = GEP->getIndices();
504     const Type *BaseType = GEP->getPtrOperand()->getType();
505     const Type *PVTy = cast<PointerType>(Ty)->getValueType();
506     Res = 0;
507     while (Indices.size() &&
508            cast<ConstPoolUInt>(Indices.back())->getValue() == 0) {
509       Indices.pop_back();
510       if (GetElementPtrInst::getIndexedType(BaseType, Indices, true) == PVTy) {
511         if (Indices.size() == 0) {
512           Res = new CastInst(GEP->getPtrOperand(), BaseType); // NOOP
513         } else {
514           Res = new GetElementPtrInst(GEP->getPtrOperand(), Indices, Name);
515         }
516         break;
517       }
518     }
519     assert(Res && "Didn't find match!");
520     break;   // No match, maybe next time.
521   }
522 #endif
523
524   default:
525     assert(0 && "Expression convertable, but don't know how to convert?");
526     return;
527   }
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);   // Keep It pointing to old instruction
532
533 #ifdef DEBUG_EXPR_CONVERT
534   cerr << "In: " << I << "Out: " << Res;
535 #endif
536
537   if (I->getType() != Res->getType())
538     ConvertUsersType(I, Res, VMC);
539   else {
540     for (unsigned It = 0; It < I->use_size(); ) {
541       User *Use = *(I->use_begin()+It);
542       if (isa<ValueHandle>(Use))            // Don't remove ValueHandles!
543         ++It;
544       else
545         Use->replaceUsesOfWith(I, Res);
546     }
547
548     if (I->use_size() == 0) {
549       // Now we just need to remove the old instruction so we don't get infinite
550       // loops.  Note that we cannot use DCE because DCE won't remove a store
551       // instruction, for example.
552       //
553       BasicBlock::iterator It = find(BIL.begin(), BIL.end(), I);
554       assert(It != BIL.end() && "Instruction no longer in basic block??");
555 #ifdef DEBUG_EXPR_CONVERT
556       cerr << "DELETING: " << (void*)I << " " << I;
557 #endif
558       delete BIL.remove(It);
559     } else {
560       for (Value::use_iterator UI = I->use_begin(), UE = I->use_end();
561            UI != UE; ++UI)
562         assert(isa<ValueHandle>((Value*)*UI) && "Uses of Instruction remain!!!");
563     }
564   }
565 }
566
567
568 ValueHandle::~ValueHandle() {
569   if (Operands[0]->use_size() == 1) {
570     Value *V = Operands[0];
571     Operands.clear();   // Drop use!
572
573     // Now we just need to remove the old instruction so we don't get infinite
574     // loops.  Note that we cannot use DCE because DCE won't remove a store
575     // instruction, for example.
576     //
577     Instruction *I = cast<Instruction>(V);
578     BasicBlock *BB = I->getParent();
579     assert(BB && "Inst not in basic block!");
580
581     BasicBlock::iterator It = find(BB->begin(), BB->end(), I);
582     assert(It != BB->end() && "Instruction no longer in basic block??");
583 #ifdef DEBUG_EXPR_CONVERT
584     cerr << "VH DELETING: " << (void*)I << " " << I;
585 #endif
586     delete BB->getInstList().remove(It);
587   } else {
588 #ifdef DEBUG_EXPR_CONVERT
589     cerr << "VH RELEASING: " << Operands[0];
590 #endif
591   }
592 }