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::Shr:
79 if (!Ty->isInteger()) return false;
80 if (Ty->isSigned() != V->getType()->isSigned()) return false;
82 case Instruction::Shl:
83 if (!Ty->isInteger()) return false;
84 if (!ExpressionConvertibleToType(I->getOperand(0), Ty, CTMap, TD))
88 case Instruction::Load: {
89 LoadInst *LI = cast<LoadInst>(I);
90 if (!ExpressionConvertibleToType(LI->getPointerOperand(),
91 PointerType::get(Ty), CTMap, TD))
95 case Instruction::PHI: {
96 PHINode *PN = cast<PHINode>(I);
97 // Be conservative if we find a giant PHI node.
98 if (PN->getNumIncomingValues() > 32) return false;
100 for (unsigned i = 0; i < PN->getNumIncomingValues(); ++i)
101 if (!ExpressionConvertibleToType(PN->getIncomingValue(i), Ty, CTMap, TD))
106 case Instruction::GetElementPtr: {
107 // GetElementPtr's are directly convertible to a pointer type if they have
108 // a number of zeros at the end. Because removing these values does not
109 // change the logical offset of the GEP, it is okay and fair to remove them.
110 // This can change this:
111 // %t1 = getelementptr %Hosp * %hosp, ubyte 4, ubyte 0 ; <%List **>
112 // %t2 = cast %List * * %t1 to %List *
114 // %t2 = getelementptr %Hosp * %hosp, ubyte 4 ; <%List *>
116 GetElementPtrInst *GEP = cast<GetElementPtrInst>(I);
117 const PointerType *PTy = dyn_cast<PointerType>(Ty);
118 if (!PTy) return false; // GEP must always return a pointer...
119 const Type *PVTy = PTy->getElementType();
121 // Check to see if there are zero elements that we can remove from the
122 // index array. If there are, check to see if removing them causes us to
123 // get to the right type...
125 std::vector<Value*> Indices(GEP->idx_begin(), GEP->idx_end());
126 const Type *BaseType = GEP->getPointerOperand()->getType();
127 const Type *ElTy = 0;
129 while (!Indices.empty() &&
130 Indices.back() == Constant::getNullValue(Indices.back()->getType())){
132 ElTy = GetElementPtrInst::getIndexedType(BaseType, Indices, true);
134 break; // Found a match!!
138 if (ElTy) break; // Found a number of zeros we can strip off!
140 // Otherwise, it could be that we have something like this:
141 // getelementptr [[sbyte] *] * %reg115, long %reg138 ; [sbyte]**
142 // and want to convert it into something like this:
143 // getelemenptr [[int] *] * %reg115, long %reg138 ; [int]**
145 if (GEP->getNumOperands() == 2 &&
146 PTy->getElementType()->isSized() &&
147 TD.getTypeSize(PTy->getElementType()) ==
148 TD.getTypeSize(GEP->getType()->getElementType())) {
149 const PointerType *NewSrcTy = PointerType::get(PVTy);
150 if (!ExpressionConvertibleToType(I->getOperand(0), NewSrcTy, CTMap, TD))
155 return false; // No match, maybe next time.
158 case Instruction::Call: {
159 if (isa<Function>(I->getOperand(0)))
160 return false; // Don't even try to change direct calls.
162 // If this is a function pointer, we can convert the return type if we can
163 // convert the source function pointer.
165 const PointerType *PT = cast<PointerType>(I->getOperand(0)->getType());
166 const FunctionType *FT = cast<FunctionType>(PT->getElementType());
167 std::vector<const Type *> ArgTys(FT->param_begin(), FT->param_end());
168 const FunctionType *NewTy =
169 FunctionType::get(Ty, ArgTys, FT->isVarArg());
170 if (!ExpressionConvertibleToType(I->getOperand(0),
171 PointerType::get(NewTy), CTMap, TD))
179 // Expressions are only convertible if all of the users of the expression can
180 // have this value converted. This makes use of the map to avoid infinite
183 for (Value::use_iterator It = I->use_begin(), E = I->use_end(); It != E; ++It)
184 if (!OperandConvertibleToType(*It, I, Ty, CTMap, TD))
191 Value *llvm::ConvertExpressionToType(Value *V, const Type *Ty,
192 ValueMapCache &VMC, const TargetData &TD) {
193 if (V->getType() == Ty) return V; // Already where we need to be?
195 ValueMapCache::ExprMapTy::iterator VMCI = VMC.ExprMap.find(V);
196 if (VMCI != VMC.ExprMap.end()) {
197 const Value *GV = VMCI->second;
198 const Type *GTy = VMCI->second->getType();
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 DEBUG(std::cerr << "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::Shr:
248 Res = new ShiftInst(cast<ShiftInst>(I)->getOpcode(), Dummy,
249 I->getOperand(1), Name);
250 VMC.ExprMap[I] = Res;
251 Res->setOperand(0, ConvertExpressionToType(I->getOperand(0), Ty, VMC, TD));
254 case Instruction::Load: {
255 LoadInst *LI = cast<LoadInst>(I);
257 Res = new LoadInst(Constant::getNullValue(PointerType::get(Ty)), Name);
258 VMC.ExprMap[I] = Res;
259 Res->setOperand(0, ConvertExpressionToType(LI->getPointerOperand(),
260 PointerType::get(Ty), VMC, TD));
261 assert(Res->getOperand(0)->getType() == PointerType::get(Ty));
262 assert(Ty == Res->getType());
263 assert(Res->getType()->isFirstClassType() && "Load of structure or array!");
267 case Instruction::PHI: {
268 PHINode *OldPN = cast<PHINode>(I);
269 PHINode *NewPN = new PHINode(Ty, Name);
271 VMC.ExprMap[I] = NewPN; // Add node to expression eagerly
272 while (OldPN->getNumOperands()) {
273 BasicBlock *BB = OldPN->getIncomingBlock(0);
274 Value *OldVal = OldPN->getIncomingValue(0);
275 ValueHandle OldValHandle(VMC, OldVal);
276 OldPN->removeIncomingValue(BB, false);
277 Value *V = ConvertExpressionToType(OldVal, Ty, VMC, TD);
278 NewPN->addIncoming(V, BB);
284 case Instruction::GetElementPtr: {
285 // GetElementPtr's are directly convertible to a pointer type if they have
286 // a number of zeros at the end. Because removing these values does not
287 // change the logical offset of the GEP, it is okay and fair to remove them.
288 // This can change this:
289 // %t1 = getelementptr %Hosp * %hosp, ubyte 4, ubyte 0 ; <%List **>
290 // %t2 = cast %List * * %t1 to %List *
292 // %t2 = getelementptr %Hosp * %hosp, ubyte 4 ; <%List *>
294 GetElementPtrInst *GEP = cast<GetElementPtrInst>(I);
296 // Check to see if there are zero elements that we can remove from the
297 // index array. If there are, check to see if removing them causes us to
298 // get to the right type...
300 std::vector<Value*> Indices(GEP->idx_begin(), GEP->idx_end());
301 const Type *BaseType = GEP->getPointerOperand()->getType();
302 const Type *PVTy = cast<PointerType>(Ty)->getElementType();
304 while (!Indices.empty() &&
305 Indices.back() == Constant::getNullValue(Indices.back()->getType())){
307 if (GetElementPtrInst::getIndexedType(BaseType, Indices, true) == PVTy) {
308 if (Indices.size() == 0)
309 Res = new CastInst(GEP->getPointerOperand(), BaseType); // NOOP CAST
311 Res = new GetElementPtrInst(GEP->getPointerOperand(), Indices, Name);
316 // Otherwise, it could be that we have something like this:
317 // getelementptr [[sbyte] *] * %reg115, uint %reg138 ; [sbyte]**
318 // and want to convert it into something like this:
319 // getelemenptr [[int] *] * %reg115, uint %reg138 ; [int]**
322 const PointerType *NewSrcTy = PointerType::get(PVTy);
323 std::vector<Value*> Indices(GEP->idx_begin(), GEP->idx_end());
324 Res = new GetElementPtrInst(Constant::getNullValue(NewSrcTy),
326 VMC.ExprMap[I] = Res;
327 Res->setOperand(0, ConvertExpressionToType(I->getOperand(0),
332 assert(Res && "Didn't find match!");
336 case Instruction::Call: {
337 assert(!isa<Function>(I->getOperand(0)));
339 // If this is a function pointer, we can convert the return type if we can
340 // convert the source function pointer.
342 const PointerType *PT = cast<PointerType>(I->getOperand(0)->getType());
343 const FunctionType *FT = cast<FunctionType>(PT->getElementType());
344 std::vector<const Type *> ArgTys(FT->param_begin(), FT->param_end());
345 const FunctionType *NewTy =
346 FunctionType::get(Ty, ArgTys, FT->isVarArg());
347 const PointerType *NewPTy = PointerType::get(NewTy);
348 if (Ty == Type::VoidTy)
349 Name = ""; // Make sure not to name calls that now return void!
351 Res = new CallInst(Constant::getNullValue(NewPTy),
352 std::vector<Value*>(I->op_begin()+1, I->op_end()),
354 if (cast<CallInst>(I)->isTailCall())
355 cast<CallInst>(Res)->setTailCall();
356 cast<CallInst>(Res)->setCallingConv(cast<CallInst>(I)->getCallingConv());
357 VMC.ExprMap[I] = Res;
358 Res->setOperand(0, ConvertExpressionToType(I->getOperand(0),NewPTy,VMC,TD));
362 assert(0 && "Expression convertible, but don't know how to convert?");
366 assert(Res->getType() == Ty && "Didn't convert expr to correct type!");
368 BB->getInstList().insert(I, Res);
370 // Add the instruction to the expression map
371 VMC.ExprMap[I] = Res;
374 //// WTF is this code! FIXME: remove this.
375 unsigned NumUses = I->getNumUses();
376 for (unsigned It = 0; It < NumUses; ) {
377 unsigned OldSize = NumUses;
378 Value::use_iterator UI = I->use_begin();
379 std::advance(UI, It);
380 ConvertOperandToType(*UI, I, Res, VMC, TD);
381 NumUses = I->getNumUses();
382 if (NumUses == OldSize) ++It;
385 DEBUG(std::cerr << "ExpIn: " << (void*)I << " " << *I
386 << "ExpOut: " << (void*)Res << " " << *Res);
393 // ValueConvertibleToType - Return true if it is possible
394 bool llvm::ValueConvertibleToType(Value *V, const Type *Ty,
395 ValueTypeCache &ConvertedTypes,
396 const TargetData &TD) {
397 ValueTypeCache::iterator I = ConvertedTypes.find(V);
398 if (I != ConvertedTypes.end()) return I->second == Ty;
399 ConvertedTypes[V] = Ty;
401 // It is safe to convert the specified value to the specified type IFF all of
402 // the uses of the value can be converted to accept the new typed value.
404 if (V->getType() != Ty) {
405 for (Value::use_iterator I = V->use_begin(), E = V->use_end(); I != E; ++I)
406 if (!OperandConvertibleToType(*I, V, Ty, ConvertedTypes, TD))
417 // OperandConvertibleToType - Return true if it is possible to convert operand
418 // V of User (instruction) U to the specified type. This is true iff it is
419 // possible to change the specified instruction to accept this. CTMap is a map
420 // of converted types, so that circular definitions will see the future type of
421 // the expression, not the static current type.
423 static bool OperandConvertibleToType(User *U, Value *V, const Type *Ty,
424 ValueTypeCache &CTMap,
425 const TargetData &TD) {
426 // if (V->getType() == Ty) return true; // Operand already the right type?
428 // Expression type must be holdable in a register.
429 if (!Ty->isFirstClassType())
432 Instruction *I = dyn_cast<Instruction>(U);
433 if (I == 0) return false; // We can't convert!
435 switch (I->getOpcode()) {
436 case Instruction::Cast:
437 assert(I->getOperand(0) == V);
438 // We can convert the expr if the cast destination type is losslessly
439 // convertible to the requested type.
440 // Also, do not change a cast that is a noop cast. For all intents and
441 // purposes it should be eliminated.
442 if (!Ty->isLosslesslyConvertibleTo(I->getOperand(0)->getType()) ||
443 I->getType() == I->getOperand(0)->getType())
446 // Do not allow a 'cast ushort %V to uint' to have it's first operand be
447 // converted to a 'short' type. Doing so changes the way sign promotion
448 // happens, and breaks things. Only allow the cast to take place if the
449 // signedness doesn't change... or if the current cast is not a lossy
452 if (!I->getType()->isLosslesslyConvertibleTo(I->getOperand(0)->getType()) &&
453 I->getOperand(0)->getType()->isSigned() != Ty->isSigned())
456 // We also do not allow conversion of a cast that casts from a ptr to array
457 // of X to a *X. For example: cast [4 x %List *] * %val to %List * *
459 if (const PointerType *SPT =
460 dyn_cast<PointerType>(I->getOperand(0)->getType()))
461 if (const PointerType *DPT = dyn_cast<PointerType>(I->getType()))
462 if (const ArrayType *AT = dyn_cast<ArrayType>(SPT->getElementType()))
463 if (AT->getElementType() == DPT->getElementType())
467 case Instruction::Add:
468 case Instruction::Sub: {
469 if (!Ty->isInteger() && !Ty->isFloatingPoint()) return false;
471 Value *OtherOp = I->getOperand((V == I->getOperand(0)) ? 1 : 0);
472 return ValueConvertibleToType(I, Ty, CTMap, TD) &&
473 ExpressionConvertibleToType(OtherOp, Ty, CTMap, TD);
475 case Instruction::SetEQ:
476 case Instruction::SetNE: {
477 Value *OtherOp = I->getOperand((V == I->getOperand(0)) ? 1 : 0);
478 return ExpressionConvertibleToType(OtherOp, Ty, CTMap, TD);
480 case Instruction::Shr:
481 if (Ty->isSigned() != V->getType()->isSigned()) return false;
483 case Instruction::Shl:
484 if (I->getOperand(1) == V) return false; // Cannot change shift amount type
485 if (!Ty->isInteger()) return false;
486 return ValueConvertibleToType(I, Ty, CTMap, TD);
488 case Instruction::Free:
489 assert(I->getOperand(0) == V);
490 return isa<PointerType>(Ty); // Free can free any pointer type!
492 case Instruction::Load:
493 // Cannot convert the types of any subscripts...
494 if (I->getOperand(0) != V) return false;
496 if (const PointerType *PT = dyn_cast<PointerType>(Ty)) {
497 LoadInst *LI = cast<LoadInst>(I);
499 const Type *LoadedTy = PT->getElementType();
501 // They could be loading the first element of a composite type...
502 if (const CompositeType *CT = dyn_cast<CompositeType>(LoadedTy)) {
503 unsigned Offset = 0; // No offset, get first leaf.
504 std::vector<Value*> Indices; // Discarded...
505 LoadedTy = getStructOffsetType(CT, Offset, Indices, TD, false);
506 assert(Offset == 0 && "Offset changed from zero???");
509 if (!LoadedTy->isFirstClassType())
512 if (TD.getTypeSize(LoadedTy) != TD.getTypeSize(LI->getType()))
515 return ValueConvertibleToType(LI, LoadedTy, CTMap, TD);
519 case Instruction::Store: {
520 StoreInst *SI = cast<StoreInst>(I);
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 (const StructType *SElTy = dyn_cast<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 //std::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::Shr:
753 assert(I->getOperand(0) == OldVal);
754 Res = new ShiftInst(cast<ShiftInst>(I)->getOpcode(), NewVal,
755 I->getOperand(1), Name);
758 case Instruction::Free: // Free can free any pointer type!
759 assert(I->getOperand(0) == OldVal);
760 Res = new FreeInst(NewVal);
764 case Instruction::Load: {
765 assert(I->getOperand(0) == OldVal && isa<PointerType>(NewVal->getType()));
766 const Type *LoadedTy =
767 cast<PointerType>(NewVal->getType())->getElementType();
771 if (const CompositeType *CT = dyn_cast<CompositeType>(LoadedTy)) {
772 std::vector<Value*> Indices;
773 Indices.push_back(Constant::getNullValue(Type::UIntTy));
775 unsigned Offset = 0; // No offset, get first leaf.
776 LoadedTy = getStructOffsetType(CT, Offset, Indices, TD, false);
777 assert(LoadedTy->isFirstClassType());
779 if (Indices.size() != 1) { // Do not generate load X, 0
780 // Insert the GEP instruction before this load.
781 Src = new GetElementPtrInst(Src, Indices, Name+".idx", I);
785 Res = new LoadInst(Src, Name);
786 assert(Res->getType()->isFirstClassType() && "Load of structure or array!");
790 case Instruction::Store: {
791 if (I->getOperand(0) == OldVal) { // Replace the source value
792 // Check to see if operand #1 has already been converted...
793 ValueMapCache::ExprMapTy::iterator VMCI =
794 VMC.ExprMap.find(I->getOperand(1));
795 if (VMCI != VMC.ExprMap.end()) {
796 // Comments describing this stuff are in the OperandConvertibleToType
797 // switch statement for Store...
800 cast<PointerType>(VMCI->second->getType())->getElementType();
802 Value *SrcPtr = VMCI->second;
805 // We check that this is a struct in the initial scan...
806 const StructType *SElTy = cast<StructType>(ElTy);
808 std::vector<Value*> Indices;
809 Indices.push_back(Constant::getNullValue(Type::UIntTy));
812 const Type *Ty = getStructOffsetType(ElTy, Offset, Indices, TD,false);
813 assert(Offset == 0 && "Offset changed!");
814 assert(NewTy == Ty && "Did not convert to correct type!");
816 // Insert the GEP instruction before this store.
817 SrcPtr = new GetElementPtrInst(SrcPtr, Indices,
818 SrcPtr->getName()+".idx", I);
820 Res = new StoreInst(NewVal, SrcPtr);
822 VMC.ExprMap[I] = Res;
824 // Otherwise, we haven't converted Operand #1 over yet...
825 const PointerType *NewPT = PointerType::get(NewTy);
826 Res = new StoreInst(NewVal, Constant::getNullValue(NewPT));
827 VMC.ExprMap[I] = Res;
828 Res->setOperand(1, ConvertExpressionToType(I->getOperand(1),
831 } else { // Replace the source pointer
832 const Type *ValTy = cast<PointerType>(NewTy)->getElementType();
834 Value *SrcPtr = NewVal;
836 if (isa<StructType>(ValTy)) {
837 std::vector<Value*> Indices;
838 Indices.push_back(Constant::getNullValue(Type::UIntTy));
841 ValTy = getStructOffsetType(ValTy, Offset, Indices, TD, false);
843 assert(Offset == 0 && ValTy);
845 // Insert the GEP instruction before this store.
846 SrcPtr = new GetElementPtrInst(SrcPtr, Indices,
847 SrcPtr->getName()+".idx", I);
850 Res = new StoreInst(Constant::getNullValue(ValTy), SrcPtr);
851 VMC.ExprMap[I] = Res;
852 Res->setOperand(0, ConvertExpressionToType(I->getOperand(0),
858 case Instruction::PHI: {
859 PHINode *OldPN = cast<PHINode>(I);
860 PHINode *NewPN = new PHINode(NewTy, Name);
861 VMC.ExprMap[I] = NewPN;
863 while (OldPN->getNumOperands()) {
864 BasicBlock *BB = OldPN->getIncomingBlock(0);
865 Value *OldVal = OldPN->getIncomingValue(0);
866 ValueHandle OldValHandle(VMC, OldVal);
867 OldPN->removeIncomingValue(BB, false);
868 Value *V = ConvertExpressionToType(OldVal, NewTy, VMC, TD);
869 NewPN->addIncoming(V, BB);
875 case Instruction::Call: {
876 Value *Meth = I->getOperand(0);
877 std::vector<Value*> Params(I->op_begin()+1, I->op_end());
879 if (Meth == OldVal) { // Changing the function pointer?
880 const PointerType *NewPTy = cast<PointerType>(NewVal->getType());
881 const FunctionType *NewTy = cast<FunctionType>(NewPTy->getElementType());
883 if (NewTy->getReturnType() == Type::VoidTy)
884 Name = ""; // Make sure not to name a void call!
886 // Get an iterator to the call instruction so that we can insert casts for
887 // operands if need be. Note that we do not require operands to be
888 // convertible, we can insert casts if they are convertible but not
889 // compatible. The reason for this is that we prefer to have resolved
890 // functions but casted arguments if possible.
892 BasicBlock::iterator It = I;
894 // Convert over all of the call operands to their new types... but only
895 // convert over the part that is not in the vararg section of the call.
897 for (unsigned i = 0; i != NewTy->getNumParams(); ++i)
898 if (Params[i]->getType() != NewTy->getParamType(i)) {
899 // Create a cast to convert it to the right type, we know that this
900 // is a lossless cast...
902 Params[i] = new CastInst(Params[i], NewTy->getParamType(i),
904 Params[i]->getName(), It);
906 Meth = NewVal; // Update call destination to new value
908 } else { // Changing an argument, must be in vararg area
909 std::vector<Value*>::iterator OI =
910 std::find(Params.begin(), Params.end(), OldVal);
911 assert (OI != Params.end() && "Not using value!");
916 Res = new CallInst(Meth, Params, Name);
917 if (cast<CallInst>(I)->isTailCall())
918 cast<CallInst>(Res)->setTailCall();
919 cast<CallInst>(Res)->setCallingConv(cast<CallInst>(I)->getCallingConv());
923 assert(0 && "Expression convertible, but don't know how to convert?");
927 // If the instruction was newly created, insert it into the instruction
930 BasicBlock::iterator It = I;
931 assert(It != BB->end() && "Instruction not in own basic block??");
932 BB->getInstList().insert(It, Res); // Keep It pointing to old instruction
934 DEBUG(std::cerr << "COT CREATED: " << (void*)Res << " " << *Res
935 << "In: " << (void*)I << " " << *I << "Out: " << (void*)Res
938 // Add the instruction to the expression map
939 VMC.ExprMap[I] = Res;
941 if (I->getType() != Res->getType())
942 ConvertValueToNewType(I, Res, VMC, TD);
944 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
946 if (isa<ValueHandle>(*UI)) {
949 Use &U = UI.getUse();
950 ++UI; // Do not invalidate UI.
957 ValueHandle::ValueHandle(ValueMapCache &VMC, Value *V)
958 : Instruction(Type::VoidTy, UserOp1, &Op, 1, ""), Op(V, this), Cache(VMC) {
959 //DEBUG(std::cerr << "VH AQUIRING: " << (void*)V << " " << V);
962 ValueHandle::ValueHandle(const ValueHandle &VH)
963 : Instruction(Type::VoidTy, UserOp1, &Op, 1, ""),
964 Op(VH.Op, this), Cache(VH.Cache) {
965 //DEBUG(std::cerr << "VH AQUIRING: " << (void*)V << " " << V);
968 static void RecursiveDelete(ValueMapCache &Cache, Instruction *I) {
969 if (!I || !I->use_empty()) return;
971 assert(I->getParent() && "Inst not in basic block!");
973 //DEBUG(std::cerr << "VH DELETING: " << (void*)I << " " << I);
975 for (User::op_iterator OI = I->op_begin(), OE = I->op_end();
977 if (Instruction *U = dyn_cast<Instruction>(OI)) {
979 RecursiveDelete(Cache, U);
982 I->getParent()->getInstList().remove(I);
984 Cache.OperandsMapped.erase(I);
985 Cache.ExprMap.erase(I);
989 ValueHandle::~ValueHandle() {
990 if (Op->hasOneUse()) {
992 Op.set(0); // Drop use!
994 // Now we just need to remove the old instruction so we don't get infinite
995 // loops. Note that we cannot use DCE because DCE won't remove a store
996 // instruction, for example.
998 RecursiveDelete(Cache, dyn_cast<Instruction>(V));
1000 //DEBUG(std::cerr << "VH RELEASING: " << (void*)Operands[0].get() << " "
1001 // << Operands[0]->getNumUses() << " " << Operands[0]);