blob: 3dcb501bbb78eb7212bef37ed60f8d161cc651f0 [file] [log] [blame]
Chris Lattnercf3056d2003-10-13 03:32:08 +00001//===- LevelRaise.cpp - Code to change LLVM to higher level ---------------===//
John Criswellb576c942003-10-20 19:43:21 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file was developed by the LLVM research group and is distributed under
6// the University of Illinois Open Source License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
Chris Lattnerd32a9612001-11-01 02:42:08 +00009//
10// This file implements the 'raising' part of the LevelChange API. This is
11// useful because, in general, it makes the LLVM code terser and easier to
Chris Lattner3cc7dde2001-11-26 16:58:14 +000012// analyze.
Chris Lattnerd32a9612001-11-01 02:42:08 +000013//
14//===----------------------------------------------------------------------===//
15
Chris Lattnerbf881002003-09-01 20:45:33 +000016#include "llvm/Transforms/Scalar.h"
Chris Lattner497c60c2002-05-07 18:12:18 +000017#include "llvm/Transforms/Utils/Local.h"
Chris Lattner59cd9f12001-11-04 23:24:06 +000018#include "TransformInternals.h"
Chris Lattnerd32a9612001-11-01 02:42:08 +000019#include "llvm/iOther.h"
20#include "llvm/iMemory.h"
Chris Lattnerbd0ef772002-02-26 21:46:54 +000021#include "llvm/Pass.h"
Chris Lattner968ddc92002-04-08 20:18:09 +000022#include "llvm/ConstantHandling.h"
Chris Lattnerd5b48ca2001-11-14 11:02:49 +000023#include "llvm/Analysis/Expressions.h"
Chris Lattner497c60c2002-05-07 18:12:18 +000024#include "llvm/Transforms/Utils/BasicBlockUtils.h"
Chris Lattner3378a5b2002-07-16 23:49:24 +000025#include "Support/CommandLine.h"
Chris Lattner6806f562003-08-01 22:15:03 +000026#include "Support/Debug.h"
27#include "Support/Statistic.h"
28#include "Support/STLExtras.h"
Chris Lattnerd32a9612001-11-01 02:42:08 +000029#include <algorithm>
30
Brian Gaeked0fde302003-11-11 22:41:34 +000031namespace llvm {
32
Chris Lattner3378a5b2002-07-16 23:49:24 +000033// StartInst - This enables the -raise-start-inst=foo option to cause the level
34// raising pass to start at instruction "foo", which is immensely useful for
35// debugging!
36//
Chris Lattner5ff62e92002-07-22 02:10:13 +000037static cl::opt<std::string>
38StartInst("raise-start-inst", cl::Hidden, cl::value_desc("inst name"),
39 cl::desc("Start raise pass at the instruction with the specified name"));
Chris Lattner3378a5b2002-07-16 23:49:24 +000040
Chris Lattner5ff62e92002-07-22 02:10:13 +000041static Statistic<>
Chris Lattner6ee6bbe2002-10-01 22:38:37 +000042NumLoadStorePeepholes("raise", "Number of load/store peepholes");
Chris Lattner5ff62e92002-07-22 02:10:13 +000043
44static Statistic<>
Chris Lattner6ee6bbe2002-10-01 22:38:37 +000045NumGEPInstFormed("raise", "Number of other getelementptr's formed");
Chris Lattner5ff62e92002-07-22 02:10:13 +000046
47static Statistic<>
Chris Lattner6ee6bbe2002-10-01 22:38:37 +000048NumExprTreesConv("raise", "Number of expression trees converted");
Chris Lattner5ff62e92002-07-22 02:10:13 +000049
50static Statistic<>
Chris Lattner6ee6bbe2002-10-01 22:38:37 +000051NumCastOfCast("raise", "Number of cast-of-self removed");
Chris Lattner5ff62e92002-07-22 02:10:13 +000052
53static Statistic<>
Chris Lattner6ee6bbe2002-10-01 22:38:37 +000054NumDCEorCP("raise", "Number of insts DCEd or constprop'd");
Chris Lattner3c019372002-05-10 15:29:25 +000055
Chris Lattner61b92c02002-10-08 22:19:25 +000056static Statistic<>
57NumVarargCallChanges("raise", "Number of vararg call peepholes");
58
Chris Lattnerd32a9612001-11-01 02:42:08 +000059#define PRINT_PEEPHOLE(ID, NUM, I) \
Chris Lattnerb3abf9d2002-05-22 17:27:12 +000060 DEBUG(std::cerr << "Inst P/H " << ID << "[" << NUM << "] " << I)
Chris Lattnerd32a9612001-11-01 02:42:08 +000061
62#define PRINT_PEEPHOLE1(ID, I1) do { PRINT_PEEPHOLE(ID, 0, I1); } while (0)
63#define PRINT_PEEPHOLE2(ID, I1, I2) \
64 do { PRINT_PEEPHOLE(ID, 0, I1); PRINT_PEEPHOLE(ID, 1, I2); } while (0)
65#define PRINT_PEEPHOLE3(ID, I1, I2, I3) \
66 do { PRINT_PEEPHOLE(ID, 0, I1); PRINT_PEEPHOLE(ID, 1, I2); \
67 PRINT_PEEPHOLE(ID, 2, I3); } while (0)
Chris Lattnerd5b48ca2001-11-14 11:02:49 +000068#define PRINT_PEEPHOLE4(ID, I1, I2, I3, I4) \
69 do { PRINT_PEEPHOLE(ID, 0, I1); PRINT_PEEPHOLE(ID, 1, I2); \
70 PRINT_PEEPHOLE(ID, 2, I3); PRINT_PEEPHOLE(ID, 3, I4); } while (0)
Chris Lattnerd32a9612001-11-01 02:42:08 +000071
Chris Lattner16125fb2003-04-24 18:25:27 +000072namespace {
73 struct RPR : public FunctionPass {
74 virtual bool runOnFunction(Function &F);
75
76 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
77 AU.setPreservesCFG();
78 AU.addRequired<TargetData>();
79 }
80
81 private:
82 bool DoRaisePass(Function &F);
83 bool PeepholeOptimize(BasicBlock *BB, BasicBlock::iterator &BI);
84 };
85
86 RegisterOpt<RPR> X("raise", "Raise Pointer References");
87}
88
Brian Gaeked0fde302003-11-11 22:41:34 +000089
Chris Lattner16125fb2003-04-24 18:25:27 +000090Pass *createRaisePointerReferencesPass() {
91 return new RPR();
92}
93
94
Chris Lattnerd32a9612001-11-01 02:42:08 +000095// isReinterpretingCast - Return true if the cast instruction specified will
96// cause the operand to be "reinterpreted". A value is reinterpreted if the
97// cast instruction would cause the underlying bits to change.
98//
99static inline bool isReinterpretingCast(const CastInst *CI) {
Misha Brukmanf117cc92003-05-20 18:45:36 +0000100 return!CI->getOperand(0)->getType()->isLosslesslyConvertibleTo(CI->getType());
Chris Lattnerd32a9612001-11-01 02:42:08 +0000101}
102
103
Chris Lattnera8b6d432001-12-05 06:34:00 +0000104// Peephole optimize the following instructions:
105// %t1 = cast ? to x *
106// %t2 = add x * %SP, %t1 ;; Constant must be 2nd operand
107//
108// Into: %t3 = getelementptr {<...>} * %SP, <element indices>
109// %t2 = cast <eltype> * %t3 to {<...>}*
110//
111static bool HandleCastToPointer(BasicBlock::iterator BI,
Chris Lattner16125fb2003-04-24 18:25:27 +0000112 const PointerType *DestPTy,
113 const TargetData &TD) {
Chris Lattner7e708292002-06-25 16:13:24 +0000114 CastInst &CI = cast<CastInst>(*BI);
115 if (CI.use_empty()) return false;
Chris Lattnerf3b976e2001-11-04 20:21:12 +0000116
Chris Lattner2d399092003-05-02 19:32:04 +0000117 // Scan all of the uses, looking for any uses that are not add or sub
Chris Lattnera8b6d432001-12-05 06:34:00 +0000118 // instructions. If we have non-adds, do not make this transformation.
119 //
Chris Lattner2d399092003-05-02 19:32:04 +0000120 bool HasSubUse = false; // Keep track of any subtracts...
Chris Lattner7e708292002-06-25 16:13:24 +0000121 for (Value::use_iterator I = CI.use_begin(), E = CI.use_end();
Chris Lattner2d399092003-05-02 19:32:04 +0000122 I != E; ++I)
Chris Lattnera8b6d432001-12-05 06:34:00 +0000123 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(*I)) {
Chris Lattner2d399092003-05-02 19:32:04 +0000124 if ((BO->getOpcode() != Instruction::Add &&
125 BO->getOpcode() != Instruction::Sub) ||
Chris Lattner3fb2ddd2002-07-16 21:41:31 +0000126 // Avoid add sbyte* %X, %X cases...
127 BO->getOperand(0) == BO->getOperand(1))
Chris Lattnera8b6d432001-12-05 06:34:00 +0000128 return false;
Chris Lattner2d399092003-05-02 19:32:04 +0000129 else
130 HasSubUse |= BO->getOpcode() == Instruction::Sub;
Chris Lattnera8b6d432001-12-05 06:34:00 +0000131 } else {
132 return false;
133 }
Chris Lattnera8b6d432001-12-05 06:34:00 +0000134
Chris Lattner697954c2002-01-20 22:54:45 +0000135 std::vector<Value*> Indices;
Chris Lattner7e708292002-06-25 16:13:24 +0000136 Value *Src = CI.getOperand(0);
Misha Brukmanf117cc92003-05-20 18:45:36 +0000137 const Type *Result = ConvertibleToGEP(DestPTy, Src, Indices, TD, &BI);
138 if (Result == 0) return false; // Not convertible...
Chris Lattnera8b6d432001-12-05 06:34:00 +0000139
Chris Lattner2d399092003-05-02 19:32:04 +0000140 // Cannot handle subtracts if there is more than one index required...
141 if (HasSubUse && Indices.size() != 1) return false;
142
Chris Lattnera8b6d432001-12-05 06:34:00 +0000143 PRINT_PEEPHOLE2("cast-add-to-gep:in", Src, CI);
144
145 // If we have a getelementptr capability... transform all of the
146 // add instruction uses into getelementptr's.
Chris Lattner7e708292002-06-25 16:13:24 +0000147 while (!CI.use_empty()) {
148 BinaryOperator *I = cast<BinaryOperator>(*CI.use_begin());
Chris Lattner2d399092003-05-02 19:32:04 +0000149 assert((I->getOpcode() == Instruction::Add ||
150 I->getOpcode() == Instruction::Sub) &&
Chris Lattnera8b6d432001-12-05 06:34:00 +0000151 "Use is not a valid add instruction!");
152
153 // Get the value added to the cast result pointer...
Chris Lattner7e708292002-06-25 16:13:24 +0000154 Value *OtherPtr = I->getOperand((I->getOperand(0) == &CI) ? 1 : 0);
Chris Lattnera8b6d432001-12-05 06:34:00 +0000155
Chris Lattner45ef5c22002-03-21 06:22:23 +0000156 Instruction *GEP = new GetElementPtrInst(OtherPtr, Indices, I->getName());
Chris Lattnera8b6d432001-12-05 06:34:00 +0000157 PRINT_PEEPHOLE1("cast-add-to-gep:i", I);
Chris Lattner45ef5c22002-03-21 06:22:23 +0000158
Chris Lattner2d399092003-05-02 19:32:04 +0000159 // If the instruction is actually a subtract, we are guaranteed to only have
160 // one index (from code above), so we just need to negate the pointer index
161 // long value.
162 if (I->getOpcode() == Instruction::Sub) {
163 Instruction *Neg = BinaryOperator::createNeg(GEP->getOperand(1),
164 GEP->getOperand(1)->getName()+".neg", I);
165 GEP->setOperand(1, Neg);
166 }
167
Chris Lattner45ef5c22002-03-21 06:22:23 +0000168 if (GEP->getType() == I->getType()) {
169 // Replace the old add instruction with the shiny new GEP inst
170 ReplaceInstWithInst(I, GEP);
171 } else {
172 // If the type produced by the gep instruction differs from the original
173 // add instruction type, insert a cast now.
174 //
175
Chris Lattner7e708292002-06-25 16:13:24 +0000176 // Insert the GEP instruction before the old add instruction...
177 I->getParent()->getInstList().insert(I, GEP);
Chris Lattner45ef5c22002-03-21 06:22:23 +0000178
179 PRINT_PEEPHOLE1("cast-add-to-gep:o", GEP);
Chris Lattner7e708292002-06-25 16:13:24 +0000180 GEP = new CastInst(GEP, I->getType());
Chris Lattner45ef5c22002-03-21 06:22:23 +0000181
182 // Replace the old add instruction with the shiny new GEP inst
Chris Lattner7e708292002-06-25 16:13:24 +0000183 ReplaceInstWithInst(I, GEP);
Chris Lattner45ef5c22002-03-21 06:22:23 +0000184 }
185
Chris Lattnera8b6d432001-12-05 06:34:00 +0000186 PRINT_PEEPHOLE1("cast-add-to-gep:o", GEP);
187 }
188 return true;
189}
Chris Lattnerd5b48ca2001-11-14 11:02:49 +0000190
191// Peephole optimize the following instructions:
192// %t1 = cast ulong <const int> to {<...>} *
193// %t2 = add {<...>} * %SP, %t1 ;; Constant must be 2nd operand
194//
195// or
196// %t1 = cast {<...>}* %SP to int*
197// %t5 = cast ulong <const int> to int*
198// %t2 = add int* %t1, %t5 ;; int is same size as field
199//
200// Into: %t3 = getelementptr {<...>} * %SP, <element indices>
201// %t2 = cast <eltype> * %t3 to {<...>}*
202//
203static bool PeepholeOptimizeAddCast(BasicBlock *BB, BasicBlock::iterator &BI,
Chris Lattner16125fb2003-04-24 18:25:27 +0000204 Value *AddOp1, CastInst *AddOp2,
205 const TargetData &TD) {
Chris Lattner3cc7dde2001-11-26 16:58:14 +0000206 const CompositeType *CompTy;
207 Value *OffsetVal = AddOp2->getOperand(0);
Chris Lattner0ceeb422002-10-22 23:34:11 +0000208 Value *SrcPtr = 0; // Of type pointer to struct...
Chris Lattnerd5b48ca2001-11-14 11:02:49 +0000209
Chris Lattner3cc7dde2001-11-26 16:58:14 +0000210 if ((CompTy = getPointedToComposite(AddOp1->getType()))) {
Chris Lattnerd5b48ca2001-11-14 11:02:49 +0000211 SrcPtr = AddOp1; // Handle the first case...
212 } else if (CastInst *AddOp1c = dyn_cast<CastInst>(AddOp1)) {
213 SrcPtr = AddOp1c->getOperand(0); // Handle the second case...
Chris Lattner3cc7dde2001-11-26 16:58:14 +0000214 CompTy = getPointedToComposite(SrcPtr->getType());
Chris Lattnerd5b48ca2001-11-14 11:02:49 +0000215 }
216
217 // Only proceed if we have detected all of our conditions successfully...
Chris Lattner0c4e8862002-09-03 01:08:28 +0000218 if (!CompTy || !SrcPtr || !OffsetVal->getType()->isInteger())
Chris Lattnerd5b48ca2001-11-14 11:02:49 +0000219 return false;
220
Chris Lattner697954c2002-01-20 22:54:45 +0000221 std::vector<Value*> Indices;
Misha Brukmanf117cc92003-05-20 18:45:36 +0000222 if (!ConvertibleToGEP(SrcPtr->getType(), OffsetVal, Indices, TD, &BI))
223 return false; // Not convertible... perhaps next time
Chris Lattnerd5b48ca2001-11-14 11:02:49 +0000224
Chris Lattner3cc7dde2001-11-26 16:58:14 +0000225 if (getPointedToComposite(AddOp1->getType())) { // case 1
Chris Lattnerd5b48ca2001-11-14 11:02:49 +0000226 PRINT_PEEPHOLE2("add-to-gep1:in", AddOp2, *BI);
227 } else {
228 PRINT_PEEPHOLE3("add-to-gep2:in", AddOp1, AddOp2, *BI);
229 }
230
Chris Lattner3cc7dde2001-11-26 16:58:14 +0000231 GetElementPtrInst *GEP = new GetElementPtrInst(SrcPtr, Indices,
Chris Lattner2a7c23e2002-09-10 17:04:02 +0000232 AddOp2->getName(), BI);
Chris Lattnerd5b48ca2001-11-14 11:02:49 +0000233
Chris Lattner3cc7dde2001-11-26 16:58:14 +0000234 Instruction *NCI = new CastInst(GEP, AddOp1->getType());
Chris Lattnerd5b48ca2001-11-14 11:02:49 +0000235 ReplaceInstWithInst(BB->getInstList(), BI, NCI);
236 PRINT_PEEPHOLE2("add-to-gep:out", GEP, NCI);
237 return true;
238}
239
Chris Lattner16125fb2003-04-24 18:25:27 +0000240bool RPR::PeepholeOptimize(BasicBlock *BB, BasicBlock::iterator &BI) {
Chris Lattner7e708292002-06-25 16:13:24 +0000241 Instruction *I = BI;
Chris Lattner16125fb2003-04-24 18:25:27 +0000242 const TargetData &TD = getAnalysis<TargetData>();
Chris Lattnerd32a9612001-11-01 02:42:08 +0000243
244 if (CastInst *CI = dyn_cast<CastInst>(I)) {
245 Value *Src = CI->getOperand(0);
246 Instruction *SrcI = dyn_cast<Instruction>(Src); // Nonnull if instr source
247 const Type *DestTy = CI->getType();
248
Chris Lattnere99c66b2001-11-01 17:05:27 +0000249 // Peephole optimize the following instruction:
250 // %V2 = cast <ty> %V to <ty>
251 //
252 // Into: <nothing>
253 //
254 if (DestTy == Src->getType()) { // Check for a cast to same type as src!!
Chris Lattnerd32a9612001-11-01 02:42:08 +0000255 PRINT_PEEPHOLE1("cast-of-self-ty", CI);
256 CI->replaceAllUsesWith(Src);
257 if (!Src->hasName() && CI->hasName()) {
Chris Lattner697954c2002-01-20 22:54:45 +0000258 std::string Name = CI->getName();
Chris Lattnerf3b976e2001-11-04 20:21:12 +0000259 CI->setName("");
Chris Lattner6e6026b2002-11-20 18:36:02 +0000260 Src->setName(Name, &BB->getParent()->getSymbolTable());
Chris Lattnerd32a9612001-11-01 02:42:08 +0000261 }
Chris Lattner3c019372002-05-10 15:29:25 +0000262
263 // DCE the instruction now, to avoid having the iterative version of DCE
264 // have to worry about it.
265 //
Chris Lattner7e708292002-06-25 16:13:24 +0000266 BI = BB->getInstList().erase(BI);
Chris Lattner3c019372002-05-10 15:29:25 +0000267
268 ++NumCastOfCast;
Chris Lattnerd32a9612001-11-01 02:42:08 +0000269 return true;
270 }
271
Chris Lattnerd32a9612001-11-01 02:42:08 +0000272 // Check to see if it's a cast of an instruction that does not depend on the
273 // specific type of the operands to do it's job.
Chris Lattnerf3b976e2001-11-04 20:21:12 +0000274 if (!isReinterpretingCast(CI)) {
Chris Lattnerb980e182001-11-04 21:32:11 +0000275 ValueTypeCache ConvertedTypes;
Chris Lattnera8b6d432001-12-05 06:34:00 +0000276
Chris Lattnerd20a98e2002-05-24 20:41:51 +0000277 // Check to see if we can convert the source of the cast to match the
278 // destination type of the cast...
Chris Lattnera8b6d432001-12-05 06:34:00 +0000279 //
Chris Lattnerd5543802001-12-14 16:37:52 +0000280 ConvertedTypes[CI] = CI->getType(); // Make sure the cast doesn't change
Misha Brukmanf117cc92003-05-20 18:45:36 +0000281 if (ExpressionConvertibleToType(Src, DestTy, ConvertedTypes, TD)) {
Chris Lattnerd5543802001-12-14 16:37:52 +0000282 PRINT_PEEPHOLE3("CAST-SRC-EXPR-CONV:in ", Src, CI, BB->getParent());
Chris Lattnerc0b90e72001-11-08 20:19:56 +0000283
Chris Lattner6806f562003-08-01 22:15:03 +0000284 DEBUG(std::cerr << "\nCONVERTING SRC EXPR TYPE:\n");
Chris Lattnerb1b42622002-07-17 17:11:33 +0000285 { // ValueMap must be destroyed before function verified!
286 ValueMapCache ValueMap;
Chris Lattner16125fb2003-04-24 18:25:27 +0000287 Value *E = ConvertExpressionToType(Src, DestTy, ValueMap, TD);
Chris Lattnerc0b90e72001-11-08 20:19:56 +0000288
Chris Lattnerb1b42622002-07-17 17:11:33 +0000289 if (Constant *CPV = dyn_cast<Constant>(E))
290 CI->replaceAllUsesWith(CPV);
291
292 PRINT_PEEPHOLE1("CAST-SRC-EXPR-CONV:out", E);
Chris Lattner6806f562003-08-01 22:15:03 +0000293 DEBUG(std::cerr << "DONE CONVERTING SRC EXPR TYPE: \n"
294 << BB->getParent());
Chris Lattnerb1b42622002-07-17 17:11:33 +0000295 }
Chris Lattner3378a5b2002-07-16 23:49:24 +0000296
Chris Lattnerb1b42622002-07-17 17:11:33 +0000297 BI = BB->begin(); // Rescan basic block. BI might be invalidated.
Chris Lattner3c019372002-05-10 15:29:25 +0000298 ++NumExprTreesConv;
Chris Lattnerd5543802001-12-14 16:37:52 +0000299 return true;
300 }
301
Chris Lattnerd20a98e2002-05-24 20:41:51 +0000302 // Check to see if we can convert the users of the cast value to match the
303 // source type of the cast...
Chris Lattnerd5543802001-12-14 16:37:52 +0000304 //
305 ConvertedTypes.clear();
Chris Lattner61b92c02002-10-08 22:19:25 +0000306 // Make sure the source doesn't change type
307 ConvertedTypes[Src] = Src->getType();
Misha Brukmanf117cc92003-05-20 18:45:36 +0000308 if (ValueConvertibleToType(CI, Src->getType(), ConvertedTypes, TD)) {
Chris Lattnerd5543802001-12-14 16:37:52 +0000309 PRINT_PEEPHOLE3("CAST-DEST-EXPR-CONV:in ", Src, CI, BB->getParent());
310
Chris Lattner6806f562003-08-01 22:15:03 +0000311 DEBUG(std::cerr << "\nCONVERTING EXPR TYPE:\n");
Chris Lattnerb1b42622002-07-17 17:11:33 +0000312 { // ValueMap must be destroyed before function verified!
313 ValueMapCache ValueMap;
Chris Lattner16125fb2003-04-24 18:25:27 +0000314 ConvertValueToNewType(CI, Src, ValueMap, TD); // This will delete CI!
Chris Lattnerb1b42622002-07-17 17:11:33 +0000315 }
Chris Lattnerd5543802001-12-14 16:37:52 +0000316
Chris Lattnerd5543802001-12-14 16:37:52 +0000317 PRINT_PEEPHOLE1("CAST-DEST-EXPR-CONV:out", Src);
Chris Lattner6806f562003-08-01 22:15:03 +0000318 DEBUG(std::cerr << "DONE CONVERTING EXPR TYPE: \n\n" << BB->getParent());
Chris Lattner3378a5b2002-07-16 23:49:24 +0000319
Chris Lattnerb1b42622002-07-17 17:11:33 +0000320 BI = BB->begin(); // Rescan basic block. BI might be invalidated.
Chris Lattner3c019372002-05-10 15:29:25 +0000321 ++NumExprTreesConv;
Chris Lattnera8b6d432001-12-05 06:34:00 +0000322 return true;
Chris Lattnerf3b976e2001-11-04 20:21:12 +0000323 }
Chris Lattnerf17a09d2001-12-06 18:06:13 +0000324 }
325
326 // Otherwise find out it this cast is a cast to a pointer type, which is
327 // then added to some other pointer, then loaded or stored through. If
328 // so, convert the add into a getelementptr instruction...
329 //
330 if (const PointerType *DestPTy = dyn_cast<PointerType>(DestTy)) {
Chris Lattner16125fb2003-04-24 18:25:27 +0000331 if (HandleCastToPointer(BI, DestPTy, TD)) {
Chris Lattnerf17a09d2001-12-06 18:06:13 +0000332 BI = BB->begin(); // Rescan basic block. BI might be invalidated.
Chris Lattner3c019372002-05-10 15:29:25 +0000333 ++NumGEPInstFormed;
Chris Lattnerf17a09d2001-12-06 18:06:13 +0000334 return true;
Chris Lattnera8b6d432001-12-05 06:34:00 +0000335 }
Chris Lattnerd32a9612001-11-01 02:42:08 +0000336 }
337
Chris Lattnere99c66b2001-11-01 17:05:27 +0000338 // Check to see if we are casting from a structure pointer to a pointer to
339 // the first element of the structure... to avoid munching other peepholes,
340 // we only let this happen if there are no add uses of the cast.
341 //
342 // Peephole optimize the following instructions:
343 // %t1 = cast {<...>} * %StructPtr to <ty> *
344 //
345 // Into: %t2 = getelementptr {<...>} * %StructPtr, <0, 0, 0, ...>
346 // %t1 = cast <eltype> * %t1 to <ty> *
347 //
Chris Lattner3cc7dde2001-11-26 16:58:14 +0000348 if (const CompositeType *CTy = getPointedToComposite(Src->getType()))
Chris Lattnere99c66b2001-11-01 17:05:27 +0000349 if (const PointerType *DestPTy = dyn_cast<PointerType>(DestTy)) {
350
351 // Loop over uses of the cast, checking for add instructions. If an add
352 // exists, this is probably a part of a more complex GEP, so we don't
353 // want to mess around with the cast.
354 //
355 bool HasAddUse = false;
356 for (Value::use_iterator I = CI->use_begin(), E = CI->use_end();
357 I != E; ++I)
358 if (isa<Instruction>(*I) &&
359 cast<Instruction>(*I)->getOpcode() == Instruction::Add) {
360 HasAddUse = true; break;
361 }
362
363 // If it doesn't have an add use, check to see if the dest type is
Misha Brukmanf117cc92003-05-20 18:45:36 +0000364 // losslessly convertible to one of the types in the start of the struct
Chris Lattnere99c66b2001-11-01 17:05:27 +0000365 // type.
366 //
367 if (!HasAddUse) {
Chris Lattner7a176752001-12-04 00:03:30 +0000368 const Type *DestPointedTy = DestPTy->getElementType();
Chris Lattnere99c66b2001-11-01 17:05:27 +0000369 unsigned Depth = 1;
Chris Lattner3cc7dde2001-11-26 16:58:14 +0000370 const CompositeType *CurCTy = CTy;
Chris Lattnere99c66b2001-11-01 17:05:27 +0000371 const Type *ElTy = 0;
Chris Lattner3cc7dde2001-11-26 16:58:14 +0000372
373 // Build the index vector, full of all zeros
Chris Lattner697954c2002-01-20 22:54:45 +0000374 std::vector<Value*> Indices;
Chris Lattner106ff452002-09-11 01:21:29 +0000375 Indices.push_back(ConstantSInt::get(Type::LongTy, 0));
Chris Lattnerd5543802001-12-14 16:37:52 +0000376 while (CurCTy && !isa<PointerType>(CurCTy)) {
Chris Lattner3cc7dde2001-11-26 16:58:14 +0000377 if (const StructType *CurSTy = dyn_cast<StructType>(CurCTy)) {
378 // Check for a zero element struct type... if we have one, bail.
379 if (CurSTy->getElementTypes().size() == 0) break;
Chris Lattnere99c66b2001-11-01 17:05:27 +0000380
Chris Lattner3cc7dde2001-11-26 16:58:14 +0000381 // Grab the first element of the struct type, which must lie at
382 // offset zero in the struct.
383 //
384 ElTy = CurSTy->getElementTypes()[0];
385 } else {
386 ElTy = cast<ArrayType>(CurCTy)->getElementType();
387 }
388
389 // Insert a zero to index through this type...
Chris Lattner106ff452002-09-11 01:21:29 +0000390 Indices.push_back(Constant::getNullValue(CurCTy->getIndexType()));
Chris Lattnere99c66b2001-11-01 17:05:27 +0000391
392 // Did we find what we're looking for?
Misha Brukmanf117cc92003-05-20 18:45:36 +0000393 if (ElTy->isLosslesslyConvertibleTo(DestPointedTy)) break;
Chris Lattnere99c66b2001-11-01 17:05:27 +0000394
395 // Nope, go a level deeper.
396 ++Depth;
Chris Lattner3cc7dde2001-11-26 16:58:14 +0000397 CurCTy = dyn_cast<CompositeType>(ElTy);
Chris Lattnere99c66b2001-11-01 17:05:27 +0000398 ElTy = 0;
399 }
400
401 // Did we find what we were looking for? If so, do the transformation
402 if (ElTy) {
403 PRINT_PEEPHOLE1("cast-for-first:in", CI);
404
Chris Lattner2a7c23e2002-09-10 17:04:02 +0000405 std::string Name = CI->getName(); CI->setName("");
406
Chris Lattnere99c66b2001-11-01 17:05:27 +0000407 // Insert the new T cast instruction... stealing old T's name
408 GetElementPtrInst *GEP = new GetElementPtrInst(Src, Indices,
Chris Lattner2a7c23e2002-09-10 17:04:02 +0000409 Name, BI);
Chris Lattnere99c66b2001-11-01 17:05:27 +0000410
411 // Make the old cast instruction reference the new GEP instead of
412 // the old src value.
413 //
414 CI->setOperand(0, GEP);
415
416 PRINT_PEEPHOLE2("cast-for-first:out", GEP, CI);
Chris Lattner3c019372002-05-10 15:29:25 +0000417 ++NumGEPInstFormed;
Chris Lattnere99c66b2001-11-01 17:05:27 +0000418 return true;
419 }
420 }
421 }
Chris Lattnere99c66b2001-11-01 17:05:27 +0000422
Chris Lattner8d38e542001-11-01 03:12:34 +0000423 } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
424 Value *Val = SI->getOperand(0);
Chris Lattner65ea1712001-11-14 11:27:58 +0000425 Value *Pointer = SI->getPointerOperand();
Chris Lattner8d38e542001-11-01 03:12:34 +0000426
Chris Lattnerdedee7b2001-11-01 05:57:59 +0000427 // Peephole optimize the following instructions:
Misha Brukmanf117cc92003-05-20 18:45:36 +0000428 // %t = cast <T1>* %P to <T2> * ;; If T1 is losslessly convertible to T2
Chris Lattnerdedee7b2001-11-01 05:57:59 +0000429 // store <T2> %V, <T2>* %t
430 //
431 // Into:
432 // %t = cast <T2> %V to <T1>
433 // store <T1> %t2, <T1>* %P
434 //
Chris Lattnerd5543802001-12-14 16:37:52 +0000435 // Note: This is not taken care of by expr conversion because there might
436 // not be a cast available for the store to convert the incoming value of.
437 // This code is basically here to make sure that pointers don't have casts
438 // if possible.
439 //
Chris Lattnerdedee7b2001-11-01 05:57:59 +0000440 if (CastInst *CI = dyn_cast<CastInst>(Pointer))
441 if (Value *CastSrc = CI->getOperand(0)) // CSPT = CastSrcPointerType
Chris Lattner7e708292002-06-25 16:13:24 +0000442 if (const PointerType *CSPT = dyn_cast<PointerType>(CastSrc->getType()))
Misha Brukmanf117cc92003-05-20 18:45:36 +0000443 // convertible types?
444 if (Val->getType()->isLosslesslyConvertibleTo(CSPT->getElementType())) {
Chris Lattnerdedee7b2001-11-01 05:57:59 +0000445 PRINT_PEEPHOLE3("st-src-cast:in ", Pointer, Val, SI);
446
447 // Insert the new T cast instruction... stealing old T's name
Chris Lattner2a7c23e2002-09-10 17:04:02 +0000448 std::string Name(CI->getName()); CI->setName("");
Chris Lattner7a176752001-12-04 00:03:30 +0000449 CastInst *NCI = new CastInst(Val, CSPT->getElementType(),
Chris Lattner2a7c23e2002-09-10 17:04:02 +0000450 Name, BI);
Chris Lattnerdedee7b2001-11-01 05:57:59 +0000451
452 // Replace the old store with a new one!
453 ReplaceInstWithInst(BB->getInstList(), BI,
454 SI = new StoreInst(NCI, CastSrc));
455 PRINT_PEEPHOLE3("st-src-cast:out", NCI, CastSrc, SI);
Chris Lattner3c019372002-05-10 15:29:25 +0000456 ++NumLoadStorePeepholes;
Chris Lattnerdedee7b2001-11-01 05:57:59 +0000457 return true;
458 }
459
Chris Lattnerc99428f2002-05-14 05:23:45 +0000460 } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
461 Value *Pointer = LI->getOperand(0);
462 const Type *PtrElType =
463 cast<PointerType>(Pointer->getType())->getElementType();
464
465 // Peephole optimize the following instructions:
Misha Brukmanf117cc92003-05-20 18:45:36 +0000466 // %Val = cast <T1>* to <T2>* ;; If T1 is losslessly convertible to T2
Chris Lattnerc99428f2002-05-14 05:23:45 +0000467 // %t = load <T2>* %P
468 //
469 // Into:
470 // %t = load <T1>* %P
471 // %Val = cast <T1> to <T2>
472 //
473 // Note: This is not taken care of by expr conversion because there might
474 // not be a cast available for the store to convert the incoming value of.
475 // This code is basically here to make sure that pointers don't have casts
476 // if possible.
477 //
478 if (CastInst *CI = dyn_cast<CastInst>(Pointer))
479 if (Value *CastSrc = CI->getOperand(0)) // CSPT = CastSrcPointerType
Chris Lattner7e708292002-06-25 16:13:24 +0000480 if (const PointerType *CSPT = dyn_cast<PointerType>(CastSrc->getType()))
Misha Brukmanf117cc92003-05-20 18:45:36 +0000481 // convertible types?
482 if (PtrElType->isLosslesslyConvertibleTo(CSPT->getElementType())) {
Chris Lattnerc99428f2002-05-14 05:23:45 +0000483 PRINT_PEEPHOLE2("load-src-cast:in ", Pointer, LI);
484
485 // Create the new load instruction... loading the pre-casted value
Chris Lattner2a7c23e2002-09-10 17:04:02 +0000486 LoadInst *NewLI = new LoadInst(CastSrc, LI->getName(), BI);
Chris Lattnerc99428f2002-05-14 05:23:45 +0000487
488 // Insert the new T cast instruction... stealing old T's name
489 CastInst *NCI = new CastInst(NewLI, LI->getType(), CI->getName());
Chris Lattnerc99428f2002-05-14 05:23:45 +0000490
491 // Replace the old store with a new one!
492 ReplaceInstWithInst(BB->getInstList(), BI, NCI);
493 PRINT_PEEPHOLE3("load-src-cast:out", NCI, CastSrc, NewLI);
494 ++NumLoadStorePeepholes;
495 return true;
496 }
497
Chris Lattnerd32a9612001-11-01 02:42:08 +0000498 } else if (I->getOpcode() == Instruction::Add &&
499 isa<CastInst>(I->getOperand(1))) {
500
Chris Lattnerd5b48ca2001-11-14 11:02:49 +0000501 if (PeepholeOptimizeAddCast(BB, BI, I->getOperand(0),
Chris Lattner16125fb2003-04-24 18:25:27 +0000502 cast<CastInst>(I->getOperand(1)), TD)) {
Chris Lattner3c019372002-05-10 15:29:25 +0000503 ++NumGEPInstFormed;
Chris Lattnerd32a9612001-11-01 02:42:08 +0000504 return true;
Chris Lattner3c019372002-05-10 15:29:25 +0000505 }
Chris Lattner61b92c02002-10-08 22:19:25 +0000506 } else if (CallInst *CI = dyn_cast<CallInst>(I)) {
507 // If we have a call with all varargs arguments, convert the call to use the
508 // actual argument types present...
509 //
510 const PointerType *PTy = cast<PointerType>(CI->getCalledValue()->getType());
511 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
512
513 // Is the call to a vararg variable with no real parameters?
Chris Lattnercdeb81d2003-05-01 21:02:53 +0000514 if (FTy->isVarArg() && FTy->getNumParams() == 0 &&
515 !CI->getCalledFunction()) {
Chris Lattner61b92c02002-10-08 22:19:25 +0000516 // If so, insert a new cast instruction, casting it to a function type
517 // that matches the current arguments...
518 //
519 std::vector<const Type *> Params; // Parameter types...
520 for (unsigned i = 1, e = CI->getNumOperands(); i != e; ++i)
521 Params.push_back(CI->getOperand(i)->getType());
522
523 FunctionType *NewFT = FunctionType::get(FTy->getReturnType(),
524 Params, false);
525 PointerType *NewPFunTy = PointerType::get(NewFT);
526
527 // Create a new cast, inserting it right before the function call...
Chris Lattner95549282003-04-28 01:25:38 +0000528 Value *NewCast;
529 Constant *ConstantCallSrc = 0;
530 if (Constant *CS = dyn_cast<Constant>(CI->getCalledValue()))
531 ConstantCallSrc = CS;
532 else if (GlobalValue *GV = dyn_cast<GlobalValue>(CI->getCalledValue()))
533 ConstantCallSrc = ConstantPointerRef::get(GV);
534
535 if (ConstantCallSrc)
536 NewCast = ConstantExpr::getCast(ConstantCallSrc, NewPFunTy);
537 else
538 NewCast = new CastInst(CI->getCalledValue(), NewPFunTy,
539 CI->getCalledValue()->getName()+"_c",CI);
Chris Lattner61b92c02002-10-08 22:19:25 +0000540
541 // Create a new call instruction...
542 CallInst *NewCall = new CallInst(NewCast,
543 std::vector<Value*>(CI->op_begin()+1, CI->op_end()));
544 ++BI;
545 ReplaceInstWithInst(CI, NewCall);
546
547 ++NumVarargCallChanges;
548 return true;
549 }
550
Chris Lattnerd32a9612001-11-01 02:42:08 +0000551 }
552
553 return false;
554}
555
556
557
558
Chris Lattner16125fb2003-04-24 18:25:27 +0000559bool RPR::DoRaisePass(Function &F) {
Chris Lattnerd32a9612001-11-01 02:42:08 +0000560 bool Changed = false;
Chris Lattner7e708292002-06-25 16:13:24 +0000561 for (Function::iterator BB = F.begin(), BBE = F.end(); BB != BBE; ++BB)
Chris Lattnerd32a9612001-11-01 02:42:08 +0000562 for (BasicBlock::iterator BI = BB->begin(); BI != BB->end();) {
Chris Lattner6806f562003-08-01 22:15:03 +0000563 DEBUG(std::cerr << "Processing: " << *BI);
Misha Brukman82c89b92003-05-20 21:01:22 +0000564 if (dceInstruction(BI) || doConstantPropagation(BI)) {
Chris Lattnerc0b90e72001-11-08 20:19:56 +0000565 Changed = true;
Chris Lattner3c019372002-05-10 15:29:25 +0000566 ++NumDCEorCP;
Chris Lattner6806f562003-08-01 22:15:03 +0000567 DEBUG(std::cerr << "***\t\t^^-- Dead code eliminated!\n");
Chris Lattner7e708292002-06-25 16:13:24 +0000568 } else if (PeepholeOptimize(BB, BI)) {
Chris Lattnerd32a9612001-11-01 02:42:08 +0000569 Changed = true;
Chris Lattner7e708292002-06-25 16:13:24 +0000570 } else {
Chris Lattnerd32a9612001-11-01 02:42:08 +0000571 ++BI;
Chris Lattner7e708292002-06-25 16:13:24 +0000572 }
Chris Lattnerd32a9612001-11-01 02:42:08 +0000573 }
Chris Lattner7e708292002-06-25 16:13:24 +0000574
Chris Lattnerd32a9612001-11-01 02:42:08 +0000575 return Changed;
576}
577
578
Chris Lattner16125fb2003-04-24 18:25:27 +0000579// runOnFunction - Raise a function representation to a higher level.
580bool RPR::runOnFunction(Function &F) {
Chris Lattner6806f562003-08-01 22:15:03 +0000581 DEBUG(std::cerr << "\n\n\nStarting to work on Function '" << F.getName()
582 << "'\n");
Chris Lattner68b07b72001-11-01 07:00:51 +0000583
Chris Lattner3cc7dde2001-11-26 16:58:14 +0000584 // Insert casts for all incoming pointer pointer values that are treated as
585 // arrays...
Chris Lattnerd32a9612001-11-01 02:42:08 +0000586 //
Chris Lattner3cc7dde2001-11-26 16:58:14 +0000587 bool Changed = false, LocalChange;
Chris Lattner3378a5b2002-07-16 23:49:24 +0000588
589 // If the StartInst option was specified, then Peephole optimize that
590 // instruction first if it occurs in this function.
591 //
592 if (!StartInst.empty()) {
593 for (Function::iterator BB = F.begin(), BBE = F.end(); BB != BBE; ++BB)
594 for (BasicBlock::iterator BI = BB->begin(); BI != BB->end(); ++BI)
595 if (BI->getName() == StartInst) {
596 bool SavedDebug = DebugFlag; // Save the DEBUG() controlling flag.
597 DebugFlag = true; // Turn on DEBUG's
598 Changed |= PeepholeOptimize(BB, BI);
599 DebugFlag = SavedDebug; // Restore DebugFlag to previous state
600 }
601 }
602
Chris Lattner4b770a32001-12-04 08:12:53 +0000603 do {
Chris Lattner6806f562003-08-01 22:15:03 +0000604 DEBUG(std::cerr << "Looping: \n" << F);
Chris Lattnera8b6d432001-12-05 06:34:00 +0000605
Chris Lattnerf57b8452002-04-27 06:56:12 +0000606 // Iterate over the function, refining it, until it converges on a stable
Chris Lattner3cc7dde2001-11-26 16:58:14 +0000607 // state
Chris Lattnerd5543802001-12-14 16:37:52 +0000608 LocalChange = false;
Chris Lattner2fbfdcf2002-04-07 20:49:59 +0000609 while (DoRaisePass(F)) LocalChange = true;
Chris Lattner3cc7dde2001-11-26 16:58:14 +0000610 Changed |= LocalChange;
611
612 } while (LocalChange);
Chris Lattnerd32a9612001-11-01 02:42:08 +0000613
614 return Changed;
615}
Brian Gaeked0fde302003-11-11 22:41:34 +0000616
617} // End llvm namespace