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"
20 static bool OperandConvertableToType(User *U, Value *V, const Type *Ty,
21 ValueTypeCache &ConvertedTypes);
23 static void ConvertOperandToType(User *U, Value *OldVal, Value *NewVal,
26 // Peephole Malloc instructions: we take a look at the use chain of the
27 // malloc instruction, and try to find out if the following conditions hold:
28 // 1. The malloc is of the form: 'malloc [sbyte], uint <constant>'
29 // 2. The only users of the malloc are cast & add instructions
30 // 3. Of the cast instructions, there is only one destination pointer type
31 // [RTy] where the size of the pointed to object is equal to the number
32 // of bytes allocated.
34 // If these conditions hold, we convert the malloc to allocate an [RTy]
35 // element. TODO: This comment is out of date WRT arrays
37 static bool MallocConvertableToType(MallocInst *MI, const Type *Ty,
38 ValueTypeCache &CTMap) {
39 if (!isa<PointerType>(Ty)) return false; // Malloc always returns pointers
41 // Deal with the type to allocate, not the pointer type...
42 Ty = cast<PointerType>(Ty)->getElementType();
43 if (!Ty->isSized()) return false; // Can only alloc something with a size
45 // Analyze the number of bytes allocated...
46 ExprType Expr = ClassifyExpression(MI->getArraySize());
48 // Get information about the base datatype being allocated, before & after
49 int ReqTypeSize = TD.getTypeSize(Ty);
50 unsigned OldTypeSize = TD.getTypeSize(MI->getType()->getElementType());
52 // Must have a scale or offset to analyze it...
53 if (!Expr.Offset && !Expr.Scale && OldTypeSize == 1) return false;
55 // Get the offset and scale of the allocation...
56 int OffsetVal = Expr.Offset ? getConstantValue(Expr.Offset) : 0;
57 int ScaleVal = Expr.Scale ? getConstantValue(Expr.Scale) : (Expr.Var ? 1 : 0);
59 // The old type might not be of unit size, take old size into consideration
61 int Offset = OffsetVal * OldTypeSize;
62 int Scale = ScaleVal * OldTypeSize;
64 // In order to be successful, both the scale and the offset must be a multiple
65 // of the requested data type's size.
67 if (Offset/ReqTypeSize*ReqTypeSize != Offset ||
68 Scale/ReqTypeSize*ReqTypeSize != Scale)
69 return false; // Nope.
74 static Instruction *ConvertMallocToType(MallocInst *MI, const Type *Ty,
75 const std::string &Name,
77 BasicBlock *BB = MI->getParent();
78 BasicBlock::iterator It = BB->end();
80 // Analyze the number of bytes allocated...
81 ExprType Expr = ClassifyExpression(MI->getArraySize());
83 const PointerType *AllocTy = cast<PointerType>(Ty);
84 const Type *ElType = AllocTy->getElementType();
86 unsigned DataSize = TD.getTypeSize(ElType);
87 unsigned OldTypeSize = TD.getTypeSize(MI->getType()->getElementType());
89 // Get the offset and scale coefficients that we are allocating...
90 int OffsetVal = (Expr.Offset ? getConstantValue(Expr.Offset) : 0);
91 int ScaleVal = Expr.Scale ? getConstantValue(Expr.Scale) : (Expr.Var ? 1 : 0);
93 // The old type might not be of unit size, take old size into consideration
95 unsigned Offset = (unsigned)OffsetVal * OldTypeSize / DataSize;
96 unsigned Scale = (unsigned)ScaleVal * OldTypeSize / DataSize;
98 // Locate the malloc instruction, because we may be inserting instructions
101 // If we have a scale, apply it first...
103 // Expr.Var is not neccesarily unsigned right now, insert a cast now.
104 if (Expr.Var->getType() != Type::UIntTy)
105 Expr.Var = new CastInst(Expr.Var, Type::UIntTy,
106 Expr.Var->getName()+"-uint", It);
109 Expr.Var = BinaryOperator::create(Instruction::Mul, Expr.Var,
110 ConstantUInt::get(Type::UIntTy, Scale),
111 Expr.Var->getName()+"-scl", It);
114 // If we are not scaling anything, just make the offset be the "var"...
115 Expr.Var = ConstantUInt::get(Type::UIntTy, Offset);
116 Offset = 0; Scale = 1;
119 // If we have an offset now, add it in...
121 assert(Expr.Var && "Var must be nonnull by now!");
122 Expr.Var = BinaryOperator::create(Instruction::Add, Expr.Var,
123 ConstantUInt::get(Type::UIntTy, Offset),
124 Expr.Var->getName()+"-off", It);
127 assert(AllocTy == Ty);
128 return = new MallocInst(AllocTy, Expr.Var, Name);
132 // ExpressionConvertableToType - Return true if it is possible
133 bool ExpressionConvertableToType(Value *V, const Type *Ty,
134 ValueTypeCache &CTMap) {
135 // Expression type must be holdable in a register.
136 if (!Ty->isFirstClassType())
139 ValueTypeCache::iterator CTMI = CTMap.find(V);
140 if (CTMI != CTMap.end()) return CTMI->second == Ty;
143 if (V->getType() == Ty) return true; // Expression already correct type!
145 Instruction *I = dyn_cast<Instruction>(V);
147 // It's not an instruction, check to see if it's a constant... all constants
148 // can be converted to an equivalent value (except pointers, they can't be
149 // const prop'd in general). We just ask the constant propogator to see if
150 // it can convert the value...
152 if (Constant *CPV = dyn_cast<Constant>(V))
153 if (ConstantFoldCastInstruction(CPV, Ty))
154 return true; // Don't worry about deallocating, it's a constant.
156 return false; // Otherwise, we can't convert!
159 switch (I->getOpcode()) {
160 case Instruction::Cast:
161 // We can convert the expr if the cast destination type is losslessly
162 // convertable to the requested type.
163 if (!Ty->isLosslesslyConvertableTo(I->getType())) return false;
165 // We also do not allow conversion of a cast that casts from a ptr to array
166 // of X to a *X. For example: cast [4 x %List *] * %val to %List * *
168 if (const PointerType *SPT =
169 dyn_cast<PointerType>(I->getOperand(0)->getType()))
170 if (const PointerType *DPT = dyn_cast<PointerType>(I->getType()))
171 if (const ArrayType *AT = dyn_cast<ArrayType>(SPT->getElementType()))
172 if (AT->getElementType() == DPT->getElementType())
176 case Instruction::Add:
177 case Instruction::Sub:
178 if (!Ty->isInteger() && !Ty->isFloatingPoint()) return false;
179 if (!ExpressionConvertableToType(I->getOperand(0), Ty, CTMap) ||
180 !ExpressionConvertableToType(I->getOperand(1), Ty, CTMap))
183 case Instruction::Shr:
184 if (!Ty->isInteger()) return false;
185 if (Ty->isSigned() != V->getType()->isSigned()) return false;
187 case Instruction::Shl:
188 if (!Ty->isInteger()) return false;
189 if (!ExpressionConvertableToType(I->getOperand(0), Ty, CTMap))
193 case Instruction::Load: {
194 LoadInst *LI = cast<LoadInst>(I);
195 if (!ExpressionConvertableToType(LI->getPointerOperand(),
196 PointerType::get(Ty), CTMap))
200 case Instruction::PHINode: {
201 PHINode *PN = cast<PHINode>(I);
202 for (unsigned i = 0; i < PN->getNumIncomingValues(); ++i)
203 if (!ExpressionConvertableToType(PN->getIncomingValue(i), Ty, CTMap))
208 case Instruction::Malloc:
209 if (!MallocConvertableToType(cast<MallocInst>(I), Ty, CTMap))
213 case Instruction::GetElementPtr: {
214 // GetElementPtr's are directly convertable to a pointer type if they have
215 // a number of zeros at the end. Because removing these values does not
216 // change the logical offset of the GEP, it is okay and fair to remove them.
217 // This can change this:
218 // %t1 = getelementptr %Hosp * %hosp, ubyte 4, ubyte 0 ; <%List **>
219 // %t2 = cast %List * * %t1 to %List *
221 // %t2 = getelementptr %Hosp * %hosp, ubyte 4 ; <%List *>
223 GetElementPtrInst *GEP = cast<GetElementPtrInst>(I);
224 const PointerType *PTy = dyn_cast<PointerType>(Ty);
225 if (!PTy) return false; // GEP must always return a pointer...
226 const Type *PVTy = PTy->getElementType();
228 // Check to see if there are zero elements that we can remove from the
229 // index array. If there are, check to see if removing them causes us to
230 // get to the right type...
232 std::vector<Value*> Indices(GEP->idx_begin(), GEP->idx_end());
233 const Type *BaseType = GEP->getPointerOperand()->getType();
234 const Type *ElTy = 0;
236 while (!Indices.empty() && isa<ConstantUInt>(Indices.back()) &&
237 cast<ConstantUInt>(Indices.back())->getValue() == 0) {
239 ElTy = GetElementPtrInst::getIndexedType(BaseType, Indices, true);
241 break; // Found a match!!
245 if (ElTy) break; // Found a number of zeros we can strip off!
247 // Otherwise, we can convert a GEP from one form to the other iff the
248 // current gep is of the form 'getelementptr sbyte*, unsigned N
249 // and we could convert this to an appropriate GEP for the new type.
251 if (GEP->getNumOperands() == 2 &&
252 GEP->getOperand(1)->getType() == Type::UIntTy &&
253 GEP->getType() == PointerType::get(Type::SByteTy)) {
255 // Do not Check to see if our incoming pointer can be converted
256 // to be a ptr to an array of the right type... because in more cases than
257 // not, it is simply not analyzable because of pointer/array
258 // discrepencies. To fix this, we will insert a cast before the GEP.
261 // Check to see if 'N' is an expression that can be converted to
262 // the appropriate size... if so, allow it.
264 std::vector<Value*> Indices;
265 const Type *ElTy = ConvertableToGEP(PTy, I->getOperand(1), Indices);
267 if (!ExpressionConvertableToType(I->getOperand(0),
268 PointerType::get(ElTy), CTMap))
269 return false; // Can't continue, ExConToTy might have polluted set!
274 // Otherwise, it could be that we have something like this:
275 // getelementptr [[sbyte] *] * %reg115, uint %reg138 ; [sbyte]**
276 // and want to convert it into something like this:
277 // getelemenptr [[int] *] * %reg115, uint %reg138 ; [int]**
279 if (GEP->getNumOperands() == 2 &&
280 GEP->getOperand(1)->getType() == Type::UIntTy &&
281 TD.getTypeSize(PTy->getElementType()) ==
282 TD.getTypeSize(GEP->getType()->getElementType())) {
283 const PointerType *NewSrcTy = PointerType::get(PVTy);
284 if (!ExpressionConvertableToType(I->getOperand(0), NewSrcTy, CTMap))
289 return false; // No match, maybe next time.
296 // Expressions are only convertable if all of the users of the expression can
297 // have this value converted. This makes use of the map to avoid infinite
300 for (Value::use_iterator It = I->use_begin(), E = I->use_end(); It != E; ++It)
301 if (!OperandConvertableToType(*It, I, Ty, CTMap))
308 Value *ConvertExpressionToType(Value *V, const Type *Ty, ValueMapCache &VMC) {
309 if (V->getType() == Ty) return V; // Already where we need to be?
311 ValueMapCache::ExprMapTy::iterator VMCI = VMC.ExprMap.find(V);
312 if (VMCI != VMC.ExprMap.end()) {
313 const Value *GV = VMCI->second;
314 const Type *GTy = VMCI->second->getType();
315 assert(VMCI->second->getType() == Ty);
317 if (Instruction *I = dyn_cast<Instruction>(V))
318 ValueHandle IHandle(VMC, I); // Remove I if it is unused now!
323 DEBUG(cerr << "CETT: " << (void*)V << " " << V);
325 Instruction *I = dyn_cast<Instruction>(V);
327 if (Constant *CPV = cast<Constant>(V)) {
328 // Constants are converted by constant folding the cast that is required.
329 // We assume here that all casts are implemented for constant prop.
330 Value *Result = ConstantFoldCastInstruction(CPV, Ty);
331 assert(Result && "ConstantFoldCastInstruction Failed!!!");
332 assert(Result->getType() == Ty && "Const prop of cast failed!");
334 // Add the instruction to the expression map
335 VMC.ExprMap[V] = Result;
340 BasicBlock *BB = I->getParent();
341 std::string Name = I->getName(); if (!Name.empty()) I->setName("");
342 Instruction *Res; // Result of conversion
344 ValueHandle IHandle(VMC, I); // Prevent I from being removed!
346 Constant *Dummy = Constant::getNullValue(Ty);
348 switch (I->getOpcode()) {
349 case Instruction::Cast:
350 assert(VMC.NewCasts.count(ValueHandle(VMC, I)) == 0);
351 Res = new CastInst(I->getOperand(0), Ty, Name);
352 VMC.NewCasts.insert(ValueHandle(VMC, Res));
355 case Instruction::Add:
356 case Instruction::Sub:
357 Res = BinaryOperator::create(cast<BinaryOperator>(I)->getOpcode(),
359 VMC.ExprMap[I] = Res; // Add node to expression eagerly
361 Res->setOperand(0, ConvertExpressionToType(I->getOperand(0), Ty, VMC));
362 Res->setOperand(1, ConvertExpressionToType(I->getOperand(1), Ty, VMC));
365 case Instruction::Shl:
366 case Instruction::Shr:
367 Res = new ShiftInst(cast<ShiftInst>(I)->getOpcode(), Dummy,
368 I->getOperand(1), Name);
369 VMC.ExprMap[I] = Res;
370 Res->setOperand(0, ConvertExpressionToType(I->getOperand(0), Ty, VMC));
373 case Instruction::Load: {
374 LoadInst *LI = cast<LoadInst>(I);
376 Res = new LoadInst(Constant::getNullValue(PointerType::get(Ty)), Name);
377 VMC.ExprMap[I] = Res;
378 Res->setOperand(0, ConvertExpressionToType(LI->getPointerOperand(),
379 PointerType::get(Ty), VMC));
380 assert(Res->getOperand(0)->getType() == PointerType::get(Ty));
381 assert(Ty == Res->getType());
382 assert(Res->getType()->isFirstClassType() && "Load of structure or array!");
386 case Instruction::PHINode: {
387 PHINode *OldPN = cast<PHINode>(I);
388 PHINode *NewPN = new PHINode(Ty, Name);
390 VMC.ExprMap[I] = NewPN; // Add node to expression eagerly
391 while (OldPN->getNumOperands()) {
392 BasicBlock *BB = OldPN->getIncomingBlock(0);
393 Value *OldVal = OldPN->getIncomingValue(0);
394 ValueHandle OldValHandle(VMC, OldVal);
395 OldPN->removeIncomingValue(BB);
396 Value *V = ConvertExpressionToType(OldVal, Ty, VMC);
397 NewPN->addIncoming(V, BB);
403 case Instruction::Malloc: {
404 Res = ConvertMallocToType(cast<MallocInst>(I), Ty, Name, VMC);
408 case Instruction::GetElementPtr: {
409 // GetElementPtr's are directly convertable to a pointer type if they have
410 // a number of zeros at the end. Because removing these values does not
411 // change the logical offset of the GEP, it is okay and fair to remove them.
412 // This can change this:
413 // %t1 = getelementptr %Hosp * %hosp, ubyte 4, ubyte 0 ; <%List **>
414 // %t2 = cast %List * * %t1 to %List *
416 // %t2 = getelementptr %Hosp * %hosp, ubyte 4 ; <%List *>
418 GetElementPtrInst *GEP = cast<GetElementPtrInst>(I);
420 // Check to see if there are zero elements that we can remove from the
421 // index array. If there are, check to see if removing them causes us to
422 // get to the right type...
424 std::vector<Value*> Indices(GEP->idx_begin(), GEP->idx_end());
425 const Type *BaseType = GEP->getPointerOperand()->getType();
426 const Type *PVTy = cast<PointerType>(Ty)->getElementType();
428 while (!Indices.empty() && isa<ConstantUInt>(Indices.back()) &&
429 cast<ConstantUInt>(Indices.back())->getValue() == 0) {
431 if (GetElementPtrInst::getIndexedType(BaseType, Indices, true) == PVTy) {
432 if (Indices.size() == 0) {
433 Res = new CastInst(GEP->getPointerOperand(), BaseType); // NOOP
435 Res = new GetElementPtrInst(GEP->getPointerOperand(), Indices, Name);
441 if (Res == 0 && GEP->getNumOperands() == 2 &&
442 GEP->getOperand(1)->getType() == Type::UIntTy &&
443 GEP->getType() == PointerType::get(Type::SByteTy)) {
445 // Otherwise, we can convert a GEP from one form to the other iff the
446 // current gep is of the form 'getelementptr [sbyte]*, unsigned N
447 // and we could convert this to an appropriate GEP for the new type.
449 const PointerType *NewSrcTy = PointerType::get(PVTy);
450 BasicBlock::iterator It = I;
452 // Check to see if 'N' is an expression that can be converted to
453 // the appropriate size... if so, allow it.
455 std::vector<Value*> Indices;
456 const Type *ElTy = ConvertableToGEP(NewSrcTy, I->getOperand(1),
459 assert(ElTy == PVTy && "Internal error, setup wrong!");
460 Res = new GetElementPtrInst(Constant::getNullValue(NewSrcTy),
462 VMC.ExprMap[I] = Res;
463 Res->setOperand(0, ConvertExpressionToType(I->getOperand(0),
468 // Otherwise, it could be that we have something like this:
469 // getelementptr [[sbyte] *] * %reg115, uint %reg138 ; [sbyte]**
470 // and want to convert it into something like this:
471 // getelemenptr [[int] *] * %reg115, uint %reg138 ; [int]**
474 const PointerType *NewSrcTy = PointerType::get(PVTy);
475 std::vector<Value*> Indices(GEP->idx_begin(), GEP->idx_end());
476 Res = new GetElementPtrInst(Constant::getNullValue(NewSrcTy),
478 VMC.ExprMap[I] = Res;
479 Res->setOperand(0, ConvertExpressionToType(I->getOperand(0),
484 assert(Res && "Didn't find match!");
485 break; // No match, maybe next time.
489 assert(0 && "Expression convertable, but don't know how to convert?");
493 assert(Res->getType() == Ty && "Didn't convert expr to correct type!");
495 BB->getInstList().insert(I, Res);
497 // Add the instruction to the expression map
498 VMC.ExprMap[I] = Res;
500 // Expressions are only convertable if all of the users of the expression can
501 // have this value converted. This makes use of the map to avoid infinite
504 unsigned NumUses = I->use_size();
505 for (unsigned It = 0; It < NumUses; ) {
506 unsigned OldSize = NumUses;
507 ConvertOperandToType(*(I->use_begin()+It), I, Res, VMC);
508 NumUses = I->use_size();
509 if (NumUses == OldSize) ++It;
512 DEBUG(cerr << "ExpIn: " << (void*)I << " " << I
513 << "ExpOut: " << (void*)Res << " " << Res);
520 // ValueConvertableToType - Return true if it is possible
521 bool ValueConvertableToType(Value *V, const Type *Ty,
522 ValueTypeCache &ConvertedTypes) {
523 ValueTypeCache::iterator I = ConvertedTypes.find(V);
524 if (I != ConvertedTypes.end()) return I->second == Ty;
525 ConvertedTypes[V] = Ty;
527 // It is safe to convert the specified value to the specified type IFF all of
528 // the uses of the value can be converted to accept the new typed value.
530 if (V->getType() != Ty) {
531 for (Value::use_iterator I = V->use_begin(), E = V->use_end(); I != E; ++I)
532 if (!OperandConvertableToType(*I, V, Ty, ConvertedTypes))
543 // OperandConvertableToType - Return true if it is possible to convert operand
544 // V of User (instruction) U to the specified type. This is true iff it is
545 // possible to change the specified instruction to accept this. CTMap is a map
546 // of converted types, so that circular definitions will see the future type of
547 // the expression, not the static current type.
549 static bool OperandConvertableToType(User *U, Value *V, const Type *Ty,
550 ValueTypeCache &CTMap) {
551 // if (V->getType() == Ty) return true; // Operand already the right type?
553 // Expression type must be holdable in a register.
554 if (!Ty->isFirstClassType())
557 Instruction *I = dyn_cast<Instruction>(U);
558 if (I == 0) return false; // We can't convert!
560 switch (I->getOpcode()) {
561 case Instruction::Cast:
562 assert(I->getOperand(0) == V);
563 // We can convert the expr if the cast destination type is losslessly
564 // convertable to the requested type.
565 // Also, do not change a cast that is a noop cast. For all intents and
566 // purposes it should be eliminated.
567 if (!Ty->isLosslesslyConvertableTo(I->getOperand(0)->getType()) ||
568 I->getType() == I->getOperand(0)->getType())
571 // Do not allow a 'cast ushort %V to uint' to have it's first operand be
572 // converted to a 'short' type. Doing so changes the way sign promotion
573 // happens, and breaks things. Only allow the cast to take place if the
574 // signedness doesn't change... or if the current cast is not a lossy
577 if (!I->getType()->isLosslesslyConvertableTo(I->getOperand(0)->getType()) &&
578 I->getOperand(0)->getType()->isSigned() != Ty->isSigned())
581 // We also do not allow conversion of a cast that casts from a ptr to array
582 // of X to a *X. For example: cast [4 x %List *] * %val to %List * *
584 if (const PointerType *SPT =
585 dyn_cast<PointerType>(I->getOperand(0)->getType()))
586 if (const PointerType *DPT = dyn_cast<PointerType>(I->getType()))
587 if (const ArrayType *AT = dyn_cast<ArrayType>(SPT->getElementType()))
588 if (AT->getElementType() == DPT->getElementType())
592 case Instruction::Add:
593 if (isa<PointerType>(Ty)) {
594 Value *IndexVal = I->getOperand(V == I->getOperand(0) ? 1 : 0);
595 std::vector<Value*> Indices;
596 if (const Type *ETy = ConvertableToGEP(Ty, IndexVal, Indices)) {
597 const Type *RetTy = PointerType::get(ETy);
599 // Only successful if we can convert this type to the required type
600 if (ValueConvertableToType(I, RetTy, CTMap)) {
604 // We have to return failure here because ValueConvertableToType could
605 // have polluted our map
610 case Instruction::Sub: {
611 if (!Ty->isInteger() && !Ty->isFloatingPoint()) return false;
613 Value *OtherOp = I->getOperand((V == I->getOperand(0)) ? 1 : 0);
614 return ValueConvertableToType(I, Ty, CTMap) &&
615 ExpressionConvertableToType(OtherOp, Ty, CTMap);
617 case Instruction::SetEQ:
618 case Instruction::SetNE: {
619 Value *OtherOp = I->getOperand((V == I->getOperand(0)) ? 1 : 0);
620 return ExpressionConvertableToType(OtherOp, Ty, CTMap);
622 case Instruction::Shr:
623 if (Ty->isSigned() != V->getType()->isSigned()) return false;
625 case Instruction::Shl:
626 assert(I->getOperand(0) == V);
627 if (!Ty->isInteger()) return false;
628 return ValueConvertableToType(I, Ty, CTMap);
630 case Instruction::Free:
631 assert(I->getOperand(0) == V);
632 return isa<PointerType>(Ty); // Free can free any pointer type!
634 case Instruction::Load:
635 // Cannot convert the types of any subscripts...
636 if (I->getOperand(0) != V) return false;
638 if (const PointerType *PT = dyn_cast<PointerType>(Ty)) {
639 LoadInst *LI = cast<LoadInst>(I);
641 const Type *LoadedTy = PT->getElementType();
643 // They could be loading the first element of a composite type...
644 if (const CompositeType *CT = dyn_cast<CompositeType>(LoadedTy)) {
645 unsigned Offset = 0; // No offset, get first leaf.
646 std::vector<Value*> Indices; // Discarded...
647 LoadedTy = getStructOffsetType(CT, Offset, Indices, false);
648 assert(Offset == 0 && "Offset changed from zero???");
651 if (!LoadedTy->isFirstClassType())
654 if (TD.getTypeSize(LoadedTy) != TD.getTypeSize(LI->getType()))
657 return ValueConvertableToType(LI, LoadedTy, CTMap);
661 case Instruction::Store: {
662 StoreInst *SI = cast<StoreInst>(I);
664 if (V == I->getOperand(0)) {
665 ValueTypeCache::iterator CTMI = CTMap.find(I->getOperand(1));
666 if (CTMI != CTMap.end()) { // Operand #1 is in the table already?
667 // If so, check to see if it's Ty*, or, more importantly, if it is a
668 // pointer to a structure where the first element is a Ty... this code
669 // is neccesary because we might be trying to change the source and
670 // destination type of the store (they might be related) and the dest
671 // pointer type might be a pointer to structure. Below we allow pointer
672 // to structures where the 0th element is compatible with the value,
673 // now we have to support the symmetrical part of this.
675 const Type *ElTy = cast<PointerType>(CTMI->second)->getElementType();
677 // Already a pointer to what we want? Trivially accept...
678 if (ElTy == Ty) return true;
680 // Tricky case now, if the destination is a pointer to structure,
681 // obviously the source is not allowed to be a structure (cannot copy
682 // a whole structure at a time), so the level raiser must be trying to
683 // store into the first field. Check for this and allow it now:
685 if (const StructType *SElTy = dyn_cast<StructType>(ElTy)) {
687 std::vector<Value*> Indices;
688 ElTy = getStructOffsetType(ElTy, Offset, Indices, false);
689 assert(Offset == 0 && "Offset changed!");
690 if (ElTy == 0) // Element at offset zero in struct doesn't exist!
691 return false; // Can only happen for {}*
693 if (ElTy == Ty) // Looks like the 0th element of structure is
694 return true; // compatible! Accept now!
696 // Otherwise we know that we can't work, so just stop trying now.
701 // Can convert the store if we can convert the pointer operand to match
702 // the new value type...
703 return ExpressionConvertableToType(I->getOperand(1), PointerType::get(Ty),
705 } else if (const PointerType *PT = dyn_cast<PointerType>(Ty)) {
706 const Type *ElTy = PT->getElementType();
707 assert(V == I->getOperand(1));
709 if (isa<StructType>(ElTy)) {
710 // We can change the destination pointer if we can store our first
711 // argument into the first element of the structure...
714 std::vector<Value*> Indices;
715 ElTy = getStructOffsetType(ElTy, Offset, Indices, false);
716 assert(Offset == 0 && "Offset changed!");
717 if (ElTy == 0) // Element at offset zero in struct doesn't exist!
718 return false; // Can only happen for {}*
721 // Must move the same amount of data...
722 if (!ElTy->isSized() ||
723 TD.getTypeSize(ElTy) != TD.getTypeSize(I->getOperand(0)->getType()))
726 // Can convert store if the incoming value is convertable...
727 return ExpressionConvertableToType(I->getOperand(0), ElTy, CTMap);
732 case Instruction::GetElementPtr:
733 if (V != I->getOperand(0) || !isa<PointerType>(Ty)) return false;
735 // If we have a two operand form of getelementptr, this is really little
736 // more than a simple addition. As with addition, check to see if the
737 // getelementptr instruction can be changed to index into the new type.
739 if (I->getNumOperands() == 2) {
740 const Type *OldElTy = cast<PointerType>(I->getType())->getElementType();
741 unsigned DataSize = TD.getTypeSize(OldElTy);
742 Value *Index = I->getOperand(1);
743 Instruction *TempScale = 0;
745 // If the old data element is not unit sized, we have to create a scale
746 // instruction so that ConvertableToGEP will know the REAL amount we are
747 // indexing by. Note that this is never inserted into the instruction
748 // stream, so we have to delete it when we're done.
751 TempScale = BinaryOperator::create(Instruction::Mul, Index,
752 ConstantUInt::get(Type::UIntTy,
757 // Check to see if the second argument is an expression that can
758 // be converted to the appropriate size... if so, allow it.
760 std::vector<Value*> Indices;
761 const Type *ElTy = ConvertableToGEP(Ty, Index, Indices);
762 delete TempScale; // Free our temporary multiply if we made it
764 if (ElTy == 0) return false; // Cannot make conversion...
765 return ValueConvertableToType(I, PointerType::get(ElTy), CTMap);
769 case Instruction::PHINode: {
770 PHINode *PN = cast<PHINode>(I);
771 for (unsigned i = 0; i < PN->getNumIncomingValues(); ++i)
772 if (!ExpressionConvertableToType(PN->getIncomingValue(i), Ty, CTMap))
774 return ValueConvertableToType(PN, Ty, CTMap);
777 case Instruction::Call: {
778 User::op_iterator OI = find(I->op_begin(), I->op_end(), V);
779 assert (OI != I->op_end() && "Not using value!");
780 unsigned OpNum = OI - I->op_begin();
782 // Are we trying to change the function pointer value to a new type?
784 const PointerType *PTy = dyn_cast<PointerType>(Ty);
785 if (PTy == 0) return false; // Can't convert to a non-pointer type...
786 const FunctionType *MTy = dyn_cast<FunctionType>(PTy->getElementType());
787 if (MTy == 0) return false; // Can't convert to a non ptr to function...
789 // Perform sanity checks to make sure that new function type has the
790 // correct number of arguments...
792 unsigned NumArgs = I->getNumOperands()-1; // Don't include function ptr
794 // Cannot convert to a type that requires more fixed arguments than
795 // the call provides...
797 if (NumArgs < MTy->getParamTypes().size()) return false;
799 // Unless this is a vararg function type, we cannot provide more arguments
800 // than are desired...
802 if (!MTy->isVarArg() && NumArgs > MTy->getParamTypes().size())
805 // Okay, at this point, we know that the call and the function type match
806 // number of arguments. Now we see if we can convert the arguments
807 // themselves. Note that we do not require operands to be convertable,
808 // we can insert casts if they are convertible but not compatible. The
809 // reason for this is that we prefer to have resolved functions but casted
810 // arguments if possible.
812 const FunctionType::ParamTypes &PTs = MTy->getParamTypes();
813 for (unsigned i = 0, NA = PTs.size(); i < NA; ++i)
814 if (!PTs[i]->isLosslesslyConvertableTo(I->getOperand(i+1)->getType()))
815 return false; // Operands must have compatible types!
817 // Okay, at this point, we know that all of the arguments can be
818 // converted. We succeed if we can change the return type if
821 return ValueConvertableToType(I, MTy->getReturnType(), CTMap);
824 const PointerType *MPtr = cast<PointerType>(I->getOperand(0)->getType());
825 const FunctionType *MTy = cast<FunctionType>(MPtr->getElementType());
826 if (!MTy->isVarArg()) return false;
828 if ((OpNum-1) < MTy->getParamTypes().size())
829 return false; // It's not in the varargs section...
831 // If we get this far, we know the value is in the varargs section of the
832 // function! We can convert if we don't reinterpret the value...
834 return Ty->isLosslesslyConvertableTo(V->getType());
841 void ConvertValueToNewType(Value *V, Value *NewVal, ValueMapCache &VMC) {
842 ValueHandle VH(VMC, V);
844 unsigned NumUses = V->use_size();
845 for (unsigned It = 0; It < NumUses; ) {
846 unsigned OldSize = NumUses;
847 ConvertOperandToType(*(V->use_begin()+It), V, NewVal, VMC);
848 NumUses = V->use_size();
849 if (NumUses == OldSize) ++It;
855 static void ConvertOperandToType(User *U, Value *OldVal, Value *NewVal,
856 ValueMapCache &VMC) {
857 if (isa<ValueHandle>(U)) return; // Valuehandles don't let go of operands...
859 if (VMC.OperandsMapped.count(U)) return;
860 VMC.OperandsMapped.insert(U);
862 ValueMapCache::ExprMapTy::iterator VMCI = VMC.ExprMap.find(U);
863 if (VMCI != VMC.ExprMap.end())
867 Instruction *I = cast<Instruction>(U); // Only Instructions convertable
869 BasicBlock *BB = I->getParent();
870 assert(BB != 0 && "Instruction not embedded in basic block!");
871 std::string Name = I->getName();
873 Instruction *Res; // Result of conversion
875 //cerr << endl << endl << "Type:\t" << Ty << "\nInst: " << I << "BB Before: " << BB << endl;
877 // Prevent I from being removed...
878 ValueHandle IHandle(VMC, I);
880 const Type *NewTy = NewVal->getType();
881 Constant *Dummy = (NewTy != Type::VoidTy) ?
882 Constant::getNullValue(NewTy) : 0;
884 switch (I->getOpcode()) {
885 case Instruction::Cast:
886 if (VMC.NewCasts.count(ValueHandle(VMC, I))) {
887 // This cast has already had it's value converted, causing a new cast to
888 // be created. We don't want to create YET ANOTHER cast instruction
889 // representing the original one, so just modify the operand of this cast
890 // instruction, which we know is newly created.
891 I->setOperand(0, NewVal);
892 I->setName(Name); // give I its name back
896 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 = 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();
953 if (const CompositeType *CT = dyn_cast<CompositeType>(LoadedTy)) {
954 std::vector<Value*> Indices;
955 Indices.push_back(ConstantUInt::get(Type::UIntTy, 0));
957 unsigned Offset = 0; // No offset, get first leaf.
958 LoadedTy = getStructOffsetType(CT, Offset, Indices, false);
959 assert(LoadedTy->isFirstClassType());
961 if (Indices.size() != 1) { // Do not generate load X, 0
962 // Insert the GEP instruction before this load.
963 Src = new GetElementPtrInst(Src, Indices, Name+".idx", I);
967 Res = new LoadInst(Src, Name);
968 assert(Res->getType()->isFirstClassType() && "Load of structure or array!");
972 case Instruction::Store: {
973 if (I->getOperand(0) == OldVal) { // Replace the source value
974 // Check to see if operand #1 has already been converted...
975 ValueMapCache::ExprMapTy::iterator VMCI =
976 VMC.ExprMap.find(I->getOperand(1));
977 if (VMCI != VMC.ExprMap.end()) {
978 // Comments describing this stuff are in the OperandConvertableToType
979 // switch statement for Store...
982 cast<PointerType>(VMCI->second->getType())->getElementType();
984 Value *SrcPtr = VMCI->second;
987 // We check that this is a struct in the initial scan...
988 const StructType *SElTy = cast<StructType>(ElTy);
990 std::vector<Value*> Indices;
991 Indices.push_back(ConstantUInt::get(Type::UIntTy, 0));
994 const Type *Ty = getStructOffsetType(ElTy, Offset, Indices, false);
995 assert(Offset == 0 && "Offset changed!");
996 assert(NewTy == Ty && "Did not convert to correct type!");
998 // Insert the GEP instruction before this store.
999 SrcPtr = new GetElementPtrInst(SrcPtr, Indices,
1000 SrcPtr->getName()+".idx", I);
1002 Res = new StoreInst(NewVal, SrcPtr);
1004 VMC.ExprMap[I] = Res;
1006 // Otherwise, we haven't converted Operand #1 over yet...
1007 const PointerType *NewPT = PointerType::get(NewTy);
1008 Res = new StoreInst(NewVal, Constant::getNullValue(NewPT));
1009 VMC.ExprMap[I] = Res;
1010 Res->setOperand(1, ConvertExpressionToType(I->getOperand(1),
1013 } else { // Replace the source pointer
1014 const Type *ValTy = cast<PointerType>(NewTy)->getElementType();
1016 Value *SrcPtr = NewVal;
1018 if (isa<StructType>(ValTy)) {
1019 std::vector<Value*> Indices;
1020 Indices.push_back(ConstantUInt::get(Type::UIntTy, 0));
1022 unsigned Offset = 0;
1023 ValTy = getStructOffsetType(ValTy, Offset, Indices, false);
1025 assert(Offset == 0 && ValTy);
1027 // Insert the GEP instruction before this store.
1028 SrcPtr = new GetElementPtrInst(SrcPtr, Indices,
1029 SrcPtr->getName()+".idx", I);
1032 Res = new StoreInst(Constant::getNullValue(ValTy), SrcPtr);
1033 VMC.ExprMap[I] = Res;
1034 Res->setOperand(0, ConvertExpressionToType(I->getOperand(0), ValTy, VMC));
1040 case Instruction::GetElementPtr: {
1041 // Convert a one index getelementptr into just about anything that is
1044 BasicBlock::iterator It = I;
1045 const Type *OldElTy = cast<PointerType>(I->getType())->getElementType();
1046 unsigned DataSize = TD.getTypeSize(OldElTy);
1047 Value *Index = I->getOperand(1);
1049 if (DataSize != 1) {
1050 // Insert a multiply of the old element type is not a unit size...
1051 Index = BinaryOperator::create(Instruction::Mul, Index,
1052 ConstantUInt::get(Type::UIntTy, DataSize),
1056 // Perform the conversion now...
1058 std::vector<Value*> Indices;
1059 const Type *ElTy = ConvertableToGEP(NewVal->getType(), Index, Indices, &It);
1060 assert(ElTy != 0 && "GEP Conversion Failure!");
1061 Res = new GetElementPtrInst(NewVal, Indices, Name);
1062 assert(Res->getType() == PointerType::get(ElTy) &&
1063 "ConvertableToGet failed!");
1066 if (I->getType() == PointerType::get(Type::SByteTy)) {
1067 // Convert a getelementptr sbyte * %reg111, uint 16 freely back to
1068 // anything that is a pointer type...
1070 BasicBlock::iterator It = I;
1072 // Check to see if the second argument is an expression that can
1073 // be converted to the appropriate size... if so, allow it.
1075 std::vector<Value*> Indices;
1076 const Type *ElTy = ConvertableToGEP(NewVal->getType(), I->getOperand(1),
1078 assert(ElTy != 0 && "GEP Conversion Failure!");
1080 Res = new GetElementPtrInst(NewVal, Indices, Name);
1082 // Convert a getelementptr ulong * %reg123, uint %N
1083 // to getelementptr long * %reg123, uint %N
1084 // ... where the type must simply stay the same size...
1086 GetElementPtrInst *GEP = cast<GetElementPtrInst>(I);
1087 std::vector<Value*> Indices(GEP->idx_begin(), GEP->idx_end());
1088 Res = new GetElementPtrInst(NewVal, Indices, Name);
1093 case Instruction::PHINode: {
1094 PHINode *OldPN = cast<PHINode>(I);
1095 PHINode *NewPN = new PHINode(NewTy, Name);
1096 VMC.ExprMap[I] = NewPN;
1098 while (OldPN->getNumOperands()) {
1099 BasicBlock *BB = OldPN->getIncomingBlock(0);
1100 Value *OldVal = OldPN->getIncomingValue(0);
1101 OldPN->removeIncomingValue(BB);
1102 Value *V = ConvertExpressionToType(OldVal, NewTy, VMC);
1103 NewPN->addIncoming(V, BB);
1109 case Instruction::Call: {
1110 Value *Meth = I->getOperand(0);
1111 std::vector<Value*> Params(I->op_begin()+1, I->op_end());
1113 if (Meth == OldVal) { // Changing the function pointer?
1114 const PointerType *NewPTy = cast<PointerType>(NewVal->getType());
1115 const FunctionType *NewTy = cast<FunctionType>(NewPTy->getElementType());
1116 const FunctionType::ParamTypes &PTs = NewTy->getParamTypes();
1118 // Get an iterator to the call instruction so that we can insert casts for
1119 // operands if needbe. Note that we do not require operands to be
1120 // convertable, we can insert casts if they are convertible but not
1121 // compatible. The reason for this is that we prefer to have resolved
1122 // functions but casted arguments if possible.
1124 BasicBlock::iterator It = I;
1126 // Convert over all of the call operands to their new types... but only
1127 // convert over the part that is not in the vararg section of the call.
1129 for (unsigned i = 0; i < PTs.size(); ++i)
1130 if (Params[i]->getType() != PTs[i]) {
1131 // Create a cast to convert it to the right type, we know that this
1132 // is a lossless cast...
1134 Params[i] = new CastInst(Params[i], PTs[i], "call.resolve.cast", It);
1136 Meth = NewVal; // Update call destination to new value
1138 } else { // Changing an argument, must be in vararg area
1139 std::vector<Value*>::iterator OI =
1140 find(Params.begin(), Params.end(), OldVal);
1141 assert (OI != Params.end() && "Not using value!");
1146 Res = new CallInst(Meth, Params, Name);
1150 assert(0 && "Expression convertable, but don't know how to convert?");
1154 // If the instruction was newly created, insert it into the instruction
1157 BasicBlock::iterator It = I;
1158 assert(It != BB->end() && "Instruction not in own basic block??");
1159 BB->getInstList().insert(It, Res); // Keep It pointing to old instruction
1161 DEBUG(cerr << "COT CREATED: " << (void*)Res << " " << Res
1162 << "In: " << (void*)I << " " << I << "Out: " << (void*)Res
1165 // Add the instruction to the expression map
1166 VMC.ExprMap[I] = Res;
1168 if (I->getType() != Res->getType())
1169 ConvertValueToNewType(I, Res, VMC);
1171 for (unsigned It = 0; It < I->use_size(); ) {
1172 User *Use = *(I->use_begin()+It);
1173 if (isa<ValueHandle>(Use)) // Don't remove ValueHandles!
1176 Use->replaceUsesOfWith(I, Res);
1179 for (Value::use_iterator UI = I->use_begin(), UE = I->use_end();
1181 assert(isa<ValueHandle>((Value*)*UI) &&"Uses of Instruction remain!!!");
1186 ValueHandle::ValueHandle(ValueMapCache &VMC, Value *V)
1187 : Instruction(Type::VoidTy, UserOp1, ""), Cache(VMC) {
1188 //DEBUG(cerr << "VH AQUIRING: " << (void*)V << " " << V);
1189 Operands.push_back(Use(V, this));
1192 ValueHandle::ValueHandle(const ValueHandle &VH)
1193 : Instruction(Type::VoidTy, UserOp1, ""), Cache(VH.Cache) {
1194 //DEBUG(cerr << "VH AQUIRING: " << (void*)V << " " << V);
1195 Operands.push_back(Use((Value*)VH.getOperand(0), this));
1198 static void RecursiveDelete(ValueMapCache &Cache, Instruction *I) {
1199 if (!I || !I->use_empty()) return;
1201 assert(I->getParent() && "Inst not in basic block!");
1203 //DEBUG(cerr << "VH DELETING: " << (void*)I << " " << I);
1205 for (User::op_iterator OI = I->op_begin(), OE = I->op_end();
1207 if (Instruction *U = dyn_cast<Instruction>(OI->get())) {
1209 RecursiveDelete(Cache, U);
1212 I->getParent()->getInstList().remove(I);
1214 Cache.OperandsMapped.erase(I);
1215 Cache.ExprMap.erase(I);
1219 ValueHandle::~ValueHandle() {
1220 if (Operands[0]->use_size() == 1) {
1221 Value *V = Operands[0];
1222 Operands[0] = 0; // Drop use!
1224 // Now we just need to remove the old instruction so we don't get infinite
1225 // loops. Note that we cannot use DCE because DCE won't remove a store
1226 // instruction, for example.
1228 RecursiveDelete(Cache, dyn_cast<Instruction>(V));
1230 //DEBUG(cerr << "VH RELEASING: " << (void*)Operands[0].get() << " "
1231 // << Operands[0]->use_size() << " " << Operands[0]);