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