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 assert(ElTy == PVTy && "Internal error, setup wrong!");
312 if (!ExpressionConvertableToType(I->getOperand(0),
313 PointerType::get(ElTy), CTMap))
314 return false; // Can't continue, ExConToTy might have polluted set!
319 // Otherwise, it could be that we have something like this:
320 // getelementptr [[sbyte] *] * %reg115, uint %reg138 ; [sbyte]**
321 // and want to convert it into something like this:
322 // getelemenptr [[int] *] * %reg115, uint %reg138 ; [int]**
324 if (GEP->getNumOperands() == 2 &&
325 GEP->getOperand(1)->getType() == Type::UIntTy &&
326 TD.getTypeSize(PTy->getElementType()) ==
327 TD.getTypeSize(GEP->getType()->getElementType())) {
328 const PointerType *NewSrcTy = PointerType::get(PVTy);
329 if (!ExpressionConvertableToType(I->getOperand(0), NewSrcTy, CTMap))
334 return false; // No match, maybe next time.
342 // Expressions are only convertable if all of the users of the expression can
343 // have this value converted. This makes use of the map to avoid infinite
346 for (Value::use_iterator It = I->use_begin(), E = I->use_end(); It != E; ++It)
347 if (!OperandConvertableToType(*It, I, Ty, CTMap))
354 Value *ConvertExpressionToType(Value *V, const Type *Ty, ValueMapCache &VMC) {
355 if (V->getType() == Ty) return V; // Already where we need to be?
357 ValueMapCache::ExprMapTy::iterator VMCI = VMC.ExprMap.find(V);
358 if (VMCI != VMC.ExprMap.end()) {
359 assert(VMCI->second->getType() == Ty);
361 if (Instruction *I = dyn_cast<Instruction>(V))
362 ValueHandle IHandle(VMC, I); // Remove I if it is unused now!
367 #ifdef DEBUG_EXPR_CONVERT
368 cerr << "CETT: " << (void*)V << " " << V;
371 Instruction *I = dyn_cast<Instruction>(V);
373 if (Constant *CPV = cast<Constant>(V)) {
374 // Constants are converted by constant folding the cast that is required.
375 // We assume here that all casts are implemented for constant prop.
376 Value *Result = ConstantFoldCastInstruction(CPV, Ty);
377 assert(Result && "ConstantFoldCastInstruction Failed!!!");
378 assert(Result->getType() == Ty && "Const prop of cast failed!");
380 // Add the instruction to the expression map
381 VMC.ExprMap[V] = Result;
386 BasicBlock *BB = I->getParent();
387 BasicBlock::InstListType &BIL = BB->getInstList();
388 std::string Name = I->getName(); if (!Name.empty()) I->setName("");
389 Instruction *Res; // Result of conversion
391 ValueHandle IHandle(VMC, I); // Prevent I from being removed!
393 Constant *Dummy = Constant::getNullConstant(Ty);
395 switch (I->getOpcode()) {
396 case Instruction::Cast:
397 Res = new CastInst(I->getOperand(0), Ty, Name);
400 case Instruction::Add:
401 case Instruction::Sub:
402 Res = BinaryOperator::create(cast<BinaryOperator>(I)->getOpcode(),
404 VMC.ExprMap[I] = Res; // Add node to expression eagerly
406 Res->setOperand(0, ConvertExpressionToType(I->getOperand(0), Ty, VMC));
407 Res->setOperand(1, ConvertExpressionToType(I->getOperand(1), Ty, VMC));
410 case Instruction::Shl:
411 case Instruction::Shr:
412 Res = new ShiftInst(cast<ShiftInst>(I)->getOpcode(), Dummy,
413 I->getOperand(1), Name);
414 VMC.ExprMap[I] = Res;
415 Res->setOperand(0, ConvertExpressionToType(I->getOperand(0), Ty, VMC));
418 case Instruction::Load: {
419 LoadInst *LI = cast<LoadInst>(I);
420 assert(!LI->hasIndices() || AllIndicesZero(LI));
422 Res = new LoadInst(Constant::getNullConstant(PointerType::get(Ty)), Name);
423 VMC.ExprMap[I] = Res;
424 Res->setOperand(0, ConvertExpressionToType(LI->getPointerOperand(),
425 PointerType::get(Ty), VMC));
426 assert(Res->getOperand(0)->getType() == PointerType::get(Ty));
427 assert(Ty == Res->getType());
428 assert(Res->getType()->isFirstClassType() && "Load of structure or array!");
432 case Instruction::PHINode: {
433 PHINode *OldPN = cast<PHINode>(I);
434 PHINode *NewPN = new PHINode(Ty, Name);
436 VMC.ExprMap[I] = NewPN; // Add node to expression eagerly
437 while (OldPN->getNumOperands()) {
438 BasicBlock *BB = OldPN->getIncomingBlock(0);
439 Value *OldVal = OldPN->getIncomingValue(0);
440 ValueHandle OldValHandle(VMC, OldVal);
441 OldPN->removeIncomingValue(BB);
442 Value *V = ConvertExpressionToType(OldVal, Ty, VMC);
443 NewPN->addIncoming(V, BB);
449 case Instruction::Malloc: {
450 Res = ConvertMallocToType(cast<MallocInst>(I), Ty, Name, VMC);
454 case Instruction::GetElementPtr: {
455 // GetElementPtr's are directly convertable to a pointer type if they have
456 // a number of zeros at the end. Because removing these values does not
457 // change the logical offset of the GEP, it is okay and fair to remove them.
458 // This can change this:
459 // %t1 = getelementptr %Hosp * %hosp, ubyte 4, ubyte 0 ; <%List **>
460 // %t2 = cast %List * * %t1 to %List *
462 // %t2 = getelementptr %Hosp * %hosp, ubyte 4 ; <%List *>
464 GetElementPtrInst *GEP = cast<GetElementPtrInst>(I);
466 // Check to see if there are zero elements that we can remove from the
467 // index array. If there are, check to see if removing them causes us to
468 // get to the right type...
470 std::vector<Value*> Indices = GEP->copyIndices();
471 const Type *BaseType = GEP->getPointerOperand()->getType();
472 const Type *PVTy = cast<PointerType>(Ty)->getElementType();
474 while (!Indices.empty() && isa<ConstantUInt>(Indices.back()) &&
475 cast<ConstantUInt>(Indices.back())->getValue() == 0) {
477 if (GetElementPtrInst::getIndexedType(BaseType, Indices, true) == PVTy) {
478 if (Indices.size() == 0) {
479 Res = new CastInst(GEP->getPointerOperand(), BaseType); // NOOP
481 Res = new GetElementPtrInst(GEP->getPointerOperand(), Indices, Name);
487 if (Res == 0 && GEP->getNumOperands() == 2 &&
488 GEP->getOperand(1)->getType() == Type::UIntTy &&
489 GEP->getType() == PointerType::get(Type::SByteTy)) {
491 // Otherwise, we can convert a GEP from one form to the other iff the
492 // current gep is of the form 'getelementptr [sbyte]*, unsigned N
493 // and we could convert this to an appropriate GEP for the new type.
495 const PointerType *NewSrcTy = PointerType::get(PVTy);
496 BasicBlock::iterator It = find(BIL.begin(), BIL.end(), I);
498 // Check to see if 'N' is an expression that can be converted to
499 // the appropriate size... if so, allow it.
501 std::vector<Value*> Indices;
502 const Type *ElTy = ConvertableToGEP(NewSrcTy, I->getOperand(1),
505 assert(ElTy == PVTy && "Internal error, setup wrong!");
506 Res = new GetElementPtrInst(Constant::getNullConstant(NewSrcTy),
508 VMC.ExprMap[I] = Res;
509 Res->setOperand(0, ConvertExpressionToType(I->getOperand(0),
514 // Otherwise, it could be that we have something like this:
515 // getelementptr [[sbyte] *] * %reg115, uint %reg138 ; [sbyte]**
516 // and want to convert it into something like this:
517 // getelemenptr [[int] *] * %reg115, uint %reg138 ; [int]**
520 const PointerType *NewSrcTy = PointerType::get(PVTy);
521 Res = new GetElementPtrInst(Constant::getNullConstant(NewSrcTy),
522 GEP->copyIndices(), Name);
523 VMC.ExprMap[I] = Res;
524 Res->setOperand(0, ConvertExpressionToType(I->getOperand(0),
529 assert(Res && "Didn't find match!");
530 break; // No match, maybe next time.
534 assert(0 && "Expression convertable, but don't know how to convert?");
538 assert(Res->getType() == Ty && "Didn't convert expr to correct type!");
540 BasicBlock::iterator It = find(BIL.begin(), BIL.end(), I);
541 assert(It != BIL.end() && "Instruction not in own basic block??");
544 // Add the instruction to the expression map
545 VMC.ExprMap[I] = Res;
547 // Expressions are only convertable if all of the users of the expression can
548 // have this value converted. This makes use of the map to avoid infinite
551 unsigned NumUses = I->use_size();
552 for (unsigned It = 0; It < NumUses; ) {
553 unsigned OldSize = NumUses;
554 ConvertOperandToType(*(I->use_begin()+It), I, Res, VMC);
555 NumUses = I->use_size();
556 if (NumUses == OldSize) ++It;
559 #ifdef DEBUG_EXPR_CONVERT
560 cerr << "ExpIn: " << (void*)I << " " << I
561 << "ExpOut: " << (void*)Res << " " << Res;
564 if (I->use_empty()) {
565 #ifdef DEBUG_EXPR_CONVERT
566 cerr << "EXPR DELETING: " << (void*)I << " " << I;
569 VMC.OperandsMapped.erase(I);
570 VMC.ExprMap.erase(I);
579 // ValueConvertableToType - Return true if it is possible
580 bool ValueConvertableToType(Value *V, const Type *Ty,
581 ValueTypeCache &ConvertedTypes) {
582 ValueTypeCache::iterator I = ConvertedTypes.find(V);
583 if (I != ConvertedTypes.end()) return I->second == Ty;
584 ConvertedTypes[V] = Ty;
586 // It is safe to convert the specified value to the specified type IFF all of
587 // the uses of the value can be converted to accept the new typed value.
589 for (Value::use_iterator I = V->use_begin(), E = V->use_end(); I != E; ++I)
590 if (!OperandConvertableToType(*I, V, Ty, ConvertedTypes))
600 // OperandConvertableToType - Return true if it is possible to convert operand
601 // V of User (instruction) U to the specified type. This is true iff it is
602 // possible to change the specified instruction to accept this. CTMap is a map
603 // of converted types, so that circular definitions will see the future type of
604 // the expression, not the static current type.
606 static bool OperandConvertableToType(User *U, Value *V, const Type *Ty,
607 ValueTypeCache &CTMap) {
608 // if (V->getType() == Ty) return true; // Operand already the right type?
610 // Expression type must be holdable in a register.
611 if (!Ty->isFirstClassType())
614 Instruction *I = dyn_cast<Instruction>(U);
615 if (I == 0) return false; // We can't convert!
617 switch (I->getOpcode()) {
618 case Instruction::Cast:
619 assert(I->getOperand(0) == V);
620 // We can convert the expr if the cast destination type is losslessly
621 // convertable to the requested type.
622 // Also, do not change a cast that is a noop cast. For all intents and
623 // purposes it should be eliminated.
624 if (!Ty->isLosslesslyConvertableTo(I->getOperand(0)->getType()) ||
625 I->getType() == I->getOperand(0)->getType())
630 // We also do not allow conversion of a cast that casts from a ptr to array
631 // of X to a *X. For example: cast [4 x %List *] * %val to %List * *
633 if (PointerType *SPT = dyn_cast<PointerType>(I->getOperand(0)->getType()))
634 if (PointerType *DPT = dyn_cast<PointerType>(I->getType()))
635 if (ArrayType *AT = dyn_cast<ArrayType>(SPT->getElementType()))
636 if (AT->getElementType() == DPT->getElementType())
641 case Instruction::Add:
642 if (isa<PointerType>(Ty)) {
643 Value *IndexVal = I->getOperand(V == I->getOperand(0) ? 1 : 0);
644 std::vector<Value*> Indices;
645 if (const Type *ETy = ConvertableToGEP(Ty, IndexVal, Indices)) {
646 const Type *RetTy = PointerType::get(ETy);
648 // Only successful if we can convert this type to the required type
649 if (ValueConvertableToType(I, RetTy, CTMap)) {
653 // We have to return failure here because ValueConvertableToType could
654 // have polluted our map
659 case Instruction::Sub: {
660 Value *OtherOp = I->getOperand((V == I->getOperand(0)) ? 1 : 0);
661 return ValueConvertableToType(I, Ty, CTMap) &&
662 ExpressionConvertableToType(OtherOp, Ty, CTMap);
664 case Instruction::SetEQ:
665 case Instruction::SetNE: {
666 Value *OtherOp = I->getOperand((V == I->getOperand(0)) ? 1 : 0);
667 return ExpressionConvertableToType(OtherOp, Ty, CTMap);
669 case Instruction::Shr:
670 if (Ty->isSigned() != V->getType()->isSigned()) return false;
672 case Instruction::Shl:
673 assert(I->getOperand(0) == V);
674 return ValueConvertableToType(I, Ty, CTMap);
676 case Instruction::Free:
677 assert(I->getOperand(0) == V);
678 return isa<PointerType>(Ty); // Free can free any pointer type!
680 case Instruction::Load:
681 // Cannot convert the types of any subscripts...
682 if (I->getOperand(0) != V) return false;
684 if (const PointerType *PT = dyn_cast<PointerType>(Ty)) {
685 LoadInst *LI = cast<LoadInst>(I);
687 if (LI->hasIndices() && !AllIndicesZero(LI))
690 const Type *LoadedTy = PT->getElementType();
692 // They could be loading the first element of a composite type...
693 if (const CompositeType *CT = dyn_cast<CompositeType>(LoadedTy)) {
694 unsigned Offset = 0; // No offset, get first leaf.
695 std::vector<Value*> Indices; // Discarded...
696 LoadedTy = getStructOffsetType(CT, Offset, Indices, false);
697 assert(Offset == 0 && "Offset changed from zero???");
700 if (!LoadedTy->isFirstClassType())
703 if (TD.getTypeSize(LoadedTy) != TD.getTypeSize(LI->getType()))
706 return ValueConvertableToType(LI, LoadedTy, CTMap);
710 case Instruction::Store: {
711 StoreInst *SI = cast<StoreInst>(I);
712 if (SI->hasIndices()) return false;
714 if (V == I->getOperand(0)) {
715 // Can convert the store if we can convert the pointer operand to match
716 // the new value type...
717 return ExpressionConvertableToType(I->getOperand(1), PointerType::get(Ty),
719 } else if (const PointerType *PT = dyn_cast<PointerType>(Ty)) {
720 const Type *ElTy = PT->getElementType();
721 assert(V == I->getOperand(1));
723 // Must move the same amount of data...
724 if (TD.getTypeSize(ElTy) != TD.getTypeSize(I->getOperand(0)->getType()))
727 // Can convert store if the incoming value is convertable...
728 return ExpressionConvertableToType(I->getOperand(0), ElTy, CTMap);
733 case Instruction::GetElementPtr:
734 if (V != I->getOperand(0) || !isa<PointerType>(Ty)) return false;
736 // If we have a two operand form of getelementptr, this is really little
737 // more than a simple addition. As with addition, check to see if the
738 // getelementptr instruction can be changed to index into the new type.
740 if (I->getNumOperands() == 2) {
741 const Type *OldElTy = cast<PointerType>(I->getType())->getElementType();
742 unsigned DataSize = TD.getTypeSize(OldElTy);
743 Value *Index = I->getOperand(1);
744 Instruction *TempScale = 0;
746 // If the old data element is not unit sized, we have to create a scale
747 // instruction so that ConvertableToGEP will know the REAL amount we are
748 // indexing by. Note that this is never inserted into the instruction
749 // stream, so we have to delete it when we're done.
752 TempScale = BinaryOperator::create(Instruction::Mul, Index,
753 ConstantUInt::get(Type::UIntTy,
758 // Check to see if the second argument is an expression that can
759 // be converted to the appropriate size... if so, allow it.
761 std::vector<Value*> Indices;
762 const Type *ElTy = ConvertableToGEP(Ty, Index, Indices);
763 delete TempScale; // Free our temporary multiply if we made it
765 if (ElTy == 0) return false; // Cannot make conversion...
766 return ValueConvertableToType(I, PointerType::get(ElTy), CTMap);
770 case Instruction::PHINode: {
771 PHINode *PN = cast<PHINode>(I);
772 for (unsigned i = 0; i < PN->getNumIncomingValues(); ++i)
773 if (!ExpressionConvertableToType(PN->getIncomingValue(i), Ty, CTMap))
775 return ValueConvertableToType(PN, Ty, CTMap);
778 case Instruction::Call: {
779 User::op_iterator OI = find(I->op_begin(), I->op_end(), V);
780 assert (OI != I->op_end() && "Not using value!");
781 unsigned OpNum = OI - I->op_begin();
784 return false; // Can't convert method pointer type yet. FIXME
786 const PointerType *MPtr = cast<PointerType>(I->getOperand(0)->getType());
787 const MethodType *MTy = cast<MethodType>(MPtr->getElementType());
788 if (!MTy->isVarArg()) return false;
790 if ((OpNum-1) < MTy->getParamTypes().size())
791 return false; // It's not in the varargs section...
793 // If we get this far, we know the value is in the varargs section of the
794 // method! We can convert if we don't reinterpret the value...
796 return Ty->isLosslesslyConvertableTo(V->getType());
803 void ConvertValueToNewType(Value *V, Value *NewVal, ValueMapCache &VMC) {
804 ValueHandle VH(VMC, V);
806 unsigned NumUses = V->use_size();
807 for (unsigned It = 0; It < NumUses; ) {
808 unsigned OldSize = NumUses;
809 ConvertOperandToType(*(V->use_begin()+It), V, NewVal, VMC);
810 NumUses = V->use_size();
811 if (NumUses == OldSize) ++It;
817 static void ConvertOperandToType(User *U, Value *OldVal, Value *NewVal,
818 ValueMapCache &VMC) {
819 if (isa<ValueHandle>(U)) return; // Valuehandles don't let go of operands...
821 if (VMC.OperandsMapped.count(U)) return;
822 VMC.OperandsMapped.insert(U);
824 ValueMapCache::ExprMapTy::iterator VMCI = VMC.ExprMap.find(U);
825 if (VMCI != VMC.ExprMap.end())
829 Instruction *I = cast<Instruction>(U); // Only Instructions convertable
831 BasicBlock *BB = I->getParent();
832 BasicBlock::InstListType &BIL = BB->getInstList();
833 std::string Name = I->getName(); if (!Name.empty()) I->setName("");
834 Instruction *Res; // Result of conversion
836 //cerr << endl << endl << "Type:\t" << Ty << "\nInst: " << I << "BB Before: " << BB << endl;
838 // Prevent I from being removed...
839 ValueHandle IHandle(VMC, I);
841 const Type *NewTy = NewVal->getType();
842 Constant *Dummy = (NewTy != Type::VoidTy) ?
843 Constant::getNullConstant(NewTy) : 0;
845 switch (I->getOpcode()) {
846 case Instruction::Cast:
847 assert(I->getOperand(0) == OldVal);
848 Res = new CastInst(NewVal, I->getType(), Name);
851 case Instruction::Add:
852 if (isa<PointerType>(NewTy)) {
853 Value *IndexVal = I->getOperand(OldVal == I->getOperand(0) ? 1 : 0);
854 std::vector<Value*> Indices;
855 BasicBlock::iterator It = find(BIL.begin(), BIL.end(), I);
857 if (const Type *ETy = ConvertableToGEP(NewTy, IndexVal, Indices, &It)) {
858 // If successful, convert the add to a GEP
859 //const Type *RetTy = PointerType::get(ETy);
860 // First operand is actually the given pointer...
861 Res = new GetElementPtrInst(NewVal, Indices, Name);
862 assert(cast<PointerType>(Res->getType())->getElementType() == ETy &&
863 "ConvertableToGEP broken!");
869 case Instruction::Sub:
870 case Instruction::SetEQ:
871 case Instruction::SetNE: {
872 Res = BinaryOperator::create(cast<BinaryOperator>(I)->getOpcode(),
874 VMC.ExprMap[I] = Res; // Add node to expression eagerly
876 unsigned OtherIdx = (OldVal == I->getOperand(0)) ? 1 : 0;
877 Value *OtherOp = I->getOperand(OtherIdx);
878 Value *NewOther = ConvertExpressionToType(OtherOp, NewTy, VMC);
880 Res->setOperand(OtherIdx, NewOther);
881 Res->setOperand(!OtherIdx, NewVal);
884 case Instruction::Shl:
885 case Instruction::Shr:
886 assert(I->getOperand(0) == OldVal);
887 Res = new ShiftInst(cast<ShiftInst>(I)->getOpcode(), NewVal,
888 I->getOperand(1), Name);
891 case Instruction::Free: // Free can free any pointer type!
892 assert(I->getOperand(0) == OldVal);
893 Res = new FreeInst(NewVal);
897 case Instruction::Load: {
898 assert(I->getOperand(0) == OldVal && isa<PointerType>(NewVal->getType()));
899 const Type *LoadedTy =
900 cast<PointerType>(NewVal->getType())->getElementType();
902 std::vector<Value*> Indices;
903 Indices.push_back(ConstantUInt::get(Type::UIntTy, 0));
905 if (const CompositeType *CT = dyn_cast<CompositeType>(LoadedTy)) {
906 unsigned Offset = 0; // No offset, get first leaf.
907 LoadedTy = getStructOffsetType(CT, Offset, Indices, false);
909 assert(LoadedTy->isFirstClassType());
911 Res = new LoadInst(NewVal, Indices, Name);
912 assert(Res->getType()->isFirstClassType() && "Load of structure or array!");
916 case Instruction::Store: {
917 if (I->getOperand(0) == OldVal) { // Replace the source value
918 const PointerType *NewPT = PointerType::get(NewTy);
919 Res = new StoreInst(NewVal, Constant::getNullConstant(NewPT));
920 VMC.ExprMap[I] = Res;
921 Res->setOperand(1, ConvertExpressionToType(I->getOperand(1), NewPT, VMC));
922 } else { // Replace the source pointer
923 const Type *ValTy = cast<PointerType>(NewTy)->getElementType();
924 std::vector<Value*> Indices;
926 Indices.push_back(ConstantUInt::get(Type::UIntTy, 0));
927 while (ArrayType *AT = dyn_cast<ArrayType>(ValTy)) {
928 Indices.push_back(ConstantUInt::get(Type::UIntTy, 0));
929 ValTy = AT->getElementType();
932 Res = new StoreInst(Constant::getNullConstant(ValTy), NewVal, Indices);
933 VMC.ExprMap[I] = Res;
934 Res->setOperand(0, ConvertExpressionToType(I->getOperand(0), ValTy, VMC));
940 case Instruction::GetElementPtr: {
941 // Convert a one index getelementptr into just about anything that is
944 BasicBlock::iterator It = find(BIL.begin(), BIL.end(), I);
945 const Type *OldElTy = cast<PointerType>(I->getType())->getElementType();
946 unsigned DataSize = TD.getTypeSize(OldElTy);
947 Value *Index = I->getOperand(1);
950 // Insert a multiply of the old element type is not a unit size...
951 Index = BinaryOperator::create(Instruction::Mul, Index,
952 ConstantUInt::get(Type::UIntTy, DataSize));
953 It = BIL.insert(It, cast<Instruction>(Index))+1;
956 // Perform the conversion now...
958 std::vector<Value*> Indices;
959 const Type *ElTy = ConvertableToGEP(NewVal->getType(), Index, Indices, &It);
960 assert(ElTy != 0 && "GEP Conversion Failure!");
961 Res = new GetElementPtrInst(NewVal, Indices, Name);
962 assert(Res->getType() == PointerType::get(ElTy) &&
963 "ConvertableToGet failed!");
966 if (I->getType() == PointerType::get(Type::SByteTy)) {
967 // Convert a getelementptr sbyte * %reg111, uint 16 freely back to
968 // anything that is a pointer type...
970 BasicBlock::iterator It = find(BIL.begin(), BIL.end(), I);
972 // Check to see if the second argument is an expression that can
973 // be converted to the appropriate size... if so, allow it.
975 std::vector<Value*> Indices;
976 const Type *ElTy = ConvertableToGEP(NewVal->getType(), I->getOperand(1),
978 assert(ElTy != 0 && "GEP Conversion Failure!");
980 Res = new GetElementPtrInst(NewVal, Indices, Name);
982 // Convert a getelementptr ulong * %reg123, uint %N
983 // to getelementptr long * %reg123, uint %N
984 // ... where the type must simply stay the same size...
986 Res = new GetElementPtrInst(NewVal,
987 cast<GetElementPtrInst>(I)->copyIndices(),
993 case Instruction::PHINode: {
994 PHINode *OldPN = cast<PHINode>(I);
995 PHINode *NewPN = new PHINode(NewTy, Name);
996 VMC.ExprMap[I] = NewPN;
998 while (OldPN->getNumOperands()) {
999 BasicBlock *BB = OldPN->getIncomingBlock(0);
1000 Value *OldVal = OldPN->getIncomingValue(0);
1001 OldPN->removeIncomingValue(BB);
1002 Value *V = ConvertExpressionToType(OldVal, NewTy, VMC);
1003 NewPN->addIncoming(V, BB);
1009 case Instruction::Call: {
1010 Value *Meth = I->getOperand(0);
1011 std::vector<Value*> Params(I->op_begin()+1, I->op_end());
1013 std::vector<Value*>::iterator OI =
1014 find(Params.begin(), Params.end(), OldVal);
1015 assert (OI != Params.end() && "Not using value!");
1018 Res = new CallInst(Meth, Params, Name);
1022 assert(0 && "Expression convertable, but don't know how to convert?");
1026 // If the instruction was newly created, insert it into the instruction
1029 BasicBlock::iterator It = find(BIL.begin(), BIL.end(), I);
1030 assert(It != BIL.end() && "Instruction not in own basic block??");
1031 BIL.insert(It, Res); // Keep It pointing to old instruction
1033 #ifdef DEBUG_EXPR_CONVERT
1034 cerr << "COT CREATED: " << (void*)Res << " " << Res;
1035 cerr << "In: " << (void*)I << " " << I << "Out: " << (void*)Res << " " << Res;
1038 // Add the instruction to the expression map
1039 VMC.ExprMap[I] = Res;
1041 if (I->getType() != Res->getType())
1042 ConvertValueToNewType(I, Res, VMC);
1044 for (unsigned It = 0; It < I->use_size(); ) {
1045 User *Use = *(I->use_begin()+It);
1046 if (isa<ValueHandle>(Use)) // Don't remove ValueHandles!
1049 Use->replaceUsesOfWith(I, Res);
1052 if (I->use_empty()) {
1053 // Now we just need to remove the old instruction so we don't get infinite
1054 // loops. Note that we cannot use DCE because DCE won't remove a store
1055 // instruction, for example.
1057 #ifdef DEBUG_EXPR_CONVERT
1058 cerr << "DELETING: " << (void*)I << " " << I;
1061 VMC.OperandsMapped.erase(I);
1062 VMC.ExprMap.erase(I);
1065 for (Value::use_iterator UI = I->use_begin(), UE = I->use_end();
1067 assert(isa<ValueHandle>((Value*)*UI) &&"Uses of Instruction remain!!!");
1073 ValueHandle::ValueHandle(ValueMapCache &VMC, Value *V)
1074 : Instruction(Type::VoidTy, UserOp1, ""), Cache(VMC) {
1075 #ifdef DEBUG_EXPR_CONVERT
1076 //cerr << "VH AQUIRING: " << (void*)V << " " << V;
1078 Operands.push_back(Use(V, this));
1081 static void RecursiveDelete(ValueMapCache &Cache, Instruction *I) {
1082 if (!I || !I->use_empty()) return;
1084 assert(I->getParent() && "Inst not in basic block!");
1086 #ifdef DEBUG_EXPR_CONVERT
1087 //cerr << "VH DELETING: " << (void*)I << " " << I;
1090 for (User::op_iterator OI = I->op_begin(), OE = I->op_end();
1092 if (Instruction *U = dyn_cast<Instruction>(*OI)) {
1094 RecursiveDelete(Cache, U);
1097 I->getParent()->getInstList().remove(I);
1099 Cache.OperandsMapped.erase(I);
1100 Cache.ExprMap.erase(I);
1104 ValueHandle::~ValueHandle() {
1105 if (Operands[0]->use_size() == 1) {
1106 Value *V = Operands[0];
1107 Operands[0] = 0; // Drop use!
1109 // Now we just need to remove the old instruction so we don't get infinite
1110 // loops. Note that we cannot use DCE because DCE won't remove a store
1111 // instruction, for example.
1113 RecursiveDelete(Cache, dyn_cast<Instruction>(V));
1115 #ifdef DEBUG_EXPR_CONVERT
1116 //cerr << "VH RELEASING: " << (void*)Operands[0].get() << " " << Operands[0]->use_size() << " " << Operands[0];