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/Constants.h"
18 #include "llvm/iOther.h"
19 #include "llvm/iPHINode.h"
20 #include "llvm/iMemory.h"
22 #include "llvm/Analysis/Expressions.h"
23 #include "Support/STLExtras.h"
24 #include "Support/Debug.h"
29 static bool OperandConvertibleToType(User *U, Value *V, const Type *Ty,
30 ValueTypeCache &ConvertedTypes,
31 const TargetData &TD);
33 static void ConvertOperandToType(User *U, Value *OldVal, Value *NewVal,
34 ValueMapCache &VMC, const TargetData &TD);
36 // Peephole Malloc instructions: we take a look at the use chain of the
37 // malloc instruction, and try to find out if the following conditions hold:
38 // 1. The malloc is of the form: 'malloc [sbyte], uint <constant>'
39 // 2. The only users of the malloc are cast & add instructions
40 // 3. Of the cast instructions, there is only one destination pointer type
41 // [RTy] where the size of the pointed to object is equal to the number
42 // of bytes allocated.
44 // If these conditions hold, we convert the malloc to allocate an [RTy]
45 // element. TODO: This comment is out of date WRT arrays
47 static bool MallocConvertibleToType(MallocInst *MI, const Type *Ty,
48 ValueTypeCache &CTMap,
49 const TargetData &TD) {
50 if (!isa<PointerType>(Ty)) return false; // Malloc always returns pointers
52 // Deal with the type to allocate, not the pointer type...
53 Ty = cast<PointerType>(Ty)->getElementType();
54 if (!Ty->isSized()) return false; // Can only alloc something with a size
56 // Analyze the number of bytes allocated...
57 ExprType Expr = ClassifyExpr(MI->getArraySize());
59 // Get information about the base datatype being allocated, before & after
60 int ReqTypeSize = TD.getTypeSize(Ty);
61 if (ReqTypeSize == 0) return false;
62 unsigned OldTypeSize = TD.getTypeSize(MI->getType()->getElementType());
64 // Must have a scale or offset to analyze it...
65 if (!Expr.Offset && !Expr.Scale && OldTypeSize == 1) return false;
67 // Get the offset and scale of the allocation...
68 int64_t OffsetVal = Expr.Offset ? getConstantValue(Expr.Offset) : 0;
69 int64_t ScaleVal = Expr.Scale ? getConstantValue(Expr.Scale) :(Expr.Var != 0);
71 // The old type might not be of unit size, take old size into consideration
73 int64_t Offset = OffsetVal * OldTypeSize;
74 int64_t Scale = ScaleVal * OldTypeSize;
76 // In order to be successful, both the scale and the offset must be a multiple
77 // of the requested data type's size.
79 if (Offset/ReqTypeSize*ReqTypeSize != Offset ||
80 Scale/ReqTypeSize*ReqTypeSize != Scale)
81 return false; // Nope.
86 static Instruction *ConvertMallocToType(MallocInst *MI, const Type *Ty,
87 const std::string &Name,
89 const TargetData &TD){
90 BasicBlock *BB = MI->getParent();
91 BasicBlock::iterator It = BB->end();
93 // Analyze the number of bytes allocated...
94 ExprType Expr = ClassifyExpr(MI->getArraySize());
96 const PointerType *AllocTy = cast<PointerType>(Ty);
97 const Type *ElType = AllocTy->getElementType();
99 unsigned DataSize = TD.getTypeSize(ElType);
100 unsigned OldTypeSize = TD.getTypeSize(MI->getType()->getElementType());
102 // Get the offset and scale coefficients that we are allocating...
103 int64_t OffsetVal = (Expr.Offset ? getConstantValue(Expr.Offset) : 0);
104 int64_t ScaleVal = Expr.Scale ? getConstantValue(Expr.Scale) : (Expr.Var !=0);
106 // The old type might not be of unit size, take old size into consideration
108 unsigned Offset = (uint64_t)OffsetVal * OldTypeSize / DataSize;
109 unsigned Scale = (uint64_t)ScaleVal * OldTypeSize / DataSize;
111 // Locate the malloc instruction, because we may be inserting instructions
114 // If we have a scale, apply it first...
116 // Expr.Var is not necessarily unsigned right now, insert a cast now.
117 if (Expr.Var->getType() != Type::UIntTy)
118 Expr.Var = new CastInst(Expr.Var, Type::UIntTy,
119 Expr.Var->getName()+"-uint", It);
122 Expr.Var = BinaryOperator::create(Instruction::Mul, Expr.Var,
123 ConstantUInt::get(Type::UIntTy, Scale),
124 Expr.Var->getName()+"-scl", It);
127 // If we are not scaling anything, just make the offset be the "var"...
128 Expr.Var = ConstantUInt::get(Type::UIntTy, Offset);
129 Offset = 0; Scale = 1;
132 // If we have an offset now, add it in...
134 assert(Expr.Var && "Var must be nonnull by now!");
135 Expr.Var = BinaryOperator::create(Instruction::Add, Expr.Var,
136 ConstantUInt::get(Type::UIntTy, Offset),
137 Expr.Var->getName()+"-off", It);
140 assert(AllocTy == Ty);
141 return new MallocInst(AllocTy->getElementType(), Expr.Var, Name);
145 // ExpressionConvertibleToType - Return true if it is possible
146 bool llvm::ExpressionConvertibleToType(Value *V, const Type *Ty,
147 ValueTypeCache &CTMap, const TargetData &TD) {
148 // Expression type must be holdable in a register.
149 if (!Ty->isFirstClassType())
152 ValueTypeCache::iterator CTMI = CTMap.find(V);
153 if (CTMI != CTMap.end()) return CTMI->second == Ty;
155 // If it's a constant... all constants can be converted to a different
158 if (Constant *CPV = dyn_cast<Constant>(V))
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 // Be conservative if we find a giant PHI node.
211 if (PN->getNumIncomingValues() > 32) return false;
213 for (unsigned i = 0; i < PN->getNumIncomingValues(); ++i)
214 if (!ExpressionConvertibleToType(PN->getIncomingValue(i), Ty, CTMap, TD))
219 case Instruction::Malloc:
220 if (!MallocConvertibleToType(cast<MallocInst>(I), Ty, CTMap, TD))
224 case Instruction::GetElementPtr: {
225 // GetElementPtr's are directly convertible to a pointer type if they have
226 // a number of zeros at the end. Because removing these values does not
227 // change the logical offset of the GEP, it is okay and fair to remove them.
228 // This can change this:
229 // %t1 = getelementptr %Hosp * %hosp, ubyte 4, ubyte 0 ; <%List **>
230 // %t2 = cast %List * * %t1 to %List *
232 // %t2 = getelementptr %Hosp * %hosp, ubyte 4 ; <%List *>
234 GetElementPtrInst *GEP = cast<GetElementPtrInst>(I);
235 const PointerType *PTy = dyn_cast<PointerType>(Ty);
236 if (!PTy) return false; // GEP must always return a pointer...
237 const Type *PVTy = PTy->getElementType();
239 // Check to see if there are zero elements that we can remove from the
240 // index array. If there are, check to see if removing them causes us to
241 // get to the right type...
243 std::vector<Value*> Indices(GEP->idx_begin(), GEP->idx_end());
244 const Type *BaseType = GEP->getPointerOperand()->getType();
245 const Type *ElTy = 0;
247 while (!Indices.empty() &&
248 Indices.back() == Constant::getNullValue(Indices.back()->getType())){
250 ElTy = GetElementPtrInst::getIndexedType(BaseType, Indices, true);
252 break; // Found a match!!
256 if (ElTy) break; // Found a number of zeros we can strip off!
258 // Otherwise, we can convert a GEP from one form to the other iff the
259 // current gep is of the form 'getelementptr sbyte*, long N
260 // and we could convert this to an appropriate GEP for the new type.
262 if (GEP->getNumOperands() == 2 &&
263 GEP->getType() == PointerType::get(Type::SByteTy)) {
265 // Do not Check to see if our incoming pointer can be converted
266 // to be a ptr to an array of the right type... because in more cases than
267 // not, it is simply not analyzable because of pointer/array
268 // discrepancies. To fix this, we will insert a cast before the GEP.
271 // Check to see if 'N' is an expression that can be converted to
272 // the appropriate size... if so, allow it.
274 std::vector<Value*> Indices;
275 const Type *ElTy = ConvertibleToGEP(PTy, I->getOperand(1), Indices, TD);
277 if (!ExpressionConvertibleToType(I->getOperand(0),
278 PointerType::get(ElTy), CTMap, TD))
279 return false; // Can't continue, ExConToTy might have polluted set!
284 // Otherwise, it could be that we have something like this:
285 // getelementptr [[sbyte] *] * %reg115, long %reg138 ; [sbyte]**
286 // and want to convert it into something like this:
287 // getelemenptr [[int] *] * %reg115, long %reg138 ; [int]**
289 if (GEP->getNumOperands() == 2 &&
290 PTy->getElementType()->isSized() &&
291 TD.getTypeSize(PTy->getElementType()) ==
292 TD.getTypeSize(GEP->getType()->getElementType())) {
293 const PointerType *NewSrcTy = PointerType::get(PVTy);
294 if (!ExpressionConvertibleToType(I->getOperand(0), NewSrcTy, CTMap, TD))
299 return false; // No match, maybe next time.
302 case Instruction::Call: {
303 if (isa<Function>(I->getOperand(0)))
304 return false; // Don't even try to change direct calls.
306 // If this is a function pointer, we can convert the return type if we can
307 // convert the source function pointer.
309 const PointerType *PT = cast<PointerType>(I->getOperand(0)->getType());
310 const FunctionType *FT = cast<FunctionType>(PT->getElementType());
311 std::vector<const Type *> ArgTys(FT->param_begin(), FT->param_end());
312 const FunctionType *NewTy =
313 FunctionType::get(Ty, ArgTys, FT->isVarArg());
314 if (!ExpressionConvertibleToType(I->getOperand(0),
315 PointerType::get(NewTy), CTMap, TD))
323 // Expressions are only convertible if all of the users of the expression can
324 // have this value converted. This makes use of the map to avoid infinite
327 for (Value::use_iterator It = I->use_begin(), E = I->use_end(); It != E; ++It)
328 if (!OperandConvertibleToType(*It, I, Ty, CTMap, TD))
335 Value *llvm::ConvertExpressionToType(Value *V, const Type *Ty,
336 ValueMapCache &VMC, const TargetData &TD) {
337 if (V->getType() == Ty) return V; // Already where we need to be?
339 ValueMapCache::ExprMapTy::iterator VMCI = VMC.ExprMap.find(V);
340 if (VMCI != VMC.ExprMap.end()) {
341 const Value *GV = VMCI->second;
342 const Type *GTy = VMCI->second->getType();
343 assert(VMCI->second->getType() == Ty);
345 if (Instruction *I = dyn_cast<Instruction>(V))
346 ValueHandle IHandle(VMC, I); // Remove I if it is unused now!
351 DEBUG(std::cerr << "CETT: " << (void*)V << " " << V);
353 Instruction *I = dyn_cast<Instruction>(V);
355 Constant *CPV = cast<Constant>(V);
356 // Constants are converted by constant folding the cast that is required.
357 // We assume here that all casts are implemented for constant prop.
358 Value *Result = ConstantExpr::getCast(CPV, Ty);
359 // Add the instruction to the expression map
360 //VMC.ExprMap[V] = Result;
365 BasicBlock *BB = I->getParent();
366 std::string Name = I->getName(); if (!Name.empty()) I->setName("");
367 Instruction *Res; // Result of conversion
369 ValueHandle IHandle(VMC, I); // Prevent I from being removed!
371 Constant *Dummy = Constant::getNullValue(Ty);
373 switch (I->getOpcode()) {
374 case Instruction::Cast:
375 assert(VMC.NewCasts.count(ValueHandle(VMC, I)) == 0);
376 Res = new CastInst(I->getOperand(0), Ty, Name);
377 VMC.NewCasts.insert(ValueHandle(VMC, Res));
380 case Instruction::Add:
381 case Instruction::Sub:
382 Res = BinaryOperator::create(cast<BinaryOperator>(I)->getOpcode(),
384 VMC.ExprMap[I] = Res; // Add node to expression eagerly
386 Res->setOperand(0, ConvertExpressionToType(I->getOperand(0), Ty, VMC, TD));
387 Res->setOperand(1, ConvertExpressionToType(I->getOperand(1), Ty, VMC, TD));
390 case Instruction::Shl:
391 case Instruction::Shr:
392 Res = new ShiftInst(cast<ShiftInst>(I)->getOpcode(), Dummy,
393 I->getOperand(1), Name);
394 VMC.ExprMap[I] = Res;
395 Res->setOperand(0, ConvertExpressionToType(I->getOperand(0), Ty, VMC, TD));
398 case Instruction::Load: {
399 LoadInst *LI = cast<LoadInst>(I);
401 Res = new LoadInst(Constant::getNullValue(PointerType::get(Ty)), Name);
402 VMC.ExprMap[I] = Res;
403 Res->setOperand(0, ConvertExpressionToType(LI->getPointerOperand(),
404 PointerType::get(Ty), VMC, TD));
405 assert(Res->getOperand(0)->getType() == PointerType::get(Ty));
406 assert(Ty == Res->getType());
407 assert(Res->getType()->isFirstClassType() && "Load of structure or array!");
411 case Instruction::PHI: {
412 PHINode *OldPN = cast<PHINode>(I);
413 PHINode *NewPN = new PHINode(Ty, Name);
415 VMC.ExprMap[I] = NewPN; // Add node to expression eagerly
416 while (OldPN->getNumOperands()) {
417 BasicBlock *BB = OldPN->getIncomingBlock(0);
418 Value *OldVal = OldPN->getIncomingValue(0);
419 ValueHandle OldValHandle(VMC, OldVal);
420 OldPN->removeIncomingValue(BB, false);
421 Value *V = ConvertExpressionToType(OldVal, Ty, VMC, TD);
422 NewPN->addIncoming(V, BB);
428 case Instruction::Malloc: {
429 Res = ConvertMallocToType(cast<MallocInst>(I), Ty, Name, VMC, TD);
433 case Instruction::GetElementPtr: {
434 // GetElementPtr's are directly convertible to a pointer type if they have
435 // a number of zeros at the end. Because removing these values does not
436 // change the logical offset of the GEP, it is okay and fair to remove them.
437 // This can change this:
438 // %t1 = getelementptr %Hosp * %hosp, ubyte 4, ubyte 0 ; <%List **>
439 // %t2 = cast %List * * %t1 to %List *
441 // %t2 = getelementptr %Hosp * %hosp, ubyte 4 ; <%List *>
443 GetElementPtrInst *GEP = cast<GetElementPtrInst>(I);
445 // Check to see if there are zero elements that we can remove from the
446 // index array. If there are, check to see if removing them causes us to
447 // get to the right type...
449 std::vector<Value*> Indices(GEP->idx_begin(), GEP->idx_end());
450 const Type *BaseType = GEP->getPointerOperand()->getType();
451 const Type *PVTy = cast<PointerType>(Ty)->getElementType();
453 while (!Indices.empty() &&
454 Indices.back() == Constant::getNullValue(Indices.back()->getType())){
456 if (GetElementPtrInst::getIndexedType(BaseType, Indices, true) == PVTy) {
457 if (Indices.size() == 0)
458 Res = new CastInst(GEP->getPointerOperand(), BaseType); // NOOP CAST
460 Res = new GetElementPtrInst(GEP->getPointerOperand(), Indices, Name);
465 if (Res == 0 && GEP->getNumOperands() == 2 &&
466 GEP->getType() == PointerType::get(Type::SByteTy)) {
468 // Otherwise, we can convert a GEP from one form to the other iff the
469 // current gep is of the form 'getelementptr sbyte*, unsigned N
470 // and we could convert this to an appropriate GEP for the new type.
472 const PointerType *NewSrcTy = PointerType::get(PVTy);
473 BasicBlock::iterator It = I;
475 // Check to see if 'N' is an expression that can be converted to
476 // the appropriate size... if so, allow it.
478 std::vector<Value*> Indices;
479 const Type *ElTy = ConvertibleToGEP(NewSrcTy, I->getOperand(1),
482 assert(ElTy == PVTy && "Internal error, setup wrong!");
483 Res = new GetElementPtrInst(Constant::getNullValue(NewSrcTy),
485 VMC.ExprMap[I] = Res;
486 Res->setOperand(0, ConvertExpressionToType(I->getOperand(0),
491 // Otherwise, it could be that we have something like this:
492 // getelementptr [[sbyte] *] * %reg115, uint %reg138 ; [sbyte]**
493 // and want to convert it into something like this:
494 // getelemenptr [[int] *] * %reg115, uint %reg138 ; [int]**
497 const PointerType *NewSrcTy = PointerType::get(PVTy);
498 std::vector<Value*> Indices(GEP->idx_begin(), GEP->idx_end());
499 Res = new GetElementPtrInst(Constant::getNullValue(NewSrcTy),
501 VMC.ExprMap[I] = Res;
502 Res->setOperand(0, ConvertExpressionToType(I->getOperand(0),
507 assert(Res && "Didn't find match!");
511 case Instruction::Call: {
512 assert(!isa<Function>(I->getOperand(0)));
514 // If this is a function pointer, we can convert the return type if we can
515 // convert the source function pointer.
517 const PointerType *PT = cast<PointerType>(I->getOperand(0)->getType());
518 const FunctionType *FT = cast<FunctionType>(PT->getElementType());
519 std::vector<const Type *> ArgTys(FT->param_begin(), FT->param_end());
520 const FunctionType *NewTy =
521 FunctionType::get(Ty, ArgTys, FT->isVarArg());
522 const PointerType *NewPTy = PointerType::get(NewTy);
523 if (Ty == Type::VoidTy)
524 Name = ""; // Make sure not to name calls that now return void!
526 Res = new CallInst(Constant::getNullValue(NewPTy),
527 std::vector<Value*>(I->op_begin()+1, I->op_end()),
529 VMC.ExprMap[I] = Res;
530 Res->setOperand(0, ConvertExpressionToType(I->getOperand(0),NewPTy,VMC,TD));
534 assert(0 && "Expression convertible, but don't know how to convert?");
538 assert(Res->getType() == Ty && "Didn't convert expr to correct type!");
540 BB->getInstList().insert(I, Res);
542 // Add the instruction to the expression map
543 VMC.ExprMap[I] = Res;
546 unsigned NumUses = I->use_size();
547 for (unsigned It = 0; It < NumUses; ) {
548 unsigned OldSize = NumUses;
549 Value::use_iterator UI = I->use_begin();
550 std::advance(UI, It);
551 ConvertOperandToType(*UI, I, Res, VMC, TD);
552 NumUses = I->use_size();
553 if (NumUses == OldSize) ++It;
556 DEBUG(std::cerr << "ExpIn: " << (void*)I << " " << I
557 << "ExpOut: " << (void*)Res << " " << Res);
564 // ValueConvertibleToType - Return true if it is possible
565 bool llvm::ValueConvertibleToType(Value *V, const Type *Ty,
566 ValueTypeCache &ConvertedTypes,
567 const TargetData &TD) {
568 ValueTypeCache::iterator I = ConvertedTypes.find(V);
569 if (I != ConvertedTypes.end()) return I->second == Ty;
570 ConvertedTypes[V] = Ty;
572 // It is safe to convert the specified value to the specified type IFF all of
573 // the uses of the value can be converted to accept the new typed value.
575 if (V->getType() != Ty) {
576 for (Value::use_iterator I = V->use_begin(), E = V->use_end(); I != E; ++I)
577 if (!OperandConvertibleToType(*I, V, Ty, ConvertedTypes, TD))
588 // OperandConvertibleToType - Return true if it is possible to convert operand
589 // V of User (instruction) U to the specified type. This is true iff it is
590 // possible to change the specified instruction to accept this. CTMap is a map
591 // of converted types, so that circular definitions will see the future type of
592 // the expression, not the static current type.
594 static bool OperandConvertibleToType(User *U, Value *V, const Type *Ty,
595 ValueTypeCache &CTMap,
596 const TargetData &TD) {
597 // if (V->getType() == Ty) return true; // Operand already the right type?
599 // Expression type must be holdable in a register.
600 if (!Ty->isFirstClassType())
603 Instruction *I = dyn_cast<Instruction>(U);
604 if (I == 0) return false; // We can't convert!
606 switch (I->getOpcode()) {
607 case Instruction::Cast:
608 assert(I->getOperand(0) == V);
609 // We can convert the expr if the cast destination type is losslessly
610 // convertible to the requested type.
611 // Also, do not change a cast that is a noop cast. For all intents and
612 // purposes it should be eliminated.
613 if (!Ty->isLosslesslyConvertibleTo(I->getOperand(0)->getType()) ||
614 I->getType() == I->getOperand(0)->getType())
617 // Do not allow a 'cast ushort %V to uint' to have it's first operand be
618 // converted to a 'short' type. Doing so changes the way sign promotion
619 // happens, and breaks things. Only allow the cast to take place if the
620 // signedness doesn't change... or if the current cast is not a lossy
623 if (!I->getType()->isLosslesslyConvertibleTo(I->getOperand(0)->getType()) &&
624 I->getOperand(0)->getType()->isSigned() != Ty->isSigned())
627 // We also do not allow conversion of a cast that casts from a ptr to array
628 // of X to a *X. For example: cast [4 x %List *] * %val to %List * *
630 if (const PointerType *SPT =
631 dyn_cast<PointerType>(I->getOperand(0)->getType()))
632 if (const PointerType *DPT = dyn_cast<PointerType>(I->getType()))
633 if (const ArrayType *AT = dyn_cast<ArrayType>(SPT->getElementType()))
634 if (AT->getElementType() == DPT->getElementType())
638 case Instruction::Add:
639 if (isa<PointerType>(Ty)) {
640 Value *IndexVal = I->getOperand(V == I->getOperand(0) ? 1 : 0);
641 std::vector<Value*> Indices;
642 if (const Type *ETy = ConvertibleToGEP(Ty, IndexVal, Indices, TD)) {
643 const Type *RetTy = PointerType::get(ETy);
645 // Only successful if we can convert this type to the required type
646 if (ValueConvertibleToType(I, RetTy, CTMap, TD)) {
650 // We have to return failure here because ValueConvertibleToType could
651 // have polluted our map
656 case Instruction::Sub: {
657 if (!Ty->isInteger() && !Ty->isFloatingPoint()) return false;
659 Value *OtherOp = I->getOperand((V == I->getOperand(0)) ? 1 : 0);
660 return ValueConvertibleToType(I, Ty, CTMap, TD) &&
661 ExpressionConvertibleToType(OtherOp, Ty, CTMap, TD);
663 case Instruction::SetEQ:
664 case Instruction::SetNE: {
665 Value *OtherOp = I->getOperand((V == I->getOperand(0)) ? 1 : 0);
666 return ExpressionConvertibleToType(OtherOp, Ty, CTMap, TD);
668 case Instruction::Shr:
669 if (Ty->isSigned() != V->getType()->isSigned()) return false;
671 case Instruction::Shl:
672 if (I->getOperand(1) == V) return false; // Cannot change shift amount type
673 if (!Ty->isInteger()) return false;
674 return ValueConvertibleToType(I, Ty, CTMap, TD);
676 case Instruction::Free:
677 assert(I->getOperand(0) == V);
678 return isa<PointerType>(Ty); // Free can free any pointer type!
680 case Instruction::Load:
681 // Cannot convert the types of any subscripts...
682 if (I->getOperand(0) != V) return false;
684 if (const PointerType *PT = dyn_cast<PointerType>(Ty)) {
685 LoadInst *LI = cast<LoadInst>(I);
687 const Type *LoadedTy = PT->getElementType();
689 // They could be loading the first element of a composite type...
690 if (const CompositeType *CT = dyn_cast<CompositeType>(LoadedTy)) {
691 unsigned Offset = 0; // No offset, get first leaf.
692 std::vector<Value*> Indices; // Discarded...
693 LoadedTy = getStructOffsetType(CT, Offset, Indices, TD, false);
694 assert(Offset == 0 && "Offset changed from zero???");
697 if (!LoadedTy->isFirstClassType())
700 if (TD.getTypeSize(LoadedTy) != TD.getTypeSize(LI->getType()))
703 return ValueConvertibleToType(LI, LoadedTy, CTMap, TD);
707 case Instruction::Store: {
708 StoreInst *SI = cast<StoreInst>(I);
710 if (V == I->getOperand(0)) {
711 ValueTypeCache::iterator CTMI = CTMap.find(I->getOperand(1));
712 if (CTMI != CTMap.end()) { // Operand #1 is in the table already?
713 // If so, check to see if it's Ty*, or, more importantly, if it is a
714 // pointer to a structure where the first element is a Ty... this code
715 // is necessary because we might be trying to change the source and
716 // destination type of the store (they might be related) and the dest
717 // pointer type might be a pointer to structure. Below we allow pointer
718 // to structures where the 0th element is compatible with the value,
719 // now we have to support the symmetrical part of this.
721 const Type *ElTy = cast<PointerType>(CTMI->second)->getElementType();
723 // Already a pointer to what we want? Trivially accept...
724 if (ElTy == Ty) return true;
726 // Tricky case now, if the destination is a pointer to structure,
727 // obviously the source is not allowed to be a structure (cannot copy
728 // a whole structure at a time), so the level raiser must be trying to
729 // store into the first field. Check for this and allow it now:
731 if (const StructType *SElTy = dyn_cast<StructType>(ElTy)) {
733 std::vector<Value*> Indices;
734 ElTy = getStructOffsetType(ElTy, Offset, Indices, TD, false);
735 assert(Offset == 0 && "Offset changed!");
736 if (ElTy == 0) // Element at offset zero in struct doesn't exist!
737 return false; // Can only happen for {}*
739 if (ElTy == Ty) // Looks like the 0th element of structure is
740 return true; // compatible! Accept now!
742 // Otherwise we know that we can't work, so just stop trying now.
747 // Can convert the store if we can convert the pointer operand to match
748 // the new value type...
749 return ExpressionConvertibleToType(I->getOperand(1), PointerType::get(Ty),
751 } else if (const PointerType *PT = dyn_cast<PointerType>(Ty)) {
752 const Type *ElTy = PT->getElementType();
753 assert(V == I->getOperand(1));
755 if (isa<StructType>(ElTy)) {
756 // We can change the destination pointer if we can store our first
757 // argument into the first element of the structure...
760 std::vector<Value*> Indices;
761 ElTy = getStructOffsetType(ElTy, Offset, Indices, TD, false);
762 assert(Offset == 0 && "Offset changed!");
763 if (ElTy == 0) // Element at offset zero in struct doesn't exist!
764 return false; // Can only happen for {}*
767 // Must move the same amount of data...
768 if (!ElTy->isSized() ||
769 TD.getTypeSize(ElTy) != TD.getTypeSize(I->getOperand(0)->getType()))
772 // Can convert store if the incoming value is convertible and if the
773 // result will preserve semantics...
774 const Type *Op0Ty = I->getOperand(0)->getType();
775 if (!(Op0Ty->isIntegral() ^ ElTy->isIntegral()) &&
776 !(Op0Ty->isFloatingPoint() ^ ElTy->isFloatingPoint()))
777 return ExpressionConvertibleToType(I->getOperand(0), ElTy, CTMap, TD);
782 case Instruction::GetElementPtr:
783 if (V != I->getOperand(0) || !isa<PointerType>(Ty)) return false;
785 // If we have a two operand form of getelementptr, this is really little
786 // more than a simple addition. As with addition, check to see if the
787 // getelementptr instruction can be changed to index into the new type.
789 if (I->getNumOperands() == 2) {
790 const Type *OldElTy = cast<PointerType>(I->getType())->getElementType();
791 unsigned DataSize = TD.getTypeSize(OldElTy);
792 Value *Index = I->getOperand(1);
793 Instruction *TempScale = 0;
795 // If the old data element is not unit sized, we have to create a scale
796 // instruction so that ConvertibleToGEP will know the REAL amount we are
797 // indexing by. Note that this is never inserted into the instruction
798 // stream, so we have to delete it when we're done.
802 if (Index->getType()->isSigned())
803 CST = ConstantSInt::get(Index->getType(), DataSize);
805 CST = ConstantUInt::get(Index->getType(), DataSize);
807 TempScale = BinaryOperator::create(Instruction::Mul, Index, CST);
811 // Check to see if the second argument is an expression that can
812 // be converted to the appropriate size... if so, allow it.
814 std::vector<Value*> Indices;
815 const Type *ElTy = ConvertibleToGEP(Ty, Index, Indices, TD);
816 delete TempScale; // Free our temporary multiply if we made it
818 if (ElTy == 0) return false; // Cannot make conversion...
819 return ValueConvertibleToType(I, PointerType::get(ElTy), CTMap, TD);
823 case Instruction::PHI: {
824 PHINode *PN = cast<PHINode>(I);
825 // Be conservative if we find a giant PHI node.
826 if (PN->getNumIncomingValues() > 32) return false;
828 for (unsigned i = 0; i < PN->getNumIncomingValues(); ++i)
829 if (!ExpressionConvertibleToType(PN->getIncomingValue(i), Ty, CTMap, TD))
831 return ValueConvertibleToType(PN, Ty, CTMap, TD);
834 case Instruction::Call: {
835 User::op_iterator OI = find(I->op_begin(), I->op_end(), V);
836 assert (OI != I->op_end() && "Not using value!");
837 unsigned OpNum = OI - I->op_begin();
839 // Are we trying to change the function pointer value to a new type?
841 const PointerType *PTy = dyn_cast<PointerType>(Ty);
842 if (PTy == 0) return false; // Can't convert to a non-pointer type...
843 const FunctionType *FTy = dyn_cast<FunctionType>(PTy->getElementType());
844 if (FTy == 0) return false; // Can't convert to a non ptr to function...
846 // Do not allow converting to a call where all of the operands are ...'s
847 if (FTy->getNumParams() == 0 && FTy->isVarArg())
848 return false; // Do not permit this conversion!
850 // Perform sanity checks to make sure that new function type has the
851 // correct number of arguments...
853 unsigned NumArgs = I->getNumOperands()-1; // Don't include function ptr
855 // Cannot convert to a type that requires more fixed arguments than
856 // the call provides...
858 if (NumArgs < FTy->getNumParams()) return false;
860 // Unless this is a vararg function type, we cannot provide more arguments
861 // than are desired...
863 if (!FTy->isVarArg() && NumArgs > FTy->getNumParams())
866 // Okay, at this point, we know that the call and the function type match
867 // number of arguments. Now we see if we can convert the arguments
868 // themselves. Note that we do not require operands to be convertible,
869 // we can insert casts if they are convertible but not compatible. The
870 // reason for this is that we prefer to have resolved functions but casted
871 // arguments if possible.
873 for (unsigned i = 0, NA = FTy->getNumParams(); i < NA; ++i)
874 if (!FTy->getParamType(i)->isLosslesslyConvertibleTo(I->getOperand(i+1)->getType()))
875 return false; // Operands must have compatible types!
877 // Okay, at this point, we know that all of the arguments can be
878 // converted. We succeed if we can change the return type if
881 return ValueConvertibleToType(I, FTy->getReturnType(), CTMap, TD);
884 const PointerType *MPtr = cast<PointerType>(I->getOperand(0)->getType());
885 const FunctionType *FTy = cast<FunctionType>(MPtr->getElementType());
886 if (!FTy->isVarArg()) return false;
888 if ((OpNum-1) < FTy->getNumParams())
889 return false; // It's not in the varargs section...
891 // If we get this far, we know the value is in the varargs section of the
892 // function! We can convert if we don't reinterpret the value...
894 return Ty->isLosslesslyConvertibleTo(V->getType());
901 void llvm::ConvertValueToNewType(Value *V, Value *NewVal, ValueMapCache &VMC,
902 const TargetData &TD) {
903 ValueHandle VH(VMC, V);
905 unsigned NumUses = V->use_size();
906 for (unsigned It = 0; It < NumUses; ) {
907 unsigned OldSize = NumUses;
908 Value::use_iterator UI = V->use_begin();
909 std::advance(UI, It);
910 ConvertOperandToType(*UI, V, NewVal, VMC, TD);
911 NumUses = V->use_size();
912 if (NumUses == OldSize) ++It;
918 static void ConvertOperandToType(User *U, Value *OldVal, Value *NewVal,
919 ValueMapCache &VMC, const TargetData &TD) {
920 if (isa<ValueHandle>(U)) return; // Valuehandles don't let go of operands...
922 if (VMC.OperandsMapped.count(U)) return;
923 VMC.OperandsMapped.insert(U);
925 ValueMapCache::ExprMapTy::iterator VMCI = VMC.ExprMap.find(U);
926 if (VMCI != VMC.ExprMap.end())
930 Instruction *I = cast<Instruction>(U); // Only Instructions convertible
932 BasicBlock *BB = I->getParent();
933 assert(BB != 0 && "Instruction not embedded in basic block!");
934 std::string Name = I->getName();
936 Instruction *Res; // Result of conversion
938 //std::cerr << endl << endl << "Type:\t" << Ty << "\nInst: " << I
939 // << "BB Before: " << BB << endl;
941 // Prevent I from being removed...
942 ValueHandle IHandle(VMC, I);
944 const Type *NewTy = NewVal->getType();
945 Constant *Dummy = (NewTy != Type::VoidTy) ?
946 Constant::getNullValue(NewTy) : 0;
948 switch (I->getOpcode()) {
949 case Instruction::Cast:
950 if (VMC.NewCasts.count(ValueHandle(VMC, I))) {
951 // This cast has already had it's value converted, causing a new cast to
952 // be created. We don't want to create YET ANOTHER cast instruction
953 // representing the original one, so just modify the operand of this cast
954 // instruction, which we know is newly created.
955 I->setOperand(0, NewVal);
956 I->setName(Name); // give I its name back
960 Res = new CastInst(NewVal, I->getType(), Name);
964 case Instruction::Add:
965 if (isa<PointerType>(NewTy)) {
966 Value *IndexVal = I->getOperand(OldVal == I->getOperand(0) ? 1 : 0);
967 std::vector<Value*> Indices;
968 BasicBlock::iterator It = I;
970 if (const Type *ETy = ConvertibleToGEP(NewTy, IndexVal, Indices, TD,&It)){
971 // If successful, convert the add to a GEP
972 //const Type *RetTy = PointerType::get(ETy);
973 // First operand is actually the given pointer...
974 Res = new GetElementPtrInst(NewVal, Indices, Name);
975 assert(cast<PointerType>(Res->getType())->getElementType() == ETy &&
976 "ConvertibleToGEP broken!");
982 case Instruction::Sub:
983 case Instruction::SetEQ:
984 case Instruction::SetNE: {
985 Res = BinaryOperator::create(cast<BinaryOperator>(I)->getOpcode(),
987 VMC.ExprMap[I] = Res; // Add node to expression eagerly
989 unsigned OtherIdx = (OldVal == I->getOperand(0)) ? 1 : 0;
990 Value *OtherOp = I->getOperand(OtherIdx);
991 Value *NewOther = ConvertExpressionToType(OtherOp, NewTy, VMC, TD);
993 Res->setOperand(OtherIdx, NewOther);
994 Res->setOperand(!OtherIdx, NewVal);
997 case Instruction::Shl:
998 case Instruction::Shr:
999 assert(I->getOperand(0) == OldVal);
1000 Res = new ShiftInst(cast<ShiftInst>(I)->getOpcode(), NewVal,
1001 I->getOperand(1), Name);
1004 case Instruction::Free: // Free can free any pointer type!
1005 assert(I->getOperand(0) == OldVal);
1006 Res = new FreeInst(NewVal);
1010 case Instruction::Load: {
1011 assert(I->getOperand(0) == OldVal && isa<PointerType>(NewVal->getType()));
1012 const Type *LoadedTy =
1013 cast<PointerType>(NewVal->getType())->getElementType();
1015 Value *Src = NewVal;
1017 if (const CompositeType *CT = dyn_cast<CompositeType>(LoadedTy)) {
1018 std::vector<Value*> Indices;
1019 Indices.push_back(Constant::getNullValue(Type::UIntTy));
1021 unsigned Offset = 0; // No offset, get first leaf.
1022 LoadedTy = getStructOffsetType(CT, Offset, Indices, TD, false);
1023 assert(LoadedTy->isFirstClassType());
1025 if (Indices.size() != 1) { // Do not generate load X, 0
1026 // Insert the GEP instruction before this load.
1027 Src = new GetElementPtrInst(Src, Indices, Name+".idx", I);
1031 Res = new LoadInst(Src, Name);
1032 assert(Res->getType()->isFirstClassType() && "Load of structure or array!");
1036 case Instruction::Store: {
1037 if (I->getOperand(0) == OldVal) { // Replace the source value
1038 // Check to see if operand #1 has already been converted...
1039 ValueMapCache::ExprMapTy::iterator VMCI =
1040 VMC.ExprMap.find(I->getOperand(1));
1041 if (VMCI != VMC.ExprMap.end()) {
1042 // Comments describing this stuff are in the OperandConvertibleToType
1043 // switch statement for Store...
1046 cast<PointerType>(VMCI->second->getType())->getElementType();
1048 Value *SrcPtr = VMCI->second;
1050 if (ElTy != NewTy) {
1051 // We check that this is a struct in the initial scan...
1052 const StructType *SElTy = cast<StructType>(ElTy);
1054 std::vector<Value*> Indices;
1055 Indices.push_back(Constant::getNullValue(Type::UIntTy));
1057 unsigned Offset = 0;
1058 const Type *Ty = getStructOffsetType(ElTy, Offset, Indices, TD,false);
1059 assert(Offset == 0 && "Offset changed!");
1060 assert(NewTy == Ty && "Did not convert to correct type!");
1062 // Insert the GEP instruction before this store.
1063 SrcPtr = new GetElementPtrInst(SrcPtr, Indices,
1064 SrcPtr->getName()+".idx", I);
1066 Res = new StoreInst(NewVal, SrcPtr);
1068 VMC.ExprMap[I] = Res;
1070 // Otherwise, we haven't converted Operand #1 over yet...
1071 const PointerType *NewPT = PointerType::get(NewTy);
1072 Res = new StoreInst(NewVal, Constant::getNullValue(NewPT));
1073 VMC.ExprMap[I] = Res;
1074 Res->setOperand(1, ConvertExpressionToType(I->getOperand(1),
1077 } else { // Replace the source pointer
1078 const Type *ValTy = cast<PointerType>(NewTy)->getElementType();
1080 Value *SrcPtr = NewVal;
1082 if (isa<StructType>(ValTy)) {
1083 std::vector<Value*> Indices;
1084 Indices.push_back(Constant::getNullValue(Type::UIntTy));
1086 unsigned Offset = 0;
1087 ValTy = getStructOffsetType(ValTy, Offset, Indices, TD, false);
1089 assert(Offset == 0 && ValTy);
1091 // Insert the GEP instruction before this store.
1092 SrcPtr = new GetElementPtrInst(SrcPtr, Indices,
1093 SrcPtr->getName()+".idx", I);
1096 Res = new StoreInst(Constant::getNullValue(ValTy), SrcPtr);
1097 VMC.ExprMap[I] = Res;
1098 Res->setOperand(0, ConvertExpressionToType(I->getOperand(0),
1105 case Instruction::GetElementPtr: {
1106 // Convert a one index getelementptr into just about anything that is
1109 BasicBlock::iterator It = I;
1110 const Type *OldElTy = cast<PointerType>(I->getType())->getElementType();
1111 unsigned DataSize = TD.getTypeSize(OldElTy);
1112 Value *Index = I->getOperand(1);
1114 if (DataSize != 1) {
1115 // Insert a multiply of the old element type is not a unit size...
1117 if (Index->getType()->isSigned())
1118 CST = ConstantSInt::get(Index->getType(), DataSize);
1120 CST = ConstantUInt::get(Index->getType(), DataSize);
1122 Index = BinaryOperator::create(Instruction::Mul, Index, CST, "scale", It);
1125 // Perform the conversion now...
1127 std::vector<Value*> Indices;
1128 const Type *ElTy = ConvertibleToGEP(NewVal->getType(),Index,Indices,TD,&It);
1129 assert(ElTy != 0 && "GEP Conversion Failure!");
1130 Res = new GetElementPtrInst(NewVal, Indices, Name);
1131 assert(Res->getType() == PointerType::get(ElTy) &&
1132 "ConvertibleToGet failed!");
1135 if (I->getType() == PointerType::get(Type::SByteTy)) {
1136 // Convert a getelementptr sbyte * %reg111, uint 16 freely back to
1137 // anything that is a pointer type...
1139 BasicBlock::iterator It = I;
1141 // Check to see if the second argument is an expression that can
1142 // be converted to the appropriate size... if so, allow it.
1144 std::vector<Value*> Indices;
1145 const Type *ElTy = ConvertibleToGEP(NewVal->getType(), I->getOperand(1),
1147 assert(ElTy != 0 && "GEP Conversion Failure!");
1149 Res = new GetElementPtrInst(NewVal, Indices, Name);
1151 // Convert a getelementptr ulong * %reg123, uint %N
1152 // to getelementptr long * %reg123, uint %N
1153 // ... where the type must simply stay the same size...
1155 GetElementPtrInst *GEP = cast<GetElementPtrInst>(I);
1156 std::vector<Value*> Indices(GEP->idx_begin(), GEP->idx_end());
1157 Res = new GetElementPtrInst(NewVal, Indices, Name);
1162 case Instruction::PHI: {
1163 PHINode *OldPN = cast<PHINode>(I);
1164 PHINode *NewPN = new PHINode(NewTy, Name);
1165 VMC.ExprMap[I] = NewPN;
1167 while (OldPN->getNumOperands()) {
1168 BasicBlock *BB = OldPN->getIncomingBlock(0);
1169 Value *OldVal = OldPN->getIncomingValue(0);
1170 ValueHandle OldValHandle(VMC, OldVal);
1171 OldPN->removeIncomingValue(BB, false);
1172 Value *V = ConvertExpressionToType(OldVal, NewTy, VMC, TD);
1173 NewPN->addIncoming(V, BB);
1179 case Instruction::Call: {
1180 Value *Meth = I->getOperand(0);
1181 std::vector<Value*> Params(I->op_begin()+1, I->op_end());
1183 if (Meth == OldVal) { // Changing the function pointer?
1184 const PointerType *NewPTy = cast<PointerType>(NewVal->getType());
1185 const FunctionType *NewTy = cast<FunctionType>(NewPTy->getElementType());
1187 if (NewTy->getReturnType() == Type::VoidTy)
1188 Name = ""; // Make sure not to name a void call!
1190 // Get an iterator to the call instruction so that we can insert casts for
1191 // operands if need be. Note that we do not require operands to be
1192 // convertible, we can insert casts if they are convertible but not
1193 // compatible. The reason for this is that we prefer to have resolved
1194 // functions but casted arguments if possible.
1196 BasicBlock::iterator It = I;
1198 // Convert over all of the call operands to their new types... but only
1199 // convert over the part that is not in the vararg section of the call.
1201 for (unsigned i = 0; i != NewTy->getNumParams(); ++i)
1202 if (Params[i]->getType() != NewTy->getParamType(i)) {
1203 // Create a cast to convert it to the right type, we know that this
1204 // is a lossless cast...
1206 Params[i] = new CastInst(Params[i], NewTy->getParamType(i),
1208 Params[i]->getName(), It);
1210 Meth = NewVal; // Update call destination to new value
1212 } else { // Changing an argument, must be in vararg area
1213 std::vector<Value*>::iterator OI =
1214 find(Params.begin(), Params.end(), OldVal);
1215 assert (OI != Params.end() && "Not using value!");
1220 Res = new CallInst(Meth, Params, Name);
1224 assert(0 && "Expression convertible, but don't know how to convert?");
1228 // If the instruction was newly created, insert it into the instruction
1231 BasicBlock::iterator It = I;
1232 assert(It != BB->end() && "Instruction not in own basic block??");
1233 BB->getInstList().insert(It, Res); // Keep It pointing to old instruction
1235 DEBUG(std::cerr << "COT CREATED: " << (void*)Res << " " << Res
1236 << "In: " << (void*)I << " " << I << "Out: " << (void*)Res
1239 // Add the instruction to the expression map
1240 VMC.ExprMap[I] = Res;
1242 if (I->getType() != Res->getType())
1243 ConvertValueToNewType(I, Res, VMC, TD);
1245 bool FromStart = true;
1246 Value::use_iterator UI;
1248 if (FromStart) UI = I->use_begin();
1249 if (UI == I->use_end()) break;
1251 if (isa<ValueHandle>(*UI)) {
1256 if (!FromStart) --UI;
1257 U->replaceUsesOfWith(I, Res);
1258 if (!FromStart) ++UI;
1265 ValueHandle::ValueHandle(ValueMapCache &VMC, Value *V)
1266 : Instruction(Type::VoidTy, UserOp1, ""), Cache(VMC) {
1267 //DEBUG(std::cerr << "VH AQUIRING: " << (void*)V << " " << V);
1268 Operands.push_back(Use(V, this));
1271 ValueHandle::ValueHandle(const ValueHandle &VH)
1272 : Instruction(Type::VoidTy, UserOp1, ""), Cache(VH.Cache) {
1273 //DEBUG(std::cerr << "VH AQUIRING: " << (void*)V << " " << V);
1274 Operands.push_back(Use((Value*)VH.getOperand(0), this));
1277 static void RecursiveDelete(ValueMapCache &Cache, Instruction *I) {
1278 if (!I || !I->use_empty()) return;
1280 assert(I->getParent() && "Inst not in basic block!");
1282 //DEBUG(std::cerr << "VH DELETING: " << (void*)I << " " << I);
1284 for (User::op_iterator OI = I->op_begin(), OE = I->op_end();
1286 if (Instruction *U = dyn_cast<Instruction>(OI)) {
1288 RecursiveDelete(Cache, U);
1291 I->getParent()->getInstList().remove(I);
1293 Cache.OperandsMapped.erase(I);
1294 Cache.ExprMap.erase(I);
1298 ValueHandle::~ValueHandle() {
1299 if (Operands[0]->hasOneUse()) {
1300 Value *V = Operands[0];
1301 Operands[0] = 0; // Drop use!
1303 // Now we just need to remove the old instruction so we don't get infinite
1304 // loops. Note that we cannot use DCE because DCE won't remove a store
1305 // instruction, for example.
1307 RecursiveDelete(Cache, dyn_cast<Instruction>(V));
1309 //DEBUG(std::cerr << "VH RELEASING: " << (void*)Operands[0].get() << " "
1310 // << Operands[0]->use_size() << " " << Operands[0]);