blob: c672c4e5015ff5b311b926b2f4ca8365b40fa09d [file] [log] [blame]
Chris Lattnerd32a9612001-11-01 02:42:08 +00001//===- LevelRaise.cpp - Code to change LLVM to higher level -----------------=//
2//
3// This file implements the 'raising' part of the LevelChange API. This is
4// useful because, in general, it makes the LLVM code terser and easier to
Chris Lattner3cc7dde2001-11-26 16:58:14 +00005// analyze.
Chris Lattnerd32a9612001-11-01 02:42:08 +00006//
7//===----------------------------------------------------------------------===//
8
9#include "llvm/Transforms/LevelChange.h"
Chris Lattner59cd9f12001-11-04 23:24:06 +000010#include "TransformInternals.h"
Chris Lattnerd32a9612001-11-01 02:42:08 +000011#include "llvm/Method.h"
Chris Lattnerd32a9612001-11-01 02:42:08 +000012#include "llvm/iOther.h"
13#include "llvm/iMemory.h"
Chris Lattnere9bb2df2001-12-03 22:26:30 +000014#include "llvm/ConstantVals.h"
Chris Lattnerdedee7b2001-11-01 05:57:59 +000015#include "llvm/Optimizations/ConstantHandling.h"
Chris Lattner68b07b72001-11-01 07:00:51 +000016#include "llvm/Optimizations/DCE.h"
Chris Lattnerbd70bb92001-11-26 18:58:55 +000017#include "llvm/Optimizations/ConstantProp.h"
Chris Lattnerd5b48ca2001-11-14 11:02:49 +000018#include "llvm/Analysis/Expressions.h"
Chris Lattnercee8f9a2001-11-27 00:03:19 +000019#include "Support/STLExtras.h"
Chris Lattnerd32a9612001-11-01 02:42:08 +000020#include <algorithm>
21
22#include "llvm/Assembly/Writer.h"
23
Chris Lattner09009802001-11-26 19:36:58 +000024//#define DEBUG_PEEPHOLE_INSTS 1
Chris Lattnerd32a9612001-11-01 02:42:08 +000025
26#ifdef DEBUG_PEEPHOLE_INSTS
27#define PRINT_PEEPHOLE(ID, NUM, I) \
28 cerr << "Inst P/H " << ID << "[" << NUM << "] " << I;
29#else
30#define PRINT_PEEPHOLE(ID, NUM, I)
31#endif
32
33#define PRINT_PEEPHOLE1(ID, I1) do { PRINT_PEEPHOLE(ID, 0, I1); } while (0)
34#define PRINT_PEEPHOLE2(ID, I1, I2) \
35 do { PRINT_PEEPHOLE(ID, 0, I1); PRINT_PEEPHOLE(ID, 1, I2); } while (0)
36#define PRINT_PEEPHOLE3(ID, I1, I2, I3) \
37 do { PRINT_PEEPHOLE(ID, 0, I1); PRINT_PEEPHOLE(ID, 1, I2); \
38 PRINT_PEEPHOLE(ID, 2, I3); } while (0)
Chris Lattnerd5b48ca2001-11-14 11:02:49 +000039#define PRINT_PEEPHOLE4(ID, I1, I2, I3, I4) \
40 do { PRINT_PEEPHOLE(ID, 0, I1); PRINT_PEEPHOLE(ID, 1, I2); \
41 PRINT_PEEPHOLE(ID, 2, I3); PRINT_PEEPHOLE(ID, 3, I4); } while (0)
Chris Lattnerd32a9612001-11-01 02:42:08 +000042
43
Chris Lattnerd32a9612001-11-01 02:42:08 +000044// isReinterpretingCast - Return true if the cast instruction specified will
45// cause the operand to be "reinterpreted". A value is reinterpreted if the
46// cast instruction would cause the underlying bits to change.
47//
48static inline bool isReinterpretingCast(const CastInst *CI) {
Chris Lattner3cc7dde2001-11-26 16:58:14 +000049 return!CI->getOperand(0)->getType()->isLosslesslyConvertableTo(CI->getType());
Chris Lattnerd32a9612001-11-01 02:42:08 +000050}
51
52
Chris Lattnerf3b976e2001-11-04 20:21:12 +000053
Chris Lattnera8b6d432001-12-05 06:34:00 +000054// Peephole optimize the following instructions:
55// %t1 = cast ? to x *
56// %t2 = add x * %SP, %t1 ;; Constant must be 2nd operand
57//
58// Into: %t3 = getelementptr {<...>} * %SP, <element indices>
59// %t2 = cast <eltype> * %t3 to {<...>}*
60//
61static bool HandleCastToPointer(BasicBlock::iterator BI,
62 const PointerType *DestPTy) {
63 CastInst *CI = cast<CastInst>(*BI);
Chris Lattnerf3b976e2001-11-04 20:21:12 +000064
Chris Lattnera8b6d432001-12-05 06:34:00 +000065 // Scan all of the uses, looking for any uses that are not add
66 // instructions. If we have non-adds, do not make this transformation.
67 //
68 for (Value::use_iterator I = CI->use_begin(), E = CI->use_end();
69 I != E; ++I) {
70 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(*I)) {
71 if (BO->getOpcode() != Instruction::Add)
72 return false;
73 } else {
74 return false;
75 }
76 }
77
78 vector<Value*> Indices;
79 Value *Src = CI->getOperand(0);
80 const Type *Result = ConvertableToGEP(DestPTy, Src, Indices, &BI);
81 const PointerType *UsedType = DestPTy;
82
83 // If we fail, check to see if we have an pointer source type that, if
84 // converted to an unsized array type, would work. In this case, we propogate
85 // the cast forward to the input of the add instruction.
86 //
87 if (Result == 0 && getPointedToComposite(DestPTy) == 0) {
88 // Make an unsized array and try again...
89 UsedType = PointerType::get(ArrayType::get(DestPTy->getElementType()));
90 Result = ConvertableToGEP(UsedType, Src, Indices, &BI);
91 }
92
93 if (Result == 0) return false; // Not convertable...
94
95 PRINT_PEEPHOLE2("cast-add-to-gep:in", Src, CI);
96
97 // If we have a getelementptr capability... transform all of the
98 // add instruction uses into getelementptr's.
99 for (Value::use_iterator UI = CI->use_begin(), E = CI->use_end();
100 UI != E; ++UI) {
101 Instruction *I = cast<Instruction>(*UI);
102 assert(I->getOpcode() == Instruction::Add && I->getNumOperands() == 2 &&
103 "Use is not a valid add instruction!");
104
105 // Get the value added to the cast result pointer...
106 Value *OtherPtr = I->getOperand((I->getOperand(0) == CI) ? 1 : 0);
107
108 BasicBlock *BB = I->getParent();
109 BasicBlock::iterator AddIt = find(BB->getInstList().begin(),
110 BB->getInstList().end(), I);
111
112 if (UsedType != DestPTy) {
113 // Insert a cast of the incoming value to something addressable...
114 CastInst *C = new CastInst(OtherPtr, UsedType, OtherPtr->getName());
115 AddIt = BB->getInstList().insert(AddIt, C)+1;
116 OtherPtr = C;
117 }
118
Chris Lattnerf17a09d2001-12-06 18:06:13 +0000119 GetElementPtrInst *GEP = new GetElementPtrInst(OtherPtr, Indices);
Chris Lattnera8b6d432001-12-05 06:34:00 +0000120
121 PRINT_PEEPHOLE1("cast-add-to-gep:i", I);
122
123 // Replace the old add instruction with the shiny new GEP inst
124 ReplaceInstWithInst(BB->getInstList(), AddIt, GEP);
125 PRINT_PEEPHOLE1("cast-add-to-gep:o", GEP);
126 }
127 return true;
128}
Chris Lattnerd5b48ca2001-11-14 11:02:49 +0000129
130// Peephole optimize the following instructions:
131// %t1 = cast ulong <const int> to {<...>} *
132// %t2 = add {<...>} * %SP, %t1 ;; Constant must be 2nd operand
133//
134// or
135// %t1 = cast {<...>}* %SP to int*
136// %t5 = cast ulong <const int> to int*
137// %t2 = add int* %t1, %t5 ;; int is same size as field
138//
139// Into: %t3 = getelementptr {<...>} * %SP, <element indices>
140// %t2 = cast <eltype> * %t3 to {<...>}*
141//
142static bool PeepholeOptimizeAddCast(BasicBlock *BB, BasicBlock::iterator &BI,
143 Value *AddOp1, CastInst *AddOp2) {
Chris Lattner3cc7dde2001-11-26 16:58:14 +0000144 const CompositeType *CompTy;
145 Value *OffsetVal = AddOp2->getOperand(0);
146 Value *SrcPtr; // Of type pointer to struct...
Chris Lattnerd5b48ca2001-11-14 11:02:49 +0000147
Chris Lattner3cc7dde2001-11-26 16:58:14 +0000148 if ((CompTy = getPointedToComposite(AddOp1->getType()))) {
Chris Lattnerd5b48ca2001-11-14 11:02:49 +0000149 SrcPtr = AddOp1; // Handle the first case...
150 } else if (CastInst *AddOp1c = dyn_cast<CastInst>(AddOp1)) {
151 SrcPtr = AddOp1c->getOperand(0); // Handle the second case...
Chris Lattner3cc7dde2001-11-26 16:58:14 +0000152 CompTy = getPointedToComposite(SrcPtr->getType());
Chris Lattnerd5b48ca2001-11-14 11:02:49 +0000153 }
154
155 // Only proceed if we have detected all of our conditions successfully...
Chris Lattner3cc7dde2001-11-26 16:58:14 +0000156 if (!CompTy || !SrcPtr || !OffsetVal->getType()->isIntegral())
Chris Lattnerd5b48ca2001-11-14 11:02:49 +0000157 return false;
158
Chris Lattner3cc7dde2001-11-26 16:58:14 +0000159 vector<Value*> Indices;
160 if (!ConvertableToGEP(SrcPtr->getType(), OffsetVal, Indices, &BI))
161 return false; // Not convertable... perhaps next time
Chris Lattnerd5b48ca2001-11-14 11:02:49 +0000162
Chris Lattner3cc7dde2001-11-26 16:58:14 +0000163 if (getPointedToComposite(AddOp1->getType())) { // case 1
Chris Lattnerd5b48ca2001-11-14 11:02:49 +0000164 PRINT_PEEPHOLE2("add-to-gep1:in", AddOp2, *BI);
165 } else {
166 PRINT_PEEPHOLE3("add-to-gep2:in", AddOp1, AddOp2, *BI);
167 }
168
Chris Lattner3cc7dde2001-11-26 16:58:14 +0000169 GetElementPtrInst *GEP = new GetElementPtrInst(SrcPtr, Indices,
170 AddOp2->getName());
Chris Lattnerd5b48ca2001-11-14 11:02:49 +0000171 BI = BB->getInstList().insert(BI, GEP)+1;
Chris Lattnerd5b48ca2001-11-14 11:02:49 +0000172
Chris Lattner3cc7dde2001-11-26 16:58:14 +0000173 Instruction *NCI = new CastInst(GEP, AddOp1->getType());
Chris Lattnerd5b48ca2001-11-14 11:02:49 +0000174 ReplaceInstWithInst(BB->getInstList(), BI, NCI);
175 PRINT_PEEPHOLE2("add-to-gep:out", GEP, NCI);
176 return true;
177}
178
Chris Lattnerd32a9612001-11-01 02:42:08 +0000179static bool PeepholeOptimize(BasicBlock *BB, BasicBlock::iterator &BI) {
180 Instruction *I = *BI;
Chris Lattnerd32a9612001-11-01 02:42:08 +0000181
182 if (CastInst *CI = dyn_cast<CastInst>(I)) {
183 Value *Src = CI->getOperand(0);
184 Instruction *SrcI = dyn_cast<Instruction>(Src); // Nonnull if instr source
185 const Type *DestTy = CI->getType();
186
Chris Lattnere99c66b2001-11-01 17:05:27 +0000187 // Peephole optimize the following instruction:
188 // %V2 = cast <ty> %V to <ty>
189 //
190 // Into: <nothing>
191 //
192 if (DestTy == Src->getType()) { // Check for a cast to same type as src!!
Chris Lattnerd32a9612001-11-01 02:42:08 +0000193 PRINT_PEEPHOLE1("cast-of-self-ty", CI);
194 CI->replaceAllUsesWith(Src);
195 if (!Src->hasName() && CI->hasName()) {
196 string Name = CI->getName();
Chris Lattnerf3b976e2001-11-04 20:21:12 +0000197 CI->setName("");
198 Src->setName(Name, BB->getParent()->getSymbolTable());
Chris Lattnerd32a9612001-11-01 02:42:08 +0000199 }
200 return true;
201 }
202
Chris Lattnere99c66b2001-11-01 17:05:27 +0000203 // Peephole optimize the following instructions:
204 // %tmp = cast <ty> %V to <ty2>
Chris Lattnera8b6d432001-12-05 06:34:00 +0000205 // %V = cast <ty2> %tmp to <ty3> ; Where ty & ty2 are same size
Chris Lattnere99c66b2001-11-01 17:05:27 +0000206 //
207 // Into: cast <ty> %V to <ty3>
208 //
Chris Lattnerd32a9612001-11-01 02:42:08 +0000209 if (SrcI)
210 if (CastInst *CSrc = dyn_cast<CastInst>(SrcI))
211 if (isReinterpretingCast(CI) + isReinterpretingCast(CSrc) < 2) {
212 // We can only do c-c elimination if, at most, one cast does a
213 // reinterpretation of the input data.
214 //
215 // If legal, make this cast refer the the original casts argument!
216 //
217 PRINT_PEEPHOLE2("cast-cast:in ", CI, CSrc);
218 CI->setOperand(0, CSrc->getOperand(0));
219 PRINT_PEEPHOLE1("cast-cast:out", CI);
220 return true;
221 }
222
223 // Check to see if it's a cast of an instruction that does not depend on the
224 // specific type of the operands to do it's job.
Chris Lattnerf3b976e2001-11-04 20:21:12 +0000225 if (!isReinterpretingCast(CI)) {
Chris Lattnera8b6d432001-12-05 06:34:00 +0000226 // Check to see if we can convert the source of the cast to match the
227 // destination type of the cast...
228 //
Chris Lattnerb980e182001-11-04 21:32:11 +0000229 ValueTypeCache ConvertedTypes;
Chris Lattner3cc7dde2001-11-26 16:58:14 +0000230 if (ValueConvertableToType(CI, Src->getType(), ConvertedTypes)) {
231 PRINT_PEEPHOLE2("CAST-DEST-EXPR-CONV:in ", Src, CI);
Chris Lattnerf3b976e2001-11-04 20:21:12 +0000232
Chris Lattnerc0b90e72001-11-08 20:19:56 +0000233#ifdef DEBUG_PEEPHOLE_INSTS
234 cerr << "\nCONVERTING EXPR TYPE:\n";
235#endif
Chris Lattnerb980e182001-11-04 21:32:11 +0000236 ValueMapCache ValueMap;
Chris Lattner3cc7dde2001-11-26 16:58:14 +0000237 ConvertValueToNewType(CI, Src, ValueMap); // This will delete CI!
Chris Lattnere4f4d8c2001-11-05 18:30:53 +0000238
Chris Lattnerf3b976e2001-11-04 20:21:12 +0000239 BI = BB->begin(); // Rescan basic block. BI might be invalidated.
Chris Lattnere34443d2001-11-06 08:34:29 +0000240 PRINT_PEEPHOLE1("CAST-DEST-EXPR-CONV:out", Src);
Chris Lattnerc0b90e72001-11-08 20:19:56 +0000241#ifdef DEBUG_PEEPHOLE_INSTS
242 cerr << "DONE CONVERTING EXPR TYPE: \n\n";// << BB->getParent();
243#endif
Chris Lattnerf3b976e2001-11-04 20:21:12 +0000244 return true;
Chris Lattnera8b6d432001-12-05 06:34:00 +0000245 }
246
247 // Check to see if we can convert the users of the cast value to match the
248 // source type of the cast...
249 //
250 ConvertedTypes.clear();
251 if (ExpressionConvertableToType(Src, DestTy, ConvertedTypes)) {
252 PRINT_PEEPHOLE2("CAST-SRC-EXPR-CONV:in ", Src, CI);
Chris Lattnerc0b90e72001-11-08 20:19:56 +0000253
254#ifdef DEBUG_PEEPHOLE_INSTS
Chris Lattnera8b6d432001-12-05 06:34:00 +0000255 cerr << "\nCONVERTING SRC EXPR TYPE:\n";
Chris Lattnerc0b90e72001-11-08 20:19:56 +0000256#endif
Chris Lattnera8b6d432001-12-05 06:34:00 +0000257 ValueMapCache ValueMap;
258 Value *E = ConvertExpressionToType(Src, DestTy, ValueMap);
259 if (Constant *CPV = dyn_cast<Constant>(E))
260 CI->replaceAllUsesWith(CPV);
Chris Lattnerc0b90e72001-11-08 20:19:56 +0000261
Chris Lattnera8b6d432001-12-05 06:34:00 +0000262 BI = BB->begin(); // Rescan basic block. BI might be invalidated.
263 PRINT_PEEPHOLE1("CAST-SRC-EXPR-CONV:out", E);
Chris Lattnerc0b90e72001-11-08 20:19:56 +0000264#ifdef DEBUG_PEEPHOLE_INSTS
Chris Lattnera8b6d432001-12-05 06:34:00 +0000265 cerr << "DONE CONVERTING SRC EXPR TYPE: \n\n";// << BB->getParent();
Chris Lattnerc0b90e72001-11-08 20:19:56 +0000266#endif
Chris Lattnera8b6d432001-12-05 06:34:00 +0000267 return true;
Chris Lattnerf3b976e2001-11-04 20:21:12 +0000268 }
Chris Lattnerf17a09d2001-12-06 18:06:13 +0000269 }
270
271 // Otherwise find out it this cast is a cast to a pointer type, which is
272 // then added to some other pointer, then loaded or stored through. If
273 // so, convert the add into a getelementptr instruction...
274 //
275 if (const PointerType *DestPTy = dyn_cast<PointerType>(DestTy)) {
276 if (HandleCastToPointer(BI, DestPTy)) {
277 BI = BB->begin(); // Rescan basic block. BI might be invalidated.
278 return true;
Chris Lattnera8b6d432001-12-05 06:34:00 +0000279 }
Chris Lattnerd32a9612001-11-01 02:42:08 +0000280 }
281
Chris Lattnere99c66b2001-11-01 17:05:27 +0000282 // Check to see if we are casting from a structure pointer to a pointer to
283 // the first element of the structure... to avoid munching other peepholes,
284 // we only let this happen if there are no add uses of the cast.
285 //
286 // Peephole optimize the following instructions:
287 // %t1 = cast {<...>} * %StructPtr to <ty> *
288 //
289 // Into: %t2 = getelementptr {<...>} * %StructPtr, <0, 0, 0, ...>
290 // %t1 = cast <eltype> * %t1 to <ty> *
291 //
Chris Lattnerc0b90e72001-11-08 20:19:56 +0000292#if 1
Chris Lattner3cc7dde2001-11-26 16:58:14 +0000293 if (const CompositeType *CTy = getPointedToComposite(Src->getType()))
Chris Lattnere99c66b2001-11-01 17:05:27 +0000294 if (const PointerType *DestPTy = dyn_cast<PointerType>(DestTy)) {
295
296 // Loop over uses of the cast, checking for add instructions. If an add
297 // exists, this is probably a part of a more complex GEP, so we don't
298 // want to mess around with the cast.
299 //
300 bool HasAddUse = false;
301 for (Value::use_iterator I = CI->use_begin(), E = CI->use_end();
302 I != E; ++I)
303 if (isa<Instruction>(*I) &&
304 cast<Instruction>(*I)->getOpcode() == Instruction::Add) {
305 HasAddUse = true; break;
306 }
307
308 // If it doesn't have an add use, check to see if the dest type is
309 // losslessly convertable to one of the types in the start of the struct
310 // type.
311 //
312 if (!HasAddUse) {
Chris Lattner7a176752001-12-04 00:03:30 +0000313 const Type *DestPointedTy = DestPTy->getElementType();
Chris Lattnere99c66b2001-11-01 17:05:27 +0000314 unsigned Depth = 1;
Chris Lattner3cc7dde2001-11-26 16:58:14 +0000315 const CompositeType *CurCTy = CTy;
Chris Lattnere99c66b2001-11-01 17:05:27 +0000316 const Type *ElTy = 0;
Chris Lattner3cc7dde2001-11-26 16:58:14 +0000317
318 // Build the index vector, full of all zeros
319 vector<Value*> Indices;
320
321 while (CurCTy) {
322 if (const StructType *CurSTy = dyn_cast<StructType>(CurCTy)) {
323 // Check for a zero element struct type... if we have one, bail.
324 if (CurSTy->getElementTypes().size() == 0) break;
Chris Lattnere99c66b2001-11-01 17:05:27 +0000325
Chris Lattner3cc7dde2001-11-26 16:58:14 +0000326 // Grab the first element of the struct type, which must lie at
327 // offset zero in the struct.
328 //
329 ElTy = CurSTy->getElementTypes()[0];
330 } else {
331 ElTy = cast<ArrayType>(CurCTy)->getElementType();
332 }
333
334 // Insert a zero to index through this type...
Chris Lattnere9bb2df2001-12-03 22:26:30 +0000335 Indices.push_back(ConstantUInt::get(CurCTy->getIndexType(), 0));
Chris Lattnere99c66b2001-11-01 17:05:27 +0000336
337 // Did we find what we're looking for?
Chris Lattner3cc7dde2001-11-26 16:58:14 +0000338 if (ElTy->isLosslesslyConvertableTo(DestPointedTy)) break;
Chris Lattnere99c66b2001-11-01 17:05:27 +0000339
340 // Nope, go a level deeper.
341 ++Depth;
Chris Lattner3cc7dde2001-11-26 16:58:14 +0000342 CurCTy = dyn_cast<CompositeType>(ElTy);
Chris Lattnere99c66b2001-11-01 17:05:27 +0000343 ElTy = 0;
344 }
345
346 // Did we find what we were looking for? If so, do the transformation
347 if (ElTy) {
348 PRINT_PEEPHOLE1("cast-for-first:in", CI);
349
Chris Lattnere99c66b2001-11-01 17:05:27 +0000350 // Insert the new T cast instruction... stealing old T's name
351 GetElementPtrInst *GEP = new GetElementPtrInst(Src, Indices,
352 CI->getName());
353 CI->setName("");
354 BI = BB->getInstList().insert(BI, GEP)+1;
355
356 // Make the old cast instruction reference the new GEP instead of
357 // the old src value.
358 //
359 CI->setOperand(0, GEP);
360
361 PRINT_PEEPHOLE2("cast-for-first:out", GEP, CI);
362 return true;
363 }
364 }
365 }
Chris Lattnerc0b90e72001-11-08 20:19:56 +0000366#endif
Chris Lattnere99c66b2001-11-01 17:05:27 +0000367
Chris Lattner3d775c32001-11-13 04:59:41 +0000368#if 1
Chris Lattner8d38e542001-11-01 03:12:34 +0000369 } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
370 Value *Val = SI->getOperand(0);
Chris Lattner65ea1712001-11-14 11:27:58 +0000371 Value *Pointer = SI->getPointerOperand();
Chris Lattner8d38e542001-11-01 03:12:34 +0000372
Chris Lattnerdedee7b2001-11-01 05:57:59 +0000373 // Peephole optimize the following instructions:
374 // %t1 = getelementptr {<...>} * %StructPtr, <element indices>
375 // store <elementty> %v, <elementty> * %t1
376 //
377 // Into: store <elementty> %v, {<...>} * %StructPtr, <element indices>
378 //
Chris Lattner8d38e542001-11-01 03:12:34 +0000379 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Pointer)) {
Chris Lattnerc0b90e72001-11-08 20:19:56 +0000380 // Append any indices that the store instruction has onto the end of the
381 // ones that the GEP is carrying...
382 //
Chris Lattner3cc7dde2001-11-26 16:58:14 +0000383 vector<Value*> Indices(GEP->copyIndices());
384 Indices.insert(Indices.end(), SI->idx_begin(), SI->idx_end());
Chris Lattnerc0b90e72001-11-08 20:19:56 +0000385
Chris Lattner8d38e542001-11-01 03:12:34 +0000386 PRINT_PEEPHOLE2("gep-store:in", GEP, SI);
387 ReplaceInstWithInst(BB->getInstList(), BI,
Chris Lattner65ea1712001-11-14 11:27:58 +0000388 SI = new StoreInst(Val, GEP->getPointerOperand(),
Chris Lattnerc0b90e72001-11-08 20:19:56 +0000389 Indices));
Chris Lattner8d38e542001-11-01 03:12:34 +0000390 PRINT_PEEPHOLE1("gep-store:out", SI);
391 return true;
392 }
Chris Lattnerdedee7b2001-11-01 05:57:59 +0000393
394 // Peephole optimize the following instructions:
395 // %t = cast <T1>* %P to <T2> * ;; If T1 is losslessly convertable to T2
396 // store <T2> %V, <T2>* %t
397 //
398 // Into:
399 // %t = cast <T2> %V to <T1>
400 // store <T1> %t2, <T1>* %P
401 //
402 if (CastInst *CI = dyn_cast<CastInst>(Pointer))
403 if (Value *CastSrc = CI->getOperand(0)) // CSPT = CastSrcPointerType
404 if (PointerType *CSPT = dyn_cast<PointerType>(CastSrc->getType()))
Chris Lattner3cc7dde2001-11-26 16:58:14 +0000405 // convertable types?
Chris Lattner7a176752001-12-04 00:03:30 +0000406 if (Val->getType()->isLosslesslyConvertableTo(CSPT->getElementType()) &&
Chris Lattnerdedee7b2001-11-01 05:57:59 +0000407 !SI->hasIndices()) { // No subscripts yet!
408 PRINT_PEEPHOLE3("st-src-cast:in ", Pointer, Val, SI);
409
410 // Insert the new T cast instruction... stealing old T's name
Chris Lattner7a176752001-12-04 00:03:30 +0000411 CastInst *NCI = new CastInst(Val, CSPT->getElementType(),
Chris Lattnerdedee7b2001-11-01 05:57:59 +0000412 CI->getName());
413 CI->setName("");
414 BI = BB->getInstList().insert(BI, NCI)+1;
415
416 // Replace the old store with a new one!
417 ReplaceInstWithInst(BB->getInstList(), BI,
418 SI = new StoreInst(NCI, CastSrc));
419 PRINT_PEEPHOLE3("st-src-cast:out", NCI, CastSrc, SI);
420 return true;
421 }
422
Chris Lattner8d38e542001-11-01 03:12:34 +0000423
424 } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Chris Lattner44480b52001-12-07 04:39:01 +0000425#if 0
Chris Lattner65ea1712001-11-14 11:27:58 +0000426 Value *Pointer = LI->getPointerOperand();
Chris Lattner8d38e542001-11-01 03:12:34 +0000427
Chris Lattnerdedee7b2001-11-01 05:57:59 +0000428 // Peephole optimize the following instructions:
429 // %t1 = getelementptr {<...>} * %StructPtr, <element indices>
430 // %V = load <elementty> * %t1
431 //
432 // Into: load {<...>} * %StructPtr, <element indices>
433 //
Chris Lattner8d38e542001-11-01 03:12:34 +0000434 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Pointer)) {
Chris Lattnerc0b90e72001-11-08 20:19:56 +0000435 // Append any indices that the load instruction has onto the end of the
436 // ones that the GEP is carrying...
437 //
Chris Lattner3cc7dde2001-11-26 16:58:14 +0000438 vector<Value*> Indices(GEP->copyIndices());
439 Indices.insert(Indices.end(), LI->idx_begin(), LI->idx_end());
Chris Lattnerc0b90e72001-11-08 20:19:56 +0000440
Chris Lattner8d38e542001-11-01 03:12:34 +0000441 PRINT_PEEPHOLE2("gep-load:in", GEP, LI);
442 ReplaceInstWithInst(BB->getInstList(), BI,
Chris Lattner65ea1712001-11-14 11:27:58 +0000443 LI = new LoadInst(GEP->getPointerOperand(),
Chris Lattnerc0b90e72001-11-08 20:19:56 +0000444 Indices));
Chris Lattner8d38e542001-11-01 03:12:34 +0000445 PRINT_PEEPHOLE1("gep-load:out", LI);
446 return true;
447 }
Chris Lattnera8b6d432001-12-05 06:34:00 +0000448#endif
Chris Lattnerd32a9612001-11-01 02:42:08 +0000449 } else if (I->getOpcode() == Instruction::Add &&
450 isa<CastInst>(I->getOperand(1))) {
451
Chris Lattnerd5b48ca2001-11-14 11:02:49 +0000452 if (PeepholeOptimizeAddCast(BB, BI, I->getOperand(0),
453 cast<CastInst>(I->getOperand(1))))
Chris Lattnerd32a9612001-11-01 02:42:08 +0000454 return true;
Chris Lattnerd5b48ca2001-11-14 11:02:49 +0000455
Chris Lattner3d775c32001-11-13 04:59:41 +0000456#endif
Chris Lattnerd32a9612001-11-01 02:42:08 +0000457 }
458
459 return false;
460}
461
462
463
464
465static bool DoRaisePass(Method *M) {
466 bool Changed = false;
467 for (Method::iterator MI = M->begin(), ME = M->end(); MI != ME; ++MI) {
468 BasicBlock *BB = *MI;
469 BasicBlock::InstListType &BIL = BB->getInstList();
470
471 for (BasicBlock::iterator BI = BB->begin(); BI != BB->end();) {
Chris Lattnerbd70bb92001-11-26 18:58:55 +0000472 if (opt::DeadCodeElimination::dceInstruction(BIL, BI) ||
473 opt::ConstantPropogation::doConstantPropogation(BB, BI)) {
Chris Lattnerc0b90e72001-11-08 20:19:56 +0000474 Changed = true;
475#ifdef DEBUG_PEEPHOLE_INSTS
476 cerr << "DeadCode Elinated!\n";
477#endif
478 } else if (PeepholeOptimize(BB, BI))
Chris Lattnerd32a9612001-11-01 02:42:08 +0000479 Changed = true;
480 else
481 ++BI;
482 }
483 }
484 return Changed;
485}
486
487
Chris Lattner3cc7dde2001-11-26 16:58:14 +0000488
489
490// DoInsertArrayCast - If the argument value has a pointer type, and if the
491// argument value is used as an array, insert a cast before the specified
492// basic block iterator that casts the value to an array pointer. Return the
493// new cast instruction (in the CastResult var), or null if no cast is inserted.
494//
495static bool DoInsertArrayCast(Value *V, BasicBlock *BB,
496 BasicBlock::iterator InsertBefore) {
497 const PointerType *ThePtrType = dyn_cast<PointerType>(V->getType());
498 if (!ThePtrType) return false;
499
Chris Lattner7a176752001-12-04 00:03:30 +0000500 const Type *ElTy = ThePtrType->getElementType();
Chris Lattner8da5d422001-12-05 19:40:32 +0000501 if (isa<MethodType>(ElTy) ||
502 (isa<ArrayType>(ElTy) && cast<ArrayType>(ElTy)->isUnsized()))
503 return false;
Chris Lattner3cc7dde2001-11-26 16:58:14 +0000504
505 unsigned ElementSize = TD.getTypeSize(ElTy);
506 bool InsertCast = false;
507
508 for (Value::use_iterator I = V->use_begin(), E = V->use_end(); I != E; ++I) {
509 Instruction *Inst = cast<Instruction>(*I);
510 switch (Inst->getOpcode()) {
511 case Instruction::Cast: // There is already a cast instruction!
512 if (const PointerType *PT = dyn_cast<const PointerType>(Inst->getType()))
Chris Lattner7a176752001-12-04 00:03:30 +0000513 if (const ArrayType *AT = dyn_cast<const ArrayType>(PT->getElementType()))
514 if (AT->getElementType() == ThePtrType->getElementType()) {
Chris Lattner3cc7dde2001-11-26 16:58:14 +0000515 // Cast already exists! Don't mess around with it.
516 return false; // No changes made to program though...
517 }
518 break;
519 case Instruction::Add: { // Analyze pointer arithmetic...
520 Value *OtherOp = Inst->getOperand(Inst->getOperand(0) == V);
521 analysis::ExprType Expr = analysis::ClassifyExpression(OtherOp);
522
523 // This looks like array addressing iff:
524 // A. The constant of the index is larger than the size of the element
525 // type.
526 // B. The scale factor is >= the size of the type.
527 //
528 if (Expr.Offset && getConstantValue(Expr.Offset) >= (int)ElementSize) // A
529 InsertCast = true;
530
531 if (Expr.Scale && getConstantValue(Expr.Scale) >= (int)ElementSize) // B
532 InsertCast = true;
533
534 break;
535 }
536 default: break; // Not an interesting use...
537 }
538 }
539
540 if (!InsertCast) return false; // There is no reason to insert a cast!
541
542 // Calculate the destination pointer type
543 const PointerType *DestTy = PointerType::get(ArrayType::get(ElTy));
544
545 // Check to make sure that all uses of the value can be converted over to use
546 // the newly typed value.
547 //
548 ValueTypeCache ConvertedTypes;
549 if (!ValueConvertableToType(V, DestTy, ConvertedTypes)) {
Chris Lattner8da5d422001-12-05 19:40:32 +0000550 cerr << "FAILED to convert types of values for " << V << " to " << DestTy << "\n";
Chris Lattner3cc7dde2001-11-26 16:58:14 +0000551 ConvertedTypes.clear();
552 ValueConvertableToType(V, DestTy, ConvertedTypes);
553 return false;
554 }
555 ConvertedTypes.clear();
556
557 // Insert a cast!
558 CastInst *TheCast =
Chris Lattnere9bb2df2001-12-03 22:26:30 +0000559 new CastInst(Constant::getNullConstant(V->getType()), DestTy, V->getName());
Chris Lattner3cc7dde2001-11-26 16:58:14 +0000560 BB->getInstList().insert(InsertBefore, TheCast);
561
Chris Lattner4b770a32001-12-04 08:12:53 +0000562#ifdef DEBUG_PEEPHOLE_INSTS
Chris Lattner3cc7dde2001-11-26 16:58:14 +0000563 cerr << "Inserting cast for " << V << endl;
Chris Lattner4b770a32001-12-04 08:12:53 +0000564#endif
Chris Lattner3cc7dde2001-11-26 16:58:14 +0000565
566 // Convert users of the old value over to use the cast result...
567 ValueMapCache VMC;
568 ConvertValueToNewType(V, TheCast, VMC);
569
570 // The cast is the only thing that is allowed to reference the value...
571 TheCast->setOperand(0, V);
572
Chris Lattner4b770a32001-12-04 08:12:53 +0000573#ifdef DEBUG_PEEPHOLE_INSTS
Chris Lattner3cc7dde2001-11-26 16:58:14 +0000574 cerr << "Inserted ptr-array cast: " << TheCast;
Chris Lattner4b770a32001-12-04 08:12:53 +0000575#endif
Chris Lattner3cc7dde2001-11-26 16:58:14 +0000576 return true; // Made a change!
577}
578
579
580// DoInsertArrayCasts - Loop over all "incoming" values in the specified method,
581// inserting a cast for pointer values that are used as arrays. For our
582// purposes, an incoming value is considered to be either a value that is
583// either a method parameter, or a pointer returned from a function call.
584//
585static bool DoInsertArrayCasts(Method *M) {
586 assert(!M->isExternal() && "Can't handle external methods!");
587
588 // Insert casts for all arguments to the function...
589 bool Changed = false;
590 BasicBlock *CurBB = M->front();
591
592 for (Method::ArgumentListType::iterator AI = M->getArgumentList().begin(),
593 AE = M->getArgumentList().end(); AI != AE; ++AI) {
594
595 Changed |= DoInsertArrayCast(*AI, CurBB, CurBB->begin());
596 }
597
598 // TODO: insert casts for alloca, malloc, and function call results. Also,
599 // look for pointers that already have casts, to add to the map.
600
Chris Lattnerf1d65212001-12-05 06:40:17 +0000601#ifdef DEBUG_PEEPHOLE_INSTS
602 if (Changed) cerr << "Inserted casts:\n" << M;
603#endif
Chris Lattnera8b6d432001-12-05 06:34:00 +0000604
Chris Lattner3cc7dde2001-11-26 16:58:14 +0000605 return Changed;
606}
607
608
609
610
Chris Lattnerd32a9612001-11-01 02:42:08 +0000611// RaisePointerReferences::doit - Raise a method representation to a higher
612// level.
613//
614bool RaisePointerReferences::doit(Method *M) {
615 if (M->isExternal()) return false;
Chris Lattnerd32a9612001-11-01 02:42:08 +0000616
Chris Lattner68b07b72001-11-01 07:00:51 +0000617#ifdef DEBUG_PEEPHOLE_INSTS
618 cerr << "\n\n\nStarting to work on Method '" << M->getName() << "'\n";
619#endif
620
Chris Lattner3cc7dde2001-11-26 16:58:14 +0000621 // Insert casts for all incoming pointer pointer values that are treated as
622 // arrays...
Chris Lattnerd32a9612001-11-01 02:42:08 +0000623 //
Chris Lattner3cc7dde2001-11-26 16:58:14 +0000624 bool Changed = false, LocalChange;
Chris Lattnera8b6d432001-12-05 06:34:00 +0000625
Chris Lattner4b770a32001-12-04 08:12:53 +0000626 do {
Chris Lattnera8b6d432001-12-05 06:34:00 +0000627#ifdef DEBUG_PEEPHOLE_INSTS
628 cerr << "Looping: \n" << M;
629#endif
630 LocalChange = DoInsertArrayCasts(M);
631
Chris Lattner3cc7dde2001-11-26 16:58:14 +0000632 // Iterate over the method, refining it, until it converges on a stable
633 // state
634 while (DoRaisePass(M)) LocalChange = true;
635 Changed |= LocalChange;
636
637 } while (LocalChange);
Chris Lattnerd32a9612001-11-01 02:42:08 +0000638
639 return Changed;
640}