blob: 8e11bf3d45194b3dc649a3819a55129f752c7989 [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 Lattner497c60c2002-05-07 18:12:18 +000022#include "llvm/Transforms/Utils/BasicBlockUtils.h"
Chris Lattner3378a5b2002-07-16 23:49:24 +000023#include "Support/CommandLine.h"
Chris Lattner6806f562003-08-01 22:15:03 +000024#include "Support/Debug.h"
25#include "Support/Statistic.h"
26#include "Support/STLExtras.h"
Chris Lattnerd32a9612001-11-01 02:42:08 +000027#include <algorithm>
Chris Lattnere7999022003-12-23 07:43:38 +000028using namespace llvm;
Brian Gaeked0fde302003-11-11 22:41:34 +000029
Chris Lattner3378a5b2002-07-16 23:49:24 +000030// StartInst - This enables the -raise-start-inst=foo option to cause the level
31// raising pass to start at instruction "foo", which is immensely useful for
32// debugging!
33//
Chris Lattner5ff62e92002-07-22 02:10:13 +000034static cl::opt<std::string>
35StartInst("raise-start-inst", cl::Hidden, cl::value_desc("inst name"),
36 cl::desc("Start raise pass at the instruction with the specified name"));
Chris Lattner3378a5b2002-07-16 23:49:24 +000037
Chris Lattner5ff62e92002-07-22 02:10:13 +000038static Statistic<>
Chris Lattner6ee6bbe2002-10-01 22:38:37 +000039NumLoadStorePeepholes("raise", "Number of load/store peepholes");
Chris Lattner5ff62e92002-07-22 02:10:13 +000040
41static Statistic<>
Chris Lattner6ee6bbe2002-10-01 22:38:37 +000042NumGEPInstFormed("raise", "Number of other getelementptr's formed");
Chris Lattner5ff62e92002-07-22 02:10:13 +000043
44static Statistic<>
Chris Lattner6ee6bbe2002-10-01 22:38:37 +000045NumExprTreesConv("raise", "Number of expression trees converted");
Chris Lattner5ff62e92002-07-22 02:10:13 +000046
47static Statistic<>
Chris Lattner6ee6bbe2002-10-01 22:38:37 +000048NumCastOfCast("raise", "Number of cast-of-self removed");
Chris Lattner5ff62e92002-07-22 02:10:13 +000049
50static Statistic<>
Chris Lattner6ee6bbe2002-10-01 22:38:37 +000051NumDCEorCP("raise", "Number of insts DCEd or constprop'd");
Chris Lattner3c019372002-05-10 15:29:25 +000052
Chris Lattner61b92c02002-10-08 22:19:25 +000053static Statistic<>
54NumVarargCallChanges("raise", "Number of vararg call peepholes");
55
Chris Lattnerd32a9612001-11-01 02:42:08 +000056#define PRINT_PEEPHOLE(ID, NUM, I) \
Chris Lattnerb3abf9d2002-05-22 17:27:12 +000057 DEBUG(std::cerr << "Inst P/H " << ID << "[" << NUM << "] " << I)
Chris Lattnerd32a9612001-11-01 02:42:08 +000058
59#define PRINT_PEEPHOLE1(ID, I1) do { PRINT_PEEPHOLE(ID, 0, I1); } while (0)
60#define PRINT_PEEPHOLE2(ID, I1, I2) \
61 do { PRINT_PEEPHOLE(ID, 0, I1); PRINT_PEEPHOLE(ID, 1, I2); } while (0)
62#define PRINT_PEEPHOLE3(ID, I1, I2, I3) \
63 do { PRINT_PEEPHOLE(ID, 0, I1); PRINT_PEEPHOLE(ID, 1, I2); \
64 PRINT_PEEPHOLE(ID, 2, I3); } while (0)
Chris Lattnerd5b48ca2001-11-14 11:02:49 +000065#define PRINT_PEEPHOLE4(ID, I1, I2, I3, I4) \
66 do { PRINT_PEEPHOLE(ID, 0, I1); PRINT_PEEPHOLE(ID, 1, I2); \
67 PRINT_PEEPHOLE(ID, 2, I3); PRINT_PEEPHOLE(ID, 3, I4); } while (0)
Chris Lattnerd32a9612001-11-01 02:42:08 +000068
Chris Lattner16125fb2003-04-24 18:25:27 +000069namespace {
70 struct RPR : public FunctionPass {
71 virtual bool runOnFunction(Function &F);
72
73 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
74 AU.setPreservesCFG();
75 AU.addRequired<TargetData>();
76 }
77
78 private:
79 bool DoRaisePass(Function &F);
80 bool PeepholeOptimize(BasicBlock *BB, BasicBlock::iterator &BI);
81 };
82
83 RegisterOpt<RPR> X("raise", "Raise Pointer References");
84}
85
Brian Gaeked0fde302003-11-11 22:41:34 +000086
Chris Lattnere7999022003-12-23 07:43:38 +000087Pass *llvm::createRaisePointerReferencesPass() {
Chris Lattner16125fb2003-04-24 18:25:27 +000088 return new RPR();
89}
90
91
Chris Lattnerd32a9612001-11-01 02:42:08 +000092// isReinterpretingCast - Return true if the cast instruction specified will
93// cause the operand to be "reinterpreted". A value is reinterpreted if the
94// cast instruction would cause the underlying bits to change.
95//
96static inline bool isReinterpretingCast(const CastInst *CI) {
Misha Brukmanf117cc92003-05-20 18:45:36 +000097 return!CI->getOperand(0)->getType()->isLosslesslyConvertibleTo(CI->getType());
Chris Lattnerd32a9612001-11-01 02:42:08 +000098}
99
100
Chris Lattnera8b6d432001-12-05 06:34:00 +0000101// Peephole optimize the following instructions:
102// %t1 = cast ? to x *
103// %t2 = add x * %SP, %t1 ;; Constant must be 2nd operand
104//
105// Into: %t3 = getelementptr {<...>} * %SP, <element indices>
106// %t2 = cast <eltype> * %t3 to {<...>}*
107//
108static bool HandleCastToPointer(BasicBlock::iterator BI,
Chris Lattner16125fb2003-04-24 18:25:27 +0000109 const PointerType *DestPTy,
110 const TargetData &TD) {
Chris Lattner7e708292002-06-25 16:13:24 +0000111 CastInst &CI = cast<CastInst>(*BI);
112 if (CI.use_empty()) return false;
Chris Lattnerf3b976e2001-11-04 20:21:12 +0000113
Chris Lattner2d399092003-05-02 19:32:04 +0000114 // Scan all of the uses, looking for any uses that are not add or sub
Chris Lattnera8b6d432001-12-05 06:34:00 +0000115 // instructions. If we have non-adds, do not make this transformation.
116 //
Chris Lattner2d399092003-05-02 19:32:04 +0000117 bool HasSubUse = false; // Keep track of any subtracts...
Chris Lattner7e708292002-06-25 16:13:24 +0000118 for (Value::use_iterator I = CI.use_begin(), E = CI.use_end();
Chris Lattner2d399092003-05-02 19:32:04 +0000119 I != E; ++I)
Chris Lattnera8b6d432001-12-05 06:34:00 +0000120 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(*I)) {
Chris Lattner2d399092003-05-02 19:32:04 +0000121 if ((BO->getOpcode() != Instruction::Add &&
122 BO->getOpcode() != Instruction::Sub) ||
Chris Lattner3fb2ddd2002-07-16 21:41:31 +0000123 // Avoid add sbyte* %X, %X cases...
124 BO->getOperand(0) == BO->getOperand(1))
Chris Lattnera8b6d432001-12-05 06:34:00 +0000125 return false;
Chris Lattner2d399092003-05-02 19:32:04 +0000126 else
127 HasSubUse |= BO->getOpcode() == Instruction::Sub;
Chris Lattnera8b6d432001-12-05 06:34:00 +0000128 } else {
129 return false;
130 }
Chris Lattnera8b6d432001-12-05 06:34:00 +0000131
Chris Lattner697954c2002-01-20 22:54:45 +0000132 std::vector<Value*> Indices;
Chris Lattner7e708292002-06-25 16:13:24 +0000133 Value *Src = CI.getOperand(0);
Misha Brukmanf117cc92003-05-20 18:45:36 +0000134 const Type *Result = ConvertibleToGEP(DestPTy, Src, Indices, TD, &BI);
135 if (Result == 0) return false; // Not convertible...
Chris Lattnera8b6d432001-12-05 06:34:00 +0000136
Chris Lattner2d399092003-05-02 19:32:04 +0000137 // Cannot handle subtracts if there is more than one index required...
138 if (HasSubUse && Indices.size() != 1) return false;
139
Chris Lattner30b43442004-07-15 02:06:12 +0000140 PRINT_PEEPHOLE2("cast-add-to-gep:in", *Src, CI);
Chris Lattnera8b6d432001-12-05 06:34:00 +0000141
142 // If we have a getelementptr capability... transform all of the
143 // add instruction uses into getelementptr's.
Chris Lattner7e708292002-06-25 16:13:24 +0000144 while (!CI.use_empty()) {
145 BinaryOperator *I = cast<BinaryOperator>(*CI.use_begin());
Chris Lattner2d399092003-05-02 19:32:04 +0000146 assert((I->getOpcode() == Instruction::Add ||
147 I->getOpcode() == Instruction::Sub) &&
Chris Lattnera8b6d432001-12-05 06:34:00 +0000148 "Use is not a valid add instruction!");
149
150 // Get the value added to the cast result pointer...
Chris Lattner7e708292002-06-25 16:13:24 +0000151 Value *OtherPtr = I->getOperand((I->getOperand(0) == &CI) ? 1 : 0);
Chris Lattnera8b6d432001-12-05 06:34:00 +0000152
Chris Lattner45ef5c22002-03-21 06:22:23 +0000153 Instruction *GEP = new GetElementPtrInst(OtherPtr, Indices, I->getName());
Chris Lattner30b43442004-07-15 02:06:12 +0000154 PRINT_PEEPHOLE1("cast-add-to-gep:i", *I);
Chris Lattner45ef5c22002-03-21 06:22:23 +0000155
Chris Lattner2d399092003-05-02 19:32:04 +0000156 // If the instruction is actually a subtract, we are guaranteed to only have
157 // one index (from code above), so we just need to negate the pointer index
158 // long value.
159 if (I->getOpcode() == Instruction::Sub) {
160 Instruction *Neg = BinaryOperator::createNeg(GEP->getOperand(1),
161 GEP->getOperand(1)->getName()+".neg", I);
162 GEP->setOperand(1, Neg);
163 }
164
Chris Lattner45ef5c22002-03-21 06:22:23 +0000165 if (GEP->getType() == I->getType()) {
166 // Replace the old add instruction with the shiny new GEP inst
167 ReplaceInstWithInst(I, GEP);
168 } else {
169 // If the type produced by the gep instruction differs from the original
170 // add instruction type, insert a cast now.
171 //
172
Chris Lattner7e708292002-06-25 16:13:24 +0000173 // Insert the GEP instruction before the old add instruction...
174 I->getParent()->getInstList().insert(I, GEP);
Chris Lattner45ef5c22002-03-21 06:22:23 +0000175
Chris Lattner30b43442004-07-15 02:06:12 +0000176 PRINT_PEEPHOLE1("cast-add-to-gep:o", *GEP);
Chris Lattner7e708292002-06-25 16:13:24 +0000177 GEP = new CastInst(GEP, I->getType());
Chris Lattner45ef5c22002-03-21 06:22:23 +0000178
179 // Replace the old add instruction with the shiny new GEP inst
Chris Lattner7e708292002-06-25 16:13:24 +0000180 ReplaceInstWithInst(I, GEP);
Chris Lattner45ef5c22002-03-21 06:22:23 +0000181 }
182
Chris Lattner30b43442004-07-15 02:06:12 +0000183 PRINT_PEEPHOLE1("cast-add-to-gep:o", *GEP);
Chris Lattnera8b6d432001-12-05 06:34:00 +0000184 }
185 return true;
186}
Chris Lattnerd5b48ca2001-11-14 11:02:49 +0000187
188// Peephole optimize the following instructions:
189// %t1 = cast ulong <const int> to {<...>} *
190// %t2 = add {<...>} * %SP, %t1 ;; Constant must be 2nd operand
191//
192// or
193// %t1 = cast {<...>}* %SP to int*
194// %t5 = cast ulong <const int> to int*
195// %t2 = add int* %t1, %t5 ;; int is same size as field
196//
197// Into: %t3 = getelementptr {<...>} * %SP, <element indices>
198// %t2 = cast <eltype> * %t3 to {<...>}*
199//
200static bool PeepholeOptimizeAddCast(BasicBlock *BB, BasicBlock::iterator &BI,
Chris Lattner16125fb2003-04-24 18:25:27 +0000201 Value *AddOp1, CastInst *AddOp2,
202 const TargetData &TD) {
Chris Lattner3cc7dde2001-11-26 16:58:14 +0000203 const CompositeType *CompTy;
204 Value *OffsetVal = AddOp2->getOperand(0);
Chris Lattner0ceeb422002-10-22 23:34:11 +0000205 Value *SrcPtr = 0; // Of type pointer to struct...
Chris Lattnerd5b48ca2001-11-14 11:02:49 +0000206
Chris Lattner3cc7dde2001-11-26 16:58:14 +0000207 if ((CompTy = getPointedToComposite(AddOp1->getType()))) {
Chris Lattnerd5b48ca2001-11-14 11:02:49 +0000208 SrcPtr = AddOp1; // Handle the first case...
209 } else if (CastInst *AddOp1c = dyn_cast<CastInst>(AddOp1)) {
210 SrcPtr = AddOp1c->getOperand(0); // Handle the second case...
Chris Lattner3cc7dde2001-11-26 16:58:14 +0000211 CompTy = getPointedToComposite(SrcPtr->getType());
Chris Lattnerd5b48ca2001-11-14 11:02:49 +0000212 }
213
214 // Only proceed if we have detected all of our conditions successfully...
Chris Lattner0c4e8862002-09-03 01:08:28 +0000215 if (!CompTy || !SrcPtr || !OffsetVal->getType()->isInteger())
Chris Lattnerd5b48ca2001-11-14 11:02:49 +0000216 return false;
217
Chris Lattner697954c2002-01-20 22:54:45 +0000218 std::vector<Value*> Indices;
Misha Brukmanf117cc92003-05-20 18:45:36 +0000219 if (!ConvertibleToGEP(SrcPtr->getType(), OffsetVal, Indices, TD, &BI))
220 return false; // Not convertible... perhaps next time
Chris Lattnerd5b48ca2001-11-14 11:02:49 +0000221
Chris Lattner3cc7dde2001-11-26 16:58:14 +0000222 if (getPointedToComposite(AddOp1->getType())) { // case 1
Chris Lattner30b43442004-07-15 02:06:12 +0000223 PRINT_PEEPHOLE2("add-to-gep1:in", *AddOp2, *BI);
Chris Lattnerd5b48ca2001-11-14 11:02:49 +0000224 } else {
Chris Lattner30b43442004-07-15 02:06:12 +0000225 PRINT_PEEPHOLE3("add-to-gep2:in", *AddOp1, *AddOp2, *BI);
Chris Lattnerd5b48ca2001-11-14 11:02:49 +0000226 }
227
Chris Lattner3cc7dde2001-11-26 16:58:14 +0000228 GetElementPtrInst *GEP = new GetElementPtrInst(SrcPtr, Indices,
Chris Lattner2a7c23e2002-09-10 17:04:02 +0000229 AddOp2->getName(), BI);
Chris Lattnerd5b48ca2001-11-14 11:02:49 +0000230
Chris Lattner3cc7dde2001-11-26 16:58:14 +0000231 Instruction *NCI = new CastInst(GEP, AddOp1->getType());
Chris Lattnerd5b48ca2001-11-14 11:02:49 +0000232 ReplaceInstWithInst(BB->getInstList(), BI, NCI);
Chris Lattner30b43442004-07-15 02:06:12 +0000233 PRINT_PEEPHOLE2("add-to-gep:out", *GEP, *NCI);
Chris Lattnerd5b48ca2001-11-14 11:02:49 +0000234 return true;
235}
236
Chris Lattner16125fb2003-04-24 18:25:27 +0000237bool RPR::PeepholeOptimize(BasicBlock *BB, BasicBlock::iterator &BI) {
Chris Lattner7e708292002-06-25 16:13:24 +0000238 Instruction *I = BI;
Chris Lattner16125fb2003-04-24 18:25:27 +0000239 const TargetData &TD = getAnalysis<TargetData>();
Chris Lattnerd32a9612001-11-01 02:42:08 +0000240
241 if (CastInst *CI = dyn_cast<CastInst>(I)) {
242 Value *Src = CI->getOperand(0);
243 Instruction *SrcI = dyn_cast<Instruction>(Src); // Nonnull if instr source
244 const Type *DestTy = CI->getType();
245
Chris Lattnere99c66b2001-11-01 17:05:27 +0000246 // Peephole optimize the following instruction:
247 // %V2 = cast <ty> %V to <ty>
248 //
249 // Into: <nothing>
250 //
251 if (DestTy == Src->getType()) { // Check for a cast to same type as src!!
Chris Lattner30b43442004-07-15 02:06:12 +0000252 PRINT_PEEPHOLE1("cast-of-self-ty", *CI);
Chris Lattnerd32a9612001-11-01 02:42:08 +0000253 CI->replaceAllUsesWith(Src);
254 if (!Src->hasName() && CI->hasName()) {
Chris Lattner697954c2002-01-20 22:54:45 +0000255 std::string Name = CI->getName();
Chris Lattnerf3b976e2001-11-04 20:21:12 +0000256 CI->setName("");
Chris Lattner6e6026b2002-11-20 18:36:02 +0000257 Src->setName(Name, &BB->getParent()->getSymbolTable());
Chris Lattnerd32a9612001-11-01 02:42:08 +0000258 }
Chris Lattner3c019372002-05-10 15:29:25 +0000259
260 // DCE the instruction now, to avoid having the iterative version of DCE
261 // have to worry about it.
262 //
Chris Lattner7e708292002-06-25 16:13:24 +0000263 BI = BB->getInstList().erase(BI);
Chris Lattner3c019372002-05-10 15:29:25 +0000264
265 ++NumCastOfCast;
Chris Lattnerd32a9612001-11-01 02:42:08 +0000266 return true;
267 }
268
Chris Lattnerd32a9612001-11-01 02:42:08 +0000269 // Check to see if it's a cast of an instruction that does not depend on the
270 // specific type of the operands to do it's job.
Chris Lattnerf3b976e2001-11-04 20:21:12 +0000271 if (!isReinterpretingCast(CI)) {
Chris Lattnerb980e182001-11-04 21:32:11 +0000272 ValueTypeCache ConvertedTypes;
Chris Lattnera8b6d432001-12-05 06:34:00 +0000273
Chris Lattnerd20a98e2002-05-24 20:41:51 +0000274 // Check to see if we can convert the source of the cast to match the
275 // destination type of the cast...
Chris Lattnera8b6d432001-12-05 06:34:00 +0000276 //
Chris Lattnerd5543802001-12-14 16:37:52 +0000277 ConvertedTypes[CI] = CI->getType(); // Make sure the cast doesn't change
Misha Brukmanf117cc92003-05-20 18:45:36 +0000278 if (ExpressionConvertibleToType(Src, DestTy, ConvertedTypes, TD)) {
Chris Lattner30b43442004-07-15 02:06:12 +0000279 PRINT_PEEPHOLE3("CAST-SRC-EXPR-CONV:in ", *Src, *CI, *BB->getParent());
Chris Lattnerc0b90e72001-11-08 20:19:56 +0000280
Chris Lattner6806f562003-08-01 22:15:03 +0000281 DEBUG(std::cerr << "\nCONVERTING SRC EXPR TYPE:\n");
Chris Lattnerb1b42622002-07-17 17:11:33 +0000282 { // ValueMap must be destroyed before function verified!
283 ValueMapCache ValueMap;
Chris Lattner16125fb2003-04-24 18:25:27 +0000284 Value *E = ConvertExpressionToType(Src, DestTy, ValueMap, TD);
Chris Lattnerc0b90e72001-11-08 20:19:56 +0000285
Chris Lattnerb1b42622002-07-17 17:11:33 +0000286 if (Constant *CPV = dyn_cast<Constant>(E))
287 CI->replaceAllUsesWith(CPV);
288
Chris Lattner30b43442004-07-15 02:06:12 +0000289 PRINT_PEEPHOLE1("CAST-SRC-EXPR-CONV:out", *E);
Chris Lattner6806f562003-08-01 22:15:03 +0000290 DEBUG(std::cerr << "DONE CONVERTING SRC EXPR TYPE: \n"
Chris Lattner30b43442004-07-15 02:06:12 +0000291 << *BB->getParent());
Chris Lattnerb1b42622002-07-17 17:11:33 +0000292 }
Chris Lattner3378a5b2002-07-16 23:49:24 +0000293
Chris Lattnerb1b42622002-07-17 17:11:33 +0000294 BI = BB->begin(); // Rescan basic block. BI might be invalidated.
Chris Lattner3c019372002-05-10 15:29:25 +0000295 ++NumExprTreesConv;
Chris Lattnerd5543802001-12-14 16:37:52 +0000296 return true;
297 }
298
Chris Lattnerd20a98e2002-05-24 20:41:51 +0000299 // Check to see if we can convert the users of the cast value to match the
300 // source type of the cast...
Chris Lattnerd5543802001-12-14 16:37:52 +0000301 //
302 ConvertedTypes.clear();
Chris Lattner61b92c02002-10-08 22:19:25 +0000303 // Make sure the source doesn't change type
304 ConvertedTypes[Src] = Src->getType();
Misha Brukmanf117cc92003-05-20 18:45:36 +0000305 if (ValueConvertibleToType(CI, Src->getType(), ConvertedTypes, TD)) {
Chris Lattner30b43442004-07-15 02:06:12 +0000306 PRINT_PEEPHOLE3("CAST-DEST-EXPR-CONV:in ", *Src, *CI, *BB->getParent());
Chris Lattnerd5543802001-12-14 16:37:52 +0000307
Chris Lattner6806f562003-08-01 22:15:03 +0000308 DEBUG(std::cerr << "\nCONVERTING EXPR TYPE:\n");
Chris Lattnerb1b42622002-07-17 17:11:33 +0000309 { // ValueMap must be destroyed before function verified!
310 ValueMapCache ValueMap;
Chris Lattner16125fb2003-04-24 18:25:27 +0000311 ConvertValueToNewType(CI, Src, ValueMap, TD); // This will delete CI!
Chris Lattnerb1b42622002-07-17 17:11:33 +0000312 }
Chris Lattnerd5543802001-12-14 16:37:52 +0000313
Chris Lattner30b43442004-07-15 02:06:12 +0000314 PRINT_PEEPHOLE1("CAST-DEST-EXPR-CONV:out", *Src);
315 DEBUG(std::cerr << "DONE CONVERTING EXPR TYPE: \n\n" <<
316 *BB->getParent());
Chris Lattner3378a5b2002-07-16 23:49:24 +0000317
Chris Lattnerb1b42622002-07-17 17:11:33 +0000318 BI = BB->begin(); // Rescan basic block. BI might be invalidated.
Chris Lattner3c019372002-05-10 15:29:25 +0000319 ++NumExprTreesConv;
Chris Lattnera8b6d432001-12-05 06:34:00 +0000320 return true;
Chris Lattnerf3b976e2001-11-04 20:21:12 +0000321 }
Chris Lattnerf17a09d2001-12-06 18:06:13 +0000322 }
323
324 // Otherwise find out it this cast is a cast to a pointer type, which is
325 // then added to some other pointer, then loaded or stored through. If
326 // so, convert the add into a getelementptr instruction...
327 //
328 if (const PointerType *DestPTy = dyn_cast<PointerType>(DestTy)) {
Chris Lattner16125fb2003-04-24 18:25:27 +0000329 if (HandleCastToPointer(BI, DestPTy, TD)) {
Chris Lattnerf17a09d2001-12-06 18:06:13 +0000330 BI = BB->begin(); // Rescan basic block. BI might be invalidated.
Chris Lattner3c019372002-05-10 15:29:25 +0000331 ++NumGEPInstFormed;
Chris Lattnerf17a09d2001-12-06 18:06:13 +0000332 return true;
Chris Lattnera8b6d432001-12-05 06:34:00 +0000333 }
Chris Lattnerd32a9612001-11-01 02:42:08 +0000334 }
335
Chris Lattnere99c66b2001-11-01 17:05:27 +0000336 // Check to see if we are casting from a structure pointer to a pointer to
337 // the first element of the structure... to avoid munching other peepholes,
338 // we only let this happen if there are no add uses of the cast.
339 //
340 // Peephole optimize the following instructions:
341 // %t1 = cast {<...>} * %StructPtr to <ty> *
342 //
343 // Into: %t2 = getelementptr {<...>} * %StructPtr, <0, 0, 0, ...>
344 // %t1 = cast <eltype> * %t1 to <ty> *
345 //
Chris Lattner3cc7dde2001-11-26 16:58:14 +0000346 if (const CompositeType *CTy = getPointedToComposite(Src->getType()))
Chris Lattnere99c66b2001-11-01 17:05:27 +0000347 if (const PointerType *DestPTy = dyn_cast<PointerType>(DestTy)) {
348
349 // Loop over uses of the cast, checking for add instructions. If an add
350 // exists, this is probably a part of a more complex GEP, so we don't
351 // want to mess around with the cast.
352 //
353 bool HasAddUse = false;
354 for (Value::use_iterator I = CI->use_begin(), E = CI->use_end();
355 I != E; ++I)
356 if (isa<Instruction>(*I) &&
357 cast<Instruction>(*I)->getOpcode() == Instruction::Add) {
358 HasAddUse = true; break;
359 }
360
361 // If it doesn't have an add use, check to see if the dest type is
Misha Brukmanf117cc92003-05-20 18:45:36 +0000362 // losslessly convertible to one of the types in the start of the struct
Chris Lattnere99c66b2001-11-01 17:05:27 +0000363 // type.
364 //
365 if (!HasAddUse) {
Chris Lattner7a176752001-12-04 00:03:30 +0000366 const Type *DestPointedTy = DestPTy->getElementType();
Chris Lattnere99c66b2001-11-01 17:05:27 +0000367 unsigned Depth = 1;
Chris Lattner3cc7dde2001-11-26 16:58:14 +0000368 const CompositeType *CurCTy = CTy;
Chris Lattnere99c66b2001-11-01 17:05:27 +0000369 const Type *ElTy = 0;
Chris Lattner3cc7dde2001-11-26 16:58:14 +0000370
371 // Build the index vector, full of all zeros
Chris Lattner697954c2002-01-20 22:54:45 +0000372 std::vector<Value*> Indices;
Chris Lattner559d5192004-01-09 05:53:38 +0000373
Chris Lattner28977af2004-04-05 01:30:19 +0000374 Indices.push_back(Constant::getNullValue(Type::UIntTy));
Chris Lattnerd5543802001-12-14 16:37:52 +0000375 while (CurCTy && !isa<PointerType>(CurCTy)) {
Chris Lattner3cc7dde2001-11-26 16:58:14 +0000376 if (const StructType *CurSTy = dyn_cast<StructType>(CurCTy)) {
377 // Check for a zero element struct type... if we have one, bail.
Chris Lattnerd21cd802004-02-09 04:37:31 +0000378 if (CurSTy->getNumElements() == 0) break;
Chris Lattnere99c66b2001-11-01 17:05:27 +0000379
Chris Lattner3cc7dde2001-11-26 16:58:14 +0000380 // Grab the first element of the struct type, which must lie at
381 // offset zero in the struct.
382 //
Chris Lattnerd21cd802004-02-09 04:37:31 +0000383 ElTy = CurSTy->getElementType(0);
Chris Lattner3cc7dde2001-11-26 16:58:14 +0000384 } else {
385 ElTy = cast<ArrayType>(CurCTy)->getElementType();
386 }
387
388 // Insert a zero to index through this type...
Chris Lattner28977af2004-04-05 01:30:19 +0000389 Indices.push_back(Constant::getNullValue(Type::UIntTy));
Chris Lattnere99c66b2001-11-01 17:05:27 +0000390
391 // Did we find what we're looking for?
Misha Brukmanf117cc92003-05-20 18:45:36 +0000392 if (ElTy->isLosslesslyConvertibleTo(DestPointedTy)) break;
Chris Lattnere99c66b2001-11-01 17:05:27 +0000393
394 // Nope, go a level deeper.
395 ++Depth;
Chris Lattner3cc7dde2001-11-26 16:58:14 +0000396 CurCTy = dyn_cast<CompositeType>(ElTy);
Chris Lattnere99c66b2001-11-01 17:05:27 +0000397 ElTy = 0;
398 }
399
400 // Did we find what we were looking for? If so, do the transformation
401 if (ElTy) {
Chris Lattner30b43442004-07-15 02:06:12 +0000402 PRINT_PEEPHOLE1("cast-for-first:in", *CI);
Chris Lattnere99c66b2001-11-01 17:05:27 +0000403
Chris Lattner2a7c23e2002-09-10 17:04:02 +0000404 std::string Name = CI->getName(); CI->setName("");
405
Chris Lattnere99c66b2001-11-01 17:05:27 +0000406 // Insert the new T cast instruction... stealing old T's name
407 GetElementPtrInst *GEP = new GetElementPtrInst(Src, Indices,
Chris Lattner2a7c23e2002-09-10 17:04:02 +0000408 Name, BI);
Chris Lattnere99c66b2001-11-01 17:05:27 +0000409
410 // Make the old cast instruction reference the new GEP instead of
411 // the old src value.
412 //
413 CI->setOperand(0, GEP);
414
Chris Lattner30b43442004-07-15 02:06:12 +0000415 PRINT_PEEPHOLE2("cast-for-first:out", *GEP, *CI);
Chris Lattner3c019372002-05-10 15:29:25 +0000416 ++NumGEPInstFormed;
Chris Lattnere99c66b2001-11-01 17:05:27 +0000417 return true;
418 }
419 }
420 }
Chris Lattnere99c66b2001-11-01 17:05:27 +0000421
Chris Lattner8d38e542001-11-01 03:12:34 +0000422 } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
423 Value *Val = SI->getOperand(0);
Chris Lattner65ea1712001-11-14 11:27:58 +0000424 Value *Pointer = SI->getPointerOperand();
Chris Lattner8d38e542001-11-01 03:12:34 +0000425
Chris Lattnerdedee7b2001-11-01 05:57:59 +0000426 // Peephole optimize the following instructions:
Misha Brukmanf117cc92003-05-20 18:45:36 +0000427 // %t = cast <T1>* %P to <T2> * ;; If T1 is losslessly convertible to T2
Chris Lattnerdedee7b2001-11-01 05:57:59 +0000428 // store <T2> %V, <T2>* %t
429 //
430 // Into:
431 // %t = cast <T2> %V to <T1>
432 // store <T1> %t2, <T1>* %P
433 //
Chris Lattnerd5543802001-12-14 16:37:52 +0000434 // Note: This is not taken care of by expr conversion because there might
435 // not be a cast available for the store to convert the incoming value of.
436 // This code is basically here to make sure that pointers don't have casts
437 // if possible.
438 //
Chris Lattnerdedee7b2001-11-01 05:57:59 +0000439 if (CastInst *CI = dyn_cast<CastInst>(Pointer))
440 if (Value *CastSrc = CI->getOperand(0)) // CSPT = CastSrcPointerType
Chris Lattner7e708292002-06-25 16:13:24 +0000441 if (const PointerType *CSPT = dyn_cast<PointerType>(CastSrc->getType()))
Misha Brukmanf117cc92003-05-20 18:45:36 +0000442 // convertible types?
443 if (Val->getType()->isLosslesslyConvertibleTo(CSPT->getElementType())) {
Chris Lattner30b43442004-07-15 02:06:12 +0000444 PRINT_PEEPHOLE3("st-src-cast:in ", *Pointer, *Val, *SI);
Chris Lattnerdedee7b2001-11-01 05:57:59 +0000445
446 // Insert the new T cast instruction... stealing old T's name
Chris Lattner2a7c23e2002-09-10 17:04:02 +0000447 std::string Name(CI->getName()); CI->setName("");
Chris Lattner7a176752001-12-04 00:03:30 +0000448 CastInst *NCI = new CastInst(Val, CSPT->getElementType(),
Chris Lattner2a7c23e2002-09-10 17:04:02 +0000449 Name, BI);
Chris Lattnerdedee7b2001-11-01 05:57:59 +0000450
451 // Replace the old store with a new one!
452 ReplaceInstWithInst(BB->getInstList(), BI,
453 SI = new StoreInst(NCI, CastSrc));
Chris Lattner30b43442004-07-15 02:06:12 +0000454 PRINT_PEEPHOLE3("st-src-cast:out", *NCI, *CastSrc, *SI);
Chris Lattner3c019372002-05-10 15:29:25 +0000455 ++NumLoadStorePeepholes;
Chris Lattnerdedee7b2001-11-01 05:57:59 +0000456 return true;
457 }
458
Chris Lattnerc99428f2002-05-14 05:23:45 +0000459 } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
460 Value *Pointer = LI->getOperand(0);
461 const Type *PtrElType =
462 cast<PointerType>(Pointer->getType())->getElementType();
463
464 // Peephole optimize the following instructions:
Misha Brukmanf117cc92003-05-20 18:45:36 +0000465 // %Val = cast <T1>* to <T2>* ;; If T1 is losslessly convertible to T2
Chris Lattnerc99428f2002-05-14 05:23:45 +0000466 // %t = load <T2>* %P
467 //
468 // Into:
469 // %t = load <T1>* %P
470 // %Val = cast <T1> to <T2>
471 //
472 // Note: This is not taken care of by expr conversion because there might
473 // not be a cast available for the store to convert the incoming value of.
474 // This code is basically here to make sure that pointers don't have casts
475 // if possible.
476 //
477 if (CastInst *CI = dyn_cast<CastInst>(Pointer))
478 if (Value *CastSrc = CI->getOperand(0)) // CSPT = CastSrcPointerType
Chris Lattner7e708292002-06-25 16:13:24 +0000479 if (const PointerType *CSPT = dyn_cast<PointerType>(CastSrc->getType()))
Misha Brukmanf117cc92003-05-20 18:45:36 +0000480 // convertible types?
481 if (PtrElType->isLosslesslyConvertibleTo(CSPT->getElementType())) {
Chris Lattner30b43442004-07-15 02:06:12 +0000482 PRINT_PEEPHOLE2("load-src-cast:in ", *Pointer, *LI);
Chris Lattnerc99428f2002-05-14 05:23:45 +0000483
484 // Create the new load instruction... loading the pre-casted value
Chris Lattner2a7c23e2002-09-10 17:04:02 +0000485 LoadInst *NewLI = new LoadInst(CastSrc, LI->getName(), BI);
Chris Lattnerc99428f2002-05-14 05:23:45 +0000486
487 // Insert the new T cast instruction... stealing old T's name
488 CastInst *NCI = new CastInst(NewLI, LI->getType(), CI->getName());
Chris Lattnerc99428f2002-05-14 05:23:45 +0000489
490 // Replace the old store with a new one!
491 ReplaceInstWithInst(BB->getInstList(), BI, NCI);
Chris Lattner30b43442004-07-15 02:06:12 +0000492 PRINT_PEEPHOLE3("load-src-cast:out", *NCI, *CastSrc, *NewLI);
Chris Lattnerc99428f2002-05-14 05:23:45 +0000493 ++NumLoadStorePeepholes;
494 return true;
495 }
496
Chris Lattnerd32a9612001-11-01 02:42:08 +0000497 } else if (I->getOpcode() == Instruction::Add &&
498 isa<CastInst>(I->getOperand(1))) {
499
Chris Lattnerd5b48ca2001-11-14 11:02:49 +0000500 if (PeepholeOptimizeAddCast(BB, BI, I->getOperand(0),
Chris Lattner16125fb2003-04-24 18:25:27 +0000501 cast<CastInst>(I->getOperand(1)), TD)) {
Chris Lattner3c019372002-05-10 15:29:25 +0000502 ++NumGEPInstFormed;
Chris Lattnerd32a9612001-11-01 02:42:08 +0000503 return true;
Chris Lattner3c019372002-05-10 15:29:25 +0000504 }
Chris Lattner61b92c02002-10-08 22:19:25 +0000505 } else if (CallInst *CI = dyn_cast<CallInst>(I)) {
506 // If we have a call with all varargs arguments, convert the call to use the
507 // actual argument types present...
508 //
509 const PointerType *PTy = cast<PointerType>(CI->getCalledValue()->getType());
510 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
511
512 // Is the call to a vararg variable with no real parameters?
Chris Lattnercdeb81d2003-05-01 21:02:53 +0000513 if (FTy->isVarArg() && FTy->getNumParams() == 0 &&
514 !CI->getCalledFunction()) {
Chris Lattner61b92c02002-10-08 22:19:25 +0000515 // If so, insert a new cast instruction, casting it to a function type
516 // that matches the current arguments...
517 //
518 std::vector<const Type *> Params; // Parameter types...
519 for (unsigned i = 1, e = CI->getNumOperands(); i != e; ++i)
520 Params.push_back(CI->getOperand(i)->getType());
521
522 FunctionType *NewFT = FunctionType::get(FTy->getReturnType(),
523 Params, false);
524 PointerType *NewPFunTy = PointerType::get(NewFT);
525
526 // Create a new cast, inserting it right before the function call...
Chris Lattner95549282003-04-28 01:25:38 +0000527 Value *NewCast;
528 Constant *ConstantCallSrc = 0;
529 if (Constant *CS = dyn_cast<Constant>(CI->getCalledValue()))
530 ConstantCallSrc = CS;
531 else if (GlobalValue *GV = dyn_cast<GlobalValue>(CI->getCalledValue()))
532 ConstantCallSrc = ConstantPointerRef::get(GV);
533
534 if (ConstantCallSrc)
535 NewCast = ConstantExpr::getCast(ConstantCallSrc, NewPFunTy);
536 else
537 NewCast = new CastInst(CI->getCalledValue(), NewPFunTy,
538 CI->getCalledValue()->getName()+"_c",CI);
Chris Lattner61b92c02002-10-08 22:19:25 +0000539
Chris Lattner99d6b8e2004-02-09 00:20:55 +0000540 // Strip off unneeded CPR's.
541 if (ConstantPointerRef *CPR = dyn_cast<ConstantPointerRef>(NewCast))
542 NewCast = CPR->getValue();
543
Chris Lattner61b92c02002-10-08 22:19:25 +0000544 // Create a new call instruction...
545 CallInst *NewCall = new CallInst(NewCast,
546 std::vector<Value*>(CI->op_begin()+1, CI->op_end()));
547 ++BI;
548 ReplaceInstWithInst(CI, NewCall);
549
550 ++NumVarargCallChanges;
551 return true;
552 }
553
Chris Lattnerd32a9612001-11-01 02:42:08 +0000554 }
555
556 return false;
557}
558
559
560
561
Chris Lattner16125fb2003-04-24 18:25:27 +0000562bool RPR::DoRaisePass(Function &F) {
Chris Lattnerd32a9612001-11-01 02:42:08 +0000563 bool Changed = false;
Chris Lattner7e708292002-06-25 16:13:24 +0000564 for (Function::iterator BB = F.begin(), BBE = F.end(); BB != BBE; ++BB)
Chris Lattnerd32a9612001-11-01 02:42:08 +0000565 for (BasicBlock::iterator BI = BB->begin(); BI != BB->end();) {
Brian Gaekea9160a02004-07-01 19:27:10 +0000566 DEBUG(std::cerr << "LevelRaising: " << *BI);
Misha Brukman82c89b92003-05-20 21:01:22 +0000567 if (dceInstruction(BI) || doConstantPropagation(BI)) {
Chris Lattnerc0b90e72001-11-08 20:19:56 +0000568 Changed = true;
Chris Lattner3c019372002-05-10 15:29:25 +0000569 ++NumDCEorCP;
Chris Lattner6806f562003-08-01 22:15:03 +0000570 DEBUG(std::cerr << "***\t\t^^-- Dead code eliminated!\n");
Chris Lattner7e708292002-06-25 16:13:24 +0000571 } else if (PeepholeOptimize(BB, BI)) {
Chris Lattnerd32a9612001-11-01 02:42:08 +0000572 Changed = true;
Chris Lattner7e708292002-06-25 16:13:24 +0000573 } else {
Chris Lattnerd32a9612001-11-01 02:42:08 +0000574 ++BI;
Chris Lattner7e708292002-06-25 16:13:24 +0000575 }
Chris Lattnerd32a9612001-11-01 02:42:08 +0000576 }
Chris Lattner7e708292002-06-25 16:13:24 +0000577
Chris Lattnerd32a9612001-11-01 02:42:08 +0000578 return Changed;
579}
580
581
Chris Lattner16125fb2003-04-24 18:25:27 +0000582// runOnFunction - Raise a function representation to a higher level.
583bool RPR::runOnFunction(Function &F) {
Chris Lattner6806f562003-08-01 22:15:03 +0000584 DEBUG(std::cerr << "\n\n\nStarting to work on Function '" << F.getName()
585 << "'\n");
Chris Lattner68b07b72001-11-01 07:00:51 +0000586
Chris Lattner3cc7dde2001-11-26 16:58:14 +0000587 // Insert casts for all incoming pointer pointer values that are treated as
588 // arrays...
Chris Lattnerd32a9612001-11-01 02:42:08 +0000589 //
Chris Lattner3cc7dde2001-11-26 16:58:14 +0000590 bool Changed = false, LocalChange;
Chris Lattner3378a5b2002-07-16 23:49:24 +0000591
592 // If the StartInst option was specified, then Peephole optimize that
593 // instruction first if it occurs in this function.
594 //
595 if (!StartInst.empty()) {
596 for (Function::iterator BB = F.begin(), BBE = F.end(); BB != BBE; ++BB)
597 for (BasicBlock::iterator BI = BB->begin(); BI != BB->end(); ++BI)
598 if (BI->getName() == StartInst) {
599 bool SavedDebug = DebugFlag; // Save the DEBUG() controlling flag.
600 DebugFlag = true; // Turn on DEBUG's
601 Changed |= PeepholeOptimize(BB, BI);
602 DebugFlag = SavedDebug; // Restore DebugFlag to previous state
603 }
604 }
605
Chris Lattner4b770a32001-12-04 08:12:53 +0000606 do {
Chris Lattner6806f562003-08-01 22:15:03 +0000607 DEBUG(std::cerr << "Looping: \n" << F);
Chris Lattnera8b6d432001-12-05 06:34:00 +0000608
Chris Lattnerf57b8452002-04-27 06:56:12 +0000609 // Iterate over the function, refining it, until it converges on a stable
Chris Lattner3cc7dde2001-11-26 16:58:14 +0000610 // state
Chris Lattnerd5543802001-12-14 16:37:52 +0000611 LocalChange = false;
Chris Lattner2fbfdcf2002-04-07 20:49:59 +0000612 while (DoRaisePass(F)) LocalChange = true;
Chris Lattner3cc7dde2001-11-26 16:58:14 +0000613 Changed |= LocalChange;
614
615 } while (LocalChange);
Chris Lattnerd32a9612001-11-01 02:42:08 +0000616
617 return Changed;
618}
Brian Gaeked0fde302003-11-11 22:41:34 +0000619