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"
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 = ClassifyExpr(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 = ClassifyExpr(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 llvm::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
157 if (Constant *CPV = dyn_cast<Constant>(V))
161 if (V->getType() == Ty) return true; // Expression already correct type!
163 Instruction *I = dyn_cast<Instruction>(V);
164 if (I == 0) return false; // Otherwise, we can't convert!
166 switch (I->getOpcode()) {
167 case Instruction::Cast:
168 // We can convert the expr if the cast destination type is losslessly
169 // convertible to the requested type.
170 if (!Ty->isLosslesslyConvertibleTo(I->getType())) return false;
172 // We also do not allow conversion of a cast that casts from a ptr to array
173 // of X to a *X. For example: cast [4 x %List *] * %val to %List * *
175 if (const PointerType *SPT =
176 dyn_cast<PointerType>(I->getOperand(0)->getType()))
177 if (const PointerType *DPT = dyn_cast<PointerType>(I->getType()))
178 if (const ArrayType *AT = dyn_cast<ArrayType>(SPT->getElementType()))
179 if (AT->getElementType() == DPT->getElementType())
183 case Instruction::Add:
184 case Instruction::Sub:
185 if (!Ty->isInteger() && !Ty->isFloatingPoint()) return false;
186 if (!ExpressionConvertibleToType(I->getOperand(0), Ty, CTMap, TD) ||
187 !ExpressionConvertibleToType(I->getOperand(1), Ty, CTMap, TD))
190 case Instruction::Shr:
191 if (!Ty->isInteger()) return false;
192 if (Ty->isSigned() != V->getType()->isSigned()) return false;
194 case Instruction::Shl:
195 if (!Ty->isInteger()) return false;
196 if (!ExpressionConvertibleToType(I->getOperand(0), Ty, CTMap, TD))
200 case Instruction::Load: {
201 LoadInst *LI = cast<LoadInst>(I);
202 if (!ExpressionConvertibleToType(LI->getPointerOperand(),
203 PointerType::get(Ty), CTMap, TD))
207 case Instruction::PHI: {
208 PHINode *PN = cast<PHINode>(I);
209 // Be conservative if we find a giant PHI node.
210 if (PN->getNumIncomingValues() > 32) return false;
212 for (unsigned i = 0; i < PN->getNumIncomingValues(); ++i)
213 if (!ExpressionConvertibleToType(PN->getIncomingValue(i), Ty, CTMap, TD))
218 case Instruction::Malloc:
219 if (!MallocConvertibleToType(cast<MallocInst>(I), Ty, CTMap, TD))
223 case Instruction::GetElementPtr: {
224 // GetElementPtr's are directly convertible to a pointer type if they have
225 // a number of zeros at the end. Because removing these values does not
226 // change the logical offset of the GEP, it is okay and fair to remove them.
227 // This can change this:
228 // %t1 = getelementptr %Hosp * %hosp, ubyte 4, ubyte 0 ; <%List **>
229 // %t2 = cast %List * * %t1 to %List *
231 // %t2 = getelementptr %Hosp * %hosp, ubyte 4 ; <%List *>
233 GetElementPtrInst *GEP = cast<GetElementPtrInst>(I);
234 const PointerType *PTy = dyn_cast<PointerType>(Ty);
235 if (!PTy) return false; // GEP must always return a pointer...
236 const Type *PVTy = PTy->getElementType();
238 // Check to see if there are zero elements that we can remove from the
239 // index array. If there are, check to see if removing them causes us to
240 // get to the right type...
242 std::vector<Value*> Indices(GEP->idx_begin(), GEP->idx_end());
243 const Type *BaseType = GEP->getPointerOperand()->getType();
244 const Type *ElTy = 0;
246 while (!Indices.empty() &&
247 Indices.back() == Constant::getNullValue(Indices.back()->getType())){
249 ElTy = GetElementPtrInst::getIndexedType(BaseType, Indices, true);
251 break; // Found a match!!
255 if (ElTy) break; // Found a number of zeros we can strip off!
257 // Otherwise, we can convert a GEP from one form to the other iff the
258 // current gep is of the form 'getelementptr sbyte*, long N
259 // and we could convert this to an appropriate GEP for the new type.
261 if (GEP->getNumOperands() == 2 &&
262 GEP->getType() == PointerType::get(Type::SByteTy)) {
264 // Do not Check to see if our incoming pointer can be converted
265 // to be a ptr to an array of the right type... because in more cases than
266 // not, it is simply not analyzable because of pointer/array
267 // discrepancies. To fix this, we will insert a cast before the GEP.
270 // Check to see if 'N' is an expression that can be converted to
271 // the appropriate size... if so, allow it.
273 std::vector<Value*> Indices;
274 const Type *ElTy = ConvertibleToGEP(PTy, I->getOperand(1), Indices, TD);
276 if (!ExpressionConvertibleToType(I->getOperand(0),
277 PointerType::get(ElTy), CTMap, TD))
278 return false; // Can't continue, ExConToTy might have polluted set!
283 // Otherwise, it could be that we have something like this:
284 // getelementptr [[sbyte] *] * %reg115, long %reg138 ; [sbyte]**
285 // and want to convert it into something like this:
286 // getelemenptr [[int] *] * %reg115, long %reg138 ; [int]**
288 if (GEP->getNumOperands() == 2 &&
289 PTy->getElementType()->isSized() &&
290 TD.getTypeSize(PTy->getElementType()) ==
291 TD.getTypeSize(GEP->getType()->getElementType())) {
292 const PointerType *NewSrcTy = PointerType::get(PVTy);
293 if (!ExpressionConvertibleToType(I->getOperand(0), NewSrcTy, CTMap, TD))
298 return false; // No match, maybe next time.
301 case Instruction::Call: {
302 if (isa<Function>(I->getOperand(0)))
303 return false; // Don't even try to change direct calls.
305 // If this is a function pointer, we can convert the return type if we can
306 // convert the source function pointer.
308 const PointerType *PT = cast<PointerType>(I->getOperand(0)->getType());
309 const FunctionType *FT = cast<FunctionType>(PT->getElementType());
310 std::vector<const Type *> ArgTys(FT->param_begin(), FT->param_end());
311 const FunctionType *NewTy =
312 FunctionType::get(Ty, ArgTys, FT->isVarArg());
313 if (!ExpressionConvertibleToType(I->getOperand(0),
314 PointerType::get(NewTy), CTMap, TD))
322 // Expressions are only convertible if all of the users of the expression can
323 // have this value converted. This makes use of the map to avoid infinite
326 for (Value::use_iterator It = I->use_begin(), E = I->use_end(); It != E; ++It)
327 if (!OperandConvertibleToType(*It, I, Ty, CTMap, TD))
334 Value *llvm::ConvertExpressionToType(Value *V, const Type *Ty,
335 ValueMapCache &VMC, const TargetData &TD) {
336 if (V->getType() == Ty) return V; // Already where we need to be?
338 ValueMapCache::ExprMapTy::iterator VMCI = VMC.ExprMap.find(V);
339 if (VMCI != VMC.ExprMap.end()) {
340 const Value *GV = VMCI->second;
341 const Type *GTy = VMCI->second->getType();
342 assert(VMCI->second->getType() == Ty);
344 if (Instruction *I = dyn_cast<Instruction>(V))
345 ValueHandle IHandle(VMC, I); // Remove I if it is unused now!
350 DEBUG(std::cerr << "CETT: " << (void*)V << " " << V);
352 Instruction *I = dyn_cast<Instruction>(V);
354 Constant *CPV = cast<Constant>(V);
355 // Constants are converted by constant folding the cast that is required.
356 // We assume here that all casts are implemented for constant prop.
357 Value *Result = ConstantExpr::getCast(CPV, Ty);
358 // Add the instruction to the expression map
359 //VMC.ExprMap[V] = Result;
364 BasicBlock *BB = I->getParent();
365 std::string Name = I->getName(); if (!Name.empty()) I->setName("");
366 Instruction *Res; // Result of conversion
368 ValueHandle IHandle(VMC, I); // Prevent I from being removed!
370 Constant *Dummy = Constant::getNullValue(Ty);
372 switch (I->getOpcode()) {
373 case Instruction::Cast:
374 assert(VMC.NewCasts.count(ValueHandle(VMC, I)) == 0);
375 Res = new CastInst(I->getOperand(0), Ty, Name);
376 VMC.NewCasts.insert(ValueHandle(VMC, Res));
379 case Instruction::Add:
380 case Instruction::Sub:
381 Res = BinaryOperator::create(cast<BinaryOperator>(I)->getOpcode(),
383 VMC.ExprMap[I] = Res; // Add node to expression eagerly
385 Res->setOperand(0, ConvertExpressionToType(I->getOperand(0), Ty, VMC, TD));
386 Res->setOperand(1, ConvertExpressionToType(I->getOperand(1), Ty, VMC, TD));
389 case Instruction::Shl:
390 case Instruction::Shr:
391 Res = new ShiftInst(cast<ShiftInst>(I)->getOpcode(), Dummy,
392 I->getOperand(1), Name);
393 VMC.ExprMap[I] = Res;
394 Res->setOperand(0, ConvertExpressionToType(I->getOperand(0), Ty, VMC, TD));
397 case Instruction::Load: {
398 LoadInst *LI = cast<LoadInst>(I);
400 Res = new LoadInst(Constant::getNullValue(PointerType::get(Ty)), Name);
401 VMC.ExprMap[I] = Res;
402 Res->setOperand(0, ConvertExpressionToType(LI->getPointerOperand(),
403 PointerType::get(Ty), VMC, TD));
404 assert(Res->getOperand(0)->getType() == PointerType::get(Ty));
405 assert(Ty == Res->getType());
406 assert(Res->getType()->isFirstClassType() && "Load of structure or array!");
410 case Instruction::PHI: {
411 PHINode *OldPN = cast<PHINode>(I);
412 PHINode *NewPN = new PHINode(Ty, Name);
414 VMC.ExprMap[I] = NewPN; // Add node to expression eagerly
415 while (OldPN->getNumOperands()) {
416 BasicBlock *BB = OldPN->getIncomingBlock(0);
417 Value *OldVal = OldPN->getIncomingValue(0);
418 ValueHandle OldValHandle(VMC, OldVal);
419 OldPN->removeIncomingValue(BB, false);
420 Value *V = ConvertExpressionToType(OldVal, Ty, VMC, TD);
421 NewPN->addIncoming(V, BB);
427 case Instruction::Malloc: {
428 Res = ConvertMallocToType(cast<MallocInst>(I), Ty, Name, VMC, TD);
432 case Instruction::GetElementPtr: {
433 // GetElementPtr's are directly convertible to a pointer type if they have
434 // a number of zeros at the end. Because removing these values does not
435 // change the logical offset of the GEP, it is okay and fair to remove them.
436 // This can change this:
437 // %t1 = getelementptr %Hosp * %hosp, ubyte 4, ubyte 0 ; <%List **>
438 // %t2 = cast %List * * %t1 to %List *
440 // %t2 = getelementptr %Hosp * %hosp, ubyte 4 ; <%List *>
442 GetElementPtrInst *GEP = cast<GetElementPtrInst>(I);
444 // Check to see if there are zero elements that we can remove from the
445 // index array. If there are, check to see if removing them causes us to
446 // get to the right type...
448 std::vector<Value*> Indices(GEP->idx_begin(), GEP->idx_end());
449 const Type *BaseType = GEP->getPointerOperand()->getType();
450 const Type *PVTy = cast<PointerType>(Ty)->getElementType();
452 while (!Indices.empty() &&
453 Indices.back() == Constant::getNullValue(Indices.back()->getType())){
455 if (GetElementPtrInst::getIndexedType(BaseType, Indices, true) == PVTy) {
456 if (Indices.size() == 0)
457 Res = new CastInst(GEP->getPointerOperand(), BaseType); // NOOP CAST
459 Res = new GetElementPtrInst(GEP->getPointerOperand(), Indices, Name);
464 if (Res == 0 && GEP->getNumOperands() == 2 &&
465 GEP->getType() == PointerType::get(Type::SByteTy)) {
467 // Otherwise, we can convert a GEP from one form to the other iff the
468 // current gep is of the form 'getelementptr sbyte*, unsigned N
469 // and we could convert this to an appropriate GEP for the new type.
471 const PointerType *NewSrcTy = PointerType::get(PVTy);
472 BasicBlock::iterator It = I;
474 // Check to see if 'N' is an expression that can be converted to
475 // the appropriate size... if so, allow it.
477 std::vector<Value*> Indices;
478 const Type *ElTy = ConvertibleToGEP(NewSrcTy, I->getOperand(1),
481 assert(ElTy == PVTy && "Internal error, setup wrong!");
482 Res = new GetElementPtrInst(Constant::getNullValue(NewSrcTy),
484 VMC.ExprMap[I] = Res;
485 Res->setOperand(0, ConvertExpressionToType(I->getOperand(0),
490 // Otherwise, it could be that we have something like this:
491 // getelementptr [[sbyte] *] * %reg115, uint %reg138 ; [sbyte]**
492 // and want to convert it into something like this:
493 // getelemenptr [[int] *] * %reg115, uint %reg138 ; [int]**
496 const PointerType *NewSrcTy = PointerType::get(PVTy);
497 std::vector<Value*> Indices(GEP->idx_begin(), GEP->idx_end());
498 Res = new GetElementPtrInst(Constant::getNullValue(NewSrcTy),
500 VMC.ExprMap[I] = Res;
501 Res->setOperand(0, ConvertExpressionToType(I->getOperand(0),
506 assert(Res && "Didn't find match!");
510 case Instruction::Call: {
511 assert(!isa<Function>(I->getOperand(0)));
513 // If this is a function pointer, we can convert the return type if we can
514 // convert the source function pointer.
516 const PointerType *PT = cast<PointerType>(I->getOperand(0)->getType());
517 const FunctionType *FT = cast<FunctionType>(PT->getElementType());
518 std::vector<const Type *> ArgTys(FT->param_begin(), FT->param_end());
519 const FunctionType *NewTy =
520 FunctionType::get(Ty, ArgTys, FT->isVarArg());
521 const PointerType *NewPTy = PointerType::get(NewTy);
522 if (Ty == Type::VoidTy)
523 Name = ""; // Make sure not to name calls that now return void!
525 Res = new CallInst(Constant::getNullValue(NewPTy),
526 std::vector<Value*>(I->op_begin()+1, I->op_end()),
528 VMC.ExprMap[I] = Res;
529 Res->setOperand(0, ConvertExpressionToType(I->getOperand(0),NewPTy,VMC,TD));
533 assert(0 && "Expression convertible, but don't know how to convert?");
537 assert(Res->getType() == Ty && "Didn't convert expr to correct type!");
539 BB->getInstList().insert(I, Res);
541 // Add the instruction to the expression map
542 VMC.ExprMap[I] = Res;
545 unsigned NumUses = I->use_size();
546 for (unsigned It = 0; It < NumUses; ) {
547 unsigned OldSize = NumUses;
548 Value::use_iterator UI = I->use_begin();
549 std::advance(UI, It);
550 ConvertOperandToType(*UI, I, Res, VMC, TD);
551 NumUses = I->use_size();
552 if (NumUses == OldSize) ++It;
555 DEBUG(std::cerr << "ExpIn: " << (void*)I << " " << I
556 << "ExpOut: " << (void*)Res << " " << Res);
563 // ValueConvertibleToType - Return true if it is possible
564 bool llvm::ValueConvertibleToType(Value *V, const Type *Ty,
565 ValueTypeCache &ConvertedTypes,
566 const TargetData &TD) {
567 ValueTypeCache::iterator I = ConvertedTypes.find(V);
568 if (I != ConvertedTypes.end()) return I->second == Ty;
569 ConvertedTypes[V] = Ty;
571 // It is safe to convert the specified value to the specified type IFF all of
572 // the uses of the value can be converted to accept the new typed value.
574 if (V->getType() != Ty) {
575 for (Value::use_iterator I = V->use_begin(), E = V->use_end(); I != E; ++I)
576 if (!OperandConvertibleToType(*I, V, Ty, ConvertedTypes, TD))
587 // OperandConvertibleToType - Return true if it is possible to convert operand
588 // V of User (instruction) U to the specified type. This is true iff it is
589 // possible to change the specified instruction to accept this. CTMap is a map
590 // of converted types, so that circular definitions will see the future type of
591 // the expression, not the static current type.
593 static bool OperandConvertibleToType(User *U, Value *V, const Type *Ty,
594 ValueTypeCache &CTMap,
595 const TargetData &TD) {
596 // if (V->getType() == Ty) return true; // Operand already the right type?
598 // Expression type must be holdable in a register.
599 if (!Ty->isFirstClassType())
602 Instruction *I = dyn_cast<Instruction>(U);
603 if (I == 0) return false; // We can't convert!
605 switch (I->getOpcode()) {
606 case Instruction::Cast:
607 assert(I->getOperand(0) == V);
608 // We can convert the expr if the cast destination type is losslessly
609 // convertible to the requested type.
610 // Also, do not change a cast that is a noop cast. For all intents and
611 // purposes it should be eliminated.
612 if (!Ty->isLosslesslyConvertibleTo(I->getOperand(0)->getType()) ||
613 I->getType() == I->getOperand(0)->getType())
616 // Do not allow a 'cast ushort %V to uint' to have it's first operand be
617 // converted to a 'short' type. Doing so changes the way sign promotion
618 // happens, and breaks things. Only allow the cast to take place if the
619 // signedness doesn't change... or if the current cast is not a lossy
622 if (!I->getType()->isLosslesslyConvertibleTo(I->getOperand(0)->getType()) &&
623 I->getOperand(0)->getType()->isSigned() != Ty->isSigned())
626 // We also do not allow conversion of a cast that casts from a ptr to array
627 // of X to a *X. For example: cast [4 x %List *] * %val to %List * *
629 if (const PointerType *SPT =
630 dyn_cast<PointerType>(I->getOperand(0)->getType()))
631 if (const PointerType *DPT = dyn_cast<PointerType>(I->getType()))
632 if (const ArrayType *AT = dyn_cast<ArrayType>(SPT->getElementType()))
633 if (AT->getElementType() == DPT->getElementType())
637 case Instruction::Add:
638 if (isa<PointerType>(Ty)) {
639 Value *IndexVal = I->getOperand(V == I->getOperand(0) ? 1 : 0);
640 std::vector<Value*> Indices;
641 if (const Type *ETy = ConvertibleToGEP(Ty, IndexVal, Indices, TD)) {
642 const Type *RetTy = PointerType::get(ETy);
644 // Only successful if we can convert this type to the required type
645 if (ValueConvertibleToType(I, RetTy, CTMap, TD)) {
649 // We have to return failure here because ValueConvertibleToType could
650 // have polluted our map
655 case Instruction::Sub: {
656 if (!Ty->isInteger() && !Ty->isFloatingPoint()) return false;
658 Value *OtherOp = I->getOperand((V == I->getOperand(0)) ? 1 : 0);
659 return ValueConvertibleToType(I, Ty, CTMap, TD) &&
660 ExpressionConvertibleToType(OtherOp, Ty, CTMap, TD);
662 case Instruction::SetEQ:
663 case Instruction::SetNE: {
664 Value *OtherOp = I->getOperand((V == I->getOperand(0)) ? 1 : 0);
665 return ExpressionConvertibleToType(OtherOp, Ty, CTMap, TD);
667 case Instruction::Shr:
668 if (Ty->isSigned() != V->getType()->isSigned()) return false;
670 case Instruction::Shl:
671 if (I->getOperand(1) == V) return false; // Cannot change shift amount type
672 if (!Ty->isInteger()) return false;
673 return ValueConvertibleToType(I, Ty, CTMap, TD);
675 case Instruction::Free:
676 assert(I->getOperand(0) == V);
677 return isa<PointerType>(Ty); // Free can free any pointer type!
679 case Instruction::Load:
680 // Cannot convert the types of any subscripts...
681 if (I->getOperand(0) != V) return false;
683 if (const PointerType *PT = dyn_cast<PointerType>(Ty)) {
684 LoadInst *LI = cast<LoadInst>(I);
686 const Type *LoadedTy = PT->getElementType();
688 // They could be loading the first element of a composite type...
689 if (const CompositeType *CT = dyn_cast<CompositeType>(LoadedTy)) {
690 unsigned Offset = 0; // No offset, get first leaf.
691 std::vector<Value*> Indices; // Discarded...
692 LoadedTy = getStructOffsetType(CT, Offset, Indices, TD, false);
693 assert(Offset == 0 && "Offset changed from zero???");
696 if (!LoadedTy->isFirstClassType())
699 if (TD.getTypeSize(LoadedTy) != TD.getTypeSize(LI->getType()))
702 return ValueConvertibleToType(LI, LoadedTy, CTMap, TD);
706 case Instruction::Store: {
707 StoreInst *SI = cast<StoreInst>(I);
709 if (V == I->getOperand(0)) {
710 ValueTypeCache::iterator CTMI = CTMap.find(I->getOperand(1));
711 if (CTMI != CTMap.end()) { // Operand #1 is in the table already?
712 // If so, check to see if it's Ty*, or, more importantly, if it is a
713 // pointer to a structure where the first element is a Ty... this code
714 // is necessary because we might be trying to change the source and
715 // destination type of the store (they might be related) and the dest
716 // pointer type might be a pointer to structure. Below we allow pointer
717 // to structures where the 0th element is compatible with the value,
718 // now we have to support the symmetrical part of this.
720 const Type *ElTy = cast<PointerType>(CTMI->second)->getElementType();
722 // Already a pointer to what we want? Trivially accept...
723 if (ElTy == Ty) return true;
725 // Tricky case now, if the destination is a pointer to structure,
726 // obviously the source is not allowed to be a structure (cannot copy
727 // a whole structure at a time), so the level raiser must be trying to
728 // store into the first field. Check for this and allow it now:
730 if (const StructType *SElTy = dyn_cast<StructType>(ElTy)) {
732 std::vector<Value*> Indices;
733 ElTy = getStructOffsetType(ElTy, Offset, Indices, TD, false);
734 assert(Offset == 0 && "Offset changed!");
735 if (ElTy == 0) // Element at offset zero in struct doesn't exist!
736 return false; // Can only happen for {}*
738 if (ElTy == Ty) // Looks like the 0th element of structure is
739 return true; // compatible! Accept now!
741 // Otherwise we know that we can't work, so just stop trying now.
746 // Can convert the store if we can convert the pointer operand to match
747 // the new value type...
748 return ExpressionConvertibleToType(I->getOperand(1), PointerType::get(Ty),
750 } else if (const PointerType *PT = dyn_cast<PointerType>(Ty)) {
751 const Type *ElTy = PT->getElementType();
752 assert(V == I->getOperand(1));
754 if (isa<StructType>(ElTy)) {
755 // We can change the destination pointer if we can store our first
756 // argument into the first element of the structure...
759 std::vector<Value*> Indices;
760 ElTy = getStructOffsetType(ElTy, Offset, Indices, TD, false);
761 assert(Offset == 0 && "Offset changed!");
762 if (ElTy == 0) // Element at offset zero in struct doesn't exist!
763 return false; // Can only happen for {}*
766 // Must move the same amount of data...
767 if (!ElTy->isSized() ||
768 TD.getTypeSize(ElTy) != TD.getTypeSize(I->getOperand(0)->getType()))
771 // Can convert store if the incoming value is convertible and if the
772 // result will preserve semantics...
773 const Type *Op0Ty = I->getOperand(0)->getType();
774 if (!(Op0Ty->isIntegral() ^ ElTy->isIntegral()) &&
775 !(Op0Ty->isFloatingPoint() ^ ElTy->isFloatingPoint()))
776 return ExpressionConvertibleToType(I->getOperand(0), ElTy, CTMap, TD);
781 case Instruction::GetElementPtr:
782 if (V != I->getOperand(0) || !isa<PointerType>(Ty)) return false;
784 // If we have a two operand form of getelementptr, this is really little
785 // more than a simple addition. As with addition, check to see if the
786 // getelementptr instruction can be changed to index into the new type.
788 if (I->getNumOperands() == 2) {
789 const Type *OldElTy = cast<PointerType>(I->getType())->getElementType();
790 unsigned DataSize = TD.getTypeSize(OldElTy);
791 Value *Index = I->getOperand(1);
792 Instruction *TempScale = 0;
794 // If the old data element is not unit sized, we have to create a scale
795 // instruction so that ConvertibleToGEP will know the REAL amount we are
796 // indexing by. Note that this is never inserted into the instruction
797 // stream, so we have to delete it when we're done.
801 if (Index->getType()->isSigned())
802 CST = ConstantSInt::get(Index->getType(), DataSize);
804 CST = ConstantUInt::get(Index->getType(), DataSize);
806 TempScale = BinaryOperator::create(Instruction::Mul, Index, CST);
810 // Check to see if the second argument is an expression that can
811 // be converted to the appropriate size... if so, allow it.
813 std::vector<Value*> Indices;
814 const Type *ElTy = ConvertibleToGEP(Ty, Index, Indices, TD);
815 delete TempScale; // Free our temporary multiply if we made it
817 if (ElTy == 0) return false; // Cannot make conversion...
818 return ValueConvertibleToType(I, PointerType::get(ElTy), CTMap, TD);
822 case Instruction::PHI: {
823 PHINode *PN = cast<PHINode>(I);
824 // Be conservative if we find a giant PHI node.
825 if (PN->getNumIncomingValues() > 32) return false;
827 for (unsigned i = 0; i < PN->getNumIncomingValues(); ++i)
828 if (!ExpressionConvertibleToType(PN->getIncomingValue(i), Ty, CTMap, TD))
830 return ValueConvertibleToType(PN, Ty, CTMap, TD);
833 case Instruction::Call: {
834 User::op_iterator OI = find(I->op_begin(), I->op_end(), V);
835 assert (OI != I->op_end() && "Not using value!");
836 unsigned OpNum = OI - I->op_begin();
838 // Are we trying to change the function pointer value to a new type?
840 const PointerType *PTy = dyn_cast<PointerType>(Ty);
841 if (PTy == 0) return false; // Can't convert to a non-pointer type...
842 const FunctionType *FTy = dyn_cast<FunctionType>(PTy->getElementType());
843 if (FTy == 0) return false; // Can't convert to a non ptr to function...
845 // Do not allow converting to a call where all of the operands are ...'s
846 if (FTy->getNumParams() == 0 && FTy->isVarArg())
847 return false; // Do not permit this conversion!
849 // Perform sanity checks to make sure that new function type has the
850 // correct number of arguments...
852 unsigned NumArgs = I->getNumOperands()-1; // Don't include function ptr
854 // Cannot convert to a type that requires more fixed arguments than
855 // the call provides...
857 if (NumArgs < FTy->getNumParams()) return false;
859 // Unless this is a vararg function type, we cannot provide more arguments
860 // than are desired...
862 if (!FTy->isVarArg() && NumArgs > FTy->getNumParams())
865 // Okay, at this point, we know that the call and the function type match
866 // number of arguments. Now we see if we can convert the arguments
867 // themselves. Note that we do not require operands to be convertible,
868 // we can insert casts if they are convertible but not compatible. The
869 // reason for this is that we prefer to have resolved functions but casted
870 // arguments if possible.
872 for (unsigned i = 0, NA = FTy->getNumParams(); i < NA; ++i)
873 if (!FTy->getParamType(i)->isLosslesslyConvertibleTo(I->getOperand(i+1)->getType()))
874 return false; // Operands must have compatible types!
876 // Okay, at this point, we know that all of the arguments can be
877 // converted. We succeed if we can change the return type if
880 return ValueConvertibleToType(I, FTy->getReturnType(), CTMap, TD);
883 const PointerType *MPtr = cast<PointerType>(I->getOperand(0)->getType());
884 const FunctionType *FTy = cast<FunctionType>(MPtr->getElementType());
885 if (!FTy->isVarArg()) return false;
887 if ((OpNum-1) < FTy->getNumParams())
888 return false; // It's not in the varargs section...
890 // If we get this far, we know the value is in the varargs section of the
891 // function! We can convert if we don't reinterpret the value...
893 return Ty->isLosslesslyConvertibleTo(V->getType());
900 void llvm::ConvertValueToNewType(Value *V, Value *NewVal, ValueMapCache &VMC,
901 const TargetData &TD) {
902 ValueHandle VH(VMC, V);
904 unsigned NumUses = V->use_size();
905 for (unsigned It = 0; It < NumUses; ) {
906 unsigned OldSize = NumUses;
907 Value::use_iterator UI = V->use_begin();
908 std::advance(UI, It);
909 ConvertOperandToType(*UI, V, NewVal, VMC, TD);
910 NumUses = V->use_size();
911 if (NumUses == OldSize) ++It;
917 static void ConvertOperandToType(User *U, Value *OldVal, Value *NewVal,
918 ValueMapCache &VMC, const TargetData &TD) {
919 if (isa<ValueHandle>(U)) return; // Valuehandles don't let go of operands...
921 if (VMC.OperandsMapped.count(U)) return;
922 VMC.OperandsMapped.insert(U);
924 ValueMapCache::ExprMapTy::iterator VMCI = VMC.ExprMap.find(U);
925 if (VMCI != VMC.ExprMap.end())
929 Instruction *I = cast<Instruction>(U); // Only Instructions convertible
931 BasicBlock *BB = I->getParent();
932 assert(BB != 0 && "Instruction not embedded in basic block!");
933 std::string Name = I->getName();
935 Instruction *Res; // Result of conversion
937 //std::cerr << endl << endl << "Type:\t" << Ty << "\nInst: " << I
938 // << "BB Before: " << BB << endl;
940 // Prevent I from being removed...
941 ValueHandle IHandle(VMC, I);
943 const Type *NewTy = NewVal->getType();
944 Constant *Dummy = (NewTy != Type::VoidTy) ?
945 Constant::getNullValue(NewTy) : 0;
947 switch (I->getOpcode()) {
948 case Instruction::Cast:
949 if (VMC.NewCasts.count(ValueHandle(VMC, I))) {
950 // This cast has already had it's value converted, causing a new cast to
951 // be created. We don't want to create YET ANOTHER cast instruction
952 // representing the original one, so just modify the operand of this cast
953 // instruction, which we know is newly created.
954 I->setOperand(0, NewVal);
955 I->setName(Name); // give I its name back
959 Res = new CastInst(NewVal, I->getType(), Name);
963 case Instruction::Add:
964 if (isa<PointerType>(NewTy)) {
965 Value *IndexVal = I->getOperand(OldVal == I->getOperand(0) ? 1 : 0);
966 std::vector<Value*> Indices;
967 BasicBlock::iterator It = I;
969 if (const Type *ETy = ConvertibleToGEP(NewTy, IndexVal, Indices, TD,&It)){
970 // If successful, convert the add to a GEP
971 //const Type *RetTy = PointerType::get(ETy);
972 // First operand is actually the given pointer...
973 Res = new GetElementPtrInst(NewVal, Indices, Name);
974 assert(cast<PointerType>(Res->getType())->getElementType() == ETy &&
975 "ConvertibleToGEP broken!");
981 case Instruction::Sub:
982 case Instruction::SetEQ:
983 case Instruction::SetNE: {
984 Res = BinaryOperator::create(cast<BinaryOperator>(I)->getOpcode(),
986 VMC.ExprMap[I] = Res; // Add node to expression eagerly
988 unsigned OtherIdx = (OldVal == I->getOperand(0)) ? 1 : 0;
989 Value *OtherOp = I->getOperand(OtherIdx);
990 Value *NewOther = ConvertExpressionToType(OtherOp, NewTy, VMC, TD);
992 Res->setOperand(OtherIdx, NewOther);
993 Res->setOperand(!OtherIdx, NewVal);
996 case Instruction::Shl:
997 case Instruction::Shr:
998 assert(I->getOperand(0) == OldVal);
999 Res = new ShiftInst(cast<ShiftInst>(I)->getOpcode(), NewVal,
1000 I->getOperand(1), Name);
1003 case Instruction::Free: // Free can free any pointer type!
1004 assert(I->getOperand(0) == OldVal);
1005 Res = new FreeInst(NewVal);
1009 case Instruction::Load: {
1010 assert(I->getOperand(0) == OldVal && isa<PointerType>(NewVal->getType()));
1011 const Type *LoadedTy =
1012 cast<PointerType>(NewVal->getType())->getElementType();
1014 Value *Src = NewVal;
1016 if (const CompositeType *CT = dyn_cast<CompositeType>(LoadedTy)) {
1017 std::vector<Value*> Indices;
1018 Indices.push_back(Constant::getNullValue(Type::UIntTy));
1020 unsigned Offset = 0; // No offset, get first leaf.
1021 LoadedTy = getStructOffsetType(CT, Offset, Indices, TD, false);
1022 assert(LoadedTy->isFirstClassType());
1024 if (Indices.size() != 1) { // Do not generate load X, 0
1025 // Insert the GEP instruction before this load.
1026 Src = new GetElementPtrInst(Src, Indices, Name+".idx", I);
1030 Res = new LoadInst(Src, Name);
1031 assert(Res->getType()->isFirstClassType() && "Load of structure or array!");
1035 case Instruction::Store: {
1036 if (I->getOperand(0) == OldVal) { // Replace the source value
1037 // Check to see if operand #1 has already been converted...
1038 ValueMapCache::ExprMapTy::iterator VMCI =
1039 VMC.ExprMap.find(I->getOperand(1));
1040 if (VMCI != VMC.ExprMap.end()) {
1041 // Comments describing this stuff are in the OperandConvertibleToType
1042 // switch statement for Store...
1045 cast<PointerType>(VMCI->second->getType())->getElementType();
1047 Value *SrcPtr = VMCI->second;
1049 if (ElTy != NewTy) {
1050 // We check that this is a struct in the initial scan...
1051 const StructType *SElTy = cast<StructType>(ElTy);
1053 std::vector<Value*> Indices;
1054 Indices.push_back(Constant::getNullValue(Type::UIntTy));
1056 unsigned Offset = 0;
1057 const Type *Ty = getStructOffsetType(ElTy, Offset, Indices, TD,false);
1058 assert(Offset == 0 && "Offset changed!");
1059 assert(NewTy == Ty && "Did not convert to correct type!");
1061 // Insert the GEP instruction before this store.
1062 SrcPtr = new GetElementPtrInst(SrcPtr, Indices,
1063 SrcPtr->getName()+".idx", I);
1065 Res = new StoreInst(NewVal, SrcPtr);
1067 VMC.ExprMap[I] = Res;
1069 // Otherwise, we haven't converted Operand #1 over yet...
1070 const PointerType *NewPT = PointerType::get(NewTy);
1071 Res = new StoreInst(NewVal, Constant::getNullValue(NewPT));
1072 VMC.ExprMap[I] = Res;
1073 Res->setOperand(1, ConvertExpressionToType(I->getOperand(1),
1076 } else { // Replace the source pointer
1077 const Type *ValTy = cast<PointerType>(NewTy)->getElementType();
1079 Value *SrcPtr = NewVal;
1081 if (isa<StructType>(ValTy)) {
1082 std::vector<Value*> Indices;
1083 Indices.push_back(Constant::getNullValue(Type::UIntTy));
1085 unsigned Offset = 0;
1086 ValTy = getStructOffsetType(ValTy, Offset, Indices, TD, false);
1088 assert(Offset == 0 && ValTy);
1090 // Insert the GEP instruction before this store.
1091 SrcPtr = new GetElementPtrInst(SrcPtr, Indices,
1092 SrcPtr->getName()+".idx", I);
1095 Res = new StoreInst(Constant::getNullValue(ValTy), SrcPtr);
1096 VMC.ExprMap[I] = Res;
1097 Res->setOperand(0, ConvertExpressionToType(I->getOperand(0),
1104 case Instruction::GetElementPtr: {
1105 // Convert a one index getelementptr into just about anything that is
1108 BasicBlock::iterator It = I;
1109 const Type *OldElTy = cast<PointerType>(I->getType())->getElementType();
1110 unsigned DataSize = TD.getTypeSize(OldElTy);
1111 Value *Index = I->getOperand(1);
1113 if (DataSize != 1) {
1114 // Insert a multiply of the old element type is not a unit size...
1116 if (Index->getType()->isSigned())
1117 CST = ConstantSInt::get(Index->getType(), DataSize);
1119 CST = ConstantUInt::get(Index->getType(), DataSize);
1121 Index = BinaryOperator::create(Instruction::Mul, Index, CST, "scale", It);
1124 // Perform the conversion now...
1126 std::vector<Value*> Indices;
1127 const Type *ElTy = ConvertibleToGEP(NewVal->getType(),Index,Indices,TD,&It);
1128 assert(ElTy != 0 && "GEP Conversion Failure!");
1129 Res = new GetElementPtrInst(NewVal, Indices, Name);
1130 assert(Res->getType() == PointerType::get(ElTy) &&
1131 "ConvertibleToGet failed!");
1134 if (I->getType() == PointerType::get(Type::SByteTy)) {
1135 // Convert a getelementptr sbyte * %reg111, uint 16 freely back to
1136 // anything that is a pointer type...
1138 BasicBlock::iterator It = I;
1140 // Check to see if the second argument is an expression that can
1141 // be converted to the appropriate size... if so, allow it.
1143 std::vector<Value*> Indices;
1144 const Type *ElTy = ConvertibleToGEP(NewVal->getType(), I->getOperand(1),
1146 assert(ElTy != 0 && "GEP Conversion Failure!");
1148 Res = new GetElementPtrInst(NewVal, Indices, Name);
1150 // Convert a getelementptr ulong * %reg123, uint %N
1151 // to getelementptr long * %reg123, uint %N
1152 // ... where the type must simply stay the same size...
1154 GetElementPtrInst *GEP = cast<GetElementPtrInst>(I);
1155 std::vector<Value*> Indices(GEP->idx_begin(), GEP->idx_end());
1156 Res = new GetElementPtrInst(NewVal, Indices, Name);
1161 case Instruction::PHI: {
1162 PHINode *OldPN = cast<PHINode>(I);
1163 PHINode *NewPN = new PHINode(NewTy, Name);
1164 VMC.ExprMap[I] = NewPN;
1166 while (OldPN->getNumOperands()) {
1167 BasicBlock *BB = OldPN->getIncomingBlock(0);
1168 Value *OldVal = OldPN->getIncomingValue(0);
1169 ValueHandle OldValHandle(VMC, OldVal);
1170 OldPN->removeIncomingValue(BB, false);
1171 Value *V = ConvertExpressionToType(OldVal, NewTy, VMC, TD);
1172 NewPN->addIncoming(V, BB);
1178 case Instruction::Call: {
1179 Value *Meth = I->getOperand(0);
1180 std::vector<Value*> Params(I->op_begin()+1, I->op_end());
1182 if (Meth == OldVal) { // Changing the function pointer?
1183 const PointerType *NewPTy = cast<PointerType>(NewVal->getType());
1184 const FunctionType *NewTy = cast<FunctionType>(NewPTy->getElementType());
1186 if (NewTy->getReturnType() == Type::VoidTy)
1187 Name = ""; // Make sure not to name a void call!
1189 // Get an iterator to the call instruction so that we can insert casts for
1190 // operands if need be. Note that we do not require operands to be
1191 // convertible, we can insert casts if they are convertible but not
1192 // compatible. The reason for this is that we prefer to have resolved
1193 // functions but casted arguments if possible.
1195 BasicBlock::iterator It = I;
1197 // Convert over all of the call operands to their new types... but only
1198 // convert over the part that is not in the vararg section of the call.
1200 for (unsigned i = 0; i != NewTy->getNumParams(); ++i)
1201 if (Params[i]->getType() != NewTy->getParamType(i)) {
1202 // Create a cast to convert it to the right type, we know that this
1203 // is a lossless cast...
1205 Params[i] = new CastInst(Params[i], NewTy->getParamType(i),
1207 Params[i]->getName(), It);
1209 Meth = NewVal; // Update call destination to new value
1211 } else { // Changing an argument, must be in vararg area
1212 std::vector<Value*>::iterator OI =
1213 find(Params.begin(), Params.end(), OldVal);
1214 assert (OI != Params.end() && "Not using value!");
1219 Res = new CallInst(Meth, Params, Name);
1223 assert(0 && "Expression convertible, but don't know how to convert?");
1227 // If the instruction was newly created, insert it into the instruction
1230 BasicBlock::iterator It = I;
1231 assert(It != BB->end() && "Instruction not in own basic block??");
1232 BB->getInstList().insert(It, Res); // Keep It pointing to old instruction
1234 DEBUG(std::cerr << "COT CREATED: " << (void*)Res << " " << Res
1235 << "In: " << (void*)I << " " << I << "Out: " << (void*)Res
1238 // Add the instruction to the expression map
1239 VMC.ExprMap[I] = Res;
1241 if (I->getType() != Res->getType())
1242 ConvertValueToNewType(I, Res, VMC, TD);
1244 bool FromStart = true;
1245 Value::use_iterator UI;
1247 if (FromStart) UI = I->use_begin();
1248 if (UI == I->use_end()) break;
1250 if (isa<ValueHandle>(*UI)) {
1255 if (!FromStart) --UI;
1256 U->replaceUsesOfWith(I, Res);
1257 if (!FromStart) ++UI;
1264 ValueHandle::ValueHandle(ValueMapCache &VMC, Value *V)
1265 : Instruction(Type::VoidTy, UserOp1, ""), Cache(VMC) {
1266 //DEBUG(std::cerr << "VH AQUIRING: " << (void*)V << " " << V);
1267 Operands.push_back(Use(V, this));
1270 ValueHandle::ValueHandle(const ValueHandle &VH)
1271 : Instruction(Type::VoidTy, UserOp1, ""), Cache(VH.Cache) {
1272 //DEBUG(std::cerr << "VH AQUIRING: " << (void*)V << " " << V);
1273 Operands.push_back(Use((Value*)VH.getOperand(0), this));
1276 static void RecursiveDelete(ValueMapCache &Cache, Instruction *I) {
1277 if (!I || !I->use_empty()) return;
1279 assert(I->getParent() && "Inst not in basic block!");
1281 //DEBUG(std::cerr << "VH DELETING: " << (void*)I << " " << I);
1283 for (User::op_iterator OI = I->op_begin(), OE = I->op_end();
1285 if (Instruction *U = dyn_cast<Instruction>(OI)) {
1287 RecursiveDelete(Cache, U);
1290 I->getParent()->getInstList().remove(I);
1292 Cache.OperandsMapped.erase(I);
1293 Cache.ExprMap.erase(I);
1297 ValueHandle::~ValueHandle() {
1298 if (Operands[0]->hasOneUse()) {
1299 Value *V = Operands[0];
1300 Operands[0] = 0; // Drop use!
1302 // Now we just need to remove the old instruction so we don't get infinite
1303 // loops. Note that we cannot use DCE because DCE won't remove a store
1304 // instruction, for example.
1306 RecursiveDelete(Cache, dyn_cast<Instruction>(V));
1308 //DEBUG(std::cerr << "VH RELEASING: " << (void*)Operands[0].get() << " "
1309 // << Operands[0]->use_size() << " " << Operands[0]);