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 // ExpressionConvertableToType - Return true if it is possible
23 static bool ExpressionConvertableToType(Value *V, const Type *Ty,
24 ValueTypeCache &CTMap) {
25 ValueTypeCache::iterator CTMI = CTMap.find(V);
26 if (CTMI != CTMap.end()) return CTMI->second == Ty;
29 Instruction *I = dyn_cast<Instruction>(V);
31 // It's not an instruction, check to see if it's a constant... all constants
32 // can be converted to an equivalent value (except pointers, they can't be
33 // const prop'd in general).
35 if (isa<ConstPoolVal>(V) &&
36 !isa<PointerType>(V->getType()) && !isa<PointerType>(Ty)) return true;
38 return false; // Otherwise, we can't convert!
40 if (I->getType() == Ty) return false; // Expression already correct type!
42 switch (I->getOpcode()) {
43 case Instruction::Cast:
44 // We can convert the expr if the cast destination type is losslessly
45 // convertable to the requested type.
46 return losslessCastableTypes(Ty, I->getType());
48 case Instruction::Add:
49 case Instruction::Sub:
50 return ExpressionConvertableToType(I->getOperand(0), Ty, CTMap) &&
51 ExpressionConvertableToType(I->getOperand(1), Ty, CTMap);
52 case Instruction::Shr:
53 if (Ty->isSigned() != V->getType()->isSigned()) return false;
55 case Instruction::Shl:
56 return ExpressionConvertableToType(I->getOperand(0), Ty, CTMap);
58 case Instruction::Load: {
59 LoadInst *LI = cast<LoadInst>(I);
60 if (LI->hasIndices()) return false;
61 return ExpressionConvertableToType(LI->getPtrOperand(),
62 PointerType::get(Ty), CTMap);
64 case Instruction::GetElementPtr: {
65 // GetElementPtr's are directly convertable to a pointer type if they have
66 // a number of zeros at the end. Because removing these values does not
67 // change the logical offset of the GEP, it is okay and fair to remove them.
68 // This can change this:
69 // %t1 = getelementptr %Hosp * %hosp, ubyte 4, ubyte 0 ; <%List **>
70 // %t2 = cast %List * * %t1 to %List *
72 // %t2 = getelementptr %Hosp * %hosp, ubyte 4 ; <%List *>
74 GetElementPtrInst *GEP = cast<GetElementPtrInst>(I);
75 const PointerType *PTy = dyn_cast<PointerType>(Ty);
76 if (!PTy) return false;
78 // Check to see if there are zero elements that we can remove from the
79 // index array. If there are, check to see if removing them causes us to
80 // get to the right type...
82 vector<ConstPoolVal*> Indices = GEP->getIndices();
83 const Type *BaseType = GEP->getPtrOperand()->getType();
85 while (Indices.size() &&
86 cast<ConstPoolUInt>(Indices.back())->getValue() == 0) {
88 const Type *ElTy = GetElementPtrInst::getIndexedType(BaseType, Indices,
90 if (ElTy == PTy->getValueType())
91 return true; // Found a match!!
93 break; // No match, maybe next time.
102 static Value *ConvertExpressionToType(Value *V, const Type *Ty,
103 ValueMapCache &VMC) {
104 Instruction *I = dyn_cast<Instruction>(V);
106 if (ConstPoolVal *CPV = cast<ConstPoolVal>(V)) {
107 // Constants are converted by constant folding the cast that is required.
108 // We assume here that all casts are implemented for constant prop.
109 Value *Result = opt::ConstantFoldCastInstruction(CPV, Ty);
110 if (!Result) cerr << "Couldn't fold " << CPV << " to " << Ty << endl;
111 assert(Result && "ConstantFoldCastInstruction Failed!!!");
116 BasicBlock *BB = I->getParent();
117 BasicBlock::InstListType &BIL = BB->getInstList();
118 string Name = I->getName(); if (!Name.empty()) I->setName("");
119 Instruction *Res; // Result of conversion
121 //cerr << endl << endl << "Type:\t" << Ty << "\nInst: " << I << "BB Before: " << BB << endl;
123 switch (I->getOpcode()) {
124 case Instruction::Cast:
125 Res = new CastInst(I->getOperand(0), Ty, Name);
128 case Instruction::Add:
129 case Instruction::Sub:
130 Res = BinaryOperator::create(cast<BinaryOperator>(I)->getOpcode(),
131 ConvertExpressionToType(I->getOperand(0), Ty, VMC),
132 ConvertExpressionToType(I->getOperand(1), Ty, VMC),
136 case Instruction::Shl:
137 case Instruction::Shr:
138 Res = new ShiftInst(cast<ShiftInst>(I)->getOpcode(),
139 ConvertExpressionToType(I->getOperand(0), Ty, VMC),
140 I->getOperand(1), Name);
143 case Instruction::Load: {
144 LoadInst *LI = cast<LoadInst>(I);
145 assert(!LI->hasIndices());
146 Res = new LoadInst(ConvertExpressionToType(LI->getPtrOperand(),
147 PointerType::get(Ty), VMC),
152 case Instruction::GetElementPtr: {
153 // GetElementPtr's are directly convertable to a pointer type if they have
154 // a number of zeros at the end. Because removing these values does not
155 // change the logical offset of the GEP, it is okay and fair to remove them.
156 // This can change this:
157 // %t1 = getelementptr %Hosp * %hosp, ubyte 4, ubyte 0 ; <%List **>
158 // %t2 = cast %List * * %t1 to %List *
160 // %t2 = getelementptr %Hosp * %hosp, ubyte 4 ; <%List *>
162 GetElementPtrInst *GEP = cast<GetElementPtrInst>(I);
164 // Check to see if there are zero elements that we can remove from the
165 // index array. If there are, check to see if removing them causes us to
166 // get to the right type...
168 vector<ConstPoolVal*> Indices = GEP->getIndices();
169 const Type *BaseType = GEP->getPtrOperand()->getType();
170 const Type *PVTy = cast<PointerType>(Ty)->getValueType();
172 while (Indices.size() &&
173 cast<ConstPoolUInt>(Indices.back())->getValue() == 0) {
175 if (GetElementPtrInst::getIndexedType(BaseType, Indices, true) == PVTy) {
176 if (Indices.size() == 0) {
177 Res = new CastInst(GEP->getPtrOperand(), BaseType); // NOOP
179 Res = new GetElementPtrInst(GEP->getPtrOperand(), Indices, Name);
184 assert(Res && "Didn't find match!");
185 break; // No match, maybe next time.
189 assert(0 && "Expression convertable, but don't know how to convert?");
193 BasicBlock::iterator It = find(BIL.begin(), BIL.end(), I);
194 assert(It != BIL.end() && "Instruction not in own basic block??");
197 //cerr << "RInst: " << Res << "BB After: " << BB << endl << endl;
208 static inline const Type *getTy(const Value *V, ValueTypeCache &CT) {
209 ValueTypeCache::iterator I = CT.find(V);
210 if (I == CT.end()) return V->getType();
215 static bool OperandConvertableToType(User *U, Value *V, const Type *Ty,
216 ValueTypeCache &ConvertedTypes);
218 // RetValConvertableToType - Return true if it is possible
219 bool RetValConvertableToType(Value *V, const Type *Ty,
220 ValueTypeCache &ConvertedTypes) {
221 ValueTypeCache::iterator I = ConvertedTypes.find(V);
222 if (I != ConvertedTypes.end()) return I->second == Ty;
223 ConvertedTypes[V] = Ty;
225 // It is safe to convert the specified value to the specified type IFF all of
226 // the uses of the value can be converted to accept the new typed value.
228 for (Value::use_iterator I = V->use_begin(), E = V->use_end(); I != E; ++I)
229 if (!OperandConvertableToType(*I, V, Ty, ConvertedTypes))
236 // OperandConvertableToType - Return true if it is possible to convert operand
237 // V of User (instruction) U to the specified type. This is true iff it is
238 // possible to change the specified instruction to accept this. CTMap is a map
239 // of converted types, so that circular definitions will see the future type of
240 // the expression, not the static current type.
242 static bool OperandConvertableToType(User *U, Value *V, const Type *Ty,
243 ValueTypeCache &CTMap) {
244 assert(V->getType() != Ty &&
245 "OperandConvertableToType: Operand is already right type!");
246 Instruction *I = dyn_cast<Instruction>(U);
247 if (I == 0) return false; // We can't convert!
249 switch (I->getOpcode()) {
250 case Instruction::Cast:
251 assert(I->getOperand(0) == V);
252 // We can convert the expr if the cast destination type is losslessly
253 // convertable to the requested type.
254 return losslessCastableTypes(Ty, I->getOperand(0)->getType());
256 case Instruction::Add:
257 case Instruction::Sub: {
258 Value *OtherOp = I->getOperand((V == I->getOperand(0)) ? 1 : 0);
259 return RetValConvertableToType(I, Ty, CTMap) &&
260 ExpressionConvertableToType(OtherOp, Ty, CTMap);
262 case Instruction::SetEQ:
263 case Instruction::SetNE: {
264 Value *OtherOp = I->getOperand((V == I->getOperand(0)) ? 1 : 0);
265 return ExpressionConvertableToType(OtherOp, Ty, CTMap);
267 case Instruction::Shr:
268 if (Ty->isSigned() != V->getType()->isSigned()) return false;
270 case Instruction::Shl:
271 assert(I->getOperand(0) == V);
272 return RetValConvertableToType(I, Ty, CTMap);
274 case Instruction::Load:
275 assert(I->getOperand(0) == V);
276 if (const PointerType *PT = dyn_cast<PointerType>(Ty)) {
277 LoadInst *LI = cast<LoadInst>(I);
278 if (LI->hasIndices() ||
279 TD.getTypeSize(PT->getValueType()) != TD.getTypeSize(LI->getType()))
282 return RetValConvertableToType(LI, PT->getValueType(), CTMap);
286 case Instruction::Store: {
287 StoreInst *SI = cast<StoreInst>(I);
288 if (SI->hasIndices()) return false;
290 if (V == I->getOperand(0)) {
291 // Can convert the store if we can convert the pointer operand to match
292 // the new value type...
293 return ExpressionConvertableToType(I->getOperand(1), PointerType::get(Ty),
295 } else if (const PointerType *PT = dyn_cast<PointerType>(Ty)) {
296 if (isa<ArrayType>(PT->getValueType()))
297 return false; // Avoid getDataSize on unsized array type!
298 assert(V == I->getOperand(1));
300 // Must move the same amount of data...
301 if (TD.getTypeSize(PT->getValueType()) !=
302 TD.getTypeSize(I->getOperand(0)->getType())) return false;
304 // Can convert store if the incoming value is convertable...
305 return ExpressionConvertableToType(I->getOperand(0), PT->getValueType(),
313 case Instruction::GetElementPtr: {
314 // GetElementPtr's are directly convertable to a pointer type if they have
315 // a number of zeros at the end. Because removing these values does not
316 // change the logical offset of the GEP, it is okay and fair to remove them.
317 // This can change this:
318 // %t1 = getelementptr %Hosp * %hosp, ubyte 4, ubyte 0 ; <%List **>
319 // %t2 = cast %List * * %t1 to %List *
321 // %t2 = getelementptr %Hosp * %hosp, ubyte 4 ; <%List *>
323 GetElementPtrInst *GEP = cast<GetElementPtrInst>(I);
324 const PointerType *PTy = dyn_cast<PointerType>(Ty);
325 if (!PTy) return false;
327 // Check to see if there are zero elements that we can remove from the
328 // index array. If there are, check to see if removing them causes us to
329 // get to the right type...
331 vector<ConstPoolVal*> Indices = GEP->getIndices();
332 const Type *BaseType = GEP->getPtrOperand()->getType();
334 while (Indices.size() &&
335 cast<ConstPoolUInt>(Indices.back())->getValue() == 0) {
337 const Type *ElTy = GetElementPtrInst::getIndexedType(BaseType, Indices,
339 if (ElTy == PTy->getValueType())
340 return true; // Found a match!!
342 break; // No match, maybe next time.
354 static void ConvertOperandToType(User *U, Value *OldVal, Value *NewVal,
357 void ConvertUsersType(Value *V, Value *NewVal, ValueMapCache &VMC) {
359 // It is safe to convert the specified value to the specified type IFF all of
360 // the uses of the value can be converted to accept the new typed value.
362 while (!V->use_empty()) {
363 unsigned OldSize = V->use_size();
364 ConvertOperandToType(V->use_back(), V, NewVal, VMC);
365 assert(V->use_size() != OldSize && "Use didn't detatch from value!");
371 static void ConvertOperandToType(User *U, Value *OldVal, Value *NewVal,
372 ValueMapCache &VMC) {
373 Instruction *I = cast<Instruction>(U); // Only Instructions convertable
375 BasicBlock *BB = I->getParent();
376 BasicBlock::InstListType &BIL = BB->getInstList();
377 string Name = I->getName(); if (!Name.empty()) I->setName("");
378 Instruction *Res; // Result of conversion
380 //cerr << endl << endl << "Type:\t" << Ty << "\nInst: " << I << "BB Before: " << BB << endl;
382 switch (I->getOpcode()) {
383 case Instruction::Cast:
384 assert(I->getOperand(0) == OldVal);
385 Res = new CastInst(NewVal, I->getType(), Name);
388 case Instruction::Add:
389 case Instruction::Sub:
390 case Instruction::SetEQ:
391 case Instruction::SetNE: {
392 unsigned OtherIdx = (OldVal == I->getOperand(0)) ? 1 : 0;
393 Value *OtherOp = I->getOperand(OtherIdx);
394 Value *NewOther = ConvertExpressionToType(OtherOp, NewVal->getType(),VMC);
396 Res = BinaryOperator::create(cast<BinaryOperator>(I)->getOpcode(),
397 OtherIdx == 0 ? NewOther : NewVal,
398 OtherIdx == 1 ? NewOther : NewVal,
402 case Instruction::Shl:
403 case Instruction::Shr:
404 assert(I->getOperand(0) == OldVal);
405 Res = new ShiftInst(cast<ShiftInst>(I)->getOpcode(), NewVal,
406 I->getOperand(1), Name);
409 case Instruction::Load:
410 assert(I->getOperand(0) == OldVal);
411 Res = new LoadInst(NewVal, Name);
414 case Instruction::Store: {
415 if (I->getOperand(0) == OldVal) { // Replace the source value
417 ConvertExpressionToType(I->getOperand(1),
418 PointerType::get(NewVal->getType()), VMC);
419 Res = new StoreInst(NewVal, NewPtr);
420 } else { // Replace the source pointer
421 const Type *ValType =cast<PointerType>(NewVal->getType())->getValueType();
422 Value *NewV = ConvertExpressionToType(I->getOperand(0), ValType, VMC);
423 Res = new StoreInst(NewV, NewVal);
429 case Instruction::GetElementPtr: {
430 // GetElementPtr's are directly convertable to a pointer type if they have
431 // a number of zeros at the end. Because removing these values does not
432 // change the logical offset of the GEP, it is okay and fair to remove them.
433 // This can change this:
434 // %t1 = getelementptr %Hosp * %hosp, ubyte 4, ubyte 0 ; <%List **>
435 // %t2 = cast %List * * %t1 to %List *
437 // %t2 = getelementptr %Hosp * %hosp, ubyte 4 ; <%List *>
439 GetElementPtrInst *GEP = cast<GetElementPtrInst>(I);
441 // Check to see if there are zero elements that we can remove from the
442 // index array. If there are, check to see if removing them causes us to
443 // get to the right type...
445 vector<ConstPoolVal*> Indices = GEP->getIndices();
446 const Type *BaseType = GEP->getPtrOperand()->getType();
447 const Type *PVTy = cast<PointerType>(Ty)->getValueType();
449 while (Indices.size() &&
450 cast<ConstPoolUInt>(Indices.back())->getValue() == 0) {
452 if (GetElementPtrInst::getIndexedType(BaseType, Indices, true) == PVTy) {
453 if (Indices.size() == 0) {
454 Res = new CastInst(GEP->getPtrOperand(), BaseType); // NOOP
456 Res = new GetElementPtrInst(GEP->getPtrOperand(), Indices, Name);
461 assert(Res && "Didn't find match!");
462 break; // No match, maybe next time.
467 assert(0 && "Expression convertable, but don't know how to convert?");
471 BasicBlock::iterator It = find(BIL.begin(), BIL.end(), I);
472 assert(It != BIL.end() && "Instruction not in own basic block??");
473 BIL.insert(It, Res); // Keep It pointing to old instruction
475 #if DEBUG_PEEPHOLE_INSTS
476 cerr << "In: " << I << "Out: " << Res;
479 //cerr << "RInst: " << Res << "BB After: " << BB << endl << endl;
481 if (I->getType() != Res->getType())
482 ConvertUsersType(I, Res, VMC);
484 I->replaceAllUsesWith(Res);
486 // Now we just need to remove the old instruction so we don't get infinite
487 // loops. Note that we cannot use DCE because DCE won't remove a store
488 // instruction, for example.
489 assert(I->use_size() == 0 && "Uses of Instruction remain!!!");
491 It = find(BIL.begin(), BIL.end(), I);
492 assert(It != BIL.end() && "Instruction no longer in basic block??");
493 delete BIL.remove(It);