blob: d76beee56f948b7a79b051f5debbb21df9f4bc6c [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 Lattner497c60c2002-05-07 18:12:18 +000023#include "llvm/Transforms/Utils/BasicBlockUtils.h"
Chris Lattner3378a5b2002-07-16 23:49:24 +000024#include "Support/CommandLine.h"
Chris Lattner6806f562003-08-01 22:15:03 +000025#include "Support/Debug.h"
26#include "Support/Statistic.h"
27#include "Support/STLExtras.h"
Chris Lattnerd32a9612001-11-01 02:42:08 +000028#include <algorithm>
Chris Lattnere7999022003-12-23 07:43:38 +000029using namespace llvm;
Brian Gaeked0fde302003-11-11 22:41:34 +000030
Chris Lattner3378a5b2002-07-16 23:49:24 +000031// StartInst - This enables the -raise-start-inst=foo option to cause the level
32// raising pass to start at instruction "foo", which is immensely useful for
33// debugging!
34//
Chris Lattner5ff62e92002-07-22 02:10:13 +000035static cl::opt<std::string>
36StartInst("raise-start-inst", cl::Hidden, cl::value_desc("inst name"),
37 cl::desc("Start raise pass at the instruction with the specified name"));
Chris Lattner3378a5b2002-07-16 23:49:24 +000038
Chris Lattner5ff62e92002-07-22 02:10:13 +000039static Statistic<>
Chris Lattner6ee6bbe2002-10-01 22:38:37 +000040NumLoadStorePeepholes("raise", "Number of load/store peepholes");
Chris Lattner5ff62e92002-07-22 02:10:13 +000041
42static Statistic<>
Chris Lattner6ee6bbe2002-10-01 22:38:37 +000043NumGEPInstFormed("raise", "Number of other getelementptr's formed");
Chris Lattner5ff62e92002-07-22 02:10:13 +000044
45static Statistic<>
Chris Lattner6ee6bbe2002-10-01 22:38:37 +000046NumExprTreesConv("raise", "Number of expression trees converted");
Chris Lattner5ff62e92002-07-22 02:10:13 +000047
48static Statistic<>
Chris Lattner6ee6bbe2002-10-01 22:38:37 +000049NumCastOfCast("raise", "Number of cast-of-self removed");
Chris Lattner5ff62e92002-07-22 02:10:13 +000050
51static Statistic<>
Chris Lattner6ee6bbe2002-10-01 22:38:37 +000052NumDCEorCP("raise", "Number of insts DCEd or constprop'd");
Chris Lattner3c019372002-05-10 15:29:25 +000053
Chris Lattner61b92c02002-10-08 22:19:25 +000054static Statistic<>
55NumVarargCallChanges("raise", "Number of vararg call peepholes");
56
Chris Lattnerd32a9612001-11-01 02:42:08 +000057#define PRINT_PEEPHOLE(ID, NUM, I) \
Chris Lattnerb3abf9d2002-05-22 17:27:12 +000058 DEBUG(std::cerr << "Inst P/H " << ID << "[" << NUM << "] " << I)
Chris Lattnerd32a9612001-11-01 02:42:08 +000059
60#define PRINT_PEEPHOLE1(ID, I1) do { PRINT_PEEPHOLE(ID, 0, I1); } while (0)
61#define PRINT_PEEPHOLE2(ID, I1, I2) \
62 do { PRINT_PEEPHOLE(ID, 0, I1); PRINT_PEEPHOLE(ID, 1, I2); } while (0)
63#define PRINT_PEEPHOLE3(ID, I1, I2, I3) \
64 do { PRINT_PEEPHOLE(ID, 0, I1); PRINT_PEEPHOLE(ID, 1, I2); \
65 PRINT_PEEPHOLE(ID, 2, I3); } while (0)
Chris Lattnerd5b48ca2001-11-14 11:02:49 +000066#define PRINT_PEEPHOLE4(ID, I1, I2, I3, I4) \
67 do { PRINT_PEEPHOLE(ID, 0, I1); PRINT_PEEPHOLE(ID, 1, I2); \
68 PRINT_PEEPHOLE(ID, 2, I3); PRINT_PEEPHOLE(ID, 3, I4); } while (0)
Chris Lattnerd32a9612001-11-01 02:42:08 +000069
Chris Lattner16125fb2003-04-24 18:25:27 +000070namespace {
71 struct RPR : public FunctionPass {
72 virtual bool runOnFunction(Function &F);
73
74 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
75 AU.setPreservesCFG();
76 AU.addRequired<TargetData>();
77 }
78
79 private:
80 bool DoRaisePass(Function &F);
81 bool PeepholeOptimize(BasicBlock *BB, BasicBlock::iterator &BI);
82 };
83
84 RegisterOpt<RPR> X("raise", "Raise Pointer References");
85}
86
Brian Gaeked0fde302003-11-11 22:41:34 +000087
Chris Lattnere7999022003-12-23 07:43:38 +000088Pass *llvm::createRaisePointerReferencesPass() {
Chris Lattner16125fb2003-04-24 18:25:27 +000089 return new RPR();
90}
91
92
Chris Lattnerd32a9612001-11-01 02:42:08 +000093// isReinterpretingCast - Return true if the cast instruction specified will
94// cause the operand to be "reinterpreted". A value is reinterpreted if the
95// cast instruction would cause the underlying bits to change.
96//
97static inline bool isReinterpretingCast(const CastInst *CI) {
Misha Brukmanf117cc92003-05-20 18:45:36 +000098 return!CI->getOperand(0)->getType()->isLosslesslyConvertibleTo(CI->getType());
Chris Lattnerd32a9612001-11-01 02:42:08 +000099}
100
101
Chris Lattnera8b6d432001-12-05 06:34:00 +0000102// Peephole optimize the following instructions:
103// %t1 = cast ? to x *
104// %t2 = add x * %SP, %t1 ;; Constant must be 2nd operand
105//
106// Into: %t3 = getelementptr {<...>} * %SP, <element indices>
107// %t2 = cast <eltype> * %t3 to {<...>}*
108//
109static bool HandleCastToPointer(BasicBlock::iterator BI,
Chris Lattner16125fb2003-04-24 18:25:27 +0000110 const PointerType *DestPTy,
111 const TargetData &TD) {
Chris Lattner7e708292002-06-25 16:13:24 +0000112 CastInst &CI = cast<CastInst>(*BI);
113 if (CI.use_empty()) return false;
Chris Lattnerf3b976e2001-11-04 20:21:12 +0000114
Chris Lattner2d399092003-05-02 19:32:04 +0000115 // Scan all of the uses, looking for any uses that are not add or sub
Chris Lattnera8b6d432001-12-05 06:34:00 +0000116 // instructions. If we have non-adds, do not make this transformation.
117 //
Chris Lattner2d399092003-05-02 19:32:04 +0000118 bool HasSubUse = false; // Keep track of any subtracts...
Chris Lattner7e708292002-06-25 16:13:24 +0000119 for (Value::use_iterator I = CI.use_begin(), E = CI.use_end();
Chris Lattner2d399092003-05-02 19:32:04 +0000120 I != E; ++I)
Chris Lattnera8b6d432001-12-05 06:34:00 +0000121 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(*I)) {
Chris Lattner2d399092003-05-02 19:32:04 +0000122 if ((BO->getOpcode() != Instruction::Add &&
123 BO->getOpcode() != Instruction::Sub) ||
Chris Lattner3fb2ddd2002-07-16 21:41:31 +0000124 // Avoid add sbyte* %X, %X cases...
125 BO->getOperand(0) == BO->getOperand(1))
Chris Lattnera8b6d432001-12-05 06:34:00 +0000126 return false;
Chris Lattner2d399092003-05-02 19:32:04 +0000127 else
128 HasSubUse |= BO->getOpcode() == Instruction::Sub;
Chris Lattnera8b6d432001-12-05 06:34:00 +0000129 } else {
130 return false;
131 }
Chris Lattnera8b6d432001-12-05 06:34:00 +0000132
Chris Lattner697954c2002-01-20 22:54:45 +0000133 std::vector<Value*> Indices;
Chris Lattner7e708292002-06-25 16:13:24 +0000134 Value *Src = CI.getOperand(0);
Misha Brukmanf117cc92003-05-20 18:45:36 +0000135 const Type *Result = ConvertibleToGEP(DestPTy, Src, Indices, TD, &BI);
136 if (Result == 0) return false; // Not convertible...
Chris Lattnera8b6d432001-12-05 06:34:00 +0000137
Chris Lattner2d399092003-05-02 19:32:04 +0000138 // Cannot handle subtracts if there is more than one index required...
139 if (HasSubUse && Indices.size() != 1) return false;
140
Chris Lattnera8b6d432001-12-05 06:34:00 +0000141 PRINT_PEEPHOLE2("cast-add-to-gep:in", Src, CI);
142
143 // If we have a getelementptr capability... transform all of the
144 // add instruction uses into getelementptr's.
Chris Lattner7e708292002-06-25 16:13:24 +0000145 while (!CI.use_empty()) {
146 BinaryOperator *I = cast<BinaryOperator>(*CI.use_begin());
Chris Lattner2d399092003-05-02 19:32:04 +0000147 assert((I->getOpcode() == Instruction::Add ||
148 I->getOpcode() == Instruction::Sub) &&
Chris Lattnera8b6d432001-12-05 06:34:00 +0000149 "Use is not a valid add instruction!");
150
151 // Get the value added to the cast result pointer...
Chris Lattner7e708292002-06-25 16:13:24 +0000152 Value *OtherPtr = I->getOperand((I->getOperand(0) == &CI) ? 1 : 0);
Chris Lattnera8b6d432001-12-05 06:34:00 +0000153
Chris Lattner45ef5c22002-03-21 06:22:23 +0000154 Instruction *GEP = new GetElementPtrInst(OtherPtr, Indices, I->getName());
Chris Lattnera8b6d432001-12-05 06:34:00 +0000155 PRINT_PEEPHOLE1("cast-add-to-gep:i", I);
Chris Lattner45ef5c22002-03-21 06:22:23 +0000156
Chris Lattner2d399092003-05-02 19:32:04 +0000157 // If the instruction is actually a subtract, we are guaranteed to only have
158 // one index (from code above), so we just need to negate the pointer index
159 // long value.
160 if (I->getOpcode() == Instruction::Sub) {
161 Instruction *Neg = BinaryOperator::createNeg(GEP->getOperand(1),
162 GEP->getOperand(1)->getName()+".neg", I);
163 GEP->setOperand(1, Neg);
164 }
165
Chris Lattner45ef5c22002-03-21 06:22:23 +0000166 if (GEP->getType() == I->getType()) {
167 // Replace the old add instruction with the shiny new GEP inst
168 ReplaceInstWithInst(I, GEP);
169 } else {
170 // If the type produced by the gep instruction differs from the original
171 // add instruction type, insert a cast now.
172 //
173
Chris Lattner7e708292002-06-25 16:13:24 +0000174 // Insert the GEP instruction before the old add instruction...
175 I->getParent()->getInstList().insert(I, GEP);
Chris Lattner45ef5c22002-03-21 06:22:23 +0000176
177 PRINT_PEEPHOLE1("cast-add-to-gep:o", GEP);
Chris Lattner7e708292002-06-25 16:13:24 +0000178 GEP = new CastInst(GEP, I->getType());
Chris Lattner45ef5c22002-03-21 06:22:23 +0000179
180 // Replace the old add instruction with the shiny new GEP inst
Chris Lattner7e708292002-06-25 16:13:24 +0000181 ReplaceInstWithInst(I, GEP);
Chris Lattner45ef5c22002-03-21 06:22:23 +0000182 }
183
Chris Lattnera8b6d432001-12-05 06:34:00 +0000184 PRINT_PEEPHOLE1("cast-add-to-gep:o", GEP);
185 }
186 return true;
187}
Chris Lattnerd5b48ca2001-11-14 11:02:49 +0000188
189// Peephole optimize the following instructions:
190// %t1 = cast ulong <const int> to {<...>} *
191// %t2 = add {<...>} * %SP, %t1 ;; Constant must be 2nd operand
192//
193// or
194// %t1 = cast {<...>}* %SP to int*
195// %t5 = cast ulong <const int> to int*
196// %t2 = add int* %t1, %t5 ;; int is same size as field
197//
198// Into: %t3 = getelementptr {<...>} * %SP, <element indices>
199// %t2 = cast <eltype> * %t3 to {<...>}*
200//
201static bool PeepholeOptimizeAddCast(BasicBlock *BB, BasicBlock::iterator &BI,
Chris Lattner16125fb2003-04-24 18:25:27 +0000202 Value *AddOp1, CastInst *AddOp2,
203 const TargetData &TD) {
Chris Lattner3cc7dde2001-11-26 16:58:14 +0000204 const CompositeType *CompTy;
205 Value *OffsetVal = AddOp2->getOperand(0);
Chris Lattner0ceeb422002-10-22 23:34:11 +0000206 Value *SrcPtr = 0; // Of type pointer to struct...
Chris Lattnerd5b48ca2001-11-14 11:02:49 +0000207
Chris Lattner3cc7dde2001-11-26 16:58:14 +0000208 if ((CompTy = getPointedToComposite(AddOp1->getType()))) {
Chris Lattnerd5b48ca2001-11-14 11:02:49 +0000209 SrcPtr = AddOp1; // Handle the first case...
210 } else if (CastInst *AddOp1c = dyn_cast<CastInst>(AddOp1)) {
211 SrcPtr = AddOp1c->getOperand(0); // Handle the second case...
Chris Lattner3cc7dde2001-11-26 16:58:14 +0000212 CompTy = getPointedToComposite(SrcPtr->getType());
Chris Lattnerd5b48ca2001-11-14 11:02:49 +0000213 }
214
215 // Only proceed if we have detected all of our conditions successfully...
Chris Lattner0c4e8862002-09-03 01:08:28 +0000216 if (!CompTy || !SrcPtr || !OffsetVal->getType()->isInteger())
Chris Lattnerd5b48ca2001-11-14 11:02:49 +0000217 return false;
218
Chris Lattner697954c2002-01-20 22:54:45 +0000219 std::vector<Value*> Indices;
Misha Brukmanf117cc92003-05-20 18:45:36 +0000220 if (!ConvertibleToGEP(SrcPtr->getType(), OffsetVal, Indices, TD, &BI))
221 return false; // Not convertible... perhaps next time
Chris Lattnerd5b48ca2001-11-14 11:02:49 +0000222
Chris Lattner3cc7dde2001-11-26 16:58:14 +0000223 if (getPointedToComposite(AddOp1->getType())) { // case 1
Chris Lattnerd5b48ca2001-11-14 11:02:49 +0000224 PRINT_PEEPHOLE2("add-to-gep1:in", AddOp2, *BI);
225 } else {
226 PRINT_PEEPHOLE3("add-to-gep2:in", AddOp1, AddOp2, *BI);
227 }
228
Chris Lattner3cc7dde2001-11-26 16:58:14 +0000229 GetElementPtrInst *GEP = new GetElementPtrInst(SrcPtr, Indices,
Chris Lattner2a7c23e2002-09-10 17:04:02 +0000230 AddOp2->getName(), BI);
Chris Lattnerd5b48ca2001-11-14 11:02:49 +0000231
Chris Lattner3cc7dde2001-11-26 16:58:14 +0000232 Instruction *NCI = new CastInst(GEP, AddOp1->getType());
Chris Lattnerd5b48ca2001-11-14 11:02:49 +0000233 ReplaceInstWithInst(BB->getInstList(), BI, NCI);
234 PRINT_PEEPHOLE2("add-to-gep:out", GEP, NCI);
235 return true;
236}
237
Chris Lattner16125fb2003-04-24 18:25:27 +0000238bool RPR::PeepholeOptimize(BasicBlock *BB, BasicBlock::iterator &BI) {
Chris Lattner7e708292002-06-25 16:13:24 +0000239 Instruction *I = BI;
Chris Lattner16125fb2003-04-24 18:25:27 +0000240 const TargetData &TD = getAnalysis<TargetData>();
Chris Lattnerd32a9612001-11-01 02:42:08 +0000241
242 if (CastInst *CI = dyn_cast<CastInst>(I)) {
243 Value *Src = CI->getOperand(0);
244 Instruction *SrcI = dyn_cast<Instruction>(Src); // Nonnull if instr source
245 const Type *DestTy = CI->getType();
246
Chris Lattnere99c66b2001-11-01 17:05:27 +0000247 // Peephole optimize the following instruction:
248 // %V2 = cast <ty> %V to <ty>
249 //
250 // Into: <nothing>
251 //
252 if (DestTy == Src->getType()) { // Check for a cast to same type as src!!
Chris Lattnerd32a9612001-11-01 02:42:08 +0000253 PRINT_PEEPHOLE1("cast-of-self-ty", CI);
254 CI->replaceAllUsesWith(Src);
255 if (!Src->hasName() && CI->hasName()) {
Chris Lattner697954c2002-01-20 22:54:45 +0000256 std::string Name = CI->getName();
Chris Lattnerf3b976e2001-11-04 20:21:12 +0000257 CI->setName("");
Chris Lattner6e6026b2002-11-20 18:36:02 +0000258 Src->setName(Name, &BB->getParent()->getSymbolTable());
Chris Lattnerd32a9612001-11-01 02:42:08 +0000259 }
Chris Lattner3c019372002-05-10 15:29:25 +0000260
261 // DCE the instruction now, to avoid having the iterative version of DCE
262 // have to worry about it.
263 //
Chris Lattner7e708292002-06-25 16:13:24 +0000264 BI = BB->getInstList().erase(BI);
Chris Lattner3c019372002-05-10 15:29:25 +0000265
266 ++NumCastOfCast;
Chris Lattnerd32a9612001-11-01 02:42:08 +0000267 return true;
268 }
269
Chris Lattnerd32a9612001-11-01 02:42:08 +0000270 // Check to see if it's a cast of an instruction that does not depend on the
271 // specific type of the operands to do it's job.
Chris Lattnerf3b976e2001-11-04 20:21:12 +0000272 if (!isReinterpretingCast(CI)) {
Chris Lattnerb980e182001-11-04 21:32:11 +0000273 ValueTypeCache ConvertedTypes;
Chris Lattnera8b6d432001-12-05 06:34:00 +0000274
Chris Lattnerd20a98e2002-05-24 20:41:51 +0000275 // Check to see if we can convert the source of the cast to match the
276 // destination type of the cast...
Chris Lattnera8b6d432001-12-05 06:34:00 +0000277 //
Chris Lattnerd5543802001-12-14 16:37:52 +0000278 ConvertedTypes[CI] = CI->getType(); // Make sure the cast doesn't change
Misha Brukmanf117cc92003-05-20 18:45:36 +0000279 if (ExpressionConvertibleToType(Src, DestTy, ConvertedTypes, TD)) {
Chris Lattnerd5543802001-12-14 16:37:52 +0000280 PRINT_PEEPHOLE3("CAST-SRC-EXPR-CONV:in ", Src, CI, BB->getParent());
Chris Lattnerc0b90e72001-11-08 20:19:56 +0000281
Chris Lattner6806f562003-08-01 22:15:03 +0000282 DEBUG(std::cerr << "\nCONVERTING SRC EXPR TYPE:\n");
Chris Lattnerb1b42622002-07-17 17:11:33 +0000283 { // ValueMap must be destroyed before function verified!
284 ValueMapCache ValueMap;
Chris Lattner16125fb2003-04-24 18:25:27 +0000285 Value *E = ConvertExpressionToType(Src, DestTy, ValueMap, TD);
Chris Lattnerc0b90e72001-11-08 20:19:56 +0000286
Chris Lattnerb1b42622002-07-17 17:11:33 +0000287 if (Constant *CPV = dyn_cast<Constant>(E))
288 CI->replaceAllUsesWith(CPV);
289
290 PRINT_PEEPHOLE1("CAST-SRC-EXPR-CONV:out", E);
Chris Lattner6806f562003-08-01 22:15:03 +0000291 DEBUG(std::cerr << "DONE CONVERTING SRC EXPR TYPE: \n"
292 << BB->getParent());
Chris Lattnerb1b42622002-07-17 17:11:33 +0000293 }
Chris Lattner3378a5b2002-07-16 23:49:24 +0000294
Chris Lattnerb1b42622002-07-17 17:11:33 +0000295 BI = BB->begin(); // Rescan basic block. BI might be invalidated.
Chris Lattner3c019372002-05-10 15:29:25 +0000296 ++NumExprTreesConv;
Chris Lattnerd5543802001-12-14 16:37:52 +0000297 return true;
298 }
299
Chris Lattnerd20a98e2002-05-24 20:41:51 +0000300 // Check to see if we can convert the users of the cast value to match the
301 // source type of the cast...
Chris Lattnerd5543802001-12-14 16:37:52 +0000302 //
303 ConvertedTypes.clear();
Chris Lattner61b92c02002-10-08 22:19:25 +0000304 // Make sure the source doesn't change type
305 ConvertedTypes[Src] = Src->getType();
Misha Brukmanf117cc92003-05-20 18:45:36 +0000306 if (ValueConvertibleToType(CI, Src->getType(), ConvertedTypes, TD)) {
Chris Lattnerd5543802001-12-14 16:37:52 +0000307 PRINT_PEEPHOLE3("CAST-DEST-EXPR-CONV:in ", Src, CI, BB->getParent());
308
Chris Lattner6806f562003-08-01 22:15:03 +0000309 DEBUG(std::cerr << "\nCONVERTING EXPR TYPE:\n");
Chris Lattnerb1b42622002-07-17 17:11:33 +0000310 { // ValueMap must be destroyed before function verified!
311 ValueMapCache ValueMap;
Chris Lattner16125fb2003-04-24 18:25:27 +0000312 ConvertValueToNewType(CI, Src, ValueMap, TD); // This will delete CI!
Chris Lattnerb1b42622002-07-17 17:11:33 +0000313 }
Chris Lattnerd5543802001-12-14 16:37:52 +0000314
Chris Lattnerd5543802001-12-14 16:37:52 +0000315 PRINT_PEEPHOLE1("CAST-DEST-EXPR-CONV:out", Src);
Chris Lattner6806f562003-08-01 22:15:03 +0000316 DEBUG(std::cerr << "DONE CONVERTING EXPR TYPE: \n\n" << 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 Lattner106ff452002-09-11 01:21:29 +0000373 Indices.push_back(ConstantSInt::get(Type::LongTy, 0));
Chris Lattnerd5543802001-12-14 16:37:52 +0000374 while (CurCTy && !isa<PointerType>(CurCTy)) {
Chris Lattner3cc7dde2001-11-26 16:58:14 +0000375 if (const StructType *CurSTy = dyn_cast<StructType>(CurCTy)) {
376 // Check for a zero element struct type... if we have one, bail.
377 if (CurSTy->getElementTypes().size() == 0) break;
Chris Lattnere99c66b2001-11-01 17:05:27 +0000378
Chris Lattner3cc7dde2001-11-26 16:58:14 +0000379 // Grab the first element of the struct type, which must lie at
380 // offset zero in the struct.
381 //
382 ElTy = CurSTy->getElementTypes()[0];
383 } else {
384 ElTy = cast<ArrayType>(CurCTy)->getElementType();
385 }
386
387 // Insert a zero to index through this type...
Chris Lattner106ff452002-09-11 01:21:29 +0000388 Indices.push_back(Constant::getNullValue(CurCTy->getIndexType()));
Chris Lattnere99c66b2001-11-01 17:05:27 +0000389
390 // Did we find what we're looking for?
Misha Brukmanf117cc92003-05-20 18:45:36 +0000391 if (ElTy->isLosslesslyConvertibleTo(DestPointedTy)) break;
Chris Lattnere99c66b2001-11-01 17:05:27 +0000392
393 // Nope, go a level deeper.
394 ++Depth;
Chris Lattner3cc7dde2001-11-26 16:58:14 +0000395 CurCTy = dyn_cast<CompositeType>(ElTy);
Chris Lattnere99c66b2001-11-01 17:05:27 +0000396 ElTy = 0;
397 }
398
399 // Did we find what we were looking for? If so, do the transformation
400 if (ElTy) {
401 PRINT_PEEPHOLE1("cast-for-first:in", CI);
402
Chris Lattner2a7c23e2002-09-10 17:04:02 +0000403 std::string Name = CI->getName(); CI->setName("");
404
Chris Lattnere99c66b2001-11-01 17:05:27 +0000405 // Insert the new T cast instruction... stealing old T's name
406 GetElementPtrInst *GEP = new GetElementPtrInst(Src, Indices,
Chris Lattner2a7c23e2002-09-10 17:04:02 +0000407 Name, BI);
Chris Lattnere99c66b2001-11-01 17:05:27 +0000408
409 // Make the old cast instruction reference the new GEP instead of
410 // the old src value.
411 //
412 CI->setOperand(0, GEP);
413
414 PRINT_PEEPHOLE2("cast-for-first:out", GEP, CI);
Chris Lattner3c019372002-05-10 15:29:25 +0000415 ++NumGEPInstFormed;
Chris Lattnere99c66b2001-11-01 17:05:27 +0000416 return true;
417 }
418 }
419 }
Chris Lattnere99c66b2001-11-01 17:05:27 +0000420
Chris Lattner8d38e542001-11-01 03:12:34 +0000421 } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
422 Value *Val = SI->getOperand(0);
Chris Lattner65ea1712001-11-14 11:27:58 +0000423 Value *Pointer = SI->getPointerOperand();
Chris Lattner8d38e542001-11-01 03:12:34 +0000424
Chris Lattnerdedee7b2001-11-01 05:57:59 +0000425 // Peephole optimize the following instructions:
Misha Brukmanf117cc92003-05-20 18:45:36 +0000426 // %t = cast <T1>* %P to <T2> * ;; If T1 is losslessly convertible to T2
Chris Lattnerdedee7b2001-11-01 05:57:59 +0000427 // store <T2> %V, <T2>* %t
428 //
429 // Into:
430 // %t = cast <T2> %V to <T1>
431 // store <T1> %t2, <T1>* %P
432 //
Chris Lattnerd5543802001-12-14 16:37:52 +0000433 // Note: This is not taken care of by expr conversion because there might
434 // not be a cast available for the store to convert the incoming value of.
435 // This code is basically here to make sure that pointers don't have casts
436 // if possible.
437 //
Chris Lattnerdedee7b2001-11-01 05:57:59 +0000438 if (CastInst *CI = dyn_cast<CastInst>(Pointer))
439 if (Value *CastSrc = CI->getOperand(0)) // CSPT = CastSrcPointerType
Chris Lattner7e708292002-06-25 16:13:24 +0000440 if (const PointerType *CSPT = dyn_cast<PointerType>(CastSrc->getType()))
Misha Brukmanf117cc92003-05-20 18:45:36 +0000441 // convertible types?
442 if (Val->getType()->isLosslesslyConvertibleTo(CSPT->getElementType())) {
Chris Lattnerdedee7b2001-11-01 05:57:59 +0000443 PRINT_PEEPHOLE3("st-src-cast:in ", Pointer, Val, SI);
444
445 // Insert the new T cast instruction... stealing old T's name
Chris Lattner2a7c23e2002-09-10 17:04:02 +0000446 std::string Name(CI->getName()); CI->setName("");
Chris Lattner7a176752001-12-04 00:03:30 +0000447 CastInst *NCI = new CastInst(Val, CSPT->getElementType(),
Chris Lattner2a7c23e2002-09-10 17:04:02 +0000448 Name, BI);
Chris Lattnerdedee7b2001-11-01 05:57:59 +0000449
450 // Replace the old store with a new one!
451 ReplaceInstWithInst(BB->getInstList(), BI,
452 SI = new StoreInst(NCI, CastSrc));
453 PRINT_PEEPHOLE3("st-src-cast:out", NCI, CastSrc, SI);
Chris Lattner3c019372002-05-10 15:29:25 +0000454 ++NumLoadStorePeepholes;
Chris Lattnerdedee7b2001-11-01 05:57:59 +0000455 return true;
456 }
457
Chris Lattnerc99428f2002-05-14 05:23:45 +0000458 } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
459 Value *Pointer = LI->getOperand(0);
460 const Type *PtrElType =
461 cast<PointerType>(Pointer->getType())->getElementType();
462
463 // Peephole optimize the following instructions:
Misha Brukmanf117cc92003-05-20 18:45:36 +0000464 // %Val = cast <T1>* to <T2>* ;; If T1 is losslessly convertible to T2
Chris Lattnerc99428f2002-05-14 05:23:45 +0000465 // %t = load <T2>* %P
466 //
467 // Into:
468 // %t = load <T1>* %P
469 // %Val = cast <T1> to <T2>
470 //
471 // Note: This is not taken care of by expr conversion because there might
472 // not be a cast available for the store to convert the incoming value of.
473 // This code is basically here to make sure that pointers don't have casts
474 // if possible.
475 //
476 if (CastInst *CI = dyn_cast<CastInst>(Pointer))
477 if (Value *CastSrc = CI->getOperand(0)) // CSPT = CastSrcPointerType
Chris Lattner7e708292002-06-25 16:13:24 +0000478 if (const PointerType *CSPT = dyn_cast<PointerType>(CastSrc->getType()))
Misha Brukmanf117cc92003-05-20 18:45:36 +0000479 // convertible types?
480 if (PtrElType->isLosslesslyConvertibleTo(CSPT->getElementType())) {
Chris Lattnerc99428f2002-05-14 05:23:45 +0000481 PRINT_PEEPHOLE2("load-src-cast:in ", Pointer, LI);
482
483 // Create the new load instruction... loading the pre-casted value
Chris Lattner2a7c23e2002-09-10 17:04:02 +0000484 LoadInst *NewLI = new LoadInst(CastSrc, LI->getName(), BI);
Chris Lattnerc99428f2002-05-14 05:23:45 +0000485
486 // Insert the new T cast instruction... stealing old T's name
487 CastInst *NCI = new CastInst(NewLI, LI->getType(), CI->getName());
Chris Lattnerc99428f2002-05-14 05:23:45 +0000488
489 // Replace the old store with a new one!
490 ReplaceInstWithInst(BB->getInstList(), BI, NCI);
491 PRINT_PEEPHOLE3("load-src-cast:out", NCI, CastSrc, NewLI);
492 ++NumLoadStorePeepholes;
493 return true;
494 }
495
Chris Lattnerd32a9612001-11-01 02:42:08 +0000496 } else if (I->getOpcode() == Instruction::Add &&
497 isa<CastInst>(I->getOperand(1))) {
498
Chris Lattnerd5b48ca2001-11-14 11:02:49 +0000499 if (PeepholeOptimizeAddCast(BB, BI, I->getOperand(0),
Chris Lattner16125fb2003-04-24 18:25:27 +0000500 cast<CastInst>(I->getOperand(1)), TD)) {
Chris Lattner3c019372002-05-10 15:29:25 +0000501 ++NumGEPInstFormed;
Chris Lattnerd32a9612001-11-01 02:42:08 +0000502 return true;
Chris Lattner3c019372002-05-10 15:29:25 +0000503 }
Chris Lattner61b92c02002-10-08 22:19:25 +0000504 } else if (CallInst *CI = dyn_cast<CallInst>(I)) {
505 // If we have a call with all varargs arguments, convert the call to use the
506 // actual argument types present...
507 //
508 const PointerType *PTy = cast<PointerType>(CI->getCalledValue()->getType());
509 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
510
511 // Is the call to a vararg variable with no real parameters?
Chris Lattnercdeb81d2003-05-01 21:02:53 +0000512 if (FTy->isVarArg() && FTy->getNumParams() == 0 &&
513 !CI->getCalledFunction()) {
Chris Lattner61b92c02002-10-08 22:19:25 +0000514 // If so, insert a new cast instruction, casting it to a function type
515 // that matches the current arguments...
516 //
517 std::vector<const Type *> Params; // Parameter types...
518 for (unsigned i = 1, e = CI->getNumOperands(); i != e; ++i)
519 Params.push_back(CI->getOperand(i)->getType());
520
521 FunctionType *NewFT = FunctionType::get(FTy->getReturnType(),
522 Params, false);
523 PointerType *NewPFunTy = PointerType::get(NewFT);
524
525 // Create a new cast, inserting it right before the function call...
Chris Lattner95549282003-04-28 01:25:38 +0000526 Value *NewCast;
527 Constant *ConstantCallSrc = 0;
528 if (Constant *CS = dyn_cast<Constant>(CI->getCalledValue()))
529 ConstantCallSrc = CS;
530 else if (GlobalValue *GV = dyn_cast<GlobalValue>(CI->getCalledValue()))
531 ConstantCallSrc = ConstantPointerRef::get(GV);
532
533 if (ConstantCallSrc)
534 NewCast = ConstantExpr::getCast(ConstantCallSrc, NewPFunTy);
535 else
536 NewCast = new CastInst(CI->getCalledValue(), NewPFunTy,
537 CI->getCalledValue()->getName()+"_c",CI);
Chris Lattner61b92c02002-10-08 22:19:25 +0000538
539 // Create a new call instruction...
540 CallInst *NewCall = new CallInst(NewCast,
541 std::vector<Value*>(CI->op_begin()+1, CI->op_end()));
542 ++BI;
543 ReplaceInstWithInst(CI, NewCall);
544
545 ++NumVarargCallChanges;
546 return true;
547 }
548
Chris Lattnerd32a9612001-11-01 02:42:08 +0000549 }
550
551 return false;
552}
553
554
555
556
Chris Lattner16125fb2003-04-24 18:25:27 +0000557bool RPR::DoRaisePass(Function &F) {
Chris Lattnerd32a9612001-11-01 02:42:08 +0000558 bool Changed = false;
Chris Lattner7e708292002-06-25 16:13:24 +0000559 for (Function::iterator BB = F.begin(), BBE = F.end(); BB != BBE; ++BB)
Chris Lattnerd32a9612001-11-01 02:42:08 +0000560 for (BasicBlock::iterator BI = BB->begin(); BI != BB->end();) {
Chris Lattner6806f562003-08-01 22:15:03 +0000561 DEBUG(std::cerr << "Processing: " << *BI);
Misha Brukman82c89b92003-05-20 21:01:22 +0000562 if (dceInstruction(BI) || doConstantPropagation(BI)) {
Chris Lattnerc0b90e72001-11-08 20:19:56 +0000563 Changed = true;
Chris Lattner3c019372002-05-10 15:29:25 +0000564 ++NumDCEorCP;
Chris Lattner6806f562003-08-01 22:15:03 +0000565 DEBUG(std::cerr << "***\t\t^^-- Dead code eliminated!\n");
Chris Lattner7e708292002-06-25 16:13:24 +0000566 } else if (PeepholeOptimize(BB, BI)) {
Chris Lattnerd32a9612001-11-01 02:42:08 +0000567 Changed = true;
Chris Lattner7e708292002-06-25 16:13:24 +0000568 } else {
Chris Lattnerd32a9612001-11-01 02:42:08 +0000569 ++BI;
Chris Lattner7e708292002-06-25 16:13:24 +0000570 }
Chris Lattnerd32a9612001-11-01 02:42:08 +0000571 }
Chris Lattner7e708292002-06-25 16:13:24 +0000572
Chris Lattnerd32a9612001-11-01 02:42:08 +0000573 return Changed;
574}
575
576
Chris Lattner16125fb2003-04-24 18:25:27 +0000577// runOnFunction - Raise a function representation to a higher level.
578bool RPR::runOnFunction(Function &F) {
Chris Lattner6806f562003-08-01 22:15:03 +0000579 DEBUG(std::cerr << "\n\n\nStarting to work on Function '" << F.getName()
580 << "'\n");
Chris Lattner68b07b72001-11-01 07:00:51 +0000581
Chris Lattner3cc7dde2001-11-26 16:58:14 +0000582 // Insert casts for all incoming pointer pointer values that are treated as
583 // arrays...
Chris Lattnerd32a9612001-11-01 02:42:08 +0000584 //
Chris Lattner3cc7dde2001-11-26 16:58:14 +0000585 bool Changed = false, LocalChange;
Chris Lattner3378a5b2002-07-16 23:49:24 +0000586
587 // If the StartInst option was specified, then Peephole optimize that
588 // instruction first if it occurs in this function.
589 //
590 if (!StartInst.empty()) {
591 for (Function::iterator BB = F.begin(), BBE = F.end(); BB != BBE; ++BB)
592 for (BasicBlock::iterator BI = BB->begin(); BI != BB->end(); ++BI)
593 if (BI->getName() == StartInst) {
594 bool SavedDebug = DebugFlag; // Save the DEBUG() controlling flag.
595 DebugFlag = true; // Turn on DEBUG's
596 Changed |= PeepholeOptimize(BB, BI);
597 DebugFlag = SavedDebug; // Restore DebugFlag to previous state
598 }
599 }
600
Chris Lattner4b770a32001-12-04 08:12:53 +0000601 do {
Chris Lattner6806f562003-08-01 22:15:03 +0000602 DEBUG(std::cerr << "Looping: \n" << F);
Chris Lattnera8b6d432001-12-05 06:34:00 +0000603
Chris Lattnerf57b8452002-04-27 06:56:12 +0000604 // Iterate over the function, refining it, until it converges on a stable
Chris Lattner3cc7dde2001-11-26 16:58:14 +0000605 // state
Chris Lattnerd5543802001-12-14 16:37:52 +0000606 LocalChange = false;
Chris Lattner2fbfdcf2002-04-07 20:49:59 +0000607 while (DoRaisePass(F)) LocalChange = true;
Chris Lattner3cc7dde2001-11-26 16:58:14 +0000608 Changed |= LocalChange;
609
610 } while (LocalChange);
Chris Lattnerd32a9612001-11-01 02:42:08 +0000611
612 return Changed;
613}
Brian Gaeked0fde302003-11-11 22:41:34 +0000614