blob: 5bc7b0b85391c562b52611e524fff7f37cb67c7a [file] [log] [blame]
Chris Lattner233f7dc2002-08-12 21:17:25 +00001//===- InstructionCombining.cpp - Combine multiple instructions -----------===//
Misha Brukmanfd939082005-04-21 23:48:37 +00002//
John Criswellb576c942003-10-20 19:43:21 +00003// The LLVM Compiler Infrastructure
4//
Chris Lattner4ee451d2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Misha Brukmanfd939082005-04-21 23:48:37 +00007//
John Criswellb576c942003-10-20 19:43:21 +00008//===----------------------------------------------------------------------===//
Chris Lattner8a2a3112001-12-14 16:52:21 +00009//
10// InstructionCombining - Combine instructions to form fewer, simple
Dan Gohman844731a2008-05-13 00:00:25 +000011// instructions. This pass does not modify the CFG. This pass is where
12// algebraic simplification happens.
Chris Lattner8a2a3112001-12-14 16:52:21 +000013//
14// This pass combines things like:
Chris Lattner318bf792007-03-18 22:51:34 +000015// %Y = add i32 %X, 1
16// %Z = add i32 %Y, 1
Chris Lattner8a2a3112001-12-14 16:52:21 +000017// into:
Chris Lattner318bf792007-03-18 22:51:34 +000018// %Z = add i32 %X, 2
Chris Lattner8a2a3112001-12-14 16:52:21 +000019//
20// This is a simple worklist driven algorithm.
21//
Chris Lattner065a6162003-09-10 05:29:43 +000022// This pass guarantees that the following canonicalizations are performed on
Chris Lattner2cd91962003-07-23 21:41:57 +000023// the program:
24// 1. If a binary operator has a constant operand, it is moved to the RHS
Chris Lattnerdf17af12003-08-12 21:53:41 +000025// 2. Bitwise operators with constant operands are always grouped so that
26// shifts are performed first, then or's, then and's, then xor's.
Reid Spencere4d87aa2006-12-23 06:05:41 +000027// 3. Compare instructions are converted from <,>,<=,>= to ==,!= if possible
28// 4. All cmp instructions on boolean values are replaced with logical ops
Chris Lattnere92d2f42003-08-13 04:18:28 +000029// 5. add X, X is represented as (X*2) => (X << 1)
30// 6. Multiplies with a power-of-two constant argument are transformed into
31// shifts.
Chris Lattnerbac32862004-11-14 19:13:23 +000032// ... etc.
Chris Lattner2cd91962003-07-23 21:41:57 +000033//
Chris Lattner8a2a3112001-12-14 16:52:21 +000034//===----------------------------------------------------------------------===//
35
Chris Lattner0cea42a2004-03-13 23:54:27 +000036#define DEBUG_TYPE "instcombine"
Chris Lattner022103b2002-05-07 20:03:00 +000037#include "llvm/Transforms/Scalar.h"
Chris Lattnerac8f2fd2010-01-04 07:12:23 +000038#include "InstCombine.h"
Chris Lattner35b9e482004-10-12 04:52:52 +000039#include "llvm/IntrinsicInst.h"
Chris Lattner79066fa2007-01-30 23:46:24 +000040#include "llvm/Analysis/ConstantFolding.h"
Chris Lattner9dbb4292009-11-09 23:28:39 +000041#include "llvm/Analysis/InstructionSimplify.h"
Victor Hernandezf006b182009-10-27 20:05:49 +000042#include "llvm/Analysis/MemoryBuiltins.h"
Chris Lattnerbc61e662003-11-02 05:57:39 +000043#include "llvm/Target/TargetData.h"
Chris Lattnerbc61e662003-11-02 05:57:39 +000044#include "llvm/Transforms/Utils/Local.h"
Chris Lattner804272c2010-01-05 07:54:43 +000045#include "llvm/Support/CFG.h"
Chris Lattnerea1c4542004-12-08 23:43:58 +000046#include "llvm/Support/Debug.h"
Chris Lattner28977af2004-04-05 01:30:19 +000047#include "llvm/Support/GetElementPtrTypeIterator.h"
Chris Lattneracd1f0f2004-07-30 07:50:03 +000048#include "llvm/Support/PatternMatch.h"
Nick Lewyckyd5061a92011-08-03 00:43:35 +000049#include "llvm/Support/ValueHandle.h"
Chris Lattner1f87a582007-02-15 19:41:52 +000050#include "llvm/ADT/SmallPtrSet.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000051#include "llvm/ADT/Statistic.h"
Owen Anderson74cfb0c2010-10-07 20:04:55 +000052#include "llvm-c/Initialization.h"
Chris Lattnerb3bc8fa2002-05-14 15:24:07 +000053#include <algorithm>
Torok Edwin3eaee312008-04-20 08:33:11 +000054#include <climits>
Chris Lattner67b1e1b2003-12-07 01:24:23 +000055using namespace llvm;
Chris Lattneracd1f0f2004-07-30 07:50:03 +000056using namespace llvm::PatternMatch;
Brian Gaeked0fde302003-11-11 22:41:34 +000057
Chris Lattner0e5f4992006-12-19 21:40:18 +000058STATISTIC(NumCombined , "Number of insts combined");
59STATISTIC(NumConstProp, "Number of constant folds");
60STATISTIC(NumDeadInst , "Number of dead inst eliminated");
Chris Lattner0e5f4992006-12-19 21:40:18 +000061STATISTIC(NumSunkInst , "Number of instructions sunk");
Duncan Sands37bf92b2010-12-22 13:36:08 +000062STATISTIC(NumExpand, "Number of expansions");
Duncan Sandsa3c44a52010-12-22 09:40:51 +000063STATISTIC(NumFactor , "Number of factorizations");
64STATISTIC(NumReassoc , "Number of reassociations");
Chris Lattnera92f6962002-10-01 22:38:41 +000065
Owen Anderson74cfb0c2010-10-07 20:04:55 +000066// Initialization Routines
67void llvm::initializeInstCombine(PassRegistry &Registry) {
68 initializeInstCombinerPass(Registry);
69}
70
71void LLVMInitializeInstCombine(LLVMPassRegistryRef R) {
72 initializeInstCombine(*unwrap(R));
73}
Chris Lattnerdd841ae2002-04-18 17:39:14 +000074
Dan Gohman844731a2008-05-13 00:00:25 +000075char InstCombiner::ID = 0;
Owen Andersond13db2c2010-07-21 22:09:45 +000076INITIALIZE_PASS(InstCombiner, "instcombine",
Owen Andersonce665bd2010-10-07 22:25:06 +000077 "Combine redundant instructions", false, false)
Dan Gohman844731a2008-05-13 00:00:25 +000078
Chris Lattnere0b4b722010-01-04 07:17:19 +000079void InstCombiner::getAnalysisUsage(AnalysisUsage &AU) const {
Chris Lattnere0b4b722010-01-04 07:17:19 +000080 AU.setPreservesCFG();
81}
82
83
Chris Lattnerc22d4d12009-11-10 07:23:37 +000084/// ShouldChangeType - Return true if it is desirable to convert a computation
85/// from 'From' to 'To'. We don't want to convert from a legal to an illegal
86/// type for example, or from a smaller to a larger illegal type.
Chris Lattnerdb125cf2011-07-18 04:54:35 +000087bool InstCombiner::ShouldChangeType(Type *From, Type *To) const {
Duncan Sands1df98592010-02-16 11:11:14 +000088 assert(From->isIntegerTy() && To->isIntegerTy());
Chris Lattnerc22d4d12009-11-10 07:23:37 +000089
90 // If we don't have TD, we don't know if the source/dest are legal.
91 if (!TD) return false;
92
93 unsigned FromWidth = From->getPrimitiveSizeInBits();
94 unsigned ToWidth = To->getPrimitiveSizeInBits();
95 bool FromLegal = TD->isLegalInteger(FromWidth);
96 bool ToLegal = TD->isLegalInteger(ToWidth);
97
98 // If this is a legal integer from type, and the result would be an illegal
99 // type, don't do the transformation.
100 if (FromLegal && !ToLegal)
101 return false;
102
103 // Otherwise, if both are illegal, do not increase the size of the result. We
104 // do allow things like i160 -> i64, but not i64 -> i160.
105 if (!FromLegal && !ToLegal && ToWidth > FromWidth)
106 return false;
107
108 return true;
109}
110
Chris Lattner33a61132006-05-06 09:00:16 +0000111
Duncan Sands096aa792010-11-13 15:10:37 +0000112/// SimplifyAssociativeOrCommutative - This performs a few simplifications for
113/// operators which are associative or commutative:
114//
115// Commutative operators:
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000116//
Chris Lattner4f98c562003-03-10 21:43:22 +0000117// 1. Order operands such that they are listed from right (least complex) to
118// left (most complex). This puts constants before unary operators before
119// binary operators.
120//
Duncan Sands096aa792010-11-13 15:10:37 +0000121// Associative operators:
Chris Lattner4f98c562003-03-10 21:43:22 +0000122//
Duncan Sands096aa792010-11-13 15:10:37 +0000123// 2. Transform: "(A op B) op C" ==> "A op (B op C)" if "B op C" simplifies.
124// 3. Transform: "A op (B op C)" ==> "(A op B) op C" if "A op B" simplifies.
125//
126// Associative and commutative operators:
127//
128// 4. Transform: "(A op B) op C" ==> "(C op A) op B" if "C op A" simplifies.
129// 5. Transform: "A op (B op C)" ==> "B op (C op A)" if "C op A" simplifies.
130// 6. Transform: "(A op C1) op (B op C2)" ==> "(A op B) op (C1 op C2)"
131// if C1 and C2 are constants.
132//
133bool InstCombiner::SimplifyAssociativeOrCommutative(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +0000134 Instruction::BinaryOps Opcode = I.getOpcode();
Duncan Sands096aa792010-11-13 15:10:37 +0000135 bool Changed = false;
Chris Lattnerc8802d22003-03-11 00:12:48 +0000136
Duncan Sands096aa792010-11-13 15:10:37 +0000137 do {
138 // Order operands such that they are listed from right (least complex) to
139 // left (most complex). This puts constants before unary operators before
140 // binary operators.
141 if (I.isCommutative() && getComplexity(I.getOperand(0)) <
142 getComplexity(I.getOperand(1)))
143 Changed = !I.swapOperands();
144
145 BinaryOperator *Op0 = dyn_cast<BinaryOperator>(I.getOperand(0));
146 BinaryOperator *Op1 = dyn_cast<BinaryOperator>(I.getOperand(1));
147
148 if (I.isAssociative()) {
149 // Transform: "(A op B) op C" ==> "A op (B op C)" if "B op C" simplifies.
150 if (Op0 && Op0->getOpcode() == Opcode) {
151 Value *A = Op0->getOperand(0);
152 Value *B = Op0->getOperand(1);
153 Value *C = I.getOperand(1);
154
155 // Does "B op C" simplify?
156 if (Value *V = SimplifyBinOp(Opcode, B, C, TD)) {
157 // It simplifies to V. Form "A op V".
158 I.setOperand(0, A);
159 I.setOperand(1, V);
Dan Gohman5195b712011-02-02 02:05:46 +0000160 // Conservatively clear the optional flags, since they may not be
161 // preserved by the reassociation.
162 I.clearSubclassOptionalData();
Duncan Sands096aa792010-11-13 15:10:37 +0000163 Changed = true;
Duncan Sandsa3c44a52010-12-22 09:40:51 +0000164 ++NumReassoc;
Duncan Sands096aa792010-11-13 15:10:37 +0000165 continue;
Misha Brukmanfd939082005-04-21 23:48:37 +0000166 }
Duncan Sands096aa792010-11-13 15:10:37 +0000167 }
168
169 // Transform: "A op (B op C)" ==> "(A op B) op C" if "A op B" simplifies.
170 if (Op1 && Op1->getOpcode() == Opcode) {
171 Value *A = I.getOperand(0);
172 Value *B = Op1->getOperand(0);
173 Value *C = Op1->getOperand(1);
174
175 // Does "A op B" simplify?
176 if (Value *V = SimplifyBinOp(Opcode, A, B, TD)) {
177 // It simplifies to V. Form "V op C".
178 I.setOperand(0, V);
179 I.setOperand(1, C);
Dan Gohman5195b712011-02-02 02:05:46 +0000180 // Conservatively clear the optional flags, since they may not be
181 // preserved by the reassociation.
182 I.clearSubclassOptionalData();
Duncan Sands096aa792010-11-13 15:10:37 +0000183 Changed = true;
Duncan Sandsa3c44a52010-12-22 09:40:51 +0000184 ++NumReassoc;
Duncan Sands096aa792010-11-13 15:10:37 +0000185 continue;
186 }
187 }
Chris Lattner4f98c562003-03-10 21:43:22 +0000188 }
Duncan Sands096aa792010-11-13 15:10:37 +0000189
190 if (I.isAssociative() && I.isCommutative()) {
191 // Transform: "(A op B) op C" ==> "(C op A) op B" if "C op A" simplifies.
192 if (Op0 && Op0->getOpcode() == Opcode) {
193 Value *A = Op0->getOperand(0);
194 Value *B = Op0->getOperand(1);
195 Value *C = I.getOperand(1);
196
197 // Does "C op A" simplify?
198 if (Value *V = SimplifyBinOp(Opcode, C, A, TD)) {
199 // It simplifies to V. Form "V op B".
200 I.setOperand(0, V);
201 I.setOperand(1, B);
Dan Gohman5195b712011-02-02 02:05:46 +0000202 // Conservatively clear the optional flags, since they may not be
203 // preserved by the reassociation.
204 I.clearSubclassOptionalData();
Duncan Sands096aa792010-11-13 15:10:37 +0000205 Changed = true;
Duncan Sandsa3c44a52010-12-22 09:40:51 +0000206 ++NumReassoc;
Duncan Sands096aa792010-11-13 15:10:37 +0000207 continue;
208 }
209 }
210
211 // Transform: "A op (B op C)" ==> "B op (C op A)" if "C op A" simplifies.
212 if (Op1 && Op1->getOpcode() == Opcode) {
213 Value *A = I.getOperand(0);
214 Value *B = Op1->getOperand(0);
215 Value *C = Op1->getOperand(1);
216
217 // Does "C op A" simplify?
218 if (Value *V = SimplifyBinOp(Opcode, C, A, TD)) {
219 // It simplifies to V. Form "B op V".
220 I.setOperand(0, B);
221 I.setOperand(1, V);
Dan Gohman5195b712011-02-02 02:05:46 +0000222 // Conservatively clear the optional flags, since they may not be
223 // preserved by the reassociation.
224 I.clearSubclassOptionalData();
Duncan Sands096aa792010-11-13 15:10:37 +0000225 Changed = true;
Duncan Sandsa3c44a52010-12-22 09:40:51 +0000226 ++NumReassoc;
Duncan Sands096aa792010-11-13 15:10:37 +0000227 continue;
228 }
229 }
230
231 // Transform: "(A op C1) op (B op C2)" ==> "(A op B) op (C1 op C2)"
232 // if C1 and C2 are constants.
233 if (Op0 && Op1 &&
234 Op0->getOpcode() == Opcode && Op1->getOpcode() == Opcode &&
235 isa<Constant>(Op0->getOperand(1)) &&
236 isa<Constant>(Op1->getOperand(1)) &&
237 Op0->hasOneUse() && Op1->hasOneUse()) {
238 Value *A = Op0->getOperand(0);
239 Constant *C1 = cast<Constant>(Op0->getOperand(1));
240 Value *B = Op1->getOperand(0);
241 Constant *C2 = cast<Constant>(Op1->getOperand(1));
242
243 Constant *Folded = ConstantExpr::get(Opcode, C1, C2);
Eli Friedmane6f364b2011-05-18 23:58:37 +0000244 Instruction *New = BinaryOperator::Create(Opcode, A, B);
Eli Friedmana311c342011-05-27 00:19:40 +0000245 InsertNewInstWith(New, I);
Eli Friedmane6f364b2011-05-18 23:58:37 +0000246 New->takeName(Op1);
Duncan Sands096aa792010-11-13 15:10:37 +0000247 I.setOperand(0, New);
248 I.setOperand(1, Folded);
Dan Gohman5195b712011-02-02 02:05:46 +0000249 // Conservatively clear the optional flags, since they may not be
250 // preserved by the reassociation.
251 I.clearSubclassOptionalData();
Duncan Sands096aa792010-11-13 15:10:37 +0000252 Changed = true;
253 continue;
254 }
255 }
256
257 // No further simplifications.
258 return Changed;
259 } while (1);
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000260}
Chris Lattner8a2a3112001-12-14 16:52:21 +0000261
Duncan Sands5057f382010-11-23 14:23:47 +0000262/// LeftDistributesOverRight - Whether "X LOp (Y ROp Z)" is always equal to
Duncan Sandsc2b1c0b2010-11-23 15:25:34 +0000263/// "(X LOp Y) ROp (X LOp Z)".
Duncan Sands5057f382010-11-23 14:23:47 +0000264static bool LeftDistributesOverRight(Instruction::BinaryOps LOp,
265 Instruction::BinaryOps ROp) {
266 switch (LOp) {
267 default:
268 return false;
269
270 case Instruction::And:
271 // And distributes over Or and Xor.
272 switch (ROp) {
273 default:
274 return false;
275 case Instruction::Or:
276 case Instruction::Xor:
277 return true;
278 }
279
280 case Instruction::Mul:
281 // Multiplication distributes over addition and subtraction.
282 switch (ROp) {
283 default:
284 return false;
285 case Instruction::Add:
286 case Instruction::Sub:
287 return true;
288 }
289
290 case Instruction::Or:
291 // Or distributes over And.
292 switch (ROp) {
293 default:
294 return false;
295 case Instruction::And:
296 return true;
297 }
298 }
299}
300
301/// RightDistributesOverLeft - Whether "(X LOp Y) ROp Z" is always equal to
302/// "(X ROp Z) LOp (Y ROp Z)".
303static bool RightDistributesOverLeft(Instruction::BinaryOps LOp,
304 Instruction::BinaryOps ROp) {
305 if (Instruction::isCommutative(ROp))
306 return LeftDistributesOverRight(ROp, LOp);
307 // TODO: It would be nice to handle division, aka "(X + Y)/Z = X/Z + Y/Z",
308 // but this requires knowing that the addition does not overflow and other
309 // such subtleties.
310 return false;
311}
312
Duncan Sands37bf92b2010-12-22 13:36:08 +0000313/// SimplifyUsingDistributiveLaws - This tries to simplify binary operations
314/// which some other binary operation distributes over either by factorizing
315/// out common terms (eg "(A*B)+(A*C)" -> "A*(B+C)") or expanding out if this
316/// results in simplifications (eg: "A & (B | C) -> (A&B) | (A&C)" if this is
317/// a win). Returns the simplified value, or null if it didn't simplify.
318Value *InstCombiner::SimplifyUsingDistributiveLaws(BinaryOperator &I) {
319 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
320 BinaryOperator *Op0 = dyn_cast<BinaryOperator>(LHS);
321 BinaryOperator *Op1 = dyn_cast<BinaryOperator>(RHS);
322 Instruction::BinaryOps TopLevelOpcode = I.getOpcode(); // op
Duncan Sands5057f382010-11-23 14:23:47 +0000323
Duncan Sands37bf92b2010-12-22 13:36:08 +0000324 // Factorization.
325 if (Op0 && Op1 && Op0->getOpcode() == Op1->getOpcode()) {
326 // The instruction has the form "(A op' B) op (C op' D)". Try to factorize
327 // a common term.
328 Value *A = Op0->getOperand(0), *B = Op0->getOperand(1);
329 Value *C = Op1->getOperand(0), *D = Op1->getOperand(1);
330 Instruction::BinaryOps InnerOpcode = Op0->getOpcode(); // op'
Duncan Sands5057f382010-11-23 14:23:47 +0000331
Duncan Sands37bf92b2010-12-22 13:36:08 +0000332 // Does "X op' Y" always equal "Y op' X"?
333 bool InnerCommutative = Instruction::isCommutative(InnerOpcode);
Duncan Sands5057f382010-11-23 14:23:47 +0000334
Duncan Sands37bf92b2010-12-22 13:36:08 +0000335 // Does "X op' (Y op Z)" always equal "(X op' Y) op (X op' Z)"?
336 if (LeftDistributesOverRight(InnerOpcode, TopLevelOpcode))
337 // Does the instruction have the form "(A op' B) op (A op' D)" or, in the
338 // commutative case, "(A op' B) op (C op' A)"?
339 if (A == C || (InnerCommutative && A == D)) {
340 if (A != C)
341 std::swap(C, D);
342 // Consider forming "A op' (B op D)".
343 // If "B op D" simplifies then it can be formed with no cost.
344 Value *V = SimplifyBinOp(TopLevelOpcode, B, D, TD);
345 // If "B op D" doesn't simplify then only go on if both of the existing
346 // operations "A op' B" and "C op' D" will be zapped as no longer used.
347 if (!V && Op0->hasOneUse() && Op1->hasOneUse())
348 V = Builder->CreateBinOp(TopLevelOpcode, B, D, Op1->getName());
349 if (V) {
350 ++NumFactor;
351 V = Builder->CreateBinOp(InnerOpcode, A, V);
352 V->takeName(&I);
353 return V;
354 }
Duncan Sandsa3c44a52010-12-22 09:40:51 +0000355 }
Duncan Sands5057f382010-11-23 14:23:47 +0000356
Duncan Sands37bf92b2010-12-22 13:36:08 +0000357 // Does "(X op Y) op' Z" always equal "(X op' Z) op (Y op' Z)"?
358 if (RightDistributesOverLeft(TopLevelOpcode, InnerOpcode))
359 // Does the instruction have the form "(A op' B) op (C op' B)" or, in the
360 // commutative case, "(A op' B) op (B op' D)"?
361 if (B == D || (InnerCommutative && B == C)) {
362 if (B != D)
363 std::swap(C, D);
364 // Consider forming "(A op C) op' B".
365 // If "A op C" simplifies then it can be formed with no cost.
366 Value *V = SimplifyBinOp(TopLevelOpcode, A, C, TD);
367 // If "A op C" doesn't simplify then only go on if both of the existing
368 // operations "A op' B" and "C op' D" will be zapped as no longer used.
369 if (!V && Op0->hasOneUse() && Op1->hasOneUse())
370 V = Builder->CreateBinOp(TopLevelOpcode, A, C, Op0->getName());
371 if (V) {
372 ++NumFactor;
373 V = Builder->CreateBinOp(InnerOpcode, V, B);
374 V->takeName(&I);
375 return V;
376 }
Duncan Sandsa3c44a52010-12-22 09:40:51 +0000377 }
Duncan Sands37bf92b2010-12-22 13:36:08 +0000378 }
379
380 // Expansion.
381 if (Op0 && RightDistributesOverLeft(Op0->getOpcode(), TopLevelOpcode)) {
382 // The instruction has the form "(A op' B) op C". See if expanding it out
383 // to "(A op C) op' (B op C)" results in simplifications.
384 Value *A = Op0->getOperand(0), *B = Op0->getOperand(1), *C = RHS;
385 Instruction::BinaryOps InnerOpcode = Op0->getOpcode(); // op'
386
387 // Do "A op C" and "B op C" both simplify?
388 if (Value *L = SimplifyBinOp(TopLevelOpcode, A, C, TD))
389 if (Value *R = SimplifyBinOp(TopLevelOpcode, B, C, TD)) {
390 // They do! Return "L op' R".
391 ++NumExpand;
392 // If "L op' R" equals "A op' B" then "L op' R" is just the LHS.
393 if ((L == A && R == B) ||
394 (Instruction::isCommutative(InnerOpcode) && L == B && R == A))
395 return Op0;
396 // Otherwise return "L op' R" if it simplifies.
397 if (Value *V = SimplifyBinOp(InnerOpcode, L, R, TD))
398 return V;
399 // Otherwise, create a new instruction.
400 C = Builder->CreateBinOp(InnerOpcode, L, R);
401 C->takeName(&I);
402 return C;
403 }
404 }
405
406 if (Op1 && LeftDistributesOverRight(TopLevelOpcode, Op1->getOpcode())) {
407 // The instruction has the form "A op (B op' C)". See if expanding it out
408 // to "(A op B) op' (A op C)" results in simplifications.
409 Value *A = LHS, *B = Op1->getOperand(0), *C = Op1->getOperand(1);
410 Instruction::BinaryOps InnerOpcode = Op1->getOpcode(); // op'
411
412 // Do "A op B" and "A op C" both simplify?
413 if (Value *L = SimplifyBinOp(TopLevelOpcode, A, B, TD))
414 if (Value *R = SimplifyBinOp(TopLevelOpcode, A, C, TD)) {
415 // They do! Return "L op' R".
416 ++NumExpand;
417 // If "L op' R" equals "B op' C" then "L op' R" is just the RHS.
418 if ((L == B && R == C) ||
419 (Instruction::isCommutative(InnerOpcode) && L == C && R == B))
420 return Op1;
421 // Otherwise return "L op' R" if it simplifies.
422 if (Value *V = SimplifyBinOp(InnerOpcode, L, R, TD))
423 return V;
424 // Otherwise, create a new instruction.
425 A = Builder->CreateBinOp(InnerOpcode, L, R);
426 A->takeName(&I);
427 return A;
428 }
429 }
Duncan Sands5057f382010-11-23 14:23:47 +0000430
431 return 0;
432}
433
Chris Lattner8d969642003-03-10 23:06:50 +0000434// dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
435// if the LHS is a constant zero (which is the 'negate' form).
Chris Lattnerb35dde12002-05-06 16:49:18 +0000436//
Chris Lattner02446fc2010-01-04 07:37:31 +0000437Value *InstCombiner::dyn_castNegVal(Value *V) const {
Owen Andersonfa82b6e2009-07-13 22:18:28 +0000438 if (BinaryOperator::isNeg(V))
Chris Lattnera1df33c2005-04-24 07:30:14 +0000439 return BinaryOperator::getNegArgument(V);
Chris Lattner8d969642003-03-10 23:06:50 +0000440
Chris Lattner0ce85802004-12-14 20:08:06 +0000441 // Constants can be considered to be negated values if they can be folded.
442 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
Owen Andersonbaf3c402009-07-29 18:55:55 +0000443 return ConstantExpr::getNeg(C);
Nick Lewycky18b3da62008-05-23 04:54:45 +0000444
445 if (ConstantVector *C = dyn_cast<ConstantVector>(V))
Duncan Sandsb0bc6c32010-02-15 16:12:20 +0000446 if (C->getType()->getElementType()->isIntegerTy())
Owen Andersonbaf3c402009-07-29 18:55:55 +0000447 return ConstantExpr::getNeg(C);
Nick Lewycky18b3da62008-05-23 04:54:45 +0000448
Chris Lattner8d969642003-03-10 23:06:50 +0000449 return 0;
Chris Lattnerb35dde12002-05-06 16:49:18 +0000450}
451
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000452// dyn_castFNegVal - Given a 'fsub' instruction, return the RHS of the
453// instruction if the LHS is a constant negative zero (which is the 'negate'
454// form).
455//
Chris Lattnerd12c27c2010-01-05 06:09:35 +0000456Value *InstCombiner::dyn_castFNegVal(Value *V) const {
Owen Andersonfa82b6e2009-07-13 22:18:28 +0000457 if (BinaryOperator::isFNeg(V))
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000458 return BinaryOperator::getFNegArgument(V);
459
460 // Constants can be considered to be negated values if they can be folded.
461 if (ConstantFP *C = dyn_cast<ConstantFP>(V))
Owen Andersonbaf3c402009-07-29 18:55:55 +0000462 return ConstantExpr::getFNeg(C);
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000463
464 if (ConstantVector *C = dyn_cast<ConstantVector>(V))
Duncan Sandsb0bc6c32010-02-15 16:12:20 +0000465 if (C->getType()->getElementType()->isFloatingPointTy())
Owen Andersonbaf3c402009-07-29 18:55:55 +0000466 return ConstantExpr::getFNeg(C);
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000467
468 return 0;
469}
470
Chris Lattner6e7ba452005-01-01 16:22:27 +0000471static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
Chris Lattner2eefe512004-04-09 19:05:30 +0000472 InstCombiner *IC) {
Nick Lewyckyacf4a7c2011-01-21 02:30:43 +0000473 if (CastInst *CI = dyn_cast<CastInst>(&I)) {
Chris Lattner2345d1d2009-08-30 20:01:10 +0000474 return IC->Builder->CreateCast(CI->getOpcode(), SO, I.getType());
Nick Lewyckyacf4a7c2011-01-21 02:30:43 +0000475 }
Chris Lattner6e7ba452005-01-01 16:22:27 +0000476
Chris Lattner2eefe512004-04-09 19:05:30 +0000477 // Figure out if the constant is the left or the right argument.
Chris Lattner6e7ba452005-01-01 16:22:27 +0000478 bool ConstIsRHS = isa<Constant>(I.getOperand(1));
479 Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
Chris Lattner564a7272003-08-13 19:01:45 +0000480
Chris Lattner2eefe512004-04-09 19:05:30 +0000481 if (Constant *SOC = dyn_cast<Constant>(SO)) {
482 if (ConstIsRHS)
Owen Andersonbaf3c402009-07-29 18:55:55 +0000483 return ConstantExpr::get(I.getOpcode(), SOC, ConstOperand);
484 return ConstantExpr::get(I.getOpcode(), ConstOperand, SOC);
Chris Lattner2eefe512004-04-09 19:05:30 +0000485 }
486
487 Value *Op0 = SO, *Op1 = ConstOperand;
488 if (!ConstIsRHS)
489 std::swap(Op0, Op1);
Chris Lattner74381062009-08-30 07:44:24 +0000490
Chris Lattner6e7ba452005-01-01 16:22:27 +0000491 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
Chris Lattner74381062009-08-30 07:44:24 +0000492 return IC->Builder->CreateBinOp(BO->getOpcode(), Op0, Op1,
493 SO->getName()+".op");
494 if (ICmpInst *CI = dyn_cast<ICmpInst>(&I))
495 return IC->Builder->CreateICmp(CI->getPredicate(), Op0, Op1,
496 SO->getName()+".cmp");
497 if (FCmpInst *CI = dyn_cast<FCmpInst>(&I))
498 return IC->Builder->CreateICmp(CI->getPredicate(), Op0, Op1,
499 SO->getName()+".cmp");
500 llvm_unreachable("Unknown binary instruction type!");
Chris Lattner6e7ba452005-01-01 16:22:27 +0000501}
502
503// FoldOpIntoSelect - Given an instruction with a select as one operand and a
504// constant as the other operand, try to fold the binary operator into the
505// select arguments. This also works for Cast instructions, which obviously do
506// not have a second operand.
Chris Lattner80f43d32010-01-04 07:53:58 +0000507Instruction *InstCombiner::FoldOpIntoSelect(Instruction &Op, SelectInst *SI) {
Chris Lattner6e7ba452005-01-01 16:22:27 +0000508 // Don't modify shared select instructions
509 if (!SI->hasOneUse()) return 0;
510 Value *TV = SI->getOperand(1);
511 Value *FV = SI->getOperand(2);
512
513 if (isa<Constant>(TV) || isa<Constant>(FV)) {
Chris Lattner956db272005-04-21 05:43:13 +0000514 // Bool selects with constant operands can be folded to logical ops.
Duncan Sandsb0bc6c32010-02-15 16:12:20 +0000515 if (SI->getType()->isIntegerTy(1)) return 0;
Chris Lattner956db272005-04-21 05:43:13 +0000516
Nick Lewyckyacf4a7c2011-01-21 02:30:43 +0000517 // If it's a bitcast involving vectors, make sure it has the same number of
518 // elements on both sides.
519 if (BitCastInst *BC = dyn_cast<BitCastInst>(&Op)) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000520 VectorType *DestTy = dyn_cast<VectorType>(BC->getDestTy());
521 VectorType *SrcTy = dyn_cast<VectorType>(BC->getSrcTy());
Nick Lewyckyacf4a7c2011-01-21 02:30:43 +0000522
523 // Verify that either both or neither are vectors.
524 if ((SrcTy == NULL) != (DestTy == NULL)) return 0;
525 // If vectors, verify that they have the same number of elements.
526 if (SrcTy && SrcTy->getNumElements() != DestTy->getNumElements())
527 return 0;
528 }
529
Chris Lattner80f43d32010-01-04 07:53:58 +0000530 Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, this);
531 Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, this);
Chris Lattner6e7ba452005-01-01 16:22:27 +0000532
Nick Lewyckyacf4a7c2011-01-21 02:30:43 +0000533 return SelectInst::Create(SI->getCondition(),
534 SelectTrueVal, SelectFalseVal);
Chris Lattner6e7ba452005-01-01 16:22:27 +0000535 }
536 return 0;
Chris Lattner2eefe512004-04-09 19:05:30 +0000537}
538
Chris Lattner4e998b22004-09-29 05:07:12 +0000539
Chris Lattner5d1704d2009-09-27 19:57:57 +0000540/// FoldOpIntoPhi - Given a binary operator, cast instruction, or select which
541/// has a PHI node as operand #0, see if we can fold the instruction into the
542/// PHI (which is only possible if all operands to the PHI are constants).
Chris Lattner213cd612009-09-27 20:46:36 +0000543///
Chris Lattner9922ccf2011-01-16 05:14:26 +0000544Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I) {
Chris Lattner4e998b22004-09-29 05:07:12 +0000545 PHINode *PN = cast<PHINode>(I.getOperand(0));
Chris Lattnerbac32862004-11-14 19:13:23 +0000546 unsigned NumPHIValues = PN->getNumIncomingValues();
Chris Lattner5aac8322011-01-16 04:37:29 +0000547 if (NumPHIValues == 0)
Chris Lattner213cd612009-09-27 20:46:36 +0000548 return 0;
549
Chris Lattner084fe622011-01-21 05:08:26 +0000550 // We normally only transform phis with a single use. However, if a PHI has
551 // multiple uses and they are all the same operation, we can fold *all* of the
552 // uses into the PHI.
Chris Lattner192228e2011-01-16 05:28:59 +0000553 if (!PN->hasOneUse()) {
554 // Walk the use list for the instruction, comparing them to I.
555 for (Value::use_iterator UI = PN->use_begin(), E = PN->use_end();
Chris Lattnercd151d22011-01-21 05:29:50 +0000556 UI != E; ++UI) {
557 Instruction *User = cast<Instruction>(*UI);
558 if (User != &I && !I.isIdenticalTo(User))
Chris Lattner192228e2011-01-16 05:28:59 +0000559 return 0;
Chris Lattnercd151d22011-01-21 05:29:50 +0000560 }
Chris Lattner192228e2011-01-16 05:28:59 +0000561 // Otherwise, we can replace *all* users with the new PHI we form.
562 }
Chris Lattner213cd612009-09-27 20:46:36 +0000563
Chris Lattner5d1704d2009-09-27 19:57:57 +0000564 // Check to see if all of the operands of the PHI are simple constants
565 // (constantint/constantfp/undef). If there is one non-constant value,
Chris Lattnerc6df8f42009-09-27 20:18:49 +0000566 // remember the BB it is in. If there is more than one or if *it* is a PHI,
567 // bail out. We don't do arbitrary constant expressions here because moving
568 // their computation can be expensive without a cost model.
Chris Lattner2a86f3b2006-09-09 22:02:56 +0000569 BasicBlock *NonConstBB = 0;
Chris Lattner5aac8322011-01-16 04:37:29 +0000570 for (unsigned i = 0; i != NumPHIValues; ++i) {
571 Value *InVal = PN->getIncomingValue(i);
572 if (isa<Constant>(InVal) && !isa<ConstantExpr>(InVal))
573 continue;
574
575 if (isa<PHINode>(InVal)) return 0; // Itself a phi.
576 if (NonConstBB) return 0; // More than one non-const value.
577
578 NonConstBB = PN->getIncomingBlock(i);
Chris Lattner7dfe8fd2011-01-16 05:08:00 +0000579
580 // If the InVal is an invoke at the end of the pred block, then we can't
581 // insert a computation after it without breaking the edge.
582 if (InvokeInst *II = dyn_cast<InvokeInst>(InVal))
583 if (II->getParent() == NonConstBB)
584 return 0;
Chris Lattnercd151d22011-01-21 05:29:50 +0000585
586 // If the incoming non-constant value is in I's block, we will remove one
587 // instruction, but insert another equivalent one, leading to infinite
588 // instcombine.
589 if (NonConstBB == I.getParent())
590 return 0;
Chris Lattner5aac8322011-01-16 04:37:29 +0000591 }
Chris Lattner2a86f3b2006-09-09 22:02:56 +0000592
593 // If there is exactly one non-constant value, we can insert a copy of the
594 // operation in that block. However, if this is a critical edge, we would be
595 // inserting the computation one some other paths (e.g. inside a loop). Only
596 // do this if the pred block is unconditionally branching into the phi block.
Chris Lattner9922ccf2011-01-16 05:14:26 +0000597 if (NonConstBB != 0) {
Chris Lattner2a86f3b2006-09-09 22:02:56 +0000598 BranchInst *BI = dyn_cast<BranchInst>(NonConstBB->getTerminator());
599 if (!BI || !BI->isUnconditional()) return 0;
600 }
Chris Lattner4e998b22004-09-29 05:07:12 +0000601
602 // Okay, we can do the transformation: create the new PHI node.
Eli Friedmane6f364b2011-05-18 23:58:37 +0000603 PHINode *NewPN = PHINode::Create(I.getType(), PN->getNumIncomingValues());
Chris Lattner857eb572009-10-21 23:41:58 +0000604 InsertNewInstBefore(NewPN, *PN);
605 NewPN->takeName(PN);
Chris Lattner7dfe8fd2011-01-16 05:08:00 +0000606
607 // If we are going to have to insert a new computation, do so right before the
608 // predecessors terminator.
609 if (NonConstBB)
610 Builder->SetInsertPoint(NonConstBB->getTerminator());
611
Chris Lattner4e998b22004-09-29 05:07:12 +0000612 // Next, add all of the operands to the PHI.
Chris Lattner5d1704d2009-09-27 19:57:57 +0000613 if (SelectInst *SI = dyn_cast<SelectInst>(&I)) {
614 // We only currently try to fold the condition of a select when it is a phi,
615 // not the true/false values.
Chris Lattnerc6df8f42009-09-27 20:18:49 +0000616 Value *TrueV = SI->getTrueValue();
617 Value *FalseV = SI->getFalseValue();
Chris Lattner3ddfb212009-09-28 06:49:44 +0000618 BasicBlock *PhiTransBB = PN->getParent();
Chris Lattner5d1704d2009-09-27 19:57:57 +0000619 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattnerc6df8f42009-09-27 20:18:49 +0000620 BasicBlock *ThisBB = PN->getIncomingBlock(i);
Chris Lattner3ddfb212009-09-28 06:49:44 +0000621 Value *TrueVInPred = TrueV->DoPHITranslation(PhiTransBB, ThisBB);
622 Value *FalseVInPred = FalseV->DoPHITranslation(PhiTransBB, ThisBB);
Chris Lattner5d1704d2009-09-27 19:57:57 +0000623 Value *InV = 0;
Chris Lattner7dfe8fd2011-01-16 05:08:00 +0000624 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i)))
Chris Lattnerc6df8f42009-09-27 20:18:49 +0000625 InV = InC->isNullValue() ? FalseVInPred : TrueVInPred;
Chris Lattner7dfe8fd2011-01-16 05:08:00 +0000626 else
627 InV = Builder->CreateSelect(PN->getIncomingValue(i),
628 TrueVInPred, FalseVInPred, "phitmp");
Chris Lattnerc6df8f42009-09-27 20:18:49 +0000629 NewPN->addIncoming(InV, ThisBB);
Chris Lattner5d1704d2009-09-27 19:57:57 +0000630 }
Chris Lattner7dfe8fd2011-01-16 05:08:00 +0000631 } else if (CmpInst *CI = dyn_cast<CmpInst>(&I)) {
632 Constant *C = cast<Constant>(I.getOperand(1));
633 for (unsigned i = 0; i != NumPHIValues; ++i) {
634 Value *InV = 0;
635 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i)))
636 InV = ConstantExpr::getCompare(CI->getPredicate(), InC, C);
637 else if (isa<ICmpInst>(CI))
638 InV = Builder->CreateICmp(CI->getPredicate(), PN->getIncomingValue(i),
639 C, "phitmp");
640 else
641 InV = Builder->CreateFCmp(CI->getPredicate(), PN->getIncomingValue(i),
642 C, "phitmp");
643 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
644 }
Chris Lattner5d1704d2009-09-27 19:57:57 +0000645 } else if (I.getNumOperands() == 2) {
Chris Lattner4e998b22004-09-29 05:07:12 +0000646 Constant *C = cast<Constant>(I.getOperand(1));
Chris Lattnerbac32862004-11-14 19:13:23 +0000647 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattnera9ff5eb2007-08-05 08:47:58 +0000648 Value *InV = 0;
Chris Lattner7dfe8fd2011-01-16 05:08:00 +0000649 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i)))
650 InV = ConstantExpr::get(I.getOpcode(), InC, C);
651 else
652 InV = Builder->CreateBinOp(cast<BinaryOperator>(I).getOpcode(),
653 PN->getIncomingValue(i), C, "phitmp");
Chris Lattner2a86f3b2006-09-09 22:02:56 +0000654 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
Chris Lattner4e998b22004-09-29 05:07:12 +0000655 }
Reid Spencer3da59db2006-11-27 01:05:10 +0000656 } else {
657 CastInst *CI = cast<CastInst>(&I);
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000658 Type *RetTy = CI->getType();
Chris Lattnerbac32862004-11-14 19:13:23 +0000659 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattner2a86f3b2006-09-09 22:02:56 +0000660 Value *InV;
Chris Lattner7dfe8fd2011-01-16 05:08:00 +0000661 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i)))
Owen Andersonbaf3c402009-07-29 18:55:55 +0000662 InV = ConstantExpr::getCast(CI->getOpcode(), InC, RetTy);
Chris Lattner7dfe8fd2011-01-16 05:08:00 +0000663 else
664 InV = Builder->CreateCast(CI->getOpcode(),
665 PN->getIncomingValue(i), I.getType(), "phitmp");
Chris Lattner2a86f3b2006-09-09 22:02:56 +0000666 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
Chris Lattner4e998b22004-09-29 05:07:12 +0000667 }
668 }
Chris Lattner192228e2011-01-16 05:28:59 +0000669
670 for (Value::use_iterator UI = PN->use_begin(), E = PN->use_end();
671 UI != E; ) {
672 Instruction *User = cast<Instruction>(*UI++);
673 if (User == &I) continue;
674 ReplaceInstUsesWith(*User, NewPN);
675 EraseInstFromFunction(*User);
676 }
Chris Lattner4e998b22004-09-29 05:07:12 +0000677 return ReplaceInstUsesWith(I, NewPN);
678}
679
Chris Lattner46cd5a12009-01-09 05:44:56 +0000680/// FindElementAtOffset - Given a type and a constant offset, determine whether
681/// or not there is a sequence of GEP indices into the type that will land us at
Chris Lattner3914f722009-01-24 01:00:13 +0000682/// the specified offset. If so, fill them into NewIndices and return the
683/// resultant element type, otherwise return null.
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000684Type *InstCombiner::FindElementAtOffset(Type *Ty, int64_t Offset,
Chris Lattner80f43d32010-01-04 07:53:58 +0000685 SmallVectorImpl<Value*> &NewIndices) {
Dan Gohmance9fe9f2009-07-21 23:21:54 +0000686 if (!TD) return 0;
Chris Lattner3914f722009-01-24 01:00:13 +0000687 if (!Ty->isSized()) return 0;
Chris Lattner46cd5a12009-01-09 05:44:56 +0000688
689 // Start with the index over the outer type. Note that the type size
690 // might be zero (even if the offset isn't zero) if the indexed type
691 // is something like [0 x {int, int}]
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000692 Type *IntPtrTy = TD->getIntPtrType(Ty->getContext());
Chris Lattner46cd5a12009-01-09 05:44:56 +0000693 int64_t FirstIdx = 0;
Duncan Sands777d2302009-05-09 07:06:46 +0000694 if (int64_t TySize = TD->getTypeAllocSize(Ty)) {
Chris Lattner46cd5a12009-01-09 05:44:56 +0000695 FirstIdx = Offset/TySize;
Chris Lattner31a69cb2009-01-11 20:41:36 +0000696 Offset -= FirstIdx*TySize;
Chris Lattner46cd5a12009-01-09 05:44:56 +0000697
Chris Lattnerdbc3bc22009-01-11 20:15:20 +0000698 // Handle hosts where % returns negative instead of values [0..TySize).
Chris Lattner46cd5a12009-01-09 05:44:56 +0000699 if (Offset < 0) {
700 --FirstIdx;
701 Offset += TySize;
702 assert(Offset >= 0);
703 }
704 assert((uint64_t)Offset < (uint64_t)TySize && "Out of range offset");
705 }
706
Owen Andersoneed707b2009-07-24 23:12:02 +0000707 NewIndices.push_back(ConstantInt::get(IntPtrTy, FirstIdx));
Chris Lattner46cd5a12009-01-09 05:44:56 +0000708
709 // Index into the types. If we fail, set OrigBase to null.
710 while (Offset) {
Chris Lattnerdbc3bc22009-01-11 20:15:20 +0000711 // Indexing into tail padding between struct/array elements.
712 if (uint64_t(Offset*8) >= TD->getTypeSizeInBits(Ty))
Chris Lattner3914f722009-01-24 01:00:13 +0000713 return 0;
Chris Lattnerdbc3bc22009-01-11 20:15:20 +0000714
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000715 if (StructType *STy = dyn_cast<StructType>(Ty)) {
Chris Lattner46cd5a12009-01-09 05:44:56 +0000716 const StructLayout *SL = TD->getStructLayout(STy);
Chris Lattnerdbc3bc22009-01-11 20:15:20 +0000717 assert(Offset < (int64_t)SL->getSizeInBytes() &&
718 "Offset must stay within the indexed type");
719
Chris Lattner46cd5a12009-01-09 05:44:56 +0000720 unsigned Elt = SL->getElementContainingOffset(Offset);
Chris Lattner4de84762010-01-04 07:02:48 +0000721 NewIndices.push_back(ConstantInt::get(Type::getInt32Ty(Ty->getContext()),
722 Elt));
Chris Lattner46cd5a12009-01-09 05:44:56 +0000723
724 Offset -= SL->getElementOffset(Elt);
725 Ty = STy->getElementType(Elt);
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000726 } else if (ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
Duncan Sands777d2302009-05-09 07:06:46 +0000727 uint64_t EltSize = TD->getTypeAllocSize(AT->getElementType());
Chris Lattnerdbc3bc22009-01-11 20:15:20 +0000728 assert(EltSize && "Cannot index into a zero-sized array");
Owen Andersoneed707b2009-07-24 23:12:02 +0000729 NewIndices.push_back(ConstantInt::get(IntPtrTy,Offset/EltSize));
Chris Lattnerdbc3bc22009-01-11 20:15:20 +0000730 Offset %= EltSize;
Chris Lattner1c412d92009-01-11 20:23:52 +0000731 Ty = AT->getElementType();
Chris Lattner46cd5a12009-01-09 05:44:56 +0000732 } else {
Chris Lattnerdbc3bc22009-01-11 20:15:20 +0000733 // Otherwise, we can't index into the middle of this atomic type, bail.
Chris Lattner3914f722009-01-24 01:00:13 +0000734 return 0;
Chris Lattner46cd5a12009-01-09 05:44:56 +0000735 }
736 }
737
Chris Lattner3914f722009-01-24 01:00:13 +0000738 return Ty;
Chris Lattner46cd5a12009-01-09 05:44:56 +0000739}
740
Rafael Espindola592ad6a2011-07-31 04:43:41 +0000741static bool shouldMergeGEPs(GEPOperator &GEP, GEPOperator &Src) {
742 // If this GEP has only 0 indices, it is the same pointer as
743 // Src. If Src is not a trivial GEP too, don't combine
744 // the indices.
745 if (GEP.hasAllZeroIndices() && !Src.hasAllZeroIndices() &&
746 !Src.hasOneUse())
747 return false;
748 return true;
749}
Chris Lattner473945d2002-05-06 18:06:38 +0000750
Chris Lattner7e708292002-06-25 16:13:24 +0000751Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
Chris Lattnerc514c1f2009-11-27 00:29:05 +0000752 SmallVector<Value*, 8> Ops(GEP.op_begin(), GEP.op_end());
753
Jay Foadb9b54eb2011-07-19 15:07:52 +0000754 if (Value *V = SimplifyGEPInst(Ops, TD))
Chris Lattnerc514c1f2009-11-27 00:29:05 +0000755 return ReplaceInstUsesWith(GEP, V);
756
Chris Lattner620ce142004-05-07 22:09:22 +0000757 Value *PtrOp = GEP.getOperand(0);
Chris Lattnerc6bd1952004-02-22 05:25:17 +0000758
Duncan Sandsa63395a2010-11-22 16:32:50 +0000759 // Eliminate unneeded casts for indices, and replace indices which displace
760 // by multiples of a zero size type with zero.
Chris Lattnerccf4b342009-08-30 04:49:01 +0000761 if (TD) {
762 bool MadeChange = false;
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000763 Type *IntPtrTy = TD->getIntPtrType(GEP.getContext());
Duncan Sandsa63395a2010-11-22 16:32:50 +0000764
Chris Lattnerccf4b342009-08-30 04:49:01 +0000765 gep_type_iterator GTI = gep_type_begin(GEP);
766 for (User::op_iterator I = GEP.op_begin() + 1, E = GEP.op_end();
767 I != E; ++I, ++GTI) {
Duncan Sandsa63395a2010-11-22 16:32:50 +0000768 // Skip indices into struct types.
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000769 SequentialType *SeqTy = dyn_cast<SequentialType>(*GTI);
Duncan Sandsa63395a2010-11-22 16:32:50 +0000770 if (!SeqTy) continue;
771
772 // If the element type has zero size then any index over it is equivalent
773 // to an index of zero, so replace it with zero if it is not zero already.
774 if (SeqTy->getElementType()->isSized() &&
775 TD->getTypeAllocSize(SeqTy->getElementType()) == 0)
776 if (!isa<Constant>(*I) || !cast<Constant>(*I)->isNullValue()) {
777 *I = Constant::getNullValue(IntPtrTy);
778 MadeChange = true;
779 }
780
781 if ((*I)->getType() != IntPtrTy) {
782 // If we are using a wider index than needed for this platform, shrink
783 // it to what we need. If narrower, sign-extend it to what we need.
784 // This explicit cast can make subsequent optimizations more obvious.
785 *I = Builder->CreateIntCast(*I, IntPtrTy, true);
786 MadeChange = true;
787 }
Chris Lattner28977af2004-04-05 01:30:19 +0000788 }
Chris Lattnerccf4b342009-08-30 04:49:01 +0000789 if (MadeChange) return &GEP;
Chris Lattnerdb9654e2007-03-25 20:43:09 +0000790 }
Chris Lattner28977af2004-04-05 01:30:19 +0000791
Chris Lattner90ac28c2002-08-02 19:29:35 +0000792 // Combine Indices - If the source pointer to this getelementptr instruction
793 // is a getelementptr instruction, combine the indices of the two
794 // getelementptr instructions into a single instruction.
795 //
Dan Gohmand6aa02d2009-07-28 01:40:03 +0000796 if (GEPOperator *Src = dyn_cast<GEPOperator>(PtrOp)) {
Rafael Espindola592ad6a2011-07-31 04:43:41 +0000797 if (!shouldMergeGEPs(*cast<GEPOperator>(&GEP), *Src))
Rafael Espindolab5a12dd2011-07-11 03:43:47 +0000798 return 0;
799
Chris Lattner620ce142004-05-07 22:09:22 +0000800 // Note that if our source is a gep chain itself that we wait for that
801 // chain to be resolved before we perform this transformation. This
802 // avoids us creating a TON of code in some cases.
Rafael Espindola592ad6a2011-07-31 04:43:41 +0000803 if (GEPOperator *SrcGEP =
804 dyn_cast<GEPOperator>(Src->getOperand(0)))
805 if (SrcGEP->getNumOperands() == 2 && shouldMergeGEPs(*Src, *SrcGEP))
Chris Lattnerf9b91bb2009-08-30 05:08:50 +0000806 return 0; // Wait until our source is folded to completion.
Chris Lattner620ce142004-05-07 22:09:22 +0000807
Chris Lattner72588fc2007-02-15 22:48:32 +0000808 SmallVector<Value*, 8> Indices;
Chris Lattner620ce142004-05-07 22:09:22 +0000809
810 // Find out whether the last index in the source GEP is a sequential idx.
811 bool EndsWithSequential = false;
Chris Lattnerab984842009-08-30 05:30:55 +0000812 for (gep_type_iterator I = gep_type_begin(*Src), E = gep_type_end(*Src);
813 I != E; ++I)
Duncan Sands1df98592010-02-16 11:11:14 +0000814 EndsWithSequential = !(*I)->isStructTy();
Misha Brukmanfd939082005-04-21 23:48:37 +0000815
Chris Lattner90ac28c2002-08-02 19:29:35 +0000816 // Can we combine the two pointer arithmetics offsets?
Chris Lattner620ce142004-05-07 22:09:22 +0000817 if (EndsWithSequential) {
Chris Lattnerdecd0812003-03-05 22:33:14 +0000818 // Replace: gep (gep %P, long B), long A, ...
819 // With: T = long A+B; gep %P, T, ...
820 //
Chris Lattnerf9b91bb2009-08-30 05:08:50 +0000821 Value *Sum;
822 Value *SO1 = Src->getOperand(Src->getNumOperands()-1);
823 Value *GO1 = GEP.getOperand(1);
Owen Andersona7235ea2009-07-31 20:28:14 +0000824 if (SO1 == Constant::getNullValue(SO1->getType())) {
Chris Lattner28977af2004-04-05 01:30:19 +0000825 Sum = GO1;
Owen Andersona7235ea2009-07-31 20:28:14 +0000826 } else if (GO1 == Constant::getNullValue(GO1->getType())) {
Chris Lattner28977af2004-04-05 01:30:19 +0000827 Sum = SO1;
828 } else {
Chris Lattnerab984842009-08-30 05:30:55 +0000829 // If they aren't the same type, then the input hasn't been processed
830 // by the loop above yet (which canonicalizes sequential index types to
831 // intptr_t). Just avoid transforming this until the input has been
832 // normalized.
833 if (SO1->getType() != GO1->getType())
834 return 0;
Chris Lattnerf925cbd2009-08-30 18:50:58 +0000835 Sum = Builder->CreateAdd(SO1, GO1, PtrOp->getName()+".sum");
Chris Lattner28977af2004-04-05 01:30:19 +0000836 }
Chris Lattner620ce142004-05-07 22:09:22 +0000837
Chris Lattnerab984842009-08-30 05:30:55 +0000838 // Update the GEP in place if possible.
Chris Lattnerf9b91bb2009-08-30 05:08:50 +0000839 if (Src->getNumOperands() == 2) {
840 GEP.setOperand(0, Src->getOperand(0));
Chris Lattner620ce142004-05-07 22:09:22 +0000841 GEP.setOperand(1, Sum);
842 return &GEP;
Chris Lattner620ce142004-05-07 22:09:22 +0000843 }
Chris Lattnerab984842009-08-30 05:30:55 +0000844 Indices.append(Src->op_begin()+1, Src->op_end()-1);
Chris Lattnerccf4b342009-08-30 04:49:01 +0000845 Indices.push_back(Sum);
Chris Lattnerab984842009-08-30 05:30:55 +0000846 Indices.append(GEP.op_begin()+2, GEP.op_end());
Misha Brukmanfd939082005-04-21 23:48:37 +0000847 } else if (isa<Constant>(*GEP.idx_begin()) &&
Chris Lattner28977af2004-04-05 01:30:19 +0000848 cast<Constant>(*GEP.idx_begin())->isNullValue() &&
Chris Lattnerf9b91bb2009-08-30 05:08:50 +0000849 Src->getNumOperands() != 1) {
Chris Lattner90ac28c2002-08-02 19:29:35 +0000850 // Otherwise we can do the fold if the first index of the GEP is a zero
Chris Lattnerab984842009-08-30 05:30:55 +0000851 Indices.append(Src->op_begin()+1, Src->op_end());
852 Indices.append(GEP.idx_begin()+1, GEP.idx_end());
Chris Lattner90ac28c2002-08-02 19:29:35 +0000853 }
854
Dan Gohmanf8dbee72009-09-07 23:54:19 +0000855 if (!Indices.empty())
Chris Lattner948cdeb2010-01-05 07:42:10 +0000856 return (GEP.isInBounds() && Src->isInBounds()) ?
Jay Foada9203102011-07-25 09:48:08 +0000857 GetElementPtrInst::CreateInBounds(Src->getOperand(0), Indices,
858 GEP.getName()) :
859 GetElementPtrInst::Create(Src->getOperand(0), Indices, GEP.getName());
Chris Lattner6e24d832009-08-30 05:00:50 +0000860 }
Nadav Rotem0286ca82011-04-05 14:29:52 +0000861
Chris Lattnerf9b91bb2009-08-30 05:08:50 +0000862 // Handle gep(bitcast x) and gep(gep x, 0, 0, 0).
Chris Lattner948cdeb2010-01-05 07:42:10 +0000863 Value *StrippedPtr = PtrOp->stripPointerCasts();
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000864 PointerType *StrippedPtrTy =cast<PointerType>(StrippedPtr->getType());
Nadav Rotem0286ca82011-04-05 14:29:52 +0000865 if (StrippedPtr != PtrOp &&
866 StrippedPtrTy->getAddressSpace() == GEP.getPointerAddressSpace()) {
Chris Lattner963f4ba2009-08-30 20:36:46 +0000867
Chris Lattnerc514c1f2009-11-27 00:29:05 +0000868 bool HasZeroPointerIndex = false;
869 if (ConstantInt *C = dyn_cast<ConstantInt>(GEP.getOperand(1)))
870 HasZeroPointerIndex = C->isZero();
Nadav Rotem0286ca82011-04-05 14:29:52 +0000871
Chris Lattner963f4ba2009-08-30 20:36:46 +0000872 // Transform: GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ...
873 // into : GEP [10 x i8]* X, i32 0, ...
874 //
875 // Likewise, transform: GEP (bitcast i8* X to [0 x i8]*), i32 0, ...
876 // into : GEP i8* X, ...
Nadav Rotem0286ca82011-04-05 14:29:52 +0000877 //
Chris Lattner963f4ba2009-08-30 20:36:46 +0000878 // This occurs when the program declares an array extern like "int X[];"
Chris Lattner6e24d832009-08-30 05:00:50 +0000879 if (HasZeroPointerIndex) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000880 PointerType *CPTy = cast<PointerType>(PtrOp->getType());
881 if (ArrayType *CATy =
Duncan Sands5b7cfb02009-03-02 09:18:21 +0000882 dyn_cast<ArrayType>(CPTy->getElementType())) {
883 // GEP (bitcast i8* X to [0 x i8]*), i32 0, ... ?
Chris Lattner948cdeb2010-01-05 07:42:10 +0000884 if (CATy->getElementType() == StrippedPtrTy->getElementType()) {
Duncan Sands5b7cfb02009-03-02 09:18:21 +0000885 // -> GEP i8* X, ...
Chris Lattner948cdeb2010-01-05 07:42:10 +0000886 SmallVector<Value*, 8> Idx(GEP.idx_begin()+1, GEP.idx_end());
887 GetElementPtrInst *Res =
Jay Foada9203102011-07-25 09:48:08 +0000888 GetElementPtrInst::Create(StrippedPtr, Idx, GEP.getName());
Chris Lattner948cdeb2010-01-05 07:42:10 +0000889 Res->setIsInBounds(GEP.isInBounds());
890 return Res;
Chris Lattner963f4ba2009-08-30 20:36:46 +0000891 }
892
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000893 if (ArrayType *XATy =
Chris Lattner948cdeb2010-01-05 07:42:10 +0000894 dyn_cast<ArrayType>(StrippedPtrTy->getElementType())){
Duncan Sands5b7cfb02009-03-02 09:18:21 +0000895 // GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ... ?
Chris Lattnereed48272005-09-13 00:40:14 +0000896 if (CATy->getElementType() == XATy->getElementType()) {
Duncan Sands5b7cfb02009-03-02 09:18:21 +0000897 // -> GEP [10 x i8]* X, i32 0, ...
Chris Lattnereed48272005-09-13 00:40:14 +0000898 // At this point, we know that the cast source type is a pointer
899 // to an array of the same type as the destination pointer
900 // array. Because the array type is never stepped over (there
901 // is a leading zero) we can fold the cast into this GEP.
Chris Lattner948cdeb2010-01-05 07:42:10 +0000902 GEP.setOperand(0, StrippedPtr);
Chris Lattnereed48272005-09-13 00:40:14 +0000903 return &GEP;
904 }
Duncan Sands5b7cfb02009-03-02 09:18:21 +0000905 }
906 }
Chris Lattnereed48272005-09-13 00:40:14 +0000907 } else if (GEP.getNumOperands() == 2) {
908 // Transform things like:
Wojciech Matyjewiczed223252007-12-12 15:21:32 +0000909 // %t = getelementptr i32* bitcast ([2 x i32]* %str to i32*), i32 %V
910 // into: %t1 = getelementptr [2 x i32]* %str, i32 0, i32 %V; bitcast
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000911 Type *SrcElTy = StrippedPtrTy->getElementType();
912 Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
Duncan Sands1df98592010-02-16 11:11:14 +0000913 if (TD && SrcElTy->isArrayTy() &&
Duncan Sands777d2302009-05-09 07:06:46 +0000914 TD->getTypeAllocSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
915 TD->getTypeAllocSize(ResElTy)) {
David Greeneb8f74792007-09-04 15:46:09 +0000916 Value *Idx[2];
Chris Lattner4de84762010-01-04 07:02:48 +0000917 Idx[0] = Constant::getNullValue(Type::getInt32Ty(GEP.getContext()));
David Greeneb8f74792007-09-04 15:46:09 +0000918 Idx[1] = GEP.getOperand(1);
Chris Lattner948cdeb2010-01-05 07:42:10 +0000919 Value *NewGEP = GEP.isInBounds() ?
Jay Foad0a2a60a2011-07-22 08:16:57 +0000920 Builder->CreateInBoundsGEP(StrippedPtr, Idx, GEP.getName()) :
921 Builder->CreateGEP(StrippedPtr, Idx, GEP.getName());
Reid Spencer3da59db2006-11-27 01:05:10 +0000922 // V and GEP are both pointer types --> BitCast
Chris Lattnerf925cbd2009-08-30 18:50:58 +0000923 return new BitCastInst(NewGEP, GEP.getType());
Chris Lattnerc6bd1952004-02-22 05:25:17 +0000924 }
Chris Lattner7835cdd2005-09-13 18:36:04 +0000925
926 // Transform things like:
Wojciech Matyjewiczed223252007-12-12 15:21:32 +0000927 // getelementptr i8* bitcast ([100 x double]* X to i8*), i32 %tmp
Chris Lattner7835cdd2005-09-13 18:36:04 +0000928 // (where tmp = 8*tmp2) into:
Wojciech Matyjewiczed223252007-12-12 15:21:32 +0000929 // getelementptr [100 x double]* %arr, i32 0, i32 %tmp2; bitcast
Chris Lattner7835cdd2005-09-13 18:36:04 +0000930
Duncan Sands1df98592010-02-16 11:11:14 +0000931 if (TD && SrcElTy->isArrayTy() && ResElTy->isIntegerTy(8)) {
Chris Lattner7835cdd2005-09-13 18:36:04 +0000932 uint64_t ArrayEltSize =
Duncan Sands777d2302009-05-09 07:06:46 +0000933 TD->getTypeAllocSize(cast<ArrayType>(SrcElTy)->getElementType());
Chris Lattner7835cdd2005-09-13 18:36:04 +0000934
935 // Check to see if "tmp" is a scale by a multiple of ArrayEltSize. We
936 // allow either a mul, shift, or constant here.
937 Value *NewIdx = 0;
938 ConstantInt *Scale = 0;
939 if (ArrayEltSize == 1) {
940 NewIdx = GEP.getOperand(1);
Chris Lattnerab984842009-08-30 05:30:55 +0000941 Scale = ConstantInt::get(cast<IntegerType>(NewIdx->getType()), 1);
Chris Lattner7835cdd2005-09-13 18:36:04 +0000942 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) {
Owen Andersoneed707b2009-07-24 23:12:02 +0000943 NewIdx = ConstantInt::get(CI->getType(), 1);
Chris Lattner7835cdd2005-09-13 18:36:04 +0000944 Scale = CI;
945 } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){
946 if (Inst->getOpcode() == Instruction::Shl &&
947 isa<ConstantInt>(Inst->getOperand(1))) {
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +0000948 ConstantInt *ShAmt = cast<ConstantInt>(Inst->getOperand(1));
949 uint32_t ShAmtVal = ShAmt->getLimitedValue(64);
Owen Andersoneed707b2009-07-24 23:12:02 +0000950 Scale = ConstantInt::get(cast<IntegerType>(Inst->getType()),
Dan Gohman6de29f82009-06-15 22:12:54 +0000951 1ULL << ShAmtVal);
Chris Lattner7835cdd2005-09-13 18:36:04 +0000952 NewIdx = Inst->getOperand(0);
953 } else if (Inst->getOpcode() == Instruction::Mul &&
954 isa<ConstantInt>(Inst->getOperand(1))) {
955 Scale = cast<ConstantInt>(Inst->getOperand(1));
956 NewIdx = Inst->getOperand(0);
957 }
958 }
Wojciech Matyjewiczed223252007-12-12 15:21:32 +0000959
Chris Lattner7835cdd2005-09-13 18:36:04 +0000960 // If the index will be to exactly the right offset with the scale taken
Wojciech Matyjewiczed223252007-12-12 15:21:32 +0000961 // out, perform the transformation. Note, we don't know whether Scale is
962 // signed or not. We'll use unsigned version of division/modulo
963 // operation after making sure Scale doesn't have the sign bit set.
Chris Lattner58b1ac72009-02-25 18:20:01 +0000964 if (ArrayEltSize && Scale && Scale->getSExtValue() >= 0LL &&
Wojciech Matyjewiczed223252007-12-12 15:21:32 +0000965 Scale->getZExtValue() % ArrayEltSize == 0) {
Owen Andersoneed707b2009-07-24 23:12:02 +0000966 Scale = ConstantInt::get(Scale->getType(),
Wojciech Matyjewiczed223252007-12-12 15:21:32 +0000967 Scale->getZExtValue() / ArrayEltSize);
Reid Spencerb83eb642006-10-20 07:07:24 +0000968 if (Scale->getZExtValue() != 1) {
Chris Lattner878daed2009-08-30 05:56:44 +0000969 Constant *C = ConstantExpr::getIntegerCast(Scale, NewIdx->getType(),
970 false /*ZExt*/);
Chris Lattnerf925cbd2009-08-30 18:50:58 +0000971 NewIdx = Builder->CreateMul(NewIdx, C, "idxscale");
Chris Lattner7835cdd2005-09-13 18:36:04 +0000972 }
973
974 // Insert the new GEP instruction.
David Greeneb8f74792007-09-04 15:46:09 +0000975 Value *Idx[2];
Chris Lattner4de84762010-01-04 07:02:48 +0000976 Idx[0] = Constant::getNullValue(Type::getInt32Ty(GEP.getContext()));
David Greeneb8f74792007-09-04 15:46:09 +0000977 Idx[1] = NewIdx;
Chris Lattner948cdeb2010-01-05 07:42:10 +0000978 Value *NewGEP = GEP.isInBounds() ?
Jay Foad0a2a60a2011-07-22 08:16:57 +0000979 Builder->CreateInBoundsGEP(StrippedPtr, Idx, GEP.getName()):
980 Builder->CreateGEP(StrippedPtr, Idx, GEP.getName());
Reid Spencer3da59db2006-11-27 01:05:10 +0000981 // The NewGEP must be pointer typed, so must the old one -> BitCast
982 return new BitCastInst(NewGEP, GEP.getType());
Chris Lattner7835cdd2005-09-13 18:36:04 +0000983 }
984 }
Chris Lattnerc6bd1952004-02-22 05:25:17 +0000985 }
Chris Lattner8a2a3112001-12-14 16:52:21 +0000986 }
Nadav Rotem0286ca82011-04-05 14:29:52 +0000987
Chris Lattner46cd5a12009-01-09 05:44:56 +0000988 /// See if we can simplify:
Chris Lattner873ff012009-08-30 05:55:36 +0000989 /// X = bitcast A* to B*
Chris Lattner46cd5a12009-01-09 05:44:56 +0000990 /// Y = gep X, <...constant indices...>
991 /// into a gep of the original struct. This is important for SROA and alias
992 /// analysis of unions. If "A" is also a bitcast, wait for A/X to be merged.
Chris Lattner58407792009-01-09 04:53:57 +0000993 if (BitCastInst *BCI = dyn_cast<BitCastInst>(PtrOp)) {
Dan Gohmance9fe9f2009-07-21 23:21:54 +0000994 if (TD &&
Nadav Rotem0286ca82011-04-05 14:29:52 +0000995 !isa<BitCastInst>(BCI->getOperand(0)) && GEP.hasAllConstantIndices() &&
996 StrippedPtrTy->getAddressSpace() == GEP.getPointerAddressSpace()) {
997
Chris Lattner46cd5a12009-01-09 05:44:56 +0000998 // Determine how much the GEP moves the pointer. We are guaranteed to get
999 // a constant back from EmitGEPOffset.
Chris Lattner02446fc2010-01-04 07:37:31 +00001000 ConstantInt *OffsetV = cast<ConstantInt>(EmitGEPOffset(&GEP));
Chris Lattner46cd5a12009-01-09 05:44:56 +00001001 int64_t Offset = OffsetV->getSExtValue();
Nadav Rotem0286ca82011-04-05 14:29:52 +00001002
Chris Lattner46cd5a12009-01-09 05:44:56 +00001003 // If this GEP instruction doesn't move the pointer, just replace the GEP
1004 // with a bitcast of the real input to the dest type.
1005 if (Offset == 0) {
1006 // If the bitcast is of an allocation, and the allocation will be
1007 // converted to match the type of the cast, don't touch this.
Victor Hernandez7b929da2009-10-23 21:09:37 +00001008 if (isa<AllocaInst>(BCI->getOperand(0)) ||
Victor Hernandez83d63912009-09-18 22:35:49 +00001009 isMalloc(BCI->getOperand(0))) {
Chris Lattner46cd5a12009-01-09 05:44:56 +00001010 // See if the bitcast simplifies, if so, don't nuke this GEP yet.
1011 if (Instruction *I = visitBitCast(*BCI)) {
1012 if (I != BCI) {
1013 I->takeName(BCI);
1014 BCI->getParent()->getInstList().insert(BCI, I);
1015 ReplaceInstUsesWith(*BCI, I);
1016 }
1017 return &GEP;
Chris Lattner58407792009-01-09 04:53:57 +00001018 }
Chris Lattner58407792009-01-09 04:53:57 +00001019 }
Chris Lattner46cd5a12009-01-09 05:44:56 +00001020 return new BitCastInst(BCI->getOperand(0), GEP.getType());
Chris Lattner58407792009-01-09 04:53:57 +00001021 }
Chris Lattner46cd5a12009-01-09 05:44:56 +00001022
1023 // Otherwise, if the offset is non-zero, we need to find out if there is a
1024 // field at Offset in 'A's type. If so, we can pull the cast through the
1025 // GEP.
1026 SmallVector<Value*, 8> NewIndices;
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001027 Type *InTy =
Chris Lattner46cd5a12009-01-09 05:44:56 +00001028 cast<PointerType>(BCI->getOperand(0)->getType())->getElementType();
Chris Lattner80f43d32010-01-04 07:53:58 +00001029 if (FindElementAtOffset(InTy, Offset, NewIndices)) {
Chris Lattner948cdeb2010-01-05 07:42:10 +00001030 Value *NGEP = GEP.isInBounds() ?
Jay Foad0a2a60a2011-07-22 08:16:57 +00001031 Builder->CreateInBoundsGEP(BCI->getOperand(0), NewIndices) :
1032 Builder->CreateGEP(BCI->getOperand(0), NewIndices);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00001033
1034 if (NGEP->getType() == GEP.getType())
1035 return ReplaceInstUsesWith(GEP, NGEP);
Chris Lattner46cd5a12009-01-09 05:44:56 +00001036 NGEP->takeName(&GEP);
1037 return new BitCastInst(NGEP, GEP.getType());
1038 }
Chris Lattner58407792009-01-09 04:53:57 +00001039 }
1040 }
1041
Chris Lattner8a2a3112001-12-14 16:52:21 +00001042 return 0;
1043}
1044
Duncan Sands1d9b9732010-05-27 19:09:06 +00001045
1046
Nick Lewyckydbd22552011-08-03 01:11:40 +00001047static bool IsOnlyNullComparedAndFreed(Value *V, SmallVectorImpl<WeakVH> &Users,
Nick Lewyckyd5061a92011-08-03 00:43:35 +00001048 int Depth = 0) {
Nick Lewyckyd8030c72011-08-02 22:08:01 +00001049 if (Depth == 8)
1050 return false;
1051
Nick Lewyckyd5061a92011-08-03 00:43:35 +00001052 for (Value::use_iterator UI = V->use_begin(), UE = V->use_end();
Duncan Sands1d9b9732010-05-27 19:09:06 +00001053 UI != UE; ++UI) {
Nick Lewyckyd5061a92011-08-03 00:43:35 +00001054 User *U = *UI;
1055 if (isFreeCall(U)) {
1056 Users.push_back(U);
Duncan Sands1d9b9732010-05-27 19:09:06 +00001057 continue;
Nick Lewyckyd8030c72011-08-02 22:08:01 +00001058 }
Nick Lewyckyd5061a92011-08-03 00:43:35 +00001059 if (ICmpInst *ICI = dyn_cast<ICmpInst>(U)) {
1060 if (ICI->isEquality() && isa<ConstantPointerNull>(ICI->getOperand(1))) {
1061 Users.push_back(ICI);
1062 continue;
1063 }
1064 }
1065 if (BitCastInst *BCI = dyn_cast<BitCastInst>(U)) {
1066 if (IsOnlyNullComparedAndFreed(BCI, Users, Depth+1)) {
1067 Users.push_back(BCI);
1068 continue;
1069 }
1070 }
1071 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(U)) {
Nick Lewyckydbd22552011-08-03 01:11:40 +00001072 if (IsOnlyNullComparedAndFreed(GEPI, Users, Depth+1)) {
Nick Lewyckyd5061a92011-08-03 00:43:35 +00001073 Users.push_back(GEPI);
Nick Lewyckyd8030c72011-08-02 22:08:01 +00001074 continue;
Nick Lewyckyd5061a92011-08-03 00:43:35 +00001075 }
Nick Lewyckyd8030c72011-08-02 22:08:01 +00001076 }
Nick Lewyckyd5061a92011-08-03 00:43:35 +00001077 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(U)) {
Nick Lewyckyd8030c72011-08-02 22:08:01 +00001078 if (II->getIntrinsicID() == Intrinsic::lifetime_start ||
Nick Lewyckyd5061a92011-08-03 00:43:35 +00001079 II->getIntrinsicID() == Intrinsic::lifetime_end) {
1080 Users.push_back(II);
Nick Lewyckyd8030c72011-08-02 22:08:01 +00001081 continue;
Nick Lewyckyd5061a92011-08-03 00:43:35 +00001082 }
Nick Lewyckyd8030c72011-08-02 22:08:01 +00001083 }
Duncan Sands1d9b9732010-05-27 19:09:06 +00001084 return false;
1085 }
1086 return true;
1087}
1088
1089Instruction *InstCombiner::visitMalloc(Instruction &MI) {
1090 // If we have a malloc call which is only used in any amount of comparisons
1091 // to null and free calls, delete the calls and replace the comparisons with
1092 // true or false as appropriate.
Nick Lewyckyd5061a92011-08-03 00:43:35 +00001093 SmallVector<WeakVH, 64> Users;
1094 if (IsOnlyNullComparedAndFreed(&MI, Users)) {
1095 for (unsigned i = 0, e = Users.size(); i != e; ++i) {
1096 Instruction *I = cast_or_null<Instruction>(&*Users[i]);
1097 if (!I) continue;
Duncan Sands1d9b9732010-05-27 19:09:06 +00001098
Nick Lewyckyd5061a92011-08-03 00:43:35 +00001099 if (ICmpInst *C = dyn_cast<ICmpInst>(I)) {
Nick Lewyckyd8030c72011-08-02 22:08:01 +00001100 ReplaceInstUsesWith(*C,
1101 ConstantInt::get(Type::getInt1Ty(C->getContext()),
1102 C->isFalseWhenEqual()));
Nick Lewyckyd5061a92011-08-03 00:43:35 +00001103 } else if (isa<BitCastInst>(I) || isa<GetElementPtrInst>(I)) {
Nick Lewyckyd8030c72011-08-02 22:08:01 +00001104 ReplaceInstUsesWith(*I, UndefValue::get(I->getType()));
Duncan Sands1d9b9732010-05-27 19:09:06 +00001105 }
Nick Lewyckyd5061a92011-08-03 00:43:35 +00001106 EraseInstFromFunction(*I);
Duncan Sands1d9b9732010-05-27 19:09:06 +00001107 }
1108 return EraseInstFromFunction(MI);
1109 }
1110 return 0;
1111}
1112
1113
1114
Gabor Greif91697372010-06-24 12:21:15 +00001115Instruction *InstCombiner::visitFree(CallInst &FI) {
1116 Value *Op = FI.getArgOperand(0);
Victor Hernandez66284e02009-10-24 04:23:03 +00001117
1118 // free undef -> unreachable.
1119 if (isa<UndefValue>(Op)) {
1120 // Insert a new store to null because we cannot modify the CFG here.
Eli Friedmane6f364b2011-05-18 23:58:37 +00001121 Builder->CreateStore(ConstantInt::getTrue(FI.getContext()),
1122 UndefValue::get(Type::getInt1PtrTy(FI.getContext())));
Victor Hernandez66284e02009-10-24 04:23:03 +00001123 return EraseInstFromFunction(FI);
1124 }
1125
1126 // If we have 'free null' delete the instruction. This can happen in stl code
1127 // when lots of inlining happens.
1128 if (isa<ConstantPointerNull>(Op))
1129 return EraseInstFromFunction(FI);
1130
Victor Hernandez66284e02009-10-24 04:23:03 +00001131 return 0;
1132}
Chris Lattner67b1e1b2003-12-07 01:24:23 +00001133
Chris Lattner3284d1f2007-04-15 00:07:55 +00001134
Chris Lattner2f503e62005-01-31 05:36:43 +00001135
Chris Lattnerc4d10eb2003-06-04 04:46:00 +00001136Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
1137 // Change br (not X), label True, label False to: br X, label False, True
Reid Spencer4b828e62005-06-18 17:37:34 +00001138 Value *X = 0;
Chris Lattneracd1f0f2004-07-30 07:50:03 +00001139 BasicBlock *TrueDest;
1140 BasicBlock *FalseDest;
Dan Gohman4ae51262009-08-12 16:23:25 +00001141 if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
Chris Lattneracd1f0f2004-07-30 07:50:03 +00001142 !isa<Constant>(X)) {
1143 // Swap Destinations and condition...
1144 BI.setCondition(X);
1145 BI.setSuccessor(0, FalseDest);
1146 BI.setSuccessor(1, TrueDest);
1147 return &BI;
1148 }
1149
Reid Spencere4d87aa2006-12-23 06:05:41 +00001150 // Cannonicalize fcmp_one -> fcmp_oeq
1151 FCmpInst::Predicate FPred; Value *Y;
1152 if (match(&BI, m_Br(m_FCmp(FPred, m_Value(X), m_Value(Y)),
Chris Lattner7a1e9242009-08-30 06:13:40 +00001153 TrueDest, FalseDest)) &&
1154 BI.getCondition()->hasOneUse())
1155 if (FPred == FCmpInst::FCMP_ONE || FPred == FCmpInst::FCMP_OLE ||
1156 FPred == FCmpInst::FCMP_OGE) {
1157 FCmpInst *Cond = cast<FCmpInst>(BI.getCondition());
1158 Cond->setPredicate(FCmpInst::getInversePredicate(FPred));
1159
1160 // Swap Destinations and condition.
Reid Spencere4d87aa2006-12-23 06:05:41 +00001161 BI.setSuccessor(0, FalseDest);
1162 BI.setSuccessor(1, TrueDest);
Chris Lattner7a1e9242009-08-30 06:13:40 +00001163 Worklist.Add(Cond);
Reid Spencere4d87aa2006-12-23 06:05:41 +00001164 return &BI;
1165 }
1166
1167 // Cannonicalize icmp_ne -> icmp_eq
1168 ICmpInst::Predicate IPred;
1169 if (match(&BI, m_Br(m_ICmp(IPred, m_Value(X), m_Value(Y)),
Chris Lattner7a1e9242009-08-30 06:13:40 +00001170 TrueDest, FalseDest)) &&
1171 BI.getCondition()->hasOneUse())
1172 if (IPred == ICmpInst::ICMP_NE || IPred == ICmpInst::ICMP_ULE ||
1173 IPred == ICmpInst::ICMP_SLE || IPred == ICmpInst::ICMP_UGE ||
1174 IPred == ICmpInst::ICMP_SGE) {
1175 ICmpInst *Cond = cast<ICmpInst>(BI.getCondition());
1176 Cond->setPredicate(ICmpInst::getInversePredicate(IPred));
1177 // Swap Destinations and condition.
Chris Lattner40f5d702003-06-04 05:10:11 +00001178 BI.setSuccessor(0, FalseDest);
1179 BI.setSuccessor(1, TrueDest);
Chris Lattner7a1e9242009-08-30 06:13:40 +00001180 Worklist.Add(Cond);
Chris Lattner40f5d702003-06-04 05:10:11 +00001181 return &BI;
1182 }
Misha Brukmanfd939082005-04-21 23:48:37 +00001183
Chris Lattnerc4d10eb2003-06-04 04:46:00 +00001184 return 0;
1185}
Chris Lattner0864acf2002-11-04 16:18:53 +00001186
Chris Lattner46238a62004-07-03 00:26:11 +00001187Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
1188 Value *Cond = SI.getCondition();
1189 if (Instruction *I = dyn_cast<Instruction>(Cond)) {
1190 if (I->getOpcode() == Instruction::Add)
1191 if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
1192 // change 'switch (X+4) case 1:' into 'switch (X) case -3'
1193 for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
Owen Andersond672ecb2009-07-03 00:17:18 +00001194 SI.setOperand(i,
Owen Andersonbaf3c402009-07-29 18:55:55 +00001195 ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)),
Chris Lattner46238a62004-07-03 00:26:11 +00001196 AddRHS));
1197 SI.setOperand(0, I->getOperand(0));
Chris Lattner7a1e9242009-08-30 06:13:40 +00001198 Worklist.Add(I);
Chris Lattner46238a62004-07-03 00:26:11 +00001199 return &SI;
1200 }
1201 }
1202 return 0;
1203}
1204
Matthijs Kooijmana9012ec2008-06-11 14:05:05 +00001205Instruction *InstCombiner::visitExtractValueInst(ExtractValueInst &EV) {
Matthijs Kooijman780ae5e2008-07-16 12:55:45 +00001206 Value *Agg = EV.getAggregateOperand();
Matthijs Kooijmana9012ec2008-06-11 14:05:05 +00001207
Matthijs Kooijman780ae5e2008-07-16 12:55:45 +00001208 if (!EV.hasIndices())
1209 return ReplaceInstUsesWith(EV, Agg);
1210
1211 if (Constant *C = dyn_cast<Constant>(Agg)) {
1212 if (isa<UndefValue>(C))
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001213 return ReplaceInstUsesWith(EV, UndefValue::get(EV.getType()));
Matthijs Kooijman780ae5e2008-07-16 12:55:45 +00001214
1215 if (isa<ConstantAggregateZero>(C))
Owen Andersona7235ea2009-07-31 20:28:14 +00001216 return ReplaceInstUsesWith(EV, Constant::getNullValue(EV.getType()));
Matthijs Kooijman780ae5e2008-07-16 12:55:45 +00001217
1218 if (isa<ConstantArray>(C) || isa<ConstantStruct>(C)) {
1219 // Extract the element indexed by the first index out of the constant
1220 Value *V = C->getOperand(*EV.idx_begin());
1221 if (EV.getNumIndices() > 1)
1222 // Extract the remaining indices out of the constant indexed by the
1223 // first index
Jay Foadfc6d3a42011-07-13 10:26:04 +00001224 return ExtractValueInst::Create(V, EV.getIndices().slice(1));
Matthijs Kooijman780ae5e2008-07-16 12:55:45 +00001225 else
1226 return ReplaceInstUsesWith(EV, V);
1227 }
1228 return 0; // Can't handle other constants
1229 }
1230 if (InsertValueInst *IV = dyn_cast<InsertValueInst>(Agg)) {
1231 // We're extracting from an insertvalue instruction, compare the indices
1232 const unsigned *exti, *exte, *insi, *inse;
1233 for (exti = EV.idx_begin(), insi = IV->idx_begin(),
1234 exte = EV.idx_end(), inse = IV->idx_end();
1235 exti != exte && insi != inse;
1236 ++exti, ++insi) {
1237 if (*insi != *exti)
1238 // The insert and extract both reference distinctly different elements.
1239 // This means the extract is not influenced by the insert, and we can
1240 // replace the aggregate operand of the extract with the aggregate
1241 // operand of the insert. i.e., replace
1242 // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
1243 // %E = extractvalue { i32, { i32 } } %I, 0
1244 // with
1245 // %E = extractvalue { i32, { i32 } } %A, 0
1246 return ExtractValueInst::Create(IV->getAggregateOperand(),
Jay Foadfc6d3a42011-07-13 10:26:04 +00001247 EV.getIndices());
Matthijs Kooijman780ae5e2008-07-16 12:55:45 +00001248 }
1249 if (exti == exte && insi == inse)
1250 // Both iterators are at the end: Index lists are identical. Replace
1251 // %B = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
1252 // %C = extractvalue { i32, { i32 } } %B, 1, 0
1253 // with "i32 42"
1254 return ReplaceInstUsesWith(EV, IV->getInsertedValueOperand());
1255 if (exti == exte) {
1256 // The extract list is a prefix of the insert list. i.e. replace
1257 // %I = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
1258 // %E = extractvalue { i32, { i32 } } %I, 1
1259 // with
1260 // %X = extractvalue { i32, { i32 } } %A, 1
1261 // %E = insertvalue { i32 } %X, i32 42, 0
1262 // by switching the order of the insert and extract (though the
1263 // insertvalue should be left in, since it may have other uses).
Chris Lattnerf925cbd2009-08-30 18:50:58 +00001264 Value *NewEV = Builder->CreateExtractValue(IV->getAggregateOperand(),
Jay Foadfc6d3a42011-07-13 10:26:04 +00001265 EV.getIndices());
Matthijs Kooijman780ae5e2008-07-16 12:55:45 +00001266 return InsertValueInst::Create(NewEV, IV->getInsertedValueOperand(),
Frits van Bommel39b5abf2011-07-18 12:00:32 +00001267 makeArrayRef(insi, inse));
Matthijs Kooijman780ae5e2008-07-16 12:55:45 +00001268 }
1269 if (insi == inse)
1270 // The insert list is a prefix of the extract list
1271 // We can simply remove the common indices from the extract and make it
1272 // operate on the inserted value instead of the insertvalue result.
1273 // i.e., replace
1274 // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
1275 // %E = extractvalue { i32, { i32 } } %I, 1, 0
1276 // with
1277 // %E extractvalue { i32 } { i32 42 }, 0
1278 return ExtractValueInst::Create(IV->getInsertedValueOperand(),
Frits van Bommel39b5abf2011-07-18 12:00:32 +00001279 makeArrayRef(exti, exte));
Matthijs Kooijman780ae5e2008-07-16 12:55:45 +00001280 }
Chris Lattner7e606e22009-11-09 07:07:56 +00001281 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(Agg)) {
1282 // We're extracting from an intrinsic, see if we're the only user, which
1283 // allows us to simplify multiple result intrinsics to simpler things that
Gabor Greif91697372010-06-24 12:21:15 +00001284 // just get one value.
Chris Lattner7e606e22009-11-09 07:07:56 +00001285 if (II->hasOneUse()) {
1286 // Check if we're grabbing the overflow bit or the result of a 'with
1287 // overflow' intrinsic. If it's the latter we can remove the intrinsic
1288 // and replace it with a traditional binary instruction.
1289 switch (II->getIntrinsicID()) {
1290 case Intrinsic::uadd_with_overflow:
1291 case Intrinsic::sadd_with_overflow:
1292 if (*EV.idx_begin() == 0) { // Normal result.
Gabor Greif91697372010-06-24 12:21:15 +00001293 Value *LHS = II->getArgOperand(0), *RHS = II->getArgOperand(1);
Eli Friedman3e22cb92011-05-18 00:32:01 +00001294 ReplaceInstUsesWith(*II, UndefValue::get(II->getType()));
Chris Lattner7e606e22009-11-09 07:07:56 +00001295 EraseInstFromFunction(*II);
1296 return BinaryOperator::CreateAdd(LHS, RHS);
1297 }
Chris Lattner74b64612010-12-19 19:43:52 +00001298
1299 // If the normal result of the add is dead, and the RHS is a constant,
1300 // we can transform this into a range comparison.
1301 // overflow = uadd a, -4 --> overflow = icmp ugt a, 3
Chris Lattnerf2a97ed2010-12-19 23:24:04 +00001302 if (II->getIntrinsicID() == Intrinsic::uadd_with_overflow)
1303 if (ConstantInt *CI = dyn_cast<ConstantInt>(II->getArgOperand(1)))
1304 return new ICmpInst(ICmpInst::ICMP_UGT, II->getArgOperand(0),
1305 ConstantExpr::getNot(CI));
Chris Lattner7e606e22009-11-09 07:07:56 +00001306 break;
1307 case Intrinsic::usub_with_overflow:
1308 case Intrinsic::ssub_with_overflow:
1309 if (*EV.idx_begin() == 0) { // Normal result.
Gabor Greif91697372010-06-24 12:21:15 +00001310 Value *LHS = II->getArgOperand(0), *RHS = II->getArgOperand(1);
Eli Friedman3e22cb92011-05-18 00:32:01 +00001311 ReplaceInstUsesWith(*II, UndefValue::get(II->getType()));
Chris Lattner7e606e22009-11-09 07:07:56 +00001312 EraseInstFromFunction(*II);
1313 return BinaryOperator::CreateSub(LHS, RHS);
1314 }
1315 break;
1316 case Intrinsic::umul_with_overflow:
1317 case Intrinsic::smul_with_overflow:
1318 if (*EV.idx_begin() == 0) { // Normal result.
Gabor Greif91697372010-06-24 12:21:15 +00001319 Value *LHS = II->getArgOperand(0), *RHS = II->getArgOperand(1);
Eli Friedman3e22cb92011-05-18 00:32:01 +00001320 ReplaceInstUsesWith(*II, UndefValue::get(II->getType()));
Chris Lattner7e606e22009-11-09 07:07:56 +00001321 EraseInstFromFunction(*II);
1322 return BinaryOperator::CreateMul(LHS, RHS);
1323 }
1324 break;
1325 default:
1326 break;
1327 }
1328 }
1329 }
Frits van Bommel34ceb4d2010-11-29 21:56:20 +00001330 if (LoadInst *L = dyn_cast<LoadInst>(Agg))
1331 // If the (non-volatile) load only has one use, we can rewrite this to a
1332 // load from a GEP. This reduces the size of the load.
1333 // FIXME: If a load is used only by extractvalue instructions then this
1334 // could be done regardless of having multiple uses.
1335 if (!L->isVolatile() && L->hasOneUse()) {
1336 // extractvalue has integer indices, getelementptr has Value*s. Convert.
1337 SmallVector<Value*, 4> Indices;
1338 // Prefix an i32 0 since we need the first element.
1339 Indices.push_back(Builder->getInt32(0));
1340 for (ExtractValueInst::idx_iterator I = EV.idx_begin(), E = EV.idx_end();
1341 I != E; ++I)
1342 Indices.push_back(Builder->getInt32(*I));
1343
1344 // We need to insert these at the location of the old load, not at that of
1345 // the extractvalue.
1346 Builder->SetInsertPoint(L->getParent(), L);
Jay Foad0a2a60a2011-07-22 08:16:57 +00001347 Value *GEP = Builder->CreateInBoundsGEP(L->getPointerOperand(), Indices);
Frits van Bommel34ceb4d2010-11-29 21:56:20 +00001348 // Returning the load directly will cause the main loop to insert it in
1349 // the wrong spot, so use ReplaceInstUsesWith().
1350 return ReplaceInstUsesWith(EV, Builder->CreateLoad(GEP));
1351 }
1352 // We could simplify extracts from other values. Note that nested extracts may
1353 // already be simplified implicitly by the above: extract (extract (insert) )
Matthijs Kooijman780ae5e2008-07-16 12:55:45 +00001354 // will be translated into extract ( insert ( extract ) ) first and then just
Frits van Bommel34ceb4d2010-11-29 21:56:20 +00001355 // the value inserted, if appropriate. Similarly for extracts from single-use
1356 // loads: extract (extract (load)) will be translated to extract (load (gep))
1357 // and if again single-use then via load (gep (gep)) to load (gep).
1358 // However, double extracts from e.g. function arguments or return values
1359 // aren't handled yet.
Matthijs Kooijmana9012ec2008-06-11 14:05:05 +00001360 return 0;
1361}
1362
Chris Lattnera844fc4c2006-04-10 22:45:52 +00001363
Robert Bocchino1d7456d2006-01-13 22:48:06 +00001364
Chris Lattnerea1c4542004-12-08 23:43:58 +00001365
1366/// TryToSinkInstruction - Try to move the specified instruction from its
1367/// current block into the beginning of DestBlock, which can only happen if it's
1368/// safe to move the instruction past all of the instructions between it and the
1369/// end of its block.
1370static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
1371 assert(I->hasOneUse() && "Invariants didn't hold!");
1372
Chris Lattner108e9022005-10-27 17:13:11 +00001373 // Cannot move control-flow-involving, volatile loads, vaarg, etc.
Duncan Sands7af1c782009-05-06 06:49:50 +00001374 if (isa<PHINode>(I) || I->mayHaveSideEffects() || isa<TerminatorInst>(I))
Chris Lattnerbfc538c2008-05-09 15:07:33 +00001375 return false;
Misha Brukmanfd939082005-04-21 23:48:37 +00001376
Chris Lattnerea1c4542004-12-08 23:43:58 +00001377 // Do not sink alloca instructions out of the entry block.
Dan Gohmanecb7a772007-03-22 16:38:57 +00001378 if (isa<AllocaInst>(I) && I->getParent() ==
1379 &DestBlock->getParent()->getEntryBlock())
Chris Lattnerea1c4542004-12-08 23:43:58 +00001380 return false;
1381
Chris Lattner96a52a62004-12-09 07:14:34 +00001382 // We can only sink load instructions if there is nothing between the load and
1383 // the end of block that could change the value.
Chris Lattner2539e332008-05-08 17:37:37 +00001384 if (I->mayReadFromMemory()) {
1385 for (BasicBlock::iterator Scan = I, E = I->getParent()->end();
Chris Lattner96a52a62004-12-09 07:14:34 +00001386 Scan != E; ++Scan)
1387 if (Scan->mayWriteToMemory())
1388 return false;
Chris Lattner96a52a62004-12-09 07:14:34 +00001389 }
Chris Lattnerea1c4542004-12-08 23:43:58 +00001390
Dan Gohman02dea8b2008-05-23 21:05:58 +00001391 BasicBlock::iterator InsertPos = DestBlock->getFirstNonPHI();
Chris Lattnerea1c4542004-12-08 23:43:58 +00001392
Chris Lattner4bc5f802005-08-08 19:11:57 +00001393 I->moveBefore(InsertPos);
Chris Lattnerea1c4542004-12-08 23:43:58 +00001394 ++NumSunkInst;
1395 return true;
1396}
1397
Chris Lattnerf4f5a772006-05-10 19:00:36 +00001398
1399/// AddReachableCodeToWorklist - Walk the function in depth-first order, adding
1400/// all reachable code to the worklist.
1401///
1402/// This has a couple of tricks to make the code faster and more powerful. In
1403/// particular, we constant fold and DCE instructions as we go, to avoid adding
1404/// them to the worklist (this significantly speeds up instcombine on code where
1405/// many instructions are dead or constant). Additionally, if we find a branch
1406/// whose condition is a known constant, we only visit the reachable successors.
1407///
Chris Lattner2ee743b2009-10-15 04:59:28 +00001408static bool AddReachableCodeToWorklist(BasicBlock *BB,
Chris Lattner1f87a582007-02-15 19:41:52 +00001409 SmallPtrSet<BasicBlock*, 64> &Visited,
Chris Lattnerdbab3862007-03-02 21:28:56 +00001410 InstCombiner &IC,
Chris Lattner8c8c66a2006-05-11 17:11:52 +00001411 const TargetData *TD) {
Chris Lattner2ee743b2009-10-15 04:59:28 +00001412 bool MadeIRChange = false;
Chris Lattner2806dff2008-08-15 04:03:01 +00001413 SmallVector<BasicBlock*, 256> Worklist;
Chris Lattner2c7718a2007-03-23 19:17:18 +00001414 Worklist.push_back(BB);
Chris Lattnerf4f5a772006-05-10 19:00:36 +00001415
Benjamin Kramera53fe602010-10-23 17:10:24 +00001416 SmallVector<Instruction*, 128> InstrsForInstCombineWorklist;
Eli Friedmana4d4aeb2011-05-24 18:52:07 +00001417 DenseMap<ConstantExpr*, Constant*> FoldedConstants;
1418
Dan Gohman321a8132010-01-05 16:27:25 +00001419 do {
1420 BB = Worklist.pop_back_val();
Chris Lattner2c7718a2007-03-23 19:17:18 +00001421
1422 // We have now visited this block! If we've already been here, ignore it.
1423 if (!Visited.insert(BB)) continue;
Devang Patel7fe1dec2008-11-19 18:56:50 +00001424
Chris Lattner2c7718a2007-03-23 19:17:18 +00001425 for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
1426 Instruction *Inst = BBI++;
Chris Lattnerf4f5a772006-05-10 19:00:36 +00001427
Chris Lattner2c7718a2007-03-23 19:17:18 +00001428 // DCE instruction if trivially dead.
1429 if (isInstructionTriviallyDead(Inst)) {
1430 ++NumDeadInst;
Chris Lattnerbdff5482009-08-23 04:37:46 +00001431 DEBUG(errs() << "IC: DCE: " << *Inst << '\n');
Chris Lattner2c7718a2007-03-23 19:17:18 +00001432 Inst->eraseFromParent();
1433 continue;
1434 }
1435
1436 // ConstantProp instruction if trivially constant.
Chris Lattnere2cc1ad2009-10-15 04:13:44 +00001437 if (!Inst->use_empty() && isa<Constant>(Inst->getOperand(0)))
Chris Lattner7b550cc2009-11-06 04:27:31 +00001438 if (Constant *C = ConstantFoldInstruction(Inst, TD)) {
Chris Lattnere2cc1ad2009-10-15 04:13:44 +00001439 DEBUG(errs() << "IC: ConstFold to: " << *C << " from: "
1440 << *Inst << '\n');
1441 Inst->replaceAllUsesWith(C);
1442 ++NumConstProp;
1443 Inst->eraseFromParent();
1444 continue;
1445 }
Chris Lattner2ee743b2009-10-15 04:59:28 +00001446
Chris Lattner2ee743b2009-10-15 04:59:28 +00001447 if (TD) {
1448 // See if we can constant fold its operands.
1449 for (User::op_iterator i = Inst->op_begin(), e = Inst->op_end();
1450 i != e; ++i) {
1451 ConstantExpr *CE = dyn_cast<ConstantExpr>(i);
1452 if (CE == 0) continue;
Eli Friedmana4d4aeb2011-05-24 18:52:07 +00001453
1454 Constant*& FoldRes = FoldedConstants[CE];
1455 if (!FoldRes)
1456 FoldRes = ConstantFoldConstantExpression(CE, TD);
1457 if (!FoldRes)
1458 FoldRes = CE;
1459
1460 if (FoldRes != CE) {
1461 *i = FoldRes;
Chris Lattner2ee743b2009-10-15 04:59:28 +00001462 MadeIRChange = true;
1463 }
1464 }
1465 }
Devang Patel7fe1dec2008-11-19 18:56:50 +00001466
Chris Lattner67f7d542009-10-12 03:58:40 +00001467 InstrsForInstCombineWorklist.push_back(Inst);
Chris Lattnerf4f5a772006-05-10 19:00:36 +00001468 }
Chris Lattner2c7718a2007-03-23 19:17:18 +00001469
1470 // Recursively visit successors. If this is a branch or switch on a
1471 // constant, only visit the reachable successor.
1472 TerminatorInst *TI = BB->getTerminator();
1473 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
1474 if (BI->isConditional() && isa<ConstantInt>(BI->getCondition())) {
1475 bool CondVal = cast<ConstantInt>(BI->getCondition())->getZExtValue();
Nick Lewycky91436992008-03-09 08:50:23 +00001476 BasicBlock *ReachableBB = BI->getSuccessor(!CondVal);
Nick Lewycky280a6e62008-04-25 16:53:59 +00001477 Worklist.push_back(ReachableBB);
Chris Lattner2c7718a2007-03-23 19:17:18 +00001478 continue;
1479 }
1480 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
1481 if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
1482 // See if this is an explicit destination.
1483 for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
1484 if (SI->getCaseValue(i) == Cond) {
Nick Lewycky91436992008-03-09 08:50:23 +00001485 BasicBlock *ReachableBB = SI->getSuccessor(i);
Nick Lewycky280a6e62008-04-25 16:53:59 +00001486 Worklist.push_back(ReachableBB);
Chris Lattner2c7718a2007-03-23 19:17:18 +00001487 continue;
1488 }
1489
1490 // Otherwise it is the default destination.
1491 Worklist.push_back(SI->getSuccessor(0));
1492 continue;
1493 }
1494 }
1495
1496 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
1497 Worklist.push_back(TI->getSuccessor(i));
Dan Gohman321a8132010-01-05 16:27:25 +00001498 } while (!Worklist.empty());
Chris Lattner67f7d542009-10-12 03:58:40 +00001499
1500 // Once we've found all of the instructions to add to instcombine's worklist,
1501 // add them in reverse order. This way instcombine will visit from the top
1502 // of the function down. This jives well with the way that it adds all uses
1503 // of instructions to the worklist after doing a transformation, thus avoiding
1504 // some N^2 behavior in pathological cases.
1505 IC.Worklist.AddInitialGroup(&InstrsForInstCombineWorklist[0],
1506 InstrsForInstCombineWorklist.size());
Chris Lattner2ee743b2009-10-15 04:59:28 +00001507
1508 return MadeIRChange;
Chris Lattnerf4f5a772006-05-10 19:00:36 +00001509}
1510
Chris Lattnerec9c3582007-03-03 02:04:50 +00001511bool InstCombiner::DoOneIteration(Function &F, unsigned Iteration) {
Chris Lattnerb0b822c2009-08-31 06:57:37 +00001512 MadeIRChange = false;
Chris Lattnerec9c3582007-03-03 02:04:50 +00001513
Daniel Dunbarce63ffb2009-07-25 00:23:56 +00001514 DEBUG(errs() << "\n\nINSTCOMBINE ITERATION #" << Iteration << " on "
1515 << F.getNameStr() << "\n");
Chris Lattner8a2a3112001-12-14 16:52:21 +00001516
Chris Lattnerb3d59702005-07-07 20:40:38 +00001517 {
Chris Lattnerf4f5a772006-05-10 19:00:36 +00001518 // Do a depth-first traversal of the function, populate the worklist with
1519 // the reachable instructions. Ignore blocks that are not reachable. Keep
1520 // track of which blocks we visit.
Chris Lattner1f87a582007-02-15 19:41:52 +00001521 SmallPtrSet<BasicBlock*, 64> Visited;
Chris Lattner2ee743b2009-10-15 04:59:28 +00001522 MadeIRChange |= AddReachableCodeToWorklist(F.begin(), Visited, *this, TD);
Jeff Cohen00b168892005-07-27 06:12:32 +00001523
Chris Lattnerb3d59702005-07-07 20:40:38 +00001524 // Do a quick scan over the function. If we find any blocks that are
1525 // unreachable, remove any instructions inside of them. This prevents
1526 // the instcombine code from having to deal with some bad special cases.
1527 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
1528 if (!Visited.count(BB)) {
1529 Instruction *Term = BB->getTerminator();
1530 while (Term != BB->begin()) { // Remove instrs bottom-up
1531 BasicBlock::iterator I = Term; --I;
Chris Lattner6ffe5512004-04-27 15:13:33 +00001532
Chris Lattnerbdff5482009-08-23 04:37:46 +00001533 DEBUG(errs() << "IC: DCE: " << *I << '\n');
Dale Johannesenff278b12009-03-10 21:19:49 +00001534 // A debug intrinsic shouldn't force another iteration if we weren't
1535 // going to do one without it.
1536 if (!isa<DbgInfoIntrinsic>(I)) {
1537 ++NumDeadInst;
Chris Lattnerb0b822c2009-08-31 06:57:37 +00001538 MadeIRChange = true;
Dale Johannesenff278b12009-03-10 21:19:49 +00001539 }
Devang Patel228ebd02009-10-13 22:56:32 +00001540
Devang Patel228ebd02009-10-13 22:56:32 +00001541 // If I is not void type then replaceAllUsesWith undef.
1542 // This allows ValueHandlers and custom metadata to adjust itself.
Devang Patel9674d152009-10-14 17:29:00 +00001543 if (!I->getType()->isVoidTy())
Devang Patel228ebd02009-10-13 22:56:32 +00001544 I->replaceAllUsesWith(UndefValue::get(I->getType()));
Chris Lattnerb3d59702005-07-07 20:40:38 +00001545 I->eraseFromParent();
1546 }
1547 }
1548 }
Chris Lattner8a2a3112001-12-14 16:52:21 +00001549
Chris Lattner873ff012009-08-30 05:55:36 +00001550 while (!Worklist.isEmpty()) {
1551 Instruction *I = Worklist.RemoveOne();
Chris Lattnerdbab3862007-03-02 21:28:56 +00001552 if (I == 0) continue; // skip null values.
Chris Lattner8a2a3112001-12-14 16:52:21 +00001553
Chris Lattner8c8c66a2006-05-11 17:11:52 +00001554 // Check to see if we can DCE the instruction.
Chris Lattner62b14df2002-09-02 04:59:56 +00001555 if (isInstructionTriviallyDead(I)) {
Chris Lattnerbdff5482009-08-23 04:37:46 +00001556 DEBUG(errs() << "IC: DCE: " << *I << '\n');
Chris Lattner7a1e9242009-08-30 06:13:40 +00001557 EraseInstFromFunction(*I);
1558 ++NumDeadInst;
Chris Lattnerb0b822c2009-08-31 06:57:37 +00001559 MadeIRChange = true;
Chris Lattner4bb7c022003-10-06 17:11:01 +00001560 continue;
1561 }
Chris Lattner62b14df2002-09-02 04:59:56 +00001562
Chris Lattner8c8c66a2006-05-11 17:11:52 +00001563 // Instruction isn't dead, see if we can constant propagate it.
Chris Lattnere2cc1ad2009-10-15 04:13:44 +00001564 if (!I->use_empty() && isa<Constant>(I->getOperand(0)))
Chris Lattner7b550cc2009-11-06 04:27:31 +00001565 if (Constant *C = ConstantFoldInstruction(I, TD)) {
Chris Lattnere2cc1ad2009-10-15 04:13:44 +00001566 DEBUG(errs() << "IC: ConstFold to: " << *C << " from: " << *I << '\n');
Chris Lattnerad5fec12005-01-28 19:32:01 +00001567
Chris Lattnere2cc1ad2009-10-15 04:13:44 +00001568 // Add operands to the worklist.
1569 ReplaceInstUsesWith(*I, C);
1570 ++NumConstProp;
1571 EraseInstFromFunction(*I);
1572 MadeIRChange = true;
1573 continue;
1574 }
Chris Lattner4bb7c022003-10-06 17:11:01 +00001575
Chris Lattnerea1c4542004-12-08 23:43:58 +00001576 // See if we can trivially sink this instruction to a successor basic block.
Dan Gohmanfc74abf2008-07-23 00:34:11 +00001577 if (I->hasOneUse()) {
Chris Lattnerea1c4542004-12-08 23:43:58 +00001578 BasicBlock *BB = I->getParent();
Chris Lattner8db2cd12009-10-14 15:21:58 +00001579 Instruction *UserInst = cast<Instruction>(I->use_back());
1580 BasicBlock *UserParent;
1581
1582 // Get the block the use occurs in.
1583 if (PHINode *PN = dyn_cast<PHINode>(UserInst))
1584 UserParent = PN->getIncomingBlock(I->use_begin().getUse());
1585 else
1586 UserParent = UserInst->getParent();
1587
Chris Lattnerea1c4542004-12-08 23:43:58 +00001588 if (UserParent != BB) {
1589 bool UserIsSuccessor = false;
1590 // See if the user is one of our successors.
1591 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
1592 if (*SI == UserParent) {
1593 UserIsSuccessor = true;
1594 break;
1595 }
1596
1597 // If the user is one of our immediate successors, and if that successor
1598 // only has us as a predecessors (we'd have to split the critical edge
1599 // otherwise), we can keep going.
Chris Lattner8db2cd12009-10-14 15:21:58 +00001600 if (UserIsSuccessor && UserParent->getSinglePredecessor())
Chris Lattnerea1c4542004-12-08 23:43:58 +00001601 // Okay, the CFG is simple enough, try to sink this instruction.
Chris Lattnerb0b822c2009-08-31 06:57:37 +00001602 MadeIRChange |= TryToSinkInstruction(I, UserParent);
Chris Lattnerea1c4542004-12-08 23:43:58 +00001603 }
1604 }
1605
Chris Lattner74381062009-08-30 07:44:24 +00001606 // Now that we have an instruction, try combining it to simplify it.
1607 Builder->SetInsertPoint(I->getParent(), I);
Eli Friedmanef819d02011-05-18 01:28:27 +00001608 Builder->SetCurrentDebugLocation(I->getDebugLoc());
Chris Lattner74381062009-08-30 07:44:24 +00001609
Reid Spencera9b81012007-03-26 17:44:01 +00001610#ifndef NDEBUG
1611 std::string OrigI;
1612#endif
Chris Lattnerbdff5482009-08-23 04:37:46 +00001613 DEBUG(raw_string_ostream SS(OrigI); I->print(SS); OrigI = SS.str(););
Jeffrey Yasskin43069632009-10-08 00:12:24 +00001614 DEBUG(errs() << "IC: Visiting: " << OrigI << '\n');
1615
Chris Lattner90ac28c2002-08-02 19:29:35 +00001616 if (Instruction *Result = visit(*I)) {
Chris Lattner3dec1f22002-05-10 15:38:35 +00001617 ++NumCombined;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00001618 // Should we replace the old instruction with a new one?
Chris Lattnerb3bc8fa2002-05-14 15:24:07 +00001619 if (Result != I) {
Chris Lattnerbdff5482009-08-23 04:37:46 +00001620 DEBUG(errs() << "IC: Old = " << *I << '\n'
1621 << " New = " << *Result << '\n');
Chris Lattner0cea42a2004-03-13 23:54:27 +00001622
Eli Friedmana311c342011-05-27 00:19:40 +00001623 if (!I->getDebugLoc().isUnknown())
1624 Result->setDebugLoc(I->getDebugLoc());
Chris Lattnerf523d062004-06-09 05:08:07 +00001625 // Everything uses the new instruction now.
1626 I->replaceAllUsesWith(Result);
1627
1628 // Push the new instruction and any users onto the worklist.
Chris Lattner7a1e9242009-08-30 06:13:40 +00001629 Worklist.Add(Result);
Chris Lattnere5ecdb52009-08-30 06:22:51 +00001630 Worklist.AddUsersToWorkList(*Result);
Chris Lattner4bb7c022003-10-06 17:11:01 +00001631
Chris Lattner6934a042007-02-11 01:23:03 +00001632 // Move the name to the new instruction first.
1633 Result->takeName(I);
Chris Lattner4bb7c022003-10-06 17:11:01 +00001634
1635 // Insert the new instruction into the basic block...
1636 BasicBlock *InstParent = I->getParent();
Chris Lattnerbac32862004-11-14 19:13:23 +00001637 BasicBlock::iterator InsertPos = I;
1638
1639 if (!isa<PHINode>(Result)) // If combining a PHI, don't insert
1640 while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
1641 ++InsertPos;
1642
1643 InstParent->getInstList().insert(InsertPos, Result);
Chris Lattner4bb7c022003-10-06 17:11:01 +00001644
Chris Lattner7a1e9242009-08-30 06:13:40 +00001645 EraseInstFromFunction(*I);
Chris Lattner7e708292002-06-25 16:13:24 +00001646 } else {
Evan Chengc7baf682007-03-27 16:44:48 +00001647#ifndef NDEBUG
Chris Lattnerbdff5482009-08-23 04:37:46 +00001648 DEBUG(errs() << "IC: Mod = " << OrigI << '\n'
1649 << " New = " << *I << '\n');
Evan Chengc7baf682007-03-27 16:44:48 +00001650#endif
Chris Lattner0cea42a2004-03-13 23:54:27 +00001651
Chris Lattner90ac28c2002-08-02 19:29:35 +00001652 // If the instruction was modified, it's possible that it is now dead.
1653 // if so, remove it.
Chris Lattner00d51312004-05-01 23:27:23 +00001654 if (isInstructionTriviallyDead(I)) {
Chris Lattner7a1e9242009-08-30 06:13:40 +00001655 EraseInstFromFunction(*I);
Chris Lattnerf523d062004-06-09 05:08:07 +00001656 } else {
Chris Lattner7a1e9242009-08-30 06:13:40 +00001657 Worklist.Add(I);
Chris Lattnere5ecdb52009-08-30 06:22:51 +00001658 Worklist.AddUsersToWorkList(*I);
Chris Lattner90ac28c2002-08-02 19:29:35 +00001659 }
Chris Lattnerb3bc8fa2002-05-14 15:24:07 +00001660 }
Chris Lattnerb0b822c2009-08-31 06:57:37 +00001661 MadeIRChange = true;
Chris Lattner8a2a3112001-12-14 16:52:21 +00001662 }
1663 }
1664
Chris Lattner873ff012009-08-30 05:55:36 +00001665 Worklist.Zap();
Chris Lattnerb0b822c2009-08-31 06:57:37 +00001666 return MadeIRChange;
Chris Lattnerbd0ef772002-02-26 21:46:54 +00001667}
1668
Chris Lattnerec9c3582007-03-03 02:04:50 +00001669
1670bool InstCombiner::runOnFunction(Function &F) {
Chris Lattnere2cc1ad2009-10-15 04:13:44 +00001671 TD = getAnalysisIfAvailable<TargetData>();
1672
Chris Lattner74381062009-08-30 07:44:24 +00001673
1674 /// Builder - This is an IRBuilder that automatically inserts new
1675 /// instructions into the worklist when they are created.
Chris Lattnere2cc1ad2009-10-15 04:13:44 +00001676 IRBuilder<true, TargetFolder, InstCombineIRInserter>
Chris Lattnerf55eeb92009-11-06 05:59:53 +00001677 TheBuilder(F.getContext(), TargetFolder(TD),
Chris Lattner74381062009-08-30 07:44:24 +00001678 InstCombineIRInserter(Worklist));
1679 Builder = &TheBuilder;
1680
Chris Lattnerec9c3582007-03-03 02:04:50 +00001681 bool EverMadeChange = false;
1682
Devang Patel813c9a02011-03-17 22:18:16 +00001683 // Lower dbg.declare intrinsics otherwise their value may be clobbered
1684 // by instcombiner.
1685 EverMadeChange = LowerDbgDeclare(F);
1686
Chris Lattnerec9c3582007-03-03 02:04:50 +00001687 // Iterate while there is work to do.
1688 unsigned Iteration = 0;
Bill Wendlinga6c31122008-05-14 22:45:20 +00001689 while (DoOneIteration(F, Iteration++))
Chris Lattnerec9c3582007-03-03 02:04:50 +00001690 EverMadeChange = true;
Chris Lattner74381062009-08-30 07:44:24 +00001691
1692 Builder = 0;
Chris Lattnerec9c3582007-03-03 02:04:50 +00001693 return EverMadeChange;
1694}
1695
Brian Gaeke96d4bf72004-07-27 17:43:21 +00001696FunctionPass *llvm::createInstructionCombiningPass() {
Chris Lattnerdd841ae2002-04-18 17:39:14 +00001697 return new InstCombiner();
Chris Lattnerbd0ef772002-02-26 21:46:54 +00001698}