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/iOther.h"
11 #include "llvm/iPHINode.h"
12 #include "llvm/iMemory.h"
13 #include "llvm/ConstantHandling.h"
14 #include "llvm/Analysis/Expressions.h"
15 #include "Support/STLExtras.h"
16 #include "Support/StatisticReporter.h"
21 static bool OperandConvertableToType(User *U, Value *V, const Type *Ty,
22 ValueTypeCache &ConvertedTypes);
24 static void ConvertOperandToType(User *U, Value *OldVal, Value *NewVal,
27 // AllIndicesZero - Return true if all of the indices of the specified memory
28 // access instruction are zero, indicating an effectively nil offset to the
31 static bool AllIndicesZero(const MemAccessInst *MAI) {
32 for (User::const_op_iterator S = MAI->idx_begin(), E = MAI->idx_end();
34 if (!isa<Constant>(*S) || !cast<Constant>(*S)->isNullValue())
40 // Peephole Malloc instructions: we take a look at the use chain of the
41 // malloc instruction, and try to find out if the following conditions hold:
42 // 1. The malloc is of the form: 'malloc [sbyte], uint <constant>'
43 // 2. The only users of the malloc are cast & add instructions
44 // 3. Of the cast instructions, there is only one destination pointer type
45 // [RTy] where the size of the pointed to object is equal to the number
46 // of bytes allocated.
48 // If these conditions hold, we convert the malloc to allocate an [RTy]
49 // element. TODO: This comment is out of date WRT arrays
51 static bool MallocConvertableToType(MallocInst *MI, const Type *Ty,
52 ValueTypeCache &CTMap) {
53 if (!isa<PointerType>(Ty)) return false; // Malloc always returns pointers
55 // Deal with the type to allocate, not the pointer type...
56 Ty = cast<PointerType>(Ty)->getElementType();
57 if (!Ty->isSized()) return false; // Can only alloc something with a size
59 // Analyze the number of bytes allocated...
60 analysis::ExprType Expr = analysis::ClassifyExpression(MI->getArraySize());
62 // Get information about the base datatype being allocated, before & after
63 int ReqTypeSize = TD.getTypeSize(Ty);
64 unsigned OldTypeSize = TD.getTypeSize(MI->getType()->getElementType());
66 // Must have a scale or offset to analyze it...
67 if (!Expr.Offset && !Expr.Scale && OldTypeSize == 1) return false;
69 // Get the offset and scale of the allocation...
70 int OffsetVal = Expr.Offset ? getConstantValue(Expr.Offset) : 0;
71 int ScaleVal = Expr.Scale ? getConstantValue(Expr.Scale) : (Expr.Var ? 1 : 0);
73 // The old type might not be of unit size, take old size into consideration
75 int Offset = OffsetVal * OldTypeSize;
76 int Scale = ScaleVal * OldTypeSize;
78 // In order to be successful, both the scale and the offset must be a multiple
79 // of the requested data type's size.
81 if (Offset/ReqTypeSize*ReqTypeSize != Offset ||
82 Scale/ReqTypeSize*ReqTypeSize != Scale)
83 return false; // Nope.
88 static Instruction *ConvertMallocToType(MallocInst *MI, const Type *Ty,
89 const std::string &Name,
91 BasicBlock *BB = MI->getParent();
92 BasicBlock::iterator It = BB->end();
94 // Analyze the number of bytes allocated...
95 analysis::ExprType Expr = analysis::ClassifyExpression(MI->getArraySize());
97 const PointerType *AllocTy = cast<PointerType>(Ty);
98 const Type *ElType = AllocTy->getElementType();
100 unsigned DataSize = TD.getTypeSize(ElType);
101 unsigned OldTypeSize = TD.getTypeSize(MI->getType()->getElementType());
103 // Get the offset and scale coefficients that we are allocating...
104 int OffsetVal = (Expr.Offset ? getConstantValue(Expr.Offset) : 0);
105 int ScaleVal = Expr.Scale ? getConstantValue(Expr.Scale) : (Expr.Var ? 1 : 0);
107 // The old type might not be of unit size, take old size into consideration
109 unsigned Offset = (unsigned)OffsetVal * OldTypeSize / DataSize;
110 unsigned Scale = (unsigned)ScaleVal * OldTypeSize / DataSize;
112 // Locate the malloc instruction, because we may be inserting instructions
113 It = find(BB->getInstList().begin(), BB->getInstList().end(), MI);
115 // If we have a scale, apply it first...
117 // Expr.Var is not neccesarily unsigned right now, insert a cast now.
118 if (Expr.Var->getType() != Type::UIntTy) {
119 Instruction *CI = new CastInst(Expr.Var, Type::UIntTy);
120 if (Expr.Var->hasName()) CI->setName(Expr.Var->getName()+"-uint");
121 It = BB->getInstList().insert(It, CI)+1;
127 BinaryOperator::create(Instruction::Mul, Expr.Var,
128 ConstantUInt::get(Type::UIntTy, Scale));
129 if (Expr.Var->hasName()) ScI->setName(Expr.Var->getName()+"-scl");
130 It = BB->getInstList().insert(It, ScI)+1;
135 // If we are not scaling anything, just make the offset be the "var"...
136 Expr.Var = ConstantUInt::get(Type::UIntTy, Offset);
137 Offset = 0; Scale = 1;
140 // If we have an offset now, add it in...
142 assert(Expr.Var && "Var must be nonnull by now!");
145 BinaryOperator::create(Instruction::Add, Expr.Var,
146 ConstantUInt::get(Type::UIntTy, Offset));
147 if (Expr.Var->hasName()) AddI->setName(Expr.Var->getName()+"-off");
148 It = BB->getInstList().insert(It, AddI)+1;
152 Instruction *NewI = new MallocInst(AllocTy, Expr.Var, Name);
154 assert(AllocTy == Ty);
159 // ExpressionConvertableToType - Return true if it is possible
160 bool ExpressionConvertableToType(Value *V, const Type *Ty,
161 ValueTypeCache &CTMap) {
162 if (V->getType() == Ty) return true; // Expression already correct type!
164 // Expression type must be holdable in a register.
165 if (!Ty->isFirstClassType())
168 ValueTypeCache::iterator CTMI = CTMap.find(V);
169 if (CTMI != CTMap.end()) return CTMI->second == Ty;
173 Instruction *I = dyn_cast<Instruction>(V);
175 // It's not an instruction, check to see if it's a constant... all constants
176 // can be converted to an equivalent value (except pointers, they can't be
177 // const prop'd in general). We just ask the constant propogator to see if
178 // it can convert the value...
180 if (Constant *CPV = dyn_cast<Constant>(V))
181 if (ConstantFoldCastInstruction(CPV, Ty))
182 return true; // Don't worry about deallocating, it's a constant.
184 return false; // Otherwise, we can't convert!
187 switch (I->getOpcode()) {
188 case Instruction::Cast:
189 // We can convert the expr if the cast destination type is losslessly
190 // convertable to the requested type.
191 if (!Ty->isLosslesslyConvertableTo(I->getType())) return false;
193 // We also do not allow conversion of a cast that casts from a ptr to array
194 // of X to a *X. For example: cast [4 x %List *] * %val to %List * *
196 if (PointerType *SPT = dyn_cast<PointerType>(I->getOperand(0)->getType()))
197 if (PointerType *DPT = dyn_cast<PointerType>(I->getType()))
198 if (ArrayType *AT = dyn_cast<ArrayType>(SPT->getElementType()))
199 if (AT->getElementType() == DPT->getElementType())
203 case Instruction::Add:
204 case Instruction::Sub:
205 if (!ExpressionConvertableToType(I->getOperand(0), Ty, CTMap) ||
206 !ExpressionConvertableToType(I->getOperand(1), Ty, CTMap))
209 case Instruction::Shr:
210 if (Ty->isSigned() != V->getType()->isSigned()) return false;
212 case Instruction::Shl:
213 if (!ExpressionConvertableToType(I->getOperand(0), Ty, CTMap))
217 case Instruction::Load: {
218 LoadInst *LI = cast<LoadInst>(I);
219 if (LI->hasIndices() && !AllIndicesZero(LI)) {
220 // We can't convert a load expression if it has indices... unless they are
225 if (!ExpressionConvertableToType(LI->getPointerOperand(),
226 PointerType::get(Ty), CTMap))
230 case Instruction::PHINode: {
231 PHINode *PN = cast<PHINode>(I);
232 for (unsigned i = 0; i < PN->getNumIncomingValues(); ++i)
233 if (!ExpressionConvertableToType(PN->getIncomingValue(i), Ty, CTMap))
238 case Instruction::Malloc:
239 if (!MallocConvertableToType(cast<MallocInst>(I), Ty, CTMap))
243 case Instruction::GetElementPtr: {
244 // GetElementPtr's are directly convertable to a pointer type if they have
245 // a number of zeros at the end. Because removing these values does not
246 // change the logical offset of the GEP, it is okay and fair to remove them.
247 // This can change this:
248 // %t1 = getelementptr %Hosp * %hosp, ubyte 4, ubyte 0 ; <%List **>
249 // %t2 = cast %List * * %t1 to %List *
251 // %t2 = getelementptr %Hosp * %hosp, ubyte 4 ; <%List *>
253 GetElementPtrInst *GEP = cast<GetElementPtrInst>(I);
254 const PointerType *PTy = dyn_cast<PointerType>(Ty);
255 if (!PTy) return false; // GEP must always return a pointer...
256 const Type *PVTy = PTy->getElementType();
258 // Check to see if there are zero elements that we can remove from the
259 // index array. If there are, check to see if removing them causes us to
260 // get to the right type...
262 std::vector<Value*> Indices = GEP->copyIndices();
263 const Type *BaseType = GEP->getPointerOperand()->getType();
264 const Type *ElTy = 0;
266 while (!Indices.empty() && isa<ConstantUInt>(Indices.back()) &&
267 cast<ConstantUInt>(Indices.back())->getValue() == 0) {
269 ElTy = GetElementPtrInst::getIndexedType(BaseType, Indices, true);
271 break; // Found a match!!
275 if (ElTy) break; // Found a number of zeros we can strip off!
277 // Otherwise, we can convert a GEP from one form to the other iff the
278 // current gep is of the form 'getelementptr sbyte*, unsigned N
279 // and we could convert this to an appropriate GEP for the new type.
281 if (GEP->getNumOperands() == 2 &&
282 GEP->getOperand(1)->getType() == Type::UIntTy &&
283 GEP->getType() == PointerType::get(Type::SByteTy)) {
285 // Do not Check to see if our incoming pointer can be converted
286 // to be a ptr to an array of the right type... because in more cases than
287 // not, it is simply not analyzable because of pointer/array
288 // discrepencies. To fix this, we will insert a cast before the GEP.
291 // Check to see if 'N' is an expression that can be converted to
292 // the appropriate size... if so, allow it.
294 std::vector<Value*> Indices;
295 const Type *ElTy = ConvertableToGEP(PTy, I->getOperand(1), Indices);
297 if (!ExpressionConvertableToType(I->getOperand(0),
298 PointerType::get(ElTy), CTMap))
299 return false; // Can't continue, ExConToTy might have polluted set!
304 // Otherwise, it could be that we have something like this:
305 // getelementptr [[sbyte] *] * %reg115, uint %reg138 ; [sbyte]**
306 // and want to convert it into something like this:
307 // getelemenptr [[int] *] * %reg115, uint %reg138 ; [int]**
309 if (GEP->getNumOperands() == 2 &&
310 GEP->getOperand(1)->getType() == Type::UIntTy &&
311 TD.getTypeSize(PTy->getElementType()) ==
312 TD.getTypeSize(GEP->getType()->getElementType())) {
313 const PointerType *NewSrcTy = PointerType::get(PVTy);
314 if (!ExpressionConvertableToType(I->getOperand(0), NewSrcTy, CTMap))
319 return false; // No match, maybe next time.
326 // Expressions are only convertable if all of the users of the expression can
327 // have this value converted. This makes use of the map to avoid infinite
330 for (Value::use_iterator It = I->use_begin(), E = I->use_end(); It != E; ++It)
331 if (!OperandConvertableToType(*It, I, Ty, CTMap))
338 Value *ConvertExpressionToType(Value *V, const Type *Ty, ValueMapCache &VMC) {
339 if (V->getType() == Ty) return V; // Already where we need to be?
341 ValueMapCache::ExprMapTy::iterator VMCI = VMC.ExprMap.find(V);
342 if (VMCI != VMC.ExprMap.end()) {
343 assert(VMCI->second->getType() == Ty);
345 if (Instruction *I = dyn_cast<Instruction>(V))
346 ValueHandle IHandle(VMC, I); // Remove I if it is unused now!
351 DEBUG(cerr << "CETT: " << (void*)V << " " << V);
353 Instruction *I = dyn_cast<Instruction>(V);
355 if (Constant *CPV = cast<Constant>(V)) {
356 // Constants are converted by constant folding the cast that is required.
357 // We assume here that all casts are implemented for constant prop.
358 Value *Result = ConstantFoldCastInstruction(CPV, Ty);
359 assert(Result && "ConstantFoldCastInstruction Failed!!!");
360 assert(Result->getType() == Ty && "Const prop of cast failed!");
362 // Add the instruction to the expression map
363 VMC.ExprMap[V] = Result;
368 BasicBlock *BB = I->getParent();
369 BasicBlock::InstListType &BIL = BB->getInstList();
370 std::string Name = I->getName(); if (!Name.empty()) I->setName("");
371 Instruction *Res; // Result of conversion
373 ValueHandle IHandle(VMC, I); // Prevent I from being removed!
375 Constant *Dummy = Constant::getNullValue(Ty);
377 switch (I->getOpcode()) {
378 case Instruction::Cast:
379 Res = new CastInst(I->getOperand(0), Ty, Name);
382 case Instruction::Add:
383 case Instruction::Sub:
384 Res = BinaryOperator::create(cast<BinaryOperator>(I)->getOpcode(),
386 VMC.ExprMap[I] = Res; // Add node to expression eagerly
388 Res->setOperand(0, ConvertExpressionToType(I->getOperand(0), Ty, VMC));
389 Res->setOperand(1, ConvertExpressionToType(I->getOperand(1), Ty, VMC));
392 case Instruction::Shl:
393 case Instruction::Shr:
394 Res = new ShiftInst(cast<ShiftInst>(I)->getOpcode(), Dummy,
395 I->getOperand(1), Name);
396 VMC.ExprMap[I] = Res;
397 Res->setOperand(0, ConvertExpressionToType(I->getOperand(0), Ty, VMC));
400 case Instruction::Load: {
401 LoadInst *LI = cast<LoadInst>(I);
402 assert(!LI->hasIndices() || AllIndicesZero(LI));
404 Res = new LoadInst(Constant::getNullValue(PointerType::get(Ty)), Name);
405 VMC.ExprMap[I] = Res;
406 Res->setOperand(0, ConvertExpressionToType(LI->getPointerOperand(),
407 PointerType::get(Ty), VMC));
408 assert(Res->getOperand(0)->getType() == PointerType::get(Ty));
409 assert(Ty == Res->getType());
410 assert(Res->getType()->isFirstClassType() && "Load of structure or array!");
414 case Instruction::PHINode: {
415 PHINode *OldPN = cast<PHINode>(I);
416 PHINode *NewPN = new PHINode(Ty, Name);
418 VMC.ExprMap[I] = NewPN; // Add node to expression eagerly
419 while (OldPN->getNumOperands()) {
420 BasicBlock *BB = OldPN->getIncomingBlock(0);
421 Value *OldVal = OldPN->getIncomingValue(0);
422 ValueHandle OldValHandle(VMC, OldVal);
423 OldPN->removeIncomingValue(BB);
424 Value *V = ConvertExpressionToType(OldVal, Ty, VMC);
425 NewPN->addIncoming(V, BB);
431 case Instruction::Malloc: {
432 Res = ConvertMallocToType(cast<MallocInst>(I), Ty, Name, VMC);
436 case Instruction::GetElementPtr: {
437 // GetElementPtr's are directly convertable to a pointer type if they have
438 // a number of zeros at the end. Because removing these values does not
439 // change the logical offset of the GEP, it is okay and fair to remove them.
440 // This can change this:
441 // %t1 = getelementptr %Hosp * %hosp, ubyte 4, ubyte 0 ; <%List **>
442 // %t2 = cast %List * * %t1 to %List *
444 // %t2 = getelementptr %Hosp * %hosp, ubyte 4 ; <%List *>
446 GetElementPtrInst *GEP = cast<GetElementPtrInst>(I);
448 // Check to see if there are zero elements that we can remove from the
449 // index array. If there are, check to see if removing them causes us to
450 // get to the right type...
452 std::vector<Value*> Indices = GEP->copyIndices();
453 const Type *BaseType = GEP->getPointerOperand()->getType();
454 const Type *PVTy = cast<PointerType>(Ty)->getElementType();
456 while (!Indices.empty() && isa<ConstantUInt>(Indices.back()) &&
457 cast<ConstantUInt>(Indices.back())->getValue() == 0) {
459 if (GetElementPtrInst::getIndexedType(BaseType, Indices, true) == PVTy) {
460 if (Indices.size() == 0) {
461 Res = new CastInst(GEP->getPointerOperand(), BaseType); // NOOP
463 Res = new GetElementPtrInst(GEP->getPointerOperand(), Indices, Name);
469 if (Res == 0 && GEP->getNumOperands() == 2 &&
470 GEP->getOperand(1)->getType() == Type::UIntTy &&
471 GEP->getType() == PointerType::get(Type::SByteTy)) {
473 // Otherwise, we can convert a GEP from one form to the other iff the
474 // current gep is of the form 'getelementptr [sbyte]*, unsigned N
475 // and we could convert this to an appropriate GEP for the new type.
477 const PointerType *NewSrcTy = PointerType::get(PVTy);
478 BasicBlock::iterator It = find(BIL.begin(), BIL.end(), I);
480 // Check to see if 'N' is an expression that can be converted to
481 // the appropriate size... if so, allow it.
483 std::vector<Value*> Indices;
484 const Type *ElTy = ConvertableToGEP(NewSrcTy, I->getOperand(1),
487 assert(ElTy == PVTy && "Internal error, setup wrong!");
488 Res = new GetElementPtrInst(Constant::getNullValue(NewSrcTy),
490 VMC.ExprMap[I] = Res;
491 Res->setOperand(0, ConvertExpressionToType(I->getOperand(0),
496 // Otherwise, it could be that we have something like this:
497 // getelementptr [[sbyte] *] * %reg115, uint %reg138 ; [sbyte]**
498 // and want to convert it into something like this:
499 // getelemenptr [[int] *] * %reg115, uint %reg138 ; [int]**
502 const PointerType *NewSrcTy = PointerType::get(PVTy);
503 Res = new GetElementPtrInst(Constant::getNullValue(NewSrcTy),
504 GEP->copyIndices(), Name);
505 VMC.ExprMap[I] = Res;
506 Res->setOperand(0, ConvertExpressionToType(I->getOperand(0),
511 assert(Res && "Didn't find match!");
512 break; // No match, maybe next time.
516 assert(0 && "Expression convertable, but don't know how to convert?");
520 assert(Res->getType() == Ty && "Didn't convert expr to correct type!");
522 BasicBlock::iterator It = find(BIL.begin(), BIL.end(), I);
523 assert(It != BIL.end() && "Instruction not in own basic block??");
526 // Add the instruction to the expression map
527 VMC.ExprMap[I] = Res;
529 // Expressions are only convertable if all of the users of the expression can
530 // have this value converted. This makes use of the map to avoid infinite
533 unsigned NumUses = I->use_size();
534 for (unsigned It = 0; It < NumUses; ) {
535 unsigned OldSize = NumUses;
536 ConvertOperandToType(*(I->use_begin()+It), I, Res, VMC);
537 NumUses = I->use_size();
538 if (NumUses == OldSize) ++It;
541 DEBUG(cerr << "ExpIn: " << (void*)I << " " << I
542 << "ExpOut: " << (void*)Res << " " << Res);
544 if (I->use_empty()) {
545 DEBUG(cerr << "EXPR DELETING: " << (void*)I << " " << I);
547 VMC.OperandsMapped.erase(I);
548 VMC.ExprMap.erase(I);
557 // ValueConvertableToType - Return true if it is possible
558 bool ValueConvertableToType(Value *V, const Type *Ty,
559 ValueTypeCache &ConvertedTypes) {
560 ValueTypeCache::iterator I = ConvertedTypes.find(V);
561 if (I != ConvertedTypes.end()) return I->second == Ty;
562 ConvertedTypes[V] = Ty;
564 // It is safe to convert the specified value to the specified type IFF all of
565 // the uses of the value can be converted to accept the new typed value.
567 if (V->getType() != Ty) {
568 for (Value::use_iterator I = V->use_begin(), E = V->use_end(); I != E; ++I)
569 if (!OperandConvertableToType(*I, V, Ty, ConvertedTypes))
580 // OperandConvertableToType - Return true if it is possible to convert operand
581 // V of User (instruction) U to the specified type. This is true iff it is
582 // possible to change the specified instruction to accept this. CTMap is a map
583 // of converted types, so that circular definitions will see the future type of
584 // the expression, not the static current type.
586 static bool OperandConvertableToType(User *U, Value *V, const Type *Ty,
587 ValueTypeCache &CTMap) {
588 // if (V->getType() == Ty) return true; // Operand already the right type?
590 // Expression type must be holdable in a register.
591 if (!Ty->isFirstClassType())
594 Instruction *I = dyn_cast<Instruction>(U);
595 if (I == 0) return false; // We can't convert!
597 switch (I->getOpcode()) {
598 case Instruction::Cast:
599 assert(I->getOperand(0) == V);
600 // We can convert the expr if the cast destination type is losslessly
601 // convertable to the requested type.
602 // Also, do not change a cast that is a noop cast. For all intents and
603 // purposes it should be eliminated.
604 if (!Ty->isLosslesslyConvertableTo(I->getOperand(0)->getType()) ||
605 I->getType() == I->getOperand(0)->getType())
608 // Do not allow a 'cast ushort %V to uint' to have it's first operand be
609 // converted to a 'short' type. Doing so changes the way sign promotion
610 // happens, and breaks things. Only allow the cast to take place if the
611 // signedness doesn't change... or if the current cast is not a lossy
614 if (!I->getType()->isLosslesslyConvertableTo(I->getOperand(0)->getType()) &&
615 I->getOperand(0)->getType()->isSigned() != Ty->isSigned())
618 // We also do not allow conversion of a cast that casts from a ptr to array
619 // of X to a *X. For example: cast [4 x %List *] * %val to %List * *
621 if (PointerType *SPT = dyn_cast<PointerType>(I->getOperand(0)->getType()))
622 if (PointerType *DPT = dyn_cast<PointerType>(I->getType()))
623 if (ArrayType *AT = dyn_cast<ArrayType>(SPT->getElementType()))
624 if (AT->getElementType() == DPT->getElementType())
628 case Instruction::Add:
629 if (isa<PointerType>(Ty)) {
630 Value *IndexVal = I->getOperand(V == I->getOperand(0) ? 1 : 0);
631 std::vector<Value*> Indices;
632 if (const Type *ETy = ConvertableToGEP(Ty, IndexVal, Indices)) {
633 const Type *RetTy = PointerType::get(ETy);
635 // Only successful if we can convert this type to the required type
636 if (ValueConvertableToType(I, RetTy, CTMap)) {
640 // We have to return failure here because ValueConvertableToType could
641 // have polluted our map
646 case Instruction::Sub: {
647 Value *OtherOp = I->getOperand((V == I->getOperand(0)) ? 1 : 0);
648 return ValueConvertableToType(I, Ty, CTMap) &&
649 ExpressionConvertableToType(OtherOp, Ty, CTMap);
651 case Instruction::SetEQ:
652 case Instruction::SetNE: {
653 Value *OtherOp = I->getOperand((V == I->getOperand(0)) ? 1 : 0);
654 return ExpressionConvertableToType(OtherOp, Ty, CTMap);
656 case Instruction::Shr:
657 if (Ty->isSigned() != V->getType()->isSigned()) return false;
659 case Instruction::Shl:
660 assert(I->getOperand(0) == V);
661 return ValueConvertableToType(I, Ty, CTMap);
663 case Instruction::Free:
664 assert(I->getOperand(0) == V);
665 return isa<PointerType>(Ty); // Free can free any pointer type!
667 case Instruction::Load:
668 // Cannot convert the types of any subscripts...
669 if (I->getOperand(0) != V) return false;
671 if (const PointerType *PT = dyn_cast<PointerType>(Ty)) {
672 LoadInst *LI = cast<LoadInst>(I);
674 if (LI->hasIndices() && !AllIndicesZero(LI))
677 const Type *LoadedTy = PT->getElementType();
679 // They could be loading the first element of a composite type...
680 if (const CompositeType *CT = dyn_cast<CompositeType>(LoadedTy)) {
681 unsigned Offset = 0; // No offset, get first leaf.
682 std::vector<Value*> Indices; // Discarded...
683 LoadedTy = getStructOffsetType(CT, Offset, Indices, false);
684 assert(Offset == 0 && "Offset changed from zero???");
687 if (!LoadedTy->isFirstClassType())
690 if (TD.getTypeSize(LoadedTy) != TD.getTypeSize(LI->getType()))
693 return ValueConvertableToType(LI, LoadedTy, CTMap);
697 case Instruction::Store: {
698 StoreInst *SI = cast<StoreInst>(I);
699 if (SI->hasIndices()) return false;
701 if (V == I->getOperand(0)) {
702 ValueTypeCache::iterator CTMI = CTMap.find(I->getOperand(1));
703 if (CTMI != CTMap.end()) { // Operand #1 is in the table already?
704 // If so, check to see if it's Ty*, or, more importantly, if it is a
705 // pointer to a structure where the first element is a Ty... this code
706 // is neccesary because we might be trying to change the source and
707 // destination type of the store (they might be related) and the dest
708 // pointer type might be a pointer to structure. Below we allow pointer
709 // to structures where the 0th element is compatible with the value,
710 // now we have to support the symmetrical part of this.
712 const Type *ElTy = cast<PointerType>(CTMI->second)->getElementType();
714 // Already a pointer to what we want? Trivially accept...
715 if (ElTy == Ty) return true;
717 // Tricky case now, if the destination is a pointer to structure,
718 // obviously the source is not allowed to be a structure (cannot copy
719 // a whole structure at a time), so the level raiser must be trying to
720 // store into the first field. Check for this and allow it now:
722 if (StructType *SElTy = dyn_cast<StructType>(ElTy)) {
724 std::vector<Value*> Indices;
725 ElTy = getStructOffsetType(ElTy, Offset, Indices, false);
726 assert(Offset == 0 && "Offset changed!");
727 if (ElTy == 0) // Element at offset zero in struct doesn't exist!
728 return false; // Can only happen for {}*
730 if (ElTy == Ty) // Looks like the 0th element of structure is
731 return true; // compatible! Accept now!
733 // Otherwise we know that we can't work, so just stop trying now.
738 // Can convert the store if we can convert the pointer operand to match
739 // the new value type...
740 return ExpressionConvertableToType(I->getOperand(1), PointerType::get(Ty),
742 } else if (const PointerType *PT = dyn_cast<PointerType>(Ty)) {
743 const Type *ElTy = PT->getElementType();
744 assert(V == I->getOperand(1));
746 if (isa<StructType>(ElTy)) {
747 // We can change the destination pointer if we can store our first
748 // argument into the first element of the structure...
751 std::vector<Value*> Indices;
752 ElTy = getStructOffsetType(ElTy, Offset, Indices, false);
753 assert(Offset == 0 && "Offset changed!");
754 if (ElTy == 0) // Element at offset zero in struct doesn't exist!
755 return false; // Can only happen for {}*
758 // Must move the same amount of data...
759 if (TD.getTypeSize(ElTy) != TD.getTypeSize(I->getOperand(0)->getType()))
762 // Can convert store if the incoming value is convertable...
763 return ExpressionConvertableToType(I->getOperand(0), ElTy, CTMap);
768 case Instruction::GetElementPtr:
769 if (V != I->getOperand(0) || !isa<PointerType>(Ty)) return false;
771 // If we have a two operand form of getelementptr, this is really little
772 // more than a simple addition. As with addition, check to see if the
773 // getelementptr instruction can be changed to index into the new type.
775 if (I->getNumOperands() == 2) {
776 const Type *OldElTy = cast<PointerType>(I->getType())->getElementType();
777 unsigned DataSize = TD.getTypeSize(OldElTy);
778 Value *Index = I->getOperand(1);
779 Instruction *TempScale = 0;
781 // If the old data element is not unit sized, we have to create a scale
782 // instruction so that ConvertableToGEP will know the REAL amount we are
783 // indexing by. Note that this is never inserted into the instruction
784 // stream, so we have to delete it when we're done.
787 TempScale = BinaryOperator::create(Instruction::Mul, Index,
788 ConstantUInt::get(Type::UIntTy,
793 // Check to see if the second argument is an expression that can
794 // be converted to the appropriate size... if so, allow it.
796 std::vector<Value*> Indices;
797 const Type *ElTy = ConvertableToGEP(Ty, Index, Indices);
798 delete TempScale; // Free our temporary multiply if we made it
800 if (ElTy == 0) return false; // Cannot make conversion...
801 return ValueConvertableToType(I, PointerType::get(ElTy), CTMap);
805 case Instruction::PHINode: {
806 PHINode *PN = cast<PHINode>(I);
807 for (unsigned i = 0; i < PN->getNumIncomingValues(); ++i)
808 if (!ExpressionConvertableToType(PN->getIncomingValue(i), Ty, CTMap))
810 return ValueConvertableToType(PN, Ty, CTMap);
813 case Instruction::Call: {
814 User::op_iterator OI = find(I->op_begin(), I->op_end(), V);
815 assert (OI != I->op_end() && "Not using value!");
816 unsigned OpNum = OI - I->op_begin();
818 // Are we trying to change the function pointer value to a new type?
820 PointerType *PTy = dyn_cast<PointerType>(Ty);
821 if (PTy == 0) return false; // Can't convert to a non-pointer type...
822 FunctionType *MTy = dyn_cast<FunctionType>(PTy->getElementType());
823 if (MTy == 0) return false; // Can't convert to a non ptr to function...
825 // Perform sanity checks to make sure that new function type has the
826 // correct number of arguments...
828 unsigned NumArgs = I->getNumOperands()-1; // Don't include function ptr
830 // Cannot convert to a type that requires more fixed arguments than
831 // the call provides...
833 if (NumArgs < MTy->getParamTypes().size()) return false;
835 // Unless this is a vararg function type, we cannot provide more arguments
836 // than are desired...
838 if (!MTy->isVarArg() && NumArgs > MTy->getParamTypes().size())
841 // Okay, at this point, we know that the call and the function type match
842 // number of arguments. Now we see if we can convert the arguments
843 // themselves. Note that we do not require operands to be convertable,
844 // we can insert casts if they are convertible but not compatible. The
845 // reason for this is that we prefer to have resolved functions but casted
846 // arguments if possible.
848 const FunctionType::ParamTypes &PTs = MTy->getParamTypes();
849 for (unsigned i = 0, NA = PTs.size(); i < NA; ++i)
850 if (!PTs[i]->isLosslesslyConvertableTo(I->getOperand(i+1)->getType()))
851 return false; // Operands must have compatible types!
853 // Okay, at this point, we know that all of the arguments can be
854 // converted. We succeed if we can change the return type if
857 return ValueConvertableToType(I, MTy->getReturnType(), CTMap);
860 const PointerType *MPtr = cast<PointerType>(I->getOperand(0)->getType());
861 const FunctionType *MTy = cast<FunctionType>(MPtr->getElementType());
862 if (!MTy->isVarArg()) return false;
864 if ((OpNum-1) < MTy->getParamTypes().size())
865 return false; // It's not in the varargs section...
867 // If we get this far, we know the value is in the varargs section of the
868 // function! We can convert if we don't reinterpret the value...
870 return Ty->isLosslesslyConvertableTo(V->getType());
877 void ConvertValueToNewType(Value *V, Value *NewVal, ValueMapCache &VMC) {
878 ValueHandle VH(VMC, V);
880 unsigned NumUses = V->use_size();
881 for (unsigned It = 0; It < NumUses; ) {
882 unsigned OldSize = NumUses;
883 ConvertOperandToType(*(V->use_begin()+It), V, NewVal, VMC);
884 NumUses = V->use_size();
885 if (NumUses == OldSize) ++It;
891 static void ConvertOperandToType(User *U, Value *OldVal, Value *NewVal,
892 ValueMapCache &VMC) {
893 if (isa<ValueHandle>(U)) return; // Valuehandles don't let go of operands...
895 if (VMC.OperandsMapped.count(U)) return;
896 VMC.OperandsMapped.insert(U);
898 ValueMapCache::ExprMapTy::iterator VMCI = VMC.ExprMap.find(U);
899 if (VMCI != VMC.ExprMap.end())
903 Instruction *I = cast<Instruction>(U); // Only Instructions convertable
905 BasicBlock *BB = I->getParent();
906 BasicBlock::InstListType &BIL = BB->getInstList();
907 std::string Name = I->getName(); if (!Name.empty()) I->setName("");
908 Instruction *Res; // Result of conversion
910 //cerr << endl << endl << "Type:\t" << Ty << "\nInst: " << I << "BB Before: " << BB << endl;
912 // Prevent I from being removed...
913 ValueHandle IHandle(VMC, I);
915 const Type *NewTy = NewVal->getType();
916 Constant *Dummy = (NewTy != Type::VoidTy) ?
917 Constant::getNullValue(NewTy) : 0;
919 switch (I->getOpcode()) {
920 case Instruction::Cast:
921 assert(I->getOperand(0) == OldVal);
922 Res = new CastInst(NewVal, I->getType(), Name);
925 case Instruction::Add:
926 if (isa<PointerType>(NewTy)) {
927 Value *IndexVal = I->getOperand(OldVal == I->getOperand(0) ? 1 : 0);
928 std::vector<Value*> Indices;
929 BasicBlock::iterator It = find(BIL.begin(), BIL.end(), I);
931 if (const Type *ETy = ConvertableToGEP(NewTy, IndexVal, Indices, &It)) {
932 // If successful, convert the add to a GEP
933 //const Type *RetTy = PointerType::get(ETy);
934 // First operand is actually the given pointer...
935 Res = new GetElementPtrInst(NewVal, Indices, Name);
936 assert(cast<PointerType>(Res->getType())->getElementType() == ETy &&
937 "ConvertableToGEP broken!");
943 case Instruction::Sub:
944 case Instruction::SetEQ:
945 case Instruction::SetNE: {
946 Res = BinaryOperator::create(cast<BinaryOperator>(I)->getOpcode(),
948 VMC.ExprMap[I] = Res; // Add node to expression eagerly
950 unsigned OtherIdx = (OldVal == I->getOperand(0)) ? 1 : 0;
951 Value *OtherOp = I->getOperand(OtherIdx);
952 Value *NewOther = ConvertExpressionToType(OtherOp, NewTy, VMC);
954 Res->setOperand(OtherIdx, NewOther);
955 Res->setOperand(!OtherIdx, NewVal);
958 case Instruction::Shl:
959 case Instruction::Shr:
960 assert(I->getOperand(0) == OldVal);
961 Res = new ShiftInst(cast<ShiftInst>(I)->getOpcode(), NewVal,
962 I->getOperand(1), Name);
965 case Instruction::Free: // Free can free any pointer type!
966 assert(I->getOperand(0) == OldVal);
967 Res = new FreeInst(NewVal);
971 case Instruction::Load: {
972 assert(I->getOperand(0) == OldVal && isa<PointerType>(NewVal->getType()));
973 const Type *LoadedTy =
974 cast<PointerType>(NewVal->getType())->getElementType();
976 std::vector<Value*> Indices;
977 Indices.push_back(ConstantUInt::get(Type::UIntTy, 0));
979 if (const CompositeType *CT = dyn_cast<CompositeType>(LoadedTy)) {
980 unsigned Offset = 0; // No offset, get first leaf.
981 LoadedTy = getStructOffsetType(CT, Offset, Indices, false);
983 assert(LoadedTy->isFirstClassType());
985 Res = new LoadInst(NewVal, Indices, Name);
986 assert(Res->getType()->isFirstClassType() && "Load of structure or array!");
990 case Instruction::Store: {
991 if (I->getOperand(0) == OldVal) { // Replace the source value
992 const PointerType *NewPT = PointerType::get(NewTy);
993 Res = new StoreInst(NewVal, Constant::getNullValue(NewPT));
994 VMC.ExprMap[I] = Res;
995 Res->setOperand(1, ConvertExpressionToType(I->getOperand(1), NewPT, VMC));
996 } else { // Replace the source pointer
997 const Type *ValTy = cast<PointerType>(NewTy)->getElementType();
998 std::vector<Value*> Indices;
1000 if (isa<StructType>(ValTy)) {
1001 unsigned Offset = 0;
1002 Indices.push_back(ConstantUInt::get(Type::UIntTy, 0));
1003 ValTy = getStructOffsetType(ValTy, Offset, Indices, false);
1004 assert(Offset == 0 && ValTy);
1007 Res = new StoreInst(Constant::getNullValue(ValTy), NewVal, Indices);
1008 VMC.ExprMap[I] = Res;
1009 Res->setOperand(0, ConvertExpressionToType(I->getOperand(0), ValTy, VMC));
1015 case Instruction::GetElementPtr: {
1016 // Convert a one index getelementptr into just about anything that is
1019 BasicBlock::iterator It = find(BIL.begin(), BIL.end(), I);
1020 const Type *OldElTy = cast<PointerType>(I->getType())->getElementType();
1021 unsigned DataSize = TD.getTypeSize(OldElTy);
1022 Value *Index = I->getOperand(1);
1024 if (DataSize != 1) {
1025 // Insert a multiply of the old element type is not a unit size...
1026 Index = BinaryOperator::create(Instruction::Mul, Index,
1027 ConstantUInt::get(Type::UIntTy, DataSize));
1028 It = BIL.insert(It, cast<Instruction>(Index))+1;
1031 // Perform the conversion now...
1033 std::vector<Value*> Indices;
1034 const Type *ElTy = ConvertableToGEP(NewVal->getType(), Index, Indices, &It);
1035 assert(ElTy != 0 && "GEP Conversion Failure!");
1036 Res = new GetElementPtrInst(NewVal, Indices, Name);
1037 assert(Res->getType() == PointerType::get(ElTy) &&
1038 "ConvertableToGet failed!");
1041 if (I->getType() == PointerType::get(Type::SByteTy)) {
1042 // Convert a getelementptr sbyte * %reg111, uint 16 freely back to
1043 // anything that is a pointer type...
1045 BasicBlock::iterator It = find(BIL.begin(), BIL.end(), I);
1047 // Check to see if the second argument is an expression that can
1048 // be converted to the appropriate size... if so, allow it.
1050 std::vector<Value*> Indices;
1051 const Type *ElTy = ConvertableToGEP(NewVal->getType(), I->getOperand(1),
1053 assert(ElTy != 0 && "GEP Conversion Failure!");
1055 Res = new GetElementPtrInst(NewVal, Indices, Name);
1057 // Convert a getelementptr ulong * %reg123, uint %N
1058 // to getelementptr long * %reg123, uint %N
1059 // ... where the type must simply stay the same size...
1061 Res = new GetElementPtrInst(NewVal,
1062 cast<GetElementPtrInst>(I)->copyIndices(),
1068 case Instruction::PHINode: {
1069 PHINode *OldPN = cast<PHINode>(I);
1070 PHINode *NewPN = new PHINode(NewTy, Name);
1071 VMC.ExprMap[I] = NewPN;
1073 while (OldPN->getNumOperands()) {
1074 BasicBlock *BB = OldPN->getIncomingBlock(0);
1075 Value *OldVal = OldPN->getIncomingValue(0);
1076 OldPN->removeIncomingValue(BB);
1077 Value *V = ConvertExpressionToType(OldVal, NewTy, VMC);
1078 NewPN->addIncoming(V, BB);
1084 case Instruction::Call: {
1085 Value *Meth = I->getOperand(0);
1086 std::vector<Value*> Params(I->op_begin()+1, I->op_end());
1088 if (Meth == OldVal) { // Changing the function pointer?
1089 PointerType *NewPTy = cast<PointerType>(NewVal->getType());
1090 FunctionType *NewTy = cast<FunctionType>(NewPTy->getElementType());
1091 const FunctionType::ParamTypes &PTs = NewTy->getParamTypes();
1093 // Get an iterator to the call instruction so that we can insert casts for
1094 // operands if needbe. Note that we do not require operands to be
1095 // convertable, we can insert casts if they are convertible but not
1096 // compatible. The reason for this is that we prefer to have resolved
1097 // functions but casted arguments if possible.
1099 BasicBlock::iterator It = find(BIL.begin(), BIL.end(), I);
1101 // Convert over all of the call operands to their new types... but only
1102 // convert over the part that is not in the vararg section of the call.
1104 for (unsigned i = 0; i < PTs.size(); ++i)
1105 if (Params[i]->getType() != PTs[i]) {
1106 // Create a cast to convert it to the right type, we know that this
1107 // is a lossless cast...
1109 Params[i] = new CastInst(Params[i], PTs[i], "call.resolve.cast");
1110 It = BIL.insert(It, cast<Instruction>(Params[i]))+1;
1112 Meth = NewVal; // Update call destination to new value
1114 } else { // Changing an argument, must be in vararg area
1115 std::vector<Value*>::iterator OI =
1116 find(Params.begin(), Params.end(), OldVal);
1117 assert (OI != Params.end() && "Not using value!");
1122 Res = new CallInst(Meth, Params, Name);
1126 assert(0 && "Expression convertable, but don't know how to convert?");
1130 // If the instruction was newly created, insert it into the instruction
1133 BasicBlock::iterator It = find(BIL.begin(), BIL.end(), I);
1134 assert(It != BIL.end() && "Instruction not in own basic block??");
1135 BIL.insert(It, Res); // Keep It pointing to old instruction
1137 DEBUG(cerr << "COT CREATED: " << (void*)Res << " " << Res
1138 << "In: " << (void*)I << " " << I << "Out: " << (void*)Res
1141 // Add the instruction to the expression map
1142 VMC.ExprMap[I] = Res;
1144 if (I->getType() != Res->getType())
1145 ConvertValueToNewType(I, Res, VMC);
1147 for (unsigned It = 0; It < I->use_size(); ) {
1148 User *Use = *(I->use_begin()+It);
1149 if (isa<ValueHandle>(Use)) // Don't remove ValueHandles!
1152 Use->replaceUsesOfWith(I, Res);
1155 if (I->use_empty()) {
1156 // Now we just need to remove the old instruction so we don't get infinite
1157 // loops. Note that we cannot use DCE because DCE won't remove a store
1158 // instruction, for example.
1160 DEBUG(cerr << "DELETING: " << (void*)I << " " << I);
1162 VMC.OperandsMapped.erase(I);
1163 VMC.ExprMap.erase(I);
1166 for (Value::use_iterator UI = I->use_begin(), UE = I->use_end();
1168 assert(isa<ValueHandle>((Value*)*UI) &&"Uses of Instruction remain!!!");
1174 ValueHandle::ValueHandle(ValueMapCache &VMC, Value *V)
1175 : Instruction(Type::VoidTy, UserOp1, ""), Cache(VMC) {
1176 //DEBUG(cerr << "VH AQUIRING: " << (void*)V << " " << V);
1177 Operands.push_back(Use(V, this));
1180 static void RecursiveDelete(ValueMapCache &Cache, Instruction *I) {
1181 if (!I || !I->use_empty()) return;
1183 assert(I->getParent() && "Inst not in basic block!");
1185 //DEBUG(cerr << "VH DELETING: " << (void*)I << " " << I);
1187 for (User::op_iterator OI = I->op_begin(), OE = I->op_end();
1189 if (Instruction *U = dyn_cast<Instruction>(*OI)) {
1191 RecursiveDelete(Cache, U);
1194 I->getParent()->getInstList().remove(I);
1196 Cache.OperandsMapped.erase(I);
1197 Cache.ExprMap.erase(I);
1201 ValueHandle::~ValueHandle() {
1202 if (Operands[0]->use_size() == 1) {
1203 Value *V = Operands[0];
1204 Operands[0] = 0; // Drop use!
1206 // Now we just need to remove the old instruction so we don't get infinite
1207 // loops. Note that we cannot use DCE because DCE won't remove a store
1208 // instruction, for example.
1210 RecursiveDelete(Cache, dyn_cast<Instruction>(V));
1212 //DEBUG(cerr << "VH RELEASING: " << (void*)Operands[0].get() << " "
1213 // << Operands[0]->use_size() << " " << Operands[0]);