blob: 734056d211870f456c77440412e4f43eb6b7e3a3 [file] [log] [blame]
Chris Lattnere6794492002-08-12 21:17:25 +00001//===- InstructionCombining.cpp - Combine multiple instructions -----------===//
Misha Brukmanb1c93172005-04-21 23:48:37 +00002//
John Criswell482202a2003-10-20 19:43:21 +00003// The LLVM Compiler Infrastructure
4//
Chris Lattnerf3ebc3f2007-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 Brukmanb1c93172005-04-21 23:48:37 +00007//
John Criswell482202a2003-10-20 19:43:21 +00008//===----------------------------------------------------------------------===//
Chris Lattnerca081252001-12-14 16:52:21 +00009//
10// InstructionCombining - Combine instructions to form fewer, simple
Dan Gohmand78c4002008-05-13 00:00:25 +000011// instructions. This pass does not modify the CFG. This pass is where
12// algebraic simplification happens.
Chris Lattnerca081252001-12-14 16:52:21 +000013//
14// This pass combines things like:
Chris Lattner07418422007-03-18 22:51:34 +000015// %Y = add i32 %X, 1
16// %Z = add i32 %Y, 1
Chris Lattnerca081252001-12-14 16:52:21 +000017// into:
Chris Lattner07418422007-03-18 22:51:34 +000018// %Z = add i32 %X, 2
Chris Lattnerca081252001-12-14 16:52:21 +000019//
20// This is a simple worklist driven algorithm.
21//
Chris Lattner216c7b82003-09-10 05:29:43 +000022// This pass guarantees that the following canonicalizations are performed on
Chris Lattnerbfb1d032003-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 Lattnerdeaa0dd2003-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 Spencer266e42b2006-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 Lattnerede3fe02003-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 Lattner7515cab2004-11-14 19:13:23 +000032// ... etc.
Chris Lattnerbfb1d032003-07-23 21:41:57 +000033//
Chris Lattnerca081252001-12-14 16:52:21 +000034//===----------------------------------------------------------------------===//
35
Chandler Carruth83ba2692015-01-24 04:19:17 +000036#include "llvm/Transforms/InstCombine/InstCombine.h"
Chandler Carrutha9174582015-01-22 05:25:13 +000037#include "InstCombineInternal.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000038#include "llvm-c/Initialization.h"
39#include "llvm/ADT/SmallPtrSet.h"
40#include "llvm/ADT/Statistic.h"
41#include "llvm/ADT/StringSwitch.h"
Chandler Carruth66b31302015-01-04 12:03:27 +000042#include "llvm/Analysis/AssumptionCache.h"
David Majnemer7e2b9882014-11-03 21:55:12 +000043#include "llvm/Analysis/CFG.h"
Chris Lattner024f4ab2007-01-30 23:46:24 +000044#include "llvm/Analysis/ConstantFolding.h"
Chris Lattnerc1f19072009-11-09 23:28:39 +000045#include "llvm/Analysis/InstructionSimplify.h"
Reid Kleckner4af64152015-01-28 01:17:38 +000046#include "llvm/Analysis/LibCallSemantics.h"
David Majnemer7e2b9882014-11-03 21:55:12 +000047#include "llvm/Analysis/LoopInfo.h"
Victor Hernandezf390e042009-10-27 20:05:49 +000048#include "llvm/Analysis/MemoryBuiltins.h"
Chandler Carruth83ba2692015-01-24 04:19:17 +000049#include "llvm/Analysis/TargetLibraryInfo.h"
Sanjay Patel58814442014-07-09 16:34:54 +000050#include "llvm/Analysis/ValueTracking.h"
Chandler Carruth1305dc32014-03-04 11:45:46 +000051#include "llvm/IR/CFG.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000052#include "llvm/IR/DataLayout.h"
Hal Finkel60db0582014-09-07 18:57:58 +000053#include "llvm/IR/Dominators.h"
Chandler Carruth03eb0de2014-03-04 10:40:04 +000054#include "llvm/IR/GetElementPtrTypeIterator.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000055#include "llvm/IR/IntrinsicInst.h"
Chandler Carruth820a9082014-03-04 11:08:18 +000056#include "llvm/IR/PatternMatch.h"
Chandler Carruth4220e9c2014-03-04 11:17:44 +000057#include "llvm/IR/ValueHandle.h"
Meador Inge193e0352012-11-13 04:16:17 +000058#include "llvm/Support/CommandLine.h"
Chris Lattner39c98bb2004-12-08 23:43:58 +000059#include "llvm/Support/Debug.h"
Benjamin Kramer799003b2015-03-23 19:32:43 +000060#include "llvm/Support/raw_ostream.h"
Chandler Carruth83ba2692015-01-24 04:19:17 +000061#include "llvm/Transforms/Scalar.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000062#include "llvm/Transforms/Utils/Local.h"
Chris Lattner053c0932002-05-14 15:24:07 +000063#include <algorithm>
Torok Edwinab207842008-04-20 08:33:11 +000064#include <climits>
Chris Lattner8427bff2003-12-07 01:24:23 +000065using namespace llvm;
Chris Lattnerd4252a72004-07-30 07:50:03 +000066using namespace llvm::PatternMatch;
Brian Gaeke960707c2003-11-11 22:41:34 +000067
Chandler Carruth964daaa2014-04-22 02:55:47 +000068#define DEBUG_TYPE "instcombine"
69
Chris Lattner79a42ac2006-12-19 21:40:18 +000070STATISTIC(NumCombined , "Number of insts combined");
71STATISTIC(NumConstProp, "Number of constant folds");
72STATISTIC(NumDeadInst , "Number of dead inst eliminated");
Chris Lattner79a42ac2006-12-19 21:40:18 +000073STATISTIC(NumSunkInst , "Number of instructions sunk");
Duncan Sandsfbb9ac32010-12-22 13:36:08 +000074STATISTIC(NumExpand, "Number of expansions");
Duncan Sands3547d2e2010-12-22 09:40:51 +000075STATISTIC(NumFactor , "Number of factorizations");
76STATISTIC(NumReassoc , "Number of reassociations");
Chris Lattnerbf3a0992002-10-01 22:38:41 +000077
Nuno Lopesa2f6cec2012-05-22 17:19:09 +000078Value *InstCombiner::EmitGEPOffset(User *GEP) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +000079 return llvm::EmitGEPOffset(Builder, DL, GEP);
Nuno Lopesa2f6cec2012-05-22 17:19:09 +000080}
81
Chris Lattner1559bed2009-11-10 07:23:37 +000082/// ShouldChangeType - Return true if it is desirable to convert a computation
83/// from 'From' to 'To'. We don't want to convert from a legal to an illegal
84/// type for example, or from a smaller to a larger illegal type.
Chris Lattner229907c2011-07-18 04:54:35 +000085bool InstCombiner::ShouldChangeType(Type *From, Type *To) const {
Duncan Sands19d0b472010-02-16 11:11:14 +000086 assert(From->isIntegerTy() && To->isIntegerTy());
Jakub Staszakcfc46f82012-05-06 13:52:31 +000087
Chris Lattner1559bed2009-11-10 07:23:37 +000088 unsigned FromWidth = From->getPrimitiveSizeInBits();
89 unsigned ToWidth = To->getPrimitiveSizeInBits();
Mehdi Aminia28d91d2015-03-10 02:37:25 +000090 bool FromLegal = DL.isLegalInteger(FromWidth);
91 bool ToLegal = DL.isLegalInteger(ToWidth);
Jakub Staszakcfc46f82012-05-06 13:52:31 +000092
Chris Lattner1559bed2009-11-10 07:23:37 +000093 // If this is a legal integer from type, and the result would be an illegal
94 // type, don't do the transformation.
95 if (FromLegal && !ToLegal)
96 return false;
Jakub Staszakcfc46f82012-05-06 13:52:31 +000097
Chris Lattner1559bed2009-11-10 07:23:37 +000098 // Otherwise, if both are illegal, do not increase the size of the result. We
99 // do allow things like i160 -> i64, but not i64 -> i160.
100 if (!FromLegal && !ToLegal && ToWidth > FromWidth)
101 return false;
Jakub Staszakcfc46f82012-05-06 13:52:31 +0000102
Chris Lattner1559bed2009-11-10 07:23:37 +0000103 return true;
104}
105
Nick Lewyckyde492782011-08-14 01:45:19 +0000106// Return true, if No Signed Wrap should be maintained for I.
107// The No Signed Wrap flag can be kept if the operation "B (I.getOpcode) C",
108// where both B and C should be ConstantInts, results in a constant that does
109// not overflow. This function only handles the Add and Sub opcodes. For
110// all other opcodes, the function conservatively returns false.
111static bool MaintainNoSignedWrap(BinaryOperator &I, Value *B, Value *C) {
112 OverflowingBinaryOperator *OBO = dyn_cast<OverflowingBinaryOperator>(&I);
113 if (!OBO || !OBO->hasNoSignedWrap()) {
114 return false;
115 }
116
117 // We reason about Add and Sub Only.
118 Instruction::BinaryOps Opcode = I.getOpcode();
Jakub Staszakcfc46f82012-05-06 13:52:31 +0000119 if (Opcode != Instruction::Add &&
Nick Lewyckyde492782011-08-14 01:45:19 +0000120 Opcode != Instruction::Sub) {
121 return false;
122 }
123
124 ConstantInt *CB = dyn_cast<ConstantInt>(B);
125 ConstantInt *CC = dyn_cast<ConstantInt>(C);
126
127 if (!CB || !CC) {
128 return false;
129 }
130
131 const APInt &BVal = CB->getValue();
132 const APInt &CVal = CC->getValue();
133 bool Overflow = false;
134
135 if (Opcode == Instruction::Add) {
136 BVal.sadd_ov(CVal, Overflow);
137 } else {
138 BVal.ssub_ov(CVal, Overflow);
139 }
140
141 return !Overflow;
142}
143
Michael Ilseman1dd6f2a2013-02-07 01:40:15 +0000144/// Conservatively clears subclassOptionalData after a reassociation or
145/// commutation. We preserve fast-math flags when applicable as they can be
146/// preserved.
147static void ClearSubclassDataAfterReassociation(BinaryOperator &I) {
148 FPMathOperator *FPMO = dyn_cast<FPMathOperator>(&I);
149 if (!FPMO) {
150 I.clearSubclassOptionalData();
151 return;
152 }
153
154 FastMathFlags FMF = I.getFastMathFlags();
155 I.clearSubclassOptionalData();
156 I.setFastMathFlags(FMF);
157}
158
Duncan Sands641baf12010-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 Lattner260ab202002-04-18 17:39:14 +0000163//
Chris Lattnerdcf240a2003-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 Sands641baf12010-11-13 15:10:37 +0000168// Associative operators:
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000169//
Duncan Sands641baf12010-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 Lattnerdcf240a2003-03-10 21:43:22 +0000181 Instruction::BinaryOps Opcode = I.getOpcode();
Duncan Sands641baf12010-11-13 15:10:37 +0000182 bool Changed = false;
Chris Lattner7fb29e12003-03-11 00:12:48 +0000183
Duncan Sands641baf12010-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?
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000203 if (Value *V = SimplifyBinOp(Opcode, B, C, DL)) {
Duncan Sands641baf12010-11-13 15:10:37 +0000204 // It simplifies to V. Form "A op V".
205 I.setOperand(0, A);
206 I.setOperand(1, V);
Dan Gohmanc6f0bda2011-02-02 02:05:46 +0000207 // Conservatively clear the optional flags, since they may not be
208 // preserved by the reassociation.
Nick Lewyckyae13df62011-08-14 03:41:33 +0000209 if (MaintainNoSignedWrap(I, B, C) &&
Bill Wendlingea6397f2012-07-19 00:11:40 +0000210 (!Op0 || (isa<BinaryOperator>(Op0) && Op0->hasNoSignedWrap()))) {
Nick Lewyckyae13df62011-08-14 03:41:33 +0000211 // Note: this is only valid because SimplifyBinOp doesn't look at
212 // the operands to Op0.
Nick Lewyckyde492782011-08-14 01:45:19 +0000213 I.clearSubclassOptionalData();
214 I.setHasNoSignedWrap(true);
215 } else {
Michael Ilseman1dd6f2a2013-02-07 01:40:15 +0000216 ClearSubclassDataAfterReassociation(I);
Nick Lewyckyde492782011-08-14 01:45:19 +0000217 }
Jakub Staszakcfc46f82012-05-06 13:52:31 +0000218
Duncan Sands641baf12010-11-13 15:10:37 +0000219 Changed = true;
Duncan Sands3547d2e2010-12-22 09:40:51 +0000220 ++NumReassoc;
Duncan Sands641baf12010-11-13 15:10:37 +0000221 continue;
Misha Brukmanb1c93172005-04-21 23:48:37 +0000222 }
Duncan Sands641baf12010-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?
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000232 if (Value *V = SimplifyBinOp(Opcode, A, B, DL)) {
Duncan Sands641baf12010-11-13 15:10:37 +0000233 // It simplifies to V. Form "V op C".
234 I.setOperand(0, V);
235 I.setOperand(1, C);
Dan Gohmanc6f0bda2011-02-02 02:05:46 +0000236 // Conservatively clear the optional flags, since they may not be
237 // preserved by the reassociation.
Michael Ilseman1dd6f2a2013-02-07 01:40:15 +0000238 ClearSubclassDataAfterReassociation(I);
Duncan Sands641baf12010-11-13 15:10:37 +0000239 Changed = true;
Duncan Sands3547d2e2010-12-22 09:40:51 +0000240 ++NumReassoc;
Duncan Sands641baf12010-11-13 15:10:37 +0000241 continue;
242 }
243 }
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000244 }
Duncan Sands641baf12010-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?
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000254 if (Value *V = SimplifyBinOp(Opcode, C, A, DL)) {
Duncan Sands641baf12010-11-13 15:10:37 +0000255 // It simplifies to V. Form "V op B".
256 I.setOperand(0, V);
257 I.setOperand(1, B);
Dan Gohmanc6f0bda2011-02-02 02:05:46 +0000258 // Conservatively clear the optional flags, since they may not be
259 // preserved by the reassociation.
Michael Ilseman1dd6f2a2013-02-07 01:40:15 +0000260 ClearSubclassDataAfterReassociation(I);
Duncan Sands641baf12010-11-13 15:10:37 +0000261 Changed = true;
Duncan Sands3547d2e2010-12-22 09:40:51 +0000262 ++NumReassoc;
Duncan Sands641baf12010-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?
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000274 if (Value *V = SimplifyBinOp(Opcode, C, A, DL)) {
Duncan Sands641baf12010-11-13 15:10:37 +0000275 // It simplifies to V. Form "B op V".
276 I.setOperand(0, B);
277 I.setOperand(1, V);
Dan Gohmanc6f0bda2011-02-02 02:05:46 +0000278 // Conservatively clear the optional flags, since they may not be
279 // preserved by the reassociation.
Michael Ilseman1dd6f2a2013-02-07 01:40:15 +0000280 ClearSubclassDataAfterReassociation(I);
Duncan Sands641baf12010-11-13 15:10:37 +0000281 Changed = true;
Duncan Sands3547d2e2010-12-22 09:40:51 +0000282 ++NumReassoc;
Duncan Sands641baf12010-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 Lewyckyde492782011-08-14 01:45:19 +0000300 BinaryOperator *New = BinaryOperator::Create(Opcode, A, B);
Owen Anderson1664dc82014-01-20 07:44:53 +0000301 if (isa<FPMathOperator>(New)) {
302 FastMathFlags Flags = I.getFastMathFlags();
303 Flags &= Op0->getFastMathFlags();
304 Flags &= Op1->getFastMathFlags();
305 New->setFastMathFlags(Flags);
306 }
Eli Friedman35211c62011-05-27 00:19:40 +0000307 InsertNewInstWith(New, I);
Eli Friedman41e509a2011-05-18 23:58:37 +0000308 New->takeName(Op1);
Duncan Sands641baf12010-11-13 15:10:37 +0000309 I.setOperand(0, New);
310 I.setOperand(1, Folded);
Dan Gohmanc6f0bda2011-02-02 02:05:46 +0000311 // Conservatively clear the optional flags, since they may not be
312 // preserved by the reassociation.
Michael Ilseman1dd6f2a2013-02-07 01:40:15 +0000313 ClearSubclassDataAfterReassociation(I);
Nick Lewyckyde492782011-08-14 01:45:19 +0000314
Duncan Sands641baf12010-11-13 15:10:37 +0000315 Changed = true;
316 continue;
317 }
318 }
319
320 // No further simplifications.
321 return Changed;
322 } while (1);
Chris Lattner260ab202002-04-18 17:39:14 +0000323}
Chris Lattnerca081252001-12-14 16:52:21 +0000324
Duncan Sandsadc7771f2010-11-23 14:23:47 +0000325/// LeftDistributesOverRight - Whether "X LOp (Y ROp Z)" is always equal to
Duncan Sands22df7412010-11-23 15:25:34 +0000326/// "(X LOp Y) ROp (X LOp Z)".
Duncan Sandsadc7771f2010-11-23 14:23:47 +0000327static bool LeftDistributesOverRight(Instruction::BinaryOps LOp,
328 Instruction::BinaryOps ROp) {
329 switch (LOp) {
330 default:
331 return false;
332
333 case Instruction::And:
334 // And distributes over Or and Xor.
335 switch (ROp) {
336 default:
337 return false;
338 case Instruction::Or:
339 case Instruction::Xor:
340 return true;
341 }
342
343 case Instruction::Mul:
344 // Multiplication distributes over addition and subtraction.
345 switch (ROp) {
346 default:
347 return false;
348 case Instruction::Add:
349 case Instruction::Sub:
350 return true;
351 }
352
353 case Instruction::Or:
354 // Or distributes over And.
355 switch (ROp) {
356 default:
357 return false;
358 case Instruction::And:
359 return true;
360 }
361 }
362}
363
364/// RightDistributesOverLeft - Whether "(X LOp Y) ROp Z" is always equal to
365/// "(X ROp Z) LOp (Y ROp Z)".
366static bool RightDistributesOverLeft(Instruction::BinaryOps LOp,
367 Instruction::BinaryOps ROp) {
368 if (Instruction::isCommutative(ROp))
369 return LeftDistributesOverRight(ROp, LOp);
Dinesh Dwivedi4919bbe2014-08-26 08:53:32 +0000370
371 switch (LOp) {
372 default:
373 return false;
374 // (X >> Z) & (Y >> Z) -> (X&Y) >> Z for all shifts.
375 // (X >> Z) | (Y >> Z) -> (X|Y) >> Z for all shifts.
376 // (X >> Z) ^ (Y >> Z) -> (X^Y) >> Z for all shifts.
377 case Instruction::And:
378 case Instruction::Or:
379 case Instruction::Xor:
380 switch (ROp) {
381 default:
382 return false;
383 case Instruction::Shl:
384 case Instruction::LShr:
385 case Instruction::AShr:
386 return true;
387 }
388 }
Duncan Sandsadc7771f2010-11-23 14:23:47 +0000389 // TODO: It would be nice to handle division, aka "(X + Y)/Z = X/Z + Y/Z",
390 // but this requires knowing that the addition does not overflow and other
391 // such subtleties.
392 return false;
393}
394
Dinesh Dwivedib62e52e2014-06-19 08:29:18 +0000395/// This function returns identity value for given opcode, which can be used to
396/// factor patterns like (X * 2) + X ==> (X * 2) + (X * 1) ==> X * (2 + 1).
397static Value *getIdentityValue(Instruction::BinaryOps OpCode, Value *V) {
398 if (isa<Constant>(V))
399 return nullptr;
400
401 if (OpCode == Instruction::Mul)
402 return ConstantInt::get(V->getType(), 1);
403
404 // TODO: We can handle other cases e.g. Instruction::And, Instruction::Or etc.
405
406 return nullptr;
407}
408
409/// This function factors binary ops which can be combined using distributive
Dinesh Dwivedi4919bbe2014-08-26 08:53:32 +0000410/// laws. This function tries to transform 'Op' based TopLevelOpcode to enable
411/// factorization e.g for ADD(SHL(X , 2), MUL(X, 5)), When this function called
412/// with TopLevelOpcode == Instruction::Add and Op = SHL(X, 2), transforms
413/// SHL(X, 2) to MUL(X, 4) i.e. returns Instruction::Mul with LHS set to 'X' and
414/// RHS to 4.
Benjamin Kramer6cbe6702014-07-07 14:47:51 +0000415static Instruction::BinaryOps
Dinesh Dwivedi4919bbe2014-08-26 08:53:32 +0000416getBinOpsForFactorization(Instruction::BinaryOps TopLevelOpcode,
417 BinaryOperator *Op, Value *&LHS, Value *&RHS) {
Dinesh Dwivedib62e52e2014-06-19 08:29:18 +0000418 if (!Op)
419 return Instruction::BinaryOpsEnd;
420
Dinesh Dwivedi4919bbe2014-08-26 08:53:32 +0000421 LHS = Op->getOperand(0);
422 RHS = Op->getOperand(1);
423
424 switch (TopLevelOpcode) {
425 default:
426 return Op->getOpcode();
427
428 case Instruction::Add:
429 case Instruction::Sub:
430 if (Op->getOpcode() == Instruction::Shl) {
431 if (Constant *CST = dyn_cast<Constant>(Op->getOperand(1))) {
432 // The multiplier is really 1 << CST.
433 RHS = ConstantExpr::getShl(ConstantInt::get(Op->getType(), 1), CST);
434 return Instruction::Mul;
435 }
Dinesh Dwivedib62e52e2014-06-19 08:29:18 +0000436 }
Dinesh Dwivedi4919bbe2014-08-26 08:53:32 +0000437 return Op->getOpcode();
Dinesh Dwivedib62e52e2014-06-19 08:29:18 +0000438 }
439
440 // TODO: We can add other conversions e.g. shr => div etc.
Dinesh Dwivedib62e52e2014-06-19 08:29:18 +0000441}
442
443/// This tries to simplify binary operations by factorizing out common terms
444/// (e. g. "(A*B)+(A*C)" -> "A*(B+C)").
445static Value *tryFactorization(InstCombiner::BuilderTy *Builder,
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000446 const DataLayout &DL, BinaryOperator &I,
Dinesh Dwivedib62e52e2014-06-19 08:29:18 +0000447 Instruction::BinaryOps InnerOpcode, Value *A,
448 Value *B, Value *C, Value *D) {
449
450 // If any of A, B, C, D are null, we can not factor I, return early.
451 // Checking A and C should be enough.
452 if (!A || !C || !B || !D)
453 return nullptr;
454
David Majnemer4c3753c2015-05-22 23:02:11 +0000455 Value *V = nullptr;
Dinesh Dwivedib62e52e2014-06-19 08:29:18 +0000456 Value *SimplifiedInst = nullptr;
457 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
458 Instruction::BinaryOps TopLevelOpcode = I.getOpcode();
459
460 // Does "X op' Y" always equal "Y op' X"?
461 bool InnerCommutative = Instruction::isCommutative(InnerOpcode);
462
463 // Does "X op' (Y op Z)" always equal "(X op' Y) op (X op' Z)"?
464 if (LeftDistributesOverRight(InnerOpcode, TopLevelOpcode))
465 // Does the instruction have the form "(A op' B) op (A op' D)" or, in the
466 // commutative case, "(A op' B) op (C op' A)"?
467 if (A == C || (InnerCommutative && A == D)) {
468 if (A != C)
469 std::swap(C, D);
470 // Consider forming "A op' (B op D)".
471 // If "B op D" simplifies then it can be formed with no cost.
David Majnemer4c3753c2015-05-22 23:02:11 +0000472 V = SimplifyBinOp(TopLevelOpcode, B, D, DL);
Dinesh Dwivedib62e52e2014-06-19 08:29:18 +0000473 // If "B op D" doesn't simplify then only go on if both of the existing
474 // operations "A op' B" and "C op' D" will be zapped as no longer used.
475 if (!V && LHS->hasOneUse() && RHS->hasOneUse())
476 V = Builder->CreateBinOp(TopLevelOpcode, B, D, RHS->getName());
477 if (V) {
478 SimplifiedInst = Builder->CreateBinOp(InnerOpcode, A, V);
479 }
480 }
481
482 // Does "(X op Y) op' Z" always equal "(X op' Z) op (Y op' Z)"?
483 if (!SimplifiedInst && RightDistributesOverLeft(TopLevelOpcode, InnerOpcode))
484 // Does the instruction have the form "(A op' B) op (C op' B)" or, in the
485 // commutative case, "(A op' B) op (B op' D)"?
486 if (B == D || (InnerCommutative && B == C)) {
487 if (B != D)
488 std::swap(C, D);
489 // Consider forming "(A op C) op' B".
490 // If "A op C" simplifies then it can be formed with no cost.
David Majnemer4c3753c2015-05-22 23:02:11 +0000491 V = SimplifyBinOp(TopLevelOpcode, A, C, DL);
Dinesh Dwivedib62e52e2014-06-19 08:29:18 +0000492
493 // If "A op C" doesn't simplify then only go on if both of the existing
494 // operations "A op' B" and "C op' D" will be zapped as no longer used.
495 if (!V && LHS->hasOneUse() && RHS->hasOneUse())
496 V = Builder->CreateBinOp(TopLevelOpcode, A, C, LHS->getName());
497 if (V) {
498 SimplifiedInst = Builder->CreateBinOp(InnerOpcode, V, B);
499 }
500 }
501
502 if (SimplifiedInst) {
503 ++NumFactor;
504 SimplifiedInst->takeName(&I);
505
506 // Check if we can add NSW flag to SimplifiedInst. If so, set NSW flag.
507 // TODO: Check for NUW.
508 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(SimplifiedInst)) {
509 if (isa<OverflowingBinaryOperator>(SimplifiedInst)) {
510 bool HasNSW = false;
511 if (isa<OverflowingBinaryOperator>(&I))
512 HasNSW = I.hasNoSignedWrap();
513
514 if (BinaryOperator *Op0 = dyn_cast<BinaryOperator>(LHS))
515 if (isa<OverflowingBinaryOperator>(Op0))
516 HasNSW &= Op0->hasNoSignedWrap();
517
518 if (BinaryOperator *Op1 = dyn_cast<BinaryOperator>(RHS))
519 if (isa<OverflowingBinaryOperator>(Op1))
520 HasNSW &= Op1->hasNoSignedWrap();
David Majnemer4c3753c2015-05-22 23:02:11 +0000521
522 // We can propogate 'nsw' if we know that
523 // %Y = mul nsw i16 %X, C
524 // %Z = add nsw i16 %Y, %X
525 // =>
526 // %Z = mul nsw i16 %X, C+1
527 //
528 // iff C+1 isn't INT_MIN
529 const APInt *CInt;
530 if (TopLevelOpcode == Instruction::Add &&
531 InnerOpcode == Instruction::Mul)
532 if (match(V, m_APInt(CInt)) && !CInt->isMinSignedValue())
533 BO->setHasNoSignedWrap(HasNSW);
Dinesh Dwivedib62e52e2014-06-19 08:29:18 +0000534 }
535 }
536 }
537 return SimplifiedInst;
538}
539
Duncan Sandsfbb9ac32010-12-22 13:36:08 +0000540/// SimplifyUsingDistributiveLaws - This tries to simplify binary operations
541/// which some other binary operation distributes over either by factorizing
542/// out common terms (eg "(A*B)+(A*C)" -> "A*(B+C)") or expanding out if this
543/// results in simplifications (eg: "A & (B | C) -> (A&B) | (A&C)" if this is
544/// a win). Returns the simplified value, or null if it didn't simplify.
545Value *InstCombiner::SimplifyUsingDistributiveLaws(BinaryOperator &I) {
546 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
547 BinaryOperator *Op0 = dyn_cast<BinaryOperator>(LHS);
548 BinaryOperator *Op1 = dyn_cast<BinaryOperator>(RHS);
Duncan Sandsadc7771f2010-11-23 14:23:47 +0000549
Duncan Sandsfbb9ac32010-12-22 13:36:08 +0000550 // Factorization.
Dinesh Dwivedib62e52e2014-06-19 08:29:18 +0000551 Value *A = nullptr, *B = nullptr, *C = nullptr, *D = nullptr;
Dinesh Dwivedi4919bbe2014-08-26 08:53:32 +0000552 auto TopLevelOpcode = I.getOpcode();
553 auto LHSOpcode = getBinOpsForFactorization(TopLevelOpcode, Op0, A, B);
554 auto RHSOpcode = getBinOpsForFactorization(TopLevelOpcode, Op1, C, D);
Duncan Sandsadc7771f2010-11-23 14:23:47 +0000555
Dinesh Dwivedib62e52e2014-06-19 08:29:18 +0000556 // The instruction has the form "(A op' B) op (C op' D)". Try to factorize
557 // a common term.
558 if (LHSOpcode == RHSOpcode) {
559 if (Value *V = tryFactorization(Builder, DL, I, LHSOpcode, A, B, C, D))
560 return V;
Duncan Sandsfbb9ac32010-12-22 13:36:08 +0000561 }
562
Dinesh Dwivedib62e52e2014-06-19 08:29:18 +0000563 // The instruction has the form "(A op' B) op (C)". Try to factorize common
564 // term.
565 if (Value *V = tryFactorization(Builder, DL, I, LHSOpcode, A, B, RHS,
566 getIdentityValue(LHSOpcode, RHS)))
567 return V;
568
569 // The instruction has the form "(B) op (C op' D)". Try to factorize common
570 // term.
571 if (Value *V = tryFactorization(Builder, DL, I, RHSOpcode, LHS,
572 getIdentityValue(RHSOpcode, LHS), C, D))
573 return V;
574
Duncan Sandsfbb9ac32010-12-22 13:36:08 +0000575 // Expansion.
576 if (Op0 && RightDistributesOverLeft(Op0->getOpcode(), TopLevelOpcode)) {
577 // The instruction has the form "(A op' B) op C". See if expanding it out
578 // to "(A op C) op' (B op C)" results in simplifications.
579 Value *A = Op0->getOperand(0), *B = Op0->getOperand(1), *C = RHS;
580 Instruction::BinaryOps InnerOpcode = Op0->getOpcode(); // op'
581
582 // Do "A op C" and "B op C" both simplify?
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000583 if (Value *L = SimplifyBinOp(TopLevelOpcode, A, C, DL))
584 if (Value *R = SimplifyBinOp(TopLevelOpcode, B, C, DL)) {
Duncan Sandsfbb9ac32010-12-22 13:36:08 +0000585 // They do! Return "L op' R".
586 ++NumExpand;
587 // If "L op' R" equals "A op' B" then "L op' R" is just the LHS.
588 if ((L == A && R == B) ||
589 (Instruction::isCommutative(InnerOpcode) && L == B && R == A))
590 return Op0;
591 // Otherwise return "L op' R" if it simplifies.
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000592 if (Value *V = SimplifyBinOp(InnerOpcode, L, R, DL))
Duncan Sandsfbb9ac32010-12-22 13:36:08 +0000593 return V;
594 // Otherwise, create a new instruction.
595 C = Builder->CreateBinOp(InnerOpcode, L, R);
596 C->takeName(&I);
597 return C;
598 }
599 }
600
601 if (Op1 && LeftDistributesOverRight(TopLevelOpcode, Op1->getOpcode())) {
602 // The instruction has the form "A op (B op' C)". See if expanding it out
603 // to "(A op B) op' (A op C)" results in simplifications.
604 Value *A = LHS, *B = Op1->getOperand(0), *C = Op1->getOperand(1);
605 Instruction::BinaryOps InnerOpcode = Op1->getOpcode(); // op'
606
607 // Do "A op B" and "A op C" both simplify?
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000608 if (Value *L = SimplifyBinOp(TopLevelOpcode, A, B, DL))
609 if (Value *R = SimplifyBinOp(TopLevelOpcode, A, C, DL)) {
Duncan Sandsfbb9ac32010-12-22 13:36:08 +0000610 // They do! Return "L op' R".
611 ++NumExpand;
612 // If "L op' R" equals "B op' C" then "L op' R" is just the RHS.
613 if ((L == B && R == C) ||
614 (Instruction::isCommutative(InnerOpcode) && L == C && R == B))
615 return Op1;
616 // Otherwise return "L op' R" if it simplifies.
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000617 if (Value *V = SimplifyBinOp(InnerOpcode, L, R, DL))
Duncan Sandsfbb9ac32010-12-22 13:36:08 +0000618 return V;
619 // Otherwise, create a new instruction.
620 A = Builder->CreateBinOp(InnerOpcode, L, R);
621 A->takeName(&I);
622 return A;
623 }
624 }
Duncan Sandsadc7771f2010-11-23 14:23:47 +0000625
David Majnemer33b6f822015-07-14 22:39:23 +0000626 // (op (select (a, c, b)), (select (a, d, b))) -> (select (a, (op c, d), 0))
627 // (op (select (a, b, c)), (select (a, b, d))) -> (select (a, 0, (op c, d)))
628 if (auto *SI0 = dyn_cast<SelectInst>(LHS)) {
629 if (auto *SI1 = dyn_cast<SelectInst>(RHS)) {
630 if (SI0->getCondition() == SI1->getCondition()) {
631 Value *SI = nullptr;
632 if (Value *V = SimplifyBinOp(TopLevelOpcode, SI0->getFalseValue(),
633 SI1->getFalseValue(), DL, TLI, DT, AC))
634 SI = Builder->CreateSelect(SI0->getCondition(),
635 Builder->CreateBinOp(TopLevelOpcode,
636 SI0->getTrueValue(),
637 SI1->getTrueValue()),
638 V);
639 if (Value *V = SimplifyBinOp(TopLevelOpcode, SI0->getTrueValue(),
640 SI1->getTrueValue(), DL, TLI, DT, AC))
641 SI = Builder->CreateSelect(
642 SI0->getCondition(), V,
643 Builder->CreateBinOp(TopLevelOpcode, SI0->getFalseValue(),
644 SI1->getFalseValue()));
645 if (SI) {
646 SI->takeName(&I);
647 return SI;
648 }
649 }
650 }
651 }
652
Craig Topperf40110f2014-04-25 05:29:35 +0000653 return nullptr;
Duncan Sandsadc7771f2010-11-23 14:23:47 +0000654}
655
Chris Lattnerbb74e222003-03-10 23:06:50 +0000656// dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
657// if the LHS is a constant zero (which is the 'negate' form).
Chris Lattner9fa53de2002-05-06 16:49:18 +0000658//
Chris Lattner2188e402010-01-04 07:37:31 +0000659Value *InstCombiner::dyn_castNegVal(Value *V) const {
Owen Andersonbb2501b2009-07-13 22:18:28 +0000660 if (BinaryOperator::isNeg(V))
Chris Lattnerd6f636a2005-04-24 07:30:14 +0000661 return BinaryOperator::getNegArgument(V);
Chris Lattnerbb74e222003-03-10 23:06:50 +0000662
Chris Lattner9ad0d552004-12-14 20:08:06 +0000663 // Constants can be considered to be negated values if they can be folded.
664 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
Owen Anderson487375e2009-07-29 18:55:55 +0000665 return ConstantExpr::getNeg(C);
Nick Lewycky3bf55122008-05-23 04:54:45 +0000666
Chris Lattner8213c8a2012-02-06 21:56:39 +0000667 if (ConstantDataVector *C = dyn_cast<ConstantDataVector>(V))
668 if (C->getType()->getElementType()->isIntegerTy())
Owen Anderson487375e2009-07-29 18:55:55 +0000669 return ConstantExpr::getNeg(C);
Nick Lewycky3bf55122008-05-23 04:54:45 +0000670
Craig Topperf40110f2014-04-25 05:29:35 +0000671 return nullptr;
Chris Lattner9fa53de2002-05-06 16:49:18 +0000672}
673
Dan Gohmana5b96452009-06-04 22:49:04 +0000674// dyn_castFNegVal - Given a 'fsub' instruction, return the RHS of the
675// instruction if the LHS is a constant negative zero (which is the 'negate'
676// form).
677//
Shuxin Yangf0537ab2013-01-09 00:13:41 +0000678Value *InstCombiner::dyn_castFNegVal(Value *V, bool IgnoreZeroSign) const {
679 if (BinaryOperator::isFNeg(V, IgnoreZeroSign))
Dan Gohmana5b96452009-06-04 22:49:04 +0000680 return BinaryOperator::getFNegArgument(V);
681
682 // Constants can be considered to be negated values if they can be folded.
683 if (ConstantFP *C = dyn_cast<ConstantFP>(V))
Owen Anderson487375e2009-07-29 18:55:55 +0000684 return ConstantExpr::getFNeg(C);
Dan Gohmana5b96452009-06-04 22:49:04 +0000685
Chris Lattner8213c8a2012-02-06 21:56:39 +0000686 if (ConstantDataVector *C = dyn_cast<ConstantDataVector>(V))
687 if (C->getType()->getElementType()->isFloatingPointTy())
Owen Anderson487375e2009-07-29 18:55:55 +0000688 return ConstantExpr::getFNeg(C);
Dan Gohmana5b96452009-06-04 22:49:04 +0000689
Craig Topperf40110f2014-04-25 05:29:35 +0000690 return nullptr;
Dan Gohmana5b96452009-06-04 22:49:04 +0000691}
692
Chris Lattner86102b82005-01-01 16:22:27 +0000693static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
Chris Lattner183b3362004-04-09 19:05:30 +0000694 InstCombiner *IC) {
Nick Lewycky6a083cf2011-01-21 02:30:43 +0000695 if (CastInst *CI = dyn_cast<CastInst>(&I)) {
Chris Lattnerc8565392009-08-30 20:01:10 +0000696 return IC->Builder->CreateCast(CI->getOpcode(), SO, I.getType());
Nick Lewycky6a083cf2011-01-21 02:30:43 +0000697 }
Chris Lattner86102b82005-01-01 16:22:27 +0000698
Chris Lattner183b3362004-04-09 19:05:30 +0000699 // Figure out if the constant is the left or the right argument.
Chris Lattner86102b82005-01-01 16:22:27 +0000700 bool ConstIsRHS = isa<Constant>(I.getOperand(1));
701 Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
Chris Lattnerb8b97502003-08-13 19:01:45 +0000702
Chris Lattner183b3362004-04-09 19:05:30 +0000703 if (Constant *SOC = dyn_cast<Constant>(SO)) {
704 if (ConstIsRHS)
Owen Anderson487375e2009-07-29 18:55:55 +0000705 return ConstantExpr::get(I.getOpcode(), SOC, ConstOperand);
706 return ConstantExpr::get(I.getOpcode(), ConstOperand, SOC);
Chris Lattner183b3362004-04-09 19:05:30 +0000707 }
708
709 Value *Op0 = SO, *Op1 = ConstOperand;
710 if (!ConstIsRHS)
711 std::swap(Op0, Op1);
Jakub Staszakcfc46f82012-05-06 13:52:31 +0000712
Owen Anderson1664dc82014-01-20 07:44:53 +0000713 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I)) {
714 Value *RI = IC->Builder->CreateBinOp(BO->getOpcode(), Op0, Op1,
Chris Lattner022a5822009-08-30 07:44:24 +0000715 SO->getName()+".op");
Owen Anderson1664dc82014-01-20 07:44:53 +0000716 Instruction *FPInst = dyn_cast<Instruction>(RI);
717 if (FPInst && isa<FPMathOperator>(FPInst))
718 FPInst->copyFastMathFlags(BO);
719 return RI;
720 }
Chris Lattner022a5822009-08-30 07:44:24 +0000721 if (ICmpInst *CI = dyn_cast<ICmpInst>(&I))
722 return IC->Builder->CreateICmp(CI->getPredicate(), Op0, Op1,
723 SO->getName()+".cmp");
724 if (FCmpInst *CI = dyn_cast<FCmpInst>(&I))
725 return IC->Builder->CreateICmp(CI->getPredicate(), Op0, Op1,
726 SO->getName()+".cmp");
727 llvm_unreachable("Unknown binary instruction type!");
Chris Lattner86102b82005-01-01 16:22:27 +0000728}
729
730// FoldOpIntoSelect - Given an instruction with a select as one operand and a
731// constant as the other operand, try to fold the binary operator into the
732// select arguments. This also works for Cast instructions, which obviously do
733// not have a second operand.
Chris Lattner2b295a02010-01-04 07:53:58 +0000734Instruction *InstCombiner::FoldOpIntoSelect(Instruction &Op, SelectInst *SI) {
Chris Lattner86102b82005-01-01 16:22:27 +0000735 // Don't modify shared select instructions
Craig Topperf40110f2014-04-25 05:29:35 +0000736 if (!SI->hasOneUse()) return nullptr;
Chris Lattner86102b82005-01-01 16:22:27 +0000737 Value *TV = SI->getOperand(1);
738 Value *FV = SI->getOperand(2);
739
740 if (isa<Constant>(TV) || isa<Constant>(FV)) {
Chris Lattner374e6592005-04-21 05:43:13 +0000741 // Bool selects with constant operands can be folded to logical ops.
Craig Topperf40110f2014-04-25 05:29:35 +0000742 if (SI->getType()->isIntegerTy(1)) return nullptr;
Chris Lattner374e6592005-04-21 05:43:13 +0000743
Nick Lewycky6a083cf2011-01-21 02:30:43 +0000744 // If it's a bitcast involving vectors, make sure it has the same number of
745 // elements on both sides.
746 if (BitCastInst *BC = dyn_cast<BitCastInst>(&Op)) {
Chris Lattner229907c2011-07-18 04:54:35 +0000747 VectorType *DestTy = dyn_cast<VectorType>(BC->getDestTy());
748 VectorType *SrcTy = dyn_cast<VectorType>(BC->getSrcTy());
Nick Lewycky6a083cf2011-01-21 02:30:43 +0000749
750 // Verify that either both or neither are vectors.
Craig Topperf40110f2014-04-25 05:29:35 +0000751 if ((SrcTy == nullptr) != (DestTy == nullptr)) return nullptr;
Nick Lewycky6a083cf2011-01-21 02:30:43 +0000752 // If vectors, verify that they have the same number of elements.
753 if (SrcTy && SrcTy->getNumElements() != DestTy->getNumElements())
Craig Topperf40110f2014-04-25 05:29:35 +0000754 return nullptr;
Nick Lewycky6a083cf2011-01-21 02:30:43 +0000755 }
Jakub Staszakcfc46f82012-05-06 13:52:31 +0000756
James Molloy2b21a7c2015-05-20 18:41:25 +0000757 // Test if a CmpInst instruction is used exclusively by a select as
758 // part of a minimum or maximum operation. If so, refrain from doing
759 // any other folding. This helps out other analyses which understand
760 // non-obfuscated minimum and maximum idioms, such as ScalarEvolution
761 // and CodeGen. And in this case, at least one of the comparison
762 // operands has at least one user besides the compare (the select),
763 // which would often largely negate the benefit of folding anyway.
764 if (auto *CI = dyn_cast<CmpInst>(SI->getCondition())) {
765 if (CI->hasOneUse()) {
766 Value *Op0 = CI->getOperand(0), *Op1 = CI->getOperand(1);
767 if ((SI->getOperand(1) == Op0 && SI->getOperand(2) == Op1) ||
768 (SI->getOperand(2) == Op0 && SI->getOperand(1) == Op1))
769 return nullptr;
770 }
771 }
772
Chris Lattner2b295a02010-01-04 07:53:58 +0000773 Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, this);
774 Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, this);
Chris Lattner86102b82005-01-01 16:22:27 +0000775
Nick Lewycky6a083cf2011-01-21 02:30:43 +0000776 return SelectInst::Create(SI->getCondition(),
777 SelectTrueVal, SelectFalseVal);
Chris Lattner86102b82005-01-01 16:22:27 +0000778 }
Craig Topperf40110f2014-04-25 05:29:35 +0000779 return nullptr;
Chris Lattner183b3362004-04-09 19:05:30 +0000780}
781
Chris Lattnerfacb8672009-09-27 19:57:57 +0000782/// FoldOpIntoPhi - Given a binary operator, cast instruction, or select which
783/// has a PHI node as operand #0, see if we can fold the instruction into the
784/// PHI (which is only possible if all operands to the PHI are constants).
Chris Lattnerb391e872009-09-27 20:46:36 +0000785///
Chris Lattnerea7131a2011-01-16 05:14:26 +0000786Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I) {
Chris Lattner6a4adcd2004-09-29 05:07:12 +0000787 PHINode *PN = cast<PHINode>(I.getOperand(0));
Chris Lattner7515cab2004-11-14 19:13:23 +0000788 unsigned NumPHIValues = PN->getNumIncomingValues();
Chris Lattner25ce2802011-01-16 04:37:29 +0000789 if (NumPHIValues == 0)
Craig Topperf40110f2014-04-25 05:29:35 +0000790 return nullptr;
Jakub Staszakcfc46f82012-05-06 13:52:31 +0000791
Chris Lattnerf4ca47b2011-01-21 05:08:26 +0000792 // We normally only transform phis with a single use. However, if a PHI has
793 // multiple uses and they are all the same operation, we can fold *all* of the
794 // uses into the PHI.
Chris Lattnerd55581d2011-01-16 05:28:59 +0000795 if (!PN->hasOneUse()) {
796 // Walk the use list for the instruction, comparing them to I.
Chandler Carruthcdf47882014-03-09 03:16:01 +0000797 for (User *U : PN->users()) {
798 Instruction *UI = cast<Instruction>(U);
799 if (UI != &I && !I.isIdenticalTo(UI))
Craig Topperf40110f2014-04-25 05:29:35 +0000800 return nullptr;
Chris Lattnerb5e15d12011-01-21 05:29:50 +0000801 }
Chris Lattnerd55581d2011-01-16 05:28:59 +0000802 // Otherwise, we can replace *all* users with the new PHI we form.
803 }
Jakub Staszakcfc46f82012-05-06 13:52:31 +0000804
Chris Lattnerfacb8672009-09-27 19:57:57 +0000805 // Check to see if all of the operands of the PHI are simple constants
806 // (constantint/constantfp/undef). If there is one non-constant value,
Chris Lattnerae289632009-09-27 20:18:49 +0000807 // remember the BB it is in. If there is more than one or if *it* is a PHI,
808 // bail out. We don't do arbitrary constant expressions here because moving
809 // their computation can be expensive without a cost model.
Craig Topperf40110f2014-04-25 05:29:35 +0000810 BasicBlock *NonConstBB = nullptr;
Chris Lattner25ce2802011-01-16 04:37:29 +0000811 for (unsigned i = 0; i != NumPHIValues; ++i) {
812 Value *InVal = PN->getIncomingValue(i);
813 if (isa<Constant>(InVal) && !isa<ConstantExpr>(InVal))
814 continue;
815
Craig Topperf40110f2014-04-25 05:29:35 +0000816 if (isa<PHINode>(InVal)) return nullptr; // Itself a phi.
817 if (NonConstBB) return nullptr; // More than one non-const value.
Jakub Staszakcfc46f82012-05-06 13:52:31 +0000818
Chris Lattner25ce2802011-01-16 04:37:29 +0000819 NonConstBB = PN->getIncomingBlock(i);
Chris Lattnerff2e7372011-01-16 05:08:00 +0000820
821 // If the InVal is an invoke at the end of the pred block, then we can't
822 // insert a computation after it without breaking the edge.
823 if (InvokeInst *II = dyn_cast<InvokeInst>(InVal))
824 if (II->getParent() == NonConstBB)
Craig Topperf40110f2014-04-25 05:29:35 +0000825 return nullptr;
Jakub Staszakcfc46f82012-05-06 13:52:31 +0000826
Chris Lattnerb5e15d12011-01-21 05:29:50 +0000827 // If the incoming non-constant value is in I's block, we will remove one
828 // instruction, but insert another equivalent one, leading to infinite
829 // instcombine.
Chandler Carruth5175b9a2015-01-20 08:35:24 +0000830 if (isPotentiallyReachable(I.getParent(), NonConstBB, DT, LI))
Craig Topperf40110f2014-04-25 05:29:35 +0000831 return nullptr;
Chris Lattner25ce2802011-01-16 04:37:29 +0000832 }
Jakub Staszakcfc46f82012-05-06 13:52:31 +0000833
Chris Lattner04689872006-09-09 22:02:56 +0000834 // If there is exactly one non-constant value, we can insert a copy of the
835 // operation in that block. However, if this is a critical edge, we would be
David Majnemer7e2b9882014-11-03 21:55:12 +0000836 // inserting the computation on some other paths (e.g. inside a loop). Only
Chris Lattner04689872006-09-09 22:02:56 +0000837 // do this if the pred block is unconditionally branching into the phi block.
Craig Topperf40110f2014-04-25 05:29:35 +0000838 if (NonConstBB != nullptr) {
Chris Lattner04689872006-09-09 22:02:56 +0000839 BranchInst *BI = dyn_cast<BranchInst>(NonConstBB->getTerminator());
Craig Topperf40110f2014-04-25 05:29:35 +0000840 if (!BI || !BI->isUnconditional()) return nullptr;
Chris Lattner04689872006-09-09 22:02:56 +0000841 }
Chris Lattner6a4adcd2004-09-29 05:07:12 +0000842
843 // Okay, we can do the transformation: create the new PHI node.
Eli Friedman41e509a2011-05-18 23:58:37 +0000844 PHINode *NewPN = PHINode::Create(I.getType(), PN->getNumIncomingValues());
Chris Lattner966526c2009-10-21 23:41:58 +0000845 InsertNewInstBefore(NewPN, *PN);
846 NewPN->takeName(PN);
Jakub Staszakcfc46f82012-05-06 13:52:31 +0000847
Chris Lattnerff2e7372011-01-16 05:08:00 +0000848 // If we are going to have to insert a new computation, do so right before the
849 // predecessors terminator.
850 if (NonConstBB)
851 Builder->SetInsertPoint(NonConstBB->getTerminator());
Jakub Staszakcfc46f82012-05-06 13:52:31 +0000852
Chris Lattner6a4adcd2004-09-29 05:07:12 +0000853 // Next, add all of the operands to the PHI.
Chris Lattnerfacb8672009-09-27 19:57:57 +0000854 if (SelectInst *SI = dyn_cast<SelectInst>(&I)) {
855 // We only currently try to fold the condition of a select when it is a phi,
856 // not the true/false values.
Chris Lattnerae289632009-09-27 20:18:49 +0000857 Value *TrueV = SI->getTrueValue();
858 Value *FalseV = SI->getFalseValue();
Chris Lattner0261b5d2009-09-28 06:49:44 +0000859 BasicBlock *PhiTransBB = PN->getParent();
Chris Lattnerfacb8672009-09-27 19:57:57 +0000860 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattnerae289632009-09-27 20:18:49 +0000861 BasicBlock *ThisBB = PN->getIncomingBlock(i);
Chris Lattner0261b5d2009-09-28 06:49:44 +0000862 Value *TrueVInPred = TrueV->DoPHITranslation(PhiTransBB, ThisBB);
863 Value *FalseVInPred = FalseV->DoPHITranslation(PhiTransBB, ThisBB);
Craig Topperf40110f2014-04-25 05:29:35 +0000864 Value *InV = nullptr;
Duncan P. N. Exon Smithce5f93e2013-12-06 21:48:36 +0000865 // Beware of ConstantExpr: it may eventually evaluate to getNullValue,
866 // even if currently isNullValue gives false.
867 Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i));
868 if (InC && !isa<ConstantExpr>(InC))
Chris Lattnerae289632009-09-27 20:18:49 +0000869 InV = InC->isNullValue() ? FalseVInPred : TrueVInPred;
Chris Lattnerff2e7372011-01-16 05:08:00 +0000870 else
871 InV = Builder->CreateSelect(PN->getIncomingValue(i),
872 TrueVInPred, FalseVInPred, "phitmp");
Chris Lattnerae289632009-09-27 20:18:49 +0000873 NewPN->addIncoming(InV, ThisBB);
Chris Lattnerfacb8672009-09-27 19:57:57 +0000874 }
Chris Lattnerff2e7372011-01-16 05:08:00 +0000875 } else if (CmpInst *CI = dyn_cast<CmpInst>(&I)) {
876 Constant *C = cast<Constant>(I.getOperand(1));
877 for (unsigned i = 0; i != NumPHIValues; ++i) {
Craig Topperf40110f2014-04-25 05:29:35 +0000878 Value *InV = nullptr;
Chris Lattnerff2e7372011-01-16 05:08:00 +0000879 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i)))
880 InV = ConstantExpr::getCompare(CI->getPredicate(), InC, C);
881 else if (isa<ICmpInst>(CI))
882 InV = Builder->CreateICmp(CI->getPredicate(), PN->getIncomingValue(i),
883 C, "phitmp");
884 else
885 InV = Builder->CreateFCmp(CI->getPredicate(), PN->getIncomingValue(i),
886 C, "phitmp");
887 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
888 }
Chris Lattnerfacb8672009-09-27 19:57:57 +0000889 } else if (I.getNumOperands() == 2) {
Chris Lattner6a4adcd2004-09-29 05:07:12 +0000890 Constant *C = cast<Constant>(I.getOperand(1));
Chris Lattner7515cab2004-11-14 19:13:23 +0000891 for (unsigned i = 0; i != NumPHIValues; ++i) {
Craig Topperf40110f2014-04-25 05:29:35 +0000892 Value *InV = nullptr;
Chris Lattnerff2e7372011-01-16 05:08:00 +0000893 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i)))
894 InV = ConstantExpr::get(I.getOpcode(), InC, C);
895 else
896 InV = Builder->CreateBinOp(cast<BinaryOperator>(I).getOpcode(),
897 PN->getIncomingValue(i), C, "phitmp");
Chris Lattner04689872006-09-09 22:02:56 +0000898 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
Chris Lattner6a4adcd2004-09-29 05:07:12 +0000899 }
Jakub Staszakcfc46f82012-05-06 13:52:31 +0000900 } else {
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000901 CastInst *CI = cast<CastInst>(&I);
Chris Lattner229907c2011-07-18 04:54:35 +0000902 Type *RetTy = CI->getType();
Chris Lattner7515cab2004-11-14 19:13:23 +0000903 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattner04689872006-09-09 22:02:56 +0000904 Value *InV;
Chris Lattnerff2e7372011-01-16 05:08:00 +0000905 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i)))
Owen Anderson487375e2009-07-29 18:55:55 +0000906 InV = ConstantExpr::getCast(CI->getOpcode(), InC, RetTy);
Jakub Staszakcfc46f82012-05-06 13:52:31 +0000907 else
Chris Lattnerff2e7372011-01-16 05:08:00 +0000908 InV = Builder->CreateCast(CI->getOpcode(),
909 PN->getIncomingValue(i), I.getType(), "phitmp");
Chris Lattner04689872006-09-09 22:02:56 +0000910 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
Chris Lattner6a4adcd2004-09-29 05:07:12 +0000911 }
912 }
Jakub Staszakcfc46f82012-05-06 13:52:31 +0000913
Chandler Carruthcdf47882014-03-09 03:16:01 +0000914 for (auto UI = PN->user_begin(), E = PN->user_end(); UI != E;) {
Chris Lattnerd55581d2011-01-16 05:28:59 +0000915 Instruction *User = cast<Instruction>(*UI++);
916 if (User == &I) continue;
917 ReplaceInstUsesWith(*User, NewPN);
918 EraseInstFromFunction(*User);
919 }
Chris Lattner6a4adcd2004-09-29 05:07:12 +0000920 return ReplaceInstUsesWith(I, NewPN);
921}
922
Matt Arsenaultd79f7d92013-08-19 22:17:40 +0000923/// FindElementAtOffset - Given a pointer type and a constant offset, determine
924/// whether or not there is a sequence of GEP indices into the pointed type that
925/// will land us at the specified offset. If so, fill them into NewIndices and
926/// return the resultant element type, otherwise return null.
David Blaikie87ca1b62015-03-27 20:56:11 +0000927Type *InstCombiner::FindElementAtOffset(PointerType *PtrTy, int64_t Offset,
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000928 SmallVectorImpl<Value *> &NewIndices) {
David Blaikie87ca1b62015-03-27 20:56:11 +0000929 Type *Ty = PtrTy->getElementType();
Matt Arsenaultd79f7d92013-08-19 22:17:40 +0000930 if (!Ty->isSized())
Craig Topperf40110f2014-04-25 05:29:35 +0000931 return nullptr;
Jakub Staszakcfc46f82012-05-06 13:52:31 +0000932
Chris Lattnerfef138b2009-01-09 05:44:56 +0000933 // Start with the index over the outer type. Note that the type size
934 // might be zero (even if the offset isn't zero) if the indexed type
935 // is something like [0 x {int, int}]
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000936 Type *IntPtrTy = DL.getIntPtrType(PtrTy);
Chris Lattnerfef138b2009-01-09 05:44:56 +0000937 int64_t FirstIdx = 0;
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000938 if (int64_t TySize = DL.getTypeAllocSize(Ty)) {
Chris Lattnerfef138b2009-01-09 05:44:56 +0000939 FirstIdx = Offset/TySize;
Chris Lattnerbd3c7c82009-01-11 20:41:36 +0000940 Offset -= FirstIdx*TySize;
Jakub Staszakcfc46f82012-05-06 13:52:31 +0000941
Benjamin Kramere4c46fe2013-01-23 17:52:29 +0000942 // Handle hosts where % returns negative instead of values [0..TySize).
943 if (Offset < 0) {
944 --FirstIdx;
945 Offset += TySize;
946 assert(Offset >= 0);
947 }
Chris Lattnerfef138b2009-01-09 05:44:56 +0000948 assert((uint64_t)Offset < (uint64_t)TySize && "Out of range offset");
949 }
Jakub Staszakcfc46f82012-05-06 13:52:31 +0000950
Owen Andersonedb4a702009-07-24 23:12:02 +0000951 NewIndices.push_back(ConstantInt::get(IntPtrTy, FirstIdx));
Jakub Staszakcfc46f82012-05-06 13:52:31 +0000952
Chris Lattnerfef138b2009-01-09 05:44:56 +0000953 // Index into the types. If we fail, set OrigBase to null.
954 while (Offset) {
Chris Lattner171d2d42009-01-11 20:15:20 +0000955 // Indexing into tail padding between struct/array elements.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000956 if (uint64_t(Offset * 8) >= DL.getTypeSizeInBits(Ty))
Craig Topperf40110f2014-04-25 05:29:35 +0000957 return nullptr;
Jakub Staszakcfc46f82012-05-06 13:52:31 +0000958
Chris Lattner229907c2011-07-18 04:54:35 +0000959 if (StructType *STy = dyn_cast<StructType>(Ty)) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000960 const StructLayout *SL = DL.getStructLayout(STy);
Chris Lattner171d2d42009-01-11 20:15:20 +0000961 assert(Offset < (int64_t)SL->getSizeInBytes() &&
962 "Offset must stay within the indexed type");
Jakub Staszakcfc46f82012-05-06 13:52:31 +0000963
Chris Lattnerfef138b2009-01-09 05:44:56 +0000964 unsigned Elt = SL->getElementContainingOffset(Offset);
Chris Lattnerb8906bd2010-01-04 07:02:48 +0000965 NewIndices.push_back(ConstantInt::get(Type::getInt32Ty(Ty->getContext()),
966 Elt));
Jakub Staszakcfc46f82012-05-06 13:52:31 +0000967
Chris Lattnerfef138b2009-01-09 05:44:56 +0000968 Offset -= SL->getElementOffset(Elt);
969 Ty = STy->getElementType(Elt);
Chris Lattner229907c2011-07-18 04:54:35 +0000970 } else if (ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000971 uint64_t EltSize = DL.getTypeAllocSize(AT->getElementType());
Chris Lattner171d2d42009-01-11 20:15:20 +0000972 assert(EltSize && "Cannot index into a zero-sized array");
Owen Andersonedb4a702009-07-24 23:12:02 +0000973 NewIndices.push_back(ConstantInt::get(IntPtrTy,Offset/EltSize));
Chris Lattner171d2d42009-01-11 20:15:20 +0000974 Offset %= EltSize;
Chris Lattnerb1915162009-01-11 20:23:52 +0000975 Ty = AT->getElementType();
Chris Lattnerfef138b2009-01-09 05:44:56 +0000976 } else {
Chris Lattner171d2d42009-01-11 20:15:20 +0000977 // Otherwise, we can't index into the middle of this atomic type, bail.
Craig Topperf40110f2014-04-25 05:29:35 +0000978 return nullptr;
Chris Lattnerfef138b2009-01-09 05:44:56 +0000979 }
980 }
Jakub Staszakcfc46f82012-05-06 13:52:31 +0000981
Chris Lattner72cd68f2009-01-24 01:00:13 +0000982 return Ty;
Chris Lattnerfef138b2009-01-09 05:44:56 +0000983}
984
Rafael Espindolaa3a44f3f2011-07-31 04:43:41 +0000985static bool shouldMergeGEPs(GEPOperator &GEP, GEPOperator &Src) {
986 // If this GEP has only 0 indices, it is the same pointer as
987 // Src. If Src is not a trivial GEP too, don't combine
988 // the indices.
989 if (GEP.hasAllZeroIndices() && !Src.hasAllZeroIndices() &&
990 !Src.hasOneUse())
991 return false;
992 return true;
993}
Chris Lattnerbbbdd852002-05-06 18:06:38 +0000994
Duncan Sands533c8ae2012-10-23 08:28:26 +0000995/// Descale - Return a value X such that Val = X * Scale, or null if none. If
996/// the multiplication is known not to overflow then NoSignedWrap is set.
997Value *InstCombiner::Descale(Value *Val, APInt Scale, bool &NoSignedWrap) {
998 assert(isa<IntegerType>(Val->getType()) && "Can only descale integers!");
999 assert(cast<IntegerType>(Val->getType())->getBitWidth() ==
1000 Scale.getBitWidth() && "Scale not compatible with value!");
1001
1002 // If Val is zero or Scale is one then Val = Val * Scale.
1003 if (match(Val, m_Zero()) || Scale == 1) {
1004 NoSignedWrap = true;
1005 return Val;
1006 }
1007
1008 // If Scale is zero then it does not divide Val.
1009 if (Scale.isMinValue())
Craig Topperf40110f2014-04-25 05:29:35 +00001010 return nullptr;
Duncan Sands533c8ae2012-10-23 08:28:26 +00001011
1012 // Look through chains of multiplications, searching for a constant that is
1013 // divisible by Scale. For example, descaling X*(Y*(Z*4)) by a factor of 4
1014 // will find the constant factor 4 and produce X*(Y*Z). Descaling X*(Y*8) by
1015 // a factor of 4 will produce X*(Y*2). The principle of operation is to bore
1016 // down from Val:
1017 //
1018 // Val = M1 * X || Analysis starts here and works down
1019 // M1 = M2 * Y || Doesn't descend into terms with more
1020 // M2 = Z * 4 \/ than one use
1021 //
1022 // Then to modify a term at the bottom:
1023 //
1024 // Val = M1 * X
1025 // M1 = Z * Y || Replaced M2 with Z
1026 //
1027 // Then to work back up correcting nsw flags.
1028
1029 // Op - the term we are currently analyzing. Starts at Val then drills down.
1030 // Replaced with its descaled value before exiting from the drill down loop.
1031 Value *Op = Val;
1032
1033 // Parent - initially null, but after drilling down notes where Op came from.
1034 // In the example above, Parent is (Val, 0) when Op is M1, because M1 is the
1035 // 0'th operand of Val.
1036 std::pair<Instruction*, unsigned> Parent;
1037
1038 // RequireNoSignedWrap - Set if the transform requires a descaling at deeper
1039 // levels that doesn't overflow.
1040 bool RequireNoSignedWrap = false;
1041
1042 // logScale - log base 2 of the scale. Negative if not a power of 2.
1043 int32_t logScale = Scale.exactLogBase2();
1044
1045 for (;; Op = Parent.first->getOperand(Parent.second)) { // Drill down
1046
1047 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op)) {
1048 // If Op is a constant divisible by Scale then descale to the quotient.
1049 APInt Quotient(Scale), Remainder(Scale); // Init ensures right bitwidth.
1050 APInt::sdivrem(CI->getValue(), Scale, Quotient, Remainder);
1051 if (!Remainder.isMinValue())
1052 // Not divisible by Scale.
Craig Topperf40110f2014-04-25 05:29:35 +00001053 return nullptr;
Duncan Sands533c8ae2012-10-23 08:28:26 +00001054 // Replace with the quotient in the parent.
1055 Op = ConstantInt::get(CI->getType(), Quotient);
1056 NoSignedWrap = true;
1057 break;
1058 }
1059
1060 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op)) {
1061
1062 if (BO->getOpcode() == Instruction::Mul) {
1063 // Multiplication.
1064 NoSignedWrap = BO->hasNoSignedWrap();
1065 if (RequireNoSignedWrap && !NoSignedWrap)
Craig Topperf40110f2014-04-25 05:29:35 +00001066 return nullptr;
Duncan Sands533c8ae2012-10-23 08:28:26 +00001067
1068 // There are three cases for multiplication: multiplication by exactly
1069 // the scale, multiplication by a constant different to the scale, and
1070 // multiplication by something else.
1071 Value *LHS = BO->getOperand(0);
1072 Value *RHS = BO->getOperand(1);
1073
1074 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHS)) {
1075 // Multiplication by a constant.
1076 if (CI->getValue() == Scale) {
1077 // Multiplication by exactly the scale, replace the multiplication
1078 // by its left-hand side in the parent.
1079 Op = LHS;
1080 break;
1081 }
1082
1083 // Otherwise drill down into the constant.
1084 if (!Op->hasOneUse())
Craig Topperf40110f2014-04-25 05:29:35 +00001085 return nullptr;
Duncan Sands533c8ae2012-10-23 08:28:26 +00001086
1087 Parent = std::make_pair(BO, 1);
1088 continue;
1089 }
1090
1091 // Multiplication by something else. Drill down into the left-hand side
1092 // since that's where the reassociate pass puts the good stuff.
1093 if (!Op->hasOneUse())
Craig Topperf40110f2014-04-25 05:29:35 +00001094 return nullptr;
Duncan Sands533c8ae2012-10-23 08:28:26 +00001095
1096 Parent = std::make_pair(BO, 0);
1097 continue;
1098 }
1099
1100 if (logScale > 0 && BO->getOpcode() == Instruction::Shl &&
1101 isa<ConstantInt>(BO->getOperand(1))) {
1102 // Multiplication by a power of 2.
1103 NoSignedWrap = BO->hasNoSignedWrap();
1104 if (RequireNoSignedWrap && !NoSignedWrap)
Craig Topperf40110f2014-04-25 05:29:35 +00001105 return nullptr;
Duncan Sands533c8ae2012-10-23 08:28:26 +00001106
1107 Value *LHS = BO->getOperand(0);
1108 int32_t Amt = cast<ConstantInt>(BO->getOperand(1))->
1109 getLimitedValue(Scale.getBitWidth());
1110 // Op = LHS << Amt.
1111
1112 if (Amt == logScale) {
1113 // Multiplication by exactly the scale, replace the multiplication
1114 // by its left-hand side in the parent.
1115 Op = LHS;
1116 break;
1117 }
1118 if (Amt < logScale || !Op->hasOneUse())
Craig Topperf40110f2014-04-25 05:29:35 +00001119 return nullptr;
Duncan Sands533c8ae2012-10-23 08:28:26 +00001120
1121 // Multiplication by more than the scale. Reduce the multiplying amount
1122 // by the scale in the parent.
1123 Parent = std::make_pair(BO, 1);
1124 Op = ConstantInt::get(BO->getType(), Amt - logScale);
1125 break;
1126 }
1127 }
1128
1129 if (!Op->hasOneUse())
Craig Topperf40110f2014-04-25 05:29:35 +00001130 return nullptr;
Duncan Sands533c8ae2012-10-23 08:28:26 +00001131
1132 if (CastInst *Cast = dyn_cast<CastInst>(Op)) {
1133 if (Cast->getOpcode() == Instruction::SExt) {
1134 // Op is sign-extended from a smaller type, descale in the smaller type.
1135 unsigned SmallSize = Cast->getSrcTy()->getPrimitiveSizeInBits();
1136 APInt SmallScale = Scale.trunc(SmallSize);
1137 // Suppose Op = sext X, and we descale X as Y * SmallScale. We want to
1138 // descale Op as (sext Y) * Scale. In order to have
1139 // sext (Y * SmallScale) = (sext Y) * Scale
1140 // some conditions need to hold however: SmallScale must sign-extend to
1141 // Scale and the multiplication Y * SmallScale should not overflow.
1142 if (SmallScale.sext(Scale.getBitWidth()) != Scale)
1143 // SmallScale does not sign-extend to Scale.
Craig Topperf40110f2014-04-25 05:29:35 +00001144 return nullptr;
Duncan Sands533c8ae2012-10-23 08:28:26 +00001145 assert(SmallScale.exactLogBase2() == logScale);
1146 // Require that Y * SmallScale must not overflow.
1147 RequireNoSignedWrap = true;
1148
1149 // Drill down through the cast.
1150 Parent = std::make_pair(Cast, 0);
1151 Scale = SmallScale;
1152 continue;
1153 }
1154
Duncan Sands5ed39002012-10-23 09:07:02 +00001155 if (Cast->getOpcode() == Instruction::Trunc) {
Duncan Sands533c8ae2012-10-23 08:28:26 +00001156 // Op is truncated from a larger type, descale in the larger type.
1157 // Suppose Op = trunc X, and we descale X as Y * sext Scale. Then
1158 // trunc (Y * sext Scale) = (trunc Y) * Scale
1159 // always holds. However (trunc Y) * Scale may overflow even if
1160 // trunc (Y * sext Scale) does not, so nsw flags need to be cleared
1161 // from this point up in the expression (see later).
1162 if (RequireNoSignedWrap)
Craig Topperf40110f2014-04-25 05:29:35 +00001163 return nullptr;
Duncan Sands533c8ae2012-10-23 08:28:26 +00001164
1165 // Drill down through the cast.
1166 unsigned LargeSize = Cast->getSrcTy()->getPrimitiveSizeInBits();
1167 Parent = std::make_pair(Cast, 0);
1168 Scale = Scale.sext(LargeSize);
1169 if (logScale + 1 == (int32_t)Cast->getType()->getPrimitiveSizeInBits())
1170 logScale = -1;
1171 assert(Scale.exactLogBase2() == logScale);
1172 continue;
1173 }
1174 }
1175
1176 // Unsupported expression, bail out.
Craig Topperf40110f2014-04-25 05:29:35 +00001177 return nullptr;
Duncan Sands533c8ae2012-10-23 08:28:26 +00001178 }
1179
Duncan P. N. Exon Smith04934b02014-07-10 17:13:27 +00001180 // If Op is zero then Val = Op * Scale.
1181 if (match(Op, m_Zero())) {
1182 NoSignedWrap = true;
1183 return Op;
1184 }
1185
Duncan Sands533c8ae2012-10-23 08:28:26 +00001186 // We know that we can successfully descale, so from here on we can safely
1187 // modify the IR. Op holds the descaled version of the deepest term in the
1188 // expression. NoSignedWrap is 'true' if multiplying Op by Scale is known
1189 // not to overflow.
1190
1191 if (!Parent.first)
1192 // The expression only had one term.
1193 return Op;
1194
1195 // Rewrite the parent using the descaled version of its operand.
1196 assert(Parent.first->hasOneUse() && "Drilled down when more than one use!");
1197 assert(Op != Parent.first->getOperand(Parent.second) &&
1198 "Descaling was a no-op?");
1199 Parent.first->setOperand(Parent.second, Op);
1200 Worklist.Add(Parent.first);
1201
1202 // Now work back up the expression correcting nsw flags. The logic is based
1203 // on the following observation: if X * Y is known not to overflow as a signed
1204 // multiplication, and Y is replaced by a value Z with smaller absolute value,
1205 // then X * Z will not overflow as a signed multiplication either. As we work
1206 // our way up, having NoSignedWrap 'true' means that the descaled value at the
1207 // current level has strictly smaller absolute value than the original.
1208 Instruction *Ancestor = Parent.first;
1209 do {
1210 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Ancestor)) {
1211 // If the multiplication wasn't nsw then we can't say anything about the
1212 // value of the descaled multiplication, and we have to clear nsw flags
1213 // from this point on up.
1214 bool OpNoSignedWrap = BO->hasNoSignedWrap();
1215 NoSignedWrap &= OpNoSignedWrap;
1216 if (NoSignedWrap != OpNoSignedWrap) {
1217 BO->setHasNoSignedWrap(NoSignedWrap);
1218 Worklist.Add(Ancestor);
1219 }
1220 } else if (Ancestor->getOpcode() == Instruction::Trunc) {
1221 // The fact that the descaled input to the trunc has smaller absolute
1222 // value than the original input doesn't tell us anything useful about
1223 // the absolute values of the truncations.
1224 NoSignedWrap = false;
1225 }
1226 assert((Ancestor->getOpcode() != Instruction::SExt || NoSignedWrap) &&
1227 "Failed to keep proper track of nsw flags while drilling down?");
1228
1229 if (Ancestor == Val)
1230 // Got to the top, all done!
1231 return Val;
1232
1233 // Move up one level in the expression.
1234 assert(Ancestor->hasOneUse() && "Drilled down when more than one use!");
Chandler Carruthcdf47882014-03-09 03:16:01 +00001235 Ancestor = Ancestor->user_back();
Duncan Sands533c8ae2012-10-23 08:28:26 +00001236 } while (1);
1237}
1238
Serge Pavlov9ef66a82014-05-11 08:46:12 +00001239/// \brief Creates node of binary operation with the same attributes as the
1240/// specified one but with other operands.
Serge Pavlove6de9e32014-05-14 09:05:09 +00001241static Value *CreateBinOpAsGiven(BinaryOperator &Inst, Value *LHS, Value *RHS,
1242 InstCombiner::BuilderTy *B) {
1243 Value *BORes = B->CreateBinOp(Inst.getOpcode(), LHS, RHS);
1244 if (BinaryOperator *NewBO = dyn_cast<BinaryOperator>(BORes)) {
1245 if (isa<OverflowingBinaryOperator>(NewBO)) {
1246 NewBO->setHasNoSignedWrap(Inst.hasNoSignedWrap());
1247 NewBO->setHasNoUnsignedWrap(Inst.hasNoUnsignedWrap());
1248 }
1249 if (isa<PossiblyExactOperator>(NewBO))
1250 NewBO->setIsExact(Inst.isExact());
Serge Pavlov9ef66a82014-05-11 08:46:12 +00001251 }
Serge Pavlove6de9e32014-05-14 09:05:09 +00001252 return BORes;
Serge Pavlov9ef66a82014-05-11 08:46:12 +00001253}
1254
1255/// \brief Makes transformation of binary operation specific for vector types.
1256/// \param Inst Binary operator to transform.
1257/// \return Pointer to node that must replace the original binary operator, or
1258/// null pointer if no transformation was made.
1259Value *InstCombiner::SimplifyVectorOp(BinaryOperator &Inst) {
1260 if (!Inst.getType()->isVectorTy()) return nullptr;
1261
Sanjay Patel58814442014-07-09 16:34:54 +00001262 // It may not be safe to reorder shuffles and things like div, urem, etc.
1263 // because we may trap when executing those ops on unknown vector elements.
1264 // See PR20059.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001265 if (!isSafeToSpeculativelyExecute(&Inst))
1266 return nullptr;
Sanjay Patel58814442014-07-09 16:34:54 +00001267
Serge Pavlov9ef66a82014-05-11 08:46:12 +00001268 unsigned VWidth = cast<VectorType>(Inst.getType())->getNumElements();
1269 Value *LHS = Inst.getOperand(0), *RHS = Inst.getOperand(1);
1270 assert(cast<VectorType>(LHS->getType())->getNumElements() == VWidth);
1271 assert(cast<VectorType>(RHS->getType())->getNumElements() == VWidth);
1272
1273 // If both arguments of binary operation are shuffles, which use the same
1274 // mask and shuffle within a single vector, it is worthwhile to move the
1275 // shuffle after binary operation:
1276 // Op(shuffle(v1, m), shuffle(v2, m)) -> shuffle(Op(v1, v2), m)
1277 if (isa<ShuffleVectorInst>(LHS) && isa<ShuffleVectorInst>(RHS)) {
1278 ShuffleVectorInst *LShuf = cast<ShuffleVectorInst>(LHS);
1279 ShuffleVectorInst *RShuf = cast<ShuffleVectorInst>(RHS);
1280 if (isa<UndefValue>(LShuf->getOperand(1)) &&
1281 isa<UndefValue>(RShuf->getOperand(1)) &&
Serge Pavlov05811092014-05-12 05:44:53 +00001282 LShuf->getOperand(0)->getType() == RShuf->getOperand(0)->getType() &&
Serge Pavlov9ef66a82014-05-11 08:46:12 +00001283 LShuf->getMask() == RShuf->getMask()) {
Serge Pavlove6de9e32014-05-14 09:05:09 +00001284 Value *NewBO = CreateBinOpAsGiven(Inst, LShuf->getOperand(0),
Serge Pavlov9ef66a82014-05-11 08:46:12 +00001285 RShuf->getOperand(0), Builder);
1286 Value *Res = Builder->CreateShuffleVector(NewBO,
Serge Pavlov02ff6202014-05-12 10:11:27 +00001287 UndefValue::get(NewBO->getType()), LShuf->getMask());
Serge Pavlov9ef66a82014-05-11 08:46:12 +00001288 return Res;
1289 }
1290 }
1291
1292 // If one argument is a shuffle within one vector, the other is a constant,
1293 // try moving the shuffle after the binary operation.
1294 ShuffleVectorInst *Shuffle = nullptr;
1295 Constant *C1 = nullptr;
1296 if (isa<ShuffleVectorInst>(LHS)) Shuffle = cast<ShuffleVectorInst>(LHS);
1297 if (isa<ShuffleVectorInst>(RHS)) Shuffle = cast<ShuffleVectorInst>(RHS);
1298 if (isa<Constant>(LHS)) C1 = cast<Constant>(LHS);
1299 if (isa<Constant>(RHS)) C1 = cast<Constant>(RHS);
Benjamin Kramer6de78662014-06-24 10:38:10 +00001300 if (Shuffle && C1 &&
1301 (isa<ConstantVector>(C1) || isa<ConstantDataVector>(C1)) &&
1302 isa<UndefValue>(Shuffle->getOperand(1)) &&
Serge Pavlov9ef66a82014-05-11 08:46:12 +00001303 Shuffle->getType() == Shuffle->getOperand(0)->getType()) {
1304 SmallVector<int, 16> ShMask = Shuffle->getShuffleMask();
1305 // Find constant C2 that has property:
1306 // shuffle(C2, ShMask) = C1
1307 // If such constant does not exist (example: ShMask=<0,0> and C1=<1,2>)
1308 // reorder is not possible.
1309 SmallVector<Constant*, 16> C2M(VWidth,
1310 UndefValue::get(C1->getType()->getScalarType()));
1311 bool MayChange = true;
1312 for (unsigned I = 0; I < VWidth; ++I) {
1313 if (ShMask[I] >= 0) {
1314 assert(ShMask[I] < (int)VWidth);
1315 if (!isa<UndefValue>(C2M[ShMask[I]])) {
1316 MayChange = false;
1317 break;
1318 }
1319 C2M[ShMask[I]] = C1->getAggregateElement(I);
1320 }
1321 }
1322 if (MayChange) {
1323 Constant *C2 = ConstantVector::get(C2M);
1324 Value *NewLHS, *NewRHS;
1325 if (isa<Constant>(LHS)) {
1326 NewLHS = C2;
1327 NewRHS = Shuffle->getOperand(0);
1328 } else {
1329 NewLHS = Shuffle->getOperand(0);
1330 NewRHS = C2;
1331 }
Serge Pavlove6de9e32014-05-14 09:05:09 +00001332 Value *NewBO = CreateBinOpAsGiven(Inst, NewLHS, NewRHS, Builder);
Serge Pavlov9ef66a82014-05-11 08:46:12 +00001333 Value *Res = Builder->CreateShuffleVector(NewBO,
1334 UndefValue::get(Inst.getType()), Shuffle->getMask());
1335 return Res;
1336 }
1337 }
1338
1339 return nullptr;
1340}
1341
Chris Lattner113f4f42002-06-25 16:13:24 +00001342Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
Chris Lattner8574aba2009-11-27 00:29:05 +00001343 SmallVector<Value*, 8> Ops(GEP.op_begin(), GEP.op_end());
1344
Chandler Carruth66b31302015-01-04 12:03:27 +00001345 if (Value *V = SimplifyGEPInst(Ops, DL, TLI, DT, AC))
Chris Lattner8574aba2009-11-27 00:29:05 +00001346 return ReplaceInstUsesWith(GEP, V);
1347
Chris Lattner5f667a62004-05-07 22:09:22 +00001348 Value *PtrOp = GEP.getOperand(0);
Chris Lattner8d0bacb2004-02-22 05:25:17 +00001349
Duncan Sandsc133c542010-11-22 16:32:50 +00001350 // Eliminate unneeded casts for indices, and replace indices which displace
1351 // by multiples of a zero size type with zero.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001352 bool MadeChange = false;
1353 Type *IntPtrTy = DL.getIntPtrType(GEP.getPointerOperandType());
Duncan Sandsc133c542010-11-22 16:32:50 +00001354
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001355 gep_type_iterator GTI = gep_type_begin(GEP);
1356 for (User::op_iterator I = GEP.op_begin() + 1, E = GEP.op_end(); I != E;
1357 ++I, ++GTI) {
1358 // Skip indices into struct types.
1359 SequentialType *SeqTy = dyn_cast<SequentialType>(*GTI);
1360 if (!SeqTy)
1361 continue;
Duncan Sandsc133c542010-11-22 16:32:50 +00001362
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001363 // If the element type has zero size then any index over it is equivalent
1364 // to an index of zero, so replace it with zero if it is not zero already.
1365 if (SeqTy->getElementType()->isSized() &&
1366 DL.getTypeAllocSize(SeqTy->getElementType()) == 0)
1367 if (!isa<Constant>(*I) || !cast<Constant>(*I)->isNullValue()) {
1368 *I = Constant::getNullValue(IntPtrTy);
Duncan Sandsc133c542010-11-22 16:32:50 +00001369 MadeChange = true;
1370 }
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001371
1372 Type *IndexTy = (*I)->getType();
1373 if (IndexTy != IntPtrTy) {
1374 // If we are using a wider index than needed for this platform, shrink
1375 // it to what we need. If narrower, sign-extend it to what we need.
1376 // This explicit cast can make subsequent optimizations more obvious.
1377 *I = Builder->CreateIntCast(*I, IntPtrTy, true);
1378 MadeChange = true;
Chris Lattner69193f92004-04-05 01:30:19 +00001379 }
Chris Lattner9bf53ff2007-03-25 20:43:09 +00001380 }
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001381 if (MadeChange)
1382 return &GEP;
Chris Lattner69193f92004-04-05 01:30:19 +00001383
Louis Gerbargc6b506a2014-05-29 20:29:47 +00001384 // Check to see if the inputs to the PHI node are getelementptr instructions.
1385 if (PHINode *PN = dyn_cast<PHINode>(PtrOp)) {
1386 GetElementPtrInst *Op1 = dyn_cast<GetElementPtrInst>(PN->getOperand(0));
1387 if (!Op1)
1388 return nullptr;
1389
Daniel Jasper5add63f2015-03-19 11:05:08 +00001390 // Don't fold a GEP into itself through a PHI node. This can only happen
1391 // through the back-edge of a loop. Folding a GEP into itself means that
1392 // the value of the previous iteration needs to be stored in the meantime,
1393 // thus requiring an additional register variable to be live, but not
1394 // actually achieving anything (the GEP still needs to be executed once per
1395 // loop iteration).
1396 if (Op1 == &GEP)
1397 return nullptr;
1398
Louis Gerbargc6b506a2014-05-29 20:29:47 +00001399 signed DI = -1;
1400
1401 for (auto I = PN->op_begin()+1, E = PN->op_end(); I !=E; ++I) {
1402 GetElementPtrInst *Op2 = dyn_cast<GetElementPtrInst>(*I);
1403 if (!Op2 || Op1->getNumOperands() != Op2->getNumOperands())
1404 return nullptr;
1405
Daniel Jasper5add63f2015-03-19 11:05:08 +00001406 // As for Op1 above, don't try to fold a GEP into itself.
1407 if (Op2 == &GEP)
1408 return nullptr;
1409
Chandler Carruth3012a1b2014-05-29 23:05:52 +00001410 // Keep track of the type as we walk the GEP.
1411 Type *CurTy = Op1->getOperand(0)->getType()->getScalarType();
1412
Louis Gerbargc6b506a2014-05-29 20:29:47 +00001413 for (unsigned J = 0, F = Op1->getNumOperands(); J != F; ++J) {
1414 if (Op1->getOperand(J)->getType() != Op2->getOperand(J)->getType())
1415 return nullptr;
1416
1417 if (Op1->getOperand(J) != Op2->getOperand(J)) {
1418 if (DI == -1) {
1419 // We have not seen any differences yet in the GEPs feeding the
1420 // PHI yet, so we record this one if it is allowed to be a
1421 // variable.
1422
1423 // The first two arguments can vary for any GEP, the rest have to be
1424 // static for struct slots
Chandler Carruth3012a1b2014-05-29 23:05:52 +00001425 if (J > 1 && CurTy->isStructTy())
1426 return nullptr;
Louis Gerbargc6b506a2014-05-29 20:29:47 +00001427
1428 DI = J;
1429 } else {
1430 // The GEP is different by more than one input. While this could be
1431 // extended to support GEPs that vary by more than one variable it
1432 // doesn't make sense since it greatly increases the complexity and
1433 // would result in an R+R+R addressing mode which no backend
1434 // directly supports and would need to be broken into several
1435 // simpler instructions anyway.
1436 return nullptr;
1437 }
1438 }
Chandler Carruthfdc0e0b2014-05-29 23:21:12 +00001439
1440 // Sink down a layer of the type for the next iteration.
1441 if (J > 0) {
1442 if (CompositeType *CT = dyn_cast<CompositeType>(CurTy)) {
1443 CurTy = CT->getTypeAtIndex(Op1->getOperand(J));
1444 } else {
1445 CurTy = nullptr;
1446 }
1447 }
Louis Gerbargc6b506a2014-05-29 20:29:47 +00001448 }
1449 }
1450
1451 GetElementPtrInst *NewGEP = cast<GetElementPtrInst>(Op1->clone());
1452
1453 if (DI == -1) {
1454 // All the GEPs feeding the PHI are identical. Clone one down into our
1455 // BB so that it can be merged with the current GEP.
Akira Hatanaka1defd5a2015-02-18 03:30:11 +00001456 GEP.getParent()->getInstList().insert(
1457 GEP.getParent()->getFirstInsertionPt(), NewGEP);
Louis Gerbargc6b506a2014-05-29 20:29:47 +00001458 } else {
1459 // All the GEPs feeding the PHI differ at a single offset. Clone a GEP
1460 // into the current block so it can be merged, and create a new PHI to
1461 // set that index.
1462 Instruction *InsertPt = Builder->GetInsertPoint();
1463 Builder->SetInsertPoint(PN);
1464 PHINode *NewPN = Builder->CreatePHI(Op1->getOperand(DI)->getType(),
1465 PN->getNumOperands());
1466 Builder->SetInsertPoint(InsertPt);
1467
1468 for (auto &I : PN->operands())
1469 NewPN->addIncoming(cast<GEPOperator>(I)->getOperand(DI),
1470 PN->getIncomingBlock(I));
1471
1472 NewGEP->setOperand(DI, NewPN);
Akira Hatanaka1defd5a2015-02-18 03:30:11 +00001473 GEP.getParent()->getInstList().insert(
1474 GEP.getParent()->getFirstInsertionPt(), NewGEP);
Louis Gerbargc6b506a2014-05-29 20:29:47 +00001475 NewGEP->setOperand(DI, NewPN);
1476 }
1477
1478 GEP.setOperand(0, NewGEP);
1479 PtrOp = NewGEP;
1480 }
1481
Chris Lattnerae7a0d32002-08-02 19:29:35 +00001482 // Combine Indices - If the source pointer to this getelementptr instruction
1483 // is a getelementptr instruction, combine the indices of the two
1484 // getelementptr instructions into a single instruction.
1485 //
Dan Gohman31a9b982009-07-28 01:40:03 +00001486 if (GEPOperator *Src = dyn_cast<GEPOperator>(PtrOp)) {
Rafael Espindolaa3a44f3f2011-07-31 04:43:41 +00001487 if (!shouldMergeGEPs(*cast<GEPOperator>(&GEP), *Src))
Craig Topperf40110f2014-04-25 05:29:35 +00001488 return nullptr;
Rafael Espindola40325672011-07-11 03:43:47 +00001489
Duncan Sands533c8ae2012-10-23 08:28:26 +00001490 // Note that if our source is a gep chain itself then we wait for that
Chris Lattner5f667a62004-05-07 22:09:22 +00001491 // chain to be resolved before we perform this transformation. This
1492 // avoids us creating a TON of code in some cases.
Rafael Espindolaa3a44f3f2011-07-31 04:43:41 +00001493 if (GEPOperator *SrcGEP =
1494 dyn_cast<GEPOperator>(Src->getOperand(0)))
1495 if (SrcGEP->getNumOperands() == 2 && shouldMergeGEPs(*Src, *SrcGEP))
Craig Topperf40110f2014-04-25 05:29:35 +00001496 return nullptr; // Wait until our source is folded to completion.
Chris Lattner5f667a62004-05-07 22:09:22 +00001497
Chris Lattneraf6094f2007-02-15 22:48:32 +00001498 SmallVector<Value*, 8> Indices;
Chris Lattner5f667a62004-05-07 22:09:22 +00001499
1500 // Find out whether the last index in the source GEP is a sequential idx.
1501 bool EndsWithSequential = false;
Chris Lattnerb2995e12009-08-30 05:30:55 +00001502 for (gep_type_iterator I = gep_type_begin(*Src), E = gep_type_end(*Src);
1503 I != E; ++I)
Duncan Sands19d0b472010-02-16 11:11:14 +00001504 EndsWithSequential = !(*I)->isStructTy();
Misha Brukmanb1c93172005-04-21 23:48:37 +00001505
Chris Lattnerae7a0d32002-08-02 19:29:35 +00001506 // Can we combine the two pointer arithmetics offsets?
Chris Lattner5f667a62004-05-07 22:09:22 +00001507 if (EndsWithSequential) {
Chris Lattner235af562003-03-05 22:33:14 +00001508 // Replace: gep (gep %P, long B), long A, ...
1509 // With: T = long A+B; gep %P, T, ...
1510 //
Chris Lattner06c687b2009-08-30 05:08:50 +00001511 Value *Sum;
1512 Value *SO1 = Src->getOperand(Src->getNumOperands()-1);
1513 Value *GO1 = GEP.getOperand(1);
Owen Anderson5a1acd92009-07-31 20:28:14 +00001514 if (SO1 == Constant::getNullValue(SO1->getType())) {
Chris Lattner69193f92004-04-05 01:30:19 +00001515 Sum = GO1;
Owen Anderson5a1acd92009-07-31 20:28:14 +00001516 } else if (GO1 == Constant::getNullValue(GO1->getType())) {
Chris Lattner69193f92004-04-05 01:30:19 +00001517 Sum = SO1;
1518 } else {
Chris Lattnerb2995e12009-08-30 05:30:55 +00001519 // If they aren't the same type, then the input hasn't been processed
1520 // by the loop above yet (which canonicalizes sequential index types to
1521 // intptr_t). Just avoid transforming this until the input has been
1522 // normalized.
1523 if (SO1->getType() != GO1->getType())
Craig Topperf40110f2014-04-25 05:29:35 +00001524 return nullptr;
Wei Mia0adf9f2015-04-21 23:02:15 +00001525 // Only do the combine when GO1 and SO1 are both constants. Only in
1526 // this case, we are sure the cost after the merge is never more than
1527 // that before the merge.
1528 if (!isa<Constant>(GO1) || !isa<Constant>(SO1))
1529 return nullptr;
Chris Lattner59663412009-08-30 18:50:58 +00001530 Sum = Builder->CreateAdd(SO1, GO1, PtrOp->getName()+".sum");
Chris Lattner69193f92004-04-05 01:30:19 +00001531 }
Chris Lattner5f667a62004-05-07 22:09:22 +00001532
Chris Lattnerb2995e12009-08-30 05:30:55 +00001533 // Update the GEP in place if possible.
Chris Lattner06c687b2009-08-30 05:08:50 +00001534 if (Src->getNumOperands() == 2) {
1535 GEP.setOperand(0, Src->getOperand(0));
Chris Lattner5f667a62004-05-07 22:09:22 +00001536 GEP.setOperand(1, Sum);
1537 return &GEP;
Chris Lattner5f667a62004-05-07 22:09:22 +00001538 }
Chris Lattnerb2995e12009-08-30 05:30:55 +00001539 Indices.append(Src->op_begin()+1, Src->op_end()-1);
Chris Lattnerd7b6e912009-08-30 04:49:01 +00001540 Indices.push_back(Sum);
Chris Lattnerb2995e12009-08-30 05:30:55 +00001541 Indices.append(GEP.op_begin()+2, GEP.op_end());
Misha Brukmanb1c93172005-04-21 23:48:37 +00001542 } else if (isa<Constant>(*GEP.idx_begin()) &&
Chris Lattner69193f92004-04-05 01:30:19 +00001543 cast<Constant>(*GEP.idx_begin())->isNullValue() &&
Chris Lattner06c687b2009-08-30 05:08:50 +00001544 Src->getNumOperands() != 1) {
Chris Lattnerae7a0d32002-08-02 19:29:35 +00001545 // Otherwise we can do the fold if the first index of the GEP is a zero
Chris Lattnerb2995e12009-08-30 05:30:55 +00001546 Indices.append(Src->op_begin()+1, Src->op_end());
1547 Indices.append(GEP.idx_begin()+1, GEP.idx_end());
Chris Lattnerae7a0d32002-08-02 19:29:35 +00001548 }
1549
Dan Gohman1b849082009-09-07 23:54:19 +00001550 if (!Indices.empty())
David Blaikie096b1da2015-03-14 19:53:33 +00001551 return GEP.isInBounds() && Src->isInBounds()
1552 ? GetElementPtrInst::CreateInBounds(
1553 Src->getSourceElementType(), Src->getOperand(0), Indices,
1554 GEP.getName())
1555 : GetElementPtrInst::Create(Src->getSourceElementType(),
1556 Src->getOperand(0), Indices,
1557 GEP.getName());
Chris Lattnere26bf172009-08-30 05:00:50 +00001558 }
Nadav Rotema069c6c2011-04-05 14:29:52 +00001559
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001560 if (GEP.getNumIndices() == 1) {
Matt Arsenaultbfa37e52013-10-03 18:15:57 +00001561 unsigned AS = GEP.getPointerAddressSpace();
David Majnemerd2df5012014-09-01 21:10:02 +00001562 if (GEP.getOperand(1)->getType()->getScalarSizeInBits() ==
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001563 DL.getPointerSizeInBits(AS)) {
David Majnemerd2df5012014-09-01 21:10:02 +00001564 Type *PtrTy = GEP.getPointerOperandType();
1565 Type *Ty = PtrTy->getPointerElementType();
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001566 uint64_t TyAllocSize = DL.getTypeAllocSize(Ty);
David Majnemerd2df5012014-09-01 21:10:02 +00001567
1568 bool Matched = false;
1569 uint64_t C;
1570 Value *V = nullptr;
1571 if (TyAllocSize == 1) {
1572 V = GEP.getOperand(1);
1573 Matched = true;
1574 } else if (match(GEP.getOperand(1),
1575 m_AShr(m_Value(V), m_ConstantInt(C)))) {
1576 if (TyAllocSize == 1ULL << C)
1577 Matched = true;
1578 } else if (match(GEP.getOperand(1),
1579 m_SDiv(m_Value(V), m_ConstantInt(C)))) {
1580 if (TyAllocSize == C)
1581 Matched = true;
1582 }
1583
1584 if (Matched) {
1585 // Canonicalize (gep i8* X, -(ptrtoint Y))
1586 // to (inttoptr (sub (ptrtoint X), (ptrtoint Y)))
1587 // The GEP pattern is emitted by the SCEV expander for certain kinds of
1588 // pointer arithmetic.
1589 if (match(V, m_Neg(m_PtrToInt(m_Value())))) {
1590 Operator *Index = cast<Operator>(V);
1591 Value *PtrToInt = Builder->CreatePtrToInt(PtrOp, Index->getType());
1592 Value *NewSub = Builder->CreateSub(PtrToInt, Index->getOperand(1));
1593 return CastInst::Create(Instruction::IntToPtr, NewSub, GEP.getType());
1594 }
1595 // Canonicalize (gep i8* X, (ptrtoint Y)-(ptrtoint X))
1596 // to (bitcast Y)
1597 Value *Y;
1598 if (match(V, m_Sub(m_PtrToInt(m_Value(Y)),
1599 m_PtrToInt(m_Specific(GEP.getOperand(0)))))) {
1600 return CastInst::CreatePointerBitCastOrAddrSpaceCast(Y,
1601 GEP.getType());
1602 }
1603 }
Matt Arsenaultbfa37e52013-10-03 18:15:57 +00001604 }
Benjamin Kramere6461e32013-09-20 14:38:44 +00001605 }
1606
Chris Lattner06c687b2009-08-30 05:08:50 +00001607 // Handle gep(bitcast x) and gep(gep x, 0, 0, 0).
Chris Lattnere903f382010-01-05 07:42:10 +00001608 Value *StrippedPtr = PtrOp->stripPointerCasts();
Nadav Roteme63e59c2012-03-26 20:39:18 +00001609 PointerType *StrippedPtrTy = dyn_cast<PointerType>(StrippedPtr->getType());
1610
Nadav Rotema8f35622012-03-26 21:00:53 +00001611 // We do not handle pointer-vector geps here.
1612 if (!StrippedPtrTy)
Craig Topperf40110f2014-04-25 05:29:35 +00001613 return nullptr;
Nadav Rotema8f35622012-03-26 21:00:53 +00001614
Matt Arsenaultaa689f52014-02-14 00:49:12 +00001615 if (StrippedPtr != PtrOp) {
Chris Lattner8574aba2009-11-27 00:29:05 +00001616 bool HasZeroPointerIndex = false;
1617 if (ConstantInt *C = dyn_cast<ConstantInt>(GEP.getOperand(1)))
1618 HasZeroPointerIndex = C->isZero();
Nadav Rotema069c6c2011-04-05 14:29:52 +00001619
Chris Lattnerc2f2cf82009-08-30 20:36:46 +00001620 // Transform: GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ...
1621 // into : GEP [10 x i8]* X, i32 0, ...
1622 //
1623 // Likewise, transform: GEP (bitcast i8* X to [0 x i8]*), i32 0, ...
1624 // into : GEP i8* X, ...
Nadav Rotema069c6c2011-04-05 14:29:52 +00001625 //
Chris Lattnerc2f2cf82009-08-30 20:36:46 +00001626 // This occurs when the program declares an array extern like "int X[];"
Chris Lattnere26bf172009-08-30 05:00:50 +00001627 if (HasZeroPointerIndex) {
Chris Lattner229907c2011-07-18 04:54:35 +00001628 PointerType *CPTy = cast<PointerType>(PtrOp->getType());
1629 if (ArrayType *CATy =
Duncan Sands5795a602009-03-02 09:18:21 +00001630 dyn_cast<ArrayType>(CPTy->getElementType())) {
1631 // GEP (bitcast i8* X to [0 x i8]*), i32 0, ... ?
Chris Lattnere903f382010-01-05 07:42:10 +00001632 if (CATy->getElementType() == StrippedPtrTy->getElementType()) {
Duncan Sands5795a602009-03-02 09:18:21 +00001633 // -> GEP i8* X, ...
Chris Lattnere903f382010-01-05 07:42:10 +00001634 SmallVector<Value*, 8> Idx(GEP.idx_begin()+1, GEP.idx_end());
David Blaikie096b1da2015-03-14 19:53:33 +00001635 GetElementPtrInst *Res = GetElementPtrInst::Create(
1636 StrippedPtrTy->getElementType(), StrippedPtr, Idx, GEP.getName());
Chris Lattnere903f382010-01-05 07:42:10 +00001637 Res->setIsInBounds(GEP.isInBounds());
Eli Bendersky9966b262014-04-03 17:51:58 +00001638 if (StrippedPtrTy->getAddressSpace() == GEP.getAddressSpace())
1639 return Res;
1640 // Insert Res, and create an addrspacecast.
1641 // e.g.,
1642 // GEP (addrspacecast i8 addrspace(1)* X to [0 x i8]*), i32 0, ...
1643 // ->
1644 // %0 = GEP i8 addrspace(1)* X, ...
1645 // addrspacecast i8 addrspace(1)* %0 to i8*
1646 return new AddrSpaceCastInst(Builder->Insert(Res), GEP.getType());
Chris Lattnerc2f2cf82009-08-30 20:36:46 +00001647 }
Jakub Staszakcfc46f82012-05-06 13:52:31 +00001648
Chris Lattner229907c2011-07-18 04:54:35 +00001649 if (ArrayType *XATy =
Chris Lattnere903f382010-01-05 07:42:10 +00001650 dyn_cast<ArrayType>(StrippedPtrTy->getElementType())){
Duncan Sands5795a602009-03-02 09:18:21 +00001651 // GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ... ?
Chris Lattner567b81f2005-09-13 00:40:14 +00001652 if (CATy->getElementType() == XATy->getElementType()) {
Duncan Sands5795a602009-03-02 09:18:21 +00001653 // -> GEP [10 x i8]* X, i32 0, ...
Chris Lattner567b81f2005-09-13 00:40:14 +00001654 // At this point, we know that the cast source type is a pointer
1655 // to an array of the same type as the destination pointer
1656 // array. Because the array type is never stepped over (there
1657 // is a leading zero) we can fold the cast into this GEP.
Eli Bendersky9966b262014-04-03 17:51:58 +00001658 if (StrippedPtrTy->getAddressSpace() == GEP.getAddressSpace()) {
1659 GEP.setOperand(0, StrippedPtr);
David Blaikie73cf8722015-05-05 18:03:48 +00001660 GEP.setSourceElementType(XATy);
Eli Bendersky9966b262014-04-03 17:51:58 +00001661 return &GEP;
1662 }
1663 // Cannot replace the base pointer directly because StrippedPtr's
1664 // address space is different. Instead, create a new GEP followed by
1665 // an addrspacecast.
1666 // e.g.,
1667 // GEP (addrspacecast [10 x i8] addrspace(1)* X to [0 x i8]*),
1668 // i32 0, ...
1669 // ->
1670 // %0 = GEP [10 x i8] addrspace(1)* X, ...
1671 // addrspacecast i8 addrspace(1)* %0 to i8*
1672 SmallVector<Value*, 8> Idx(GEP.idx_begin(), GEP.idx_end());
David Blaikieaa41cd52015-04-03 21:33:42 +00001673 Value *NewGEP = GEP.isInBounds()
1674 ? Builder->CreateInBoundsGEP(
1675 nullptr, StrippedPtr, Idx, GEP.getName())
1676 : Builder->CreateGEP(nullptr, StrippedPtr, Idx,
1677 GEP.getName());
Eli Bendersky9966b262014-04-03 17:51:58 +00001678 return new AddrSpaceCastInst(NewGEP, GEP.getType());
Chris Lattner567b81f2005-09-13 00:40:14 +00001679 }
Duncan Sands5795a602009-03-02 09:18:21 +00001680 }
1681 }
Chris Lattner567b81f2005-09-13 00:40:14 +00001682 } else if (GEP.getNumOperands() == 2) {
1683 // Transform things like:
Wojciech Matyjewicz309e5a72007-12-12 15:21:32 +00001684 // %t = getelementptr i32* bitcast ([2 x i32]* %str to i32*), i32 %V
1685 // into: %t1 = getelementptr [2 x i32]* %str, i32 0, i32 %V; bitcast
Chris Lattner229907c2011-07-18 04:54:35 +00001686 Type *SrcElTy = StrippedPtrTy->getElementType();
Matt Arsenaultfc00f7e2013-08-14 00:24:34 +00001687 Type *ResElTy = PtrOp->getType()->getPointerElementType();
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001688 if (SrcElTy->isArrayTy() &&
1689 DL.getTypeAllocSize(SrcElTy->getArrayElementType()) ==
1690 DL.getTypeAllocSize(ResElTy)) {
1691 Type *IdxType = DL.getIntPtrType(GEP.getType());
Matt Arsenault9e3a6ca2013-08-14 00:24:38 +00001692 Value *Idx[2] = { Constant::getNullValue(IdxType), GEP.getOperand(1) };
David Blaikie68d535c2015-03-24 22:38:16 +00001693 Value *NewGEP =
1694 GEP.isInBounds()
David Blaikieaa41cd52015-04-03 21:33:42 +00001695 ? Builder->CreateInBoundsGEP(nullptr, StrippedPtr, Idx,
1696 GEP.getName())
1697 : Builder->CreateGEP(nullptr, StrippedPtr, Idx, GEP.getName());
Matt Arsenaultaa689f52014-02-14 00:49:12 +00001698
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001699 // V and GEP are both pointer types --> BitCast
Manuel Jacob405fb182014-07-16 20:13:45 +00001700 return CastInst::CreatePointerBitCastOrAddrSpaceCast(NewGEP,
1701 GEP.getType());
Chris Lattner8d0bacb2004-02-22 05:25:17 +00001702 }
Jakub Staszakcfc46f82012-05-06 13:52:31 +00001703
Chris Lattner2a893292005-09-13 18:36:04 +00001704 // Transform things like:
Duncan Sands533c8ae2012-10-23 08:28:26 +00001705 // %V = mul i64 %N, 4
1706 // %t = getelementptr i8* bitcast (i32* %arr to i8*), i32 %V
1707 // into: %t1 = getelementptr i32* %arr, i32 %N; bitcast
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001708 if (ResElTy->isSized() && SrcElTy->isSized()) {
Duncan Sands533c8ae2012-10-23 08:28:26 +00001709 // Check that changing the type amounts to dividing the index by a scale
1710 // factor.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001711 uint64_t ResSize = DL.getTypeAllocSize(ResElTy);
1712 uint64_t SrcSize = DL.getTypeAllocSize(SrcElTy);
Duncan Sands533c8ae2012-10-23 08:28:26 +00001713 if (ResSize && SrcSize % ResSize == 0) {
1714 Value *Idx = GEP.getOperand(1);
1715 unsigned BitWidth = Idx->getType()->getPrimitiveSizeInBits();
1716 uint64_t Scale = SrcSize / ResSize;
1717
1718 // Earlier transforms ensure that the index has type IntPtrType, which
1719 // considerably simplifies the logic by eliminating implicit casts.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001720 assert(Idx->getType() == DL.getIntPtrType(GEP.getType()) &&
Duncan Sands533c8ae2012-10-23 08:28:26 +00001721 "Index not cast to pointer width?");
1722
1723 bool NSW;
1724 if (Value *NewIdx = Descale(Idx, APInt(BitWidth, Scale), NSW)) {
1725 // Successfully decomposed Idx as NewIdx * Scale, form a new GEP.
1726 // If the multiplication NewIdx * Scale may overflow then the new
1727 // GEP may not be "inbounds".
David Blaikie68d535c2015-03-24 22:38:16 +00001728 Value *NewGEP =
1729 GEP.isInBounds() && NSW
David Blaikieaa41cd52015-04-03 21:33:42 +00001730 ? Builder->CreateInBoundsGEP(nullptr, StrippedPtr, NewIdx,
David Blaikie68d535c2015-03-24 22:38:16 +00001731 GEP.getName())
David Blaikieaa41cd52015-04-03 21:33:42 +00001732 : Builder->CreateGEP(nullptr, StrippedPtr, NewIdx,
1733 GEP.getName());
Matt Arsenaultaa689f52014-02-14 00:49:12 +00001734
Duncan Sands533c8ae2012-10-23 08:28:26 +00001735 // The NewGEP must be pointer typed, so must the old one -> BitCast
Manuel Jacob405fb182014-07-16 20:13:45 +00001736 return CastInst::CreatePointerBitCastOrAddrSpaceCast(NewGEP,
1737 GEP.getType());
Duncan Sands533c8ae2012-10-23 08:28:26 +00001738 }
1739 }
1740 }
1741
1742 // Similarly, transform things like:
Wojciech Matyjewicz309e5a72007-12-12 15:21:32 +00001743 // getelementptr i8* bitcast ([100 x double]* X to i8*), i32 %tmp
Chris Lattner2a893292005-09-13 18:36:04 +00001744 // (where tmp = 8*tmp2) into:
Wojciech Matyjewicz309e5a72007-12-12 15:21:32 +00001745 // getelementptr [100 x double]* %arr, i32 0, i32 %tmp2; bitcast
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001746 if (ResElTy->isSized() && SrcElTy->isSized() && SrcElTy->isArrayTy()) {
Duncan Sands533c8ae2012-10-23 08:28:26 +00001747 // Check that changing to the array element type amounts to dividing the
1748 // index by a scale factor.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001749 uint64_t ResSize = DL.getTypeAllocSize(ResElTy);
1750 uint64_t ArrayEltSize =
1751 DL.getTypeAllocSize(SrcElTy->getArrayElementType());
Duncan Sands533c8ae2012-10-23 08:28:26 +00001752 if (ResSize && ArrayEltSize % ResSize == 0) {
1753 Value *Idx = GEP.getOperand(1);
1754 unsigned BitWidth = Idx->getType()->getPrimitiveSizeInBits();
1755 uint64_t Scale = ArrayEltSize / ResSize;
Jakub Staszakcfc46f82012-05-06 13:52:31 +00001756
Duncan Sands533c8ae2012-10-23 08:28:26 +00001757 // Earlier transforms ensure that the index has type IntPtrType, which
1758 // considerably simplifies the logic by eliminating implicit casts.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001759 assert(Idx->getType() == DL.getIntPtrType(GEP.getType()) &&
Duncan Sands533c8ae2012-10-23 08:28:26 +00001760 "Index not cast to pointer width?");
1761
1762 bool NSW;
1763 if (Value *NewIdx = Descale(Idx, APInt(BitWidth, Scale), NSW)) {
1764 // Successfully decomposed Idx as NewIdx * Scale, form a new GEP.
1765 // If the multiplication NewIdx * Scale may overflow then the new
1766 // GEP may not be "inbounds".
Matt Arsenault9e3a6ca2013-08-14 00:24:38 +00001767 Value *Off[2] = {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001768 Constant::getNullValue(DL.getIntPtrType(GEP.getType())),
1769 NewIdx};
Matt Arsenault9e3a6ca2013-08-14 00:24:38 +00001770
David Blaikieaa41cd52015-04-03 21:33:42 +00001771 Value *NewGEP = GEP.isInBounds() && NSW
1772 ? Builder->CreateInBoundsGEP(
1773 SrcElTy, StrippedPtr, Off, GEP.getName())
1774 : Builder->CreateGEP(SrcElTy, StrippedPtr, Off,
1775 GEP.getName());
Duncan Sands533c8ae2012-10-23 08:28:26 +00001776 // The NewGEP must be pointer typed, so must the old one -> BitCast
Manuel Jacob405fb182014-07-16 20:13:45 +00001777 return CastInst::CreatePointerBitCastOrAddrSpaceCast(NewGEP,
1778 GEP.getType());
Chris Lattner2a893292005-09-13 18:36:04 +00001779 }
1780 }
Chris Lattner2a893292005-09-13 18:36:04 +00001781 }
Chris Lattner8d0bacb2004-02-22 05:25:17 +00001782 }
Chris Lattnerca081252001-12-14 16:52:21 +00001783 }
Nadav Rotema069c6c2011-04-05 14:29:52 +00001784
Matt Arsenault4815f092014-08-12 19:46:13 +00001785 // addrspacecast between types is canonicalized as a bitcast, then an
1786 // addrspacecast. To take advantage of the below bitcast + struct GEP, look
1787 // through the addrspacecast.
1788 if (AddrSpaceCastInst *ASC = dyn_cast<AddrSpaceCastInst>(PtrOp)) {
1789 // X = bitcast A addrspace(1)* to B addrspace(1)*
1790 // Y = addrspacecast A addrspace(1)* to B addrspace(2)*
1791 // Z = gep Y, <...constant indices...>
1792 // Into an addrspacecasted GEP of the struct.
1793 if (BitCastInst *BC = dyn_cast<BitCastInst>(ASC->getOperand(0)))
1794 PtrOp = BC;
1795 }
1796
Chris Lattnerfef138b2009-01-09 05:44:56 +00001797 /// See if we can simplify:
Chris Lattner97fd3592009-08-30 05:55:36 +00001798 /// X = bitcast A* to B*
Chris Lattnerfef138b2009-01-09 05:44:56 +00001799 /// Y = gep X, <...constant indices...>
1800 /// into a gep of the original struct. This is important for SROA and alias
1801 /// analysis of unions. If "A" is also a bitcast, wait for A/X to be merged.
Chris Lattnera784a2c2009-01-09 04:53:57 +00001802 if (BitCastInst *BCI = dyn_cast<BitCastInst>(PtrOp)) {
Matt Arsenault98f34e32013-08-19 22:17:34 +00001803 Value *Operand = BCI->getOperand(0);
1804 PointerType *OpType = cast<PointerType>(Operand->getType());
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001805 unsigned OffsetBits = DL.getPointerTypeSizeInBits(GEP.getType());
Matt Arsenault98f34e32013-08-19 22:17:34 +00001806 APInt Offset(OffsetBits, 0);
1807 if (!isa<BitCastInst>(Operand) &&
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001808 GEP.accumulateConstantOffset(DL, Offset)) {
Nadav Rotema069c6c2011-04-05 14:29:52 +00001809
Chris Lattnerfef138b2009-01-09 05:44:56 +00001810 // If this GEP instruction doesn't move the pointer, just replace the GEP
1811 // with a bitcast of the real input to the dest type.
Nuno Lopesb6ad9822012-12-30 16:25:48 +00001812 if (!Offset) {
Chris Lattnerfef138b2009-01-09 05:44:56 +00001813 // If the bitcast is of an allocation, and the allocation will be
1814 // converted to match the type of the cast, don't touch this.
Matt Arsenault98f34e32013-08-19 22:17:34 +00001815 if (isa<AllocaInst>(Operand) || isAllocationFn(Operand, TLI)) {
Chris Lattnerfef138b2009-01-09 05:44:56 +00001816 // See if the bitcast simplifies, if so, don't nuke this GEP yet.
1817 if (Instruction *I = visitBitCast(*BCI)) {
1818 if (I != BCI) {
1819 I->takeName(BCI);
1820 BCI->getParent()->getInstList().insert(BCI, I);
1821 ReplaceInstUsesWith(*BCI, I);
1822 }
1823 return &GEP;
Chris Lattnera784a2c2009-01-09 04:53:57 +00001824 }
Chris Lattnera784a2c2009-01-09 04:53:57 +00001825 }
Matt Arsenault4815f092014-08-12 19:46:13 +00001826
1827 if (Operand->getType()->getPointerAddressSpace() != GEP.getAddressSpace())
1828 return new AddrSpaceCastInst(Operand, GEP.getType());
Matt Arsenault98f34e32013-08-19 22:17:34 +00001829 return new BitCastInst(Operand, GEP.getType());
Chris Lattnera784a2c2009-01-09 04:53:57 +00001830 }
Jakub Staszakcfc46f82012-05-06 13:52:31 +00001831
Chris Lattnerfef138b2009-01-09 05:44:56 +00001832 // Otherwise, if the offset is non-zero, we need to find out if there is a
1833 // field at Offset in 'A's type. If so, we can pull the cast through the
1834 // GEP.
1835 SmallVector<Value*, 8> NewIndices;
Matt Arsenaultd79f7d92013-08-19 22:17:40 +00001836 if (FindElementAtOffset(OpType, Offset.getSExtValue(), NewIndices)) {
David Blaikieaa41cd52015-04-03 21:33:42 +00001837 Value *NGEP =
1838 GEP.isInBounds()
1839 ? Builder->CreateInBoundsGEP(nullptr, Operand, NewIndices)
1840 : Builder->CreateGEP(nullptr, Operand, NewIndices);
Jakub Staszakcfc46f82012-05-06 13:52:31 +00001841
Chris Lattner59663412009-08-30 18:50:58 +00001842 if (NGEP->getType() == GEP.getType())
1843 return ReplaceInstUsesWith(GEP, NGEP);
Chris Lattnerfef138b2009-01-09 05:44:56 +00001844 NGEP->takeName(&GEP);
Matt Arsenault4815f092014-08-12 19:46:13 +00001845
1846 if (NGEP->getType()->getPointerAddressSpace() != GEP.getAddressSpace())
1847 return new AddrSpaceCastInst(NGEP, GEP.getType());
Chris Lattnerfef138b2009-01-09 05:44:56 +00001848 return new BitCastInst(NGEP, GEP.getType());
1849 }
Chris Lattnera784a2c2009-01-09 04:53:57 +00001850 }
Jakub Staszakcfc46f82012-05-06 13:52:31 +00001851 }
1852
Craig Topperf40110f2014-04-25 05:29:35 +00001853 return nullptr;
Chris Lattnerca081252001-12-14 16:52:21 +00001854}
1855
Nuno Lopes95cc4f32012-07-09 18:38:20 +00001856static bool
Benjamin Kramer8bcc9712012-08-29 15:32:21 +00001857isAllocSiteRemovable(Instruction *AI, SmallVectorImpl<WeakVH> &Users,
1858 const TargetLibraryInfo *TLI) {
Nuno Lopes95cc4f32012-07-09 18:38:20 +00001859 SmallVector<Instruction*, 4> Worklist;
1860 Worklist.push_back(AI);
Nick Lewyckye8ae02d2011-08-02 22:08:01 +00001861
Nuno Lopes95cc4f32012-07-09 18:38:20 +00001862 do {
1863 Instruction *PI = Worklist.pop_back_val();
Chandler Carruthcdf47882014-03-09 03:16:01 +00001864 for (User *U : PI->users()) {
1865 Instruction *I = cast<Instruction>(U);
Nuno Lopes95cc4f32012-07-09 18:38:20 +00001866 switch (I->getOpcode()) {
1867 default:
1868 // Give up the moment we see something we can't handle.
Nuno Lopesfa0dffc2012-07-06 23:09:25 +00001869 return false;
Nuno Lopes95cc4f32012-07-09 18:38:20 +00001870
1871 case Instruction::BitCast:
1872 case Instruction::GetElementPtr:
Benjamin Kramerf5e2fc42015-05-29 19:43:39 +00001873 Users.emplace_back(I);
Nuno Lopes95cc4f32012-07-09 18:38:20 +00001874 Worklist.push_back(I);
1875 continue;
1876
1877 case Instruction::ICmp: {
1878 ICmpInst *ICI = cast<ICmpInst>(I);
1879 // We can fold eq/ne comparisons with null to false/true, respectively.
1880 if (!ICI->isEquality() || !isa<ConstantPointerNull>(ICI->getOperand(1)))
1881 return false;
Benjamin Kramerf5e2fc42015-05-29 19:43:39 +00001882 Users.emplace_back(I);
Nuno Lopes95cc4f32012-07-09 18:38:20 +00001883 continue;
1884 }
1885
1886 case Instruction::Call:
1887 // Ignore no-op and store intrinsics.
1888 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
1889 switch (II->getIntrinsicID()) {
1890 default:
1891 return false;
1892
1893 case Intrinsic::memmove:
1894 case Intrinsic::memcpy:
1895 case Intrinsic::memset: {
1896 MemIntrinsic *MI = cast<MemIntrinsic>(II);
1897 if (MI->isVolatile() || MI->getRawDest() != PI)
1898 return false;
1899 }
1900 // fall through
1901 case Intrinsic::dbg_declare:
1902 case Intrinsic::dbg_value:
1903 case Intrinsic::invariant_start:
1904 case Intrinsic::invariant_end:
1905 case Intrinsic::lifetime_start:
1906 case Intrinsic::lifetime_end:
1907 case Intrinsic::objectsize:
Benjamin Kramerf5e2fc42015-05-29 19:43:39 +00001908 Users.emplace_back(I);
Nuno Lopes95cc4f32012-07-09 18:38:20 +00001909 continue;
1910 }
1911 }
1912
Benjamin Kramer8bcc9712012-08-29 15:32:21 +00001913 if (isFreeCall(I, TLI)) {
Benjamin Kramerf5e2fc42015-05-29 19:43:39 +00001914 Users.emplace_back(I);
Nuno Lopes95cc4f32012-07-09 18:38:20 +00001915 continue;
1916 }
1917 return false;
1918
1919 case Instruction::Store: {
1920 StoreInst *SI = cast<StoreInst>(I);
1921 if (SI->isVolatile() || SI->getPointerOperand() != PI)
1922 return false;
Benjamin Kramerf5e2fc42015-05-29 19:43:39 +00001923 Users.emplace_back(I);
Nuno Lopes95cc4f32012-07-09 18:38:20 +00001924 continue;
1925 }
1926 }
1927 llvm_unreachable("missing a return?");
Nuno Lopesfa0dffc2012-07-06 23:09:25 +00001928 }
Nuno Lopes95cc4f32012-07-09 18:38:20 +00001929 } while (!Worklist.empty());
Duncan Sandsf162eac2010-05-27 19:09:06 +00001930 return true;
1931}
1932
Nuno Lopes95cc4f32012-07-09 18:38:20 +00001933Instruction *InstCombiner::visitAllocSite(Instruction &MI) {
Duncan Sandsf162eac2010-05-27 19:09:06 +00001934 // If we have a malloc call which is only used in any amount of comparisons
1935 // to null and free calls, delete the calls and replace the comparisons with
1936 // true or false as appropriate.
Nick Lewycky50f49662011-08-03 00:43:35 +00001937 SmallVector<WeakVH, 64> Users;
Benjamin Kramer8bcc9712012-08-29 15:32:21 +00001938 if (isAllocSiteRemovable(&MI, Users, TLI)) {
Nick Lewycky50f49662011-08-03 00:43:35 +00001939 for (unsigned i = 0, e = Users.size(); i != e; ++i) {
1940 Instruction *I = cast_or_null<Instruction>(&*Users[i]);
1941 if (!I) continue;
Duncan Sandsf162eac2010-05-27 19:09:06 +00001942
Nick Lewycky50f49662011-08-03 00:43:35 +00001943 if (ICmpInst *C = dyn_cast<ICmpInst>(I)) {
Nick Lewyckye8ae02d2011-08-02 22:08:01 +00001944 ReplaceInstUsesWith(*C,
1945 ConstantInt::get(Type::getInt1Ty(C->getContext()),
1946 C->isFalseWhenEqual()));
Nick Lewycky50f49662011-08-03 00:43:35 +00001947 } else if (isa<BitCastInst>(I) || isa<GetElementPtrInst>(I)) {
Nick Lewyckye8ae02d2011-08-02 22:08:01 +00001948 ReplaceInstUsesWith(*I, UndefValue::get(I->getType()));
Nuno Lopesfa0dffc2012-07-06 23:09:25 +00001949 } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
1950 if (II->getIntrinsicID() == Intrinsic::objectsize) {
1951 ConstantInt *CI = cast<ConstantInt>(II->getArgOperand(1));
1952 uint64_t DontKnow = CI->isZero() ? -1ULL : 0;
1953 ReplaceInstUsesWith(*I, ConstantInt::get(I->getType(), DontKnow));
1954 }
Duncan Sandsf162eac2010-05-27 19:09:06 +00001955 }
Nick Lewycky50f49662011-08-03 00:43:35 +00001956 EraseInstFromFunction(*I);
Duncan Sandsf162eac2010-05-27 19:09:06 +00001957 }
Nuno Lopesdc6085e2012-06-21 21:25:05 +00001958
1959 if (InvokeInst *II = dyn_cast<InvokeInst>(&MI)) {
Nuno Lopes9ac46612012-06-28 22:31:24 +00001960 // Replace invoke with a NOP intrinsic to maintain the original CFG
Nuno Lopes07594cb2012-06-25 17:11:47 +00001961 Module *M = II->getParent()->getParent()->getParent();
Nuno Lopes9ac46612012-06-28 22:31:24 +00001962 Function *F = Intrinsic::getDeclaration(M, Intrinsic::donothing);
1963 InvokeInst::Create(F, II->getNormalDest(), II->getUnwindDest(),
Dmitri Gribenko3238fb72013-05-05 00:40:33 +00001964 None, "", II->getParent());
Nuno Lopesdc6085e2012-06-21 21:25:05 +00001965 }
Duncan Sandsf162eac2010-05-27 19:09:06 +00001966 return EraseInstFromFunction(MI);
1967 }
Craig Topperf40110f2014-04-25 05:29:35 +00001968 return nullptr;
Duncan Sandsf162eac2010-05-27 19:09:06 +00001969}
1970
Quentin Colombet3b2db0b2013-01-07 18:37:41 +00001971/// \brief Move the call to free before a NULL test.
1972///
1973/// Check if this free is accessed after its argument has been test
1974/// against NULL (property 0).
1975/// If yes, it is legal to move this call in its predecessor block.
1976///
1977/// The move is performed only if the block containing the call to free
1978/// will be removed, i.e.:
1979/// 1. it has only one predecessor P, and P has two successors
1980/// 2. it contains the call and an unconditional branch
1981/// 3. its successor is the same as its predecessor's successor
1982///
1983/// The profitability is out-of concern here and this function should
1984/// be called only if the caller knows this transformation would be
1985/// profitable (e.g., for code size).
1986static Instruction *
1987tryToMoveFreeBeforeNullTest(CallInst &FI) {
1988 Value *Op = FI.getArgOperand(0);
1989 BasicBlock *FreeInstrBB = FI.getParent();
1990 BasicBlock *PredBB = FreeInstrBB->getSinglePredecessor();
1991
1992 // Validate part of constraint #1: Only one predecessor
1993 // FIXME: We can extend the number of predecessor, but in that case, we
1994 // would duplicate the call to free in each predecessor and it may
1995 // not be profitable even for code size.
1996 if (!PredBB)
Craig Topperf40110f2014-04-25 05:29:35 +00001997 return nullptr;
Quentin Colombet3b2db0b2013-01-07 18:37:41 +00001998
1999 // Validate constraint #2: Does this block contains only the call to
2000 // free and an unconditional branch?
2001 // FIXME: We could check if we can speculate everything in the
2002 // predecessor block
2003 if (FreeInstrBB->size() != 2)
Craig Topperf40110f2014-04-25 05:29:35 +00002004 return nullptr;
Quentin Colombet3b2db0b2013-01-07 18:37:41 +00002005 BasicBlock *SuccBB;
2006 if (!match(FreeInstrBB->getTerminator(), m_UnconditionalBr(SuccBB)))
Craig Topperf40110f2014-04-25 05:29:35 +00002007 return nullptr;
Quentin Colombet3b2db0b2013-01-07 18:37:41 +00002008
2009 // Validate the rest of constraint #1 by matching on the pred branch.
2010 TerminatorInst *TI = PredBB->getTerminator();
2011 BasicBlock *TrueBB, *FalseBB;
2012 ICmpInst::Predicate Pred;
2013 if (!match(TI, m_Br(m_ICmp(Pred, m_Specific(Op), m_Zero()), TrueBB, FalseBB)))
Craig Topperf40110f2014-04-25 05:29:35 +00002014 return nullptr;
Quentin Colombet3b2db0b2013-01-07 18:37:41 +00002015 if (Pred != ICmpInst::ICMP_EQ && Pred != ICmpInst::ICMP_NE)
Craig Topperf40110f2014-04-25 05:29:35 +00002016 return nullptr;
Quentin Colombet3b2db0b2013-01-07 18:37:41 +00002017
2018 // Validate constraint #3: Ensure the null case just falls through.
2019 if (SuccBB != (Pred == ICmpInst::ICMP_EQ ? TrueBB : FalseBB))
Craig Topperf40110f2014-04-25 05:29:35 +00002020 return nullptr;
Quentin Colombet3b2db0b2013-01-07 18:37:41 +00002021 assert(FreeInstrBB == (Pred == ICmpInst::ICMP_EQ ? FalseBB : TrueBB) &&
2022 "Broken CFG: missing edge from predecessor to successor");
2023
2024 FI.moveBefore(TI);
2025 return &FI;
2026}
Duncan Sandsf162eac2010-05-27 19:09:06 +00002027
2028
Gabor Greif75f69432010-06-24 12:21:15 +00002029Instruction *InstCombiner::visitFree(CallInst &FI) {
2030 Value *Op = FI.getArgOperand(0);
Victor Hernandeze2971492009-10-24 04:23:03 +00002031
2032 // free undef -> unreachable.
2033 if (isa<UndefValue>(Op)) {
2034 // Insert a new store to null because we cannot modify the CFG here.
Eli Friedman41e509a2011-05-18 23:58:37 +00002035 Builder->CreateStore(ConstantInt::getTrue(FI.getContext()),
2036 UndefValue::get(Type::getInt1PtrTy(FI.getContext())));
Victor Hernandeze2971492009-10-24 04:23:03 +00002037 return EraseInstFromFunction(FI);
2038 }
Jakub Staszakcfc46f82012-05-06 13:52:31 +00002039
Victor Hernandeze2971492009-10-24 04:23:03 +00002040 // If we have 'free null' delete the instruction. This can happen in stl code
2041 // when lots of inlining happens.
2042 if (isa<ConstantPointerNull>(Op))
2043 return EraseInstFromFunction(FI);
2044
Quentin Colombet3b2db0b2013-01-07 18:37:41 +00002045 // If we optimize for code size, try to move the call to free before the null
2046 // test so that simplify cfg can remove the empty block and dead code
2047 // elimination the branch. I.e., helps to turn something like:
2048 // if (foo) free(foo);
2049 // into
2050 // free(foo);
2051 if (MinimizeSize)
2052 if (Instruction *I = tryToMoveFreeBeforeNullTest(FI))
2053 return I;
2054
Craig Topperf40110f2014-04-25 05:29:35 +00002055 return nullptr;
Victor Hernandeze2971492009-10-24 04:23:03 +00002056}
Chris Lattner8427bff2003-12-07 01:24:23 +00002057
Hal Finkel93873cc12014-09-07 21:28:34 +00002058Instruction *InstCombiner::visitReturnInst(ReturnInst &RI) {
2059 if (RI.getNumOperands() == 0) // ret void
2060 return nullptr;
Chris Lattner14a251b2007-04-15 00:07:55 +00002061
Hal Finkel93873cc12014-09-07 21:28:34 +00002062 Value *ResultOp = RI.getOperand(0);
2063 Type *VTy = ResultOp->getType();
2064 if (!VTy->isIntegerTy())
2065 return nullptr;
2066
2067 // There might be assume intrinsics dominating this return that completely
2068 // determine the value. If so, constant fold it.
2069 unsigned BitWidth = VTy->getPrimitiveSizeInBits();
2070 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
2071 computeKnownBits(ResultOp, KnownZero, KnownOne, 0, &RI);
2072 if ((KnownZero|KnownOne).isAllOnesValue())
2073 RI.setOperand(0, Constant::getIntegerValue(VTy, KnownOne));
2074
2075 return nullptr;
2076}
Chris Lattner31f486c2005-01-31 05:36:43 +00002077
Chris Lattner9eef8a72003-06-04 04:46:00 +00002078Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
2079 // Change br (not X), label True, label False to: br X, label False, True
Craig Topperf40110f2014-04-25 05:29:35 +00002080 Value *X = nullptr;
Chris Lattnerd4252a72004-07-30 07:50:03 +00002081 BasicBlock *TrueDest;
2082 BasicBlock *FalseDest;
Dan Gohman5476cfd2009-08-12 16:23:25 +00002083 if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
Chris Lattnerd4252a72004-07-30 07:50:03 +00002084 !isa<Constant>(X)) {
2085 // Swap Destinations and condition...
2086 BI.setCondition(X);
Chandler Carruth3e8aa652011-10-17 01:11:57 +00002087 BI.swapSuccessors();
Chris Lattnerd4252a72004-07-30 07:50:03 +00002088 return &BI;
2089 }
2090
Philip Reames71c40352015-03-10 22:52:37 +00002091 // If the condition is irrelevant, remove the use so that other
2092 // transforms on the condition become more effective.
2093 if (BI.isConditional() &&
2094 BI.getSuccessor(0) == BI.getSuccessor(1) &&
2095 !isa<UndefValue>(BI.getCondition())) {
2096 BI.setCondition(UndefValue::get(BI.getCondition()->getType()));
2097 return &BI;
2098 }
2099
Alp Tokercb402912014-01-24 17:20:08 +00002100 // Canonicalize fcmp_one -> fcmp_oeq
Reid Spencer266e42b2006-12-23 06:05:41 +00002101 FCmpInst::Predicate FPred; Value *Y;
Jakub Staszakcfc46f82012-05-06 13:52:31 +00002102 if (match(&BI, m_Br(m_FCmp(FPred, m_Value(X), m_Value(Y)),
Chris Lattner905976b2009-08-30 06:13:40 +00002103 TrueDest, FalseDest)) &&
2104 BI.getCondition()->hasOneUse())
2105 if (FPred == FCmpInst::FCMP_ONE || FPred == FCmpInst::FCMP_OLE ||
2106 FPred == FCmpInst::FCMP_OGE) {
2107 FCmpInst *Cond = cast<FCmpInst>(BI.getCondition());
2108 Cond->setPredicate(FCmpInst::getInversePredicate(FPred));
Jakub Staszakcfc46f82012-05-06 13:52:31 +00002109
Chris Lattner905976b2009-08-30 06:13:40 +00002110 // Swap Destinations and condition.
Chandler Carruth3e8aa652011-10-17 01:11:57 +00002111 BI.swapSuccessors();
Chris Lattner905976b2009-08-30 06:13:40 +00002112 Worklist.Add(Cond);
Reid Spencer266e42b2006-12-23 06:05:41 +00002113 return &BI;
2114 }
2115
Alp Tokercb402912014-01-24 17:20:08 +00002116 // Canonicalize icmp_ne -> icmp_eq
Reid Spencer266e42b2006-12-23 06:05:41 +00002117 ICmpInst::Predicate IPred;
2118 if (match(&BI, m_Br(m_ICmp(IPred, m_Value(X), m_Value(Y)),
Chris Lattner905976b2009-08-30 06:13:40 +00002119 TrueDest, FalseDest)) &&
2120 BI.getCondition()->hasOneUse())
2121 if (IPred == ICmpInst::ICMP_NE || IPred == ICmpInst::ICMP_ULE ||
2122 IPred == ICmpInst::ICMP_SLE || IPred == ICmpInst::ICMP_UGE ||
2123 IPred == ICmpInst::ICMP_SGE) {
2124 ICmpInst *Cond = cast<ICmpInst>(BI.getCondition());
2125 Cond->setPredicate(ICmpInst::getInversePredicate(IPred));
2126 // Swap Destinations and condition.
Chandler Carruth3e8aa652011-10-17 01:11:57 +00002127 BI.swapSuccessors();
Chris Lattner905976b2009-08-30 06:13:40 +00002128 Worklist.Add(Cond);
Chris Lattnere967b342003-06-04 05:10:11 +00002129 return &BI;
2130 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00002131
Craig Topperf40110f2014-04-25 05:29:35 +00002132 return nullptr;
Chris Lattner9eef8a72003-06-04 04:46:00 +00002133}
Chris Lattner1085bdf2002-11-04 16:18:53 +00002134
Chris Lattner4c9c20a2004-07-03 00:26:11 +00002135Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
2136 Value *Cond = SI.getCondition();
Akira Hatanaka5c221ef2014-10-16 06:00:46 +00002137 unsigned BitWidth = cast<IntegerType>(Cond->getType())->getBitWidth();
2138 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002139 computeKnownBits(Cond, KnownZero, KnownOne, 0, &SI);
Akira Hatanaka5c221ef2014-10-16 06:00:46 +00002140 unsigned LeadingKnownZeros = KnownZero.countLeadingOnes();
2141 unsigned LeadingKnownOnes = KnownOne.countLeadingOnes();
2142
2143 // Compute the number of leading bits we can ignore.
2144 for (auto &C : SI.cases()) {
2145 LeadingKnownZeros = std::min(
2146 LeadingKnownZeros, C.getCaseValue()->getValue().countLeadingZeros());
2147 LeadingKnownOnes = std::min(
2148 LeadingKnownOnes, C.getCaseValue()->getValue().countLeadingOnes());
2149 }
2150
2151 unsigned NewWidth = BitWidth - std::max(LeadingKnownZeros, LeadingKnownOnes);
2152
2153 // Truncate the condition operand if the new type is equal to or larger than
2154 // the largest legal integer type. We need to be conservative here since
Sanjay Patel6a248112015-06-23 23:26:22 +00002155 // x86 generates redundant zero-extension instructions if the operand is
Akira Hatanaka5c221ef2014-10-16 06:00:46 +00002156 // truncated to i8 or i16.
Bruno Cardoso Lopesf6cf8ad2014-12-19 17:12:35 +00002157 bool TruncCond = false;
Owen Anderson58364dc2015-03-10 06:51:39 +00002158 if (NewWidth > 0 && BitWidth > NewWidth &&
2159 NewWidth >= DL.getLargestLegalIntTypeSize()) {
Bruno Cardoso Lopesf6cf8ad2014-12-19 17:12:35 +00002160 TruncCond = true;
Akira Hatanaka5c221ef2014-10-16 06:00:46 +00002161 IntegerType *Ty = IntegerType::get(SI.getContext(), NewWidth);
2162 Builder->SetInsertPoint(&SI);
2163 Value *NewCond = Builder->CreateTrunc(SI.getCondition(), Ty, "trunc");
2164 SI.setCondition(NewCond);
2165
2166 for (auto &C : SI.cases())
2167 static_cast<SwitchInst::CaseIt *>(&C)->setValue(ConstantInt::get(
2168 SI.getContext(), C.getCaseValue()->getValue().trunc(NewWidth)));
2169 }
2170
Chris Lattner4c9c20a2004-07-03 00:26:11 +00002171 if (Instruction *I = dyn_cast<Instruction>(Cond)) {
2172 if (I->getOpcode() == Instruction::Add)
2173 if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
2174 // change 'switch (X+4) case 1:' into 'switch (X) case -3'
Eli Friedman95031ed2011-09-29 20:21:17 +00002175 // Skip the first item since that's the default case.
Stepan Dyatkovskiy97b02fc2012-03-11 06:09:17 +00002176 for (SwitchInst::CaseIt i = SI.case_begin(), e = SI.case_end();
Stepan Dyatkovskiy5b648af2012-03-08 07:06:20 +00002177 i != e; ++i) {
2178 ConstantInt* CaseVal = i.getCaseValue();
Bruno Cardoso Lopesf6cf8ad2014-12-19 17:12:35 +00002179 Constant *LHS = CaseVal;
2180 if (TruncCond)
2181 LHS = LeadingKnownZeros
2182 ? ConstantExpr::getZExt(CaseVal, Cond->getType())
2183 : ConstantExpr::getSExt(CaseVal, Cond->getType());
2184 Constant* NewCaseVal = ConstantExpr::getSub(LHS, AddRHS);
Eli Friedman95031ed2011-09-29 20:21:17 +00002185 assert(isa<ConstantInt>(NewCaseVal) &&
2186 "Result of expression should be constant");
Stepan Dyatkovskiy5b648af2012-03-08 07:06:20 +00002187 i.setValue(cast<ConstantInt>(NewCaseVal));
Eli Friedman95031ed2011-09-29 20:21:17 +00002188 }
2189 SI.setCondition(I->getOperand(0));
Chris Lattner905976b2009-08-30 06:13:40 +00002190 Worklist.Add(I);
Chris Lattner4c9c20a2004-07-03 00:26:11 +00002191 return &SI;
2192 }
2193 }
Bruno Cardoso Lopesf6cf8ad2014-12-19 17:12:35 +00002194
2195 return TruncCond ? &SI : nullptr;
Chris Lattner4c9c20a2004-07-03 00:26:11 +00002196}
2197
Matthijs Kooijmanb2fc72b2008-06-11 14:05:05 +00002198Instruction *InstCombiner::visitExtractValueInst(ExtractValueInst &EV) {
Matthijs Kooijmanc1d74772008-07-16 12:55:45 +00002199 Value *Agg = EV.getAggregateOperand();
Matthijs Kooijmanb2fc72b2008-06-11 14:05:05 +00002200
Matthijs Kooijmanc1d74772008-07-16 12:55:45 +00002201 if (!EV.hasIndices())
2202 return ReplaceInstUsesWith(EV, Agg);
2203
David Majnemer25a796e2015-07-13 01:15:46 +00002204 if (Value *V =
2205 SimplifyExtractValueInst(Agg, EV.getIndices(), DL, TLI, DT, AC))
2206 return ReplaceInstUsesWith(EV, V);
Jakub Staszakcfc46f82012-05-06 13:52:31 +00002207
Matthijs Kooijmanc1d74772008-07-16 12:55:45 +00002208 if (InsertValueInst *IV = dyn_cast<InsertValueInst>(Agg)) {
2209 // We're extracting from an insertvalue instruction, compare the indices
2210 const unsigned *exti, *exte, *insi, *inse;
2211 for (exti = EV.idx_begin(), insi = IV->idx_begin(),
2212 exte = EV.idx_end(), inse = IV->idx_end();
2213 exti != exte && insi != inse;
2214 ++exti, ++insi) {
2215 if (*insi != *exti)
2216 // The insert and extract both reference distinctly different elements.
2217 // This means the extract is not influenced by the insert, and we can
2218 // replace the aggregate operand of the extract with the aggregate
2219 // operand of the insert. i.e., replace
2220 // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
2221 // %E = extractvalue { i32, { i32 } } %I, 0
2222 // with
2223 // %E = extractvalue { i32, { i32 } } %A, 0
2224 return ExtractValueInst::Create(IV->getAggregateOperand(),
Jay Foad57aa6362011-07-13 10:26:04 +00002225 EV.getIndices());
Matthijs Kooijmanc1d74772008-07-16 12:55:45 +00002226 }
2227 if (exti == exte && insi == inse)
2228 // Both iterators are at the end: Index lists are identical. Replace
2229 // %B = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
2230 // %C = extractvalue { i32, { i32 } } %B, 1, 0
2231 // with "i32 42"
2232 return ReplaceInstUsesWith(EV, IV->getInsertedValueOperand());
2233 if (exti == exte) {
2234 // The extract list is a prefix of the insert list. i.e. replace
2235 // %I = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
2236 // %E = extractvalue { i32, { i32 } } %I, 1
2237 // with
2238 // %X = extractvalue { i32, { i32 } } %A, 1
2239 // %E = insertvalue { i32 } %X, i32 42, 0
2240 // by switching the order of the insert and extract (though the
2241 // insertvalue should be left in, since it may have other uses).
Chris Lattner59663412009-08-30 18:50:58 +00002242 Value *NewEV = Builder->CreateExtractValue(IV->getAggregateOperand(),
Jay Foad57aa6362011-07-13 10:26:04 +00002243 EV.getIndices());
Matthijs Kooijmanc1d74772008-07-16 12:55:45 +00002244 return InsertValueInst::Create(NewEV, IV->getInsertedValueOperand(),
Frits van Bommel717d7ed2011-07-18 12:00:32 +00002245 makeArrayRef(insi, inse));
Matthijs Kooijmanc1d74772008-07-16 12:55:45 +00002246 }
2247 if (insi == inse)
2248 // The insert list is a prefix of the extract list
2249 // We can simply remove the common indices from the extract and make it
2250 // operate on the inserted value instead of the insertvalue result.
2251 // i.e., replace
2252 // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
2253 // %E = extractvalue { i32, { i32 } } %I, 1, 0
2254 // with
2255 // %E extractvalue { i32 } { i32 42 }, 0
Jakub Staszakcfc46f82012-05-06 13:52:31 +00002256 return ExtractValueInst::Create(IV->getInsertedValueOperand(),
Frits van Bommel717d7ed2011-07-18 12:00:32 +00002257 makeArrayRef(exti, exte));
Matthijs Kooijmanc1d74772008-07-16 12:55:45 +00002258 }
Chris Lattner39c07b22009-11-09 07:07:56 +00002259 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(Agg)) {
2260 // We're extracting from an intrinsic, see if we're the only user, which
2261 // allows us to simplify multiple result intrinsics to simpler things that
Gabor Greif75f69432010-06-24 12:21:15 +00002262 // just get one value.
Chris Lattner39c07b22009-11-09 07:07:56 +00002263 if (II->hasOneUse()) {
2264 // Check if we're grabbing the overflow bit or the result of a 'with
2265 // overflow' intrinsic. If it's the latter we can remove the intrinsic
2266 // and replace it with a traditional binary instruction.
2267 switch (II->getIntrinsicID()) {
2268 case Intrinsic::uadd_with_overflow:
2269 case Intrinsic::sadd_with_overflow:
2270 if (*EV.idx_begin() == 0) { // Normal result.
Gabor Greif75f69432010-06-24 12:21:15 +00002271 Value *LHS = II->getArgOperand(0), *RHS = II->getArgOperand(1);
Eli Friedmanb9ed18f2011-05-18 00:32:01 +00002272 ReplaceInstUsesWith(*II, UndefValue::get(II->getType()));
Chris Lattner39c07b22009-11-09 07:07:56 +00002273 EraseInstFromFunction(*II);
2274 return BinaryOperator::CreateAdd(LHS, RHS);
2275 }
Jakub Staszakcfc46f82012-05-06 13:52:31 +00002276
Chris Lattner3e635d22010-12-19 19:43:52 +00002277 // If the normal result of the add is dead, and the RHS is a constant,
2278 // we can transform this into a range comparison.
2279 // overflow = uadd a, -4 --> overflow = icmp ugt a, 3
Chris Lattner4fb9dd42010-12-19 23:24:04 +00002280 if (II->getIntrinsicID() == Intrinsic::uadd_with_overflow)
2281 if (ConstantInt *CI = dyn_cast<ConstantInt>(II->getArgOperand(1)))
2282 return new ICmpInst(ICmpInst::ICMP_UGT, II->getArgOperand(0),
2283 ConstantExpr::getNot(CI));
Chris Lattner39c07b22009-11-09 07:07:56 +00002284 break;
2285 case Intrinsic::usub_with_overflow:
2286 case Intrinsic::ssub_with_overflow:
2287 if (*EV.idx_begin() == 0) { // Normal result.
Gabor Greif75f69432010-06-24 12:21:15 +00002288 Value *LHS = II->getArgOperand(0), *RHS = II->getArgOperand(1);
Eli Friedmanb9ed18f2011-05-18 00:32:01 +00002289 ReplaceInstUsesWith(*II, UndefValue::get(II->getType()));
Chris Lattner39c07b22009-11-09 07:07:56 +00002290 EraseInstFromFunction(*II);
2291 return BinaryOperator::CreateSub(LHS, RHS);
2292 }
2293 break;
2294 case Intrinsic::umul_with_overflow:
2295 case Intrinsic::smul_with_overflow:
2296 if (*EV.idx_begin() == 0) { // Normal result.
Gabor Greif75f69432010-06-24 12:21:15 +00002297 Value *LHS = II->getArgOperand(0), *RHS = II->getArgOperand(1);
Eli Friedmanb9ed18f2011-05-18 00:32:01 +00002298 ReplaceInstUsesWith(*II, UndefValue::get(II->getType()));
Chris Lattner39c07b22009-11-09 07:07:56 +00002299 EraseInstFromFunction(*II);
2300 return BinaryOperator::CreateMul(LHS, RHS);
2301 }
2302 break;
2303 default:
2304 break;
2305 }
2306 }
2307 }
Frits van Bommel28218aa2010-11-29 21:56:20 +00002308 if (LoadInst *L = dyn_cast<LoadInst>(Agg))
2309 // If the (non-volatile) load only has one use, we can rewrite this to a
2310 // load from a GEP. This reduces the size of the load.
2311 // FIXME: If a load is used only by extractvalue instructions then this
2312 // could be done regardless of having multiple uses.
Eli Friedman8bc586e2011-08-15 22:09:40 +00002313 if (L->isSimple() && L->hasOneUse()) {
Frits van Bommel28218aa2010-11-29 21:56:20 +00002314 // extractvalue has integer indices, getelementptr has Value*s. Convert.
2315 SmallVector<Value*, 4> Indices;
2316 // Prefix an i32 0 since we need the first element.
2317 Indices.push_back(Builder->getInt32(0));
2318 for (ExtractValueInst::idx_iterator I = EV.idx_begin(), E = EV.idx_end();
2319 I != E; ++I)
2320 Indices.push_back(Builder->getInt32(*I));
2321
2322 // We need to insert these at the location of the old load, not at that of
2323 // the extractvalue.
2324 Builder->SetInsertPoint(L->getParent(), L);
David Blaikieaa41cd52015-04-03 21:33:42 +00002325 Value *GEP = Builder->CreateInBoundsGEP(L->getType(),
2326 L->getPointerOperand(), Indices);
Frits van Bommel28218aa2010-11-29 21:56:20 +00002327 // Returning the load directly will cause the main loop to insert it in
2328 // the wrong spot, so use ReplaceInstUsesWith().
2329 return ReplaceInstUsesWith(EV, Builder->CreateLoad(GEP));
2330 }
2331 // We could simplify extracts from other values. Note that nested extracts may
2332 // already be simplified implicitly by the above: extract (extract (insert) )
Matthijs Kooijmanc1d74772008-07-16 12:55:45 +00002333 // will be translated into extract ( insert ( extract ) ) first and then just
Frits van Bommel28218aa2010-11-29 21:56:20 +00002334 // the value inserted, if appropriate. Similarly for extracts from single-use
2335 // loads: extract (extract (load)) will be translated to extract (load (gep))
2336 // and if again single-use then via load (gep (gep)) to load (gep).
2337 // However, double extracts from e.g. function arguments or return values
2338 // aren't handled yet.
Craig Topperf40110f2014-04-25 05:29:35 +00002339 return nullptr;
Matthijs Kooijmanb2fc72b2008-06-11 14:05:05 +00002340}
2341
Duncan Sands5c055792011-09-30 13:12:16 +00002342/// isCatchAll - Return 'true' if the given typeinfo will match anything.
Reid Kleckner4af64152015-01-28 01:17:38 +00002343static bool isCatchAll(EHPersonality Personality, Constant *TypeInfo) {
Duncan Sands5c055792011-09-30 13:12:16 +00002344 switch (Personality) {
Reid Kleckner4af64152015-01-28 01:17:38 +00002345 case EHPersonality::GNU_C:
2346 // The GCC C EH personality only exists to support cleanups, so it's not
2347 // clear what the semantics of catch clauses are.
Duncan Sands5c055792011-09-30 13:12:16 +00002348 return false;
Reid Kleckner4af64152015-01-28 01:17:38 +00002349 case EHPersonality::Unknown:
2350 return false;
2351 case EHPersonality::GNU_Ada:
Duncan Sands5c055792011-09-30 13:12:16 +00002352 // While __gnat_all_others_value will match any Ada exception, it doesn't
2353 // match foreign exceptions (or didn't, before gcc-4.7).
2354 return false;
Reid Kleckner4af64152015-01-28 01:17:38 +00002355 case EHPersonality::GNU_CXX:
2356 case EHPersonality::GNU_ObjC:
Reid Kleckner96d01132015-02-11 01:23:16 +00002357 case EHPersonality::MSVC_X86SEH:
Reid Kleckner4af64152015-01-28 01:17:38 +00002358 case EHPersonality::MSVC_Win64SEH:
2359 case EHPersonality::MSVC_CXX:
Duncan Sands5c055792011-09-30 13:12:16 +00002360 return TypeInfo->isNullValue();
2361 }
Reid Kleckner4af64152015-01-28 01:17:38 +00002362 llvm_unreachable("invalid enum");
Duncan Sands5c055792011-09-30 13:12:16 +00002363}
2364
2365static bool shorter_filter(const Value *LHS, const Value *RHS) {
2366 return
2367 cast<ArrayType>(LHS->getType())->getNumElements()
2368 <
2369 cast<ArrayType>(RHS->getType())->getNumElements();
2370}
2371
2372Instruction *InstCombiner::visitLandingPadInst(LandingPadInst &LI) {
2373 // The logic here should be correct for any real-world personality function.
2374 // However if that turns out not to be true, the offending logic can always
2375 // be conditioned on the personality function, like the catch-all logic is.
David Majnemer7fddecc2015-06-17 20:52:32 +00002376 EHPersonality Personality =
2377 classifyEHPersonality(LI.getParent()->getParent()->getPersonalityFn());
Duncan Sands5c055792011-09-30 13:12:16 +00002378
2379 // Simplify the list of clauses, eg by removing repeated catch clauses
2380 // (these are often created by inlining).
2381 bool MakeNewInstruction = false; // If true, recreate using the following:
Rafael Espindola4dc5dfc2014-06-04 18:51:31 +00002382 SmallVector<Constant *, 16> NewClauses; // - Clauses for the new instruction;
Duncan Sands5c055792011-09-30 13:12:16 +00002383 bool CleanupFlag = LI.isCleanup(); // - The new instruction is a cleanup.
2384
2385 SmallPtrSet<Value *, 16> AlreadyCaught; // Typeinfos known caught already.
2386 for (unsigned i = 0, e = LI.getNumClauses(); i != e; ++i) {
2387 bool isLastClause = i + 1 == e;
2388 if (LI.isCatch(i)) {
2389 // A catch clause.
Rafael Espindola4dc5dfc2014-06-04 18:51:31 +00002390 Constant *CatchClause = LI.getClause(i);
Rafael Espindola78598d92014-06-04 19:01:48 +00002391 Constant *TypeInfo = CatchClause->stripPointerCasts();
Duncan Sands5c055792011-09-30 13:12:16 +00002392
2393 // If we already saw this clause, there is no point in having a second
2394 // copy of it.
David Blaikie70573dc2014-11-19 07:49:26 +00002395 if (AlreadyCaught.insert(TypeInfo).second) {
Duncan Sands5c055792011-09-30 13:12:16 +00002396 // This catch clause was not already seen.
2397 NewClauses.push_back(CatchClause);
2398 } else {
2399 // Repeated catch clause - drop the redundant copy.
2400 MakeNewInstruction = true;
2401 }
2402
2403 // If this is a catch-all then there is no point in keeping any following
2404 // clauses or marking the landingpad as having a cleanup.
2405 if (isCatchAll(Personality, TypeInfo)) {
2406 if (!isLastClause)
2407 MakeNewInstruction = true;
2408 CleanupFlag = false;
2409 break;
2410 }
2411 } else {
2412 // A filter clause. If any of the filter elements were already caught
2413 // then they can be dropped from the filter. It is tempting to try to
2414 // exploit the filter further by saying that any typeinfo that does not
2415 // occur in the filter can't be caught later (and thus can be dropped).
2416 // However this would be wrong, since typeinfos can match without being
2417 // equal (for example if one represents a C++ class, and the other some
2418 // class derived from it).
2419 assert(LI.isFilter(i) && "Unsupported landingpad clause!");
Rafael Espindola4dc5dfc2014-06-04 18:51:31 +00002420 Constant *FilterClause = LI.getClause(i);
Duncan Sands5c055792011-09-30 13:12:16 +00002421 ArrayType *FilterType = cast<ArrayType>(FilterClause->getType());
2422 unsigned NumTypeInfos = FilterType->getNumElements();
2423
2424 // An empty filter catches everything, so there is no point in keeping any
2425 // following clauses or marking the landingpad as having a cleanup. By
2426 // dealing with this case here the following code is made a bit simpler.
2427 if (!NumTypeInfos) {
2428 NewClauses.push_back(FilterClause);
2429 if (!isLastClause)
2430 MakeNewInstruction = true;
2431 CleanupFlag = false;
2432 break;
2433 }
2434
2435 bool MakeNewFilter = false; // If true, make a new filter.
2436 SmallVector<Constant *, 16> NewFilterElts; // New elements.
2437 if (isa<ConstantAggregateZero>(FilterClause)) {
2438 // Not an empty filter - it contains at least one null typeinfo.
2439 assert(NumTypeInfos > 0 && "Should have handled empty filter already!");
2440 Constant *TypeInfo =
2441 Constant::getNullValue(FilterType->getElementType());
2442 // If this typeinfo is a catch-all then the filter can never match.
2443 if (isCatchAll(Personality, TypeInfo)) {
2444 // Throw the filter away.
2445 MakeNewInstruction = true;
2446 continue;
2447 }
2448
2449 // There is no point in having multiple copies of this typeinfo, so
2450 // discard all but the first copy if there is more than one.
2451 NewFilterElts.push_back(TypeInfo);
2452 if (NumTypeInfos > 1)
2453 MakeNewFilter = true;
2454 } else {
2455 ConstantArray *Filter = cast<ConstantArray>(FilterClause);
2456 SmallPtrSet<Value *, 16> SeenInFilter; // For uniquing the elements.
2457 NewFilterElts.reserve(NumTypeInfos);
2458
2459 // Remove any filter elements that were already caught or that already
2460 // occurred in the filter. While there, see if any of the elements are
2461 // catch-alls. If so, the filter can be discarded.
2462 bool SawCatchAll = false;
2463 for (unsigned j = 0; j != NumTypeInfos; ++j) {
Rafael Espindola78598d92014-06-04 19:01:48 +00002464 Constant *Elt = Filter->getOperand(j);
2465 Constant *TypeInfo = Elt->stripPointerCasts();
Duncan Sands5c055792011-09-30 13:12:16 +00002466 if (isCatchAll(Personality, TypeInfo)) {
2467 // This element is a catch-all. Bail out, noting this fact.
2468 SawCatchAll = true;
2469 break;
2470 }
2471 if (AlreadyCaught.count(TypeInfo))
2472 // Already caught by an earlier clause, so having it in the filter
2473 // is pointless.
2474 continue;
2475 // There is no point in having multiple copies of the same typeinfo in
2476 // a filter, so only add it if we didn't already.
David Blaikie70573dc2014-11-19 07:49:26 +00002477 if (SeenInFilter.insert(TypeInfo).second)
Duncan Sands5c055792011-09-30 13:12:16 +00002478 NewFilterElts.push_back(cast<Constant>(Elt));
2479 }
2480 // A filter containing a catch-all cannot match anything by definition.
2481 if (SawCatchAll) {
2482 // Throw the filter away.
2483 MakeNewInstruction = true;
2484 continue;
2485 }
2486
2487 // If we dropped something from the filter, make a new one.
2488 if (NewFilterElts.size() < NumTypeInfos)
2489 MakeNewFilter = true;
2490 }
2491 if (MakeNewFilter) {
2492 FilterType = ArrayType::get(FilterType->getElementType(),
2493 NewFilterElts.size());
2494 FilterClause = ConstantArray::get(FilterType, NewFilterElts);
2495 MakeNewInstruction = true;
2496 }
2497
2498 NewClauses.push_back(FilterClause);
2499
2500 // If the new filter is empty then it will catch everything so there is
2501 // no point in keeping any following clauses or marking the landingpad
2502 // as having a cleanup. The case of the original filter being empty was
2503 // already handled above.
2504 if (MakeNewFilter && !NewFilterElts.size()) {
2505 assert(MakeNewInstruction && "New filter but not a new instruction!");
2506 CleanupFlag = false;
2507 break;
2508 }
2509 }
2510 }
2511
2512 // If several filters occur in a row then reorder them so that the shortest
2513 // filters come first (those with the smallest number of elements). This is
2514 // advantageous because shorter filters are more likely to match, speeding up
2515 // unwinding, but mostly because it increases the effectiveness of the other
2516 // filter optimizations below.
2517 for (unsigned i = 0, e = NewClauses.size(); i + 1 < e; ) {
2518 unsigned j;
2519 // Find the maximal 'j' s.t. the range [i, j) consists entirely of filters.
2520 for (j = i; j != e; ++j)
2521 if (!isa<ArrayType>(NewClauses[j]->getType()))
2522 break;
2523
2524 // Check whether the filters are already sorted by length. We need to know
2525 // if sorting them is actually going to do anything so that we only make a
2526 // new landingpad instruction if it does.
2527 for (unsigned k = i; k + 1 < j; ++k)
2528 if (shorter_filter(NewClauses[k+1], NewClauses[k])) {
2529 // Not sorted, so sort the filters now. Doing an unstable sort would be
2530 // correct too but reordering filters pointlessly might confuse users.
2531 std::stable_sort(NewClauses.begin() + i, NewClauses.begin() + j,
2532 shorter_filter);
2533 MakeNewInstruction = true;
2534 break;
2535 }
2536
2537 // Look for the next batch of filters.
2538 i = j + 1;
2539 }
2540
2541 // If typeinfos matched if and only if equal, then the elements of a filter L
2542 // that occurs later than a filter F could be replaced by the intersection of
2543 // the elements of F and L. In reality two typeinfos can match without being
2544 // equal (for example if one represents a C++ class, and the other some class
2545 // derived from it) so it would be wrong to perform this transform in general.
2546 // However the transform is correct and useful if F is a subset of L. In that
2547 // case L can be replaced by F, and thus removed altogether since repeating a
2548 // filter is pointless. So here we look at all pairs of filters F and L where
2549 // L follows F in the list of clauses, and remove L if every element of F is
2550 // an element of L. This can occur when inlining C++ functions with exception
2551 // specifications.
2552 for (unsigned i = 0; i + 1 < NewClauses.size(); ++i) {
2553 // Examine each filter in turn.
2554 Value *Filter = NewClauses[i];
2555 ArrayType *FTy = dyn_cast<ArrayType>(Filter->getType());
2556 if (!FTy)
2557 // Not a filter - skip it.
2558 continue;
2559 unsigned FElts = FTy->getNumElements();
2560 // Examine each filter following this one. Doing this backwards means that
2561 // we don't have to worry about filters disappearing under us when removed.
2562 for (unsigned j = NewClauses.size() - 1; j != i; --j) {
2563 Value *LFilter = NewClauses[j];
2564 ArrayType *LTy = dyn_cast<ArrayType>(LFilter->getType());
2565 if (!LTy)
2566 // Not a filter - skip it.
2567 continue;
2568 // If Filter is a subset of LFilter, i.e. every element of Filter is also
2569 // an element of LFilter, then discard LFilter.
Rafael Espindola4dc5dfc2014-06-04 18:51:31 +00002570 SmallVectorImpl<Constant *>::iterator J = NewClauses.begin() + j;
Duncan Sands5c055792011-09-30 13:12:16 +00002571 // If Filter is empty then it is a subset of LFilter.
2572 if (!FElts) {
2573 // Discard LFilter.
2574 NewClauses.erase(J);
2575 MakeNewInstruction = true;
2576 // Move on to the next filter.
2577 continue;
2578 }
2579 unsigned LElts = LTy->getNumElements();
2580 // If Filter is longer than LFilter then it cannot be a subset of it.
2581 if (FElts > LElts)
2582 // Move on to the next filter.
2583 continue;
2584 // At this point we know that LFilter has at least one element.
2585 if (isa<ConstantAggregateZero>(LFilter)) { // LFilter only contains zeros.
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00002586 // Filter is a subset of LFilter iff Filter contains only zeros (as we
Duncan Sands5c055792011-09-30 13:12:16 +00002587 // already know that Filter is not longer than LFilter).
2588 if (isa<ConstantAggregateZero>(Filter)) {
2589 assert(FElts <= LElts && "Should have handled this case earlier!");
2590 // Discard LFilter.
2591 NewClauses.erase(J);
2592 MakeNewInstruction = true;
2593 }
2594 // Move on to the next filter.
2595 continue;
2596 }
2597 ConstantArray *LArray = cast<ConstantArray>(LFilter);
2598 if (isa<ConstantAggregateZero>(Filter)) { // Filter only contains zeros.
2599 // Since Filter is non-empty and contains only zeros, it is a subset of
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00002600 // LFilter iff LFilter contains a zero.
Duncan Sands5c055792011-09-30 13:12:16 +00002601 assert(FElts > 0 && "Should have eliminated the empty filter earlier!");
2602 for (unsigned l = 0; l != LElts; ++l)
2603 if (LArray->getOperand(l)->isNullValue()) {
2604 // LFilter contains a zero - discard it.
2605 NewClauses.erase(J);
2606 MakeNewInstruction = true;
2607 break;
2608 }
2609 // Move on to the next filter.
2610 continue;
2611 }
2612 // At this point we know that both filters are ConstantArrays. Loop over
2613 // operands to see whether every element of Filter is also an element of
2614 // LFilter. Since filters tend to be short this is probably faster than
2615 // using a method that scales nicely.
2616 ConstantArray *FArray = cast<ConstantArray>(Filter);
2617 bool AllFound = true;
2618 for (unsigned f = 0; f != FElts; ++f) {
2619 Value *FTypeInfo = FArray->getOperand(f)->stripPointerCasts();
2620 AllFound = false;
2621 for (unsigned l = 0; l != LElts; ++l) {
2622 Value *LTypeInfo = LArray->getOperand(l)->stripPointerCasts();
2623 if (LTypeInfo == FTypeInfo) {
2624 AllFound = true;
2625 break;
2626 }
2627 }
2628 if (!AllFound)
2629 break;
2630 }
2631 if (AllFound) {
2632 // Discard LFilter.
2633 NewClauses.erase(J);
2634 MakeNewInstruction = true;
2635 }
2636 // Move on to the next filter.
2637 }
2638 }
2639
2640 // If we changed any of the clauses, replace the old landingpad instruction
2641 // with a new one.
2642 if (MakeNewInstruction) {
2643 LandingPadInst *NLI = LandingPadInst::Create(LI.getType(),
Duncan Sands5c055792011-09-30 13:12:16 +00002644 NewClauses.size());
2645 for (unsigned i = 0, e = NewClauses.size(); i != e; ++i)
2646 NLI->addClause(NewClauses[i]);
2647 // A landing pad with no clauses must have the cleanup flag set. It is
2648 // theoretically possible, though highly unlikely, that we eliminated all
2649 // clauses. If so, force the cleanup flag to true.
2650 if (NewClauses.empty())
2651 CleanupFlag = true;
2652 NLI->setCleanup(CleanupFlag);
2653 return NLI;
2654 }
2655
2656 // Even if none of the clauses changed, we may nonetheless have understood
2657 // that the cleanup flag is pointless. Clear it if so.
2658 if (LI.isCleanup() != CleanupFlag) {
2659 assert(!CleanupFlag && "Adding a cleanup, not removing one?!");
2660 LI.setCleanup(CleanupFlag);
2661 return &LI;
2662 }
2663
Craig Topperf40110f2014-04-25 05:29:35 +00002664 return nullptr;
Duncan Sands5c055792011-09-30 13:12:16 +00002665}
2666
Chris Lattner39c98bb2004-12-08 23:43:58 +00002667/// TryToSinkInstruction - Try to move the specified instruction from its
2668/// current block into the beginning of DestBlock, which can only happen if it's
2669/// safe to move the instruction past all of the instructions between it and the
2670/// end of its block.
2671static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
2672 assert(I->hasOneUse() && "Invariants didn't hold!");
2673
Bill Wendlinge86965e2011-08-15 21:14:31 +00002674 // Cannot move control-flow-involving, volatile loads, vaarg, etc.
David Majnemer60c994b2015-08-08 03:51:49 +00002675 if (isa<PHINode>(I) || I->isEHPad() || I->mayHaveSideEffects() ||
Bill Wendlinga9ee09f2011-08-17 20:36:44 +00002676 isa<TerminatorInst>(I))
Chris Lattnera4ee1f52008-05-09 15:07:33 +00002677 return false;
Misha Brukmanb1c93172005-04-21 23:48:37 +00002678
Chris Lattner39c98bb2004-12-08 23:43:58 +00002679 // Do not sink alloca instructions out of the entry block.
Dan Gohmandcb291f2007-03-22 16:38:57 +00002680 if (isa<AllocaInst>(I) && I->getParent() ==
2681 &DestBlock->getParent()->getEntryBlock())
Chris Lattner39c98bb2004-12-08 23:43:58 +00002682 return false;
2683
Chris Lattnerf17a2fb2004-12-09 07:14:34 +00002684 // We can only sink load instructions if there is nothing between the load and
2685 // the end of block that could change the value.
Chris Lattner49a594e2008-05-08 17:37:37 +00002686 if (I->mayReadFromMemory()) {
2687 for (BasicBlock::iterator Scan = I, E = I->getParent()->end();
Chris Lattnerf17a2fb2004-12-09 07:14:34 +00002688 Scan != E; ++Scan)
2689 if (Scan->mayWriteToMemory())
2690 return false;
Chris Lattnerf17a2fb2004-12-09 07:14:34 +00002691 }
Chris Lattner39c98bb2004-12-08 23:43:58 +00002692
Bill Wendling8ddfc092011-08-16 20:45:24 +00002693 BasicBlock::iterator InsertPos = DestBlock->getFirstInsertionPt();
Chris Lattner9f269e42005-08-08 19:11:57 +00002694 I->moveBefore(InsertPos);
Chris Lattner39c98bb2004-12-08 23:43:58 +00002695 ++NumSunkInst;
2696 return true;
2697}
2698
Chandler Carruthdf5747a2015-01-21 11:38:17 +00002699bool InstCombiner::run() {
Chris Lattner97fd3592009-08-30 05:55:36 +00002700 while (!Worklist.isEmpty()) {
2701 Instruction *I = Worklist.RemoveOne();
Craig Topperf40110f2014-04-25 05:29:35 +00002702 if (I == nullptr) continue; // skip null values.
Chris Lattnerca081252001-12-14 16:52:21 +00002703
Chris Lattner1443bc52006-05-11 17:11:52 +00002704 // Check to see if we can DCE the instruction.
Benjamin Kramer8bcc9712012-08-29 15:32:21 +00002705 if (isInstructionTriviallyDead(I, TLI)) {
Matt Arsenaulte6db7602013-09-05 19:48:28 +00002706 DEBUG(dbgs() << "IC: DCE: " << *I << '\n');
Chris Lattner905976b2009-08-30 06:13:40 +00002707 EraseInstFromFunction(*I);
2708 ++NumDeadInst;
Chris Lattnerff5f1e42009-08-31 06:57:37 +00002709 MadeIRChange = true;
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00002710 continue;
2711 }
Chris Lattner99f48c62002-09-02 04:59:56 +00002712
Chris Lattner1443bc52006-05-11 17:11:52 +00002713 // Instruction isn't dead, see if we can constant propagate it.
David Majnemer7fddecc2015-06-17 20:52:32 +00002714 if (!I->use_empty() &&
2715 (I->getNumOperands() == 0 || isa<Constant>(I->getOperand(0)))) {
Rafael Espindola37dc9e12014-02-21 00:06:31 +00002716 if (Constant *C = ConstantFoldInstruction(I, DL, TLI)) {
Matt Arsenaulte6db7602013-09-05 19:48:28 +00002717 DEBUG(dbgs() << "IC: ConstFold to: " << *C << " from: " << *I << '\n');
Chris Lattnercd517ff2005-01-28 19:32:01 +00002718
Chris Lattnerdd1f68a2009-10-15 04:13:44 +00002719 // Add operands to the worklist.
2720 ReplaceInstUsesWith(*I, C);
2721 ++NumConstProp;
2722 EraseInstFromFunction(*I);
2723 MadeIRChange = true;
2724 continue;
2725 }
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002726 }
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00002727
Chris Lattner39c98bb2004-12-08 23:43:58 +00002728 // See if we can trivially sink this instruction to a successor basic block.
Dan Gohmanfa1211f2008-07-23 00:34:11 +00002729 if (I->hasOneUse()) {
Chris Lattner39c98bb2004-12-08 23:43:58 +00002730 BasicBlock *BB = I->getParent();
Chandler Carruthcdf47882014-03-09 03:16:01 +00002731 Instruction *UserInst = cast<Instruction>(*I->user_begin());
Chris Lattner6b9044d2009-10-14 15:21:58 +00002732 BasicBlock *UserParent;
Jakub Staszakcfc46f82012-05-06 13:52:31 +00002733
Chris Lattner6b9044d2009-10-14 15:21:58 +00002734 // Get the block the use occurs in.
2735 if (PHINode *PN = dyn_cast<PHINode>(UserInst))
Chandler Carruthcdf47882014-03-09 03:16:01 +00002736 UserParent = PN->getIncomingBlock(*I->use_begin());
Chris Lattner6b9044d2009-10-14 15:21:58 +00002737 else
2738 UserParent = UserInst->getParent();
Jakub Staszakcfc46f82012-05-06 13:52:31 +00002739
Chris Lattner39c98bb2004-12-08 23:43:58 +00002740 if (UserParent != BB) {
2741 bool UserIsSuccessor = false;
2742 // See if the user is one of our successors.
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +00002743 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
2744 if (*SI == UserParent) {
Chris Lattner39c98bb2004-12-08 23:43:58 +00002745 UserIsSuccessor = true;
2746 break;
2747 }
2748
2749 // If the user is one of our immediate successors, and if that successor
2750 // only has us as a predecessors (we'd have to split the critical edge
2751 // otherwise), we can keep going.
Aditya Nandakumar0b5a6742014-07-11 21:49:39 +00002752 if (UserIsSuccessor && UserParent->getSinglePredecessor()) {
Chris Lattner39c98bb2004-12-08 23:43:58 +00002753 // Okay, the CFG is simple enough, try to sink this instruction.
Aditya Nandakumar0b5a6742014-07-11 21:49:39 +00002754 if (TryToSinkInstruction(I, UserParent)) {
2755 MadeIRChange = true;
2756 // We'll add uses of the sunk instruction below, but since sinking
2757 // can expose opportunities for it's *operands* add them to the
2758 // worklist
2759 for (Use &U : I->operands())
2760 if (Instruction *OpI = dyn_cast<Instruction>(U.get()))
2761 Worklist.Add(OpI);
2762 }
2763 }
Chris Lattner39c98bb2004-12-08 23:43:58 +00002764 }
2765 }
2766
Chris Lattner022a5822009-08-30 07:44:24 +00002767 // Now that we have an instruction, try combining it to simplify it.
2768 Builder->SetInsertPoint(I->getParent(), I);
Eli Friedman96254a02011-05-18 01:28:27 +00002769 Builder->SetCurrentDebugLocation(I->getDebugLoc());
Jakub Staszakcfc46f82012-05-06 13:52:31 +00002770
Reid Spencer755d0e72007-03-26 17:44:01 +00002771#ifndef NDEBUG
2772 std::string OrigI;
2773#endif
Chris Lattnerb25de3f2009-08-23 04:37:46 +00002774 DEBUG(raw_string_ostream SS(OrigI); I->print(SS); OrigI = SS.str(););
Matt Arsenaulte6db7602013-09-05 19:48:28 +00002775 DEBUG(dbgs() << "IC: Visiting: " << OrigI << '\n');
Jeffrey Yasskindafd08e2009-10-08 00:12:24 +00002776
Chris Lattnerae7a0d32002-08-02 19:29:35 +00002777 if (Instruction *Result = visit(*I)) {
Chris Lattner0b18c1d2002-05-10 15:38:35 +00002778 ++NumCombined;
Chris Lattner260ab202002-04-18 17:39:14 +00002779 // Should we replace the old instruction with a new one?
Chris Lattner053c0932002-05-14 15:24:07 +00002780 if (Result != I) {
Matt Arsenaulte6db7602013-09-05 19:48:28 +00002781 DEBUG(dbgs() << "IC: Old = " << *I << '\n'
Jim Grosbach8f9acfa2011-10-05 20:44:29 +00002782 << " New = " << *Result << '\n');
2783
Duncan P. N. Exon Smithec819c02015-03-30 19:49:49 +00002784 if (I->getDebugLoc())
Eli Friedman35211c62011-05-27 00:19:40 +00002785 Result->setDebugLoc(I->getDebugLoc());
Chris Lattner396dbfe2004-06-09 05:08:07 +00002786 // Everything uses the new instruction now.
2787 I->replaceAllUsesWith(Result);
2788
Jim Grosbache7abae02011-10-05 20:53:43 +00002789 // Move the name to the new instruction first.
2790 Result->takeName(I);
2791
Jim Grosbach8f9acfa2011-10-05 20:44:29 +00002792 // Push the new instruction and any users onto the worklist.
2793 Worklist.Add(Result);
2794 Worklist.AddUsersToWorkList(*Result);
2795
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00002796 // Insert the new instruction into the basic block...
2797 BasicBlock *InstParent = I->getParent();
Chris Lattner7515cab2004-11-14 19:13:23 +00002798 BasicBlock::iterator InsertPos = I;
2799
Eli Friedmana49b8282011-11-01 04:49:29 +00002800 // If we replace a PHI with something that isn't a PHI, fix up the
2801 // insertion point.
2802 if (!isa<PHINode>(Result) && isa<PHINode>(InsertPos))
2803 InsertPos = InstParent->getFirstInsertionPt();
Chris Lattner7515cab2004-11-14 19:13:23 +00002804
2805 InstParent->getInstList().insert(InsertPos, Result);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00002806
Chris Lattner905976b2009-08-30 06:13:40 +00002807 EraseInstFromFunction(*I);
Chris Lattner113f4f42002-06-25 16:13:24 +00002808 } else {
Evan Chenga4ed8a52007-03-27 16:44:48 +00002809#ifndef NDEBUG
Matt Arsenaulte6db7602013-09-05 19:48:28 +00002810 DEBUG(dbgs() << "IC: Mod = " << OrigI << '\n'
Chris Lattnerb25de3f2009-08-23 04:37:46 +00002811 << " New = " << *I << '\n');
Evan Chenga4ed8a52007-03-27 16:44:48 +00002812#endif
Chris Lattner7d2a5392004-03-13 23:54:27 +00002813
Chris Lattnerae7a0d32002-08-02 19:29:35 +00002814 // If the instruction was modified, it's possible that it is now dead.
2815 // if so, remove it.
Benjamin Kramer8bcc9712012-08-29 15:32:21 +00002816 if (isInstructionTriviallyDead(I, TLI)) {
Chris Lattner905976b2009-08-30 06:13:40 +00002817 EraseInstFromFunction(*I);
Chris Lattner396dbfe2004-06-09 05:08:07 +00002818 } else {
Chris Lattner905976b2009-08-30 06:13:40 +00002819 Worklist.Add(I);
Chris Lattnerbacd05c2009-08-30 06:22:51 +00002820 Worklist.AddUsersToWorkList(*I);
Chris Lattnerae7a0d32002-08-02 19:29:35 +00002821 }
Chris Lattner053c0932002-05-14 15:24:07 +00002822 }
Chris Lattnerff5f1e42009-08-31 06:57:37 +00002823 MadeIRChange = true;
Chris Lattnerca081252001-12-14 16:52:21 +00002824 }
2825 }
2826
Chris Lattner97fd3592009-08-30 05:55:36 +00002827 Worklist.Zap();
Chris Lattnerff5f1e42009-08-31 06:57:37 +00002828 return MadeIRChange;
Chris Lattner04805fa2002-02-26 21:46:54 +00002829}
2830
Chandler Carruthdf5747a2015-01-21 11:38:17 +00002831/// AddReachableCodeToWorklist - Walk the function in depth-first order, adding
2832/// all reachable code to the worklist.
2833///
2834/// This has a couple of tricks to make the code faster and more powerful. In
2835/// particular, we constant fold and DCE instructions as we go, to avoid adding
2836/// them to the worklist (this significantly speeds up instcombine on code where
2837/// many instructions are dead or constant). Additionally, if we find a branch
2838/// whose condition is a known constant, we only visit the reachable successors.
2839///
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002840static bool AddReachableCodeToWorklist(BasicBlock *BB, const DataLayout &DL,
2841 SmallPtrSetImpl<BasicBlock *> &Visited,
Chandler Carruthdf5747a2015-01-21 11:38:17 +00002842 InstCombineWorklist &ICWorklist,
Chandler Carruthdf5747a2015-01-21 11:38:17 +00002843 const TargetLibraryInfo *TLI) {
2844 bool MadeIRChange = false;
2845 SmallVector<BasicBlock*, 256> Worklist;
2846 Worklist.push_back(BB);
Hal Finkel60db0582014-09-07 18:57:58 +00002847
Chandler Carruthdf5747a2015-01-21 11:38:17 +00002848 SmallVector<Instruction*, 128> InstrsForInstCombineWorklist;
2849 DenseMap<ConstantExpr*, Constant*> FoldedConstants;
Jakub Staszakcfc46f82012-05-06 13:52:31 +00002850
Chandler Carruthdf5747a2015-01-21 11:38:17 +00002851 do {
2852 BB = Worklist.pop_back_val();
Jakub Staszakcfc46f82012-05-06 13:52:31 +00002853
Chandler Carruthdf5747a2015-01-21 11:38:17 +00002854 // We have now visited this block! If we've already been here, ignore it.
2855 if (!Visited.insert(BB).second)
2856 continue;
Chris Lattner960a5432007-03-03 02:04:50 +00002857
Chandler Carruthdf5747a2015-01-21 11:38:17 +00002858 for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
2859 Instruction *Inst = BBI++;
Devang Patelaad34d82011-03-17 22:18:16 +00002860
Chandler Carruthdf5747a2015-01-21 11:38:17 +00002861 // DCE instruction if trivially dead.
2862 if (isInstructionTriviallyDead(Inst, TLI)) {
2863 ++NumDeadInst;
2864 DEBUG(dbgs() << "IC: DCE: " << *Inst << '\n');
2865 Inst->eraseFromParent();
2866 continue;
2867 }
Jakub Staszakcfc46f82012-05-06 13:52:31 +00002868
Chandler Carruthdf5747a2015-01-21 11:38:17 +00002869 // ConstantProp instruction if trivially constant.
David Majnemer7fddecc2015-06-17 20:52:32 +00002870 if (!Inst->use_empty() &&
2871 (Inst->getNumOperands() == 0 || isa<Constant>(Inst->getOperand(0))))
Chandler Carruthdf5747a2015-01-21 11:38:17 +00002872 if (Constant *C = ConstantFoldInstruction(Inst, DL, TLI)) {
2873 DEBUG(dbgs() << "IC: ConstFold to: " << *C << " from: "
2874 << *Inst << '\n');
2875 Inst->replaceAllUsesWith(C);
2876 ++NumConstProp;
2877 Inst->eraseFromParent();
2878 continue;
2879 }
2880
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002881 // See if we can constant fold its operands.
2882 for (User::op_iterator i = Inst->op_begin(), e = Inst->op_end(); i != e;
2883 ++i) {
2884 ConstantExpr *CE = dyn_cast<ConstantExpr>(i);
2885 if (CE == nullptr)
2886 continue;
Chandler Carruthdf5747a2015-01-21 11:38:17 +00002887
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002888 Constant *&FoldRes = FoldedConstants[CE];
2889 if (!FoldRes)
2890 FoldRes = ConstantFoldConstantExpression(CE, DL, TLI);
2891 if (!FoldRes)
2892 FoldRes = CE;
Chandler Carruthdf5747a2015-01-21 11:38:17 +00002893
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002894 if (FoldRes != CE) {
2895 *i = FoldRes;
2896 MadeIRChange = true;
Chandler Carruthdf5747a2015-01-21 11:38:17 +00002897 }
2898 }
2899
2900 InstrsForInstCombineWorklist.push_back(Inst);
2901 }
2902
2903 // Recursively visit successors. If this is a branch or switch on a
2904 // constant, only visit the reachable successor.
2905 TerminatorInst *TI = BB->getTerminator();
2906 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
2907 if (BI->isConditional() && isa<ConstantInt>(BI->getCondition())) {
2908 bool CondVal = cast<ConstantInt>(BI->getCondition())->getZExtValue();
2909 BasicBlock *ReachableBB = BI->getSuccessor(!CondVal);
2910 Worklist.push_back(ReachableBB);
2911 continue;
2912 }
2913 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
2914 if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
2915 // See if this is an explicit destination.
2916 for (SwitchInst::CaseIt i = SI->case_begin(), e = SI->case_end();
2917 i != e; ++i)
2918 if (i.getCaseValue() == Cond) {
2919 BasicBlock *ReachableBB = i.getCaseSuccessor();
2920 Worklist.push_back(ReachableBB);
2921 continue;
2922 }
2923
2924 // Otherwise it is the default destination.
2925 Worklist.push_back(SI->getDefaultDest());
2926 continue;
2927 }
2928 }
2929
Pete Cooperebcd7482015-08-06 20:22:46 +00002930 for (BasicBlock *SuccBB : TI->successors())
2931 Worklist.push_back(SuccBB);
Chandler Carruthdf5747a2015-01-21 11:38:17 +00002932 } while (!Worklist.empty());
2933
2934 // Once we've found all of the instructions to add to instcombine's worklist,
2935 // add them in reverse order. This way instcombine will visit from the top
2936 // of the function down. This jives well with the way that it adds all uses
2937 // of instructions to the worklist after doing a transformation, thus avoiding
2938 // some N^2 behavior in pathological cases.
2939 ICWorklist.AddInitialGroup(&InstrsForInstCombineWorklist[0],
2940 InstrsForInstCombineWorklist.size());
2941
2942 return MadeIRChange;
2943}
2944
2945/// \brief Populate the IC worklist from a function, and prune any dead basic
2946/// blocks discovered in the process.
2947///
2948/// This also does basic constant propagation and other forward fixing to make
2949/// the combiner itself run much faster.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002950static bool prepareICWorklistFromFunction(Function &F, const DataLayout &DL,
Chandler Carruthdf5747a2015-01-21 11:38:17 +00002951 TargetLibraryInfo *TLI,
2952 InstCombineWorklist &ICWorklist) {
2953 bool MadeIRChange = false;
2954
2955 // Do a depth-first traversal of the function, populate the worklist with
2956 // the reachable instructions. Ignore blocks that are not reachable. Keep
2957 // track of which blocks we visit.
2958 SmallPtrSet<BasicBlock *, 64> Visited;
2959 MadeIRChange |=
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002960 AddReachableCodeToWorklist(F.begin(), DL, Visited, ICWorklist, TLI);
Chandler Carruthdf5747a2015-01-21 11:38:17 +00002961
2962 // Do a quick scan over the function. If we find any blocks that are
2963 // unreachable, remove any instructions inside of them. This prevents
2964 // the instcombine code from having to deal with some bad special cases.
2965 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
2966 if (Visited.count(BB))
2967 continue;
2968
2969 // Delete the instructions backwards, as it has a reduced likelihood of
2970 // having to update as many def-use and use-def chains.
2971 Instruction *EndInst = BB->getTerminator(); // Last not to be deleted.
2972 while (EndInst != BB->begin()) {
2973 // Delete the next to last instruction.
2974 BasicBlock::iterator I = EndInst;
2975 Instruction *Inst = --I;
2976 if (!Inst->use_empty())
2977 Inst->replaceAllUsesWith(UndefValue::get(Inst->getType()));
David Majnemer60c994b2015-08-08 03:51:49 +00002978 if (Inst->isEHPad()) {
Chandler Carruthdf5747a2015-01-21 11:38:17 +00002979 EndInst = Inst;
2980 continue;
2981 }
2982 if (!isa<DbgInfoIntrinsic>(Inst)) {
2983 ++NumDeadInst;
2984 MadeIRChange = true;
2985 }
2986 Inst->eraseFromParent();
2987 }
2988 }
2989
2990 return MadeIRChange;
Chris Lattner960a5432007-03-03 02:04:50 +00002991}
2992
Mehdi Amini46a43552015-03-04 18:43:29 +00002993static bool
2994combineInstructionsOverFunction(Function &F, InstCombineWorklist &Worklist,
Bjorn Steinbrink83505342015-07-10 06:55:49 +00002995 AliasAnalysis *AA, AssumptionCache &AC,
2996 TargetLibraryInfo &TLI, DominatorTree &DT,
2997 LoopInfo *LI = nullptr) {
Chandler Carruth83ba2692015-01-24 04:19:17 +00002998 // Minimizing size?
Duncan P. N. Exon Smith2c79ad92015-02-14 01:11:29 +00002999 bool MinimizeSize = F.hasFnAttribute(Attribute::MinSize);
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003000 auto &DL = F.getParent()->getDataLayout();
Chandler Carruth83ba2692015-01-24 04:19:17 +00003001
3002 /// Builder - This is an IRBuilder that automatically inserts new
3003 /// instructions into the worklist when they are created.
3004 IRBuilder<true, TargetFolder, InstCombineIRInserter> Builder(
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003005 F.getContext(), TargetFolder(DL), InstCombineIRInserter(Worklist, &AC));
Chandler Carruth83ba2692015-01-24 04:19:17 +00003006
3007 // Lower dbg.declare intrinsics otherwise their value may be clobbered
3008 // by instcombiner.
3009 bool DbgDeclaresChanged = LowerDbgDeclare(F);
3010
3011 // Iterate while there is work to do.
3012 int Iteration = 0;
3013 for (;;) {
3014 ++Iteration;
3015 DEBUG(dbgs() << "\n\nINSTCOMBINE ITERATION #" << Iteration << " on "
3016 << F.getName() << "\n");
3017
3018 bool Changed = false;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003019 if (prepareICWorklistFromFunction(F, DL, &TLI, Worklist))
Chandler Carruth83ba2692015-01-24 04:19:17 +00003020 Changed = true;
3021
Bjorn Steinbrink83505342015-07-10 06:55:49 +00003022 InstCombiner IC(Worklist, &Builder, MinimizeSize,
3023 AA, &AC, &TLI, &DT, DL, LI);
Chandler Carruth83ba2692015-01-24 04:19:17 +00003024 if (IC.run())
3025 Changed = true;
3026
3027 if (!Changed)
3028 break;
3029 }
3030
3031 return DbgDeclaresChanged || Iteration > 1;
3032}
3033
3034PreservedAnalyses InstCombinePass::run(Function &F,
3035 AnalysisManager<Function> *AM) {
Chandler Carruth83ba2692015-01-24 04:19:17 +00003036 auto &AC = AM->getResult<AssumptionAnalysis>(F);
3037 auto &DT = AM->getResult<DominatorTreeAnalysis>(F);
3038 auto &TLI = AM->getResult<TargetLibraryAnalysis>(F);
3039
3040 auto *LI = AM->getCachedResult<LoopAnalysis>(F);
3041
Bjorn Steinbrink83505342015-07-10 06:55:49 +00003042 // FIXME: The AliasAnalysis is not yet supported in the new pass manager
3043 if (!combineInstructionsOverFunction(F, Worklist, nullptr, AC, TLI, DT, LI))
Chandler Carruth83ba2692015-01-24 04:19:17 +00003044 // No changes, all analyses are preserved.
3045 return PreservedAnalyses::all();
3046
3047 // Mark all the analyses that instcombine updates as preserved.
3048 // FIXME: Need a way to preserve CFG analyses here!
3049 PreservedAnalyses PA;
3050 PA.preserve<DominatorTreeAnalysis>();
3051 return PA;
3052}
3053
Chandler Carruth1edb9d62015-01-20 22:44:35 +00003054namespace {
3055/// \brief The legacy pass manager's instcombine pass.
3056///
3057/// This is a basic whole-function wrapper around the instcombine utility. It
3058/// will try to combine all instructions in the function.
3059class InstructionCombiningPass : public FunctionPass {
Chandler Carruthdf5747a2015-01-21 11:38:17 +00003060 InstCombineWorklist Worklist;
Chandler Carruth1edb9d62015-01-20 22:44:35 +00003061
3062public:
3063 static char ID; // Pass identification, replacement for typeid
3064
3065 InstructionCombiningPass() : FunctionPass(ID) {
3066 initializeInstructionCombiningPassPass(*PassRegistry::getPassRegistry());
3067 }
3068
3069 void getAnalysisUsage(AnalysisUsage &AU) const override;
3070 bool runOnFunction(Function &F) override;
3071};
Alexander Kornienkof00654e2015-06-23 09:49:53 +00003072}
Chandler Carruth1edb9d62015-01-20 22:44:35 +00003073
3074void InstructionCombiningPass::getAnalysisUsage(AnalysisUsage &AU) const {
3075 AU.setPreservesCFG();
Bjorn Steinbrink83505342015-07-10 06:55:49 +00003076 AU.addRequired<AliasAnalysis>();
Chandler Carruth1edb9d62015-01-20 22:44:35 +00003077 AU.addRequired<AssumptionCacheTracker>();
3078 AU.addRequired<TargetLibraryInfoWrapperPass>();
3079 AU.addRequired<DominatorTreeWrapperPass>();
3080 AU.addPreserved<DominatorTreeWrapperPass>();
3081}
3082
3083bool InstructionCombiningPass::runOnFunction(Function &F) {
3084 if (skipOptnoneFunction(F))
3085 return false;
3086
Chandler Carruthdf5747a2015-01-21 11:38:17 +00003087 // Required analyses.
Bjorn Steinbrink83505342015-07-10 06:55:49 +00003088 auto AA = &getAnalysis<AliasAnalysis>();
Chandler Carruth1edb9d62015-01-20 22:44:35 +00003089 auto &AC = getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
Chandler Carruth1edb9d62015-01-20 22:44:35 +00003090 auto &TLI = getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
3091 auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
Chandler Carruthdf5747a2015-01-21 11:38:17 +00003092
3093 // Optional analyses.
Chandler Carruth1edb9d62015-01-20 22:44:35 +00003094 auto *LIWP = getAnalysisIfAvailable<LoopInfoWrapperPass>();
3095 auto *LI = LIWP ? &LIWP->getLoopInfo() : nullptr;
3096
Bjorn Steinbrink83505342015-07-10 06:55:49 +00003097 return combineInstructionsOverFunction(F, Worklist, AA, AC, TLI, DT, LI);
Chandler Carruth1edb9d62015-01-20 22:44:35 +00003098}
3099
3100char InstructionCombiningPass::ID = 0;
3101INITIALIZE_PASS_BEGIN(InstructionCombiningPass, "instcombine",
3102 "Combine redundant instructions", false, false)
3103INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
3104INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
3105INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
Bjorn Steinbrink83505342015-07-10 06:55:49 +00003106INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
Chandler Carruth1edb9d62015-01-20 22:44:35 +00003107INITIALIZE_PASS_END(InstructionCombiningPass, "instcombine",
3108 "Combine redundant instructions", false, false)
3109
3110// Initialization Routines
3111void llvm::initializeInstCombine(PassRegistry &Registry) {
3112 initializeInstructionCombiningPassPass(Registry);
3113}
3114
3115void LLVMInitializeInstCombine(LLVMPassRegistryRef R) {
3116 initializeInstructionCombiningPassPass(*unwrap(R));
3117}
3118
Brian Gaeke38b79e82004-07-27 17:43:21 +00003119FunctionPass *llvm::createInstructionCombiningPass() {
Chandler Carruth1edb9d62015-01-20 22:44:35 +00003120 return new InstructionCombiningPass();
Chris Lattner04805fa2002-02-26 21:46:54 +00003121}