blob: 1b95e9334c12babf5bf6fc8fb46aa5da5f0411c0 [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 Carruthac072702016-02-19 03:12:14 +000042#include "llvm/Analysis/AliasAnalysis.h"
Chandler Carruth66b31302015-01-04 12:03:27 +000043#include "llvm/Analysis/AssumptionCache.h"
Chandler Carruthac072702016-02-19 03:12:14 +000044#include "llvm/Analysis/BasicAliasAnalysis.h"
David Majnemer7e2b9882014-11-03 21:55:12 +000045#include "llvm/Analysis/CFG.h"
Chris Lattner024f4ab2007-01-30 23:46:24 +000046#include "llvm/Analysis/ConstantFolding.h"
David Majnemer70497c62015-12-02 23:06:39 +000047#include "llvm/Analysis/EHPersonalities.h"
Chandler Carruth7b560d42015-09-09 17:55:00 +000048#include "llvm/Analysis/GlobalsModRef.h"
Chris Lattnerc1f19072009-11-09 23:28:39 +000049#include "llvm/Analysis/InstructionSimplify.h"
David Majnemer7e2b9882014-11-03 21:55:12 +000050#include "llvm/Analysis/LoopInfo.h"
Victor Hernandezf390e042009-10-27 20:05:49 +000051#include "llvm/Analysis/MemoryBuiltins.h"
Chandler Carruth83ba2692015-01-24 04:19:17 +000052#include "llvm/Analysis/TargetLibraryInfo.h"
Sanjay Patel58814442014-07-09 16:34:54 +000053#include "llvm/Analysis/ValueTracking.h"
Chandler Carruth1305dc32014-03-04 11:45:46 +000054#include "llvm/IR/CFG.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000055#include "llvm/IR/DataLayout.h"
Hal Finkel60db0582014-09-07 18:57:58 +000056#include "llvm/IR/Dominators.h"
Chandler Carruth03eb0de2014-03-04 10:40:04 +000057#include "llvm/IR/GetElementPtrTypeIterator.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000058#include "llvm/IR/IntrinsicInst.h"
Chandler Carruth820a9082014-03-04 11:08:18 +000059#include "llvm/IR/PatternMatch.h"
Chandler Carruth4220e9c2014-03-04 11:17:44 +000060#include "llvm/IR/ValueHandle.h"
Meador Inge193e0352012-11-13 04:16:17 +000061#include "llvm/Support/CommandLine.h"
Chris Lattner39c98bb2004-12-08 23:43:58 +000062#include "llvm/Support/Debug.h"
Benjamin Kramer799003b2015-03-23 19:32:43 +000063#include "llvm/Support/raw_ostream.h"
Chandler Carruth83ba2692015-01-24 04:19:17 +000064#include "llvm/Transforms/Scalar.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000065#include "llvm/Transforms/Utils/Local.h"
Chris Lattner053c0932002-05-14 15:24:07 +000066#include <algorithm>
Torok Edwinab207842008-04-20 08:33:11 +000067#include <climits>
Chris Lattner8427bff2003-12-07 01:24:23 +000068using namespace llvm;
Chris Lattnerd4252a72004-07-30 07:50:03 +000069using namespace llvm::PatternMatch;
Brian Gaeke960707c2003-11-11 22:41:34 +000070
Chandler Carruth964daaa2014-04-22 02:55:47 +000071#define DEBUG_TYPE "instcombine"
72
Chris Lattner79a42ac2006-12-19 21:40:18 +000073STATISTIC(NumCombined , "Number of insts combined");
74STATISTIC(NumConstProp, "Number of constant folds");
75STATISTIC(NumDeadInst , "Number of dead inst eliminated");
Chris Lattner79a42ac2006-12-19 21:40:18 +000076STATISTIC(NumSunkInst , "Number of instructions sunk");
Duncan Sandsfbb9ac32010-12-22 13:36:08 +000077STATISTIC(NumExpand, "Number of expansions");
Duncan Sands3547d2e2010-12-22 09:40:51 +000078STATISTIC(NumFactor , "Number of factorizations");
79STATISTIC(NumReassoc , "Number of reassociations");
Chris Lattnerbf3a0992002-10-01 22:38:41 +000080
Nuno Lopesa2f6cec2012-05-22 17:19:09 +000081Value *InstCombiner::EmitGEPOffset(User *GEP) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +000082 return llvm::EmitGEPOffset(Builder, DL, GEP);
Nuno Lopesa2f6cec2012-05-22 17:19:09 +000083}
84
Sanjay Patel55dcd402015-09-21 16:09:37 +000085/// Return true if it is desirable to convert an integer computation from a
86/// given bit width to a new bit width.
Sanjay Patel84dca492015-09-21 15:33:26 +000087/// We don't want to convert from a legal to an illegal type for example or from
88/// a smaller to a larger illegal type.
Sanjay Patel55dcd402015-09-21 16:09:37 +000089bool InstCombiner::ShouldChangeType(unsigned FromWidth,
90 unsigned ToWidth) const {
Mehdi Aminia28d91d2015-03-10 02:37:25 +000091 bool FromLegal = DL.isLegalInteger(FromWidth);
92 bool ToLegal = DL.isLegalInteger(ToWidth);
Jakub Staszakcfc46f82012-05-06 13:52:31 +000093
Chris Lattner1559bed2009-11-10 07:23:37 +000094 // If this is a legal integer from type, and the result would be an illegal
95 // type, don't do the transformation.
96 if (FromLegal && !ToLegal)
97 return false;
Jakub Staszakcfc46f82012-05-06 13:52:31 +000098
Chris Lattner1559bed2009-11-10 07:23:37 +000099 // Otherwise, if both are illegal, do not increase the size of the result. We
100 // do allow things like i160 -> i64, but not i64 -> i160.
101 if (!FromLegal && !ToLegal && ToWidth > FromWidth)
102 return false;
Jakub Staszakcfc46f82012-05-06 13:52:31 +0000103
Chris Lattner1559bed2009-11-10 07:23:37 +0000104 return true;
105}
106
Sanjay Patel55dcd402015-09-21 16:09:37 +0000107/// Return true if it is desirable to convert a computation from 'From' to 'To'.
108/// We don't want to convert from a legal to an illegal type for example or from
109/// a smaller to a larger illegal type.
110bool InstCombiner::ShouldChangeType(Type *From, Type *To) const {
111 assert(From->isIntegerTy() && To->isIntegerTy());
112
113 unsigned FromWidth = From->getPrimitiveSizeInBits();
114 unsigned ToWidth = To->getPrimitiveSizeInBits();
115 return ShouldChangeType(FromWidth, ToWidth);
116}
117
Nick Lewyckyde492782011-08-14 01:45:19 +0000118// Return true, if No Signed Wrap should be maintained for I.
119// The No Signed Wrap flag can be kept if the operation "B (I.getOpcode) C",
120// where both B and C should be ConstantInts, results in a constant that does
121// not overflow. This function only handles the Add and Sub opcodes. For
122// all other opcodes, the function conservatively returns false.
123static bool MaintainNoSignedWrap(BinaryOperator &I, Value *B, Value *C) {
124 OverflowingBinaryOperator *OBO = dyn_cast<OverflowingBinaryOperator>(&I);
125 if (!OBO || !OBO->hasNoSignedWrap()) {
126 return false;
127 }
128
129 // We reason about Add and Sub Only.
130 Instruction::BinaryOps Opcode = I.getOpcode();
Jakub Staszakcfc46f82012-05-06 13:52:31 +0000131 if (Opcode != Instruction::Add &&
Nick Lewyckyde492782011-08-14 01:45:19 +0000132 Opcode != Instruction::Sub) {
133 return false;
134 }
135
136 ConstantInt *CB = dyn_cast<ConstantInt>(B);
137 ConstantInt *CC = dyn_cast<ConstantInt>(C);
138
139 if (!CB || !CC) {
140 return false;
141 }
142
143 const APInt &BVal = CB->getValue();
144 const APInt &CVal = CC->getValue();
145 bool Overflow = false;
146
147 if (Opcode == Instruction::Add) {
148 BVal.sadd_ov(CVal, Overflow);
149 } else {
150 BVal.ssub_ov(CVal, Overflow);
151 }
152
153 return !Overflow;
154}
155
Michael Ilseman1dd6f2a2013-02-07 01:40:15 +0000156/// Conservatively clears subclassOptionalData after a reassociation or
157/// commutation. We preserve fast-math flags when applicable as they can be
158/// preserved.
159static void ClearSubclassDataAfterReassociation(BinaryOperator &I) {
160 FPMathOperator *FPMO = dyn_cast<FPMathOperator>(&I);
161 if (!FPMO) {
162 I.clearSubclassOptionalData();
163 return;
164 }
165
166 FastMathFlags FMF = I.getFastMathFlags();
167 I.clearSubclassOptionalData();
168 I.setFastMathFlags(FMF);
169}
170
Sanjay Patel84dca492015-09-21 15:33:26 +0000171/// This performs a few simplifications for operators that are associative or
172/// commutative:
173///
174/// Commutative operators:
175///
176/// 1. Order operands such that they are listed from right (least complex) to
177/// left (most complex). This puts constants before unary operators before
178/// binary operators.
179///
180/// Associative operators:
181///
182/// 2. Transform: "(A op B) op C" ==> "A op (B op C)" if "B op C" simplifies.
183/// 3. Transform: "A op (B op C)" ==> "(A op B) op C" if "A op B" simplifies.
184///
185/// Associative and commutative operators:
186///
187/// 4. Transform: "(A op B) op C" ==> "(C op A) op B" if "C op A" simplifies.
188/// 5. Transform: "A op (B op C)" ==> "B op (C op A)" if "C op A" simplifies.
189/// 6. Transform: "(A op C1) op (B op C2)" ==> "(A op B) op (C1 op C2)"
190/// if C1 and C2 are constants.
Duncan Sands641baf12010-11-13 15:10:37 +0000191bool InstCombiner::SimplifyAssociativeOrCommutative(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000192 Instruction::BinaryOps Opcode = I.getOpcode();
Duncan Sands641baf12010-11-13 15:10:37 +0000193 bool Changed = false;
Chris Lattner7fb29e12003-03-11 00:12:48 +0000194
Duncan Sands641baf12010-11-13 15:10:37 +0000195 do {
196 // Order operands such that they are listed from right (least complex) to
197 // left (most complex). This puts constants before unary operators before
198 // binary operators.
199 if (I.isCommutative() && getComplexity(I.getOperand(0)) <
200 getComplexity(I.getOperand(1)))
201 Changed = !I.swapOperands();
202
203 BinaryOperator *Op0 = dyn_cast<BinaryOperator>(I.getOperand(0));
204 BinaryOperator *Op1 = dyn_cast<BinaryOperator>(I.getOperand(1));
205
206 if (I.isAssociative()) {
207 // Transform: "(A op B) op C" ==> "A op (B op C)" if "B op C" simplifies.
208 if (Op0 && Op0->getOpcode() == Opcode) {
209 Value *A = Op0->getOperand(0);
210 Value *B = Op0->getOperand(1);
211 Value *C = I.getOperand(1);
212
213 // Does "B op C" simplify?
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000214 if (Value *V = SimplifyBinOp(Opcode, B, C, DL)) {
Duncan Sands641baf12010-11-13 15:10:37 +0000215 // It simplifies to V. Form "A op V".
216 I.setOperand(0, A);
217 I.setOperand(1, V);
Dan Gohmanc6f0bda2011-02-02 02:05:46 +0000218 // Conservatively clear the optional flags, since they may not be
219 // preserved by the reassociation.
Nick Lewyckyae13df62011-08-14 03:41:33 +0000220 if (MaintainNoSignedWrap(I, B, C) &&
Bill Wendlingea6397f2012-07-19 00:11:40 +0000221 (!Op0 || (isa<BinaryOperator>(Op0) && Op0->hasNoSignedWrap()))) {
Nick Lewyckyae13df62011-08-14 03:41:33 +0000222 // Note: this is only valid because SimplifyBinOp doesn't look at
223 // the operands to Op0.
Nick Lewyckyde492782011-08-14 01:45:19 +0000224 I.clearSubclassOptionalData();
225 I.setHasNoSignedWrap(true);
226 } else {
Michael Ilseman1dd6f2a2013-02-07 01:40:15 +0000227 ClearSubclassDataAfterReassociation(I);
Nick Lewyckyde492782011-08-14 01:45:19 +0000228 }
Jakub Staszakcfc46f82012-05-06 13:52:31 +0000229
Duncan Sands641baf12010-11-13 15:10:37 +0000230 Changed = true;
Duncan Sands3547d2e2010-12-22 09:40:51 +0000231 ++NumReassoc;
Duncan Sands641baf12010-11-13 15:10:37 +0000232 continue;
Misha Brukmanb1c93172005-04-21 23:48:37 +0000233 }
Duncan Sands641baf12010-11-13 15:10:37 +0000234 }
235
236 // Transform: "A op (B op C)" ==> "(A op B) op C" if "A op B" simplifies.
237 if (Op1 && Op1->getOpcode() == Opcode) {
238 Value *A = I.getOperand(0);
239 Value *B = Op1->getOperand(0);
240 Value *C = Op1->getOperand(1);
241
242 // Does "A op B" simplify?
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000243 if (Value *V = SimplifyBinOp(Opcode, A, B, DL)) {
Duncan Sands641baf12010-11-13 15:10:37 +0000244 // It simplifies to V. Form "V op C".
245 I.setOperand(0, V);
246 I.setOperand(1, C);
Dan Gohmanc6f0bda2011-02-02 02:05:46 +0000247 // Conservatively clear the optional flags, since they may not be
248 // preserved by the reassociation.
Michael Ilseman1dd6f2a2013-02-07 01:40:15 +0000249 ClearSubclassDataAfterReassociation(I);
Duncan Sands641baf12010-11-13 15:10:37 +0000250 Changed = true;
Duncan Sands3547d2e2010-12-22 09:40:51 +0000251 ++NumReassoc;
Duncan Sands641baf12010-11-13 15:10:37 +0000252 continue;
253 }
254 }
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000255 }
Duncan Sands641baf12010-11-13 15:10:37 +0000256
257 if (I.isAssociative() && I.isCommutative()) {
258 // Transform: "(A op B) op C" ==> "(C op A) op B" if "C op A" simplifies.
259 if (Op0 && Op0->getOpcode() == Opcode) {
260 Value *A = Op0->getOperand(0);
261 Value *B = Op0->getOperand(1);
262 Value *C = I.getOperand(1);
263
264 // Does "C op A" simplify?
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000265 if (Value *V = SimplifyBinOp(Opcode, C, A, DL)) {
Duncan Sands641baf12010-11-13 15:10:37 +0000266 // It simplifies to V. Form "V op B".
267 I.setOperand(0, V);
268 I.setOperand(1, B);
Dan Gohmanc6f0bda2011-02-02 02:05:46 +0000269 // Conservatively clear the optional flags, since they may not be
270 // preserved by the reassociation.
Michael Ilseman1dd6f2a2013-02-07 01:40:15 +0000271 ClearSubclassDataAfterReassociation(I);
Duncan Sands641baf12010-11-13 15:10:37 +0000272 Changed = true;
Duncan Sands3547d2e2010-12-22 09:40:51 +0000273 ++NumReassoc;
Duncan Sands641baf12010-11-13 15:10:37 +0000274 continue;
275 }
276 }
277
278 // Transform: "A op (B op C)" ==> "B op (C op A)" if "C op A" simplifies.
279 if (Op1 && Op1->getOpcode() == Opcode) {
280 Value *A = I.getOperand(0);
281 Value *B = Op1->getOperand(0);
282 Value *C = Op1->getOperand(1);
283
284 // Does "C op A" simplify?
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000285 if (Value *V = SimplifyBinOp(Opcode, C, A, DL)) {
Duncan Sands641baf12010-11-13 15:10:37 +0000286 // It simplifies to V. Form "B op V".
287 I.setOperand(0, B);
288 I.setOperand(1, V);
Dan Gohmanc6f0bda2011-02-02 02:05:46 +0000289 // Conservatively clear the optional flags, since they may not be
290 // preserved by the reassociation.
Michael Ilseman1dd6f2a2013-02-07 01:40:15 +0000291 ClearSubclassDataAfterReassociation(I);
Duncan Sands641baf12010-11-13 15:10:37 +0000292 Changed = true;
Duncan Sands3547d2e2010-12-22 09:40:51 +0000293 ++NumReassoc;
Duncan Sands641baf12010-11-13 15:10:37 +0000294 continue;
295 }
296 }
297
298 // Transform: "(A op C1) op (B op C2)" ==> "(A op B) op (C1 op C2)"
299 // if C1 and C2 are constants.
300 if (Op0 && Op1 &&
301 Op0->getOpcode() == Opcode && Op1->getOpcode() == Opcode &&
302 isa<Constant>(Op0->getOperand(1)) &&
303 isa<Constant>(Op1->getOperand(1)) &&
304 Op0->hasOneUse() && Op1->hasOneUse()) {
305 Value *A = Op0->getOperand(0);
306 Constant *C1 = cast<Constant>(Op0->getOperand(1));
307 Value *B = Op1->getOperand(0);
308 Constant *C2 = cast<Constant>(Op1->getOperand(1));
309
310 Constant *Folded = ConstantExpr::get(Opcode, C1, C2);
Nick Lewyckyde492782011-08-14 01:45:19 +0000311 BinaryOperator *New = BinaryOperator::Create(Opcode, A, B);
Owen Anderson1664dc82014-01-20 07:44:53 +0000312 if (isa<FPMathOperator>(New)) {
313 FastMathFlags Flags = I.getFastMathFlags();
314 Flags &= Op0->getFastMathFlags();
315 Flags &= Op1->getFastMathFlags();
316 New->setFastMathFlags(Flags);
317 }
Eli Friedman35211c62011-05-27 00:19:40 +0000318 InsertNewInstWith(New, I);
Eli Friedman41e509a2011-05-18 23:58:37 +0000319 New->takeName(Op1);
Duncan Sands641baf12010-11-13 15:10:37 +0000320 I.setOperand(0, New);
321 I.setOperand(1, Folded);
Dan Gohmanc6f0bda2011-02-02 02:05:46 +0000322 // Conservatively clear the optional flags, since they may not be
323 // preserved by the reassociation.
Michael Ilseman1dd6f2a2013-02-07 01:40:15 +0000324 ClearSubclassDataAfterReassociation(I);
Nick Lewyckyde492782011-08-14 01:45:19 +0000325
Duncan Sands641baf12010-11-13 15:10:37 +0000326 Changed = true;
327 continue;
328 }
329 }
330
331 // No further simplifications.
332 return Changed;
333 } while (1);
Chris Lattner260ab202002-04-18 17:39:14 +0000334}
Chris Lattnerca081252001-12-14 16:52:21 +0000335
Sanjay Patel84dca492015-09-21 15:33:26 +0000336/// Return whether "X LOp (Y ROp Z)" is always equal to
Duncan Sands22df7412010-11-23 15:25:34 +0000337/// "(X LOp Y) ROp (X LOp Z)".
Duncan Sandsadc7771f2010-11-23 14:23:47 +0000338static bool LeftDistributesOverRight(Instruction::BinaryOps LOp,
339 Instruction::BinaryOps ROp) {
340 switch (LOp) {
341 default:
342 return false;
343
344 case Instruction::And:
345 // And distributes over Or and Xor.
346 switch (ROp) {
347 default:
348 return false;
349 case Instruction::Or:
350 case Instruction::Xor:
351 return true;
352 }
353
354 case Instruction::Mul:
355 // Multiplication distributes over addition and subtraction.
356 switch (ROp) {
357 default:
358 return false;
359 case Instruction::Add:
360 case Instruction::Sub:
361 return true;
362 }
363
364 case Instruction::Or:
365 // Or distributes over And.
366 switch (ROp) {
367 default:
368 return false;
369 case Instruction::And:
370 return true;
371 }
372 }
373}
374
Sanjay Patel84dca492015-09-21 15:33:26 +0000375/// Return whether "(X LOp Y) ROp Z" is always equal to
Duncan Sandsadc7771f2010-11-23 14:23:47 +0000376/// "(X ROp Z) LOp (Y ROp Z)".
377static bool RightDistributesOverLeft(Instruction::BinaryOps LOp,
378 Instruction::BinaryOps ROp) {
379 if (Instruction::isCommutative(ROp))
380 return LeftDistributesOverRight(ROp, LOp);
Dinesh Dwivedi4919bbe2014-08-26 08:53:32 +0000381
382 switch (LOp) {
383 default:
384 return false;
385 // (X >> Z) & (Y >> Z) -> (X&Y) >> Z for all shifts.
386 // (X >> Z) | (Y >> Z) -> (X|Y) >> Z for all shifts.
387 // (X >> Z) ^ (Y >> Z) -> (X^Y) >> Z for all shifts.
388 case Instruction::And:
389 case Instruction::Or:
390 case Instruction::Xor:
391 switch (ROp) {
392 default:
393 return false;
394 case Instruction::Shl:
395 case Instruction::LShr:
396 case Instruction::AShr:
397 return true;
398 }
399 }
Duncan Sandsadc7771f2010-11-23 14:23:47 +0000400 // TODO: It would be nice to handle division, aka "(X + Y)/Z = X/Z + Y/Z",
401 // but this requires knowing that the addition does not overflow and other
402 // such subtleties.
403 return false;
404}
405
Dinesh Dwivedib62e52e2014-06-19 08:29:18 +0000406/// This function returns identity value for given opcode, which can be used to
407/// factor patterns like (X * 2) + X ==> (X * 2) + (X * 1) ==> X * (2 + 1).
408static Value *getIdentityValue(Instruction::BinaryOps OpCode, Value *V) {
409 if (isa<Constant>(V))
410 return nullptr;
411
412 if (OpCode == Instruction::Mul)
413 return ConstantInt::get(V->getType(), 1);
414
415 // TODO: We can handle other cases e.g. Instruction::And, Instruction::Or etc.
416
417 return nullptr;
418}
419
420/// This function factors binary ops which can be combined using distributive
Dinesh Dwivedi4919bbe2014-08-26 08:53:32 +0000421/// laws. This function tries to transform 'Op' based TopLevelOpcode to enable
422/// factorization e.g for ADD(SHL(X , 2), MUL(X, 5)), When this function called
423/// with TopLevelOpcode == Instruction::Add and Op = SHL(X, 2), transforms
424/// SHL(X, 2) to MUL(X, 4) i.e. returns Instruction::Mul with LHS set to 'X' and
425/// RHS to 4.
Benjamin Kramer6cbe6702014-07-07 14:47:51 +0000426static Instruction::BinaryOps
Dinesh Dwivedi4919bbe2014-08-26 08:53:32 +0000427getBinOpsForFactorization(Instruction::BinaryOps TopLevelOpcode,
428 BinaryOperator *Op, Value *&LHS, Value *&RHS) {
Dinesh Dwivedib62e52e2014-06-19 08:29:18 +0000429 if (!Op)
430 return Instruction::BinaryOpsEnd;
431
Dinesh Dwivedi4919bbe2014-08-26 08:53:32 +0000432 LHS = Op->getOperand(0);
433 RHS = Op->getOperand(1);
434
435 switch (TopLevelOpcode) {
436 default:
437 return Op->getOpcode();
438
439 case Instruction::Add:
440 case Instruction::Sub:
441 if (Op->getOpcode() == Instruction::Shl) {
442 if (Constant *CST = dyn_cast<Constant>(Op->getOperand(1))) {
443 // The multiplier is really 1 << CST.
444 RHS = ConstantExpr::getShl(ConstantInt::get(Op->getType(), 1), CST);
445 return Instruction::Mul;
446 }
Dinesh Dwivedib62e52e2014-06-19 08:29:18 +0000447 }
Dinesh Dwivedi4919bbe2014-08-26 08:53:32 +0000448 return Op->getOpcode();
Dinesh Dwivedib62e52e2014-06-19 08:29:18 +0000449 }
450
451 // TODO: We can add other conversions e.g. shr => div etc.
Dinesh Dwivedib62e52e2014-06-19 08:29:18 +0000452}
453
454/// This tries to simplify binary operations by factorizing out common terms
455/// (e. g. "(A*B)+(A*C)" -> "A*(B+C)").
456static Value *tryFactorization(InstCombiner::BuilderTy *Builder,
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000457 const DataLayout &DL, BinaryOperator &I,
Dinesh Dwivedib62e52e2014-06-19 08:29:18 +0000458 Instruction::BinaryOps InnerOpcode, Value *A,
459 Value *B, Value *C, Value *D) {
460
461 // If any of A, B, C, D are null, we can not factor I, return early.
462 // Checking A and C should be enough.
463 if (!A || !C || !B || !D)
464 return nullptr;
465
David Majnemer4c3753c2015-05-22 23:02:11 +0000466 Value *V = nullptr;
Dinesh Dwivedib62e52e2014-06-19 08:29:18 +0000467 Value *SimplifiedInst = nullptr;
468 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
469 Instruction::BinaryOps TopLevelOpcode = I.getOpcode();
470
471 // Does "X op' Y" always equal "Y op' X"?
472 bool InnerCommutative = Instruction::isCommutative(InnerOpcode);
473
474 // Does "X op' (Y op Z)" always equal "(X op' Y) op (X op' Z)"?
475 if (LeftDistributesOverRight(InnerOpcode, TopLevelOpcode))
476 // Does the instruction have the form "(A op' B) op (A op' D)" or, in the
477 // commutative case, "(A op' B) op (C op' A)"?
478 if (A == C || (InnerCommutative && A == D)) {
479 if (A != C)
480 std::swap(C, D);
481 // Consider forming "A op' (B op D)".
482 // If "B op D" simplifies then it can be formed with no cost.
David Majnemer4c3753c2015-05-22 23:02:11 +0000483 V = SimplifyBinOp(TopLevelOpcode, B, D, DL);
Dinesh Dwivedib62e52e2014-06-19 08:29:18 +0000484 // If "B op D" doesn't simplify then only go on if both of the existing
485 // operations "A op' B" and "C op' D" will be zapped as no longer used.
486 if (!V && LHS->hasOneUse() && RHS->hasOneUse())
487 V = Builder->CreateBinOp(TopLevelOpcode, B, D, RHS->getName());
488 if (V) {
489 SimplifiedInst = Builder->CreateBinOp(InnerOpcode, A, V);
490 }
491 }
492
493 // Does "(X op Y) op' Z" always equal "(X op' Z) op (Y op' Z)"?
494 if (!SimplifiedInst && RightDistributesOverLeft(TopLevelOpcode, InnerOpcode))
495 // Does the instruction have the form "(A op' B) op (C op' B)" or, in the
496 // commutative case, "(A op' B) op (B op' D)"?
497 if (B == D || (InnerCommutative && B == C)) {
498 if (B != D)
499 std::swap(C, D);
500 // Consider forming "(A op C) op' B".
501 // If "A op C" simplifies then it can be formed with no cost.
David Majnemer4c3753c2015-05-22 23:02:11 +0000502 V = SimplifyBinOp(TopLevelOpcode, A, C, DL);
Dinesh Dwivedib62e52e2014-06-19 08:29:18 +0000503
504 // If "A op C" doesn't simplify then only go on if both of the existing
505 // operations "A op' B" and "C op' D" will be zapped as no longer used.
506 if (!V && LHS->hasOneUse() && RHS->hasOneUse())
507 V = Builder->CreateBinOp(TopLevelOpcode, A, C, LHS->getName());
508 if (V) {
509 SimplifiedInst = Builder->CreateBinOp(InnerOpcode, V, B);
510 }
511 }
512
513 if (SimplifiedInst) {
514 ++NumFactor;
515 SimplifiedInst->takeName(&I);
516
517 // Check if we can add NSW flag to SimplifiedInst. If so, set NSW flag.
518 // TODO: Check for NUW.
519 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(SimplifiedInst)) {
520 if (isa<OverflowingBinaryOperator>(SimplifiedInst)) {
521 bool HasNSW = false;
522 if (isa<OverflowingBinaryOperator>(&I))
523 HasNSW = I.hasNoSignedWrap();
524
525 if (BinaryOperator *Op0 = dyn_cast<BinaryOperator>(LHS))
526 if (isa<OverflowingBinaryOperator>(Op0))
527 HasNSW &= Op0->hasNoSignedWrap();
528
529 if (BinaryOperator *Op1 = dyn_cast<BinaryOperator>(RHS))
530 if (isa<OverflowingBinaryOperator>(Op1))
531 HasNSW &= Op1->hasNoSignedWrap();
David Majnemer4c3753c2015-05-22 23:02:11 +0000532
Benjamin Kramerdf005cb2015-08-08 18:27:36 +0000533 // We can propagate 'nsw' if we know that
David Majnemer4c3753c2015-05-22 23:02:11 +0000534 // %Y = mul nsw i16 %X, C
535 // %Z = add nsw i16 %Y, %X
536 // =>
537 // %Z = mul nsw i16 %X, C+1
538 //
539 // iff C+1 isn't INT_MIN
540 const APInt *CInt;
541 if (TopLevelOpcode == Instruction::Add &&
542 InnerOpcode == Instruction::Mul)
543 if (match(V, m_APInt(CInt)) && !CInt->isMinSignedValue())
544 BO->setHasNoSignedWrap(HasNSW);
Dinesh Dwivedib62e52e2014-06-19 08:29:18 +0000545 }
546 }
547 }
548 return SimplifiedInst;
549}
550
Sanjay Patel84dca492015-09-21 15:33:26 +0000551/// This tries to simplify binary operations which some other binary operation
552/// distributes over either by factorizing out common terms
553/// (eg "(A*B)+(A*C)" -> "A*(B+C)") or expanding out if this results in
554/// simplifications (eg: "A & (B | C) -> (A&B) | (A&C)" if this is a win).
555/// Returns the simplified value, or null if it didn't simplify.
Duncan Sandsfbb9ac32010-12-22 13:36:08 +0000556Value *InstCombiner::SimplifyUsingDistributiveLaws(BinaryOperator &I) {
557 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
558 BinaryOperator *Op0 = dyn_cast<BinaryOperator>(LHS);
559 BinaryOperator *Op1 = dyn_cast<BinaryOperator>(RHS);
Duncan Sandsadc7771f2010-11-23 14:23:47 +0000560
Duncan Sandsfbb9ac32010-12-22 13:36:08 +0000561 // Factorization.
Dinesh Dwivedib62e52e2014-06-19 08:29:18 +0000562 Value *A = nullptr, *B = nullptr, *C = nullptr, *D = nullptr;
Dinesh Dwivedi4919bbe2014-08-26 08:53:32 +0000563 auto TopLevelOpcode = I.getOpcode();
564 auto LHSOpcode = getBinOpsForFactorization(TopLevelOpcode, Op0, A, B);
565 auto RHSOpcode = getBinOpsForFactorization(TopLevelOpcode, Op1, C, D);
Duncan Sandsadc7771f2010-11-23 14:23:47 +0000566
Dinesh Dwivedib62e52e2014-06-19 08:29:18 +0000567 // The instruction has the form "(A op' B) op (C op' D)". Try to factorize
568 // a common term.
569 if (LHSOpcode == RHSOpcode) {
570 if (Value *V = tryFactorization(Builder, DL, I, LHSOpcode, A, B, C, D))
571 return V;
Duncan Sandsfbb9ac32010-12-22 13:36:08 +0000572 }
573
Dinesh Dwivedib62e52e2014-06-19 08:29:18 +0000574 // The instruction has the form "(A op' B) op (C)". Try to factorize common
575 // term.
576 if (Value *V = tryFactorization(Builder, DL, I, LHSOpcode, A, B, RHS,
577 getIdentityValue(LHSOpcode, RHS)))
578 return V;
579
580 // The instruction has the form "(B) op (C op' D)". Try to factorize common
581 // term.
582 if (Value *V = tryFactorization(Builder, DL, I, RHSOpcode, LHS,
583 getIdentityValue(RHSOpcode, LHS), C, D))
584 return V;
585
Duncan Sandsfbb9ac32010-12-22 13:36:08 +0000586 // Expansion.
587 if (Op0 && RightDistributesOverLeft(Op0->getOpcode(), TopLevelOpcode)) {
588 // The instruction has the form "(A op' B) op C". See if expanding it out
589 // to "(A op C) op' (B op C)" results in simplifications.
590 Value *A = Op0->getOperand(0), *B = Op0->getOperand(1), *C = RHS;
591 Instruction::BinaryOps InnerOpcode = Op0->getOpcode(); // op'
592
593 // Do "A op C" and "B op C" both simplify?
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000594 if (Value *L = SimplifyBinOp(TopLevelOpcode, A, C, DL))
595 if (Value *R = SimplifyBinOp(TopLevelOpcode, B, C, DL)) {
Duncan Sandsfbb9ac32010-12-22 13:36:08 +0000596 // They do! Return "L op' R".
597 ++NumExpand;
598 // If "L op' R" equals "A op' B" then "L op' R" is just the LHS.
599 if ((L == A && R == B) ||
600 (Instruction::isCommutative(InnerOpcode) && L == B && R == A))
601 return Op0;
602 // Otherwise return "L op' R" if it simplifies.
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000603 if (Value *V = SimplifyBinOp(InnerOpcode, L, R, DL))
Duncan Sandsfbb9ac32010-12-22 13:36:08 +0000604 return V;
605 // Otherwise, create a new instruction.
606 C = Builder->CreateBinOp(InnerOpcode, L, R);
607 C->takeName(&I);
608 return C;
609 }
610 }
611
612 if (Op1 && LeftDistributesOverRight(TopLevelOpcode, Op1->getOpcode())) {
613 // The instruction has the form "A op (B op' C)". See if expanding it out
614 // to "(A op B) op' (A op C)" results in simplifications.
615 Value *A = LHS, *B = Op1->getOperand(0), *C = Op1->getOperand(1);
616 Instruction::BinaryOps InnerOpcode = Op1->getOpcode(); // op'
617
618 // Do "A op B" and "A op C" both simplify?
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000619 if (Value *L = SimplifyBinOp(TopLevelOpcode, A, B, DL))
620 if (Value *R = SimplifyBinOp(TopLevelOpcode, A, C, DL)) {
Duncan Sandsfbb9ac32010-12-22 13:36:08 +0000621 // They do! Return "L op' R".
622 ++NumExpand;
623 // If "L op' R" equals "B op' C" then "L op' R" is just the RHS.
624 if ((L == B && R == C) ||
625 (Instruction::isCommutative(InnerOpcode) && L == C && R == B))
626 return Op1;
627 // Otherwise return "L op' R" if it simplifies.
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000628 if (Value *V = SimplifyBinOp(InnerOpcode, L, R, DL))
Duncan Sandsfbb9ac32010-12-22 13:36:08 +0000629 return V;
630 // Otherwise, create a new instruction.
631 A = Builder->CreateBinOp(InnerOpcode, L, R);
632 A->takeName(&I);
633 return A;
634 }
635 }
Duncan Sandsadc7771f2010-11-23 14:23:47 +0000636
David Majnemer33b6f822015-07-14 22:39:23 +0000637 // (op (select (a, c, b)), (select (a, d, b))) -> (select (a, (op c, d), 0))
638 // (op (select (a, b, c)), (select (a, b, d))) -> (select (a, 0, (op c, d)))
639 if (auto *SI0 = dyn_cast<SelectInst>(LHS)) {
640 if (auto *SI1 = dyn_cast<SelectInst>(RHS)) {
641 if (SI0->getCondition() == SI1->getCondition()) {
642 Value *SI = nullptr;
643 if (Value *V = SimplifyBinOp(TopLevelOpcode, SI0->getFalseValue(),
644 SI1->getFalseValue(), DL, TLI, DT, AC))
645 SI = Builder->CreateSelect(SI0->getCondition(),
646 Builder->CreateBinOp(TopLevelOpcode,
647 SI0->getTrueValue(),
648 SI1->getTrueValue()),
649 V);
650 if (Value *V = SimplifyBinOp(TopLevelOpcode, SI0->getTrueValue(),
651 SI1->getTrueValue(), DL, TLI, DT, AC))
652 SI = Builder->CreateSelect(
653 SI0->getCondition(), V,
654 Builder->CreateBinOp(TopLevelOpcode, SI0->getFalseValue(),
655 SI1->getFalseValue()));
656 if (SI) {
657 SI->takeName(&I);
658 return SI;
659 }
660 }
661 }
662 }
663
Craig Topperf40110f2014-04-25 05:29:35 +0000664 return nullptr;
Duncan Sandsadc7771f2010-11-23 14:23:47 +0000665}
666
Sanjay Patel84dca492015-09-21 15:33:26 +0000667/// Given a 'sub' instruction, return the RHS of the instruction if the LHS is a
668/// constant zero (which is the 'negate' form).
Chris Lattner2188e402010-01-04 07:37:31 +0000669Value *InstCombiner::dyn_castNegVal(Value *V) const {
Owen Andersonbb2501b2009-07-13 22:18:28 +0000670 if (BinaryOperator::isNeg(V))
Chris Lattnerd6f636a2005-04-24 07:30:14 +0000671 return BinaryOperator::getNegArgument(V);
Chris Lattnerbb74e222003-03-10 23:06:50 +0000672
Chris Lattner9ad0d552004-12-14 20:08:06 +0000673 // Constants can be considered to be negated values if they can be folded.
674 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
Owen Anderson487375e2009-07-29 18:55:55 +0000675 return ConstantExpr::getNeg(C);
Nick Lewycky3bf55122008-05-23 04:54:45 +0000676
Chris Lattner8213c8a2012-02-06 21:56:39 +0000677 if (ConstantDataVector *C = dyn_cast<ConstantDataVector>(V))
678 if (C->getType()->getElementType()->isIntegerTy())
Owen Anderson487375e2009-07-29 18:55:55 +0000679 return ConstantExpr::getNeg(C);
Nick Lewycky3bf55122008-05-23 04:54:45 +0000680
Craig Topperf40110f2014-04-25 05:29:35 +0000681 return nullptr;
Chris Lattner9fa53de2002-05-06 16:49:18 +0000682}
683
Sanjay Patel84dca492015-09-21 15:33:26 +0000684/// Given a 'fsub' instruction, return the RHS of the instruction if the LHS is
685/// a constant negative zero (which is the 'negate' form).
Shuxin Yangf0537ab2013-01-09 00:13:41 +0000686Value *InstCombiner::dyn_castFNegVal(Value *V, bool IgnoreZeroSign) const {
687 if (BinaryOperator::isFNeg(V, IgnoreZeroSign))
Dan Gohmana5b96452009-06-04 22:49:04 +0000688 return BinaryOperator::getFNegArgument(V);
689
690 // Constants can be considered to be negated values if they can be folded.
691 if (ConstantFP *C = dyn_cast<ConstantFP>(V))
Owen Anderson487375e2009-07-29 18:55:55 +0000692 return ConstantExpr::getFNeg(C);
Dan Gohmana5b96452009-06-04 22:49:04 +0000693
Chris Lattner8213c8a2012-02-06 21:56:39 +0000694 if (ConstantDataVector *C = dyn_cast<ConstantDataVector>(V))
695 if (C->getType()->getElementType()->isFloatingPointTy())
Owen Anderson487375e2009-07-29 18:55:55 +0000696 return ConstantExpr::getFNeg(C);
Dan Gohmana5b96452009-06-04 22:49:04 +0000697
Craig Topperf40110f2014-04-25 05:29:35 +0000698 return nullptr;
Dan Gohmana5b96452009-06-04 22:49:04 +0000699}
700
Chris Lattner86102b82005-01-01 16:22:27 +0000701static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
Chris Lattner183b3362004-04-09 19:05:30 +0000702 InstCombiner *IC) {
Nick Lewycky6a083cf2011-01-21 02:30:43 +0000703 if (CastInst *CI = dyn_cast<CastInst>(&I)) {
Chris Lattnerc8565392009-08-30 20:01:10 +0000704 return IC->Builder->CreateCast(CI->getOpcode(), SO, I.getType());
Nick Lewycky6a083cf2011-01-21 02:30:43 +0000705 }
Chris Lattner86102b82005-01-01 16:22:27 +0000706
Chris Lattner183b3362004-04-09 19:05:30 +0000707 // Figure out if the constant is the left or the right argument.
Chris Lattner86102b82005-01-01 16:22:27 +0000708 bool ConstIsRHS = isa<Constant>(I.getOperand(1));
709 Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
Chris Lattnerb8b97502003-08-13 19:01:45 +0000710
Chris Lattner183b3362004-04-09 19:05:30 +0000711 if (Constant *SOC = dyn_cast<Constant>(SO)) {
712 if (ConstIsRHS)
Owen Anderson487375e2009-07-29 18:55:55 +0000713 return ConstantExpr::get(I.getOpcode(), SOC, ConstOperand);
714 return ConstantExpr::get(I.getOpcode(), ConstOperand, SOC);
Chris Lattner183b3362004-04-09 19:05:30 +0000715 }
716
717 Value *Op0 = SO, *Op1 = ConstOperand;
718 if (!ConstIsRHS)
719 std::swap(Op0, Op1);
Jakub Staszakcfc46f82012-05-06 13:52:31 +0000720
Owen Anderson1664dc82014-01-20 07:44:53 +0000721 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I)) {
722 Value *RI = IC->Builder->CreateBinOp(BO->getOpcode(), Op0, Op1,
Chris Lattner022a5822009-08-30 07:44:24 +0000723 SO->getName()+".op");
Owen Anderson1664dc82014-01-20 07:44:53 +0000724 Instruction *FPInst = dyn_cast<Instruction>(RI);
725 if (FPInst && isa<FPMathOperator>(FPInst))
726 FPInst->copyFastMathFlags(BO);
727 return RI;
728 }
Chris Lattner022a5822009-08-30 07:44:24 +0000729 if (ICmpInst *CI = dyn_cast<ICmpInst>(&I))
730 return IC->Builder->CreateICmp(CI->getPredicate(), Op0, Op1,
731 SO->getName()+".cmp");
732 if (FCmpInst *CI = dyn_cast<FCmpInst>(&I))
733 return IC->Builder->CreateICmp(CI->getPredicate(), Op0, Op1,
734 SO->getName()+".cmp");
735 llvm_unreachable("Unknown binary instruction type!");
Chris Lattner86102b82005-01-01 16:22:27 +0000736}
737
Sanjay Patel84dca492015-09-21 15:33:26 +0000738/// Given an instruction with a select as one operand and a constant as the
739/// other operand, try to fold the binary operator into the select arguments.
740/// This also works for Cast instructions, which obviously do not have a second
741/// operand.
Chris Lattner2b295a02010-01-04 07:53:58 +0000742Instruction *InstCombiner::FoldOpIntoSelect(Instruction &Op, SelectInst *SI) {
Chris Lattner86102b82005-01-01 16:22:27 +0000743 // Don't modify shared select instructions
Craig Topperf40110f2014-04-25 05:29:35 +0000744 if (!SI->hasOneUse()) return nullptr;
Chris Lattner86102b82005-01-01 16:22:27 +0000745 Value *TV = SI->getOperand(1);
746 Value *FV = SI->getOperand(2);
747
748 if (isa<Constant>(TV) || isa<Constant>(FV)) {
Chris Lattner374e6592005-04-21 05:43:13 +0000749 // Bool selects with constant operands can be folded to logical ops.
Craig Topperf40110f2014-04-25 05:29:35 +0000750 if (SI->getType()->isIntegerTy(1)) return nullptr;
Chris Lattner374e6592005-04-21 05:43:13 +0000751
Nick Lewycky6a083cf2011-01-21 02:30:43 +0000752 // If it's a bitcast involving vectors, make sure it has the same number of
753 // elements on both sides.
754 if (BitCastInst *BC = dyn_cast<BitCastInst>(&Op)) {
Chris Lattner229907c2011-07-18 04:54:35 +0000755 VectorType *DestTy = dyn_cast<VectorType>(BC->getDestTy());
756 VectorType *SrcTy = dyn_cast<VectorType>(BC->getSrcTy());
Nick Lewycky6a083cf2011-01-21 02:30:43 +0000757
758 // Verify that either both or neither are vectors.
Craig Topperf40110f2014-04-25 05:29:35 +0000759 if ((SrcTy == nullptr) != (DestTy == nullptr)) return nullptr;
Nick Lewycky6a083cf2011-01-21 02:30:43 +0000760 // If vectors, verify that they have the same number of elements.
761 if (SrcTy && SrcTy->getNumElements() != DestTy->getNumElements())
Craig Topperf40110f2014-04-25 05:29:35 +0000762 return nullptr;
Nick Lewycky6a083cf2011-01-21 02:30:43 +0000763 }
Jakub Staszakcfc46f82012-05-06 13:52:31 +0000764
James Molloy2b21a7c2015-05-20 18:41:25 +0000765 // Test if a CmpInst instruction is used exclusively by a select as
766 // part of a minimum or maximum operation. If so, refrain from doing
767 // any other folding. This helps out other analyses which understand
768 // non-obfuscated minimum and maximum idioms, such as ScalarEvolution
769 // and CodeGen. And in this case, at least one of the comparison
770 // operands has at least one user besides the compare (the select),
771 // which would often largely negate the benefit of folding anyway.
772 if (auto *CI = dyn_cast<CmpInst>(SI->getCondition())) {
773 if (CI->hasOneUse()) {
774 Value *Op0 = CI->getOperand(0), *Op1 = CI->getOperand(1);
775 if ((SI->getOperand(1) == Op0 && SI->getOperand(2) == Op1) ||
776 (SI->getOperand(2) == Op0 && SI->getOperand(1) == Op1))
777 return nullptr;
778 }
779 }
780
Chris Lattner2b295a02010-01-04 07:53:58 +0000781 Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, this);
782 Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, this);
Chris Lattner86102b82005-01-01 16:22:27 +0000783
Nick Lewycky6a083cf2011-01-21 02:30:43 +0000784 return SelectInst::Create(SI->getCondition(),
785 SelectTrueVal, SelectFalseVal);
Chris Lattner86102b82005-01-01 16:22:27 +0000786 }
Craig Topperf40110f2014-04-25 05:29:35 +0000787 return nullptr;
Chris Lattner183b3362004-04-09 19:05:30 +0000788}
789
Sanjay Patel84dca492015-09-21 15:33:26 +0000790/// Given a binary operator, cast instruction, or select which has a PHI node as
791/// operand #0, see if we can fold the instruction into the PHI (which is only
792/// possible if all operands to the PHI are constants).
Chris Lattnerea7131a2011-01-16 05:14:26 +0000793Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I) {
Chris Lattner6a4adcd2004-09-29 05:07:12 +0000794 PHINode *PN = cast<PHINode>(I.getOperand(0));
Chris Lattner7515cab2004-11-14 19:13:23 +0000795 unsigned NumPHIValues = PN->getNumIncomingValues();
Chris Lattner25ce2802011-01-16 04:37:29 +0000796 if (NumPHIValues == 0)
Craig Topperf40110f2014-04-25 05:29:35 +0000797 return nullptr;
Jakub Staszakcfc46f82012-05-06 13:52:31 +0000798
Chris Lattnerf4ca47b2011-01-21 05:08:26 +0000799 // We normally only transform phis with a single use. However, if a PHI has
800 // multiple uses and they are all the same operation, we can fold *all* of the
801 // uses into the PHI.
Chris Lattnerd55581d2011-01-16 05:28:59 +0000802 if (!PN->hasOneUse()) {
803 // Walk the use list for the instruction, comparing them to I.
Chandler Carruthcdf47882014-03-09 03:16:01 +0000804 for (User *U : PN->users()) {
805 Instruction *UI = cast<Instruction>(U);
806 if (UI != &I && !I.isIdenticalTo(UI))
Craig Topperf40110f2014-04-25 05:29:35 +0000807 return nullptr;
Chris Lattnerb5e15d12011-01-21 05:29:50 +0000808 }
Chris Lattnerd55581d2011-01-16 05:28:59 +0000809 // Otherwise, we can replace *all* users with the new PHI we form.
810 }
Jakub Staszakcfc46f82012-05-06 13:52:31 +0000811
Chris Lattnerfacb8672009-09-27 19:57:57 +0000812 // Check to see if all of the operands of the PHI are simple constants
813 // (constantint/constantfp/undef). If there is one non-constant value,
Chris Lattnerae289632009-09-27 20:18:49 +0000814 // remember the BB it is in. If there is more than one or if *it* is a PHI,
815 // bail out. We don't do arbitrary constant expressions here because moving
816 // their computation can be expensive without a cost model.
Craig Topperf40110f2014-04-25 05:29:35 +0000817 BasicBlock *NonConstBB = nullptr;
Chris Lattner25ce2802011-01-16 04:37:29 +0000818 for (unsigned i = 0; i != NumPHIValues; ++i) {
819 Value *InVal = PN->getIncomingValue(i);
820 if (isa<Constant>(InVal) && !isa<ConstantExpr>(InVal))
821 continue;
822
Craig Topperf40110f2014-04-25 05:29:35 +0000823 if (isa<PHINode>(InVal)) return nullptr; // Itself a phi.
824 if (NonConstBB) return nullptr; // More than one non-const value.
Jakub Staszakcfc46f82012-05-06 13:52:31 +0000825
Chris Lattner25ce2802011-01-16 04:37:29 +0000826 NonConstBB = PN->getIncomingBlock(i);
Chris Lattnerff2e7372011-01-16 05:08:00 +0000827
828 // If the InVal is an invoke at the end of the pred block, then we can't
829 // insert a computation after it without breaking the edge.
830 if (InvokeInst *II = dyn_cast<InvokeInst>(InVal))
831 if (II->getParent() == NonConstBB)
Craig Topperf40110f2014-04-25 05:29:35 +0000832 return nullptr;
Jakub Staszakcfc46f82012-05-06 13:52:31 +0000833
Chris Lattnerb5e15d12011-01-21 05:29:50 +0000834 // If the incoming non-constant value is in I's block, we will remove one
835 // instruction, but insert another equivalent one, leading to infinite
836 // instcombine.
Chandler Carruth5175b9a2015-01-20 08:35:24 +0000837 if (isPotentiallyReachable(I.getParent(), NonConstBB, DT, LI))
Craig Topperf40110f2014-04-25 05:29:35 +0000838 return nullptr;
Chris Lattner25ce2802011-01-16 04:37:29 +0000839 }
Jakub Staszakcfc46f82012-05-06 13:52:31 +0000840
Chris Lattner04689872006-09-09 22:02:56 +0000841 // If there is exactly one non-constant value, we can insert a copy of the
842 // operation in that block. However, if this is a critical edge, we would be
David Majnemer7e2b9882014-11-03 21:55:12 +0000843 // inserting the computation on some other paths (e.g. inside a loop). Only
Chris Lattner04689872006-09-09 22:02:56 +0000844 // do this if the pred block is unconditionally branching into the phi block.
Craig Topperf40110f2014-04-25 05:29:35 +0000845 if (NonConstBB != nullptr) {
Chris Lattner04689872006-09-09 22:02:56 +0000846 BranchInst *BI = dyn_cast<BranchInst>(NonConstBB->getTerminator());
Craig Topperf40110f2014-04-25 05:29:35 +0000847 if (!BI || !BI->isUnconditional()) return nullptr;
Chris Lattner04689872006-09-09 22:02:56 +0000848 }
Chris Lattner6a4adcd2004-09-29 05:07:12 +0000849
850 // Okay, we can do the transformation: create the new PHI node.
Eli Friedman41e509a2011-05-18 23:58:37 +0000851 PHINode *NewPN = PHINode::Create(I.getType(), PN->getNumIncomingValues());
Chris Lattner966526c2009-10-21 23:41:58 +0000852 InsertNewInstBefore(NewPN, *PN);
853 NewPN->takeName(PN);
Jakub Staszakcfc46f82012-05-06 13:52:31 +0000854
Chris Lattnerff2e7372011-01-16 05:08:00 +0000855 // If we are going to have to insert a new computation, do so right before the
Sanjay Patel41c739b2015-09-11 19:29:18 +0000856 // predecessor's terminator.
Chris Lattnerff2e7372011-01-16 05:08:00 +0000857 if (NonConstBB)
858 Builder->SetInsertPoint(NonConstBB->getTerminator());
Jakub Staszakcfc46f82012-05-06 13:52:31 +0000859
Chris Lattner6a4adcd2004-09-29 05:07:12 +0000860 // Next, add all of the operands to the PHI.
Chris Lattnerfacb8672009-09-27 19:57:57 +0000861 if (SelectInst *SI = dyn_cast<SelectInst>(&I)) {
862 // We only currently try to fold the condition of a select when it is a phi,
863 // not the true/false values.
Chris Lattnerae289632009-09-27 20:18:49 +0000864 Value *TrueV = SI->getTrueValue();
865 Value *FalseV = SI->getFalseValue();
Chris Lattner0261b5d2009-09-28 06:49:44 +0000866 BasicBlock *PhiTransBB = PN->getParent();
Chris Lattnerfacb8672009-09-27 19:57:57 +0000867 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattnerae289632009-09-27 20:18:49 +0000868 BasicBlock *ThisBB = PN->getIncomingBlock(i);
Chris Lattner0261b5d2009-09-28 06:49:44 +0000869 Value *TrueVInPred = TrueV->DoPHITranslation(PhiTransBB, ThisBB);
870 Value *FalseVInPred = FalseV->DoPHITranslation(PhiTransBB, ThisBB);
Craig Topperf40110f2014-04-25 05:29:35 +0000871 Value *InV = nullptr;
Duncan P. N. Exon Smithce5f93e2013-12-06 21:48:36 +0000872 // Beware of ConstantExpr: it may eventually evaluate to getNullValue,
873 // even if currently isNullValue gives false.
874 Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i));
875 if (InC && !isa<ConstantExpr>(InC))
Chris Lattnerae289632009-09-27 20:18:49 +0000876 InV = InC->isNullValue() ? FalseVInPred : TrueVInPred;
Chris Lattnerff2e7372011-01-16 05:08:00 +0000877 else
878 InV = Builder->CreateSelect(PN->getIncomingValue(i),
879 TrueVInPred, FalseVInPred, "phitmp");
Chris Lattnerae289632009-09-27 20:18:49 +0000880 NewPN->addIncoming(InV, ThisBB);
Chris Lattnerfacb8672009-09-27 19:57:57 +0000881 }
Chris Lattnerff2e7372011-01-16 05:08:00 +0000882 } else if (CmpInst *CI = dyn_cast<CmpInst>(&I)) {
883 Constant *C = cast<Constant>(I.getOperand(1));
884 for (unsigned i = 0; i != NumPHIValues; ++i) {
Craig Topperf40110f2014-04-25 05:29:35 +0000885 Value *InV = nullptr;
Chris Lattnerff2e7372011-01-16 05:08:00 +0000886 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i)))
887 InV = ConstantExpr::getCompare(CI->getPredicate(), InC, C);
888 else if (isa<ICmpInst>(CI))
889 InV = Builder->CreateICmp(CI->getPredicate(), PN->getIncomingValue(i),
890 C, "phitmp");
891 else
892 InV = Builder->CreateFCmp(CI->getPredicate(), PN->getIncomingValue(i),
893 C, "phitmp");
894 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
895 }
Chris Lattnerfacb8672009-09-27 19:57:57 +0000896 } else if (I.getNumOperands() == 2) {
Chris Lattner6a4adcd2004-09-29 05:07:12 +0000897 Constant *C = cast<Constant>(I.getOperand(1));
Chris Lattner7515cab2004-11-14 19:13:23 +0000898 for (unsigned i = 0; i != NumPHIValues; ++i) {
Craig Topperf40110f2014-04-25 05:29:35 +0000899 Value *InV = nullptr;
Chris Lattnerff2e7372011-01-16 05:08:00 +0000900 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i)))
901 InV = ConstantExpr::get(I.getOpcode(), InC, C);
902 else
903 InV = Builder->CreateBinOp(cast<BinaryOperator>(I).getOpcode(),
904 PN->getIncomingValue(i), C, "phitmp");
Chris Lattner04689872006-09-09 22:02:56 +0000905 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
Chris Lattner6a4adcd2004-09-29 05:07:12 +0000906 }
Jakub Staszakcfc46f82012-05-06 13:52:31 +0000907 } else {
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000908 CastInst *CI = cast<CastInst>(&I);
Chris Lattner229907c2011-07-18 04:54:35 +0000909 Type *RetTy = CI->getType();
Chris Lattner7515cab2004-11-14 19:13:23 +0000910 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattner04689872006-09-09 22:02:56 +0000911 Value *InV;
Chris Lattnerff2e7372011-01-16 05:08:00 +0000912 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i)))
Owen Anderson487375e2009-07-29 18:55:55 +0000913 InV = ConstantExpr::getCast(CI->getOpcode(), InC, RetTy);
Jakub Staszakcfc46f82012-05-06 13:52:31 +0000914 else
Chris Lattnerff2e7372011-01-16 05:08:00 +0000915 InV = Builder->CreateCast(CI->getOpcode(),
916 PN->getIncomingValue(i), I.getType(), "phitmp");
Chris Lattner04689872006-09-09 22:02:56 +0000917 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
Chris Lattner6a4adcd2004-09-29 05:07:12 +0000918 }
919 }
Jakub Staszakcfc46f82012-05-06 13:52:31 +0000920
Chandler Carruthcdf47882014-03-09 03:16:01 +0000921 for (auto UI = PN->user_begin(), E = PN->user_end(); UI != E;) {
Chris Lattnerd55581d2011-01-16 05:28:59 +0000922 Instruction *User = cast<Instruction>(*UI++);
923 if (User == &I) continue;
Sanjay Patel4b198802016-02-01 22:23:39 +0000924 replaceInstUsesWith(*User, NewPN);
925 eraseInstFromFunction(*User);
Chris Lattnerd55581d2011-01-16 05:28:59 +0000926 }
Sanjay Patel4b198802016-02-01 22:23:39 +0000927 return replaceInstUsesWith(I, NewPN);
Chris Lattner6a4adcd2004-09-29 05:07:12 +0000928}
929
Sanjay Patel84dca492015-09-21 15:33:26 +0000930/// Given a pointer type and a constant offset, determine whether or not there
931/// is a sequence of GEP indices into the pointed type that will land us at the
932/// specified offset. If so, fill them into NewIndices and return the resultant
933/// element type, otherwise return null.
David Blaikie87ca1b62015-03-27 20:56:11 +0000934Type *InstCombiner::FindElementAtOffset(PointerType *PtrTy, int64_t Offset,
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000935 SmallVectorImpl<Value *> &NewIndices) {
David Blaikie87ca1b62015-03-27 20:56:11 +0000936 Type *Ty = PtrTy->getElementType();
Matt Arsenaultd79f7d92013-08-19 22:17:40 +0000937 if (!Ty->isSized())
Craig Topperf40110f2014-04-25 05:29:35 +0000938 return nullptr;
Jakub Staszakcfc46f82012-05-06 13:52:31 +0000939
Chris Lattnerfef138b2009-01-09 05:44:56 +0000940 // Start with the index over the outer type. Note that the type size
941 // might be zero (even if the offset isn't zero) if the indexed type
942 // is something like [0 x {int, int}]
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000943 Type *IntPtrTy = DL.getIntPtrType(PtrTy);
Chris Lattnerfef138b2009-01-09 05:44:56 +0000944 int64_t FirstIdx = 0;
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000945 if (int64_t TySize = DL.getTypeAllocSize(Ty)) {
Chris Lattnerfef138b2009-01-09 05:44:56 +0000946 FirstIdx = Offset/TySize;
Chris Lattnerbd3c7c82009-01-11 20:41:36 +0000947 Offset -= FirstIdx*TySize;
Jakub Staszakcfc46f82012-05-06 13:52:31 +0000948
Benjamin Kramere4c46fe2013-01-23 17:52:29 +0000949 // Handle hosts where % returns negative instead of values [0..TySize).
950 if (Offset < 0) {
951 --FirstIdx;
952 Offset += TySize;
953 assert(Offset >= 0);
954 }
Chris Lattnerfef138b2009-01-09 05:44:56 +0000955 assert((uint64_t)Offset < (uint64_t)TySize && "Out of range offset");
956 }
Jakub Staszakcfc46f82012-05-06 13:52:31 +0000957
Owen Andersonedb4a702009-07-24 23:12:02 +0000958 NewIndices.push_back(ConstantInt::get(IntPtrTy, FirstIdx));
Jakub Staszakcfc46f82012-05-06 13:52:31 +0000959
Chris Lattnerfef138b2009-01-09 05:44:56 +0000960 // Index into the types. If we fail, set OrigBase to null.
961 while (Offset) {
Chris Lattner171d2d42009-01-11 20:15:20 +0000962 // Indexing into tail padding between struct/array elements.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000963 if (uint64_t(Offset * 8) >= DL.getTypeSizeInBits(Ty))
Craig Topperf40110f2014-04-25 05:29:35 +0000964 return nullptr;
Jakub Staszakcfc46f82012-05-06 13:52:31 +0000965
Chris Lattner229907c2011-07-18 04:54:35 +0000966 if (StructType *STy = dyn_cast<StructType>(Ty)) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000967 const StructLayout *SL = DL.getStructLayout(STy);
Chris Lattner171d2d42009-01-11 20:15:20 +0000968 assert(Offset < (int64_t)SL->getSizeInBytes() &&
969 "Offset must stay within the indexed type");
Jakub Staszakcfc46f82012-05-06 13:52:31 +0000970
Chris Lattnerfef138b2009-01-09 05:44:56 +0000971 unsigned Elt = SL->getElementContainingOffset(Offset);
Chris Lattnerb8906bd2010-01-04 07:02:48 +0000972 NewIndices.push_back(ConstantInt::get(Type::getInt32Ty(Ty->getContext()),
973 Elt));
Jakub Staszakcfc46f82012-05-06 13:52:31 +0000974
Chris Lattnerfef138b2009-01-09 05:44:56 +0000975 Offset -= SL->getElementOffset(Elt);
976 Ty = STy->getElementType(Elt);
Chris Lattner229907c2011-07-18 04:54:35 +0000977 } else if (ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000978 uint64_t EltSize = DL.getTypeAllocSize(AT->getElementType());
Chris Lattner171d2d42009-01-11 20:15:20 +0000979 assert(EltSize && "Cannot index into a zero-sized array");
Owen Andersonedb4a702009-07-24 23:12:02 +0000980 NewIndices.push_back(ConstantInt::get(IntPtrTy,Offset/EltSize));
Chris Lattner171d2d42009-01-11 20:15:20 +0000981 Offset %= EltSize;
Chris Lattnerb1915162009-01-11 20:23:52 +0000982 Ty = AT->getElementType();
Chris Lattnerfef138b2009-01-09 05:44:56 +0000983 } else {
Chris Lattner171d2d42009-01-11 20:15:20 +0000984 // Otherwise, we can't index into the middle of this atomic type, bail.
Craig Topperf40110f2014-04-25 05:29:35 +0000985 return nullptr;
Chris Lattnerfef138b2009-01-09 05:44:56 +0000986 }
987 }
Jakub Staszakcfc46f82012-05-06 13:52:31 +0000988
Chris Lattner72cd68f2009-01-24 01:00:13 +0000989 return Ty;
Chris Lattnerfef138b2009-01-09 05:44:56 +0000990}
991
Rafael Espindolaa3a44f3f2011-07-31 04:43:41 +0000992static bool shouldMergeGEPs(GEPOperator &GEP, GEPOperator &Src) {
993 // If this GEP has only 0 indices, it is the same pointer as
994 // Src. If Src is not a trivial GEP too, don't combine
995 // the indices.
996 if (GEP.hasAllZeroIndices() && !Src.hasAllZeroIndices() &&
997 !Src.hasOneUse())
998 return false;
999 return true;
1000}
Chris Lattnerbbbdd852002-05-06 18:06:38 +00001001
Sanjay Patel84dca492015-09-21 15:33:26 +00001002/// Return a value X such that Val = X * Scale, or null if none.
1003/// If the multiplication is known not to overflow, then NoSignedWrap is set.
Duncan Sands533c8ae2012-10-23 08:28:26 +00001004Value *InstCombiner::Descale(Value *Val, APInt Scale, bool &NoSignedWrap) {
1005 assert(isa<IntegerType>(Val->getType()) && "Can only descale integers!");
1006 assert(cast<IntegerType>(Val->getType())->getBitWidth() ==
1007 Scale.getBitWidth() && "Scale not compatible with value!");
1008
1009 // If Val is zero or Scale is one then Val = Val * Scale.
1010 if (match(Val, m_Zero()) || Scale == 1) {
1011 NoSignedWrap = true;
1012 return Val;
1013 }
1014
1015 // If Scale is zero then it does not divide Val.
1016 if (Scale.isMinValue())
Craig Topperf40110f2014-04-25 05:29:35 +00001017 return nullptr;
Duncan Sands533c8ae2012-10-23 08:28:26 +00001018
1019 // Look through chains of multiplications, searching for a constant that is
1020 // divisible by Scale. For example, descaling X*(Y*(Z*4)) by a factor of 4
1021 // will find the constant factor 4 and produce X*(Y*Z). Descaling X*(Y*8) by
1022 // a factor of 4 will produce X*(Y*2). The principle of operation is to bore
1023 // down from Val:
1024 //
1025 // Val = M1 * X || Analysis starts here and works down
1026 // M1 = M2 * Y || Doesn't descend into terms with more
1027 // M2 = Z * 4 \/ than one use
1028 //
1029 // Then to modify a term at the bottom:
1030 //
1031 // Val = M1 * X
1032 // M1 = Z * Y || Replaced M2 with Z
1033 //
1034 // Then to work back up correcting nsw flags.
1035
1036 // Op - the term we are currently analyzing. Starts at Val then drills down.
1037 // Replaced with its descaled value before exiting from the drill down loop.
1038 Value *Op = Val;
1039
1040 // Parent - initially null, but after drilling down notes where Op came from.
1041 // In the example above, Parent is (Val, 0) when Op is M1, because M1 is the
1042 // 0'th operand of Val.
1043 std::pair<Instruction*, unsigned> Parent;
1044
Sanjay Patel84dca492015-09-21 15:33:26 +00001045 // Set if the transform requires a descaling at deeper levels that doesn't
1046 // overflow.
Duncan Sands533c8ae2012-10-23 08:28:26 +00001047 bool RequireNoSignedWrap = false;
1048
Sanjay Patel84dca492015-09-21 15:33:26 +00001049 // Log base 2 of the scale. Negative if not a power of 2.
Duncan Sands533c8ae2012-10-23 08:28:26 +00001050 int32_t logScale = Scale.exactLogBase2();
1051
1052 for (;; Op = Parent.first->getOperand(Parent.second)) { // Drill down
1053
1054 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op)) {
1055 // If Op is a constant divisible by Scale then descale to the quotient.
1056 APInt Quotient(Scale), Remainder(Scale); // Init ensures right bitwidth.
1057 APInt::sdivrem(CI->getValue(), Scale, Quotient, Remainder);
1058 if (!Remainder.isMinValue())
1059 // Not divisible by Scale.
Craig Topperf40110f2014-04-25 05:29:35 +00001060 return nullptr;
Duncan Sands533c8ae2012-10-23 08:28:26 +00001061 // Replace with the quotient in the parent.
1062 Op = ConstantInt::get(CI->getType(), Quotient);
1063 NoSignedWrap = true;
1064 break;
1065 }
1066
1067 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op)) {
1068
1069 if (BO->getOpcode() == Instruction::Mul) {
1070 // Multiplication.
1071 NoSignedWrap = BO->hasNoSignedWrap();
1072 if (RequireNoSignedWrap && !NoSignedWrap)
Craig Topperf40110f2014-04-25 05:29:35 +00001073 return nullptr;
Duncan Sands533c8ae2012-10-23 08:28:26 +00001074
1075 // There are three cases for multiplication: multiplication by exactly
1076 // the scale, multiplication by a constant different to the scale, and
1077 // multiplication by something else.
1078 Value *LHS = BO->getOperand(0);
1079 Value *RHS = BO->getOperand(1);
1080
1081 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHS)) {
1082 // Multiplication by a constant.
1083 if (CI->getValue() == Scale) {
1084 // Multiplication by exactly the scale, replace the multiplication
1085 // by its left-hand side in the parent.
1086 Op = LHS;
1087 break;
1088 }
1089
1090 // Otherwise drill down into the constant.
1091 if (!Op->hasOneUse())
Craig Topperf40110f2014-04-25 05:29:35 +00001092 return nullptr;
Duncan Sands533c8ae2012-10-23 08:28:26 +00001093
1094 Parent = std::make_pair(BO, 1);
1095 continue;
1096 }
1097
1098 // Multiplication by something else. Drill down into the left-hand side
1099 // since that's where the reassociate pass puts the good stuff.
1100 if (!Op->hasOneUse())
Craig Topperf40110f2014-04-25 05:29:35 +00001101 return nullptr;
Duncan Sands533c8ae2012-10-23 08:28:26 +00001102
1103 Parent = std::make_pair(BO, 0);
1104 continue;
1105 }
1106
1107 if (logScale > 0 && BO->getOpcode() == Instruction::Shl &&
1108 isa<ConstantInt>(BO->getOperand(1))) {
1109 // Multiplication by a power of 2.
1110 NoSignedWrap = BO->hasNoSignedWrap();
1111 if (RequireNoSignedWrap && !NoSignedWrap)
Craig Topperf40110f2014-04-25 05:29:35 +00001112 return nullptr;
Duncan Sands533c8ae2012-10-23 08:28:26 +00001113
1114 Value *LHS = BO->getOperand(0);
1115 int32_t Amt = cast<ConstantInt>(BO->getOperand(1))->
1116 getLimitedValue(Scale.getBitWidth());
1117 // Op = LHS << Amt.
1118
1119 if (Amt == logScale) {
1120 // Multiplication by exactly the scale, replace the multiplication
1121 // by its left-hand side in the parent.
1122 Op = LHS;
1123 break;
1124 }
1125 if (Amt < logScale || !Op->hasOneUse())
Craig Topperf40110f2014-04-25 05:29:35 +00001126 return nullptr;
Duncan Sands533c8ae2012-10-23 08:28:26 +00001127
1128 // Multiplication by more than the scale. Reduce the multiplying amount
1129 // by the scale in the parent.
1130 Parent = std::make_pair(BO, 1);
1131 Op = ConstantInt::get(BO->getType(), Amt - logScale);
1132 break;
1133 }
1134 }
1135
1136 if (!Op->hasOneUse())
Craig Topperf40110f2014-04-25 05:29:35 +00001137 return nullptr;
Duncan Sands533c8ae2012-10-23 08:28:26 +00001138
1139 if (CastInst *Cast = dyn_cast<CastInst>(Op)) {
1140 if (Cast->getOpcode() == Instruction::SExt) {
1141 // Op is sign-extended from a smaller type, descale in the smaller type.
1142 unsigned SmallSize = Cast->getSrcTy()->getPrimitiveSizeInBits();
1143 APInt SmallScale = Scale.trunc(SmallSize);
1144 // Suppose Op = sext X, and we descale X as Y * SmallScale. We want to
1145 // descale Op as (sext Y) * Scale. In order to have
1146 // sext (Y * SmallScale) = (sext Y) * Scale
1147 // some conditions need to hold however: SmallScale must sign-extend to
1148 // Scale and the multiplication Y * SmallScale should not overflow.
1149 if (SmallScale.sext(Scale.getBitWidth()) != Scale)
1150 // SmallScale does not sign-extend to Scale.
Craig Topperf40110f2014-04-25 05:29:35 +00001151 return nullptr;
Duncan Sands533c8ae2012-10-23 08:28:26 +00001152 assert(SmallScale.exactLogBase2() == logScale);
1153 // Require that Y * SmallScale must not overflow.
1154 RequireNoSignedWrap = true;
1155
1156 // Drill down through the cast.
1157 Parent = std::make_pair(Cast, 0);
1158 Scale = SmallScale;
1159 continue;
1160 }
1161
Duncan Sands5ed39002012-10-23 09:07:02 +00001162 if (Cast->getOpcode() == Instruction::Trunc) {
Duncan Sands533c8ae2012-10-23 08:28:26 +00001163 // Op is truncated from a larger type, descale in the larger type.
1164 // Suppose Op = trunc X, and we descale X as Y * sext Scale. Then
1165 // trunc (Y * sext Scale) = (trunc Y) * Scale
1166 // always holds. However (trunc Y) * Scale may overflow even if
1167 // trunc (Y * sext Scale) does not, so nsw flags need to be cleared
1168 // from this point up in the expression (see later).
1169 if (RequireNoSignedWrap)
Craig Topperf40110f2014-04-25 05:29:35 +00001170 return nullptr;
Duncan Sands533c8ae2012-10-23 08:28:26 +00001171
1172 // Drill down through the cast.
1173 unsigned LargeSize = Cast->getSrcTy()->getPrimitiveSizeInBits();
1174 Parent = std::make_pair(Cast, 0);
1175 Scale = Scale.sext(LargeSize);
1176 if (logScale + 1 == (int32_t)Cast->getType()->getPrimitiveSizeInBits())
1177 logScale = -1;
1178 assert(Scale.exactLogBase2() == logScale);
1179 continue;
1180 }
1181 }
1182
1183 // Unsupported expression, bail out.
Craig Topperf40110f2014-04-25 05:29:35 +00001184 return nullptr;
Duncan Sands533c8ae2012-10-23 08:28:26 +00001185 }
1186
Duncan P. N. Exon Smith04934b02014-07-10 17:13:27 +00001187 // If Op is zero then Val = Op * Scale.
1188 if (match(Op, m_Zero())) {
1189 NoSignedWrap = true;
1190 return Op;
1191 }
1192
Duncan Sands533c8ae2012-10-23 08:28:26 +00001193 // We know that we can successfully descale, so from here on we can safely
1194 // modify the IR. Op holds the descaled version of the deepest term in the
1195 // expression. NoSignedWrap is 'true' if multiplying Op by Scale is known
1196 // not to overflow.
1197
1198 if (!Parent.first)
1199 // The expression only had one term.
1200 return Op;
1201
1202 // Rewrite the parent using the descaled version of its operand.
1203 assert(Parent.first->hasOneUse() && "Drilled down when more than one use!");
1204 assert(Op != Parent.first->getOperand(Parent.second) &&
1205 "Descaling was a no-op?");
1206 Parent.first->setOperand(Parent.second, Op);
1207 Worklist.Add(Parent.first);
1208
1209 // Now work back up the expression correcting nsw flags. The logic is based
1210 // on the following observation: if X * Y is known not to overflow as a signed
1211 // multiplication, and Y is replaced by a value Z with smaller absolute value,
1212 // then X * Z will not overflow as a signed multiplication either. As we work
1213 // our way up, having NoSignedWrap 'true' means that the descaled value at the
1214 // current level has strictly smaller absolute value than the original.
1215 Instruction *Ancestor = Parent.first;
1216 do {
1217 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Ancestor)) {
1218 // If the multiplication wasn't nsw then we can't say anything about the
1219 // value of the descaled multiplication, and we have to clear nsw flags
1220 // from this point on up.
1221 bool OpNoSignedWrap = BO->hasNoSignedWrap();
1222 NoSignedWrap &= OpNoSignedWrap;
1223 if (NoSignedWrap != OpNoSignedWrap) {
1224 BO->setHasNoSignedWrap(NoSignedWrap);
1225 Worklist.Add(Ancestor);
1226 }
1227 } else if (Ancestor->getOpcode() == Instruction::Trunc) {
1228 // The fact that the descaled input to the trunc has smaller absolute
1229 // value than the original input doesn't tell us anything useful about
1230 // the absolute values of the truncations.
1231 NoSignedWrap = false;
1232 }
1233 assert((Ancestor->getOpcode() != Instruction::SExt || NoSignedWrap) &&
1234 "Failed to keep proper track of nsw flags while drilling down?");
1235
1236 if (Ancestor == Val)
1237 // Got to the top, all done!
1238 return Val;
1239
1240 // Move up one level in the expression.
1241 assert(Ancestor->hasOneUse() && "Drilled down when more than one use!");
Chandler Carruthcdf47882014-03-09 03:16:01 +00001242 Ancestor = Ancestor->user_back();
Duncan Sands533c8ae2012-10-23 08:28:26 +00001243 } while (1);
1244}
1245
Serge Pavlov9ef66a82014-05-11 08:46:12 +00001246/// \brief Creates node of binary operation with the same attributes as the
1247/// specified one but with other operands.
Serge Pavlove6de9e32014-05-14 09:05:09 +00001248static Value *CreateBinOpAsGiven(BinaryOperator &Inst, Value *LHS, Value *RHS,
1249 InstCombiner::BuilderTy *B) {
Sanjay Patel968e91a2015-11-24 17:51:20 +00001250 Value *BO = B->CreateBinOp(Inst.getOpcode(), LHS, RHS);
1251 // If LHS and RHS are constant, BO won't be a binary operator.
1252 if (BinaryOperator *NewBO = dyn_cast<BinaryOperator>(BO))
1253 NewBO->copyIRFlags(&Inst);
1254 return BO;
Serge Pavlov9ef66a82014-05-11 08:46:12 +00001255}
1256
1257/// \brief Makes transformation of binary operation specific for vector types.
1258/// \param Inst Binary operator to transform.
1259/// \return Pointer to node that must replace the original binary operator, or
1260/// null pointer if no transformation was made.
1261Value *InstCombiner::SimplifyVectorOp(BinaryOperator &Inst) {
1262 if (!Inst.getType()->isVectorTy()) return nullptr;
1263
Sanjay Patel58814442014-07-09 16:34:54 +00001264 // It may not be safe to reorder shuffles and things like div, urem, etc.
1265 // because we may trap when executing those ops on unknown vector elements.
1266 // See PR20059.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001267 if (!isSafeToSpeculativelyExecute(&Inst))
1268 return nullptr;
Sanjay Patel58814442014-07-09 16:34:54 +00001269
Serge Pavlov9ef66a82014-05-11 08:46:12 +00001270 unsigned VWidth = cast<VectorType>(Inst.getType())->getNumElements();
1271 Value *LHS = Inst.getOperand(0), *RHS = Inst.getOperand(1);
1272 assert(cast<VectorType>(LHS->getType())->getNumElements() == VWidth);
1273 assert(cast<VectorType>(RHS->getType())->getNumElements() == VWidth);
1274
1275 // If both arguments of binary operation are shuffles, which use the same
1276 // mask and shuffle within a single vector, it is worthwhile to move the
1277 // shuffle after binary operation:
1278 // Op(shuffle(v1, m), shuffle(v2, m)) -> shuffle(Op(v1, v2), m)
1279 if (isa<ShuffleVectorInst>(LHS) && isa<ShuffleVectorInst>(RHS)) {
1280 ShuffleVectorInst *LShuf = cast<ShuffleVectorInst>(LHS);
1281 ShuffleVectorInst *RShuf = cast<ShuffleVectorInst>(RHS);
1282 if (isa<UndefValue>(LShuf->getOperand(1)) &&
1283 isa<UndefValue>(RShuf->getOperand(1)) &&
Serge Pavlov05811092014-05-12 05:44:53 +00001284 LShuf->getOperand(0)->getType() == RShuf->getOperand(0)->getType() &&
Serge Pavlov9ef66a82014-05-11 08:46:12 +00001285 LShuf->getMask() == RShuf->getMask()) {
Serge Pavlove6de9e32014-05-14 09:05:09 +00001286 Value *NewBO = CreateBinOpAsGiven(Inst, LShuf->getOperand(0),
Serge Pavlov9ef66a82014-05-11 08:46:12 +00001287 RShuf->getOperand(0), Builder);
Sanjay Patel1f3fa212015-11-21 16:37:09 +00001288 return Builder->CreateShuffleVector(NewBO,
Serge Pavlov02ff6202014-05-12 10:11:27 +00001289 UndefValue::get(NewBO->getType()), LShuf->getMask());
Serge Pavlov9ef66a82014-05-11 08:46:12 +00001290 }
1291 }
1292
1293 // If one argument is a shuffle within one vector, the other is a constant,
1294 // try moving the shuffle after the binary operation.
1295 ShuffleVectorInst *Shuffle = nullptr;
1296 Constant *C1 = nullptr;
1297 if (isa<ShuffleVectorInst>(LHS)) Shuffle = cast<ShuffleVectorInst>(LHS);
1298 if (isa<ShuffleVectorInst>(RHS)) Shuffle = cast<ShuffleVectorInst>(RHS);
1299 if (isa<Constant>(LHS)) C1 = cast<Constant>(LHS);
1300 if (isa<Constant>(RHS)) C1 = cast<Constant>(RHS);
Benjamin Kramer6de78662014-06-24 10:38:10 +00001301 if (Shuffle && C1 &&
1302 (isa<ConstantVector>(C1) || isa<ConstantDataVector>(C1)) &&
1303 isa<UndefValue>(Shuffle->getOperand(1)) &&
Serge Pavlov9ef66a82014-05-11 08:46:12 +00001304 Shuffle->getType() == Shuffle->getOperand(0)->getType()) {
1305 SmallVector<int, 16> ShMask = Shuffle->getShuffleMask();
1306 // Find constant C2 that has property:
1307 // shuffle(C2, ShMask) = C1
1308 // If such constant does not exist (example: ShMask=<0,0> and C1=<1,2>)
1309 // reorder is not possible.
1310 SmallVector<Constant*, 16> C2M(VWidth,
1311 UndefValue::get(C1->getType()->getScalarType()));
1312 bool MayChange = true;
1313 for (unsigned I = 0; I < VWidth; ++I) {
1314 if (ShMask[I] >= 0) {
1315 assert(ShMask[I] < (int)VWidth);
1316 if (!isa<UndefValue>(C2M[ShMask[I]])) {
1317 MayChange = false;
1318 break;
1319 }
1320 C2M[ShMask[I]] = C1->getAggregateElement(I);
1321 }
1322 }
1323 if (MayChange) {
1324 Constant *C2 = ConstantVector::get(C2M);
Sanjay Patel04df5832015-11-21 16:51:19 +00001325 Value *NewLHS = isa<Constant>(LHS) ? C2 : Shuffle->getOperand(0);
1326 Value *NewRHS = isa<Constant>(LHS) ? Shuffle->getOperand(0) : C2;
Serge Pavlove6de9e32014-05-14 09:05:09 +00001327 Value *NewBO = CreateBinOpAsGiven(Inst, NewLHS, NewRHS, Builder);
Sanjay Patel1f3fa212015-11-21 16:37:09 +00001328 return Builder->CreateShuffleVector(NewBO,
Serge Pavlov9ef66a82014-05-11 08:46:12 +00001329 UndefValue::get(Inst.getType()), Shuffle->getMask());
Serge Pavlov9ef66a82014-05-11 08:46:12 +00001330 }
1331 }
1332
1333 return nullptr;
1334}
1335
Chris Lattner113f4f42002-06-25 16:13:24 +00001336Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
Chris Lattner8574aba2009-11-27 00:29:05 +00001337 SmallVector<Value*, 8> Ops(GEP.op_begin(), GEP.op_end());
1338
Manuel Jacob20c6d5b2016-01-17 22:46:43 +00001339 if (Value *V = SimplifyGEPInst(GEP.getSourceElementType(), Ops, DL, TLI, DT, AC))
Sanjay Patel4b198802016-02-01 22:23:39 +00001340 return replaceInstUsesWith(GEP, V);
Chris Lattner8574aba2009-11-27 00:29:05 +00001341
Chris Lattner5f667a62004-05-07 22:09:22 +00001342 Value *PtrOp = GEP.getOperand(0);
Chris Lattner8d0bacb2004-02-22 05:25:17 +00001343
Duncan Sandsc133c542010-11-22 16:32:50 +00001344 // Eliminate unneeded casts for indices, and replace indices which displace
1345 // by multiples of a zero size type with zero.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001346 bool MadeChange = false;
Elena Demikhovsky121d49b2015-11-15 08:19:35 +00001347 Type *IntPtrTy =
1348 DL.getIntPtrType(GEP.getPointerOperandType()->getScalarType());
Duncan Sandsc133c542010-11-22 16:32:50 +00001349
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001350 gep_type_iterator GTI = gep_type_begin(GEP);
1351 for (User::op_iterator I = GEP.op_begin() + 1, E = GEP.op_end(); I != E;
1352 ++I, ++GTI) {
1353 // Skip indices into struct types.
Eduard Burtescu19eb0312016-01-19 17:28:00 +00001354 if (isa<StructType>(*GTI))
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001355 continue;
Duncan Sandsc133c542010-11-22 16:32:50 +00001356
Elena Demikhovsky121d49b2015-11-15 08:19:35 +00001357 // Index type should have the same width as IntPtr
1358 Type *IndexTy = (*I)->getType();
1359 Type *NewIndexType = IndexTy->isVectorTy() ?
1360 VectorType::get(IntPtrTy, IndexTy->getVectorNumElements()) : IntPtrTy;
Eduard Burtescu19eb0312016-01-19 17:28:00 +00001361
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001362 // If the element type has zero size then any index over it is equivalent
1363 // to an index of zero, so replace it with zero if it is not zero already.
Eduard Burtescu19eb0312016-01-19 17:28:00 +00001364 Type *EltTy = GTI.getIndexedType();
1365 if (EltTy->isSized() && DL.getTypeAllocSize(EltTy) == 0)
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001366 if (!isa<Constant>(*I) || !cast<Constant>(*I)->isNullValue()) {
Elena Demikhovsky121d49b2015-11-15 08:19:35 +00001367 *I = Constant::getNullValue(NewIndexType);
Duncan Sandsc133c542010-11-22 16:32:50 +00001368 MadeChange = true;
1369 }
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001370
Elena Demikhovsky121d49b2015-11-15 08:19:35 +00001371 if (IndexTy != NewIndexType) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001372 // If we are using a wider index than needed for this platform, shrink
1373 // it to what we need. If narrower, sign-extend it to what we need.
1374 // This explicit cast can make subsequent optimizations more obvious.
Elena Demikhovsky121d49b2015-11-15 08:19:35 +00001375 *I = Builder->CreateIntCast(*I, NewIndexType, true);
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001376 MadeChange = true;
Chris Lattner69193f92004-04-05 01:30:19 +00001377 }
Chris Lattner9bf53ff2007-03-25 20:43:09 +00001378 }
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001379 if (MadeChange)
1380 return &GEP;
Chris Lattner69193f92004-04-05 01:30:19 +00001381
Louis Gerbargc6b506a2014-05-29 20:29:47 +00001382 // Check to see if the inputs to the PHI node are getelementptr instructions.
1383 if (PHINode *PN = dyn_cast<PHINode>(PtrOp)) {
1384 GetElementPtrInst *Op1 = dyn_cast<GetElementPtrInst>(PN->getOperand(0));
1385 if (!Op1)
1386 return nullptr;
1387
Daniel Jasper5add63f2015-03-19 11:05:08 +00001388 // Don't fold a GEP into itself through a PHI node. This can only happen
1389 // through the back-edge of a loop. Folding a GEP into itself means that
1390 // the value of the previous iteration needs to be stored in the meantime,
1391 // thus requiring an additional register variable to be live, but not
1392 // actually achieving anything (the GEP still needs to be executed once per
1393 // loop iteration).
1394 if (Op1 == &GEP)
1395 return nullptr;
1396
Louis Gerbargc6b506a2014-05-29 20:29:47 +00001397 signed DI = -1;
1398
1399 for (auto I = PN->op_begin()+1, E = PN->op_end(); I !=E; ++I) {
1400 GetElementPtrInst *Op2 = dyn_cast<GetElementPtrInst>(*I);
1401 if (!Op2 || Op1->getNumOperands() != Op2->getNumOperands())
1402 return nullptr;
1403
Daniel Jasper5add63f2015-03-19 11:05:08 +00001404 // As for Op1 above, don't try to fold a GEP into itself.
1405 if (Op2 == &GEP)
1406 return nullptr;
1407
Chandler Carruth3012a1b2014-05-29 23:05:52 +00001408 // Keep track of the type as we walk the GEP.
Eduard Burtescu19eb0312016-01-19 17:28:00 +00001409 Type *CurTy = nullptr;
Chandler Carruth3012a1b2014-05-29 23:05:52 +00001410
Louis Gerbargc6b506a2014-05-29 20:29:47 +00001411 for (unsigned J = 0, F = Op1->getNumOperands(); J != F; ++J) {
1412 if (Op1->getOperand(J)->getType() != Op2->getOperand(J)->getType())
1413 return nullptr;
1414
1415 if (Op1->getOperand(J) != Op2->getOperand(J)) {
1416 if (DI == -1) {
1417 // We have not seen any differences yet in the GEPs feeding the
1418 // PHI yet, so we record this one if it is allowed to be a
1419 // variable.
1420
1421 // The first two arguments can vary for any GEP, the rest have to be
1422 // static for struct slots
Chandler Carruth3012a1b2014-05-29 23:05:52 +00001423 if (J > 1 && CurTy->isStructTy())
1424 return nullptr;
Louis Gerbargc6b506a2014-05-29 20:29:47 +00001425
1426 DI = J;
1427 } else {
1428 // The GEP is different by more than one input. While this could be
1429 // extended to support GEPs that vary by more than one variable it
1430 // doesn't make sense since it greatly increases the complexity and
1431 // would result in an R+R+R addressing mode which no backend
1432 // directly supports and would need to be broken into several
1433 // simpler instructions anyway.
1434 return nullptr;
1435 }
1436 }
Chandler Carruthfdc0e0b2014-05-29 23:21:12 +00001437
1438 // Sink down a layer of the type for the next iteration.
1439 if (J > 0) {
Eduard Burtescu19eb0312016-01-19 17:28:00 +00001440 if (J == 1) {
1441 CurTy = Op1->getSourceElementType();
1442 } else if (CompositeType *CT = dyn_cast<CompositeType>(CurTy)) {
Chandler Carruthfdc0e0b2014-05-29 23:21:12 +00001443 CurTy = CT->getTypeAtIndex(Op1->getOperand(J));
1444 } else {
1445 CurTy = nullptr;
1446 }
1447 }
Louis Gerbargc6b506a2014-05-29 20:29:47 +00001448 }
1449 }
1450
Silviu Barangab892e352015-10-26 10:25:05 +00001451 // If not all GEPs are identical we'll have to create a new PHI node.
1452 // Check that the old PHI node has only one use so that it will get
1453 // removed.
1454 if (DI != -1 && !PN->hasOneUse())
1455 return nullptr;
Louis Gerbargc6b506a2014-05-29 20:29:47 +00001456
Silviu Barangab892e352015-10-26 10:25:05 +00001457 GetElementPtrInst *NewGEP = cast<GetElementPtrInst>(Op1->clone());
Louis Gerbargc6b506a2014-05-29 20:29:47 +00001458 if (DI == -1) {
1459 // All the GEPs feeding the PHI are identical. Clone one down into our
1460 // BB so that it can be merged with the current GEP.
Akira Hatanaka1defd5a2015-02-18 03:30:11 +00001461 GEP.getParent()->getInstList().insert(
1462 GEP.getParent()->getFirstInsertionPt(), NewGEP);
Louis Gerbargc6b506a2014-05-29 20:29:47 +00001463 } else {
1464 // All the GEPs feeding the PHI differ at a single offset. Clone a GEP
1465 // into the current block so it can be merged, and create a new PHI to
1466 // set that index.
Duncan P. N. Exon Smith9f8aaf22015-10-13 16:59:33 +00001467 PHINode *NewPN;
1468 {
1469 IRBuilderBase::InsertPointGuard Guard(*Builder);
1470 Builder->SetInsertPoint(PN);
1471 NewPN = Builder->CreatePHI(Op1->getOperand(DI)->getType(),
1472 PN->getNumOperands());
1473 }
Louis Gerbargc6b506a2014-05-29 20:29:47 +00001474
1475 for (auto &I : PN->operands())
1476 NewPN->addIncoming(cast<GEPOperator>(I)->getOperand(DI),
1477 PN->getIncomingBlock(I));
1478
1479 NewGEP->setOperand(DI, NewPN);
Akira Hatanaka1defd5a2015-02-18 03:30:11 +00001480 GEP.getParent()->getInstList().insert(
1481 GEP.getParent()->getFirstInsertionPt(), NewGEP);
Louis Gerbargc6b506a2014-05-29 20:29:47 +00001482 NewGEP->setOperand(DI, NewPN);
1483 }
1484
1485 GEP.setOperand(0, NewGEP);
1486 PtrOp = NewGEP;
1487 }
1488
Chris Lattnerae7a0d32002-08-02 19:29:35 +00001489 // Combine Indices - If the source pointer to this getelementptr instruction
1490 // is a getelementptr instruction, combine the indices of the two
1491 // getelementptr instructions into a single instruction.
1492 //
Dan Gohman31a9b982009-07-28 01:40:03 +00001493 if (GEPOperator *Src = dyn_cast<GEPOperator>(PtrOp)) {
Rafael Espindolaa3a44f3f2011-07-31 04:43:41 +00001494 if (!shouldMergeGEPs(*cast<GEPOperator>(&GEP), *Src))
Craig Topperf40110f2014-04-25 05:29:35 +00001495 return nullptr;
Rafael Espindola40325672011-07-11 03:43:47 +00001496
Duncan Sands533c8ae2012-10-23 08:28:26 +00001497 // Note that if our source is a gep chain itself then we wait for that
Chris Lattner5f667a62004-05-07 22:09:22 +00001498 // chain to be resolved before we perform this transformation. This
1499 // avoids us creating a TON of code in some cases.
Rafael Espindolaa3a44f3f2011-07-31 04:43:41 +00001500 if (GEPOperator *SrcGEP =
1501 dyn_cast<GEPOperator>(Src->getOperand(0)))
1502 if (SrcGEP->getNumOperands() == 2 && shouldMergeGEPs(*Src, *SrcGEP))
Craig Topperf40110f2014-04-25 05:29:35 +00001503 return nullptr; // Wait until our source is folded to completion.
Chris Lattner5f667a62004-05-07 22:09:22 +00001504
Chris Lattneraf6094f2007-02-15 22:48:32 +00001505 SmallVector<Value*, 8> Indices;
Chris Lattner5f667a62004-05-07 22:09:22 +00001506
1507 // Find out whether the last index in the source GEP is a sequential idx.
1508 bool EndsWithSequential = false;
Chris Lattnerb2995e12009-08-30 05:30:55 +00001509 for (gep_type_iterator I = gep_type_begin(*Src), E = gep_type_end(*Src);
1510 I != E; ++I)
Duncan Sands19d0b472010-02-16 11:11:14 +00001511 EndsWithSequential = !(*I)->isStructTy();
Misha Brukmanb1c93172005-04-21 23:48:37 +00001512
Chris Lattnerae7a0d32002-08-02 19:29:35 +00001513 // Can we combine the two pointer arithmetics offsets?
Chris Lattner5f667a62004-05-07 22:09:22 +00001514 if (EndsWithSequential) {
Chris Lattner235af562003-03-05 22:33:14 +00001515 // Replace: gep (gep %P, long B), long A, ...
1516 // With: T = long A+B; gep %P, T, ...
1517 //
Chris Lattner06c687b2009-08-30 05:08:50 +00001518 Value *Sum;
1519 Value *SO1 = Src->getOperand(Src->getNumOperands()-1);
1520 Value *GO1 = GEP.getOperand(1);
Owen Anderson5a1acd92009-07-31 20:28:14 +00001521 if (SO1 == Constant::getNullValue(SO1->getType())) {
Chris Lattner69193f92004-04-05 01:30:19 +00001522 Sum = GO1;
Owen Anderson5a1acd92009-07-31 20:28:14 +00001523 } else if (GO1 == Constant::getNullValue(GO1->getType())) {
Chris Lattner69193f92004-04-05 01:30:19 +00001524 Sum = SO1;
1525 } else {
Chris Lattnerb2995e12009-08-30 05:30:55 +00001526 // If they aren't the same type, then the input hasn't been processed
1527 // by the loop above yet (which canonicalizes sequential index types to
1528 // intptr_t). Just avoid transforming this until the input has been
1529 // normalized.
1530 if (SO1->getType() != GO1->getType())
Craig Topperf40110f2014-04-25 05:29:35 +00001531 return nullptr;
Wei Mia0adf9f2015-04-21 23:02:15 +00001532 // Only do the combine when GO1 and SO1 are both constants. Only in
1533 // this case, we are sure the cost after the merge is never more than
1534 // that before the merge.
1535 if (!isa<Constant>(GO1) || !isa<Constant>(SO1))
1536 return nullptr;
Chris Lattner59663412009-08-30 18:50:58 +00001537 Sum = Builder->CreateAdd(SO1, GO1, PtrOp->getName()+".sum");
Chris Lattner69193f92004-04-05 01:30:19 +00001538 }
Chris Lattner5f667a62004-05-07 22:09:22 +00001539
Chris Lattnerb2995e12009-08-30 05:30:55 +00001540 // Update the GEP in place if possible.
Chris Lattner06c687b2009-08-30 05:08:50 +00001541 if (Src->getNumOperands() == 2) {
1542 GEP.setOperand(0, Src->getOperand(0));
Chris Lattner5f667a62004-05-07 22:09:22 +00001543 GEP.setOperand(1, Sum);
1544 return &GEP;
Chris Lattner5f667a62004-05-07 22:09:22 +00001545 }
Chris Lattnerb2995e12009-08-30 05:30:55 +00001546 Indices.append(Src->op_begin()+1, Src->op_end()-1);
Chris Lattnerd7b6e912009-08-30 04:49:01 +00001547 Indices.push_back(Sum);
Chris Lattnerb2995e12009-08-30 05:30:55 +00001548 Indices.append(GEP.op_begin()+2, GEP.op_end());
Misha Brukmanb1c93172005-04-21 23:48:37 +00001549 } else if (isa<Constant>(*GEP.idx_begin()) &&
Chris Lattner69193f92004-04-05 01:30:19 +00001550 cast<Constant>(*GEP.idx_begin())->isNullValue() &&
Chris Lattner06c687b2009-08-30 05:08:50 +00001551 Src->getNumOperands() != 1) {
Chris Lattnerae7a0d32002-08-02 19:29:35 +00001552 // Otherwise we can do the fold if the first index of the GEP is a zero
Chris Lattnerb2995e12009-08-30 05:30:55 +00001553 Indices.append(Src->op_begin()+1, Src->op_end());
1554 Indices.append(GEP.idx_begin()+1, GEP.idx_end());
Chris Lattnerae7a0d32002-08-02 19:29:35 +00001555 }
1556
Dan Gohman1b849082009-09-07 23:54:19 +00001557 if (!Indices.empty())
David Blaikie096b1da2015-03-14 19:53:33 +00001558 return GEP.isInBounds() && Src->isInBounds()
1559 ? GetElementPtrInst::CreateInBounds(
1560 Src->getSourceElementType(), Src->getOperand(0), Indices,
1561 GEP.getName())
1562 : GetElementPtrInst::Create(Src->getSourceElementType(),
1563 Src->getOperand(0), Indices,
1564 GEP.getName());
Chris Lattnere26bf172009-08-30 05:00:50 +00001565 }
Nadav Rotema069c6c2011-04-05 14:29:52 +00001566
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001567 if (GEP.getNumIndices() == 1) {
Matt Arsenaultbfa37e52013-10-03 18:15:57 +00001568 unsigned AS = GEP.getPointerAddressSpace();
David Majnemerd2df5012014-09-01 21:10:02 +00001569 if (GEP.getOperand(1)->getType()->getScalarSizeInBits() ==
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001570 DL.getPointerSizeInBits(AS)) {
Eduard Burtescu19eb0312016-01-19 17:28:00 +00001571 Type *Ty = GEP.getSourceElementType();
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001572 uint64_t TyAllocSize = DL.getTypeAllocSize(Ty);
David Majnemerd2df5012014-09-01 21:10:02 +00001573
1574 bool Matched = false;
1575 uint64_t C;
1576 Value *V = nullptr;
1577 if (TyAllocSize == 1) {
1578 V = GEP.getOperand(1);
1579 Matched = true;
1580 } else if (match(GEP.getOperand(1),
1581 m_AShr(m_Value(V), m_ConstantInt(C)))) {
1582 if (TyAllocSize == 1ULL << C)
1583 Matched = true;
1584 } else if (match(GEP.getOperand(1),
1585 m_SDiv(m_Value(V), m_ConstantInt(C)))) {
1586 if (TyAllocSize == C)
1587 Matched = true;
1588 }
1589
1590 if (Matched) {
1591 // Canonicalize (gep i8* X, -(ptrtoint Y))
1592 // to (inttoptr (sub (ptrtoint X), (ptrtoint Y)))
1593 // The GEP pattern is emitted by the SCEV expander for certain kinds of
1594 // pointer arithmetic.
1595 if (match(V, m_Neg(m_PtrToInt(m_Value())))) {
1596 Operator *Index = cast<Operator>(V);
1597 Value *PtrToInt = Builder->CreatePtrToInt(PtrOp, Index->getType());
1598 Value *NewSub = Builder->CreateSub(PtrToInt, Index->getOperand(1));
1599 return CastInst::Create(Instruction::IntToPtr, NewSub, GEP.getType());
1600 }
1601 // Canonicalize (gep i8* X, (ptrtoint Y)-(ptrtoint X))
1602 // to (bitcast Y)
1603 Value *Y;
1604 if (match(V, m_Sub(m_PtrToInt(m_Value(Y)),
1605 m_PtrToInt(m_Specific(GEP.getOperand(0)))))) {
1606 return CastInst::CreatePointerBitCastOrAddrSpaceCast(Y,
1607 GEP.getType());
1608 }
1609 }
Matt Arsenaultbfa37e52013-10-03 18:15:57 +00001610 }
Benjamin Kramere6461e32013-09-20 14:38:44 +00001611 }
1612
Chris Lattner06c687b2009-08-30 05:08:50 +00001613 // Handle gep(bitcast x) and gep(gep x, 0, 0, 0).
Chris Lattnere903f382010-01-05 07:42:10 +00001614 Value *StrippedPtr = PtrOp->stripPointerCasts();
Nadav Roteme63e59c2012-03-26 20:39:18 +00001615 PointerType *StrippedPtrTy = dyn_cast<PointerType>(StrippedPtr->getType());
1616
Nadav Rotema8f35622012-03-26 21:00:53 +00001617 // We do not handle pointer-vector geps here.
1618 if (!StrippedPtrTy)
Craig Topperf40110f2014-04-25 05:29:35 +00001619 return nullptr;
Nadav Rotema8f35622012-03-26 21:00:53 +00001620
Matt Arsenaultaa689f52014-02-14 00:49:12 +00001621 if (StrippedPtr != PtrOp) {
Chris Lattner8574aba2009-11-27 00:29:05 +00001622 bool HasZeroPointerIndex = false;
1623 if (ConstantInt *C = dyn_cast<ConstantInt>(GEP.getOperand(1)))
1624 HasZeroPointerIndex = C->isZero();
Nadav Rotema069c6c2011-04-05 14:29:52 +00001625
Chris Lattnerc2f2cf82009-08-30 20:36:46 +00001626 // Transform: GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ...
1627 // into : GEP [10 x i8]* X, i32 0, ...
1628 //
1629 // Likewise, transform: GEP (bitcast i8* X to [0 x i8]*), i32 0, ...
1630 // into : GEP i8* X, ...
Nadav Rotema069c6c2011-04-05 14:29:52 +00001631 //
Chris Lattnerc2f2cf82009-08-30 20:36:46 +00001632 // This occurs when the program declares an array extern like "int X[];"
Chris Lattnere26bf172009-08-30 05:00:50 +00001633 if (HasZeroPointerIndex) {
Chris Lattner229907c2011-07-18 04:54:35 +00001634 if (ArrayType *CATy =
Eduard Burtescu19eb0312016-01-19 17:28:00 +00001635 dyn_cast<ArrayType>(GEP.getSourceElementType())) {
Duncan Sands5795a602009-03-02 09:18:21 +00001636 // GEP (bitcast i8* X to [0 x i8]*), i32 0, ... ?
Chris Lattnere903f382010-01-05 07:42:10 +00001637 if (CATy->getElementType() == StrippedPtrTy->getElementType()) {
Duncan Sands5795a602009-03-02 09:18:21 +00001638 // -> GEP i8* X, ...
Chris Lattnere903f382010-01-05 07:42:10 +00001639 SmallVector<Value*, 8> Idx(GEP.idx_begin()+1, GEP.idx_end());
David Blaikie096b1da2015-03-14 19:53:33 +00001640 GetElementPtrInst *Res = GetElementPtrInst::Create(
1641 StrippedPtrTy->getElementType(), StrippedPtr, Idx, GEP.getName());
Chris Lattnere903f382010-01-05 07:42:10 +00001642 Res->setIsInBounds(GEP.isInBounds());
Eli Bendersky9966b262014-04-03 17:51:58 +00001643 if (StrippedPtrTy->getAddressSpace() == GEP.getAddressSpace())
1644 return Res;
1645 // Insert Res, and create an addrspacecast.
1646 // e.g.,
1647 // GEP (addrspacecast i8 addrspace(1)* X to [0 x i8]*), i32 0, ...
1648 // ->
1649 // %0 = GEP i8 addrspace(1)* X, ...
1650 // addrspacecast i8 addrspace(1)* %0 to i8*
1651 return new AddrSpaceCastInst(Builder->Insert(Res), GEP.getType());
Chris Lattnerc2f2cf82009-08-30 20:36:46 +00001652 }
Jakub Staszakcfc46f82012-05-06 13:52:31 +00001653
Chris Lattner229907c2011-07-18 04:54:35 +00001654 if (ArrayType *XATy =
Chris Lattnere903f382010-01-05 07:42:10 +00001655 dyn_cast<ArrayType>(StrippedPtrTy->getElementType())){
Duncan Sands5795a602009-03-02 09:18:21 +00001656 // GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ... ?
Chris Lattner567b81f2005-09-13 00:40:14 +00001657 if (CATy->getElementType() == XATy->getElementType()) {
Duncan Sands5795a602009-03-02 09:18:21 +00001658 // -> GEP [10 x i8]* X, i32 0, ...
Chris Lattner567b81f2005-09-13 00:40:14 +00001659 // At this point, we know that the cast source type is a pointer
1660 // to an array of the same type as the destination pointer
1661 // array. Because the array type is never stepped over (there
1662 // is a leading zero) we can fold the cast into this GEP.
Eli Bendersky9966b262014-04-03 17:51:58 +00001663 if (StrippedPtrTy->getAddressSpace() == GEP.getAddressSpace()) {
1664 GEP.setOperand(0, StrippedPtr);
David Blaikie73cf8722015-05-05 18:03:48 +00001665 GEP.setSourceElementType(XATy);
Eli Bendersky9966b262014-04-03 17:51:58 +00001666 return &GEP;
1667 }
1668 // Cannot replace the base pointer directly because StrippedPtr's
1669 // address space is different. Instead, create a new GEP followed by
1670 // an addrspacecast.
1671 // e.g.,
1672 // GEP (addrspacecast [10 x i8] addrspace(1)* X to [0 x i8]*),
1673 // i32 0, ...
1674 // ->
1675 // %0 = GEP [10 x i8] addrspace(1)* X, ...
1676 // addrspacecast i8 addrspace(1)* %0 to i8*
1677 SmallVector<Value*, 8> Idx(GEP.idx_begin(), GEP.idx_end());
David Blaikieaa41cd52015-04-03 21:33:42 +00001678 Value *NewGEP = GEP.isInBounds()
1679 ? Builder->CreateInBoundsGEP(
1680 nullptr, StrippedPtr, Idx, GEP.getName())
1681 : Builder->CreateGEP(nullptr, StrippedPtr, Idx,
1682 GEP.getName());
Eli Bendersky9966b262014-04-03 17:51:58 +00001683 return new AddrSpaceCastInst(NewGEP, GEP.getType());
Chris Lattner567b81f2005-09-13 00:40:14 +00001684 }
Duncan Sands5795a602009-03-02 09:18:21 +00001685 }
1686 }
Chris Lattner567b81f2005-09-13 00:40:14 +00001687 } else if (GEP.getNumOperands() == 2) {
1688 // Transform things like:
Wojciech Matyjewicz309e5a72007-12-12 15:21:32 +00001689 // %t = getelementptr i32* bitcast ([2 x i32]* %str to i32*), i32 %V
1690 // into: %t1 = getelementptr [2 x i32]* %str, i32 0, i32 %V; bitcast
Chris Lattner229907c2011-07-18 04:54:35 +00001691 Type *SrcElTy = StrippedPtrTy->getElementType();
Eduard Burtescu19eb0312016-01-19 17:28:00 +00001692 Type *ResElTy = GEP.getSourceElementType();
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001693 if (SrcElTy->isArrayTy() &&
1694 DL.getTypeAllocSize(SrcElTy->getArrayElementType()) ==
1695 DL.getTypeAllocSize(ResElTy)) {
1696 Type *IdxType = DL.getIntPtrType(GEP.getType());
Matt Arsenault9e3a6ca2013-08-14 00:24:38 +00001697 Value *Idx[2] = { Constant::getNullValue(IdxType), GEP.getOperand(1) };
David Blaikie68d535c2015-03-24 22:38:16 +00001698 Value *NewGEP =
1699 GEP.isInBounds()
David Blaikieaa41cd52015-04-03 21:33:42 +00001700 ? Builder->CreateInBoundsGEP(nullptr, StrippedPtr, Idx,
1701 GEP.getName())
1702 : Builder->CreateGEP(nullptr, StrippedPtr, Idx, GEP.getName());
Matt Arsenaultaa689f52014-02-14 00:49:12 +00001703
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001704 // V and GEP are both pointer types --> BitCast
Manuel Jacob405fb182014-07-16 20:13:45 +00001705 return CastInst::CreatePointerBitCastOrAddrSpaceCast(NewGEP,
1706 GEP.getType());
Chris Lattner8d0bacb2004-02-22 05:25:17 +00001707 }
Jakub Staszakcfc46f82012-05-06 13:52:31 +00001708
Chris Lattner2a893292005-09-13 18:36:04 +00001709 // Transform things like:
Duncan Sands533c8ae2012-10-23 08:28:26 +00001710 // %V = mul i64 %N, 4
1711 // %t = getelementptr i8* bitcast (i32* %arr to i8*), i32 %V
1712 // into: %t1 = getelementptr i32* %arr, i32 %N; bitcast
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001713 if (ResElTy->isSized() && SrcElTy->isSized()) {
Duncan Sands533c8ae2012-10-23 08:28:26 +00001714 // Check that changing the type amounts to dividing the index by a scale
1715 // factor.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001716 uint64_t ResSize = DL.getTypeAllocSize(ResElTy);
1717 uint64_t SrcSize = DL.getTypeAllocSize(SrcElTy);
Duncan Sands533c8ae2012-10-23 08:28:26 +00001718 if (ResSize && SrcSize % ResSize == 0) {
1719 Value *Idx = GEP.getOperand(1);
1720 unsigned BitWidth = Idx->getType()->getPrimitiveSizeInBits();
1721 uint64_t Scale = SrcSize / ResSize;
1722
1723 // Earlier transforms ensure that the index has type IntPtrType, which
1724 // considerably simplifies the logic by eliminating implicit casts.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001725 assert(Idx->getType() == DL.getIntPtrType(GEP.getType()) &&
Duncan Sands533c8ae2012-10-23 08:28:26 +00001726 "Index not cast to pointer width?");
1727
1728 bool NSW;
1729 if (Value *NewIdx = Descale(Idx, APInt(BitWidth, Scale), NSW)) {
1730 // Successfully decomposed Idx as NewIdx * Scale, form a new GEP.
1731 // If the multiplication NewIdx * Scale may overflow then the new
1732 // GEP may not be "inbounds".
David Blaikie68d535c2015-03-24 22:38:16 +00001733 Value *NewGEP =
1734 GEP.isInBounds() && NSW
David Blaikieaa41cd52015-04-03 21:33:42 +00001735 ? Builder->CreateInBoundsGEP(nullptr, StrippedPtr, NewIdx,
David Blaikie68d535c2015-03-24 22:38:16 +00001736 GEP.getName())
David Blaikieaa41cd52015-04-03 21:33:42 +00001737 : Builder->CreateGEP(nullptr, StrippedPtr, NewIdx,
1738 GEP.getName());
Matt Arsenaultaa689f52014-02-14 00:49:12 +00001739
Duncan Sands533c8ae2012-10-23 08:28:26 +00001740 // The NewGEP must be pointer typed, so must the old one -> BitCast
Manuel Jacob405fb182014-07-16 20:13:45 +00001741 return CastInst::CreatePointerBitCastOrAddrSpaceCast(NewGEP,
1742 GEP.getType());
Duncan Sands533c8ae2012-10-23 08:28:26 +00001743 }
1744 }
1745 }
1746
1747 // Similarly, transform things like:
Wojciech Matyjewicz309e5a72007-12-12 15:21:32 +00001748 // getelementptr i8* bitcast ([100 x double]* X to i8*), i32 %tmp
Chris Lattner2a893292005-09-13 18:36:04 +00001749 // (where tmp = 8*tmp2) into:
Wojciech Matyjewicz309e5a72007-12-12 15:21:32 +00001750 // getelementptr [100 x double]* %arr, i32 0, i32 %tmp2; bitcast
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001751 if (ResElTy->isSized() && SrcElTy->isSized() && SrcElTy->isArrayTy()) {
Duncan Sands533c8ae2012-10-23 08:28:26 +00001752 // Check that changing to the array element type amounts to dividing the
1753 // index by a scale factor.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001754 uint64_t ResSize = DL.getTypeAllocSize(ResElTy);
1755 uint64_t ArrayEltSize =
1756 DL.getTypeAllocSize(SrcElTy->getArrayElementType());
Duncan Sands533c8ae2012-10-23 08:28:26 +00001757 if (ResSize && ArrayEltSize % ResSize == 0) {
1758 Value *Idx = GEP.getOperand(1);
1759 unsigned BitWidth = Idx->getType()->getPrimitiveSizeInBits();
1760 uint64_t Scale = ArrayEltSize / ResSize;
Jakub Staszakcfc46f82012-05-06 13:52:31 +00001761
Duncan Sands533c8ae2012-10-23 08:28:26 +00001762 // Earlier transforms ensure that the index has type IntPtrType, which
1763 // considerably simplifies the logic by eliminating implicit casts.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001764 assert(Idx->getType() == DL.getIntPtrType(GEP.getType()) &&
Duncan Sands533c8ae2012-10-23 08:28:26 +00001765 "Index not cast to pointer width?");
1766
1767 bool NSW;
1768 if (Value *NewIdx = Descale(Idx, APInt(BitWidth, Scale), NSW)) {
1769 // Successfully decomposed Idx as NewIdx * Scale, form a new GEP.
1770 // If the multiplication NewIdx * Scale may overflow then the new
1771 // GEP may not be "inbounds".
Matt Arsenault9e3a6ca2013-08-14 00:24:38 +00001772 Value *Off[2] = {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001773 Constant::getNullValue(DL.getIntPtrType(GEP.getType())),
1774 NewIdx};
Matt Arsenault9e3a6ca2013-08-14 00:24:38 +00001775
David Blaikieaa41cd52015-04-03 21:33:42 +00001776 Value *NewGEP = GEP.isInBounds() && NSW
1777 ? Builder->CreateInBoundsGEP(
1778 SrcElTy, StrippedPtr, Off, GEP.getName())
1779 : Builder->CreateGEP(SrcElTy, StrippedPtr, Off,
1780 GEP.getName());
Duncan Sands533c8ae2012-10-23 08:28:26 +00001781 // The NewGEP must be pointer typed, so must the old one -> BitCast
Manuel Jacob405fb182014-07-16 20:13:45 +00001782 return CastInst::CreatePointerBitCastOrAddrSpaceCast(NewGEP,
1783 GEP.getType());
Chris Lattner2a893292005-09-13 18:36:04 +00001784 }
1785 }
Chris Lattner2a893292005-09-13 18:36:04 +00001786 }
Chris Lattner8d0bacb2004-02-22 05:25:17 +00001787 }
Chris Lattnerca081252001-12-14 16:52:21 +00001788 }
Nadav Rotema069c6c2011-04-05 14:29:52 +00001789
Matt Arsenault4815f092014-08-12 19:46:13 +00001790 // addrspacecast between types is canonicalized as a bitcast, then an
1791 // addrspacecast. To take advantage of the below bitcast + struct GEP, look
1792 // through the addrspacecast.
1793 if (AddrSpaceCastInst *ASC = dyn_cast<AddrSpaceCastInst>(PtrOp)) {
1794 // X = bitcast A addrspace(1)* to B addrspace(1)*
1795 // Y = addrspacecast A addrspace(1)* to B addrspace(2)*
1796 // Z = gep Y, <...constant indices...>
1797 // Into an addrspacecasted GEP of the struct.
1798 if (BitCastInst *BC = dyn_cast<BitCastInst>(ASC->getOperand(0)))
1799 PtrOp = BC;
1800 }
1801
Chris Lattnerfef138b2009-01-09 05:44:56 +00001802 /// See if we can simplify:
Chris Lattner97fd3592009-08-30 05:55:36 +00001803 /// X = bitcast A* to B*
Chris Lattnerfef138b2009-01-09 05:44:56 +00001804 /// Y = gep X, <...constant indices...>
1805 /// into a gep of the original struct. This is important for SROA and alias
1806 /// analysis of unions. If "A" is also a bitcast, wait for A/X to be merged.
Chris Lattnera784a2c2009-01-09 04:53:57 +00001807 if (BitCastInst *BCI = dyn_cast<BitCastInst>(PtrOp)) {
Matt Arsenault98f34e32013-08-19 22:17:34 +00001808 Value *Operand = BCI->getOperand(0);
1809 PointerType *OpType = cast<PointerType>(Operand->getType());
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001810 unsigned OffsetBits = DL.getPointerTypeSizeInBits(GEP.getType());
Matt Arsenault98f34e32013-08-19 22:17:34 +00001811 APInt Offset(OffsetBits, 0);
1812 if (!isa<BitCastInst>(Operand) &&
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001813 GEP.accumulateConstantOffset(DL, Offset)) {
Nadav Rotema069c6c2011-04-05 14:29:52 +00001814
Chris Lattnerfef138b2009-01-09 05:44:56 +00001815 // If this GEP instruction doesn't move the pointer, just replace the GEP
1816 // with a bitcast of the real input to the dest type.
Nuno Lopesb6ad9822012-12-30 16:25:48 +00001817 if (!Offset) {
Chris Lattnerfef138b2009-01-09 05:44:56 +00001818 // If the bitcast is of an allocation, and the allocation will be
1819 // converted to match the type of the cast, don't touch this.
Matt Arsenault98f34e32013-08-19 22:17:34 +00001820 if (isa<AllocaInst>(Operand) || isAllocationFn(Operand, TLI)) {
Chris Lattnerfef138b2009-01-09 05:44:56 +00001821 // See if the bitcast simplifies, if so, don't nuke this GEP yet.
1822 if (Instruction *I = visitBitCast(*BCI)) {
1823 if (I != BCI) {
1824 I->takeName(BCI);
Duncan P. N. Exon Smith9f8aaf22015-10-13 16:59:33 +00001825 BCI->getParent()->getInstList().insert(BCI->getIterator(), I);
Sanjay Patel4b198802016-02-01 22:23:39 +00001826 replaceInstUsesWith(*BCI, I);
Chris Lattnerfef138b2009-01-09 05:44:56 +00001827 }
1828 return &GEP;
Chris Lattnera784a2c2009-01-09 04:53:57 +00001829 }
Chris Lattnera784a2c2009-01-09 04:53:57 +00001830 }
Matt Arsenault4815f092014-08-12 19:46:13 +00001831
1832 if (Operand->getType()->getPointerAddressSpace() != GEP.getAddressSpace())
1833 return new AddrSpaceCastInst(Operand, GEP.getType());
Matt Arsenault98f34e32013-08-19 22:17:34 +00001834 return new BitCastInst(Operand, GEP.getType());
Chris Lattnera784a2c2009-01-09 04:53:57 +00001835 }
Jakub Staszakcfc46f82012-05-06 13:52:31 +00001836
Chris Lattnerfef138b2009-01-09 05:44:56 +00001837 // Otherwise, if the offset is non-zero, we need to find out if there is a
1838 // field at Offset in 'A's type. If so, we can pull the cast through the
1839 // GEP.
1840 SmallVector<Value*, 8> NewIndices;
Matt Arsenaultd79f7d92013-08-19 22:17:40 +00001841 if (FindElementAtOffset(OpType, Offset.getSExtValue(), NewIndices)) {
David Blaikieaa41cd52015-04-03 21:33:42 +00001842 Value *NGEP =
1843 GEP.isInBounds()
1844 ? Builder->CreateInBoundsGEP(nullptr, Operand, NewIndices)
1845 : Builder->CreateGEP(nullptr, Operand, NewIndices);
Jakub Staszakcfc46f82012-05-06 13:52:31 +00001846
Chris Lattner59663412009-08-30 18:50:58 +00001847 if (NGEP->getType() == GEP.getType())
Sanjay Patel4b198802016-02-01 22:23:39 +00001848 return replaceInstUsesWith(GEP, NGEP);
Chris Lattnerfef138b2009-01-09 05:44:56 +00001849 NGEP->takeName(&GEP);
Matt Arsenault4815f092014-08-12 19:46:13 +00001850
1851 if (NGEP->getType()->getPointerAddressSpace() != GEP.getAddressSpace())
1852 return new AddrSpaceCastInst(NGEP, GEP.getType());
Chris Lattnerfef138b2009-01-09 05:44:56 +00001853 return new BitCastInst(NGEP, GEP.getType());
1854 }
Chris Lattnera784a2c2009-01-09 04:53:57 +00001855 }
Jakub Staszakcfc46f82012-05-06 13:52:31 +00001856 }
1857
Craig Topperf40110f2014-04-25 05:29:35 +00001858 return nullptr;
Chris Lattnerca081252001-12-14 16:52:21 +00001859}
1860
Nuno Lopes95cc4f32012-07-09 18:38:20 +00001861static bool
Benjamin Kramer8bcc9712012-08-29 15:32:21 +00001862isAllocSiteRemovable(Instruction *AI, SmallVectorImpl<WeakVH> &Users,
1863 const TargetLibraryInfo *TLI) {
Nuno Lopes95cc4f32012-07-09 18:38:20 +00001864 SmallVector<Instruction*, 4> Worklist;
1865 Worklist.push_back(AI);
Nick Lewyckye8ae02d2011-08-02 22:08:01 +00001866
Nuno Lopes95cc4f32012-07-09 18:38:20 +00001867 do {
1868 Instruction *PI = Worklist.pop_back_val();
Chandler Carruthcdf47882014-03-09 03:16:01 +00001869 for (User *U : PI->users()) {
1870 Instruction *I = cast<Instruction>(U);
Nuno Lopes95cc4f32012-07-09 18:38:20 +00001871 switch (I->getOpcode()) {
1872 default:
1873 // Give up the moment we see something we can't handle.
Nuno Lopesfa0dffc2012-07-06 23:09:25 +00001874 return false;
Nuno Lopes95cc4f32012-07-09 18:38:20 +00001875
1876 case Instruction::BitCast:
1877 case Instruction::GetElementPtr:
Benjamin Kramerf5e2fc42015-05-29 19:43:39 +00001878 Users.emplace_back(I);
Nuno Lopes95cc4f32012-07-09 18:38:20 +00001879 Worklist.push_back(I);
1880 continue;
1881
1882 case Instruction::ICmp: {
1883 ICmpInst *ICI = cast<ICmpInst>(I);
1884 // We can fold eq/ne comparisons with null to false/true, respectively.
1885 if (!ICI->isEquality() || !isa<ConstantPointerNull>(ICI->getOperand(1)))
1886 return false;
Benjamin Kramerf5e2fc42015-05-29 19:43:39 +00001887 Users.emplace_back(I);
Nuno Lopes95cc4f32012-07-09 18:38:20 +00001888 continue;
1889 }
1890
1891 case Instruction::Call:
1892 // Ignore no-op and store intrinsics.
1893 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
1894 switch (II->getIntrinsicID()) {
1895 default:
1896 return false;
1897
1898 case Intrinsic::memmove:
1899 case Intrinsic::memcpy:
1900 case Intrinsic::memset: {
1901 MemIntrinsic *MI = cast<MemIntrinsic>(II);
1902 if (MI->isVolatile() || MI->getRawDest() != PI)
1903 return false;
1904 }
1905 // fall through
1906 case Intrinsic::dbg_declare:
1907 case Intrinsic::dbg_value:
1908 case Intrinsic::invariant_start:
1909 case Intrinsic::invariant_end:
1910 case Intrinsic::lifetime_start:
1911 case Intrinsic::lifetime_end:
1912 case Intrinsic::objectsize:
Benjamin Kramerf5e2fc42015-05-29 19:43:39 +00001913 Users.emplace_back(I);
Nuno Lopes95cc4f32012-07-09 18:38:20 +00001914 continue;
1915 }
1916 }
1917
Benjamin Kramer8bcc9712012-08-29 15:32:21 +00001918 if (isFreeCall(I, TLI)) {
Benjamin Kramerf5e2fc42015-05-29 19:43:39 +00001919 Users.emplace_back(I);
Nuno Lopes95cc4f32012-07-09 18:38:20 +00001920 continue;
1921 }
1922 return false;
1923
1924 case Instruction::Store: {
1925 StoreInst *SI = cast<StoreInst>(I);
1926 if (SI->isVolatile() || SI->getPointerOperand() != PI)
1927 return false;
Benjamin Kramerf5e2fc42015-05-29 19:43:39 +00001928 Users.emplace_back(I);
Nuno Lopes95cc4f32012-07-09 18:38:20 +00001929 continue;
1930 }
1931 }
1932 llvm_unreachable("missing a return?");
Nuno Lopesfa0dffc2012-07-06 23:09:25 +00001933 }
Nuno Lopes95cc4f32012-07-09 18:38:20 +00001934 } while (!Worklist.empty());
Duncan Sandsf162eac2010-05-27 19:09:06 +00001935 return true;
1936}
1937
Nuno Lopes95cc4f32012-07-09 18:38:20 +00001938Instruction *InstCombiner::visitAllocSite(Instruction &MI) {
Duncan Sandsf162eac2010-05-27 19:09:06 +00001939 // If we have a malloc call which is only used in any amount of comparisons
1940 // to null and free calls, delete the calls and replace the comparisons with
1941 // true or false as appropriate.
Nick Lewycky50f49662011-08-03 00:43:35 +00001942 SmallVector<WeakVH, 64> Users;
Benjamin Kramer8bcc9712012-08-29 15:32:21 +00001943 if (isAllocSiteRemovable(&MI, Users, TLI)) {
Nick Lewycky50f49662011-08-03 00:43:35 +00001944 for (unsigned i = 0, e = Users.size(); i != e; ++i) {
1945 Instruction *I = cast_or_null<Instruction>(&*Users[i]);
1946 if (!I) continue;
Duncan Sandsf162eac2010-05-27 19:09:06 +00001947
Nick Lewycky50f49662011-08-03 00:43:35 +00001948 if (ICmpInst *C = dyn_cast<ICmpInst>(I)) {
Sanjay Patel4b198802016-02-01 22:23:39 +00001949 replaceInstUsesWith(*C,
Nick Lewyckye8ae02d2011-08-02 22:08:01 +00001950 ConstantInt::get(Type::getInt1Ty(C->getContext()),
1951 C->isFalseWhenEqual()));
Nick Lewycky50f49662011-08-03 00:43:35 +00001952 } else if (isa<BitCastInst>(I) || isa<GetElementPtrInst>(I)) {
Sanjay Patel4b198802016-02-01 22:23:39 +00001953 replaceInstUsesWith(*I, UndefValue::get(I->getType()));
Nuno Lopesfa0dffc2012-07-06 23:09:25 +00001954 } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
1955 if (II->getIntrinsicID() == Intrinsic::objectsize) {
1956 ConstantInt *CI = cast<ConstantInt>(II->getArgOperand(1));
1957 uint64_t DontKnow = CI->isZero() ? -1ULL : 0;
Sanjay Patel4b198802016-02-01 22:23:39 +00001958 replaceInstUsesWith(*I, ConstantInt::get(I->getType(), DontKnow));
Nuno Lopesfa0dffc2012-07-06 23:09:25 +00001959 }
Duncan Sandsf162eac2010-05-27 19:09:06 +00001960 }
Sanjay Patel4b198802016-02-01 22:23:39 +00001961 eraseInstFromFunction(*I);
Duncan Sandsf162eac2010-05-27 19:09:06 +00001962 }
Nuno Lopesdc6085e2012-06-21 21:25:05 +00001963
1964 if (InvokeInst *II = dyn_cast<InvokeInst>(&MI)) {
Nuno Lopes9ac46612012-06-28 22:31:24 +00001965 // Replace invoke with a NOP intrinsic to maintain the original CFG
Sanjay Patelaf674fb2015-12-14 17:24:23 +00001966 Module *M = II->getModule();
Nuno Lopes9ac46612012-06-28 22:31:24 +00001967 Function *F = Intrinsic::getDeclaration(M, Intrinsic::donothing);
1968 InvokeInst::Create(F, II->getNormalDest(), II->getUnwindDest(),
Dmitri Gribenko3238fb72013-05-05 00:40:33 +00001969 None, "", II->getParent());
Nuno Lopesdc6085e2012-06-21 21:25:05 +00001970 }
Sanjay Patel4b198802016-02-01 22:23:39 +00001971 return eraseInstFromFunction(MI);
Duncan Sandsf162eac2010-05-27 19:09:06 +00001972 }
Craig Topperf40110f2014-04-25 05:29:35 +00001973 return nullptr;
Duncan Sandsf162eac2010-05-27 19:09:06 +00001974}
1975
Quentin Colombet3b2db0b2013-01-07 18:37:41 +00001976/// \brief Move the call to free before a NULL test.
1977///
1978/// Check if this free is accessed after its argument has been test
1979/// against NULL (property 0).
1980/// If yes, it is legal to move this call in its predecessor block.
1981///
1982/// The move is performed only if the block containing the call to free
1983/// will be removed, i.e.:
1984/// 1. it has only one predecessor P, and P has two successors
1985/// 2. it contains the call and an unconditional branch
1986/// 3. its successor is the same as its predecessor's successor
1987///
1988/// The profitability is out-of concern here and this function should
1989/// be called only if the caller knows this transformation would be
1990/// profitable (e.g., for code size).
1991static Instruction *
1992tryToMoveFreeBeforeNullTest(CallInst &FI) {
1993 Value *Op = FI.getArgOperand(0);
1994 BasicBlock *FreeInstrBB = FI.getParent();
1995 BasicBlock *PredBB = FreeInstrBB->getSinglePredecessor();
1996
1997 // Validate part of constraint #1: Only one predecessor
1998 // FIXME: We can extend the number of predecessor, but in that case, we
1999 // would duplicate the call to free in each predecessor and it may
2000 // not be profitable even for code size.
2001 if (!PredBB)
Craig Topperf40110f2014-04-25 05:29:35 +00002002 return nullptr;
Quentin Colombet3b2db0b2013-01-07 18:37:41 +00002003
2004 // Validate constraint #2: Does this block contains only the call to
2005 // free and an unconditional branch?
2006 // FIXME: We could check if we can speculate everything in the
2007 // predecessor block
2008 if (FreeInstrBB->size() != 2)
Craig Topperf40110f2014-04-25 05:29:35 +00002009 return nullptr;
Quentin Colombet3b2db0b2013-01-07 18:37:41 +00002010 BasicBlock *SuccBB;
2011 if (!match(FreeInstrBB->getTerminator(), m_UnconditionalBr(SuccBB)))
Craig Topperf40110f2014-04-25 05:29:35 +00002012 return nullptr;
Quentin Colombet3b2db0b2013-01-07 18:37:41 +00002013
2014 // Validate the rest of constraint #1 by matching on the pred branch.
2015 TerminatorInst *TI = PredBB->getTerminator();
2016 BasicBlock *TrueBB, *FalseBB;
2017 ICmpInst::Predicate Pred;
2018 if (!match(TI, m_Br(m_ICmp(Pred, m_Specific(Op), m_Zero()), TrueBB, FalseBB)))
Craig Topperf40110f2014-04-25 05:29:35 +00002019 return nullptr;
Quentin Colombet3b2db0b2013-01-07 18:37:41 +00002020 if (Pred != ICmpInst::ICMP_EQ && Pred != ICmpInst::ICMP_NE)
Craig Topperf40110f2014-04-25 05:29:35 +00002021 return nullptr;
Quentin Colombet3b2db0b2013-01-07 18:37:41 +00002022
2023 // Validate constraint #3: Ensure the null case just falls through.
2024 if (SuccBB != (Pred == ICmpInst::ICMP_EQ ? TrueBB : FalseBB))
Craig Topperf40110f2014-04-25 05:29:35 +00002025 return nullptr;
Quentin Colombet3b2db0b2013-01-07 18:37:41 +00002026 assert(FreeInstrBB == (Pred == ICmpInst::ICMP_EQ ? FalseBB : TrueBB) &&
2027 "Broken CFG: missing edge from predecessor to successor");
2028
2029 FI.moveBefore(TI);
2030 return &FI;
2031}
Duncan Sandsf162eac2010-05-27 19:09:06 +00002032
2033
Gabor Greif75f69432010-06-24 12:21:15 +00002034Instruction *InstCombiner::visitFree(CallInst &FI) {
2035 Value *Op = FI.getArgOperand(0);
Victor Hernandeze2971492009-10-24 04:23:03 +00002036
2037 // free undef -> unreachable.
2038 if (isa<UndefValue>(Op)) {
2039 // Insert a new store to null because we cannot modify the CFG here.
Eli Friedman41e509a2011-05-18 23:58:37 +00002040 Builder->CreateStore(ConstantInt::getTrue(FI.getContext()),
2041 UndefValue::get(Type::getInt1PtrTy(FI.getContext())));
Sanjay Patel4b198802016-02-01 22:23:39 +00002042 return eraseInstFromFunction(FI);
Victor Hernandeze2971492009-10-24 04:23:03 +00002043 }
Jakub Staszakcfc46f82012-05-06 13:52:31 +00002044
Victor Hernandeze2971492009-10-24 04:23:03 +00002045 // If we have 'free null' delete the instruction. This can happen in stl code
2046 // when lots of inlining happens.
2047 if (isa<ConstantPointerNull>(Op))
Sanjay Patel4b198802016-02-01 22:23:39 +00002048 return eraseInstFromFunction(FI);
Victor Hernandeze2971492009-10-24 04:23:03 +00002049
Quentin Colombet3b2db0b2013-01-07 18:37:41 +00002050 // If we optimize for code size, try to move the call to free before the null
2051 // test so that simplify cfg can remove the empty block and dead code
2052 // elimination the branch. I.e., helps to turn something like:
2053 // if (foo) free(foo);
2054 // into
2055 // free(foo);
2056 if (MinimizeSize)
2057 if (Instruction *I = tryToMoveFreeBeforeNullTest(FI))
2058 return I;
2059
Craig Topperf40110f2014-04-25 05:29:35 +00002060 return nullptr;
Victor Hernandeze2971492009-10-24 04:23:03 +00002061}
Chris Lattner8427bff2003-12-07 01:24:23 +00002062
Hal Finkel93873cc12014-09-07 21:28:34 +00002063Instruction *InstCombiner::visitReturnInst(ReturnInst &RI) {
2064 if (RI.getNumOperands() == 0) // ret void
2065 return nullptr;
Chris Lattner14a251b2007-04-15 00:07:55 +00002066
Hal Finkel93873cc12014-09-07 21:28:34 +00002067 Value *ResultOp = RI.getOperand(0);
2068 Type *VTy = ResultOp->getType();
2069 if (!VTy->isIntegerTy())
2070 return nullptr;
2071
2072 // There might be assume intrinsics dominating this return that completely
2073 // determine the value. If so, constant fold it.
2074 unsigned BitWidth = VTy->getPrimitiveSizeInBits();
2075 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
2076 computeKnownBits(ResultOp, KnownZero, KnownOne, 0, &RI);
2077 if ((KnownZero|KnownOne).isAllOnesValue())
2078 RI.setOperand(0, Constant::getIntegerValue(VTy, KnownOne));
2079
2080 return nullptr;
2081}
Chris Lattner31f486c2005-01-31 05:36:43 +00002082
Chris Lattner9eef8a72003-06-04 04:46:00 +00002083Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
2084 // Change br (not X), label True, label False to: br X, label False, True
Craig Topperf40110f2014-04-25 05:29:35 +00002085 Value *X = nullptr;
Chris Lattnerd4252a72004-07-30 07:50:03 +00002086 BasicBlock *TrueDest;
2087 BasicBlock *FalseDest;
Dan Gohman5476cfd2009-08-12 16:23:25 +00002088 if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
Chris Lattnerd4252a72004-07-30 07:50:03 +00002089 !isa<Constant>(X)) {
2090 // Swap Destinations and condition...
2091 BI.setCondition(X);
Chandler Carruth3e8aa652011-10-17 01:11:57 +00002092 BI.swapSuccessors();
Chris Lattnerd4252a72004-07-30 07:50:03 +00002093 return &BI;
2094 }
2095
Philip Reames71c40352015-03-10 22:52:37 +00002096 // If the condition is irrelevant, remove the use so that other
2097 // transforms on the condition become more effective.
2098 if (BI.isConditional() &&
2099 BI.getSuccessor(0) == BI.getSuccessor(1) &&
2100 !isa<UndefValue>(BI.getCondition())) {
2101 BI.setCondition(UndefValue::get(BI.getCondition()->getType()));
2102 return &BI;
2103 }
2104
Alp Tokercb402912014-01-24 17:20:08 +00002105 // Canonicalize fcmp_one -> fcmp_oeq
Reid Spencer266e42b2006-12-23 06:05:41 +00002106 FCmpInst::Predicate FPred; Value *Y;
Jakub Staszakcfc46f82012-05-06 13:52:31 +00002107 if (match(&BI, m_Br(m_FCmp(FPred, m_Value(X), m_Value(Y)),
Chris Lattner905976b2009-08-30 06:13:40 +00002108 TrueDest, FalseDest)) &&
2109 BI.getCondition()->hasOneUse())
2110 if (FPred == FCmpInst::FCMP_ONE || FPred == FCmpInst::FCMP_OLE ||
2111 FPred == FCmpInst::FCMP_OGE) {
2112 FCmpInst *Cond = cast<FCmpInst>(BI.getCondition());
2113 Cond->setPredicate(FCmpInst::getInversePredicate(FPred));
Jakub Staszakcfc46f82012-05-06 13:52:31 +00002114
Chris Lattner905976b2009-08-30 06:13:40 +00002115 // Swap Destinations and condition.
Chandler Carruth3e8aa652011-10-17 01:11:57 +00002116 BI.swapSuccessors();
Chris Lattner905976b2009-08-30 06:13:40 +00002117 Worklist.Add(Cond);
Reid Spencer266e42b2006-12-23 06:05:41 +00002118 return &BI;
2119 }
2120
Alp Tokercb402912014-01-24 17:20:08 +00002121 // Canonicalize icmp_ne -> icmp_eq
Reid Spencer266e42b2006-12-23 06:05:41 +00002122 ICmpInst::Predicate IPred;
2123 if (match(&BI, m_Br(m_ICmp(IPred, m_Value(X), m_Value(Y)),
Chris Lattner905976b2009-08-30 06:13:40 +00002124 TrueDest, FalseDest)) &&
2125 BI.getCondition()->hasOneUse())
2126 if (IPred == ICmpInst::ICMP_NE || IPred == ICmpInst::ICMP_ULE ||
2127 IPred == ICmpInst::ICMP_SLE || IPred == ICmpInst::ICMP_UGE ||
2128 IPred == ICmpInst::ICMP_SGE) {
2129 ICmpInst *Cond = cast<ICmpInst>(BI.getCondition());
2130 Cond->setPredicate(ICmpInst::getInversePredicate(IPred));
2131 // Swap Destinations and condition.
Chandler Carruth3e8aa652011-10-17 01:11:57 +00002132 BI.swapSuccessors();
Chris Lattner905976b2009-08-30 06:13:40 +00002133 Worklist.Add(Cond);
Chris Lattnere967b342003-06-04 05:10:11 +00002134 return &BI;
2135 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00002136
Craig Topperf40110f2014-04-25 05:29:35 +00002137 return nullptr;
Chris Lattner9eef8a72003-06-04 04:46:00 +00002138}
Chris Lattner1085bdf2002-11-04 16:18:53 +00002139
Chris Lattner4c9c20a2004-07-03 00:26:11 +00002140Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
2141 Value *Cond = SI.getCondition();
Akira Hatanaka5c221ef2014-10-16 06:00:46 +00002142 unsigned BitWidth = cast<IntegerType>(Cond->getType())->getBitWidth();
2143 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002144 computeKnownBits(Cond, KnownZero, KnownOne, 0, &SI);
Akira Hatanaka5c221ef2014-10-16 06:00:46 +00002145 unsigned LeadingKnownZeros = KnownZero.countLeadingOnes();
2146 unsigned LeadingKnownOnes = KnownOne.countLeadingOnes();
2147
2148 // Compute the number of leading bits we can ignore.
2149 for (auto &C : SI.cases()) {
2150 LeadingKnownZeros = std::min(
2151 LeadingKnownZeros, C.getCaseValue()->getValue().countLeadingZeros());
2152 LeadingKnownOnes = std::min(
2153 LeadingKnownOnes, C.getCaseValue()->getValue().countLeadingOnes());
2154 }
2155
2156 unsigned NewWidth = BitWidth - std::max(LeadingKnownZeros, LeadingKnownOnes);
2157
2158 // Truncate the condition operand if the new type is equal to or larger than
2159 // the largest legal integer type. We need to be conservative here since
Sanjay Patel6a248112015-06-23 23:26:22 +00002160 // x86 generates redundant zero-extension instructions if the operand is
Akira Hatanaka5c221ef2014-10-16 06:00:46 +00002161 // truncated to i8 or i16.
Bruno Cardoso Lopesf6cf8ad2014-12-19 17:12:35 +00002162 bool TruncCond = false;
Owen Anderson58364dc2015-03-10 06:51:39 +00002163 if (NewWidth > 0 && BitWidth > NewWidth &&
2164 NewWidth >= DL.getLargestLegalIntTypeSize()) {
Bruno Cardoso Lopesf6cf8ad2014-12-19 17:12:35 +00002165 TruncCond = true;
Akira Hatanaka5c221ef2014-10-16 06:00:46 +00002166 IntegerType *Ty = IntegerType::get(SI.getContext(), NewWidth);
2167 Builder->SetInsertPoint(&SI);
2168 Value *NewCond = Builder->CreateTrunc(SI.getCondition(), Ty, "trunc");
2169 SI.setCondition(NewCond);
2170
2171 for (auto &C : SI.cases())
2172 static_cast<SwitchInst::CaseIt *>(&C)->setValue(ConstantInt::get(
2173 SI.getContext(), C.getCaseValue()->getValue().trunc(NewWidth)));
2174 }
2175
Chris Lattner4c9c20a2004-07-03 00:26:11 +00002176 if (Instruction *I = dyn_cast<Instruction>(Cond)) {
2177 if (I->getOpcode() == Instruction::Add)
2178 if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
2179 // change 'switch (X+4) case 1:' into 'switch (X) case -3'
Eli Friedman95031ed2011-09-29 20:21:17 +00002180 // Skip the first item since that's the default case.
Stepan Dyatkovskiy97b02fc2012-03-11 06:09:17 +00002181 for (SwitchInst::CaseIt i = SI.case_begin(), e = SI.case_end();
Stepan Dyatkovskiy5b648af2012-03-08 07:06:20 +00002182 i != e; ++i) {
2183 ConstantInt* CaseVal = i.getCaseValue();
Bruno Cardoso Lopesf6cf8ad2014-12-19 17:12:35 +00002184 Constant *LHS = CaseVal;
2185 if (TruncCond)
2186 LHS = LeadingKnownZeros
2187 ? ConstantExpr::getZExt(CaseVal, Cond->getType())
2188 : ConstantExpr::getSExt(CaseVal, Cond->getType());
2189 Constant* NewCaseVal = ConstantExpr::getSub(LHS, AddRHS);
Eli Friedman95031ed2011-09-29 20:21:17 +00002190 assert(isa<ConstantInt>(NewCaseVal) &&
2191 "Result of expression should be constant");
Stepan Dyatkovskiy5b648af2012-03-08 07:06:20 +00002192 i.setValue(cast<ConstantInt>(NewCaseVal));
Eli Friedman95031ed2011-09-29 20:21:17 +00002193 }
2194 SI.setCondition(I->getOperand(0));
Chris Lattner905976b2009-08-30 06:13:40 +00002195 Worklist.Add(I);
Chris Lattner4c9c20a2004-07-03 00:26:11 +00002196 return &SI;
2197 }
2198 }
Bruno Cardoso Lopesf6cf8ad2014-12-19 17:12:35 +00002199
2200 return TruncCond ? &SI : nullptr;
Chris Lattner4c9c20a2004-07-03 00:26:11 +00002201}
2202
Matthijs Kooijmanb2fc72b2008-06-11 14:05:05 +00002203Instruction *InstCombiner::visitExtractValueInst(ExtractValueInst &EV) {
Matthijs Kooijmanc1d74772008-07-16 12:55:45 +00002204 Value *Agg = EV.getAggregateOperand();
Matthijs Kooijmanb2fc72b2008-06-11 14:05:05 +00002205
Matthijs Kooijmanc1d74772008-07-16 12:55:45 +00002206 if (!EV.hasIndices())
Sanjay Patel4b198802016-02-01 22:23:39 +00002207 return replaceInstUsesWith(EV, Agg);
Matthijs Kooijmanc1d74772008-07-16 12:55:45 +00002208
David Majnemer25a796e2015-07-13 01:15:46 +00002209 if (Value *V =
2210 SimplifyExtractValueInst(Agg, EV.getIndices(), DL, TLI, DT, AC))
Sanjay Patel4b198802016-02-01 22:23:39 +00002211 return replaceInstUsesWith(EV, V);
Jakub Staszakcfc46f82012-05-06 13:52:31 +00002212
Matthijs Kooijmanc1d74772008-07-16 12:55:45 +00002213 if (InsertValueInst *IV = dyn_cast<InsertValueInst>(Agg)) {
2214 // We're extracting from an insertvalue instruction, compare the indices
2215 const unsigned *exti, *exte, *insi, *inse;
2216 for (exti = EV.idx_begin(), insi = IV->idx_begin(),
2217 exte = EV.idx_end(), inse = IV->idx_end();
2218 exti != exte && insi != inse;
2219 ++exti, ++insi) {
2220 if (*insi != *exti)
2221 // The insert and extract both reference distinctly different elements.
2222 // This means the extract is not influenced by the insert, and we can
2223 // replace the aggregate operand of the extract with the aggregate
2224 // operand of the insert. i.e., replace
2225 // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
2226 // %E = extractvalue { i32, { i32 } } %I, 0
2227 // with
2228 // %E = extractvalue { i32, { i32 } } %A, 0
2229 return ExtractValueInst::Create(IV->getAggregateOperand(),
Jay Foad57aa6362011-07-13 10:26:04 +00002230 EV.getIndices());
Matthijs Kooijmanc1d74772008-07-16 12:55:45 +00002231 }
2232 if (exti == exte && insi == inse)
2233 // Both iterators are at the end: Index lists are identical. Replace
2234 // %B = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
2235 // %C = extractvalue { i32, { i32 } } %B, 1, 0
2236 // with "i32 42"
Sanjay Patel4b198802016-02-01 22:23:39 +00002237 return replaceInstUsesWith(EV, IV->getInsertedValueOperand());
Matthijs Kooijmanc1d74772008-07-16 12:55:45 +00002238 if (exti == exte) {
2239 // The extract list is a prefix of the insert list. i.e. replace
2240 // %I = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
2241 // %E = extractvalue { i32, { i32 } } %I, 1
2242 // with
2243 // %X = extractvalue { i32, { i32 } } %A, 1
2244 // %E = insertvalue { i32 } %X, i32 42, 0
2245 // by switching the order of the insert and extract (though the
2246 // insertvalue should be left in, since it may have other uses).
Chris Lattner59663412009-08-30 18:50:58 +00002247 Value *NewEV = Builder->CreateExtractValue(IV->getAggregateOperand(),
Jay Foad57aa6362011-07-13 10:26:04 +00002248 EV.getIndices());
Matthijs Kooijmanc1d74772008-07-16 12:55:45 +00002249 return InsertValueInst::Create(NewEV, IV->getInsertedValueOperand(),
Frits van Bommel717d7ed2011-07-18 12:00:32 +00002250 makeArrayRef(insi, inse));
Matthijs Kooijmanc1d74772008-07-16 12:55:45 +00002251 }
2252 if (insi == inse)
2253 // The insert list is a prefix of the extract list
2254 // We can simply remove the common indices from the extract and make it
2255 // operate on the inserted value instead of the insertvalue result.
2256 // i.e., replace
2257 // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
2258 // %E = extractvalue { i32, { i32 } } %I, 1, 0
2259 // with
2260 // %E extractvalue { i32 } { i32 42 }, 0
Jakub Staszakcfc46f82012-05-06 13:52:31 +00002261 return ExtractValueInst::Create(IV->getInsertedValueOperand(),
Frits van Bommel717d7ed2011-07-18 12:00:32 +00002262 makeArrayRef(exti, exte));
Matthijs Kooijmanc1d74772008-07-16 12:55:45 +00002263 }
Chris Lattner39c07b22009-11-09 07:07:56 +00002264 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(Agg)) {
2265 // We're extracting from an intrinsic, see if we're the only user, which
2266 // allows us to simplify multiple result intrinsics to simpler things that
Gabor Greif75f69432010-06-24 12:21:15 +00002267 // just get one value.
Chris Lattner39c07b22009-11-09 07:07:56 +00002268 if (II->hasOneUse()) {
2269 // Check if we're grabbing the overflow bit or the result of a 'with
2270 // overflow' intrinsic. If it's the latter we can remove the intrinsic
2271 // and replace it with a traditional binary instruction.
2272 switch (II->getIntrinsicID()) {
2273 case Intrinsic::uadd_with_overflow:
2274 case Intrinsic::sadd_with_overflow:
2275 if (*EV.idx_begin() == 0) { // Normal result.
Gabor Greif75f69432010-06-24 12:21:15 +00002276 Value *LHS = II->getArgOperand(0), *RHS = II->getArgOperand(1);
Sanjay Patel4b198802016-02-01 22:23:39 +00002277 replaceInstUsesWith(*II, UndefValue::get(II->getType()));
2278 eraseInstFromFunction(*II);
Chris Lattner39c07b22009-11-09 07:07:56 +00002279 return BinaryOperator::CreateAdd(LHS, RHS);
2280 }
Jakub Staszakcfc46f82012-05-06 13:52:31 +00002281
Chris Lattner3e635d22010-12-19 19:43:52 +00002282 // If the normal result of the add is dead, and the RHS is a constant,
2283 // we can transform this into a range comparison.
2284 // overflow = uadd a, -4 --> overflow = icmp ugt a, 3
Chris Lattner4fb9dd42010-12-19 23:24:04 +00002285 if (II->getIntrinsicID() == Intrinsic::uadd_with_overflow)
2286 if (ConstantInt *CI = dyn_cast<ConstantInt>(II->getArgOperand(1)))
2287 return new ICmpInst(ICmpInst::ICMP_UGT, II->getArgOperand(0),
2288 ConstantExpr::getNot(CI));
Chris Lattner39c07b22009-11-09 07:07:56 +00002289 break;
2290 case Intrinsic::usub_with_overflow:
2291 case Intrinsic::ssub_with_overflow:
2292 if (*EV.idx_begin() == 0) { // Normal result.
Gabor Greif75f69432010-06-24 12:21:15 +00002293 Value *LHS = II->getArgOperand(0), *RHS = II->getArgOperand(1);
Sanjay Patel4b198802016-02-01 22:23:39 +00002294 replaceInstUsesWith(*II, UndefValue::get(II->getType()));
2295 eraseInstFromFunction(*II);
Chris Lattner39c07b22009-11-09 07:07:56 +00002296 return BinaryOperator::CreateSub(LHS, RHS);
2297 }
2298 break;
2299 case Intrinsic::umul_with_overflow:
2300 case Intrinsic::smul_with_overflow:
2301 if (*EV.idx_begin() == 0) { // Normal result.
Gabor Greif75f69432010-06-24 12:21:15 +00002302 Value *LHS = II->getArgOperand(0), *RHS = II->getArgOperand(1);
Sanjay Patel4b198802016-02-01 22:23:39 +00002303 replaceInstUsesWith(*II, UndefValue::get(II->getType()));
2304 eraseInstFromFunction(*II);
Chris Lattner39c07b22009-11-09 07:07:56 +00002305 return BinaryOperator::CreateMul(LHS, RHS);
2306 }
2307 break;
2308 default:
2309 break;
2310 }
2311 }
2312 }
Frits van Bommel28218aa2010-11-29 21:56:20 +00002313 if (LoadInst *L = dyn_cast<LoadInst>(Agg))
2314 // If the (non-volatile) load only has one use, we can rewrite this to a
Mehdi Amini1c131b32015-12-15 01:44:07 +00002315 // load from a GEP. This reduces the size of the load. If a load is used
2316 // only by extractvalue instructions then this either must have been
2317 // optimized before, or it is a struct with padding, in which case we
2318 // don't want to do the transformation as it loses padding knowledge.
Eli Friedman8bc586e2011-08-15 22:09:40 +00002319 if (L->isSimple() && L->hasOneUse()) {
Frits van Bommel28218aa2010-11-29 21:56:20 +00002320 // extractvalue has integer indices, getelementptr has Value*s. Convert.
2321 SmallVector<Value*, 4> Indices;
2322 // Prefix an i32 0 since we need the first element.
2323 Indices.push_back(Builder->getInt32(0));
2324 for (ExtractValueInst::idx_iterator I = EV.idx_begin(), E = EV.idx_end();
2325 I != E; ++I)
2326 Indices.push_back(Builder->getInt32(*I));
2327
2328 // We need to insert these at the location of the old load, not at that of
2329 // the extractvalue.
Duncan P. N. Exon Smith9f8aaf22015-10-13 16:59:33 +00002330 Builder->SetInsertPoint(L);
David Blaikieaa41cd52015-04-03 21:33:42 +00002331 Value *GEP = Builder->CreateInBoundsGEP(L->getType(),
2332 L->getPointerOperand(), Indices);
Frits van Bommel28218aa2010-11-29 21:56:20 +00002333 // Returning the load directly will cause the main loop to insert it in
Sanjay Patel4b198802016-02-01 22:23:39 +00002334 // the wrong spot, so use replaceInstUsesWith().
2335 return replaceInstUsesWith(EV, Builder->CreateLoad(GEP));
Frits van Bommel28218aa2010-11-29 21:56:20 +00002336 }
2337 // We could simplify extracts from other values. Note that nested extracts may
2338 // already be simplified implicitly by the above: extract (extract (insert) )
Matthijs Kooijmanc1d74772008-07-16 12:55:45 +00002339 // will be translated into extract ( insert ( extract ) ) first and then just
Frits van Bommel28218aa2010-11-29 21:56:20 +00002340 // the value inserted, if appropriate. Similarly for extracts from single-use
2341 // loads: extract (extract (load)) will be translated to extract (load (gep))
2342 // and if again single-use then via load (gep (gep)) to load (gep).
2343 // However, double extracts from e.g. function arguments or return values
2344 // aren't handled yet.
Craig Topperf40110f2014-04-25 05:29:35 +00002345 return nullptr;
Matthijs Kooijmanb2fc72b2008-06-11 14:05:05 +00002346}
2347
Sanjay Patel84dca492015-09-21 15:33:26 +00002348/// Return 'true' if the given typeinfo will match anything.
Reid Kleckner4af64152015-01-28 01:17:38 +00002349static bool isCatchAll(EHPersonality Personality, Constant *TypeInfo) {
Duncan Sands5c055792011-09-30 13:12:16 +00002350 switch (Personality) {
Reid Kleckner4af64152015-01-28 01:17:38 +00002351 case EHPersonality::GNU_C:
2352 // The GCC C EH personality only exists to support cleanups, so it's not
2353 // clear what the semantics of catch clauses are.
Duncan Sands5c055792011-09-30 13:12:16 +00002354 return false;
Reid Kleckner4af64152015-01-28 01:17:38 +00002355 case EHPersonality::Unknown:
2356 return false;
2357 case EHPersonality::GNU_Ada:
Duncan Sands5c055792011-09-30 13:12:16 +00002358 // While __gnat_all_others_value will match any Ada exception, it doesn't
2359 // match foreign exceptions (or didn't, before gcc-4.7).
2360 return false;
Reid Kleckner4af64152015-01-28 01:17:38 +00002361 case EHPersonality::GNU_CXX:
2362 case EHPersonality::GNU_ObjC:
Reid Kleckner96d01132015-02-11 01:23:16 +00002363 case EHPersonality::MSVC_X86SEH:
Reid Kleckner4af64152015-01-28 01:17:38 +00002364 case EHPersonality::MSVC_Win64SEH:
2365 case EHPersonality::MSVC_CXX:
Joseph Tremoulet2afea542015-10-06 20:28:16 +00002366 case EHPersonality::CoreCLR:
Duncan Sands5c055792011-09-30 13:12:16 +00002367 return TypeInfo->isNullValue();
2368 }
Reid Kleckner4af64152015-01-28 01:17:38 +00002369 llvm_unreachable("invalid enum");
Duncan Sands5c055792011-09-30 13:12:16 +00002370}
2371
2372static bool shorter_filter(const Value *LHS, const Value *RHS) {
2373 return
2374 cast<ArrayType>(LHS->getType())->getNumElements()
2375 <
2376 cast<ArrayType>(RHS->getType())->getNumElements();
2377}
2378
2379Instruction *InstCombiner::visitLandingPadInst(LandingPadInst &LI) {
2380 // The logic here should be correct for any real-world personality function.
2381 // However if that turns out not to be true, the offending logic can always
2382 // be conditioned on the personality function, like the catch-all logic is.
David Majnemer7fddecc2015-06-17 20:52:32 +00002383 EHPersonality Personality =
2384 classifyEHPersonality(LI.getParent()->getParent()->getPersonalityFn());
Duncan Sands5c055792011-09-30 13:12:16 +00002385
2386 // Simplify the list of clauses, eg by removing repeated catch clauses
2387 // (these are often created by inlining).
2388 bool MakeNewInstruction = false; // If true, recreate using the following:
Rafael Espindola4dc5dfc2014-06-04 18:51:31 +00002389 SmallVector<Constant *, 16> NewClauses; // - Clauses for the new instruction;
Duncan Sands5c055792011-09-30 13:12:16 +00002390 bool CleanupFlag = LI.isCleanup(); // - The new instruction is a cleanup.
2391
2392 SmallPtrSet<Value *, 16> AlreadyCaught; // Typeinfos known caught already.
2393 for (unsigned i = 0, e = LI.getNumClauses(); i != e; ++i) {
2394 bool isLastClause = i + 1 == e;
2395 if (LI.isCatch(i)) {
2396 // A catch clause.
Rafael Espindola4dc5dfc2014-06-04 18:51:31 +00002397 Constant *CatchClause = LI.getClause(i);
Rafael Espindola78598d92014-06-04 19:01:48 +00002398 Constant *TypeInfo = CatchClause->stripPointerCasts();
Duncan Sands5c055792011-09-30 13:12:16 +00002399
2400 // If we already saw this clause, there is no point in having a second
2401 // copy of it.
David Blaikie70573dc2014-11-19 07:49:26 +00002402 if (AlreadyCaught.insert(TypeInfo).second) {
Duncan Sands5c055792011-09-30 13:12:16 +00002403 // This catch clause was not already seen.
2404 NewClauses.push_back(CatchClause);
2405 } else {
2406 // Repeated catch clause - drop the redundant copy.
2407 MakeNewInstruction = true;
2408 }
2409
2410 // If this is a catch-all then there is no point in keeping any following
2411 // clauses or marking the landingpad as having a cleanup.
2412 if (isCatchAll(Personality, TypeInfo)) {
2413 if (!isLastClause)
2414 MakeNewInstruction = true;
2415 CleanupFlag = false;
2416 break;
2417 }
2418 } else {
2419 // A filter clause. If any of the filter elements were already caught
2420 // then they can be dropped from the filter. It is tempting to try to
2421 // exploit the filter further by saying that any typeinfo that does not
2422 // occur in the filter can't be caught later (and thus can be dropped).
2423 // However this would be wrong, since typeinfos can match without being
2424 // equal (for example if one represents a C++ class, and the other some
2425 // class derived from it).
2426 assert(LI.isFilter(i) && "Unsupported landingpad clause!");
Rafael Espindola4dc5dfc2014-06-04 18:51:31 +00002427 Constant *FilterClause = LI.getClause(i);
Duncan Sands5c055792011-09-30 13:12:16 +00002428 ArrayType *FilterType = cast<ArrayType>(FilterClause->getType());
2429 unsigned NumTypeInfos = FilterType->getNumElements();
2430
2431 // An empty filter catches everything, so there is no point in keeping any
2432 // following clauses or marking the landingpad as having a cleanup. By
2433 // dealing with this case here the following code is made a bit simpler.
2434 if (!NumTypeInfos) {
2435 NewClauses.push_back(FilterClause);
2436 if (!isLastClause)
2437 MakeNewInstruction = true;
2438 CleanupFlag = false;
2439 break;
2440 }
2441
2442 bool MakeNewFilter = false; // If true, make a new filter.
2443 SmallVector<Constant *, 16> NewFilterElts; // New elements.
2444 if (isa<ConstantAggregateZero>(FilterClause)) {
2445 // Not an empty filter - it contains at least one null typeinfo.
2446 assert(NumTypeInfos > 0 && "Should have handled empty filter already!");
2447 Constant *TypeInfo =
2448 Constant::getNullValue(FilterType->getElementType());
2449 // If this typeinfo is a catch-all then the filter can never match.
2450 if (isCatchAll(Personality, TypeInfo)) {
2451 // Throw the filter away.
2452 MakeNewInstruction = true;
2453 continue;
2454 }
2455
2456 // There is no point in having multiple copies of this typeinfo, so
2457 // discard all but the first copy if there is more than one.
2458 NewFilterElts.push_back(TypeInfo);
2459 if (NumTypeInfos > 1)
2460 MakeNewFilter = true;
2461 } else {
2462 ConstantArray *Filter = cast<ConstantArray>(FilterClause);
2463 SmallPtrSet<Value *, 16> SeenInFilter; // For uniquing the elements.
2464 NewFilterElts.reserve(NumTypeInfos);
2465
2466 // Remove any filter elements that were already caught or that already
2467 // occurred in the filter. While there, see if any of the elements are
2468 // catch-alls. If so, the filter can be discarded.
2469 bool SawCatchAll = false;
2470 for (unsigned j = 0; j != NumTypeInfos; ++j) {
Rafael Espindola78598d92014-06-04 19:01:48 +00002471 Constant *Elt = Filter->getOperand(j);
2472 Constant *TypeInfo = Elt->stripPointerCasts();
Duncan Sands5c055792011-09-30 13:12:16 +00002473 if (isCatchAll(Personality, TypeInfo)) {
2474 // This element is a catch-all. Bail out, noting this fact.
2475 SawCatchAll = true;
2476 break;
2477 }
Andrew Kaylorde642ce2015-11-17 20:13:04 +00002478
2479 // Even if we've seen a type in a catch clause, we don't want to
2480 // remove it from the filter. An unexpected type handler may be
2481 // set up for a call site which throws an exception of the same
2482 // type caught. In order for the exception thrown by the unexpected
2483 // handler to propogate correctly, the filter must be correctly
2484 // described for the call site.
2485 //
2486 // Example:
2487 //
2488 // void unexpected() { throw 1;}
2489 // void foo() throw (int) {
2490 // std::set_unexpected(unexpected);
2491 // try {
2492 // throw 2.0;
2493 // } catch (int i) {}
2494 // }
2495
Duncan Sands5c055792011-09-30 13:12:16 +00002496 // There is no point in having multiple copies of the same typeinfo in
2497 // a filter, so only add it if we didn't already.
David Blaikie70573dc2014-11-19 07:49:26 +00002498 if (SeenInFilter.insert(TypeInfo).second)
Duncan Sands5c055792011-09-30 13:12:16 +00002499 NewFilterElts.push_back(cast<Constant>(Elt));
2500 }
2501 // A filter containing a catch-all cannot match anything by definition.
2502 if (SawCatchAll) {
2503 // Throw the filter away.
2504 MakeNewInstruction = true;
2505 continue;
2506 }
2507
2508 // If we dropped something from the filter, make a new one.
2509 if (NewFilterElts.size() < NumTypeInfos)
2510 MakeNewFilter = true;
2511 }
2512 if (MakeNewFilter) {
2513 FilterType = ArrayType::get(FilterType->getElementType(),
2514 NewFilterElts.size());
2515 FilterClause = ConstantArray::get(FilterType, NewFilterElts);
2516 MakeNewInstruction = true;
2517 }
2518
2519 NewClauses.push_back(FilterClause);
2520
2521 // If the new filter is empty then it will catch everything so there is
2522 // no point in keeping any following clauses or marking the landingpad
2523 // as having a cleanup. The case of the original filter being empty was
2524 // already handled above.
2525 if (MakeNewFilter && !NewFilterElts.size()) {
2526 assert(MakeNewInstruction && "New filter but not a new instruction!");
2527 CleanupFlag = false;
2528 break;
2529 }
2530 }
2531 }
2532
2533 // If several filters occur in a row then reorder them so that the shortest
2534 // filters come first (those with the smallest number of elements). This is
2535 // advantageous because shorter filters are more likely to match, speeding up
2536 // unwinding, but mostly because it increases the effectiveness of the other
2537 // filter optimizations below.
2538 for (unsigned i = 0, e = NewClauses.size(); i + 1 < e; ) {
2539 unsigned j;
2540 // Find the maximal 'j' s.t. the range [i, j) consists entirely of filters.
2541 for (j = i; j != e; ++j)
2542 if (!isa<ArrayType>(NewClauses[j]->getType()))
2543 break;
2544
2545 // Check whether the filters are already sorted by length. We need to know
2546 // if sorting them is actually going to do anything so that we only make a
2547 // new landingpad instruction if it does.
2548 for (unsigned k = i; k + 1 < j; ++k)
2549 if (shorter_filter(NewClauses[k+1], NewClauses[k])) {
2550 // Not sorted, so sort the filters now. Doing an unstable sort would be
2551 // correct too but reordering filters pointlessly might confuse users.
2552 std::stable_sort(NewClauses.begin() + i, NewClauses.begin() + j,
2553 shorter_filter);
2554 MakeNewInstruction = true;
2555 break;
2556 }
2557
2558 // Look for the next batch of filters.
2559 i = j + 1;
2560 }
2561
2562 // If typeinfos matched if and only if equal, then the elements of a filter L
2563 // that occurs later than a filter F could be replaced by the intersection of
2564 // the elements of F and L. In reality two typeinfos can match without being
2565 // equal (for example if one represents a C++ class, and the other some class
2566 // derived from it) so it would be wrong to perform this transform in general.
2567 // However the transform is correct and useful if F is a subset of L. In that
2568 // case L can be replaced by F, and thus removed altogether since repeating a
2569 // filter is pointless. So here we look at all pairs of filters F and L where
2570 // L follows F in the list of clauses, and remove L if every element of F is
2571 // an element of L. This can occur when inlining C++ functions with exception
2572 // specifications.
2573 for (unsigned i = 0; i + 1 < NewClauses.size(); ++i) {
2574 // Examine each filter in turn.
2575 Value *Filter = NewClauses[i];
2576 ArrayType *FTy = dyn_cast<ArrayType>(Filter->getType());
2577 if (!FTy)
2578 // Not a filter - skip it.
2579 continue;
2580 unsigned FElts = FTy->getNumElements();
2581 // Examine each filter following this one. Doing this backwards means that
2582 // we don't have to worry about filters disappearing under us when removed.
2583 for (unsigned j = NewClauses.size() - 1; j != i; --j) {
2584 Value *LFilter = NewClauses[j];
2585 ArrayType *LTy = dyn_cast<ArrayType>(LFilter->getType());
2586 if (!LTy)
2587 // Not a filter - skip it.
2588 continue;
2589 // If Filter is a subset of LFilter, i.e. every element of Filter is also
2590 // an element of LFilter, then discard LFilter.
Rafael Espindola4dc5dfc2014-06-04 18:51:31 +00002591 SmallVectorImpl<Constant *>::iterator J = NewClauses.begin() + j;
Duncan Sands5c055792011-09-30 13:12:16 +00002592 // If Filter is empty then it is a subset of LFilter.
2593 if (!FElts) {
2594 // Discard LFilter.
2595 NewClauses.erase(J);
2596 MakeNewInstruction = true;
2597 // Move on to the next filter.
2598 continue;
2599 }
2600 unsigned LElts = LTy->getNumElements();
2601 // If Filter is longer than LFilter then it cannot be a subset of it.
2602 if (FElts > LElts)
2603 // Move on to the next filter.
2604 continue;
2605 // At this point we know that LFilter has at least one element.
2606 if (isa<ConstantAggregateZero>(LFilter)) { // LFilter only contains zeros.
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00002607 // Filter is a subset of LFilter iff Filter contains only zeros (as we
Duncan Sands5c055792011-09-30 13:12:16 +00002608 // already know that Filter is not longer than LFilter).
2609 if (isa<ConstantAggregateZero>(Filter)) {
2610 assert(FElts <= LElts && "Should have handled this case earlier!");
2611 // Discard LFilter.
2612 NewClauses.erase(J);
2613 MakeNewInstruction = true;
2614 }
2615 // Move on to the next filter.
2616 continue;
2617 }
2618 ConstantArray *LArray = cast<ConstantArray>(LFilter);
2619 if (isa<ConstantAggregateZero>(Filter)) { // Filter only contains zeros.
2620 // Since Filter is non-empty and contains only zeros, it is a subset of
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00002621 // LFilter iff LFilter contains a zero.
Duncan Sands5c055792011-09-30 13:12:16 +00002622 assert(FElts > 0 && "Should have eliminated the empty filter earlier!");
2623 for (unsigned l = 0; l != LElts; ++l)
2624 if (LArray->getOperand(l)->isNullValue()) {
2625 // LFilter contains a zero - discard it.
2626 NewClauses.erase(J);
2627 MakeNewInstruction = true;
2628 break;
2629 }
2630 // Move on to the next filter.
2631 continue;
2632 }
2633 // At this point we know that both filters are ConstantArrays. Loop over
2634 // operands to see whether every element of Filter is also an element of
2635 // LFilter. Since filters tend to be short this is probably faster than
2636 // using a method that scales nicely.
2637 ConstantArray *FArray = cast<ConstantArray>(Filter);
2638 bool AllFound = true;
2639 for (unsigned f = 0; f != FElts; ++f) {
2640 Value *FTypeInfo = FArray->getOperand(f)->stripPointerCasts();
2641 AllFound = false;
2642 for (unsigned l = 0; l != LElts; ++l) {
2643 Value *LTypeInfo = LArray->getOperand(l)->stripPointerCasts();
2644 if (LTypeInfo == FTypeInfo) {
2645 AllFound = true;
2646 break;
2647 }
2648 }
2649 if (!AllFound)
2650 break;
2651 }
2652 if (AllFound) {
2653 // Discard LFilter.
2654 NewClauses.erase(J);
2655 MakeNewInstruction = true;
2656 }
2657 // Move on to the next filter.
2658 }
2659 }
2660
2661 // If we changed any of the clauses, replace the old landingpad instruction
2662 // with a new one.
2663 if (MakeNewInstruction) {
2664 LandingPadInst *NLI = LandingPadInst::Create(LI.getType(),
Duncan Sands5c055792011-09-30 13:12:16 +00002665 NewClauses.size());
2666 for (unsigned i = 0, e = NewClauses.size(); i != e; ++i)
2667 NLI->addClause(NewClauses[i]);
2668 // A landing pad with no clauses must have the cleanup flag set. It is
2669 // theoretically possible, though highly unlikely, that we eliminated all
2670 // clauses. If so, force the cleanup flag to true.
2671 if (NewClauses.empty())
2672 CleanupFlag = true;
2673 NLI->setCleanup(CleanupFlag);
2674 return NLI;
2675 }
2676
2677 // Even if none of the clauses changed, we may nonetheless have understood
2678 // that the cleanup flag is pointless. Clear it if so.
2679 if (LI.isCleanup() != CleanupFlag) {
2680 assert(!CleanupFlag && "Adding a cleanup, not removing one?!");
2681 LI.setCleanup(CleanupFlag);
2682 return &LI;
2683 }
2684
Craig Topperf40110f2014-04-25 05:29:35 +00002685 return nullptr;
Duncan Sands5c055792011-09-30 13:12:16 +00002686}
2687
Sanjay Patel84dca492015-09-21 15:33:26 +00002688/// Try to move the specified instruction from its current block into the
2689/// beginning of DestBlock, which can only happen if it's safe to move the
2690/// instruction past all of the instructions between it and the end of its
2691/// block.
Chris Lattner39c98bb2004-12-08 23:43:58 +00002692static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
2693 assert(I->hasOneUse() && "Invariants didn't hold!");
2694
Bill Wendlinge86965e2011-08-15 21:14:31 +00002695 // Cannot move control-flow-involving, volatile loads, vaarg, etc.
David Majnemer60c994b2015-08-08 03:51:49 +00002696 if (isa<PHINode>(I) || I->isEHPad() || I->mayHaveSideEffects() ||
Bill Wendlinga9ee09f2011-08-17 20:36:44 +00002697 isa<TerminatorInst>(I))
Chris Lattnera4ee1f52008-05-09 15:07:33 +00002698 return false;
Misha Brukmanb1c93172005-04-21 23:48:37 +00002699
Chris Lattner39c98bb2004-12-08 23:43:58 +00002700 // Do not sink alloca instructions out of the entry block.
Dan Gohmandcb291f2007-03-22 16:38:57 +00002701 if (isa<AllocaInst>(I) && I->getParent() ==
2702 &DestBlock->getParent()->getEntryBlock())
Chris Lattner39c98bb2004-12-08 23:43:58 +00002703 return false;
2704
Fiona Glasera8b653a2015-11-03 22:23:39 +00002705 // Do not sink convergent call instructions.
2706 if (auto *CI = dyn_cast<CallInst>(I)) {
2707 if (CI->isConvergent())
2708 return false;
2709 }
2710
Chris Lattnerf17a2fb2004-12-09 07:14:34 +00002711 // We can only sink load instructions if there is nothing between the load and
2712 // the end of block that could change the value.
Chris Lattner49a594e2008-05-08 17:37:37 +00002713 if (I->mayReadFromMemory()) {
Duncan P. N. Exon Smith9f8aaf22015-10-13 16:59:33 +00002714 for (BasicBlock::iterator Scan = I->getIterator(),
2715 E = I->getParent()->end();
Chris Lattnerf17a2fb2004-12-09 07:14:34 +00002716 Scan != E; ++Scan)
2717 if (Scan->mayWriteToMemory())
2718 return false;
Chris Lattnerf17a2fb2004-12-09 07:14:34 +00002719 }
Chris Lattner39c98bb2004-12-08 23:43:58 +00002720
Bill Wendling8ddfc092011-08-16 20:45:24 +00002721 BasicBlock::iterator InsertPos = DestBlock->getFirstInsertionPt();
Duncan P. N. Exon Smith9f8aaf22015-10-13 16:59:33 +00002722 I->moveBefore(&*InsertPos);
Chris Lattner39c98bb2004-12-08 23:43:58 +00002723 ++NumSunkInst;
2724 return true;
2725}
2726
Chandler Carruthdf5747a2015-01-21 11:38:17 +00002727bool InstCombiner::run() {
Chris Lattner97fd3592009-08-30 05:55:36 +00002728 while (!Worklist.isEmpty()) {
2729 Instruction *I = Worklist.RemoveOne();
Craig Topperf40110f2014-04-25 05:29:35 +00002730 if (I == nullptr) continue; // skip null values.
Chris Lattnerca081252001-12-14 16:52:21 +00002731
Chris Lattner1443bc52006-05-11 17:11:52 +00002732 // Check to see if we can DCE the instruction.
Benjamin Kramer8bcc9712012-08-29 15:32:21 +00002733 if (isInstructionTriviallyDead(I, TLI)) {
Matt Arsenaulte6db7602013-09-05 19:48:28 +00002734 DEBUG(dbgs() << "IC: DCE: " << *I << '\n');
Sanjay Patel4b198802016-02-01 22:23:39 +00002735 eraseInstFromFunction(*I);
Chris Lattner905976b2009-08-30 06:13:40 +00002736 ++NumDeadInst;
Chris Lattnerff5f1e42009-08-31 06:57:37 +00002737 MadeIRChange = true;
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00002738 continue;
2739 }
Chris Lattner99f48c62002-09-02 04:59:56 +00002740
Chris Lattner1443bc52006-05-11 17:11:52 +00002741 // Instruction isn't dead, see if we can constant propagate it.
David Majnemer7fddecc2015-06-17 20:52:32 +00002742 if (!I->use_empty() &&
2743 (I->getNumOperands() == 0 || isa<Constant>(I->getOperand(0)))) {
Rafael Espindola37dc9e12014-02-21 00:06:31 +00002744 if (Constant *C = ConstantFoldInstruction(I, DL, TLI)) {
Matt Arsenaulte6db7602013-09-05 19:48:28 +00002745 DEBUG(dbgs() << "IC: ConstFold to: " << *C << " from: " << *I << '\n');
Chris Lattnercd517ff2005-01-28 19:32:01 +00002746
Chris Lattnerdd1f68a2009-10-15 04:13:44 +00002747 // Add operands to the worklist.
Sanjay Patel4b198802016-02-01 22:23:39 +00002748 replaceInstUsesWith(*I, C);
Chris Lattnerdd1f68a2009-10-15 04:13:44 +00002749 ++NumConstProp;
Sanjay Patel4b198802016-02-01 22:23:39 +00002750 eraseInstFromFunction(*I);
Chris Lattnerdd1f68a2009-10-15 04:13:44 +00002751 MadeIRChange = true;
2752 continue;
2753 }
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002754 }
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00002755
Hal Finkelf2199b22015-10-23 20:37:08 +00002756 // In general, it is possible for computeKnownBits to determine all bits in a
2757 // value even when the operands are not all constants.
2758 if (!I->use_empty() && I->getType()->isIntegerTy()) {
2759 unsigned BitWidth = I->getType()->getScalarSizeInBits();
2760 APInt KnownZero(BitWidth, 0);
2761 APInt KnownOne(BitWidth, 0);
2762 computeKnownBits(I, KnownZero, KnownOne, /*Depth*/0, I);
2763 if ((KnownZero | KnownOne).isAllOnesValue()) {
2764 Constant *C = ConstantInt::get(I->getContext(), KnownOne);
2765 DEBUG(dbgs() << "IC: ConstFold (all bits known) to: " << *C <<
2766 " from: " << *I << '\n');
2767
2768 // Add operands to the worklist.
Sanjay Patel4b198802016-02-01 22:23:39 +00002769 replaceInstUsesWith(*I, C);
Hal Finkelf2199b22015-10-23 20:37:08 +00002770 ++NumConstProp;
Sanjay Patel4b198802016-02-01 22:23:39 +00002771 eraseInstFromFunction(*I);
Hal Finkelf2199b22015-10-23 20:37:08 +00002772 MadeIRChange = true;
2773 continue;
2774 }
2775 }
2776
Chris Lattner39c98bb2004-12-08 23:43:58 +00002777 // See if we can trivially sink this instruction to a successor basic block.
Dan Gohmanfa1211f2008-07-23 00:34:11 +00002778 if (I->hasOneUse()) {
Chris Lattner39c98bb2004-12-08 23:43:58 +00002779 BasicBlock *BB = I->getParent();
Chandler Carruthcdf47882014-03-09 03:16:01 +00002780 Instruction *UserInst = cast<Instruction>(*I->user_begin());
Chris Lattner6b9044d2009-10-14 15:21:58 +00002781 BasicBlock *UserParent;
Jakub Staszakcfc46f82012-05-06 13:52:31 +00002782
Chris Lattner6b9044d2009-10-14 15:21:58 +00002783 // Get the block the use occurs in.
2784 if (PHINode *PN = dyn_cast<PHINode>(UserInst))
Chandler Carruthcdf47882014-03-09 03:16:01 +00002785 UserParent = PN->getIncomingBlock(*I->use_begin());
Chris Lattner6b9044d2009-10-14 15:21:58 +00002786 else
2787 UserParent = UserInst->getParent();
Jakub Staszakcfc46f82012-05-06 13:52:31 +00002788
Chris Lattner39c98bb2004-12-08 23:43:58 +00002789 if (UserParent != BB) {
2790 bool UserIsSuccessor = false;
2791 // See if the user is one of our successors.
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +00002792 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
2793 if (*SI == UserParent) {
Chris Lattner39c98bb2004-12-08 23:43:58 +00002794 UserIsSuccessor = true;
2795 break;
2796 }
2797
2798 // If the user is one of our immediate successors, and if that successor
2799 // only has us as a predecessors (we'd have to split the critical edge
2800 // otherwise), we can keep going.
Aditya Nandakumar0b5a6742014-07-11 21:49:39 +00002801 if (UserIsSuccessor && UserParent->getSinglePredecessor()) {
Chris Lattner39c98bb2004-12-08 23:43:58 +00002802 // Okay, the CFG is simple enough, try to sink this instruction.
Aditya Nandakumar0b5a6742014-07-11 21:49:39 +00002803 if (TryToSinkInstruction(I, UserParent)) {
2804 MadeIRChange = true;
2805 // We'll add uses of the sunk instruction below, but since sinking
2806 // can expose opportunities for it's *operands* add them to the
2807 // worklist
2808 for (Use &U : I->operands())
2809 if (Instruction *OpI = dyn_cast<Instruction>(U.get()))
2810 Worklist.Add(OpI);
2811 }
2812 }
Chris Lattner39c98bb2004-12-08 23:43:58 +00002813 }
2814 }
2815
Chris Lattner022a5822009-08-30 07:44:24 +00002816 // Now that we have an instruction, try combining it to simplify it.
Duncan P. N. Exon Smith9f8aaf22015-10-13 16:59:33 +00002817 Builder->SetInsertPoint(I);
Eli Friedman96254a02011-05-18 01:28:27 +00002818 Builder->SetCurrentDebugLocation(I->getDebugLoc());
Jakub Staszakcfc46f82012-05-06 13:52:31 +00002819
Reid Spencer755d0e72007-03-26 17:44:01 +00002820#ifndef NDEBUG
2821 std::string OrigI;
2822#endif
Chris Lattnerb25de3f2009-08-23 04:37:46 +00002823 DEBUG(raw_string_ostream SS(OrigI); I->print(SS); OrigI = SS.str(););
Matt Arsenaulte6db7602013-09-05 19:48:28 +00002824 DEBUG(dbgs() << "IC: Visiting: " << OrigI << '\n');
Jeffrey Yasskindafd08e2009-10-08 00:12:24 +00002825
Chris Lattnerae7a0d32002-08-02 19:29:35 +00002826 if (Instruction *Result = visit(*I)) {
Chris Lattner0b18c1d2002-05-10 15:38:35 +00002827 ++NumCombined;
Chris Lattner260ab202002-04-18 17:39:14 +00002828 // Should we replace the old instruction with a new one?
Chris Lattner053c0932002-05-14 15:24:07 +00002829 if (Result != I) {
Matt Arsenaulte6db7602013-09-05 19:48:28 +00002830 DEBUG(dbgs() << "IC: Old = " << *I << '\n'
Jim Grosbach8f9acfa2011-10-05 20:44:29 +00002831 << " New = " << *Result << '\n');
2832
Duncan P. N. Exon Smithec819c02015-03-30 19:49:49 +00002833 if (I->getDebugLoc())
Eli Friedman35211c62011-05-27 00:19:40 +00002834 Result->setDebugLoc(I->getDebugLoc());
Chris Lattner396dbfe2004-06-09 05:08:07 +00002835 // Everything uses the new instruction now.
2836 I->replaceAllUsesWith(Result);
2837
Jim Grosbache7abae02011-10-05 20:53:43 +00002838 // Move the name to the new instruction first.
2839 Result->takeName(I);
2840
Jim Grosbach8f9acfa2011-10-05 20:44:29 +00002841 // Push the new instruction and any users onto the worklist.
2842 Worklist.Add(Result);
2843 Worklist.AddUsersToWorkList(*Result);
2844
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00002845 // Insert the new instruction into the basic block...
2846 BasicBlock *InstParent = I->getParent();
Duncan P. N. Exon Smith9f8aaf22015-10-13 16:59:33 +00002847 BasicBlock::iterator InsertPos = I->getIterator();
Chris Lattner7515cab2004-11-14 19:13:23 +00002848
Eli Friedmana49b8282011-11-01 04:49:29 +00002849 // If we replace a PHI with something that isn't a PHI, fix up the
2850 // insertion point.
2851 if (!isa<PHINode>(Result) && isa<PHINode>(InsertPos))
2852 InsertPos = InstParent->getFirstInsertionPt();
Chris Lattner7515cab2004-11-14 19:13:23 +00002853
2854 InstParent->getInstList().insert(InsertPos, Result);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00002855
Sanjay Patel4b198802016-02-01 22:23:39 +00002856 eraseInstFromFunction(*I);
Chris Lattner113f4f42002-06-25 16:13:24 +00002857 } else {
Evan Chenga4ed8a52007-03-27 16:44:48 +00002858#ifndef NDEBUG
Matt Arsenaulte6db7602013-09-05 19:48:28 +00002859 DEBUG(dbgs() << "IC: Mod = " << OrigI << '\n'
Chris Lattnerb25de3f2009-08-23 04:37:46 +00002860 << " New = " << *I << '\n');
Evan Chenga4ed8a52007-03-27 16:44:48 +00002861#endif
Chris Lattner7d2a5392004-03-13 23:54:27 +00002862
Chris Lattnerae7a0d32002-08-02 19:29:35 +00002863 // If the instruction was modified, it's possible that it is now dead.
2864 // if so, remove it.
Benjamin Kramer8bcc9712012-08-29 15:32:21 +00002865 if (isInstructionTriviallyDead(I, TLI)) {
Sanjay Patel4b198802016-02-01 22:23:39 +00002866 eraseInstFromFunction(*I);
Chris Lattner396dbfe2004-06-09 05:08:07 +00002867 } else {
Chris Lattner905976b2009-08-30 06:13:40 +00002868 Worklist.Add(I);
Chris Lattnerbacd05c2009-08-30 06:22:51 +00002869 Worklist.AddUsersToWorkList(*I);
Chris Lattnerae7a0d32002-08-02 19:29:35 +00002870 }
Chris Lattner053c0932002-05-14 15:24:07 +00002871 }
Chris Lattnerff5f1e42009-08-31 06:57:37 +00002872 MadeIRChange = true;
Chris Lattnerca081252001-12-14 16:52:21 +00002873 }
2874 }
2875
Chris Lattner97fd3592009-08-30 05:55:36 +00002876 Worklist.Zap();
Chris Lattnerff5f1e42009-08-31 06:57:37 +00002877 return MadeIRChange;
Chris Lattner04805fa2002-02-26 21:46:54 +00002878}
2879
Sanjay Patel84dca492015-09-21 15:33:26 +00002880/// Walk the function in depth-first order, adding all reachable code to the
2881/// worklist.
Chandler Carruthdf5747a2015-01-21 11:38:17 +00002882///
2883/// This has a couple of tricks to make the code faster and more powerful. In
2884/// particular, we constant fold and DCE instructions as we go, to avoid adding
2885/// them to the worklist (this significantly speeds up instcombine on code where
2886/// many instructions are dead or constant). Additionally, if we find a branch
2887/// whose condition is a known constant, we only visit the reachable successors.
2888///
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002889static bool AddReachableCodeToWorklist(BasicBlock *BB, const DataLayout &DL,
2890 SmallPtrSetImpl<BasicBlock *> &Visited,
Chandler Carruthdf5747a2015-01-21 11:38:17 +00002891 InstCombineWorklist &ICWorklist,
Chandler Carruthdf5747a2015-01-21 11:38:17 +00002892 const TargetLibraryInfo *TLI) {
2893 bool MadeIRChange = false;
2894 SmallVector<BasicBlock*, 256> Worklist;
2895 Worklist.push_back(BB);
Hal Finkel60db0582014-09-07 18:57:58 +00002896
Chandler Carruthdf5747a2015-01-21 11:38:17 +00002897 SmallVector<Instruction*, 128> InstrsForInstCombineWorklist;
2898 DenseMap<ConstantExpr*, Constant*> FoldedConstants;
Jakub Staszakcfc46f82012-05-06 13:52:31 +00002899
Chandler Carruthdf5747a2015-01-21 11:38:17 +00002900 do {
2901 BB = Worklist.pop_back_val();
Jakub Staszakcfc46f82012-05-06 13:52:31 +00002902
Chandler Carruthdf5747a2015-01-21 11:38:17 +00002903 // We have now visited this block! If we've already been here, ignore it.
2904 if (!Visited.insert(BB).second)
2905 continue;
Chris Lattner960a5432007-03-03 02:04:50 +00002906
Chandler Carruthdf5747a2015-01-21 11:38:17 +00002907 for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
Duncan P. N. Exon Smith9f8aaf22015-10-13 16:59:33 +00002908 Instruction *Inst = &*BBI++;
Devang Patelaad34d82011-03-17 22:18:16 +00002909
Chandler Carruthdf5747a2015-01-21 11:38:17 +00002910 // DCE instruction if trivially dead.
2911 if (isInstructionTriviallyDead(Inst, TLI)) {
2912 ++NumDeadInst;
2913 DEBUG(dbgs() << "IC: DCE: " << *Inst << '\n');
2914 Inst->eraseFromParent();
2915 continue;
2916 }
Jakub Staszakcfc46f82012-05-06 13:52:31 +00002917
Chandler Carruthdf5747a2015-01-21 11:38:17 +00002918 // ConstantProp instruction if trivially constant.
David Majnemer7fddecc2015-06-17 20:52:32 +00002919 if (!Inst->use_empty() &&
2920 (Inst->getNumOperands() == 0 || isa<Constant>(Inst->getOperand(0))))
Chandler Carruthdf5747a2015-01-21 11:38:17 +00002921 if (Constant *C = ConstantFoldInstruction(Inst, DL, TLI)) {
2922 DEBUG(dbgs() << "IC: ConstFold to: " << *C << " from: "
2923 << *Inst << '\n');
2924 Inst->replaceAllUsesWith(C);
2925 ++NumConstProp;
2926 Inst->eraseFromParent();
2927 continue;
2928 }
2929
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002930 // See if we can constant fold its operands.
2931 for (User::op_iterator i = Inst->op_begin(), e = Inst->op_end(); i != e;
2932 ++i) {
2933 ConstantExpr *CE = dyn_cast<ConstantExpr>(i);
2934 if (CE == nullptr)
2935 continue;
Chandler Carruthdf5747a2015-01-21 11:38:17 +00002936
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002937 Constant *&FoldRes = FoldedConstants[CE];
2938 if (!FoldRes)
2939 FoldRes = ConstantFoldConstantExpression(CE, DL, TLI);
2940 if (!FoldRes)
2941 FoldRes = CE;
Chandler Carruthdf5747a2015-01-21 11:38:17 +00002942
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002943 if (FoldRes != CE) {
2944 *i = FoldRes;
2945 MadeIRChange = true;
Chandler Carruthdf5747a2015-01-21 11:38:17 +00002946 }
2947 }
2948
2949 InstrsForInstCombineWorklist.push_back(Inst);
2950 }
2951
2952 // Recursively visit successors. If this is a branch or switch on a
2953 // constant, only visit the reachable successor.
2954 TerminatorInst *TI = BB->getTerminator();
2955 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
2956 if (BI->isConditional() && isa<ConstantInt>(BI->getCondition())) {
2957 bool CondVal = cast<ConstantInt>(BI->getCondition())->getZExtValue();
2958 BasicBlock *ReachableBB = BI->getSuccessor(!CondVal);
2959 Worklist.push_back(ReachableBB);
2960 continue;
2961 }
2962 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
2963 if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
2964 // See if this is an explicit destination.
2965 for (SwitchInst::CaseIt i = SI->case_begin(), e = SI->case_end();
2966 i != e; ++i)
2967 if (i.getCaseValue() == Cond) {
2968 BasicBlock *ReachableBB = i.getCaseSuccessor();
2969 Worklist.push_back(ReachableBB);
2970 continue;
2971 }
2972
2973 // Otherwise it is the default destination.
2974 Worklist.push_back(SI->getDefaultDest());
2975 continue;
2976 }
2977 }
2978
Pete Cooperebcd7482015-08-06 20:22:46 +00002979 for (BasicBlock *SuccBB : TI->successors())
2980 Worklist.push_back(SuccBB);
Chandler Carruthdf5747a2015-01-21 11:38:17 +00002981 } while (!Worklist.empty());
2982
2983 // Once we've found all of the instructions to add to instcombine's worklist,
2984 // add them in reverse order. This way instcombine will visit from the top
2985 // of the function down. This jives well with the way that it adds all uses
2986 // of instructions to the worklist after doing a transformation, thus avoiding
2987 // some N^2 behavior in pathological cases.
Craig Topper42526d32015-10-22 16:35:56 +00002988 ICWorklist.AddInitialGroup(InstrsForInstCombineWorklist);
Chandler Carruthdf5747a2015-01-21 11:38:17 +00002989
2990 return MadeIRChange;
2991}
2992
2993/// \brief Populate the IC worklist from a function, and prune any dead basic
2994/// blocks discovered in the process.
2995///
2996/// This also does basic constant propagation and other forward fixing to make
2997/// the combiner itself run much faster.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002998static bool prepareICWorklistFromFunction(Function &F, const DataLayout &DL,
Chandler Carruthdf5747a2015-01-21 11:38:17 +00002999 TargetLibraryInfo *TLI,
3000 InstCombineWorklist &ICWorklist) {
3001 bool MadeIRChange = false;
3002
3003 // Do a depth-first traversal of the function, populate the worklist with
3004 // the reachable instructions. Ignore blocks that are not reachable. Keep
3005 // track of which blocks we visit.
Matthias Braunb30f2f512016-01-30 01:24:31 +00003006 SmallPtrSet<BasicBlock *, 32> Visited;
Chandler Carruthdf5747a2015-01-21 11:38:17 +00003007 MadeIRChange |=
Duncan P. N. Exon Smith9f8aaf22015-10-13 16:59:33 +00003008 AddReachableCodeToWorklist(&F.front(), DL, Visited, ICWorklist, TLI);
Chandler Carruthdf5747a2015-01-21 11:38:17 +00003009
3010 // Do a quick scan over the function. If we find any blocks that are
3011 // unreachable, remove any instructions inside of them. This prevents
3012 // the instcombine code from having to deal with some bad special cases.
3013 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
Duncan P. N. Exon Smith9f8aaf22015-10-13 16:59:33 +00003014 if (Visited.count(&*BB))
Chandler Carruthdf5747a2015-01-21 11:38:17 +00003015 continue;
3016
David Majnemer35c46d32016-01-24 05:26:18 +00003017 unsigned NumDeadInstInBB = removeAllNonTerminatorAndEHPadInstructions(&*BB);
3018 MadeIRChange |= NumDeadInstInBB > 0;
3019 NumDeadInst += NumDeadInstInBB;
Chandler Carruthdf5747a2015-01-21 11:38:17 +00003020 }
3021
3022 return MadeIRChange;
Chris Lattner960a5432007-03-03 02:04:50 +00003023}
3024
Mehdi Amini46a43552015-03-04 18:43:29 +00003025static bool
3026combineInstructionsOverFunction(Function &F, InstCombineWorklist &Worklist,
Bjorn Steinbrink83505342015-07-10 06:55:49 +00003027 AliasAnalysis *AA, AssumptionCache &AC,
3028 TargetLibraryInfo &TLI, DominatorTree &DT,
3029 LoopInfo *LI = nullptr) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003030 auto &DL = F.getParent()->getDataLayout();
Chandler Carruth83ba2692015-01-24 04:19:17 +00003031
3032 /// Builder - This is an IRBuilder that automatically inserts new
3033 /// instructions into the worklist when they are created.
3034 IRBuilder<true, TargetFolder, InstCombineIRInserter> Builder(
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003035 F.getContext(), TargetFolder(DL), InstCombineIRInserter(Worklist, &AC));
Chandler Carruth83ba2692015-01-24 04:19:17 +00003036
3037 // Lower dbg.declare intrinsics otherwise their value may be clobbered
3038 // by instcombiner.
3039 bool DbgDeclaresChanged = LowerDbgDeclare(F);
3040
3041 // Iterate while there is work to do.
3042 int Iteration = 0;
3043 for (;;) {
3044 ++Iteration;
3045 DEBUG(dbgs() << "\n\nINSTCOMBINE ITERATION #" << Iteration << " on "
3046 << F.getName() << "\n");
3047
Sanjay Patel24b77d12016-01-31 16:33:33 +00003048 bool Changed = prepareICWorklistFromFunction(F, DL, &TLI, Worklist);
Chandler Carruth83ba2692015-01-24 04:19:17 +00003049
Sanjay Patel24b77d12016-01-31 16:33:33 +00003050 InstCombiner IC(Worklist, &Builder, F.optForMinSize(), AA, &AC, &TLI, &DT,
3051 DL, LI);
3052 Changed |= IC.run();
Chandler Carruth83ba2692015-01-24 04:19:17 +00003053
3054 if (!Changed)
3055 break;
3056 }
3057
3058 return DbgDeclaresChanged || Iteration > 1;
3059}
3060
3061PreservedAnalyses InstCombinePass::run(Function &F,
3062 AnalysisManager<Function> *AM) {
Chandler Carruth83ba2692015-01-24 04:19:17 +00003063 auto &AC = AM->getResult<AssumptionAnalysis>(F);
3064 auto &DT = AM->getResult<DominatorTreeAnalysis>(F);
3065 auto &TLI = AM->getResult<TargetLibraryAnalysis>(F);
3066
3067 auto *LI = AM->getCachedResult<LoopAnalysis>(F);
3068
Bjorn Steinbrink83505342015-07-10 06:55:49 +00003069 // FIXME: The AliasAnalysis is not yet supported in the new pass manager
3070 if (!combineInstructionsOverFunction(F, Worklist, nullptr, AC, TLI, DT, LI))
Chandler Carruth83ba2692015-01-24 04:19:17 +00003071 // No changes, all analyses are preserved.
3072 return PreservedAnalyses::all();
3073
3074 // Mark all the analyses that instcombine updates as preserved.
3075 // FIXME: Need a way to preserve CFG analyses here!
3076 PreservedAnalyses PA;
3077 PA.preserve<DominatorTreeAnalysis>();
3078 return PA;
3079}
3080
Chandler Carruth1edb9d62015-01-20 22:44:35 +00003081namespace {
3082/// \brief The legacy pass manager's instcombine pass.
3083///
3084/// This is a basic whole-function wrapper around the instcombine utility. It
3085/// will try to combine all instructions in the function.
3086class InstructionCombiningPass : public FunctionPass {
Chandler Carruthdf5747a2015-01-21 11:38:17 +00003087 InstCombineWorklist Worklist;
Chandler Carruth1edb9d62015-01-20 22:44:35 +00003088
3089public:
3090 static char ID; // Pass identification, replacement for typeid
3091
3092 InstructionCombiningPass() : FunctionPass(ID) {
3093 initializeInstructionCombiningPassPass(*PassRegistry::getPassRegistry());
3094 }
3095
3096 void getAnalysisUsage(AnalysisUsage &AU) const override;
3097 bool runOnFunction(Function &F) override;
3098};
Alexander Kornienkof00654e2015-06-23 09:49:53 +00003099}
Chandler Carruth1edb9d62015-01-20 22:44:35 +00003100
3101void InstructionCombiningPass::getAnalysisUsage(AnalysisUsage &AU) const {
3102 AU.setPreservesCFG();
Chandler Carruth7b560d42015-09-09 17:55:00 +00003103 AU.addRequired<AAResultsWrapperPass>();
Chandler Carruth1edb9d62015-01-20 22:44:35 +00003104 AU.addRequired<AssumptionCacheTracker>();
3105 AU.addRequired<TargetLibraryInfoWrapperPass>();
3106 AU.addRequired<DominatorTreeWrapperPass>();
3107 AU.addPreserved<DominatorTreeWrapperPass>();
Chandler Carruthac072702016-02-19 03:12:14 +00003108 AU.addPreserved<AAResultsWrapperPass>();
3109 AU.addPreserved<BasicAAWrapperPass>();
Chandler Carruth7b560d42015-09-09 17:55:00 +00003110 AU.addPreserved<GlobalsAAWrapperPass>();
Chandler Carruth1edb9d62015-01-20 22:44:35 +00003111}
3112
3113bool InstructionCombiningPass::runOnFunction(Function &F) {
3114 if (skipOptnoneFunction(F))
3115 return false;
3116
Chandler Carruthdf5747a2015-01-21 11:38:17 +00003117 // Required analyses.
Chandler Carruth7b560d42015-09-09 17:55:00 +00003118 auto AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
Chandler Carruth1edb9d62015-01-20 22:44:35 +00003119 auto &AC = getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
Chandler Carruth1edb9d62015-01-20 22:44:35 +00003120 auto &TLI = getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
3121 auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
Chandler Carruthdf5747a2015-01-21 11:38:17 +00003122
3123 // Optional analyses.
Chandler Carruth1edb9d62015-01-20 22:44:35 +00003124 auto *LIWP = getAnalysisIfAvailable<LoopInfoWrapperPass>();
3125 auto *LI = LIWP ? &LIWP->getLoopInfo() : nullptr;
3126
Bjorn Steinbrink83505342015-07-10 06:55:49 +00003127 return combineInstructionsOverFunction(F, Worklist, AA, AC, TLI, DT, LI);
Chandler Carruth1edb9d62015-01-20 22:44:35 +00003128}
3129
3130char InstructionCombiningPass::ID = 0;
3131INITIALIZE_PASS_BEGIN(InstructionCombiningPass, "instcombine",
3132 "Combine redundant instructions", false, false)
3133INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
3134INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
3135INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
Chandler Carruth7b560d42015-09-09 17:55:00 +00003136INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
3137INITIALIZE_PASS_DEPENDENCY(GlobalsAAWrapperPass)
Chandler Carruth1edb9d62015-01-20 22:44:35 +00003138INITIALIZE_PASS_END(InstructionCombiningPass, "instcombine",
3139 "Combine redundant instructions", false, false)
3140
3141// Initialization Routines
3142void llvm::initializeInstCombine(PassRegistry &Registry) {
3143 initializeInstructionCombiningPassPass(Registry);
3144}
3145
3146void LLVMInitializeInstCombine(LLVMPassRegistryRef R) {
3147 initializeInstructionCombiningPassPass(*unwrap(R));
3148}
3149
Brian Gaeke38b79e82004-07-27 17:43:21 +00003150FunctionPass *llvm::createInstructionCombiningPass() {
Chandler Carruth1edb9d62015-01-20 22:44:35 +00003151 return new InstructionCombiningPass();
Chris Lattner04805fa2002-02-26 21:46:54 +00003152}