blob: d5cf626e60fba0fe38db054306eb88a78045dbbb [file] [log] [blame]
Chris Lattner9f3c25a2009-11-09 22:57:59 +00001//===- InstructionSimplify.cpp - Fold instruction operands ----------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements routines for folding instructions into simpler forms
Duncan Sands4cd2ad12010-11-23 10:50:08 +000011// that do not require creating new instructions. This does constant folding
12// ("add i32 1, 1" -> "2") but can also handle non-constant operands, either
13// returning a constant ("and i32 %x, 0" -> "0") or an already existing value
Duncan Sandsee9a2e32010-12-20 14:47:04 +000014// ("and i32 %x, %x" -> "%x"). All operands are assumed to have already been
15// simplified: This is usually true and assuming it simplifies the logic (if
16// they have not been simplified then results are correct but maybe suboptimal).
Chris Lattner9f3c25a2009-11-09 22:57:59 +000017//
18//===----------------------------------------------------------------------===//
19
Duncan Sandsa3c44a52010-12-22 09:40:51 +000020#define DEBUG_TYPE "instsimplify"
21#include "llvm/ADT/Statistic.h"
Chris Lattner9f3c25a2009-11-09 22:57:59 +000022#include "llvm/Analysis/InstructionSimplify.h"
23#include "llvm/Analysis/ConstantFolding.h"
Duncan Sands18450092010-11-16 12:16:38 +000024#include "llvm/Analysis/Dominators.h"
Chris Lattnerd06094f2009-11-10 00:55:12 +000025#include "llvm/Support/PatternMatch.h"
Duncan Sands18450092010-11-16 12:16:38 +000026#include "llvm/Support/ValueHandle.h"
Duncan Sandse60d79f2010-11-21 13:53:09 +000027#include "llvm/Target/TargetData.h"
Chris Lattner9f3c25a2009-11-09 22:57:59 +000028using namespace llvm;
Chris Lattnerd06094f2009-11-10 00:55:12 +000029using namespace llvm::PatternMatch;
Chris Lattner9f3c25a2009-11-09 22:57:59 +000030
Duncan Sands124708d2011-01-01 20:08:02 +000031#define RecursionLimit 3
Duncan Sandsa74a58c2010-11-10 18:23:01 +000032
Duncan Sandsa3c44a52010-12-22 09:40:51 +000033STATISTIC(NumExpand, "Number of expansions");
34STATISTIC(NumFactor , "Number of factorizations");
35STATISTIC(NumReassoc, "Number of reassociations");
36
Duncan Sands82fdab32010-12-21 14:00:22 +000037static Value *SimplifyAndInst(Value *, Value *, const TargetData *,
38 const DominatorTree *, unsigned);
Duncan Sandsa74a58c2010-11-10 18:23:01 +000039static Value *SimplifyBinOp(unsigned, Value *, Value *, const TargetData *,
Duncan Sands18450092010-11-16 12:16:38 +000040 const DominatorTree *, unsigned);
Duncan Sandsa74a58c2010-11-10 18:23:01 +000041static Value *SimplifyCmpInst(unsigned, Value *, Value *, const TargetData *,
Duncan Sands18450092010-11-16 12:16:38 +000042 const DominatorTree *, unsigned);
Duncan Sands82fdab32010-12-21 14:00:22 +000043static Value *SimplifyOrInst(Value *, Value *, const TargetData *,
44 const DominatorTree *, unsigned);
45static Value *SimplifyXorInst(Value *, Value *, const TargetData *,
46 const DominatorTree *, unsigned);
Duncan Sands18450092010-11-16 12:16:38 +000047
48/// ValueDominatesPHI - Does the given value dominate the specified phi node?
49static bool ValueDominatesPHI(Value *V, PHINode *P, const DominatorTree *DT) {
50 Instruction *I = dyn_cast<Instruction>(V);
51 if (!I)
52 // Arguments and constants dominate all instructions.
53 return true;
54
55 // If we have a DominatorTree then do a precise test.
56 if (DT)
57 return DT->dominates(I, P);
58
59 // Otherwise, if the instruction is in the entry block, and is not an invoke,
60 // then it obviously dominates all phi nodes.
61 if (I->getParent() == &I->getParent()->getParent()->getEntryBlock() &&
62 !isa<InvokeInst>(I))
63 return true;
64
65 return false;
66}
Duncan Sandsa74a58c2010-11-10 18:23:01 +000067
Duncan Sands3421d902010-12-21 13:32:22 +000068/// ExpandBinOp - Simplify "A op (B op' C)" by distributing op over op', turning
69/// it into "(A op B) op' (A op C)". Here "op" is given by Opcode and "op'" is
70/// given by OpcodeToExpand, while "A" corresponds to LHS and "B op' C" to RHS.
71/// Also performs the transform "(A op' B) op C" -> "(A op C) op' (B op C)".
72/// Returns the simplified value, or null if no simplification was performed.
73static Value *ExpandBinOp(unsigned Opcode, Value *LHS, Value *RHS,
Benjamin Kramere21083a2010-12-28 13:52:52 +000074 unsigned OpcToExpand, const TargetData *TD,
Duncan Sands3421d902010-12-21 13:32:22 +000075 const DominatorTree *DT, unsigned MaxRecurse) {
Benjamin Kramere21083a2010-12-28 13:52:52 +000076 Instruction::BinaryOps OpcodeToExpand = (Instruction::BinaryOps)OpcToExpand;
Duncan Sands3421d902010-12-21 13:32:22 +000077 // Recursion is always used, so bail out at once if we already hit the limit.
78 if (!MaxRecurse--)
79 return 0;
80
81 // Check whether the expression has the form "(A op' B) op C".
82 if (BinaryOperator *Op0 = dyn_cast<BinaryOperator>(LHS))
83 if (Op0->getOpcode() == OpcodeToExpand) {
84 // It does! Try turning it into "(A op C) op' (B op C)".
85 Value *A = Op0->getOperand(0), *B = Op0->getOperand(1), *C = RHS;
86 // Do "A op C" and "B op C" both simplify?
87 if (Value *L = SimplifyBinOp(Opcode, A, C, TD, DT, MaxRecurse))
88 if (Value *R = SimplifyBinOp(Opcode, B, C, TD, DT, MaxRecurse)) {
89 // They do! Return "L op' R" if it simplifies or is already available.
90 // If "L op' R" equals "A op' B" then "L op' R" is just the LHS.
Duncan Sands124708d2011-01-01 20:08:02 +000091 if ((L == A && R == B) || (Instruction::isCommutative(OpcodeToExpand)
92 && L == B && R == A)) {
Duncan Sandsa3c44a52010-12-22 09:40:51 +000093 ++NumExpand;
Duncan Sands3421d902010-12-21 13:32:22 +000094 return LHS;
Duncan Sandsa3c44a52010-12-22 09:40:51 +000095 }
Duncan Sands3421d902010-12-21 13:32:22 +000096 // Otherwise return "L op' R" if it simplifies.
Duncan Sandsa3c44a52010-12-22 09:40:51 +000097 if (Value *V = SimplifyBinOp(OpcodeToExpand, L, R, TD, DT,
98 MaxRecurse)) {
99 ++NumExpand;
Duncan Sands3421d902010-12-21 13:32:22 +0000100 return V;
Duncan Sandsa3c44a52010-12-22 09:40:51 +0000101 }
Duncan Sands3421d902010-12-21 13:32:22 +0000102 }
103 }
104
105 // Check whether the expression has the form "A op (B op' C)".
106 if (BinaryOperator *Op1 = dyn_cast<BinaryOperator>(RHS))
107 if (Op1->getOpcode() == OpcodeToExpand) {
108 // It does! Try turning it into "(A op B) op' (A op C)".
109 Value *A = LHS, *B = Op1->getOperand(0), *C = Op1->getOperand(1);
110 // Do "A op B" and "A op C" both simplify?
111 if (Value *L = SimplifyBinOp(Opcode, A, B, TD, DT, MaxRecurse))
112 if (Value *R = SimplifyBinOp(Opcode, A, C, TD, DT, MaxRecurse)) {
113 // They do! Return "L op' R" if it simplifies or is already available.
114 // If "L op' R" equals "B op' C" then "L op' R" is just the RHS.
Duncan Sands124708d2011-01-01 20:08:02 +0000115 if ((L == B && R == C) || (Instruction::isCommutative(OpcodeToExpand)
116 && L == C && R == B)) {
Duncan Sandsa3c44a52010-12-22 09:40:51 +0000117 ++NumExpand;
Duncan Sands3421d902010-12-21 13:32:22 +0000118 return RHS;
Duncan Sandsa3c44a52010-12-22 09:40:51 +0000119 }
Duncan Sands3421d902010-12-21 13:32:22 +0000120 // Otherwise return "L op' R" if it simplifies.
Duncan Sandsa3c44a52010-12-22 09:40:51 +0000121 if (Value *V = SimplifyBinOp(OpcodeToExpand, L, R, TD, DT,
122 MaxRecurse)) {
123 ++NumExpand;
Duncan Sands3421d902010-12-21 13:32:22 +0000124 return V;
Duncan Sandsa3c44a52010-12-22 09:40:51 +0000125 }
Duncan Sands3421d902010-12-21 13:32:22 +0000126 }
127 }
128
129 return 0;
130}
131
132/// FactorizeBinOp - Simplify "LHS Opcode RHS" by factorizing out a common term
133/// using the operation OpCodeToExtract. For example, when Opcode is Add and
134/// OpCodeToExtract is Mul then this tries to turn "(A*B)+(A*C)" into "A*(B+C)".
135/// Returns the simplified value, or null if no simplification was performed.
136static Value *FactorizeBinOp(unsigned Opcode, Value *LHS, Value *RHS,
Benjamin Kramere21083a2010-12-28 13:52:52 +0000137 unsigned OpcToExtract, const TargetData *TD,
Duncan Sands3421d902010-12-21 13:32:22 +0000138 const DominatorTree *DT, unsigned MaxRecurse) {
Benjamin Kramere21083a2010-12-28 13:52:52 +0000139 Instruction::BinaryOps OpcodeToExtract = (Instruction::BinaryOps)OpcToExtract;
Duncan Sands3421d902010-12-21 13:32:22 +0000140 // Recursion is always used, so bail out at once if we already hit the limit.
141 if (!MaxRecurse--)
142 return 0;
143
144 BinaryOperator *Op0 = dyn_cast<BinaryOperator>(LHS);
145 BinaryOperator *Op1 = dyn_cast<BinaryOperator>(RHS);
146
147 if (!Op0 || Op0->getOpcode() != OpcodeToExtract ||
148 !Op1 || Op1->getOpcode() != OpcodeToExtract)
149 return 0;
150
151 // The expression has the form "(A op' B) op (C op' D)".
Duncan Sands82fdab32010-12-21 14:00:22 +0000152 Value *A = Op0->getOperand(0), *B = Op0->getOperand(1);
153 Value *C = Op1->getOperand(0), *D = Op1->getOperand(1);
Duncan Sands3421d902010-12-21 13:32:22 +0000154
155 // Use left distributivity, i.e. "X op' (Y op Z) = (X op' Y) op (X op' Z)".
156 // Does the instruction have the form "(A op' B) op (A op' D)" or, in the
157 // commutative case, "(A op' B) op (C op' A)"?
Duncan Sands124708d2011-01-01 20:08:02 +0000158 if (A == C || (Instruction::isCommutative(OpcodeToExtract) && A == D)) {
159 Value *DD = A == C ? D : C;
Duncan Sands3421d902010-12-21 13:32:22 +0000160 // Form "A op' (B op DD)" if it simplifies completely.
161 // Does "B op DD" simplify?
162 if (Value *V = SimplifyBinOp(Opcode, B, DD, TD, DT, MaxRecurse)) {
163 // It does! Return "A op' V" if it simplifies or is already available.
Duncan Sands1cd05bb2010-12-22 17:15:25 +0000164 // If V equals B then "A op' V" is just the LHS. If V equals DD then
165 // "A op' V" is just the RHS.
Duncan Sands124708d2011-01-01 20:08:02 +0000166 if (V == B || V == DD) {
Duncan Sandsa3c44a52010-12-22 09:40:51 +0000167 ++NumFactor;
Duncan Sands124708d2011-01-01 20:08:02 +0000168 return V == B ? LHS : RHS;
Duncan Sandsa3c44a52010-12-22 09:40:51 +0000169 }
Duncan Sands3421d902010-12-21 13:32:22 +0000170 // Otherwise return "A op' V" if it simplifies.
Duncan Sandsa3c44a52010-12-22 09:40:51 +0000171 if (Value *W = SimplifyBinOp(OpcodeToExtract, A, V, TD, DT, MaxRecurse)) {
172 ++NumFactor;
Duncan Sands3421d902010-12-21 13:32:22 +0000173 return W;
Duncan Sandsa3c44a52010-12-22 09:40:51 +0000174 }
Duncan Sands3421d902010-12-21 13:32:22 +0000175 }
176 }
177
178 // Use right distributivity, i.e. "(X op Y) op' Z = (X op' Z) op (Y op' Z)".
179 // Does the instruction have the form "(A op' B) op (C op' B)" or, in the
180 // commutative case, "(A op' B) op (B op' D)"?
Duncan Sands124708d2011-01-01 20:08:02 +0000181 if (B == D || (Instruction::isCommutative(OpcodeToExtract) && B == C)) {
182 Value *CC = B == D ? C : D;
Duncan Sands3421d902010-12-21 13:32:22 +0000183 // Form "(A op CC) op' B" if it simplifies completely..
184 // Does "A op CC" simplify?
185 if (Value *V = SimplifyBinOp(Opcode, A, CC, TD, DT, MaxRecurse)) {
186 // It does! Return "V op' B" if it simplifies or is already available.
Duncan Sands1cd05bb2010-12-22 17:15:25 +0000187 // If V equals A then "V op' B" is just the LHS. If V equals CC then
188 // "V op' B" is just the RHS.
Duncan Sands124708d2011-01-01 20:08:02 +0000189 if (V == A || V == CC) {
Duncan Sandsa3c44a52010-12-22 09:40:51 +0000190 ++NumFactor;
Duncan Sands124708d2011-01-01 20:08:02 +0000191 return V == A ? LHS : RHS;
Duncan Sandsa3c44a52010-12-22 09:40:51 +0000192 }
Duncan Sands3421d902010-12-21 13:32:22 +0000193 // Otherwise return "V op' B" if it simplifies.
Duncan Sandsa3c44a52010-12-22 09:40:51 +0000194 if (Value *W = SimplifyBinOp(OpcodeToExtract, V, B, TD, DT, MaxRecurse)) {
195 ++NumFactor;
Duncan Sands3421d902010-12-21 13:32:22 +0000196 return W;
Duncan Sandsa3c44a52010-12-22 09:40:51 +0000197 }
Duncan Sands3421d902010-12-21 13:32:22 +0000198 }
199 }
200
201 return 0;
202}
203
204/// SimplifyAssociativeBinOp - Generic simplifications for associative binary
205/// operations. Returns the simpler value, or null if none was found.
Benjamin Kramere21083a2010-12-28 13:52:52 +0000206static Value *SimplifyAssociativeBinOp(unsigned Opc, Value *LHS, Value *RHS,
Duncan Sands566edb02010-12-21 08:49:00 +0000207 const TargetData *TD,
208 const DominatorTree *DT,
209 unsigned MaxRecurse) {
Benjamin Kramere21083a2010-12-28 13:52:52 +0000210 Instruction::BinaryOps Opcode = (Instruction::BinaryOps)Opc;
Duncan Sands566edb02010-12-21 08:49:00 +0000211 assert(Instruction::isAssociative(Opcode) && "Not an associative operation!");
212
213 // Recursion is always used, so bail out at once if we already hit the limit.
214 if (!MaxRecurse--)
215 return 0;
216
217 BinaryOperator *Op0 = dyn_cast<BinaryOperator>(LHS);
218 BinaryOperator *Op1 = dyn_cast<BinaryOperator>(RHS);
219
220 // Transform: "(A op B) op C" ==> "A op (B op C)" if it simplifies completely.
221 if (Op0 && Op0->getOpcode() == Opcode) {
222 Value *A = Op0->getOperand(0);
223 Value *B = Op0->getOperand(1);
224 Value *C = RHS;
225
226 // Does "B op C" simplify?
227 if (Value *V = SimplifyBinOp(Opcode, B, C, TD, DT, MaxRecurse)) {
228 // It does! Return "A op V" if it simplifies or is already available.
229 // If V equals B then "A op V" is just the LHS.
Duncan Sands124708d2011-01-01 20:08:02 +0000230 if (V == B) return LHS;
Duncan Sands566edb02010-12-21 08:49:00 +0000231 // Otherwise return "A op V" if it simplifies.
Duncan Sandsa3c44a52010-12-22 09:40:51 +0000232 if (Value *W = SimplifyBinOp(Opcode, A, V, TD, DT, MaxRecurse)) {
233 ++NumReassoc;
Duncan Sands566edb02010-12-21 08:49:00 +0000234 return W;
Duncan Sandsa3c44a52010-12-22 09:40:51 +0000235 }
Duncan Sands566edb02010-12-21 08:49:00 +0000236 }
237 }
238
239 // Transform: "A op (B op C)" ==> "(A op B) op C" if it simplifies completely.
240 if (Op1 && Op1->getOpcode() == Opcode) {
241 Value *A = LHS;
242 Value *B = Op1->getOperand(0);
243 Value *C = Op1->getOperand(1);
244
245 // Does "A op B" simplify?
246 if (Value *V = SimplifyBinOp(Opcode, A, B, TD, DT, MaxRecurse)) {
247 // It does! Return "V op C" if it simplifies or is already available.
248 // If V equals B then "V op C" is just the RHS.
Duncan Sands124708d2011-01-01 20:08:02 +0000249 if (V == B) return RHS;
Duncan Sands566edb02010-12-21 08:49:00 +0000250 // Otherwise return "V op C" if it simplifies.
Duncan Sandsa3c44a52010-12-22 09:40:51 +0000251 if (Value *W = SimplifyBinOp(Opcode, V, C, TD, DT, MaxRecurse)) {
252 ++NumReassoc;
Duncan Sands566edb02010-12-21 08:49:00 +0000253 return W;
Duncan Sandsa3c44a52010-12-22 09:40:51 +0000254 }
Duncan Sands566edb02010-12-21 08:49:00 +0000255 }
256 }
257
258 // The remaining transforms require commutativity as well as associativity.
259 if (!Instruction::isCommutative(Opcode))
260 return 0;
261
262 // Transform: "(A op B) op C" ==> "(C op A) op B" if it simplifies completely.
263 if (Op0 && Op0->getOpcode() == Opcode) {
264 Value *A = Op0->getOperand(0);
265 Value *B = Op0->getOperand(1);
266 Value *C = RHS;
267
268 // Does "C op A" simplify?
269 if (Value *V = SimplifyBinOp(Opcode, C, A, TD, DT, MaxRecurse)) {
270 // It does! Return "V op B" if it simplifies or is already available.
271 // If V equals A then "V op B" is just the LHS.
Duncan Sands124708d2011-01-01 20:08:02 +0000272 if (V == A) return LHS;
Duncan Sands566edb02010-12-21 08:49:00 +0000273 // Otherwise return "V op B" if it simplifies.
Duncan Sandsa3c44a52010-12-22 09:40:51 +0000274 if (Value *W = SimplifyBinOp(Opcode, V, B, TD, DT, MaxRecurse)) {
275 ++NumReassoc;
Duncan Sands566edb02010-12-21 08:49:00 +0000276 return W;
Duncan Sandsa3c44a52010-12-22 09:40:51 +0000277 }
Duncan Sands566edb02010-12-21 08:49:00 +0000278 }
279 }
280
281 // Transform: "A op (B op C)" ==> "B op (C op A)" if it simplifies completely.
282 if (Op1 && Op1->getOpcode() == Opcode) {
283 Value *A = LHS;
284 Value *B = Op1->getOperand(0);
285 Value *C = Op1->getOperand(1);
286
287 // Does "C op A" simplify?
288 if (Value *V = SimplifyBinOp(Opcode, C, A, TD, DT, MaxRecurse)) {
289 // It does! Return "B op V" if it simplifies or is already available.
290 // If V equals C then "B op V" is just the RHS.
Duncan Sands124708d2011-01-01 20:08:02 +0000291 if (V == C) return RHS;
Duncan Sands566edb02010-12-21 08:49:00 +0000292 // Otherwise return "B op V" if it simplifies.
Duncan Sandsa3c44a52010-12-22 09:40:51 +0000293 if (Value *W = SimplifyBinOp(Opcode, B, V, TD, DT, MaxRecurse)) {
294 ++NumReassoc;
Duncan Sands566edb02010-12-21 08:49:00 +0000295 return W;
Duncan Sandsa3c44a52010-12-22 09:40:51 +0000296 }
Duncan Sands566edb02010-12-21 08:49:00 +0000297 }
298 }
299
300 return 0;
301}
302
Duncan Sandsb2cbdc32010-11-10 13:00:08 +0000303/// ThreadBinOpOverSelect - In the case of a binary operation with a select
304/// instruction as an operand, try to simplify the binop by seeing whether
305/// evaluating it on both branches of the select results in the same value.
306/// Returns the common value if so, otherwise returns null.
307static Value *ThreadBinOpOverSelect(unsigned Opcode, Value *LHS, Value *RHS,
Duncan Sands18450092010-11-16 12:16:38 +0000308 const TargetData *TD,
309 const DominatorTree *DT,
310 unsigned MaxRecurse) {
Duncan Sands0312a932010-12-21 09:09:15 +0000311 // Recursion is always used, so bail out at once if we already hit the limit.
312 if (!MaxRecurse--)
313 return 0;
314
Duncan Sandsb2cbdc32010-11-10 13:00:08 +0000315 SelectInst *SI;
316 if (isa<SelectInst>(LHS)) {
317 SI = cast<SelectInst>(LHS);
318 } else {
319 assert(isa<SelectInst>(RHS) && "No select instruction operand!");
320 SI = cast<SelectInst>(RHS);
321 }
322
323 // Evaluate the BinOp on the true and false branches of the select.
324 Value *TV;
325 Value *FV;
326 if (SI == LHS) {
Duncan Sands18450092010-11-16 12:16:38 +0000327 TV = SimplifyBinOp(Opcode, SI->getTrueValue(), RHS, TD, DT, MaxRecurse);
328 FV = SimplifyBinOp(Opcode, SI->getFalseValue(), RHS, TD, DT, MaxRecurse);
Duncan Sandsb2cbdc32010-11-10 13:00:08 +0000329 } else {
Duncan Sands18450092010-11-16 12:16:38 +0000330 TV = SimplifyBinOp(Opcode, LHS, SI->getTrueValue(), TD, DT, MaxRecurse);
331 FV = SimplifyBinOp(Opcode, LHS, SI->getFalseValue(), TD, DT, MaxRecurse);
Duncan Sandsb2cbdc32010-11-10 13:00:08 +0000332 }
333
Duncan Sands7cf85e72011-01-01 16:12:09 +0000334 // If they simplified to the same value, then return the common value.
Duncan Sands124708d2011-01-01 20:08:02 +0000335 // If they both failed to simplify then return null.
336 if (TV == FV)
Duncan Sandsb2cbdc32010-11-10 13:00:08 +0000337 return TV;
338
339 // If one branch simplified to undef, return the other one.
340 if (TV && isa<UndefValue>(TV))
341 return FV;
342 if (FV && isa<UndefValue>(FV))
343 return TV;
344
345 // If applying the operation did not change the true and false select values,
346 // then the result of the binop is the select itself.
Duncan Sands124708d2011-01-01 20:08:02 +0000347 if (TV == SI->getTrueValue() && FV == SI->getFalseValue())
Duncan Sandsb2cbdc32010-11-10 13:00:08 +0000348 return SI;
349
350 // If one branch simplified and the other did not, and the simplified
351 // value is equal to the unsimplified one, return the simplified value.
352 // For example, select (cond, X, X & Z) & Z -> X & Z.
353 if ((FV && !TV) || (TV && !FV)) {
354 // Check that the simplified value has the form "X op Y" where "op" is the
355 // same as the original operation.
356 Instruction *Simplified = dyn_cast<Instruction>(FV ? FV : TV);
357 if (Simplified && Simplified->getOpcode() == Opcode) {
358 // The value that didn't simplify is "UnsimplifiedLHS op UnsimplifiedRHS".
359 // We already know that "op" is the same as for the simplified value. See
360 // if the operands match too. If so, return the simplified value.
361 Value *UnsimplifiedBranch = FV ? SI->getTrueValue() : SI->getFalseValue();
362 Value *UnsimplifiedLHS = SI == LHS ? UnsimplifiedBranch : LHS;
363 Value *UnsimplifiedRHS = SI == LHS ? RHS : UnsimplifiedBranch;
Duncan Sands124708d2011-01-01 20:08:02 +0000364 if (Simplified->getOperand(0) == UnsimplifiedLHS &&
365 Simplified->getOperand(1) == UnsimplifiedRHS)
Duncan Sandsb2cbdc32010-11-10 13:00:08 +0000366 return Simplified;
367 if (Simplified->isCommutative() &&
Duncan Sands124708d2011-01-01 20:08:02 +0000368 Simplified->getOperand(1) == UnsimplifiedLHS &&
369 Simplified->getOperand(0) == UnsimplifiedRHS)
Duncan Sandsb2cbdc32010-11-10 13:00:08 +0000370 return Simplified;
371 }
372 }
373
374 return 0;
375}
376
377/// ThreadCmpOverSelect - In the case of a comparison with a select instruction,
378/// try to simplify the comparison by seeing whether both branches of the select
379/// result in the same value. Returns the common value if so, otherwise returns
380/// null.
381static Value *ThreadCmpOverSelect(CmpInst::Predicate Pred, Value *LHS,
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000382 Value *RHS, const TargetData *TD,
Duncan Sands18450092010-11-16 12:16:38 +0000383 const DominatorTree *DT,
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000384 unsigned MaxRecurse) {
Duncan Sands0312a932010-12-21 09:09:15 +0000385 // Recursion is always used, so bail out at once if we already hit the limit.
386 if (!MaxRecurse--)
387 return 0;
388
Duncan Sandsb2cbdc32010-11-10 13:00:08 +0000389 // Make sure the select is on the LHS.
390 if (!isa<SelectInst>(LHS)) {
391 std::swap(LHS, RHS);
392 Pred = CmpInst::getSwappedPredicate(Pred);
393 }
394 assert(isa<SelectInst>(LHS) && "Not comparing with a select instruction!");
395 SelectInst *SI = cast<SelectInst>(LHS);
396
397 // Now that we have "cmp select(cond, TV, FV), RHS", analyse it.
398 // Does "cmp TV, RHS" simplify?
Duncan Sands18450092010-11-16 12:16:38 +0000399 if (Value *TCmp = SimplifyCmpInst(Pred, SI->getTrueValue(), RHS, TD, DT,
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000400 MaxRecurse))
Duncan Sandsb2cbdc32010-11-10 13:00:08 +0000401 // It does! Does "cmp FV, RHS" simplify?
Duncan Sands18450092010-11-16 12:16:38 +0000402 if (Value *FCmp = SimplifyCmpInst(Pred, SI->getFalseValue(), RHS, TD, DT,
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000403 MaxRecurse))
Duncan Sandsb2cbdc32010-11-10 13:00:08 +0000404 // It does! If they simplified to the same value, then use it as the
405 // result of the original comparison.
Duncan Sands124708d2011-01-01 20:08:02 +0000406 if (TCmp == FCmp)
Duncan Sandsb2cbdc32010-11-10 13:00:08 +0000407 return TCmp;
408 return 0;
409}
410
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000411/// ThreadBinOpOverPHI - In the case of a binary operation with an operand that
412/// is a PHI instruction, try to simplify the binop by seeing whether evaluating
413/// it on the incoming phi values yields the same result for every value. If so
414/// returns the common value, otherwise returns null.
415static Value *ThreadBinOpOverPHI(unsigned Opcode, Value *LHS, Value *RHS,
Duncan Sands18450092010-11-16 12:16:38 +0000416 const TargetData *TD, const DominatorTree *DT,
417 unsigned MaxRecurse) {
Duncan Sands0312a932010-12-21 09:09:15 +0000418 // Recursion is always used, so bail out at once if we already hit the limit.
419 if (!MaxRecurse--)
420 return 0;
421
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000422 PHINode *PI;
423 if (isa<PHINode>(LHS)) {
424 PI = cast<PHINode>(LHS);
Duncan Sands18450092010-11-16 12:16:38 +0000425 // Bail out if RHS and the phi may be mutually interdependent due to a loop.
426 if (!ValueDominatesPHI(RHS, PI, DT))
427 return 0;
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000428 } else {
429 assert(isa<PHINode>(RHS) && "No PHI instruction operand!");
430 PI = cast<PHINode>(RHS);
Duncan Sands18450092010-11-16 12:16:38 +0000431 // Bail out if LHS and the phi may be mutually interdependent due to a loop.
432 if (!ValueDominatesPHI(LHS, PI, DT))
433 return 0;
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000434 }
435
436 // Evaluate the BinOp on the incoming phi values.
437 Value *CommonValue = 0;
438 for (unsigned i = 0, e = PI->getNumIncomingValues(); i != e; ++i) {
Duncan Sands55200892010-11-15 17:52:45 +0000439 Value *Incoming = PI->getIncomingValue(i);
Duncan Sandsff103412010-11-17 04:30:22 +0000440 // If the incoming value is the phi node itself, it can safely be skipped.
Duncan Sands55200892010-11-15 17:52:45 +0000441 if (Incoming == PI) continue;
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000442 Value *V = PI == LHS ?
Duncan Sands18450092010-11-16 12:16:38 +0000443 SimplifyBinOp(Opcode, Incoming, RHS, TD, DT, MaxRecurse) :
444 SimplifyBinOp(Opcode, LHS, Incoming, TD, DT, MaxRecurse);
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000445 // If the operation failed to simplify, or simplified to a different value
446 // to previously, then give up.
447 if (!V || (CommonValue && V != CommonValue))
448 return 0;
449 CommonValue = V;
450 }
451
452 return CommonValue;
453}
454
455/// ThreadCmpOverPHI - In the case of a comparison with a PHI instruction, try
456/// try to simplify the comparison by seeing whether comparing with all of the
457/// incoming phi values yields the same result every time. If so returns the
458/// common result, otherwise returns null.
459static Value *ThreadCmpOverPHI(CmpInst::Predicate Pred, Value *LHS, Value *RHS,
Duncan Sands18450092010-11-16 12:16:38 +0000460 const TargetData *TD, const DominatorTree *DT,
461 unsigned MaxRecurse) {
Duncan Sands0312a932010-12-21 09:09:15 +0000462 // Recursion is always used, so bail out at once if we already hit the limit.
463 if (!MaxRecurse--)
464 return 0;
465
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000466 // Make sure the phi is on the LHS.
467 if (!isa<PHINode>(LHS)) {
468 std::swap(LHS, RHS);
469 Pred = CmpInst::getSwappedPredicate(Pred);
470 }
471 assert(isa<PHINode>(LHS) && "Not comparing with a phi instruction!");
472 PHINode *PI = cast<PHINode>(LHS);
473
Duncan Sands18450092010-11-16 12:16:38 +0000474 // Bail out if RHS and the phi may be mutually interdependent due to a loop.
475 if (!ValueDominatesPHI(RHS, PI, DT))
476 return 0;
477
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000478 // Evaluate the BinOp on the incoming phi values.
479 Value *CommonValue = 0;
480 for (unsigned i = 0, e = PI->getNumIncomingValues(); i != e; ++i) {
Duncan Sands55200892010-11-15 17:52:45 +0000481 Value *Incoming = PI->getIncomingValue(i);
Duncan Sandsff103412010-11-17 04:30:22 +0000482 // If the incoming value is the phi node itself, it can safely be skipped.
Duncan Sands55200892010-11-15 17:52:45 +0000483 if (Incoming == PI) continue;
Duncan Sands18450092010-11-16 12:16:38 +0000484 Value *V = SimplifyCmpInst(Pred, Incoming, RHS, TD, DT, MaxRecurse);
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000485 // If the operation failed to simplify, or simplified to a different value
486 // to previously, then give up.
487 if (!V || (CommonValue && V != CommonValue))
488 return 0;
489 CommonValue = V;
490 }
491
492 return CommonValue;
493}
494
Chris Lattner8aee8ef2009-11-27 17:42:22 +0000495/// SimplifyAddInst - Given operands for an Add, see if we can
496/// fold the result. If not, this returns null.
Duncan Sandsee9a2e32010-12-20 14:47:04 +0000497static Value *SimplifyAddInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
498 const TargetData *TD, const DominatorTree *DT,
499 unsigned MaxRecurse) {
Chris Lattner8aee8ef2009-11-27 17:42:22 +0000500 if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
501 if (Constant *CRHS = dyn_cast<Constant>(Op1)) {
502 Constant *Ops[] = { CLHS, CRHS };
503 return ConstantFoldInstOperands(Instruction::Add, CLHS->getType(),
504 Ops, 2, TD);
505 }
Duncan Sands12a86f52010-11-14 11:23:23 +0000506
Chris Lattner8aee8ef2009-11-27 17:42:22 +0000507 // Canonicalize the constant to the RHS.
508 std::swap(Op0, Op1);
509 }
Duncan Sands12a86f52010-11-14 11:23:23 +0000510
Duncan Sandsfea3b212010-12-15 14:07:39 +0000511 // X + undef -> undef
512 if (isa<UndefValue>(Op1))
513 return Op1;
Duncan Sands12a86f52010-11-14 11:23:23 +0000514
Duncan Sandsfea3b212010-12-15 14:07:39 +0000515 // X + 0 -> X
516 if (match(Op1, m_Zero()))
517 return Op0;
Duncan Sands12a86f52010-11-14 11:23:23 +0000518
Duncan Sandsfea3b212010-12-15 14:07:39 +0000519 // X + (Y - X) -> Y
520 // (Y - X) + X -> Y
Duncan Sandsee9a2e32010-12-20 14:47:04 +0000521 // Eg: X + -X -> 0
Duncan Sands124708d2011-01-01 20:08:02 +0000522 Value *Y = 0;
523 if (match(Op1, m_Sub(m_Value(Y), m_Specific(Op0))) ||
524 match(Op0, m_Sub(m_Value(Y), m_Specific(Op1))))
Duncan Sandsfea3b212010-12-15 14:07:39 +0000525 return Y;
526
527 // X + ~X -> -1 since ~X = -X-1
Duncan Sands124708d2011-01-01 20:08:02 +0000528 if (match(Op0, m_Not(m_Specific(Op1))) ||
529 match(Op1, m_Not(m_Specific(Op0))))
Duncan Sandsfea3b212010-12-15 14:07:39 +0000530 return Constant::getAllOnesValue(Op0->getType());
Duncan Sands87689cf2010-11-19 09:20:39 +0000531
Duncan Sands82fdab32010-12-21 14:00:22 +0000532 /// i1 add -> xor.
Duncan Sands75d289e2010-12-21 14:48:48 +0000533 if (MaxRecurse && Op0->getType()->isIntegerTy(1))
Duncan Sands07f30fb2010-12-21 15:03:43 +0000534 if (Value *V = SimplifyXorInst(Op0, Op1, TD, DT, MaxRecurse-1))
535 return V;
Duncan Sands82fdab32010-12-21 14:00:22 +0000536
Duncan Sands566edb02010-12-21 08:49:00 +0000537 // Try some generic simplifications for associative operations.
538 if (Value *V = SimplifyAssociativeBinOp(Instruction::Add, Op0, Op1, TD, DT,
539 MaxRecurse))
540 return V;
541
Duncan Sands3421d902010-12-21 13:32:22 +0000542 // Mul distributes over Add. Try some generic simplifications based on this.
543 if (Value *V = FactorizeBinOp(Instruction::Add, Op0, Op1, Instruction::Mul,
544 TD, DT, MaxRecurse))
545 return V;
546
Duncan Sands87689cf2010-11-19 09:20:39 +0000547 // Threading Add over selects and phi nodes is pointless, so don't bother.
548 // Threading over the select in "A + select(cond, B, C)" means evaluating
549 // "A+B" and "A+C" and seeing if they are equal; but they are equal if and
550 // only if B and C are equal. If B and C are equal then (since we assume
551 // that operands have already been simplified) "select(cond, B, C)" should
552 // have been simplified to the common value of B and C already. Analysing
553 // "A+B" and "A+C" thus gains nothing, but costs compile time. Similarly
554 // for threading over phi nodes.
555
Chris Lattner8aee8ef2009-11-27 17:42:22 +0000556 return 0;
557}
558
Duncan Sandsee9a2e32010-12-20 14:47:04 +0000559Value *llvm::SimplifyAddInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
560 const TargetData *TD, const DominatorTree *DT) {
561 return ::SimplifyAddInst(Op0, Op1, isNSW, isNUW, TD, DT, RecursionLimit);
562}
563
Duncan Sandsfea3b212010-12-15 14:07:39 +0000564/// SimplifySubInst - Given operands for a Sub, see if we can
565/// fold the result. If not, this returns null.
Duncan Sandsee9a2e32010-12-20 14:47:04 +0000566static Value *SimplifySubInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
Duncan Sands3421d902010-12-21 13:32:22 +0000567 const TargetData *TD, const DominatorTree *DT,
Duncan Sandsee9a2e32010-12-20 14:47:04 +0000568 unsigned MaxRecurse) {
Duncan Sandsfea3b212010-12-15 14:07:39 +0000569 if (Constant *CLHS = dyn_cast<Constant>(Op0))
570 if (Constant *CRHS = dyn_cast<Constant>(Op1)) {
571 Constant *Ops[] = { CLHS, CRHS };
572 return ConstantFoldInstOperands(Instruction::Sub, CLHS->getType(),
573 Ops, 2, TD);
574 }
575
576 // X - undef -> undef
577 // undef - X -> undef
578 if (isa<UndefValue>(Op0) || isa<UndefValue>(Op1))
579 return UndefValue::get(Op0->getType());
580
581 // X - 0 -> X
582 if (match(Op1, m_Zero()))
583 return Op0;
584
585 // X - X -> 0
Duncan Sands124708d2011-01-01 20:08:02 +0000586 if (Op0 == Op1)
Duncan Sandsfea3b212010-12-15 14:07:39 +0000587 return Constant::getNullValue(Op0->getType());
588
589 // (X + Y) - Y -> X
590 // (Y + X) - Y -> X
Duncan Sands124708d2011-01-01 20:08:02 +0000591 Value *X = 0;
592 if (match(Op0, m_Add(m_Value(X), m_Specific(Op1))) ||
593 match(Op0, m_Add(m_Specific(Op1), m_Value(X))))
Duncan Sandsfea3b212010-12-15 14:07:39 +0000594 return X;
595
Duncan Sands82fdab32010-12-21 14:00:22 +0000596 /// i1 sub -> xor.
Duncan Sands75d289e2010-12-21 14:48:48 +0000597 if (MaxRecurse && Op0->getType()->isIntegerTy(1))
Duncan Sands07f30fb2010-12-21 15:03:43 +0000598 if (Value *V = SimplifyXorInst(Op0, Op1, TD, DT, MaxRecurse-1))
599 return V;
Duncan Sands82fdab32010-12-21 14:00:22 +0000600
Duncan Sands3421d902010-12-21 13:32:22 +0000601 // Mul distributes over Sub. Try some generic simplifications based on this.
602 if (Value *V = FactorizeBinOp(Instruction::Sub, Op0, Op1, Instruction::Mul,
603 TD, DT, MaxRecurse))
604 return V;
605
Duncan Sandsfea3b212010-12-15 14:07:39 +0000606 // Threading Sub over selects and phi nodes is pointless, so don't bother.
607 // Threading over the select in "A - select(cond, B, C)" means evaluating
608 // "A-B" and "A-C" and seeing if they are equal; but they are equal if and
609 // only if B and C are equal. If B and C are equal then (since we assume
610 // that operands have already been simplified) "select(cond, B, C)" should
611 // have been simplified to the common value of B and C already. Analysing
612 // "A-B" and "A-C" thus gains nothing, but costs compile time. Similarly
613 // for threading over phi nodes.
614
615 return 0;
616}
617
Duncan Sandsee9a2e32010-12-20 14:47:04 +0000618Value *llvm::SimplifySubInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
619 const TargetData *TD, const DominatorTree *DT) {
620 return ::SimplifySubInst(Op0, Op1, isNSW, isNUW, TD, DT, RecursionLimit);
621}
622
Duncan Sands82fdab32010-12-21 14:00:22 +0000623/// SimplifyMulInst - Given operands for a Mul, see if we can
624/// fold the result. If not, this returns null.
625static Value *SimplifyMulInst(Value *Op0, Value *Op1, const TargetData *TD,
626 const DominatorTree *DT, unsigned MaxRecurse) {
627 if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
628 if (Constant *CRHS = dyn_cast<Constant>(Op1)) {
629 Constant *Ops[] = { CLHS, CRHS };
630 return ConstantFoldInstOperands(Instruction::Mul, CLHS->getType(),
631 Ops, 2, TD);
632 }
633
634 // Canonicalize the constant to the RHS.
635 std::swap(Op0, Op1);
636 }
637
638 // X * undef -> 0
639 if (isa<UndefValue>(Op1))
640 return Constant::getNullValue(Op0->getType());
641
642 // X * 0 -> 0
643 if (match(Op1, m_Zero()))
644 return Op1;
645
646 // X * 1 -> X
647 if (match(Op1, m_One()))
648 return Op0;
649
650 /// i1 mul -> and.
Duncan Sands75d289e2010-12-21 14:48:48 +0000651 if (MaxRecurse && Op0->getType()->isIntegerTy(1))
Duncan Sands07f30fb2010-12-21 15:03:43 +0000652 if (Value *V = SimplifyAndInst(Op0, Op1, TD, DT, MaxRecurse-1))
653 return V;
Duncan Sands82fdab32010-12-21 14:00:22 +0000654
655 // Try some generic simplifications for associative operations.
656 if (Value *V = SimplifyAssociativeBinOp(Instruction::Mul, Op0, Op1, TD, DT,
657 MaxRecurse))
658 return V;
659
660 // Mul distributes over Add. Try some generic simplifications based on this.
661 if (Value *V = ExpandBinOp(Instruction::Mul, Op0, Op1, Instruction::Add,
662 TD, DT, MaxRecurse))
663 return V;
664
665 // If the operation is with the result of a select instruction, check whether
666 // operating on either branch of the select always yields the same value.
667 if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
668 if (Value *V = ThreadBinOpOverSelect(Instruction::Mul, Op0, Op1, TD, DT,
669 MaxRecurse))
670 return V;
671
672 // If the operation is with the result of a phi instruction, check whether
673 // operating on all incoming values of the phi always yields the same value.
674 if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
675 if (Value *V = ThreadBinOpOverPHI(Instruction::Mul, Op0, Op1, TD, DT,
676 MaxRecurse))
677 return V;
678
679 return 0;
680}
681
682Value *llvm::SimplifyMulInst(Value *Op0, Value *Op1, const TargetData *TD,
683 const DominatorTree *DT) {
684 return ::SimplifyMulInst(Op0, Op1, TD, DT, RecursionLimit);
685}
686
Duncan Sandscf80bc12011-01-14 14:44:12 +0000687/// SimplifyShift - Given operands for an Shl, LShr or AShr, see if we can
Duncan Sandsc43cee32011-01-14 00:37:45 +0000688/// fold the result. If not, this returns null.
Duncan Sandscf80bc12011-01-14 14:44:12 +0000689static Value *SimplifyShift(unsigned Opcode, Value *Op0, Value *Op1,
690 const TargetData *TD, const DominatorTree *DT,
691 unsigned MaxRecurse) {
Duncan Sandsc43cee32011-01-14 00:37:45 +0000692 if (Constant *C0 = dyn_cast<Constant>(Op0)) {
693 if (Constant *C1 = dyn_cast<Constant>(Op1)) {
694 Constant *Ops[] = { C0, C1 };
Duncan Sandscf80bc12011-01-14 14:44:12 +0000695 return ConstantFoldInstOperands(Opcode, C0->getType(), Ops, 2, TD);
Duncan Sandsc43cee32011-01-14 00:37:45 +0000696 }
697 }
698
Duncan Sandscf80bc12011-01-14 14:44:12 +0000699 // 0 shift by X -> 0
Duncan Sandsc43cee32011-01-14 00:37:45 +0000700 if (match(Op0, m_Zero()))
701 return Op0;
702
Duncan Sandscf80bc12011-01-14 14:44:12 +0000703 // X shift by 0 -> X
Duncan Sandsc43cee32011-01-14 00:37:45 +0000704 if (match(Op1, m_Zero()))
705 return Op0;
706
Duncan Sandscf80bc12011-01-14 14:44:12 +0000707 // X shift by undef -> undef because it may shift by the bitwidth.
Duncan Sandsc43cee32011-01-14 00:37:45 +0000708 if (isa<UndefValue>(Op1))
709 return Op1;
710
711 // Shifting by the bitwidth or more is undefined.
712 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1))
713 if (CI->getValue().getLimitedValue() >=
714 Op0->getType()->getScalarSizeInBits())
715 return UndefValue::get(Op0->getType());
716
Duncan Sandscf80bc12011-01-14 14:44:12 +0000717 // If the operation is with the result of a select instruction, check whether
718 // operating on either branch of the select always yields the same value.
719 if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
720 if (Value *V = ThreadBinOpOverSelect(Opcode, Op0, Op1, TD, DT, MaxRecurse))
721 return V;
722
723 // If the operation is with the result of a phi instruction, check whether
724 // operating on all incoming values of the phi always yields the same value.
725 if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
726 if (Value *V = ThreadBinOpOverPHI(Opcode, Op0, Op1, TD, DT, MaxRecurse))
727 return V;
728
729 return 0;
730}
731
732/// SimplifyShlInst - Given operands for an Shl, see if we can
733/// fold the result. If not, this returns null.
734static Value *SimplifyShlInst(Value *Op0, Value *Op1, const TargetData *TD,
735 const DominatorTree *DT, unsigned MaxRecurse) {
736 if (Value *V = SimplifyShift(Instruction::Shl, Op0, Op1, TD, DT, MaxRecurse))
737 return V;
738
739 // undef << X -> 0
740 if (isa<UndefValue>(Op0))
741 return Constant::getNullValue(Op0->getType());
742
Duncan Sandsc43cee32011-01-14 00:37:45 +0000743 return 0;
744}
745
746Value *llvm::SimplifyShlInst(Value *Op0, Value *Op1, const TargetData *TD,
747 const DominatorTree *DT) {
748 return ::SimplifyShlInst(Op0, Op1, TD, DT, RecursionLimit);
749}
750
751/// SimplifyLShrInst - Given operands for an LShr, see if we can
752/// fold the result. If not, this returns null.
753static Value *SimplifyLShrInst(Value *Op0, Value *Op1, const TargetData *TD,
754 const DominatorTree *DT, unsigned MaxRecurse) {
Duncan Sandscf80bc12011-01-14 14:44:12 +0000755 if (Value *V = SimplifyShift(Instruction::LShr, Op0, Op1, TD, DT, MaxRecurse))
756 return V;
Duncan Sandsc43cee32011-01-14 00:37:45 +0000757
758 // undef >>l X -> 0
759 if (isa<UndefValue>(Op0))
760 return Constant::getNullValue(Op0->getType());
761
Duncan Sandsc43cee32011-01-14 00:37:45 +0000762 return 0;
763}
764
765Value *llvm::SimplifyLShrInst(Value *Op0, Value *Op1, const TargetData *TD,
766 const DominatorTree *DT) {
767 return ::SimplifyLShrInst(Op0, Op1, TD, DT, RecursionLimit);
768}
769
770/// SimplifyAShrInst - Given operands for an AShr, see if we can
771/// fold the result. If not, this returns null.
772static Value *SimplifyAShrInst(Value *Op0, Value *Op1, const TargetData *TD,
773 const DominatorTree *DT, unsigned MaxRecurse) {
Duncan Sandscf80bc12011-01-14 14:44:12 +0000774 if (Value *V = SimplifyShift(Instruction::AShr, Op0, Op1, TD, DT, MaxRecurse))
775 return V;
Duncan Sandsc43cee32011-01-14 00:37:45 +0000776
777 // all ones >>a X -> all ones
778 if (match(Op0, m_AllOnes()))
779 return Op0;
780
781 // undef >>a X -> all ones
782 if (isa<UndefValue>(Op0))
783 return Constant::getAllOnesValue(Op0->getType());
784
Duncan Sandsc43cee32011-01-14 00:37:45 +0000785 return 0;
786}
787
788Value *llvm::SimplifyAShrInst(Value *Op0, Value *Op1, const TargetData *TD,
789 const DominatorTree *DT) {
790 return ::SimplifyAShrInst(Op0, Op1, TD, DT, RecursionLimit);
791}
792
Chris Lattnerd06094f2009-11-10 00:55:12 +0000793/// SimplifyAndInst - Given operands for an And, see if we can
Chris Lattner9f3c25a2009-11-09 22:57:59 +0000794/// fold the result. If not, this returns null.
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000795static Value *SimplifyAndInst(Value *Op0, Value *Op1, const TargetData *TD,
Duncan Sands18450092010-11-16 12:16:38 +0000796 const DominatorTree *DT, unsigned MaxRecurse) {
Chris Lattnerd06094f2009-11-10 00:55:12 +0000797 if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
798 if (Constant *CRHS = dyn_cast<Constant>(Op1)) {
799 Constant *Ops[] = { CLHS, CRHS };
800 return ConstantFoldInstOperands(Instruction::And, CLHS->getType(),
801 Ops, 2, TD);
802 }
Duncan Sands12a86f52010-11-14 11:23:23 +0000803
Chris Lattnerd06094f2009-11-10 00:55:12 +0000804 // Canonicalize the constant to the RHS.
805 std::swap(Op0, Op1);
806 }
Duncan Sands12a86f52010-11-14 11:23:23 +0000807
Chris Lattnerd06094f2009-11-10 00:55:12 +0000808 // X & undef -> 0
809 if (isa<UndefValue>(Op1))
810 return Constant::getNullValue(Op0->getType());
Duncan Sands12a86f52010-11-14 11:23:23 +0000811
Chris Lattnerd06094f2009-11-10 00:55:12 +0000812 // X & X = X
Duncan Sands124708d2011-01-01 20:08:02 +0000813 if (Op0 == Op1)
Chris Lattnerd06094f2009-11-10 00:55:12 +0000814 return Op0;
Duncan Sands12a86f52010-11-14 11:23:23 +0000815
Duncan Sands2b749872010-11-17 18:52:15 +0000816 // X & 0 = 0
817 if (match(Op1, m_Zero()))
Chris Lattnerd06094f2009-11-10 00:55:12 +0000818 return Op1;
Duncan Sands12a86f52010-11-14 11:23:23 +0000819
Duncan Sands2b749872010-11-17 18:52:15 +0000820 // X & -1 = X
821 if (match(Op1, m_AllOnes()))
822 return Op0;
Duncan Sands12a86f52010-11-14 11:23:23 +0000823
Chris Lattnerd06094f2009-11-10 00:55:12 +0000824 // A & ~A = ~A & A = 0
Chandler Carruthe89ada92010-11-29 01:41:13 +0000825 Value *A = 0, *B = 0;
Duncan Sands124708d2011-01-01 20:08:02 +0000826 if ((match(Op0, m_Not(m_Value(A))) && A == Op1) ||
827 (match(Op1, m_Not(m_Value(A))) && A == Op0))
Chris Lattnerd06094f2009-11-10 00:55:12 +0000828 return Constant::getNullValue(Op0->getType());
Duncan Sands12a86f52010-11-14 11:23:23 +0000829
Chris Lattnerd06094f2009-11-10 00:55:12 +0000830 // (A | ?) & A = A
831 if (match(Op0, m_Or(m_Value(A), m_Value(B))) &&
Duncan Sands124708d2011-01-01 20:08:02 +0000832 (A == Op1 || B == Op1))
Chris Lattnerd06094f2009-11-10 00:55:12 +0000833 return Op1;
Duncan Sands12a86f52010-11-14 11:23:23 +0000834
Chris Lattnerd06094f2009-11-10 00:55:12 +0000835 // A & (A | ?) = A
836 if (match(Op1, m_Or(m_Value(A), m_Value(B))) &&
Duncan Sands124708d2011-01-01 20:08:02 +0000837 (A == Op0 || B == Op0))
Chris Lattnerd06094f2009-11-10 00:55:12 +0000838 return Op0;
Duncan Sands12a86f52010-11-14 11:23:23 +0000839
Duncan Sands566edb02010-12-21 08:49:00 +0000840 // Try some generic simplifications for associative operations.
841 if (Value *V = SimplifyAssociativeBinOp(Instruction::And, Op0, Op1, TD, DT,
842 MaxRecurse))
843 return V;
Benjamin Kramer6844c8e2010-09-10 22:39:55 +0000844
Duncan Sands3421d902010-12-21 13:32:22 +0000845 // And distributes over Or. Try some generic simplifications based on this.
846 if (Value *V = ExpandBinOp(Instruction::And, Op0, Op1, Instruction::Or,
847 TD, DT, MaxRecurse))
848 return V;
849
850 // And distributes over Xor. Try some generic simplifications based on this.
851 if (Value *V = ExpandBinOp(Instruction::And, Op0, Op1, Instruction::Xor,
852 TD, DT, MaxRecurse))
853 return V;
854
855 // Or distributes over And. Try some generic simplifications based on this.
856 if (Value *V = FactorizeBinOp(Instruction::And, Op0, Op1, Instruction::Or,
857 TD, DT, MaxRecurse))
858 return V;
859
Duncan Sandsb2cbdc32010-11-10 13:00:08 +0000860 // If the operation is with the result of a select instruction, check whether
861 // operating on either branch of the select always yields the same value.
Duncan Sands0312a932010-12-21 09:09:15 +0000862 if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
Duncan Sands18450092010-11-16 12:16:38 +0000863 if (Value *V = ThreadBinOpOverSelect(Instruction::And, Op0, Op1, TD, DT,
Duncan Sands0312a932010-12-21 09:09:15 +0000864 MaxRecurse))
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000865 return V;
866
867 // If the operation is with the result of a phi instruction, check whether
868 // operating on all incoming values of the phi always yields the same value.
Duncan Sands0312a932010-12-21 09:09:15 +0000869 if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
Duncan Sands18450092010-11-16 12:16:38 +0000870 if (Value *V = ThreadBinOpOverPHI(Instruction::And, Op0, Op1, TD, DT,
Duncan Sands0312a932010-12-21 09:09:15 +0000871 MaxRecurse))
Duncan Sandsb2cbdc32010-11-10 13:00:08 +0000872 return V;
873
Chris Lattner9f3c25a2009-11-09 22:57:59 +0000874 return 0;
875}
876
Duncan Sands18450092010-11-16 12:16:38 +0000877Value *llvm::SimplifyAndInst(Value *Op0, Value *Op1, const TargetData *TD,
878 const DominatorTree *DT) {
879 return ::SimplifyAndInst(Op0, Op1, TD, DT, RecursionLimit);
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000880}
881
Chris Lattnerd06094f2009-11-10 00:55:12 +0000882/// SimplifyOrInst - Given operands for an Or, see if we can
883/// fold the result. If not, this returns null.
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000884static Value *SimplifyOrInst(Value *Op0, Value *Op1, const TargetData *TD,
Duncan Sands18450092010-11-16 12:16:38 +0000885 const DominatorTree *DT, unsigned MaxRecurse) {
Chris Lattnerd06094f2009-11-10 00:55:12 +0000886 if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
887 if (Constant *CRHS = dyn_cast<Constant>(Op1)) {
888 Constant *Ops[] = { CLHS, CRHS };
889 return ConstantFoldInstOperands(Instruction::Or, CLHS->getType(),
890 Ops, 2, TD);
891 }
Duncan Sands12a86f52010-11-14 11:23:23 +0000892
Chris Lattnerd06094f2009-11-10 00:55:12 +0000893 // Canonicalize the constant to the RHS.
894 std::swap(Op0, Op1);
895 }
Duncan Sands12a86f52010-11-14 11:23:23 +0000896
Chris Lattnerd06094f2009-11-10 00:55:12 +0000897 // X | undef -> -1
898 if (isa<UndefValue>(Op1))
899 return Constant::getAllOnesValue(Op0->getType());
Duncan Sands12a86f52010-11-14 11:23:23 +0000900
Chris Lattnerd06094f2009-11-10 00:55:12 +0000901 // X | X = X
Duncan Sands124708d2011-01-01 20:08:02 +0000902 if (Op0 == Op1)
Chris Lattnerd06094f2009-11-10 00:55:12 +0000903 return Op0;
904
Duncan Sands2b749872010-11-17 18:52:15 +0000905 // X | 0 = X
906 if (match(Op1, m_Zero()))
Chris Lattnerd06094f2009-11-10 00:55:12 +0000907 return Op0;
Duncan Sands12a86f52010-11-14 11:23:23 +0000908
Duncan Sands2b749872010-11-17 18:52:15 +0000909 // X | -1 = -1
910 if (match(Op1, m_AllOnes()))
911 return Op1;
Duncan Sands12a86f52010-11-14 11:23:23 +0000912
Chris Lattnerd06094f2009-11-10 00:55:12 +0000913 // A | ~A = ~A | A = -1
Chandler Carruthe89ada92010-11-29 01:41:13 +0000914 Value *A = 0, *B = 0;
Duncan Sands124708d2011-01-01 20:08:02 +0000915 if ((match(Op0, m_Not(m_Value(A))) && A == Op1) ||
916 (match(Op1, m_Not(m_Value(A))) && A == Op0))
Chris Lattnerd06094f2009-11-10 00:55:12 +0000917 return Constant::getAllOnesValue(Op0->getType());
Duncan Sands12a86f52010-11-14 11:23:23 +0000918
Chris Lattnerd06094f2009-11-10 00:55:12 +0000919 // (A & ?) | A = A
920 if (match(Op0, m_And(m_Value(A), m_Value(B))) &&
Duncan Sands124708d2011-01-01 20:08:02 +0000921 (A == Op1 || B == Op1))
Chris Lattnerd06094f2009-11-10 00:55:12 +0000922 return Op1;
Duncan Sands12a86f52010-11-14 11:23:23 +0000923
Chris Lattnerd06094f2009-11-10 00:55:12 +0000924 // A | (A & ?) = A
925 if (match(Op1, m_And(m_Value(A), m_Value(B))) &&
Duncan Sands124708d2011-01-01 20:08:02 +0000926 (A == Op0 || B == Op0))
Chris Lattnerd06094f2009-11-10 00:55:12 +0000927 return Op0;
Duncan Sands12a86f52010-11-14 11:23:23 +0000928
Duncan Sands566edb02010-12-21 08:49:00 +0000929 // Try some generic simplifications for associative operations.
930 if (Value *V = SimplifyAssociativeBinOp(Instruction::Or, Op0, Op1, TD, DT,
931 MaxRecurse))
932 return V;
Benjamin Kramer6844c8e2010-09-10 22:39:55 +0000933
Duncan Sands3421d902010-12-21 13:32:22 +0000934 // Or distributes over And. Try some generic simplifications based on this.
935 if (Value *V = ExpandBinOp(Instruction::Or, Op0, Op1, Instruction::And,
936 TD, DT, MaxRecurse))
937 return V;
938
939 // And distributes over Or. Try some generic simplifications based on this.
940 if (Value *V = FactorizeBinOp(Instruction::Or, Op0, Op1, Instruction::And,
941 TD, DT, MaxRecurse))
942 return V;
943
Duncan Sandsb2cbdc32010-11-10 13:00:08 +0000944 // If the operation is with the result of a select instruction, check whether
945 // operating on either branch of the select always yields the same value.
Duncan Sands0312a932010-12-21 09:09:15 +0000946 if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
Duncan Sands18450092010-11-16 12:16:38 +0000947 if (Value *V = ThreadBinOpOverSelect(Instruction::Or, Op0, Op1, TD, DT,
Duncan Sands0312a932010-12-21 09:09:15 +0000948 MaxRecurse))
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000949 return V;
950
951 // If the operation is with the result of a phi instruction, check whether
952 // operating on all incoming values of the phi always yields the same value.
Duncan Sands0312a932010-12-21 09:09:15 +0000953 if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
Duncan Sands18450092010-11-16 12:16:38 +0000954 if (Value *V = ThreadBinOpOverPHI(Instruction::Or, Op0, Op1, TD, DT,
Duncan Sands0312a932010-12-21 09:09:15 +0000955 MaxRecurse))
Duncan Sandsb2cbdc32010-11-10 13:00:08 +0000956 return V;
957
Chris Lattnerd06094f2009-11-10 00:55:12 +0000958 return 0;
959}
960
Duncan Sands18450092010-11-16 12:16:38 +0000961Value *llvm::SimplifyOrInst(Value *Op0, Value *Op1, const TargetData *TD,
962 const DominatorTree *DT) {
963 return ::SimplifyOrInst(Op0, Op1, TD, DT, RecursionLimit);
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000964}
Chris Lattnerd06094f2009-11-10 00:55:12 +0000965
Duncan Sands2b749872010-11-17 18:52:15 +0000966/// SimplifyXorInst - Given operands for a Xor, see if we can
967/// fold the result. If not, this returns null.
968static Value *SimplifyXorInst(Value *Op0, Value *Op1, const TargetData *TD,
969 const DominatorTree *DT, unsigned MaxRecurse) {
970 if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
971 if (Constant *CRHS = dyn_cast<Constant>(Op1)) {
972 Constant *Ops[] = { CLHS, CRHS };
973 return ConstantFoldInstOperands(Instruction::Xor, CLHS->getType(),
974 Ops, 2, TD);
975 }
976
977 // Canonicalize the constant to the RHS.
978 std::swap(Op0, Op1);
979 }
980
981 // A ^ undef -> undef
982 if (isa<UndefValue>(Op1))
Duncan Sandsf8b1a5e2010-12-15 11:02:22 +0000983 return Op1;
Duncan Sands2b749872010-11-17 18:52:15 +0000984
985 // A ^ 0 = A
986 if (match(Op1, m_Zero()))
987 return Op0;
988
989 // A ^ A = 0
Duncan Sands124708d2011-01-01 20:08:02 +0000990 if (Op0 == Op1)
Duncan Sands2b749872010-11-17 18:52:15 +0000991 return Constant::getNullValue(Op0->getType());
992
993 // A ^ ~A = ~A ^ A = -1
Duncan Sands566edb02010-12-21 08:49:00 +0000994 Value *A = 0;
Duncan Sands124708d2011-01-01 20:08:02 +0000995 if ((match(Op0, m_Not(m_Value(A))) && A == Op1) ||
996 (match(Op1, m_Not(m_Value(A))) && A == Op0))
Duncan Sands2b749872010-11-17 18:52:15 +0000997 return Constant::getAllOnesValue(Op0->getType());
998
Duncan Sands566edb02010-12-21 08:49:00 +0000999 // Try some generic simplifications for associative operations.
1000 if (Value *V = SimplifyAssociativeBinOp(Instruction::Xor, Op0, Op1, TD, DT,
1001 MaxRecurse))
1002 return V;
Duncan Sands2b749872010-11-17 18:52:15 +00001003
Duncan Sands3421d902010-12-21 13:32:22 +00001004 // And distributes over Xor. Try some generic simplifications based on this.
1005 if (Value *V = FactorizeBinOp(Instruction::Xor, Op0, Op1, Instruction::And,
1006 TD, DT, MaxRecurse))
1007 return V;
1008
Duncan Sands87689cf2010-11-19 09:20:39 +00001009 // Threading Xor over selects and phi nodes is pointless, so don't bother.
1010 // Threading over the select in "A ^ select(cond, B, C)" means evaluating
1011 // "A^B" and "A^C" and seeing if they are equal; but they are equal if and
1012 // only if B and C are equal. If B and C are equal then (since we assume
1013 // that operands have already been simplified) "select(cond, B, C)" should
1014 // have been simplified to the common value of B and C already. Analysing
1015 // "A^B" and "A^C" thus gains nothing, but costs compile time. Similarly
1016 // for threading over phi nodes.
Duncan Sands2b749872010-11-17 18:52:15 +00001017
1018 return 0;
1019}
1020
1021Value *llvm::SimplifyXorInst(Value *Op0, Value *Op1, const TargetData *TD,
1022 const DominatorTree *DT) {
1023 return ::SimplifyXorInst(Op0, Op1, TD, DT, RecursionLimit);
1024}
1025
Chris Lattner210c5d42009-11-09 23:55:12 +00001026static const Type *GetCompareTy(Value *Op) {
1027 return CmpInst::makeCmpResultType(Op->getType());
1028}
1029
Chris Lattner9dbb4292009-11-09 23:28:39 +00001030/// SimplifyICmpInst - Given operands for an ICmpInst, see if we can
1031/// fold the result. If not, this returns null.
Duncan Sandsa74a58c2010-11-10 18:23:01 +00001032static Value *SimplifyICmpInst(unsigned Predicate, Value *LHS, Value *RHS,
Duncan Sands18450092010-11-16 12:16:38 +00001033 const TargetData *TD, const DominatorTree *DT,
1034 unsigned MaxRecurse) {
Chris Lattner9f3c25a2009-11-09 22:57:59 +00001035 CmpInst::Predicate Pred = (CmpInst::Predicate)Predicate;
Chris Lattner9dbb4292009-11-09 23:28:39 +00001036 assert(CmpInst::isIntPredicate(Pred) && "Not an integer compare!");
Duncan Sands12a86f52010-11-14 11:23:23 +00001037
Chris Lattnerd06094f2009-11-10 00:55:12 +00001038 if (Constant *CLHS = dyn_cast<Constant>(LHS)) {
Chris Lattner8f73dea2009-11-09 23:06:58 +00001039 if (Constant *CRHS = dyn_cast<Constant>(RHS))
1040 return ConstantFoldCompareInstOperands(Pred, CLHS, CRHS, TD);
Chris Lattnerd06094f2009-11-10 00:55:12 +00001041
1042 // If we have a constant, make sure it is on the RHS.
1043 std::swap(LHS, RHS);
1044 Pred = CmpInst::getSwappedPredicate(Pred);
1045 }
Duncan Sands12a86f52010-11-14 11:23:23 +00001046
Duncan Sands6dc91252011-01-13 08:56:29 +00001047 const Type *ITy = GetCompareTy(LHS); // The return type.
1048 const Type *OpTy = LHS->getType(); // The operand type.
Duncan Sands12a86f52010-11-14 11:23:23 +00001049
Chris Lattner210c5d42009-11-09 23:55:12 +00001050 // icmp X, X -> true/false
Chris Lattnerc8e14b32010-03-03 19:46:03 +00001051 // X icmp undef -> true/false. For example, icmp ugt %X, undef -> false
1052 // because X could be 0.
Duncan Sands124708d2011-01-01 20:08:02 +00001053 if (LHS == RHS || isa<UndefValue>(RHS))
Chris Lattner210c5d42009-11-09 23:55:12 +00001054 return ConstantInt::get(ITy, CmpInst::isTrueWhenEqual(Pred));
Duncan Sands12a86f52010-11-14 11:23:23 +00001055
Duncan Sands6dc91252011-01-13 08:56:29 +00001056 // Special case logic when the operands have i1 type.
1057 if (OpTy->isIntegerTy(1) || (OpTy->isVectorTy() &&
1058 cast<VectorType>(OpTy)->getElementType()->isIntegerTy(1))) {
1059 switch (Pred) {
1060 default: break;
1061 case ICmpInst::ICMP_EQ:
1062 // X == 1 -> X
1063 if (match(RHS, m_One()))
1064 return LHS;
1065 break;
1066 case ICmpInst::ICMP_NE:
1067 // X != 0 -> X
1068 if (match(RHS, m_Zero()))
1069 return LHS;
1070 break;
1071 case ICmpInst::ICMP_UGT:
1072 // X >u 0 -> X
1073 if (match(RHS, m_Zero()))
1074 return LHS;
1075 break;
1076 case ICmpInst::ICMP_UGE:
1077 // X >=u 1 -> X
1078 if (match(RHS, m_One()))
1079 return LHS;
1080 break;
1081 case ICmpInst::ICMP_SLT:
1082 // X <s 0 -> X
1083 if (match(RHS, m_Zero()))
1084 return LHS;
1085 break;
1086 case ICmpInst::ICMP_SLE:
1087 // X <=s -1 -> X
1088 if (match(RHS, m_One()))
1089 return LHS;
1090 break;
1091 }
1092 }
1093
1094 // See if we are doing a comparison with a constant.
1095 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHS)) {
1096 switch (Pred) {
1097 default: break;
1098 case ICmpInst::ICMP_UGT:
1099 if (CI->isMaxValue(false)) // A >u MAX -> FALSE
1100 return ConstantInt::getFalse(CI->getContext());
1101 break;
1102 case ICmpInst::ICMP_UGE:
1103 if (CI->isMinValue(false)) // A >=u MIN -> TRUE
1104 return ConstantInt::getTrue(CI->getContext());
1105 break;
1106 case ICmpInst::ICMP_ULT:
1107 if (CI->isMinValue(false)) // A <u MIN -> FALSE
1108 return ConstantInt::getFalse(CI->getContext());
1109 break;
1110 case ICmpInst::ICMP_ULE:
1111 if (CI->isMaxValue(false)) // A <=u MAX -> TRUE
1112 return ConstantInt::getTrue(CI->getContext());
1113 break;
1114 case ICmpInst::ICMP_SGT:
1115 if (CI->isMaxValue(true)) // A >s MAX -> FALSE
1116 return ConstantInt::getFalse(CI->getContext());
1117 break;
1118 case ICmpInst::ICMP_SGE:
1119 if (CI->isMinValue(true)) // A >=s MIN -> TRUE
1120 return ConstantInt::getTrue(CI->getContext());
1121 break;
1122 case ICmpInst::ICMP_SLT:
1123 if (CI->isMinValue(true)) // A <s MIN -> FALSE
1124 return ConstantInt::getFalse(CI->getContext());
1125 break;
1126 case ICmpInst::ICMP_SLE:
1127 if (CI->isMaxValue(true)) // A <=s MAX -> TRUE
1128 return ConstantInt::getTrue(CI->getContext());
1129 break;
1130 }
1131 }
1132
Duncan Sands53ad8612011-01-13 10:43:08 +00001133 // icmp <alloca*>, <global/alloca*/null> - Different stack variables have
1134 // different addresses, and what's more the address of a stack variable is
1135 // never null or equal to the address of a global. Note that generalizing
1136 // to the case where LHS is a global variable address or null is pointless,
1137 // since if both LHS and RHS are constants then we already constant folded
1138 // the compare, and if only one of them is then we moved it to RHS already.
1139 if (isa<AllocaInst>(LHS) && (isa<GlobalValue>(RHS) || isa<AllocaInst>(RHS) ||
1140 isa<ConstantPointerNull>(RHS)))
1141 // We already know that LHS != LHS.
Chris Lattner210c5d42009-11-09 23:55:12 +00001142 return ConstantInt::get(ITy, CmpInst::isFalseWhenEqual(Pred));
Duncan Sands12a86f52010-11-14 11:23:23 +00001143
Duncan Sands1ac7c992010-11-07 16:12:23 +00001144 // If the comparison is with the result of a select instruction, check whether
1145 // comparing with either branch of the select always yields the same value.
Duncan Sands0312a932010-12-21 09:09:15 +00001146 if (isa<SelectInst>(LHS) || isa<SelectInst>(RHS))
1147 if (Value *V = ThreadCmpOverSelect(Pred, LHS, RHS, TD, DT, MaxRecurse))
Duncan Sandsa74a58c2010-11-10 18:23:01 +00001148 return V;
1149
1150 // If the comparison is with the result of a phi instruction, check whether
1151 // doing the compare with each incoming phi value yields a common result.
Duncan Sands0312a932010-12-21 09:09:15 +00001152 if (isa<PHINode>(LHS) || isa<PHINode>(RHS))
1153 if (Value *V = ThreadCmpOverPHI(Pred, LHS, RHS, TD, DT, MaxRecurse))
Duncan Sands3bbb0cc2010-11-09 17:25:51 +00001154 return V;
Duncan Sands1ac7c992010-11-07 16:12:23 +00001155
Chris Lattner9f3c25a2009-11-09 22:57:59 +00001156 return 0;
1157}
1158
Duncan Sandsa74a58c2010-11-10 18:23:01 +00001159Value *llvm::SimplifyICmpInst(unsigned Predicate, Value *LHS, Value *RHS,
Duncan Sands18450092010-11-16 12:16:38 +00001160 const TargetData *TD, const DominatorTree *DT) {
1161 return ::SimplifyICmpInst(Predicate, LHS, RHS, TD, DT, RecursionLimit);
Duncan Sandsa74a58c2010-11-10 18:23:01 +00001162}
1163
Chris Lattner9dbb4292009-11-09 23:28:39 +00001164/// SimplifyFCmpInst - Given operands for an FCmpInst, see if we can
1165/// fold the result. If not, this returns null.
Duncan Sandsa74a58c2010-11-10 18:23:01 +00001166static Value *SimplifyFCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
Duncan Sands18450092010-11-16 12:16:38 +00001167 const TargetData *TD, const DominatorTree *DT,
1168 unsigned MaxRecurse) {
Chris Lattner9dbb4292009-11-09 23:28:39 +00001169 CmpInst::Predicate Pred = (CmpInst::Predicate)Predicate;
1170 assert(CmpInst::isFPPredicate(Pred) && "Not an FP compare!");
1171
Chris Lattnerd06094f2009-11-10 00:55:12 +00001172 if (Constant *CLHS = dyn_cast<Constant>(LHS)) {
Chris Lattner9dbb4292009-11-09 23:28:39 +00001173 if (Constant *CRHS = dyn_cast<Constant>(RHS))
1174 return ConstantFoldCompareInstOperands(Pred, CLHS, CRHS, TD);
Duncan Sands12a86f52010-11-14 11:23:23 +00001175
Chris Lattnerd06094f2009-11-10 00:55:12 +00001176 // If we have a constant, make sure it is on the RHS.
1177 std::swap(LHS, RHS);
1178 Pred = CmpInst::getSwappedPredicate(Pred);
1179 }
Duncan Sands12a86f52010-11-14 11:23:23 +00001180
Chris Lattner210c5d42009-11-09 23:55:12 +00001181 // Fold trivial predicates.
1182 if (Pred == FCmpInst::FCMP_FALSE)
1183 return ConstantInt::get(GetCompareTy(LHS), 0);
1184 if (Pred == FCmpInst::FCMP_TRUE)
1185 return ConstantInt::get(GetCompareTy(LHS), 1);
1186
Chris Lattner210c5d42009-11-09 23:55:12 +00001187 if (isa<UndefValue>(RHS)) // fcmp pred X, undef -> undef
1188 return UndefValue::get(GetCompareTy(LHS));
1189
1190 // fcmp x,x -> true/false. Not all compares are foldable.
Duncan Sands124708d2011-01-01 20:08:02 +00001191 if (LHS == RHS) {
Chris Lattner210c5d42009-11-09 23:55:12 +00001192 if (CmpInst::isTrueWhenEqual(Pred))
1193 return ConstantInt::get(GetCompareTy(LHS), 1);
1194 if (CmpInst::isFalseWhenEqual(Pred))
1195 return ConstantInt::get(GetCompareTy(LHS), 0);
1196 }
Duncan Sands12a86f52010-11-14 11:23:23 +00001197
Chris Lattner210c5d42009-11-09 23:55:12 +00001198 // Handle fcmp with constant RHS
1199 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
1200 // If the constant is a nan, see if we can fold the comparison based on it.
1201 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
1202 if (CFP->getValueAPF().isNaN()) {
1203 if (FCmpInst::isOrdered(Pred)) // True "if ordered and foo"
1204 return ConstantInt::getFalse(CFP->getContext());
1205 assert(FCmpInst::isUnordered(Pred) &&
1206 "Comparison must be either ordered or unordered!");
1207 // True if unordered.
1208 return ConstantInt::getTrue(CFP->getContext());
1209 }
Dan Gohman6b617a72010-02-22 04:06:03 +00001210 // Check whether the constant is an infinity.
1211 if (CFP->getValueAPF().isInfinity()) {
1212 if (CFP->getValueAPF().isNegative()) {
1213 switch (Pred) {
1214 case FCmpInst::FCMP_OLT:
1215 // No value is ordered and less than negative infinity.
1216 return ConstantInt::getFalse(CFP->getContext());
1217 case FCmpInst::FCMP_UGE:
1218 // All values are unordered with or at least negative infinity.
1219 return ConstantInt::getTrue(CFP->getContext());
1220 default:
1221 break;
1222 }
1223 } else {
1224 switch (Pred) {
1225 case FCmpInst::FCMP_OGT:
1226 // No value is ordered and greater than infinity.
1227 return ConstantInt::getFalse(CFP->getContext());
1228 case FCmpInst::FCMP_ULE:
1229 // All values are unordered with and at most infinity.
1230 return ConstantInt::getTrue(CFP->getContext());
1231 default:
1232 break;
1233 }
1234 }
1235 }
Chris Lattner210c5d42009-11-09 23:55:12 +00001236 }
1237 }
Duncan Sands12a86f52010-11-14 11:23:23 +00001238
Duncan Sands92826de2010-11-07 16:46:25 +00001239 // If the comparison is with the result of a select instruction, check whether
1240 // comparing with either branch of the select always yields the same value.
Duncan Sands0312a932010-12-21 09:09:15 +00001241 if (isa<SelectInst>(LHS) || isa<SelectInst>(RHS))
1242 if (Value *V = ThreadCmpOverSelect(Pred, LHS, RHS, TD, DT, MaxRecurse))
Duncan Sandsa74a58c2010-11-10 18:23:01 +00001243 return V;
1244
1245 // If the comparison is with the result of a phi instruction, check whether
1246 // doing the compare with each incoming phi value yields a common result.
Duncan Sands0312a932010-12-21 09:09:15 +00001247 if (isa<PHINode>(LHS) || isa<PHINode>(RHS))
1248 if (Value *V = ThreadCmpOverPHI(Pred, LHS, RHS, TD, DT, MaxRecurse))
Duncan Sands3bbb0cc2010-11-09 17:25:51 +00001249 return V;
Duncan Sands92826de2010-11-07 16:46:25 +00001250
Chris Lattner9dbb4292009-11-09 23:28:39 +00001251 return 0;
1252}
1253
Duncan Sandsa74a58c2010-11-10 18:23:01 +00001254Value *llvm::SimplifyFCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
Duncan Sands18450092010-11-16 12:16:38 +00001255 const TargetData *TD, const DominatorTree *DT) {
1256 return ::SimplifyFCmpInst(Predicate, LHS, RHS, TD, DT, RecursionLimit);
Duncan Sandsa74a58c2010-11-10 18:23:01 +00001257}
1258
Chris Lattner04754262010-04-20 05:32:14 +00001259/// SimplifySelectInst - Given operands for a SelectInst, see if we can fold
1260/// the result. If not, this returns null.
Duncan Sands124708d2011-01-01 20:08:02 +00001261Value *llvm::SimplifySelectInst(Value *CondVal, Value *TrueVal, Value *FalseVal,
1262 const TargetData *TD, const DominatorTree *) {
Chris Lattner04754262010-04-20 05:32:14 +00001263 // select true, X, Y -> X
1264 // select false, X, Y -> Y
1265 if (ConstantInt *CB = dyn_cast<ConstantInt>(CondVal))
1266 return CB->getZExtValue() ? TrueVal : FalseVal;
Duncan Sands12a86f52010-11-14 11:23:23 +00001267
Chris Lattner04754262010-04-20 05:32:14 +00001268 // select C, X, X -> X
Duncan Sands124708d2011-01-01 20:08:02 +00001269 if (TrueVal == FalseVal)
Chris Lattner04754262010-04-20 05:32:14 +00001270 return TrueVal;
Duncan Sands12a86f52010-11-14 11:23:23 +00001271
Chris Lattner04754262010-04-20 05:32:14 +00001272 if (isa<UndefValue>(TrueVal)) // select C, undef, X -> X
1273 return FalseVal;
1274 if (isa<UndefValue>(FalseVal)) // select C, X, undef -> X
1275 return TrueVal;
1276 if (isa<UndefValue>(CondVal)) { // select undef, X, Y -> X or Y
1277 if (isa<Constant>(TrueVal))
1278 return TrueVal;
1279 return FalseVal;
1280 }
Duncan Sands12a86f52010-11-14 11:23:23 +00001281
Chris Lattner04754262010-04-20 05:32:14 +00001282 return 0;
1283}
1284
Chris Lattnerc514c1f2009-11-27 00:29:05 +00001285/// SimplifyGEPInst - Given operands for an GetElementPtrInst, see if we can
1286/// fold the result. If not, this returns null.
1287Value *llvm::SimplifyGEPInst(Value *const *Ops, unsigned NumOps,
Duncan Sands18450092010-11-16 12:16:38 +00001288 const TargetData *TD, const DominatorTree *) {
Duncan Sands85bbff62010-11-22 13:42:49 +00001289 // The type of the GEP pointer operand.
1290 const PointerType *PtrTy = cast<PointerType>(Ops[0]->getType());
1291
Chris Lattnerc514c1f2009-11-27 00:29:05 +00001292 // getelementptr P -> P.
1293 if (NumOps == 1)
1294 return Ops[0];
1295
Duncan Sands85bbff62010-11-22 13:42:49 +00001296 if (isa<UndefValue>(Ops[0])) {
1297 // Compute the (pointer) type returned by the GEP instruction.
1298 const Type *LastType = GetElementPtrInst::getIndexedType(PtrTy, &Ops[1],
1299 NumOps-1);
1300 const Type *GEPTy = PointerType::get(LastType, PtrTy->getAddressSpace());
1301 return UndefValue::get(GEPTy);
1302 }
Chris Lattnerc514c1f2009-11-27 00:29:05 +00001303
Duncan Sandse60d79f2010-11-21 13:53:09 +00001304 if (NumOps == 2) {
1305 // getelementptr P, 0 -> P.
Chris Lattnerc514c1f2009-11-27 00:29:05 +00001306 if (ConstantInt *C = dyn_cast<ConstantInt>(Ops[1]))
1307 if (C->isZero())
1308 return Ops[0];
Duncan Sandse60d79f2010-11-21 13:53:09 +00001309 // getelementptr P, N -> P if P points to a type of zero size.
1310 if (TD) {
Duncan Sands85bbff62010-11-22 13:42:49 +00001311 const Type *Ty = PtrTy->getElementType();
Duncan Sandsa63395a2010-11-22 16:32:50 +00001312 if (Ty->isSized() && TD->getTypeAllocSize(Ty) == 0)
Duncan Sandse60d79f2010-11-21 13:53:09 +00001313 return Ops[0];
1314 }
1315 }
Duncan Sands12a86f52010-11-14 11:23:23 +00001316
Chris Lattnerc514c1f2009-11-27 00:29:05 +00001317 // Check to see if this is constant foldable.
1318 for (unsigned i = 0; i != NumOps; ++i)
1319 if (!isa<Constant>(Ops[i]))
1320 return 0;
Duncan Sands12a86f52010-11-14 11:23:23 +00001321
Chris Lattnerc514c1f2009-11-27 00:29:05 +00001322 return ConstantExpr::getGetElementPtr(cast<Constant>(Ops[0]),
1323 (Constant *const*)Ops+1, NumOps-1);
1324}
1325
Duncan Sandsff103412010-11-17 04:30:22 +00001326/// SimplifyPHINode - See if we can fold the given phi. If not, returns null.
1327static Value *SimplifyPHINode(PHINode *PN, const DominatorTree *DT) {
1328 // If all of the PHI's incoming values are the same then replace the PHI node
1329 // with the common value.
1330 Value *CommonValue = 0;
1331 bool HasUndefInput = false;
1332 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
1333 Value *Incoming = PN->getIncomingValue(i);
1334 // If the incoming value is the phi node itself, it can safely be skipped.
1335 if (Incoming == PN) continue;
1336 if (isa<UndefValue>(Incoming)) {
1337 // Remember that we saw an undef value, but otherwise ignore them.
1338 HasUndefInput = true;
1339 continue;
1340 }
1341 if (CommonValue && Incoming != CommonValue)
1342 return 0; // Not the same, bail out.
1343 CommonValue = Incoming;
1344 }
1345
1346 // If CommonValue is null then all of the incoming values were either undef or
1347 // equal to the phi node itself.
1348 if (!CommonValue)
1349 return UndefValue::get(PN->getType());
1350
1351 // If we have a PHI node like phi(X, undef, X), where X is defined by some
1352 // instruction, we cannot return X as the result of the PHI node unless it
1353 // dominates the PHI block.
1354 if (HasUndefInput)
1355 return ValueDominatesPHI(CommonValue, PN, DT) ? CommonValue : 0;
1356
1357 return CommonValue;
1358}
1359
Chris Lattnerc514c1f2009-11-27 00:29:05 +00001360
Chris Lattnerd06094f2009-11-10 00:55:12 +00001361//=== Helper functions for higher up the class hierarchy.
Chris Lattner9dbb4292009-11-09 23:28:39 +00001362
Chris Lattnerd06094f2009-11-10 00:55:12 +00001363/// SimplifyBinOp - Given operands for a BinaryOperator, see if we can
1364/// fold the result. If not, this returns null.
Duncan Sandsa74a58c2010-11-10 18:23:01 +00001365static Value *SimplifyBinOp(unsigned Opcode, Value *LHS, Value *RHS,
Duncan Sands18450092010-11-16 12:16:38 +00001366 const TargetData *TD, const DominatorTree *DT,
1367 unsigned MaxRecurse) {
Chris Lattnerd06094f2009-11-10 00:55:12 +00001368 switch (Opcode) {
Duncan Sandsee9a2e32010-12-20 14:47:04 +00001369 case Instruction::Add: return SimplifyAddInst(LHS, RHS, /* isNSW */ false,
1370 /* isNUW */ false, TD, DT,
1371 MaxRecurse);
1372 case Instruction::Sub: return SimplifySubInst(LHS, RHS, /* isNSW */ false,
1373 /* isNUW */ false, TD, DT,
1374 MaxRecurse);
Duncan Sands82fdab32010-12-21 14:00:22 +00001375 case Instruction::Mul: return SimplifyMulInst(LHS, RHS, TD, DT, MaxRecurse);
Duncan Sandsc43cee32011-01-14 00:37:45 +00001376 case Instruction::Shl: return SimplifyShlInst(LHS, RHS, TD, DT, MaxRecurse);
1377 case Instruction::LShr: return SimplifyLShrInst(LHS, RHS, TD, DT, MaxRecurse);
1378 case Instruction::AShr: return SimplifyAShrInst(LHS, RHS, TD, DT, MaxRecurse);
Duncan Sands82fdab32010-12-21 14:00:22 +00001379 case Instruction::And: return SimplifyAndInst(LHS, RHS, TD, DT, MaxRecurse);
1380 case Instruction::Or: return SimplifyOrInst(LHS, RHS, TD, DT, MaxRecurse);
1381 case Instruction::Xor: return SimplifyXorInst(LHS, RHS, TD, DT, MaxRecurse);
Chris Lattnerd06094f2009-11-10 00:55:12 +00001382 default:
1383 if (Constant *CLHS = dyn_cast<Constant>(LHS))
1384 if (Constant *CRHS = dyn_cast<Constant>(RHS)) {
1385 Constant *COps[] = {CLHS, CRHS};
1386 return ConstantFoldInstOperands(Opcode, LHS->getType(), COps, 2, TD);
1387 }
Duncan Sandsb2cbdc32010-11-10 13:00:08 +00001388
Duncan Sands566edb02010-12-21 08:49:00 +00001389 // If the operation is associative, try some generic simplifications.
1390 if (Instruction::isAssociative(Opcode))
1391 if (Value *V = SimplifyAssociativeBinOp(Opcode, LHS, RHS, TD, DT,
1392 MaxRecurse))
1393 return V;
1394
Duncan Sandsb2cbdc32010-11-10 13:00:08 +00001395 // If the operation is with the result of a select instruction, check whether
1396 // operating on either branch of the select always yields the same value.
Duncan Sands0312a932010-12-21 09:09:15 +00001397 if (isa<SelectInst>(LHS) || isa<SelectInst>(RHS))
Duncan Sands18450092010-11-16 12:16:38 +00001398 if (Value *V = ThreadBinOpOverSelect(Opcode, LHS, RHS, TD, DT,
Duncan Sands0312a932010-12-21 09:09:15 +00001399 MaxRecurse))
Duncan Sandsa74a58c2010-11-10 18:23:01 +00001400 return V;
1401
1402 // If the operation is with the result of a phi instruction, check whether
1403 // operating on all incoming values of the phi always yields the same value.
Duncan Sands0312a932010-12-21 09:09:15 +00001404 if (isa<PHINode>(LHS) || isa<PHINode>(RHS))
1405 if (Value *V = ThreadBinOpOverPHI(Opcode, LHS, RHS, TD, DT, MaxRecurse))
Duncan Sandsb2cbdc32010-11-10 13:00:08 +00001406 return V;
1407
Chris Lattnerd06094f2009-11-10 00:55:12 +00001408 return 0;
1409 }
1410}
Chris Lattner9dbb4292009-11-09 23:28:39 +00001411
Duncan Sands12a86f52010-11-14 11:23:23 +00001412Value *llvm::SimplifyBinOp(unsigned Opcode, Value *LHS, Value *RHS,
Duncan Sands18450092010-11-16 12:16:38 +00001413 const TargetData *TD, const DominatorTree *DT) {
1414 return ::SimplifyBinOp(Opcode, LHS, RHS, TD, DT, RecursionLimit);
Chris Lattner9dbb4292009-11-09 23:28:39 +00001415}
1416
Duncan Sandsa74a58c2010-11-10 18:23:01 +00001417/// SimplifyCmpInst - Given operands for a CmpInst, see if we can
1418/// fold the result.
1419static Value *SimplifyCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
Duncan Sands18450092010-11-16 12:16:38 +00001420 const TargetData *TD, const DominatorTree *DT,
1421 unsigned MaxRecurse) {
Duncan Sandsa74a58c2010-11-10 18:23:01 +00001422 if (CmpInst::isIntPredicate((CmpInst::Predicate)Predicate))
Duncan Sands18450092010-11-16 12:16:38 +00001423 return SimplifyICmpInst(Predicate, LHS, RHS, TD, DT, MaxRecurse);
1424 return SimplifyFCmpInst(Predicate, LHS, RHS, TD, DT, MaxRecurse);
Duncan Sandsa74a58c2010-11-10 18:23:01 +00001425}
1426
1427Value *llvm::SimplifyCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
Duncan Sands18450092010-11-16 12:16:38 +00001428 const TargetData *TD, const DominatorTree *DT) {
1429 return ::SimplifyCmpInst(Predicate, LHS, RHS, TD, DT, RecursionLimit);
Duncan Sandsa74a58c2010-11-10 18:23:01 +00001430}
Chris Lattnere3453782009-11-10 01:08:51 +00001431
1432/// SimplifyInstruction - See if we can compute a simplified version of this
1433/// instruction. If not, this returns null.
Duncan Sandseff05812010-11-14 18:36:10 +00001434Value *llvm::SimplifyInstruction(Instruction *I, const TargetData *TD,
1435 const DominatorTree *DT) {
Duncan Sandsd261dc62010-11-17 08:35:29 +00001436 Value *Result;
1437
Chris Lattnere3453782009-11-10 01:08:51 +00001438 switch (I->getOpcode()) {
1439 default:
Duncan Sandsd261dc62010-11-17 08:35:29 +00001440 Result = ConstantFoldInstruction(I, TD);
1441 break;
Chris Lattner8aee8ef2009-11-27 17:42:22 +00001442 case Instruction::Add:
Duncan Sandsd261dc62010-11-17 08:35:29 +00001443 Result = SimplifyAddInst(I->getOperand(0), I->getOperand(1),
1444 cast<BinaryOperator>(I)->hasNoSignedWrap(),
1445 cast<BinaryOperator>(I)->hasNoUnsignedWrap(),
1446 TD, DT);
1447 break;
Duncan Sandsfea3b212010-12-15 14:07:39 +00001448 case Instruction::Sub:
1449 Result = SimplifySubInst(I->getOperand(0), I->getOperand(1),
1450 cast<BinaryOperator>(I)->hasNoSignedWrap(),
1451 cast<BinaryOperator>(I)->hasNoUnsignedWrap(),
1452 TD, DT);
1453 break;
Duncan Sands82fdab32010-12-21 14:00:22 +00001454 case Instruction::Mul:
1455 Result = SimplifyMulInst(I->getOperand(0), I->getOperand(1), TD, DT);
1456 break;
Duncan Sandsc43cee32011-01-14 00:37:45 +00001457 case Instruction::Shl:
1458 Result = SimplifyShlInst(I->getOperand(0), I->getOperand(1), TD, DT);
1459 break;
1460 case Instruction::LShr:
1461 Result = SimplifyLShrInst(I->getOperand(0), I->getOperand(1), TD, DT);
1462 break;
1463 case Instruction::AShr:
1464 Result = SimplifyAShrInst(I->getOperand(0), I->getOperand(1), TD, DT);
1465 break;
Chris Lattnere3453782009-11-10 01:08:51 +00001466 case Instruction::And:
Duncan Sandsd261dc62010-11-17 08:35:29 +00001467 Result = SimplifyAndInst(I->getOperand(0), I->getOperand(1), TD, DT);
1468 break;
Chris Lattnere3453782009-11-10 01:08:51 +00001469 case Instruction::Or:
Duncan Sandsd261dc62010-11-17 08:35:29 +00001470 Result = SimplifyOrInst(I->getOperand(0), I->getOperand(1), TD, DT);
1471 break;
Duncan Sands2b749872010-11-17 18:52:15 +00001472 case Instruction::Xor:
1473 Result = SimplifyXorInst(I->getOperand(0), I->getOperand(1), TD, DT);
1474 break;
Chris Lattnere3453782009-11-10 01:08:51 +00001475 case Instruction::ICmp:
Duncan Sandsd261dc62010-11-17 08:35:29 +00001476 Result = SimplifyICmpInst(cast<ICmpInst>(I)->getPredicate(),
1477 I->getOperand(0), I->getOperand(1), TD, DT);
1478 break;
Chris Lattnere3453782009-11-10 01:08:51 +00001479 case Instruction::FCmp:
Duncan Sandsd261dc62010-11-17 08:35:29 +00001480 Result = SimplifyFCmpInst(cast<FCmpInst>(I)->getPredicate(),
1481 I->getOperand(0), I->getOperand(1), TD, DT);
1482 break;
Chris Lattner04754262010-04-20 05:32:14 +00001483 case Instruction::Select:
Duncan Sandsd261dc62010-11-17 08:35:29 +00001484 Result = SimplifySelectInst(I->getOperand(0), I->getOperand(1),
1485 I->getOperand(2), TD, DT);
1486 break;
Chris Lattnerc514c1f2009-11-27 00:29:05 +00001487 case Instruction::GetElementPtr: {
1488 SmallVector<Value*, 8> Ops(I->op_begin(), I->op_end());
Duncan Sandsd261dc62010-11-17 08:35:29 +00001489 Result = SimplifyGEPInst(&Ops[0], Ops.size(), TD, DT);
1490 break;
Chris Lattnerc514c1f2009-11-27 00:29:05 +00001491 }
Duncan Sandscd6636c2010-11-14 13:30:18 +00001492 case Instruction::PHI:
Duncan Sandsd261dc62010-11-17 08:35:29 +00001493 Result = SimplifyPHINode(cast<PHINode>(I), DT);
1494 break;
Chris Lattnere3453782009-11-10 01:08:51 +00001495 }
Duncan Sandsd261dc62010-11-17 08:35:29 +00001496
1497 /// If called on unreachable code, the above logic may report that the
1498 /// instruction simplified to itself. Make life easier for users by
Duncan Sandsf8b1a5e2010-12-15 11:02:22 +00001499 /// detecting that case here, returning a safe value instead.
1500 return Result == I ? UndefValue::get(I->getType()) : Result;
Chris Lattnere3453782009-11-10 01:08:51 +00001501}
1502
Chris Lattner40d8c282009-11-10 22:26:15 +00001503/// ReplaceAndSimplifyAllUses - Perform From->replaceAllUsesWith(To) and then
1504/// delete the From instruction. In addition to a basic RAUW, this does a
1505/// recursive simplification of the newly formed instructions. This catches
1506/// things where one simplification exposes other opportunities. This only
1507/// simplifies and deletes scalar operations, it does not change the CFG.
1508///
1509void llvm::ReplaceAndSimplifyAllUses(Instruction *From, Value *To,
Duncan Sandseff05812010-11-14 18:36:10 +00001510 const TargetData *TD,
1511 const DominatorTree *DT) {
Chris Lattner40d8c282009-11-10 22:26:15 +00001512 assert(From != To && "ReplaceAndSimplifyAllUses(X,X) is not valid!");
Duncan Sands12a86f52010-11-14 11:23:23 +00001513
Chris Lattnerd2bfe542010-07-15 06:36:08 +00001514 // FromHandle/ToHandle - This keeps a WeakVH on the from/to values so that
1515 // we can know if it gets deleted out from under us or replaced in a
1516 // recursive simplification.
Chris Lattner40d8c282009-11-10 22:26:15 +00001517 WeakVH FromHandle(From);
Chris Lattnerd2bfe542010-07-15 06:36:08 +00001518 WeakVH ToHandle(To);
Duncan Sands12a86f52010-11-14 11:23:23 +00001519
Chris Lattner40d8c282009-11-10 22:26:15 +00001520 while (!From->use_empty()) {
1521 // Update the instruction to use the new value.
Chris Lattnerd2bfe542010-07-15 06:36:08 +00001522 Use &TheUse = From->use_begin().getUse();
1523 Instruction *User = cast<Instruction>(TheUse.getUser());
1524 TheUse = To;
1525
1526 // Check to see if the instruction can be folded due to the operand
1527 // replacement. For example changing (or X, Y) into (or X, -1) can replace
1528 // the 'or' with -1.
1529 Value *SimplifiedVal;
1530 {
1531 // Sanity check to make sure 'User' doesn't dangle across
1532 // SimplifyInstruction.
1533 AssertingVH<> UserHandle(User);
Duncan Sands12a86f52010-11-14 11:23:23 +00001534
Duncan Sandseff05812010-11-14 18:36:10 +00001535 SimplifiedVal = SimplifyInstruction(User, TD, DT);
Chris Lattnerd2bfe542010-07-15 06:36:08 +00001536 if (SimplifiedVal == 0) continue;
Chris Lattner40d8c282009-11-10 22:26:15 +00001537 }
Duncan Sands12a86f52010-11-14 11:23:23 +00001538
Chris Lattnerd2bfe542010-07-15 06:36:08 +00001539 // Recursively simplify this user to the new value.
Duncan Sandseff05812010-11-14 18:36:10 +00001540 ReplaceAndSimplifyAllUses(User, SimplifiedVal, TD, DT);
Chris Lattnerd2bfe542010-07-15 06:36:08 +00001541 From = dyn_cast_or_null<Instruction>((Value*)FromHandle);
1542 To = ToHandle;
Duncan Sands12a86f52010-11-14 11:23:23 +00001543
Chris Lattnerd2bfe542010-07-15 06:36:08 +00001544 assert(ToHandle && "To value deleted by recursive simplification?");
Duncan Sands12a86f52010-11-14 11:23:23 +00001545
Chris Lattnerd2bfe542010-07-15 06:36:08 +00001546 // If the recursive simplification ended up revisiting and deleting
1547 // 'From' then we're done.
1548 if (From == 0)
1549 return;
Chris Lattner40d8c282009-11-10 22:26:15 +00001550 }
Duncan Sands12a86f52010-11-14 11:23:23 +00001551
Chris Lattnerd2bfe542010-07-15 06:36:08 +00001552 // If 'From' has value handles referring to it, do a real RAUW to update them.
1553 From->replaceAllUsesWith(To);
Duncan Sands12a86f52010-11-14 11:23:23 +00001554
Chris Lattner40d8c282009-11-10 22:26:15 +00001555 From->eraseFromParent();
1556}