1 //===-- TransformInternals.cpp - Implement shared functions for transforms --=//
3 // This file defines shared functions used by the different components of the
6 //===----------------------------------------------------------------------===//
8 #include "TransformInternals.h"
9 #include "llvm/Method.h"
10 #include "llvm/Type.h"
11 #include "llvm/ConstantVals.h"
12 #include "llvm/Analysis/Expressions.h"
13 #include "llvm/iOther.h"
15 // TargetData Hack: Eventually we will have annotations given to us by the
16 // backend so that we know stuff about type size and alignments. For now
17 // though, just use this, because it happens to match the model that GCC uses.
19 const TargetData TD("LevelRaise: Should be GCC though!");
21 // ReplaceInstWithValue - Replace all uses of an instruction (specified by BI)
22 // with a value, then remove and delete the original instruction.
24 void ReplaceInstWithValue(BasicBlock::InstListType &BIL,
25 BasicBlock::iterator &BI, Value *V) {
27 // Replaces all of the uses of the instruction with uses of the value
28 I->replaceAllUsesWith(V);
30 // Remove the unneccesary instruction now...
33 // Make sure to propogate a name if there is one already...
34 if (I->hasName() && !V->hasName())
35 V->setName(I->getName(), BIL.getParent()->getSymbolTable());
37 // Remove the dead instruction now...
42 // ReplaceInstWithInst - Replace the instruction specified by BI with the
43 // instruction specified by I. The original instruction is deleted and BI is
44 // updated to point to the new instruction.
46 void ReplaceInstWithInst(BasicBlock::InstListType &BIL,
47 BasicBlock::iterator &BI, Instruction *I) {
48 assert(I->getParent() == 0 &&
49 "ReplaceInstWithInst: Instruction already inserted into basic block!");
51 // Insert the new instruction into the basic block...
52 BI = BIL.insert(BI, I)+1;
54 // Replace all uses of the old instruction, and delete it.
55 ReplaceInstWithValue(BIL, BI, I);
57 // Reexamine the instruction just inserted next time around the cleanup pass
63 // getStructOffsetType - Return a vector of offsets that are to be used to index
64 // into the specified struct type to get as close as possible to index as we
65 // can. Note that it is possible that we cannot get exactly to Offset, in which
66 // case we update offset to be the offset we actually obtained. The resultant
67 // leaf type is returned.
69 // If StopEarly is set to true (the default), the first object with the
70 // specified type is returned, even if it is a struct type itself. In this
71 // case, this routine will not drill down to the leaf type. Set StopEarly to
72 // false if you want a leaf
74 const Type *getStructOffsetType(const Type *Ty, unsigned &Offset,
75 vector<Value*> &Offsets,
76 bool StopEarly = true) {
77 if (!isa<CompositeType>(Ty) ||
78 (Offset == 0 && StopEarly && !Offsets.empty())) {
79 Offset = 0; // Return the offset that we were able to acheive
80 return Ty; // Return the leaf type
85 if (const StructType *STy = dyn_cast<StructType>(Ty)) {
86 assert(Offset < TD.getTypeSize(Ty) && "Offset not in composite!");
87 const StructLayout *SL = TD.getStructLayout(STy);
89 // This loop terminates always on a 0 <= i < MemberOffsets.size()
91 for (i = 0; i < SL->MemberOffsets.size()-1; ++i)
92 if (Offset >= SL->MemberOffsets[i] && Offset < SL->MemberOffsets[i+1])
95 assert(Offset >= SL->MemberOffsets[i] &&
96 (i == SL->MemberOffsets.size()-1 || Offset <SL->MemberOffsets[i+1]));
98 // Make sure to save the current index...
99 Offsets.push_back(ConstantUInt::get(Type::UByteTy, i));
100 ThisOffset = SL->MemberOffsets[i];
101 NextType = STy->getElementTypes()[i];
103 const ArrayType *ATy = cast<ArrayType>(Ty);
104 assert(ATy->isUnsized() || Offset < TD.getTypeSize(Ty) &&
105 "Offset not in composite!");
107 NextType = ATy->getElementType();
108 unsigned ChildSize = TD.getTypeSize(NextType);
109 Offsets.push_back(ConstantUInt::get(Type::UIntTy, Offset/ChildSize));
110 ThisOffset = (Offset/ChildSize)*ChildSize;
113 unsigned SubOffs = Offset - ThisOffset;
114 const Type *LeafTy = getStructOffsetType(NextType, SubOffs, Offsets);
115 Offset = ThisOffset + SubOffs;
119 // ConvertableToGEP - This function returns true if the specified value V is
120 // a valid index into a pointer of type Ty. If it is valid, Idx is filled in
121 // with the values that would be appropriate to make this a getelementptr
122 // instruction. The type returned is the root type that the GEP would point to
124 const Type *ConvertableToGEP(const Type *Ty, Value *OffsetVal,
125 vector<Value*> &Indices,
126 BasicBlock::iterator *BI = 0) {
127 const CompositeType *CompTy = getPointedToComposite(Ty);
128 if (CompTy == 0) return 0;
130 // See if the cast is of an integer expression that is either a constant,
131 // or a value scaled by some amount with a possible offset.
133 analysis::ExprType Expr = analysis::ClassifyExpression(OffsetVal);
135 // The expression must either be a constant, or a scaled index to be useful
136 if (!Expr.Offset && !Expr.Scale)
139 // Get the offset and scale now...
140 unsigned Offset = 0, Scale = Expr.Var != 0;
142 // Get the offset value if it exists...
144 int Val = getConstantValue(Expr.Offset);
145 if (Val < 0) return false; // Don't mess with negative offsets
146 Offset = (unsigned)Val;
149 // Get the scale value if it exists...
151 int Val = getConstantValue(Expr.Scale);
152 if (Val < 0) return false; // Don't mess with negative scales
153 Scale = (unsigned)Val;
156 // Check to make sure the offset is not negative or really large, outside the
157 // scope of this structure...
159 if (!isa<ArrayType>(CompTy) || cast<ArrayType>(CompTy)->isSized())
160 if (Offset >= TD.getTypeSize(CompTy))
163 // Loop over the Scale and Offset values, filling in the Indices vector for
164 // our final getelementptr instruction.
166 const Type *NextTy = CompTy;
168 if (!isa<CompositeType>(NextTy))
169 return 0; // Type must not be ready for processing...
170 CompTy = cast<CompositeType>(NextTy);
172 if (const StructType *StructTy = dyn_cast<StructType>(CompTy)) {
173 const StructLayout *SL = TD.getStructLayout(StructTy);
174 unsigned ActualOffset = Offset;
175 NextTy = getStructOffsetType(StructTy, ActualOffset, Indices);
176 Offset -= ActualOffset;
178 const ArrayType *AT = cast<ArrayType>(CompTy);
179 const Type *ElTy = AT->getElementType();
180 unsigned ElSize = TD.getTypeSize(ElTy);
182 // See if the user is indexing into a different cell of this array...
183 if (Offset >= ElSize) {
184 // Calculate the index that we are entering into the array cell with
185 unsigned Index = Offset/ElSize;
186 Indices.push_back(ConstantUInt::get(Type::UIntTy, Index));
187 Offset -= Index*ElSize; // Consume part of the offset
189 } else if (Scale && Scale != 1) {
190 // Must be indexing into this element with a variable...
192 return 0; // Type must not be finished yet...
194 if (Expr.Var->getType() != Type::UIntTy && BI) {
195 BasicBlock *BB = (**BI)->getParent();
196 CastInst *IdxCast = new CastInst(Expr.Var, Type::UIntTy);
197 *BI = BB->getInstList().insert(*BI, IdxCast)+1;
201 Indices.push_back(Expr.Var);
202 Scale = 0; // Consume scale factor!
204 // Must be indexing a small amount into the first cell of the array
205 // Just index into element zero of the array here.
207 Indices.push_back(ConstantUInt::get(Type::UIntTy, 0));
211 } while (Offset || Scale); // Go until we're done!