blob: 7f8c3ae55812914d8b4bfc8e177820b9b84eedba [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"
Micah Villmow3574eca2012-10-08 16:38:25 +000043#include "llvm/DataLayout.h"
Chad Rosier3d925d22011-11-29 23:57:10 +000044#include "llvm/Target/TargetLibraryInfo.h"
Chris Lattnerbc61e662003-11-02 05:57:39 +000045#include "llvm/Transforms/Utils/Local.h"
Chris Lattner804272c2010-01-05 07:54:43 +000046#include "llvm/Support/CFG.h"
Chris Lattnerea1c4542004-12-08 23:43:58 +000047#include "llvm/Support/Debug.h"
Chris Lattner28977af2004-04-05 01:30:19 +000048#include "llvm/Support/GetElementPtrTypeIterator.h"
Chris Lattneracd1f0f2004-07-30 07:50:03 +000049#include "llvm/Support/PatternMatch.h"
Nick Lewyckyd5061a92011-08-03 00:43:35 +000050#include "llvm/Support/ValueHandle.h"
Chris Lattner1f87a582007-02-15 19:41:52 +000051#include "llvm/ADT/SmallPtrSet.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000052#include "llvm/ADT/Statistic.h"
Duncan Sands0ad7b6e2011-09-30 13:12:16 +000053#include "llvm/ADT/StringSwitch.h"
Owen Anderson74cfb0c2010-10-07 20:04:55 +000054#include "llvm-c/Initialization.h"
Chris Lattnerb3bc8fa2002-05-14 15:24:07 +000055#include <algorithm>
Torok Edwin3eaee312008-04-20 08:33:11 +000056#include <climits>
Chris Lattner67b1e1b2003-12-07 01:24:23 +000057using namespace llvm;
Chris Lattneracd1f0f2004-07-30 07:50:03 +000058using namespace llvm::PatternMatch;
Brian Gaeked0fde302003-11-11 22:41:34 +000059
Chris Lattner0e5f4992006-12-19 21:40:18 +000060STATISTIC(NumCombined , "Number of insts combined");
61STATISTIC(NumConstProp, "Number of constant folds");
62STATISTIC(NumDeadInst , "Number of dead inst eliminated");
Chris Lattner0e5f4992006-12-19 21:40:18 +000063STATISTIC(NumSunkInst , "Number of instructions sunk");
Duncan Sands37bf92b2010-12-22 13:36:08 +000064STATISTIC(NumExpand, "Number of expansions");
Duncan Sandsa3c44a52010-12-22 09:40:51 +000065STATISTIC(NumFactor , "Number of factorizations");
66STATISTIC(NumReassoc , "Number of reassociations");
Chris Lattnera92f6962002-10-01 22:38:41 +000067
Owen Anderson74cfb0c2010-10-07 20:04:55 +000068// Initialization Routines
69void llvm::initializeInstCombine(PassRegistry &Registry) {
70 initializeInstCombinerPass(Registry);
71}
72
73void LLVMInitializeInstCombine(LLVMPassRegistryRef R) {
74 initializeInstCombine(*unwrap(R));
75}
Chris Lattnerdd841ae2002-04-18 17:39:14 +000076
Dan Gohman844731a2008-05-13 00:00:25 +000077char InstCombiner::ID = 0;
Chad Rosier00737bd2011-12-01 21:29:16 +000078INITIALIZE_PASS_BEGIN(InstCombiner, "instcombine",
79 "Combine redundant instructions", false, false)
80INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfo)
81INITIALIZE_PASS_END(InstCombiner, "instcombine",
Owen Andersonce665bd2010-10-07 22:25:06 +000082 "Combine redundant instructions", false, false)
Dan Gohman844731a2008-05-13 00:00:25 +000083
Chris Lattnere0b4b722010-01-04 07:17:19 +000084void InstCombiner::getAnalysisUsage(AnalysisUsage &AU) const {
Chris Lattnere0b4b722010-01-04 07:17:19 +000085 AU.setPreservesCFG();
Chad Rosier3d925d22011-11-29 23:57:10 +000086 AU.addRequired<TargetLibraryInfo>();
Chris Lattnere0b4b722010-01-04 07:17:19 +000087}
88
89
Nuno Lopes5c525b52012-05-22 17:19:09 +000090Value *InstCombiner::EmitGEPOffset(User *GEP) {
Micah Villmow3574eca2012-10-08 16:38:25 +000091 return llvm::EmitGEPOffset(Builder, *getDataLayout(), GEP);
Nuno Lopes5c525b52012-05-22 17:19:09 +000092}
93
Chris Lattnerc22d4d12009-11-10 07:23:37 +000094/// ShouldChangeType - Return true if it is desirable to convert a computation
95/// from 'From' to 'To'. We don't want to convert from a legal to an illegal
96/// type for example, or from a smaller to a larger illegal type.
Chris Lattnerdb125cf2011-07-18 04:54:35 +000097bool InstCombiner::ShouldChangeType(Type *From, Type *To) const {
Duncan Sands1df98592010-02-16 11:11:14 +000098 assert(From->isIntegerTy() && To->isIntegerTy());
Jakub Staszak58c1da82012-05-06 13:52:31 +000099
Chris Lattnerc22d4d12009-11-10 07:23:37 +0000100 // If we don't have TD, we don't know if the source/dest are legal.
101 if (!TD) return false;
Jakub Staszak58c1da82012-05-06 13:52:31 +0000102
Chris Lattnerc22d4d12009-11-10 07:23:37 +0000103 unsigned FromWidth = From->getPrimitiveSizeInBits();
104 unsigned ToWidth = To->getPrimitiveSizeInBits();
105 bool FromLegal = TD->isLegalInteger(FromWidth);
106 bool ToLegal = TD->isLegalInteger(ToWidth);
Jakub Staszak58c1da82012-05-06 13:52:31 +0000107
Chris Lattnerc22d4d12009-11-10 07:23:37 +0000108 // If this is a legal integer from type, and the result would be an illegal
109 // type, don't do the transformation.
110 if (FromLegal && !ToLegal)
111 return false;
Jakub Staszak58c1da82012-05-06 13:52:31 +0000112
Chris Lattnerc22d4d12009-11-10 07:23:37 +0000113 // Otherwise, if both are illegal, do not increase the size of the result. We
114 // do allow things like i160 -> i64, but not i64 -> i160.
115 if (!FromLegal && !ToLegal && ToWidth > FromWidth)
116 return false;
Jakub Staszak58c1da82012-05-06 13:52:31 +0000117
Chris Lattnerc22d4d12009-11-10 07:23:37 +0000118 return true;
119}
120
Nick Lewyckydaf27ea2011-08-14 01:45:19 +0000121// Return true, if No Signed Wrap should be maintained for I.
122// The No Signed Wrap flag can be kept if the operation "B (I.getOpcode) C",
123// where both B and C should be ConstantInts, results in a constant that does
124// not overflow. This function only handles the Add and Sub opcodes. For
125// all other opcodes, the function conservatively returns false.
126static bool MaintainNoSignedWrap(BinaryOperator &I, Value *B, Value *C) {
127 OverflowingBinaryOperator *OBO = dyn_cast<OverflowingBinaryOperator>(&I);
128 if (!OBO || !OBO->hasNoSignedWrap()) {
129 return false;
130 }
131
132 // We reason about Add and Sub Only.
133 Instruction::BinaryOps Opcode = I.getOpcode();
Jakub Staszak58c1da82012-05-06 13:52:31 +0000134 if (Opcode != Instruction::Add &&
Nick Lewyckydaf27ea2011-08-14 01:45:19 +0000135 Opcode != Instruction::Sub) {
136 return false;
137 }
138
139 ConstantInt *CB = dyn_cast<ConstantInt>(B);
140 ConstantInt *CC = dyn_cast<ConstantInt>(C);
141
142 if (!CB || !CC) {
143 return false;
144 }
145
146 const APInt &BVal = CB->getValue();
147 const APInt &CVal = CC->getValue();
148 bool Overflow = false;
149
150 if (Opcode == Instruction::Add) {
151 BVal.sadd_ov(CVal, Overflow);
152 } else {
153 BVal.ssub_ov(CVal, Overflow);
154 }
155
156 return !Overflow;
157}
158
Duncan Sands096aa792010-11-13 15:10:37 +0000159/// SimplifyAssociativeOrCommutative - This performs a few simplifications for
160/// operators which are associative or commutative:
161//
162// Commutative operators:
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000163//
Chris Lattner4f98c562003-03-10 21:43:22 +0000164// 1. Order operands such that they are listed from right (least complex) to
165// left (most complex). This puts constants before unary operators before
166// binary operators.
167//
Duncan Sands096aa792010-11-13 15:10:37 +0000168// Associative operators:
Chris Lattner4f98c562003-03-10 21:43:22 +0000169//
Duncan Sands096aa792010-11-13 15:10:37 +0000170// 2. Transform: "(A op B) op C" ==> "A op (B op C)" if "B op C" simplifies.
171// 3. Transform: "A op (B op C)" ==> "(A op B) op C" if "A op B" simplifies.
172//
173// Associative and commutative operators:
174//
175// 4. Transform: "(A op B) op C" ==> "(C op A) op B" if "C op A" simplifies.
176// 5. Transform: "A op (B op C)" ==> "B op (C op A)" if "C op A" simplifies.
177// 6. Transform: "(A op C1) op (B op C2)" ==> "(A op B) op (C1 op C2)"
178// if C1 and C2 are constants.
179//
180bool InstCombiner::SimplifyAssociativeOrCommutative(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +0000181 Instruction::BinaryOps Opcode = I.getOpcode();
Duncan Sands096aa792010-11-13 15:10:37 +0000182 bool Changed = false;
Chris Lattnerc8802d22003-03-11 00:12:48 +0000183
Duncan Sands096aa792010-11-13 15:10:37 +0000184 do {
185 // Order operands such that they are listed from right (least complex) to
186 // left (most complex). This puts constants before unary operators before
187 // binary operators.
188 if (I.isCommutative() && getComplexity(I.getOperand(0)) <
189 getComplexity(I.getOperand(1)))
190 Changed = !I.swapOperands();
191
192 BinaryOperator *Op0 = dyn_cast<BinaryOperator>(I.getOperand(0));
193 BinaryOperator *Op1 = dyn_cast<BinaryOperator>(I.getOperand(1));
194
195 if (I.isAssociative()) {
196 // Transform: "(A op B) op C" ==> "A op (B op C)" if "B op C" simplifies.
197 if (Op0 && Op0->getOpcode() == Opcode) {
198 Value *A = Op0->getOperand(0);
199 Value *B = Op0->getOperand(1);
200 Value *C = I.getOperand(1);
201
202 // Does "B op C" simplify?
203 if (Value *V = SimplifyBinOp(Opcode, B, C, TD)) {
204 // It simplifies to V. Form "A op V".
205 I.setOperand(0, A);
206 I.setOperand(1, V);
Dan Gohman5195b712011-02-02 02:05:46 +0000207 // Conservatively clear the optional flags, since they may not be
208 // preserved by the reassociation.
Nick Lewycky7f0170c2011-08-14 03:41:33 +0000209 if (MaintainNoSignedWrap(I, B, C) &&
Bill Wendling56cb2292012-07-19 00:11:40 +0000210 (!Op0 || (isa<BinaryOperator>(Op0) && Op0->hasNoSignedWrap()))) {
Nick Lewycky7f0170c2011-08-14 03:41:33 +0000211 // Note: this is only valid because SimplifyBinOp doesn't look at
212 // the operands to Op0.
Nick Lewyckydaf27ea2011-08-14 01:45:19 +0000213 I.clearSubclassOptionalData();
214 I.setHasNoSignedWrap(true);
215 } else {
216 I.clearSubclassOptionalData();
217 }
Jakub Staszak58c1da82012-05-06 13:52:31 +0000218
Duncan Sands096aa792010-11-13 15:10:37 +0000219 Changed = true;
Duncan Sandsa3c44a52010-12-22 09:40:51 +0000220 ++NumReassoc;
Duncan Sands096aa792010-11-13 15:10:37 +0000221 continue;
Misha Brukmanfd939082005-04-21 23:48:37 +0000222 }
Duncan Sands096aa792010-11-13 15:10:37 +0000223 }
224
225 // Transform: "A op (B op C)" ==> "(A op B) op C" if "A op B" simplifies.
226 if (Op1 && Op1->getOpcode() == Opcode) {
227 Value *A = I.getOperand(0);
228 Value *B = Op1->getOperand(0);
229 Value *C = Op1->getOperand(1);
230
231 // Does "A op B" simplify?
232 if (Value *V = SimplifyBinOp(Opcode, A, B, TD)) {
233 // It simplifies to V. Form "V op C".
234 I.setOperand(0, V);
235 I.setOperand(1, C);
Dan Gohman5195b712011-02-02 02:05:46 +0000236 // Conservatively clear the optional flags, since they may not be
237 // preserved by the reassociation.
238 I.clearSubclassOptionalData();
Duncan Sands096aa792010-11-13 15:10:37 +0000239 Changed = true;
Duncan Sandsa3c44a52010-12-22 09:40:51 +0000240 ++NumReassoc;
Duncan Sands096aa792010-11-13 15:10:37 +0000241 continue;
242 }
243 }
Chris Lattner4f98c562003-03-10 21:43:22 +0000244 }
Duncan Sands096aa792010-11-13 15:10:37 +0000245
246 if (I.isAssociative() && I.isCommutative()) {
247 // Transform: "(A op B) op C" ==> "(C op A) op B" if "C op A" simplifies.
248 if (Op0 && Op0->getOpcode() == Opcode) {
249 Value *A = Op0->getOperand(0);
250 Value *B = Op0->getOperand(1);
251 Value *C = I.getOperand(1);
252
253 // Does "C op A" simplify?
254 if (Value *V = SimplifyBinOp(Opcode, C, A, TD)) {
255 // It simplifies to V. Form "V op B".
256 I.setOperand(0, V);
257 I.setOperand(1, B);
Dan Gohman5195b712011-02-02 02:05:46 +0000258 // Conservatively clear the optional flags, since they may not be
259 // preserved by the reassociation.
260 I.clearSubclassOptionalData();
Duncan Sands096aa792010-11-13 15:10:37 +0000261 Changed = true;
Duncan Sandsa3c44a52010-12-22 09:40:51 +0000262 ++NumReassoc;
Duncan Sands096aa792010-11-13 15:10:37 +0000263 continue;
264 }
265 }
266
267 // Transform: "A op (B op C)" ==> "B op (C op A)" if "C op A" simplifies.
268 if (Op1 && Op1->getOpcode() == Opcode) {
269 Value *A = I.getOperand(0);
270 Value *B = Op1->getOperand(0);
271 Value *C = Op1->getOperand(1);
272
273 // Does "C op A" simplify?
274 if (Value *V = SimplifyBinOp(Opcode, C, A, TD)) {
275 // It simplifies to V. Form "B op V".
276 I.setOperand(0, B);
277 I.setOperand(1, V);
Dan Gohman5195b712011-02-02 02:05:46 +0000278 // Conservatively clear the optional flags, since they may not be
279 // preserved by the reassociation.
280 I.clearSubclassOptionalData();
Duncan Sands096aa792010-11-13 15:10:37 +0000281 Changed = true;
Duncan Sandsa3c44a52010-12-22 09:40:51 +0000282 ++NumReassoc;
Duncan Sands096aa792010-11-13 15:10:37 +0000283 continue;
284 }
285 }
286
287 // Transform: "(A op C1) op (B op C2)" ==> "(A op B) op (C1 op C2)"
288 // if C1 and C2 are constants.
289 if (Op0 && Op1 &&
290 Op0->getOpcode() == Opcode && Op1->getOpcode() == Opcode &&
291 isa<Constant>(Op0->getOperand(1)) &&
292 isa<Constant>(Op1->getOperand(1)) &&
293 Op0->hasOneUse() && Op1->hasOneUse()) {
294 Value *A = Op0->getOperand(0);
295 Constant *C1 = cast<Constant>(Op0->getOperand(1));
296 Value *B = Op1->getOperand(0);
297 Constant *C2 = cast<Constant>(Op1->getOperand(1));
298
299 Constant *Folded = ConstantExpr::get(Opcode, C1, C2);
Nick Lewyckydaf27ea2011-08-14 01:45:19 +0000300 BinaryOperator *New = BinaryOperator::Create(Opcode, A, B);
Eli Friedmana311c342011-05-27 00:19:40 +0000301 InsertNewInstWith(New, I);
Eli Friedmane6f364b2011-05-18 23:58:37 +0000302 New->takeName(Op1);
Duncan Sands096aa792010-11-13 15:10:37 +0000303 I.setOperand(0, New);
304 I.setOperand(1, Folded);
Dan Gohman5195b712011-02-02 02:05:46 +0000305 // Conservatively clear the optional flags, since they may not be
306 // preserved by the reassociation.
Nick Lewycky28b84ff2011-08-14 04:51:49 +0000307 I.clearSubclassOptionalData();
Nick Lewyckydaf27ea2011-08-14 01:45:19 +0000308
Duncan Sands096aa792010-11-13 15:10:37 +0000309 Changed = true;
310 continue;
311 }
312 }
313
314 // No further simplifications.
315 return Changed;
316 } while (1);
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000317}
Chris Lattner8a2a3112001-12-14 16:52:21 +0000318
Duncan Sands5057f382010-11-23 14:23:47 +0000319/// LeftDistributesOverRight - Whether "X LOp (Y ROp Z)" is always equal to
Duncan Sandsc2b1c0b2010-11-23 15:25:34 +0000320/// "(X LOp Y) ROp (X LOp Z)".
Duncan Sands5057f382010-11-23 14:23:47 +0000321static bool LeftDistributesOverRight(Instruction::BinaryOps LOp,
322 Instruction::BinaryOps ROp) {
323 switch (LOp) {
324 default:
325 return false;
326
327 case Instruction::And:
328 // And distributes over Or and Xor.
329 switch (ROp) {
330 default:
331 return false;
332 case Instruction::Or:
333 case Instruction::Xor:
334 return true;
335 }
336
337 case Instruction::Mul:
338 // Multiplication distributes over addition and subtraction.
339 switch (ROp) {
340 default:
341 return false;
342 case Instruction::Add:
343 case Instruction::Sub:
344 return true;
345 }
346
347 case Instruction::Or:
348 // Or distributes over And.
349 switch (ROp) {
350 default:
351 return false;
352 case Instruction::And:
353 return true;
354 }
355 }
356}
357
358/// RightDistributesOverLeft - Whether "(X LOp Y) ROp Z" is always equal to
359/// "(X ROp Z) LOp (Y ROp Z)".
360static bool RightDistributesOverLeft(Instruction::BinaryOps LOp,
361 Instruction::BinaryOps ROp) {
362 if (Instruction::isCommutative(ROp))
363 return LeftDistributesOverRight(ROp, LOp);
364 // TODO: It would be nice to handle division, aka "(X + Y)/Z = X/Z + Y/Z",
365 // but this requires knowing that the addition does not overflow and other
366 // such subtleties.
367 return false;
368}
369
Duncan Sands37bf92b2010-12-22 13:36:08 +0000370/// SimplifyUsingDistributiveLaws - This tries to simplify binary operations
371/// which some other binary operation distributes over either by factorizing
372/// out common terms (eg "(A*B)+(A*C)" -> "A*(B+C)") or expanding out if this
373/// results in simplifications (eg: "A & (B | C) -> (A&B) | (A&C)" if this is
374/// a win). Returns the simplified value, or null if it didn't simplify.
375Value *InstCombiner::SimplifyUsingDistributiveLaws(BinaryOperator &I) {
376 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
377 BinaryOperator *Op0 = dyn_cast<BinaryOperator>(LHS);
378 BinaryOperator *Op1 = dyn_cast<BinaryOperator>(RHS);
379 Instruction::BinaryOps TopLevelOpcode = I.getOpcode(); // op
Duncan Sands5057f382010-11-23 14:23:47 +0000380
Duncan Sands37bf92b2010-12-22 13:36:08 +0000381 // Factorization.
382 if (Op0 && Op1 && Op0->getOpcode() == Op1->getOpcode()) {
383 // The instruction has the form "(A op' B) op (C op' D)". Try to factorize
384 // a common term.
385 Value *A = Op0->getOperand(0), *B = Op0->getOperand(1);
386 Value *C = Op1->getOperand(0), *D = Op1->getOperand(1);
387 Instruction::BinaryOps InnerOpcode = Op0->getOpcode(); // op'
Duncan Sands5057f382010-11-23 14:23:47 +0000388
Duncan Sands37bf92b2010-12-22 13:36:08 +0000389 // Does "X op' Y" always equal "Y op' X"?
390 bool InnerCommutative = Instruction::isCommutative(InnerOpcode);
Duncan Sands5057f382010-11-23 14:23:47 +0000391
Duncan Sands37bf92b2010-12-22 13:36:08 +0000392 // Does "X op' (Y op Z)" always equal "(X op' Y) op (X op' Z)"?
393 if (LeftDistributesOverRight(InnerOpcode, TopLevelOpcode))
394 // Does the instruction have the form "(A op' B) op (A op' D)" or, in the
395 // commutative case, "(A op' B) op (C op' A)"?
396 if (A == C || (InnerCommutative && A == D)) {
397 if (A != C)
398 std::swap(C, D);
399 // Consider forming "A op' (B op D)".
400 // If "B op D" simplifies then it can be formed with no cost.
401 Value *V = SimplifyBinOp(TopLevelOpcode, B, D, TD);
402 // If "B op D" doesn't simplify then only go on if both of the existing
403 // operations "A op' B" and "C op' D" will be zapped as no longer used.
404 if (!V && Op0->hasOneUse() && Op1->hasOneUse())
405 V = Builder->CreateBinOp(TopLevelOpcode, B, D, Op1->getName());
406 if (V) {
407 ++NumFactor;
408 V = Builder->CreateBinOp(InnerOpcode, A, V);
409 V->takeName(&I);
410 return V;
411 }
Duncan Sandsa3c44a52010-12-22 09:40:51 +0000412 }
Duncan Sands5057f382010-11-23 14:23:47 +0000413
Duncan Sands37bf92b2010-12-22 13:36:08 +0000414 // Does "(X op Y) op' Z" always equal "(X op' Z) op (Y op' Z)"?
415 if (RightDistributesOverLeft(TopLevelOpcode, InnerOpcode))
416 // Does the instruction have the form "(A op' B) op (C op' B)" or, in the
417 // commutative case, "(A op' B) op (B op' D)"?
418 if (B == D || (InnerCommutative && B == C)) {
419 if (B != D)
420 std::swap(C, D);
421 // Consider forming "(A op C) op' B".
422 // If "A op C" simplifies then it can be formed with no cost.
423 Value *V = SimplifyBinOp(TopLevelOpcode, A, C, TD);
424 // If "A op C" doesn't simplify then only go on if both of the existing
425 // operations "A op' B" and "C op' D" will be zapped as no longer used.
426 if (!V && Op0->hasOneUse() && Op1->hasOneUse())
427 V = Builder->CreateBinOp(TopLevelOpcode, A, C, Op0->getName());
428 if (V) {
429 ++NumFactor;
430 V = Builder->CreateBinOp(InnerOpcode, V, B);
431 V->takeName(&I);
432 return V;
433 }
Duncan Sandsa3c44a52010-12-22 09:40:51 +0000434 }
Duncan Sands37bf92b2010-12-22 13:36:08 +0000435 }
436
437 // Expansion.
438 if (Op0 && RightDistributesOverLeft(Op0->getOpcode(), TopLevelOpcode)) {
439 // The instruction has the form "(A op' B) op C". See if expanding it out
440 // to "(A op C) op' (B op C)" results in simplifications.
441 Value *A = Op0->getOperand(0), *B = Op0->getOperand(1), *C = RHS;
442 Instruction::BinaryOps InnerOpcode = Op0->getOpcode(); // op'
443
444 // Do "A op C" and "B op C" both simplify?
445 if (Value *L = SimplifyBinOp(TopLevelOpcode, A, C, TD))
446 if (Value *R = SimplifyBinOp(TopLevelOpcode, B, C, TD)) {
447 // They do! Return "L op' R".
448 ++NumExpand;
449 // If "L op' R" equals "A op' B" then "L op' R" is just the LHS.
450 if ((L == A && R == B) ||
451 (Instruction::isCommutative(InnerOpcode) && L == B && R == A))
452 return Op0;
453 // Otherwise return "L op' R" if it simplifies.
454 if (Value *V = SimplifyBinOp(InnerOpcode, L, R, TD))
455 return V;
456 // Otherwise, create a new instruction.
457 C = Builder->CreateBinOp(InnerOpcode, L, R);
458 C->takeName(&I);
459 return C;
460 }
461 }
462
463 if (Op1 && LeftDistributesOverRight(TopLevelOpcode, Op1->getOpcode())) {
464 // The instruction has the form "A op (B op' C)". See if expanding it out
465 // to "(A op B) op' (A op C)" results in simplifications.
466 Value *A = LHS, *B = Op1->getOperand(0), *C = Op1->getOperand(1);
467 Instruction::BinaryOps InnerOpcode = Op1->getOpcode(); // op'
468
469 // Do "A op B" and "A op C" both simplify?
470 if (Value *L = SimplifyBinOp(TopLevelOpcode, A, B, TD))
471 if (Value *R = SimplifyBinOp(TopLevelOpcode, A, C, TD)) {
472 // They do! Return "L op' R".
473 ++NumExpand;
474 // If "L op' R" equals "B op' C" then "L op' R" is just the RHS.
475 if ((L == B && R == C) ||
476 (Instruction::isCommutative(InnerOpcode) && L == C && R == B))
477 return Op1;
478 // Otherwise return "L op' R" if it simplifies.
479 if (Value *V = SimplifyBinOp(InnerOpcode, L, R, TD))
480 return V;
481 // Otherwise, create a new instruction.
482 A = Builder->CreateBinOp(InnerOpcode, L, R);
483 A->takeName(&I);
484 return A;
485 }
486 }
Duncan Sands5057f382010-11-23 14:23:47 +0000487
488 return 0;
489}
490
Chris Lattner8d969642003-03-10 23:06:50 +0000491// dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
492// if the LHS is a constant zero (which is the 'negate' form).
Chris Lattnerb35dde12002-05-06 16:49:18 +0000493//
Chris Lattner02446fc2010-01-04 07:37:31 +0000494Value *InstCombiner::dyn_castNegVal(Value *V) const {
Owen Andersonfa82b6e2009-07-13 22:18:28 +0000495 if (BinaryOperator::isNeg(V))
Chris Lattnera1df33c2005-04-24 07:30:14 +0000496 return BinaryOperator::getNegArgument(V);
Chris Lattner8d969642003-03-10 23:06:50 +0000497
Chris Lattner0ce85802004-12-14 20:08:06 +0000498 // Constants can be considered to be negated values if they can be folded.
499 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
Owen Andersonbaf3c402009-07-29 18:55:55 +0000500 return ConstantExpr::getNeg(C);
Nick Lewycky18b3da62008-05-23 04:54:45 +0000501
Chris Lattner7302d802012-02-06 21:56:39 +0000502 if (ConstantDataVector *C = dyn_cast<ConstantDataVector>(V))
503 if (C->getType()->getElementType()->isIntegerTy())
Owen Andersonbaf3c402009-07-29 18:55:55 +0000504 return ConstantExpr::getNeg(C);
Nick Lewycky18b3da62008-05-23 04:54:45 +0000505
Chris Lattner8d969642003-03-10 23:06:50 +0000506 return 0;
Chris Lattnerb35dde12002-05-06 16:49:18 +0000507}
508
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000509// dyn_castFNegVal - Given a 'fsub' instruction, return the RHS of the
510// instruction if the LHS is a constant negative zero (which is the 'negate'
511// form).
512//
Chris Lattnerd12c27c2010-01-05 06:09:35 +0000513Value *InstCombiner::dyn_castFNegVal(Value *V) const {
Owen Andersonfa82b6e2009-07-13 22:18:28 +0000514 if (BinaryOperator::isFNeg(V))
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000515 return BinaryOperator::getFNegArgument(V);
516
517 // Constants can be considered to be negated values if they can be folded.
518 if (ConstantFP *C = dyn_cast<ConstantFP>(V))
Owen Andersonbaf3c402009-07-29 18:55:55 +0000519 return ConstantExpr::getFNeg(C);
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000520
Chris Lattner7302d802012-02-06 21:56:39 +0000521 if (ConstantDataVector *C = dyn_cast<ConstantDataVector>(V))
522 if (C->getType()->getElementType()->isFloatingPointTy())
Owen Andersonbaf3c402009-07-29 18:55:55 +0000523 return ConstantExpr::getFNeg(C);
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000524
525 return 0;
526}
527
Chris Lattner6e7ba452005-01-01 16:22:27 +0000528static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
Chris Lattner2eefe512004-04-09 19:05:30 +0000529 InstCombiner *IC) {
Nick Lewyckyacf4a7c2011-01-21 02:30:43 +0000530 if (CastInst *CI = dyn_cast<CastInst>(&I)) {
Chris Lattner2345d1d2009-08-30 20:01:10 +0000531 return IC->Builder->CreateCast(CI->getOpcode(), SO, I.getType());
Nick Lewyckyacf4a7c2011-01-21 02:30:43 +0000532 }
Chris Lattner6e7ba452005-01-01 16:22:27 +0000533
Chris Lattner2eefe512004-04-09 19:05:30 +0000534 // Figure out if the constant is the left or the right argument.
Chris Lattner6e7ba452005-01-01 16:22:27 +0000535 bool ConstIsRHS = isa<Constant>(I.getOperand(1));
536 Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
Chris Lattner564a7272003-08-13 19:01:45 +0000537
Chris Lattner2eefe512004-04-09 19:05:30 +0000538 if (Constant *SOC = dyn_cast<Constant>(SO)) {
539 if (ConstIsRHS)
Owen Andersonbaf3c402009-07-29 18:55:55 +0000540 return ConstantExpr::get(I.getOpcode(), SOC, ConstOperand);
541 return ConstantExpr::get(I.getOpcode(), ConstOperand, SOC);
Chris Lattner2eefe512004-04-09 19:05:30 +0000542 }
543
544 Value *Op0 = SO, *Op1 = ConstOperand;
545 if (!ConstIsRHS)
546 std::swap(Op0, Op1);
Jakub Staszak58c1da82012-05-06 13:52:31 +0000547
Chris Lattner6e7ba452005-01-01 16:22:27 +0000548 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
Chris Lattner74381062009-08-30 07:44:24 +0000549 return IC->Builder->CreateBinOp(BO->getOpcode(), Op0, Op1,
550 SO->getName()+".op");
551 if (ICmpInst *CI = dyn_cast<ICmpInst>(&I))
552 return IC->Builder->CreateICmp(CI->getPredicate(), Op0, Op1,
553 SO->getName()+".cmp");
554 if (FCmpInst *CI = dyn_cast<FCmpInst>(&I))
555 return IC->Builder->CreateICmp(CI->getPredicate(), Op0, Op1,
556 SO->getName()+".cmp");
557 llvm_unreachable("Unknown binary instruction type!");
Chris Lattner6e7ba452005-01-01 16:22:27 +0000558}
559
560// FoldOpIntoSelect - Given an instruction with a select as one operand and a
561// constant as the other operand, try to fold the binary operator into the
562// select arguments. This also works for Cast instructions, which obviously do
563// not have a second operand.
Chris Lattner80f43d32010-01-04 07:53:58 +0000564Instruction *InstCombiner::FoldOpIntoSelect(Instruction &Op, SelectInst *SI) {
Chris Lattner6e7ba452005-01-01 16:22:27 +0000565 // Don't modify shared select instructions
566 if (!SI->hasOneUse()) return 0;
567 Value *TV = SI->getOperand(1);
568 Value *FV = SI->getOperand(2);
569
570 if (isa<Constant>(TV) || isa<Constant>(FV)) {
Chris Lattner956db272005-04-21 05:43:13 +0000571 // Bool selects with constant operands can be folded to logical ops.
Duncan Sandsb0bc6c32010-02-15 16:12:20 +0000572 if (SI->getType()->isIntegerTy(1)) return 0;
Chris Lattner956db272005-04-21 05:43:13 +0000573
Nick Lewyckyacf4a7c2011-01-21 02:30:43 +0000574 // If it's a bitcast involving vectors, make sure it has the same number of
575 // elements on both sides.
576 if (BitCastInst *BC = dyn_cast<BitCastInst>(&Op)) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000577 VectorType *DestTy = dyn_cast<VectorType>(BC->getDestTy());
578 VectorType *SrcTy = dyn_cast<VectorType>(BC->getSrcTy());
Nick Lewyckyacf4a7c2011-01-21 02:30:43 +0000579
580 // Verify that either both or neither are vectors.
581 if ((SrcTy == NULL) != (DestTy == NULL)) return 0;
582 // If vectors, verify that they have the same number of elements.
583 if (SrcTy && SrcTy->getNumElements() != DestTy->getNumElements())
584 return 0;
585 }
Jakub Staszak58c1da82012-05-06 13:52:31 +0000586
Chris Lattner80f43d32010-01-04 07:53:58 +0000587 Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, this);
588 Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, this);
Chris Lattner6e7ba452005-01-01 16:22:27 +0000589
Nick Lewyckyacf4a7c2011-01-21 02:30:43 +0000590 return SelectInst::Create(SI->getCondition(),
591 SelectTrueVal, SelectFalseVal);
Chris Lattner6e7ba452005-01-01 16:22:27 +0000592 }
593 return 0;
Chris Lattner2eefe512004-04-09 19:05:30 +0000594}
595
Chris Lattner4e998b22004-09-29 05:07:12 +0000596
Chris Lattner5d1704d2009-09-27 19:57:57 +0000597/// FoldOpIntoPhi - Given a binary operator, cast instruction, or select which
598/// has a PHI node as operand #0, see if we can fold the instruction into the
599/// PHI (which is only possible if all operands to the PHI are constants).
Chris Lattner213cd612009-09-27 20:46:36 +0000600///
Chris Lattner9922ccf2011-01-16 05:14:26 +0000601Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I) {
Chris Lattner4e998b22004-09-29 05:07:12 +0000602 PHINode *PN = cast<PHINode>(I.getOperand(0));
Chris Lattnerbac32862004-11-14 19:13:23 +0000603 unsigned NumPHIValues = PN->getNumIncomingValues();
Chris Lattner5aac8322011-01-16 04:37:29 +0000604 if (NumPHIValues == 0)
Chris Lattner213cd612009-09-27 20:46:36 +0000605 return 0;
Jakub Staszak58c1da82012-05-06 13:52:31 +0000606
Chris Lattner084fe622011-01-21 05:08:26 +0000607 // We normally only transform phis with a single use. However, if a PHI has
608 // multiple uses and they are all the same operation, we can fold *all* of the
609 // uses into the PHI.
Chris Lattner192228e2011-01-16 05:28:59 +0000610 if (!PN->hasOneUse()) {
611 // Walk the use list for the instruction, comparing them to I.
612 for (Value::use_iterator UI = PN->use_begin(), E = PN->use_end();
Chris Lattnercd151d22011-01-21 05:29:50 +0000613 UI != E; ++UI) {
614 Instruction *User = cast<Instruction>(*UI);
615 if (User != &I && !I.isIdenticalTo(User))
Chris Lattner192228e2011-01-16 05:28:59 +0000616 return 0;
Chris Lattnercd151d22011-01-21 05:29:50 +0000617 }
Chris Lattner192228e2011-01-16 05:28:59 +0000618 // Otherwise, we can replace *all* users with the new PHI we form.
619 }
Jakub Staszak58c1da82012-05-06 13:52:31 +0000620
Chris Lattner5d1704d2009-09-27 19:57:57 +0000621 // Check to see if all of the operands of the PHI are simple constants
622 // (constantint/constantfp/undef). If there is one non-constant value,
Chris Lattnerc6df8f42009-09-27 20:18:49 +0000623 // remember the BB it is in. If there is more than one or if *it* is a PHI,
624 // bail out. We don't do arbitrary constant expressions here because moving
625 // their computation can be expensive without a cost model.
Chris Lattner2a86f3b2006-09-09 22:02:56 +0000626 BasicBlock *NonConstBB = 0;
Chris Lattner5aac8322011-01-16 04:37:29 +0000627 for (unsigned i = 0; i != NumPHIValues; ++i) {
628 Value *InVal = PN->getIncomingValue(i);
629 if (isa<Constant>(InVal) && !isa<ConstantExpr>(InVal))
630 continue;
631
632 if (isa<PHINode>(InVal)) return 0; // Itself a phi.
633 if (NonConstBB) return 0; // More than one non-const value.
Jakub Staszak58c1da82012-05-06 13:52:31 +0000634
Chris Lattner5aac8322011-01-16 04:37:29 +0000635 NonConstBB = PN->getIncomingBlock(i);
Chris Lattner7dfe8fd2011-01-16 05:08:00 +0000636
637 // If the InVal is an invoke at the end of the pred block, then we can't
638 // insert a computation after it without breaking the edge.
639 if (InvokeInst *II = dyn_cast<InvokeInst>(InVal))
640 if (II->getParent() == NonConstBB)
641 return 0;
Jakub Staszak58c1da82012-05-06 13:52:31 +0000642
Chris Lattnercd151d22011-01-21 05:29:50 +0000643 // If the incoming non-constant value is in I's block, we will remove one
644 // instruction, but insert another equivalent one, leading to infinite
645 // instcombine.
646 if (NonConstBB == I.getParent())
647 return 0;
Chris Lattner5aac8322011-01-16 04:37:29 +0000648 }
Jakub Staszak58c1da82012-05-06 13:52:31 +0000649
Chris Lattner2a86f3b2006-09-09 22:02:56 +0000650 // If there is exactly one non-constant value, we can insert a copy of the
651 // operation in that block. However, if this is a critical edge, we would be
652 // inserting the computation one some other paths (e.g. inside a loop). Only
653 // do this if the pred block is unconditionally branching into the phi block.
Chris Lattner9922ccf2011-01-16 05:14:26 +0000654 if (NonConstBB != 0) {
Chris Lattner2a86f3b2006-09-09 22:02:56 +0000655 BranchInst *BI = dyn_cast<BranchInst>(NonConstBB->getTerminator());
656 if (!BI || !BI->isUnconditional()) return 0;
657 }
Chris Lattner4e998b22004-09-29 05:07:12 +0000658
659 // Okay, we can do the transformation: create the new PHI node.
Eli Friedmane6f364b2011-05-18 23:58:37 +0000660 PHINode *NewPN = PHINode::Create(I.getType(), PN->getNumIncomingValues());
Chris Lattner857eb572009-10-21 23:41:58 +0000661 InsertNewInstBefore(NewPN, *PN);
662 NewPN->takeName(PN);
Jakub Staszak58c1da82012-05-06 13:52:31 +0000663
Chris Lattner7dfe8fd2011-01-16 05:08:00 +0000664 // If we are going to have to insert a new computation, do so right before the
665 // predecessors terminator.
666 if (NonConstBB)
667 Builder->SetInsertPoint(NonConstBB->getTerminator());
Jakub Staszak58c1da82012-05-06 13:52:31 +0000668
Chris Lattner4e998b22004-09-29 05:07:12 +0000669 // Next, add all of the operands to the PHI.
Chris Lattner5d1704d2009-09-27 19:57:57 +0000670 if (SelectInst *SI = dyn_cast<SelectInst>(&I)) {
671 // We only currently try to fold the condition of a select when it is a phi,
672 // not the true/false values.
Chris Lattnerc6df8f42009-09-27 20:18:49 +0000673 Value *TrueV = SI->getTrueValue();
674 Value *FalseV = SI->getFalseValue();
Chris Lattner3ddfb212009-09-28 06:49:44 +0000675 BasicBlock *PhiTransBB = PN->getParent();
Chris Lattner5d1704d2009-09-27 19:57:57 +0000676 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattnerc6df8f42009-09-27 20:18:49 +0000677 BasicBlock *ThisBB = PN->getIncomingBlock(i);
Chris Lattner3ddfb212009-09-28 06:49:44 +0000678 Value *TrueVInPred = TrueV->DoPHITranslation(PhiTransBB, ThisBB);
679 Value *FalseVInPred = FalseV->DoPHITranslation(PhiTransBB, ThisBB);
Chris Lattner5d1704d2009-09-27 19:57:57 +0000680 Value *InV = 0;
Chris Lattner7dfe8fd2011-01-16 05:08:00 +0000681 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i)))
Chris Lattnerc6df8f42009-09-27 20:18:49 +0000682 InV = InC->isNullValue() ? FalseVInPred : TrueVInPred;
Chris Lattner7dfe8fd2011-01-16 05:08:00 +0000683 else
684 InV = Builder->CreateSelect(PN->getIncomingValue(i),
685 TrueVInPred, FalseVInPred, "phitmp");
Chris Lattnerc6df8f42009-09-27 20:18:49 +0000686 NewPN->addIncoming(InV, ThisBB);
Chris Lattner5d1704d2009-09-27 19:57:57 +0000687 }
Chris Lattner7dfe8fd2011-01-16 05:08:00 +0000688 } else if (CmpInst *CI = dyn_cast<CmpInst>(&I)) {
689 Constant *C = cast<Constant>(I.getOperand(1));
690 for (unsigned i = 0; i != NumPHIValues; ++i) {
691 Value *InV = 0;
692 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i)))
693 InV = ConstantExpr::getCompare(CI->getPredicate(), InC, C);
694 else if (isa<ICmpInst>(CI))
695 InV = Builder->CreateICmp(CI->getPredicate(), PN->getIncomingValue(i),
696 C, "phitmp");
697 else
698 InV = Builder->CreateFCmp(CI->getPredicate(), PN->getIncomingValue(i),
699 C, "phitmp");
700 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
701 }
Chris Lattner5d1704d2009-09-27 19:57:57 +0000702 } else if (I.getNumOperands() == 2) {
Chris Lattner4e998b22004-09-29 05:07:12 +0000703 Constant *C = cast<Constant>(I.getOperand(1));
Chris Lattnerbac32862004-11-14 19:13:23 +0000704 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattnera9ff5eb2007-08-05 08:47:58 +0000705 Value *InV = 0;
Chris Lattner7dfe8fd2011-01-16 05:08:00 +0000706 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i)))
707 InV = ConstantExpr::get(I.getOpcode(), InC, C);
708 else
709 InV = Builder->CreateBinOp(cast<BinaryOperator>(I).getOpcode(),
710 PN->getIncomingValue(i), C, "phitmp");
Chris Lattner2a86f3b2006-09-09 22:02:56 +0000711 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
Chris Lattner4e998b22004-09-29 05:07:12 +0000712 }
Jakub Staszak58c1da82012-05-06 13:52:31 +0000713 } else {
Reid Spencer3da59db2006-11-27 01:05:10 +0000714 CastInst *CI = cast<CastInst>(&I);
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000715 Type *RetTy = CI->getType();
Chris Lattnerbac32862004-11-14 19:13:23 +0000716 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattner2a86f3b2006-09-09 22:02:56 +0000717 Value *InV;
Chris Lattner7dfe8fd2011-01-16 05:08:00 +0000718 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i)))
Owen Andersonbaf3c402009-07-29 18:55:55 +0000719 InV = ConstantExpr::getCast(CI->getOpcode(), InC, RetTy);
Jakub Staszak58c1da82012-05-06 13:52:31 +0000720 else
Chris Lattner7dfe8fd2011-01-16 05:08:00 +0000721 InV = Builder->CreateCast(CI->getOpcode(),
722 PN->getIncomingValue(i), I.getType(), "phitmp");
Chris Lattner2a86f3b2006-09-09 22:02:56 +0000723 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
Chris Lattner4e998b22004-09-29 05:07:12 +0000724 }
725 }
Jakub Staszak58c1da82012-05-06 13:52:31 +0000726
Chris Lattner192228e2011-01-16 05:28:59 +0000727 for (Value::use_iterator UI = PN->use_begin(), E = PN->use_end();
728 UI != E; ) {
729 Instruction *User = cast<Instruction>(*UI++);
730 if (User == &I) continue;
731 ReplaceInstUsesWith(*User, NewPN);
732 EraseInstFromFunction(*User);
733 }
Chris Lattner4e998b22004-09-29 05:07:12 +0000734 return ReplaceInstUsesWith(I, NewPN);
735}
736
Chris Lattner46cd5a12009-01-09 05:44:56 +0000737/// FindElementAtOffset - Given a type and a constant offset, determine whether
738/// or not there is a sequence of GEP indices into the type that will land us at
Chris Lattner3914f722009-01-24 01:00:13 +0000739/// the specified offset. If so, fill them into NewIndices and return the
740/// resultant element type, otherwise return null.
Jakub Staszak58c1da82012-05-06 13:52:31 +0000741Type *InstCombiner::FindElementAtOffset(Type *Ty, int64_t Offset,
Chris Lattner80f43d32010-01-04 07:53:58 +0000742 SmallVectorImpl<Value*> &NewIndices) {
Dan Gohmance9fe9f2009-07-21 23:21:54 +0000743 if (!TD) return 0;
Chris Lattner3914f722009-01-24 01:00:13 +0000744 if (!Ty->isSized()) return 0;
Jakub Staszak58c1da82012-05-06 13:52:31 +0000745
Chris Lattner46cd5a12009-01-09 05:44:56 +0000746 // Start with the index over the outer type. Note that the type size
747 // might be zero (even if the offset isn't zero) if the indexed type
748 // is something like [0 x {int, int}]
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000749 Type *IntPtrTy = TD->getIntPtrType(Ty->getContext());
Chris Lattner46cd5a12009-01-09 05:44:56 +0000750 int64_t FirstIdx = 0;
Duncan Sands777d2302009-05-09 07:06:46 +0000751 if (int64_t TySize = TD->getTypeAllocSize(Ty)) {
Chris Lattner46cd5a12009-01-09 05:44:56 +0000752 FirstIdx = Offset/TySize;
Chris Lattner31a69cb2009-01-11 20:41:36 +0000753 Offset -= FirstIdx*TySize;
Jakub Staszak58c1da82012-05-06 13:52:31 +0000754
Chris Lattnerdbc3bc22009-01-11 20:15:20 +0000755 // Handle hosts where % returns negative instead of values [0..TySize).
Chris Lattner46cd5a12009-01-09 05:44:56 +0000756 if (Offset < 0) {
757 --FirstIdx;
758 Offset += TySize;
759 assert(Offset >= 0);
760 }
761 assert((uint64_t)Offset < (uint64_t)TySize && "Out of range offset");
762 }
Jakub Staszak58c1da82012-05-06 13:52:31 +0000763
Owen Andersoneed707b2009-07-24 23:12:02 +0000764 NewIndices.push_back(ConstantInt::get(IntPtrTy, FirstIdx));
Jakub Staszak58c1da82012-05-06 13:52:31 +0000765
Chris Lattner46cd5a12009-01-09 05:44:56 +0000766 // Index into the types. If we fail, set OrigBase to null.
767 while (Offset) {
Chris Lattnerdbc3bc22009-01-11 20:15:20 +0000768 // Indexing into tail padding between struct/array elements.
769 if (uint64_t(Offset*8) >= TD->getTypeSizeInBits(Ty))
Chris Lattner3914f722009-01-24 01:00:13 +0000770 return 0;
Jakub Staszak58c1da82012-05-06 13:52:31 +0000771
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000772 if (StructType *STy = dyn_cast<StructType>(Ty)) {
Chris Lattner46cd5a12009-01-09 05:44:56 +0000773 const StructLayout *SL = TD->getStructLayout(STy);
Chris Lattnerdbc3bc22009-01-11 20:15:20 +0000774 assert(Offset < (int64_t)SL->getSizeInBytes() &&
775 "Offset must stay within the indexed type");
Jakub Staszak58c1da82012-05-06 13:52:31 +0000776
Chris Lattner46cd5a12009-01-09 05:44:56 +0000777 unsigned Elt = SL->getElementContainingOffset(Offset);
Chris Lattner4de84762010-01-04 07:02:48 +0000778 NewIndices.push_back(ConstantInt::get(Type::getInt32Ty(Ty->getContext()),
779 Elt));
Jakub Staszak58c1da82012-05-06 13:52:31 +0000780
Chris Lattner46cd5a12009-01-09 05:44:56 +0000781 Offset -= SL->getElementOffset(Elt);
782 Ty = STy->getElementType(Elt);
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000783 } else if (ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
Duncan Sands777d2302009-05-09 07:06:46 +0000784 uint64_t EltSize = TD->getTypeAllocSize(AT->getElementType());
Chris Lattnerdbc3bc22009-01-11 20:15:20 +0000785 assert(EltSize && "Cannot index into a zero-sized array");
Owen Andersoneed707b2009-07-24 23:12:02 +0000786 NewIndices.push_back(ConstantInt::get(IntPtrTy,Offset/EltSize));
Chris Lattnerdbc3bc22009-01-11 20:15:20 +0000787 Offset %= EltSize;
Chris Lattner1c412d92009-01-11 20:23:52 +0000788 Ty = AT->getElementType();
Chris Lattner46cd5a12009-01-09 05:44:56 +0000789 } else {
Chris Lattnerdbc3bc22009-01-11 20:15:20 +0000790 // Otherwise, we can't index into the middle of this atomic type, bail.
Chris Lattner3914f722009-01-24 01:00:13 +0000791 return 0;
Chris Lattner46cd5a12009-01-09 05:44:56 +0000792 }
793 }
Jakub Staszak58c1da82012-05-06 13:52:31 +0000794
Chris Lattner3914f722009-01-24 01:00:13 +0000795 return Ty;
Chris Lattner46cd5a12009-01-09 05:44:56 +0000796}
797
Rafael Espindola592ad6a2011-07-31 04:43:41 +0000798static bool shouldMergeGEPs(GEPOperator &GEP, GEPOperator &Src) {
799 // If this GEP has only 0 indices, it is the same pointer as
800 // Src. If Src is not a trivial GEP too, don't combine
801 // the indices.
802 if (GEP.hasAllZeroIndices() && !Src.hasAllZeroIndices() &&
803 !Src.hasOneUse())
804 return false;
805 return true;
806}
Chris Lattner473945d2002-05-06 18:06:38 +0000807
Duncan Sandsbbc70162012-10-23 08:28:26 +0000808/// Descale - Return a value X such that Val = X * Scale, or null if none. If
809/// the multiplication is known not to overflow then NoSignedWrap is set.
810Value *InstCombiner::Descale(Value *Val, APInt Scale, bool &NoSignedWrap) {
811 assert(isa<IntegerType>(Val->getType()) && "Can only descale integers!");
812 assert(cast<IntegerType>(Val->getType())->getBitWidth() ==
813 Scale.getBitWidth() && "Scale not compatible with value!");
814
815 // If Val is zero or Scale is one then Val = Val * Scale.
816 if (match(Val, m_Zero()) || Scale == 1) {
817 NoSignedWrap = true;
818 return Val;
819 }
820
821 // If Scale is zero then it does not divide Val.
822 if (Scale.isMinValue())
823 return 0;
824
825 // Look through chains of multiplications, searching for a constant that is
826 // divisible by Scale. For example, descaling X*(Y*(Z*4)) by a factor of 4
827 // will find the constant factor 4 and produce X*(Y*Z). Descaling X*(Y*8) by
828 // a factor of 4 will produce X*(Y*2). The principle of operation is to bore
829 // down from Val:
830 //
831 // Val = M1 * X || Analysis starts here and works down
832 // M1 = M2 * Y || Doesn't descend into terms with more
833 // M2 = Z * 4 \/ than one use
834 //
835 // Then to modify a term at the bottom:
836 //
837 // Val = M1 * X
838 // M1 = Z * Y || Replaced M2 with Z
839 //
840 // Then to work back up correcting nsw flags.
841
842 // Op - the term we are currently analyzing. Starts at Val then drills down.
843 // Replaced with its descaled value before exiting from the drill down loop.
844 Value *Op = Val;
845
846 // Parent - initially null, but after drilling down notes where Op came from.
847 // In the example above, Parent is (Val, 0) when Op is M1, because M1 is the
848 // 0'th operand of Val.
849 std::pair<Instruction*, unsigned> Parent;
850
851 // RequireNoSignedWrap - Set if the transform requires a descaling at deeper
852 // levels that doesn't overflow.
853 bool RequireNoSignedWrap = false;
854
855 // logScale - log base 2 of the scale. Negative if not a power of 2.
856 int32_t logScale = Scale.exactLogBase2();
857
858 for (;; Op = Parent.first->getOperand(Parent.second)) { // Drill down
859
860 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op)) {
861 // If Op is a constant divisible by Scale then descale to the quotient.
862 APInt Quotient(Scale), Remainder(Scale); // Init ensures right bitwidth.
863 APInt::sdivrem(CI->getValue(), Scale, Quotient, Remainder);
864 if (!Remainder.isMinValue())
865 // Not divisible by Scale.
866 return 0;
867 // Replace with the quotient in the parent.
868 Op = ConstantInt::get(CI->getType(), Quotient);
869 NoSignedWrap = true;
870 break;
871 }
872
873 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op)) {
874
875 if (BO->getOpcode() == Instruction::Mul) {
876 // Multiplication.
877 NoSignedWrap = BO->hasNoSignedWrap();
878 if (RequireNoSignedWrap && !NoSignedWrap)
879 return 0;
880
881 // There are three cases for multiplication: multiplication by exactly
882 // the scale, multiplication by a constant different to the scale, and
883 // multiplication by something else.
884 Value *LHS = BO->getOperand(0);
885 Value *RHS = BO->getOperand(1);
886
887 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHS)) {
888 // Multiplication by a constant.
889 if (CI->getValue() == Scale) {
890 // Multiplication by exactly the scale, replace the multiplication
891 // by its left-hand side in the parent.
892 Op = LHS;
893 break;
894 }
895
896 // Otherwise drill down into the constant.
897 if (!Op->hasOneUse())
898 return 0;
899
900 Parent = std::make_pair(BO, 1);
901 continue;
902 }
903
904 // Multiplication by something else. Drill down into the left-hand side
905 // since that's where the reassociate pass puts the good stuff.
906 if (!Op->hasOneUse())
907 return 0;
908
909 Parent = std::make_pair(BO, 0);
910 continue;
911 }
912
913 if (logScale > 0 && BO->getOpcode() == Instruction::Shl &&
914 isa<ConstantInt>(BO->getOperand(1))) {
915 // Multiplication by a power of 2.
916 NoSignedWrap = BO->hasNoSignedWrap();
917 if (RequireNoSignedWrap && !NoSignedWrap)
918 return 0;
919
920 Value *LHS = BO->getOperand(0);
921 int32_t Amt = cast<ConstantInt>(BO->getOperand(1))->
922 getLimitedValue(Scale.getBitWidth());
923 // Op = LHS << Amt.
924
925 if (Amt == logScale) {
926 // Multiplication by exactly the scale, replace the multiplication
927 // by its left-hand side in the parent.
928 Op = LHS;
929 break;
930 }
931 if (Amt < logScale || !Op->hasOneUse())
932 return 0;
933
934 // Multiplication by more than the scale. Reduce the multiplying amount
935 // by the scale in the parent.
936 Parent = std::make_pair(BO, 1);
937 Op = ConstantInt::get(BO->getType(), Amt - logScale);
938 break;
939 }
940 }
941
942 if (!Op->hasOneUse())
943 return 0;
944
945 if (CastInst *Cast = dyn_cast<CastInst>(Op)) {
946 if (Cast->getOpcode() == Instruction::SExt) {
947 // Op is sign-extended from a smaller type, descale in the smaller type.
948 unsigned SmallSize = Cast->getSrcTy()->getPrimitiveSizeInBits();
949 APInt SmallScale = Scale.trunc(SmallSize);
950 // Suppose Op = sext X, and we descale X as Y * SmallScale. We want to
951 // descale Op as (sext Y) * Scale. In order to have
952 // sext (Y * SmallScale) = (sext Y) * Scale
953 // some conditions need to hold however: SmallScale must sign-extend to
954 // Scale and the multiplication Y * SmallScale should not overflow.
955 if (SmallScale.sext(Scale.getBitWidth()) != Scale)
956 // SmallScale does not sign-extend to Scale.
957 return 0;
958 assert(SmallScale.exactLogBase2() == logScale);
959 // Require that Y * SmallScale must not overflow.
960 RequireNoSignedWrap = true;
961
962 // Drill down through the cast.
963 Parent = std::make_pair(Cast, 0);
964 Scale = SmallScale;
965 continue;
966 }
967
Duncan Sandsf1ec4e42012-10-23 09:07:02 +0000968 if (Cast->getOpcode() == Instruction::Trunc) {
Duncan Sandsbbc70162012-10-23 08:28:26 +0000969 // Op is truncated from a larger type, descale in the larger type.
970 // Suppose Op = trunc X, and we descale X as Y * sext Scale. Then
971 // trunc (Y * sext Scale) = (trunc Y) * Scale
972 // always holds. However (trunc Y) * Scale may overflow even if
973 // trunc (Y * sext Scale) does not, so nsw flags need to be cleared
974 // from this point up in the expression (see later).
975 if (RequireNoSignedWrap)
976 return 0;
977
978 // Drill down through the cast.
979 unsigned LargeSize = Cast->getSrcTy()->getPrimitiveSizeInBits();
980 Parent = std::make_pair(Cast, 0);
981 Scale = Scale.sext(LargeSize);
982 if (logScale + 1 == (int32_t)Cast->getType()->getPrimitiveSizeInBits())
983 logScale = -1;
984 assert(Scale.exactLogBase2() == logScale);
985 continue;
986 }
987 }
988
989 // Unsupported expression, bail out.
990 return 0;
991 }
992
993 // We know that we can successfully descale, so from here on we can safely
994 // modify the IR. Op holds the descaled version of the deepest term in the
995 // expression. NoSignedWrap is 'true' if multiplying Op by Scale is known
996 // not to overflow.
997
998 if (!Parent.first)
999 // The expression only had one term.
1000 return Op;
1001
1002 // Rewrite the parent using the descaled version of its operand.
1003 assert(Parent.first->hasOneUse() && "Drilled down when more than one use!");
1004 assert(Op != Parent.first->getOperand(Parent.second) &&
1005 "Descaling was a no-op?");
1006 Parent.first->setOperand(Parent.second, Op);
1007 Worklist.Add(Parent.first);
1008
1009 // Now work back up the expression correcting nsw flags. The logic is based
1010 // on the following observation: if X * Y is known not to overflow as a signed
1011 // multiplication, and Y is replaced by a value Z with smaller absolute value,
1012 // then X * Z will not overflow as a signed multiplication either. As we work
1013 // our way up, having NoSignedWrap 'true' means that the descaled value at the
1014 // current level has strictly smaller absolute value than the original.
1015 Instruction *Ancestor = Parent.first;
1016 do {
1017 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Ancestor)) {
1018 // If the multiplication wasn't nsw then we can't say anything about the
1019 // value of the descaled multiplication, and we have to clear nsw flags
1020 // from this point on up.
1021 bool OpNoSignedWrap = BO->hasNoSignedWrap();
1022 NoSignedWrap &= OpNoSignedWrap;
1023 if (NoSignedWrap != OpNoSignedWrap) {
1024 BO->setHasNoSignedWrap(NoSignedWrap);
1025 Worklist.Add(Ancestor);
1026 }
1027 } else if (Ancestor->getOpcode() == Instruction::Trunc) {
1028 // The fact that the descaled input to the trunc has smaller absolute
1029 // value than the original input doesn't tell us anything useful about
1030 // the absolute values of the truncations.
1031 NoSignedWrap = false;
1032 }
1033 assert((Ancestor->getOpcode() != Instruction::SExt || NoSignedWrap) &&
1034 "Failed to keep proper track of nsw flags while drilling down?");
1035
1036 if (Ancestor == Val)
1037 // Got to the top, all done!
1038 return Val;
1039
1040 // Move up one level in the expression.
1041 assert(Ancestor->hasOneUse() && "Drilled down when more than one use!");
1042 Ancestor = Ancestor->use_back();
1043 } while (1);
1044}
1045
Chris Lattner7e708292002-06-25 16:13:24 +00001046Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
Chris Lattnerc514c1f2009-11-27 00:29:05 +00001047 SmallVector<Value*, 8> Ops(GEP.op_begin(), GEP.op_end());
1048
Jay Foadb9b54eb2011-07-19 15:07:52 +00001049 if (Value *V = SimplifyGEPInst(Ops, TD))
Chris Lattnerc514c1f2009-11-27 00:29:05 +00001050 return ReplaceInstUsesWith(GEP, V);
1051
Chris Lattner620ce142004-05-07 22:09:22 +00001052 Value *PtrOp = GEP.getOperand(0);
Chris Lattnerc6bd1952004-02-22 05:25:17 +00001053
Duncan Sandsa63395a2010-11-22 16:32:50 +00001054 // Eliminate unneeded casts for indices, and replace indices which displace
1055 // by multiples of a zero size type with zero.
Chris Lattnerccf4b342009-08-30 04:49:01 +00001056 if (TD) {
1057 bool MadeChange = false;
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001058 Type *IntPtrTy = TD->getIntPtrType(GEP.getContext());
Duncan Sandsa63395a2010-11-22 16:32:50 +00001059
Chris Lattnerccf4b342009-08-30 04:49:01 +00001060 gep_type_iterator GTI = gep_type_begin(GEP);
1061 for (User::op_iterator I = GEP.op_begin() + 1, E = GEP.op_end();
1062 I != E; ++I, ++GTI) {
Duncan Sandsa63395a2010-11-22 16:32:50 +00001063 // Skip indices into struct types.
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001064 SequentialType *SeqTy = dyn_cast<SequentialType>(*GTI);
Duncan Sandsa63395a2010-11-22 16:32:50 +00001065 if (!SeqTy) continue;
1066
1067 // If the element type has zero size then any index over it is equivalent
1068 // to an index of zero, so replace it with zero if it is not zero already.
1069 if (SeqTy->getElementType()->isSized() &&
1070 TD->getTypeAllocSize(SeqTy->getElementType()) == 0)
1071 if (!isa<Constant>(*I) || !cast<Constant>(*I)->isNullValue()) {
1072 *I = Constant::getNullValue(IntPtrTy);
1073 MadeChange = true;
1074 }
1075
Nadav Rotem16087692011-12-05 06:29:09 +00001076 Type *IndexTy = (*I)->getType();
1077 if (IndexTy != IntPtrTy && !IndexTy->isVectorTy()) {
Duncan Sandsa63395a2010-11-22 16:32:50 +00001078 // If we are using a wider index than needed for this platform, shrink
1079 // it to what we need. If narrower, sign-extend it to what we need.
1080 // This explicit cast can make subsequent optimizations more obvious.
1081 *I = Builder->CreateIntCast(*I, IntPtrTy, true);
1082 MadeChange = true;
1083 }
Chris Lattner28977af2004-04-05 01:30:19 +00001084 }
Chris Lattnerccf4b342009-08-30 04:49:01 +00001085 if (MadeChange) return &GEP;
Chris Lattnerdb9654e2007-03-25 20:43:09 +00001086 }
Chris Lattner28977af2004-04-05 01:30:19 +00001087
Chris Lattner90ac28c2002-08-02 19:29:35 +00001088 // Combine Indices - If the source pointer to this getelementptr instruction
1089 // is a getelementptr instruction, combine the indices of the two
1090 // getelementptr instructions into a single instruction.
1091 //
Dan Gohmand6aa02d2009-07-28 01:40:03 +00001092 if (GEPOperator *Src = dyn_cast<GEPOperator>(PtrOp)) {
Rafael Espindola592ad6a2011-07-31 04:43:41 +00001093 if (!shouldMergeGEPs(*cast<GEPOperator>(&GEP), *Src))
Rafael Espindolab5a12dd2011-07-11 03:43:47 +00001094 return 0;
1095
Duncan Sandsbbc70162012-10-23 08:28:26 +00001096 // Note that if our source is a gep chain itself then we wait for that
Chris Lattner620ce142004-05-07 22:09:22 +00001097 // chain to be resolved before we perform this transformation. This
1098 // avoids us creating a TON of code in some cases.
Rafael Espindola592ad6a2011-07-31 04:43:41 +00001099 if (GEPOperator *SrcGEP =
1100 dyn_cast<GEPOperator>(Src->getOperand(0)))
1101 if (SrcGEP->getNumOperands() == 2 && shouldMergeGEPs(*Src, *SrcGEP))
Chris Lattnerf9b91bb2009-08-30 05:08:50 +00001102 return 0; // Wait until our source is folded to completion.
Chris Lattner620ce142004-05-07 22:09:22 +00001103
Chris Lattner72588fc2007-02-15 22:48:32 +00001104 SmallVector<Value*, 8> Indices;
Chris Lattner620ce142004-05-07 22:09:22 +00001105
1106 // Find out whether the last index in the source GEP is a sequential idx.
1107 bool EndsWithSequential = false;
Chris Lattnerab984842009-08-30 05:30:55 +00001108 for (gep_type_iterator I = gep_type_begin(*Src), E = gep_type_end(*Src);
1109 I != E; ++I)
Duncan Sands1df98592010-02-16 11:11:14 +00001110 EndsWithSequential = !(*I)->isStructTy();
Misha Brukmanfd939082005-04-21 23:48:37 +00001111
Chris Lattner90ac28c2002-08-02 19:29:35 +00001112 // Can we combine the two pointer arithmetics offsets?
Chris Lattner620ce142004-05-07 22:09:22 +00001113 if (EndsWithSequential) {
Chris Lattnerdecd0812003-03-05 22:33:14 +00001114 // Replace: gep (gep %P, long B), long A, ...
1115 // With: T = long A+B; gep %P, T, ...
1116 //
Chris Lattnerf9b91bb2009-08-30 05:08:50 +00001117 Value *Sum;
1118 Value *SO1 = Src->getOperand(Src->getNumOperands()-1);
1119 Value *GO1 = GEP.getOperand(1);
Owen Andersona7235ea2009-07-31 20:28:14 +00001120 if (SO1 == Constant::getNullValue(SO1->getType())) {
Chris Lattner28977af2004-04-05 01:30:19 +00001121 Sum = GO1;
Owen Andersona7235ea2009-07-31 20:28:14 +00001122 } else if (GO1 == Constant::getNullValue(GO1->getType())) {
Chris Lattner28977af2004-04-05 01:30:19 +00001123 Sum = SO1;
1124 } else {
Chris Lattnerab984842009-08-30 05:30:55 +00001125 // If they aren't the same type, then the input hasn't been processed
1126 // by the loop above yet (which canonicalizes sequential index types to
1127 // intptr_t). Just avoid transforming this until the input has been
1128 // normalized.
1129 if (SO1->getType() != GO1->getType())
1130 return 0;
Chris Lattnerf925cbd2009-08-30 18:50:58 +00001131 Sum = Builder->CreateAdd(SO1, GO1, PtrOp->getName()+".sum");
Chris Lattner28977af2004-04-05 01:30:19 +00001132 }
Chris Lattner620ce142004-05-07 22:09:22 +00001133
Chris Lattnerab984842009-08-30 05:30:55 +00001134 // Update the GEP in place if possible.
Chris Lattnerf9b91bb2009-08-30 05:08:50 +00001135 if (Src->getNumOperands() == 2) {
1136 GEP.setOperand(0, Src->getOperand(0));
Chris Lattner620ce142004-05-07 22:09:22 +00001137 GEP.setOperand(1, Sum);
1138 return &GEP;
Chris Lattner620ce142004-05-07 22:09:22 +00001139 }
Chris Lattnerab984842009-08-30 05:30:55 +00001140 Indices.append(Src->op_begin()+1, Src->op_end()-1);
Chris Lattnerccf4b342009-08-30 04:49:01 +00001141 Indices.push_back(Sum);
Chris Lattnerab984842009-08-30 05:30:55 +00001142 Indices.append(GEP.op_begin()+2, GEP.op_end());
Misha Brukmanfd939082005-04-21 23:48:37 +00001143 } else if (isa<Constant>(*GEP.idx_begin()) &&
Chris Lattner28977af2004-04-05 01:30:19 +00001144 cast<Constant>(*GEP.idx_begin())->isNullValue() &&
Chris Lattnerf9b91bb2009-08-30 05:08:50 +00001145 Src->getNumOperands() != 1) {
Chris Lattner90ac28c2002-08-02 19:29:35 +00001146 // Otherwise we can do the fold if the first index of the GEP is a zero
Chris Lattnerab984842009-08-30 05:30:55 +00001147 Indices.append(Src->op_begin()+1, Src->op_end());
1148 Indices.append(GEP.idx_begin()+1, GEP.idx_end());
Chris Lattner90ac28c2002-08-02 19:29:35 +00001149 }
1150
Dan Gohmanf8dbee72009-09-07 23:54:19 +00001151 if (!Indices.empty())
Chris Lattner948cdeb2010-01-05 07:42:10 +00001152 return (GEP.isInBounds() && Src->isInBounds()) ?
Jay Foada9203102011-07-25 09:48:08 +00001153 GetElementPtrInst::CreateInBounds(Src->getOperand(0), Indices,
1154 GEP.getName()) :
1155 GetElementPtrInst::Create(Src->getOperand(0), Indices, GEP.getName());
Chris Lattner6e24d832009-08-30 05:00:50 +00001156 }
Nadav Rotem0286ca82011-04-05 14:29:52 +00001157
Chris Lattnerf9b91bb2009-08-30 05:08:50 +00001158 // Handle gep(bitcast x) and gep(gep x, 0, 0, 0).
Chris Lattner948cdeb2010-01-05 07:42:10 +00001159 Value *StrippedPtr = PtrOp->stripPointerCasts();
Nadav Rotemc71108b2012-03-26 20:39:18 +00001160 PointerType *StrippedPtrTy = dyn_cast<PointerType>(StrippedPtr->getType());
1161
Nadav Rotem02f0a492012-03-26 21:00:53 +00001162 // We do not handle pointer-vector geps here.
1163 if (!StrippedPtrTy)
1164 return 0;
1165
Nadav Rotem0286ca82011-04-05 14:29:52 +00001166 if (StrippedPtr != PtrOp &&
1167 StrippedPtrTy->getAddressSpace() == GEP.getPointerAddressSpace()) {
Chris Lattner963f4ba2009-08-30 20:36:46 +00001168
Chris Lattnerc514c1f2009-11-27 00:29:05 +00001169 bool HasZeroPointerIndex = false;
1170 if (ConstantInt *C = dyn_cast<ConstantInt>(GEP.getOperand(1)))
1171 HasZeroPointerIndex = C->isZero();
Nadav Rotem0286ca82011-04-05 14:29:52 +00001172
Chris Lattner963f4ba2009-08-30 20:36:46 +00001173 // Transform: GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ...
1174 // into : GEP [10 x i8]* X, i32 0, ...
1175 //
1176 // Likewise, transform: GEP (bitcast i8* X to [0 x i8]*), i32 0, ...
1177 // into : GEP i8* X, ...
Nadav Rotem0286ca82011-04-05 14:29:52 +00001178 //
Chris Lattner963f4ba2009-08-30 20:36:46 +00001179 // This occurs when the program declares an array extern like "int X[];"
Chris Lattner6e24d832009-08-30 05:00:50 +00001180 if (HasZeroPointerIndex) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001181 PointerType *CPTy = cast<PointerType>(PtrOp->getType());
1182 if (ArrayType *CATy =
Duncan Sands5b7cfb02009-03-02 09:18:21 +00001183 dyn_cast<ArrayType>(CPTy->getElementType())) {
1184 // GEP (bitcast i8* X to [0 x i8]*), i32 0, ... ?
Chris Lattner948cdeb2010-01-05 07:42:10 +00001185 if (CATy->getElementType() == StrippedPtrTy->getElementType()) {
Duncan Sands5b7cfb02009-03-02 09:18:21 +00001186 // -> GEP i8* X, ...
Chris Lattner948cdeb2010-01-05 07:42:10 +00001187 SmallVector<Value*, 8> Idx(GEP.idx_begin()+1, GEP.idx_end());
1188 GetElementPtrInst *Res =
Jay Foada9203102011-07-25 09:48:08 +00001189 GetElementPtrInst::Create(StrippedPtr, Idx, GEP.getName());
Chris Lattner948cdeb2010-01-05 07:42:10 +00001190 Res->setIsInBounds(GEP.isInBounds());
1191 return Res;
Chris Lattner963f4ba2009-08-30 20:36:46 +00001192 }
Jakub Staszak58c1da82012-05-06 13:52:31 +00001193
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001194 if (ArrayType *XATy =
Chris Lattner948cdeb2010-01-05 07:42:10 +00001195 dyn_cast<ArrayType>(StrippedPtrTy->getElementType())){
Duncan Sands5b7cfb02009-03-02 09:18:21 +00001196 // GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ... ?
Chris Lattnereed48272005-09-13 00:40:14 +00001197 if (CATy->getElementType() == XATy->getElementType()) {
Duncan Sands5b7cfb02009-03-02 09:18:21 +00001198 // -> GEP [10 x i8]* X, i32 0, ...
Chris Lattnereed48272005-09-13 00:40:14 +00001199 // At this point, we know that the cast source type is a pointer
1200 // to an array of the same type as the destination pointer
1201 // array. Because the array type is never stepped over (there
1202 // is a leading zero) we can fold the cast into this GEP.
Chris Lattner948cdeb2010-01-05 07:42:10 +00001203 GEP.setOperand(0, StrippedPtr);
Chris Lattnereed48272005-09-13 00:40:14 +00001204 return &GEP;
1205 }
Duncan Sands5b7cfb02009-03-02 09:18:21 +00001206 }
1207 }
Chris Lattnereed48272005-09-13 00:40:14 +00001208 } else if (GEP.getNumOperands() == 2) {
1209 // Transform things like:
Wojciech Matyjewiczed223252007-12-12 15:21:32 +00001210 // %t = getelementptr i32* bitcast ([2 x i32]* %str to i32*), i32 %V
1211 // into: %t1 = getelementptr [2 x i32]* %str, i32 0, i32 %V; bitcast
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001212 Type *SrcElTy = StrippedPtrTy->getElementType();
1213 Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
Duncan Sands1df98592010-02-16 11:11:14 +00001214 if (TD && SrcElTy->isArrayTy() &&
Duncan Sands777d2302009-05-09 07:06:46 +00001215 TD->getTypeAllocSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
1216 TD->getTypeAllocSize(ResElTy)) {
David Greeneb8f74792007-09-04 15:46:09 +00001217 Value *Idx[2];
Chris Lattner4de84762010-01-04 07:02:48 +00001218 Idx[0] = Constant::getNullValue(Type::getInt32Ty(GEP.getContext()));
David Greeneb8f74792007-09-04 15:46:09 +00001219 Idx[1] = GEP.getOperand(1);
Chris Lattner948cdeb2010-01-05 07:42:10 +00001220 Value *NewGEP = GEP.isInBounds() ?
Jay Foad0a2a60a2011-07-22 08:16:57 +00001221 Builder->CreateInBoundsGEP(StrippedPtr, Idx, GEP.getName()) :
1222 Builder->CreateGEP(StrippedPtr, Idx, GEP.getName());
Reid Spencer3da59db2006-11-27 01:05:10 +00001223 // V and GEP are both pointer types --> BitCast
Chris Lattnerf925cbd2009-08-30 18:50:58 +00001224 return new BitCastInst(NewGEP, GEP.getType());
Chris Lattnerc6bd1952004-02-22 05:25:17 +00001225 }
Jakub Staszak58c1da82012-05-06 13:52:31 +00001226
Chris Lattner7835cdd2005-09-13 18:36:04 +00001227 // Transform things like:
Duncan Sandsbbc70162012-10-23 08:28:26 +00001228 // %V = mul i64 %N, 4
1229 // %t = getelementptr i8* bitcast (i32* %arr to i8*), i32 %V
1230 // into: %t1 = getelementptr i32* %arr, i32 %N; bitcast
1231 if (TD && ResElTy->isSized() && SrcElTy->isSized()) {
1232 // Check that changing the type amounts to dividing the index by a scale
1233 // factor.
1234 uint64_t ResSize = TD->getTypeAllocSize(ResElTy);
1235 uint64_t SrcSize = TD->getTypeAllocSize(SrcElTy);
1236 if (ResSize && SrcSize % ResSize == 0) {
1237 Value *Idx = GEP.getOperand(1);
1238 unsigned BitWidth = Idx->getType()->getPrimitiveSizeInBits();
1239 uint64_t Scale = SrcSize / ResSize;
1240
1241 // Earlier transforms ensure that the index has type IntPtrType, which
1242 // considerably simplifies the logic by eliminating implicit casts.
1243 assert(Idx->getType() == TD->getIntPtrType(GEP.getContext()) &&
1244 "Index not cast to pointer width?");
1245
1246 bool NSW;
1247 if (Value *NewIdx = Descale(Idx, APInt(BitWidth, Scale), NSW)) {
1248 // Successfully decomposed Idx as NewIdx * Scale, form a new GEP.
1249 // If the multiplication NewIdx * Scale may overflow then the new
1250 // GEP may not be "inbounds".
1251 Value *NewGEP = GEP.isInBounds() && NSW ?
1252 Builder->CreateInBoundsGEP(StrippedPtr, NewIdx, GEP.getName()) :
1253 Builder->CreateGEP(StrippedPtr, NewIdx, GEP.getName());
1254 // The NewGEP must be pointer typed, so must the old one -> BitCast
1255 return new BitCastInst(NewGEP, GEP.getType());
1256 }
1257 }
1258 }
1259
1260 // Similarly, transform things like:
Wojciech Matyjewiczed223252007-12-12 15:21:32 +00001261 // getelementptr i8* bitcast ([100 x double]* X to i8*), i32 %tmp
Chris Lattner7835cdd2005-09-13 18:36:04 +00001262 // (where tmp = 8*tmp2) into:
Wojciech Matyjewiczed223252007-12-12 15:21:32 +00001263 // getelementptr [100 x double]* %arr, i32 0, i32 %tmp2; bitcast
Duncan Sandsbbc70162012-10-23 08:28:26 +00001264 if (TD && ResElTy->isSized() && SrcElTy->isSized() &&
1265 SrcElTy->isArrayTy()) {
1266 // Check that changing to the array element type amounts to dividing the
1267 // index by a scale factor.
1268 uint64_t ResSize = TD->getTypeAllocSize(ResElTy);
Chris Lattner7835cdd2005-09-13 18:36:04 +00001269 uint64_t ArrayEltSize =
Duncan Sandsbbc70162012-10-23 08:28:26 +00001270 TD->getTypeAllocSize(cast<ArrayType>(SrcElTy)->getElementType());
1271 if (ResSize && ArrayEltSize % ResSize == 0) {
1272 Value *Idx = GEP.getOperand(1);
1273 unsigned BitWidth = Idx->getType()->getPrimitiveSizeInBits();
1274 uint64_t Scale = ArrayEltSize / ResSize;
Jakub Staszak58c1da82012-05-06 13:52:31 +00001275
Duncan Sandsbbc70162012-10-23 08:28:26 +00001276 // Earlier transforms ensure that the index has type IntPtrType, which
1277 // considerably simplifies the logic by eliminating implicit casts.
1278 assert(Idx->getType() == TD->getIntPtrType(GEP.getContext()) &&
1279 "Index not cast to pointer width?");
1280
1281 bool NSW;
1282 if (Value *NewIdx = Descale(Idx, APInt(BitWidth, Scale), NSW)) {
1283 // Successfully decomposed Idx as NewIdx * Scale, form a new GEP.
1284 // If the multiplication NewIdx * Scale may overflow then the new
1285 // GEP may not be "inbounds".
1286 Value *Off[2];
1287 Off[0] = Constant::getNullValue(Type::getInt32Ty(GEP.getContext()));
1288 Off[1] = NewIdx;
1289 Value *NewGEP = GEP.isInBounds() && NSW ?
1290 Builder->CreateInBoundsGEP(StrippedPtr, Off, GEP.getName()) :
1291 Builder->CreateGEP(StrippedPtr, Off, GEP.getName());
1292 // The NewGEP must be pointer typed, so must the old one -> BitCast
1293 return new BitCastInst(NewGEP, GEP.getType());
Chris Lattner7835cdd2005-09-13 18:36:04 +00001294 }
1295 }
Chris Lattner7835cdd2005-09-13 18:36:04 +00001296 }
Chris Lattnerc6bd1952004-02-22 05:25:17 +00001297 }
Chris Lattner8a2a3112001-12-14 16:52:21 +00001298 }
Nadav Rotem0286ca82011-04-05 14:29:52 +00001299
Chris Lattner46cd5a12009-01-09 05:44:56 +00001300 /// See if we can simplify:
Chris Lattner873ff012009-08-30 05:55:36 +00001301 /// X = bitcast A* to B*
Chris Lattner46cd5a12009-01-09 05:44:56 +00001302 /// Y = gep X, <...constant indices...>
1303 /// into a gep of the original struct. This is important for SROA and alias
1304 /// analysis of unions. If "A" is also a bitcast, wait for A/X to be merged.
Chris Lattner58407792009-01-09 04:53:57 +00001305 if (BitCastInst *BCI = dyn_cast<BitCastInst>(PtrOp)) {
Dan Gohmance9fe9f2009-07-21 23:21:54 +00001306 if (TD &&
Nadav Rotem0286ca82011-04-05 14:29:52 +00001307 !isa<BitCastInst>(BCI->getOperand(0)) && GEP.hasAllConstantIndices() &&
1308 StrippedPtrTy->getAddressSpace() == GEP.getPointerAddressSpace()) {
1309
Nuno Lopesb47f3ea2012-06-20 17:30:51 +00001310 // Determine how much the GEP moves the pointer.
1311 SmallVector<Value*, 8> Ops(GEP.idx_begin(), GEP.idx_end());
1312 int64_t Offset = TD->getIndexedOffset(GEP.getPointerOperandType(), Ops);
Nadav Rotem0286ca82011-04-05 14:29:52 +00001313
Chris Lattner46cd5a12009-01-09 05:44:56 +00001314 // If this GEP instruction doesn't move the pointer, just replace the GEP
1315 // with a bitcast of the real input to the dest type.
1316 if (Offset == 0) {
1317 // If the bitcast is of an allocation, and the allocation will be
1318 // converted to match the type of the cast, don't touch this.
Victor Hernandez7b929da2009-10-23 21:09:37 +00001319 if (isa<AllocaInst>(BCI->getOperand(0)) ||
Benjamin Kramer8e0d1c02012-08-29 15:32:21 +00001320 isAllocationFn(BCI->getOperand(0), TLI)) {
Chris Lattner46cd5a12009-01-09 05:44:56 +00001321 // See if the bitcast simplifies, if so, don't nuke this GEP yet.
1322 if (Instruction *I = visitBitCast(*BCI)) {
1323 if (I != BCI) {
1324 I->takeName(BCI);
1325 BCI->getParent()->getInstList().insert(BCI, I);
1326 ReplaceInstUsesWith(*BCI, I);
1327 }
1328 return &GEP;
Chris Lattner58407792009-01-09 04:53:57 +00001329 }
Chris Lattner58407792009-01-09 04:53:57 +00001330 }
Chris Lattner46cd5a12009-01-09 05:44:56 +00001331 return new BitCastInst(BCI->getOperand(0), GEP.getType());
Chris Lattner58407792009-01-09 04:53:57 +00001332 }
Jakub Staszak58c1da82012-05-06 13:52:31 +00001333
Chris Lattner46cd5a12009-01-09 05:44:56 +00001334 // Otherwise, if the offset is non-zero, we need to find out if there is a
1335 // field at Offset in 'A's type. If so, we can pull the cast through the
1336 // GEP.
1337 SmallVector<Value*, 8> NewIndices;
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001338 Type *InTy =
Chris Lattner46cd5a12009-01-09 05:44:56 +00001339 cast<PointerType>(BCI->getOperand(0)->getType())->getElementType();
Chris Lattner80f43d32010-01-04 07:53:58 +00001340 if (FindElementAtOffset(InTy, Offset, NewIndices)) {
Chris Lattner948cdeb2010-01-05 07:42:10 +00001341 Value *NGEP = GEP.isInBounds() ?
Jay Foad0a2a60a2011-07-22 08:16:57 +00001342 Builder->CreateInBoundsGEP(BCI->getOperand(0), NewIndices) :
1343 Builder->CreateGEP(BCI->getOperand(0), NewIndices);
Jakub Staszak58c1da82012-05-06 13:52:31 +00001344
Chris Lattnerf925cbd2009-08-30 18:50:58 +00001345 if (NGEP->getType() == GEP.getType())
1346 return ReplaceInstUsesWith(GEP, NGEP);
Chris Lattner46cd5a12009-01-09 05:44:56 +00001347 NGEP->takeName(&GEP);
1348 return new BitCastInst(NGEP, GEP.getType());
1349 }
Chris Lattner58407792009-01-09 04:53:57 +00001350 }
Jakub Staszak58c1da82012-05-06 13:52:31 +00001351 }
1352
Chris Lattner8a2a3112001-12-14 16:52:21 +00001353 return 0;
1354}
1355
Duncan Sands1d9b9732010-05-27 19:09:06 +00001356
1357
Nuno Lopes78f8ef42012-07-09 18:38:20 +00001358static bool
Benjamin Kramer8e0d1c02012-08-29 15:32:21 +00001359isAllocSiteRemovable(Instruction *AI, SmallVectorImpl<WeakVH> &Users,
1360 const TargetLibraryInfo *TLI) {
Nuno Lopes78f8ef42012-07-09 18:38:20 +00001361 SmallVector<Instruction*, 4> Worklist;
1362 Worklist.push_back(AI);
Nick Lewyckyd8030c72011-08-02 22:08:01 +00001363
Nuno Lopes78f8ef42012-07-09 18:38:20 +00001364 do {
1365 Instruction *PI = Worklist.pop_back_val();
1366 for (Value::use_iterator UI = PI->use_begin(), UE = PI->use_end(); UI != UE;
1367 ++UI) {
1368 Instruction *I = cast<Instruction>(*UI);
1369 switch (I->getOpcode()) {
1370 default:
1371 // Give up the moment we see something we can't handle.
Nuno Lopes99694582012-07-06 23:09:25 +00001372 return false;
Nuno Lopes78f8ef42012-07-09 18:38:20 +00001373
1374 case Instruction::BitCast:
1375 case Instruction::GetElementPtr:
1376 Users.push_back(I);
1377 Worklist.push_back(I);
1378 continue;
1379
1380 case Instruction::ICmp: {
1381 ICmpInst *ICI = cast<ICmpInst>(I);
1382 // We can fold eq/ne comparisons with null to false/true, respectively.
1383 if (!ICI->isEquality() || !isa<ConstantPointerNull>(ICI->getOperand(1)))
1384 return false;
1385 Users.push_back(I);
1386 continue;
1387 }
1388
1389 case Instruction::Call:
1390 // Ignore no-op and store intrinsics.
1391 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
1392 switch (II->getIntrinsicID()) {
1393 default:
1394 return false;
1395
1396 case Intrinsic::memmove:
1397 case Intrinsic::memcpy:
1398 case Intrinsic::memset: {
1399 MemIntrinsic *MI = cast<MemIntrinsic>(II);
1400 if (MI->isVolatile() || MI->getRawDest() != PI)
1401 return false;
1402 }
1403 // fall through
1404 case Intrinsic::dbg_declare:
1405 case Intrinsic::dbg_value:
1406 case Intrinsic::invariant_start:
1407 case Intrinsic::invariant_end:
1408 case Intrinsic::lifetime_start:
1409 case Intrinsic::lifetime_end:
1410 case Intrinsic::objectsize:
1411 Users.push_back(I);
1412 continue;
1413 }
1414 }
1415
Benjamin Kramer8e0d1c02012-08-29 15:32:21 +00001416 if (isFreeCall(I, TLI)) {
Nuno Lopes78f8ef42012-07-09 18:38:20 +00001417 Users.push_back(I);
1418 continue;
1419 }
1420 return false;
1421
1422 case Instruction::Store: {
1423 StoreInst *SI = cast<StoreInst>(I);
1424 if (SI->isVolatile() || SI->getPointerOperand() != PI)
1425 return false;
1426 Users.push_back(I);
1427 continue;
1428 }
1429 }
1430 llvm_unreachable("missing a return?");
Nuno Lopes99694582012-07-06 23:09:25 +00001431 }
Nuno Lopes78f8ef42012-07-09 18:38:20 +00001432 } while (!Worklist.empty());
Duncan Sands1d9b9732010-05-27 19:09:06 +00001433 return true;
1434}
1435
Nuno Lopes78f8ef42012-07-09 18:38:20 +00001436Instruction *InstCombiner::visitAllocSite(Instruction &MI) {
Duncan Sands1d9b9732010-05-27 19:09:06 +00001437 // If we have a malloc call which is only used in any amount of comparisons
1438 // to null and free calls, delete the calls and replace the comparisons with
1439 // true or false as appropriate.
Nick Lewyckyd5061a92011-08-03 00:43:35 +00001440 SmallVector<WeakVH, 64> Users;
Benjamin Kramer8e0d1c02012-08-29 15:32:21 +00001441 if (isAllocSiteRemovable(&MI, Users, TLI)) {
Nick Lewyckyd5061a92011-08-03 00:43:35 +00001442 for (unsigned i = 0, e = Users.size(); i != e; ++i) {
1443 Instruction *I = cast_or_null<Instruction>(&*Users[i]);
1444 if (!I) continue;
Duncan Sands1d9b9732010-05-27 19:09:06 +00001445
Nick Lewyckyd5061a92011-08-03 00:43:35 +00001446 if (ICmpInst *C = dyn_cast<ICmpInst>(I)) {
Nick Lewyckyd8030c72011-08-02 22:08:01 +00001447 ReplaceInstUsesWith(*C,
1448 ConstantInt::get(Type::getInt1Ty(C->getContext()),
1449 C->isFalseWhenEqual()));
Nick Lewyckyd5061a92011-08-03 00:43:35 +00001450 } else if (isa<BitCastInst>(I) || isa<GetElementPtrInst>(I)) {
Nick Lewyckyd8030c72011-08-02 22:08:01 +00001451 ReplaceInstUsesWith(*I, UndefValue::get(I->getType()));
Nuno Lopes99694582012-07-06 23:09:25 +00001452 } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
1453 if (II->getIntrinsicID() == Intrinsic::objectsize) {
1454 ConstantInt *CI = cast<ConstantInt>(II->getArgOperand(1));
1455 uint64_t DontKnow = CI->isZero() ? -1ULL : 0;
1456 ReplaceInstUsesWith(*I, ConstantInt::get(I->getType(), DontKnow));
1457 }
Duncan Sands1d9b9732010-05-27 19:09:06 +00001458 }
Nick Lewyckyd5061a92011-08-03 00:43:35 +00001459 EraseInstFromFunction(*I);
Duncan Sands1d9b9732010-05-27 19:09:06 +00001460 }
Nuno Lopes2b3e9582012-06-21 21:25:05 +00001461
1462 if (InvokeInst *II = dyn_cast<InvokeInst>(&MI)) {
Nuno Lopesc363c742012-06-28 22:31:24 +00001463 // Replace invoke with a NOP intrinsic to maintain the original CFG
Nuno Lopes3769fe12012-06-25 17:11:47 +00001464 Module *M = II->getParent()->getParent()->getParent();
Nuno Lopesc363c742012-06-28 22:31:24 +00001465 Function *F = Intrinsic::getDeclaration(M, Intrinsic::donothing);
1466 InvokeInst::Create(F, II->getNormalDest(), II->getUnwindDest(),
1467 ArrayRef<Value *>(), "", II->getParent());
Nuno Lopes2b3e9582012-06-21 21:25:05 +00001468 }
Duncan Sands1d9b9732010-05-27 19:09:06 +00001469 return EraseInstFromFunction(MI);
1470 }
1471 return 0;
1472}
1473
1474
1475
Gabor Greif91697372010-06-24 12:21:15 +00001476Instruction *InstCombiner::visitFree(CallInst &FI) {
1477 Value *Op = FI.getArgOperand(0);
Victor Hernandez66284e02009-10-24 04:23:03 +00001478
1479 // free undef -> unreachable.
1480 if (isa<UndefValue>(Op)) {
1481 // Insert a new store to null because we cannot modify the CFG here.
Eli Friedmane6f364b2011-05-18 23:58:37 +00001482 Builder->CreateStore(ConstantInt::getTrue(FI.getContext()),
1483 UndefValue::get(Type::getInt1PtrTy(FI.getContext())));
Victor Hernandez66284e02009-10-24 04:23:03 +00001484 return EraseInstFromFunction(FI);
1485 }
Jakub Staszak58c1da82012-05-06 13:52:31 +00001486
Victor Hernandez66284e02009-10-24 04:23:03 +00001487 // If we have 'free null' delete the instruction. This can happen in stl code
1488 // when lots of inlining happens.
1489 if (isa<ConstantPointerNull>(Op))
1490 return EraseInstFromFunction(FI);
1491
Victor Hernandez66284e02009-10-24 04:23:03 +00001492 return 0;
1493}
Chris Lattner67b1e1b2003-12-07 01:24:23 +00001494
Chris Lattner3284d1f2007-04-15 00:07:55 +00001495
Chris Lattner2f503e62005-01-31 05:36:43 +00001496
Chris Lattnerc4d10eb2003-06-04 04:46:00 +00001497Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
1498 // Change br (not X), label True, label False to: br X, label False, True
Reid Spencer4b828e62005-06-18 17:37:34 +00001499 Value *X = 0;
Chris Lattneracd1f0f2004-07-30 07:50:03 +00001500 BasicBlock *TrueDest;
1501 BasicBlock *FalseDest;
Dan Gohman4ae51262009-08-12 16:23:25 +00001502 if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
Chris Lattneracd1f0f2004-07-30 07:50:03 +00001503 !isa<Constant>(X)) {
1504 // Swap Destinations and condition...
1505 BI.setCondition(X);
Chandler Carruth602650c2011-10-17 01:11:57 +00001506 BI.swapSuccessors();
Chris Lattneracd1f0f2004-07-30 07:50:03 +00001507 return &BI;
1508 }
1509
Reid Spencere4d87aa2006-12-23 06:05:41 +00001510 // Cannonicalize fcmp_one -> fcmp_oeq
1511 FCmpInst::Predicate FPred; Value *Y;
Jakub Staszak58c1da82012-05-06 13:52:31 +00001512 if (match(&BI, m_Br(m_FCmp(FPred, m_Value(X), m_Value(Y)),
Chris Lattner7a1e9242009-08-30 06:13:40 +00001513 TrueDest, FalseDest)) &&
1514 BI.getCondition()->hasOneUse())
1515 if (FPred == FCmpInst::FCMP_ONE || FPred == FCmpInst::FCMP_OLE ||
1516 FPred == FCmpInst::FCMP_OGE) {
1517 FCmpInst *Cond = cast<FCmpInst>(BI.getCondition());
1518 Cond->setPredicate(FCmpInst::getInversePredicate(FPred));
Jakub Staszak58c1da82012-05-06 13:52:31 +00001519
Chris Lattner7a1e9242009-08-30 06:13:40 +00001520 // Swap Destinations and condition.
Chandler Carruth602650c2011-10-17 01:11:57 +00001521 BI.swapSuccessors();
Chris Lattner7a1e9242009-08-30 06:13:40 +00001522 Worklist.Add(Cond);
Reid Spencere4d87aa2006-12-23 06:05:41 +00001523 return &BI;
1524 }
1525
1526 // Cannonicalize icmp_ne -> icmp_eq
1527 ICmpInst::Predicate IPred;
1528 if (match(&BI, m_Br(m_ICmp(IPred, m_Value(X), m_Value(Y)),
Chris Lattner7a1e9242009-08-30 06:13:40 +00001529 TrueDest, FalseDest)) &&
1530 BI.getCondition()->hasOneUse())
1531 if (IPred == ICmpInst::ICMP_NE || IPred == ICmpInst::ICMP_ULE ||
1532 IPred == ICmpInst::ICMP_SLE || IPred == ICmpInst::ICMP_UGE ||
1533 IPred == ICmpInst::ICMP_SGE) {
1534 ICmpInst *Cond = cast<ICmpInst>(BI.getCondition());
1535 Cond->setPredicate(ICmpInst::getInversePredicate(IPred));
1536 // Swap Destinations and condition.
Chandler Carruth602650c2011-10-17 01:11:57 +00001537 BI.swapSuccessors();
Chris Lattner7a1e9242009-08-30 06:13:40 +00001538 Worklist.Add(Cond);
Chris Lattner40f5d702003-06-04 05:10:11 +00001539 return &BI;
1540 }
Misha Brukmanfd939082005-04-21 23:48:37 +00001541
Chris Lattnerc4d10eb2003-06-04 04:46:00 +00001542 return 0;
1543}
Chris Lattner0864acf2002-11-04 16:18:53 +00001544
Chris Lattner46238a62004-07-03 00:26:11 +00001545Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
1546 Value *Cond = SI.getCondition();
1547 if (Instruction *I = dyn_cast<Instruction>(Cond)) {
1548 if (I->getOpcode() == Instruction::Add)
1549 if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
1550 // change 'switch (X+4) case 1:' into 'switch (X) case -3'
Eli Friedmanbb5a7442011-09-29 20:21:17 +00001551 // Skip the first item since that's the default case.
Stepan Dyatkovskiy3d3abe02012-03-11 06:09:17 +00001552 for (SwitchInst::CaseIt i = SI.case_begin(), e = SI.case_end();
Stepan Dyatkovskiyc10fa6c2012-03-08 07:06:20 +00001553 i != e; ++i) {
1554 ConstantInt* CaseVal = i.getCaseValue();
Eli Friedmanbb5a7442011-09-29 20:21:17 +00001555 Constant* NewCaseVal = ConstantExpr::getSub(cast<Constant>(CaseVal),
1556 AddRHS);
1557 assert(isa<ConstantInt>(NewCaseVal) &&
1558 "Result of expression should be constant");
Stepan Dyatkovskiyc10fa6c2012-03-08 07:06:20 +00001559 i.setValue(cast<ConstantInt>(NewCaseVal));
Eli Friedmanbb5a7442011-09-29 20:21:17 +00001560 }
1561 SI.setCondition(I->getOperand(0));
Chris Lattner7a1e9242009-08-30 06:13:40 +00001562 Worklist.Add(I);
Chris Lattner46238a62004-07-03 00:26:11 +00001563 return &SI;
1564 }
1565 }
1566 return 0;
1567}
1568
Matthijs Kooijmana9012ec2008-06-11 14:05:05 +00001569Instruction *InstCombiner::visitExtractValueInst(ExtractValueInst &EV) {
Matthijs Kooijman780ae5e2008-07-16 12:55:45 +00001570 Value *Agg = EV.getAggregateOperand();
Matthijs Kooijmana9012ec2008-06-11 14:05:05 +00001571
Matthijs Kooijman780ae5e2008-07-16 12:55:45 +00001572 if (!EV.hasIndices())
1573 return ReplaceInstUsesWith(EV, Agg);
1574
1575 if (Constant *C = dyn_cast<Constant>(Agg)) {
Chris Lattnerd59ae902012-01-26 02:32:04 +00001576 if (Constant *C2 = C->getAggregateElement(*EV.idx_begin())) {
1577 if (EV.getNumIndices() == 0)
1578 return ReplaceInstUsesWith(EV, C2);
1579 // Extract the remaining indices out of the constant indexed by the
1580 // first index
1581 return ExtractValueInst::Create(C2, EV.getIndices().slice(1));
Matthijs Kooijman780ae5e2008-07-16 12:55:45 +00001582 }
1583 return 0; // Can't handle other constants
Chris Lattnerd59ae902012-01-26 02:32:04 +00001584 }
Jakub Staszak58c1da82012-05-06 13:52:31 +00001585
Matthijs Kooijman780ae5e2008-07-16 12:55:45 +00001586 if (InsertValueInst *IV = dyn_cast<InsertValueInst>(Agg)) {
1587 // We're extracting from an insertvalue instruction, compare the indices
1588 const unsigned *exti, *exte, *insi, *inse;
1589 for (exti = EV.idx_begin(), insi = IV->idx_begin(),
1590 exte = EV.idx_end(), inse = IV->idx_end();
1591 exti != exte && insi != inse;
1592 ++exti, ++insi) {
1593 if (*insi != *exti)
1594 // The insert and extract both reference distinctly different elements.
1595 // This means the extract is not influenced by the insert, and we can
1596 // replace the aggregate operand of the extract with the aggregate
1597 // operand of the insert. i.e., replace
1598 // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
1599 // %E = extractvalue { i32, { i32 } } %I, 0
1600 // with
1601 // %E = extractvalue { i32, { i32 } } %A, 0
1602 return ExtractValueInst::Create(IV->getAggregateOperand(),
Jay Foadfc6d3a42011-07-13 10:26:04 +00001603 EV.getIndices());
Matthijs Kooijman780ae5e2008-07-16 12:55:45 +00001604 }
1605 if (exti == exte && insi == inse)
1606 // Both iterators are at the end: Index lists are identical. Replace
1607 // %B = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
1608 // %C = extractvalue { i32, { i32 } } %B, 1, 0
1609 // with "i32 42"
1610 return ReplaceInstUsesWith(EV, IV->getInsertedValueOperand());
1611 if (exti == exte) {
1612 // The extract list is a prefix of the insert list. i.e. replace
1613 // %I = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
1614 // %E = extractvalue { i32, { i32 } } %I, 1
1615 // with
1616 // %X = extractvalue { i32, { i32 } } %A, 1
1617 // %E = insertvalue { i32 } %X, i32 42, 0
1618 // by switching the order of the insert and extract (though the
1619 // insertvalue should be left in, since it may have other uses).
Chris Lattnerf925cbd2009-08-30 18:50:58 +00001620 Value *NewEV = Builder->CreateExtractValue(IV->getAggregateOperand(),
Jay Foadfc6d3a42011-07-13 10:26:04 +00001621 EV.getIndices());
Matthijs Kooijman780ae5e2008-07-16 12:55:45 +00001622 return InsertValueInst::Create(NewEV, IV->getInsertedValueOperand(),
Frits van Bommel39b5abf2011-07-18 12:00:32 +00001623 makeArrayRef(insi, inse));
Matthijs Kooijman780ae5e2008-07-16 12:55:45 +00001624 }
1625 if (insi == inse)
1626 // The insert list is a prefix of the extract list
1627 // We can simply remove the common indices from the extract and make it
1628 // operate on the inserted value instead of the insertvalue result.
1629 // i.e., replace
1630 // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
1631 // %E = extractvalue { i32, { i32 } } %I, 1, 0
1632 // with
1633 // %E extractvalue { i32 } { i32 42 }, 0
Jakub Staszak58c1da82012-05-06 13:52:31 +00001634 return ExtractValueInst::Create(IV->getInsertedValueOperand(),
Frits van Bommel39b5abf2011-07-18 12:00:32 +00001635 makeArrayRef(exti, exte));
Matthijs Kooijman780ae5e2008-07-16 12:55:45 +00001636 }
Chris Lattner7e606e22009-11-09 07:07:56 +00001637 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(Agg)) {
1638 // We're extracting from an intrinsic, see if we're the only user, which
1639 // allows us to simplify multiple result intrinsics to simpler things that
Gabor Greif91697372010-06-24 12:21:15 +00001640 // just get one value.
Chris Lattner7e606e22009-11-09 07:07:56 +00001641 if (II->hasOneUse()) {
1642 // Check if we're grabbing the overflow bit or the result of a 'with
1643 // overflow' intrinsic. If it's the latter we can remove the intrinsic
1644 // and replace it with a traditional binary instruction.
1645 switch (II->getIntrinsicID()) {
1646 case Intrinsic::uadd_with_overflow:
1647 case Intrinsic::sadd_with_overflow:
1648 if (*EV.idx_begin() == 0) { // Normal result.
Gabor Greif91697372010-06-24 12:21:15 +00001649 Value *LHS = II->getArgOperand(0), *RHS = II->getArgOperand(1);
Eli Friedman3e22cb92011-05-18 00:32:01 +00001650 ReplaceInstUsesWith(*II, UndefValue::get(II->getType()));
Chris Lattner7e606e22009-11-09 07:07:56 +00001651 EraseInstFromFunction(*II);
1652 return BinaryOperator::CreateAdd(LHS, RHS);
1653 }
Jakub Staszak58c1da82012-05-06 13:52:31 +00001654
Chris Lattner74b64612010-12-19 19:43:52 +00001655 // If the normal result of the add is dead, and the RHS is a constant,
1656 // we can transform this into a range comparison.
1657 // overflow = uadd a, -4 --> overflow = icmp ugt a, 3
Chris Lattnerf2a97ed2010-12-19 23:24:04 +00001658 if (II->getIntrinsicID() == Intrinsic::uadd_with_overflow)
1659 if (ConstantInt *CI = dyn_cast<ConstantInt>(II->getArgOperand(1)))
1660 return new ICmpInst(ICmpInst::ICMP_UGT, II->getArgOperand(0),
1661 ConstantExpr::getNot(CI));
Chris Lattner7e606e22009-11-09 07:07:56 +00001662 break;
1663 case Intrinsic::usub_with_overflow:
1664 case Intrinsic::ssub_with_overflow:
1665 if (*EV.idx_begin() == 0) { // Normal result.
Gabor Greif91697372010-06-24 12:21:15 +00001666 Value *LHS = II->getArgOperand(0), *RHS = II->getArgOperand(1);
Eli Friedman3e22cb92011-05-18 00:32:01 +00001667 ReplaceInstUsesWith(*II, UndefValue::get(II->getType()));
Chris Lattner7e606e22009-11-09 07:07:56 +00001668 EraseInstFromFunction(*II);
1669 return BinaryOperator::CreateSub(LHS, RHS);
1670 }
1671 break;
1672 case Intrinsic::umul_with_overflow:
1673 case Intrinsic::smul_with_overflow:
1674 if (*EV.idx_begin() == 0) { // Normal result.
Gabor Greif91697372010-06-24 12:21:15 +00001675 Value *LHS = II->getArgOperand(0), *RHS = II->getArgOperand(1);
Eli Friedman3e22cb92011-05-18 00:32:01 +00001676 ReplaceInstUsesWith(*II, UndefValue::get(II->getType()));
Chris Lattner7e606e22009-11-09 07:07:56 +00001677 EraseInstFromFunction(*II);
1678 return BinaryOperator::CreateMul(LHS, RHS);
1679 }
1680 break;
1681 default:
1682 break;
1683 }
1684 }
1685 }
Frits van Bommel34ceb4d2010-11-29 21:56:20 +00001686 if (LoadInst *L = dyn_cast<LoadInst>(Agg))
1687 // If the (non-volatile) load only has one use, we can rewrite this to a
1688 // load from a GEP. This reduces the size of the load.
1689 // FIXME: If a load is used only by extractvalue instructions then this
1690 // could be done regardless of having multiple uses.
Eli Friedmancc4a0432011-08-15 22:09:40 +00001691 if (L->isSimple() && L->hasOneUse()) {
Frits van Bommel34ceb4d2010-11-29 21:56:20 +00001692 // extractvalue has integer indices, getelementptr has Value*s. Convert.
1693 SmallVector<Value*, 4> Indices;
1694 // Prefix an i32 0 since we need the first element.
1695 Indices.push_back(Builder->getInt32(0));
1696 for (ExtractValueInst::idx_iterator I = EV.idx_begin(), E = EV.idx_end();
1697 I != E; ++I)
1698 Indices.push_back(Builder->getInt32(*I));
1699
1700 // We need to insert these at the location of the old load, not at that of
1701 // the extractvalue.
1702 Builder->SetInsertPoint(L->getParent(), L);
Jay Foad0a2a60a2011-07-22 08:16:57 +00001703 Value *GEP = Builder->CreateInBoundsGEP(L->getPointerOperand(), Indices);
Frits van Bommel34ceb4d2010-11-29 21:56:20 +00001704 // Returning the load directly will cause the main loop to insert it in
1705 // the wrong spot, so use ReplaceInstUsesWith().
1706 return ReplaceInstUsesWith(EV, Builder->CreateLoad(GEP));
1707 }
1708 // We could simplify extracts from other values. Note that nested extracts may
1709 // already be simplified implicitly by the above: extract (extract (insert) )
Matthijs Kooijman780ae5e2008-07-16 12:55:45 +00001710 // will be translated into extract ( insert ( extract ) ) first and then just
Frits van Bommel34ceb4d2010-11-29 21:56:20 +00001711 // the value inserted, if appropriate. Similarly for extracts from single-use
1712 // loads: extract (extract (load)) will be translated to extract (load (gep))
1713 // and if again single-use then via load (gep (gep)) to load (gep).
1714 // However, double extracts from e.g. function arguments or return values
1715 // aren't handled yet.
Matthijs Kooijmana9012ec2008-06-11 14:05:05 +00001716 return 0;
1717}
1718
Duncan Sands0ad7b6e2011-09-30 13:12:16 +00001719enum Personality_Type {
1720 Unknown_Personality,
1721 GNU_Ada_Personality,
Bill Wendling76f267d2011-10-17 21:20:24 +00001722 GNU_CXX_Personality,
1723 GNU_ObjC_Personality
Duncan Sands0ad7b6e2011-09-30 13:12:16 +00001724};
1725
1726/// RecognizePersonality - See if the given exception handling personality
1727/// function is one that we understand. If so, return a description of it;
1728/// otherwise return Unknown_Personality.
1729static Personality_Type RecognizePersonality(Value *Pers) {
1730 Function *F = dyn_cast<Function>(Pers->stripPointerCasts());
1731 if (!F)
1732 return Unknown_Personality;
1733 return StringSwitch<Personality_Type>(F->getName())
1734 .Case("__gnat_eh_personality", GNU_Ada_Personality)
Bill Wendling76f267d2011-10-17 21:20:24 +00001735 .Case("__gxx_personality_v0", GNU_CXX_Personality)
1736 .Case("__objc_personality_v0", GNU_ObjC_Personality)
Duncan Sands0ad7b6e2011-09-30 13:12:16 +00001737 .Default(Unknown_Personality);
1738}
1739
1740/// isCatchAll - Return 'true' if the given typeinfo will match anything.
1741static bool isCatchAll(Personality_Type Personality, Constant *TypeInfo) {
1742 switch (Personality) {
1743 case Unknown_Personality:
1744 return false;
1745 case GNU_Ada_Personality:
1746 // While __gnat_all_others_value will match any Ada exception, it doesn't
1747 // match foreign exceptions (or didn't, before gcc-4.7).
1748 return false;
1749 case GNU_CXX_Personality:
Bill Wendling76f267d2011-10-17 21:20:24 +00001750 case GNU_ObjC_Personality:
Duncan Sands0ad7b6e2011-09-30 13:12:16 +00001751 return TypeInfo->isNullValue();
1752 }
1753 llvm_unreachable("Unknown personality!");
1754}
1755
1756static bool shorter_filter(const Value *LHS, const Value *RHS) {
1757 return
1758 cast<ArrayType>(LHS->getType())->getNumElements()
1759 <
1760 cast<ArrayType>(RHS->getType())->getNumElements();
1761}
1762
1763Instruction *InstCombiner::visitLandingPadInst(LandingPadInst &LI) {
1764 // The logic here should be correct for any real-world personality function.
1765 // However if that turns out not to be true, the offending logic can always
1766 // be conditioned on the personality function, like the catch-all logic is.
1767 Personality_Type Personality = RecognizePersonality(LI.getPersonalityFn());
1768
1769 // Simplify the list of clauses, eg by removing repeated catch clauses
1770 // (these are often created by inlining).
1771 bool MakeNewInstruction = false; // If true, recreate using the following:
1772 SmallVector<Value *, 16> NewClauses; // - Clauses for the new instruction;
1773 bool CleanupFlag = LI.isCleanup(); // - The new instruction is a cleanup.
1774
1775 SmallPtrSet<Value *, 16> AlreadyCaught; // Typeinfos known caught already.
1776 for (unsigned i = 0, e = LI.getNumClauses(); i != e; ++i) {
1777 bool isLastClause = i + 1 == e;
1778 if (LI.isCatch(i)) {
1779 // A catch clause.
1780 Value *CatchClause = LI.getClause(i);
1781 Constant *TypeInfo = cast<Constant>(CatchClause->stripPointerCasts());
1782
1783 // If we already saw this clause, there is no point in having a second
1784 // copy of it.
1785 if (AlreadyCaught.insert(TypeInfo)) {
1786 // This catch clause was not already seen.
1787 NewClauses.push_back(CatchClause);
1788 } else {
1789 // Repeated catch clause - drop the redundant copy.
1790 MakeNewInstruction = true;
1791 }
1792
1793 // If this is a catch-all then there is no point in keeping any following
1794 // clauses or marking the landingpad as having a cleanup.
1795 if (isCatchAll(Personality, TypeInfo)) {
1796 if (!isLastClause)
1797 MakeNewInstruction = true;
1798 CleanupFlag = false;
1799 break;
1800 }
1801 } else {
1802 // A filter clause. If any of the filter elements were already caught
1803 // then they can be dropped from the filter. It is tempting to try to
1804 // exploit the filter further by saying that any typeinfo that does not
1805 // occur in the filter can't be caught later (and thus can be dropped).
1806 // However this would be wrong, since typeinfos can match without being
1807 // equal (for example if one represents a C++ class, and the other some
1808 // class derived from it).
1809 assert(LI.isFilter(i) && "Unsupported landingpad clause!");
1810 Value *FilterClause = LI.getClause(i);
1811 ArrayType *FilterType = cast<ArrayType>(FilterClause->getType());
1812 unsigned NumTypeInfos = FilterType->getNumElements();
1813
1814 // An empty filter catches everything, so there is no point in keeping any
1815 // following clauses or marking the landingpad as having a cleanup. By
1816 // dealing with this case here the following code is made a bit simpler.
1817 if (!NumTypeInfos) {
1818 NewClauses.push_back(FilterClause);
1819 if (!isLastClause)
1820 MakeNewInstruction = true;
1821 CleanupFlag = false;
1822 break;
1823 }
1824
1825 bool MakeNewFilter = false; // If true, make a new filter.
1826 SmallVector<Constant *, 16> NewFilterElts; // New elements.
1827 if (isa<ConstantAggregateZero>(FilterClause)) {
1828 // Not an empty filter - it contains at least one null typeinfo.
1829 assert(NumTypeInfos > 0 && "Should have handled empty filter already!");
1830 Constant *TypeInfo =
1831 Constant::getNullValue(FilterType->getElementType());
1832 // If this typeinfo is a catch-all then the filter can never match.
1833 if (isCatchAll(Personality, TypeInfo)) {
1834 // Throw the filter away.
1835 MakeNewInstruction = true;
1836 continue;
1837 }
1838
1839 // There is no point in having multiple copies of this typeinfo, so
1840 // discard all but the first copy if there is more than one.
1841 NewFilterElts.push_back(TypeInfo);
1842 if (NumTypeInfos > 1)
1843 MakeNewFilter = true;
1844 } else {
1845 ConstantArray *Filter = cast<ConstantArray>(FilterClause);
1846 SmallPtrSet<Value *, 16> SeenInFilter; // For uniquing the elements.
1847 NewFilterElts.reserve(NumTypeInfos);
1848
1849 // Remove any filter elements that were already caught or that already
1850 // occurred in the filter. While there, see if any of the elements are
1851 // catch-alls. If so, the filter can be discarded.
1852 bool SawCatchAll = false;
1853 for (unsigned j = 0; j != NumTypeInfos; ++j) {
1854 Value *Elt = Filter->getOperand(j);
1855 Constant *TypeInfo = cast<Constant>(Elt->stripPointerCasts());
1856 if (isCatchAll(Personality, TypeInfo)) {
1857 // This element is a catch-all. Bail out, noting this fact.
1858 SawCatchAll = true;
1859 break;
1860 }
1861 if (AlreadyCaught.count(TypeInfo))
1862 // Already caught by an earlier clause, so having it in the filter
1863 // is pointless.
1864 continue;
1865 // There is no point in having multiple copies of the same typeinfo in
1866 // a filter, so only add it if we didn't already.
1867 if (SeenInFilter.insert(TypeInfo))
1868 NewFilterElts.push_back(cast<Constant>(Elt));
1869 }
1870 // A filter containing a catch-all cannot match anything by definition.
1871 if (SawCatchAll) {
1872 // Throw the filter away.
1873 MakeNewInstruction = true;
1874 continue;
1875 }
1876
1877 // If we dropped something from the filter, make a new one.
1878 if (NewFilterElts.size() < NumTypeInfos)
1879 MakeNewFilter = true;
1880 }
1881 if (MakeNewFilter) {
1882 FilterType = ArrayType::get(FilterType->getElementType(),
1883 NewFilterElts.size());
1884 FilterClause = ConstantArray::get(FilterType, NewFilterElts);
1885 MakeNewInstruction = true;
1886 }
1887
1888 NewClauses.push_back(FilterClause);
1889
1890 // If the new filter is empty then it will catch everything so there is
1891 // no point in keeping any following clauses or marking the landingpad
1892 // as having a cleanup. The case of the original filter being empty was
1893 // already handled above.
1894 if (MakeNewFilter && !NewFilterElts.size()) {
1895 assert(MakeNewInstruction && "New filter but not a new instruction!");
1896 CleanupFlag = false;
1897 break;
1898 }
1899 }
1900 }
1901
1902 // If several filters occur in a row then reorder them so that the shortest
1903 // filters come first (those with the smallest number of elements). This is
1904 // advantageous because shorter filters are more likely to match, speeding up
1905 // unwinding, but mostly because it increases the effectiveness of the other
1906 // filter optimizations below.
1907 for (unsigned i = 0, e = NewClauses.size(); i + 1 < e; ) {
1908 unsigned j;
1909 // Find the maximal 'j' s.t. the range [i, j) consists entirely of filters.
1910 for (j = i; j != e; ++j)
1911 if (!isa<ArrayType>(NewClauses[j]->getType()))
1912 break;
1913
1914 // Check whether the filters are already sorted by length. We need to know
1915 // if sorting them is actually going to do anything so that we only make a
1916 // new landingpad instruction if it does.
1917 for (unsigned k = i; k + 1 < j; ++k)
1918 if (shorter_filter(NewClauses[k+1], NewClauses[k])) {
1919 // Not sorted, so sort the filters now. Doing an unstable sort would be
1920 // correct too but reordering filters pointlessly might confuse users.
1921 std::stable_sort(NewClauses.begin() + i, NewClauses.begin() + j,
1922 shorter_filter);
1923 MakeNewInstruction = true;
1924 break;
1925 }
1926
1927 // Look for the next batch of filters.
1928 i = j + 1;
1929 }
1930
1931 // If typeinfos matched if and only if equal, then the elements of a filter L
1932 // that occurs later than a filter F could be replaced by the intersection of
1933 // the elements of F and L. In reality two typeinfos can match without being
1934 // equal (for example if one represents a C++ class, and the other some class
1935 // derived from it) so it would be wrong to perform this transform in general.
1936 // However the transform is correct and useful if F is a subset of L. In that
1937 // case L can be replaced by F, and thus removed altogether since repeating a
1938 // filter is pointless. So here we look at all pairs of filters F and L where
1939 // L follows F in the list of clauses, and remove L if every element of F is
1940 // an element of L. This can occur when inlining C++ functions with exception
1941 // specifications.
1942 for (unsigned i = 0; i + 1 < NewClauses.size(); ++i) {
1943 // Examine each filter in turn.
1944 Value *Filter = NewClauses[i];
1945 ArrayType *FTy = dyn_cast<ArrayType>(Filter->getType());
1946 if (!FTy)
1947 // Not a filter - skip it.
1948 continue;
1949 unsigned FElts = FTy->getNumElements();
1950 // Examine each filter following this one. Doing this backwards means that
1951 // we don't have to worry about filters disappearing under us when removed.
1952 for (unsigned j = NewClauses.size() - 1; j != i; --j) {
1953 Value *LFilter = NewClauses[j];
1954 ArrayType *LTy = dyn_cast<ArrayType>(LFilter->getType());
1955 if (!LTy)
1956 // Not a filter - skip it.
1957 continue;
1958 // If Filter is a subset of LFilter, i.e. every element of Filter is also
1959 // an element of LFilter, then discard LFilter.
1960 SmallVector<Value *, 16>::iterator J = NewClauses.begin() + j;
1961 // If Filter is empty then it is a subset of LFilter.
1962 if (!FElts) {
1963 // Discard LFilter.
1964 NewClauses.erase(J);
1965 MakeNewInstruction = true;
1966 // Move on to the next filter.
1967 continue;
1968 }
1969 unsigned LElts = LTy->getNumElements();
1970 // If Filter is longer than LFilter then it cannot be a subset of it.
1971 if (FElts > LElts)
1972 // Move on to the next filter.
1973 continue;
1974 // At this point we know that LFilter has at least one element.
1975 if (isa<ConstantAggregateZero>(LFilter)) { // LFilter only contains zeros.
Sylvestre Ledru94c22712012-09-27 10:14:43 +00001976 // Filter is a subset of LFilter iff Filter contains only zeros (as we
Duncan Sands0ad7b6e2011-09-30 13:12:16 +00001977 // already know that Filter is not longer than LFilter).
1978 if (isa<ConstantAggregateZero>(Filter)) {
1979 assert(FElts <= LElts && "Should have handled this case earlier!");
1980 // Discard LFilter.
1981 NewClauses.erase(J);
1982 MakeNewInstruction = true;
1983 }
1984 // Move on to the next filter.
1985 continue;
1986 }
1987 ConstantArray *LArray = cast<ConstantArray>(LFilter);
1988 if (isa<ConstantAggregateZero>(Filter)) { // Filter only contains zeros.
1989 // Since Filter is non-empty and contains only zeros, it is a subset of
Sylvestre Ledru94c22712012-09-27 10:14:43 +00001990 // LFilter iff LFilter contains a zero.
Duncan Sands0ad7b6e2011-09-30 13:12:16 +00001991 assert(FElts > 0 && "Should have eliminated the empty filter earlier!");
1992 for (unsigned l = 0; l != LElts; ++l)
1993 if (LArray->getOperand(l)->isNullValue()) {
1994 // LFilter contains a zero - discard it.
1995 NewClauses.erase(J);
1996 MakeNewInstruction = true;
1997 break;
1998 }
1999 // Move on to the next filter.
2000 continue;
2001 }
2002 // At this point we know that both filters are ConstantArrays. Loop over
2003 // operands to see whether every element of Filter is also an element of
2004 // LFilter. Since filters tend to be short this is probably faster than
2005 // using a method that scales nicely.
2006 ConstantArray *FArray = cast<ConstantArray>(Filter);
2007 bool AllFound = true;
2008 for (unsigned f = 0; f != FElts; ++f) {
2009 Value *FTypeInfo = FArray->getOperand(f)->stripPointerCasts();
2010 AllFound = false;
2011 for (unsigned l = 0; l != LElts; ++l) {
2012 Value *LTypeInfo = LArray->getOperand(l)->stripPointerCasts();
2013 if (LTypeInfo == FTypeInfo) {
2014 AllFound = true;
2015 break;
2016 }
2017 }
2018 if (!AllFound)
2019 break;
2020 }
2021 if (AllFound) {
2022 // Discard LFilter.
2023 NewClauses.erase(J);
2024 MakeNewInstruction = true;
2025 }
2026 // Move on to the next filter.
2027 }
2028 }
2029
2030 // If we changed any of the clauses, replace the old landingpad instruction
2031 // with a new one.
2032 if (MakeNewInstruction) {
2033 LandingPadInst *NLI = LandingPadInst::Create(LI.getType(),
2034 LI.getPersonalityFn(),
2035 NewClauses.size());
2036 for (unsigned i = 0, e = NewClauses.size(); i != e; ++i)
2037 NLI->addClause(NewClauses[i]);
2038 // A landing pad with no clauses must have the cleanup flag set. It is
2039 // theoretically possible, though highly unlikely, that we eliminated all
2040 // clauses. If so, force the cleanup flag to true.
2041 if (NewClauses.empty())
2042 CleanupFlag = true;
2043 NLI->setCleanup(CleanupFlag);
2044 return NLI;
2045 }
2046
2047 // Even if none of the clauses changed, we may nonetheless have understood
2048 // that the cleanup flag is pointless. Clear it if so.
2049 if (LI.isCleanup() != CleanupFlag) {
2050 assert(!CleanupFlag && "Adding a cleanup, not removing one?!");
2051 LI.setCleanup(CleanupFlag);
2052 return &LI;
2053 }
2054
2055 return 0;
2056}
2057
Chris Lattnera844fc4c2006-04-10 22:45:52 +00002058
Robert Bocchino1d7456d2006-01-13 22:48:06 +00002059
Chris Lattnerea1c4542004-12-08 23:43:58 +00002060
2061/// TryToSinkInstruction - Try to move the specified instruction from its
2062/// current block into the beginning of DestBlock, which can only happen if it's
2063/// safe to move the instruction past all of the instructions between it and the
2064/// end of its block.
2065static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
2066 assert(I->hasOneUse() && "Invariants didn't hold!");
2067
Bill Wendling9d6070f2011-08-15 21:14:31 +00002068 // Cannot move control-flow-involving, volatile loads, vaarg, etc.
Bill Wendlingc9b2a982011-08-17 20:36:44 +00002069 if (isa<PHINode>(I) || isa<LandingPadInst>(I) || I->mayHaveSideEffects() ||
2070 isa<TerminatorInst>(I))
Chris Lattnerbfc538c2008-05-09 15:07:33 +00002071 return false;
Misha Brukmanfd939082005-04-21 23:48:37 +00002072
Chris Lattnerea1c4542004-12-08 23:43:58 +00002073 // Do not sink alloca instructions out of the entry block.
Dan Gohmanecb7a772007-03-22 16:38:57 +00002074 if (isa<AllocaInst>(I) && I->getParent() ==
2075 &DestBlock->getParent()->getEntryBlock())
Chris Lattnerea1c4542004-12-08 23:43:58 +00002076 return false;
2077
Chris Lattner96a52a62004-12-09 07:14:34 +00002078 // We can only sink load instructions if there is nothing between the load and
2079 // the end of block that could change the value.
Chris Lattner2539e332008-05-08 17:37:37 +00002080 if (I->mayReadFromMemory()) {
2081 for (BasicBlock::iterator Scan = I, E = I->getParent()->end();
Chris Lattner96a52a62004-12-09 07:14:34 +00002082 Scan != E; ++Scan)
2083 if (Scan->mayWriteToMemory())
2084 return false;
Chris Lattner96a52a62004-12-09 07:14:34 +00002085 }
Chris Lattnerea1c4542004-12-08 23:43:58 +00002086
Bill Wendling5b6f42f2011-08-16 20:45:24 +00002087 BasicBlock::iterator InsertPos = DestBlock->getFirstInsertionPt();
Chris Lattner4bc5f802005-08-08 19:11:57 +00002088 I->moveBefore(InsertPos);
Chris Lattnerea1c4542004-12-08 23:43:58 +00002089 ++NumSunkInst;
2090 return true;
2091}
2092
Chris Lattnerf4f5a772006-05-10 19:00:36 +00002093
2094/// AddReachableCodeToWorklist - Walk the function in depth-first order, adding
2095/// all reachable code to the worklist.
2096///
2097/// This has a couple of tricks to make the code faster and more powerful. In
2098/// particular, we constant fold and DCE instructions as we go, to avoid adding
2099/// them to the worklist (this significantly speeds up instcombine on code where
2100/// many instructions are dead or constant). Additionally, if we find a branch
2101/// whose condition is a known constant, we only visit the reachable successors.
2102///
Jakub Staszak58c1da82012-05-06 13:52:31 +00002103static bool AddReachableCodeToWorklist(BasicBlock *BB,
Chris Lattner1f87a582007-02-15 19:41:52 +00002104 SmallPtrSet<BasicBlock*, 64> &Visited,
Chris Lattnerdbab3862007-03-02 21:28:56 +00002105 InstCombiner &IC,
Micah Villmow3574eca2012-10-08 16:38:25 +00002106 const DataLayout *TD,
Chad Rosier00737bd2011-12-01 21:29:16 +00002107 const TargetLibraryInfo *TLI) {
Chris Lattner2ee743b2009-10-15 04:59:28 +00002108 bool MadeIRChange = false;
Chris Lattner2806dff2008-08-15 04:03:01 +00002109 SmallVector<BasicBlock*, 256> Worklist;
Chris Lattner2c7718a2007-03-23 19:17:18 +00002110 Worklist.push_back(BB);
Chris Lattnerf4f5a772006-05-10 19:00:36 +00002111
Benjamin Kramera53fe602010-10-23 17:10:24 +00002112 SmallVector<Instruction*, 128> InstrsForInstCombineWorklist;
Eli Friedmana4d4aeb2011-05-24 18:52:07 +00002113 DenseMap<ConstantExpr*, Constant*> FoldedConstants;
2114
Dan Gohman321a8132010-01-05 16:27:25 +00002115 do {
2116 BB = Worklist.pop_back_val();
Jakub Staszak58c1da82012-05-06 13:52:31 +00002117
Chris Lattner2c7718a2007-03-23 19:17:18 +00002118 // We have now visited this block! If we've already been here, ignore it.
2119 if (!Visited.insert(BB)) continue;
Devang Patel7fe1dec2008-11-19 18:56:50 +00002120
Chris Lattner2c7718a2007-03-23 19:17:18 +00002121 for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
2122 Instruction *Inst = BBI++;
Jakub Staszak58c1da82012-05-06 13:52:31 +00002123
Chris Lattner2c7718a2007-03-23 19:17:18 +00002124 // DCE instruction if trivially dead.
Benjamin Kramer8e0d1c02012-08-29 15:32:21 +00002125 if (isInstructionTriviallyDead(Inst, TLI)) {
Chris Lattner2c7718a2007-03-23 19:17:18 +00002126 ++NumDeadInst;
Chris Lattnerbdff5482009-08-23 04:37:46 +00002127 DEBUG(errs() << "IC: DCE: " << *Inst << '\n');
Chris Lattner2c7718a2007-03-23 19:17:18 +00002128 Inst->eraseFromParent();
2129 continue;
2130 }
Jakub Staszak58c1da82012-05-06 13:52:31 +00002131
Chris Lattner2c7718a2007-03-23 19:17:18 +00002132 // ConstantProp instruction if trivially constant.
Chris Lattnere2cc1ad2009-10-15 04:13:44 +00002133 if (!Inst->use_empty() && isa<Constant>(Inst->getOperand(0)))
Chad Rosier00737bd2011-12-01 21:29:16 +00002134 if (Constant *C = ConstantFoldInstruction(Inst, TD, TLI)) {
Chris Lattnere2cc1ad2009-10-15 04:13:44 +00002135 DEBUG(errs() << "IC: ConstFold to: " << *C << " from: "
2136 << *Inst << '\n');
2137 Inst->replaceAllUsesWith(C);
2138 ++NumConstProp;
2139 Inst->eraseFromParent();
2140 continue;
2141 }
Jakub Staszak58c1da82012-05-06 13:52:31 +00002142
Chris Lattner2ee743b2009-10-15 04:59:28 +00002143 if (TD) {
2144 // See if we can constant fold its operands.
2145 for (User::op_iterator i = Inst->op_begin(), e = Inst->op_end();
2146 i != e; ++i) {
2147 ConstantExpr *CE = dyn_cast<ConstantExpr>(i);
2148 if (CE == 0) continue;
Eli Friedmana4d4aeb2011-05-24 18:52:07 +00002149
2150 Constant*& FoldRes = FoldedConstants[CE];
2151 if (!FoldRes)
Chad Rosieraab8e282011-12-02 01:26:24 +00002152 FoldRes = ConstantFoldConstantExpression(CE, TD, TLI);
Eli Friedmana4d4aeb2011-05-24 18:52:07 +00002153 if (!FoldRes)
2154 FoldRes = CE;
2155
2156 if (FoldRes != CE) {
2157 *i = FoldRes;
Chris Lattner2ee743b2009-10-15 04:59:28 +00002158 MadeIRChange = true;
2159 }
2160 }
2161 }
Devang Patel7fe1dec2008-11-19 18:56:50 +00002162
Chris Lattner67f7d542009-10-12 03:58:40 +00002163 InstrsForInstCombineWorklist.push_back(Inst);
Chris Lattnerf4f5a772006-05-10 19:00:36 +00002164 }
Chris Lattner2c7718a2007-03-23 19:17:18 +00002165
2166 // Recursively visit successors. If this is a branch or switch on a
2167 // constant, only visit the reachable successor.
2168 TerminatorInst *TI = BB->getTerminator();
2169 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
2170 if (BI->isConditional() && isa<ConstantInt>(BI->getCondition())) {
2171 bool CondVal = cast<ConstantInt>(BI->getCondition())->getZExtValue();
Nick Lewycky91436992008-03-09 08:50:23 +00002172 BasicBlock *ReachableBB = BI->getSuccessor(!CondVal);
Nick Lewycky280a6e62008-04-25 16:53:59 +00002173 Worklist.push_back(ReachableBB);
Chris Lattner2c7718a2007-03-23 19:17:18 +00002174 continue;
2175 }
2176 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
2177 if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
2178 // See if this is an explicit destination.
Stepan Dyatkovskiy3d3abe02012-03-11 06:09:17 +00002179 for (SwitchInst::CaseIt i = SI->case_begin(), e = SI->case_end();
Stepan Dyatkovskiyc10fa6c2012-03-08 07:06:20 +00002180 i != e; ++i)
2181 if (i.getCaseValue() == Cond) {
2182 BasicBlock *ReachableBB = i.getCaseSuccessor();
Nick Lewycky280a6e62008-04-25 16:53:59 +00002183 Worklist.push_back(ReachableBB);
Chris Lattner2c7718a2007-03-23 19:17:18 +00002184 continue;
2185 }
Jakub Staszak58c1da82012-05-06 13:52:31 +00002186
Chris Lattner2c7718a2007-03-23 19:17:18 +00002187 // Otherwise it is the default destination.
Stepan Dyatkovskiy24473122012-02-01 07:49:51 +00002188 Worklist.push_back(SI->getDefaultDest());
Chris Lattner2c7718a2007-03-23 19:17:18 +00002189 continue;
2190 }
2191 }
Jakub Staszak58c1da82012-05-06 13:52:31 +00002192
Chris Lattner2c7718a2007-03-23 19:17:18 +00002193 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
2194 Worklist.push_back(TI->getSuccessor(i));
Dan Gohman321a8132010-01-05 16:27:25 +00002195 } while (!Worklist.empty());
Jakub Staszak58c1da82012-05-06 13:52:31 +00002196
Chris Lattner67f7d542009-10-12 03:58:40 +00002197 // Once we've found all of the instructions to add to instcombine's worklist,
2198 // add them in reverse order. This way instcombine will visit from the top
2199 // of the function down. This jives well with the way that it adds all uses
2200 // of instructions to the worklist after doing a transformation, thus avoiding
2201 // some N^2 behavior in pathological cases.
2202 IC.Worklist.AddInitialGroup(&InstrsForInstCombineWorklist[0],
2203 InstrsForInstCombineWorklist.size());
Jakub Staszak58c1da82012-05-06 13:52:31 +00002204
Chris Lattner2ee743b2009-10-15 04:59:28 +00002205 return MadeIRChange;
Chris Lattnerf4f5a772006-05-10 19:00:36 +00002206}
2207
Chris Lattnerec9c3582007-03-03 02:04:50 +00002208bool InstCombiner::DoOneIteration(Function &F, unsigned Iteration) {
Chris Lattnerb0b822c2009-08-31 06:57:37 +00002209 MadeIRChange = false;
Jakub Staszak58c1da82012-05-06 13:52:31 +00002210
Daniel Dunbarce63ffb2009-07-25 00:23:56 +00002211 DEBUG(errs() << "\n\nINSTCOMBINE ITERATION #" << Iteration << " on "
Benjamin Kramera7b0cb72011-11-15 16:27:03 +00002212 << F.getName() << "\n");
Chris Lattner8a2a3112001-12-14 16:52:21 +00002213
Chris Lattnerb3d59702005-07-07 20:40:38 +00002214 {
Chris Lattnerf4f5a772006-05-10 19:00:36 +00002215 // Do a depth-first traversal of the function, populate the worklist with
2216 // the reachable instructions. Ignore blocks that are not reachable. Keep
2217 // track of which blocks we visit.
Chris Lattner1f87a582007-02-15 19:41:52 +00002218 SmallPtrSet<BasicBlock*, 64> Visited;
Chad Rosier00737bd2011-12-01 21:29:16 +00002219 MadeIRChange |= AddReachableCodeToWorklist(F.begin(), Visited, *this, TD,
2220 TLI);
Jeff Cohen00b168892005-07-27 06:12:32 +00002221
Chris Lattnerb3d59702005-07-07 20:40:38 +00002222 // Do a quick scan over the function. If we find any blocks that are
2223 // unreachable, remove any instructions inside of them. This prevents
2224 // the instcombine code from having to deal with some bad special cases.
Bill Wendling6bb4e7e2011-09-01 21:29:49 +00002225 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
2226 if (Visited.count(BB)) continue;
2227
Bill Wendlinga2684682011-09-04 09:43:36 +00002228 // Delete the instructions backwards, as it has a reduced likelihood of
2229 // having to update as many def-use and use-def chains.
2230 Instruction *EndInst = BB->getTerminator(); // Last not to be deleted.
2231 while (EndInst != BB->begin()) {
2232 // Delete the next to last instruction.
2233 BasicBlock::iterator I = EndInst;
2234 Instruction *Inst = --I;
Bill Wendling6bb4e7e2011-09-01 21:29:49 +00002235 if (!Inst->use_empty())
2236 Inst->replaceAllUsesWith(UndefValue::get(Inst->getType()));
Bill Wendlinga2684682011-09-04 09:43:36 +00002237 if (isa<LandingPadInst>(Inst)) {
2238 EndInst = Inst;
Bill Wendling6bb4e7e2011-09-01 21:29:49 +00002239 continue;
Bill Wendlinga2684682011-09-04 09:43:36 +00002240 }
Bill Wendling6bb4e7e2011-09-01 21:29:49 +00002241 if (!isa<DbgInfoIntrinsic>(Inst)) {
2242 ++NumDeadInst;
2243 MadeIRChange = true;
Chris Lattnerb3d59702005-07-07 20:40:38 +00002244 }
Bill Wendling6bb4e7e2011-09-01 21:29:49 +00002245 Inst->eraseFromParent();
Chris Lattnerb3d59702005-07-07 20:40:38 +00002246 }
Bill Wendling6bb4e7e2011-09-01 21:29:49 +00002247 }
Chris Lattnerb3d59702005-07-07 20:40:38 +00002248 }
Chris Lattner8a2a3112001-12-14 16:52:21 +00002249
Chris Lattner873ff012009-08-30 05:55:36 +00002250 while (!Worklist.isEmpty()) {
2251 Instruction *I = Worklist.RemoveOne();
Chris Lattnerdbab3862007-03-02 21:28:56 +00002252 if (I == 0) continue; // skip null values.
Chris Lattner8a2a3112001-12-14 16:52:21 +00002253
Chris Lattner8c8c66a2006-05-11 17:11:52 +00002254 // Check to see if we can DCE the instruction.
Benjamin Kramer8e0d1c02012-08-29 15:32:21 +00002255 if (isInstructionTriviallyDead(I, TLI)) {
Chris Lattnerbdff5482009-08-23 04:37:46 +00002256 DEBUG(errs() << "IC: DCE: " << *I << '\n');
Chris Lattner7a1e9242009-08-30 06:13:40 +00002257 EraseInstFromFunction(*I);
2258 ++NumDeadInst;
Chris Lattnerb0b822c2009-08-31 06:57:37 +00002259 MadeIRChange = true;
Chris Lattner4bb7c022003-10-06 17:11:01 +00002260 continue;
2261 }
Chris Lattner62b14df2002-09-02 04:59:56 +00002262
Chris Lattner8c8c66a2006-05-11 17:11:52 +00002263 // Instruction isn't dead, see if we can constant propagate it.
Chris Lattnere2cc1ad2009-10-15 04:13:44 +00002264 if (!I->use_empty() && isa<Constant>(I->getOperand(0)))
Chad Rosier00737bd2011-12-01 21:29:16 +00002265 if (Constant *C = ConstantFoldInstruction(I, TD, TLI)) {
Chris Lattnere2cc1ad2009-10-15 04:13:44 +00002266 DEBUG(errs() << "IC: ConstFold to: " << *C << " from: " << *I << '\n');
Chris Lattnerad5fec12005-01-28 19:32:01 +00002267
Chris Lattnere2cc1ad2009-10-15 04:13:44 +00002268 // Add operands to the worklist.
2269 ReplaceInstUsesWith(*I, C);
2270 ++NumConstProp;
2271 EraseInstFromFunction(*I);
2272 MadeIRChange = true;
2273 continue;
2274 }
Chris Lattner4bb7c022003-10-06 17:11:01 +00002275
Chris Lattnerea1c4542004-12-08 23:43:58 +00002276 // See if we can trivially sink this instruction to a successor basic block.
Dan Gohmanfc74abf2008-07-23 00:34:11 +00002277 if (I->hasOneUse()) {
Chris Lattnerea1c4542004-12-08 23:43:58 +00002278 BasicBlock *BB = I->getParent();
Chris Lattner8db2cd12009-10-14 15:21:58 +00002279 Instruction *UserInst = cast<Instruction>(I->use_back());
2280 BasicBlock *UserParent;
Jakub Staszak58c1da82012-05-06 13:52:31 +00002281
Chris Lattner8db2cd12009-10-14 15:21:58 +00002282 // Get the block the use occurs in.
2283 if (PHINode *PN = dyn_cast<PHINode>(UserInst))
2284 UserParent = PN->getIncomingBlock(I->use_begin().getUse());
2285 else
2286 UserParent = UserInst->getParent();
Jakub Staszak58c1da82012-05-06 13:52:31 +00002287
Chris Lattnerea1c4542004-12-08 23:43:58 +00002288 if (UserParent != BB) {
2289 bool UserIsSuccessor = false;
2290 // See if the user is one of our successors.
2291 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
2292 if (*SI == UserParent) {
2293 UserIsSuccessor = true;
2294 break;
2295 }
2296
2297 // If the user is one of our immediate successors, and if that successor
2298 // only has us as a predecessors (we'd have to split the critical edge
2299 // otherwise), we can keep going.
Chris Lattner8db2cd12009-10-14 15:21:58 +00002300 if (UserIsSuccessor && UserParent->getSinglePredecessor())
Chris Lattnerea1c4542004-12-08 23:43:58 +00002301 // Okay, the CFG is simple enough, try to sink this instruction.
Chris Lattnerb0b822c2009-08-31 06:57:37 +00002302 MadeIRChange |= TryToSinkInstruction(I, UserParent);
Chris Lattnerea1c4542004-12-08 23:43:58 +00002303 }
2304 }
2305
Chris Lattner74381062009-08-30 07:44:24 +00002306 // Now that we have an instruction, try combining it to simplify it.
2307 Builder->SetInsertPoint(I->getParent(), I);
Eli Friedmanef819d02011-05-18 01:28:27 +00002308 Builder->SetCurrentDebugLocation(I->getDebugLoc());
Jakub Staszak58c1da82012-05-06 13:52:31 +00002309
Reid Spencera9b81012007-03-26 17:44:01 +00002310#ifndef NDEBUG
2311 std::string OrigI;
2312#endif
Chris Lattnerbdff5482009-08-23 04:37:46 +00002313 DEBUG(raw_string_ostream SS(OrigI); I->print(SS); OrigI = SS.str(););
Jeffrey Yasskin43069632009-10-08 00:12:24 +00002314 DEBUG(errs() << "IC: Visiting: " << OrigI << '\n');
2315
Chris Lattner90ac28c2002-08-02 19:29:35 +00002316 if (Instruction *Result = visit(*I)) {
Chris Lattner3dec1f22002-05-10 15:38:35 +00002317 ++NumCombined;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002318 // Should we replace the old instruction with a new one?
Chris Lattnerb3bc8fa2002-05-14 15:24:07 +00002319 if (Result != I) {
Jim Grosbache2999b42011-10-05 20:44:29 +00002320 DEBUG(errs() << "IC: Old = " << *I << '\n'
2321 << " New = " << *Result << '\n');
2322
Eli Friedmana311c342011-05-27 00:19:40 +00002323 if (!I->getDebugLoc().isUnknown())
2324 Result->setDebugLoc(I->getDebugLoc());
Chris Lattnerf523d062004-06-09 05:08:07 +00002325 // Everything uses the new instruction now.
2326 I->replaceAllUsesWith(Result);
2327
Jim Grosbach35d9da32011-10-05 20:53:43 +00002328 // Move the name to the new instruction first.
2329 Result->takeName(I);
2330
Jim Grosbache2999b42011-10-05 20:44:29 +00002331 // Push the new instruction and any users onto the worklist.
2332 Worklist.Add(Result);
2333 Worklist.AddUsersToWorkList(*Result);
2334
Chris Lattner4bb7c022003-10-06 17:11:01 +00002335 // Insert the new instruction into the basic block...
2336 BasicBlock *InstParent = I->getParent();
Chris Lattnerbac32862004-11-14 19:13:23 +00002337 BasicBlock::iterator InsertPos = I;
2338
Eli Friedman049260d2011-11-01 04:49:29 +00002339 // If we replace a PHI with something that isn't a PHI, fix up the
2340 // insertion point.
2341 if (!isa<PHINode>(Result) && isa<PHINode>(InsertPos))
2342 InsertPos = InstParent->getFirstInsertionPt();
Chris Lattnerbac32862004-11-14 19:13:23 +00002343
2344 InstParent->getInstList().insert(InsertPos, Result);
Chris Lattner4bb7c022003-10-06 17:11:01 +00002345
Chris Lattner7a1e9242009-08-30 06:13:40 +00002346 EraseInstFromFunction(*I);
Chris Lattner7e708292002-06-25 16:13:24 +00002347 } else {
Evan Chengc7baf682007-03-27 16:44:48 +00002348#ifndef NDEBUG
Chris Lattnerbdff5482009-08-23 04:37:46 +00002349 DEBUG(errs() << "IC: Mod = " << OrigI << '\n'
2350 << " New = " << *I << '\n');
Evan Chengc7baf682007-03-27 16:44:48 +00002351#endif
Chris Lattner0cea42a2004-03-13 23:54:27 +00002352
Chris Lattner90ac28c2002-08-02 19:29:35 +00002353 // If the instruction was modified, it's possible that it is now dead.
2354 // if so, remove it.
Benjamin Kramer8e0d1c02012-08-29 15:32:21 +00002355 if (isInstructionTriviallyDead(I, TLI)) {
Chris Lattner7a1e9242009-08-30 06:13:40 +00002356 EraseInstFromFunction(*I);
Chris Lattnerf523d062004-06-09 05:08:07 +00002357 } else {
Chris Lattner7a1e9242009-08-30 06:13:40 +00002358 Worklist.Add(I);
Chris Lattnere5ecdb52009-08-30 06:22:51 +00002359 Worklist.AddUsersToWorkList(*I);
Chris Lattner90ac28c2002-08-02 19:29:35 +00002360 }
Chris Lattnerb3bc8fa2002-05-14 15:24:07 +00002361 }
Chris Lattnerb0b822c2009-08-31 06:57:37 +00002362 MadeIRChange = true;
Chris Lattner8a2a3112001-12-14 16:52:21 +00002363 }
2364 }
2365
Chris Lattner873ff012009-08-30 05:55:36 +00002366 Worklist.Zap();
Chris Lattnerb0b822c2009-08-31 06:57:37 +00002367 return MadeIRChange;
Chris Lattnerbd0ef772002-02-26 21:46:54 +00002368}
2369
Chris Lattnerec9c3582007-03-03 02:04:50 +00002370
2371bool InstCombiner::runOnFunction(Function &F) {
Micah Villmow3574eca2012-10-08 16:38:25 +00002372 TD = getAnalysisIfAvailable<DataLayout>();
Chad Rosier00737bd2011-12-01 21:29:16 +00002373 TLI = &getAnalysis<TargetLibraryInfo>();
Jakub Staszak58c1da82012-05-06 13:52:31 +00002374
Chris Lattner74381062009-08-30 07:44:24 +00002375 /// Builder - This is an IRBuilder that automatically inserts new
2376 /// instructions into the worklist when they are created.
Jakub Staszak58c1da82012-05-06 13:52:31 +00002377 IRBuilder<true, TargetFolder, InstCombineIRInserter>
Chris Lattnerf55eeb92009-11-06 05:59:53 +00002378 TheBuilder(F.getContext(), TargetFolder(TD),
Chris Lattner74381062009-08-30 07:44:24 +00002379 InstCombineIRInserter(Worklist));
2380 Builder = &TheBuilder;
Jakub Staszak58c1da82012-05-06 13:52:31 +00002381
Meador Inge5e890452012-10-13 16:45:24 +00002382 LibCallSimplifier TheSimplifier(TD, TLI);
2383 Simplifier = &TheSimplifier;
2384
Chris Lattnerec9c3582007-03-03 02:04:50 +00002385 bool EverMadeChange = false;
2386
Devang Patel813c9a02011-03-17 22:18:16 +00002387 // Lower dbg.declare intrinsics otherwise their value may be clobbered
2388 // by instcombiner.
2389 EverMadeChange = LowerDbgDeclare(F);
2390
Chris Lattnerec9c3582007-03-03 02:04:50 +00002391 // Iterate while there is work to do.
2392 unsigned Iteration = 0;
Bill Wendlinga6c31122008-05-14 22:45:20 +00002393 while (DoOneIteration(F, Iteration++))
Chris Lattnerec9c3582007-03-03 02:04:50 +00002394 EverMadeChange = true;
Jakub Staszak58c1da82012-05-06 13:52:31 +00002395
Chris Lattner74381062009-08-30 07:44:24 +00002396 Builder = 0;
Chris Lattnerec9c3582007-03-03 02:04:50 +00002397 return EverMadeChange;
2398}
2399
Brian Gaeke96d4bf72004-07-27 17:43:21 +00002400FunctionPass *llvm::createInstructionCombiningPass() {
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002401 return new InstCombiner();
Chris Lattnerbd0ef772002-02-26 21:46:54 +00002402}