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 // convertible, 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/Debug.h"
19 static bool OperandConvertibleToType(User *U, Value *V, const Type *Ty,
20 ValueTypeCache &ConvertedTypes,
21 const TargetData &TD);
23 static void ConvertOperandToType(User *U, Value *OldVal, Value *NewVal,
24 ValueMapCache &VMC, const TargetData &TD);
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 MallocConvertibleToType(MallocInst *MI, const Type *Ty,
38 ValueTypeCache &CTMap,
39 const TargetData &TD) {
40 if (!isa<PointerType>(Ty)) return false; // Malloc always returns pointers
42 // Deal with the type to allocate, not the pointer type...
43 Ty = cast<PointerType>(Ty)->getElementType();
44 if (!Ty->isSized()) return false; // Can only alloc something with a size
46 // Analyze the number of bytes allocated...
47 ExprType Expr = ClassifyExpression(MI->getArraySize());
49 // Get information about the base datatype being allocated, before & after
50 int ReqTypeSize = TD.getTypeSize(Ty);
51 if (ReqTypeSize == 0) return false;
52 unsigned OldTypeSize = TD.getTypeSize(MI->getType()->getElementType());
54 // Must have a scale or offset to analyze it...
55 if (!Expr.Offset && !Expr.Scale && OldTypeSize == 1) return false;
57 // Get the offset and scale of the allocation...
58 int64_t OffsetVal = Expr.Offset ? getConstantValue(Expr.Offset) : 0;
59 int64_t ScaleVal = Expr.Scale ? getConstantValue(Expr.Scale) :(Expr.Var != 0);
61 // The old type might not be of unit size, take old size into consideration
63 int64_t Offset = OffsetVal * OldTypeSize;
64 int64_t Scale = ScaleVal * OldTypeSize;
66 // In order to be successful, both the scale and the offset must be a multiple
67 // of the requested data type's size.
69 if (Offset/ReqTypeSize*ReqTypeSize != Offset ||
70 Scale/ReqTypeSize*ReqTypeSize != Scale)
71 return false; // Nope.
76 static Instruction *ConvertMallocToType(MallocInst *MI, const Type *Ty,
77 const std::string &Name,
79 const TargetData &TD){
80 BasicBlock *BB = MI->getParent();
81 BasicBlock::iterator It = BB->end();
83 // Analyze the number of bytes allocated...
84 ExprType Expr = ClassifyExpression(MI->getArraySize());
86 const PointerType *AllocTy = cast<PointerType>(Ty);
87 const Type *ElType = AllocTy->getElementType();
89 unsigned DataSize = TD.getTypeSize(ElType);
90 unsigned OldTypeSize = TD.getTypeSize(MI->getType()->getElementType());
92 // Get the offset and scale coefficients that we are allocating...
93 int64_t OffsetVal = (Expr.Offset ? getConstantValue(Expr.Offset) : 0);
94 int64_t ScaleVal = Expr.Scale ? getConstantValue(Expr.Scale) : (Expr.Var !=0);
96 // The old type might not be of unit size, take old size into consideration
98 unsigned Offset = (uint64_t)OffsetVal * OldTypeSize / DataSize;
99 unsigned Scale = (uint64_t)ScaleVal * OldTypeSize / DataSize;
101 // Locate the malloc instruction, because we may be inserting instructions
104 // If we have a scale, apply it first...
106 // Expr.Var is not necessarily unsigned right now, insert a cast now.
107 if (Expr.Var->getType() != Type::UIntTy)
108 Expr.Var = new CastInst(Expr.Var, Type::UIntTy,
109 Expr.Var->getName()+"-uint", It);
112 Expr.Var = BinaryOperator::create(Instruction::Mul, Expr.Var,
113 ConstantUInt::get(Type::UIntTy, Scale),
114 Expr.Var->getName()+"-scl", It);
117 // If we are not scaling anything, just make the offset be the "var"...
118 Expr.Var = ConstantUInt::get(Type::UIntTy, Offset);
119 Offset = 0; Scale = 1;
122 // If we have an offset now, add it in...
124 assert(Expr.Var && "Var must be nonnull by now!");
125 Expr.Var = BinaryOperator::create(Instruction::Add, Expr.Var,
126 ConstantUInt::get(Type::UIntTy, Offset),
127 Expr.Var->getName()+"-off", It);
130 assert(AllocTy == Ty);
131 return new MallocInst(AllocTy->getElementType(), Expr.Var, Name);
135 // ExpressionConvertibleToType - Return true if it is possible
136 bool ExpressionConvertibleToType(Value *V, const Type *Ty,
137 ValueTypeCache &CTMap, const TargetData &TD) {
138 // Expression type must be holdable in a register.
139 if (!Ty->isFirstClassType())
142 ValueTypeCache::iterator CTMI = CTMap.find(V);
143 if (CTMI != CTMap.end()) return CTMI->second == Ty;
145 // If it's a constant... all constants can be converted to a different
146 // type. We just ask the constant propagator to see if it can convert the
149 if (Constant *CPV = dyn_cast<Constant>(V))
150 return ConstantFoldCastInstruction(CPV, Ty);
153 if (V->getType() == Ty) return true; // Expression already correct type!
155 Instruction *I = dyn_cast<Instruction>(V);
156 if (I == 0) return false; // Otherwise, we can't convert!
158 switch (I->getOpcode()) {
159 case Instruction::Cast:
160 // We can convert the expr if the cast destination type is losslessly
161 // convertible to the requested type.
162 if (!Ty->isLosslesslyConvertibleTo(I->getType())) return false;
164 // We also do not allow conversion of a cast that casts from a ptr to array
165 // of X to a *X. For example: cast [4 x %List *] * %val to %List * *
167 if (const PointerType *SPT =
168 dyn_cast<PointerType>(I->getOperand(0)->getType()))
169 if (const PointerType *DPT = dyn_cast<PointerType>(I->getType()))
170 if (const ArrayType *AT = dyn_cast<ArrayType>(SPT->getElementType()))
171 if (AT->getElementType() == DPT->getElementType())
175 case Instruction::Add:
176 case Instruction::Sub:
177 if (!Ty->isInteger() && !Ty->isFloatingPoint()) return false;
178 if (!ExpressionConvertibleToType(I->getOperand(0), Ty, CTMap, TD) ||
179 !ExpressionConvertibleToType(I->getOperand(1), Ty, CTMap, TD))
182 case Instruction::Shr:
183 if (!Ty->isInteger()) return false;
184 if (Ty->isSigned() != V->getType()->isSigned()) return false;
186 case Instruction::Shl:
187 if (!Ty->isInteger()) return false;
188 if (!ExpressionConvertibleToType(I->getOperand(0), Ty, CTMap, TD))
192 case Instruction::Load: {
193 LoadInst *LI = cast<LoadInst>(I);
194 if (!ExpressionConvertibleToType(LI->getPointerOperand(),
195 PointerType::get(Ty), CTMap, TD))
199 case Instruction::PHI: {
200 PHINode *PN = cast<PHINode>(I);
201 for (unsigned i = 0; i < PN->getNumIncomingValues(); ++i)
202 if (!ExpressionConvertibleToType(PN->getIncomingValue(i), Ty, CTMap, TD))
207 case Instruction::Malloc:
208 if (!MallocConvertibleToType(cast<MallocInst>(I), Ty, CTMap, TD))
212 case Instruction::GetElementPtr: {
213 // GetElementPtr's are directly convertible to a pointer type if they have
214 // a number of zeros at the end. Because removing these values does not
215 // change the logical offset of the GEP, it is okay and fair to remove them.
216 // This can change this:
217 // %t1 = getelementptr %Hosp * %hosp, ubyte 4, ubyte 0 ; <%List **>
218 // %t2 = cast %List * * %t1 to %List *
220 // %t2 = getelementptr %Hosp * %hosp, ubyte 4 ; <%List *>
222 GetElementPtrInst *GEP = cast<GetElementPtrInst>(I);
223 const PointerType *PTy = dyn_cast<PointerType>(Ty);
224 if (!PTy) return false; // GEP must always return a pointer...
225 const Type *PVTy = PTy->getElementType();
227 // Check to see if there are zero elements that we can remove from the
228 // index array. If there are, check to see if removing them causes us to
229 // get to the right type...
231 std::vector<Value*> Indices(GEP->idx_begin(), GEP->idx_end());
232 const Type *BaseType = GEP->getPointerOperand()->getType();
233 const Type *ElTy = 0;
235 while (!Indices.empty() &&
236 Indices.back() == Constant::getNullValue(Indices.back()->getType())){
238 ElTy = GetElementPtrInst::getIndexedType(BaseType, Indices, true);
240 break; // Found a match!!
244 if (ElTy) break; // Found a number of zeros we can strip off!
246 // Otherwise, we can convert a GEP from one form to the other iff the
247 // current gep is of the form 'getelementptr sbyte*, long N
248 // and we could convert this to an appropriate GEP for the new type.
250 if (GEP->getNumOperands() == 2 &&
251 GEP->getOperand(1)->getType() == Type::LongTy &&
252 GEP->getType() == PointerType::get(Type::SByteTy)) {
254 // Do not Check to see if our incoming pointer can be converted
255 // to be a ptr to an array of the right type... because in more cases than
256 // not, it is simply not analyzable because of pointer/array
257 // discrepancies. To fix this, we will insert a cast before the GEP.
260 // Check to see if 'N' is an expression that can be converted to
261 // the appropriate size... if so, allow it.
263 std::vector<Value*> Indices;
264 const Type *ElTy = ConvertibleToGEP(PTy, I->getOperand(1), Indices, TD);
266 if (!ExpressionConvertibleToType(I->getOperand(0),
267 PointerType::get(ElTy), CTMap, TD))
268 return false; // Can't continue, ExConToTy might have polluted set!
273 // Otherwise, it could be that we have something like this:
274 // getelementptr [[sbyte] *] * %reg115, long %reg138 ; [sbyte]**
275 // and want to convert it into something like this:
276 // getelemenptr [[int] *] * %reg115, long %reg138 ; [int]**
278 if (GEP->getNumOperands() == 2 &&
279 GEP->getOperand(1)->getType() == Type::LongTy &&
280 PTy->getElementType()->isSized() &&
281 TD.getTypeSize(PTy->getElementType()) ==
282 TD.getTypeSize(GEP->getType()->getElementType())) {
283 const PointerType *NewSrcTy = PointerType::get(PVTy);
284 if (!ExpressionConvertibleToType(I->getOperand(0), NewSrcTy, CTMap, TD))
289 return false; // No match, maybe next time.
292 case Instruction::Call: {
293 if (isa<Function>(I->getOperand(0)))
294 return false; // Don't even try to change direct calls.
296 // If this is a function pointer, we can convert the return type if we can
297 // convert the source function pointer.
299 const PointerType *PT = cast<PointerType>(I->getOperand(0)->getType());
300 const FunctionType *FT = cast<FunctionType>(PT->getElementType());
301 std::vector<const Type *> ArgTys(FT->getParamTypes().begin(),
302 FT->getParamTypes().end());
303 const FunctionType *NewTy =
304 FunctionType::get(Ty, ArgTys, FT->isVarArg());
305 if (!ExpressionConvertibleToType(I->getOperand(0),
306 PointerType::get(NewTy), CTMap, TD))
314 // Expressions are only convertible if all of the users of the expression can
315 // have this value converted. This makes use of the map to avoid infinite
318 for (Value::use_iterator It = I->use_begin(), E = I->use_end(); It != E; ++It)
319 if (!OperandConvertibleToType(*It, I, Ty, CTMap, TD))
326 Value *ConvertExpressionToType(Value *V, const Type *Ty, ValueMapCache &VMC,
327 const TargetData &TD) {
328 if (V->getType() == Ty) return V; // Already where we need to be?
330 ValueMapCache::ExprMapTy::iterator VMCI = VMC.ExprMap.find(V);
331 if (VMCI != VMC.ExprMap.end()) {
332 const Value *GV = VMCI->second;
333 const Type *GTy = VMCI->second->getType();
334 assert(VMCI->second->getType() == Ty);
336 if (Instruction *I = dyn_cast<Instruction>(V))
337 ValueHandle IHandle(VMC, I); // Remove I if it is unused now!
342 DEBUG(std::cerr << "CETT: " << (void*)V << " " << V);
344 Instruction *I = dyn_cast<Instruction>(V);
346 Constant *CPV = cast<Constant>(V);
347 // Constants are converted by constant folding the cast that is required.
348 // We assume here that all casts are implemented for constant prop.
349 Value *Result = ConstantFoldCastInstruction(CPV, Ty);
350 assert(Result && "ConstantFoldCastInstruction Failed!!!");
351 assert(Result->getType() == Ty && "Const prop of cast failed!");
353 // Add the instruction to the expression map
354 //VMC.ExprMap[V] = Result;
359 BasicBlock *BB = I->getParent();
360 std::string Name = I->getName(); if (!Name.empty()) I->setName("");
361 Instruction *Res; // Result of conversion
363 ValueHandle IHandle(VMC, I); // Prevent I from being removed!
365 Constant *Dummy = Constant::getNullValue(Ty);
367 switch (I->getOpcode()) {
368 case Instruction::Cast:
369 assert(VMC.NewCasts.count(ValueHandle(VMC, I)) == 0);
370 Res = new CastInst(I->getOperand(0), Ty, Name);
371 VMC.NewCasts.insert(ValueHandle(VMC, Res));
374 case Instruction::Add:
375 case Instruction::Sub:
376 Res = BinaryOperator::create(cast<BinaryOperator>(I)->getOpcode(),
378 VMC.ExprMap[I] = Res; // Add node to expression eagerly
380 Res->setOperand(0, ConvertExpressionToType(I->getOperand(0), Ty, VMC, TD));
381 Res->setOperand(1, ConvertExpressionToType(I->getOperand(1), Ty, VMC, TD));
384 case Instruction::Shl:
385 case Instruction::Shr:
386 Res = new ShiftInst(cast<ShiftInst>(I)->getOpcode(), Dummy,
387 I->getOperand(1), Name);
388 VMC.ExprMap[I] = Res;
389 Res->setOperand(0, ConvertExpressionToType(I->getOperand(0), Ty, VMC, TD));
392 case Instruction::Load: {
393 LoadInst *LI = cast<LoadInst>(I);
395 Res = new LoadInst(Constant::getNullValue(PointerType::get(Ty)), Name);
396 VMC.ExprMap[I] = Res;
397 Res->setOperand(0, ConvertExpressionToType(LI->getPointerOperand(),
398 PointerType::get(Ty), VMC, TD));
399 assert(Res->getOperand(0)->getType() == PointerType::get(Ty));
400 assert(Ty == Res->getType());
401 assert(Res->getType()->isFirstClassType() && "Load of structure or array!");
405 case Instruction::PHI: {
406 PHINode *OldPN = cast<PHINode>(I);
407 PHINode *NewPN = new PHINode(Ty, Name);
409 VMC.ExprMap[I] = NewPN; // Add node to expression eagerly
410 while (OldPN->getNumOperands()) {
411 BasicBlock *BB = OldPN->getIncomingBlock(0);
412 Value *OldVal = OldPN->getIncomingValue(0);
413 ValueHandle OldValHandle(VMC, OldVal);
414 OldPN->removeIncomingValue(BB, false);
415 Value *V = ConvertExpressionToType(OldVal, Ty, VMC, TD);
416 NewPN->addIncoming(V, BB);
422 case Instruction::Malloc: {
423 Res = ConvertMallocToType(cast<MallocInst>(I), Ty, Name, VMC, TD);
427 case Instruction::GetElementPtr: {
428 // GetElementPtr's are directly convertible to a pointer type if they have
429 // a number of zeros at the end. Because removing these values does not
430 // change the logical offset of the GEP, it is okay and fair to remove them.
431 // This can change this:
432 // %t1 = getelementptr %Hosp * %hosp, ubyte 4, ubyte 0 ; <%List **>
433 // %t2 = cast %List * * %t1 to %List *
435 // %t2 = getelementptr %Hosp * %hosp, ubyte 4 ; <%List *>
437 GetElementPtrInst *GEP = cast<GetElementPtrInst>(I);
439 // Check to see if there are zero elements that we can remove from the
440 // index array. If there are, check to see if removing them causes us to
441 // get to the right type...
443 std::vector<Value*> Indices(GEP->idx_begin(), GEP->idx_end());
444 const Type *BaseType = GEP->getPointerOperand()->getType();
445 const Type *PVTy = cast<PointerType>(Ty)->getElementType();
447 while (!Indices.empty() &&
448 Indices.back() == Constant::getNullValue(Indices.back()->getType())){
450 if (GetElementPtrInst::getIndexedType(BaseType, Indices, true) == PVTy) {
451 if (Indices.size() == 0)
452 Res = new CastInst(GEP->getPointerOperand(), BaseType); // NOOP CAST
454 Res = new GetElementPtrInst(GEP->getPointerOperand(), Indices, Name);
459 if (Res == 0 && GEP->getNumOperands() == 2 &&
460 GEP->getOperand(1)->getType() == Type::LongTy &&
461 GEP->getType() == PointerType::get(Type::SByteTy)) {
463 // Otherwise, we can convert a GEP from one form to the other iff the
464 // current gep is of the form 'getelementptr [sbyte]*, unsigned N
465 // and we could convert this to an appropriate GEP for the new type.
467 const PointerType *NewSrcTy = PointerType::get(PVTy);
468 BasicBlock::iterator It = I;
470 // Check to see if 'N' is an expression that can be converted to
471 // the appropriate size... if so, allow it.
473 std::vector<Value*> Indices;
474 const Type *ElTy = ConvertibleToGEP(NewSrcTy, I->getOperand(1),
477 assert(ElTy == PVTy && "Internal error, setup wrong!");
478 Res = new GetElementPtrInst(Constant::getNullValue(NewSrcTy),
480 VMC.ExprMap[I] = Res;
481 Res->setOperand(0, ConvertExpressionToType(I->getOperand(0),
486 // Otherwise, it could be that we have something like this:
487 // getelementptr [[sbyte] *] * %reg115, uint %reg138 ; [sbyte]**
488 // and want to convert it into something like this:
489 // getelemenptr [[int] *] * %reg115, uint %reg138 ; [int]**
492 const PointerType *NewSrcTy = PointerType::get(PVTy);
493 std::vector<Value*> Indices(GEP->idx_begin(), GEP->idx_end());
494 Res = new GetElementPtrInst(Constant::getNullValue(NewSrcTy),
496 VMC.ExprMap[I] = Res;
497 Res->setOperand(0, ConvertExpressionToType(I->getOperand(0),
502 assert(Res && "Didn't find match!");
506 case Instruction::Call: {
507 assert(!isa<Function>(I->getOperand(0)));
509 // If this is a function pointer, we can convert the return type if we can
510 // convert the source function pointer.
512 const PointerType *PT = cast<PointerType>(I->getOperand(0)->getType());
513 const FunctionType *FT = cast<FunctionType>(PT->getElementType());
514 std::vector<const Type *> ArgTys(FT->getParamTypes().begin(),
515 FT->getParamTypes().end());
516 const FunctionType *NewTy =
517 FunctionType::get(Ty, ArgTys, FT->isVarArg());
518 const PointerType *NewPTy = PointerType::get(NewTy);
519 if (Ty == Type::VoidTy)
520 Name = ""; // Make sure not to name calls that now return void!
522 Res = new CallInst(Constant::getNullValue(NewPTy),
523 std::vector<Value*>(I->op_begin()+1, I->op_end()),
525 VMC.ExprMap[I] = Res;
526 Res->setOperand(0, ConvertExpressionToType(I->getOperand(0),NewPTy,VMC,TD));
530 assert(0 && "Expression convertible, but don't know how to convert?");
534 assert(Res->getType() == Ty && "Didn't convert expr to correct type!");
536 BB->getInstList().insert(I, Res);
538 // Add the instruction to the expression map
539 VMC.ExprMap[I] = Res;
542 unsigned NumUses = I->use_size();
543 for (unsigned It = 0; It < NumUses; ) {
544 unsigned OldSize = NumUses;
545 Value::use_iterator UI = I->use_begin();
546 std::advance(UI, It);
547 ConvertOperandToType(*UI, I, Res, VMC, TD);
548 NumUses = I->use_size();
549 if (NumUses == OldSize) ++It;
552 DEBUG(std::cerr << "ExpIn: " << (void*)I << " " << I
553 << "ExpOut: " << (void*)Res << " " << Res);
560 // ValueConvertibleToType - Return true if it is possible
561 bool ValueConvertibleToType(Value *V, const Type *Ty,
562 ValueTypeCache &ConvertedTypes,
563 const TargetData &TD) {
564 ValueTypeCache::iterator I = ConvertedTypes.find(V);
565 if (I != ConvertedTypes.end()) return I->second == Ty;
566 ConvertedTypes[V] = Ty;
568 // It is safe to convert the specified value to the specified type IFF all of
569 // the uses of the value can be converted to accept the new typed value.
571 if (V->getType() != Ty) {
572 for (Value::use_iterator I = V->use_begin(), E = V->use_end(); I != E; ++I)
573 if (!OperandConvertibleToType(*I, V, Ty, ConvertedTypes, TD))
584 // OperandConvertibleToType - Return true if it is possible to convert operand
585 // V of User (instruction) U to the specified type. This is true iff it is
586 // possible to change the specified instruction to accept this. CTMap is a map
587 // of converted types, so that circular definitions will see the future type of
588 // the expression, not the static current type.
590 static bool OperandConvertibleToType(User *U, Value *V, const Type *Ty,
591 ValueTypeCache &CTMap,
592 const TargetData &TD) {
593 // if (V->getType() == Ty) return true; // Operand already the right type?
595 // Expression type must be holdable in a register.
596 if (!Ty->isFirstClassType())
599 Instruction *I = dyn_cast<Instruction>(U);
600 if (I == 0) return false; // We can't convert!
602 switch (I->getOpcode()) {
603 case Instruction::Cast:
604 assert(I->getOperand(0) == V);
605 // We can convert the expr if the cast destination type is losslessly
606 // convertible to the requested type.
607 // Also, do not change a cast that is a noop cast. For all intents and
608 // purposes it should be eliminated.
609 if (!Ty->isLosslesslyConvertibleTo(I->getOperand(0)->getType()) ||
610 I->getType() == I->getOperand(0)->getType())
613 // Do not allow a 'cast ushort %V to uint' to have it's first operand be
614 // converted to a 'short' type. Doing so changes the way sign promotion
615 // happens, and breaks things. Only allow the cast to take place if the
616 // signedness doesn't change... or if the current cast is not a lossy
619 if (!I->getType()->isLosslesslyConvertibleTo(I->getOperand(0)->getType()) &&
620 I->getOperand(0)->getType()->isSigned() != Ty->isSigned())
623 // We also do not allow conversion of a cast that casts from a ptr to array
624 // of X to a *X. For example: cast [4 x %List *] * %val to %List * *
626 if (const PointerType *SPT =
627 dyn_cast<PointerType>(I->getOperand(0)->getType()))
628 if (const PointerType *DPT = dyn_cast<PointerType>(I->getType()))
629 if (const ArrayType *AT = dyn_cast<ArrayType>(SPT->getElementType()))
630 if (AT->getElementType() == DPT->getElementType())
634 case Instruction::Add:
635 if (isa<PointerType>(Ty)) {
636 Value *IndexVal = I->getOperand(V == I->getOperand(0) ? 1 : 0);
637 std::vector<Value*> Indices;
638 if (const Type *ETy = ConvertibleToGEP(Ty, IndexVal, Indices, TD)) {
639 const Type *RetTy = PointerType::get(ETy);
641 // Only successful if we can convert this type to the required type
642 if (ValueConvertibleToType(I, RetTy, CTMap, TD)) {
646 // We have to return failure here because ValueConvertibleToType could
647 // have polluted our map
652 case Instruction::Sub: {
653 if (!Ty->isInteger() && !Ty->isFloatingPoint()) return false;
655 Value *OtherOp = I->getOperand((V == I->getOperand(0)) ? 1 : 0);
656 return ValueConvertibleToType(I, Ty, CTMap, TD) &&
657 ExpressionConvertibleToType(OtherOp, Ty, CTMap, TD);
659 case Instruction::SetEQ:
660 case Instruction::SetNE: {
661 Value *OtherOp = I->getOperand((V == I->getOperand(0)) ? 1 : 0);
662 return ExpressionConvertibleToType(OtherOp, Ty, CTMap, TD);
664 case Instruction::Shr:
665 if (Ty->isSigned() != V->getType()->isSigned()) return false;
667 case Instruction::Shl:
668 if (I->getOperand(1) == V) return false; // Cannot change shift amount type
669 if (!Ty->isInteger()) return false;
670 return ValueConvertibleToType(I, Ty, CTMap, TD);
672 case Instruction::Free:
673 assert(I->getOperand(0) == V);
674 return isa<PointerType>(Ty); // Free can free any pointer type!
676 case Instruction::Load:
677 // Cannot convert the types of any subscripts...
678 if (I->getOperand(0) != V) return false;
680 if (const PointerType *PT = dyn_cast<PointerType>(Ty)) {
681 LoadInst *LI = cast<LoadInst>(I);
683 const Type *LoadedTy = PT->getElementType();
685 // They could be loading the first element of a composite type...
686 if (const CompositeType *CT = dyn_cast<CompositeType>(LoadedTy)) {
687 unsigned Offset = 0; // No offset, get first leaf.
688 std::vector<Value*> Indices; // Discarded...
689 LoadedTy = getStructOffsetType(CT, Offset, Indices, TD, false);
690 assert(Offset == 0 && "Offset changed from zero???");
693 if (!LoadedTy->isFirstClassType())
696 if (TD.getTypeSize(LoadedTy) != TD.getTypeSize(LI->getType()))
699 return ValueConvertibleToType(LI, LoadedTy, CTMap, TD);
703 case Instruction::Store: {
704 StoreInst *SI = cast<StoreInst>(I);
706 if (V == I->getOperand(0)) {
707 ValueTypeCache::iterator CTMI = CTMap.find(I->getOperand(1));
708 if (CTMI != CTMap.end()) { // Operand #1 is in the table already?
709 // If so, check to see if it's Ty*, or, more importantly, if it is a
710 // pointer to a structure where the first element is a Ty... this code
711 // is necessary because we might be trying to change the source and
712 // destination type of the store (they might be related) and the dest
713 // pointer type might be a pointer to structure. Below we allow pointer
714 // to structures where the 0th element is compatible with the value,
715 // now we have to support the symmetrical part of this.
717 const Type *ElTy = cast<PointerType>(CTMI->second)->getElementType();
719 // Already a pointer to what we want? Trivially accept...
720 if (ElTy == Ty) return true;
722 // Tricky case now, if the destination is a pointer to structure,
723 // obviously the source is not allowed to be a structure (cannot copy
724 // a whole structure at a time), so the level raiser must be trying to
725 // store into the first field. Check for this and allow it now:
727 if (const StructType *SElTy = dyn_cast<StructType>(ElTy)) {
729 std::vector<Value*> Indices;
730 ElTy = getStructOffsetType(ElTy, Offset, Indices, TD, false);
731 assert(Offset == 0 && "Offset changed!");
732 if (ElTy == 0) // Element at offset zero in struct doesn't exist!
733 return false; // Can only happen for {}*
735 if (ElTy == Ty) // Looks like the 0th element of structure is
736 return true; // compatible! Accept now!
738 // Otherwise we know that we can't work, so just stop trying now.
743 // Can convert the store if we can convert the pointer operand to match
744 // the new value type...
745 return ExpressionConvertibleToType(I->getOperand(1), PointerType::get(Ty),
747 } else if (const PointerType *PT = dyn_cast<PointerType>(Ty)) {
748 const Type *ElTy = PT->getElementType();
749 assert(V == I->getOperand(1));
751 if (isa<StructType>(ElTy)) {
752 // We can change the destination pointer if we can store our first
753 // argument into the first element of the structure...
756 std::vector<Value*> Indices;
757 ElTy = getStructOffsetType(ElTy, Offset, Indices, TD, false);
758 assert(Offset == 0 && "Offset changed!");
759 if (ElTy == 0) // Element at offset zero in struct doesn't exist!
760 return false; // Can only happen for {}*
763 // Must move the same amount of data...
764 if (!ElTy->isSized() ||
765 TD.getTypeSize(ElTy) != TD.getTypeSize(I->getOperand(0)->getType()))
768 // Can convert store if the incoming value is convertible...
769 return ExpressionConvertibleToType(I->getOperand(0), ElTy, CTMap, TD);
774 case Instruction::GetElementPtr:
775 if (V != I->getOperand(0) || !isa<PointerType>(Ty)) return false;
777 // If we have a two operand form of getelementptr, this is really little
778 // more than a simple addition. As with addition, check to see if the
779 // getelementptr instruction can be changed to index into the new type.
781 if (I->getNumOperands() == 2) {
782 const Type *OldElTy = cast<PointerType>(I->getType())->getElementType();
783 unsigned DataSize = TD.getTypeSize(OldElTy);
784 Value *Index = I->getOperand(1);
785 Instruction *TempScale = 0;
787 // If the old data element is not unit sized, we have to create a scale
788 // instruction so that ConvertibleToGEP will know the REAL amount we are
789 // indexing by. Note that this is never inserted into the instruction
790 // stream, so we have to delete it when we're done.
793 TempScale = BinaryOperator::create(Instruction::Mul, Index,
794 ConstantSInt::get(Type::LongTy,
799 // Check to see if the second argument is an expression that can
800 // be converted to the appropriate size... if so, allow it.
802 std::vector<Value*> Indices;
803 const Type *ElTy = ConvertibleToGEP(Ty, Index, Indices, TD);
804 delete TempScale; // Free our temporary multiply if we made it
806 if (ElTy == 0) return false; // Cannot make conversion...
807 return ValueConvertibleToType(I, PointerType::get(ElTy), CTMap, TD);
811 case Instruction::PHI: {
812 PHINode *PN = cast<PHINode>(I);
813 for (unsigned i = 0; i < PN->getNumIncomingValues(); ++i)
814 if (!ExpressionConvertibleToType(PN->getIncomingValue(i), Ty, CTMap, TD))
816 return ValueConvertibleToType(PN, Ty, CTMap, TD);
819 case Instruction::Call: {
820 User::op_iterator OI = find(I->op_begin(), I->op_end(), V);
821 assert (OI != I->op_end() && "Not using value!");
822 unsigned OpNum = OI - I->op_begin();
824 // Are we trying to change the function pointer value to a new type?
826 const PointerType *PTy = dyn_cast<PointerType>(Ty);
827 if (PTy == 0) return false; // Can't convert to a non-pointer type...
828 const FunctionType *FTy = dyn_cast<FunctionType>(PTy->getElementType());
829 if (FTy == 0) return false; // Can't convert to a non ptr to function...
831 // Do not allow converting to a call where all of the operands are ...'s
832 if (FTy->getNumParams() == 0 && FTy->isVarArg())
833 return false; // Do not permit this conversion!
835 // Perform sanity checks to make sure that new function type has the
836 // correct number of arguments...
838 unsigned NumArgs = I->getNumOperands()-1; // Don't include function ptr
840 // Cannot convert to a type that requires more fixed arguments than
841 // the call provides...
843 if (NumArgs < FTy->getNumParams()) return false;
845 // Unless this is a vararg function type, we cannot provide more arguments
846 // than are desired...
848 if (!FTy->isVarArg() && NumArgs > FTy->getNumParams())
851 // Okay, at this point, we know that the call and the function type match
852 // number of arguments. Now we see if we can convert the arguments
853 // themselves. Note that we do not require operands to be convertible,
854 // we can insert casts if they are convertible but not compatible. The
855 // reason for this is that we prefer to have resolved functions but casted
856 // arguments if possible.
858 const FunctionType::ParamTypes &PTs = FTy->getParamTypes();
859 for (unsigned i = 0, NA = PTs.size(); i < NA; ++i)
860 if (!PTs[i]->isLosslesslyConvertibleTo(I->getOperand(i+1)->getType()))
861 return false; // Operands must have compatible types!
863 // Okay, at this point, we know that all of the arguments can be
864 // converted. We succeed if we can change the return type if
867 return ValueConvertibleToType(I, FTy->getReturnType(), CTMap, TD);
870 const PointerType *MPtr = cast<PointerType>(I->getOperand(0)->getType());
871 const FunctionType *FTy = cast<FunctionType>(MPtr->getElementType());
872 if (!FTy->isVarArg()) return false;
874 if ((OpNum-1) < FTy->getParamTypes().size())
875 return false; // It's not in the varargs section...
877 // If we get this far, we know the value is in the varargs section of the
878 // function! We can convert if we don't reinterpret the value...
880 return Ty->isLosslesslyConvertibleTo(V->getType());
887 void ConvertValueToNewType(Value *V, Value *NewVal, ValueMapCache &VMC,
888 const TargetData &TD) {
889 ValueHandle VH(VMC, V);
891 unsigned NumUses = V->use_size();
892 for (unsigned It = 0; It < NumUses; ) {
893 unsigned OldSize = NumUses;
894 Value::use_iterator UI = V->use_begin();
895 std::advance(UI, It);
896 ConvertOperandToType(*UI, V, NewVal, VMC, TD);
897 NumUses = V->use_size();
898 if (NumUses == OldSize) ++It;
904 static void ConvertOperandToType(User *U, Value *OldVal, Value *NewVal,
905 ValueMapCache &VMC, const TargetData &TD) {
906 if (isa<ValueHandle>(U)) return; // Valuehandles don't let go of operands...
908 if (VMC.OperandsMapped.count(U)) return;
909 VMC.OperandsMapped.insert(U);
911 ValueMapCache::ExprMapTy::iterator VMCI = VMC.ExprMap.find(U);
912 if (VMCI != VMC.ExprMap.end())
916 Instruction *I = cast<Instruction>(U); // Only Instructions convertible
918 BasicBlock *BB = I->getParent();
919 assert(BB != 0 && "Instruction not embedded in basic block!");
920 std::string Name = I->getName();
922 Instruction *Res; // Result of conversion
924 //std::cerr << endl << endl << "Type:\t" << Ty << "\nInst: " << I
925 // << "BB Before: " << BB << endl;
927 // Prevent I from being removed...
928 ValueHandle IHandle(VMC, I);
930 const Type *NewTy = NewVal->getType();
931 Constant *Dummy = (NewTy != Type::VoidTy) ?
932 Constant::getNullValue(NewTy) : 0;
934 switch (I->getOpcode()) {
935 case Instruction::Cast:
936 if (VMC.NewCasts.count(ValueHandle(VMC, I))) {
937 // This cast has already had it's value converted, causing a new cast to
938 // be created. We don't want to create YET ANOTHER cast instruction
939 // representing the original one, so just modify the operand of this cast
940 // instruction, which we know is newly created.
941 I->setOperand(0, NewVal);
942 I->setName(Name); // give I its name back
946 Res = new CastInst(NewVal, I->getType(), Name);
950 case Instruction::Add:
951 if (isa<PointerType>(NewTy)) {
952 Value *IndexVal = I->getOperand(OldVal == I->getOperand(0) ? 1 : 0);
953 std::vector<Value*> Indices;
954 BasicBlock::iterator It = I;
956 if (const Type *ETy = ConvertibleToGEP(NewTy, IndexVal, Indices, TD,&It)){
957 // If successful, convert the add to a GEP
958 //const Type *RetTy = PointerType::get(ETy);
959 // First operand is actually the given pointer...
960 Res = new GetElementPtrInst(NewVal, Indices, Name);
961 assert(cast<PointerType>(Res->getType())->getElementType() == ETy &&
962 "ConvertibleToGEP broken!");
968 case Instruction::Sub:
969 case Instruction::SetEQ:
970 case Instruction::SetNE: {
971 Res = BinaryOperator::create(cast<BinaryOperator>(I)->getOpcode(),
973 VMC.ExprMap[I] = Res; // Add node to expression eagerly
975 unsigned OtherIdx = (OldVal == I->getOperand(0)) ? 1 : 0;
976 Value *OtherOp = I->getOperand(OtherIdx);
977 Value *NewOther = ConvertExpressionToType(OtherOp, NewTy, VMC, TD);
979 Res->setOperand(OtherIdx, NewOther);
980 Res->setOperand(!OtherIdx, NewVal);
983 case Instruction::Shl:
984 case Instruction::Shr:
985 assert(I->getOperand(0) == OldVal);
986 Res = new ShiftInst(cast<ShiftInst>(I)->getOpcode(), NewVal,
987 I->getOperand(1), Name);
990 case Instruction::Free: // Free can free any pointer type!
991 assert(I->getOperand(0) == OldVal);
992 Res = new FreeInst(NewVal);
996 case Instruction::Load: {
997 assert(I->getOperand(0) == OldVal && isa<PointerType>(NewVal->getType()));
998 const Type *LoadedTy =
999 cast<PointerType>(NewVal->getType())->getElementType();
1001 Value *Src = NewVal;
1003 if (const CompositeType *CT = dyn_cast<CompositeType>(LoadedTy)) {
1004 std::vector<Value*> Indices;
1005 Indices.push_back(ConstantSInt::get(Type::LongTy, 0));
1007 unsigned Offset = 0; // No offset, get first leaf.
1008 LoadedTy = getStructOffsetType(CT, Offset, Indices, TD, false);
1009 assert(LoadedTy->isFirstClassType());
1011 if (Indices.size() != 1) { // Do not generate load X, 0
1012 // Insert the GEP instruction before this load.
1013 Src = new GetElementPtrInst(Src, Indices, Name+".idx", I);
1017 Res = new LoadInst(Src, Name);
1018 assert(Res->getType()->isFirstClassType() && "Load of structure or array!");
1022 case Instruction::Store: {
1023 if (I->getOperand(0) == OldVal) { // Replace the source value
1024 // Check to see if operand #1 has already been converted...
1025 ValueMapCache::ExprMapTy::iterator VMCI =
1026 VMC.ExprMap.find(I->getOperand(1));
1027 if (VMCI != VMC.ExprMap.end()) {
1028 // Comments describing this stuff are in the OperandConvertibleToType
1029 // switch statement for Store...
1032 cast<PointerType>(VMCI->second->getType())->getElementType();
1034 Value *SrcPtr = VMCI->second;
1036 if (ElTy != NewTy) {
1037 // We check that this is a struct in the initial scan...
1038 const StructType *SElTy = cast<StructType>(ElTy);
1040 std::vector<Value*> Indices;
1041 Indices.push_back(Constant::getNullValue(Type::LongTy));
1043 unsigned Offset = 0;
1044 const Type *Ty = getStructOffsetType(ElTy, Offset, Indices, TD,false);
1045 assert(Offset == 0 && "Offset changed!");
1046 assert(NewTy == Ty && "Did not convert to correct type!");
1048 // Insert the GEP instruction before this store.
1049 SrcPtr = new GetElementPtrInst(SrcPtr, Indices,
1050 SrcPtr->getName()+".idx", I);
1052 Res = new StoreInst(NewVal, SrcPtr);
1054 VMC.ExprMap[I] = Res;
1056 // Otherwise, we haven't converted Operand #1 over yet...
1057 const PointerType *NewPT = PointerType::get(NewTy);
1058 Res = new StoreInst(NewVal, Constant::getNullValue(NewPT));
1059 VMC.ExprMap[I] = Res;
1060 Res->setOperand(1, ConvertExpressionToType(I->getOperand(1),
1063 } else { // Replace the source pointer
1064 const Type *ValTy = cast<PointerType>(NewTy)->getElementType();
1066 Value *SrcPtr = NewVal;
1068 if (isa<StructType>(ValTy)) {
1069 std::vector<Value*> Indices;
1070 Indices.push_back(Constant::getNullValue(Type::LongTy));
1072 unsigned Offset = 0;
1073 ValTy = getStructOffsetType(ValTy, Offset, Indices, TD, false);
1075 assert(Offset == 0 && ValTy);
1077 // Insert the GEP instruction before this store.
1078 SrcPtr = new GetElementPtrInst(SrcPtr, Indices,
1079 SrcPtr->getName()+".idx", I);
1082 Res = new StoreInst(Constant::getNullValue(ValTy), SrcPtr);
1083 VMC.ExprMap[I] = Res;
1084 Res->setOperand(0, ConvertExpressionToType(I->getOperand(0),
1091 case Instruction::GetElementPtr: {
1092 // Convert a one index getelementptr into just about anything that is
1095 BasicBlock::iterator It = I;
1096 const Type *OldElTy = cast<PointerType>(I->getType())->getElementType();
1097 unsigned DataSize = TD.getTypeSize(OldElTy);
1098 Value *Index = I->getOperand(1);
1100 if (DataSize != 1) {
1101 // Insert a multiply of the old element type is not a unit size...
1102 Index = BinaryOperator::create(Instruction::Mul, Index,
1103 ConstantSInt::get(Type::LongTy, DataSize),
1107 // Perform the conversion now...
1109 std::vector<Value*> Indices;
1110 const Type *ElTy = ConvertibleToGEP(NewVal->getType(),Index,Indices,TD,&It);
1111 assert(ElTy != 0 && "GEP Conversion Failure!");
1112 Res = new GetElementPtrInst(NewVal, Indices, Name);
1113 assert(Res->getType() == PointerType::get(ElTy) &&
1114 "ConvertibleToGet failed!");
1117 if (I->getType() == PointerType::get(Type::SByteTy)) {
1118 // Convert a getelementptr sbyte * %reg111, uint 16 freely back to
1119 // anything that is a pointer type...
1121 BasicBlock::iterator It = I;
1123 // Check to see if the second argument is an expression that can
1124 // be converted to the appropriate size... if so, allow it.
1126 std::vector<Value*> Indices;
1127 const Type *ElTy = ConvertibleToGEP(NewVal->getType(), I->getOperand(1),
1129 assert(ElTy != 0 && "GEP Conversion Failure!");
1131 Res = new GetElementPtrInst(NewVal, Indices, Name);
1133 // Convert a getelementptr ulong * %reg123, uint %N
1134 // to getelementptr long * %reg123, uint %N
1135 // ... where the type must simply stay the same size...
1137 GetElementPtrInst *GEP = cast<GetElementPtrInst>(I);
1138 std::vector<Value*> Indices(GEP->idx_begin(), GEP->idx_end());
1139 Res = new GetElementPtrInst(NewVal, Indices, Name);
1144 case Instruction::PHI: {
1145 PHINode *OldPN = cast<PHINode>(I);
1146 PHINode *NewPN = new PHINode(NewTy, Name);
1147 VMC.ExprMap[I] = NewPN;
1149 while (OldPN->getNumOperands()) {
1150 BasicBlock *BB = OldPN->getIncomingBlock(0);
1151 Value *OldVal = OldPN->getIncomingValue(0);
1152 OldPN->removeIncomingValue(BB, false);
1153 Value *V = ConvertExpressionToType(OldVal, NewTy, VMC, TD);
1154 NewPN->addIncoming(V, BB);
1160 case Instruction::Call: {
1161 Value *Meth = I->getOperand(0);
1162 std::vector<Value*> Params(I->op_begin()+1, I->op_end());
1164 if (Meth == OldVal) { // Changing the function pointer?
1165 const PointerType *NewPTy = cast<PointerType>(NewVal->getType());
1166 const FunctionType *NewTy = cast<FunctionType>(NewPTy->getElementType());
1167 const FunctionType::ParamTypes &PTs = NewTy->getParamTypes();
1169 if (NewTy->getReturnType() == Type::VoidTy)
1170 Name = ""; // Make sure not to name a void call!
1172 // Get an iterator to the call instruction so that we can insert casts for
1173 // operands if need be. Note that we do not require operands to be
1174 // convertible, we can insert casts if they are convertible but not
1175 // compatible. The reason for this is that we prefer to have resolved
1176 // functions but casted arguments if possible.
1178 BasicBlock::iterator It = I;
1180 // Convert over all of the call operands to their new types... but only
1181 // convert over the part that is not in the vararg section of the call.
1183 for (unsigned i = 0; i < PTs.size(); ++i)
1184 if (Params[i]->getType() != PTs[i]) {
1185 // Create a cast to convert it to the right type, we know that this
1186 // is a lossless cast...
1188 Params[i] = new CastInst(Params[i], PTs[i], "callarg.cast." +
1189 Params[i]->getName(), It);
1191 Meth = NewVal; // Update call destination to new value
1193 } else { // Changing an argument, must be in vararg area
1194 std::vector<Value*>::iterator OI =
1195 find(Params.begin(), Params.end(), OldVal);
1196 assert (OI != Params.end() && "Not using value!");
1201 Res = new CallInst(Meth, Params, Name);
1205 assert(0 && "Expression convertible, but don't know how to convert?");
1209 // If the instruction was newly created, insert it into the instruction
1212 BasicBlock::iterator It = I;
1213 assert(It != BB->end() && "Instruction not in own basic block??");
1214 BB->getInstList().insert(It, Res); // Keep It pointing to old instruction
1216 DEBUG(std::cerr << "COT CREATED: " << (void*)Res << " " << Res
1217 << "In: " << (void*)I << " " << I << "Out: " << (void*)Res
1220 // Add the instruction to the expression map
1221 VMC.ExprMap[I] = Res;
1223 if (I->getType() != Res->getType())
1224 ConvertValueToNewType(I, Res, VMC, TD);
1226 bool FromStart = true;
1227 Value::use_iterator UI;
1229 if (FromStart) UI = I->use_begin();
1230 if (UI == I->use_end()) break;
1232 if (isa<ValueHandle>(*UI)) {
1237 if (!FromStart) --UI;
1238 U->replaceUsesOfWith(I, Res);
1239 if (!FromStart) ++UI;
1246 ValueHandle::ValueHandle(ValueMapCache &VMC, Value *V)
1247 : Instruction(Type::VoidTy, UserOp1, ""), Cache(VMC) {
1248 //DEBUG(std::cerr << "VH AQUIRING: " << (void*)V << " " << V);
1249 Operands.push_back(Use(V, this));
1252 ValueHandle::ValueHandle(const ValueHandle &VH)
1253 : Instruction(Type::VoidTy, UserOp1, ""), Cache(VH.Cache) {
1254 //DEBUG(std::cerr << "VH AQUIRING: " << (void*)V << " " << V);
1255 Operands.push_back(Use((Value*)VH.getOperand(0), this));
1258 static void RecursiveDelete(ValueMapCache &Cache, Instruction *I) {
1259 if (!I || !I->use_empty()) return;
1261 assert(I->getParent() && "Inst not in basic block!");
1263 //DEBUG(std::cerr << "VH DELETING: " << (void*)I << " " << I);
1265 for (User::op_iterator OI = I->op_begin(), OE = I->op_end();
1267 if (Instruction *U = dyn_cast<Instruction>(OI)) {
1269 RecursiveDelete(Cache, U);
1272 I->getParent()->getInstList().remove(I);
1274 Cache.OperandsMapped.erase(I);
1275 Cache.ExprMap.erase(I);
1279 ValueHandle::~ValueHandle() {
1280 if (Operands[0]->hasOneUse()) {
1281 Value *V = Operands[0];
1282 Operands[0] = 0; // Drop use!
1284 // Now we just need to remove the old instruction so we don't get infinite
1285 // loops. Note that we cannot use DCE because DCE won't remove a store
1286 // instruction, for example.
1288 RecursiveDelete(Cache, dyn_cast<Instruction>(V));
1290 //DEBUG(std::cerr << "VH RELEASING: " << (void*)Operands[0].get() << " "
1291 // << Operands[0]->use_size() << " " << Operands[0]);