blob: cf64aea1cdd70ded5a4c6d0f0ae14b5ec554e72d [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 Lattner3378a5b2002-07-16 23:49:24 +000024#include "llvm/Analysis/Verifier.h"
Chris Lattner497c60c2002-05-07 18:12:18 +000025#include "llvm/Transforms/Utils/BasicBlockUtils.h"
Chris Lattner3378a5b2002-07-16 23:49:24 +000026#include "Support/CommandLine.h"
Chris Lattner6806f562003-08-01 22:15:03 +000027#include "Support/Debug.h"
28#include "Support/Statistic.h"
29#include "Support/STLExtras.h"
Chris Lattnerd32a9612001-11-01 02:42:08 +000030#include <algorithm>
31
Chris Lattner3378a5b2002-07-16 23:49:24 +000032// StartInst - This enables the -raise-start-inst=foo option to cause the level
33// raising pass to start at instruction "foo", which is immensely useful for
34// debugging!
35//
Chris Lattner5ff62e92002-07-22 02:10:13 +000036static cl::opt<std::string>
37StartInst("raise-start-inst", cl::Hidden, cl::value_desc("inst name"),
38 cl::desc("Start raise pass at the instruction with the specified name"));
Chris Lattner3378a5b2002-07-16 23:49:24 +000039
Chris Lattner5ff62e92002-07-22 02:10:13 +000040static Statistic<>
Chris Lattner6ee6bbe2002-10-01 22:38:37 +000041NumLoadStorePeepholes("raise", "Number of load/store peepholes");
Chris Lattner5ff62e92002-07-22 02:10:13 +000042
43static Statistic<>
Chris Lattner6ee6bbe2002-10-01 22:38:37 +000044NumGEPInstFormed("raise", "Number of other getelementptr's formed");
Chris Lattner5ff62e92002-07-22 02:10:13 +000045
46static Statistic<>
Chris Lattner6ee6bbe2002-10-01 22:38:37 +000047NumExprTreesConv("raise", "Number of expression trees converted");
Chris Lattner5ff62e92002-07-22 02:10:13 +000048
49static Statistic<>
Chris Lattner6ee6bbe2002-10-01 22:38:37 +000050NumCastOfCast("raise", "Number of cast-of-self removed");
Chris Lattner5ff62e92002-07-22 02:10:13 +000051
52static Statistic<>
Chris Lattner6ee6bbe2002-10-01 22:38:37 +000053NumDCEorCP("raise", "Number of insts DCEd or constprop'd");
Chris Lattner3c019372002-05-10 15:29:25 +000054
Chris Lattner61b92c02002-10-08 22:19:25 +000055static Statistic<>
56NumVarargCallChanges("raise", "Number of vararg call peepholes");
57
Chris Lattner3c019372002-05-10 15:29:25 +000058
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
89Pass *createRaisePointerReferencesPass() {
90 return new RPR();
91}
92
93
Chris Lattnerd32a9612001-11-01 02:42:08 +000094
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
297 DEBUG(assert(verifyFunction(*BB->getParent()) == false &&
298 "Function broken!"));
Chris Lattnerb1b42622002-07-17 17:11:33 +0000299 BI = BB->begin(); // Rescan basic block. BI might be invalidated.
Chris Lattner3c019372002-05-10 15:29:25 +0000300 ++NumExprTreesConv;
Chris Lattnerd5543802001-12-14 16:37:52 +0000301 return true;
302 }
303
Chris Lattnerd20a98e2002-05-24 20:41:51 +0000304 // Check to see if we can convert the users of the cast value to match the
305 // source type of the cast...
Chris Lattnerd5543802001-12-14 16:37:52 +0000306 //
307 ConvertedTypes.clear();
Chris Lattner61b92c02002-10-08 22:19:25 +0000308 // Make sure the source doesn't change type
309 ConvertedTypes[Src] = Src->getType();
Misha Brukmanf117cc92003-05-20 18:45:36 +0000310 if (ValueConvertibleToType(CI, Src->getType(), ConvertedTypes, TD)) {
Chris Lattnerd5543802001-12-14 16:37:52 +0000311 PRINT_PEEPHOLE3("CAST-DEST-EXPR-CONV:in ", Src, CI, BB->getParent());
312
Chris Lattner6806f562003-08-01 22:15:03 +0000313 DEBUG(std::cerr << "\nCONVERTING EXPR TYPE:\n");
Chris Lattnerb1b42622002-07-17 17:11:33 +0000314 { // ValueMap must be destroyed before function verified!
315 ValueMapCache ValueMap;
Chris Lattner16125fb2003-04-24 18:25:27 +0000316 ConvertValueToNewType(CI, Src, ValueMap, TD); // This will delete CI!
Chris Lattnerb1b42622002-07-17 17:11:33 +0000317 }
Chris Lattnerd5543802001-12-14 16:37:52 +0000318
Chris Lattnerd5543802001-12-14 16:37:52 +0000319 PRINT_PEEPHOLE1("CAST-DEST-EXPR-CONV:out", Src);
Chris Lattner6806f562003-08-01 22:15:03 +0000320 DEBUG(std::cerr << "DONE CONVERTING EXPR TYPE: \n\n" << BB->getParent());
Chris Lattner3378a5b2002-07-16 23:49:24 +0000321
322 DEBUG(assert(verifyFunction(*BB->getParent()) == false &&
323 "Function broken!"));
Chris Lattnerb1b42622002-07-17 17:11:33 +0000324 BI = BB->begin(); // Rescan basic block. BI might be invalidated.
Chris Lattner3c019372002-05-10 15:29:25 +0000325 ++NumExprTreesConv;
Chris Lattnera8b6d432001-12-05 06:34:00 +0000326 return true;
Chris Lattnerf3b976e2001-11-04 20:21:12 +0000327 }
Chris Lattnerf17a09d2001-12-06 18:06:13 +0000328 }
329
330 // Otherwise find out it this cast is a cast to a pointer type, which is
331 // then added to some other pointer, then loaded or stored through. If
332 // so, convert the add into a getelementptr instruction...
333 //
334 if (const PointerType *DestPTy = dyn_cast<PointerType>(DestTy)) {
Chris Lattner16125fb2003-04-24 18:25:27 +0000335 if (HandleCastToPointer(BI, DestPTy, TD)) {
Chris Lattnerf17a09d2001-12-06 18:06:13 +0000336 BI = BB->begin(); // Rescan basic block. BI might be invalidated.
Chris Lattner3c019372002-05-10 15:29:25 +0000337 ++NumGEPInstFormed;
Chris Lattnerf17a09d2001-12-06 18:06:13 +0000338 return true;
Chris Lattnera8b6d432001-12-05 06:34:00 +0000339 }
Chris Lattnerd32a9612001-11-01 02:42:08 +0000340 }
341
Chris Lattnere99c66b2001-11-01 17:05:27 +0000342 // Check to see if we are casting from a structure pointer to a pointer to
343 // the first element of the structure... to avoid munching other peepholes,
344 // we only let this happen if there are no add uses of the cast.
345 //
346 // Peephole optimize the following instructions:
347 // %t1 = cast {<...>} * %StructPtr to <ty> *
348 //
349 // Into: %t2 = getelementptr {<...>} * %StructPtr, <0, 0, 0, ...>
350 // %t1 = cast <eltype> * %t1 to <ty> *
351 //
Chris Lattner3cc7dde2001-11-26 16:58:14 +0000352 if (const CompositeType *CTy = getPointedToComposite(Src->getType()))
Chris Lattnere99c66b2001-11-01 17:05:27 +0000353 if (const PointerType *DestPTy = dyn_cast<PointerType>(DestTy)) {
354
355 // Loop over uses of the cast, checking for add instructions. If an add
356 // exists, this is probably a part of a more complex GEP, so we don't
357 // want to mess around with the cast.
358 //
359 bool HasAddUse = false;
360 for (Value::use_iterator I = CI->use_begin(), E = CI->use_end();
361 I != E; ++I)
362 if (isa<Instruction>(*I) &&
363 cast<Instruction>(*I)->getOpcode() == Instruction::Add) {
364 HasAddUse = true; break;
365 }
366
367 // If it doesn't have an add use, check to see if the dest type is
Misha Brukmanf117cc92003-05-20 18:45:36 +0000368 // losslessly convertible to one of the types in the start of the struct
Chris Lattnere99c66b2001-11-01 17:05:27 +0000369 // type.
370 //
371 if (!HasAddUse) {
Chris Lattner7a176752001-12-04 00:03:30 +0000372 const Type *DestPointedTy = DestPTy->getElementType();
Chris Lattnere99c66b2001-11-01 17:05:27 +0000373 unsigned Depth = 1;
Chris Lattner3cc7dde2001-11-26 16:58:14 +0000374 const CompositeType *CurCTy = CTy;
Chris Lattnere99c66b2001-11-01 17:05:27 +0000375 const Type *ElTy = 0;
Chris Lattner3cc7dde2001-11-26 16:58:14 +0000376
377 // Build the index vector, full of all zeros
Chris Lattner697954c2002-01-20 22:54:45 +0000378 std::vector<Value*> Indices;
Chris Lattner106ff452002-09-11 01:21:29 +0000379 Indices.push_back(ConstantSInt::get(Type::LongTy, 0));
Chris Lattnerd5543802001-12-14 16:37:52 +0000380 while (CurCTy && !isa<PointerType>(CurCTy)) {
Chris Lattner3cc7dde2001-11-26 16:58:14 +0000381 if (const StructType *CurSTy = dyn_cast<StructType>(CurCTy)) {
382 // Check for a zero element struct type... if we have one, bail.
383 if (CurSTy->getElementTypes().size() == 0) break;
Chris Lattnere99c66b2001-11-01 17:05:27 +0000384
Chris Lattner3cc7dde2001-11-26 16:58:14 +0000385 // Grab the first element of the struct type, which must lie at
386 // offset zero in the struct.
387 //
388 ElTy = CurSTy->getElementTypes()[0];
389 } else {
390 ElTy = cast<ArrayType>(CurCTy)->getElementType();
391 }
392
393 // Insert a zero to index through this type...
Chris Lattner106ff452002-09-11 01:21:29 +0000394 Indices.push_back(Constant::getNullValue(CurCTy->getIndexType()));
Chris Lattnere99c66b2001-11-01 17:05:27 +0000395
396 // Did we find what we're looking for?
Misha Brukmanf117cc92003-05-20 18:45:36 +0000397 if (ElTy->isLosslesslyConvertibleTo(DestPointedTy)) break;
Chris Lattnere99c66b2001-11-01 17:05:27 +0000398
399 // Nope, go a level deeper.
400 ++Depth;
Chris Lattner3cc7dde2001-11-26 16:58:14 +0000401 CurCTy = dyn_cast<CompositeType>(ElTy);
Chris Lattnere99c66b2001-11-01 17:05:27 +0000402 ElTy = 0;
403 }
404
405 // Did we find what we were looking for? If so, do the transformation
406 if (ElTy) {
407 PRINT_PEEPHOLE1("cast-for-first:in", CI);
408
Chris Lattner2a7c23e2002-09-10 17:04:02 +0000409 std::string Name = CI->getName(); CI->setName("");
410
Chris Lattnere99c66b2001-11-01 17:05:27 +0000411 // Insert the new T cast instruction... stealing old T's name
412 GetElementPtrInst *GEP = new GetElementPtrInst(Src, Indices,
Chris Lattner2a7c23e2002-09-10 17:04:02 +0000413 Name, BI);
Chris Lattnere99c66b2001-11-01 17:05:27 +0000414
415 // Make the old cast instruction reference the new GEP instead of
416 // the old src value.
417 //
418 CI->setOperand(0, GEP);
419
420 PRINT_PEEPHOLE2("cast-for-first:out", GEP, CI);
Chris Lattner3c019372002-05-10 15:29:25 +0000421 ++NumGEPInstFormed;
Chris Lattnere99c66b2001-11-01 17:05:27 +0000422 return true;
423 }
424 }
425 }
Chris Lattnere99c66b2001-11-01 17:05:27 +0000426
Chris Lattner8d38e542001-11-01 03:12:34 +0000427 } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
428 Value *Val = SI->getOperand(0);
Chris Lattner65ea1712001-11-14 11:27:58 +0000429 Value *Pointer = SI->getPointerOperand();
Chris Lattner8d38e542001-11-01 03:12:34 +0000430
Chris Lattnerdedee7b2001-11-01 05:57:59 +0000431 // Peephole optimize the following instructions:
Misha Brukmanf117cc92003-05-20 18:45:36 +0000432 // %t = cast <T1>* %P to <T2> * ;; If T1 is losslessly convertible to T2
Chris Lattnerdedee7b2001-11-01 05:57:59 +0000433 // store <T2> %V, <T2>* %t
434 //
435 // Into:
436 // %t = cast <T2> %V to <T1>
437 // store <T1> %t2, <T1>* %P
438 //
Chris Lattnerd5543802001-12-14 16:37:52 +0000439 // Note: This is not taken care of by expr conversion because there might
440 // not be a cast available for the store to convert the incoming value of.
441 // This code is basically here to make sure that pointers don't have casts
442 // if possible.
443 //
Chris Lattnerdedee7b2001-11-01 05:57:59 +0000444 if (CastInst *CI = dyn_cast<CastInst>(Pointer))
445 if (Value *CastSrc = CI->getOperand(0)) // CSPT = CastSrcPointerType
Chris Lattner7e708292002-06-25 16:13:24 +0000446 if (const PointerType *CSPT = dyn_cast<PointerType>(CastSrc->getType()))
Misha Brukmanf117cc92003-05-20 18:45:36 +0000447 // convertible types?
448 if (Val->getType()->isLosslesslyConvertibleTo(CSPT->getElementType())) {
Chris Lattnerdedee7b2001-11-01 05:57:59 +0000449 PRINT_PEEPHOLE3("st-src-cast:in ", Pointer, Val, SI);
450
451 // Insert the new T cast instruction... stealing old T's name
Chris Lattner2a7c23e2002-09-10 17:04:02 +0000452 std::string Name(CI->getName()); CI->setName("");
Chris Lattner7a176752001-12-04 00:03:30 +0000453 CastInst *NCI = new CastInst(Val, CSPT->getElementType(),
Chris Lattner2a7c23e2002-09-10 17:04:02 +0000454 Name, BI);
Chris Lattnerdedee7b2001-11-01 05:57:59 +0000455
456 // Replace the old store with a new one!
457 ReplaceInstWithInst(BB->getInstList(), BI,
458 SI = new StoreInst(NCI, CastSrc));
459 PRINT_PEEPHOLE3("st-src-cast:out", NCI, CastSrc, SI);
Chris Lattner3c019372002-05-10 15:29:25 +0000460 ++NumLoadStorePeepholes;
Chris Lattnerdedee7b2001-11-01 05:57:59 +0000461 return true;
462 }
463
Chris Lattnerc99428f2002-05-14 05:23:45 +0000464 } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
465 Value *Pointer = LI->getOperand(0);
466 const Type *PtrElType =
467 cast<PointerType>(Pointer->getType())->getElementType();
468
469 // Peephole optimize the following instructions:
Misha Brukmanf117cc92003-05-20 18:45:36 +0000470 // %Val = cast <T1>* to <T2>* ;; If T1 is losslessly convertible to T2
Chris Lattnerc99428f2002-05-14 05:23:45 +0000471 // %t = load <T2>* %P
472 //
473 // Into:
474 // %t = load <T1>* %P
475 // %Val = cast <T1> to <T2>
476 //
477 // Note: This is not taken care of by expr conversion because there might
478 // not be a cast available for the store to convert the incoming value of.
479 // This code is basically here to make sure that pointers don't have casts
480 // if possible.
481 //
482 if (CastInst *CI = dyn_cast<CastInst>(Pointer))
483 if (Value *CastSrc = CI->getOperand(0)) // CSPT = CastSrcPointerType
Chris Lattner7e708292002-06-25 16:13:24 +0000484 if (const PointerType *CSPT = dyn_cast<PointerType>(CastSrc->getType()))
Misha Brukmanf117cc92003-05-20 18:45:36 +0000485 // convertible types?
486 if (PtrElType->isLosslesslyConvertibleTo(CSPT->getElementType())) {
Chris Lattnerc99428f2002-05-14 05:23:45 +0000487 PRINT_PEEPHOLE2("load-src-cast:in ", Pointer, LI);
488
489 // Create the new load instruction... loading the pre-casted value
Chris Lattner2a7c23e2002-09-10 17:04:02 +0000490 LoadInst *NewLI = new LoadInst(CastSrc, LI->getName(), BI);
Chris Lattnerc99428f2002-05-14 05:23:45 +0000491
492 // Insert the new T cast instruction... stealing old T's name
493 CastInst *NCI = new CastInst(NewLI, LI->getType(), CI->getName());
Chris Lattnerc99428f2002-05-14 05:23:45 +0000494
495 // Replace the old store with a new one!
496 ReplaceInstWithInst(BB->getInstList(), BI, NCI);
497 PRINT_PEEPHOLE3("load-src-cast:out", NCI, CastSrc, NewLI);
498 ++NumLoadStorePeepholes;
499 return true;
500 }
501
Chris Lattnerd32a9612001-11-01 02:42:08 +0000502 } else if (I->getOpcode() == Instruction::Add &&
503 isa<CastInst>(I->getOperand(1))) {
504
Chris Lattnerd5b48ca2001-11-14 11:02:49 +0000505 if (PeepholeOptimizeAddCast(BB, BI, I->getOperand(0),
Chris Lattner16125fb2003-04-24 18:25:27 +0000506 cast<CastInst>(I->getOperand(1)), TD)) {
Chris Lattner3c019372002-05-10 15:29:25 +0000507 ++NumGEPInstFormed;
Chris Lattnerd32a9612001-11-01 02:42:08 +0000508 return true;
Chris Lattner3c019372002-05-10 15:29:25 +0000509 }
Chris Lattner61b92c02002-10-08 22:19:25 +0000510 } else if (CallInst *CI = dyn_cast<CallInst>(I)) {
511 // If we have a call with all varargs arguments, convert the call to use the
512 // actual argument types present...
513 //
514 const PointerType *PTy = cast<PointerType>(CI->getCalledValue()->getType());
515 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
516
517 // Is the call to a vararg variable with no real parameters?
Chris Lattnercdeb81d2003-05-01 21:02:53 +0000518 if (FTy->isVarArg() && FTy->getNumParams() == 0 &&
519 !CI->getCalledFunction()) {
Chris Lattner61b92c02002-10-08 22:19:25 +0000520 // If so, insert a new cast instruction, casting it to a function type
521 // that matches the current arguments...
522 //
523 std::vector<const Type *> Params; // Parameter types...
524 for (unsigned i = 1, e = CI->getNumOperands(); i != e; ++i)
525 Params.push_back(CI->getOperand(i)->getType());
526
527 FunctionType *NewFT = FunctionType::get(FTy->getReturnType(),
528 Params, false);
529 PointerType *NewPFunTy = PointerType::get(NewFT);
530
531 // Create a new cast, inserting it right before the function call...
Chris Lattner95549282003-04-28 01:25:38 +0000532 Value *NewCast;
533 Constant *ConstantCallSrc = 0;
534 if (Constant *CS = dyn_cast<Constant>(CI->getCalledValue()))
535 ConstantCallSrc = CS;
536 else if (GlobalValue *GV = dyn_cast<GlobalValue>(CI->getCalledValue()))
537 ConstantCallSrc = ConstantPointerRef::get(GV);
538
539 if (ConstantCallSrc)
540 NewCast = ConstantExpr::getCast(ConstantCallSrc, NewPFunTy);
541 else
542 NewCast = new CastInst(CI->getCalledValue(), NewPFunTy,
543 CI->getCalledValue()->getName()+"_c",CI);
Chris Lattner61b92c02002-10-08 22:19:25 +0000544
545 // Create a new call instruction...
546 CallInst *NewCall = new CallInst(NewCast,
547 std::vector<Value*>(CI->op_begin()+1, CI->op_end()));
548 ++BI;
549 ReplaceInstWithInst(CI, NewCall);
550
551 ++NumVarargCallChanges;
552 return true;
553 }
554
Chris Lattnerd32a9612001-11-01 02:42:08 +0000555 }
556
557 return false;
558}
559
560
561
562
Chris Lattner16125fb2003-04-24 18:25:27 +0000563bool RPR::DoRaisePass(Function &F) {
Chris Lattnerd32a9612001-11-01 02:42:08 +0000564 bool Changed = false;
Chris Lattner7e708292002-06-25 16:13:24 +0000565 for (Function::iterator BB = F.begin(), BBE = F.end(); BB != BBE; ++BB)
Chris Lattnerd32a9612001-11-01 02:42:08 +0000566 for (BasicBlock::iterator BI = BB->begin(); BI != BB->end();) {
Chris Lattner6806f562003-08-01 22:15:03 +0000567 DEBUG(std::cerr << "Processing: " << *BI);
Misha Brukman82c89b92003-05-20 21:01:22 +0000568 if (dceInstruction(BI) || doConstantPropagation(BI)) {
Chris Lattnerc0b90e72001-11-08 20:19:56 +0000569 Changed = true;
Chris Lattner3c019372002-05-10 15:29:25 +0000570 ++NumDCEorCP;
Chris Lattner6806f562003-08-01 22:15:03 +0000571 DEBUG(std::cerr << "***\t\t^^-- Dead code eliminated!\n");
Chris Lattner7e708292002-06-25 16:13:24 +0000572 } else if (PeepholeOptimize(BB, BI)) {
Chris Lattnerd32a9612001-11-01 02:42:08 +0000573 Changed = true;
Chris Lattner7e708292002-06-25 16:13:24 +0000574 } else {
Chris Lattnerd32a9612001-11-01 02:42:08 +0000575 ++BI;
Chris Lattner7e708292002-06-25 16:13:24 +0000576 }
Chris Lattnerd32a9612001-11-01 02:42:08 +0000577 }
Chris Lattner7e708292002-06-25 16:13:24 +0000578
Chris Lattnerd32a9612001-11-01 02:42:08 +0000579 return Changed;
580}
581
582
Chris Lattner16125fb2003-04-24 18:25:27 +0000583// runOnFunction - Raise a function representation to a higher level.
584bool RPR::runOnFunction(Function &F) {
Chris Lattner6806f562003-08-01 22:15:03 +0000585 DEBUG(std::cerr << "\n\n\nStarting to work on Function '" << F.getName()
586 << "'\n");
Chris Lattner68b07b72001-11-01 07:00:51 +0000587
Chris Lattner3cc7dde2001-11-26 16:58:14 +0000588 // Insert casts for all incoming pointer pointer values that are treated as
589 // arrays...
Chris Lattnerd32a9612001-11-01 02:42:08 +0000590 //
Chris Lattner3cc7dde2001-11-26 16:58:14 +0000591 bool Changed = false, LocalChange;
Chris Lattner3378a5b2002-07-16 23:49:24 +0000592
593 // If the StartInst option was specified, then Peephole optimize that
594 // instruction first if it occurs in this function.
595 //
596 if (!StartInst.empty()) {
597 for (Function::iterator BB = F.begin(), BBE = F.end(); BB != BBE; ++BB)
598 for (BasicBlock::iterator BI = BB->begin(); BI != BB->end(); ++BI)
599 if (BI->getName() == StartInst) {
600 bool SavedDebug = DebugFlag; // Save the DEBUG() controlling flag.
601 DebugFlag = true; // Turn on DEBUG's
602 Changed |= PeepholeOptimize(BB, BI);
603 DebugFlag = SavedDebug; // Restore DebugFlag to previous state
604 }
605 }
606
Chris Lattner4b770a32001-12-04 08:12:53 +0000607 do {
Chris Lattner6806f562003-08-01 22:15:03 +0000608 DEBUG(std::cerr << "Looping: \n" << F);
Chris Lattnera8b6d432001-12-05 06:34:00 +0000609
Chris Lattnerf57b8452002-04-27 06:56:12 +0000610 // Iterate over the function, refining it, until it converges on a stable
Chris Lattner3cc7dde2001-11-26 16:58:14 +0000611 // state
Chris Lattnerd5543802001-12-14 16:37:52 +0000612 LocalChange = false;
Chris Lattner2fbfdcf2002-04-07 20:49:59 +0000613 while (DoRaisePass(F)) LocalChange = true;
Chris Lattner3cc7dde2001-11-26 16:58:14 +0000614 Changed |= LocalChange;
615
616 } while (LocalChange);
Chris Lattnerd32a9612001-11-01 02:42:08 +0000617
618 return Changed;
619}