blob: 9f93c27f5382c8d7e3c718bc39b29a57e180b0d0 [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
Chris Lattnerb7135992002-07-23 19:57:08 +00009#include "llvm/Transforms/RaisePointerReferences.h"
Chris Lattner497c60c2002-05-07 18:12:18 +000010#include "llvm/Transforms/Utils/Local.h"
Chris Lattner59cd9f12001-11-04 23:24:06 +000011#include "TransformInternals.h"
Chris Lattnerd32a9612001-11-01 02:42:08 +000012#include "llvm/iOther.h"
13#include "llvm/iMemory.h"
Chris Lattnerbd0ef772002-02-26 21:46:54 +000014#include "llvm/Pass.h"
Chris Lattner968ddc92002-04-08 20:18:09 +000015#include "llvm/ConstantHandling.h"
Chris Lattnerd5b48ca2001-11-14 11:02:49 +000016#include "llvm/Analysis/Expressions.h"
Chris Lattner3378a5b2002-07-16 23:49:24 +000017#include "llvm/Analysis/Verifier.h"
Chris Lattner497c60c2002-05-07 18:12:18 +000018#include "llvm/Transforms/Utils/BasicBlockUtils.h"
Chris Lattnercee8f9a2001-11-27 00:03:19 +000019#include "Support/STLExtras.h"
Chris Lattner6ee6bbe2002-10-01 22:38:37 +000020#include "Support/Statistic.h"
Chris Lattner3378a5b2002-07-16 23:49:24 +000021#include "Support/CommandLine.h"
Chris Lattnerd32a9612001-11-01 02:42:08 +000022#include <algorithm>
Anand Shuklacfb22d32002-06-25 20:55:50 +000023using std::cerr;
Chris Lattnerd32a9612001-11-01 02:42:08 +000024
Chris Lattner3378a5b2002-07-16 23:49:24 +000025// StartInst - This enables the -raise-start-inst=foo option to cause the level
26// raising pass to start at instruction "foo", which is immensely useful for
27// debugging!
28//
Chris Lattner5ff62e92002-07-22 02:10:13 +000029static cl::opt<std::string>
30StartInst("raise-start-inst", cl::Hidden, cl::value_desc("inst name"),
31 cl::desc("Start raise pass at the instruction with the specified name"));
Chris Lattner3378a5b2002-07-16 23:49:24 +000032
Chris Lattner5ff62e92002-07-22 02:10:13 +000033static Statistic<>
Chris Lattner6ee6bbe2002-10-01 22:38:37 +000034NumLoadStorePeepholes("raise", "Number of load/store peepholes");
Chris Lattner5ff62e92002-07-22 02:10:13 +000035
36static Statistic<>
Chris Lattner6ee6bbe2002-10-01 22:38:37 +000037NumGEPInstFormed("raise", "Number of other getelementptr's formed");
Chris Lattner5ff62e92002-07-22 02:10:13 +000038
39static Statistic<>
Chris Lattner6ee6bbe2002-10-01 22:38:37 +000040NumExprTreesConv("raise", "Number of expression trees converted");
Chris Lattner5ff62e92002-07-22 02:10:13 +000041
42static Statistic<>
Chris Lattner6ee6bbe2002-10-01 22:38:37 +000043NumCastOfCast("raise", "Number of cast-of-self removed");
Chris Lattner5ff62e92002-07-22 02:10:13 +000044
45static Statistic<>
Chris Lattner6ee6bbe2002-10-01 22:38:37 +000046NumDCEorCP("raise", "Number of insts DCEd or constprop'd");
Chris Lattner3c019372002-05-10 15:29:25 +000047
Chris Lattner61b92c02002-10-08 22:19:25 +000048static Statistic<>
49NumVarargCallChanges("raise", "Number of vararg call peepholes");
50
Chris Lattner3c019372002-05-10 15:29:25 +000051
Chris Lattnerd32a9612001-11-01 02:42:08 +000052#define PRINT_PEEPHOLE(ID, NUM, I) \
Chris Lattnerb3abf9d2002-05-22 17:27:12 +000053 DEBUG(std::cerr << "Inst P/H " << ID << "[" << NUM << "] " << I)
Chris Lattnerd32a9612001-11-01 02:42:08 +000054
55#define PRINT_PEEPHOLE1(ID, I1) do { PRINT_PEEPHOLE(ID, 0, I1); } while (0)
56#define PRINT_PEEPHOLE2(ID, I1, I2) \
57 do { PRINT_PEEPHOLE(ID, 0, I1); PRINT_PEEPHOLE(ID, 1, I2); } while (0)
58#define PRINT_PEEPHOLE3(ID, I1, I2, I3) \
59 do { PRINT_PEEPHOLE(ID, 0, I1); PRINT_PEEPHOLE(ID, 1, I2); \
60 PRINT_PEEPHOLE(ID, 2, I3); } while (0)
Chris Lattnerd5b48ca2001-11-14 11:02:49 +000061#define PRINT_PEEPHOLE4(ID, I1, I2, I3, I4) \
62 do { PRINT_PEEPHOLE(ID, 0, I1); PRINT_PEEPHOLE(ID, 1, I2); \
63 PRINT_PEEPHOLE(ID, 2, I3); PRINT_PEEPHOLE(ID, 3, I4); } while (0)
Chris Lattnerd32a9612001-11-01 02:42:08 +000064
Chris Lattner16125fb2003-04-24 18:25:27 +000065namespace {
66 struct RPR : public FunctionPass {
67 virtual bool runOnFunction(Function &F);
68
69 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
70 AU.setPreservesCFG();
71 AU.addRequired<TargetData>();
72 }
73
74 private:
75 bool DoRaisePass(Function &F);
76 bool PeepholeOptimize(BasicBlock *BB, BasicBlock::iterator &BI);
77 };
78
79 RegisterOpt<RPR> X("raise", "Raise Pointer References");
80}
81
82Pass *createRaisePointerReferencesPass() {
83 return new RPR();
84}
85
86
Chris Lattnerd32a9612001-11-01 02:42:08 +000087
Chris Lattnerd32a9612001-11-01 02:42:08 +000088// isReinterpretingCast - Return true if the cast instruction specified will
89// cause the operand to be "reinterpreted". A value is reinterpreted if the
90// cast instruction would cause the underlying bits to change.
91//
92static inline bool isReinterpretingCast(const CastInst *CI) {
Misha Brukmanf117cc92003-05-20 18:45:36 +000093 return!CI->getOperand(0)->getType()->isLosslesslyConvertibleTo(CI->getType());
Chris Lattnerd32a9612001-11-01 02:42:08 +000094}
95
96
Chris Lattnera8b6d432001-12-05 06:34:00 +000097// Peephole optimize the following instructions:
98// %t1 = cast ? to x *
99// %t2 = add x * %SP, %t1 ;; Constant must be 2nd operand
100//
101// Into: %t3 = getelementptr {<...>} * %SP, <element indices>
102// %t2 = cast <eltype> * %t3 to {<...>}*
103//
104static bool HandleCastToPointer(BasicBlock::iterator BI,
Chris Lattner16125fb2003-04-24 18:25:27 +0000105 const PointerType *DestPTy,
106 const TargetData &TD) {
Chris Lattner7e708292002-06-25 16:13:24 +0000107 CastInst &CI = cast<CastInst>(*BI);
108 if (CI.use_empty()) return false;
Chris Lattnerf3b976e2001-11-04 20:21:12 +0000109
Chris Lattner2d399092003-05-02 19:32:04 +0000110 // Scan all of the uses, looking for any uses that are not add or sub
Chris Lattnera8b6d432001-12-05 06:34:00 +0000111 // instructions. If we have non-adds, do not make this transformation.
112 //
Chris Lattner2d399092003-05-02 19:32:04 +0000113 bool HasSubUse = false; // Keep track of any subtracts...
Chris Lattner7e708292002-06-25 16:13:24 +0000114 for (Value::use_iterator I = CI.use_begin(), E = CI.use_end();
Chris Lattner2d399092003-05-02 19:32:04 +0000115 I != E; ++I)
Chris Lattnera8b6d432001-12-05 06:34:00 +0000116 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(*I)) {
Chris Lattner2d399092003-05-02 19:32:04 +0000117 if ((BO->getOpcode() != Instruction::Add &&
118 BO->getOpcode() != Instruction::Sub) ||
Chris Lattner3fb2ddd2002-07-16 21:41:31 +0000119 // Avoid add sbyte* %X, %X cases...
120 BO->getOperand(0) == BO->getOperand(1))
Chris Lattnera8b6d432001-12-05 06:34:00 +0000121 return false;
Chris Lattner2d399092003-05-02 19:32:04 +0000122 else
123 HasSubUse |= BO->getOpcode() == Instruction::Sub;
Chris Lattnera8b6d432001-12-05 06:34:00 +0000124 } else {
125 return false;
126 }
Chris Lattnera8b6d432001-12-05 06:34:00 +0000127
Chris Lattner697954c2002-01-20 22:54:45 +0000128 std::vector<Value*> Indices;
Chris Lattner7e708292002-06-25 16:13:24 +0000129 Value *Src = CI.getOperand(0);
Misha Brukmanf117cc92003-05-20 18:45:36 +0000130 const Type *Result = ConvertibleToGEP(DestPTy, Src, Indices, TD, &BI);
131 if (Result == 0) return false; // Not convertible...
Chris Lattnera8b6d432001-12-05 06:34:00 +0000132
Chris Lattner2d399092003-05-02 19:32:04 +0000133 // Cannot handle subtracts if there is more than one index required...
134 if (HasSubUse && Indices.size() != 1) return false;
135
Chris Lattnera8b6d432001-12-05 06:34:00 +0000136 PRINT_PEEPHOLE2("cast-add-to-gep:in", Src, CI);
137
138 // If we have a getelementptr capability... transform all of the
139 // add instruction uses into getelementptr's.
Chris Lattner7e708292002-06-25 16:13:24 +0000140 while (!CI.use_empty()) {
141 BinaryOperator *I = cast<BinaryOperator>(*CI.use_begin());
Chris Lattner2d399092003-05-02 19:32:04 +0000142 assert((I->getOpcode() == Instruction::Add ||
143 I->getOpcode() == Instruction::Sub) &&
Chris Lattnera8b6d432001-12-05 06:34:00 +0000144 "Use is not a valid add instruction!");
145
146 // Get the value added to the cast result pointer...
Chris Lattner7e708292002-06-25 16:13:24 +0000147 Value *OtherPtr = I->getOperand((I->getOperand(0) == &CI) ? 1 : 0);
Chris Lattnera8b6d432001-12-05 06:34:00 +0000148
Chris Lattner45ef5c22002-03-21 06:22:23 +0000149 Instruction *GEP = new GetElementPtrInst(OtherPtr, Indices, I->getName());
Chris Lattnera8b6d432001-12-05 06:34:00 +0000150 PRINT_PEEPHOLE1("cast-add-to-gep:i", I);
Chris Lattner45ef5c22002-03-21 06:22:23 +0000151
Chris Lattner2d399092003-05-02 19:32:04 +0000152 // If the instruction is actually a subtract, we are guaranteed to only have
153 // one index (from code above), so we just need to negate the pointer index
154 // long value.
155 if (I->getOpcode() == Instruction::Sub) {
156 Instruction *Neg = BinaryOperator::createNeg(GEP->getOperand(1),
157 GEP->getOperand(1)->getName()+".neg", I);
158 GEP->setOperand(1, Neg);
159 }
160
Chris Lattner45ef5c22002-03-21 06:22:23 +0000161 if (GEP->getType() == I->getType()) {
162 // Replace the old add instruction with the shiny new GEP inst
163 ReplaceInstWithInst(I, GEP);
164 } else {
165 // If the type produced by the gep instruction differs from the original
166 // add instruction type, insert a cast now.
167 //
168
Chris Lattner7e708292002-06-25 16:13:24 +0000169 // Insert the GEP instruction before the old add instruction...
170 I->getParent()->getInstList().insert(I, GEP);
Chris Lattner45ef5c22002-03-21 06:22:23 +0000171
172 PRINT_PEEPHOLE1("cast-add-to-gep:o", GEP);
Chris Lattner7e708292002-06-25 16:13:24 +0000173 GEP = new CastInst(GEP, I->getType());
Chris Lattner45ef5c22002-03-21 06:22:23 +0000174
175 // Replace the old add instruction with the shiny new GEP inst
Chris Lattner7e708292002-06-25 16:13:24 +0000176 ReplaceInstWithInst(I, GEP);
Chris Lattner45ef5c22002-03-21 06:22:23 +0000177 }
178
Chris Lattnera8b6d432001-12-05 06:34:00 +0000179 PRINT_PEEPHOLE1("cast-add-to-gep:o", GEP);
180 }
181 return true;
182}
Chris Lattnerd5b48ca2001-11-14 11:02:49 +0000183
184// Peephole optimize the following instructions:
185// %t1 = cast ulong <const int> to {<...>} *
186// %t2 = add {<...>} * %SP, %t1 ;; Constant must be 2nd operand
187//
188// or
189// %t1 = cast {<...>}* %SP to int*
190// %t5 = cast ulong <const int> to int*
191// %t2 = add int* %t1, %t5 ;; int is same size as field
192//
193// Into: %t3 = getelementptr {<...>} * %SP, <element indices>
194// %t2 = cast <eltype> * %t3 to {<...>}*
195//
196static bool PeepholeOptimizeAddCast(BasicBlock *BB, BasicBlock::iterator &BI,
Chris Lattner16125fb2003-04-24 18:25:27 +0000197 Value *AddOp1, CastInst *AddOp2,
198 const TargetData &TD) {
Chris Lattner3cc7dde2001-11-26 16:58:14 +0000199 const CompositeType *CompTy;
200 Value *OffsetVal = AddOp2->getOperand(0);
Chris Lattner0ceeb422002-10-22 23:34:11 +0000201 Value *SrcPtr = 0; // Of type pointer to struct...
Chris Lattnerd5b48ca2001-11-14 11:02:49 +0000202
Chris Lattner3cc7dde2001-11-26 16:58:14 +0000203 if ((CompTy = getPointedToComposite(AddOp1->getType()))) {
Chris Lattnerd5b48ca2001-11-14 11:02:49 +0000204 SrcPtr = AddOp1; // Handle the first case...
205 } else if (CastInst *AddOp1c = dyn_cast<CastInst>(AddOp1)) {
206 SrcPtr = AddOp1c->getOperand(0); // Handle the second case...
Chris Lattner3cc7dde2001-11-26 16:58:14 +0000207 CompTy = getPointedToComposite(SrcPtr->getType());
Chris Lattnerd5b48ca2001-11-14 11:02:49 +0000208 }
209
210 // Only proceed if we have detected all of our conditions successfully...
Chris Lattner0c4e8862002-09-03 01:08:28 +0000211 if (!CompTy || !SrcPtr || !OffsetVal->getType()->isInteger())
Chris Lattnerd5b48ca2001-11-14 11:02:49 +0000212 return false;
213
Chris Lattner697954c2002-01-20 22:54:45 +0000214 std::vector<Value*> Indices;
Misha Brukmanf117cc92003-05-20 18:45:36 +0000215 if (!ConvertibleToGEP(SrcPtr->getType(), OffsetVal, Indices, TD, &BI))
216 return false; // Not convertible... perhaps next time
Chris Lattnerd5b48ca2001-11-14 11:02:49 +0000217
Chris Lattner3cc7dde2001-11-26 16:58:14 +0000218 if (getPointedToComposite(AddOp1->getType())) { // case 1
Chris Lattnerd5b48ca2001-11-14 11:02:49 +0000219 PRINT_PEEPHOLE2("add-to-gep1:in", AddOp2, *BI);
220 } else {
221 PRINT_PEEPHOLE3("add-to-gep2:in", AddOp1, AddOp2, *BI);
222 }
223
Chris Lattner3cc7dde2001-11-26 16:58:14 +0000224 GetElementPtrInst *GEP = new GetElementPtrInst(SrcPtr, Indices,
Chris Lattner2a7c23e2002-09-10 17:04:02 +0000225 AddOp2->getName(), BI);
Chris Lattnerd5b48ca2001-11-14 11:02:49 +0000226
Chris Lattner3cc7dde2001-11-26 16:58:14 +0000227 Instruction *NCI = new CastInst(GEP, AddOp1->getType());
Chris Lattnerd5b48ca2001-11-14 11:02:49 +0000228 ReplaceInstWithInst(BB->getInstList(), BI, NCI);
229 PRINT_PEEPHOLE2("add-to-gep:out", GEP, NCI);
230 return true;
231}
232
Chris Lattner16125fb2003-04-24 18:25:27 +0000233bool RPR::PeepholeOptimize(BasicBlock *BB, BasicBlock::iterator &BI) {
Chris Lattner7e708292002-06-25 16:13:24 +0000234 Instruction *I = BI;
Chris Lattner16125fb2003-04-24 18:25:27 +0000235 const TargetData &TD = getAnalysis<TargetData>();
Chris Lattnerd32a9612001-11-01 02:42:08 +0000236
237 if (CastInst *CI = dyn_cast<CastInst>(I)) {
238 Value *Src = CI->getOperand(0);
239 Instruction *SrcI = dyn_cast<Instruction>(Src); // Nonnull if instr source
240 const Type *DestTy = CI->getType();
241
Chris Lattnere99c66b2001-11-01 17:05:27 +0000242 // Peephole optimize the following instruction:
243 // %V2 = cast <ty> %V to <ty>
244 //
245 // Into: <nothing>
246 //
247 if (DestTy == Src->getType()) { // Check for a cast to same type as src!!
Chris Lattnerd32a9612001-11-01 02:42:08 +0000248 PRINT_PEEPHOLE1("cast-of-self-ty", CI);
249 CI->replaceAllUsesWith(Src);
250 if (!Src->hasName() && CI->hasName()) {
Chris Lattner697954c2002-01-20 22:54:45 +0000251 std::string Name = CI->getName();
Chris Lattnerf3b976e2001-11-04 20:21:12 +0000252 CI->setName("");
Chris Lattner6e6026b2002-11-20 18:36:02 +0000253 Src->setName(Name, &BB->getParent()->getSymbolTable());
Chris Lattnerd32a9612001-11-01 02:42:08 +0000254 }
Chris Lattner3c019372002-05-10 15:29:25 +0000255
256 // DCE the instruction now, to avoid having the iterative version of DCE
257 // have to worry about it.
258 //
Chris Lattner7e708292002-06-25 16:13:24 +0000259 BI = BB->getInstList().erase(BI);
Chris Lattner3c019372002-05-10 15:29:25 +0000260
261 ++NumCastOfCast;
Chris Lattnerd32a9612001-11-01 02:42:08 +0000262 return true;
263 }
264
Chris Lattnerd32a9612001-11-01 02:42:08 +0000265 // Check to see if it's a cast of an instruction that does not depend on the
266 // specific type of the operands to do it's job.
Chris Lattnerf3b976e2001-11-04 20:21:12 +0000267 if (!isReinterpretingCast(CI)) {
Chris Lattnerb980e182001-11-04 21:32:11 +0000268 ValueTypeCache ConvertedTypes;
Chris Lattnera8b6d432001-12-05 06:34:00 +0000269
Chris Lattnerd20a98e2002-05-24 20:41:51 +0000270 // Check to see if we can convert the source of the cast to match the
271 // destination type of the cast...
Chris Lattnera8b6d432001-12-05 06:34:00 +0000272 //
Chris Lattnerd5543802001-12-14 16:37:52 +0000273 ConvertedTypes[CI] = CI->getType(); // Make sure the cast doesn't change
Misha Brukmanf117cc92003-05-20 18:45:36 +0000274 if (ExpressionConvertibleToType(Src, DestTy, ConvertedTypes, TD)) {
Chris Lattnerd5543802001-12-14 16:37:52 +0000275 PRINT_PEEPHOLE3("CAST-SRC-EXPR-CONV:in ", Src, CI, BB->getParent());
Chris Lattnerc0b90e72001-11-08 20:19:56 +0000276
Chris Lattnerb3abf9d2002-05-22 17:27:12 +0000277 DEBUG(cerr << "\nCONVERTING SRC EXPR TYPE:\n");
Chris Lattnerb1b42622002-07-17 17:11:33 +0000278 { // ValueMap must be destroyed before function verified!
279 ValueMapCache ValueMap;
Chris Lattner16125fb2003-04-24 18:25:27 +0000280 Value *E = ConvertExpressionToType(Src, DestTy, ValueMap, TD);
Chris Lattnerc0b90e72001-11-08 20:19:56 +0000281
Chris Lattnerb1b42622002-07-17 17:11:33 +0000282 if (Constant *CPV = dyn_cast<Constant>(E))
283 CI->replaceAllUsesWith(CPV);
284
285 PRINT_PEEPHOLE1("CAST-SRC-EXPR-CONV:out", E);
286 DEBUG(cerr << "DONE CONVERTING SRC EXPR TYPE: \n" << BB->getParent());
287 }
Chris Lattner3378a5b2002-07-16 23:49:24 +0000288
289 DEBUG(assert(verifyFunction(*BB->getParent()) == false &&
290 "Function broken!"));
Chris Lattnerb1b42622002-07-17 17:11:33 +0000291 BI = BB->begin(); // Rescan basic block. BI might be invalidated.
Chris Lattner3c019372002-05-10 15:29:25 +0000292 ++NumExprTreesConv;
Chris Lattnerd5543802001-12-14 16:37:52 +0000293 return true;
294 }
295
Chris Lattnerd20a98e2002-05-24 20:41:51 +0000296 // Check to see if we can convert the users of the cast value to match the
297 // source type of the cast...
Chris Lattnerd5543802001-12-14 16:37:52 +0000298 //
299 ConvertedTypes.clear();
Chris Lattner61b92c02002-10-08 22:19:25 +0000300 // Make sure the source doesn't change type
301 ConvertedTypes[Src] = Src->getType();
Misha Brukmanf117cc92003-05-20 18:45:36 +0000302 if (ValueConvertibleToType(CI, Src->getType(), ConvertedTypes, TD)) {
Chris Lattnerd5543802001-12-14 16:37:52 +0000303 PRINT_PEEPHOLE3("CAST-DEST-EXPR-CONV:in ", Src, CI, BB->getParent());
304
Chris Lattnerb3abf9d2002-05-22 17:27:12 +0000305 DEBUG(cerr << "\nCONVERTING EXPR TYPE:\n");
Chris Lattnerb1b42622002-07-17 17:11:33 +0000306 { // ValueMap must be destroyed before function verified!
307 ValueMapCache ValueMap;
Chris Lattner16125fb2003-04-24 18:25:27 +0000308 ConvertValueToNewType(CI, Src, ValueMap, TD); // This will delete CI!
Chris Lattnerb1b42622002-07-17 17:11:33 +0000309 }
Chris Lattnerd5543802001-12-14 16:37:52 +0000310
Chris Lattnerd5543802001-12-14 16:37:52 +0000311 PRINT_PEEPHOLE1("CAST-DEST-EXPR-CONV:out", Src);
Chris Lattnerb3abf9d2002-05-22 17:27:12 +0000312 DEBUG(cerr << "DONE CONVERTING EXPR TYPE: \n\n" << BB->getParent());
Chris Lattner3378a5b2002-07-16 23:49:24 +0000313
314 DEBUG(assert(verifyFunction(*BB->getParent()) == false &&
315 "Function broken!"));
Chris Lattnerb1b42622002-07-17 17:11:33 +0000316 BI = BB->begin(); // Rescan basic block. BI might be invalidated.
Chris Lattner3c019372002-05-10 15:29:25 +0000317 ++NumExprTreesConv;
Chris Lattnera8b6d432001-12-05 06:34:00 +0000318 return true;
Chris Lattnerf3b976e2001-11-04 20:21:12 +0000319 }
Chris Lattnerf17a09d2001-12-06 18:06:13 +0000320 }
321
322 // Otherwise find out it this cast is a cast to a pointer type, which is
323 // then added to some other pointer, then loaded or stored through. If
324 // so, convert the add into a getelementptr instruction...
325 //
326 if (const PointerType *DestPTy = dyn_cast<PointerType>(DestTy)) {
Chris Lattner16125fb2003-04-24 18:25:27 +0000327 if (HandleCastToPointer(BI, DestPTy, TD)) {
Chris Lattnerf17a09d2001-12-06 18:06:13 +0000328 BI = BB->begin(); // Rescan basic block. BI might be invalidated.
Chris Lattner3c019372002-05-10 15:29:25 +0000329 ++NumGEPInstFormed;
Chris Lattnerf17a09d2001-12-06 18:06:13 +0000330 return true;
Chris Lattnera8b6d432001-12-05 06:34:00 +0000331 }
Chris Lattnerd32a9612001-11-01 02:42:08 +0000332 }
333
Chris Lattnere99c66b2001-11-01 17:05:27 +0000334 // Check to see if we are casting from a structure pointer to a pointer to
335 // the first element of the structure... to avoid munching other peepholes,
336 // we only let this happen if there are no add uses of the cast.
337 //
338 // Peephole optimize the following instructions:
339 // %t1 = cast {<...>} * %StructPtr to <ty> *
340 //
341 // Into: %t2 = getelementptr {<...>} * %StructPtr, <0, 0, 0, ...>
342 // %t1 = cast <eltype> * %t1 to <ty> *
343 //
Chris Lattner3cc7dde2001-11-26 16:58:14 +0000344 if (const CompositeType *CTy = getPointedToComposite(Src->getType()))
Chris Lattnere99c66b2001-11-01 17:05:27 +0000345 if (const PointerType *DestPTy = dyn_cast<PointerType>(DestTy)) {
346
347 // Loop over uses of the cast, checking for add instructions. If an add
348 // exists, this is probably a part of a more complex GEP, so we don't
349 // want to mess around with the cast.
350 //
351 bool HasAddUse = false;
352 for (Value::use_iterator I = CI->use_begin(), E = CI->use_end();
353 I != E; ++I)
354 if (isa<Instruction>(*I) &&
355 cast<Instruction>(*I)->getOpcode() == Instruction::Add) {
356 HasAddUse = true; break;
357 }
358
359 // If it doesn't have an add use, check to see if the dest type is
Misha Brukmanf117cc92003-05-20 18:45:36 +0000360 // losslessly convertible to one of the types in the start of the struct
Chris Lattnere99c66b2001-11-01 17:05:27 +0000361 // type.
362 //
363 if (!HasAddUse) {
Chris Lattner7a176752001-12-04 00:03:30 +0000364 const Type *DestPointedTy = DestPTy->getElementType();
Chris Lattnere99c66b2001-11-01 17:05:27 +0000365 unsigned Depth = 1;
Chris Lattner3cc7dde2001-11-26 16:58:14 +0000366 const CompositeType *CurCTy = CTy;
Chris Lattnere99c66b2001-11-01 17:05:27 +0000367 const Type *ElTy = 0;
Chris Lattner3cc7dde2001-11-26 16:58:14 +0000368
369 // Build the index vector, full of all zeros
Chris Lattner697954c2002-01-20 22:54:45 +0000370 std::vector<Value*> Indices;
Chris Lattner106ff452002-09-11 01:21:29 +0000371 Indices.push_back(ConstantSInt::get(Type::LongTy, 0));
Chris Lattnerd5543802001-12-14 16:37:52 +0000372 while (CurCTy && !isa<PointerType>(CurCTy)) {
Chris Lattner3cc7dde2001-11-26 16:58:14 +0000373 if (const StructType *CurSTy = dyn_cast<StructType>(CurCTy)) {
374 // Check for a zero element struct type... if we have one, bail.
375 if (CurSTy->getElementTypes().size() == 0) break;
Chris Lattnere99c66b2001-11-01 17:05:27 +0000376
Chris Lattner3cc7dde2001-11-26 16:58:14 +0000377 // Grab the first element of the struct type, which must lie at
378 // offset zero in the struct.
379 //
380 ElTy = CurSTy->getElementTypes()[0];
381 } else {
382 ElTy = cast<ArrayType>(CurCTy)->getElementType();
383 }
384
385 // Insert a zero to index through this type...
Chris Lattner106ff452002-09-11 01:21:29 +0000386 Indices.push_back(Constant::getNullValue(CurCTy->getIndexType()));
Chris Lattnere99c66b2001-11-01 17:05:27 +0000387
388 // Did we find what we're looking for?
Misha Brukmanf117cc92003-05-20 18:45:36 +0000389 if (ElTy->isLosslesslyConvertibleTo(DestPointedTy)) break;
Chris Lattnere99c66b2001-11-01 17:05:27 +0000390
391 // Nope, go a level deeper.
392 ++Depth;
Chris Lattner3cc7dde2001-11-26 16:58:14 +0000393 CurCTy = dyn_cast<CompositeType>(ElTy);
Chris Lattnere99c66b2001-11-01 17:05:27 +0000394 ElTy = 0;
395 }
396
397 // Did we find what we were looking for? If so, do the transformation
398 if (ElTy) {
399 PRINT_PEEPHOLE1("cast-for-first:in", CI);
400
Chris Lattner2a7c23e2002-09-10 17:04:02 +0000401 std::string Name = CI->getName(); CI->setName("");
402
Chris Lattnere99c66b2001-11-01 17:05:27 +0000403 // Insert the new T cast instruction... stealing old T's name
404 GetElementPtrInst *GEP = new GetElementPtrInst(Src, Indices,
Chris Lattner2a7c23e2002-09-10 17:04:02 +0000405 Name, BI);
Chris Lattnere99c66b2001-11-01 17:05:27 +0000406
407 // Make the old cast instruction reference the new GEP instead of
408 // the old src value.
409 //
410 CI->setOperand(0, GEP);
411
412 PRINT_PEEPHOLE2("cast-for-first:out", GEP, CI);
Chris Lattner3c019372002-05-10 15:29:25 +0000413 ++NumGEPInstFormed;
Chris Lattnere99c66b2001-11-01 17:05:27 +0000414 return true;
415 }
416 }
417 }
Chris Lattnere99c66b2001-11-01 17:05:27 +0000418
Chris Lattner8d38e542001-11-01 03:12:34 +0000419 } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
420 Value *Val = SI->getOperand(0);
Chris Lattner65ea1712001-11-14 11:27:58 +0000421 Value *Pointer = SI->getPointerOperand();
Chris Lattner8d38e542001-11-01 03:12:34 +0000422
Chris Lattnerdedee7b2001-11-01 05:57:59 +0000423 // Peephole optimize the following instructions:
Misha Brukmanf117cc92003-05-20 18:45:36 +0000424 // %t = cast <T1>* %P to <T2> * ;; If T1 is losslessly convertible to T2
Chris Lattnerdedee7b2001-11-01 05:57:59 +0000425 // store <T2> %V, <T2>* %t
426 //
427 // Into:
428 // %t = cast <T2> %V to <T1>
429 // store <T1> %t2, <T1>* %P
430 //
Chris Lattnerd5543802001-12-14 16:37:52 +0000431 // Note: This is not taken care of by expr conversion because there might
432 // not be a cast available for the store to convert the incoming value of.
433 // This code is basically here to make sure that pointers don't have casts
434 // if possible.
435 //
Chris Lattnerdedee7b2001-11-01 05:57:59 +0000436 if (CastInst *CI = dyn_cast<CastInst>(Pointer))
437 if (Value *CastSrc = CI->getOperand(0)) // CSPT = CastSrcPointerType
Chris Lattner7e708292002-06-25 16:13:24 +0000438 if (const PointerType *CSPT = dyn_cast<PointerType>(CastSrc->getType()))
Misha Brukmanf117cc92003-05-20 18:45:36 +0000439 // convertible types?
440 if (Val->getType()->isLosslesslyConvertibleTo(CSPT->getElementType())) {
Chris Lattnerdedee7b2001-11-01 05:57:59 +0000441 PRINT_PEEPHOLE3("st-src-cast:in ", Pointer, Val, SI);
442
443 // Insert the new T cast instruction... stealing old T's name
Chris Lattner2a7c23e2002-09-10 17:04:02 +0000444 std::string Name(CI->getName()); CI->setName("");
Chris Lattner7a176752001-12-04 00:03:30 +0000445 CastInst *NCI = new CastInst(Val, CSPT->getElementType(),
Chris Lattner2a7c23e2002-09-10 17:04:02 +0000446 Name, BI);
Chris Lattnerdedee7b2001-11-01 05:57:59 +0000447
448 // Replace the old store with a new one!
449 ReplaceInstWithInst(BB->getInstList(), BI,
450 SI = new StoreInst(NCI, CastSrc));
451 PRINT_PEEPHOLE3("st-src-cast:out", NCI, CastSrc, SI);
Chris Lattner3c019372002-05-10 15:29:25 +0000452 ++NumLoadStorePeepholes;
Chris Lattnerdedee7b2001-11-01 05:57:59 +0000453 return true;
454 }
455
Chris Lattnerc99428f2002-05-14 05:23:45 +0000456 } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
457 Value *Pointer = LI->getOperand(0);
458 const Type *PtrElType =
459 cast<PointerType>(Pointer->getType())->getElementType();
460
461 // Peephole optimize the following instructions:
Misha Brukmanf117cc92003-05-20 18:45:36 +0000462 // %Val = cast <T1>* to <T2>* ;; If T1 is losslessly convertible to T2
Chris Lattnerc99428f2002-05-14 05:23:45 +0000463 // %t = load <T2>* %P
464 //
465 // Into:
466 // %t = load <T1>* %P
467 // %Val = cast <T1> to <T2>
468 //
469 // Note: This is not taken care of by expr conversion because there might
470 // not be a cast available for the store to convert the incoming value of.
471 // This code is basically here to make sure that pointers don't have casts
472 // if possible.
473 //
474 if (CastInst *CI = dyn_cast<CastInst>(Pointer))
475 if (Value *CastSrc = CI->getOperand(0)) // CSPT = CastSrcPointerType
Chris Lattner7e708292002-06-25 16:13:24 +0000476 if (const PointerType *CSPT = dyn_cast<PointerType>(CastSrc->getType()))
Misha Brukmanf117cc92003-05-20 18:45:36 +0000477 // convertible types?
478 if (PtrElType->isLosslesslyConvertibleTo(CSPT->getElementType())) {
Chris Lattnerc99428f2002-05-14 05:23:45 +0000479 PRINT_PEEPHOLE2("load-src-cast:in ", Pointer, LI);
480
481 // Create the new load instruction... loading the pre-casted value
Chris Lattner2a7c23e2002-09-10 17:04:02 +0000482 LoadInst *NewLI = new LoadInst(CastSrc, LI->getName(), BI);
Chris Lattnerc99428f2002-05-14 05:23:45 +0000483
484 // Insert the new T cast instruction... stealing old T's name
485 CastInst *NCI = new CastInst(NewLI, LI->getType(), CI->getName());
Chris Lattnerc99428f2002-05-14 05:23:45 +0000486
487 // Replace the old store with a new one!
488 ReplaceInstWithInst(BB->getInstList(), BI, NCI);
489 PRINT_PEEPHOLE3("load-src-cast:out", NCI, CastSrc, NewLI);
490 ++NumLoadStorePeepholes;
491 return true;
492 }
493
Chris Lattnerd32a9612001-11-01 02:42:08 +0000494 } else if (I->getOpcode() == Instruction::Add &&
495 isa<CastInst>(I->getOperand(1))) {
496
Chris Lattnerd5b48ca2001-11-14 11:02:49 +0000497 if (PeepholeOptimizeAddCast(BB, BI, I->getOperand(0),
Chris Lattner16125fb2003-04-24 18:25:27 +0000498 cast<CastInst>(I->getOperand(1)), TD)) {
Chris Lattner3c019372002-05-10 15:29:25 +0000499 ++NumGEPInstFormed;
Chris Lattnerd32a9612001-11-01 02:42:08 +0000500 return true;
Chris Lattner3c019372002-05-10 15:29:25 +0000501 }
Chris Lattner61b92c02002-10-08 22:19:25 +0000502 } else if (CallInst *CI = dyn_cast<CallInst>(I)) {
503 // If we have a call with all varargs arguments, convert the call to use the
504 // actual argument types present...
505 //
506 const PointerType *PTy = cast<PointerType>(CI->getCalledValue()->getType());
507 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
508
509 // Is the call to a vararg variable with no real parameters?
Chris Lattnercdeb81d2003-05-01 21:02:53 +0000510 if (FTy->isVarArg() && FTy->getNumParams() == 0 &&
511 !CI->getCalledFunction()) {
Chris Lattner61b92c02002-10-08 22:19:25 +0000512 // If so, insert a new cast instruction, casting it to a function type
513 // that matches the current arguments...
514 //
515 std::vector<const Type *> Params; // Parameter types...
516 for (unsigned i = 1, e = CI->getNumOperands(); i != e; ++i)
517 Params.push_back(CI->getOperand(i)->getType());
518
519 FunctionType *NewFT = FunctionType::get(FTy->getReturnType(),
520 Params, false);
521 PointerType *NewPFunTy = PointerType::get(NewFT);
522
523 // Create a new cast, inserting it right before the function call...
Chris Lattner95549282003-04-28 01:25:38 +0000524 Value *NewCast;
525 Constant *ConstantCallSrc = 0;
526 if (Constant *CS = dyn_cast<Constant>(CI->getCalledValue()))
527 ConstantCallSrc = CS;
528 else if (GlobalValue *GV = dyn_cast<GlobalValue>(CI->getCalledValue()))
529 ConstantCallSrc = ConstantPointerRef::get(GV);
530
531 if (ConstantCallSrc)
532 NewCast = ConstantExpr::getCast(ConstantCallSrc, NewPFunTy);
533 else
534 NewCast = new CastInst(CI->getCalledValue(), NewPFunTy,
535 CI->getCalledValue()->getName()+"_c",CI);
Chris Lattner61b92c02002-10-08 22:19:25 +0000536
537 // Create a new call instruction...
538 CallInst *NewCall = new CallInst(NewCast,
539 std::vector<Value*>(CI->op_begin()+1, CI->op_end()));
540 ++BI;
541 ReplaceInstWithInst(CI, NewCall);
542
543 ++NumVarargCallChanges;
544 return true;
545 }
546
Chris Lattnerd32a9612001-11-01 02:42:08 +0000547 }
548
549 return false;
550}
551
552
553
554
Chris Lattner16125fb2003-04-24 18:25:27 +0000555bool RPR::DoRaisePass(Function &F) {
Chris Lattnerd32a9612001-11-01 02:42:08 +0000556 bool Changed = false;
Chris Lattner7e708292002-06-25 16:13:24 +0000557 for (Function::iterator BB = F.begin(), BBE = F.end(); BB != BBE; ++BB)
Chris Lattnerd32a9612001-11-01 02:42:08 +0000558 for (BasicBlock::iterator BI = BB->begin(); BI != BB->end();) {
Chris Lattnerb3abf9d2002-05-22 17:27:12 +0000559 DEBUG(cerr << "Processing: " << *BI);
Misha Brukman82c89b92003-05-20 21:01:22 +0000560 if (dceInstruction(BI) || doConstantPropagation(BI)) {
Chris Lattnerc0b90e72001-11-08 20:19:56 +0000561 Changed = true;
Chris Lattner3c019372002-05-10 15:29:25 +0000562 ++NumDCEorCP;
Misha Brukman5f417482002-09-18 00:42:45 +0000563 DEBUG(cerr << "***\t\t^^-- Dead code eliminated!\n");
Chris Lattner7e708292002-06-25 16:13:24 +0000564 } else if (PeepholeOptimize(BB, BI)) {
Chris Lattnerd32a9612001-11-01 02:42:08 +0000565 Changed = true;
Chris Lattner7e708292002-06-25 16:13:24 +0000566 } else {
Chris Lattnerd32a9612001-11-01 02:42:08 +0000567 ++BI;
Chris Lattner7e708292002-06-25 16:13:24 +0000568 }
Chris Lattnerd32a9612001-11-01 02:42:08 +0000569 }
Chris Lattner7e708292002-06-25 16:13:24 +0000570
Chris Lattnerd32a9612001-11-01 02:42:08 +0000571 return Changed;
572}
573
574
Chris Lattner16125fb2003-04-24 18:25:27 +0000575// runOnFunction - Raise a function representation to a higher level.
576bool RPR::runOnFunction(Function &F) {
Chris Lattner7e708292002-06-25 16:13:24 +0000577 DEBUG(cerr << "\n\n\nStarting to work on Function '" << F.getName() << "'\n");
Chris Lattner68b07b72001-11-01 07:00:51 +0000578
Chris Lattner3cc7dde2001-11-26 16:58:14 +0000579 // Insert casts for all incoming pointer pointer values that are treated as
580 // arrays...
Chris Lattnerd32a9612001-11-01 02:42:08 +0000581 //
Chris Lattner3cc7dde2001-11-26 16:58:14 +0000582 bool Changed = false, LocalChange;
Chris Lattner3378a5b2002-07-16 23:49:24 +0000583
584 // If the StartInst option was specified, then Peephole optimize that
585 // instruction first if it occurs in this function.
586 //
587 if (!StartInst.empty()) {
588 for (Function::iterator BB = F.begin(), BBE = F.end(); BB != BBE; ++BB)
589 for (BasicBlock::iterator BI = BB->begin(); BI != BB->end(); ++BI)
590 if (BI->getName() == StartInst) {
591 bool SavedDebug = DebugFlag; // Save the DEBUG() controlling flag.
592 DebugFlag = true; // Turn on DEBUG's
593 Changed |= PeepholeOptimize(BB, BI);
594 DebugFlag = SavedDebug; // Restore DebugFlag to previous state
595 }
596 }
597
Chris Lattner4b770a32001-12-04 08:12:53 +0000598 do {
Chris Lattnerb3abf9d2002-05-22 17:27:12 +0000599 DEBUG(cerr << "Looping: \n" << F);
Chris Lattnera8b6d432001-12-05 06:34:00 +0000600
Chris Lattnerf57b8452002-04-27 06:56:12 +0000601 // Iterate over the function, refining it, until it converges on a stable
Chris Lattner3cc7dde2001-11-26 16:58:14 +0000602 // state
Chris Lattnerd5543802001-12-14 16:37:52 +0000603 LocalChange = false;
Chris Lattner2fbfdcf2002-04-07 20:49:59 +0000604 while (DoRaisePass(F)) LocalChange = true;
Chris Lattner3cc7dde2001-11-26 16:58:14 +0000605 Changed |= LocalChange;
606
607 } while (LocalChange);
Chris Lattnerd32a9612001-11-01 02:42:08 +0000608
609 return Changed;
610}