blob: 03d7acf5b6f76fb0ccb8181762164a4320c958a7 [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
5// analyze. Note that it is good to run DCE after doing this transformation.
6//
7// Eliminate silly things in the source that do not effect the level, but do
8// clean up the code:
9// * Casts of casts
10// - getelementptr/load & getelementptr/store are folded into a direct
11// load or store
12// - Convert this code (for both alloca and malloc):
13// %reg110 = shl uint %n, ubyte 2 ;;<uint>
14// %reg108 = alloca ubyte, uint %reg110 ;;<ubyte*>
15// %cast76 = cast ubyte* %reg108 to uint* ;;<uint*>
16// To: %cast76 = alloca uint, uint %n
17// Convert explicit addressing to use getelementptr instruction where possible
18// - ...
19//
20// Convert explicit addressing on pointers to use getelementptr instruction.
21// - If a pointer is used by arithmetic operation, insert an array casted
22// version into the source program, only for the following pointer types:
23// * Method argument pointers
24// - Pointers returned by alloca or malloc
25// - Pointers returned by function calls
26// - If a pointer is indexed with a value scaled by a constant size equal
27// to the element size of the array, the expression is replaced with a
28// getelementptr instruction.
29//
30//===----------------------------------------------------------------------===//
31
32#include "llvm/Transforms/LevelChange.h"
Chris Lattner59cd9f12001-11-04 23:24:06 +000033#include "TransformInternals.h"
Chris Lattnerd32a9612001-11-01 02:42:08 +000034#include "llvm/Method.h"
35#include "llvm/Support/STLExtras.h"
36#include "llvm/iOther.h"
37#include "llvm/iMemory.h"
38#include "llvm/ConstPoolVals.h"
Chris Lattnerdedee7b2001-11-01 05:57:59 +000039#include "llvm/Optimizations/ConstantHandling.h"
Chris Lattner68b07b72001-11-01 07:00:51 +000040#include "llvm/Optimizations/DCE.h"
Chris Lattnerd32a9612001-11-01 02:42:08 +000041#include <algorithm>
42
43#include "llvm/Assembly/Writer.h"
44
Chris Lattnere4f4d8c2001-11-05 18:30:53 +000045//#define DEBUG_PEEPHOLE_INSTS 1
Chris Lattnerd32a9612001-11-01 02:42:08 +000046
47#ifdef DEBUG_PEEPHOLE_INSTS
48#define PRINT_PEEPHOLE(ID, NUM, I) \
49 cerr << "Inst P/H " << ID << "[" << NUM << "] " << I;
50#else
51#define PRINT_PEEPHOLE(ID, NUM, I)
52#endif
53
54#define PRINT_PEEPHOLE1(ID, I1) do { PRINT_PEEPHOLE(ID, 0, I1); } while (0)
55#define PRINT_PEEPHOLE2(ID, I1, I2) \
56 do { PRINT_PEEPHOLE(ID, 0, I1); PRINT_PEEPHOLE(ID, 1, I2); } while (0)
57#define PRINT_PEEPHOLE3(ID, I1, I2, I3) \
58 do { PRINT_PEEPHOLE(ID, 0, I1); PRINT_PEEPHOLE(ID, 1, I2); \
59 PRINT_PEEPHOLE(ID, 2, I3); } while (0)
60
61
Chris Lattnerd32a9612001-11-01 02:42:08 +000062// isReinterpretingCast - Return true if the cast instruction specified will
63// cause the operand to be "reinterpreted". A value is reinterpreted if the
64// cast instruction would cause the underlying bits to change.
65//
66static inline bool isReinterpretingCast(const CastInst *CI) {
67 return !losslessCastableTypes(CI->getOperand(0)->getType(), CI->getType());
68}
69
70
Chris Lattnerf3b976e2001-11-04 20:21:12 +000071
72
Chris Lattnerd32a9612001-11-01 02:42:08 +000073// DoInsertArrayCast - If the argument value has a pointer type, and if the
74// argument value is used as an array, insert a cast before the specified
75// basic block iterator that casts the value to an array pointer. Return the
76// new cast instruction (in the CastResult var), or null if no cast is inserted.
77//
78static bool DoInsertArrayCast(Method *CurMeth, Value *V, BasicBlock *BB,
79 BasicBlock::iterator &InsertBefore,
80 CastInst *&CastResult) {
81 const PointerType *ThePtrType = dyn_cast<PointerType>(V->getType());
82 if (!ThePtrType) return false;
83 bool InsertCast = false;
84
85 for (Value::use_iterator I = V->use_begin(), E = V->use_end(); I != E; ++I) {
86 Instruction *Inst = cast<Instruction>(*I);
87 switch (Inst->getOpcode()) {
88 default: break; // Not an interesting use...
89 case Instruction::Add: // It's being used as an array index!
90 //case Instruction::Sub:
91 InsertCast = true;
92 break;
93 case Instruction::Cast: // There is already a cast instruction!
94 if (const PointerType *PT = dyn_cast<const PointerType>(Inst->getType()))
95 if (const ArrayType *AT = dyn_cast<const ArrayType>(PT->getValueType()))
96 if (AT->getElementType() == ThePtrType->getValueType()) {
97 // Cast already exists! Return the existing one!
98 CastResult = cast<CastInst>(Inst);
99 return false; // No changes made to program though...
100 }
101 break;
102 }
103 }
104
105 if (!InsertCast) return false; // There is no reason to insert a cast!
106
107 // Insert a cast!
108 const Type *ElTy = ThePtrType->getValueType();
109 const PointerType *DestTy = PointerType::get(ArrayType::get(ElTy));
110
111 CastResult = new CastInst(V, DestTy);
112 BB->getInstList().insert(InsertBefore, CastResult);
113 //cerr << "Inserted cast: " << CastResult;
114 return true; // Made a change!
115}
116
117
118// DoInsertArrayCasts - Loop over all "incoming" values in the specified method,
119// inserting a cast for pointer values that are used as arrays. For our
120// purposes, an incoming value is considered to be either a value that is
121// either a method parameter, a value created by alloca or malloc, or a value
122// returned from a function call. All casts are kept attached to their original
123// values through the PtrCasts map.
124//
125static bool DoInsertArrayCasts(Method *M, map<Value*, CastInst*> &PtrCasts) {
126 assert(!M->isExternal() && "Can't handle external methods!");
127
128 // Insert casts for all arguments to the function...
129 bool Changed = false;
130 BasicBlock *CurBB = M->front();
131 BasicBlock::iterator It = CurBB->begin();
132 for (Method::ArgumentListType::iterator AI = M->getArgumentList().begin(),
133 AE = M->getArgumentList().end(); AI != AE; ++AI) {
134 CastInst *TheCast = 0;
135 if (DoInsertArrayCast(M, *AI, CurBB, It, TheCast)) {
136 It = CurBB->begin(); // We might have just invalidated the iterator!
137 Changed = true; // Yes we made a change
138 ++It; // Insert next cast AFTER this one...
139 }
140
141 if (TheCast) // Is there a cast associated with this value?
142 PtrCasts[*AI] = TheCast; // Yes, add it to the map...
143 }
144
145 // TODO: insert casts for alloca, malloc, and function call results. Also,
146 // look for pointers that already have casts, to add to the map.
147
148 return Changed;
149}
150
151
152
153
154// DoElminatePointerArithmetic - Loop over each incoming pointer variable,
155// replacing indexing arithmetic with getelementptr calls.
156//
157static bool DoEliminatePointerArithmetic(const pair<Value*, CastInst*> &Val) {
158 Value *V = Val.first; // The original pointer
159 CastInst *CV = Val.second; // The array casted version of the pointer...
160
161 for (Value::use_iterator I = V->use_begin(), E = V->use_end(); I != E; ++I) {
162 Instruction *Inst = cast<Instruction>(*I);
163 if (Inst->getOpcode() != Instruction::Add)
164 continue; // We only care about add instructions
165
166 BinaryOperator *Add = cast<BinaryOperator>(Inst);
167
168 // Make sure the array is the first operand of the add expression...
169 if (Add->getOperand(0) != V)
170 Add->swapOperands();
171
172 // Get the amount added to the pointer value...
173 Value *AddAmount = Add->getOperand(1);
174
175
176 }
177 return false;
178}
179
180
181// Peephole Malloc instructions: we take a look at the use chain of the
182// malloc instruction, and try to find out if the following conditions hold:
183// 1. The malloc is of the form: 'malloc [sbyte], uint <constant>'
Chris Lattnerbacec7b2001-11-04 22:11:10 +0000184// 2. The only users of the malloc are cast & add instructions
Chris Lattnerd32a9612001-11-01 02:42:08 +0000185// 3. Of the cast instructions, there is only one destination pointer type
186// [RTy] where the size of the pointed to object is equal to the number
187// of bytes allocated.
188//
189// If these conditions hold, we convert the malloc to allocate an [RTy]
190// element. This should be extended in the future to handle arrays. TODO
191//
192static bool PeepholeMallocInst(BasicBlock *BB, BasicBlock::iterator &BI) {
193 MallocInst *MI = cast<MallocInst>(*BI);
194 if (!MI->isArrayAllocation()) return false; // No array allocation?
195
196 ConstPoolUInt *Amt = dyn_cast<ConstPoolUInt>(MI->getArraySize());
197 if (Amt == 0 || MI->getAllocatedType() != ArrayType::get(Type::SByteTy))
198 return false;
199
200 // Get the number of bytes allocated...
201 unsigned Size = Amt->getValue();
202 const Type *ResultTy = 0;
203
204 // Loop over all of the uses of the malloc instruction, inspecting casts.
205 for (Value::use_iterator I = MI->use_begin(), E = MI->use_end();
206 I != E; ++I) {
Chris Lattnerbacec7b2001-11-04 22:11:10 +0000207 if (CastInst *CI = dyn_cast<CastInst>(*I)) {
208 //cerr << "\t" << CI;
Chris Lattnerd32a9612001-11-01 02:42:08 +0000209
Chris Lattnerbacec7b2001-11-04 22:11:10 +0000210 // We only work on casts to pointer types for sure, be conservative
211 if (!isa<PointerType>(CI->getType())) {
212 cerr << "Found cast of malloc value to non pointer type:\n" << CI;
Chris Lattnerd32a9612001-11-01 02:42:08 +0000213 return false;
214 }
Chris Lattnerbacec7b2001-11-04 22:11:10 +0000215
216 const Type *DestTy = cast<PointerType>(CI->getType())->getValueType();
Chris Lattner3d775c32001-11-13 04:59:41 +0000217 if (isa<ArrayType>(DestTy)) {
218 cerr << "Avoided malloc conversion because of type: " << DestTy
219 << " TODO.\n";
220 return false;
221 }
Chris Lattnerbacec7b2001-11-04 22:11:10 +0000222 if (TD.getTypeSize(DestTy) == Size && DestTy != ResultTy) {
223 // Does the size of the allocated type match the number of bytes
224 // allocated?
225 //
226 if (ResultTy == 0) {
227 ResultTy = DestTy; // Keep note of this for future uses...
228 } else {
229 // It's overdefined! We don't know which type to convert to!
230 return false;
231 }
232 }
Chris Lattnerd32a9612001-11-01 02:42:08 +0000233 }
234 }
235
236 // If we get this far, we have either found, or not, a type that is cast to
237 // that is of the same size as the malloc instruction.
238 if (!ResultTy) return false;
239
Chris Lattnerc109d302001-11-05 21:13:30 +0000240 // Now we check to see if we can convert the return value of malloc to the
241 // specified pointer type. All this is moot if we can't.
242 //
243 ValueTypeCache ConvertedTypes;
244 if (RetValConvertableToType(MI, PointerType::get(ResultTy), ConvertedTypes)) {
245 // Yup, it's convertable, do the transformation now!
246 PRINT_PEEPHOLE1("mall-refine:in ", MI);
247
248 // Create a new malloc instruction, and insert it into the method...
249 MallocInst *NewMI = new MallocInst(PointerType::get(ResultTy));
250 NewMI->setName(MI->getName());
251 MI->setName("");
252 BI = BB->getInstList().insert(BI, NewMI)+1;
253
254 // Create a new cast instruction to cast it to the old type...
255 CastInst *NewCI = new CastInst(NewMI, MI->getType());
256 BB->getInstList().insert(BI, NewCI);
257
258 // Move all users of the old malloc instruction over to use the new cast...
259 MI->replaceAllUsesWith(NewCI);
260
261 ValueMapCache ValueMap;
262 ConvertUsersType(NewCI, NewMI, ValueMap); // This will delete MI!
263
264 BI = BB->begin(); // Rescan basic block. BI might be invalidated.
265 PRINT_PEEPHOLE1("mall-refine:out", NewMI);
266 return true;
267 }
268 return false;
Chris Lattnerd32a9612001-11-01 02:42:08 +0000269}
270
271
Chris Lattnerb9693952001-11-04 07:42:17 +0000272// Peephole optimize the following instructions:
273// %t1 = cast int (uint) * %reg111 to uint (...) *
274// %t2 = call uint (...) * %cast111( uint %key )
275//
276// Into: %t3 = call int (uint) * %reg111( uint %key )
277// %t2 = cast int %t3 to uint
278//
279static bool PeepholeCallInst(BasicBlock *BB, BasicBlock::iterator &BI) {
280 CallInst *CI = cast<CallInst>(*BI);
281 return false;
282}
283
Chris Lattnerd32a9612001-11-01 02:42:08 +0000284
285static bool PeepholeOptimize(BasicBlock *BB, BasicBlock::iterator &BI) {
286 Instruction *I = *BI;
Chris Lattnerd32a9612001-11-01 02:42:08 +0000287
288 if (CastInst *CI = dyn_cast<CastInst>(I)) {
289 Value *Src = CI->getOperand(0);
290 Instruction *SrcI = dyn_cast<Instruction>(Src); // Nonnull if instr source
291 const Type *DestTy = CI->getType();
292
Chris Lattnere99c66b2001-11-01 17:05:27 +0000293 // Peephole optimize the following instruction:
294 // %V2 = cast <ty> %V to <ty>
295 //
296 // Into: <nothing>
297 //
298 if (DestTy == Src->getType()) { // Check for a cast to same type as src!!
Chris Lattnerd32a9612001-11-01 02:42:08 +0000299 PRINT_PEEPHOLE1("cast-of-self-ty", CI);
300 CI->replaceAllUsesWith(Src);
301 if (!Src->hasName() && CI->hasName()) {
302 string Name = CI->getName();
Chris Lattnerf3b976e2001-11-04 20:21:12 +0000303 CI->setName("");
304 Src->setName(Name, BB->getParent()->getSymbolTable());
Chris Lattnerd32a9612001-11-01 02:42:08 +0000305 }
306 return true;
307 }
308
Chris Lattnere99c66b2001-11-01 17:05:27 +0000309 // Peephole optimize the following instructions:
310 // %tmp = cast <ty> %V to <ty2>
311 // %V = cast <ty2> %tmp to <ty3> ; Where ty & ty2 are same size
312 //
313 // Into: cast <ty> %V to <ty3>
314 //
Chris Lattnerd32a9612001-11-01 02:42:08 +0000315 if (SrcI)
316 if (CastInst *CSrc = dyn_cast<CastInst>(SrcI))
317 if (isReinterpretingCast(CI) + isReinterpretingCast(CSrc) < 2) {
318 // We can only do c-c elimination if, at most, one cast does a
319 // reinterpretation of the input data.
320 //
321 // If legal, make this cast refer the the original casts argument!
322 //
323 PRINT_PEEPHOLE2("cast-cast:in ", CI, CSrc);
324 CI->setOperand(0, CSrc->getOperand(0));
325 PRINT_PEEPHOLE1("cast-cast:out", CI);
326 return true;
327 }
328
329 // Check to see if it's a cast of an instruction that does not depend on the
330 // specific type of the operands to do it's job.
Chris Lattnerf3b976e2001-11-04 20:21:12 +0000331 if (!isReinterpretingCast(CI)) {
Chris Lattnerb980e182001-11-04 21:32:11 +0000332 ValueTypeCache ConvertedTypes;
333 if (RetValConvertableToType(CI, Src->getType(), ConvertedTypes)) {
Chris Lattnerbacec7b2001-11-04 22:11:10 +0000334 PRINT_PEEPHOLE2("CAST-DEST-EXPR-CONV:in ", CI, Src);
Chris Lattnerf3b976e2001-11-04 20:21:12 +0000335
Chris Lattnerc0b90e72001-11-08 20:19:56 +0000336#ifdef DEBUG_PEEPHOLE_INSTS
337 cerr << "\nCONVERTING EXPR TYPE:\n";
338#endif
Chris Lattnerb980e182001-11-04 21:32:11 +0000339 ValueMapCache ValueMap;
Chris Lattnere4f4d8c2001-11-05 18:30:53 +0000340 ConvertUsersType(CI, Src, ValueMap); // This will delete CI!
341
Chris Lattnerf3b976e2001-11-04 20:21:12 +0000342 BI = BB->begin(); // Rescan basic block. BI might be invalidated.
Chris Lattnere34443d2001-11-06 08:34:29 +0000343 PRINT_PEEPHOLE1("CAST-DEST-EXPR-CONV:out", Src);
Chris Lattnerc0b90e72001-11-08 20:19:56 +0000344#ifdef DEBUG_PEEPHOLE_INSTS
345 cerr << "DONE CONVERTING EXPR TYPE: \n\n";// << BB->getParent();
346#endif
Chris Lattnerf3b976e2001-11-04 20:21:12 +0000347 return true;
Chris Lattnerc0b90e72001-11-08 20:19:56 +0000348 } else {
349 ConvertedTypes.clear();
350 if (ExpressionConvertableToType(Src, DestTy, ConvertedTypes)) {
351 PRINT_PEEPHOLE2("CAST-SRC-EXPR-CONV:in ", CI, Src);
352
353#ifdef DEBUG_PEEPHOLE_INSTS
354 cerr << "\nCONVERTING SRC EXPR TYPE:\n";
355#endif
356 ValueMapCache ValueMap;
357 Value *E = ConvertExpressionToType(Src, DestTy, ValueMap);
358 if (ConstPoolVal *CPV = dyn_cast<ConstPoolVal>(E))
359 CI->replaceAllUsesWith(CPV);
360
361 BI = BB->begin(); // Rescan basic block. BI might be invalidated.
362 PRINT_PEEPHOLE1("CAST-SRC-EXPR-CONV:out", E);
363#ifdef DEBUG_PEEPHOLE_INSTS
364 cerr << "DONE CONVERTING SRC EXPR TYPE: \n\n";// << BB->getParent();
365#endif
366 return true;
367 }
Chris Lattnerf3b976e2001-11-04 20:21:12 +0000368 }
Chris Lattnerc0b90e72001-11-08 20:19:56 +0000369
Chris Lattnerd32a9612001-11-01 02:42:08 +0000370 }
371
Chris Lattnere99c66b2001-11-01 17:05:27 +0000372 // Check to see if we are casting from a structure pointer to a pointer to
373 // the first element of the structure... to avoid munching other peepholes,
374 // we only let this happen if there are no add uses of the cast.
375 //
376 // Peephole optimize the following instructions:
377 // %t1 = cast {<...>} * %StructPtr to <ty> *
378 //
379 // Into: %t2 = getelementptr {<...>} * %StructPtr, <0, 0, 0, ...>
380 // %t1 = cast <eltype> * %t1 to <ty> *
381 //
Chris Lattnerc0b90e72001-11-08 20:19:56 +0000382#if 1
Chris Lattnere99c66b2001-11-01 17:05:27 +0000383 if (const StructType *STy = getPointedToStruct(Src->getType()))
384 if (const PointerType *DestPTy = dyn_cast<PointerType>(DestTy)) {
385
386 // Loop over uses of the cast, checking for add instructions. If an add
387 // exists, this is probably a part of a more complex GEP, so we don't
388 // want to mess around with the cast.
389 //
390 bool HasAddUse = false;
391 for (Value::use_iterator I = CI->use_begin(), E = CI->use_end();
392 I != E; ++I)
393 if (isa<Instruction>(*I) &&
394 cast<Instruction>(*I)->getOpcode() == Instruction::Add) {
395 HasAddUse = true; break;
396 }
397
398 // If it doesn't have an add use, check to see if the dest type is
399 // losslessly convertable to one of the types in the start of the struct
400 // type.
401 //
402 if (!HasAddUse) {
403 const Type *DestPointedTy = DestPTy->getValueType();
404 unsigned Depth = 1;
405 const StructType *CurSTy = STy;
406 const Type *ElTy = 0;
407 while (CurSTy) {
408
409 // Check for a zero element struct type... if we have one, bail.
410 if (CurSTy->getElementTypes().size() == 0) break;
411
412 // Grab the first element of the struct type, which must lie at
413 // offset zero in the struct.
414 //
415 ElTy = CurSTy->getElementTypes()[0];
416
417 // Did we find what we're looking for?
418 if (losslessCastableTypes(ElTy, DestPointedTy)) break;
419
420 // Nope, go a level deeper.
421 ++Depth;
422 CurSTy = dyn_cast<StructType>(ElTy);
423 ElTy = 0;
424 }
425
426 // Did we find what we were looking for? If so, do the transformation
427 if (ElTy) {
428 PRINT_PEEPHOLE1("cast-for-first:in", CI);
429
430 // Build the index vector, full of all zeros
431 vector<ConstPoolVal *> Indices(Depth,
432 ConstPoolUInt::get(Type::UByteTy,0));
433
434 // Insert the new T cast instruction... stealing old T's name
435 GetElementPtrInst *GEP = new GetElementPtrInst(Src, Indices,
436 CI->getName());
437 CI->setName("");
438 BI = BB->getInstList().insert(BI, GEP)+1;
439
440 // Make the old cast instruction reference the new GEP instead of
441 // the old src value.
442 //
443 CI->setOperand(0, GEP);
444
445 PRINT_PEEPHOLE2("cast-for-first:out", GEP, CI);
446 return true;
447 }
448 }
449 }
Chris Lattnerc0b90e72001-11-08 20:19:56 +0000450#endif
Chris Lattnere99c66b2001-11-01 17:05:27 +0000451
Chris Lattner3d775c32001-11-13 04:59:41 +0000452#if 1
Chris Lattnerd32a9612001-11-01 02:42:08 +0000453 } else if (MallocInst *MI = dyn_cast<MallocInst>(I)) {
454 if (PeepholeMallocInst(BB, BI)) return true;
Chris Lattner8d38e542001-11-01 03:12:34 +0000455
Chris Lattnerb9693952001-11-04 07:42:17 +0000456 } else if (CallInst *CI = dyn_cast<CallInst>(I)) {
457 if (PeepholeCallInst(BB, BI)) return true;
458
Chris Lattner8d38e542001-11-01 03:12:34 +0000459 } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
460 Value *Val = SI->getOperand(0);
461 Value *Pointer = SI->getPtrOperand();
462
Chris Lattnerdedee7b2001-11-01 05:57:59 +0000463 // Peephole optimize the following instructions:
464 // %t1 = getelementptr {<...>} * %StructPtr, <element indices>
465 // store <elementty> %v, <elementty> * %t1
466 //
467 // Into: store <elementty> %v, {<...>} * %StructPtr, <element indices>
468 //
Chris Lattner8d38e542001-11-01 03:12:34 +0000469 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Pointer)) {
Chris Lattnerc0b90e72001-11-08 20:19:56 +0000470 // Append any indices that the store instruction has onto the end of the
471 // ones that the GEP is carrying...
472 //
473 vector<ConstPoolVal*> Indices(GEP->getIndices());
474 Indices.insert(Indices.end(), SI->getIndices().begin(),
475 SI->getIndices().end());
476
Chris Lattner8d38e542001-11-01 03:12:34 +0000477 PRINT_PEEPHOLE2("gep-store:in", GEP, SI);
478 ReplaceInstWithInst(BB->getInstList(), BI,
479 SI = new StoreInst(Val, GEP->getPtrOperand(),
Chris Lattnerc0b90e72001-11-08 20:19:56 +0000480 Indices));
Chris Lattner8d38e542001-11-01 03:12:34 +0000481 PRINT_PEEPHOLE1("gep-store:out", SI);
482 return true;
483 }
Chris Lattnerdedee7b2001-11-01 05:57:59 +0000484
485 // Peephole optimize the following instructions:
486 // %t = cast <T1>* %P to <T2> * ;; If T1 is losslessly convertable to T2
487 // store <T2> %V, <T2>* %t
488 //
489 // Into:
490 // %t = cast <T2> %V to <T1>
491 // store <T1> %t2, <T1>* %P
492 //
493 if (CastInst *CI = dyn_cast<CastInst>(Pointer))
494 if (Value *CastSrc = CI->getOperand(0)) // CSPT = CastSrcPointerType
495 if (PointerType *CSPT = dyn_cast<PointerType>(CastSrc->getType()))
496 if (losslessCastableTypes(Val->getType(), // convertable types!
497 CSPT->getValueType()) &&
498 !SI->hasIndices()) { // No subscripts yet!
499 PRINT_PEEPHOLE3("st-src-cast:in ", Pointer, Val, SI);
500
501 // Insert the new T cast instruction... stealing old T's name
502 CastInst *NCI = new CastInst(Val, CSPT->getValueType(),
503 CI->getName());
504 CI->setName("");
505 BI = BB->getInstList().insert(BI, NCI)+1;
506
507 // Replace the old store with a new one!
508 ReplaceInstWithInst(BB->getInstList(), BI,
509 SI = new StoreInst(NCI, CastSrc));
510 PRINT_PEEPHOLE3("st-src-cast:out", NCI, CastSrc, SI);
511 return true;
512 }
513
Chris Lattner8d38e542001-11-01 03:12:34 +0000514
515 } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
516 Value *Pointer = LI->getPtrOperand();
517
Chris Lattnerdedee7b2001-11-01 05:57:59 +0000518 // Peephole optimize the following instructions:
519 // %t1 = getelementptr {<...>} * %StructPtr, <element indices>
520 // %V = load <elementty> * %t1
521 //
522 // Into: load {<...>} * %StructPtr, <element indices>
523 //
Chris Lattner8d38e542001-11-01 03:12:34 +0000524 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Pointer)) {
Chris Lattnerc0b90e72001-11-08 20:19:56 +0000525 // Append any indices that the load instruction has onto the end of the
526 // ones that the GEP is carrying...
527 //
528 vector<ConstPoolVal*> Indices(GEP->getIndices());
529 Indices.insert(Indices.end(), LI->getIndices().begin(),
530 LI->getIndices().end());
531
Chris Lattner8d38e542001-11-01 03:12:34 +0000532 PRINT_PEEPHOLE2("gep-load:in", GEP, LI);
533 ReplaceInstWithInst(BB->getInstList(), BI,
534 LI = new LoadInst(GEP->getPtrOperand(),
Chris Lattnerc0b90e72001-11-08 20:19:56 +0000535 Indices));
Chris Lattner8d38e542001-11-01 03:12:34 +0000536 PRINT_PEEPHOLE1("gep-load:out", LI);
537 return true;
538 }
Chris Lattnerc0b90e72001-11-08 20:19:56 +0000539
540
541 // Peephole optimize the following instructions:
542 // %t1 = cast <ty> * %t0 to <ty2> *
543 // %V = load <ty2> * %t1
544 //
545 // Into: %t1 = load <ty> * %t0
546 // %V = cast <ty> %t1 to <ty2>
547 //
548 // The idea behind this transformation is that if the expression type
549 // conversion engine could not convert the cast into some other nice form,
550 // that there is something fundementally wrong with the current shape of
551 // the program. Move the cast through the load and try again. This will
552 // leave the original cast instruction, to presumably become dead.
553 //
554 if (CastInst *CI = dyn_cast<CastInst>(Pointer)) {
555 Value *SrcVal = CI->getOperand(0);
556 const PointerType *SrcTy = dyn_cast<PointerType>(SrcVal->getType());
557 const Type *ElTy = SrcTy ? SrcTy->getValueType() : 0;
558
559 // Make sure that nothing will be lost in the new cast...
560 if (SrcTy && losslessCastableTypes(ElTy, LI->getType())) {
561 PRINT_PEEPHOLE2("CL-LoadCast:in ", CI, LI);
562
563 string CName = CI->getName(); CI->setName("");
564 LoadInst *NLI = new LoadInst(SrcVal, LI->getName());
565 LI->setName(""); // Take over the old load's name
566
567 // Insert the load before the old load
568 BI = BB->getInstList().insert(BI, NLI)+1;
569
570 // Replace the old load with a new cast...
571 ReplaceInstWithInst(BB->getInstList(), BI,
572 CI = new CastInst(NLI, LI->getType(), CName));
573 PRINT_PEEPHOLE2("CL-LoadCast:out", NLI, CI);
574
575 return true;
576 }
577 }
Chris Lattnerd32a9612001-11-01 02:42:08 +0000578 } else if (I->getOpcode() == Instruction::Add &&
579 isa<CastInst>(I->getOperand(1))) {
580
581 // Peephole optimize the following instructions:
582 // %t1 = cast ulong <const int> to {<...>} *
583 // %t2 = add {<...>} * %SP, %t1 ;; Constant must be 2nd operand
584 //
585 // or
586 // %t1 = cast {<...>}* %SP to int*
587 // %t5 = cast ulong <const int> to int*
588 // %t2 = add int* %t1, %t5 ;; int is same size as field
589 //
590 // Into: %t3 = getelementptr {<...>} * %SP, <element indices>
591 // %t2 = cast <eltype> * %t3 to {<...>}*
592 //
593 Value *AddOp1 = I->getOperand(0);
594 CastInst *AddOp2 = cast<CastInst>(I->getOperand(1));
595 ConstPoolUInt *OffsetV = dyn_cast<ConstPoolUInt>(AddOp2->getOperand(0));
596 unsigned Offset = OffsetV ? OffsetV->getValue() : 0;
597 Value *SrcPtr; // Of type pointer to struct...
598 const StructType *StructTy;
599
600 if ((StructTy = getPointedToStruct(AddOp1->getType()))) {
601 SrcPtr = AddOp1; // Handle the first case...
602 } else if (CastInst *AddOp1c = dyn_cast<CastInst>(AddOp1)) {
603 SrcPtr = AddOp1c->getOperand(0); // Handle the second case...
604 StructTy = getPointedToStruct(SrcPtr->getType());
605 }
606
607 // Only proceed if we have detected all of our conditions successfully...
608 if (Offset && StructTy && SrcPtr && Offset < TD.getTypeSize(StructTy)) {
609 const StructLayout *SL = TD.getStructLayout(StructTy);
610 vector<ConstPoolVal*> Offsets;
611 unsigned ActualOffset = Offset;
612 const Type *ElTy = getStructOffsetType(StructTy, ActualOffset, Offsets);
613
614 if (getPointedToStruct(AddOp1->getType())) { // case 1
615 PRINT_PEEPHOLE2("add-to-gep1:in", AddOp2, I);
616 } else {
617 PRINT_PEEPHOLE3("add-to-gep2:in", AddOp1, AddOp2, I);
618 }
619
620 GetElementPtrInst *GEP = new GetElementPtrInst(SrcPtr, Offsets);
Chris Lattnerc0b90e72001-11-08 20:19:56 +0000621 //AddOp2->getName());
Chris Lattnerd32a9612001-11-01 02:42:08 +0000622 BI = BB->getInstList().insert(BI, GEP)+1;
623
624 assert(Offset-ActualOffset == 0 &&
625 "GEP to middle of element not implemented yet!");
626
627 ReplaceInstWithInst(BB->getInstList(), BI,
628 I = new CastInst(GEP, I->getType()));
629 PRINT_PEEPHOLE2("add-to-gep:out", GEP, I);
630 return true;
631 }
Chris Lattner3d775c32001-11-13 04:59:41 +0000632#endif
Chris Lattnerd32a9612001-11-01 02:42:08 +0000633 }
634
635 return false;
636}
637
638
639
640
641static bool DoRaisePass(Method *M) {
642 bool Changed = false;
643 for (Method::iterator MI = M->begin(), ME = M->end(); MI != ME; ++MI) {
644 BasicBlock *BB = *MI;
645 BasicBlock::InstListType &BIL = BB->getInstList();
646
647 for (BasicBlock::iterator BI = BB->begin(); BI != BB->end();) {
Chris Lattnerc0b90e72001-11-08 20:19:56 +0000648 if (opt::DeadCodeElimination::dceInstruction(BIL, BI)) {
649 Changed = true;
650#ifdef DEBUG_PEEPHOLE_INSTS
651 cerr << "DeadCode Elinated!\n";
652#endif
653 } else if (PeepholeOptimize(BB, BI))
Chris Lattnerd32a9612001-11-01 02:42:08 +0000654 Changed = true;
655 else
656 ++BI;
657 }
658 }
659 return Changed;
660}
661
662
663// RaisePointerReferences::doit - Raise a method representation to a higher
664// level.
665//
666bool RaisePointerReferences::doit(Method *M) {
667 if (M->isExternal()) return false;
668 bool Changed = false;
669
Chris Lattner68b07b72001-11-01 07:00:51 +0000670#ifdef DEBUG_PEEPHOLE_INSTS
671 cerr << "\n\n\nStarting to work on Method '" << M->getName() << "'\n";
672#endif
673
Chris Lattnerd32a9612001-11-01 02:42:08 +0000674 while (DoRaisePass(M)) Changed = true;
675
Chris Lattnerc0b90e72001-11-08 20:19:56 +0000676#if 0
Chris Lattnerd32a9612001-11-01 02:42:08 +0000677 // PtrCasts - Keep a mapping between the pointer values (the key of the
678 // map), and the cast to array pointer (the value) in this map. This is
679 // used when converting pointer math into array addressing.
680 //
681 map<Value*, CastInst*> PtrCasts;
682
683 // Insert casts for all incoming pointer values. Keep track of those casts
684 // and the identified incoming values in the PtrCasts map.
685 //
686 Changed |= DoInsertArrayCasts(M, PtrCasts);
687
688 // Loop over each incoming pointer variable, replacing indexing arithmetic
689 // with getelementptr calls.
690 //
691 Changed |= reduce_apply_bool(PtrCasts.begin(), PtrCasts.end(),
692 ptr_fun(DoEliminatePointerArithmetic));
Chris Lattnerc0b90e72001-11-08 20:19:56 +0000693#endif
Chris Lattnerd32a9612001-11-01 02:42:08 +0000694
695 return Changed;
696}