1 //===- ExprTypeConvert.cpp - Code to change an LLVM Expr Type ---------------=//
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.
7 //===----------------------------------------------------------------------===//
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"
20 #include "llvm/Assembly/Writer.h"
22 //#define DEBUG_EXPR_CONVERT 1
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();
31 static bool OperandConvertableToType(User *U, Value *V, const Type *Ty,
32 ValueTypeCache &ConvertedTypes);
34 static void ConvertOperandToType(User *U, Value *OldVal, Value *NewVal,
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;
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
49 for (Value::use_iterator I = V->use_begin(), E = V->use_end(); I != E; ++I)
50 if (!OperandConvertableToType(*I, V, Ty, CTMap))
53 Instruction *I = dyn_cast<Instruction>(V);
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).
59 if (isa<ConstPoolVal>(V) &&
60 !isa<PointerType>(V->getType()) && !isa<PointerType>(Ty)) return true;
62 return false; // Otherwise, we can't convert!
64 if (I->getType() == Ty) return false; // Expression already correct type!
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());
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;
79 case Instruction::Shl:
80 return ExpressionConvertableToType(I->getOperand(0), Ty, CTMap);
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);
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 *
96 // %t2 = getelementptr %Hosp * %hosp, ubyte 4 ; <%List *>
98 GetElementPtrInst *GEP = cast<GetElementPtrInst>(I);
99 const PointerType *PTy = dyn_cast<PointerType>(Ty);
100 if (!PTy) return false;
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...
106 vector<ConstPoolVal*> Indices = GEP->getIndices();
107 const Type *BaseType = GEP->getPtrOperand()->getType();
109 while (Indices.size() &&
110 cast<ConstPoolUInt>(Indices.back())->getValue() == 0) {
112 const Type *ElTy = GetElementPtrInst::getIndexedType(BaseType, Indices,
114 if (ElTy == PTy->getValueType())
115 return true; // Found a match!!
117 break; // No match, maybe next time.
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())
132 Instruction *I = dyn_cast<Instruction>(V);
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!!!");
141 // Add the instruction to the expression map
142 VMC.ExprMap[V] = Result;
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
152 //cerr << endl << endl << "Type:\t" << Ty << "\nInst: " << I << "BB Before: " << BB << endl;
154 switch (I->getOpcode()) {
155 case Instruction::Cast:
156 Res = new CastInst(I->getOperand(0), Ty, Name);
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),
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);
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),
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 *
191 // %t2 = getelementptr %Hosp * %hosp, ubyte 4 ; <%List *>
193 GetElementPtrInst *GEP = cast<GetElementPtrInst>(I);
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...
199 vector<ConstPoolVal*> Indices = GEP->getIndices();
200 const Type *BaseType = GEP->getPtrOperand()->getType();
201 const Type *PVTy = cast<PointerType>(Ty)->getValueType();
203 while (Indices.size() &&
204 cast<ConstPoolUInt>(Indices.back())->getValue() == 0) {
206 if (GetElementPtrInst::getIndexedType(BaseType, Indices, true) == PVTy) {
207 if (Indices.size() == 0) {
208 Res = new CastInst(GEP->getPtrOperand(), BaseType); // NOOP
210 Res = new GetElementPtrInst(GEP->getPtrOperand(), Indices, Name);
215 assert(Res && "Didn't find match!");
216 break; // No match, maybe next time.
220 assert(0 && "Expression convertable, but don't know how to convert?");
224 BasicBlock::iterator It = find(BIL.begin(), BIL.end(), I);
225 assert(It != BIL.end() && "Instruction not in own basic block??");
228 // Add the instruction to the expression map
229 VMC.ExprMap[I] = Res;
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
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;
243 #ifdef DEBUG_EXPR_CONVERT
244 cerr << "ExpIn: " << I << "ExpOut: " << Res;
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;
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.
262 for (Value::use_iterator I = V->use_begin(), E = V->use_end(); I != E; ++I)
263 if (!OperandConvertableToType(*I, V, Ty, ConvertedTypes))
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.
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!
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());
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);
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);
306 case Instruction::Shr:
307 if (Ty->isSigned() != V->getType()->isSigned()) return false;
309 case Instruction::Shl:
310 assert(I->getOperand(0) == V);
311 return RetValConvertableToType(I, Ty, CTMap);
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()))
321 return RetValConvertableToType(LI, PT->getValueType(), CTMap);
325 case Instruction::Store: {
326 StoreInst *SI = cast<StoreInst>(I);
327 if (SI->hasIndices()) return false;
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),
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));
339 // Must move the same amount of data...
340 if (TD.getTypeSize(PT->getValueType()) !=
341 TD.getTypeSize(I->getOperand(0)->getType())) return false;
343 // Can convert store if the incoming value is convertable...
344 return ExpressionConvertableToType(I->getOperand(0), PT->getValueType(),
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 *
360 // %t2 = getelementptr %Hosp * %hosp, ubyte 4 ; <%List *>
362 GetElementPtrInst *GEP = cast<GetElementPtrInst>(I);
363 const PointerType *PTy = dyn_cast<PointerType>(Ty);
364 if (!PTy) return false;
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...
370 vector<ConstPoolVal*> Indices = GEP->getIndices();
371 const Type *BaseType = GEP->getPtrOperand()->getType();
373 while (Indices.size() &&
374 cast<ConstPoolUInt>(Indices.back())->getValue() == 0) {
376 const Type *ElTy = GetElementPtrInst::getIndexedType(BaseType, Indices,
378 if (ElTy == PTy->getValueType())
379 return true; // Found a match!!
381 break; // No match, maybe next time.
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;
399 if (Instruction *I = dyn_cast<Instruction>(V)) {
400 BasicBlock *BB = I->getParent();
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.
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;
411 delete BB->getInstList().remove(It);
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...
421 if (VMC.OperandsMapped.count(make_pair(U, OldVal))) return;
423 VMC.OperandsMapped.insert(make_pair(U, OldVal));
425 Instruction *I = cast<Instruction>(U); // Only Instructions convertable
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
432 //cerr << endl << endl << "Type:\t" << Ty << "\nInst: " << I << "BB Before: " << BB << endl;
434 // Prevent I from being removed...
435 ValueHandle IHandle(I);
436 #ifdef DEBUG_EXPR_CONVERT
437 cerr << "VH AQUIRING: " << I;
440 switch (I->getOpcode()) {
441 case Instruction::Cast:
442 assert(I->getOperand(0) == OldVal);
443 Res = new CastInst(NewVal, I->getType(), Name);
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);
454 Res = BinaryOperator::create(cast<BinaryOperator>(I)->getOpcode(),
455 OtherIdx == 0 ? NewOther : NewVal,
456 OtherIdx == 1 ? NewOther : NewVal,
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);
467 case Instruction::Load:
468 assert(I->getOperand(0) == OldVal);
469 Res = new LoadInst(NewVal, Name);
472 case Instruction::Store: {
473 if (I->getOperand(0) == OldVal) { // Replace the source value
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);
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 *
495 // %t2 = getelementptr %Hosp * %hosp, ubyte 4 ; <%List *>
497 GetElementPtrInst *GEP = cast<GetElementPtrInst>(I);
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...
503 vector<ConstPoolVal*> Indices = GEP->getIndices();
504 const Type *BaseType = GEP->getPtrOperand()->getType();
505 const Type *PVTy = cast<PointerType>(Ty)->getValueType();
507 while (Indices.size() &&
508 cast<ConstPoolUInt>(Indices.back())->getValue() == 0) {
510 if (GetElementPtrInst::getIndexedType(BaseType, Indices, true) == PVTy) {
511 if (Indices.size() == 0) {
512 Res = new CastInst(GEP->getPtrOperand(), BaseType); // NOOP
514 Res = new GetElementPtrInst(GEP->getPtrOperand(), Indices, Name);
519 assert(Res && "Didn't find match!");
520 break; // No match, maybe next time.
525 assert(0 && "Expression convertable, but don't know how to convert?");
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
533 #ifdef DEBUG_EXPR_CONVERT
534 cerr << "In: " << I << "Out: " << Res;
537 if (I->getType() != Res->getType())
538 ConvertUsersType(I, Res, VMC);
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!
545 Use->replaceUsesOfWith(I, Res);
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.
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;
558 delete BIL.remove(It);
560 for (Value::use_iterator UI = I->use_begin(), UE = I->use_end();
562 assert(isa<ValueHandle>((Value*)*UI) && "Uses of Instruction remain!!!");
568 ValueHandle::~ValueHandle() {
569 if (Operands[0]->use_size() == 1) {
570 Value *V = Operands[0];
571 Operands.clear(); // Drop use!
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.
577 Instruction *I = cast<Instruction>(V);
578 BasicBlock *BB = I->getParent();
579 assert(BB && "Inst not in basic block!");
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;
586 delete BB->getInstList().remove(It);
588 #ifdef DEBUG_EXPR_CONVERT
589 cerr << "VH RELEASING: " << Operands[0];