1 //===- ExprTypeConvert.cpp - Code to change an LLVM Expr Type -------------===//
3 // This file implements the part of level raising that checks to see if it is
4 // possible to coerce an entire expression tree into a different type. If
5 // convertable, other routines from this file will do the conversion.
7 //===----------------------------------------------------------------------===//
9 #include "TransformInternals.h"
10 #include "llvm/iOther.h"
11 #include "llvm/iPHINode.h"
12 #include "llvm/iMemory.h"
13 #include "llvm/ConstantHandling.h"
14 #include "llvm/Analysis/Expressions.h"
15 #include "Support/STLExtras.h"
16 #include "Support/Statistic.h"
20 static bool OperandConvertableToType(User *U, Value *V, const Type *Ty,
21 ValueTypeCache &ConvertedTypes);
23 static void ConvertOperandToType(User *U, Value *OldVal, Value *NewVal,
26 // Peephole Malloc instructions: we take a look at the use chain of the
27 // malloc instruction, and try to find out if the following conditions hold:
28 // 1. The malloc is of the form: 'malloc [sbyte], uint <constant>'
29 // 2. The only users of the malloc are cast & add instructions
30 // 3. Of the cast instructions, there is only one destination pointer type
31 // [RTy] where the size of the pointed to object is equal to the number
32 // of bytes allocated.
34 // If these conditions hold, we convert the malloc to allocate an [RTy]
35 // element. TODO: This comment is out of date WRT arrays
37 static bool MallocConvertableToType(MallocInst *MI, const Type *Ty,
38 ValueTypeCache &CTMap) {
39 if (!isa<PointerType>(Ty)) return false; // Malloc always returns pointers
41 // Deal with the type to allocate, not the pointer type...
42 Ty = cast<PointerType>(Ty)->getElementType();
43 if (!Ty->isSized()) return false; // Can only alloc something with a size
45 // Analyze the number of bytes allocated...
46 ExprType Expr = ClassifyExpression(MI->getArraySize());
48 // Get information about the base datatype being allocated, before & after
49 int ReqTypeSize = TD.getTypeSize(Ty);
50 unsigned OldTypeSize = TD.getTypeSize(MI->getType()->getElementType());
52 // Must have a scale or offset to analyze it...
53 if (!Expr.Offset && !Expr.Scale && OldTypeSize == 1) return false;
55 // Get the offset and scale of the allocation...
56 int64_t OffsetVal = Expr.Offset ? getConstantValue(Expr.Offset) : 0;
57 int64_t ScaleVal = Expr.Scale ? getConstantValue(Expr.Scale) :(Expr.Var != 0);
59 // The old type might not be of unit size, take old size into consideration
61 int64_t Offset = OffsetVal * OldTypeSize;
62 int64_t Scale = ScaleVal * OldTypeSize;
64 // In order to be successful, both the scale and the offset must be a multiple
65 // of the requested data type's size.
67 if (Offset/ReqTypeSize*ReqTypeSize != Offset ||
68 Scale/ReqTypeSize*ReqTypeSize != Scale)
69 return false; // Nope.
74 static Instruction *ConvertMallocToType(MallocInst *MI, const Type *Ty,
75 const std::string &Name,
77 BasicBlock *BB = MI->getParent();
78 BasicBlock::iterator It = BB->end();
80 // Analyze the number of bytes allocated...
81 ExprType Expr = ClassifyExpression(MI->getArraySize());
83 const PointerType *AllocTy = cast<PointerType>(Ty);
84 const Type *ElType = AllocTy->getElementType();
86 unsigned DataSize = TD.getTypeSize(ElType);
87 unsigned OldTypeSize = TD.getTypeSize(MI->getType()->getElementType());
89 // Get the offset and scale coefficients that we are allocating...
90 int64_t OffsetVal = (Expr.Offset ? getConstantValue(Expr.Offset) : 0);
91 int64_t ScaleVal = Expr.Scale ? getConstantValue(Expr.Scale) : (Expr.Var !=0);
93 // The old type might not be of unit size, take old size into consideration
95 unsigned Offset = (uint64_t)OffsetVal * OldTypeSize / DataSize;
96 unsigned Scale = (uint64_t)ScaleVal * OldTypeSize / DataSize;
98 // Locate the malloc instruction, because we may be inserting instructions
101 // If we have a scale, apply it first...
103 // Expr.Var is not neccesarily unsigned right now, insert a cast now.
104 if (Expr.Var->getType() != Type::UIntTy)
105 Expr.Var = new CastInst(Expr.Var, Type::UIntTy,
106 Expr.Var->getName()+"-uint", It);
109 Expr.Var = BinaryOperator::create(Instruction::Mul, Expr.Var,
110 ConstantUInt::get(Type::UIntTy, Scale),
111 Expr.Var->getName()+"-scl", It);
114 // If we are not scaling anything, just make the offset be the "var"...
115 Expr.Var = ConstantUInt::get(Type::UIntTy, Offset);
116 Offset = 0; Scale = 1;
119 // If we have an offset now, add it in...
121 assert(Expr.Var && "Var must be nonnull by now!");
122 Expr.Var = BinaryOperator::create(Instruction::Add, Expr.Var,
123 ConstantUInt::get(Type::UIntTy, Offset),
124 Expr.Var->getName()+"-off", It);
127 assert(AllocTy == Ty);
128 return new MallocInst(AllocTy->getElementType(), Expr.Var, Name);
132 // ExpressionConvertableToType - Return true if it is possible
133 bool ExpressionConvertableToType(Value *V, const Type *Ty,
134 ValueTypeCache &CTMap) {
135 // Expression type must be holdable in a register.
136 if (!Ty->isFirstClassType())
139 ValueTypeCache::iterator CTMI = CTMap.find(V);
140 if (CTMI != CTMap.end()) return CTMI->second == Ty;
142 // If it's a constant... all constants can be converted to a different type We
143 // just ask the constant propogator to see if it can convert the value...
145 if (Constant *CPV = dyn_cast<Constant>(V))
146 return ConstantFoldCastInstruction(CPV, Ty);
150 if (V->getType() == Ty) return true; // Expression already correct type!
152 Instruction *I = dyn_cast<Instruction>(V);
153 if (I == 0) return false; // Otherwise, we can't convert!
155 switch (I->getOpcode()) {
156 case Instruction::Cast:
157 // We can convert the expr if the cast destination type is losslessly
158 // convertable to the requested type.
159 if (!Ty->isLosslesslyConvertableTo(I->getType())) return false;
161 // We also do not allow conversion of a cast that casts from a ptr to array
162 // of X to a *X. For example: cast [4 x %List *] * %val to %List * *
164 if (const PointerType *SPT =
165 dyn_cast<PointerType>(I->getOperand(0)->getType()))
166 if (const PointerType *DPT = dyn_cast<PointerType>(I->getType()))
167 if (const ArrayType *AT = dyn_cast<ArrayType>(SPT->getElementType()))
168 if (AT->getElementType() == DPT->getElementType())
172 case Instruction::Add:
173 case Instruction::Sub:
174 if (!Ty->isInteger() && !Ty->isFloatingPoint()) return false;
175 if (!ExpressionConvertableToType(I->getOperand(0), Ty, CTMap) ||
176 !ExpressionConvertableToType(I->getOperand(1), Ty, CTMap))
179 case Instruction::Shr:
180 if (!Ty->isInteger()) return false;
181 if (Ty->isSigned() != V->getType()->isSigned()) return false;
183 case Instruction::Shl:
184 if (!Ty->isInteger()) return false;
185 if (!ExpressionConvertableToType(I->getOperand(0), Ty, CTMap))
189 case Instruction::Load: {
190 LoadInst *LI = cast<LoadInst>(I);
191 if (!ExpressionConvertableToType(LI->getPointerOperand(),
192 PointerType::get(Ty), CTMap))
196 case Instruction::PHINode: {
197 PHINode *PN = cast<PHINode>(I);
198 for (unsigned i = 0; i < PN->getNumIncomingValues(); ++i)
199 if (!ExpressionConvertableToType(PN->getIncomingValue(i), Ty, CTMap))
204 case Instruction::Malloc:
205 if (!MallocConvertableToType(cast<MallocInst>(I), Ty, CTMap))
209 case Instruction::GetElementPtr: {
210 // GetElementPtr's are directly convertable to a pointer type if they have
211 // a number of zeros at the end. Because removing these values does not
212 // change the logical offset of the GEP, it is okay and fair to remove them.
213 // This can change this:
214 // %t1 = getelementptr %Hosp * %hosp, ubyte 4, ubyte 0 ; <%List **>
215 // %t2 = cast %List * * %t1 to %List *
217 // %t2 = getelementptr %Hosp * %hosp, ubyte 4 ; <%List *>
219 GetElementPtrInst *GEP = cast<GetElementPtrInst>(I);
220 const PointerType *PTy = dyn_cast<PointerType>(Ty);
221 if (!PTy) return false; // GEP must always return a pointer...
222 const Type *PVTy = PTy->getElementType();
224 // Check to see if there are zero elements that we can remove from the
225 // index array. If there are, check to see if removing them causes us to
226 // get to the right type...
228 std::vector<Value*> Indices(GEP->idx_begin(), GEP->idx_end());
229 const Type *BaseType = GEP->getPointerOperand()->getType();
230 const Type *ElTy = 0;
232 while (!Indices.empty() &&
233 Indices.back() == Constant::getNullValue(Indices.back()->getType())){
235 ElTy = GetElementPtrInst::getIndexedType(BaseType, Indices, true);
237 break; // Found a match!!
241 if (ElTy) break; // Found a number of zeros we can strip off!
243 // Otherwise, we can convert a GEP from one form to the other iff the
244 // current gep is of the form 'getelementptr sbyte*, long N
245 // and we could convert this to an appropriate GEP for the new type.
247 if (GEP->getNumOperands() == 2 &&
248 GEP->getOperand(1)->getType() == Type::LongTy &&
249 GEP->getType() == PointerType::get(Type::SByteTy)) {
251 // Do not Check to see if our incoming pointer can be converted
252 // to be a ptr to an array of the right type... because in more cases than
253 // not, it is simply not analyzable because of pointer/array
254 // discrepencies. To fix this, we will insert a cast before the GEP.
257 // Check to see if 'N' is an expression that can be converted to
258 // the appropriate size... if so, allow it.
260 std::vector<Value*> Indices;
261 const Type *ElTy = ConvertableToGEP(PTy, I->getOperand(1), Indices);
263 if (!ExpressionConvertableToType(I->getOperand(0),
264 PointerType::get(ElTy), CTMap))
265 return false; // Can't continue, ExConToTy might have polluted set!
270 // Otherwise, it could be that we have something like this:
271 // getelementptr [[sbyte] *] * %reg115, long %reg138 ; [sbyte]**
272 // and want to convert it into something like this:
273 // getelemenptr [[int] *] * %reg115, long %reg138 ; [int]**
275 if (GEP->getNumOperands() == 2 &&
276 GEP->getOperand(1)->getType() == Type::LongTy &&
277 TD.getTypeSize(PTy->getElementType()) ==
278 TD.getTypeSize(GEP->getType()->getElementType())) {
279 const PointerType *NewSrcTy = PointerType::get(PVTy);
280 if (!ExpressionConvertableToType(I->getOperand(0), NewSrcTy, CTMap))
285 return false; // No match, maybe next time.
292 // Expressions are only convertable if all of the users of the expression can
293 // have this value converted. This makes use of the map to avoid infinite
296 for (Value::use_iterator It = I->use_begin(), E = I->use_end(); It != E; ++It)
297 if (!OperandConvertableToType(*It, I, Ty, CTMap))
304 Value *ConvertExpressionToType(Value *V, const Type *Ty, ValueMapCache &VMC) {
305 if (V->getType() == Ty) return V; // Already where we need to be?
307 ValueMapCache::ExprMapTy::iterator VMCI = VMC.ExprMap.find(V);
308 if (VMCI != VMC.ExprMap.end()) {
309 const Value *GV = VMCI->second;
310 const Type *GTy = VMCI->second->getType();
311 assert(VMCI->second->getType() == Ty);
313 if (Instruction *I = dyn_cast<Instruction>(V))
314 ValueHandle IHandle(VMC, I); // Remove I if it is unused now!
319 DEBUG(cerr << "CETT: " << (void*)V << " " << V);
321 Instruction *I = dyn_cast<Instruction>(V);
323 Constant *CPV = cast<Constant>(V);
324 // Constants are converted by constant folding the cast that is required.
325 // We assume here that all casts are implemented for constant prop.
326 Value *Result = ConstantFoldCastInstruction(CPV, Ty);
327 assert(Result && "ConstantFoldCastInstruction Failed!!!");
328 assert(Result->getType() == Ty && "Const prop of cast failed!");
330 // Add the instruction to the expression map
331 //VMC.ExprMap[V] = Result;
336 BasicBlock *BB = I->getParent();
337 std::string Name = I->getName(); if (!Name.empty()) I->setName("");
338 Instruction *Res; // Result of conversion
340 ValueHandle IHandle(VMC, I); // Prevent I from being removed!
342 Constant *Dummy = Constant::getNullValue(Ty);
344 switch (I->getOpcode()) {
345 case Instruction::Cast:
346 assert(VMC.NewCasts.count(ValueHandle(VMC, I)) == 0);
347 Res = new CastInst(I->getOperand(0), Ty, Name);
348 VMC.NewCasts.insert(ValueHandle(VMC, Res));
351 case Instruction::Add:
352 case Instruction::Sub:
353 Res = BinaryOperator::create(cast<BinaryOperator>(I)->getOpcode(),
355 VMC.ExprMap[I] = Res; // Add node to expression eagerly
357 Res->setOperand(0, ConvertExpressionToType(I->getOperand(0), Ty, VMC));
358 Res->setOperand(1, ConvertExpressionToType(I->getOperand(1), Ty, VMC));
361 case Instruction::Shl:
362 case Instruction::Shr:
363 Res = new ShiftInst(cast<ShiftInst>(I)->getOpcode(), Dummy,
364 I->getOperand(1), Name);
365 VMC.ExprMap[I] = Res;
366 Res->setOperand(0, ConvertExpressionToType(I->getOperand(0), Ty, VMC));
369 case Instruction::Load: {
370 LoadInst *LI = cast<LoadInst>(I);
372 Res = new LoadInst(Constant::getNullValue(PointerType::get(Ty)), Name);
373 VMC.ExprMap[I] = Res;
374 Res->setOperand(0, ConvertExpressionToType(LI->getPointerOperand(),
375 PointerType::get(Ty), VMC));
376 assert(Res->getOperand(0)->getType() == PointerType::get(Ty));
377 assert(Ty == Res->getType());
378 assert(Res->getType()->isFirstClassType() && "Load of structure or array!");
382 case Instruction::PHINode: {
383 PHINode *OldPN = cast<PHINode>(I);
384 PHINode *NewPN = new PHINode(Ty, Name);
386 VMC.ExprMap[I] = NewPN; // Add node to expression eagerly
387 while (OldPN->getNumOperands()) {
388 BasicBlock *BB = OldPN->getIncomingBlock(0);
389 Value *OldVal = OldPN->getIncomingValue(0);
390 ValueHandle OldValHandle(VMC, OldVal);
391 OldPN->removeIncomingValue(BB, false);
392 Value *V = ConvertExpressionToType(OldVal, Ty, VMC);
393 NewPN->addIncoming(V, BB);
399 case Instruction::Malloc: {
400 Res = ConvertMallocToType(cast<MallocInst>(I), Ty, Name, VMC);
404 case Instruction::GetElementPtr: {
405 // GetElementPtr's are directly convertable to a pointer type if they have
406 // a number of zeros at the end. Because removing these values does not
407 // change the logical offset of the GEP, it is okay and fair to remove them.
408 // This can change this:
409 // %t1 = getelementptr %Hosp * %hosp, ubyte 4, ubyte 0 ; <%List **>
410 // %t2 = cast %List * * %t1 to %List *
412 // %t2 = getelementptr %Hosp * %hosp, ubyte 4 ; <%List *>
414 GetElementPtrInst *GEP = cast<GetElementPtrInst>(I);
416 // Check to see if there are zero elements that we can remove from the
417 // index array. If there are, check to see if removing them causes us to
418 // get to the right type...
420 std::vector<Value*> Indices(GEP->idx_begin(), GEP->idx_end());
421 const Type *BaseType = GEP->getPointerOperand()->getType();
422 const Type *PVTy = cast<PointerType>(Ty)->getElementType();
424 while (!Indices.empty() &&
425 Indices.back() == Constant::getNullValue(Indices.back()->getType())){
427 if (GetElementPtrInst::getIndexedType(BaseType, Indices, true) == PVTy) {
428 if (Indices.size() == 0)
429 Res = new CastInst(GEP->getPointerOperand(), BaseType); // NOOP CAST
431 Res = new GetElementPtrInst(GEP->getPointerOperand(), Indices, Name);
436 if (Res == 0 && GEP->getNumOperands() == 2 &&
437 GEP->getOperand(1)->getType() == Type::LongTy &&
438 GEP->getType() == PointerType::get(Type::SByteTy)) {
440 // Otherwise, we can convert a GEP from one form to the other iff the
441 // current gep is of the form 'getelementptr [sbyte]*, unsigned N
442 // and we could convert this to an appropriate GEP for the new type.
444 const PointerType *NewSrcTy = PointerType::get(PVTy);
445 BasicBlock::iterator It = I;
447 // Check to see if 'N' is an expression that can be converted to
448 // the appropriate size... if so, allow it.
450 std::vector<Value*> Indices;
451 const Type *ElTy = ConvertableToGEP(NewSrcTy, I->getOperand(1),
454 assert(ElTy == PVTy && "Internal error, setup wrong!");
455 Res = new GetElementPtrInst(Constant::getNullValue(NewSrcTy),
457 VMC.ExprMap[I] = Res;
458 Res->setOperand(0, ConvertExpressionToType(I->getOperand(0),
463 // Otherwise, it could be that we have something like this:
464 // getelementptr [[sbyte] *] * %reg115, uint %reg138 ; [sbyte]**
465 // and want to convert it into something like this:
466 // getelemenptr [[int] *] * %reg115, uint %reg138 ; [int]**
469 const PointerType *NewSrcTy = PointerType::get(PVTy);
470 std::vector<Value*> Indices(GEP->idx_begin(), GEP->idx_end());
471 Res = new GetElementPtrInst(Constant::getNullValue(NewSrcTy),
473 VMC.ExprMap[I] = Res;
474 Res->setOperand(0, ConvertExpressionToType(I->getOperand(0),
479 assert(Res && "Didn't find match!");
480 break; // No match, maybe next time.
484 assert(0 && "Expression convertable, but don't know how to convert?");
488 assert(Res->getType() == Ty && "Didn't convert expr to correct type!");
490 BB->getInstList().insert(I, Res);
492 // Add the instruction to the expression map
493 VMC.ExprMap[I] = Res;
495 // Expressions are only convertable if all of the users of the expression can
496 // have this value converted. This makes use of the map to avoid infinite
499 unsigned NumUses = I->use_size();
500 for (unsigned It = 0; It < NumUses; ) {
501 unsigned OldSize = NumUses;
502 ConvertOperandToType(*(I->use_begin()+It), I, Res, VMC);
503 NumUses = I->use_size();
504 if (NumUses == OldSize) ++It;
507 DEBUG(cerr << "ExpIn: " << (void*)I << " " << I
508 << "ExpOut: " << (void*)Res << " " << Res);
515 // ValueConvertableToType - Return true if it is possible
516 bool ValueConvertableToType(Value *V, const Type *Ty,
517 ValueTypeCache &ConvertedTypes) {
518 ValueTypeCache::iterator I = ConvertedTypes.find(V);
519 if (I != ConvertedTypes.end()) return I->second == Ty;
520 ConvertedTypes[V] = Ty;
522 // It is safe to convert the specified value to the specified type IFF all of
523 // the uses of the value can be converted to accept the new typed value.
525 if (V->getType() != Ty) {
526 for (Value::use_iterator I = V->use_begin(), E = V->use_end(); I != E; ++I)
527 if (!OperandConvertableToType(*I, V, Ty, ConvertedTypes))
538 // OperandConvertableToType - Return true if it is possible to convert operand
539 // V of User (instruction) U to the specified type. This is true iff it is
540 // possible to change the specified instruction to accept this. CTMap is a map
541 // of converted types, so that circular definitions will see the future type of
542 // the expression, not the static current type.
544 static bool OperandConvertableToType(User *U, Value *V, const Type *Ty,
545 ValueTypeCache &CTMap) {
546 // if (V->getType() == Ty) return true; // Operand already the right type?
548 // Expression type must be holdable in a register.
549 if (!Ty->isFirstClassType())
552 Instruction *I = dyn_cast<Instruction>(U);
553 if (I == 0) return false; // We can't convert!
555 switch (I->getOpcode()) {
556 case Instruction::Cast:
557 assert(I->getOperand(0) == V);
558 // We can convert the expr if the cast destination type is losslessly
559 // convertable to the requested type.
560 // Also, do not change a cast that is a noop cast. For all intents and
561 // purposes it should be eliminated.
562 if (!Ty->isLosslesslyConvertableTo(I->getOperand(0)->getType()) ||
563 I->getType() == I->getOperand(0)->getType())
566 // Do not allow a 'cast ushort %V to uint' to have it's first operand be
567 // converted to a 'short' type. Doing so changes the way sign promotion
568 // happens, and breaks things. Only allow the cast to take place if the
569 // signedness doesn't change... or if the current cast is not a lossy
572 if (!I->getType()->isLosslesslyConvertableTo(I->getOperand(0)->getType()) &&
573 I->getOperand(0)->getType()->isSigned() != Ty->isSigned())
576 // We also do not allow conversion of a cast that casts from a ptr to array
577 // of X to a *X. For example: cast [4 x %List *] * %val to %List * *
579 if (const PointerType *SPT =
580 dyn_cast<PointerType>(I->getOperand(0)->getType()))
581 if (const PointerType *DPT = dyn_cast<PointerType>(I->getType()))
582 if (const ArrayType *AT = dyn_cast<ArrayType>(SPT->getElementType()))
583 if (AT->getElementType() == DPT->getElementType())
587 case Instruction::Add:
588 if (isa<PointerType>(Ty)) {
589 Value *IndexVal = I->getOperand(V == I->getOperand(0) ? 1 : 0);
590 std::vector<Value*> Indices;
591 if (const Type *ETy = ConvertableToGEP(Ty, IndexVal, Indices)) {
592 const Type *RetTy = PointerType::get(ETy);
594 // Only successful if we can convert this type to the required type
595 if (ValueConvertableToType(I, RetTy, CTMap)) {
599 // We have to return failure here because ValueConvertableToType could
600 // have polluted our map
605 case Instruction::Sub: {
606 if (!Ty->isInteger() && !Ty->isFloatingPoint()) return false;
608 Value *OtherOp = I->getOperand((V == I->getOperand(0)) ? 1 : 0);
609 return ValueConvertableToType(I, Ty, CTMap) &&
610 ExpressionConvertableToType(OtherOp, Ty, CTMap);
612 case Instruction::SetEQ:
613 case Instruction::SetNE: {
614 Value *OtherOp = I->getOperand((V == I->getOperand(0)) ? 1 : 0);
615 return ExpressionConvertableToType(OtherOp, Ty, CTMap);
617 case Instruction::Shr:
618 if (Ty->isSigned() != V->getType()->isSigned()) return false;
620 case Instruction::Shl:
621 assert(I->getOperand(0) == V);
622 if (!Ty->isInteger()) return false;
623 return ValueConvertableToType(I, Ty, CTMap);
625 case Instruction::Free:
626 assert(I->getOperand(0) == V);
627 return isa<PointerType>(Ty); // Free can free any pointer type!
629 case Instruction::Load:
630 // Cannot convert the types of any subscripts...
631 if (I->getOperand(0) != V) return false;
633 if (const PointerType *PT = dyn_cast<PointerType>(Ty)) {
634 LoadInst *LI = cast<LoadInst>(I);
636 const Type *LoadedTy = PT->getElementType();
638 // They could be loading the first element of a composite type...
639 if (const CompositeType *CT = dyn_cast<CompositeType>(LoadedTy)) {
640 unsigned Offset = 0; // No offset, get first leaf.
641 std::vector<Value*> Indices; // Discarded...
642 LoadedTy = getStructOffsetType(CT, Offset, Indices, false);
643 assert(Offset == 0 && "Offset changed from zero???");
646 if (!LoadedTy->isFirstClassType())
649 if (TD.getTypeSize(LoadedTy) != TD.getTypeSize(LI->getType()))
652 return ValueConvertableToType(LI, LoadedTy, CTMap);
656 case Instruction::Store: {
657 StoreInst *SI = cast<StoreInst>(I);
659 if (V == I->getOperand(0)) {
660 ValueTypeCache::iterator CTMI = CTMap.find(I->getOperand(1));
661 if (CTMI != CTMap.end()) { // Operand #1 is in the table already?
662 // If so, check to see if it's Ty*, or, more importantly, if it is a
663 // pointer to a structure where the first element is a Ty... this code
664 // is neccesary because we might be trying to change the source and
665 // destination type of the store (they might be related) and the dest
666 // pointer type might be a pointer to structure. Below we allow pointer
667 // to structures where the 0th element is compatible with the value,
668 // now we have to support the symmetrical part of this.
670 const Type *ElTy = cast<PointerType>(CTMI->second)->getElementType();
672 // Already a pointer to what we want? Trivially accept...
673 if (ElTy == Ty) return true;
675 // Tricky case now, if the destination is a pointer to structure,
676 // obviously the source is not allowed to be a structure (cannot copy
677 // a whole structure at a time), so the level raiser must be trying to
678 // store into the first field. Check for this and allow it now:
680 if (const StructType *SElTy = dyn_cast<StructType>(ElTy)) {
682 std::vector<Value*> Indices;
683 ElTy = getStructOffsetType(ElTy, Offset, Indices, false);
684 assert(Offset == 0 && "Offset changed!");
685 if (ElTy == 0) // Element at offset zero in struct doesn't exist!
686 return false; // Can only happen for {}*
688 if (ElTy == Ty) // Looks like the 0th element of structure is
689 return true; // compatible! Accept now!
691 // Otherwise we know that we can't work, so just stop trying now.
696 // Can convert the store if we can convert the pointer operand to match
697 // the new value type...
698 return ExpressionConvertableToType(I->getOperand(1), PointerType::get(Ty),
700 } else if (const PointerType *PT = dyn_cast<PointerType>(Ty)) {
701 const Type *ElTy = PT->getElementType();
702 assert(V == I->getOperand(1));
704 if (isa<StructType>(ElTy)) {
705 // We can change the destination pointer if we can store our first
706 // argument into the first element of the structure...
709 std::vector<Value*> Indices;
710 ElTy = getStructOffsetType(ElTy, Offset, Indices, false);
711 assert(Offset == 0 && "Offset changed!");
712 if (ElTy == 0) // Element at offset zero in struct doesn't exist!
713 return false; // Can only happen for {}*
716 // Must move the same amount of data...
717 if (!ElTy->isSized() ||
718 TD.getTypeSize(ElTy) != TD.getTypeSize(I->getOperand(0)->getType()))
721 // Can convert store if the incoming value is convertable...
722 return ExpressionConvertableToType(I->getOperand(0), ElTy, CTMap);
727 case Instruction::GetElementPtr:
728 if (V != I->getOperand(0) || !isa<PointerType>(Ty)) return false;
730 // If we have a two operand form of getelementptr, this is really little
731 // more than a simple addition. As with addition, check to see if the
732 // getelementptr instruction can be changed to index into the new type.
734 if (I->getNumOperands() == 2) {
735 const Type *OldElTy = cast<PointerType>(I->getType())->getElementType();
736 unsigned DataSize = TD.getTypeSize(OldElTy);
737 Value *Index = I->getOperand(1);
738 Instruction *TempScale = 0;
740 // If the old data element is not unit sized, we have to create a scale
741 // instruction so that ConvertableToGEP will know the REAL amount we are
742 // indexing by. Note that this is never inserted into the instruction
743 // stream, so we have to delete it when we're done.
746 TempScale = BinaryOperator::create(Instruction::Mul, Index,
747 ConstantSInt::get(Type::LongTy,
752 // Check to see if the second argument is an expression that can
753 // be converted to the appropriate size... if so, allow it.
755 std::vector<Value*> Indices;
756 const Type *ElTy = ConvertableToGEP(Ty, Index, Indices);
757 delete TempScale; // Free our temporary multiply if we made it
759 if (ElTy == 0) return false; // Cannot make conversion...
760 return ValueConvertableToType(I, PointerType::get(ElTy), CTMap);
764 case Instruction::PHINode: {
765 PHINode *PN = cast<PHINode>(I);
766 for (unsigned i = 0; i < PN->getNumIncomingValues(); ++i)
767 if (!ExpressionConvertableToType(PN->getIncomingValue(i), Ty, CTMap))
769 return ValueConvertableToType(PN, Ty, CTMap);
772 case Instruction::Call: {
773 User::op_iterator OI = find(I->op_begin(), I->op_end(), V);
774 assert (OI != I->op_end() && "Not using value!");
775 unsigned OpNum = OI - I->op_begin();
777 // Are we trying to change the function pointer value to a new type?
779 const PointerType *PTy = dyn_cast<PointerType>(Ty);
780 if (PTy == 0) return false; // Can't convert to a non-pointer type...
781 const FunctionType *FTy = dyn_cast<FunctionType>(PTy->getElementType());
782 if (FTy == 0) return false; // Can't convert to a non ptr to function...
784 // Do not allow converting to a call where all of the operands are ...'s
785 if (FTy->getNumParams() == 0 && FTy->isVarArg())
786 return false; // Do not permit this conversion!
788 // Perform sanity checks to make sure that new function type has the
789 // correct number of arguments...
791 unsigned NumArgs = I->getNumOperands()-1; // Don't include function ptr
793 // Cannot convert to a type that requires more fixed arguments than
794 // the call provides...
796 if (NumArgs < FTy->getNumParams()) return false;
798 // Unless this is a vararg function type, we cannot provide more arguments
799 // than are desired...
801 if (!FTy->isVarArg() && NumArgs > FTy->getNumParams())
804 // Okay, at this point, we know that the call and the function type match
805 // number of arguments. Now we see if we can convert the arguments
806 // themselves. Note that we do not require operands to be convertable,
807 // we can insert casts if they are convertible but not compatible. The
808 // reason for this is that we prefer to have resolved functions but casted
809 // arguments if possible.
811 const FunctionType::ParamTypes &PTs = FTy->getParamTypes();
812 for (unsigned i = 0, NA = PTs.size(); i < NA; ++i)
813 if (!PTs[i]->isLosslesslyConvertableTo(I->getOperand(i+1)->getType()))
814 return false; // Operands must have compatible types!
816 // Okay, at this point, we know that all of the arguments can be
817 // converted. We succeed if we can change the return type if
820 return ValueConvertableToType(I, FTy->getReturnType(), CTMap);
823 const PointerType *MPtr = cast<PointerType>(I->getOperand(0)->getType());
824 const FunctionType *FTy = cast<FunctionType>(MPtr->getElementType());
825 if (!FTy->isVarArg()) return false;
827 if ((OpNum-1) < FTy->getParamTypes().size())
828 return false; // It's not in the varargs section...
830 // If we get this far, we know the value is in the varargs section of the
831 // function! We can convert if we don't reinterpret the value...
833 return Ty->isLosslesslyConvertableTo(V->getType());
840 void ConvertValueToNewType(Value *V, Value *NewVal, ValueMapCache &VMC) {
841 ValueHandle VH(VMC, V);
843 unsigned NumUses = V->use_size();
844 for (unsigned It = 0; It < NumUses; ) {
845 unsigned OldSize = NumUses;
846 ConvertOperandToType(*(V->use_begin()+It), V, NewVal, VMC);
847 NumUses = V->use_size();
848 if (NumUses == OldSize) ++It;
854 static void ConvertOperandToType(User *U, Value *OldVal, Value *NewVal,
855 ValueMapCache &VMC) {
856 if (isa<ValueHandle>(U)) return; // Valuehandles don't let go of operands...
858 if (VMC.OperandsMapped.count(U)) return;
859 VMC.OperandsMapped.insert(U);
861 ValueMapCache::ExprMapTy::iterator VMCI = VMC.ExprMap.find(U);
862 if (VMCI != VMC.ExprMap.end())
866 Instruction *I = cast<Instruction>(U); // Only Instructions convertable
868 BasicBlock *BB = I->getParent();
869 assert(BB != 0 && "Instruction not embedded in basic block!");
870 std::string Name = I->getName();
872 Instruction *Res; // Result of conversion
874 //cerr << endl << endl << "Type:\t" << Ty << "\nInst: " << I << "BB Before: " << BB << endl;
876 // Prevent I from being removed...
877 ValueHandle IHandle(VMC, I);
879 const Type *NewTy = NewVal->getType();
880 Constant *Dummy = (NewTy != Type::VoidTy) ?
881 Constant::getNullValue(NewTy) : 0;
883 switch (I->getOpcode()) {
884 case Instruction::Cast:
885 if (VMC.NewCasts.count(ValueHandle(VMC, I))) {
886 // This cast has already had it's value converted, causing a new cast to
887 // be created. We don't want to create YET ANOTHER cast instruction
888 // representing the original one, so just modify the operand of this cast
889 // instruction, which we know is newly created.
890 I->setOperand(0, NewVal);
891 I->setName(Name); // give I its name back
895 Res = new CastInst(NewVal, I->getType(), Name);
899 case Instruction::Add:
900 if (isa<PointerType>(NewTy)) {
901 Value *IndexVal = I->getOperand(OldVal == I->getOperand(0) ? 1 : 0);
902 std::vector<Value*> Indices;
903 BasicBlock::iterator It = I;
905 if (const Type *ETy = ConvertableToGEP(NewTy, IndexVal, Indices, &It)) {
906 // If successful, convert the add to a GEP
907 //const Type *RetTy = PointerType::get(ETy);
908 // First operand is actually the given pointer...
909 Res = new GetElementPtrInst(NewVal, Indices, Name);
910 assert(cast<PointerType>(Res->getType())->getElementType() == ETy &&
911 "ConvertableToGEP broken!");
917 case Instruction::Sub:
918 case Instruction::SetEQ:
919 case Instruction::SetNE: {
920 Res = BinaryOperator::create(cast<BinaryOperator>(I)->getOpcode(),
922 VMC.ExprMap[I] = Res; // Add node to expression eagerly
924 unsigned OtherIdx = (OldVal == I->getOperand(0)) ? 1 : 0;
925 Value *OtherOp = I->getOperand(OtherIdx);
926 Value *NewOther = ConvertExpressionToType(OtherOp, NewTy, VMC);
928 Res->setOperand(OtherIdx, NewOther);
929 Res->setOperand(!OtherIdx, NewVal);
932 case Instruction::Shl:
933 case Instruction::Shr:
934 assert(I->getOperand(0) == OldVal);
935 Res = new ShiftInst(cast<ShiftInst>(I)->getOpcode(), NewVal,
936 I->getOperand(1), Name);
939 case Instruction::Free: // Free can free any pointer type!
940 assert(I->getOperand(0) == OldVal);
941 Res = new FreeInst(NewVal);
945 case Instruction::Load: {
946 assert(I->getOperand(0) == OldVal && isa<PointerType>(NewVal->getType()));
947 const Type *LoadedTy =
948 cast<PointerType>(NewVal->getType())->getElementType();
952 if (const CompositeType *CT = dyn_cast<CompositeType>(LoadedTy)) {
953 std::vector<Value*> Indices;
954 Indices.push_back(ConstantSInt::get(Type::LongTy, 0));
956 unsigned Offset = 0; // No offset, get first leaf.
957 LoadedTy = getStructOffsetType(CT, Offset, Indices, false);
958 assert(LoadedTy->isFirstClassType());
960 if (Indices.size() != 1) { // Do not generate load X, 0
961 // Insert the GEP instruction before this load.
962 Src = new GetElementPtrInst(Src, Indices, Name+".idx", I);
966 Res = new LoadInst(Src, Name);
967 assert(Res->getType()->isFirstClassType() && "Load of structure or array!");
971 case Instruction::Store: {
972 if (I->getOperand(0) == OldVal) { // Replace the source value
973 // Check to see if operand #1 has already been converted...
974 ValueMapCache::ExprMapTy::iterator VMCI =
975 VMC.ExprMap.find(I->getOperand(1));
976 if (VMCI != VMC.ExprMap.end()) {
977 // Comments describing this stuff are in the OperandConvertableToType
978 // switch statement for Store...
981 cast<PointerType>(VMCI->second->getType())->getElementType();
983 Value *SrcPtr = VMCI->second;
986 // We check that this is a struct in the initial scan...
987 const StructType *SElTy = cast<StructType>(ElTy);
989 std::vector<Value*> Indices;
990 Indices.push_back(Constant::getNullValue(Type::LongTy));
993 const Type *Ty = getStructOffsetType(ElTy, Offset, Indices, false);
994 assert(Offset == 0 && "Offset changed!");
995 assert(NewTy == Ty && "Did not convert to correct type!");
997 // Insert the GEP instruction before this store.
998 SrcPtr = new GetElementPtrInst(SrcPtr, Indices,
999 SrcPtr->getName()+".idx", I);
1001 Res = new StoreInst(NewVal, SrcPtr);
1003 VMC.ExprMap[I] = Res;
1005 // Otherwise, we haven't converted Operand #1 over yet...
1006 const PointerType *NewPT = PointerType::get(NewTy);
1007 Res = new StoreInst(NewVal, Constant::getNullValue(NewPT));
1008 VMC.ExprMap[I] = Res;
1009 Res->setOperand(1, ConvertExpressionToType(I->getOperand(1),
1012 } else { // Replace the source pointer
1013 const Type *ValTy = cast<PointerType>(NewTy)->getElementType();
1015 Value *SrcPtr = NewVal;
1017 if (isa<StructType>(ValTy)) {
1018 std::vector<Value*> Indices;
1019 Indices.push_back(Constant::getNullValue(Type::LongTy));
1021 unsigned Offset = 0;
1022 ValTy = getStructOffsetType(ValTy, Offset, Indices, false);
1024 assert(Offset == 0 && ValTy);
1026 // Insert the GEP instruction before this store.
1027 SrcPtr = new GetElementPtrInst(SrcPtr, Indices,
1028 SrcPtr->getName()+".idx", I);
1031 Res = new StoreInst(Constant::getNullValue(ValTy), SrcPtr);
1032 VMC.ExprMap[I] = Res;
1033 Res->setOperand(0, ConvertExpressionToType(I->getOperand(0), ValTy, VMC));
1039 case Instruction::GetElementPtr: {
1040 // Convert a one index getelementptr into just about anything that is
1043 BasicBlock::iterator It = I;
1044 const Type *OldElTy = cast<PointerType>(I->getType())->getElementType();
1045 unsigned DataSize = TD.getTypeSize(OldElTy);
1046 Value *Index = I->getOperand(1);
1048 if (DataSize != 1) {
1049 // Insert a multiply of the old element type is not a unit size...
1050 Index = BinaryOperator::create(Instruction::Mul, Index,
1051 ConstantSInt::get(Type::LongTy, DataSize),
1055 // Perform the conversion now...
1057 std::vector<Value*> Indices;
1058 const Type *ElTy = ConvertableToGEP(NewVal->getType(), Index, Indices, &It);
1059 assert(ElTy != 0 && "GEP Conversion Failure!");
1060 Res = new GetElementPtrInst(NewVal, Indices, Name);
1061 assert(Res->getType() == PointerType::get(ElTy) &&
1062 "ConvertableToGet failed!");
1065 if (I->getType() == PointerType::get(Type::SByteTy)) {
1066 // Convert a getelementptr sbyte * %reg111, uint 16 freely back to
1067 // anything that is a pointer type...
1069 BasicBlock::iterator It = I;
1071 // Check to see if the second argument is an expression that can
1072 // be converted to the appropriate size... if so, allow it.
1074 std::vector<Value*> Indices;
1075 const Type *ElTy = ConvertableToGEP(NewVal->getType(), I->getOperand(1),
1077 assert(ElTy != 0 && "GEP Conversion Failure!");
1079 Res = new GetElementPtrInst(NewVal, Indices, Name);
1081 // Convert a getelementptr ulong * %reg123, uint %N
1082 // to getelementptr long * %reg123, uint %N
1083 // ... where the type must simply stay the same size...
1085 GetElementPtrInst *GEP = cast<GetElementPtrInst>(I);
1086 std::vector<Value*> Indices(GEP->idx_begin(), GEP->idx_end());
1087 Res = new GetElementPtrInst(NewVal, Indices, Name);
1092 case Instruction::PHINode: {
1093 PHINode *OldPN = cast<PHINode>(I);
1094 PHINode *NewPN = new PHINode(NewTy, Name);
1095 VMC.ExprMap[I] = NewPN;
1097 while (OldPN->getNumOperands()) {
1098 BasicBlock *BB = OldPN->getIncomingBlock(0);
1099 Value *OldVal = OldPN->getIncomingValue(0);
1100 OldPN->removeIncomingValue(BB, false);
1101 Value *V = ConvertExpressionToType(OldVal, NewTy, VMC);
1102 NewPN->addIncoming(V, BB);
1108 case Instruction::Call: {
1109 Value *Meth = I->getOperand(0);
1110 std::vector<Value*> Params(I->op_begin()+1, I->op_end());
1112 if (Meth == OldVal) { // Changing the function pointer?
1113 const PointerType *NewPTy = cast<PointerType>(NewVal->getType());
1114 const FunctionType *NewTy = cast<FunctionType>(NewPTy->getElementType());
1115 const FunctionType::ParamTypes &PTs = NewTy->getParamTypes();
1117 // Get an iterator to the call instruction so that we can insert casts for
1118 // operands if needbe. Note that we do not require operands to be
1119 // convertable, we can insert casts if they are convertible but not
1120 // compatible. The reason for this is that we prefer to have resolved
1121 // functions but casted arguments if possible.
1123 BasicBlock::iterator It = I;
1125 // Convert over all of the call operands to their new types... but only
1126 // convert over the part that is not in the vararg section of the call.
1128 for (unsigned i = 0; i < PTs.size(); ++i)
1129 if (Params[i]->getType() != PTs[i]) {
1130 // Create a cast to convert it to the right type, we know that this
1131 // is a lossless cast...
1133 Params[i] = new CastInst(Params[i], PTs[i], "callarg.cast." +
1134 Params[i]->getName(), It);
1136 Meth = NewVal; // Update call destination to new value
1138 } else { // Changing an argument, must be in vararg area
1139 std::vector<Value*>::iterator OI =
1140 find(Params.begin(), Params.end(), OldVal);
1141 assert (OI != Params.end() && "Not using value!");
1146 Res = new CallInst(Meth, Params, Name);
1150 assert(0 && "Expression convertable, but don't know how to convert?");
1154 // If the instruction was newly created, insert it into the instruction
1157 BasicBlock::iterator It = I;
1158 assert(It != BB->end() && "Instruction not in own basic block??");
1159 BB->getInstList().insert(It, Res); // Keep It pointing to old instruction
1161 DEBUG(cerr << "COT CREATED: " << (void*)Res << " " << Res
1162 << "In: " << (void*)I << " " << I << "Out: " << (void*)Res
1165 // Add the instruction to the expression map
1166 VMC.ExprMap[I] = Res;
1168 if (I->getType() != Res->getType())
1169 ConvertValueToNewType(I, Res, VMC);
1171 for (unsigned It = 0; It < I->use_size(); ) {
1172 User *Use = *(I->use_begin()+It);
1173 if (isa<ValueHandle>(Use)) // Don't remove ValueHandles!
1176 Use->replaceUsesOfWith(I, Res);
1179 for (Value::use_iterator UI = I->use_begin(), UE = I->use_end();
1181 assert(isa<ValueHandle>((Value*)*UI) &&"Uses of Instruction remain!!!");
1186 ValueHandle::ValueHandle(ValueMapCache &VMC, Value *V)
1187 : Instruction(Type::VoidTy, UserOp1, ""), Cache(VMC) {
1188 //DEBUG(cerr << "VH AQUIRING: " << (void*)V << " " << V);
1189 Operands.push_back(Use(V, this));
1192 ValueHandle::ValueHandle(const ValueHandle &VH)
1193 : Instruction(Type::VoidTy, UserOp1, ""), Cache(VH.Cache) {
1194 //DEBUG(cerr << "VH AQUIRING: " << (void*)V << " " << V);
1195 Operands.push_back(Use((Value*)VH.getOperand(0), this));
1198 static void RecursiveDelete(ValueMapCache &Cache, Instruction *I) {
1199 if (!I || !I->use_empty()) return;
1201 assert(I->getParent() && "Inst not in basic block!");
1203 //DEBUG(cerr << "VH DELETING: " << (void*)I << " " << I);
1205 for (User::op_iterator OI = I->op_begin(), OE = I->op_end();
1207 if (Instruction *U = dyn_cast<Instruction>(OI->get())) {
1209 RecursiveDelete(Cache, U);
1212 I->getParent()->getInstList().remove(I);
1214 Cache.OperandsMapped.erase(I);
1215 Cache.ExprMap.erase(I);
1219 ValueHandle::~ValueHandle() {
1220 if (Operands[0]->use_size() == 1) {
1221 Value *V = Operands[0];
1222 Operands[0] = 0; // Drop use!
1224 // Now we just need to remove the old instruction so we don't get infinite
1225 // loops. Note that we cannot use DCE because DCE won't remove a store
1226 // instruction, for example.
1228 RecursiveDelete(Cache, dyn_cast<Instruction>(V));
1230 //DEBUG(cerr << "VH RELEASING: " << (void*)Operands[0].get() << " "
1231 // << Operands[0]->use_size() << " " << Operands[0]);