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/Instructions.h"
19 #include "llvm/ADT/STLExtras.h"
20 #include "llvm/Support/Debug.h"
24 static bool OperandConvertibleToType(User *U, Value *V, const Type *Ty,
25 ValueTypeCache &ConvertedTypes,
26 const TargetData &TD);
28 static void ConvertOperandToType(User *U, Value *OldVal, Value *NewVal,
29 ValueMapCache &VMC, const TargetData &TD);
32 // ExpressionConvertibleToType - Return true if it is possible
33 bool llvm::ExpressionConvertibleToType(Value *V, const Type *Ty,
34 ValueTypeCache &CTMap, const TargetData &TD) {
35 // Expression type must be holdable in a register.
36 if (!Ty->isFirstClassType())
39 ValueTypeCache::iterator CTMI = CTMap.find(V);
40 if (CTMI != CTMap.end()) return CTMI->second == Ty;
42 // If it's a constant... all constants can be converted to a different
45 if (isa<Constant>(V) && !isa<GlobalValue>(V))
49 if (V->getType() == Ty) return true; // Expression already correct type!
51 Instruction *I = dyn_cast<Instruction>(V);
52 if (I == 0) return false; // Otherwise, we can't convert!
54 switch (I->getOpcode()) {
55 case Instruction::Cast:
56 // We can convert the expr if the cast destination type is losslessly
57 // convertible to the requested type.
58 if (!Ty->isLosslesslyConvertibleTo(I->getType())) return false;
60 // We also do not allow conversion of a cast that casts from a ptr to array
61 // of X to a *X. For example: cast [4 x %List *] * %val to %List * *
63 if (const PointerType *SPT =
64 dyn_cast<PointerType>(I->getOperand(0)->getType()))
65 if (const PointerType *DPT = dyn_cast<PointerType>(I->getType()))
66 if (const ArrayType *AT = dyn_cast<ArrayType>(SPT->getElementType()))
67 if (AT->getElementType() == DPT->getElementType())
71 case Instruction::Add:
72 case Instruction::Sub:
73 if (!Ty->isInteger() && !Ty->isFloatingPoint()) return false;
74 if (!ExpressionConvertibleToType(I->getOperand(0), Ty, CTMap, TD) ||
75 !ExpressionConvertibleToType(I->getOperand(1), Ty, CTMap, TD))
78 case Instruction::LShr:
79 case Instruction::AShr:
80 if (!Ty->isInteger()) return false;
81 if (!ExpressionConvertibleToType(I->getOperand(0), Ty, CTMap, TD))
84 case Instruction::Shl:
85 if (!Ty->isInteger()) return false;
86 if (!ExpressionConvertibleToType(I->getOperand(0), Ty, CTMap, TD))
90 case Instruction::Load: {
91 LoadInst *LI = cast<LoadInst>(I);
92 if (!ExpressionConvertibleToType(LI->getPointerOperand(),
93 PointerType::get(Ty), CTMap, TD))
97 case Instruction::PHI: {
98 PHINode *PN = cast<PHINode>(I);
99 // Be conservative if we find a giant PHI node.
100 if (PN->getNumIncomingValues() > 32) return false;
102 for (unsigned i = 0; i < PN->getNumIncomingValues(); ++i)
103 if (!ExpressionConvertibleToType(PN->getIncomingValue(i), Ty, CTMap, TD))
108 case Instruction::GetElementPtr: {
109 // GetElementPtr's are directly convertible to a pointer type if they have
110 // a number of zeros at the end. Because removing these values does not
111 // change the logical offset of the GEP, it is okay and fair to remove them.
112 // This can change this:
113 // %t1 = getelementptr %Hosp * %hosp, ubyte 4, ubyte 0 ; <%List **>
114 // %t2 = cast %List * * %t1 to %List *
116 // %t2 = getelementptr %Hosp * %hosp, ubyte 4 ; <%List *>
118 GetElementPtrInst *GEP = cast<GetElementPtrInst>(I);
119 const PointerType *PTy = dyn_cast<PointerType>(Ty);
120 if (!PTy) return false; // GEP must always return a pointer...
121 const Type *PVTy = PTy->getElementType();
123 // Check to see if there are zero elements that we can remove from the
124 // index array. If there are, check to see if removing them causes us to
125 // get to the right type...
127 std::vector<Value*> Indices(GEP->idx_begin(), GEP->idx_end());
128 const Type *BaseType = GEP->getPointerOperand()->getType();
129 const Type *ElTy = 0;
131 while (!Indices.empty() &&
132 Indices.back() == Constant::getNullValue(Indices.back()->getType())){
134 ElTy = GetElementPtrInst::getIndexedType(BaseType, Indices, true);
136 break; // Found a match!!
140 if (ElTy) break; // Found a number of zeros we can strip off!
142 // Otherwise, it could be that we have something like this:
143 // getelementptr [[sbyte] *] * %reg115, long %reg138 ; [sbyte]**
144 // and want to convert it into something like this:
145 // getelemenptr [[int] *] * %reg115, long %reg138 ; [int]**
147 if (GEP->getNumOperands() == 2 &&
148 PTy->getElementType()->isSized() &&
149 TD.getTypeSize(PTy->getElementType()) ==
150 TD.getTypeSize(GEP->getType()->getElementType())) {
151 const PointerType *NewSrcTy = PointerType::get(PVTy);
152 if (!ExpressionConvertibleToType(I->getOperand(0), NewSrcTy, CTMap, TD))
157 return false; // No match, maybe next time.
160 case Instruction::Call: {
161 if (isa<Function>(I->getOperand(0)))
162 return false; // Don't even try to change direct calls.
164 // If this is a function pointer, we can convert the return type if we can
165 // convert the source function pointer.
167 const PointerType *PT = cast<PointerType>(I->getOperand(0)->getType());
168 const FunctionType *FT = cast<FunctionType>(PT->getElementType());
169 std::vector<const Type *> ArgTys(FT->param_begin(), FT->param_end());
170 const FunctionType *NewTy =
171 FunctionType::get(Ty, ArgTys, FT->isVarArg());
172 if (!ExpressionConvertibleToType(I->getOperand(0),
173 PointerType::get(NewTy), CTMap, TD))
181 // Expressions are only convertible if all of the users of the expression can
182 // have this value converted. This makes use of the map to avoid infinite
185 for (Value::use_iterator It = I->use_begin(), E = I->use_end(); It != E; ++It)
186 if (!OperandConvertibleToType(*It, I, Ty, CTMap, TD))
193 Value *llvm::ConvertExpressionToType(Value *V, const Type *Ty,
194 ValueMapCache &VMC, const TargetData &TD) {
195 if (V->getType() == Ty) return V; // Already where we need to be?
197 ValueMapCache::ExprMapTy::iterator VMCI = VMC.ExprMap.find(V);
198 if (VMCI != VMC.ExprMap.end()) {
199 assert(VMCI->second->getType() == Ty);
201 if (Instruction *I = dyn_cast<Instruction>(V))
202 ValueHandle IHandle(VMC, I); // Remove I if it is unused now!
207 DOUT << "CETT: " << (void*)V << " " << *V;
209 Instruction *I = dyn_cast<Instruction>(V);
211 Constant *CPV = cast<Constant>(V);
212 // Constants are converted by constant folding the cast that is required.
213 // We assume here that all casts are implemented for constant prop.
214 Value *Result = ConstantExpr::getCast(CPV, Ty);
215 // Add the instruction to the expression map
216 //VMC.ExprMap[V] = Result;
221 BasicBlock *BB = I->getParent();
222 std::string Name = I->getName(); if (!Name.empty()) I->setName("");
223 Instruction *Res; // Result of conversion
225 ValueHandle IHandle(VMC, I); // Prevent I from being removed!
227 Constant *Dummy = Constant::getNullValue(Ty);
229 switch (I->getOpcode()) {
230 case Instruction::Cast:
231 assert(VMC.NewCasts.count(ValueHandle(VMC, I)) == 0);
232 Res = new CastInst(I->getOperand(0), Ty, Name);
233 VMC.NewCasts.insert(ValueHandle(VMC, Res));
236 case Instruction::Add:
237 case Instruction::Sub:
238 Res = BinaryOperator::create(cast<BinaryOperator>(I)->getOpcode(),
240 VMC.ExprMap[I] = Res; // Add node to expression eagerly
242 Res->setOperand(0, ConvertExpressionToType(I->getOperand(0), Ty, VMC, TD));
243 Res->setOperand(1, ConvertExpressionToType(I->getOperand(1), Ty, VMC, TD));
246 case Instruction::Shl:
247 case Instruction::LShr:
248 case Instruction::AShr:
249 Res = new ShiftInst(cast<ShiftInst>(I)->getOpcode(), Dummy,
250 I->getOperand(1), Name);
251 VMC.ExprMap[I] = Res;
252 Res->setOperand(0, ConvertExpressionToType(I->getOperand(0), Ty, VMC, TD));
255 case Instruction::Load: {
256 LoadInst *LI = cast<LoadInst>(I);
258 Res = new LoadInst(Constant::getNullValue(PointerType::get(Ty)), Name);
259 VMC.ExprMap[I] = Res;
260 Res->setOperand(0, ConvertExpressionToType(LI->getPointerOperand(),
261 PointerType::get(Ty), VMC, TD));
262 assert(Res->getOperand(0)->getType() == PointerType::get(Ty));
263 assert(Ty == Res->getType());
264 assert(Res->getType()->isFirstClassType() && "Load of structure or array!");
268 case Instruction::PHI: {
269 PHINode *OldPN = cast<PHINode>(I);
270 PHINode *NewPN = new PHINode(Ty, Name);
272 VMC.ExprMap[I] = NewPN; // Add node to expression eagerly
273 while (OldPN->getNumOperands()) {
274 BasicBlock *BB = OldPN->getIncomingBlock(0);
275 Value *OldVal = OldPN->getIncomingValue(0);
276 ValueHandle OldValHandle(VMC, OldVal);
277 OldPN->removeIncomingValue(BB, false);
278 Value *V = ConvertExpressionToType(OldVal, Ty, VMC, TD);
279 NewPN->addIncoming(V, BB);
285 case Instruction::GetElementPtr: {
286 // GetElementPtr's are directly convertible to a pointer type if they have
287 // a number of zeros at the end. Because removing these values does not
288 // change the logical offset of the GEP, it is okay and fair to remove them.
289 // This can change this:
290 // %t1 = getelementptr %Hosp * %hosp, ubyte 4, ubyte 0 ; <%List **>
291 // %t2 = cast %List * * %t1 to %List *
293 // %t2 = getelementptr %Hosp * %hosp, ubyte 4 ; <%List *>
295 GetElementPtrInst *GEP = cast<GetElementPtrInst>(I);
297 // Check to see if there are zero elements that we can remove from the
298 // index array. If there are, check to see if removing them causes us to
299 // get to the right type...
301 std::vector<Value*> Indices(GEP->idx_begin(), GEP->idx_end());
302 const Type *BaseType = GEP->getPointerOperand()->getType();
303 const Type *PVTy = cast<PointerType>(Ty)->getElementType();
305 while (!Indices.empty() &&
306 Indices.back() == Constant::getNullValue(Indices.back()->getType())){
308 if (GetElementPtrInst::getIndexedType(BaseType, Indices, true) == PVTy) {
309 if (Indices.size() == 0)
310 Res = new CastInst(GEP->getPointerOperand(), BaseType); // NOOP CAST
312 Res = new GetElementPtrInst(GEP->getPointerOperand(), Indices, Name);
317 // Otherwise, it could be that we have something like this:
318 // getelementptr [[sbyte] *] * %reg115, uint %reg138 ; [sbyte]**
319 // and want to convert it into something like this:
320 // getelemenptr [[int] *] * %reg115, uint %reg138 ; [int]**
323 const PointerType *NewSrcTy = PointerType::get(PVTy);
324 std::vector<Value*> Indices(GEP->idx_begin(), GEP->idx_end());
325 Res = new GetElementPtrInst(Constant::getNullValue(NewSrcTy),
327 VMC.ExprMap[I] = Res;
328 Res->setOperand(0, ConvertExpressionToType(I->getOperand(0),
333 assert(Res && "Didn't find match!");
337 case Instruction::Call: {
338 assert(!isa<Function>(I->getOperand(0)));
340 // If this is a function pointer, we can convert the return type if we can
341 // convert the source function pointer.
343 const PointerType *PT = cast<PointerType>(I->getOperand(0)->getType());
344 const FunctionType *FT = cast<FunctionType>(PT->getElementType());
345 std::vector<const Type *> ArgTys(FT->param_begin(), FT->param_end());
346 const FunctionType *NewTy =
347 FunctionType::get(Ty, ArgTys, FT->isVarArg());
348 const PointerType *NewPTy = PointerType::get(NewTy);
349 if (Ty == Type::VoidTy)
350 Name = ""; // Make sure not to name calls that now return void!
352 Res = new CallInst(Constant::getNullValue(NewPTy),
353 std::vector<Value*>(I->op_begin()+1, I->op_end()),
355 if (cast<CallInst>(I)->isTailCall())
356 cast<CallInst>(Res)->setTailCall();
357 cast<CallInst>(Res)->setCallingConv(cast<CallInst>(I)->getCallingConv());
358 VMC.ExprMap[I] = Res;
359 Res->setOperand(0, ConvertExpressionToType(I->getOperand(0),NewPTy,VMC,TD));
363 assert(0 && "Expression convertible, but don't know how to convert?");
367 assert(Res->getType() == Ty && "Didn't convert expr to correct type!");
369 BB->getInstList().insert(I, Res);
371 // Add the instruction to the expression map
372 VMC.ExprMap[I] = Res;
375 //// WTF is this code! FIXME: remove this.
376 unsigned NumUses = I->getNumUses();
377 for (unsigned It = 0; It < NumUses; ) {
378 unsigned OldSize = NumUses;
379 Value::use_iterator UI = I->use_begin();
380 std::advance(UI, It);
381 ConvertOperandToType(*UI, I, Res, VMC, TD);
382 NumUses = I->getNumUses();
383 if (NumUses == OldSize) ++It;
386 DOUT << "ExpIn: " << (void*)I << " " << *I
387 << "ExpOut: " << (void*)Res << " " << *Res;
394 // ValueConvertibleToType - Return true if it is possible
395 bool llvm::ValueConvertibleToType(Value *V, const Type *Ty,
396 ValueTypeCache &ConvertedTypes,
397 const TargetData &TD) {
398 ValueTypeCache::iterator I = ConvertedTypes.find(V);
399 if (I != ConvertedTypes.end()) return I->second == Ty;
400 ConvertedTypes[V] = Ty;
402 // It is safe to convert the specified value to the specified type IFF all of
403 // the uses of the value can be converted to accept the new typed value.
405 if (V->getType() != Ty) {
406 for (Value::use_iterator I = V->use_begin(), E = V->use_end(); I != E; ++I)
407 if (!OperandConvertibleToType(*I, V, Ty, ConvertedTypes, TD))
418 // OperandConvertibleToType - Return true if it is possible to convert operand
419 // V of User (instruction) U to the specified type. This is true iff it is
420 // possible to change the specified instruction to accept this. CTMap is a map
421 // of converted types, so that circular definitions will see the future type of
422 // the expression, not the static current type.
424 static bool OperandConvertibleToType(User *U, Value *V, const Type *Ty,
425 ValueTypeCache &CTMap,
426 const TargetData &TD) {
427 // if (V->getType() == Ty) return true; // Operand already the right type?
429 // Expression type must be holdable in a register.
430 if (!Ty->isFirstClassType())
433 Instruction *I = dyn_cast<Instruction>(U);
434 if (I == 0) return false; // We can't convert!
436 switch (I->getOpcode()) {
437 case Instruction::Cast:
438 assert(I->getOperand(0) == V);
439 // We can convert the expr if the cast destination type is losslessly
440 // convertible to the requested type.
441 // Also, do not change a cast that is a noop cast. For all intents and
442 // purposes it should be eliminated.
443 if (!Ty->isLosslesslyConvertibleTo(I->getOperand(0)->getType()) ||
444 I->getType() == I->getOperand(0)->getType())
447 // Do not allow a 'cast ushort %V to uint' to have it's first operand be
448 // converted to a 'short' type. Doing so changes the way sign promotion
449 // happens, and breaks things. Only allow the cast to take place if the
450 // signedness doesn't change... or if the current cast is not a lossy
453 if (!I->getType()->isLosslesslyConvertibleTo(I->getOperand(0)->getType()) &&
454 I->getOperand(0)->getType()->isSigned() != Ty->isSigned())
457 // We also do not allow conversion of a cast that casts from a ptr to array
458 // of X to a *X. For example: cast [4 x %List *] * %val to %List * *
460 if (const PointerType *SPT =
461 dyn_cast<PointerType>(I->getOperand(0)->getType()))
462 if (const PointerType *DPT = dyn_cast<PointerType>(I->getType()))
463 if (const ArrayType *AT = dyn_cast<ArrayType>(SPT->getElementType()))
464 if (AT->getElementType() == DPT->getElementType())
468 case Instruction::Add:
469 case Instruction::Sub: {
470 if (!Ty->isInteger() && !Ty->isFloatingPoint()) return false;
472 Value *OtherOp = I->getOperand((V == I->getOperand(0)) ? 1 : 0);
473 return ValueConvertibleToType(I, Ty, CTMap, TD) &&
474 ExpressionConvertibleToType(OtherOp, Ty, CTMap, TD);
476 case Instruction::SetEQ:
477 case Instruction::SetNE: {
478 Value *OtherOp = I->getOperand((V == I->getOperand(0)) ? 1 : 0);
479 return ExpressionConvertibleToType(OtherOp, Ty, CTMap, TD);
481 case Instruction::LShr:
482 case Instruction::AShr:
483 if (Ty->isSigned() != V->getType()->isSigned()) return false;
485 case Instruction::Shl:
486 if (I->getOperand(1) == V) return false; // Cannot change shift amount type
487 if (!Ty->isInteger()) return false;
488 return ValueConvertibleToType(I, Ty, CTMap, TD);
490 case Instruction::Free:
491 assert(I->getOperand(0) == V);
492 return isa<PointerType>(Ty); // Free can free any pointer type!
494 case Instruction::Load:
495 // Cannot convert the types of any subscripts...
496 if (I->getOperand(0) != V) return false;
498 if (const PointerType *PT = dyn_cast<PointerType>(Ty)) {
499 LoadInst *LI = cast<LoadInst>(I);
501 const Type *LoadedTy = PT->getElementType();
503 // They could be loading the first element of a composite type...
504 if (const CompositeType *CT = dyn_cast<CompositeType>(LoadedTy)) {
505 unsigned Offset = 0; // No offset, get first leaf.
506 std::vector<Value*> Indices; // Discarded...
507 LoadedTy = getStructOffsetType(CT, Offset, Indices, TD, false);
508 assert(Offset == 0 && "Offset changed from zero???");
511 if (!LoadedTy->isFirstClassType())
514 if (TD.getTypeSize(LoadedTy) != TD.getTypeSize(LI->getType()))
517 return ValueConvertibleToType(LI, LoadedTy, CTMap, TD);
521 case Instruction::Store: {
522 if (V == I->getOperand(0)) {
523 ValueTypeCache::iterator CTMI = CTMap.find(I->getOperand(1));
524 if (CTMI != CTMap.end()) { // Operand #1 is in the table already?
525 // If so, check to see if it's Ty*, or, more importantly, if it is a
526 // pointer to a structure where the first element is a Ty... this code
527 // is necessary because we might be trying to change the source and
528 // destination type of the store (they might be related) and the dest
529 // pointer type might be a pointer to structure. Below we allow pointer
530 // to structures where the 0th element is compatible with the value,
531 // now we have to support the symmetrical part of this.
533 const Type *ElTy = cast<PointerType>(CTMI->second)->getElementType();
535 // Already a pointer to what we want? Trivially accept...
536 if (ElTy == Ty) return true;
538 // Tricky case now, if the destination is a pointer to structure,
539 // obviously the source is not allowed to be a structure (cannot copy
540 // a whole structure at a time), so the level raiser must be trying to
541 // store into the first field. Check for this and allow it now:
543 if (isa<StructType>(ElTy)) {
545 std::vector<Value*> Indices;
546 ElTy = getStructOffsetType(ElTy, Offset, Indices, TD, false);
547 assert(Offset == 0 && "Offset changed!");
548 if (ElTy == 0) // Element at offset zero in struct doesn't exist!
549 return false; // Can only happen for {}*
551 if (ElTy == Ty) // Looks like the 0th element of structure is
552 return true; // compatible! Accept now!
554 // Otherwise we know that we can't work, so just stop trying now.
559 // Can convert the store if we can convert the pointer operand to match
560 // the new value type...
561 return ExpressionConvertibleToType(I->getOperand(1), PointerType::get(Ty),
563 } else if (const PointerType *PT = dyn_cast<PointerType>(Ty)) {
564 const Type *ElTy = PT->getElementType();
565 assert(V == I->getOperand(1));
567 if (isa<StructType>(ElTy)) {
568 // We can change the destination pointer if we can store our first
569 // argument into the first element of the structure...
572 std::vector<Value*> Indices;
573 ElTy = getStructOffsetType(ElTy, Offset, Indices, TD, false);
574 assert(Offset == 0 && "Offset changed!");
575 if (ElTy == 0) // Element at offset zero in struct doesn't exist!
576 return false; // Can only happen for {}*
579 // Must move the same amount of data...
580 if (!ElTy->isSized() ||
581 TD.getTypeSize(ElTy) != TD.getTypeSize(I->getOperand(0)->getType()))
584 // Can convert store if the incoming value is convertible and if the
585 // result will preserve semantics...
586 const Type *Op0Ty = I->getOperand(0)->getType();
587 if (!(Op0Ty->isIntegral() ^ ElTy->isIntegral()) &&
588 !(Op0Ty->isFloatingPoint() ^ ElTy->isFloatingPoint()))
589 return ExpressionConvertibleToType(I->getOperand(0), ElTy, CTMap, TD);
594 case Instruction::PHI: {
595 PHINode *PN = cast<PHINode>(I);
596 // Be conservative if we find a giant PHI node.
597 if (PN->getNumIncomingValues() > 32) return false;
599 for (unsigned i = 0; i < PN->getNumIncomingValues(); ++i)
600 if (!ExpressionConvertibleToType(PN->getIncomingValue(i), Ty, CTMap, TD))
602 return ValueConvertibleToType(PN, Ty, CTMap, TD);
605 case Instruction::Call: {
606 User::op_iterator OI = std::find(I->op_begin(), I->op_end(), V);
607 assert (OI != I->op_end() && "Not using value!");
608 unsigned OpNum = OI - I->op_begin();
610 // Are we trying to change the function pointer value to a new type?
612 const PointerType *PTy = dyn_cast<PointerType>(Ty);
613 if (PTy == 0) return false; // Can't convert to a non-pointer type...
614 const FunctionType *FTy = dyn_cast<FunctionType>(PTy->getElementType());
615 if (FTy == 0) return false; // Can't convert to a non ptr to function...
617 // Do not allow converting to a call where all of the operands are ...'s
618 if (FTy->getNumParams() == 0 && FTy->isVarArg())
619 return false; // Do not permit this conversion!
621 // Perform sanity checks to make sure that new function type has the
622 // correct number of arguments...
624 unsigned NumArgs = I->getNumOperands()-1; // Don't include function ptr
626 // Cannot convert to a type that requires more fixed arguments than
627 // the call provides...
629 if (NumArgs < FTy->getNumParams()) return false;
631 // Unless this is a vararg function type, we cannot provide more arguments
632 // than are desired...
634 if (!FTy->isVarArg() && NumArgs > FTy->getNumParams())
637 // Okay, at this point, we know that the call and the function type match
638 // number of arguments. Now we see if we can convert the arguments
639 // themselves. Note that we do not require operands to be convertible,
640 // we can insert casts if they are convertible but not compatible. The
641 // reason for this is that we prefer to have resolved functions but casted
642 // arguments if possible.
644 for (unsigned i = 0, NA = FTy->getNumParams(); i < NA; ++i)
645 if (!FTy->getParamType(i)->isLosslesslyConvertibleTo(I->getOperand(i+1)->getType()))
646 return false; // Operands must have compatible types!
648 // Okay, at this point, we know that all of the arguments can be
649 // converted. We succeed if we can change the return type if
652 return ValueConvertibleToType(I, FTy->getReturnType(), CTMap, TD);
655 const PointerType *MPtr = cast<PointerType>(I->getOperand(0)->getType());
656 const FunctionType *FTy = cast<FunctionType>(MPtr->getElementType());
657 if (!FTy->isVarArg()) return false;
659 if ((OpNum-1) < FTy->getNumParams())
660 return false; // It's not in the varargs section...
662 // If we get this far, we know the value is in the varargs section of the
663 // function! We can convert if we don't reinterpret the value...
665 return Ty->isLosslesslyConvertibleTo(V->getType());
672 void llvm::ConvertValueToNewType(Value *V, Value *NewVal, ValueMapCache &VMC,
673 const TargetData &TD) {
674 ValueHandle VH(VMC, V);
676 // FIXME: This is horrible!
677 unsigned NumUses = V->getNumUses();
678 for (unsigned It = 0; It < NumUses; ) {
679 unsigned OldSize = NumUses;
680 Value::use_iterator UI = V->use_begin();
681 std::advance(UI, It);
682 ConvertOperandToType(*UI, V, NewVal, VMC, TD);
683 NumUses = V->getNumUses();
684 if (NumUses == OldSize) ++It;
690 static void ConvertOperandToType(User *U, Value *OldVal, Value *NewVal,
691 ValueMapCache &VMC, const TargetData &TD) {
692 if (isa<ValueHandle>(U)) return; // Valuehandles don't let go of operands...
694 if (VMC.OperandsMapped.count(U)) return;
695 VMC.OperandsMapped.insert(U);
697 ValueMapCache::ExprMapTy::iterator VMCI = VMC.ExprMap.find(U);
698 if (VMCI != VMC.ExprMap.end())
702 Instruction *I = cast<Instruction>(U); // Only Instructions convertible
704 BasicBlock *BB = I->getParent();
705 assert(BB != 0 && "Instruction not embedded in basic block!");
706 std::string Name = I->getName();
708 Instruction *Res; // Result of conversion
710 //llvm_cerr << endl << endl << "Type:\t" << Ty << "\nInst: " << I
711 // << "BB Before: " << BB << endl;
713 // Prevent I from being removed...
714 ValueHandle IHandle(VMC, I);
716 const Type *NewTy = NewVal->getType();
717 Constant *Dummy = (NewTy != Type::VoidTy) ?
718 Constant::getNullValue(NewTy) : 0;
720 switch (I->getOpcode()) {
721 case Instruction::Cast:
722 if (VMC.NewCasts.count(ValueHandle(VMC, I))) {
723 // This cast has already had it's value converted, causing a new cast to
724 // be created. We don't want to create YET ANOTHER cast instruction
725 // representing the original one, so just modify the operand of this cast
726 // instruction, which we know is newly created.
727 I->setOperand(0, NewVal);
728 I->setName(Name); // give I its name back
732 Res = new CastInst(NewVal, I->getType(), Name);
736 case Instruction::Add:
737 case Instruction::Sub:
738 case Instruction::SetEQ:
739 case Instruction::SetNE: {
740 Res = BinaryOperator::create(cast<BinaryOperator>(I)->getOpcode(),
742 VMC.ExprMap[I] = Res; // Add node to expression eagerly
744 unsigned OtherIdx = (OldVal == I->getOperand(0)) ? 1 : 0;
745 Value *OtherOp = I->getOperand(OtherIdx);
746 Res->setOperand(!OtherIdx, NewVal);
747 Value *NewOther = ConvertExpressionToType(OtherOp, NewTy, VMC, TD);
748 Res->setOperand(OtherIdx, NewOther);
751 case Instruction::Shl:
752 case Instruction::LShr:
753 case Instruction::AShr:
754 assert(I->getOperand(0) == OldVal);
755 Res = new ShiftInst(cast<ShiftInst>(I)->getOpcode(), NewVal,
756 I->getOperand(1), Name);
759 case Instruction::Free: // Free can free any pointer type!
760 assert(I->getOperand(0) == OldVal);
761 Res = new FreeInst(NewVal);
765 case Instruction::Load: {
766 assert(I->getOperand(0) == OldVal && isa<PointerType>(NewVal->getType()));
767 const Type *LoadedTy =
768 cast<PointerType>(NewVal->getType())->getElementType();
772 if (const CompositeType *CT = dyn_cast<CompositeType>(LoadedTy)) {
773 std::vector<Value*> Indices;
774 Indices.push_back(Constant::getNullValue(Type::UIntTy));
776 unsigned Offset = 0; // No offset, get first leaf.
777 LoadedTy = getStructOffsetType(CT, Offset, Indices, TD, false);
778 assert(LoadedTy->isFirstClassType());
780 if (Indices.size() != 1) { // Do not generate load X, 0
781 // Insert the GEP instruction before this load.
782 Src = new GetElementPtrInst(Src, Indices, Name+".idx", I);
786 Res = new LoadInst(Src, Name);
787 assert(Res->getType()->isFirstClassType() && "Load of structure or array!");
791 case Instruction::Store: {
792 if (I->getOperand(0) == OldVal) { // Replace the source value
793 // Check to see if operand #1 has already been converted...
794 ValueMapCache::ExprMapTy::iterator VMCI =
795 VMC.ExprMap.find(I->getOperand(1));
796 if (VMCI != VMC.ExprMap.end()) {
797 // Comments describing this stuff are in the OperandConvertibleToType
798 // switch statement for Store...
801 cast<PointerType>(VMCI->second->getType())->getElementType();
803 Value *SrcPtr = VMCI->second;
806 std::vector<Value*> Indices;
807 Indices.push_back(Constant::getNullValue(Type::UIntTy));
810 const Type *Ty = getStructOffsetType(ElTy, Offset, Indices, TD,false);
811 assert(Offset == 0 && "Offset changed!");
812 assert(NewTy == Ty && "Did not convert to correct type!");
814 // Insert the GEP instruction before this store.
815 SrcPtr = new GetElementPtrInst(SrcPtr, Indices,
816 SrcPtr->getName()+".idx", I);
818 Res = new StoreInst(NewVal, SrcPtr);
820 VMC.ExprMap[I] = Res;
822 // Otherwise, we haven't converted Operand #1 over yet...
823 const PointerType *NewPT = PointerType::get(NewTy);
824 Res = new StoreInst(NewVal, Constant::getNullValue(NewPT));
825 VMC.ExprMap[I] = Res;
826 Res->setOperand(1, ConvertExpressionToType(I->getOperand(1),
829 } else { // Replace the source pointer
830 const Type *ValTy = cast<PointerType>(NewTy)->getElementType();
832 Value *SrcPtr = NewVal;
834 if (isa<StructType>(ValTy)) {
835 std::vector<Value*> Indices;
836 Indices.push_back(Constant::getNullValue(Type::UIntTy));
839 ValTy = getStructOffsetType(ValTy, Offset, Indices, TD, false);
841 assert(Offset == 0 && ValTy);
843 // Insert the GEP instruction before this store.
844 SrcPtr = new GetElementPtrInst(SrcPtr, Indices,
845 SrcPtr->getName()+".idx", I);
848 Res = new StoreInst(Constant::getNullValue(ValTy), SrcPtr);
849 VMC.ExprMap[I] = Res;
850 Res->setOperand(0, ConvertExpressionToType(I->getOperand(0),
856 case Instruction::PHI: {
857 PHINode *OldPN = cast<PHINode>(I);
858 PHINode *NewPN = new PHINode(NewTy, Name);
859 VMC.ExprMap[I] = NewPN;
861 while (OldPN->getNumOperands()) {
862 BasicBlock *BB = OldPN->getIncomingBlock(0);
863 Value *OldVal = OldPN->getIncomingValue(0);
864 ValueHandle OldValHandle(VMC, OldVal);
865 OldPN->removeIncomingValue(BB, false);
866 Value *V = ConvertExpressionToType(OldVal, NewTy, VMC, TD);
867 NewPN->addIncoming(V, BB);
873 case Instruction::Call: {
874 Value *Meth = I->getOperand(0);
875 std::vector<Value*> Params(I->op_begin()+1, I->op_end());
877 if (Meth == OldVal) { // Changing the function pointer?
878 const PointerType *NewPTy = cast<PointerType>(NewVal->getType());
879 const FunctionType *NewTy = cast<FunctionType>(NewPTy->getElementType());
881 if (NewTy->getReturnType() == Type::VoidTy)
882 Name = ""; // Make sure not to name a void call!
884 // Get an iterator to the call instruction so that we can insert casts for
885 // operands if need be. Note that we do not require operands to be
886 // convertible, we can insert casts if they are convertible but not
887 // compatible. The reason for this is that we prefer to have resolved
888 // functions but casted arguments if possible.
890 BasicBlock::iterator It = I;
892 // Convert over all of the call operands to their new types... but only
893 // convert over the part that is not in the vararg section of the call.
895 for (unsigned i = 0; i != NewTy->getNumParams(); ++i)
896 if (Params[i]->getType() != NewTy->getParamType(i)) {
897 // Create a cast to convert it to the right type, we know that this
898 // is a lossless cast...
900 Params[i] = new CastInst(Params[i], NewTy->getParamType(i),
902 Params[i]->getName(), It);
904 Meth = NewVal; // Update call destination to new value
906 } else { // Changing an argument, must be in vararg area
907 std::vector<Value*>::iterator OI =
908 std::find(Params.begin(), Params.end(), OldVal);
909 assert (OI != Params.end() && "Not using value!");
914 Res = new CallInst(Meth, Params, Name);
915 if (cast<CallInst>(I)->isTailCall())
916 cast<CallInst>(Res)->setTailCall();
917 cast<CallInst>(Res)->setCallingConv(cast<CallInst>(I)->getCallingConv());
921 assert(0 && "Expression convertible, but don't know how to convert?");
925 // If the instruction was newly created, insert it into the instruction
928 BasicBlock::iterator It = I;
929 assert(It != BB->end() && "Instruction not in own basic block??");
930 BB->getInstList().insert(It, Res); // Keep It pointing to old instruction
932 DOUT << "COT CREATED: " << (void*)Res << " " << *Res
933 << "In: " << (void*)I << " " << *I << "Out: " << (void*)Res
936 // Add the instruction to the expression map
937 VMC.ExprMap[I] = Res;
939 if (I->getType() != Res->getType())
940 ConvertValueToNewType(I, Res, VMC, TD);
942 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
944 if (isa<ValueHandle>(*UI)) {
947 Use &U = UI.getUse();
948 ++UI; // Do not invalidate UI.
955 ValueHandle::ValueHandle(ValueMapCache &VMC, Value *V)
956 : Instruction(Type::VoidTy, UserOp1, &Op, 1, ""), Op(V, this), Cache(VMC) {
957 //DOUT << "VH AQUIRING: " << (void*)V << " " << V;
960 ValueHandle::ValueHandle(const ValueHandle &VH)
961 : Instruction(Type::VoidTy, UserOp1, &Op, 1, ""),
962 Op(VH.Op, this), Cache(VH.Cache) {
963 //DOUT << "VH AQUIRING: " << (void*)V << " " << V;
966 static void RecursiveDelete(ValueMapCache &Cache, Instruction *I) {
967 if (!I || !I->use_empty()) return;
969 assert(I->getParent() && "Inst not in basic block!");
971 //DOUT << "VH DELETING: " << (void*)I << " " << I;
973 for (User::op_iterator OI = I->op_begin(), OE = I->op_end();
975 if (Instruction *U = dyn_cast<Instruction>(OI)) {
977 RecursiveDelete(Cache, U);
980 I->getParent()->getInstList().remove(I);
982 Cache.OperandsMapped.erase(I);
983 Cache.ExprMap.erase(I);
987 ValueHandle::~ValueHandle() {
988 if (Op->hasOneUse()) {
990 Op.set(0); // Drop use!
992 // Now we just need to remove the old instruction so we don't get infinite
993 // loops. Note that we cannot use DCE because DCE won't remove a store
994 // instruction, for example.
996 RecursiveDelete(Cache, dyn_cast<Instruction>(V));
998 //DOUT << "VH RELEASING: " << (void*)Operands[0].get() << " "
999 // << Operands[0]->getNumUses() << " " << Operands[0];