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/iOther.h"
12 #include "llvm/iPHINode.h"
13 #include "llvm/iMemory.h"
14 #include "llvm/ConstantVals.h"
15 #include "llvm/Transforms/Scalar/ConstantHandling.h"
16 #include "llvm/Transforms/Scalar/DCE.h"
17 #include "llvm/Analysis/Expressions.h"
18 #include "Support/STLExtras.h"
24 #include "llvm/Assembly/Writer.h"
26 //#define DEBUG_EXPR_CONVERT 1
28 static bool OperandConvertableToType(User *U, Value *V, const Type *Ty,
29 ValueTypeCache &ConvertedTypes);
31 static void ConvertOperandToType(User *U, Value *OldVal, Value *NewVal,
34 // AllIndicesZero - Return true if all of the indices of the specified memory
35 // access instruction are zero, indicating an effectively nil offset to the
38 static bool AllIndicesZero(const MemAccessInst *MAI) {
39 for (User::const_op_iterator S = MAI->idx_begin(), E = MAI->idx_end();
41 if (!isa<Constant>(*S) || !cast<Constant>(*S)->isNullValue())
47 // Peephole Malloc instructions: we take a look at the use chain of the
48 // malloc instruction, and try to find out if the following conditions hold:
49 // 1. The malloc is of the form: 'malloc [sbyte], uint <constant>'
50 // 2. The only users of the malloc are cast & add instructions
51 // 3. Of the cast instructions, there is only one destination pointer type
52 // [RTy] where the size of the pointed to object is equal to the number
53 // of bytes allocated.
55 // If these conditions hold, we convert the malloc to allocate an [RTy]
56 // element. TODO: This comment is out of date WRT arrays
58 static bool MallocConvertableToType(MallocInst *MI, const Type *Ty,
59 ValueTypeCache &CTMap) {
60 if (!MI->isArrayAllocation() || // No array allocation?
61 !isa<PointerType>(Ty)) return false; // Malloc always returns pointers
63 // Deal with the type to allocate, not the pointer type...
64 Ty = cast<PointerType>(Ty)->getElementType();
65 if (!Ty->isSized()) return false; // Can only alloc something with a size
67 // Analyze the number of bytes allocated...
68 analysis::ExprType Expr = analysis::ClassifyExpression(MI->getArraySize());
70 // Get information about the base datatype being allocated, before & after
71 unsigned ReqTypeSize = TD.getTypeSize(Ty);
72 unsigned OldTypeSize = TD.getTypeSize(MI->getType()->getElementType());
74 // Must have a scale or offset to analyze it...
75 if (!Expr.Offset && !Expr.Scale) return false;
77 // Get the offset and scale of the allocation...
78 int OffsetVal = Expr.Offset ? getConstantValue(Expr.Offset) : 0;
79 int ScaleVal = Expr.Scale ? getConstantValue(Expr.Scale) : (Expr.Var ? 1 : 0);
80 if (ScaleVal < 0 || OffsetVal < 0) {
81 cerr << "malloc of a negative number???\n";
85 // The old type might not be of unit size, take old size into consideration
87 unsigned Offset = (unsigned)OffsetVal * OldTypeSize;
88 unsigned Scale = (unsigned)ScaleVal * OldTypeSize;
90 // In order to be successful, both the scale and the offset must be a multiple
91 // of the requested data type's size.
93 if (Offset/ReqTypeSize*ReqTypeSize != Offset ||
94 Scale/ReqTypeSize*ReqTypeSize != Scale)
95 return false; // Nope.
100 static Instruction *ConvertMallocToType(MallocInst *MI, const Type *Ty,
101 const std::string &Name,
103 BasicBlock *BB = MI->getParent();
104 BasicBlock::iterator It = BB->end();
106 // Analyze the number of bytes allocated...
107 analysis::ExprType Expr = analysis::ClassifyExpression(MI->getArraySize());
109 const PointerType *AllocTy = cast<PointerType>(Ty);
110 const Type *ElType = AllocTy->getElementType();
112 unsigned DataSize = TD.getTypeSize(ElType);
113 unsigned OldTypeSize = TD.getTypeSize(MI->getType()->getElementType());
115 // Get the offset and scale coefficients that we are allocating...
116 int OffsetVal = (Expr.Offset ? getConstantValue(Expr.Offset) : 0);
117 int ScaleVal = Expr.Scale ? getConstantValue(Expr.Scale) : (Expr.Var ? 1 : 0);
119 // The old type might not be of unit size, take old size into consideration
121 unsigned Offset = (unsigned)OffsetVal * OldTypeSize / DataSize;
122 unsigned Scale = (unsigned)ScaleVal * OldTypeSize / DataSize;
124 // Locate the malloc instruction, because we may be inserting instructions
125 It = find(BB->getInstList().begin(), BB->getInstList().end(), MI);
127 // If we have a scale, apply it first...
129 // Expr.Var is not neccesarily unsigned right now, insert a cast now.
130 if (Expr.Var->getType() != Type::UIntTy) {
131 Instruction *CI = new CastInst(Expr.Var, Type::UIntTy);
132 if (Expr.Var->hasName()) CI->setName(Expr.Var->getName()+"-uint");
133 It = BB->getInstList().insert(It, CI)+1;
139 BinaryOperator::create(Instruction::Mul, Expr.Var,
140 ConstantUInt::get(Type::UIntTy, Scale));
141 if (Expr.Var->hasName()) ScI->setName(Expr.Var->getName()+"-scl");
142 It = BB->getInstList().insert(It, ScI)+1;
147 // If we are not scaling anything, just make the offset be the "var"...
148 Expr.Var = ConstantUInt::get(Type::UIntTy, Offset);
149 Offset = 0; Scale = 1;
152 // If we have an offset now, add it in...
154 assert(Expr.Var && "Var must be nonnull by now!");
157 BinaryOperator::create(Instruction::Add, Expr.Var,
158 ConstantUInt::get(Type::UIntTy, Offset));
159 if (Expr.Var->hasName()) AddI->setName(Expr.Var->getName()+"-off");
160 It = BB->getInstList().insert(It, AddI)+1;
164 Instruction *NewI = new MallocInst(AllocTy, Expr.Var, Name);
166 assert(AllocTy == Ty);
171 // ExpressionConvertableToType - Return true if it is possible
172 bool ExpressionConvertableToType(Value *V, const Type *Ty,
173 ValueTypeCache &CTMap) {
174 if (V->getType() == Ty) return true; // Expression already correct type!
176 // Expression type must be holdable in a register.
177 if (!Ty->isFirstClassType())
180 ValueTypeCache::iterator CTMI = CTMap.find(V);
181 if (CTMI != CTMap.end()) return CTMI->second == Ty;
185 Instruction *I = dyn_cast<Instruction>(V);
187 // It's not an instruction, check to see if it's a constant... all constants
188 // can be converted to an equivalent value (except pointers, they can't be
189 // const prop'd in general). We just ask the constant propogator to see if
190 // it can convert the value...
192 if (Constant *CPV = dyn_cast<Constant>(V))
193 if (ConstantFoldCastInstruction(CPV, Ty))
194 return true; // Don't worry about deallocating, it's a constant.
196 return false; // Otherwise, we can't convert!
199 switch (I->getOpcode()) {
200 case Instruction::Cast:
201 // We can convert the expr if the cast destination type is losslessly
202 // convertable to the requested type.
203 if (!Ty->isLosslesslyConvertableTo(I->getType())) return false;
205 // We also do not allow conversion of a cast that casts from a ptr to array
206 // of X to a *X. For example: cast [4 x %List *] * %val to %List * *
208 if (PointerType *SPT = dyn_cast<PointerType>(I->getOperand(0)->getType()))
209 if (PointerType *DPT = dyn_cast<PointerType>(I->getType()))
210 if (ArrayType *AT = dyn_cast<ArrayType>(SPT->getElementType()))
211 if (AT->getElementType() == DPT->getElementType())
216 case Instruction::Add:
217 case Instruction::Sub:
218 if (!ExpressionConvertableToType(I->getOperand(0), Ty, CTMap) ||
219 !ExpressionConvertableToType(I->getOperand(1), Ty, CTMap))
222 case Instruction::Shr:
223 if (Ty->isSigned() != V->getType()->isSigned()) return false;
225 case Instruction::Shl:
226 if (!ExpressionConvertableToType(I->getOperand(0), Ty, CTMap))
230 case Instruction::Load: {
231 LoadInst *LI = cast<LoadInst>(I);
232 if (LI->hasIndices() && !AllIndicesZero(LI)) {
233 // We can't convert a load expression if it has indices... unless they are
238 if (!ExpressionConvertableToType(LI->getPointerOperand(),
239 PointerType::get(Ty), CTMap))
243 case Instruction::PHINode: {
244 PHINode *PN = cast<PHINode>(I);
245 for (unsigned i = 0; i < PN->getNumIncomingValues(); ++i)
246 if (!ExpressionConvertableToType(PN->getIncomingValue(i), Ty, CTMap))
251 case Instruction::Malloc:
252 if (!MallocConvertableToType(cast<MallocInst>(I), Ty, CTMap))
257 case Instruction::GetElementPtr: {
258 // GetElementPtr's are directly convertable to a pointer type if they have
259 // a number of zeros at the end. Because removing these values does not
260 // change the logical offset of the GEP, it is okay and fair to remove them.
261 // This can change this:
262 // %t1 = getelementptr %Hosp * %hosp, ubyte 4, ubyte 0 ; <%List **>
263 // %t2 = cast %List * * %t1 to %List *
265 // %t2 = getelementptr %Hosp * %hosp, ubyte 4 ; <%List *>
267 GetElementPtrInst *GEP = cast<GetElementPtrInst>(I);
268 const PointerType *PTy = dyn_cast<PointerType>(Ty);
269 if (!PTy) return false; // GEP must always return a pointer...
270 const Type *PVTy = PTy->getElementType();
272 // Check to see if there are zero elements that we can remove from the
273 // index array. If there are, check to see if removing them causes us to
274 // get to the right type...
276 std::vector<Value*> Indices = GEP->copyIndices();
277 const Type *BaseType = GEP->getPointerOperand()->getType();
278 const Type *ElTy = 0;
280 while (!Indices.empty() && isa<ConstantUInt>(Indices.back()) &&
281 cast<ConstantUInt>(Indices.back())->getValue() == 0) {
283 ElTy = GetElementPtrInst::getIndexedType(BaseType, Indices, true);
285 break; // Found a match!!
289 if (ElTy) break; // Found a number of zeros we can strip off!
291 // Otherwise, we can convert a GEP from one form to the other iff the
292 // current gep is of the form 'getelementptr sbyte*, unsigned N
293 // and we could convert this to an appropriate GEP for the new type.
295 if (GEP->getNumOperands() == 2 &&
296 GEP->getOperand(1)->getType() == Type::UIntTy &&
297 GEP->getType() == PointerType::get(Type::SByteTy)) {
299 // Do not Check to see if our incoming pointer can be converted
300 // to be a ptr to an array of the right type... because in more cases than
301 // not, it is simply not analyzable because of pointer/array
302 // discrepencies. To fix this, we will insert a cast before the GEP.
305 // Check to see if 'N' is an expression that can be converted to
306 // the appropriate size... if so, allow it.
308 std::vector<Value*> Indices;
309 const Type *ElTy = ConvertableToGEP(PTy, I->getOperand(1), Indices);
311 if (!ExpressionConvertableToType(I->getOperand(0),
312 PointerType::get(ElTy), CTMap))
313 return false; // Can't continue, ExConToTy might have polluted set!
318 // Otherwise, it could be that we have something like this:
319 // getelementptr [[sbyte] *] * %reg115, uint %reg138 ; [sbyte]**
320 // and want to convert it into something like this:
321 // getelemenptr [[int] *] * %reg115, uint %reg138 ; [int]**
323 if (GEP->getNumOperands() == 2 &&
324 GEP->getOperand(1)->getType() == Type::UIntTy &&
325 TD.getTypeSize(PTy->getElementType()) ==
326 TD.getTypeSize(GEP->getType()->getElementType())) {
327 const PointerType *NewSrcTy = PointerType::get(PVTy);
328 if (!ExpressionConvertableToType(I->getOperand(0), NewSrcTy, CTMap))
333 return false; // No match, maybe next time.
341 // Expressions are only convertable if all of the users of the expression can
342 // have this value converted. This makes use of the map to avoid infinite
345 for (Value::use_iterator It = I->use_begin(), E = I->use_end(); It != E; ++It)
346 if (!OperandConvertableToType(*It, I, Ty, CTMap))
353 Value *ConvertExpressionToType(Value *V, const Type *Ty, ValueMapCache &VMC) {
354 if (V->getType() == Ty) return V; // Already where we need to be?
356 ValueMapCache::ExprMapTy::iterator VMCI = VMC.ExprMap.find(V);
357 if (VMCI != VMC.ExprMap.end()) {
358 assert(VMCI->second->getType() == Ty);
360 if (Instruction *I = dyn_cast<Instruction>(V))
361 ValueHandle IHandle(VMC, I); // Remove I if it is unused now!
366 #ifdef DEBUG_EXPR_CONVERT
367 cerr << "CETT: " << (void*)V << " " << V;
370 Instruction *I = dyn_cast<Instruction>(V);
372 if (Constant *CPV = cast<Constant>(V)) {
373 // Constants are converted by constant folding the cast that is required.
374 // We assume here that all casts are implemented for constant prop.
375 Value *Result = ConstantFoldCastInstruction(CPV, Ty);
376 assert(Result && "ConstantFoldCastInstruction Failed!!!");
377 assert(Result->getType() == Ty && "Const prop of cast failed!");
379 // Add the instruction to the expression map
380 VMC.ExprMap[V] = Result;
385 BasicBlock *BB = I->getParent();
386 BasicBlock::InstListType &BIL = BB->getInstList();
387 std::string Name = I->getName(); if (!Name.empty()) I->setName("");
388 Instruction *Res; // Result of conversion
390 ValueHandle IHandle(VMC, I); // Prevent I from being removed!
392 Constant *Dummy = Constant::getNullConstant(Ty);
394 switch (I->getOpcode()) {
395 case Instruction::Cast:
396 Res = new CastInst(I->getOperand(0), Ty, Name);
399 case Instruction::Add:
400 case Instruction::Sub:
401 Res = BinaryOperator::create(cast<BinaryOperator>(I)->getOpcode(),
403 VMC.ExprMap[I] = Res; // Add node to expression eagerly
405 Res->setOperand(0, ConvertExpressionToType(I->getOperand(0), Ty, VMC));
406 Res->setOperand(1, ConvertExpressionToType(I->getOperand(1), Ty, VMC));
409 case Instruction::Shl:
410 case Instruction::Shr:
411 Res = new ShiftInst(cast<ShiftInst>(I)->getOpcode(), Dummy,
412 I->getOperand(1), Name);
413 VMC.ExprMap[I] = Res;
414 Res->setOperand(0, ConvertExpressionToType(I->getOperand(0), Ty, VMC));
417 case Instruction::Load: {
418 LoadInst *LI = cast<LoadInst>(I);
419 assert(!LI->hasIndices() || AllIndicesZero(LI));
421 Res = new LoadInst(Constant::getNullConstant(PointerType::get(Ty)), Name);
422 VMC.ExprMap[I] = Res;
423 Res->setOperand(0, ConvertExpressionToType(LI->getPointerOperand(),
424 PointerType::get(Ty), VMC));
425 assert(Res->getOperand(0)->getType() == PointerType::get(Ty));
426 assert(Ty == Res->getType());
427 assert(Res->getType()->isFirstClassType() && "Load of structure or array!");
431 case Instruction::PHINode: {
432 PHINode *OldPN = cast<PHINode>(I);
433 PHINode *NewPN = new PHINode(Ty, Name);
435 VMC.ExprMap[I] = NewPN; // Add node to expression eagerly
436 while (OldPN->getNumOperands()) {
437 BasicBlock *BB = OldPN->getIncomingBlock(0);
438 Value *OldVal = OldPN->getIncomingValue(0);
439 ValueHandle OldValHandle(VMC, OldVal);
440 OldPN->removeIncomingValue(BB);
441 Value *V = ConvertExpressionToType(OldVal, Ty, VMC);
442 NewPN->addIncoming(V, BB);
448 case Instruction::Malloc: {
449 Res = ConvertMallocToType(cast<MallocInst>(I), Ty, Name, VMC);
453 case Instruction::GetElementPtr: {
454 // GetElementPtr's are directly convertable to a pointer type if they have
455 // a number of zeros at the end. Because removing these values does not
456 // change the logical offset of the GEP, it is okay and fair to remove them.
457 // This can change this:
458 // %t1 = getelementptr %Hosp * %hosp, ubyte 4, ubyte 0 ; <%List **>
459 // %t2 = cast %List * * %t1 to %List *
461 // %t2 = getelementptr %Hosp * %hosp, ubyte 4 ; <%List *>
463 GetElementPtrInst *GEP = cast<GetElementPtrInst>(I);
465 // Check to see if there are zero elements that we can remove from the
466 // index array. If there are, check to see if removing them causes us to
467 // get to the right type...
469 std::vector<Value*> Indices = GEP->copyIndices();
470 const Type *BaseType = GEP->getPointerOperand()->getType();
471 const Type *PVTy = cast<PointerType>(Ty)->getElementType();
473 while (!Indices.empty() && isa<ConstantUInt>(Indices.back()) &&
474 cast<ConstantUInt>(Indices.back())->getValue() == 0) {
476 if (GetElementPtrInst::getIndexedType(BaseType, Indices, true) == PVTy) {
477 if (Indices.size() == 0) {
478 Res = new CastInst(GEP->getPointerOperand(), BaseType); // NOOP
480 Res = new GetElementPtrInst(GEP->getPointerOperand(), Indices, Name);
486 if (Res == 0 && GEP->getNumOperands() == 2 &&
487 GEP->getOperand(1)->getType() == Type::UIntTy &&
488 GEP->getType() == PointerType::get(Type::SByteTy)) {
490 // Otherwise, we can convert a GEP from one form to the other iff the
491 // current gep is of the form 'getelementptr [sbyte]*, unsigned N
492 // and we could convert this to an appropriate GEP for the new type.
494 const PointerType *NewSrcTy = PointerType::get(PVTy);
495 BasicBlock::iterator It = find(BIL.begin(), BIL.end(), I);
497 // Check to see if 'N' is an expression that can be converted to
498 // the appropriate size... if so, allow it.
500 std::vector<Value*> Indices;
501 const Type *ElTy = ConvertableToGEP(NewSrcTy, I->getOperand(1),
504 assert(ElTy == PVTy && "Internal error, setup wrong!");
505 Res = new GetElementPtrInst(Constant::getNullConstant(NewSrcTy),
507 VMC.ExprMap[I] = Res;
508 Res->setOperand(0, ConvertExpressionToType(I->getOperand(0),
513 // Otherwise, it could be that we have something like this:
514 // getelementptr [[sbyte] *] * %reg115, uint %reg138 ; [sbyte]**
515 // and want to convert it into something like this:
516 // getelemenptr [[int] *] * %reg115, uint %reg138 ; [int]**
519 const PointerType *NewSrcTy = PointerType::get(PVTy);
520 Res = new GetElementPtrInst(Constant::getNullConstant(NewSrcTy),
521 GEP->copyIndices(), Name);
522 VMC.ExprMap[I] = Res;
523 Res->setOperand(0, ConvertExpressionToType(I->getOperand(0),
528 assert(Res && "Didn't find match!");
529 break; // No match, maybe next time.
533 assert(0 && "Expression convertable, but don't know how to convert?");
537 assert(Res->getType() == Ty && "Didn't convert expr to correct type!");
539 BasicBlock::iterator It = find(BIL.begin(), BIL.end(), I);
540 assert(It != BIL.end() && "Instruction not in own basic block??");
543 // Add the instruction to the expression map
544 VMC.ExprMap[I] = Res;
546 // Expressions are only convertable if all of the users of the expression can
547 // have this value converted. This makes use of the map to avoid infinite
550 unsigned NumUses = I->use_size();
551 for (unsigned It = 0; It < NumUses; ) {
552 unsigned OldSize = NumUses;
553 ConvertOperandToType(*(I->use_begin()+It), I, Res, VMC);
554 NumUses = I->use_size();
555 if (NumUses == OldSize) ++It;
558 #ifdef DEBUG_EXPR_CONVERT
559 cerr << "ExpIn: " << (void*)I << " " << I
560 << "ExpOut: " << (void*)Res << " " << Res;
563 if (I->use_empty()) {
564 #ifdef DEBUG_EXPR_CONVERT
565 cerr << "EXPR DELETING: " << (void*)I << " " << I;
568 VMC.OperandsMapped.erase(I);
569 VMC.ExprMap.erase(I);
578 // ValueConvertableToType - Return true if it is possible
579 bool ValueConvertableToType(Value *V, const Type *Ty,
580 ValueTypeCache &ConvertedTypes) {
581 ValueTypeCache::iterator I = ConvertedTypes.find(V);
582 if (I != ConvertedTypes.end()) return I->second == Ty;
583 ConvertedTypes[V] = Ty;
585 // It is safe to convert the specified value to the specified type IFF all of
586 // the uses of the value can be converted to accept the new typed value.
588 if (V->getType() != Ty) {
589 for (Value::use_iterator I = V->use_begin(), E = V->use_end(); I != E; ++I)
590 if (!OperandConvertableToType(*I, V, Ty, ConvertedTypes))
601 // OperandConvertableToType - Return true if it is possible to convert operand
602 // V of User (instruction) U to the specified type. This is true iff it is
603 // possible to change the specified instruction to accept this. CTMap is a map
604 // of converted types, so that circular definitions will see the future type of
605 // the expression, not the static current type.
607 static bool OperandConvertableToType(User *U, Value *V, const Type *Ty,
608 ValueTypeCache &CTMap) {
609 // if (V->getType() == Ty) return true; // Operand already the right type?
611 // Expression type must be holdable in a register.
612 if (!Ty->isFirstClassType())
615 Instruction *I = dyn_cast<Instruction>(U);
616 if (I == 0) return false; // We can't convert!
618 switch (I->getOpcode()) {
619 case Instruction::Cast:
620 assert(I->getOperand(0) == V);
621 // We can convert the expr if the cast destination type is losslessly
622 // convertable to the requested type.
623 // Also, do not change a cast that is a noop cast. For all intents and
624 // purposes it should be eliminated.
625 if (!Ty->isLosslesslyConvertableTo(I->getOperand(0)->getType()) ||
626 I->getType() == I->getOperand(0)->getType())
631 // We also do not allow conversion of a cast that casts from a ptr to array
632 // of X to a *X. For example: cast [4 x %List *] * %val to %List * *
634 if (PointerType *SPT = dyn_cast<PointerType>(I->getOperand(0)->getType()))
635 if (PointerType *DPT = dyn_cast<PointerType>(I->getType()))
636 if (ArrayType *AT = dyn_cast<ArrayType>(SPT->getElementType()))
637 if (AT->getElementType() == DPT->getElementType())
642 case Instruction::Add:
643 if (isa<PointerType>(Ty)) {
644 Value *IndexVal = I->getOperand(V == I->getOperand(0) ? 1 : 0);
645 std::vector<Value*> Indices;
646 if (const Type *ETy = ConvertableToGEP(Ty, IndexVal, Indices)) {
647 const Type *RetTy = PointerType::get(ETy);
649 // Only successful if we can convert this type to the required type
650 if (ValueConvertableToType(I, RetTy, CTMap)) {
654 // We have to return failure here because ValueConvertableToType could
655 // have polluted our map
660 case Instruction::Sub: {
661 Value *OtherOp = I->getOperand((V == I->getOperand(0)) ? 1 : 0);
662 return ValueConvertableToType(I, Ty, CTMap) &&
663 ExpressionConvertableToType(OtherOp, Ty, CTMap);
665 case Instruction::SetEQ:
666 case Instruction::SetNE: {
667 Value *OtherOp = I->getOperand((V == I->getOperand(0)) ? 1 : 0);
668 return ExpressionConvertableToType(OtherOp, Ty, CTMap);
670 case Instruction::Shr:
671 if (Ty->isSigned() != V->getType()->isSigned()) return false;
673 case Instruction::Shl:
674 assert(I->getOperand(0) == V);
675 return ValueConvertableToType(I, Ty, CTMap);
677 case Instruction::Free:
678 assert(I->getOperand(0) == V);
679 return isa<PointerType>(Ty); // Free can free any pointer type!
681 case Instruction::Load:
682 // Cannot convert the types of any subscripts...
683 if (I->getOperand(0) != V) return false;
685 if (const PointerType *PT = dyn_cast<PointerType>(Ty)) {
686 LoadInst *LI = cast<LoadInst>(I);
688 if (LI->hasIndices() && !AllIndicesZero(LI))
691 const Type *LoadedTy = PT->getElementType();
693 // They could be loading the first element of a composite type...
694 if (const CompositeType *CT = dyn_cast<CompositeType>(LoadedTy)) {
695 unsigned Offset = 0; // No offset, get first leaf.
696 std::vector<Value*> Indices; // Discarded...
697 LoadedTy = getStructOffsetType(CT, Offset, Indices, false);
698 assert(Offset == 0 && "Offset changed from zero???");
701 if (!LoadedTy->isFirstClassType())
704 if (TD.getTypeSize(LoadedTy) != TD.getTypeSize(LI->getType()))
707 return ValueConvertableToType(LI, LoadedTy, CTMap);
711 case Instruction::Store: {
712 StoreInst *SI = cast<StoreInst>(I);
713 if (SI->hasIndices()) return false;
715 if (V == I->getOperand(0)) {
716 // Can convert the store if we can convert the pointer operand to match
717 // the new value type...
718 return ExpressionConvertableToType(I->getOperand(1), PointerType::get(Ty),
720 } else if (const PointerType *PT = dyn_cast<PointerType>(Ty)) {
721 const Type *ElTy = PT->getElementType();
722 assert(V == I->getOperand(1));
724 if (isa<StructType>(ElTy)) {
725 // We can change the destination pointer if we can store our first
726 // argument into the first element of the structure...
729 std::vector<Value*> Indices;
730 ElTy = getStructOffsetType(ElTy, Offset, Indices, false);
731 assert(Offset == 0 && "Offset changed!");
732 if (ElTy == 0) // Element at offset zero in struct doesn't exist!
733 return false; // Can only happen for {}*
736 // Must move the same amount of data...
737 if (TD.getTypeSize(ElTy) != TD.getTypeSize(I->getOperand(0)->getType()))
740 // Can convert store if the incoming value is convertable...
741 return ExpressionConvertableToType(I->getOperand(0), ElTy, CTMap);
746 case Instruction::GetElementPtr:
747 if (V != I->getOperand(0) || !isa<PointerType>(Ty)) return false;
749 // If we have a two operand form of getelementptr, this is really little
750 // more than a simple addition. As with addition, check to see if the
751 // getelementptr instruction can be changed to index into the new type.
753 if (I->getNumOperands() == 2) {
754 const Type *OldElTy = cast<PointerType>(I->getType())->getElementType();
755 unsigned DataSize = TD.getTypeSize(OldElTy);
756 Value *Index = I->getOperand(1);
757 Instruction *TempScale = 0;
759 // If the old data element is not unit sized, we have to create a scale
760 // instruction so that ConvertableToGEP will know the REAL amount we are
761 // indexing by. Note that this is never inserted into the instruction
762 // stream, so we have to delete it when we're done.
765 TempScale = BinaryOperator::create(Instruction::Mul, Index,
766 ConstantUInt::get(Type::UIntTy,
771 // Check to see if the second argument is an expression that can
772 // be converted to the appropriate size... if so, allow it.
774 std::vector<Value*> Indices;
775 const Type *ElTy = ConvertableToGEP(Ty, Index, Indices);
776 delete TempScale; // Free our temporary multiply if we made it
778 if (ElTy == 0) return false; // Cannot make conversion...
779 return ValueConvertableToType(I, PointerType::get(ElTy), CTMap);
783 case Instruction::PHINode: {
784 PHINode *PN = cast<PHINode>(I);
785 for (unsigned i = 0; i < PN->getNumIncomingValues(); ++i)
786 if (!ExpressionConvertableToType(PN->getIncomingValue(i), Ty, CTMap))
788 return ValueConvertableToType(PN, Ty, CTMap);
791 case Instruction::Call: {
792 User::op_iterator OI = find(I->op_begin(), I->op_end(), V);
793 assert (OI != I->op_end() && "Not using value!");
794 unsigned OpNum = OI - I->op_begin();
796 // Are we trying to change the method pointer value to a new type?
798 PointerType *PTy = dyn_cast<PointerType>(Ty);
799 if (PTy == 0) return false; // Can't convert to a non-pointer type...
800 MethodType *MTy = dyn_cast_or_null<MethodType>(PTy->getElementType());
801 if (MTy == 0) return false; // Can't convert to a non ptr to method...
803 // Perform sanity checks to make sure that new method type has the
804 // correct number of arguments...
806 unsigned NumArgs = I->getNumOperands()-1; // Don't include method ptr
808 // Cannot convert to a type that requires more fixed arguments than
809 // the call provides...
811 if (NumArgs < MTy->getParamTypes().size()) return false;
813 // Unless this is a vararg method type, we cannot provide more arguments
814 // than are desired...
816 if (!MTy->isVarArg() && NumArgs > MTy->getParamTypes().size())
819 // Okay, at this point, we know that the call and the method type match
820 // number of arguments. Now we see if we can convert the arguments
823 const MethodType::ParamTypes &PTs = MTy->getParamTypes();
824 for (unsigned i = 0, NA = PTs.size(); i < NA; ++i)
825 if (!PTs[i]->isLosslesslyConvertableTo(I->getOperand(i+1)->getType()))
826 return false; // Operands must have compatible types!
828 // Okay, at this point, we know that all of the arguments can be
829 // converted. We succeed if we can change the return type if
832 return ValueConvertableToType(I, MTy->getReturnType(), CTMap);
835 const PointerType *MPtr = cast<PointerType>(I->getOperand(0)->getType());
836 const MethodType *MTy = cast<MethodType>(MPtr->getElementType());
837 if (!MTy->isVarArg()) return false;
839 if ((OpNum-1) < MTy->getParamTypes().size())
840 return false; // It's not in the varargs section...
842 // If we get this far, we know the value is in the varargs section of the
843 // method! We can convert if we don't reinterpret the value...
845 return Ty->isLosslesslyConvertableTo(V->getType());
852 void ConvertValueToNewType(Value *V, Value *NewVal, ValueMapCache &VMC) {
853 ValueHandle VH(VMC, V);
855 unsigned NumUses = V->use_size();
856 for (unsigned It = 0; It < NumUses; ) {
857 unsigned OldSize = NumUses;
858 ConvertOperandToType(*(V->use_begin()+It), V, NewVal, VMC);
859 NumUses = V->use_size();
860 if (NumUses == OldSize) ++It;
866 static void ConvertOperandToType(User *U, Value *OldVal, Value *NewVal,
867 ValueMapCache &VMC) {
868 if (isa<ValueHandle>(U)) return; // Valuehandles don't let go of operands...
870 if (VMC.OperandsMapped.count(U)) return;
871 VMC.OperandsMapped.insert(U);
873 ValueMapCache::ExprMapTy::iterator VMCI = VMC.ExprMap.find(U);
874 if (VMCI != VMC.ExprMap.end())
878 Instruction *I = cast<Instruction>(U); // Only Instructions convertable
880 BasicBlock *BB = I->getParent();
881 BasicBlock::InstListType &BIL = BB->getInstList();
882 std::string Name = I->getName(); if (!Name.empty()) I->setName("");
883 Instruction *Res; // Result of conversion
885 //cerr << endl << endl << "Type:\t" << Ty << "\nInst: " << I << "BB Before: " << BB << endl;
887 // Prevent I from being removed...
888 ValueHandle IHandle(VMC, I);
890 const Type *NewTy = NewVal->getType();
891 Constant *Dummy = (NewTy != Type::VoidTy) ?
892 Constant::getNullConstant(NewTy) : 0;
894 switch (I->getOpcode()) {
895 case Instruction::Cast:
896 assert(I->getOperand(0) == OldVal);
897 Res = new CastInst(NewVal, I->getType(), Name);
900 case Instruction::Add:
901 if (isa<PointerType>(NewTy)) {
902 Value *IndexVal = I->getOperand(OldVal == I->getOperand(0) ? 1 : 0);
903 std::vector<Value*> Indices;
904 BasicBlock::iterator It = find(BIL.begin(), BIL.end(), I);
906 if (const Type *ETy = ConvertableToGEP(NewTy, IndexVal, Indices, &It)) {
907 // If successful, convert the add to a GEP
908 //const Type *RetTy = PointerType::get(ETy);
909 // First operand is actually the given pointer...
910 Res = new GetElementPtrInst(NewVal, Indices, Name);
911 assert(cast<PointerType>(Res->getType())->getElementType() == ETy &&
912 "ConvertableToGEP broken!");
918 case Instruction::Sub:
919 case Instruction::SetEQ:
920 case Instruction::SetNE: {
921 Res = BinaryOperator::create(cast<BinaryOperator>(I)->getOpcode(),
923 VMC.ExprMap[I] = Res; // Add node to expression eagerly
925 unsigned OtherIdx = (OldVal == I->getOperand(0)) ? 1 : 0;
926 Value *OtherOp = I->getOperand(OtherIdx);
927 Value *NewOther = ConvertExpressionToType(OtherOp, NewTy, VMC);
929 Res->setOperand(OtherIdx, NewOther);
930 Res->setOperand(!OtherIdx, NewVal);
933 case Instruction::Shl:
934 case Instruction::Shr:
935 assert(I->getOperand(0) == OldVal);
936 Res = new ShiftInst(cast<ShiftInst>(I)->getOpcode(), NewVal,
937 I->getOperand(1), Name);
940 case Instruction::Free: // Free can free any pointer type!
941 assert(I->getOperand(0) == OldVal);
942 Res = new FreeInst(NewVal);
946 case Instruction::Load: {
947 assert(I->getOperand(0) == OldVal && isa<PointerType>(NewVal->getType()));
948 const Type *LoadedTy =
949 cast<PointerType>(NewVal->getType())->getElementType();
951 std::vector<Value*> Indices;
952 Indices.push_back(ConstantUInt::get(Type::UIntTy, 0));
954 if (const CompositeType *CT = dyn_cast<CompositeType>(LoadedTy)) {
955 unsigned Offset = 0; // No offset, get first leaf.
956 LoadedTy = getStructOffsetType(CT, Offset, Indices, false);
958 assert(LoadedTy->isFirstClassType());
960 Res = new LoadInst(NewVal, Indices, Name);
961 assert(Res->getType()->isFirstClassType() && "Load of structure or array!");
965 case Instruction::Store: {
966 if (I->getOperand(0) == OldVal) { // Replace the source value
967 const PointerType *NewPT = PointerType::get(NewTy);
968 Res = new StoreInst(NewVal, Constant::getNullConstant(NewPT));
969 VMC.ExprMap[I] = Res;
970 Res->setOperand(1, ConvertExpressionToType(I->getOperand(1), NewPT, VMC));
971 } else { // Replace the source pointer
972 const Type *ValTy = cast<PointerType>(NewTy)->getElementType();
973 std::vector<Value*> Indices;
975 if (isa<StructType>(ValTy)) {
977 Indices.push_back(ConstantUInt::get(Type::UIntTy, 0));
978 ValTy = getStructOffsetType(ValTy, Offset, Indices, false);
979 assert(Offset == 0 && ValTy);
982 Res = new StoreInst(Constant::getNullConstant(ValTy), NewVal, Indices);
983 VMC.ExprMap[I] = Res;
984 Res->setOperand(0, ConvertExpressionToType(I->getOperand(0), ValTy, VMC));
990 case Instruction::GetElementPtr: {
991 // Convert a one index getelementptr into just about anything that is
994 BasicBlock::iterator It = find(BIL.begin(), BIL.end(), I);
995 const Type *OldElTy = cast<PointerType>(I->getType())->getElementType();
996 unsigned DataSize = TD.getTypeSize(OldElTy);
997 Value *Index = I->getOperand(1);
1000 // Insert a multiply of the old element type is not a unit size...
1001 Index = BinaryOperator::create(Instruction::Mul, Index,
1002 ConstantUInt::get(Type::UIntTy, DataSize));
1003 It = BIL.insert(It, cast<Instruction>(Index))+1;
1006 // Perform the conversion now...
1008 std::vector<Value*> Indices;
1009 const Type *ElTy = ConvertableToGEP(NewVal->getType(), Index, Indices, &It);
1010 assert(ElTy != 0 && "GEP Conversion Failure!");
1011 Res = new GetElementPtrInst(NewVal, Indices, Name);
1012 assert(Res->getType() == PointerType::get(ElTy) &&
1013 "ConvertableToGet failed!");
1016 if (I->getType() == PointerType::get(Type::SByteTy)) {
1017 // Convert a getelementptr sbyte * %reg111, uint 16 freely back to
1018 // anything that is a pointer type...
1020 BasicBlock::iterator It = find(BIL.begin(), BIL.end(), I);
1022 // Check to see if the second argument is an expression that can
1023 // be converted to the appropriate size... if so, allow it.
1025 std::vector<Value*> Indices;
1026 const Type *ElTy = ConvertableToGEP(NewVal->getType(), I->getOperand(1),
1028 assert(ElTy != 0 && "GEP Conversion Failure!");
1030 Res = new GetElementPtrInst(NewVal, Indices, Name);
1032 // Convert a getelementptr ulong * %reg123, uint %N
1033 // to getelementptr long * %reg123, uint %N
1034 // ... where the type must simply stay the same size...
1036 Res = new GetElementPtrInst(NewVal,
1037 cast<GetElementPtrInst>(I)->copyIndices(),
1043 case Instruction::PHINode: {
1044 PHINode *OldPN = cast<PHINode>(I);
1045 PHINode *NewPN = new PHINode(NewTy, Name);
1046 VMC.ExprMap[I] = NewPN;
1048 while (OldPN->getNumOperands()) {
1049 BasicBlock *BB = OldPN->getIncomingBlock(0);
1050 Value *OldVal = OldPN->getIncomingValue(0);
1051 OldPN->removeIncomingValue(BB);
1052 Value *V = ConvertExpressionToType(OldVal, NewTy, VMC);
1053 NewPN->addIncoming(V, BB);
1059 case Instruction::Call: {
1060 Value *Meth = I->getOperand(0);
1061 std::vector<Value*> Params(I->op_begin()+1, I->op_end());
1063 if (Meth == OldVal) { // Changing the method pointer?
1064 PointerType *NewPTy = cast<PointerType>(NewVal->getType());
1065 MethodType *NewTy = cast<MethodType>(NewPTy->getElementType());
1066 const MethodType::ParamTypes &PTs = NewTy->getParamTypes();
1068 // Convert over all of the call operands to their new types... but only
1069 // convert over the part that is not in the vararg section of the call.
1071 for (unsigned i = 0; i < PTs.size(); ++i)
1072 Params[i] = ConvertExpressionToType(Params[i], PTs[i], VMC);
1073 Meth = NewVal; // Update call destination to new value
1075 } else { // Changing an argument, must be in vararg area
1076 std::vector<Value*>::iterator OI =
1077 find(Params.begin(), Params.end(), OldVal);
1078 assert (OI != Params.end() && "Not using value!");
1083 Res = new CallInst(Meth, Params, Name);
1087 assert(0 && "Expression convertable, but don't know how to convert?");
1091 // If the instruction was newly created, insert it into the instruction
1094 BasicBlock::iterator It = find(BIL.begin(), BIL.end(), I);
1095 assert(It != BIL.end() && "Instruction not in own basic block??");
1096 BIL.insert(It, Res); // Keep It pointing to old instruction
1098 #ifdef DEBUG_EXPR_CONVERT
1099 cerr << "COT CREATED: " << (void*)Res << " " << Res;
1100 cerr << "In: " << (void*)I << " " << I << "Out: " << (void*)Res << " " << Res;
1103 // Add the instruction to the expression map
1104 VMC.ExprMap[I] = Res;
1106 if (I->getType() != Res->getType())
1107 ConvertValueToNewType(I, Res, VMC);
1109 for (unsigned It = 0; It < I->use_size(); ) {
1110 User *Use = *(I->use_begin()+It);
1111 if (isa<ValueHandle>(Use)) // Don't remove ValueHandles!
1114 Use->replaceUsesOfWith(I, Res);
1117 if (I->use_empty()) {
1118 // Now we just need to remove the old instruction so we don't get infinite
1119 // loops. Note that we cannot use DCE because DCE won't remove a store
1120 // instruction, for example.
1122 #ifdef DEBUG_EXPR_CONVERT
1123 cerr << "DELETING: " << (void*)I << " " << I;
1126 VMC.OperandsMapped.erase(I);
1127 VMC.ExprMap.erase(I);
1130 for (Value::use_iterator UI = I->use_begin(), UE = I->use_end();
1132 assert(isa<ValueHandle>((Value*)*UI) &&"Uses of Instruction remain!!!");
1138 ValueHandle::ValueHandle(ValueMapCache &VMC, Value *V)
1139 : Instruction(Type::VoidTy, UserOp1, ""), Cache(VMC) {
1140 #ifdef DEBUG_EXPR_CONVERT
1141 //cerr << "VH AQUIRING: " << (void*)V << " " << V;
1143 Operands.push_back(Use(V, this));
1146 static void RecursiveDelete(ValueMapCache &Cache, Instruction *I) {
1147 if (!I || !I->use_empty()) return;
1149 assert(I->getParent() && "Inst not in basic block!");
1151 #ifdef DEBUG_EXPR_CONVERT
1152 //cerr << "VH DELETING: " << (void*)I << " " << I;
1155 for (User::op_iterator OI = I->op_begin(), OE = I->op_end();
1157 if (Instruction *U = dyn_cast<Instruction>(*OI)) {
1159 RecursiveDelete(Cache, U);
1162 I->getParent()->getInstList().remove(I);
1164 Cache.OperandsMapped.erase(I);
1165 Cache.ExprMap.erase(I);
1169 ValueHandle::~ValueHandle() {
1170 if (Operands[0]->use_size() == 1) {
1171 Value *V = Operands[0];
1172 Operands[0] = 0; // Drop use!
1174 // Now we just need to remove the old instruction so we don't get infinite
1175 // loops. Note that we cannot use DCE because DCE won't remove a store
1176 // instruction, for example.
1178 RecursiveDelete(Cache, dyn_cast<Instruction>(V));
1180 #ifdef DEBUG_EXPR_CONVERT
1181 //cerr << "VH RELEASING: " << (void*)Operands[0].get() << " " << Operands[0]->use_size() << " " << Operands[0];