Refactor code a little bit, eliminating the gratuitous InstVisitor, which
[oota-llvm.git] / lib / Transforms / TransformInternals.cpp
1 //===- TransformInternals.cpp - Implement shared functions for transforms -===//
2 // 
3 //                     The LLVM Compiler Infrastructure
4 //
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.
7 // 
8 //===----------------------------------------------------------------------===//
9 //
10 //  This file defines shared functions used by the different components of the
11 //  Transforms library.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #include "TransformInternals.h"
16 #include "llvm/Type.h"
17 #include "llvm/Analysis/Expressions.h"
18 #include "llvm/Function.h"
19 #include "llvm/iOther.h"
20
21 namespace llvm {
22
23 static const Type *getStructOffsetStep(const StructType *STy, uint64_t &Offset,
24                                        std::vector<Value*> &Indices,
25                                        const TargetData &TD) {
26   assert(Offset < TD.getTypeSize(STy) && "Offset not in composite!");
27   const StructLayout *SL = TD.getStructLayout(STy);
28
29   // This loop terminates always on a 0 <= i < MemberOffsets.size()
30   unsigned i;
31   for (i = 0; i < SL->MemberOffsets.size()-1; ++i)
32     if (Offset >= SL->MemberOffsets[i] && Offset < SL->MemberOffsets[i+1])
33       break;
34   
35   assert(Offset >= SL->MemberOffsets[i] &&
36          (i == SL->MemberOffsets.size()-1 || Offset < SL->MemberOffsets[i+1]));
37   
38   // Make sure to save the current index...
39   Indices.push_back(ConstantUInt::get(Type::UByteTy, i));
40   Offset = SL->MemberOffsets[i];
41   return STy->getContainedType(i);
42 }
43
44
45 // getStructOffsetType - Return a vector of offsets that are to be used to index
46 // into the specified struct type to get as close as possible to index as we
47 // can.  Note that it is possible that we cannot get exactly to Offset, in which
48 // case we update offset to be the offset we actually obtained.  The resultant
49 // leaf type is returned.
50 //
51 // If StopEarly is set to true (the default), the first object with the
52 // specified type is returned, even if it is a struct type itself.  In this
53 // case, this routine will not drill down to the leaf type.  Set StopEarly to
54 // false if you want a leaf
55 //
56 const Type *getStructOffsetType(const Type *Ty, unsigned &Offset,
57                                 std::vector<Value*> &Indices,
58                                 const TargetData &TD, bool StopEarly) {
59   if (Offset == 0 && StopEarly && !Indices.empty())
60     return Ty;    // Return the leaf type
61
62   uint64_t ThisOffset;
63   const Type *NextType;
64   if (const StructType *STy = dyn_cast<StructType>(Ty)) {
65     if (STy->getElementTypes().empty()) {
66       Offset = 0;
67       return STy;
68     }
69
70     ThisOffset = Offset;
71     NextType = getStructOffsetStep(STy, ThisOffset, Indices, TD);
72   } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
73     assert(Offset == 0 || Offset < TD.getTypeSize(ATy) &&
74            "Offset not in composite!");
75
76     NextType = ATy->getElementType();
77     unsigned ChildSize = TD.getTypeSize(NextType);
78     Indices.push_back(ConstantSInt::get(Type::LongTy, Offset/ChildSize));
79     ThisOffset = (Offset/ChildSize)*ChildSize;
80   } else {
81     Offset = 0;   // Return the offset that we were able to achieve
82     return Ty;    // Return the leaf type
83   }
84
85   unsigned SubOffs = Offset - ThisOffset;
86   const Type *LeafTy = getStructOffsetType(NextType, SubOffs,
87                                            Indices, TD, StopEarly);
88   Offset = ThisOffset + SubOffs;
89   return LeafTy;
90 }
91
92 // ConvertibleToGEP - This function returns true if the specified value V is
93 // a valid index into a pointer of type Ty.  If it is valid, Idx is filled in
94 // with the values that would be appropriate to make this a getelementptr
95 // instruction.  The type returned is the root type that the GEP would point to
96 //
97 const Type *ConvertibleToGEP(const Type *Ty, Value *OffsetVal,
98                              std::vector<Value*> &Indices,
99                              const TargetData &TD,
100                              BasicBlock::iterator *BI) {
101   const CompositeType *CompTy = dyn_cast<CompositeType>(Ty);
102   if (CompTy == 0) return 0;
103
104   // See if the cast is of an integer expression that is either a constant,
105   // or a value scaled by some amount with a possible offset.
106   //
107   ExprType Expr = ClassifyExpression(OffsetVal);
108
109   // Get the offset and scale values if they exists...
110   // A scale of zero with Expr.Var != 0 means a scale of 1.
111   //
112   int64_t Offset = Expr.Offset ? getConstantValue(Expr.Offset) : 0;
113   int64_t Scale  = Expr.Scale  ? getConstantValue(Expr.Scale)  : 0;
114
115   if (Expr.Var && Scale == 0) Scale = 1;   // Scale != 0 if Expr.Var != 0
116  
117   // Loop over the Scale and Offset values, filling in the Indices vector for
118   // our final getelementptr instruction.
119   //
120   const Type *NextTy = CompTy;
121   do {
122     if (!isa<CompositeType>(NextTy))
123       return 0;  // Type must not be ready for processing...
124     CompTy = cast<CompositeType>(NextTy);
125
126     if (const StructType *StructTy = dyn_cast<StructType>(CompTy)) {
127       // Step into the appropriate element of the structure...
128       uint64_t ActualOffset = (Offset < 0) ? 0 : (uint64_t)Offset;
129       NextTy = getStructOffsetStep(StructTy, ActualOffset, Indices, TD);
130       Offset -= ActualOffset;
131     } else {
132       const Type *ElTy = cast<SequentialType>(CompTy)->getElementType();
133       if (!ElTy->isSized() || (isa<PointerType>(CompTy) && !Indices.empty()))
134         return 0; // Type is unreasonable... escape!
135       unsigned ElSize = TD.getTypeSize(ElTy);
136       if (ElSize == 0) return 0;   // Avoid division by zero...
137       int64_t ElSizeS = ElSize;
138
139       // See if the user is indexing into a different cell of this array...
140       if (Scale && (Scale >= ElSizeS || -Scale >= ElSizeS)) {
141         // A scale n*ElSize might occur if we are not stepping through
142         // array by one.  In this case, we will have to insert math to munge
143         // the index.
144         //
145         int64_t ScaleAmt = Scale/ElSizeS;
146         if (Scale-ScaleAmt*ElSizeS)
147           return 0;  // Didn't scale by a multiple of element size, bail out
148         Scale = 0;   // Scale is consumed
149
150         int64_t Index = Offset/ElSize;        // is zero unless Offset > ElSize
151         Offset -= Index*ElSize;               // Consume part of the offset
152
153         if (BI) {              // Generate code?
154           BasicBlock *BB = (*BI)->getParent();
155           if (Expr.Var->getType() != Type::LongTy)
156             Expr.Var = new CastInst(Expr.Var, Type::LongTy,
157                                     Expr.Var->getName()+"-idxcast", *BI);
158
159           if (ScaleAmt && ScaleAmt != 1) {
160             // If we have to scale up our index, do so now
161             Value *ScaleAmtVal = ConstantSInt::get(Type::LongTy, ScaleAmt);
162             Expr.Var = BinaryOperator::create(Instruction::Mul, Expr.Var,
163                                               ScaleAmtVal,
164                                               Expr.Var->getName()+"-scale",*BI);
165           }
166
167           if (Index) {  // Add an offset to the index
168             Value *IndexAmt = ConstantSInt::get(Type::LongTy, Index);
169             Expr.Var = BinaryOperator::create(Instruction::Add, Expr.Var,
170                                               IndexAmt,
171                                               Expr.Var->getName()+"-offset",
172                                               *BI);
173           }
174         }
175
176         Indices.push_back(Expr.Var);
177         Expr.Var = 0;
178       } else if (Offset >= (int64_t)ElSize || -Offset >= (int64_t)ElSize) {
179         // Calculate the index that we are entering into the array cell with
180         uint64_t Index = Offset/ElSize;
181         Indices.push_back(ConstantSInt::get(Type::LongTy, Index));
182         Offset -= (int64_t)(Index*ElSize);        // Consume part of the offset
183
184       } else if (isa<ArrayType>(CompTy) || Indices.empty()) {
185         // Must be indexing a small amount into the first cell of the array
186         // Just index into element zero of the array here.
187         //
188         Indices.push_back(ConstantSInt::get(Type::LongTy, 0));
189       } else {
190         return 0;  // Hrm. wierd, can't handle this case.  Bail
191       }
192       NextTy = ElTy;
193     }
194   } while (Offset || Scale);    // Go until we're done!
195
196   return NextTy;
197 }
198
199 } // End llvm namespace