Adjust to the changed StructType interface. In particular, getElementTypes() is...
[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 using namespace llvm;
21
22 static const Type *getStructOffsetStep(const StructType *STy, uint64_t &Offset,
23                                        std::vector<Value*> &Indices,
24                                        const TargetData &TD) {
25   assert(Offset < TD.getTypeSize(STy) && "Offset not in composite!");
26   const StructLayout *SL = TD.getStructLayout(STy);
27
28   // This loop terminates always on a 0 <= i < MemberOffsets.size()
29   unsigned i;
30   for (i = 0; i < SL->MemberOffsets.size()-1; ++i)
31     if (Offset >= SL->MemberOffsets[i] && Offset < SL->MemberOffsets[i+1])
32       break;
33   
34   assert(Offset >= SL->MemberOffsets[i] &&
35          (i == SL->MemberOffsets.size()-1 || Offset < SL->MemberOffsets[i+1]));
36   
37   // Make sure to save the current index...
38   // FIXME for PR82
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 *llvm::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->getNumElements()) {
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     // FIXME for PR82
79     Indices.push_back(ConstantSInt::get(Type::LongTy, Offset/ChildSize));
80     ThisOffset = (Offset/ChildSize)*ChildSize;
81   } else {
82     Offset = 0;   // Return the offset that we were able to achieve
83     return Ty;    // Return the leaf type
84   }
85
86   unsigned SubOffs = Offset - ThisOffset;
87   const Type *LeafTy = getStructOffsetType(NextType, SubOffs,
88                                            Indices, TD, StopEarly);
89   Offset = ThisOffset + SubOffs;
90   return LeafTy;
91 }
92
93 // ConvertibleToGEP - This function returns true if the specified value V is
94 // a valid index into a pointer of type Ty.  If it is valid, Idx is filled in
95 // with the values that would be appropriate to make this a getelementptr
96 // instruction.  The type returned is the root type that the GEP would point to
97 //
98 const Type *llvm::ConvertibleToGEP(const Type *Ty, Value *OffsetVal,
99                                    std::vector<Value*> &Indices,
100                                    const TargetData &TD,
101                                    BasicBlock::iterator *BI) {
102   const CompositeType *CompTy = dyn_cast<CompositeType>(Ty);
103   if (CompTy == 0) return 0;
104
105   // See if the cast is of an integer expression that is either a constant,
106   // or a value scaled by some amount with a possible offset.
107   //
108   ExprType Expr = ClassifyExpr(OffsetVal);
109
110   // Get the offset and scale values if they exists...
111   // A scale of zero with Expr.Var != 0 means a scale of 1.
112   //
113   int64_t Offset = Expr.Offset ? getConstantValue(Expr.Offset) : 0;
114   int64_t Scale  = Expr.Scale  ? getConstantValue(Expr.Scale)  : 0;
115
116   if (Expr.Var && Scale == 0) Scale = 1;   // Scale != 0 if Expr.Var != 0
117  
118   // Loop over the Scale and Offset values, filling in the Indices vector for
119   // our final getelementptr instruction.
120   //
121   const Type *NextTy = CompTy;
122   do {
123     if (!isa<CompositeType>(NextTy))
124       return 0;  // Type must not be ready for processing...
125     CompTy = cast<CompositeType>(NextTy);
126
127     if (const StructType *StructTy = dyn_cast<StructType>(CompTy)) {
128       // Step into the appropriate element of the structure...
129       uint64_t ActualOffset = (Offset < 0) ? 0 : (uint64_t)Offset;
130       NextTy = getStructOffsetStep(StructTy, ActualOffset, Indices, TD);
131       Offset -= ActualOffset;
132     } else {
133       const Type *ElTy = cast<SequentialType>(CompTy)->getElementType();
134       if (!ElTy->isSized() || (isa<PointerType>(CompTy) && !Indices.empty()))
135         return 0; // Type is unreasonable... escape!
136       unsigned ElSize = TD.getTypeSize(ElTy);
137       if (ElSize == 0) return 0;   // Avoid division by zero...
138       int64_t ElSizeS = ElSize;
139
140       // See if the user is indexing into a different cell of this array...
141       if (Scale && (Scale >= ElSizeS || -Scale >= ElSizeS)) {
142         // A scale n*ElSize might occur if we are not stepping through
143         // array by one.  In this case, we will have to insert math to munge
144         // the index.
145         //
146         int64_t ScaleAmt = Scale/ElSizeS;
147         if (Scale-ScaleAmt*ElSizeS)
148           return 0;  // Didn't scale by a multiple of element size, bail out
149         Scale = 0;   // Scale is consumed
150
151         int64_t Index = Offset/ElSize;        // is zero unless Offset > ElSize
152         Offset -= Index*ElSize;               // Consume part of the offset
153
154         if (BI) {              // Generate code?
155           BasicBlock *BB = (*BI)->getParent();
156           if (Expr.Var->getType() != Type::LongTy)    // FIXME for PR82
157             Expr.Var = new CastInst(Expr.Var, Type::LongTy,    // FIXME for PR82
158                                     Expr.Var->getName()+"-idxcast", *BI);
159
160           if (ScaleAmt && ScaleAmt != 1) {
161             // If we have to scale up our index, do so now
162             // FIXME for PR82
163             Value *ScaleAmtVal = ConstantSInt::get(Type::LongTy, ScaleAmt);
164             Expr.Var = BinaryOperator::create(Instruction::Mul, Expr.Var,
165                                               ScaleAmtVal,
166                                               Expr.Var->getName()+"-scale",*BI);
167           }
168
169           if (Index) {  // Add an offset to the index
170             // FIXME for PR82
171             Value *IndexAmt = ConstantSInt::get(Type::LongTy, Index);
172             Expr.Var = BinaryOperator::create(Instruction::Add, Expr.Var,
173                                               IndexAmt,
174                                               Expr.Var->getName()+"-offset",
175                                               *BI);
176           }
177         }
178
179         Indices.push_back(Expr.Var);
180         Expr.Var = 0;
181       } else if (Offset >= (int64_t)ElSize || -Offset >= (int64_t)ElSize) {
182         // Calculate the index that we are entering into the array cell with
183         uint64_t Index = Offset/ElSize;
184         // FIXME for PR82
185         Indices.push_back(ConstantSInt::get(Type::LongTy, Index));
186         Offset -= (int64_t)(Index*ElSize);        // Consume part of the offset
187
188       } else if (isa<ArrayType>(CompTy) || Indices.empty()) {
189         // Must be indexing a small amount into the first cell of the array
190         // Just index into element zero of the array here.
191         //
192         // FIXME for PR82
193         Indices.push_back(ConstantSInt::get(Type::LongTy, 0));
194       } else {
195         return 0;  // Hrm. wierd, can't handle this case.  Bail
196       }
197       NextTy = ElTy;
198     }
199   } while (Offset || Scale);    // Go until we're done!
200
201   return NextTy;
202 }
203