1 //===- ExprTypeConvert.cpp - Code to change an LLVM Expr Type -------------===//
3 // The LLVM Compiler Infrastructure
5 // This file was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements the part of level raising that checks to see if it is
11 // possible to coerce an entire expression tree into a different type. If
12 // convertible, other routines from this file will do the conversion.
14 //===----------------------------------------------------------------------===//
16 #include "TransformInternals.h"
17 #include "llvm/iOther.h"
18 #include "llvm/iPHINode.h"
19 #include "llvm/iMemory.h"
20 #include "llvm/ConstantHandling.h"
21 #include "llvm/Analysis/Expressions.h"
22 #include "Support/STLExtras.h"
23 #include "Support/Debug.h"
28 static bool OperandConvertibleToType(User *U, Value *V, const Type *Ty,
29 ValueTypeCache &ConvertedTypes,
30 const TargetData &TD);
32 static void ConvertOperandToType(User *U, Value *OldVal, Value *NewVal,
33 ValueMapCache &VMC, const TargetData &TD);
35 // Peephole Malloc instructions: we take a look at the use chain of the
36 // malloc instruction, and try to find out if the following conditions hold:
37 // 1. The malloc is of the form: 'malloc [sbyte], uint <constant>'
38 // 2. The only users of the malloc are cast & add instructions
39 // 3. Of the cast instructions, there is only one destination pointer type
40 // [RTy] where the size of the pointed to object is equal to the number
41 // of bytes allocated.
43 // If these conditions hold, we convert the malloc to allocate an [RTy]
44 // element. TODO: This comment is out of date WRT arrays
46 static bool MallocConvertibleToType(MallocInst *MI, const Type *Ty,
47 ValueTypeCache &CTMap,
48 const TargetData &TD) {
49 if (!isa<PointerType>(Ty)) return false; // Malloc always returns pointers
51 // Deal with the type to allocate, not the pointer type...
52 Ty = cast<PointerType>(Ty)->getElementType();
53 if (!Ty->isSized()) return false; // Can only alloc something with a size
55 // Analyze the number of bytes allocated...
56 ExprType Expr = ClassifyExpression(MI->getArraySize());
58 // Get information about the base datatype being allocated, before & after
59 int ReqTypeSize = TD.getTypeSize(Ty);
60 if (ReqTypeSize == 0) return false;
61 unsigned OldTypeSize = TD.getTypeSize(MI->getType()->getElementType());
63 // Must have a scale or offset to analyze it...
64 if (!Expr.Offset && !Expr.Scale && OldTypeSize == 1) return false;
66 // Get the offset and scale of the allocation...
67 int64_t OffsetVal = Expr.Offset ? getConstantValue(Expr.Offset) : 0;
68 int64_t ScaleVal = Expr.Scale ? getConstantValue(Expr.Scale) :(Expr.Var != 0);
70 // The old type might not be of unit size, take old size into consideration
72 int64_t Offset = OffsetVal * OldTypeSize;
73 int64_t Scale = ScaleVal * OldTypeSize;
75 // In order to be successful, both the scale and the offset must be a multiple
76 // of the requested data type's size.
78 if (Offset/ReqTypeSize*ReqTypeSize != Offset ||
79 Scale/ReqTypeSize*ReqTypeSize != Scale)
80 return false; // Nope.
85 static Instruction *ConvertMallocToType(MallocInst *MI, const Type *Ty,
86 const std::string &Name,
88 const TargetData &TD){
89 BasicBlock *BB = MI->getParent();
90 BasicBlock::iterator It = BB->end();
92 // Analyze the number of bytes allocated...
93 ExprType Expr = ClassifyExpression(MI->getArraySize());
95 const PointerType *AllocTy = cast<PointerType>(Ty);
96 const Type *ElType = AllocTy->getElementType();
98 unsigned DataSize = TD.getTypeSize(ElType);
99 unsigned OldTypeSize = TD.getTypeSize(MI->getType()->getElementType());
101 // Get the offset and scale coefficients that we are allocating...
102 int64_t OffsetVal = (Expr.Offset ? getConstantValue(Expr.Offset) : 0);
103 int64_t ScaleVal = Expr.Scale ? getConstantValue(Expr.Scale) : (Expr.Var !=0);
105 // The old type might not be of unit size, take old size into consideration
107 unsigned Offset = (uint64_t)OffsetVal * OldTypeSize / DataSize;
108 unsigned Scale = (uint64_t)ScaleVal * OldTypeSize / DataSize;
110 // Locate the malloc instruction, because we may be inserting instructions
113 // If we have a scale, apply it first...
115 // Expr.Var is not necessarily unsigned right now, insert a cast now.
116 if (Expr.Var->getType() != Type::UIntTy)
117 Expr.Var = new CastInst(Expr.Var, Type::UIntTy,
118 Expr.Var->getName()+"-uint", It);
121 Expr.Var = BinaryOperator::create(Instruction::Mul, Expr.Var,
122 ConstantUInt::get(Type::UIntTy, Scale),
123 Expr.Var->getName()+"-scl", It);
126 // If we are not scaling anything, just make the offset be the "var"...
127 Expr.Var = ConstantUInt::get(Type::UIntTy, Offset);
128 Offset = 0; Scale = 1;
131 // If we have an offset now, add it in...
133 assert(Expr.Var && "Var must be nonnull by now!");
134 Expr.Var = BinaryOperator::create(Instruction::Add, Expr.Var,
135 ConstantUInt::get(Type::UIntTy, Offset),
136 Expr.Var->getName()+"-off", It);
139 assert(AllocTy == Ty);
140 return new MallocInst(AllocTy->getElementType(), Expr.Var, Name);
144 // ExpressionConvertibleToType - Return true if it is possible
145 bool ExpressionConvertibleToType(Value *V, const Type *Ty,
146 ValueTypeCache &CTMap, const TargetData &TD) {
147 // Expression type must be holdable in a register.
148 if (!Ty->isFirstClassType())
151 ValueTypeCache::iterator CTMI = CTMap.find(V);
152 if (CTMI != CTMap.end()) return CTMI->second == Ty;
154 // If it's a constant... all constants can be converted to a different
155 // type. We just ask the constant propagator to see if it can convert the
158 if (Constant *CPV = dyn_cast<Constant>(V))
159 return ConstantFoldCastInstruction(CPV, Ty);
162 if (V->getType() == Ty) return true; // Expression already correct type!
164 Instruction *I = dyn_cast<Instruction>(V);
165 if (I == 0) return false; // Otherwise, we can't convert!
167 switch (I->getOpcode()) {
168 case Instruction::Cast:
169 // We can convert the expr if the cast destination type is losslessly
170 // convertible to the requested type.
171 if (!Ty->isLosslesslyConvertibleTo(I->getType())) return false;
173 // We also do not allow conversion of a cast that casts from a ptr to array
174 // of X to a *X. For example: cast [4 x %List *] * %val to %List * *
176 if (const PointerType *SPT =
177 dyn_cast<PointerType>(I->getOperand(0)->getType()))
178 if (const PointerType *DPT = dyn_cast<PointerType>(I->getType()))
179 if (const ArrayType *AT = dyn_cast<ArrayType>(SPT->getElementType()))
180 if (AT->getElementType() == DPT->getElementType())
184 case Instruction::Add:
185 case Instruction::Sub:
186 if (!Ty->isInteger() && !Ty->isFloatingPoint()) return false;
187 if (!ExpressionConvertibleToType(I->getOperand(0), Ty, CTMap, TD) ||
188 !ExpressionConvertibleToType(I->getOperand(1), Ty, CTMap, TD))
191 case Instruction::Shr:
192 if (!Ty->isInteger()) return false;
193 if (Ty->isSigned() != V->getType()->isSigned()) return false;
195 case Instruction::Shl:
196 if (!Ty->isInteger()) return false;
197 if (!ExpressionConvertibleToType(I->getOperand(0), Ty, CTMap, TD))
201 case Instruction::Load: {
202 LoadInst *LI = cast<LoadInst>(I);
203 if (!ExpressionConvertibleToType(LI->getPointerOperand(),
204 PointerType::get(Ty), CTMap, TD))
208 case Instruction::PHI: {
209 PHINode *PN = cast<PHINode>(I);
210 for (unsigned i = 0; i < PN->getNumIncomingValues(); ++i)
211 if (!ExpressionConvertibleToType(PN->getIncomingValue(i), Ty, CTMap, TD))
216 case Instruction::Malloc:
217 if (!MallocConvertibleToType(cast<MallocInst>(I), Ty, CTMap, TD))
221 case Instruction::GetElementPtr: {
222 // GetElementPtr's are directly convertible to a pointer type if they have
223 // a number of zeros at the end. Because removing these values does not
224 // change the logical offset of the GEP, it is okay and fair to remove them.
225 // This can change this:
226 // %t1 = getelementptr %Hosp * %hosp, ubyte 4, ubyte 0 ; <%List **>
227 // %t2 = cast %List * * %t1 to %List *
229 // %t2 = getelementptr %Hosp * %hosp, ubyte 4 ; <%List *>
231 GetElementPtrInst *GEP = cast<GetElementPtrInst>(I);
232 const PointerType *PTy = dyn_cast<PointerType>(Ty);
233 if (!PTy) return false; // GEP must always return a pointer...
234 const Type *PVTy = PTy->getElementType();
236 // Check to see if there are zero elements that we can remove from the
237 // index array. If there are, check to see if removing them causes us to
238 // get to the right type...
240 std::vector<Value*> Indices(GEP->idx_begin(), GEP->idx_end());
241 const Type *BaseType = GEP->getPointerOperand()->getType();
242 const Type *ElTy = 0;
244 while (!Indices.empty() &&
245 Indices.back() == Constant::getNullValue(Indices.back()->getType())){
247 ElTy = GetElementPtrInst::getIndexedType(BaseType, Indices, true);
249 break; // Found a match!!
253 if (ElTy) break; // Found a number of zeros we can strip off!
255 // Otherwise, we can convert a GEP from one form to the other iff the
256 // current gep is of the form 'getelementptr sbyte*, long N
257 // and we could convert this to an appropriate GEP for the new type.
259 if (GEP->getNumOperands() == 2 &&
260 GEP->getType() == PointerType::get(Type::SByteTy)) {
262 // Do not Check to see if our incoming pointer can be converted
263 // to be a ptr to an array of the right type... because in more cases than
264 // not, it is simply not analyzable because of pointer/array
265 // discrepancies. To fix this, we will insert a cast before the GEP.
268 // Check to see if 'N' is an expression that can be converted to
269 // the appropriate size... if so, allow it.
271 std::vector<Value*> Indices;
272 const Type *ElTy = ConvertibleToGEP(PTy, I->getOperand(1), Indices, TD);
274 if (!ExpressionConvertibleToType(I->getOperand(0),
275 PointerType::get(ElTy), CTMap, TD))
276 return false; // Can't continue, ExConToTy might have polluted set!
281 // Otherwise, it could be that we have something like this:
282 // getelementptr [[sbyte] *] * %reg115, long %reg138 ; [sbyte]**
283 // and want to convert it into something like this:
284 // getelemenptr [[int] *] * %reg115, long %reg138 ; [int]**
286 if (GEP->getNumOperands() == 2 &&
287 PTy->getElementType()->isSized() &&
288 TD.getTypeSize(PTy->getElementType()) ==
289 TD.getTypeSize(GEP->getType()->getElementType())) {
290 const PointerType *NewSrcTy = PointerType::get(PVTy);
291 if (!ExpressionConvertibleToType(I->getOperand(0), NewSrcTy, CTMap, TD))
296 return false; // No match, maybe next time.
299 case Instruction::Call: {
300 if (isa<Function>(I->getOperand(0)))
301 return false; // Don't even try to change direct calls.
303 // If this is a function pointer, we can convert the return type if we can
304 // convert the source function pointer.
306 const PointerType *PT = cast<PointerType>(I->getOperand(0)->getType());
307 const FunctionType *FT = cast<FunctionType>(PT->getElementType());
308 std::vector<const Type *> ArgTys(FT->getParamTypes().begin(),
309 FT->getParamTypes().end());
310 const FunctionType *NewTy =
311 FunctionType::get(Ty, ArgTys, FT->isVarArg());
312 if (!ExpressionConvertibleToType(I->getOperand(0),
313 PointerType::get(NewTy), CTMap, TD))
321 // Expressions are only convertible if all of the users of the expression can
322 // have this value converted. This makes use of the map to avoid infinite
325 for (Value::use_iterator It = I->use_begin(), E = I->use_end(); It != E; ++It)
326 if (!OperandConvertibleToType(*It, I, Ty, CTMap, TD))
333 Value *ConvertExpressionToType(Value *V, const Type *Ty, ValueMapCache &VMC,
334 const TargetData &TD) {
335 if (V->getType() == Ty) return V; // Already where we need to be?
337 ValueMapCache::ExprMapTy::iterator VMCI = VMC.ExprMap.find(V);
338 if (VMCI != VMC.ExprMap.end()) {
339 const Value *GV = VMCI->second;
340 const Type *GTy = VMCI->second->getType();
341 assert(VMCI->second->getType() == Ty);
343 if (Instruction *I = dyn_cast<Instruction>(V))
344 ValueHandle IHandle(VMC, I); // Remove I if it is unused now!
349 DEBUG(std::cerr << "CETT: " << (void*)V << " " << V);
351 Instruction *I = dyn_cast<Instruction>(V);
353 Constant *CPV = cast<Constant>(V);
354 // Constants are converted by constant folding the cast that is required.
355 // We assume here that all casts are implemented for constant prop.
356 Value *Result = ConstantFoldCastInstruction(CPV, Ty);
357 assert(Result && "ConstantFoldCastInstruction Failed!!!");
358 assert(Result->getType() == Ty && "Const prop of cast failed!");
360 // Add the instruction to the expression map
361 //VMC.ExprMap[V] = Result;
366 BasicBlock *BB = I->getParent();
367 std::string Name = I->getName(); if (!Name.empty()) I->setName("");
368 Instruction *Res; // Result of conversion
370 ValueHandle IHandle(VMC, I); // Prevent I from being removed!
372 Constant *Dummy = Constant::getNullValue(Ty);
374 switch (I->getOpcode()) {
375 case Instruction::Cast:
376 assert(VMC.NewCasts.count(ValueHandle(VMC, I)) == 0);
377 Res = new CastInst(I->getOperand(0), Ty, Name);
378 VMC.NewCasts.insert(ValueHandle(VMC, Res));
381 case Instruction::Add:
382 case Instruction::Sub:
383 Res = BinaryOperator::create(cast<BinaryOperator>(I)->getOpcode(),
385 VMC.ExprMap[I] = Res; // Add node to expression eagerly
387 Res->setOperand(0, ConvertExpressionToType(I->getOperand(0), Ty, VMC, TD));
388 Res->setOperand(1, ConvertExpressionToType(I->getOperand(1), Ty, VMC, TD));
391 case Instruction::Shl:
392 case Instruction::Shr:
393 Res = new ShiftInst(cast<ShiftInst>(I)->getOpcode(), Dummy,
394 I->getOperand(1), Name);
395 VMC.ExprMap[I] = Res;
396 Res->setOperand(0, ConvertExpressionToType(I->getOperand(0), Ty, VMC, TD));
399 case Instruction::Load: {
400 LoadInst *LI = cast<LoadInst>(I);
402 Res = new LoadInst(Constant::getNullValue(PointerType::get(Ty)), Name);
403 VMC.ExprMap[I] = Res;
404 Res->setOperand(0, ConvertExpressionToType(LI->getPointerOperand(),
405 PointerType::get(Ty), VMC, TD));
406 assert(Res->getOperand(0)->getType() == PointerType::get(Ty));
407 assert(Ty == Res->getType());
408 assert(Res->getType()->isFirstClassType() && "Load of structure or array!");
412 case Instruction::PHI: {
413 PHINode *OldPN = cast<PHINode>(I);
414 PHINode *NewPN = new PHINode(Ty, Name);
416 VMC.ExprMap[I] = NewPN; // Add node to expression eagerly
417 while (OldPN->getNumOperands()) {
418 BasicBlock *BB = OldPN->getIncomingBlock(0);
419 Value *OldVal = OldPN->getIncomingValue(0);
420 ValueHandle OldValHandle(VMC, OldVal);
421 OldPN->removeIncomingValue(BB, false);
422 Value *V = ConvertExpressionToType(OldVal, Ty, VMC, TD);
423 NewPN->addIncoming(V, BB);
429 case Instruction::Malloc: {
430 Res = ConvertMallocToType(cast<MallocInst>(I), Ty, Name, VMC, TD);
434 case Instruction::GetElementPtr: {
435 // GetElementPtr's are directly convertible to a pointer type if they have
436 // a number of zeros at the end. Because removing these values does not
437 // change the logical offset of the GEP, it is okay and fair to remove them.
438 // This can change this:
439 // %t1 = getelementptr %Hosp * %hosp, ubyte 4, ubyte 0 ; <%List **>
440 // %t2 = cast %List * * %t1 to %List *
442 // %t2 = getelementptr %Hosp * %hosp, ubyte 4 ; <%List *>
444 GetElementPtrInst *GEP = cast<GetElementPtrInst>(I);
446 // Check to see if there are zero elements that we can remove from the
447 // index array. If there are, check to see if removing them causes us to
448 // get to the right type...
450 std::vector<Value*> Indices(GEP->idx_begin(), GEP->idx_end());
451 const Type *BaseType = GEP->getPointerOperand()->getType();
452 const Type *PVTy = cast<PointerType>(Ty)->getElementType();
454 while (!Indices.empty() &&
455 Indices.back() == Constant::getNullValue(Indices.back()->getType())){
457 if (GetElementPtrInst::getIndexedType(BaseType, Indices, true) == PVTy) {
458 if (Indices.size() == 0)
459 Res = new CastInst(GEP->getPointerOperand(), BaseType); // NOOP CAST
461 Res = new GetElementPtrInst(GEP->getPointerOperand(), Indices, Name);
466 if (Res == 0 && GEP->getNumOperands() == 2 &&
467 GEP->getType() == PointerType::get(Type::SByteTy)) {
469 // Otherwise, we can convert a GEP from one form to the other iff the
470 // current gep is of the form 'getelementptr sbyte*, unsigned N
471 // and we could convert this to an appropriate GEP for the new type.
473 const PointerType *NewSrcTy = PointerType::get(PVTy);
474 BasicBlock::iterator It = I;
476 // Check to see if 'N' is an expression that can be converted to
477 // the appropriate size... if so, allow it.
479 std::vector<Value*> Indices;
480 const Type *ElTy = ConvertibleToGEP(NewSrcTy, I->getOperand(1),
483 assert(ElTy == PVTy && "Internal error, setup wrong!");
484 Res = new GetElementPtrInst(Constant::getNullValue(NewSrcTy),
486 VMC.ExprMap[I] = Res;
487 Res->setOperand(0, ConvertExpressionToType(I->getOperand(0),
492 // Otherwise, it could be that we have something like this:
493 // getelementptr [[sbyte] *] * %reg115, uint %reg138 ; [sbyte]**
494 // and want to convert it into something like this:
495 // getelemenptr [[int] *] * %reg115, uint %reg138 ; [int]**
498 const PointerType *NewSrcTy = PointerType::get(PVTy);
499 std::vector<Value*> Indices(GEP->idx_begin(), GEP->idx_end());
500 Res = new GetElementPtrInst(Constant::getNullValue(NewSrcTy),
502 VMC.ExprMap[I] = Res;
503 Res->setOperand(0, ConvertExpressionToType(I->getOperand(0),
508 assert(Res && "Didn't find match!");
512 case Instruction::Call: {
513 assert(!isa<Function>(I->getOperand(0)));
515 // If this is a function pointer, we can convert the return type if we can
516 // convert the source function pointer.
518 const PointerType *PT = cast<PointerType>(I->getOperand(0)->getType());
519 const FunctionType *FT = cast<FunctionType>(PT->getElementType());
520 std::vector<const Type *> ArgTys(FT->getParamTypes().begin(),
521 FT->getParamTypes().end());
522 const FunctionType *NewTy =
523 FunctionType::get(Ty, ArgTys, FT->isVarArg());
524 const PointerType *NewPTy = PointerType::get(NewTy);
525 if (Ty == Type::VoidTy)
526 Name = ""; // Make sure not to name calls that now return void!
528 Res = new CallInst(Constant::getNullValue(NewPTy),
529 std::vector<Value*>(I->op_begin()+1, I->op_end()),
531 VMC.ExprMap[I] = Res;
532 Res->setOperand(0, ConvertExpressionToType(I->getOperand(0),NewPTy,VMC,TD));
536 assert(0 && "Expression convertible, but don't know how to convert?");
540 assert(Res->getType() == Ty && "Didn't convert expr to correct type!");
542 BB->getInstList().insert(I, Res);
544 // Add the instruction to the expression map
545 VMC.ExprMap[I] = Res;
548 unsigned NumUses = I->use_size();
549 for (unsigned It = 0; It < NumUses; ) {
550 unsigned OldSize = NumUses;
551 Value::use_iterator UI = I->use_begin();
552 std::advance(UI, It);
553 ConvertOperandToType(*UI, I, Res, VMC, TD);
554 NumUses = I->use_size();
555 if (NumUses == OldSize) ++It;
558 DEBUG(std::cerr << "ExpIn: " << (void*)I << " " << I
559 << "ExpOut: " << (void*)Res << " " << Res);
566 // ValueConvertibleToType - Return true if it is possible
567 bool ValueConvertibleToType(Value *V, const Type *Ty,
568 ValueTypeCache &ConvertedTypes,
569 const TargetData &TD) {
570 ValueTypeCache::iterator I = ConvertedTypes.find(V);
571 if (I != ConvertedTypes.end()) return I->second == Ty;
572 ConvertedTypes[V] = Ty;
574 // It is safe to convert the specified value to the specified type IFF all of
575 // the uses of the value can be converted to accept the new typed value.
577 if (V->getType() != Ty) {
578 for (Value::use_iterator I = V->use_begin(), E = V->use_end(); I != E; ++I)
579 if (!OperandConvertibleToType(*I, V, Ty, ConvertedTypes, TD))
590 // OperandConvertibleToType - Return true if it is possible to convert operand
591 // V of User (instruction) U to the specified type. This is true iff it is
592 // possible to change the specified instruction to accept this. CTMap is a map
593 // of converted types, so that circular definitions will see the future type of
594 // the expression, not the static current type.
596 static bool OperandConvertibleToType(User *U, Value *V, const Type *Ty,
597 ValueTypeCache &CTMap,
598 const TargetData &TD) {
599 // if (V->getType() == Ty) return true; // Operand already the right type?
601 // Expression type must be holdable in a register.
602 if (!Ty->isFirstClassType())
605 Instruction *I = dyn_cast<Instruction>(U);
606 if (I == 0) return false; // We can't convert!
608 switch (I->getOpcode()) {
609 case Instruction::Cast:
610 assert(I->getOperand(0) == V);
611 // We can convert the expr if the cast destination type is losslessly
612 // convertible to the requested type.
613 // Also, do not change a cast that is a noop cast. For all intents and
614 // purposes it should be eliminated.
615 if (!Ty->isLosslesslyConvertibleTo(I->getOperand(0)->getType()) ||
616 I->getType() == I->getOperand(0)->getType())
619 // Do not allow a 'cast ushort %V to uint' to have it's first operand be
620 // converted to a 'short' type. Doing so changes the way sign promotion
621 // happens, and breaks things. Only allow the cast to take place if the
622 // signedness doesn't change... or if the current cast is not a lossy
625 if (!I->getType()->isLosslesslyConvertibleTo(I->getOperand(0)->getType()) &&
626 I->getOperand(0)->getType()->isSigned() != Ty->isSigned())
629 // We also do not allow conversion of a cast that casts from a ptr to array
630 // of X to a *X. For example: cast [4 x %List *] * %val to %List * *
632 if (const PointerType *SPT =
633 dyn_cast<PointerType>(I->getOperand(0)->getType()))
634 if (const PointerType *DPT = dyn_cast<PointerType>(I->getType()))
635 if (const ArrayType *AT = dyn_cast<ArrayType>(SPT->getElementType()))
636 if (AT->getElementType() == DPT->getElementType())
640 case Instruction::Add:
641 if (isa<PointerType>(Ty)) {
642 Value *IndexVal = I->getOperand(V == I->getOperand(0) ? 1 : 0);
643 std::vector<Value*> Indices;
644 if (const Type *ETy = ConvertibleToGEP(Ty, IndexVal, Indices, TD)) {
645 const Type *RetTy = PointerType::get(ETy);
647 // Only successful if we can convert this type to the required type
648 if (ValueConvertibleToType(I, RetTy, CTMap, TD)) {
652 // We have to return failure here because ValueConvertibleToType could
653 // have polluted our map
658 case Instruction::Sub: {
659 if (!Ty->isInteger() && !Ty->isFloatingPoint()) return false;
661 Value *OtherOp = I->getOperand((V == I->getOperand(0)) ? 1 : 0);
662 return ValueConvertibleToType(I, Ty, CTMap, TD) &&
663 ExpressionConvertibleToType(OtherOp, Ty, CTMap, TD);
665 case Instruction::SetEQ:
666 case Instruction::SetNE: {
667 Value *OtherOp = I->getOperand((V == I->getOperand(0)) ? 1 : 0);
668 return ExpressionConvertibleToType(OtherOp, Ty, CTMap, TD);
670 case Instruction::Shr:
671 if (Ty->isSigned() != V->getType()->isSigned()) return false;
673 case Instruction::Shl:
674 if (I->getOperand(1) == V) return false; // Cannot change shift amount type
675 if (!Ty->isInteger()) return false;
676 return ValueConvertibleToType(I, Ty, CTMap, TD);
678 case Instruction::Free:
679 assert(I->getOperand(0) == V);
680 return isa<PointerType>(Ty); // Free can free any pointer type!
682 case Instruction::Load:
683 // Cannot convert the types of any subscripts...
684 if (I->getOperand(0) != V) return false;
686 if (const PointerType *PT = dyn_cast<PointerType>(Ty)) {
687 LoadInst *LI = cast<LoadInst>(I);
689 const Type *LoadedTy = PT->getElementType();
691 // They could be loading the first element of a composite type...
692 if (const CompositeType *CT = dyn_cast<CompositeType>(LoadedTy)) {
693 unsigned Offset = 0; // No offset, get first leaf.
694 std::vector<Value*> Indices; // Discarded...
695 LoadedTy = getStructOffsetType(CT, Offset, Indices, TD, false);
696 assert(Offset == 0 && "Offset changed from zero???");
699 if (!LoadedTy->isFirstClassType())
702 if (TD.getTypeSize(LoadedTy) != TD.getTypeSize(LI->getType()))
705 return ValueConvertibleToType(LI, LoadedTy, CTMap, TD);
709 case Instruction::Store: {
710 StoreInst *SI = cast<StoreInst>(I);
712 if (V == I->getOperand(0)) {
713 ValueTypeCache::iterator CTMI = CTMap.find(I->getOperand(1));
714 if (CTMI != CTMap.end()) { // Operand #1 is in the table already?
715 // If so, check to see if it's Ty*, or, more importantly, if it is a
716 // pointer to a structure where the first element is a Ty... this code
717 // is necessary because we might be trying to change the source and
718 // destination type of the store (they might be related) and the dest
719 // pointer type might be a pointer to structure. Below we allow pointer
720 // to structures where the 0th element is compatible with the value,
721 // now we have to support the symmetrical part of this.
723 const Type *ElTy = cast<PointerType>(CTMI->second)->getElementType();
725 // Already a pointer to what we want? Trivially accept...
726 if (ElTy == Ty) return true;
728 // Tricky case now, if the destination is a pointer to structure,
729 // obviously the source is not allowed to be a structure (cannot copy
730 // a whole structure at a time), so the level raiser must be trying to
731 // store into the first field. Check for this and allow it now:
733 if (const StructType *SElTy = dyn_cast<StructType>(ElTy)) {
735 std::vector<Value*> Indices;
736 ElTy = getStructOffsetType(ElTy, Offset, Indices, TD, false);
737 assert(Offset == 0 && "Offset changed!");
738 if (ElTy == 0) // Element at offset zero in struct doesn't exist!
739 return false; // Can only happen for {}*
741 if (ElTy == Ty) // Looks like the 0th element of structure is
742 return true; // compatible! Accept now!
744 // Otherwise we know that we can't work, so just stop trying now.
749 // Can convert the store if we can convert the pointer operand to match
750 // the new value type...
751 return ExpressionConvertibleToType(I->getOperand(1), PointerType::get(Ty),
753 } else if (const PointerType *PT = dyn_cast<PointerType>(Ty)) {
754 const Type *ElTy = PT->getElementType();
755 assert(V == I->getOperand(1));
757 if (isa<StructType>(ElTy)) {
758 // We can change the destination pointer if we can store our first
759 // argument into the first element of the structure...
762 std::vector<Value*> Indices;
763 ElTy = getStructOffsetType(ElTy, Offset, Indices, TD, false);
764 assert(Offset == 0 && "Offset changed!");
765 if (ElTy == 0) // Element at offset zero in struct doesn't exist!
766 return false; // Can only happen for {}*
769 // Must move the same amount of data...
770 if (!ElTy->isSized() ||
771 TD.getTypeSize(ElTy) != TD.getTypeSize(I->getOperand(0)->getType()))
774 // Can convert store if the incoming value is convertible and if the
775 // result will preserve semantics...
776 const Type *Op0Ty = I->getOperand(0)->getType();
777 if (!(Op0Ty->isIntegral() ^ ElTy->isIntegral()) &&
778 !(Op0Ty->isFloatingPoint() ^ ElTy->isFloatingPoint()))
779 return ExpressionConvertibleToType(I->getOperand(0), ElTy, CTMap, TD);
784 case Instruction::GetElementPtr:
785 if (V != I->getOperand(0) || !isa<PointerType>(Ty)) return false;
787 // If we have a two operand form of getelementptr, this is really little
788 // more than a simple addition. As with addition, check to see if the
789 // getelementptr instruction can be changed to index into the new type.
791 if (I->getNumOperands() == 2) {
792 const Type *OldElTy = cast<PointerType>(I->getType())->getElementType();
793 unsigned DataSize = TD.getTypeSize(OldElTy);
794 Value *Index = I->getOperand(1);
795 Instruction *TempScale = 0;
797 // If the old data element is not unit sized, we have to create a scale
798 // instruction so that ConvertibleToGEP will know the REAL amount we are
799 // indexing by. Note that this is never inserted into the instruction
800 // stream, so we have to delete it when we're done.
803 TempScale = BinaryOperator::create(Instruction::Mul, Index,
804 ConstantSInt::get(Type::LongTy,
809 // Check to see if the second argument is an expression that can
810 // be converted to the appropriate size... if so, allow it.
812 std::vector<Value*> Indices;
813 const Type *ElTy = ConvertibleToGEP(Ty, Index, Indices, TD);
814 delete TempScale; // Free our temporary multiply if we made it
816 if (ElTy == 0) return false; // Cannot make conversion...
817 return ValueConvertibleToType(I, PointerType::get(ElTy), CTMap, TD);
821 case Instruction::PHI: {
822 PHINode *PN = cast<PHINode>(I);
823 for (unsigned i = 0; i < PN->getNumIncomingValues(); ++i)
824 if (!ExpressionConvertibleToType(PN->getIncomingValue(i), Ty, CTMap, TD))
826 return ValueConvertibleToType(PN, Ty, CTMap, TD);
829 case Instruction::Call: {
830 User::op_iterator OI = find(I->op_begin(), I->op_end(), V);
831 assert (OI != I->op_end() && "Not using value!");
832 unsigned OpNum = OI - I->op_begin();
834 // Are we trying to change the function pointer value to a new type?
836 const PointerType *PTy = dyn_cast<PointerType>(Ty);
837 if (PTy == 0) return false; // Can't convert to a non-pointer type...
838 const FunctionType *FTy = dyn_cast<FunctionType>(PTy->getElementType());
839 if (FTy == 0) return false; // Can't convert to a non ptr to function...
841 // Do not allow converting to a call where all of the operands are ...'s
842 if (FTy->getNumParams() == 0 && FTy->isVarArg())
843 return false; // Do not permit this conversion!
845 // Perform sanity checks to make sure that new function type has the
846 // correct number of arguments...
848 unsigned NumArgs = I->getNumOperands()-1; // Don't include function ptr
850 // Cannot convert to a type that requires more fixed arguments than
851 // the call provides...
853 if (NumArgs < FTy->getNumParams()) return false;
855 // Unless this is a vararg function type, we cannot provide more arguments
856 // than are desired...
858 if (!FTy->isVarArg() && NumArgs > FTy->getNumParams())
861 // Okay, at this point, we know that the call and the function type match
862 // number of arguments. Now we see if we can convert the arguments
863 // themselves. Note that we do not require operands to be convertible,
864 // we can insert casts if they are convertible but not compatible. The
865 // reason for this is that we prefer to have resolved functions but casted
866 // arguments if possible.
868 const FunctionType::ParamTypes &PTs = FTy->getParamTypes();
869 for (unsigned i = 0, NA = PTs.size(); i < NA; ++i)
870 if (!PTs[i]->isLosslesslyConvertibleTo(I->getOperand(i+1)->getType()))
871 return false; // Operands must have compatible types!
873 // Okay, at this point, we know that all of the arguments can be
874 // converted. We succeed if we can change the return type if
877 return ValueConvertibleToType(I, FTy->getReturnType(), CTMap, TD);
880 const PointerType *MPtr = cast<PointerType>(I->getOperand(0)->getType());
881 const FunctionType *FTy = cast<FunctionType>(MPtr->getElementType());
882 if (!FTy->isVarArg()) return false;
884 if ((OpNum-1) < FTy->getParamTypes().size())
885 return false; // It's not in the varargs section...
887 // If we get this far, we know the value is in the varargs section of the
888 // function! We can convert if we don't reinterpret the value...
890 return Ty->isLosslesslyConvertibleTo(V->getType());
897 void ConvertValueToNewType(Value *V, Value *NewVal, ValueMapCache &VMC,
898 const TargetData &TD) {
899 ValueHandle VH(VMC, V);
901 unsigned NumUses = V->use_size();
902 for (unsigned It = 0; It < NumUses; ) {
903 unsigned OldSize = NumUses;
904 Value::use_iterator UI = V->use_begin();
905 std::advance(UI, It);
906 ConvertOperandToType(*UI, V, NewVal, VMC, TD);
907 NumUses = V->use_size();
908 if (NumUses == OldSize) ++It;
914 static void ConvertOperandToType(User *U, Value *OldVal, Value *NewVal,
915 ValueMapCache &VMC, const TargetData &TD) {
916 if (isa<ValueHandle>(U)) return; // Valuehandles don't let go of operands...
918 if (VMC.OperandsMapped.count(U)) return;
919 VMC.OperandsMapped.insert(U);
921 ValueMapCache::ExprMapTy::iterator VMCI = VMC.ExprMap.find(U);
922 if (VMCI != VMC.ExprMap.end())
926 Instruction *I = cast<Instruction>(U); // Only Instructions convertible
928 BasicBlock *BB = I->getParent();
929 assert(BB != 0 && "Instruction not embedded in basic block!");
930 std::string Name = I->getName();
932 Instruction *Res; // Result of conversion
934 //std::cerr << endl << endl << "Type:\t" << Ty << "\nInst: " << I
935 // << "BB Before: " << BB << endl;
937 // Prevent I from being removed...
938 ValueHandle IHandle(VMC, I);
940 const Type *NewTy = NewVal->getType();
941 Constant *Dummy = (NewTy != Type::VoidTy) ?
942 Constant::getNullValue(NewTy) : 0;
944 switch (I->getOpcode()) {
945 case Instruction::Cast:
946 if (VMC.NewCasts.count(ValueHandle(VMC, I))) {
947 // This cast has already had it's value converted, causing a new cast to
948 // be created. We don't want to create YET ANOTHER cast instruction
949 // representing the original one, so just modify the operand of this cast
950 // instruction, which we know is newly created.
951 I->setOperand(0, NewVal);
952 I->setName(Name); // give I its name back
956 Res = new CastInst(NewVal, I->getType(), Name);
960 case Instruction::Add:
961 if (isa<PointerType>(NewTy)) {
962 Value *IndexVal = I->getOperand(OldVal == I->getOperand(0) ? 1 : 0);
963 std::vector<Value*> Indices;
964 BasicBlock::iterator It = I;
966 if (const Type *ETy = ConvertibleToGEP(NewTy, IndexVal, Indices, TD,&It)){
967 // If successful, convert the add to a GEP
968 //const Type *RetTy = PointerType::get(ETy);
969 // First operand is actually the given pointer...
970 Res = new GetElementPtrInst(NewVal, Indices, Name);
971 assert(cast<PointerType>(Res->getType())->getElementType() == ETy &&
972 "ConvertibleToGEP broken!");
978 case Instruction::Sub:
979 case Instruction::SetEQ:
980 case Instruction::SetNE: {
981 Res = BinaryOperator::create(cast<BinaryOperator>(I)->getOpcode(),
983 VMC.ExprMap[I] = Res; // Add node to expression eagerly
985 unsigned OtherIdx = (OldVal == I->getOperand(0)) ? 1 : 0;
986 Value *OtherOp = I->getOperand(OtherIdx);
987 Value *NewOther = ConvertExpressionToType(OtherOp, NewTy, VMC, TD);
989 Res->setOperand(OtherIdx, NewOther);
990 Res->setOperand(!OtherIdx, NewVal);
993 case Instruction::Shl:
994 case Instruction::Shr:
995 assert(I->getOperand(0) == OldVal);
996 Res = new ShiftInst(cast<ShiftInst>(I)->getOpcode(), NewVal,
997 I->getOperand(1), Name);
1000 case Instruction::Free: // Free can free any pointer type!
1001 assert(I->getOperand(0) == OldVal);
1002 Res = new FreeInst(NewVal);
1006 case Instruction::Load: {
1007 assert(I->getOperand(0) == OldVal && isa<PointerType>(NewVal->getType()));
1008 const Type *LoadedTy =
1009 cast<PointerType>(NewVal->getType())->getElementType();
1011 Value *Src = NewVal;
1013 if (const CompositeType *CT = dyn_cast<CompositeType>(LoadedTy)) {
1014 std::vector<Value*> Indices;
1015 Indices.push_back(ConstantSInt::get(Type::LongTy, 0));
1017 unsigned Offset = 0; // No offset, get first leaf.
1018 LoadedTy = getStructOffsetType(CT, Offset, Indices, TD, false);
1019 assert(LoadedTy->isFirstClassType());
1021 if (Indices.size() != 1) { // Do not generate load X, 0
1022 // Insert the GEP instruction before this load.
1023 Src = new GetElementPtrInst(Src, Indices, Name+".idx", I);
1027 Res = new LoadInst(Src, Name);
1028 assert(Res->getType()->isFirstClassType() && "Load of structure or array!");
1032 case Instruction::Store: {
1033 if (I->getOperand(0) == OldVal) { // Replace the source value
1034 // Check to see if operand #1 has already been converted...
1035 ValueMapCache::ExprMapTy::iterator VMCI =
1036 VMC.ExprMap.find(I->getOperand(1));
1037 if (VMCI != VMC.ExprMap.end()) {
1038 // Comments describing this stuff are in the OperandConvertibleToType
1039 // switch statement for Store...
1042 cast<PointerType>(VMCI->second->getType())->getElementType();
1044 Value *SrcPtr = VMCI->second;
1046 if (ElTy != NewTy) {
1047 // We check that this is a struct in the initial scan...
1048 const StructType *SElTy = cast<StructType>(ElTy);
1050 std::vector<Value*> Indices;
1051 Indices.push_back(Constant::getNullValue(Type::LongTy));
1053 unsigned Offset = 0;
1054 const Type *Ty = getStructOffsetType(ElTy, Offset, Indices, TD,false);
1055 assert(Offset == 0 && "Offset changed!");
1056 assert(NewTy == Ty && "Did not convert to correct type!");
1058 // Insert the GEP instruction before this store.
1059 SrcPtr = new GetElementPtrInst(SrcPtr, Indices,
1060 SrcPtr->getName()+".idx", I);
1062 Res = new StoreInst(NewVal, SrcPtr);
1064 VMC.ExprMap[I] = Res;
1066 // Otherwise, we haven't converted Operand #1 over yet...
1067 const PointerType *NewPT = PointerType::get(NewTy);
1068 Res = new StoreInst(NewVal, Constant::getNullValue(NewPT));
1069 VMC.ExprMap[I] = Res;
1070 Res->setOperand(1, ConvertExpressionToType(I->getOperand(1),
1073 } else { // Replace the source pointer
1074 const Type *ValTy = cast<PointerType>(NewTy)->getElementType();
1076 Value *SrcPtr = NewVal;
1078 if (isa<StructType>(ValTy)) {
1079 std::vector<Value*> Indices;
1080 Indices.push_back(Constant::getNullValue(Type::LongTy));
1082 unsigned Offset = 0;
1083 ValTy = getStructOffsetType(ValTy, Offset, Indices, TD, false);
1085 assert(Offset == 0 && ValTy);
1087 // Insert the GEP instruction before this store.
1088 SrcPtr = new GetElementPtrInst(SrcPtr, Indices,
1089 SrcPtr->getName()+".idx", I);
1092 Res = new StoreInst(Constant::getNullValue(ValTy), SrcPtr);
1093 VMC.ExprMap[I] = Res;
1094 Res->setOperand(0, ConvertExpressionToType(I->getOperand(0),
1101 case Instruction::GetElementPtr: {
1102 // Convert a one index getelementptr into just about anything that is
1105 BasicBlock::iterator It = I;
1106 const Type *OldElTy = cast<PointerType>(I->getType())->getElementType();
1107 unsigned DataSize = TD.getTypeSize(OldElTy);
1108 Value *Index = I->getOperand(1);
1110 if (DataSize != 1) {
1111 // Insert a multiply of the old element type is not a unit size...
1112 Index = BinaryOperator::create(Instruction::Mul, Index,
1113 ConstantSInt::get(Type::LongTy, DataSize),
1117 // Perform the conversion now...
1119 std::vector<Value*> Indices;
1120 const Type *ElTy = ConvertibleToGEP(NewVal->getType(),Index,Indices,TD,&It);
1121 assert(ElTy != 0 && "GEP Conversion Failure!");
1122 Res = new GetElementPtrInst(NewVal, Indices, Name);
1123 assert(Res->getType() == PointerType::get(ElTy) &&
1124 "ConvertibleToGet failed!");
1127 if (I->getType() == PointerType::get(Type::SByteTy)) {
1128 // Convert a getelementptr sbyte * %reg111, uint 16 freely back to
1129 // anything that is a pointer type...
1131 BasicBlock::iterator It = I;
1133 // Check to see if the second argument is an expression that can
1134 // be converted to the appropriate size... if so, allow it.
1136 std::vector<Value*> Indices;
1137 const Type *ElTy = ConvertibleToGEP(NewVal->getType(), I->getOperand(1),
1139 assert(ElTy != 0 && "GEP Conversion Failure!");
1141 Res = new GetElementPtrInst(NewVal, Indices, Name);
1143 // Convert a getelementptr ulong * %reg123, uint %N
1144 // to getelementptr long * %reg123, uint %N
1145 // ... where the type must simply stay the same size...
1147 GetElementPtrInst *GEP = cast<GetElementPtrInst>(I);
1148 std::vector<Value*> Indices(GEP->idx_begin(), GEP->idx_end());
1149 Res = new GetElementPtrInst(NewVal, Indices, Name);
1154 case Instruction::PHI: {
1155 PHINode *OldPN = cast<PHINode>(I);
1156 PHINode *NewPN = new PHINode(NewTy, Name);
1157 VMC.ExprMap[I] = NewPN;
1159 while (OldPN->getNumOperands()) {
1160 BasicBlock *BB = OldPN->getIncomingBlock(0);
1161 Value *OldVal = OldPN->getIncomingValue(0);
1162 OldPN->removeIncomingValue(BB, false);
1163 Value *V = ConvertExpressionToType(OldVal, NewTy, VMC, TD);
1164 NewPN->addIncoming(V, BB);
1170 case Instruction::Call: {
1171 Value *Meth = I->getOperand(0);
1172 std::vector<Value*> Params(I->op_begin()+1, I->op_end());
1174 if (Meth == OldVal) { // Changing the function pointer?
1175 const PointerType *NewPTy = cast<PointerType>(NewVal->getType());
1176 const FunctionType *NewTy = cast<FunctionType>(NewPTy->getElementType());
1177 const FunctionType::ParamTypes &PTs = NewTy->getParamTypes();
1179 if (NewTy->getReturnType() == Type::VoidTy)
1180 Name = ""; // Make sure not to name a void call!
1182 // Get an iterator to the call instruction so that we can insert casts for
1183 // operands if need be. Note that we do not require operands to be
1184 // convertible, we can insert casts if they are convertible but not
1185 // compatible. The reason for this is that we prefer to have resolved
1186 // functions but casted arguments if possible.
1188 BasicBlock::iterator It = I;
1190 // Convert over all of the call operands to their new types... but only
1191 // convert over the part that is not in the vararg section of the call.
1193 for (unsigned i = 0; i < PTs.size(); ++i)
1194 if (Params[i]->getType() != PTs[i]) {
1195 // Create a cast to convert it to the right type, we know that this
1196 // is a lossless cast...
1198 Params[i] = new CastInst(Params[i], PTs[i], "callarg.cast." +
1199 Params[i]->getName(), It);
1201 Meth = NewVal; // Update call destination to new value
1203 } else { // Changing an argument, must be in vararg area
1204 std::vector<Value*>::iterator OI =
1205 find(Params.begin(), Params.end(), OldVal);
1206 assert (OI != Params.end() && "Not using value!");
1211 Res = new CallInst(Meth, Params, Name);
1215 assert(0 && "Expression convertible, but don't know how to convert?");
1219 // If the instruction was newly created, insert it into the instruction
1222 BasicBlock::iterator It = I;
1223 assert(It != BB->end() && "Instruction not in own basic block??");
1224 BB->getInstList().insert(It, Res); // Keep It pointing to old instruction
1226 DEBUG(std::cerr << "COT CREATED: " << (void*)Res << " " << Res
1227 << "In: " << (void*)I << " " << I << "Out: " << (void*)Res
1230 // Add the instruction to the expression map
1231 VMC.ExprMap[I] = Res;
1233 if (I->getType() != Res->getType())
1234 ConvertValueToNewType(I, Res, VMC, TD);
1236 bool FromStart = true;
1237 Value::use_iterator UI;
1239 if (FromStart) UI = I->use_begin();
1240 if (UI == I->use_end()) break;
1242 if (isa<ValueHandle>(*UI)) {
1247 if (!FromStart) --UI;
1248 U->replaceUsesOfWith(I, Res);
1249 if (!FromStart) ++UI;
1256 ValueHandle::ValueHandle(ValueMapCache &VMC, Value *V)
1257 : Instruction(Type::VoidTy, UserOp1, ""), Cache(VMC) {
1258 //DEBUG(std::cerr << "VH AQUIRING: " << (void*)V << " " << V);
1259 Operands.push_back(Use(V, this));
1262 ValueHandle::ValueHandle(const ValueHandle &VH)
1263 : Instruction(Type::VoidTy, UserOp1, ""), Cache(VH.Cache) {
1264 //DEBUG(std::cerr << "VH AQUIRING: " << (void*)V << " " << V);
1265 Operands.push_back(Use((Value*)VH.getOperand(0), this));
1268 static void RecursiveDelete(ValueMapCache &Cache, Instruction *I) {
1269 if (!I || !I->use_empty()) return;
1271 assert(I->getParent() && "Inst not in basic block!");
1273 //DEBUG(std::cerr << "VH DELETING: " << (void*)I << " " << I);
1275 for (User::op_iterator OI = I->op_begin(), OE = I->op_end();
1277 if (Instruction *U = dyn_cast<Instruction>(OI)) {
1279 RecursiveDelete(Cache, U);
1282 I->getParent()->getInstList().remove(I);
1284 Cache.OperandsMapped.erase(I);
1285 Cache.ExprMap.erase(I);
1289 ValueHandle::~ValueHandle() {
1290 if (Operands[0]->hasOneUse()) {
1291 Value *V = Operands[0];
1292 Operands[0] = 0; // Drop use!
1294 // Now we just need to remove the old instruction so we don't get infinite
1295 // loops. Note that we cannot use DCE because DCE won't remove a store
1296 // instruction, for example.
1298 RecursiveDelete(Cache, dyn_cast<Instruction>(V));
1300 //DEBUG(std::cerr << "VH RELEASING: " << (void*)Operands[0].get() << " "
1301 // << Operands[0]->use_size() << " " << Operands[0]);
1305 } // End llvm namespace