blob: de9db8c713c7708fb9d2be610d00f6a5c721ed4d [file] [log] [blame]
Chris Lattner233f7dc2002-08-12 21:17:25 +00001//===- InstructionCombining.cpp - Combine multiple instructions -----------===//
Misha Brukmanfd939082005-04-21 23:48:37 +00002//
John Criswellb576c942003-10-20 19:43:21 +00003// The LLVM Compiler Infrastructure
4//
Chris Lattner4ee451d2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Misha Brukmanfd939082005-04-21 23:48:37 +00007//
John Criswellb576c942003-10-20 19:43:21 +00008//===----------------------------------------------------------------------===//
Chris Lattner8a2a3112001-12-14 16:52:21 +00009//
10// InstructionCombining - Combine instructions to form fewer, simple
Dan Gohman844731a2008-05-13 00:00:25 +000011// instructions. This pass does not modify the CFG. This pass is where
12// algebraic simplification happens.
Chris Lattner8a2a3112001-12-14 16:52:21 +000013//
14// This pass combines things like:
Chris Lattner318bf792007-03-18 22:51:34 +000015// %Y = add i32 %X, 1
16// %Z = add i32 %Y, 1
Chris Lattner8a2a3112001-12-14 16:52:21 +000017// into:
Chris Lattner318bf792007-03-18 22:51:34 +000018// %Z = add i32 %X, 2
Chris Lattner8a2a3112001-12-14 16:52:21 +000019//
20// This is a simple worklist driven algorithm.
21//
Chris Lattner065a6162003-09-10 05:29:43 +000022// This pass guarantees that the following canonicalizations are performed on
Chris Lattner2cd91962003-07-23 21:41:57 +000023// the program:
24// 1. If a binary operator has a constant operand, it is moved to the RHS
Chris Lattnerdf17af12003-08-12 21:53:41 +000025// 2. Bitwise operators with constant operands are always grouped so that
26// shifts are performed first, then or's, then and's, then xor's.
Reid Spencere4d87aa2006-12-23 06:05:41 +000027// 3. Compare instructions are converted from <,>,<=,>= to ==,!= if possible
28// 4. All cmp instructions on boolean values are replaced with logical ops
Chris Lattnere92d2f42003-08-13 04:18:28 +000029// 5. add X, X is represented as (X*2) => (X << 1)
30// 6. Multiplies with a power-of-two constant argument are transformed into
31// shifts.
Chris Lattnerbac32862004-11-14 19:13:23 +000032// ... etc.
Chris Lattner2cd91962003-07-23 21:41:57 +000033//
Chris Lattner8a2a3112001-12-14 16:52:21 +000034//===----------------------------------------------------------------------===//
35
Chris Lattner0cea42a2004-03-13 23:54:27 +000036#define DEBUG_TYPE "instcombine"
Chris Lattner022103b2002-05-07 20:03:00 +000037#include "llvm/Transforms/Scalar.h"
Chris Lattner35b9e482004-10-12 04:52:52 +000038#include "llvm/IntrinsicInst.h"
Owen Andersond672ecb2009-07-03 00:17:18 +000039#include "llvm/LLVMContext.h"
Chris Lattnerbd0ef772002-02-26 21:46:54 +000040#include "llvm/Pass.h"
Chris Lattner0864acf2002-11-04 16:18:53 +000041#include "llvm/DerivedTypes.h"
Chris Lattner833b8a42003-06-26 05:06:25 +000042#include "llvm/GlobalVariable.h"
Dan Gohmanca178902009-07-17 20:47:02 +000043#include "llvm/Operator.h"
Chris Lattner79066fa2007-01-30 23:46:24 +000044#include "llvm/Analysis/ConstantFolding.h"
Chris Lattner173234a2008-06-02 01:18:21 +000045#include "llvm/Analysis/ValueTracking.h"
Chris Lattnerbc61e662003-11-02 05:57:39 +000046#include "llvm/Target/TargetData.h"
47#include "llvm/Transforms/Utils/BasicBlockUtils.h"
48#include "llvm/Transforms/Utils/Local.h"
Chris Lattner28977af2004-04-05 01:30:19 +000049#include "llvm/Support/CallSite.h"
Nick Lewycky5be29202008-02-03 16:33:09 +000050#include "llvm/Support/ConstantRange.h"
Chris Lattnerea1c4542004-12-08 23:43:58 +000051#include "llvm/Support/Debug.h"
Torok Edwin7d696d82009-07-11 13:10:19 +000052#include "llvm/Support/ErrorHandling.h"
Chris Lattner28977af2004-04-05 01:30:19 +000053#include "llvm/Support/GetElementPtrTypeIterator.h"
Chris Lattnerdd841ae2002-04-18 17:39:14 +000054#include "llvm/Support/InstVisitor.h"
Chris Lattnerbcd7db52005-08-02 19:16:58 +000055#include "llvm/Support/MathExtras.h"
Chris Lattneracd1f0f2004-07-30 07:50:03 +000056#include "llvm/Support/PatternMatch.h"
Chris Lattnera4f0b3a2006-08-27 12:54:02 +000057#include "llvm/Support/Compiler.h"
Daniel Dunbarce63ffb2009-07-25 00:23:56 +000058#include "llvm/Support/raw_ostream.h"
Chris Lattnerdbab3862007-03-02 21:28:56 +000059#include "llvm/ADT/DenseMap.h"
Chris Lattner55eb1c42007-01-31 04:40:53 +000060#include "llvm/ADT/SmallVector.h"
Chris Lattner1f87a582007-02-15 19:41:52 +000061#include "llvm/ADT/SmallPtrSet.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000062#include "llvm/ADT/Statistic.h"
Chris Lattnerea1c4542004-12-08 23:43:58 +000063#include "llvm/ADT/STLExtras.h"
Chris Lattnerb3bc8fa2002-05-14 15:24:07 +000064#include <algorithm>
Torok Edwin3eaee312008-04-20 08:33:11 +000065#include <climits>
Reid Spencera9b81012007-03-26 17:44:01 +000066#include <sstream>
Chris Lattner67b1e1b2003-12-07 01:24:23 +000067using namespace llvm;
Chris Lattneracd1f0f2004-07-30 07:50:03 +000068using namespace llvm::PatternMatch;
Brian Gaeked0fde302003-11-11 22:41:34 +000069
Chris Lattner0e5f4992006-12-19 21:40:18 +000070STATISTIC(NumCombined , "Number of insts combined");
71STATISTIC(NumConstProp, "Number of constant folds");
72STATISTIC(NumDeadInst , "Number of dead inst eliminated");
73STATISTIC(NumDeadStore, "Number of dead stores eliminated");
74STATISTIC(NumSunkInst , "Number of instructions sunk");
Chris Lattnera92f6962002-10-01 22:38:41 +000075
Chris Lattner0e5f4992006-12-19 21:40:18 +000076namespace {
Chris Lattnerf4b54612006-06-28 22:08:15 +000077 class VISIBILITY_HIDDEN InstCombiner
78 : public FunctionPass,
79 public InstVisitor<InstCombiner, Instruction*> {
Chris Lattnerdd841ae2002-04-18 17:39:14 +000080 // Worklist of all of the instructions that need to be simplified.
Chris Lattner2806dff2008-08-15 04:03:01 +000081 SmallVector<Instruction*, 256> Worklist;
Chris Lattnerdbab3862007-03-02 21:28:56 +000082 DenseMap<Instruction*, unsigned> WorklistMap;
Chris Lattnerbc61e662003-11-02 05:57:39 +000083 TargetData *TD;
Chris Lattnerf964f322007-03-04 04:27:24 +000084 bool MustPreserveLCSSA;
Chris Lattnerdbab3862007-03-02 21:28:56 +000085 public:
Nick Lewyckyecd94c82007-05-06 13:37:16 +000086 static char ID; // Pass identification, replacement for typeid
Dan Gohmanae73dc12008-09-04 17:05:41 +000087 InstCombiner() : FunctionPass(&ID) {}
Devang Patel794fd752007-05-01 21:15:47 +000088
Owen Andersone922c022009-07-22 00:24:57 +000089 LLVMContext *Context;
90 LLVMContext *getContext() const { return Context; }
Owen Andersond672ecb2009-07-03 00:17:18 +000091
Chris Lattnerdbab3862007-03-02 21:28:56 +000092 /// AddToWorkList - Add the specified instruction to the worklist if it
93 /// isn't already in it.
94 void AddToWorkList(Instruction *I) {
Dan Gohman6b345ee2008-07-07 17:46:23 +000095 if (WorklistMap.insert(std::make_pair(I, Worklist.size())).second)
Chris Lattnerdbab3862007-03-02 21:28:56 +000096 Worklist.push_back(I);
97 }
98
99 // RemoveFromWorkList - remove I from the worklist if it exists.
100 void RemoveFromWorkList(Instruction *I) {
101 DenseMap<Instruction*, unsigned>::iterator It = WorklistMap.find(I);
102 if (It == WorklistMap.end()) return; // Not in worklist.
103
104 // Don't bother moving everything down, just null out the slot.
105 Worklist[It->second] = 0;
106
107 WorklistMap.erase(It);
108 }
109
110 Instruction *RemoveOneFromWorkList() {
111 Instruction *I = Worklist.back();
112 Worklist.pop_back();
113 WorklistMap.erase(I);
114 return I;
115 }
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000116
Chris Lattnerdbab3862007-03-02 21:28:56 +0000117
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000118 /// AddUsersToWorkList - When an instruction is simplified, add all users of
119 /// the instruction to the work lists because they might get more simplified
120 /// now.
121 ///
Chris Lattner6dce1a72006-02-07 06:56:34 +0000122 void AddUsersToWorkList(Value &I) {
Chris Lattner7e708292002-06-25 16:13:24 +0000123 for (Value::use_iterator UI = I.use_begin(), UE = I.use_end();
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000124 UI != UE; ++UI)
Chris Lattnerdbab3862007-03-02 21:28:56 +0000125 AddToWorkList(cast<Instruction>(*UI));
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000126 }
127
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000128 /// AddUsesToWorkList - When an instruction is simplified, add operands to
129 /// the work lists because they might get more simplified now.
130 ///
131 void AddUsesToWorkList(Instruction &I) {
Gabor Greif177dd3f2008-06-12 21:37:33 +0000132 for (User::op_iterator i = I.op_begin(), e = I.op_end(); i != e; ++i)
133 if (Instruction *Op = dyn_cast<Instruction>(*i))
Chris Lattnerdbab3862007-03-02 21:28:56 +0000134 AddToWorkList(Op);
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000135 }
Chris Lattner867b99f2006-10-05 06:55:50 +0000136
137 /// AddSoonDeadInstToWorklist - The specified instruction is about to become
138 /// dead. Add all of its operands to the worklist, turning them into
139 /// undef's to reduce the number of uses of those instructions.
140 ///
141 /// Return the specified operand before it is turned into an undef.
142 ///
143 Value *AddSoonDeadInstToWorklist(Instruction &I, unsigned op) {
144 Value *R = I.getOperand(op);
145
Gabor Greif177dd3f2008-06-12 21:37:33 +0000146 for (User::op_iterator i = I.op_begin(), e = I.op_end(); i != e; ++i)
147 if (Instruction *Op = dyn_cast<Instruction>(*i)) {
Chris Lattnerdbab3862007-03-02 21:28:56 +0000148 AddToWorkList(Op);
Chris Lattner867b99f2006-10-05 06:55:50 +0000149 // Set the operand to undef to drop the use.
Owen Anderson9e9a0d52009-07-30 23:03:37 +0000150 *i = UndefValue::get(Op->getType());
Chris Lattner867b99f2006-10-05 06:55:50 +0000151 }
152
153 return R;
154 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000155
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000156 public:
Chris Lattner7e708292002-06-25 16:13:24 +0000157 virtual bool runOnFunction(Function &F);
Chris Lattnerec9c3582007-03-03 02:04:50 +0000158
159 bool DoOneIteration(Function &F, unsigned ItNum);
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000160
Chris Lattner97e52e42002-04-28 21:27:06 +0000161 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Owen Andersond1b78a12006-07-10 19:03:49 +0000162 AU.addPreservedID(LCSSAID);
Chris Lattnercb2610e2002-10-21 20:00:28 +0000163 AU.setPreservesCFG();
Chris Lattner97e52e42002-04-28 21:27:06 +0000164 }
165
Dan Gohmance9fe9f2009-07-21 23:21:54 +0000166 TargetData *getTargetData() const { return TD; }
Chris Lattner28977af2004-04-05 01:30:19 +0000167
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000168 // Visitation implementation - Implement instruction combining for different
169 // instruction types. The semantics are as follows:
170 // Return Value:
171 // null - No change was made
Chris Lattner233f7dc2002-08-12 21:17:25 +0000172 // I - Change was made, I is still valid, I may be dead though
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000173 // otherwise - Change was made, replace I with returned instruction
Misha Brukmanfd939082005-04-21 23:48:37 +0000174 //
Chris Lattner7e708292002-06-25 16:13:24 +0000175 Instruction *visitAdd(BinaryOperator &I);
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000176 Instruction *visitFAdd(BinaryOperator &I);
Chris Lattner7e708292002-06-25 16:13:24 +0000177 Instruction *visitSub(BinaryOperator &I);
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000178 Instruction *visitFSub(BinaryOperator &I);
Chris Lattner7e708292002-06-25 16:13:24 +0000179 Instruction *visitMul(BinaryOperator &I);
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000180 Instruction *visitFMul(BinaryOperator &I);
Reid Spencer0a783f72006-11-02 01:53:59 +0000181 Instruction *visitURem(BinaryOperator &I);
182 Instruction *visitSRem(BinaryOperator &I);
183 Instruction *visitFRem(BinaryOperator &I);
Chris Lattnerfdb19e52008-07-14 00:15:52 +0000184 bool SimplifyDivRemOfSelect(BinaryOperator &I);
Reid Spencer0a783f72006-11-02 01:53:59 +0000185 Instruction *commonRemTransforms(BinaryOperator &I);
186 Instruction *commonIRemTransforms(BinaryOperator &I);
Reid Spencer1628cec2006-10-26 06:15:43 +0000187 Instruction *commonDivTransforms(BinaryOperator &I);
188 Instruction *commonIDivTransforms(BinaryOperator &I);
189 Instruction *visitUDiv(BinaryOperator &I);
190 Instruction *visitSDiv(BinaryOperator &I);
191 Instruction *visitFDiv(BinaryOperator &I);
Chris Lattner29cd5ba2008-11-16 05:06:21 +0000192 Instruction *FoldAndOfICmps(Instruction &I, ICmpInst *LHS, ICmpInst *RHS);
Chris Lattner42d1be02009-07-23 05:14:02 +0000193 Instruction *FoldAndOfFCmps(Instruction &I, FCmpInst *LHS, FCmpInst *RHS);
Chris Lattner7e708292002-06-25 16:13:24 +0000194 Instruction *visitAnd(BinaryOperator &I);
Chris Lattner69d4ced2008-11-16 05:20:07 +0000195 Instruction *FoldOrOfICmps(Instruction &I, ICmpInst *LHS, ICmpInst *RHS);
Chris Lattner5414cc52009-07-23 05:46:22 +0000196 Instruction *FoldOrOfFCmps(Instruction &I, FCmpInst *LHS, FCmpInst *RHS);
Bill Wendlingd54d8602008-12-01 08:32:40 +0000197 Instruction *FoldOrWithConstants(BinaryOperator &I, Value *Op,
Bill Wendlinga698a472008-12-01 08:23:25 +0000198 Value *A, Value *B, Value *C);
Chris Lattner7e708292002-06-25 16:13:24 +0000199 Instruction *visitOr (BinaryOperator &I);
200 Instruction *visitXor(BinaryOperator &I);
Reid Spencer832254e2007-02-02 02:16:23 +0000201 Instruction *visitShl(BinaryOperator &I);
202 Instruction *visitAShr(BinaryOperator &I);
203 Instruction *visitLShr(BinaryOperator &I);
204 Instruction *commonShiftTransforms(BinaryOperator &I);
Chris Lattnera5406232008-05-19 20:18:56 +0000205 Instruction *FoldFCmp_IntToFP_Cst(FCmpInst &I, Instruction *LHSI,
206 Constant *RHSC);
Reid Spencere4d87aa2006-12-23 06:05:41 +0000207 Instruction *visitFCmpInst(FCmpInst &I);
208 Instruction *visitICmpInst(ICmpInst &I);
209 Instruction *visitICmpInstWithCastAndCast(ICmpInst &ICI);
Chris Lattner01deb9d2007-04-03 17:43:25 +0000210 Instruction *visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
211 Instruction *LHS,
212 ConstantInt *RHS);
Chris Lattner562ef782007-06-20 23:46:26 +0000213 Instruction *FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
214 ConstantInt *DivRHS);
Chris Lattner484d3cf2005-04-24 06:59:08 +0000215
Dan Gohmand6aa02d2009-07-28 01:40:03 +0000216 Instruction *FoldGEPICmp(GEPOperator *GEPLHS, Value *RHS,
Reid Spencere4d87aa2006-12-23 06:05:41 +0000217 ICmpInst::Predicate Cond, Instruction &I);
Reid Spencerb83eb642006-10-20 07:07:24 +0000218 Instruction *FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
Reid Spencer832254e2007-02-02 02:16:23 +0000219 BinaryOperator &I);
Reid Spencer3da59db2006-11-27 01:05:10 +0000220 Instruction *commonCastTransforms(CastInst &CI);
221 Instruction *commonIntCastTransforms(CastInst &CI);
Chris Lattnerd3e28342007-04-27 17:44:50 +0000222 Instruction *commonPointerCastTransforms(CastInst &CI);
Chris Lattner8a9f5712007-04-11 06:57:46 +0000223 Instruction *visitTrunc(TruncInst &CI);
224 Instruction *visitZExt(ZExtInst &CI);
225 Instruction *visitSExt(SExtInst &CI);
Chris Lattnerb7530652008-01-27 05:29:54 +0000226 Instruction *visitFPTrunc(FPTruncInst &CI);
Reid Spencer3da59db2006-11-27 01:05:10 +0000227 Instruction *visitFPExt(CastInst &CI);
Chris Lattner0c7a9a02008-05-19 20:25:04 +0000228 Instruction *visitFPToUI(FPToUIInst &FI);
229 Instruction *visitFPToSI(FPToSIInst &FI);
Reid Spencer3da59db2006-11-27 01:05:10 +0000230 Instruction *visitUIToFP(CastInst &CI);
231 Instruction *visitSIToFP(CastInst &CI);
Chris Lattnera0e69692009-03-24 18:35:40 +0000232 Instruction *visitPtrToInt(PtrToIntInst &CI);
Chris Lattnerf9d9e452008-01-08 07:23:51 +0000233 Instruction *visitIntToPtr(IntToPtrInst &CI);
Chris Lattnerd3e28342007-04-27 17:44:50 +0000234 Instruction *visitBitCast(BitCastInst &CI);
Chris Lattner6fb5a4a2005-01-19 21:50:18 +0000235 Instruction *FoldSelectOpOp(SelectInst &SI, Instruction *TI,
236 Instruction *FI);
Evan Chengde621922009-03-31 20:42:45 +0000237 Instruction *FoldSelectIntoOp(SelectInst &SI, Value*, Value*);
Dan Gohman81b28ce2008-09-16 18:46:06 +0000238 Instruction *visitSelectInst(SelectInst &SI);
239 Instruction *visitSelectInstWithICmp(SelectInst &SI, ICmpInst *ICI);
Chris Lattner9fe38862003-06-19 17:00:31 +0000240 Instruction *visitCallInst(CallInst &CI);
241 Instruction *visitInvokeInst(InvokeInst &II);
Chris Lattner7e708292002-06-25 16:13:24 +0000242 Instruction *visitPHINode(PHINode &PN);
243 Instruction *visitGetElementPtrInst(GetElementPtrInst &GEP);
Chris Lattner0864acf2002-11-04 16:18:53 +0000244 Instruction *visitAllocationInst(AllocationInst &AI);
Chris Lattner67b1e1b2003-12-07 01:24:23 +0000245 Instruction *visitFreeInst(FreeInst &FI);
Chris Lattner833b8a42003-06-26 05:06:25 +0000246 Instruction *visitLoadInst(LoadInst &LI);
Chris Lattner2f503e62005-01-31 05:36:43 +0000247 Instruction *visitStoreInst(StoreInst &SI);
Chris Lattnerc4d10eb2003-06-04 04:46:00 +0000248 Instruction *visitBranchInst(BranchInst &BI);
Chris Lattner46238a62004-07-03 00:26:11 +0000249 Instruction *visitSwitchInst(SwitchInst &SI);
Chris Lattnerefb47352006-04-15 01:39:45 +0000250 Instruction *visitInsertElementInst(InsertElementInst &IE);
Robert Bocchino1d7456d2006-01-13 22:48:06 +0000251 Instruction *visitExtractElementInst(ExtractElementInst &EI);
Chris Lattnera844fc4c2006-04-10 22:45:52 +0000252 Instruction *visitShuffleVectorInst(ShuffleVectorInst &SVI);
Matthijs Kooijmana9012ec2008-06-11 14:05:05 +0000253 Instruction *visitExtractValueInst(ExtractValueInst &EV);
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000254
255 // visitInstruction - Specify what to return for unhandled instructions...
Chris Lattner7e708292002-06-25 16:13:24 +0000256 Instruction *visitInstruction(Instruction &I) { return 0; }
Chris Lattner8b170942002-08-09 23:47:40 +0000257
Chris Lattner9fe38862003-06-19 17:00:31 +0000258 private:
Chris Lattnera44d8a22003-10-07 22:32:43 +0000259 Instruction *visitCallSite(CallSite CS);
Chris Lattner9fe38862003-06-19 17:00:31 +0000260 bool transformConstExprCastCall(CallSite CS);
Duncan Sandscdb6d922007-09-17 10:26:40 +0000261 Instruction *transformCallThroughTrampoline(CallSite CS);
Evan Chengb98a10e2008-03-24 00:21:34 +0000262 Instruction *transformZExtICmp(ICmpInst *ICI, Instruction &CI,
263 bool DoXform = true);
Chris Lattner3d28b1b2008-05-20 05:46:13 +0000264 bool WillNotOverflowSignedAdd(Value *LHS, Value *RHS);
Dale Johannesen4945c652009-03-03 21:26:39 +0000265 DbgDeclareInst *hasOneUsePlusDeclare(Value *V);
266
Chris Lattner9fe38862003-06-19 17:00:31 +0000267
Chris Lattner28977af2004-04-05 01:30:19 +0000268 public:
Chris Lattner8b170942002-08-09 23:47:40 +0000269 // InsertNewInstBefore - insert an instruction New before instruction Old
270 // in the program. Add the new instruction to the worklist.
271 //
Chris Lattner955f3312004-09-28 21:48:02 +0000272 Instruction *InsertNewInstBefore(Instruction *New, Instruction &Old) {
Chris Lattnere6f9a912002-08-23 18:32:43 +0000273 assert(New && New->getParent() == 0 &&
274 "New instruction already inserted into a basic block!");
Chris Lattner8b170942002-08-09 23:47:40 +0000275 BasicBlock *BB = Old.getParent();
276 BB->getInstList().insert(&Old, New); // Insert inst
Chris Lattnerdbab3862007-03-02 21:28:56 +0000277 AddToWorkList(New);
Chris Lattner4cb170c2004-02-23 06:38:22 +0000278 return New;
Chris Lattner8b170942002-08-09 23:47:40 +0000279 }
280
Chris Lattner0c967662004-09-24 15:21:34 +0000281 /// InsertCastBefore - Insert a cast of V to TY before the instruction POS.
282 /// This also adds the cast to the worklist. Finally, this returns the
283 /// cast.
Reid Spencer17212df2006-12-12 09:18:51 +0000284 Value *InsertCastBefore(Instruction::CastOps opc, Value *V, const Type *Ty,
285 Instruction &Pos) {
Chris Lattner0c967662004-09-24 15:21:34 +0000286 if (V->getType() == Ty) return V;
Misha Brukmanfd939082005-04-21 23:48:37 +0000287
Chris Lattnere2ed0572006-04-06 19:19:17 +0000288 if (Constant *CV = dyn_cast<Constant>(V))
Owen Andersonbaf3c402009-07-29 18:55:55 +0000289 return ConstantExpr::getCast(opc, CV, Ty);
Chris Lattnere2ed0572006-04-06 19:19:17 +0000290
Gabor Greif7cbd8a32008-05-16 19:29:10 +0000291 Instruction *C = CastInst::Create(opc, V, Ty, V->getName(), &Pos);
Chris Lattnerdbab3862007-03-02 21:28:56 +0000292 AddToWorkList(C);
Chris Lattner0c967662004-09-24 15:21:34 +0000293 return C;
294 }
Chris Lattner6d0339d2008-01-13 22:23:22 +0000295
296 Value *InsertBitCastBefore(Value *V, const Type *Ty, Instruction &Pos) {
297 return InsertCastBefore(Instruction::BitCast, V, Ty, Pos);
298 }
299
Chris Lattner0c967662004-09-24 15:21:34 +0000300
Chris Lattner8b170942002-08-09 23:47:40 +0000301 // ReplaceInstUsesWith - This method is to be used when an instruction is
302 // found to be dead, replacable with another preexisting expression. Here
303 // we add all uses of I to the worklist, replace all uses of I with the new
304 // value, then return I, so that the inst combiner will know that I was
305 // modified.
306 //
307 Instruction *ReplaceInstUsesWith(Instruction &I, Value *V) {
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000308 AddUsersToWorkList(I); // Add all modified instrs to worklist
Chris Lattner15a76c02004-04-05 02:10:19 +0000309 if (&I != V) {
310 I.replaceAllUsesWith(V);
311 return &I;
312 } else {
313 // If we are replacing the instruction with itself, this must be in a
314 // segment of unreachable code, so just clobber the instruction.
Owen Anderson9e9a0d52009-07-30 23:03:37 +0000315 I.replaceAllUsesWith(UndefValue::get(I.getType()));
Chris Lattner15a76c02004-04-05 02:10:19 +0000316 return &I;
317 }
Chris Lattner8b170942002-08-09 23:47:40 +0000318 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000319
320 // EraseInstFromFunction - When dealing with an instruction that has side
321 // effects or produces a void value, we can't rely on DCE to delete the
322 // instruction. Instead, visit methods should return the value returned by
323 // this function.
324 Instruction *EraseInstFromFunction(Instruction &I) {
325 assert(I.use_empty() && "Cannot erase instruction that is used!");
326 AddUsesToWorkList(I);
Chris Lattnerdbab3862007-03-02 21:28:56 +0000327 RemoveFromWorkList(&I);
Chris Lattner954f66a2004-11-18 21:41:39 +0000328 I.eraseFromParent();
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000329 return 0; // Don't do anything with FI
330 }
Chris Lattner173234a2008-06-02 01:18:21 +0000331
332 void ComputeMaskedBits(Value *V, const APInt &Mask, APInt &KnownZero,
333 APInt &KnownOne, unsigned Depth = 0) const {
334 return llvm::ComputeMaskedBits(V, Mask, KnownZero, KnownOne, TD, Depth);
335 }
336
337 bool MaskedValueIsZero(Value *V, const APInt &Mask,
338 unsigned Depth = 0) const {
339 return llvm::MaskedValueIsZero(V, Mask, TD, Depth);
340 }
341 unsigned ComputeNumSignBits(Value *Op, unsigned Depth = 0) const {
342 return llvm::ComputeNumSignBits(Op, TD, Depth);
343 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000344
Chris Lattneraa9c1f12003-08-13 20:16:26 +0000345 private:
Chris Lattner24c8e382003-07-24 17:35:25 +0000346
Reid Spencere4d87aa2006-12-23 06:05:41 +0000347 /// SimplifyCommutative - This performs a few simplifications for
348 /// commutative operators.
Chris Lattnerc8802d22003-03-11 00:12:48 +0000349 bool SimplifyCommutative(BinaryOperator &I);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +0000350
Reid Spencere4d87aa2006-12-23 06:05:41 +0000351 /// SimplifyCompare - This reorders the operands of a CmpInst to get them in
352 /// most-complex to least-complex order.
353 bool SimplifyCompare(CmpInst &I);
354
Chris Lattner886ab6c2009-01-31 08:15:18 +0000355 /// SimplifyDemandedUseBits - Attempts to replace V with a simpler value
356 /// based on the demanded bits.
357 Value *SimplifyDemandedUseBits(Value *V, APInt DemandedMask,
358 APInt& KnownZero, APInt& KnownOne,
359 unsigned Depth);
360 bool SimplifyDemandedBits(Use &U, APInt DemandedMask,
Reid Spencer8cb68342007-03-12 17:25:59 +0000361 APInt& KnownZero, APInt& KnownOne,
Chris Lattner886ab6c2009-01-31 08:15:18 +0000362 unsigned Depth=0);
363
364 /// SimplifyDemandedInstructionBits - Inst is an integer instruction that
365 /// SimplifyDemandedBits knows about. See if the instruction has any
366 /// properties that allow us to simplify its operands.
367 bool SimplifyDemandedInstructionBits(Instruction &Inst);
368
Evan Cheng388df622009-02-03 10:05:09 +0000369 Value *SimplifyDemandedVectorElts(Value *V, APInt DemandedElts,
370 APInt& UndefElts, unsigned Depth = 0);
Chris Lattner867b99f2006-10-05 06:55:50 +0000371
Chris Lattner4e998b22004-09-29 05:07:12 +0000372 // FoldOpIntoPhi - Given a binary operator or cast instruction which has a
373 // PHI node as operand #0, see if we can fold the instruction into the PHI
374 // (which is only possible if all operands to the PHI are constants).
375 Instruction *FoldOpIntoPhi(Instruction &I);
376
Chris Lattnerbac32862004-11-14 19:13:23 +0000377 // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
378 // operator and they all are only used by the PHI, PHI together their
379 // inputs, and do the operation once, to the result of the PHI.
380 Instruction *FoldPHIArgOpIntoPHI(PHINode &PN);
Chris Lattner7da52b22006-11-01 04:51:18 +0000381 Instruction *FoldPHIArgBinOpIntoPHI(PHINode &PN);
Chris Lattner05f18922008-12-01 02:34:36 +0000382 Instruction *FoldPHIArgGEPIntoPHI(PHINode &PN);
383
Chris Lattner7da52b22006-11-01 04:51:18 +0000384
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +0000385 Instruction *OptAndOp(Instruction *Op, ConstantInt *OpRHS,
386 ConstantInt *AndRHS, BinaryOperator &TheAnd);
Chris Lattnerc8e77562005-09-18 04:24:45 +0000387
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +0000388 Value *FoldLogicalPlusAnd(Value *LHS, Value *RHS, ConstantInt *Mask,
Chris Lattnerc8e77562005-09-18 04:24:45 +0000389 bool isSub, Instruction &I);
Chris Lattnera96879a2004-09-29 17:40:11 +0000390 Instruction *InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
Reid Spencere4d87aa2006-12-23 06:05:41 +0000391 bool isSigned, bool Inside, Instruction &IB);
Chris Lattnerd3e28342007-04-27 17:44:50 +0000392 Instruction *PromoteCastOfAllocation(BitCastInst &CI, AllocationInst &AI);
Chris Lattnerafe91a52006-06-15 19:07:26 +0000393 Instruction *MatchBSwap(BinaryOperator &I);
Chris Lattner3284d1f2007-04-15 00:07:55 +0000394 bool SimplifyStoreAtEndOfBlock(StoreInst &SI);
Chris Lattnerf497b022008-01-13 23:50:23 +0000395 Instruction *SimplifyMemTransfer(MemIntrinsic *MI);
Chris Lattner69ea9d22008-04-30 06:39:11 +0000396 Instruction *SimplifyMemSet(MemSetInst *MI);
Chris Lattnerf497b022008-01-13 23:50:23 +0000397
Chris Lattnerafe91a52006-06-15 19:07:26 +0000398
Reid Spencerc55b2432006-12-13 18:21:21 +0000399 Value *EvaluateInDifferentType(Value *V, const Type *Ty, bool isSigned);
Dan Gohmaneee962e2008-04-10 18:43:06 +0000400
Dan Gohman6de29f82009-06-15 22:12:54 +0000401 bool CanEvaluateInDifferentType(Value *V, const Type *Ty,
Evan Cheng4e56ab22009-01-16 02:11:43 +0000402 unsigned CastOpc, int &NumCastsRemoved);
Dan Gohmaneee962e2008-04-10 18:43:06 +0000403 unsigned GetOrEnforceKnownAlignment(Value *V,
404 unsigned PrefAlign = 0);
Matthijs Kooijmana9012ec2008-06-11 14:05:05 +0000405
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000406 };
407}
408
Dan Gohman844731a2008-05-13 00:00:25 +0000409char InstCombiner::ID = 0;
410static RegisterPass<InstCombiner>
411X("instcombine", "Combine redundant instructions");
412
Chris Lattner4f98c562003-03-10 21:43:22 +0000413// getComplexity: Assign a complexity or rank value to LLVM Values...
Chris Lattnere87597f2004-10-16 18:11:37 +0000414// 0 -> undef, 1 -> Const, 2 -> Other, 3 -> Arg, 3 -> Unary, 4 -> OtherInst
Owen Anderson0a5372e2009-07-13 04:09:18 +0000415static unsigned getComplexity(LLVMContext *Context, Value *V) {
Chris Lattner4f98c562003-03-10 21:43:22 +0000416 if (isa<Instruction>(V)) {
Owen Andersonfa82b6e2009-07-13 22:18:28 +0000417 if (BinaryOperator::isNeg(V) ||
418 BinaryOperator::isFNeg(V) ||
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000419 BinaryOperator::isNot(V))
Chris Lattnere87597f2004-10-16 18:11:37 +0000420 return 3;
421 return 4;
Chris Lattner4f98c562003-03-10 21:43:22 +0000422 }
Chris Lattnere87597f2004-10-16 18:11:37 +0000423 if (isa<Argument>(V)) return 3;
424 return isa<Constant>(V) ? (isa<UndefValue>(V) ? 0 : 1) : 2;
Chris Lattner4f98c562003-03-10 21:43:22 +0000425}
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000426
Chris Lattnerc8802d22003-03-11 00:12:48 +0000427// isOnlyUse - Return true if this instruction will be deleted if we stop using
428// it.
429static bool isOnlyUse(Value *V) {
Chris Lattnerfd059242003-10-15 16:48:29 +0000430 return V->hasOneUse() || isa<Constant>(V);
Chris Lattnerc8802d22003-03-11 00:12:48 +0000431}
432
Chris Lattner4cb170c2004-02-23 06:38:22 +0000433// getPromotedType - Return the specified type promoted as it would be to pass
434// though a va_arg area...
435static const Type *getPromotedType(const Type *Ty) {
Reid Spencera54b7cb2007-01-12 07:05:14 +0000436 if (const IntegerType* ITy = dyn_cast<IntegerType>(Ty)) {
437 if (ITy->getBitWidth() < 32)
438 return Type::Int32Ty;
Chris Lattner2b7e0ad2007-05-23 01:17:04 +0000439 }
Reid Spencera54b7cb2007-01-12 07:05:14 +0000440 return Ty;
Chris Lattner4cb170c2004-02-23 06:38:22 +0000441}
442
Matthijs Kooijman7e6d9b92008-10-13 15:17:01 +0000443/// getBitCastOperand - If the specified operand is a CastInst, a constant
444/// expression bitcast, or a GetElementPtrInst with all zero indices, return the
445/// operand value, otherwise return null.
Reid Spencer3da59db2006-11-27 01:05:10 +0000446static Value *getBitCastOperand(Value *V) {
Dan Gohman016de812009-07-17 23:55:56 +0000447 if (Operator *O = dyn_cast<Operator>(V)) {
448 if (O->getOpcode() == Instruction::BitCast)
449 return O->getOperand(0);
450 if (GEPOperator *GEP = dyn_cast<GEPOperator>(V))
451 if (GEP->hasAllZeroIndices())
452 return GEP->getPointerOperand();
Matthijs Kooijman7e6d9b92008-10-13 15:17:01 +0000453 }
Chris Lattnereed48272005-09-13 00:40:14 +0000454 return 0;
455}
456
Reid Spencer3da59db2006-11-27 01:05:10 +0000457/// This function is a wrapper around CastInst::isEliminableCastPair. It
458/// simply extracts arguments and returns what that function returns.
Reid Spencer3da59db2006-11-27 01:05:10 +0000459static Instruction::CastOps
460isEliminableCastPair(
461 const CastInst *CI, ///< The first cast instruction
462 unsigned opcode, ///< The opcode of the second cast instruction
463 const Type *DstTy, ///< The target type for the second cast instruction
464 TargetData *TD ///< The target data for pointer size
465) {
Dan Gohmance9fe9f2009-07-21 23:21:54 +0000466
Reid Spencer3da59db2006-11-27 01:05:10 +0000467 const Type *SrcTy = CI->getOperand(0)->getType(); // A from above
468 const Type *MidTy = CI->getType(); // B from above
Chris Lattner33a61132006-05-06 09:00:16 +0000469
Reid Spencer3da59db2006-11-27 01:05:10 +0000470 // Get the opcodes of the two Cast instructions
471 Instruction::CastOps firstOp = Instruction::CastOps(CI->getOpcode());
472 Instruction::CastOps secondOp = Instruction::CastOps(opcode);
Chris Lattner33a61132006-05-06 09:00:16 +0000473
Chris Lattnera0e69692009-03-24 18:35:40 +0000474 unsigned Res = CastInst::isEliminableCastPair(firstOp, secondOp, SrcTy, MidTy,
Dan Gohmance9fe9f2009-07-21 23:21:54 +0000475 DstTy,
476 TD ? TD->getIntPtrType() : 0);
Chris Lattnera0e69692009-03-24 18:35:40 +0000477
478 // We don't want to form an inttoptr or ptrtoint that converts to an integer
479 // type that differs from the pointer size.
480 if ((Res == Instruction::IntToPtr && SrcTy != TD->getIntPtrType()) ||
481 (Res == Instruction::PtrToInt && DstTy != TD->getIntPtrType()))
482 Res = 0;
483
484 return Instruction::CastOps(Res);
Chris Lattner33a61132006-05-06 09:00:16 +0000485}
486
487/// ValueRequiresCast - Return true if the cast from "V to Ty" actually results
488/// in any code being generated. It does not require codegen if V is simple
489/// enough or if the cast can be folded into other casts.
Reid Spencere4d87aa2006-12-23 06:05:41 +0000490static bool ValueRequiresCast(Instruction::CastOps opcode, const Value *V,
491 const Type *Ty, TargetData *TD) {
Chris Lattner33a61132006-05-06 09:00:16 +0000492 if (V->getType() == Ty || isa<Constant>(V)) return false;
493
Chris Lattner01575b72006-05-25 23:24:33 +0000494 // If this is another cast that can be eliminated, it isn't codegen either.
Chris Lattner33a61132006-05-06 09:00:16 +0000495 if (const CastInst *CI = dyn_cast<CastInst>(V))
Dan Gohmance9fe9f2009-07-21 23:21:54 +0000496 if (isEliminableCastPair(CI, opcode, Ty, TD))
Chris Lattner33a61132006-05-06 09:00:16 +0000497 return false;
498 return true;
499}
500
Chris Lattner4f98c562003-03-10 21:43:22 +0000501// SimplifyCommutative - This performs a few simplifications for commutative
502// operators:
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000503//
Chris Lattner4f98c562003-03-10 21:43:22 +0000504// 1. Order operands such that they are listed from right (least complex) to
505// left (most complex). This puts constants before unary operators before
506// binary operators.
507//
Chris Lattnerc8802d22003-03-11 00:12:48 +0000508// 2. Transform: (op (op V, C1), C2) ==> (op V, (op C1, C2))
509// 3. Transform: (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Chris Lattner4f98c562003-03-10 21:43:22 +0000510//
Chris Lattnerc8802d22003-03-11 00:12:48 +0000511bool InstCombiner::SimplifyCommutative(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +0000512 bool Changed = false;
Owen Anderson0a5372e2009-07-13 04:09:18 +0000513 if (getComplexity(Context, I.getOperand(0)) <
514 getComplexity(Context, I.getOperand(1)))
Chris Lattner4f98c562003-03-10 21:43:22 +0000515 Changed = !I.swapOperands();
Misha Brukmanfd939082005-04-21 23:48:37 +0000516
Chris Lattner4f98c562003-03-10 21:43:22 +0000517 if (!I.isAssociative()) return Changed;
518 Instruction::BinaryOps Opcode = I.getOpcode();
Chris Lattnerc8802d22003-03-11 00:12:48 +0000519 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(I.getOperand(0)))
520 if (Op->getOpcode() == Opcode && isa<Constant>(Op->getOperand(1))) {
521 if (isa<Constant>(I.getOperand(1))) {
Owen Andersonbaf3c402009-07-29 18:55:55 +0000522 Constant *Folded = ConstantExpr::get(I.getOpcode(),
Chris Lattner2a9c8472003-05-27 16:40:51 +0000523 cast<Constant>(I.getOperand(1)),
524 cast<Constant>(Op->getOperand(1)));
Chris Lattnerc8802d22003-03-11 00:12:48 +0000525 I.setOperand(0, Op->getOperand(0));
526 I.setOperand(1, Folded);
527 return true;
528 } else if (BinaryOperator *Op1=dyn_cast<BinaryOperator>(I.getOperand(1)))
529 if (Op1->getOpcode() == Opcode && isa<Constant>(Op1->getOperand(1)) &&
530 isOnlyUse(Op) && isOnlyUse(Op1)) {
531 Constant *C1 = cast<Constant>(Op->getOperand(1));
532 Constant *C2 = cast<Constant>(Op1->getOperand(1));
533
534 // Fold (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Owen Andersonbaf3c402009-07-29 18:55:55 +0000535 Constant *Folded = ConstantExpr::get(I.getOpcode(), C1, C2);
Gabor Greif7cbd8a32008-05-16 19:29:10 +0000536 Instruction *New = BinaryOperator::Create(Opcode, Op->getOperand(0),
Chris Lattnerc8802d22003-03-11 00:12:48 +0000537 Op1->getOperand(0),
538 Op1->getName(), &I);
Chris Lattnerdbab3862007-03-02 21:28:56 +0000539 AddToWorkList(New);
Chris Lattnerc8802d22003-03-11 00:12:48 +0000540 I.setOperand(0, New);
541 I.setOperand(1, Folded);
542 return true;
Misha Brukmanfd939082005-04-21 23:48:37 +0000543 }
Chris Lattner4f98c562003-03-10 21:43:22 +0000544 }
Chris Lattner4f98c562003-03-10 21:43:22 +0000545 return Changed;
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000546}
Chris Lattner8a2a3112001-12-14 16:52:21 +0000547
Reid Spencere4d87aa2006-12-23 06:05:41 +0000548/// SimplifyCompare - For a CmpInst this function just orders the operands
549/// so that theyare listed from right (least complex) to left (most complex).
550/// This puts constants before unary operators before binary operators.
551bool InstCombiner::SimplifyCompare(CmpInst &I) {
Owen Anderson0a5372e2009-07-13 04:09:18 +0000552 if (getComplexity(Context, I.getOperand(0)) >=
553 getComplexity(Context, I.getOperand(1)))
Reid Spencere4d87aa2006-12-23 06:05:41 +0000554 return false;
555 I.swapOperands();
556 // Compare instructions are not associative so there's nothing else we can do.
557 return true;
558}
559
Chris Lattner8d969642003-03-10 23:06:50 +0000560// dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
561// if the LHS is a constant zero (which is the 'negate' form).
Chris Lattnerb35dde12002-05-06 16:49:18 +0000562//
Dan Gohman186a6362009-08-12 16:04:34 +0000563static inline Value *dyn_castNegVal(Value *V) {
Owen Andersonfa82b6e2009-07-13 22:18:28 +0000564 if (BinaryOperator::isNeg(V))
Chris Lattnera1df33c2005-04-24 07:30:14 +0000565 return BinaryOperator::getNegArgument(V);
Chris Lattner8d969642003-03-10 23:06:50 +0000566
Chris Lattner0ce85802004-12-14 20:08:06 +0000567 // Constants can be considered to be negated values if they can be folded.
568 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
Owen Andersonbaf3c402009-07-29 18:55:55 +0000569 return ConstantExpr::getNeg(C);
Nick Lewycky18b3da62008-05-23 04:54:45 +0000570
571 if (ConstantVector *C = dyn_cast<ConstantVector>(V))
572 if (C->getType()->getElementType()->isInteger())
Owen Andersonbaf3c402009-07-29 18:55:55 +0000573 return ConstantExpr::getNeg(C);
Nick Lewycky18b3da62008-05-23 04:54:45 +0000574
Chris Lattner8d969642003-03-10 23:06:50 +0000575 return 0;
Chris Lattnerb35dde12002-05-06 16:49:18 +0000576}
577
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000578// dyn_castFNegVal - Given a 'fsub' instruction, return the RHS of the
579// instruction if the LHS is a constant negative zero (which is the 'negate'
580// form).
581//
Dan Gohman186a6362009-08-12 16:04:34 +0000582static inline Value *dyn_castFNegVal(Value *V) {
Owen Andersonfa82b6e2009-07-13 22:18:28 +0000583 if (BinaryOperator::isFNeg(V))
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000584 return BinaryOperator::getFNegArgument(V);
585
586 // Constants can be considered to be negated values if they can be folded.
587 if (ConstantFP *C = dyn_cast<ConstantFP>(V))
Owen Andersonbaf3c402009-07-29 18:55:55 +0000588 return ConstantExpr::getFNeg(C);
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000589
590 if (ConstantVector *C = dyn_cast<ConstantVector>(V))
591 if (C->getType()->getElementType()->isFloatingPoint())
Owen Andersonbaf3c402009-07-29 18:55:55 +0000592 return ConstantExpr::getFNeg(C);
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000593
594 return 0;
595}
596
Dan Gohman186a6362009-08-12 16:04:34 +0000597static inline Value *dyn_castNotVal(Value *V) {
Chris Lattner8d969642003-03-10 23:06:50 +0000598 if (BinaryOperator::isNot(V))
Chris Lattnera1df33c2005-04-24 07:30:14 +0000599 return BinaryOperator::getNotArgument(V);
Chris Lattner8d969642003-03-10 23:06:50 +0000600
601 // Constants can be considered to be not'ed values...
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +0000602 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
Dan Gohman186a6362009-08-12 16:04:34 +0000603 return ConstantInt::get(C->getType(), ~C->getValue());
Chris Lattner8d969642003-03-10 23:06:50 +0000604 return 0;
605}
606
Chris Lattnerc8802d22003-03-11 00:12:48 +0000607// dyn_castFoldableMul - If this value is a multiply that can be folded into
608// other computations (because it has a constant operand), return the
Chris Lattner50af16a2004-11-13 19:50:12 +0000609// non-constant operand of the multiply, and set CST to point to the multiplier.
610// Otherwise, return null.
Chris Lattnerc8802d22003-03-11 00:12:48 +0000611//
Dan Gohman186a6362009-08-12 16:04:34 +0000612static inline Value *dyn_castFoldableMul(Value *V, ConstantInt *&CST) {
Chris Lattner42a75512007-01-15 02:27:26 +0000613 if (V->hasOneUse() && V->getType()->isInteger())
Chris Lattner50af16a2004-11-13 19:50:12 +0000614 if (Instruction *I = dyn_cast<Instruction>(V)) {
Chris Lattnerc8802d22003-03-11 00:12:48 +0000615 if (I->getOpcode() == Instruction::Mul)
Chris Lattner50e60c72004-11-15 05:54:07 +0000616 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1))))
Chris Lattnerc8802d22003-03-11 00:12:48 +0000617 return I->getOperand(0);
Chris Lattner50af16a2004-11-13 19:50:12 +0000618 if (I->getOpcode() == Instruction::Shl)
Chris Lattner50e60c72004-11-15 05:54:07 +0000619 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1)))) {
Chris Lattner50af16a2004-11-13 19:50:12 +0000620 // The multiplier is really 1 << CST.
Zhou Sheng97b52c22007-03-29 01:57:21 +0000621 uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +0000622 uint32_t CSTVal = CST->getLimitedValue(BitWidth);
Dan Gohman186a6362009-08-12 16:04:34 +0000623 CST = ConstantInt::get(V->getType()->getContext(),
624 APInt(BitWidth, 1).shl(CSTVal));
Chris Lattner50af16a2004-11-13 19:50:12 +0000625 return I->getOperand(0);
626 }
627 }
Chris Lattnerc8802d22003-03-11 00:12:48 +0000628 return 0;
Chris Lattnera2881962003-02-18 19:28:33 +0000629}
Chris Lattneraf2930e2002-08-14 17:51:49 +0000630
Reid Spencer7177c3a2007-03-25 05:33:51 +0000631/// AddOne - Add one to a ConstantInt
Dan Gohman186a6362009-08-12 16:04:34 +0000632static Constant *AddOne(Constant *C) {
Owen Andersonbaf3c402009-07-29 18:55:55 +0000633 return ConstantExpr::getAdd(C,
Owen Andersoneed707b2009-07-24 23:12:02 +0000634 ConstantInt::get(C->getType(), 1));
Chris Lattner955f3312004-09-28 21:48:02 +0000635}
Reid Spencer7177c3a2007-03-25 05:33:51 +0000636/// SubOne - Subtract one from a ConstantInt
Dan Gohman186a6362009-08-12 16:04:34 +0000637static Constant *SubOne(ConstantInt *C) {
Owen Andersonbaf3c402009-07-29 18:55:55 +0000638 return ConstantExpr::getSub(C,
Owen Andersoneed707b2009-07-24 23:12:02 +0000639 ConstantInt::get(C->getType(), 1));
Chris Lattner955f3312004-09-28 21:48:02 +0000640}
Nick Lewyckye0cfecf2008-02-18 22:48:05 +0000641/// MultiplyOverflows - True if the multiply can not be expressed in an int
642/// this size.
Dan Gohman186a6362009-08-12 16:04:34 +0000643static bool MultiplyOverflows(ConstantInt *C1, ConstantInt *C2, bool sign) {
Nick Lewyckye0cfecf2008-02-18 22:48:05 +0000644 uint32_t W = C1->getBitWidth();
645 APInt LHSExt = C1->getValue(), RHSExt = C2->getValue();
646 if (sign) {
647 LHSExt.sext(W * 2);
648 RHSExt.sext(W * 2);
649 } else {
650 LHSExt.zext(W * 2);
651 RHSExt.zext(W * 2);
652 }
653
654 APInt MulExt = LHSExt * RHSExt;
655
656 if (sign) {
657 APInt Min = APInt::getSignedMinValue(W).sext(W * 2);
658 APInt Max = APInt::getSignedMaxValue(W).sext(W * 2);
659 return MulExt.slt(Min) || MulExt.sgt(Max);
660 } else
661 return MulExt.ugt(APInt::getLowBitsSet(W * 2, W));
662}
Chris Lattner955f3312004-09-28 21:48:02 +0000663
Reid Spencere7816b52007-03-08 01:52:58 +0000664
Chris Lattner255d8912006-02-11 09:31:47 +0000665/// ShrinkDemandedConstant - Check to see if the specified operand of the
666/// specified instruction is a constant integer. If so, check to see if there
667/// are any bits set in the constant that are not demanded. If so, shrink the
668/// constant and return true.
669static bool ShrinkDemandedConstant(Instruction *I, unsigned OpNo,
Dan Gohman186a6362009-08-12 16:04:34 +0000670 APInt Demanded) {
Reid Spencer6b79e2d2007-03-12 17:15:10 +0000671 assert(I && "No instruction?");
672 assert(OpNo < I->getNumOperands() && "Operand index too large");
673
674 // If the operand is not a constant integer, nothing to do.
675 ConstantInt *OpC = dyn_cast<ConstantInt>(I->getOperand(OpNo));
676 if (!OpC) return false;
677
678 // If there are no bits set that aren't demanded, nothing to do.
679 Demanded.zextOrTrunc(OpC->getValue().getBitWidth());
680 if ((~Demanded & OpC->getValue()) == 0)
681 return false;
682
683 // This instruction is producing bits that are not demanded. Shrink the RHS.
684 Demanded &= OpC->getValue();
Dan Gohman186a6362009-08-12 16:04:34 +0000685 I->setOperand(OpNo, ConstantInt::get(OpC->getType(), Demanded));
Reid Spencer6b79e2d2007-03-12 17:15:10 +0000686 return true;
687}
688
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000689// ComputeSignedMinMaxValuesFromKnownBits - Given a signed integer type and a
690// set of known zero and one bits, compute the maximum and minimum values that
691// could have the specified known zero and known one bits, returning them in
692// min/max.
Dan Gohman1c8491e2009-04-25 17:12:48 +0000693static void ComputeSignedMinMaxValuesFromKnownBits(const APInt& KnownZero,
Reid Spencer0460fb32007-03-22 20:36:03 +0000694 const APInt& KnownOne,
695 APInt& Min, APInt& Max) {
Dan Gohman1c8491e2009-04-25 17:12:48 +0000696 assert(KnownZero.getBitWidth() == KnownOne.getBitWidth() &&
697 KnownZero.getBitWidth() == Min.getBitWidth() &&
698 KnownZero.getBitWidth() == Max.getBitWidth() &&
699 "KnownZero, KnownOne and Min, Max must have equal bitwidth.");
Reid Spencer2f549172007-03-25 04:26:16 +0000700 APInt UnknownBits = ~(KnownZero|KnownOne);
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000701
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000702 // The minimum value is when all unknown bits are zeros, EXCEPT for the sign
703 // bit if it is unknown.
704 Min = KnownOne;
705 Max = KnownOne|UnknownBits;
706
Dan Gohman1c8491e2009-04-25 17:12:48 +0000707 if (UnknownBits.isNegative()) { // Sign bit is unknown
708 Min.set(Min.getBitWidth()-1);
709 Max.clear(Max.getBitWidth()-1);
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000710 }
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000711}
712
713// ComputeUnsignedMinMaxValuesFromKnownBits - Given an unsigned integer type and
714// a set of known zero and one bits, compute the maximum and minimum values that
715// could have the specified known zero and known one bits, returning them in
716// min/max.
Dan Gohman1c8491e2009-04-25 17:12:48 +0000717static void ComputeUnsignedMinMaxValuesFromKnownBits(const APInt &KnownZero,
Chris Lattnera9ff5eb2007-08-05 08:47:58 +0000718 const APInt &KnownOne,
719 APInt &Min, APInt &Max) {
Dan Gohman1c8491e2009-04-25 17:12:48 +0000720 assert(KnownZero.getBitWidth() == KnownOne.getBitWidth() &&
721 KnownZero.getBitWidth() == Min.getBitWidth() &&
722 KnownZero.getBitWidth() == Max.getBitWidth() &&
Reid Spencer0460fb32007-03-22 20:36:03 +0000723 "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.");
Reid Spencer2f549172007-03-25 04:26:16 +0000724 APInt UnknownBits = ~(KnownZero|KnownOne);
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000725
726 // The minimum value is when the unknown bits are all zeros.
727 Min = KnownOne;
728 // The maximum value is when the unknown bits are all ones.
729 Max = KnownOne|UnknownBits;
730}
Chris Lattner255d8912006-02-11 09:31:47 +0000731
Chris Lattner886ab6c2009-01-31 08:15:18 +0000732/// SimplifyDemandedInstructionBits - Inst is an integer instruction that
733/// SimplifyDemandedBits knows about. See if the instruction has any
734/// properties that allow us to simplify its operands.
735bool InstCombiner::SimplifyDemandedInstructionBits(Instruction &Inst) {
Dan Gohman6de29f82009-06-15 22:12:54 +0000736 unsigned BitWidth = Inst.getType()->getScalarSizeInBits();
Chris Lattner886ab6c2009-01-31 08:15:18 +0000737 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
738 APInt DemandedMask(APInt::getAllOnesValue(BitWidth));
739
740 Value *V = SimplifyDemandedUseBits(&Inst, DemandedMask,
741 KnownZero, KnownOne, 0);
742 if (V == 0) return false;
743 if (V == &Inst) return true;
744 ReplaceInstUsesWith(Inst, V);
745 return true;
746}
747
748/// SimplifyDemandedBits - This form of SimplifyDemandedBits simplifies the
749/// specified instruction operand if possible, updating it in place. It returns
750/// true if it made any change and false otherwise.
751bool InstCombiner::SimplifyDemandedBits(Use &U, APInt DemandedMask,
752 APInt &KnownZero, APInt &KnownOne,
753 unsigned Depth) {
754 Value *NewVal = SimplifyDemandedUseBits(U.get(), DemandedMask,
755 KnownZero, KnownOne, Depth);
756 if (NewVal == 0) return false;
757 U.set(NewVal);
758 return true;
759}
760
761
762/// SimplifyDemandedUseBits - This function attempts to replace V with a simpler
763/// value based on the demanded bits. When this function is called, it is known
Reid Spencer8cb68342007-03-12 17:25:59 +0000764/// that only the bits set in DemandedMask of the result of V are ever used
765/// downstream. Consequently, depending on the mask and V, it may be possible
766/// to replace V with a constant or one of its operands. In such cases, this
767/// function does the replacement and returns true. In all other cases, it
768/// returns false after analyzing the expression and setting KnownOne and known
Chris Lattner886ab6c2009-01-31 08:15:18 +0000769/// to be one in the expression. KnownZero contains all the bits that are known
Reid Spencer8cb68342007-03-12 17:25:59 +0000770/// to be zero in the expression. These are provided to potentially allow the
771/// caller (which might recursively be SimplifyDemandedBits itself) to simplify
772/// the expression. KnownOne and KnownZero always follow the invariant that
773/// KnownOne & KnownZero == 0. That is, a bit can't be both 1 and 0. Note that
774/// the bits in KnownOne and KnownZero may only be accurate for those bits set
775/// in DemandedMask. Note also that the bitwidth of V, DemandedMask, KnownZero
776/// and KnownOne must all be the same.
Chris Lattner886ab6c2009-01-31 08:15:18 +0000777///
778/// This returns null if it did not change anything and it permits no
779/// simplification. This returns V itself if it did some simplification of V's
780/// operands based on the information about what bits are demanded. This returns
781/// some other non-null value if it found out that V is equal to another value
782/// in the context where the specified bits are demanded, but not for all users.
783Value *InstCombiner::SimplifyDemandedUseBits(Value *V, APInt DemandedMask,
784 APInt &KnownZero, APInt &KnownOne,
785 unsigned Depth) {
Reid Spencer8cb68342007-03-12 17:25:59 +0000786 assert(V != 0 && "Null pointer of Value???");
787 assert(Depth <= 6 && "Limit Search Depth");
788 uint32_t BitWidth = DemandedMask.getBitWidth();
Dan Gohman1c8491e2009-04-25 17:12:48 +0000789 const Type *VTy = V->getType();
790 assert((TD || !isa<PointerType>(VTy)) &&
791 "SimplifyDemandedBits needs to know bit widths!");
Dan Gohman6de29f82009-06-15 22:12:54 +0000792 assert((!TD || TD->getTypeSizeInBits(VTy->getScalarType()) == BitWidth) &&
793 (!VTy->isIntOrIntVector() ||
794 VTy->getScalarSizeInBits() == BitWidth) &&
Dan Gohman1c8491e2009-04-25 17:12:48 +0000795 KnownZero.getBitWidth() == BitWidth &&
Reid Spencer8cb68342007-03-12 17:25:59 +0000796 KnownOne.getBitWidth() == BitWidth &&
Dan Gohman6de29f82009-06-15 22:12:54 +0000797 "Value *V, DemandedMask, KnownZero and KnownOne "
798 "must have same BitWidth");
Reid Spencer8cb68342007-03-12 17:25:59 +0000799 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
800 // We know all of the bits for a constant!
801 KnownOne = CI->getValue() & DemandedMask;
802 KnownZero = ~KnownOne & DemandedMask;
Chris Lattner886ab6c2009-01-31 08:15:18 +0000803 return 0;
Reid Spencer8cb68342007-03-12 17:25:59 +0000804 }
Dan Gohman1c8491e2009-04-25 17:12:48 +0000805 if (isa<ConstantPointerNull>(V)) {
806 // We know all of the bits for a constant!
807 KnownOne.clear();
808 KnownZero = DemandedMask;
809 return 0;
810 }
811
Chris Lattner08d2cc72009-01-31 07:26:06 +0000812 KnownZero.clear();
Zhou Sheng96704452007-03-14 03:21:24 +0000813 KnownOne.clear();
Chris Lattner886ab6c2009-01-31 08:15:18 +0000814 if (DemandedMask == 0) { // Not demanding any bits from V.
815 if (isa<UndefValue>(V))
816 return 0;
Owen Anderson9e9a0d52009-07-30 23:03:37 +0000817 return UndefValue::get(VTy);
Reid Spencer8cb68342007-03-12 17:25:59 +0000818 }
819
Chris Lattner4598c942009-01-31 08:24:16 +0000820 if (Depth == 6) // Limit search depth.
821 return 0;
822
Chris Lattnerd1b5e3f2009-01-31 08:40:03 +0000823 APInt LHSKnownZero(BitWidth, 0), LHSKnownOne(BitWidth, 0);
824 APInt &RHSKnownZero = KnownZero, &RHSKnownOne = KnownOne;
825
Dan Gohman1c8491e2009-04-25 17:12:48 +0000826 Instruction *I = dyn_cast<Instruction>(V);
827 if (!I) {
828 ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
829 return 0; // Only analyze instructions.
830 }
831
Chris Lattner4598c942009-01-31 08:24:16 +0000832 // If there are multiple uses of this value and we aren't at the root, then
833 // we can't do any simplifications of the operands, because DemandedMask
834 // only reflects the bits demanded by *one* of the users.
835 if (Depth != 0 && !I->hasOneUse()) {
Chris Lattnerd1b5e3f2009-01-31 08:40:03 +0000836 // Despite the fact that we can't simplify this instruction in all User's
837 // context, we can at least compute the knownzero/knownone bits, and we can
838 // do simplifications that apply to *just* the one user if we know that
839 // this instruction has a simpler value in that context.
840 if (I->getOpcode() == Instruction::And) {
841 // If either the LHS or the RHS are Zero, the result is zero.
842 ComputeMaskedBits(I->getOperand(1), DemandedMask,
843 RHSKnownZero, RHSKnownOne, Depth+1);
844 ComputeMaskedBits(I->getOperand(0), DemandedMask & ~RHSKnownZero,
845 LHSKnownZero, LHSKnownOne, Depth+1);
846
847 // If all of the demanded bits are known 1 on one side, return the other.
848 // These bits cannot contribute to the result of the 'and' in this
849 // context.
850 if ((DemandedMask & ~LHSKnownZero & RHSKnownOne) ==
851 (DemandedMask & ~LHSKnownZero))
852 return I->getOperand(0);
853 if ((DemandedMask & ~RHSKnownZero & LHSKnownOne) ==
854 (DemandedMask & ~RHSKnownZero))
855 return I->getOperand(1);
856
857 // If all of the demanded bits in the inputs are known zeros, return zero.
858 if ((DemandedMask & (RHSKnownZero|LHSKnownZero)) == DemandedMask)
Owen Andersona7235ea2009-07-31 20:28:14 +0000859 return Constant::getNullValue(VTy);
Chris Lattnerd1b5e3f2009-01-31 08:40:03 +0000860
861 } else if (I->getOpcode() == Instruction::Or) {
862 // We can simplify (X|Y) -> X or Y in the user's context if we know that
863 // only bits from X or Y are demanded.
864
865 // If either the LHS or the RHS are One, the result is One.
866 ComputeMaskedBits(I->getOperand(1), DemandedMask,
867 RHSKnownZero, RHSKnownOne, Depth+1);
868 ComputeMaskedBits(I->getOperand(0), DemandedMask & ~RHSKnownOne,
869 LHSKnownZero, LHSKnownOne, Depth+1);
870
871 // If all of the demanded bits are known zero on one side, return the
872 // other. These bits cannot contribute to the result of the 'or' in this
873 // context.
874 if ((DemandedMask & ~LHSKnownOne & RHSKnownZero) ==
875 (DemandedMask & ~LHSKnownOne))
876 return I->getOperand(0);
877 if ((DemandedMask & ~RHSKnownOne & LHSKnownZero) ==
878 (DemandedMask & ~RHSKnownOne))
879 return I->getOperand(1);
880
881 // If all of the potentially set bits on one side are known to be set on
882 // the other side, just use the 'other' side.
883 if ((DemandedMask & (~RHSKnownZero) & LHSKnownOne) ==
884 (DemandedMask & (~RHSKnownZero)))
885 return I->getOperand(0);
886 if ((DemandedMask & (~LHSKnownZero) & RHSKnownOne) ==
887 (DemandedMask & (~LHSKnownZero)))
888 return I->getOperand(1);
889 }
890
Chris Lattner4598c942009-01-31 08:24:16 +0000891 // Compute the KnownZero/KnownOne bits to simplify things downstream.
892 ComputeMaskedBits(I, DemandedMask, KnownZero, KnownOne, Depth);
893 return 0;
894 }
895
896 // If this is the root being simplified, allow it to have multiple uses,
897 // just set the DemandedMask to all bits so that we can try to simplify the
898 // operands. This allows visitTruncInst (for example) to simplify the
899 // operand of a trunc without duplicating all the logic below.
900 if (Depth == 0 && !V->hasOneUse())
901 DemandedMask = APInt::getAllOnesValue(BitWidth);
902
Reid Spencer8cb68342007-03-12 17:25:59 +0000903 switch (I->getOpcode()) {
Dan Gohman23e8b712008-04-28 17:02:21 +0000904 default:
Chris Lattner886ab6c2009-01-31 08:15:18 +0000905 ComputeMaskedBits(I, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
Dan Gohman23e8b712008-04-28 17:02:21 +0000906 break;
Reid Spencer8cb68342007-03-12 17:25:59 +0000907 case Instruction::And:
908 // If either the LHS or the RHS are Zero, the result is zero.
Chris Lattner886ab6c2009-01-31 08:15:18 +0000909 if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
910 RHSKnownZero, RHSKnownOne, Depth+1) ||
911 SimplifyDemandedBits(I->getOperandUse(0), DemandedMask & ~RHSKnownZero,
Reid Spencer8cb68342007-03-12 17:25:59 +0000912 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000913 return I;
914 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
915 assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +0000916
917 // If all of the demanded bits are known 1 on one side, return the other.
918 // These bits cannot contribute to the result of the 'and'.
919 if ((DemandedMask & ~LHSKnownZero & RHSKnownOne) ==
920 (DemandedMask & ~LHSKnownZero))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000921 return I->getOperand(0);
Reid Spencer8cb68342007-03-12 17:25:59 +0000922 if ((DemandedMask & ~RHSKnownZero & LHSKnownOne) ==
923 (DemandedMask & ~RHSKnownZero))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000924 return I->getOperand(1);
Reid Spencer8cb68342007-03-12 17:25:59 +0000925
926 // If all of the demanded bits in the inputs are known zeros, return zero.
927 if ((DemandedMask & (RHSKnownZero|LHSKnownZero)) == DemandedMask)
Owen Andersona7235ea2009-07-31 20:28:14 +0000928 return Constant::getNullValue(VTy);
Reid Spencer8cb68342007-03-12 17:25:59 +0000929
930 // If the RHS is a constant, see if we can simplify it.
Dan Gohman186a6362009-08-12 16:04:34 +0000931 if (ShrinkDemandedConstant(I, 1, DemandedMask & ~LHSKnownZero))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000932 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +0000933
934 // Output known-1 bits are only known if set in both the LHS & RHS.
935 RHSKnownOne &= LHSKnownOne;
936 // Output known-0 are known to be clear if zero in either the LHS | RHS.
937 RHSKnownZero |= LHSKnownZero;
938 break;
939 case Instruction::Or:
940 // If either the LHS or the RHS are One, the result is One.
Chris Lattner886ab6c2009-01-31 08:15:18 +0000941 if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
942 RHSKnownZero, RHSKnownOne, Depth+1) ||
943 SimplifyDemandedBits(I->getOperandUse(0), DemandedMask & ~RHSKnownOne,
Reid Spencer8cb68342007-03-12 17:25:59 +0000944 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000945 return I;
946 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
947 assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +0000948
949 // If all of the demanded bits are known zero on one side, return the other.
950 // These bits cannot contribute to the result of the 'or'.
951 if ((DemandedMask & ~LHSKnownOne & RHSKnownZero) ==
952 (DemandedMask & ~LHSKnownOne))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000953 return I->getOperand(0);
Reid Spencer8cb68342007-03-12 17:25:59 +0000954 if ((DemandedMask & ~RHSKnownOne & LHSKnownZero) ==
955 (DemandedMask & ~RHSKnownOne))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000956 return I->getOperand(1);
Reid Spencer8cb68342007-03-12 17:25:59 +0000957
958 // If all of the potentially set bits on one side are known to be set on
959 // the other side, just use the 'other' side.
960 if ((DemandedMask & (~RHSKnownZero) & LHSKnownOne) ==
961 (DemandedMask & (~RHSKnownZero)))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000962 return I->getOperand(0);
Reid Spencer8cb68342007-03-12 17:25:59 +0000963 if ((DemandedMask & (~LHSKnownZero) & RHSKnownOne) ==
964 (DemandedMask & (~LHSKnownZero)))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000965 return I->getOperand(1);
Reid Spencer8cb68342007-03-12 17:25:59 +0000966
967 // If the RHS is a constant, see if we can simplify it.
Dan Gohman186a6362009-08-12 16:04:34 +0000968 if (ShrinkDemandedConstant(I, 1, DemandedMask))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000969 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +0000970
971 // Output known-0 bits are only known if clear in both the LHS & RHS.
972 RHSKnownZero &= LHSKnownZero;
973 // Output known-1 are known to be set if set in either the LHS | RHS.
974 RHSKnownOne |= LHSKnownOne;
975 break;
976 case Instruction::Xor: {
Chris Lattner886ab6c2009-01-31 08:15:18 +0000977 if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
978 RHSKnownZero, RHSKnownOne, Depth+1) ||
979 SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
Reid Spencer8cb68342007-03-12 17:25:59 +0000980 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000981 return I;
982 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
983 assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +0000984
985 // If all of the demanded bits are known zero on one side, return the other.
986 // These bits cannot contribute to the result of the 'xor'.
987 if ((DemandedMask & RHSKnownZero) == DemandedMask)
Chris Lattner886ab6c2009-01-31 08:15:18 +0000988 return I->getOperand(0);
Reid Spencer8cb68342007-03-12 17:25:59 +0000989 if ((DemandedMask & LHSKnownZero) == DemandedMask)
Chris Lattner886ab6c2009-01-31 08:15:18 +0000990 return I->getOperand(1);
Reid Spencer8cb68342007-03-12 17:25:59 +0000991
992 // Output known-0 bits are known if clear or set in both the LHS & RHS.
993 APInt KnownZeroOut = (RHSKnownZero & LHSKnownZero) |
994 (RHSKnownOne & LHSKnownOne);
995 // Output known-1 are known to be set if set in only one of the LHS, RHS.
996 APInt KnownOneOut = (RHSKnownZero & LHSKnownOne) |
997 (RHSKnownOne & LHSKnownZero);
998
999 // If all of the demanded bits are known to be zero on one side or the
1000 // other, turn this into an *inclusive* or.
1001 // e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
1002 if ((DemandedMask & ~RHSKnownZero & ~LHSKnownZero) == 0) {
1003 Instruction *Or =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001004 BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1),
Reid Spencer8cb68342007-03-12 17:25:59 +00001005 I->getName());
Chris Lattner886ab6c2009-01-31 08:15:18 +00001006 return InsertNewInstBefore(Or, *I);
Reid Spencer8cb68342007-03-12 17:25:59 +00001007 }
1008
1009 // If all of the demanded bits on one side are known, and all of the set
1010 // bits on that side are also known to be set on the other side, turn this
1011 // into an AND, as we know the bits will be cleared.
1012 // e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
1013 if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask) {
1014 // all known
1015 if ((RHSKnownOne & LHSKnownOne) == RHSKnownOne) {
Dan Gohman43ee5f72009-08-03 22:07:33 +00001016 Constant *AndC = Constant::getIntegerValue(VTy,
1017 ~RHSKnownOne & DemandedMask);
Reid Spencer8cb68342007-03-12 17:25:59 +00001018 Instruction *And =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001019 BinaryOperator::CreateAnd(I->getOperand(0), AndC, "tmp");
Chris Lattner886ab6c2009-01-31 08:15:18 +00001020 return InsertNewInstBefore(And, *I);
Reid Spencer8cb68342007-03-12 17:25:59 +00001021 }
1022 }
1023
1024 // If the RHS is a constant, see if we can simplify it.
1025 // FIXME: for XOR, we prefer to force bits to 1 if they will make a -1.
Dan Gohman186a6362009-08-12 16:04:34 +00001026 if (ShrinkDemandedConstant(I, 1, DemandedMask))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001027 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001028
1029 RHSKnownZero = KnownZeroOut;
1030 RHSKnownOne = KnownOneOut;
1031 break;
1032 }
1033 case Instruction::Select:
Chris Lattner886ab6c2009-01-31 08:15:18 +00001034 if (SimplifyDemandedBits(I->getOperandUse(2), DemandedMask,
1035 RHSKnownZero, RHSKnownOne, Depth+1) ||
1036 SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
Reid Spencer8cb68342007-03-12 17:25:59 +00001037 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001038 return I;
1039 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
1040 assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001041
1042 // If the operands are constants, see if we can simplify them.
Dan Gohman186a6362009-08-12 16:04:34 +00001043 if (ShrinkDemandedConstant(I, 1, DemandedMask) ||
1044 ShrinkDemandedConstant(I, 2, DemandedMask))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001045 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001046
1047 // Only known if known in both the LHS and RHS.
1048 RHSKnownOne &= LHSKnownOne;
1049 RHSKnownZero &= LHSKnownZero;
1050 break;
1051 case Instruction::Trunc: {
Dan Gohman6de29f82009-06-15 22:12:54 +00001052 unsigned truncBf = I->getOperand(0)->getType()->getScalarSizeInBits();
Zhou Sheng01542f32007-03-29 02:26:30 +00001053 DemandedMask.zext(truncBf);
1054 RHSKnownZero.zext(truncBf);
1055 RHSKnownOne.zext(truncBf);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001056 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
Zhou Sheng01542f32007-03-29 02:26:30 +00001057 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001058 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001059 DemandedMask.trunc(BitWidth);
1060 RHSKnownZero.trunc(BitWidth);
1061 RHSKnownOne.trunc(BitWidth);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001062 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001063 break;
1064 }
1065 case Instruction::BitCast:
Dan Gohman6cc18fe2009-07-01 21:38:46 +00001066 if (!I->getOperand(0)->getType()->isIntOrIntVector())
Chris Lattner886ab6c2009-01-31 08:15:18 +00001067 return false; // vector->int or fp->int?
Dan Gohman6cc18fe2009-07-01 21:38:46 +00001068
1069 if (const VectorType *DstVTy = dyn_cast<VectorType>(I->getType())) {
1070 if (const VectorType *SrcVTy =
1071 dyn_cast<VectorType>(I->getOperand(0)->getType())) {
1072 if (DstVTy->getNumElements() != SrcVTy->getNumElements())
1073 // Don't touch a bitcast between vectors of different element counts.
1074 return false;
1075 } else
1076 // Don't touch a scalar-to-vector bitcast.
1077 return false;
1078 } else if (isa<VectorType>(I->getOperand(0)->getType()))
1079 // Don't touch a vector-to-scalar bitcast.
1080 return false;
1081
Chris Lattner886ab6c2009-01-31 08:15:18 +00001082 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
Reid Spencer8cb68342007-03-12 17:25:59 +00001083 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001084 return I;
1085 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001086 break;
1087 case Instruction::ZExt: {
1088 // Compute the bits in the result that are not present in the input.
Dan Gohman6de29f82009-06-15 22:12:54 +00001089 unsigned SrcBitWidth =I->getOperand(0)->getType()->getScalarSizeInBits();
Reid Spencer8cb68342007-03-12 17:25:59 +00001090
Zhou Shengd48653a2007-03-29 04:45:55 +00001091 DemandedMask.trunc(SrcBitWidth);
1092 RHSKnownZero.trunc(SrcBitWidth);
1093 RHSKnownOne.trunc(SrcBitWidth);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001094 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
Zhou Sheng01542f32007-03-29 02:26:30 +00001095 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001096 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001097 DemandedMask.zext(BitWidth);
1098 RHSKnownZero.zext(BitWidth);
1099 RHSKnownOne.zext(BitWidth);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001100 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001101 // The top bits are known to be zero.
Zhou Sheng01542f32007-03-29 02:26:30 +00001102 RHSKnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001103 break;
1104 }
1105 case Instruction::SExt: {
1106 // Compute the bits in the result that are not present in the input.
Dan Gohman6de29f82009-06-15 22:12:54 +00001107 unsigned SrcBitWidth =I->getOperand(0)->getType()->getScalarSizeInBits();
Reid Spencer8cb68342007-03-12 17:25:59 +00001108
Reid Spencer8cb68342007-03-12 17:25:59 +00001109 APInt InputDemandedBits = DemandedMask &
Zhou Sheng01542f32007-03-29 02:26:30 +00001110 APInt::getLowBitsSet(BitWidth, SrcBitWidth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001111
Zhou Sheng01542f32007-03-29 02:26:30 +00001112 APInt NewBits(APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth));
Reid Spencer8cb68342007-03-12 17:25:59 +00001113 // If any of the sign extended bits are demanded, we know that the sign
1114 // bit is demanded.
1115 if ((NewBits & DemandedMask) != 0)
Zhou Sheng4a1822a2007-04-02 13:45:30 +00001116 InputDemandedBits.set(SrcBitWidth-1);
Reid Spencer8cb68342007-03-12 17:25:59 +00001117
Zhou Shengd48653a2007-03-29 04:45:55 +00001118 InputDemandedBits.trunc(SrcBitWidth);
1119 RHSKnownZero.trunc(SrcBitWidth);
1120 RHSKnownOne.trunc(SrcBitWidth);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001121 if (SimplifyDemandedBits(I->getOperandUse(0), InputDemandedBits,
Zhou Sheng01542f32007-03-29 02:26:30 +00001122 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001123 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001124 InputDemandedBits.zext(BitWidth);
1125 RHSKnownZero.zext(BitWidth);
1126 RHSKnownOne.zext(BitWidth);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001127 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001128
1129 // If the sign bit of the input is known set or clear, then we know the
1130 // top bits of the result.
1131
1132 // If the input sign bit is known zero, or if the NewBits are not demanded
1133 // convert this into a zero extension.
Chris Lattner886ab6c2009-01-31 08:15:18 +00001134 if (RHSKnownZero[SrcBitWidth-1] || (NewBits & ~DemandedMask) == NewBits) {
Reid Spencer8cb68342007-03-12 17:25:59 +00001135 // Convert to ZExt cast
Chris Lattner886ab6c2009-01-31 08:15:18 +00001136 CastInst *NewCast = new ZExtInst(I->getOperand(0), VTy, I->getName());
1137 return InsertNewInstBefore(NewCast, *I);
Zhou Sheng01542f32007-03-29 02:26:30 +00001138 } else if (RHSKnownOne[SrcBitWidth-1]) { // Input sign bit known set
Reid Spencer8cb68342007-03-12 17:25:59 +00001139 RHSKnownOne |= NewBits;
Reid Spencer8cb68342007-03-12 17:25:59 +00001140 }
1141 break;
1142 }
1143 case Instruction::Add: {
1144 // Figure out what the input bits are. If the top bits of the and result
1145 // are not demanded, then the add doesn't demand them from its input
1146 // either.
Chris Lattner886ab6c2009-01-31 08:15:18 +00001147 unsigned NLZ = DemandedMask.countLeadingZeros();
Reid Spencer8cb68342007-03-12 17:25:59 +00001148
1149 // If there is a constant on the RHS, there are a variety of xformations
1150 // we can do.
1151 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
1152 // If null, this should be simplified elsewhere. Some of the xforms here
1153 // won't work if the RHS is zero.
1154 if (RHS->isZero())
1155 break;
1156
1157 // If the top bit of the output is demanded, demand everything from the
1158 // input. Otherwise, we demand all the input bits except NLZ top bits.
Zhou Sheng01542f32007-03-29 02:26:30 +00001159 APInt InDemandedBits(APInt::getLowBitsSet(BitWidth, BitWidth - NLZ));
Reid Spencer8cb68342007-03-12 17:25:59 +00001160
1161 // Find information about known zero/one bits in the input.
Chris Lattner886ab6c2009-01-31 08:15:18 +00001162 if (SimplifyDemandedBits(I->getOperandUse(0), InDemandedBits,
Reid Spencer8cb68342007-03-12 17:25:59 +00001163 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001164 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001165
1166 // If the RHS of the add has bits set that can't affect the input, reduce
1167 // the constant.
Dan Gohman186a6362009-08-12 16:04:34 +00001168 if (ShrinkDemandedConstant(I, 1, InDemandedBits))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001169 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001170
1171 // Avoid excess work.
1172 if (LHSKnownZero == 0 && LHSKnownOne == 0)
1173 break;
1174
1175 // Turn it into OR if input bits are zero.
1176 if ((LHSKnownZero & RHS->getValue()) == RHS->getValue()) {
1177 Instruction *Or =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001178 BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1),
Reid Spencer8cb68342007-03-12 17:25:59 +00001179 I->getName());
Chris Lattner886ab6c2009-01-31 08:15:18 +00001180 return InsertNewInstBefore(Or, *I);
Reid Spencer8cb68342007-03-12 17:25:59 +00001181 }
1182
1183 // We can say something about the output known-zero and known-one bits,
1184 // depending on potential carries from the input constant and the
1185 // unknowns. For example if the LHS is known to have at most the 0x0F0F0
1186 // bits set and the RHS constant is 0x01001, then we know we have a known
1187 // one mask of 0x00001 and a known zero mask of 0xE0F0E.
1188
1189 // To compute this, we first compute the potential carry bits. These are
1190 // the bits which may be modified. I'm not aware of a better way to do
1191 // this scan.
Chris Lattner886ab6c2009-01-31 08:15:18 +00001192 const APInt &RHSVal = RHS->getValue();
Zhou Shengb9cb95f2007-03-31 02:38:39 +00001193 APInt CarryBits((~LHSKnownZero + RHSVal) ^ (~LHSKnownZero ^ RHSVal));
Reid Spencer8cb68342007-03-12 17:25:59 +00001194
1195 // Now that we know which bits have carries, compute the known-1/0 sets.
1196
1197 // Bits are known one if they are known zero in one operand and one in the
1198 // other, and there is no input carry.
1199 RHSKnownOne = ((LHSKnownZero & RHSVal) |
1200 (LHSKnownOne & ~RHSVal)) & ~CarryBits;
1201
1202 // Bits are known zero if they are known zero in both operands and there
1203 // is no input carry.
1204 RHSKnownZero = LHSKnownZero & ~RHSVal & ~CarryBits;
1205 } else {
1206 // If the high-bits of this ADD are not demanded, then it does not demand
1207 // the high bits of its LHS or RHS.
Zhou Sheng01542f32007-03-29 02:26:30 +00001208 if (DemandedMask[BitWidth-1] == 0) {
Reid Spencer8cb68342007-03-12 17:25:59 +00001209 // Right fill the mask of bits for this ADD to demand the most
1210 // significant bit and all those below it.
Zhou Sheng01542f32007-03-29 02:26:30 +00001211 APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
Chris Lattner886ab6c2009-01-31 08:15:18 +00001212 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedFromOps,
1213 LHSKnownZero, LHSKnownOne, Depth+1) ||
1214 SimplifyDemandedBits(I->getOperandUse(1), DemandedFromOps,
Reid Spencer8cb68342007-03-12 17:25:59 +00001215 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001216 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001217 }
1218 }
1219 break;
1220 }
1221 case Instruction::Sub:
1222 // If the high-bits of this SUB are not demanded, then it does not demand
1223 // the high bits of its LHS or RHS.
Zhou Sheng01542f32007-03-29 02:26:30 +00001224 if (DemandedMask[BitWidth-1] == 0) {
Reid Spencer8cb68342007-03-12 17:25:59 +00001225 // Right fill the mask of bits for this SUB to demand the most
1226 // significant bit and all those below it.
Zhou Sheng4351c642007-04-02 08:20:41 +00001227 uint32_t NLZ = DemandedMask.countLeadingZeros();
Zhou Sheng01542f32007-03-29 02:26:30 +00001228 APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
Chris Lattner886ab6c2009-01-31 08:15:18 +00001229 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedFromOps,
1230 LHSKnownZero, LHSKnownOne, Depth+1) ||
1231 SimplifyDemandedBits(I->getOperandUse(1), DemandedFromOps,
Reid Spencer8cb68342007-03-12 17:25:59 +00001232 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001233 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001234 }
Dan Gohman23e8b712008-04-28 17:02:21 +00001235 // Otherwise just hand the sub off to ComputeMaskedBits to fill in
1236 // the known zeros and ones.
1237 ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001238 break;
1239 case Instruction::Shl:
1240 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00001241 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
Zhou Sheng01542f32007-03-29 02:26:30 +00001242 APInt DemandedMaskIn(DemandedMask.lshr(ShiftAmt));
Chris Lattner886ab6c2009-01-31 08:15:18 +00001243 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn,
Reid Spencer8cb68342007-03-12 17:25:59 +00001244 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001245 return I;
1246 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001247 RHSKnownZero <<= ShiftAmt;
1248 RHSKnownOne <<= ShiftAmt;
1249 // low bits known zero.
Zhou Shengadc14952007-03-14 09:07:33 +00001250 if (ShiftAmt)
Zhou Shenge9e03f62007-03-28 15:02:20 +00001251 RHSKnownZero |= APInt::getLowBitsSet(BitWidth, ShiftAmt);
Reid Spencer8cb68342007-03-12 17:25:59 +00001252 }
1253 break;
1254 case Instruction::LShr:
1255 // For a logical shift right
1256 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00001257 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001258
Reid Spencer8cb68342007-03-12 17:25:59 +00001259 // Unsigned shift right.
Zhou Sheng01542f32007-03-29 02:26:30 +00001260 APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
Chris Lattner886ab6c2009-01-31 08:15:18 +00001261 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn,
Reid Spencer8cb68342007-03-12 17:25:59 +00001262 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001263 return I;
1264 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001265 RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1266 RHSKnownOne = APIntOps::lshr(RHSKnownOne, ShiftAmt);
Zhou Shengadc14952007-03-14 09:07:33 +00001267 if (ShiftAmt) {
1268 // Compute the new bits that are at the top now.
Zhou Sheng01542f32007-03-29 02:26:30 +00001269 APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
Zhou Shengadc14952007-03-14 09:07:33 +00001270 RHSKnownZero |= HighBits; // high bits known zero.
1271 }
Reid Spencer8cb68342007-03-12 17:25:59 +00001272 }
1273 break;
1274 case Instruction::AShr:
1275 // If this is an arithmetic shift right and only the low-bit is set, we can
1276 // always convert this into a logical shr, even if the shift amount is
1277 // variable. The low bit of the shift cannot be an input sign bit unless
1278 // the shift amount is >= the size of the datatype, which is undefined.
1279 if (DemandedMask == 1) {
1280 // Perform the logical shift right.
Chris Lattner886ab6c2009-01-31 08:15:18 +00001281 Instruction *NewVal = BinaryOperator::CreateLShr(
Reid Spencer8cb68342007-03-12 17:25:59 +00001282 I->getOperand(0), I->getOperand(1), I->getName());
Chris Lattner886ab6c2009-01-31 08:15:18 +00001283 return InsertNewInstBefore(NewVal, *I);
Reid Spencer8cb68342007-03-12 17:25:59 +00001284 }
Chris Lattner4241e4d2007-07-15 20:54:51 +00001285
1286 // If the sign bit is the only bit demanded by this ashr, then there is no
1287 // need to do it, the shift doesn't change the high bit.
1288 if (DemandedMask.isSignBit())
Chris Lattner886ab6c2009-01-31 08:15:18 +00001289 return I->getOperand(0);
Reid Spencer8cb68342007-03-12 17:25:59 +00001290
1291 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng302748d2007-03-30 17:20:39 +00001292 uint32_t ShiftAmt = SA->getLimitedValue(BitWidth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001293
Reid Spencer8cb68342007-03-12 17:25:59 +00001294 // Signed shift right.
Zhou Sheng01542f32007-03-29 02:26:30 +00001295 APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
Lauro Ramos Venanciod0499af2007-06-06 17:08:48 +00001296 // If any of the "high bits" are demanded, we should set the sign bit as
1297 // demanded.
1298 if (DemandedMask.countLeadingZeros() <= ShiftAmt)
1299 DemandedMaskIn.set(BitWidth-1);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001300 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn,
Reid Spencer8cb68342007-03-12 17:25:59 +00001301 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001302 return I;
1303 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001304 // Compute the new bits that are at the top now.
Zhou Sheng01542f32007-03-29 02:26:30 +00001305 APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
Reid Spencer8cb68342007-03-12 17:25:59 +00001306 RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1307 RHSKnownOne = APIntOps::lshr(RHSKnownOne, ShiftAmt);
1308
1309 // Handle the sign bits.
1310 APInt SignBit(APInt::getSignBit(BitWidth));
1311 // Adjust to where it is now in the mask.
1312 SignBit = APIntOps::lshr(SignBit, ShiftAmt);
1313
1314 // If the input sign bit is known to be zero, or if none of the top bits
1315 // are demanded, turn this into an unsigned shift right.
Zhou Shengcc419402008-06-06 08:32:05 +00001316 if (BitWidth <= ShiftAmt || RHSKnownZero[BitWidth-ShiftAmt-1] ||
Reid Spencer8cb68342007-03-12 17:25:59 +00001317 (HighBits & ~DemandedMask) == HighBits) {
1318 // Perform the logical shift right.
Chris Lattner886ab6c2009-01-31 08:15:18 +00001319 Instruction *NewVal = BinaryOperator::CreateLShr(
Reid Spencer8cb68342007-03-12 17:25:59 +00001320 I->getOperand(0), SA, I->getName());
Chris Lattner886ab6c2009-01-31 08:15:18 +00001321 return InsertNewInstBefore(NewVal, *I);
Reid Spencer8cb68342007-03-12 17:25:59 +00001322 } else if ((RHSKnownOne & SignBit) != 0) { // New bits are known one.
1323 RHSKnownOne |= HighBits;
1324 }
1325 }
1326 break;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001327 case Instruction::SRem:
1328 if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
Nick Lewycky8e394322008-11-02 02:41:50 +00001329 APInt RA = Rem->getValue().abs();
1330 if (RA.isPowerOf2()) {
Eli Friedmana999a512009-06-17 02:57:36 +00001331 if (DemandedMask.ult(RA)) // srem won't affect demanded bits
Chris Lattner886ab6c2009-01-31 08:15:18 +00001332 return I->getOperand(0);
Nick Lewycky3ac9e102008-07-12 05:04:38 +00001333
Nick Lewycky8e394322008-11-02 02:41:50 +00001334 APInt LowBits = RA - 1;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001335 APInt Mask2 = LowBits | APInt::getSignBit(BitWidth);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001336 if (SimplifyDemandedBits(I->getOperandUse(0), Mask2,
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001337 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001338 return I;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001339
1340 if (LHSKnownZero[BitWidth-1] || ((LHSKnownZero & LowBits) == LowBits))
1341 LHSKnownZero |= ~LowBits;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001342
1343 KnownZero |= LHSKnownZero & DemandedMask;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001344
Chris Lattner886ab6c2009-01-31 08:15:18 +00001345 assert(!(KnownZero & KnownOne) && "Bits known to be one AND zero?");
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001346 }
1347 }
1348 break;
Dan Gohman23e8b712008-04-28 17:02:21 +00001349 case Instruction::URem: {
Dan Gohman23e8b712008-04-28 17:02:21 +00001350 APInt KnownZero2(BitWidth, 0), KnownOne2(BitWidth, 0);
1351 APInt AllOnes = APInt::getAllOnesValue(BitWidth);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001352 if (SimplifyDemandedBits(I->getOperandUse(0), AllOnes,
1353 KnownZero2, KnownOne2, Depth+1) ||
1354 SimplifyDemandedBits(I->getOperandUse(1), AllOnes,
Dan Gohmane85b7582008-05-01 19:13:24 +00001355 KnownZero2, KnownOne2, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001356 return I;
Dan Gohmane85b7582008-05-01 19:13:24 +00001357
Chris Lattner455e9ab2009-01-21 18:09:24 +00001358 unsigned Leaders = KnownZero2.countLeadingOnes();
Dan Gohman23e8b712008-04-28 17:02:21 +00001359 Leaders = std::max(Leaders,
1360 KnownZero2.countLeadingOnes());
1361 KnownZero = APInt::getHighBitsSet(BitWidth, Leaders) & DemandedMask;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001362 break;
Reid Spencer8cb68342007-03-12 17:25:59 +00001363 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00001364 case Instruction::Call:
1365 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
1366 switch (II->getIntrinsicID()) {
1367 default: break;
1368 case Intrinsic::bswap: {
1369 // If the only bits demanded come from one byte of the bswap result,
1370 // just shift the input byte into position to eliminate the bswap.
1371 unsigned NLZ = DemandedMask.countLeadingZeros();
1372 unsigned NTZ = DemandedMask.countTrailingZeros();
1373
1374 // Round NTZ down to the next byte. If we have 11 trailing zeros, then
1375 // we need all the bits down to bit 8. Likewise, round NLZ. If we
1376 // have 14 leading zeros, round to 8.
1377 NLZ &= ~7;
1378 NTZ &= ~7;
1379 // If we need exactly one byte, we can do this transformation.
1380 if (BitWidth-NLZ-NTZ == 8) {
1381 unsigned ResultBit = NTZ;
1382 unsigned InputBit = BitWidth-NTZ-8;
1383
1384 // Replace this with either a left or right shift to get the byte into
1385 // the right place.
1386 Instruction *NewVal;
1387 if (InputBit > ResultBit)
1388 NewVal = BinaryOperator::CreateLShr(I->getOperand(1),
Owen Andersoneed707b2009-07-24 23:12:02 +00001389 ConstantInt::get(I->getType(), InputBit-ResultBit));
Chris Lattner0521e3c2008-06-18 04:33:20 +00001390 else
1391 NewVal = BinaryOperator::CreateShl(I->getOperand(1),
Owen Andersoneed707b2009-07-24 23:12:02 +00001392 ConstantInt::get(I->getType(), ResultBit-InputBit));
Chris Lattner0521e3c2008-06-18 04:33:20 +00001393 NewVal->takeName(I);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001394 return InsertNewInstBefore(NewVal, *I);
Chris Lattner0521e3c2008-06-18 04:33:20 +00001395 }
1396
1397 // TODO: Could compute known zero/one bits based on the input.
1398 break;
1399 }
1400 }
1401 }
Chris Lattner6c3bfba2008-06-18 18:11:55 +00001402 ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
Chris Lattner0521e3c2008-06-18 04:33:20 +00001403 break;
Dan Gohman23e8b712008-04-28 17:02:21 +00001404 }
Reid Spencer8cb68342007-03-12 17:25:59 +00001405
1406 // If the client is only demanding bits that we know, return the known
1407 // constant.
Dan Gohman43ee5f72009-08-03 22:07:33 +00001408 if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask)
1409 return Constant::getIntegerValue(VTy, RHSKnownOne);
Reid Spencer8cb68342007-03-12 17:25:59 +00001410 return false;
1411}
1412
Chris Lattner867b99f2006-10-05 06:55:50 +00001413
Mon P Wangaeb06d22008-11-10 04:46:22 +00001414/// SimplifyDemandedVectorElts - The specified value produces a vector with
Evan Cheng388df622009-02-03 10:05:09 +00001415/// any number of elements. DemandedElts contains the set of elements that are
Chris Lattner867b99f2006-10-05 06:55:50 +00001416/// actually used by the caller. This method analyzes which elements of the
1417/// operand are undef and returns that information in UndefElts.
1418///
1419/// If the information about demanded elements can be used to simplify the
1420/// operation, the operation is simplified, then the resultant value is
1421/// returned. This returns null if no change was made.
Evan Cheng388df622009-02-03 10:05:09 +00001422Value *InstCombiner::SimplifyDemandedVectorElts(Value *V, APInt DemandedElts,
1423 APInt& UndefElts,
Chris Lattner867b99f2006-10-05 06:55:50 +00001424 unsigned Depth) {
Reid Spencer9d6565a2007-02-15 02:26:10 +00001425 unsigned VWidth = cast<VectorType>(V->getType())->getNumElements();
Evan Cheng388df622009-02-03 10:05:09 +00001426 APInt EltMask(APInt::getAllOnesValue(VWidth));
Dan Gohman488fbfc2008-09-09 18:11:14 +00001427 assert((DemandedElts & ~EltMask) == 0 && "Invalid DemandedElts!");
Chris Lattner867b99f2006-10-05 06:55:50 +00001428
1429 if (isa<UndefValue>(V)) {
1430 // If the entire vector is undefined, just return this info.
1431 UndefElts = EltMask;
1432 return 0;
1433 } else if (DemandedElts == 0) { // If nothing is demanded, provide undef.
1434 UndefElts = EltMask;
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001435 return UndefValue::get(V->getType());
Chris Lattner867b99f2006-10-05 06:55:50 +00001436 }
Mon P Wangaeb06d22008-11-10 04:46:22 +00001437
Chris Lattner867b99f2006-10-05 06:55:50 +00001438 UndefElts = 0;
Reid Spencer9d6565a2007-02-15 02:26:10 +00001439 if (ConstantVector *CP = dyn_cast<ConstantVector>(V)) {
1440 const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001441 Constant *Undef = UndefValue::get(EltTy);
Chris Lattner867b99f2006-10-05 06:55:50 +00001442
1443 std::vector<Constant*> Elts;
1444 for (unsigned i = 0; i != VWidth; ++i)
Evan Cheng388df622009-02-03 10:05:09 +00001445 if (!DemandedElts[i]) { // If not demanded, set to undef.
Chris Lattner867b99f2006-10-05 06:55:50 +00001446 Elts.push_back(Undef);
Evan Cheng388df622009-02-03 10:05:09 +00001447 UndefElts.set(i);
Chris Lattner867b99f2006-10-05 06:55:50 +00001448 } else if (isa<UndefValue>(CP->getOperand(i))) { // Already undef.
1449 Elts.push_back(Undef);
Evan Cheng388df622009-02-03 10:05:09 +00001450 UndefElts.set(i);
Chris Lattner867b99f2006-10-05 06:55:50 +00001451 } else { // Otherwise, defined.
1452 Elts.push_back(CP->getOperand(i));
1453 }
Mon P Wangaeb06d22008-11-10 04:46:22 +00001454
Chris Lattner867b99f2006-10-05 06:55:50 +00001455 // If we changed the constant, return it.
Owen Andersonaf7ec972009-07-28 21:19:26 +00001456 Constant *NewCP = ConstantVector::get(Elts);
Chris Lattner867b99f2006-10-05 06:55:50 +00001457 return NewCP != CP ? NewCP : 0;
1458 } else if (isa<ConstantAggregateZero>(V)) {
Reid Spencer9d6565a2007-02-15 02:26:10 +00001459 // Simplify the CAZ to a ConstantVector where the non-demanded elements are
Chris Lattner867b99f2006-10-05 06:55:50 +00001460 // set to undef.
Mon P Wange0b436a2008-11-06 22:52:21 +00001461
1462 // Check if this is identity. If so, return 0 since we are not simplifying
1463 // anything.
1464 if (DemandedElts == ((1ULL << VWidth) -1))
1465 return 0;
1466
Reid Spencer9d6565a2007-02-15 02:26:10 +00001467 const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
Owen Andersona7235ea2009-07-31 20:28:14 +00001468 Constant *Zero = Constant::getNullValue(EltTy);
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001469 Constant *Undef = UndefValue::get(EltTy);
Chris Lattner867b99f2006-10-05 06:55:50 +00001470 std::vector<Constant*> Elts;
Evan Cheng388df622009-02-03 10:05:09 +00001471 for (unsigned i = 0; i != VWidth; ++i) {
1472 Constant *Elt = DemandedElts[i] ? Zero : Undef;
1473 Elts.push_back(Elt);
1474 }
Chris Lattner867b99f2006-10-05 06:55:50 +00001475 UndefElts = DemandedElts ^ EltMask;
Owen Andersonaf7ec972009-07-28 21:19:26 +00001476 return ConstantVector::get(Elts);
Chris Lattner867b99f2006-10-05 06:55:50 +00001477 }
1478
Dan Gohman488fbfc2008-09-09 18:11:14 +00001479 // Limit search depth.
1480 if (Depth == 10)
Dan Gohman2fe4d0a2009-04-25 17:28:45 +00001481 return 0;
Dan Gohman488fbfc2008-09-09 18:11:14 +00001482
1483 // If multiple users are using the root value, procede with
1484 // simplification conservatively assuming that all elements
1485 // are needed.
1486 if (!V->hasOneUse()) {
1487 // Quit if we find multiple users of a non-root value though.
1488 // They'll be handled when it's their turn to be visited by
1489 // the main instcombine process.
1490 if (Depth != 0)
Chris Lattner867b99f2006-10-05 06:55:50 +00001491 // TODO: Just compute the UndefElts information recursively.
Dan Gohman2fe4d0a2009-04-25 17:28:45 +00001492 return 0;
Dan Gohman488fbfc2008-09-09 18:11:14 +00001493
1494 // Conservatively assume that all elements are needed.
1495 DemandedElts = EltMask;
Chris Lattner867b99f2006-10-05 06:55:50 +00001496 }
1497
1498 Instruction *I = dyn_cast<Instruction>(V);
Dan Gohman2fe4d0a2009-04-25 17:28:45 +00001499 if (!I) return 0; // Only analyze instructions.
Chris Lattner867b99f2006-10-05 06:55:50 +00001500
1501 bool MadeChange = false;
Evan Cheng388df622009-02-03 10:05:09 +00001502 APInt UndefElts2(VWidth, 0);
Chris Lattner867b99f2006-10-05 06:55:50 +00001503 Value *TmpV;
1504 switch (I->getOpcode()) {
1505 default: break;
1506
1507 case Instruction::InsertElement: {
1508 // If this is a variable index, we don't know which element it overwrites.
1509 // demand exactly the same input as we produce.
Reid Spencerb83eb642006-10-20 07:07:24 +00001510 ConstantInt *Idx = dyn_cast<ConstantInt>(I->getOperand(2));
Chris Lattner867b99f2006-10-05 06:55:50 +00001511 if (Idx == 0) {
1512 // Note that we can't propagate undef elt info, because we don't know
1513 // which elt is getting updated.
1514 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1515 UndefElts2, Depth+1);
1516 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1517 break;
1518 }
1519
1520 // If this is inserting an element that isn't demanded, remove this
1521 // insertelement.
Reid Spencerb83eb642006-10-20 07:07:24 +00001522 unsigned IdxNo = Idx->getZExtValue();
Evan Cheng388df622009-02-03 10:05:09 +00001523 if (IdxNo >= VWidth || !DemandedElts[IdxNo])
Chris Lattner867b99f2006-10-05 06:55:50 +00001524 return AddSoonDeadInstToWorklist(*I, 0);
1525
1526 // Otherwise, the element inserted overwrites whatever was there, so the
1527 // input demanded set is simpler than the output set.
Evan Cheng388df622009-02-03 10:05:09 +00001528 APInt DemandedElts2 = DemandedElts;
1529 DemandedElts2.clear(IdxNo);
1530 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts2,
Chris Lattner867b99f2006-10-05 06:55:50 +00001531 UndefElts, Depth+1);
1532 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1533
1534 // The inserted element is defined.
Evan Cheng388df622009-02-03 10:05:09 +00001535 UndefElts.clear(IdxNo);
Dan Gohman488fbfc2008-09-09 18:11:14 +00001536 break;
1537 }
1538 case Instruction::ShuffleVector: {
1539 ShuffleVectorInst *Shuffle = cast<ShuffleVectorInst>(I);
Mon P Wangaeb06d22008-11-10 04:46:22 +00001540 uint64_t LHSVWidth =
1541 cast<VectorType>(Shuffle->getOperand(0)->getType())->getNumElements();
Evan Cheng388df622009-02-03 10:05:09 +00001542 APInt LeftDemanded(LHSVWidth, 0), RightDemanded(LHSVWidth, 0);
Dan Gohman488fbfc2008-09-09 18:11:14 +00001543 for (unsigned i = 0; i < VWidth; i++) {
Evan Cheng388df622009-02-03 10:05:09 +00001544 if (DemandedElts[i]) {
Dan Gohman488fbfc2008-09-09 18:11:14 +00001545 unsigned MaskVal = Shuffle->getMaskValue(i);
1546 if (MaskVal != -1u) {
Mon P Wangaeb06d22008-11-10 04:46:22 +00001547 assert(MaskVal < LHSVWidth * 2 &&
Dan Gohman488fbfc2008-09-09 18:11:14 +00001548 "shufflevector mask index out of range!");
Mon P Wangaeb06d22008-11-10 04:46:22 +00001549 if (MaskVal < LHSVWidth)
Evan Cheng388df622009-02-03 10:05:09 +00001550 LeftDemanded.set(MaskVal);
Dan Gohman488fbfc2008-09-09 18:11:14 +00001551 else
Evan Cheng388df622009-02-03 10:05:09 +00001552 RightDemanded.set(MaskVal - LHSVWidth);
Dan Gohman488fbfc2008-09-09 18:11:14 +00001553 }
1554 }
1555 }
1556
Nate Begeman7b254672009-02-11 22:36:25 +00001557 APInt UndefElts4(LHSVWidth, 0);
Dan Gohman488fbfc2008-09-09 18:11:14 +00001558 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), LeftDemanded,
Nate Begeman7b254672009-02-11 22:36:25 +00001559 UndefElts4, Depth+1);
Dan Gohman488fbfc2008-09-09 18:11:14 +00001560 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1561
Nate Begeman7b254672009-02-11 22:36:25 +00001562 APInt UndefElts3(LHSVWidth, 0);
Dan Gohman488fbfc2008-09-09 18:11:14 +00001563 TmpV = SimplifyDemandedVectorElts(I->getOperand(1), RightDemanded,
1564 UndefElts3, Depth+1);
1565 if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1566
1567 bool NewUndefElts = false;
1568 for (unsigned i = 0; i < VWidth; i++) {
1569 unsigned MaskVal = Shuffle->getMaskValue(i);
Dan Gohmancb893092008-09-10 01:09:32 +00001570 if (MaskVal == -1u) {
Evan Cheng388df622009-02-03 10:05:09 +00001571 UndefElts.set(i);
Mon P Wangaeb06d22008-11-10 04:46:22 +00001572 } else if (MaskVal < LHSVWidth) {
Nate Begeman7b254672009-02-11 22:36:25 +00001573 if (UndefElts4[MaskVal]) {
Evan Cheng388df622009-02-03 10:05:09 +00001574 NewUndefElts = true;
1575 UndefElts.set(i);
1576 }
Dan Gohman488fbfc2008-09-09 18:11:14 +00001577 } else {
Evan Cheng388df622009-02-03 10:05:09 +00001578 if (UndefElts3[MaskVal - LHSVWidth]) {
1579 NewUndefElts = true;
1580 UndefElts.set(i);
1581 }
Dan Gohman488fbfc2008-09-09 18:11:14 +00001582 }
1583 }
1584
1585 if (NewUndefElts) {
1586 // Add additional discovered undefs.
1587 std::vector<Constant*> Elts;
1588 for (unsigned i = 0; i < VWidth; ++i) {
Evan Cheng388df622009-02-03 10:05:09 +00001589 if (UndefElts[i])
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001590 Elts.push_back(UndefValue::get(Type::Int32Ty));
Dan Gohman488fbfc2008-09-09 18:11:14 +00001591 else
Owen Andersoneed707b2009-07-24 23:12:02 +00001592 Elts.push_back(ConstantInt::get(Type::Int32Ty,
Dan Gohman488fbfc2008-09-09 18:11:14 +00001593 Shuffle->getMaskValue(i)));
1594 }
Owen Andersonaf7ec972009-07-28 21:19:26 +00001595 I->setOperand(2, ConstantVector::get(Elts));
Dan Gohman488fbfc2008-09-09 18:11:14 +00001596 MadeChange = true;
1597 }
Chris Lattner867b99f2006-10-05 06:55:50 +00001598 break;
1599 }
Chris Lattner69878332007-04-14 22:29:23 +00001600 case Instruction::BitCast: {
Dan Gohman07a96762007-07-16 14:29:03 +00001601 // Vector->vector casts only.
Chris Lattner69878332007-04-14 22:29:23 +00001602 const VectorType *VTy = dyn_cast<VectorType>(I->getOperand(0)->getType());
1603 if (!VTy) break;
1604 unsigned InVWidth = VTy->getNumElements();
Evan Cheng388df622009-02-03 10:05:09 +00001605 APInt InputDemandedElts(InVWidth, 0);
Chris Lattner69878332007-04-14 22:29:23 +00001606 unsigned Ratio;
1607
1608 if (VWidth == InVWidth) {
Dan Gohman07a96762007-07-16 14:29:03 +00001609 // If we are converting from <4 x i32> -> <4 x f32>, we demand the same
Chris Lattner69878332007-04-14 22:29:23 +00001610 // elements as are demanded of us.
1611 Ratio = 1;
1612 InputDemandedElts = DemandedElts;
1613 } else if (VWidth > InVWidth) {
1614 // Untested so far.
1615 break;
1616
1617 // If there are more elements in the result than there are in the source,
1618 // then an input element is live if any of the corresponding output
1619 // elements are live.
1620 Ratio = VWidth/InVWidth;
1621 for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx) {
Evan Cheng388df622009-02-03 10:05:09 +00001622 if (DemandedElts[OutIdx])
1623 InputDemandedElts.set(OutIdx/Ratio);
Chris Lattner69878332007-04-14 22:29:23 +00001624 }
1625 } else {
1626 // Untested so far.
1627 break;
1628
1629 // If there are more elements in the source than there are in the result,
1630 // then an input element is live if the corresponding output element is
1631 // live.
1632 Ratio = InVWidth/VWidth;
1633 for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
Evan Cheng388df622009-02-03 10:05:09 +00001634 if (DemandedElts[InIdx/Ratio])
1635 InputDemandedElts.set(InIdx);
Chris Lattner69878332007-04-14 22:29:23 +00001636 }
Chris Lattner867b99f2006-10-05 06:55:50 +00001637
Chris Lattner69878332007-04-14 22:29:23 +00001638 // div/rem demand all inputs, because they don't want divide by zero.
1639 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), InputDemandedElts,
1640 UndefElts2, Depth+1);
1641 if (TmpV) {
1642 I->setOperand(0, TmpV);
1643 MadeChange = true;
1644 }
1645
1646 UndefElts = UndefElts2;
1647 if (VWidth > InVWidth) {
Torok Edwinc23197a2009-07-14 16:55:14 +00001648 llvm_unreachable("Unimp");
Chris Lattner69878332007-04-14 22:29:23 +00001649 // If there are more elements in the result than there are in the source,
1650 // then an output element is undef if the corresponding input element is
1651 // undef.
1652 for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx)
Evan Cheng388df622009-02-03 10:05:09 +00001653 if (UndefElts2[OutIdx/Ratio])
1654 UndefElts.set(OutIdx);
Chris Lattner69878332007-04-14 22:29:23 +00001655 } else if (VWidth < InVWidth) {
Torok Edwinc23197a2009-07-14 16:55:14 +00001656 llvm_unreachable("Unimp");
Chris Lattner69878332007-04-14 22:29:23 +00001657 // If there are more elements in the source than there are in the result,
1658 // then a result element is undef if all of the corresponding input
1659 // elements are undef.
1660 UndefElts = ~0ULL >> (64-VWidth); // Start out all undef.
1661 for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
Evan Cheng388df622009-02-03 10:05:09 +00001662 if (!UndefElts2[InIdx]) // Not undef?
1663 UndefElts.clear(InIdx/Ratio); // Clear undef bit.
Chris Lattner69878332007-04-14 22:29:23 +00001664 }
1665 break;
1666 }
Chris Lattner867b99f2006-10-05 06:55:50 +00001667 case Instruction::And:
1668 case Instruction::Or:
1669 case Instruction::Xor:
1670 case Instruction::Add:
1671 case Instruction::Sub:
1672 case Instruction::Mul:
1673 // div/rem demand all inputs, because they don't want divide by zero.
1674 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1675 UndefElts, Depth+1);
1676 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1677 TmpV = SimplifyDemandedVectorElts(I->getOperand(1), DemandedElts,
1678 UndefElts2, Depth+1);
1679 if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1680
1681 // Output elements are undefined if both are undefined. Consider things
1682 // like undef&0. The result is known zero, not undef.
1683 UndefElts &= UndefElts2;
1684 break;
1685
1686 case Instruction::Call: {
1687 IntrinsicInst *II = dyn_cast<IntrinsicInst>(I);
1688 if (!II) break;
1689 switch (II->getIntrinsicID()) {
1690 default: break;
1691
1692 // Binary vector operations that work column-wise. A dest element is a
1693 // function of the corresponding input elements from the two inputs.
1694 case Intrinsic::x86_sse_sub_ss:
1695 case Intrinsic::x86_sse_mul_ss:
1696 case Intrinsic::x86_sse_min_ss:
1697 case Intrinsic::x86_sse_max_ss:
1698 case Intrinsic::x86_sse2_sub_sd:
1699 case Intrinsic::x86_sse2_mul_sd:
1700 case Intrinsic::x86_sse2_min_sd:
1701 case Intrinsic::x86_sse2_max_sd:
1702 TmpV = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
1703 UndefElts, Depth+1);
1704 if (TmpV) { II->setOperand(1, TmpV); MadeChange = true; }
1705 TmpV = SimplifyDemandedVectorElts(II->getOperand(2), DemandedElts,
1706 UndefElts2, Depth+1);
1707 if (TmpV) { II->setOperand(2, TmpV); MadeChange = true; }
1708
1709 // If only the low elt is demanded and this is a scalarizable intrinsic,
1710 // scalarize it now.
1711 if (DemandedElts == 1) {
1712 switch (II->getIntrinsicID()) {
1713 default: break;
1714 case Intrinsic::x86_sse_sub_ss:
1715 case Intrinsic::x86_sse_mul_ss:
1716 case Intrinsic::x86_sse2_sub_sd:
1717 case Intrinsic::x86_sse2_mul_sd:
1718 // TODO: Lower MIN/MAX/ABS/etc
1719 Value *LHS = II->getOperand(1);
1720 Value *RHS = II->getOperand(2);
1721 // Extract the element as scalars.
Eric Christophera3500da2009-07-25 02:28:41 +00001722 LHS = InsertNewInstBefore(ExtractElementInst::Create(LHS,
Owen Andersoneed707b2009-07-24 23:12:02 +00001723 ConstantInt::get(Type::Int32Ty, 0U, false), "tmp"), *II);
Eric Christophera3500da2009-07-25 02:28:41 +00001724 RHS = InsertNewInstBefore(ExtractElementInst::Create(RHS,
Owen Andersoneed707b2009-07-24 23:12:02 +00001725 ConstantInt::get(Type::Int32Ty, 0U, false), "tmp"), *II);
Chris Lattner867b99f2006-10-05 06:55:50 +00001726
1727 switch (II->getIntrinsicID()) {
Torok Edwinc23197a2009-07-14 16:55:14 +00001728 default: llvm_unreachable("Case stmts out of sync!");
Chris Lattner867b99f2006-10-05 06:55:50 +00001729 case Intrinsic::x86_sse_sub_ss:
1730 case Intrinsic::x86_sse2_sub_sd:
Dan Gohmanae3a0be2009-06-04 22:49:04 +00001731 TmpV = InsertNewInstBefore(BinaryOperator::CreateFSub(LHS, RHS,
Chris Lattner867b99f2006-10-05 06:55:50 +00001732 II->getName()), *II);
1733 break;
1734 case Intrinsic::x86_sse_mul_ss:
1735 case Intrinsic::x86_sse2_mul_sd:
Dan Gohmanae3a0be2009-06-04 22:49:04 +00001736 TmpV = InsertNewInstBefore(BinaryOperator::CreateFMul(LHS, RHS,
Chris Lattner867b99f2006-10-05 06:55:50 +00001737 II->getName()), *II);
1738 break;
1739 }
1740
1741 Instruction *New =
Owen Andersond672ecb2009-07-03 00:17:18 +00001742 InsertElementInst::Create(
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001743 UndefValue::get(II->getType()), TmpV,
Owen Andersoneed707b2009-07-24 23:12:02 +00001744 ConstantInt::get(Type::Int32Ty, 0U, false), II->getName());
Chris Lattner867b99f2006-10-05 06:55:50 +00001745 InsertNewInstBefore(New, *II);
1746 AddSoonDeadInstToWorklist(*II, 0);
1747 return New;
1748 }
1749 }
1750
1751 // Output elements are undefined if both are undefined. Consider things
1752 // like undef&0. The result is known zero, not undef.
1753 UndefElts &= UndefElts2;
1754 break;
1755 }
1756 break;
1757 }
1758 }
1759 return MadeChange ? I : 0;
1760}
1761
Dan Gohman45b4e482008-05-19 22:14:15 +00001762
Chris Lattner564a7272003-08-13 19:01:45 +00001763/// AssociativeOpt - Perform an optimization on an associative operator. This
1764/// function is designed to check a chain of associative operators for a
1765/// potential to apply a certain optimization. Since the optimization may be
1766/// applicable if the expression was reassociated, this checks the chain, then
1767/// reassociates the expression as necessary to expose the optimization
1768/// opportunity. This makes use of a special Functor, which must define
1769/// 'shouldApply' and 'apply' methods.
1770///
1771template<typename Functor>
Dan Gohman186a6362009-08-12 16:04:34 +00001772static Instruction *AssociativeOpt(BinaryOperator &Root, const Functor &F) {
Chris Lattner564a7272003-08-13 19:01:45 +00001773 unsigned Opcode = Root.getOpcode();
1774 Value *LHS = Root.getOperand(0);
1775
1776 // Quick check, see if the immediate LHS matches...
1777 if (F.shouldApply(LHS))
1778 return F.apply(Root);
1779
1780 // Otherwise, if the LHS is not of the same opcode as the root, return.
1781 Instruction *LHSI = dyn_cast<Instruction>(LHS);
Chris Lattnerfd059242003-10-15 16:48:29 +00001782 while (LHSI && LHSI->getOpcode() == Opcode && LHSI->hasOneUse()) {
Chris Lattner564a7272003-08-13 19:01:45 +00001783 // Should we apply this transform to the RHS?
1784 bool ShouldApply = F.shouldApply(LHSI->getOperand(1));
1785
1786 // If not to the RHS, check to see if we should apply to the LHS...
1787 if (!ShouldApply && F.shouldApply(LHSI->getOperand(0))) {
1788 cast<BinaryOperator>(LHSI)->swapOperands(); // Make the LHS the RHS
1789 ShouldApply = true;
1790 }
1791
1792 // If the functor wants to apply the optimization to the RHS of LHSI,
1793 // reassociate the expression from ((? op A) op B) to (? op (A op B))
1794 if (ShouldApply) {
Chris Lattner564a7272003-08-13 19:01:45 +00001795 // Now all of the instructions are in the current basic block, go ahead
1796 // and perform the reassociation.
1797 Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
1798
1799 // First move the selected RHS to the LHS of the root...
1800 Root.setOperand(0, LHSI->getOperand(1));
1801
1802 // Make what used to be the LHS of the root be the user of the root...
1803 Value *ExtraOperand = TmpLHSI->getOperand(1);
Chris Lattner65725312004-04-16 18:08:07 +00001804 if (&Root == TmpLHSI) {
Owen Andersona7235ea2009-07-31 20:28:14 +00001805 Root.replaceAllUsesWith(Constant::getNullValue(TmpLHSI->getType()));
Chris Lattner15a76c02004-04-05 02:10:19 +00001806 return 0;
1807 }
Chris Lattner65725312004-04-16 18:08:07 +00001808 Root.replaceAllUsesWith(TmpLHSI); // Users now use TmpLHSI
Chris Lattner564a7272003-08-13 19:01:45 +00001809 TmpLHSI->setOperand(1, &Root); // TmpLHSI now uses the root
Chris Lattner65725312004-04-16 18:08:07 +00001810 BasicBlock::iterator ARI = &Root; ++ARI;
Dan Gohmand02d9172008-06-19 17:47:47 +00001811 TmpLHSI->moveBefore(ARI); // Move TmpLHSI to after Root
Chris Lattner65725312004-04-16 18:08:07 +00001812 ARI = Root;
Chris Lattner564a7272003-08-13 19:01:45 +00001813
1814 // Now propagate the ExtraOperand down the chain of instructions until we
1815 // get to LHSI.
1816 while (TmpLHSI != LHSI) {
1817 Instruction *NextLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
Chris Lattner65725312004-04-16 18:08:07 +00001818 // Move the instruction to immediately before the chain we are
1819 // constructing to avoid breaking dominance properties.
Dan Gohmand02d9172008-06-19 17:47:47 +00001820 NextLHSI->moveBefore(ARI);
Chris Lattner65725312004-04-16 18:08:07 +00001821 ARI = NextLHSI;
1822
Chris Lattner564a7272003-08-13 19:01:45 +00001823 Value *NextOp = NextLHSI->getOperand(1);
1824 NextLHSI->setOperand(1, ExtraOperand);
1825 TmpLHSI = NextLHSI;
1826 ExtraOperand = NextOp;
1827 }
Misha Brukmanfd939082005-04-21 23:48:37 +00001828
Chris Lattner564a7272003-08-13 19:01:45 +00001829 // Now that the instructions are reassociated, have the functor perform
1830 // the transformation...
1831 return F.apply(Root);
1832 }
Misha Brukmanfd939082005-04-21 23:48:37 +00001833
Chris Lattner564a7272003-08-13 19:01:45 +00001834 LHSI = dyn_cast<Instruction>(LHSI->getOperand(0));
1835 }
1836 return 0;
1837}
1838
Dan Gohman844731a2008-05-13 00:00:25 +00001839namespace {
Chris Lattner564a7272003-08-13 19:01:45 +00001840
Nick Lewycky02d639f2008-05-23 04:34:58 +00001841// AddRHS - Implements: X + X --> X << 1
Chris Lattner564a7272003-08-13 19:01:45 +00001842struct AddRHS {
1843 Value *RHS;
Owen Anderson07cf79e2009-07-06 23:00:19 +00001844 LLVMContext *Context;
1845 AddRHS(Value *rhs, LLVMContext *C) : RHS(rhs), Context(C) {}
Chris Lattner564a7272003-08-13 19:01:45 +00001846 bool shouldApply(Value *LHS) const { return LHS == RHS; }
1847 Instruction *apply(BinaryOperator &Add) const {
Nick Lewycky02d639f2008-05-23 04:34:58 +00001848 return BinaryOperator::CreateShl(Add.getOperand(0),
Owen Andersoneed707b2009-07-24 23:12:02 +00001849 ConstantInt::get(Add.getType(), 1));
Chris Lattner564a7272003-08-13 19:01:45 +00001850 }
1851};
1852
1853// AddMaskingAnd - Implements (A & C1)+(B & C2) --> (A & C1)|(B & C2)
1854// iff C1&C2 == 0
1855struct AddMaskingAnd {
1856 Constant *C2;
Owen Anderson07cf79e2009-07-06 23:00:19 +00001857 LLVMContext *Context;
1858 AddMaskingAnd(Constant *c, LLVMContext *C) : C2(c), Context(C) {}
Chris Lattner564a7272003-08-13 19:01:45 +00001859 bool shouldApply(Value *LHS) const {
Chris Lattneracd1f0f2004-07-30 07:50:03 +00001860 ConstantInt *C1;
Owen Andersonc7d2ce72009-07-10 17:35:01 +00001861 return match(LHS, m_And(m_Value(), m_ConstantInt(C1)), *Context) &&
Owen Andersonbaf3c402009-07-29 18:55:55 +00001862 ConstantExpr::getAnd(C1, C2)->isNullValue();
Chris Lattner564a7272003-08-13 19:01:45 +00001863 }
1864 Instruction *apply(BinaryOperator &Add) const {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001865 return BinaryOperator::CreateOr(Add.getOperand(0), Add.getOperand(1));
Chris Lattner564a7272003-08-13 19:01:45 +00001866 }
1867};
1868
Dan Gohman844731a2008-05-13 00:00:25 +00001869}
1870
Chris Lattner6e7ba452005-01-01 16:22:27 +00001871static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
Chris Lattner2eefe512004-04-09 19:05:30 +00001872 InstCombiner *IC) {
Owen Anderson07cf79e2009-07-06 23:00:19 +00001873 LLVMContext *Context = IC->getContext();
Owen Andersond672ecb2009-07-03 00:17:18 +00001874
Reid Spencer3da59db2006-11-27 01:05:10 +00001875 if (CastInst *CI = dyn_cast<CastInst>(&I)) {
Eli Friedmand1fd1da2008-11-30 21:09:11 +00001876 return IC->InsertCastBefore(CI->getOpcode(), SO, I.getType(), I);
Chris Lattner6e7ba452005-01-01 16:22:27 +00001877 }
1878
Chris Lattner2eefe512004-04-09 19:05:30 +00001879 // Figure out if the constant is the left or the right argument.
Chris Lattner6e7ba452005-01-01 16:22:27 +00001880 bool ConstIsRHS = isa<Constant>(I.getOperand(1));
1881 Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
Chris Lattner564a7272003-08-13 19:01:45 +00001882
Chris Lattner2eefe512004-04-09 19:05:30 +00001883 if (Constant *SOC = dyn_cast<Constant>(SO)) {
1884 if (ConstIsRHS)
Owen Andersonbaf3c402009-07-29 18:55:55 +00001885 return ConstantExpr::get(I.getOpcode(), SOC, ConstOperand);
1886 return ConstantExpr::get(I.getOpcode(), ConstOperand, SOC);
Chris Lattner2eefe512004-04-09 19:05:30 +00001887 }
1888
1889 Value *Op0 = SO, *Op1 = ConstOperand;
1890 if (!ConstIsRHS)
1891 std::swap(Op0, Op1);
1892 Instruction *New;
Chris Lattner6e7ba452005-01-01 16:22:27 +00001893 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001894 New = BinaryOperator::Create(BO->getOpcode(), Op0, Op1,SO->getName()+".op");
Reid Spencere4d87aa2006-12-23 06:05:41 +00001895 else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
Owen Anderson333c4002009-07-09 23:48:35 +00001896 New = CmpInst::Create(*Context, CI->getOpcode(), CI->getPredicate(),
1897 Op0, Op1, SO->getName()+".cmp");
Chris Lattner326c0f32004-04-10 19:15:56 +00001898 else {
Torok Edwinc23197a2009-07-14 16:55:14 +00001899 llvm_unreachable("Unknown binary instruction type!");
Chris Lattner326c0f32004-04-10 19:15:56 +00001900 }
Chris Lattner6e7ba452005-01-01 16:22:27 +00001901 return IC->InsertNewInstBefore(New, I);
1902}
1903
1904// FoldOpIntoSelect - Given an instruction with a select as one operand and a
1905// constant as the other operand, try to fold the binary operator into the
1906// select arguments. This also works for Cast instructions, which obviously do
1907// not have a second operand.
1908static Instruction *FoldOpIntoSelect(Instruction &Op, SelectInst *SI,
1909 InstCombiner *IC) {
1910 // Don't modify shared select instructions
1911 if (!SI->hasOneUse()) return 0;
1912 Value *TV = SI->getOperand(1);
1913 Value *FV = SI->getOperand(2);
1914
1915 if (isa<Constant>(TV) || isa<Constant>(FV)) {
Chris Lattner956db272005-04-21 05:43:13 +00001916 // Bool selects with constant operands can be folded to logical ops.
Reid Spencer4fe16d62007-01-11 18:21:29 +00001917 if (SI->getType() == Type::Int1Ty) return 0;
Chris Lattner956db272005-04-21 05:43:13 +00001918
Chris Lattner6e7ba452005-01-01 16:22:27 +00001919 Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, IC);
1920 Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, IC);
1921
Gabor Greif051a9502008-04-06 20:25:17 +00001922 return SelectInst::Create(SI->getCondition(), SelectTrueVal,
1923 SelectFalseVal);
Chris Lattner6e7ba452005-01-01 16:22:27 +00001924 }
1925 return 0;
Chris Lattner2eefe512004-04-09 19:05:30 +00001926}
1927
Chris Lattner4e998b22004-09-29 05:07:12 +00001928
1929/// FoldOpIntoPhi - Given a binary operator or cast instruction which has a PHI
1930/// node as operand #0, see if we can fold the instruction into the PHI (which
1931/// is only possible if all operands to the PHI are constants).
1932Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I) {
1933 PHINode *PN = cast<PHINode>(I.getOperand(0));
Chris Lattnerbac32862004-11-14 19:13:23 +00001934 unsigned NumPHIValues = PN->getNumIncomingValues();
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001935 if (!PN->hasOneUse() || NumPHIValues == 0) return 0;
Chris Lattner4e998b22004-09-29 05:07:12 +00001936
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001937 // Check to see if all of the operands of the PHI are constants. If there is
1938 // one non-constant value, remember the BB it is. If there is more than one
Chris Lattnerb3036682007-02-24 01:03:45 +00001939 // or if *it* is a PHI, bail out.
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001940 BasicBlock *NonConstBB = 0;
1941 for (unsigned i = 0; i != NumPHIValues; ++i)
1942 if (!isa<Constant>(PN->getIncomingValue(i))) {
1943 if (NonConstBB) return 0; // More than one non-const value.
Chris Lattnerb3036682007-02-24 01:03:45 +00001944 if (isa<PHINode>(PN->getIncomingValue(i))) return 0; // Itself a phi.
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001945 NonConstBB = PN->getIncomingBlock(i);
1946
1947 // If the incoming non-constant value is in I's block, we have an infinite
1948 // loop.
1949 if (NonConstBB == I.getParent())
1950 return 0;
1951 }
1952
1953 // If there is exactly one non-constant value, we can insert a copy of the
1954 // operation in that block. However, if this is a critical edge, we would be
1955 // inserting the computation one some other paths (e.g. inside a loop). Only
1956 // do this if the pred block is unconditionally branching into the phi block.
1957 if (NonConstBB) {
1958 BranchInst *BI = dyn_cast<BranchInst>(NonConstBB->getTerminator());
1959 if (!BI || !BI->isUnconditional()) return 0;
1960 }
Chris Lattner4e998b22004-09-29 05:07:12 +00001961
1962 // Okay, we can do the transformation: create the new PHI node.
Gabor Greif051a9502008-04-06 20:25:17 +00001963 PHINode *NewPN = PHINode::Create(I.getType(), "");
Chris Lattner55517062005-01-29 00:39:08 +00001964 NewPN->reserveOperandSpace(PN->getNumOperands()/2);
Chris Lattner4e998b22004-09-29 05:07:12 +00001965 InsertNewInstBefore(NewPN, *PN);
Chris Lattner6934a042007-02-11 01:23:03 +00001966 NewPN->takeName(PN);
Chris Lattner4e998b22004-09-29 05:07:12 +00001967
1968 // Next, add all of the operands to the PHI.
1969 if (I.getNumOperands() == 2) {
1970 Constant *C = cast<Constant>(I.getOperand(1));
Chris Lattnerbac32862004-11-14 19:13:23 +00001971 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattnera9ff5eb2007-08-05 08:47:58 +00001972 Value *InV = 0;
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001973 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00001974 if (CmpInst *CI = dyn_cast<CmpInst>(&I))
Owen Andersonbaf3c402009-07-29 18:55:55 +00001975 InV = ConstantExpr::getCompare(CI->getPredicate(), InC, C);
Reid Spencere4d87aa2006-12-23 06:05:41 +00001976 else
Owen Andersonbaf3c402009-07-29 18:55:55 +00001977 InV = ConstantExpr::get(I.getOpcode(), InC, C);
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001978 } else {
1979 assert(PN->getIncomingBlock(i) == NonConstBB);
1980 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001981 InV = BinaryOperator::Create(BO->getOpcode(),
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001982 PN->getIncomingValue(i), C, "phitmp",
1983 NonConstBB->getTerminator());
Reid Spencere4d87aa2006-12-23 06:05:41 +00001984 else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
Owen Anderson333c4002009-07-09 23:48:35 +00001985 InV = CmpInst::Create(*Context, CI->getOpcode(),
Reid Spencere4d87aa2006-12-23 06:05:41 +00001986 CI->getPredicate(),
1987 PN->getIncomingValue(i), C, "phitmp",
1988 NonConstBB->getTerminator());
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001989 else
Torok Edwinc23197a2009-07-14 16:55:14 +00001990 llvm_unreachable("Unknown binop!");
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001991
Chris Lattnerdbab3862007-03-02 21:28:56 +00001992 AddToWorkList(cast<Instruction>(InV));
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001993 }
1994 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
Chris Lattner4e998b22004-09-29 05:07:12 +00001995 }
Reid Spencer3da59db2006-11-27 01:05:10 +00001996 } else {
1997 CastInst *CI = cast<CastInst>(&I);
1998 const Type *RetTy = CI->getType();
Chris Lattnerbac32862004-11-14 19:13:23 +00001999 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002000 Value *InV;
2001 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00002002 InV = ConstantExpr::getCast(CI->getOpcode(), InC, RetTy);
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002003 } else {
2004 assert(PN->getIncomingBlock(i) == NonConstBB);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002005 InV = CastInst::Create(CI->getOpcode(), PN->getIncomingValue(i),
Reid Spencer3da59db2006-11-27 01:05:10 +00002006 I.getType(), "phitmp",
2007 NonConstBB->getTerminator());
Chris Lattnerdbab3862007-03-02 21:28:56 +00002008 AddToWorkList(cast<Instruction>(InV));
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002009 }
2010 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
Chris Lattner4e998b22004-09-29 05:07:12 +00002011 }
2012 }
2013 return ReplaceInstUsesWith(I, NewPN);
2014}
2015
Chris Lattner2454a2e2008-01-29 06:52:45 +00002016
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002017/// WillNotOverflowSignedAdd - Return true if we can prove that:
2018/// (sext (add LHS, RHS)) === (add (sext LHS), (sext RHS))
2019/// This basically requires proving that the add in the original type would not
2020/// overflow to change the sign bit or have a carry out.
2021bool InstCombiner::WillNotOverflowSignedAdd(Value *LHS, Value *RHS) {
2022 // There are different heuristics we can use for this. Here are some simple
2023 // ones.
2024
2025 // Add has the property that adding any two 2's complement numbers can only
2026 // have one carry bit which can change a sign. As such, if LHS and RHS each
2027 // have at least two sign bits, we know that the addition of the two values will
2028 // sign extend fine.
2029 if (ComputeNumSignBits(LHS) > 1 && ComputeNumSignBits(RHS) > 1)
2030 return true;
2031
2032
2033 // If one of the operands only has one non-zero bit, and if the other operand
2034 // has a known-zero bit in a more significant place than it (not including the
2035 // sign bit) the ripple may go up to and fill the zero, but won't change the
2036 // sign. For example, (X & ~4) + 1.
2037
2038 // TODO: Implement.
2039
2040 return false;
2041}
2042
Chris Lattner2454a2e2008-01-29 06:52:45 +00002043
Chris Lattner7e708292002-06-25 16:13:24 +00002044Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00002045 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00002046 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
Chris Lattnerb35dde12002-05-06 16:49:18 +00002047
Chris Lattner66331a42004-04-10 22:01:55 +00002048 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
Chris Lattnere87597f2004-10-16 18:11:37 +00002049 // X + undef -> undef
2050 if (isa<UndefValue>(RHS))
2051 return ReplaceInstUsesWith(I, RHS);
2052
Chris Lattner66331a42004-04-10 22:01:55 +00002053 // X + 0 --> X
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002054 if (RHSC->isNullValue())
2055 return ReplaceInstUsesWith(I, LHS);
Misha Brukmanfd939082005-04-21 23:48:37 +00002056
Chris Lattner66331a42004-04-10 22:01:55 +00002057 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHSC)) {
Chris Lattnerb4a2f052006-11-09 05:12:27 +00002058 // X + (signbit) --> X ^ signbit
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002059 const APInt& Val = CI->getValue();
Zhou Sheng4351c642007-04-02 08:20:41 +00002060 uint32_t BitWidth = Val.getBitWidth();
Reid Spencer2ec619a2007-03-23 21:24:59 +00002061 if (Val == APInt::getSignBit(BitWidth))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002062 return BinaryOperator::CreateXor(LHS, RHS);
Chris Lattnerb4a2f052006-11-09 05:12:27 +00002063
2064 // See if SimplifyDemandedBits can simplify this. This handles stuff like
2065 // (X & 254)+1 -> (X&254)|1
Dan Gohman6de29f82009-06-15 22:12:54 +00002066 if (SimplifyDemandedInstructionBits(I))
Chris Lattner886ab6c2009-01-31 08:15:18 +00002067 return &I;
Dan Gohman1975d032008-10-30 20:40:10 +00002068
Eli Friedman709b33d2009-07-13 22:27:52 +00002069 // zext(bool) + C -> bool ? C + 1 : C
Dan Gohman1975d032008-10-30 20:40:10 +00002070 if (ZExtInst *ZI = dyn_cast<ZExtInst>(LHS))
Eli Friedman709b33d2009-07-13 22:27:52 +00002071 if (ZI->getSrcTy() == Type::Int1Ty)
Dan Gohman186a6362009-08-12 16:04:34 +00002072 return SelectInst::Create(ZI->getOperand(0), AddOne(CI), CI);
Chris Lattner66331a42004-04-10 22:01:55 +00002073 }
Chris Lattner4e998b22004-09-29 05:07:12 +00002074
2075 if (isa<PHINode>(LHS))
2076 if (Instruction *NV = FoldOpIntoPhi(I))
2077 return NV;
Chris Lattner5931c542005-09-24 23:43:33 +00002078
Chris Lattner4f637d42006-01-06 17:59:59 +00002079 ConstantInt *XorRHS = 0;
2080 Value *XorLHS = 0;
Chris Lattnerc5eff442007-01-30 22:32:46 +00002081 if (isa<ConstantInt>(RHSC) &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00002082 match(LHS, m_Xor(m_Value(XorLHS), m_ConstantInt(XorRHS)), *Context)) {
Dan Gohman6de29f82009-06-15 22:12:54 +00002083 uint32_t TySizeBits = I.getType()->getScalarSizeInBits();
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002084 const APInt& RHSVal = cast<ConstantInt>(RHSC)->getValue();
Chris Lattner5931c542005-09-24 23:43:33 +00002085
Zhou Sheng4351c642007-04-02 08:20:41 +00002086 uint32_t Size = TySizeBits / 2;
Reid Spencer2ec619a2007-03-23 21:24:59 +00002087 APInt C0080Val(APInt(TySizeBits, 1ULL).shl(Size - 1));
2088 APInt CFF80Val(-C0080Val);
Chris Lattner5931c542005-09-24 23:43:33 +00002089 do {
2090 if (TySizeBits > Size) {
Chris Lattner5931c542005-09-24 23:43:33 +00002091 // If we have ADD(XOR(AND(X, 0xFF), 0x80), 0xF..F80), it's a sext.
2092 // If we have ADD(XOR(AND(X, 0xFF), 0xF..F80), 0x80), it's a sext.
Reid Spencer2ec619a2007-03-23 21:24:59 +00002093 if ((RHSVal == CFF80Val && XorRHS->getValue() == C0080Val) ||
2094 (RHSVal == C0080Val && XorRHS->getValue() == CFF80Val)) {
Chris Lattner5931c542005-09-24 23:43:33 +00002095 // This is a sign extend if the top bits are known zero.
Zhou Sheng290bec52007-03-29 08:15:12 +00002096 if (!MaskedValueIsZero(XorLHS,
2097 APInt::getHighBitsSet(TySizeBits, TySizeBits - Size)))
Chris Lattner5931c542005-09-24 23:43:33 +00002098 Size = 0; // Not a sign ext, but can't be any others either.
Reid Spencer2ec619a2007-03-23 21:24:59 +00002099 break;
Chris Lattner5931c542005-09-24 23:43:33 +00002100 }
2101 }
2102 Size >>= 1;
Reid Spencer2ec619a2007-03-23 21:24:59 +00002103 C0080Val = APIntOps::lshr(C0080Val, Size);
2104 CFF80Val = APIntOps::ashr(CFF80Val, Size);
2105 } while (Size >= 1);
Chris Lattner5931c542005-09-24 23:43:33 +00002106
Reid Spencer35c38852007-03-28 01:36:16 +00002107 // FIXME: This shouldn't be necessary. When the backends can handle types
Chris Lattner0c7a9a02008-05-19 20:25:04 +00002108 // with funny bit widths then this switch statement should be removed. It
2109 // is just here to get the size of the "middle" type back up to something
2110 // that the back ends can handle.
Reid Spencer35c38852007-03-28 01:36:16 +00002111 const Type *MiddleType = 0;
2112 switch (Size) {
2113 default: break;
2114 case 32: MiddleType = Type::Int32Ty; break;
2115 case 16: MiddleType = Type::Int16Ty; break;
2116 case 8: MiddleType = Type::Int8Ty; break;
2117 }
2118 if (MiddleType) {
Reid Spencerd977d862006-12-12 23:36:14 +00002119 Instruction *NewTrunc = new TruncInst(XorLHS, MiddleType, "sext");
Chris Lattner5931c542005-09-24 23:43:33 +00002120 InsertNewInstBefore(NewTrunc, I);
Reid Spencer35c38852007-03-28 01:36:16 +00002121 return new SExtInst(NewTrunc, I.getType(), I.getName());
Chris Lattner5931c542005-09-24 23:43:33 +00002122 }
2123 }
Chris Lattner66331a42004-04-10 22:01:55 +00002124 }
Chris Lattnerb35dde12002-05-06 16:49:18 +00002125
Nick Lewycky9419ddb2008-05-31 17:59:52 +00002126 if (I.getType() == Type::Int1Ty)
2127 return BinaryOperator::CreateXor(LHS, RHS);
2128
Nick Lewycky7d26bd82008-05-23 04:39:38 +00002129 // X + X --> X << 1
Nick Lewycky9419ddb2008-05-31 17:59:52 +00002130 if (I.getType()->isInteger()) {
Dan Gohman186a6362009-08-12 16:04:34 +00002131 if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS, Context)))
Owen Andersond672ecb2009-07-03 00:17:18 +00002132 return Result;
Chris Lattner7edc8c22005-04-07 17:14:51 +00002133
2134 if (Instruction *RHSI = dyn_cast<Instruction>(RHS)) {
2135 if (RHSI->getOpcode() == Instruction::Sub)
2136 if (LHS == RHSI->getOperand(1)) // A + (B - A) --> B
2137 return ReplaceInstUsesWith(I, RHSI->getOperand(0));
2138 }
2139 if (Instruction *LHSI = dyn_cast<Instruction>(LHS)) {
2140 if (LHSI->getOpcode() == Instruction::Sub)
2141 if (RHS == LHSI->getOperand(1)) // (B - A) + A --> B
2142 return ReplaceInstUsesWith(I, LHSI->getOperand(0));
2143 }
Robert Bocchino71698282004-07-27 21:02:21 +00002144 }
Chris Lattnere92d2f42003-08-13 04:18:28 +00002145
Chris Lattner5c4afb92002-05-08 22:46:53 +00002146 // -A + B --> B - A
Chris Lattnerdd12f962008-02-17 21:03:36 +00002147 // -A + -B --> -(A + B)
Dan Gohman186a6362009-08-12 16:04:34 +00002148 if (Value *LHSV = dyn_castNegVal(LHS)) {
Chris Lattnere10c0b92008-02-18 17:50:16 +00002149 if (LHS->getType()->isIntOrIntVector()) {
Dan Gohman186a6362009-08-12 16:04:34 +00002150 if (Value *RHSV = dyn_castNegVal(RHS)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002151 Instruction *NewAdd = BinaryOperator::CreateAdd(LHSV, RHSV, "sum");
Chris Lattnere10c0b92008-02-18 17:50:16 +00002152 InsertNewInstBefore(NewAdd, I);
Owen Anderson0a5372e2009-07-13 04:09:18 +00002153 return BinaryOperator::CreateNeg(*Context, NewAdd);
Chris Lattnere10c0b92008-02-18 17:50:16 +00002154 }
Chris Lattnerdd12f962008-02-17 21:03:36 +00002155 }
2156
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002157 return BinaryOperator::CreateSub(RHS, LHSV);
Chris Lattnerdd12f962008-02-17 21:03:36 +00002158 }
Chris Lattnerb35dde12002-05-06 16:49:18 +00002159
2160 // A + -B --> A - B
Chris Lattner8d969642003-03-10 23:06:50 +00002161 if (!isa<Constant>(RHS))
Dan Gohman186a6362009-08-12 16:04:34 +00002162 if (Value *V = dyn_castNegVal(RHS))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002163 return BinaryOperator::CreateSub(LHS, V);
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002164
Misha Brukmanfd939082005-04-21 23:48:37 +00002165
Chris Lattner50af16a2004-11-13 19:50:12 +00002166 ConstantInt *C2;
Dan Gohman186a6362009-08-12 16:04:34 +00002167 if (Value *X = dyn_castFoldableMul(LHS, C2)) {
Chris Lattner50af16a2004-11-13 19:50:12 +00002168 if (X == RHS) // X*C + X --> X * (C+1)
Dan Gohman186a6362009-08-12 16:04:34 +00002169 return BinaryOperator::CreateMul(RHS, AddOne(C2));
Chris Lattner50af16a2004-11-13 19:50:12 +00002170
2171 // X*C1 + X*C2 --> X * (C1+C2)
2172 ConstantInt *C1;
Dan Gohman186a6362009-08-12 16:04:34 +00002173 if (X == dyn_castFoldableMul(RHS, C1))
Owen Andersonbaf3c402009-07-29 18:55:55 +00002174 return BinaryOperator::CreateMul(X, ConstantExpr::getAdd(C1, C2));
Chris Lattnerad3448c2003-02-18 19:57:07 +00002175 }
2176
2177 // X + X*C --> X * (C+1)
Dan Gohman186a6362009-08-12 16:04:34 +00002178 if (dyn_castFoldableMul(RHS, C2) == LHS)
2179 return BinaryOperator::CreateMul(LHS, AddOne(C2));
Chris Lattner50af16a2004-11-13 19:50:12 +00002180
Chris Lattnere617c9e2007-01-05 02:17:46 +00002181 // X + ~X --> -1 since ~X = -X-1
Dan Gohman186a6362009-08-12 16:04:34 +00002182 if (dyn_castNotVal(LHS) == RHS ||
2183 dyn_castNotVal(RHS) == LHS)
Owen Andersona7235ea2009-07-31 20:28:14 +00002184 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnere617c9e2007-01-05 02:17:46 +00002185
Chris Lattnerad3448c2003-02-18 19:57:07 +00002186
Chris Lattner564a7272003-08-13 19:01:45 +00002187 // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
Owen Andersonc7d2ce72009-07-10 17:35:01 +00002188 if (match(RHS, m_And(m_Value(), m_ConstantInt(C2)), *Context))
Dan Gohman186a6362009-08-12 16:04:34 +00002189 if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2, Context)))
Chris Lattnere617c9e2007-01-05 02:17:46 +00002190 return R;
Chris Lattner5e0d7182008-05-19 20:01:56 +00002191
2192 // A+B --> A|B iff A and B have no bits set in common.
2193 if (const IntegerType *IT = dyn_cast<IntegerType>(I.getType())) {
2194 APInt Mask = APInt::getAllOnesValue(IT->getBitWidth());
2195 APInt LHSKnownOne(IT->getBitWidth(), 0);
2196 APInt LHSKnownZero(IT->getBitWidth(), 0);
2197 ComputeMaskedBits(LHS, Mask, LHSKnownZero, LHSKnownOne);
2198 if (LHSKnownZero != 0) {
2199 APInt RHSKnownOne(IT->getBitWidth(), 0);
2200 APInt RHSKnownZero(IT->getBitWidth(), 0);
2201 ComputeMaskedBits(RHS, Mask, RHSKnownZero, RHSKnownOne);
2202
2203 // No bits in common -> bitwise or.
Chris Lattner9d60ba92008-05-19 20:03:53 +00002204 if ((LHSKnownZero|RHSKnownZero).isAllOnesValue())
Chris Lattner5e0d7182008-05-19 20:01:56 +00002205 return BinaryOperator::CreateOr(LHS, RHS);
Chris Lattner5e0d7182008-05-19 20:01:56 +00002206 }
2207 }
Chris Lattnerc8802d22003-03-11 00:12:48 +00002208
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002209 // W*X + Y*Z --> W * (X+Z) iff W == Y
Nick Lewycky0c2c3f62008-02-03 08:19:11 +00002210 if (I.getType()->isIntOrIntVector()) {
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002211 Value *W, *X, *Y, *Z;
Owen Andersonc7d2ce72009-07-10 17:35:01 +00002212 if (match(LHS, m_Mul(m_Value(W), m_Value(X)), *Context) &&
2213 match(RHS, m_Mul(m_Value(Y), m_Value(Z)), *Context)) {
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002214 if (W != Y) {
2215 if (W == Z) {
Bill Wendling587c01d2008-02-26 10:53:30 +00002216 std::swap(Y, Z);
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002217 } else if (Y == X) {
Bill Wendling587c01d2008-02-26 10:53:30 +00002218 std::swap(W, X);
2219 } else if (X == Z) {
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002220 std::swap(Y, Z);
2221 std::swap(W, X);
2222 }
2223 }
2224
2225 if (W == Y) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002226 Value *NewAdd = InsertNewInstBefore(BinaryOperator::CreateAdd(X, Z,
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002227 LHS->getName()), I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002228 return BinaryOperator::CreateMul(W, NewAdd);
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002229 }
2230 }
2231 }
2232
Chris Lattner6b032052003-10-02 15:11:26 +00002233 if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
Chris Lattner4f637d42006-01-06 17:59:59 +00002234 Value *X = 0;
Owen Andersonc7d2ce72009-07-10 17:35:01 +00002235 if (match(LHS, m_Not(m_Value(X)), *Context)) // ~X + C --> (C-1) - X
Dan Gohman186a6362009-08-12 16:04:34 +00002236 return BinaryOperator::CreateSub(SubOne(CRHS), X);
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002237
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002238 // (X & FF00) + xx00 -> (X+xx00) & FF00
Owen Andersonc7d2ce72009-07-10 17:35:01 +00002239 if (LHS->hasOneUse() &&
2240 match(LHS, m_And(m_Value(X), m_ConstantInt(C2)), *Context)) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00002241 Constant *Anded = ConstantExpr::getAnd(CRHS, C2);
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002242 if (Anded == CRHS) {
2243 // See if all bits from the first bit set in the Add RHS up are included
2244 // in the mask. First, get the rightmost bit.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002245 const APInt& AddRHSV = CRHS->getValue();
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002246
2247 // Form a mask of all bits from the lowest bit added through the top.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002248 APInt AddRHSHighBits(~((AddRHSV & -AddRHSV)-1));
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002249
2250 // See if the and mask includes all of these bits.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002251 APInt AddRHSHighBitsAnd(AddRHSHighBits & C2->getValue());
Misha Brukmanfd939082005-04-21 23:48:37 +00002252
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002253 if (AddRHSHighBits == AddRHSHighBitsAnd) {
2254 // Okay, the xform is safe. Insert the new add pronto.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002255 Value *NewAdd = InsertNewInstBefore(BinaryOperator::CreateAdd(X, CRHS,
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002256 LHS->getName()), I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002257 return BinaryOperator::CreateAnd(NewAdd, C2);
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002258 }
2259 }
2260 }
2261
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002262 // Try to fold constant add into select arguments.
2263 if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
Chris Lattner6e7ba452005-01-01 16:22:27 +00002264 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002265 return R;
Chris Lattner6b032052003-10-02 15:11:26 +00002266 }
2267
Chris Lattner42790482007-12-20 01:56:58 +00002268 // add (select X 0 (sub n A)) A --> select X A n
Christopher Lamb30f017a2007-12-18 09:34:41 +00002269 {
2270 SelectInst *SI = dyn_cast<SelectInst>(LHS);
Chris Lattner6046fb72008-11-16 04:46:19 +00002271 Value *A = RHS;
Christopher Lamb30f017a2007-12-18 09:34:41 +00002272 if (!SI) {
2273 SI = dyn_cast<SelectInst>(RHS);
Chris Lattner6046fb72008-11-16 04:46:19 +00002274 A = LHS;
Christopher Lamb30f017a2007-12-18 09:34:41 +00002275 }
Chris Lattner42790482007-12-20 01:56:58 +00002276 if (SI && SI->hasOneUse()) {
Christopher Lamb30f017a2007-12-18 09:34:41 +00002277 Value *TV = SI->getTrueValue();
2278 Value *FV = SI->getFalseValue();
Chris Lattner6046fb72008-11-16 04:46:19 +00002279 Value *N;
Christopher Lamb30f017a2007-12-18 09:34:41 +00002280
2281 // Can we fold the add into the argument of the select?
2282 // We check both true and false select arguments for a matching subtract.
Owen Andersonc7d2ce72009-07-10 17:35:01 +00002283 if (match(FV, m_Zero(), *Context) &&
2284 match(TV, m_Sub(m_Value(N), m_Specific(A)), *Context))
Chris Lattner6046fb72008-11-16 04:46:19 +00002285 // Fold the add into the true select value.
Gabor Greif051a9502008-04-06 20:25:17 +00002286 return SelectInst::Create(SI->getCondition(), N, A);
Owen Andersonc7d2ce72009-07-10 17:35:01 +00002287 if (match(TV, m_Zero(), *Context) &&
2288 match(FV, m_Sub(m_Value(N), m_Specific(A)), *Context))
Chris Lattner6046fb72008-11-16 04:46:19 +00002289 // Fold the add into the false select value.
Gabor Greif051a9502008-04-06 20:25:17 +00002290 return SelectInst::Create(SI->getCondition(), A, N);
Christopher Lamb30f017a2007-12-18 09:34:41 +00002291 }
2292 }
Andrew Lenharth16d79552006-09-19 18:24:51 +00002293
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002294 // Check for (add (sext x), y), see if we can merge this into an
2295 // integer add followed by a sext.
2296 if (SExtInst *LHSConv = dyn_cast<SExtInst>(LHS)) {
2297 // (add (sext x), cst) --> (sext (add x, cst'))
2298 if (ConstantInt *RHSC = dyn_cast<ConstantInt>(RHS)) {
2299 Constant *CI =
Owen Andersonbaf3c402009-07-29 18:55:55 +00002300 ConstantExpr::getTrunc(RHSC, LHSConv->getOperand(0)->getType());
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002301 if (LHSConv->hasOneUse() &&
Owen Andersonbaf3c402009-07-29 18:55:55 +00002302 ConstantExpr::getSExt(CI, I.getType()) == RHSC &&
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002303 WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
2304 // Insert the new, smaller add.
2305 Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0),
2306 CI, "addconv");
2307 InsertNewInstBefore(NewAdd, I);
2308 return new SExtInst(NewAdd, I.getType());
2309 }
2310 }
2311
2312 // (add (sext x), (sext y)) --> (sext (add int x, y))
2313 if (SExtInst *RHSConv = dyn_cast<SExtInst>(RHS)) {
2314 // Only do this if x/y have the same type, if at last one of them has a
2315 // single use (so we don't increase the number of sexts), and if the
2316 // integer add will not overflow.
2317 if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
2318 (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
2319 WillNotOverflowSignedAdd(LHSConv->getOperand(0),
2320 RHSConv->getOperand(0))) {
2321 // Insert the new integer add.
2322 Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0),
2323 RHSConv->getOperand(0),
2324 "addconv");
2325 InsertNewInstBefore(NewAdd, I);
2326 return new SExtInst(NewAdd, I.getType());
2327 }
2328 }
2329 }
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002330
2331 return Changed ? &I : 0;
2332}
2333
2334Instruction *InstCombiner::visitFAdd(BinaryOperator &I) {
2335 bool Changed = SimplifyCommutative(I);
2336 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
2337
2338 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
2339 // X + 0 --> X
2340 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
Owen Anderson6f83c9c2009-07-27 20:59:43 +00002341 if (CFP->isExactlyValue(ConstantFP::getNegativeZero
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002342 (I.getType())->getValueAPF()))
2343 return ReplaceInstUsesWith(I, LHS);
2344 }
2345
2346 if (isa<PHINode>(LHS))
2347 if (Instruction *NV = FoldOpIntoPhi(I))
2348 return NV;
2349 }
2350
2351 // -A + B --> B - A
2352 // -A + -B --> -(A + B)
Dan Gohman186a6362009-08-12 16:04:34 +00002353 if (Value *LHSV = dyn_castFNegVal(LHS))
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002354 return BinaryOperator::CreateFSub(RHS, LHSV);
2355
2356 // A + -B --> A - B
2357 if (!isa<Constant>(RHS))
Dan Gohman186a6362009-08-12 16:04:34 +00002358 if (Value *V = dyn_castFNegVal(RHS))
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002359 return BinaryOperator::CreateFSub(LHS, V);
2360
2361 // Check for X+0.0. Simplify it to X if we know X is not -0.0.
2362 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS))
2363 if (CFP->getValueAPF().isPosZero() && CannotBeNegativeZero(LHS))
2364 return ReplaceInstUsesWith(I, LHS);
2365
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002366 // Check for (add double (sitofp x), y), see if we can merge this into an
2367 // integer add followed by a promotion.
2368 if (SIToFPInst *LHSConv = dyn_cast<SIToFPInst>(LHS)) {
2369 // (add double (sitofp x), fpcst) --> (sitofp (add int x, intcst))
2370 // ... if the constant fits in the integer value. This is useful for things
2371 // like (double)(x & 1234) + 4.0 -> (double)((X & 1234)+4) which no longer
2372 // requires a constant pool load, and generally allows the add to be better
2373 // instcombined.
2374 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS)) {
2375 Constant *CI =
Owen Andersonbaf3c402009-07-29 18:55:55 +00002376 ConstantExpr::getFPToSI(CFP, LHSConv->getOperand(0)->getType());
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002377 if (LHSConv->hasOneUse() &&
Owen Andersonbaf3c402009-07-29 18:55:55 +00002378 ConstantExpr::getSIToFP(CI, I.getType()) == CFP &&
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002379 WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
2380 // Insert the new integer add.
2381 Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0),
2382 CI, "addconv");
2383 InsertNewInstBefore(NewAdd, I);
2384 return new SIToFPInst(NewAdd, I.getType());
2385 }
2386 }
2387
2388 // (add double (sitofp x), (sitofp y)) --> (sitofp (add int x, y))
2389 if (SIToFPInst *RHSConv = dyn_cast<SIToFPInst>(RHS)) {
2390 // Only do this if x/y have the same type, if at last one of them has a
2391 // single use (so we don't increase the number of int->fp conversions),
2392 // and if the integer add will not overflow.
2393 if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
2394 (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
2395 WillNotOverflowSignedAdd(LHSConv->getOperand(0),
2396 RHSConv->getOperand(0))) {
2397 // Insert the new integer add.
2398 Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0),
2399 RHSConv->getOperand(0),
2400 "addconv");
2401 InsertNewInstBefore(NewAdd, I);
2402 return new SIToFPInst(NewAdd, I.getType());
2403 }
2404 }
2405 }
2406
Chris Lattner7e708292002-06-25 16:13:24 +00002407 return Changed ? &I : 0;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002408}
2409
Chris Lattner7e708292002-06-25 16:13:24 +00002410Instruction *InstCombiner::visitSub(BinaryOperator &I) {
Chris Lattner7e708292002-06-25 16:13:24 +00002411 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00002412
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002413 if (Op0 == Op1) // sub X, X -> 0
Owen Andersona7235ea2009-07-31 20:28:14 +00002414 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002415
Chris Lattner233f7dc2002-08-12 21:17:25 +00002416 // If this is a 'B = x-(-A)', change to B = x+A...
Dan Gohman186a6362009-08-12 16:04:34 +00002417 if (Value *V = dyn_castNegVal(Op1))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002418 return BinaryOperator::CreateAdd(Op0, V);
Chris Lattnerb35dde12002-05-06 16:49:18 +00002419
Chris Lattnere87597f2004-10-16 18:11:37 +00002420 if (isa<UndefValue>(Op0))
2421 return ReplaceInstUsesWith(I, Op0); // undef - X -> undef
2422 if (isa<UndefValue>(Op1))
2423 return ReplaceInstUsesWith(I, Op1); // X - undef -> undef
2424
Chris Lattnerd65460f2003-11-05 01:06:05 +00002425 if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
2426 // Replace (-1 - A) with (~A)...
Chris Lattnera2881962003-02-18 19:28:33 +00002427 if (C->isAllOnesValue())
Owen Anderson73c6b712009-07-13 20:58:05 +00002428 return BinaryOperator::CreateNot(*Context, Op1);
Chris Lattner40371712002-05-09 01:29:19 +00002429
Chris Lattnerd65460f2003-11-05 01:06:05 +00002430 // C - ~X == X + (1+C)
Reid Spencer4b828e62005-06-18 17:37:34 +00002431 Value *X = 0;
Owen Andersonc7d2ce72009-07-10 17:35:01 +00002432 if (match(Op1, m_Not(m_Value(X)), *Context))
Dan Gohman186a6362009-08-12 16:04:34 +00002433 return BinaryOperator::CreateAdd(X, AddOne(C));
Reid Spencer7177c3a2007-03-25 05:33:51 +00002434
Chris Lattner76b7a062007-01-15 07:02:54 +00002435 // -(X >>u 31) -> (X >>s 31)
2436 // -(X >>s 31) -> (X >>u 31)
Zhou Sheng302748d2007-03-30 17:20:39 +00002437 if (C->isZero()) {
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00002438 if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op1)) {
Reid Spencer3822ff52006-11-08 06:47:33 +00002439 if (SI->getOpcode() == Instruction::LShr) {
Reid Spencerb83eb642006-10-20 07:07:24 +00002440 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
Chris Lattner9c290672004-03-12 23:53:13 +00002441 // Check to see if we are shifting out everything but the sign bit.
Zhou Sheng302748d2007-03-30 17:20:39 +00002442 if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
Reid Spencerb83eb642006-10-20 07:07:24 +00002443 SI->getType()->getPrimitiveSizeInBits()-1) {
Reid Spencer3822ff52006-11-08 06:47:33 +00002444 // Ok, the transformation is safe. Insert AShr.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002445 return BinaryOperator::Create(Instruction::AShr,
Reid Spencer832254e2007-02-02 02:16:23 +00002446 SI->getOperand(0), CU, SI->getName());
Chris Lattner9c290672004-03-12 23:53:13 +00002447 }
2448 }
Reid Spencer3822ff52006-11-08 06:47:33 +00002449 }
2450 else if (SI->getOpcode() == Instruction::AShr) {
2451 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2452 // Check to see if we are shifting out everything but the sign bit.
Zhou Sheng302748d2007-03-30 17:20:39 +00002453 if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
Reid Spencer3822ff52006-11-08 06:47:33 +00002454 SI->getType()->getPrimitiveSizeInBits()-1) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00002455 // Ok, the transformation is safe. Insert LShr.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002456 return BinaryOperator::CreateLShr(
Reid Spencer832254e2007-02-02 02:16:23 +00002457 SI->getOperand(0), CU, SI->getName());
Reid Spencer3822ff52006-11-08 06:47:33 +00002458 }
2459 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00002460 }
2461 }
Chris Lattnerbfe492b2004-03-13 00:11:49 +00002462 }
Chris Lattner2eefe512004-04-09 19:05:30 +00002463
2464 // Try to fold constant sub into select arguments.
2465 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner6e7ba452005-01-01 16:22:27 +00002466 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00002467 return R;
Eli Friedman709b33d2009-07-13 22:27:52 +00002468
2469 // C - zext(bool) -> bool ? C - 1 : C
2470 if (ZExtInst *ZI = dyn_cast<ZExtInst>(Op1))
2471 if (ZI->getSrcTy() == Type::Int1Ty)
Dan Gohman186a6362009-08-12 16:04:34 +00002472 return SelectInst::Create(ZI->getOperand(0), SubOne(C), C);
Chris Lattnerd65460f2003-11-05 01:06:05 +00002473 }
2474
Nick Lewycky9419ddb2008-05-31 17:59:52 +00002475 if (I.getType() == Type::Int1Ty)
2476 return BinaryOperator::CreateXor(Op0, Op1);
2477
Chris Lattner43d84d62005-04-07 16:15:25 +00002478 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002479 if (Op1I->getOpcode() == Instruction::Add) {
Chris Lattner08954a22005-04-07 16:28:01 +00002480 if (Op1I->getOperand(0) == Op0) // X-(X+Y) == -Y
Owen Anderson0a5372e2009-07-13 04:09:18 +00002481 return BinaryOperator::CreateNeg(*Context, Op1I->getOperand(1),
2482 I.getName());
Chris Lattner08954a22005-04-07 16:28:01 +00002483 else if (Op1I->getOperand(1) == Op0) // X-(Y+X) == -Y
Owen Anderson0a5372e2009-07-13 04:09:18 +00002484 return BinaryOperator::CreateNeg(*Context, Op1I->getOperand(0),
2485 I.getName());
Chris Lattner08954a22005-04-07 16:28:01 +00002486 else if (ConstantInt *CI1 = dyn_cast<ConstantInt>(I.getOperand(0))) {
2487 if (ConstantInt *CI2 = dyn_cast<ConstantInt>(Op1I->getOperand(1)))
2488 // C1-(X+C2) --> (C1-C2)-X
Owen Andersond672ecb2009-07-03 00:17:18 +00002489 return BinaryOperator::CreateSub(
Owen Andersonbaf3c402009-07-29 18:55:55 +00002490 ConstantExpr::getSub(CI1, CI2), Op1I->getOperand(0));
Chris Lattner08954a22005-04-07 16:28:01 +00002491 }
Chris Lattner43d84d62005-04-07 16:15:25 +00002492 }
2493
Chris Lattnerfd059242003-10-15 16:48:29 +00002494 if (Op1I->hasOneUse()) {
Chris Lattnera2881962003-02-18 19:28:33 +00002495 // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
2496 // is not used by anyone else...
2497 //
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002498 if (Op1I->getOpcode() == Instruction::Sub) {
Chris Lattnera2881962003-02-18 19:28:33 +00002499 // Swap the two operands of the subexpr...
2500 Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
2501 Op1I->setOperand(0, IIOp1);
2502 Op1I->setOperand(1, IIOp0);
Misha Brukmanfd939082005-04-21 23:48:37 +00002503
Chris Lattnera2881962003-02-18 19:28:33 +00002504 // Create the new top level add instruction...
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002505 return BinaryOperator::CreateAdd(Op0, Op1);
Chris Lattnera2881962003-02-18 19:28:33 +00002506 }
2507
2508 // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
2509 //
2510 if (Op1I->getOpcode() == Instruction::And &&
2511 (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
2512 Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
2513
Chris Lattnerf523d062004-06-09 05:08:07 +00002514 Value *NewNot =
Owen Anderson73c6b712009-07-13 20:58:05 +00002515 InsertNewInstBefore(BinaryOperator::CreateNot(*Context,
2516 OtherOp, "B.not"), I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002517 return BinaryOperator::CreateAnd(Op0, NewNot);
Chris Lattnera2881962003-02-18 19:28:33 +00002518 }
Chris Lattnerad3448c2003-02-18 19:57:07 +00002519
Reid Spencerac5209e2006-10-16 23:08:08 +00002520 // 0 - (X sdiv C) -> (X sdiv -C)
Reid Spencer1628cec2006-10-26 06:15:43 +00002521 if (Op1I->getOpcode() == Instruction::SDiv)
Reid Spencerb83eb642006-10-20 07:07:24 +00002522 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
Zhou Sheng843f07672007-04-19 05:39:12 +00002523 if (CSI->isZero())
Chris Lattner91ccc152004-10-06 15:08:25 +00002524 if (Constant *DivRHS = dyn_cast<Constant>(Op1I->getOperand(1)))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002525 return BinaryOperator::CreateSDiv(Op1I->getOperand(0),
Owen Andersonbaf3c402009-07-29 18:55:55 +00002526 ConstantExpr::getNeg(DivRHS));
Chris Lattner91ccc152004-10-06 15:08:25 +00002527
Chris Lattnerad3448c2003-02-18 19:57:07 +00002528 // X - X*C --> X * (1-C)
Reid Spencer4b828e62005-06-18 17:37:34 +00002529 ConstantInt *C2 = 0;
Dan Gohman186a6362009-08-12 16:04:34 +00002530 if (dyn_castFoldableMul(Op1I, C2) == Op0) {
Owen Andersond672ecb2009-07-03 00:17:18 +00002531 Constant *CP1 =
Owen Andersonbaf3c402009-07-29 18:55:55 +00002532 ConstantExpr::getSub(ConstantInt::get(I.getType(), 1),
Dan Gohman6de29f82009-06-15 22:12:54 +00002533 C2);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002534 return BinaryOperator::CreateMul(Op0, CP1);
Chris Lattnerad3448c2003-02-18 19:57:07 +00002535 }
Chris Lattner40371712002-05-09 01:29:19 +00002536 }
Chris Lattner43d84d62005-04-07 16:15:25 +00002537 }
Chris Lattnera2881962003-02-18 19:28:33 +00002538
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002539 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
2540 if (Op0I->getOpcode() == Instruction::Add) {
2541 if (Op0I->getOperand(0) == Op1) // (Y+X)-Y == X
2542 return ReplaceInstUsesWith(I, Op0I->getOperand(1));
2543 else if (Op0I->getOperand(1) == Op1) // (X+Y)-Y == X
2544 return ReplaceInstUsesWith(I, Op0I->getOperand(0));
2545 } else if (Op0I->getOpcode() == Instruction::Sub) {
2546 if (Op0I->getOperand(0) == Op1) // (X-Y)-X == -Y
Owen Anderson0a5372e2009-07-13 04:09:18 +00002547 return BinaryOperator::CreateNeg(*Context, Op0I->getOperand(1),
2548 I.getName());
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00002549 }
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002550 }
Misha Brukmanfd939082005-04-21 23:48:37 +00002551
Chris Lattner50af16a2004-11-13 19:50:12 +00002552 ConstantInt *C1;
Dan Gohman186a6362009-08-12 16:04:34 +00002553 if (Value *X = dyn_castFoldableMul(Op0, C1)) {
Reid Spencer7177c3a2007-03-25 05:33:51 +00002554 if (X == Op1) // X*C - X --> X * (C-1)
Dan Gohman186a6362009-08-12 16:04:34 +00002555 return BinaryOperator::CreateMul(Op1, SubOne(C1));
Chris Lattnerad3448c2003-02-18 19:57:07 +00002556
Chris Lattner50af16a2004-11-13 19:50:12 +00002557 ConstantInt *C2; // X*C1 - X*C2 -> X * (C1-C2)
Dan Gohman186a6362009-08-12 16:04:34 +00002558 if (X == dyn_castFoldableMul(Op1, C2))
Owen Andersonbaf3c402009-07-29 18:55:55 +00002559 return BinaryOperator::CreateMul(X, ConstantExpr::getSub(C1, C2));
Chris Lattner50af16a2004-11-13 19:50:12 +00002560 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00002561 return 0;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002562}
2563
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002564Instruction *InstCombiner::visitFSub(BinaryOperator &I) {
2565 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2566
2567 // If this is a 'B = x-(-A)', change to B = x+A...
Dan Gohman186a6362009-08-12 16:04:34 +00002568 if (Value *V = dyn_castFNegVal(Op1))
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002569 return BinaryOperator::CreateFAdd(Op0, V);
2570
2571 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
2572 if (Op1I->getOpcode() == Instruction::FAdd) {
2573 if (Op1I->getOperand(0) == Op0) // X-(X+Y) == -Y
Owen Anderson0a5372e2009-07-13 04:09:18 +00002574 return BinaryOperator::CreateFNeg(*Context, Op1I->getOperand(1),
2575 I.getName());
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002576 else if (Op1I->getOperand(1) == Op0) // X-(Y+X) == -Y
Owen Anderson0a5372e2009-07-13 04:09:18 +00002577 return BinaryOperator::CreateFNeg(*Context, Op1I->getOperand(0),
2578 I.getName());
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002579 }
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002580 }
2581
2582 return 0;
2583}
2584
Chris Lattnera0141b92007-07-15 20:42:37 +00002585/// isSignBitCheck - Given an exploded icmp instruction, return true if the
2586/// comparison only checks the sign bit. If it only checks the sign bit, set
2587/// TrueIfSigned if the result of the comparison is true when the input value is
2588/// signed.
2589static bool isSignBitCheck(ICmpInst::Predicate pred, ConstantInt *RHS,
2590 bool &TrueIfSigned) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00002591 switch (pred) {
Chris Lattnera0141b92007-07-15 20:42:37 +00002592 case ICmpInst::ICMP_SLT: // True if LHS s< 0
2593 TrueIfSigned = true;
2594 return RHS->isZero();
Chris Lattnercb7122b2007-07-16 04:15:34 +00002595 case ICmpInst::ICMP_SLE: // True if LHS s<= RHS and RHS == -1
2596 TrueIfSigned = true;
2597 return RHS->isAllOnesValue();
Chris Lattnera0141b92007-07-15 20:42:37 +00002598 case ICmpInst::ICMP_SGT: // True if LHS s> -1
2599 TrueIfSigned = false;
2600 return RHS->isAllOnesValue();
Chris Lattnercb7122b2007-07-16 04:15:34 +00002601 case ICmpInst::ICMP_UGT:
2602 // True if LHS u> RHS and RHS == high-bit-mask - 1
2603 TrueIfSigned = true;
2604 return RHS->getValue() ==
2605 APInt::getSignedMaxValue(RHS->getType()->getPrimitiveSizeInBits());
2606 case ICmpInst::ICMP_UGE:
2607 // True if LHS u>= RHS and RHS == high-bit-mask (2^7, 2^15, 2^31, etc)
2608 TrueIfSigned = true;
Chris Lattner833f25d2008-06-02 01:29:46 +00002609 return RHS->getValue().isSignBit();
Chris Lattnera0141b92007-07-15 20:42:37 +00002610 default:
2611 return false;
Chris Lattner4cb170c2004-02-23 06:38:22 +00002612 }
Chris Lattner4cb170c2004-02-23 06:38:22 +00002613}
2614
Chris Lattner7e708292002-06-25 16:13:24 +00002615Instruction *InstCombiner::visitMul(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00002616 bool Changed = SimplifyCommutative(I);
Chris Lattnera2881962003-02-18 19:28:33 +00002617 Value *Op0 = I.getOperand(0);
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002618
Eli Friedman1694e092009-07-18 09:12:15 +00002619 if (isa<UndefValue>(I.getOperand(1))) // undef * X -> 0
Owen Andersona7235ea2009-07-31 20:28:14 +00002620 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00002621
Chris Lattner233f7dc2002-08-12 21:17:25 +00002622 // Simplify mul instructions with a constant RHS...
Chris Lattnera2881962003-02-18 19:28:33 +00002623 if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
2624 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Chris Lattnere92d2f42003-08-13 04:18:28 +00002625
2626 // ((X << C1)*C2) == (X * (C2 << C1))
Reid Spencer832254e2007-02-02 02:16:23 +00002627 if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op0))
Chris Lattnere92d2f42003-08-13 04:18:28 +00002628 if (SI->getOpcode() == Instruction::Shl)
2629 if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002630 return BinaryOperator::CreateMul(SI->getOperand(0),
Owen Andersonbaf3c402009-07-29 18:55:55 +00002631 ConstantExpr::getShl(CI, ShOp));
Misha Brukmanfd939082005-04-21 23:48:37 +00002632
Zhou Sheng843f07672007-04-19 05:39:12 +00002633 if (CI->isZero())
Chris Lattner515c97c2003-09-11 22:24:54 +00002634 return ReplaceInstUsesWith(I, Op1); // X * 0 == 0
2635 if (CI->equalsInt(1)) // X * 1 == X
2636 return ReplaceInstUsesWith(I, Op0);
2637 if (CI->isAllOnesValue()) // X * -1 == 0 - X
Owen Anderson0a5372e2009-07-13 04:09:18 +00002638 return BinaryOperator::CreateNeg(*Context, Op0, I.getName());
Chris Lattner6c1ce212002-04-29 22:24:47 +00002639
Zhou Sheng97b52c22007-03-29 01:57:21 +00002640 const APInt& Val = cast<ConstantInt>(CI)->getValue();
Reid Spencerbca0e382007-03-23 20:05:17 +00002641 if (Val.isPowerOf2()) { // Replace X*(2^C) with X << C
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002642 return BinaryOperator::CreateShl(Op0,
Owen Andersoneed707b2009-07-24 23:12:02 +00002643 ConstantInt::get(Op0->getType(), Val.logBase2()));
Chris Lattnerbcd7db52005-08-02 19:16:58 +00002644 }
Chris Lattnerb8cd4d32008-08-11 22:06:05 +00002645 } else if (isa<VectorType>(Op1->getType())) {
Eli Friedmanb4687092009-07-14 02:01:53 +00002646 if (Op1->isNullValue())
2647 return ReplaceInstUsesWith(I, Op1);
Nick Lewycky895f0852008-11-27 20:21:08 +00002648
2649 if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1)) {
2650 if (Op1V->isAllOnesValue()) // X * -1 == 0 - X
Owen Anderson0a5372e2009-07-13 04:09:18 +00002651 return BinaryOperator::CreateNeg(*Context, Op0, I.getName());
Nick Lewycky895f0852008-11-27 20:21:08 +00002652
2653 // As above, vector X*splat(1.0) -> X in all defined cases.
2654 if (Constant *Splat = Op1V->getSplatValue()) {
Nick Lewycky895f0852008-11-27 20:21:08 +00002655 if (ConstantInt *CI = dyn_cast<ConstantInt>(Splat))
2656 if (CI->equalsInt(1))
2657 return ReplaceInstUsesWith(I, Op0);
2658 }
2659 }
Chris Lattnera2881962003-02-18 19:28:33 +00002660 }
Chris Lattnerab51f3f2006-03-04 06:04:02 +00002661
2662 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
2663 if (Op0I->getOpcode() == Instruction::Add && Op0I->hasOneUse() &&
Chris Lattner47c99092008-05-18 04:11:26 +00002664 isa<ConstantInt>(Op0I->getOperand(1)) && isa<ConstantInt>(Op1)) {
Chris Lattnerab51f3f2006-03-04 06:04:02 +00002665 // Canonicalize (X+C1)*C2 -> X*C2+C1*C2.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002666 Instruction *Add = BinaryOperator::CreateMul(Op0I->getOperand(0),
Chris Lattnerab51f3f2006-03-04 06:04:02 +00002667 Op1, "tmp");
2668 InsertNewInstBefore(Add, I);
Owen Andersonbaf3c402009-07-29 18:55:55 +00002669 Value *C1C2 = ConstantExpr::getMul(Op1,
Chris Lattnerab51f3f2006-03-04 06:04:02 +00002670 cast<Constant>(Op0I->getOperand(1)));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002671 return BinaryOperator::CreateAdd(Add, C1C2);
Chris Lattnerab51f3f2006-03-04 06:04:02 +00002672
2673 }
Chris Lattner2eefe512004-04-09 19:05:30 +00002674
2675 // Try to fold constant mul into select arguments.
2676 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00002677 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00002678 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00002679
2680 if (isa<PHINode>(Op0))
2681 if (Instruction *NV = FoldOpIntoPhi(I))
2682 return NV;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002683 }
2684
Dan Gohman186a6362009-08-12 16:04:34 +00002685 if (Value *Op0v = dyn_castNegVal(Op0)) // -X * -Y = X*Y
2686 if (Value *Op1v = dyn_castNegVal(I.getOperand(1)))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002687 return BinaryOperator::CreateMul(Op0v, Op1v);
Chris Lattnera4f445b2003-03-10 23:23:04 +00002688
Nick Lewycky0c730792008-11-21 07:33:58 +00002689 // (X / Y) * Y = X - (X % Y)
2690 // (X / Y) * -Y = (X % Y) - X
2691 {
2692 Value *Op1 = I.getOperand(1);
2693 BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0);
2694 if (!BO ||
2695 (BO->getOpcode() != Instruction::UDiv &&
2696 BO->getOpcode() != Instruction::SDiv)) {
2697 Op1 = Op0;
2698 BO = dyn_cast<BinaryOperator>(I.getOperand(1));
2699 }
Dan Gohman186a6362009-08-12 16:04:34 +00002700 Value *Neg = dyn_castNegVal(Op1);
Nick Lewycky0c730792008-11-21 07:33:58 +00002701 if (BO && BO->hasOneUse() &&
2702 (BO->getOperand(1) == Op1 || BO->getOperand(1) == Neg) &&
2703 (BO->getOpcode() == Instruction::UDiv ||
2704 BO->getOpcode() == Instruction::SDiv)) {
2705 Value *Op0BO = BO->getOperand(0), *Op1BO = BO->getOperand(1);
2706
2707 Instruction *Rem;
2708 if (BO->getOpcode() == Instruction::UDiv)
2709 Rem = BinaryOperator::CreateURem(Op0BO, Op1BO);
2710 else
2711 Rem = BinaryOperator::CreateSRem(Op0BO, Op1BO);
2712
2713 InsertNewInstBefore(Rem, I);
2714 Rem->takeName(BO);
2715
2716 if (Op1BO == Op1)
2717 return BinaryOperator::CreateSub(Op0BO, Rem);
2718 else
2719 return BinaryOperator::CreateSub(Rem, Op0BO);
2720 }
2721 }
2722
Nick Lewycky9419ddb2008-05-31 17:59:52 +00002723 if (I.getType() == Type::Int1Ty)
2724 return BinaryOperator::CreateAnd(Op0, I.getOperand(1));
2725
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002726 // If one of the operands of the multiply is a cast from a boolean value, then
2727 // we know the bool is either zero or one, so this is a 'masking' multiply.
2728 // See if we can simplify things based on how the boolean was originally
2729 // formed.
2730 CastInst *BoolCast = 0;
Nick Lewycky9419ddb2008-05-31 17:59:52 +00002731 if (ZExtInst *CI = dyn_cast<ZExtInst>(Op0))
Reid Spencer4fe16d62007-01-11 18:21:29 +00002732 if (CI->getOperand(0)->getType() == Type::Int1Ty)
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002733 BoolCast = CI;
2734 if (!BoolCast)
Reid Spencerc55b2432006-12-13 18:21:21 +00002735 if (ZExtInst *CI = dyn_cast<ZExtInst>(I.getOperand(1)))
Reid Spencer4fe16d62007-01-11 18:21:29 +00002736 if (CI->getOperand(0)->getType() == Type::Int1Ty)
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002737 BoolCast = CI;
2738 if (BoolCast) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00002739 if (ICmpInst *SCI = dyn_cast<ICmpInst>(BoolCast->getOperand(0))) {
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002740 Value *SCIOp0 = SCI->getOperand(0), *SCIOp1 = SCI->getOperand(1);
2741 const Type *SCOpTy = SCIOp0->getType();
Chris Lattnera0141b92007-07-15 20:42:37 +00002742 bool TIS = false;
2743
Reid Spencere4d87aa2006-12-23 06:05:41 +00002744 // If the icmp is true iff the sign bit of X is set, then convert this
Chris Lattner4cb170c2004-02-23 06:38:22 +00002745 // multiply into a shift/and combination.
2746 if (isa<ConstantInt>(SCIOp1) &&
Chris Lattnera0141b92007-07-15 20:42:37 +00002747 isSignBitCheck(SCI->getPredicate(), cast<ConstantInt>(SCIOp1), TIS) &&
2748 TIS) {
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002749 // Shift the X value right to turn it into "all signbits".
Owen Andersoneed707b2009-07-24 23:12:02 +00002750 Constant *Amt = ConstantInt::get(SCIOp0->getType(),
Chris Lattner484d3cf2005-04-24 06:59:08 +00002751 SCOpTy->getPrimitiveSizeInBits()-1);
Chris Lattner4cb170c2004-02-23 06:38:22 +00002752 Value *V =
Reid Spencer832254e2007-02-02 02:16:23 +00002753 InsertNewInstBefore(
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002754 BinaryOperator::Create(Instruction::AShr, SCIOp0, Amt,
Chris Lattner4cb170c2004-02-23 06:38:22 +00002755 BoolCast->getOperand(0)->getName()+
2756 ".mask"), I);
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002757
2758 // If the multiply type is not the same as the source type, sign extend
2759 // or truncate to the multiply type.
Reid Spencer17212df2006-12-12 09:18:51 +00002760 if (I.getType() != V->getType()) {
Zhou Sheng4351c642007-04-02 08:20:41 +00002761 uint32_t SrcBits = V->getType()->getPrimitiveSizeInBits();
2762 uint32_t DstBits = I.getType()->getPrimitiveSizeInBits();
Reid Spencer17212df2006-12-12 09:18:51 +00002763 Instruction::CastOps opcode =
2764 (SrcBits == DstBits ? Instruction::BitCast :
2765 (SrcBits < DstBits ? Instruction::SExt : Instruction::Trunc));
2766 V = InsertCastBefore(opcode, V, I.getType(), I);
2767 }
Misha Brukmanfd939082005-04-21 23:48:37 +00002768
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002769 Value *OtherOp = Op0 == BoolCast ? I.getOperand(1) : Op0;
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002770 return BinaryOperator::CreateAnd(V, OtherOp);
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002771 }
2772 }
2773 }
2774
Chris Lattner7e708292002-06-25 16:13:24 +00002775 return Changed ? &I : 0;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002776}
2777
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002778Instruction *InstCombiner::visitFMul(BinaryOperator &I) {
2779 bool Changed = SimplifyCommutative(I);
2780 Value *Op0 = I.getOperand(0);
2781
2782 // Simplify mul instructions with a constant RHS...
2783 if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
2784 if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1)) {
2785 // "In IEEE floating point, x*1 is not equivalent to x for nans. However,
2786 // ANSI says we can drop signals, so we can do this anyway." (from GCC)
2787 if (Op1F->isExactlyValue(1.0))
2788 return ReplaceInstUsesWith(I, Op0); // Eliminate 'mul double %X, 1.0'
2789 } else if (isa<VectorType>(Op1->getType())) {
2790 if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1)) {
2791 // As above, vector X*splat(1.0) -> X in all defined cases.
2792 if (Constant *Splat = Op1V->getSplatValue()) {
2793 if (ConstantFP *F = dyn_cast<ConstantFP>(Splat))
2794 if (F->isExactlyValue(1.0))
2795 return ReplaceInstUsesWith(I, Op0);
2796 }
2797 }
2798 }
2799
2800 // Try to fold constant mul into select arguments.
2801 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2802 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2803 return R;
2804
2805 if (isa<PHINode>(Op0))
2806 if (Instruction *NV = FoldOpIntoPhi(I))
2807 return NV;
2808 }
2809
Dan Gohman186a6362009-08-12 16:04:34 +00002810 if (Value *Op0v = dyn_castFNegVal(Op0)) // -X * -Y = X*Y
2811 if (Value *Op1v = dyn_castFNegVal(I.getOperand(1)))
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002812 return BinaryOperator::CreateFMul(Op0v, Op1v);
2813
2814 return Changed ? &I : 0;
2815}
2816
Chris Lattnerfdb19e52008-07-14 00:15:52 +00002817/// SimplifyDivRemOfSelect - Try to fold a divide or remainder of a select
2818/// instruction.
2819bool InstCombiner::SimplifyDivRemOfSelect(BinaryOperator &I) {
2820 SelectInst *SI = cast<SelectInst>(I.getOperand(1));
2821
2822 // div/rem X, (Cond ? 0 : Y) -> div/rem X, Y
2823 int NonNullOperand = -1;
2824 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
2825 if (ST->isNullValue())
2826 NonNullOperand = 2;
2827 // div/rem X, (Cond ? Y : 0) -> div/rem X, Y
2828 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
2829 if (ST->isNullValue())
2830 NonNullOperand = 1;
2831
2832 if (NonNullOperand == -1)
2833 return false;
2834
2835 Value *SelectCond = SI->getOperand(0);
2836
2837 // Change the div/rem to use 'Y' instead of the select.
2838 I.setOperand(1, SI->getOperand(NonNullOperand));
2839
2840 // Okay, we know we replace the operand of the div/rem with 'Y' with no
2841 // problem. However, the select, or the condition of the select may have
2842 // multiple uses. Based on our knowledge that the operand must be non-zero,
2843 // propagate the known value for the select into other uses of it, and
2844 // propagate a known value of the condition into its other users.
2845
2846 // If the select and condition only have a single use, don't bother with this,
2847 // early exit.
2848 if (SI->use_empty() && SelectCond->hasOneUse())
2849 return true;
2850
2851 // Scan the current block backward, looking for other uses of SI.
2852 BasicBlock::iterator BBI = &I, BBFront = I.getParent()->begin();
2853
2854 while (BBI != BBFront) {
2855 --BBI;
2856 // If we found a call to a function, we can't assume it will return, so
2857 // information from below it cannot be propagated above it.
2858 if (isa<CallInst>(BBI) && !isa<IntrinsicInst>(BBI))
2859 break;
2860
2861 // Replace uses of the select or its condition with the known values.
2862 for (Instruction::op_iterator I = BBI->op_begin(), E = BBI->op_end();
2863 I != E; ++I) {
2864 if (*I == SI) {
2865 *I = SI->getOperand(NonNullOperand);
2866 AddToWorkList(BBI);
2867 } else if (*I == SelectCond) {
Owen Anderson5defacc2009-07-31 17:39:07 +00002868 *I = NonNullOperand == 1 ? ConstantInt::getTrue(*Context) :
2869 ConstantInt::getFalse(*Context);
Chris Lattnerfdb19e52008-07-14 00:15:52 +00002870 AddToWorkList(BBI);
2871 }
2872 }
2873
2874 // If we past the instruction, quit looking for it.
2875 if (&*BBI == SI)
2876 SI = 0;
2877 if (&*BBI == SelectCond)
2878 SelectCond = 0;
2879
2880 // If we ran out of things to eliminate, break out of the loop.
2881 if (SelectCond == 0 && SI == 0)
2882 break;
2883
2884 }
2885 return true;
2886}
2887
2888
Reid Spencer1628cec2006-10-26 06:15:43 +00002889/// This function implements the transforms on div instructions that work
2890/// regardless of the kind of div instruction it is (udiv, sdiv, or fdiv). It is
2891/// used by the visitors to those instructions.
2892/// @brief Transforms common to all three div instructions
Reid Spencer3da59db2006-11-27 01:05:10 +00002893Instruction *InstCombiner::commonDivTransforms(BinaryOperator &I) {
Chris Lattner857e8cd2004-12-12 21:48:58 +00002894 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnere87597f2004-10-16 18:11:37 +00002895
Chris Lattner50b2ca42008-02-19 06:12:18 +00002896 // undef / X -> 0 for integer.
2897 // undef / X -> undef for FP (the undef could be a snan).
2898 if (isa<UndefValue>(Op0)) {
2899 if (Op0->getType()->isFPOrFPVector())
2900 return ReplaceInstUsesWith(I, Op0);
Owen Andersona7235ea2009-07-31 20:28:14 +00002901 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner50b2ca42008-02-19 06:12:18 +00002902 }
Reid Spencer1628cec2006-10-26 06:15:43 +00002903
2904 // X / undef -> undef
Chris Lattner857e8cd2004-12-12 21:48:58 +00002905 if (isa<UndefValue>(Op1))
Reid Spencer1628cec2006-10-26 06:15:43 +00002906 return ReplaceInstUsesWith(I, Op1);
Chris Lattner857e8cd2004-12-12 21:48:58 +00002907
Reid Spencer1628cec2006-10-26 06:15:43 +00002908 return 0;
2909}
Misha Brukmanfd939082005-04-21 23:48:37 +00002910
Reid Spencer1628cec2006-10-26 06:15:43 +00002911/// This function implements the transforms common to both integer division
2912/// instructions (udiv and sdiv). It is called by the visitors to those integer
2913/// division instructions.
2914/// @brief Common integer divide transforms
Reid Spencer3da59db2006-11-27 01:05:10 +00002915Instruction *InstCombiner::commonIDivTransforms(BinaryOperator &I) {
Reid Spencer1628cec2006-10-26 06:15:43 +00002916 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2917
Chris Lattnerb2ae9e32008-05-16 02:59:42 +00002918 // (sdiv X, X) --> 1 (udiv X, X) --> 1
Nick Lewycky39ac3b52008-05-23 03:26:47 +00002919 if (Op0 == Op1) {
2920 if (const VectorType *Ty = dyn_cast<VectorType>(I.getType())) {
Owen Andersoneed707b2009-07-24 23:12:02 +00002921 Constant *CI = ConstantInt::get(Ty->getElementType(), 1);
Nick Lewycky39ac3b52008-05-23 03:26:47 +00002922 std::vector<Constant*> Elts(Ty->getNumElements(), CI);
Owen Andersonaf7ec972009-07-28 21:19:26 +00002923 return ReplaceInstUsesWith(I, ConstantVector::get(Elts));
Nick Lewycky39ac3b52008-05-23 03:26:47 +00002924 }
2925
Owen Andersoneed707b2009-07-24 23:12:02 +00002926 Constant *CI = ConstantInt::get(I.getType(), 1);
Nick Lewycky39ac3b52008-05-23 03:26:47 +00002927 return ReplaceInstUsesWith(I, CI);
2928 }
Chris Lattnerb2ae9e32008-05-16 02:59:42 +00002929
Reid Spencer1628cec2006-10-26 06:15:43 +00002930 if (Instruction *Common = commonDivTransforms(I))
2931 return Common;
Chris Lattnerfdb19e52008-07-14 00:15:52 +00002932
2933 // Handle cases involving: [su]div X, (select Cond, Y, Z)
2934 // This does not apply for fdiv.
2935 if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
2936 return &I;
Reid Spencer1628cec2006-10-26 06:15:43 +00002937
2938 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2939 // div X, 1 == X
2940 if (RHS->equalsInt(1))
2941 return ReplaceInstUsesWith(I, Op0);
2942
2943 // (X / C1) / C2 -> X / (C1*C2)
2944 if (Instruction *LHS = dyn_cast<Instruction>(Op0))
2945 if (Instruction::BinaryOps(LHS->getOpcode()) == I.getOpcode())
2946 if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
Owen Andersond672ecb2009-07-03 00:17:18 +00002947 if (MultiplyOverflows(RHS, LHSRHS,
Dan Gohman186a6362009-08-12 16:04:34 +00002948 I.getOpcode()==Instruction::SDiv))
Owen Andersona7235ea2009-07-31 20:28:14 +00002949 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Nick Lewyckye0cfecf2008-02-18 22:48:05 +00002950 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002951 return BinaryOperator::Create(I.getOpcode(), LHS->getOperand(0),
Owen Andersonbaf3c402009-07-29 18:55:55 +00002952 ConstantExpr::getMul(RHS, LHSRHS));
Chris Lattnerbf70b832005-04-08 04:03:26 +00002953 }
Reid Spencer1628cec2006-10-26 06:15:43 +00002954
Reid Spencerbca0e382007-03-23 20:05:17 +00002955 if (!RHS->isZero()) { // avoid X udiv 0
Reid Spencer1628cec2006-10-26 06:15:43 +00002956 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2957 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2958 return R;
2959 if (isa<PHINode>(Op0))
2960 if (Instruction *NV = FoldOpIntoPhi(I))
2961 return NV;
2962 }
Chris Lattner8e49e082006-09-09 20:26:32 +00002963 }
Misha Brukmanfd939082005-04-21 23:48:37 +00002964
Chris Lattnera2881962003-02-18 19:28:33 +00002965 // 0 / X == 0, we don't need to preserve faults!
Chris Lattner857e8cd2004-12-12 21:48:58 +00002966 if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
Chris Lattnera2881962003-02-18 19:28:33 +00002967 if (LHS->equalsInt(0))
Owen Andersona7235ea2009-07-31 20:28:14 +00002968 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnera2881962003-02-18 19:28:33 +00002969
Nick Lewycky9419ddb2008-05-31 17:59:52 +00002970 // It can't be division by zero, hence it must be division by one.
2971 if (I.getType() == Type::Int1Ty)
2972 return ReplaceInstUsesWith(I, Op0);
2973
Nick Lewycky895f0852008-11-27 20:21:08 +00002974 if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1)) {
2975 if (ConstantInt *X = cast_or_null<ConstantInt>(Op1V->getSplatValue()))
2976 // div X, 1 == X
2977 if (X->isOne())
2978 return ReplaceInstUsesWith(I, Op0);
2979 }
2980
Reid Spencer1628cec2006-10-26 06:15:43 +00002981 return 0;
2982}
2983
2984Instruction *InstCombiner::visitUDiv(BinaryOperator &I) {
2985 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2986
2987 // Handle the integer div common cases
2988 if (Instruction *Common = commonIDivTransforms(I))
2989 return Common;
2990
Reid Spencer1628cec2006-10-26 06:15:43 +00002991 if (ConstantInt *C = dyn_cast<ConstantInt>(Op1)) {
Nick Lewycky8ca52482008-11-27 22:41:10 +00002992 // X udiv C^2 -> X >> C
2993 // Check to see if this is an unsigned division with an exact power of 2,
2994 // if so, convert to a right shift.
Reid Spencer6eb0d992007-03-26 23:58:26 +00002995 if (C->getValue().isPowerOf2()) // 0 not included in isPowerOf2
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002996 return BinaryOperator::CreateLShr(Op0,
Owen Andersoneed707b2009-07-24 23:12:02 +00002997 ConstantInt::get(Op0->getType(), C->getValue().logBase2()));
Nick Lewycky8ca52482008-11-27 22:41:10 +00002998
2999 // X udiv C, where C >= signbit
3000 if (C->getValue().isNegative()) {
Owen Anderson333c4002009-07-09 23:48:35 +00003001 Value *IC = InsertNewInstBefore(new ICmpInst(*Context,
3002 ICmpInst::ICMP_ULT, Op0, C),
Nick Lewycky8ca52482008-11-27 22:41:10 +00003003 I);
Owen Andersona7235ea2009-07-31 20:28:14 +00003004 return SelectInst::Create(IC, Constant::getNullValue(I.getType()),
Owen Andersoneed707b2009-07-24 23:12:02 +00003005 ConstantInt::get(I.getType(), 1));
Nick Lewycky8ca52482008-11-27 22:41:10 +00003006 }
Reid Spencer1628cec2006-10-26 06:15:43 +00003007 }
3008
3009 // X udiv (C1 << N), where C1 is "1<<C2" --> X >> (N+C2)
Reid Spencer832254e2007-02-02 02:16:23 +00003010 if (BinaryOperator *RHSI = dyn_cast<BinaryOperator>(I.getOperand(1))) {
Reid Spencer1628cec2006-10-26 06:15:43 +00003011 if (RHSI->getOpcode() == Instruction::Shl &&
3012 isa<ConstantInt>(RHSI->getOperand(0))) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003013 const APInt& C1 = cast<ConstantInt>(RHSI->getOperand(0))->getValue();
Reid Spencerbca0e382007-03-23 20:05:17 +00003014 if (C1.isPowerOf2()) {
Reid Spencer1628cec2006-10-26 06:15:43 +00003015 Value *N = RHSI->getOperand(1);
Reid Spencer3da59db2006-11-27 01:05:10 +00003016 const Type *NTy = N->getType();
Reid Spencer2ec619a2007-03-23 21:24:59 +00003017 if (uint32_t C2 = C1.logBase2()) {
Owen Andersoneed707b2009-07-24 23:12:02 +00003018 Constant *C2V = ConstantInt::get(NTy, C2);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003019 N = InsertNewInstBefore(BinaryOperator::CreateAdd(N, C2V, "tmp"), I);
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003020 }
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003021 return BinaryOperator::CreateLShr(Op0, N);
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003022 }
3023 }
Chris Lattnerc812e5d2005-11-05 07:40:31 +00003024 }
3025
Reid Spencer1628cec2006-10-26 06:15:43 +00003026 // udiv X, (Select Cond, C1, C2) --> Select Cond, (shr X, C1), (shr X, C2)
3027 // where C1&C2 are powers of two.
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003028 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Reid Spencer1628cec2006-10-26 06:15:43 +00003029 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003030 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003031 const APInt &TVA = STO->getValue(), &FVA = SFO->getValue();
Reid Spencerbca0e382007-03-23 20:05:17 +00003032 if (TVA.isPowerOf2() && FVA.isPowerOf2()) {
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003033 // Compute the shift amounts
Reid Spencerbca0e382007-03-23 20:05:17 +00003034 uint32_t TSA = TVA.logBase2(), FSA = FVA.logBase2();
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003035 // Construct the "on true" case of the select
Owen Andersoneed707b2009-07-24 23:12:02 +00003036 Constant *TC = ConstantInt::get(Op0->getType(), TSA);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003037 Instruction *TSI = BinaryOperator::CreateLShr(
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003038 Op0, TC, SI->getName()+".t");
3039 TSI = InsertNewInstBefore(TSI, I);
3040
3041 // Construct the "on false" case of the select
Owen Andersoneed707b2009-07-24 23:12:02 +00003042 Constant *FC = ConstantInt::get(Op0->getType(), FSA);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003043 Instruction *FSI = BinaryOperator::CreateLShr(
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003044 Op0, FC, SI->getName()+".f");
3045 FSI = InsertNewInstBefore(FSI, I);
Reid Spencer1628cec2006-10-26 06:15:43 +00003046
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003047 // construct the select instruction and return it.
Gabor Greif051a9502008-04-06 20:25:17 +00003048 return SelectInst::Create(SI->getOperand(0), TSI, FSI, SI->getName());
Reid Spencer1628cec2006-10-26 06:15:43 +00003049 }
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003050 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00003051 return 0;
3052}
3053
Reid Spencer1628cec2006-10-26 06:15:43 +00003054Instruction *InstCombiner::visitSDiv(BinaryOperator &I) {
3055 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3056
3057 // Handle the integer div common cases
3058 if (Instruction *Common = commonIDivTransforms(I))
3059 return Common;
3060
3061 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3062 // sdiv X, -1 == -X
3063 if (RHS->isAllOnesValue())
Owen Anderson0a5372e2009-07-13 04:09:18 +00003064 return BinaryOperator::CreateNeg(*Context, Op0);
Dan Gohman1bdf5dc2009-08-11 20:47:47 +00003065
3066 // sdiv X, C --> ashr X, log2(C)
3067 if (cast<SDivOperator>(&I)->isExact() &&
3068 RHS->getValue().isNonNegative() &&
3069 RHS->getValue().isPowerOf2()) {
3070 Value *ShAmt = llvm::ConstantInt::get(RHS->getType(),
3071 RHS->getValue().exactLogBase2());
3072 return BinaryOperator::CreateAShr(Op0, ShAmt, I.getName());
3073 }
Reid Spencer1628cec2006-10-26 06:15:43 +00003074 }
3075
3076 // If the sign bits of both operands are zero (i.e. we can prove they are
3077 // unsigned inputs), turn this into a udiv.
Chris Lattner42a75512007-01-15 02:27:26 +00003078 if (I.getType()->isInteger()) {
Reid Spencerbca0e382007-03-23 20:05:17 +00003079 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
Eli Friedman8be17392009-07-18 09:53:21 +00003080 if (MaskedValueIsZero(Op0, Mask)) {
3081 if (MaskedValueIsZero(Op1, Mask)) {
3082 // X sdiv Y -> X udiv Y, iff X and Y don't have sign bit set
3083 return BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
3084 }
3085 ConstantInt *ShiftedInt;
3086 if (match(Op1, m_Shl(m_ConstantInt(ShiftedInt), m_Value()), *Context) &&
3087 ShiftedInt->getValue().isPowerOf2()) {
3088 // X sdiv (1 << Y) -> X udiv (1 << Y) ( -> X u>> Y)
3089 // Safe because the only negative value (1 << Y) can take on is
3090 // INT_MIN, and X sdiv INT_MIN == X udiv INT_MIN == 0 if X doesn't have
3091 // the sign bit set.
3092 return BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
3093 }
Reid Spencer1628cec2006-10-26 06:15:43 +00003094 }
Eli Friedman8be17392009-07-18 09:53:21 +00003095 }
Reid Spencer1628cec2006-10-26 06:15:43 +00003096
3097 return 0;
3098}
3099
3100Instruction *InstCombiner::visitFDiv(BinaryOperator &I) {
3101 return commonDivTransforms(I);
3102}
Chris Lattner3f5b8772002-05-06 16:14:14 +00003103
Reid Spencer0a783f72006-11-02 01:53:59 +00003104/// This function implements the transforms on rem instructions that work
3105/// regardless of the kind of rem instruction it is (urem, srem, or frem). It
3106/// is used by the visitors to those instructions.
3107/// @brief Transforms common to all three rem instructions
3108Instruction *InstCombiner::commonRemTransforms(BinaryOperator &I) {
Chris Lattner857e8cd2004-12-12 21:48:58 +00003109 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Reid Spencer0a783f72006-11-02 01:53:59 +00003110
Chris Lattner50b2ca42008-02-19 06:12:18 +00003111 if (isa<UndefValue>(Op0)) { // undef % X -> 0
3112 if (I.getType()->isFPOrFPVector())
3113 return ReplaceInstUsesWith(I, Op0); // X % undef -> undef (could be SNaN)
Owen Andersona7235ea2009-07-31 20:28:14 +00003114 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner50b2ca42008-02-19 06:12:18 +00003115 }
Chris Lattner19ccd5c2006-02-28 05:30:45 +00003116 if (isa<UndefValue>(Op1))
3117 return ReplaceInstUsesWith(I, Op1); // X % undef -> undef
Reid Spencer0a783f72006-11-02 01:53:59 +00003118
3119 // Handle cases involving: rem X, (select Cond, Y, Z)
Chris Lattnerfdb19e52008-07-14 00:15:52 +00003120 if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
3121 return &I;
Chris Lattner5b73c082004-07-06 07:01:22 +00003122
Reid Spencer0a783f72006-11-02 01:53:59 +00003123 return 0;
3124}
3125
3126/// This function implements the transforms common to both integer remainder
3127/// instructions (urem and srem). It is called by the visitors to those integer
3128/// remainder instructions.
3129/// @brief Common integer remainder transforms
3130Instruction *InstCombiner::commonIRemTransforms(BinaryOperator &I) {
3131 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3132
3133 if (Instruction *common = commonRemTransforms(I))
3134 return common;
3135
Dale Johannesened6af242009-01-21 00:35:19 +00003136 // 0 % X == 0 for integer, we don't need to preserve faults!
3137 if (Constant *LHS = dyn_cast<Constant>(Op0))
3138 if (LHS->isNullValue())
Owen Andersona7235ea2009-07-31 20:28:14 +00003139 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Dale Johannesened6af242009-01-21 00:35:19 +00003140
Chris Lattner857e8cd2004-12-12 21:48:58 +00003141 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner19ccd5c2006-02-28 05:30:45 +00003142 // X % 0 == undef, we don't need to preserve faults!
3143 if (RHS->equalsInt(0))
Owen Anderson9e9a0d52009-07-30 23:03:37 +00003144 return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
Chris Lattner19ccd5c2006-02-28 05:30:45 +00003145
Chris Lattnera2881962003-02-18 19:28:33 +00003146 if (RHS->equalsInt(1)) // X % 1 == 0
Owen Andersona7235ea2009-07-31 20:28:14 +00003147 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnera2881962003-02-18 19:28:33 +00003148
Chris Lattner97943922006-02-28 05:49:21 +00003149 if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
3150 if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
3151 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3152 return R;
3153 } else if (isa<PHINode>(Op0I)) {
3154 if (Instruction *NV = FoldOpIntoPhi(I))
3155 return NV;
Chris Lattner97943922006-02-28 05:49:21 +00003156 }
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00003157
3158 // See if we can fold away this rem instruction.
Chris Lattner886ab6c2009-01-31 08:15:18 +00003159 if (SimplifyDemandedInstructionBits(I))
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00003160 return &I;
Chris Lattner97943922006-02-28 05:49:21 +00003161 }
Chris Lattnera2881962003-02-18 19:28:33 +00003162 }
3163
Reid Spencer0a783f72006-11-02 01:53:59 +00003164 return 0;
3165}
3166
3167Instruction *InstCombiner::visitURem(BinaryOperator &I) {
3168 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3169
3170 if (Instruction *common = commonIRemTransforms(I))
3171 return common;
3172
3173 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3174 // X urem C^2 -> X and C
3175 // Check to see if this is an unsigned remainder with an exact power of 2,
3176 // if so, convert to a bitwise and.
3177 if (ConstantInt *C = dyn_cast<ConstantInt>(RHS))
Reid Spencerbca0e382007-03-23 20:05:17 +00003178 if (C->getValue().isPowerOf2())
Dan Gohman186a6362009-08-12 16:04:34 +00003179 return BinaryOperator::CreateAnd(Op0, SubOne(C));
Reid Spencer0a783f72006-11-02 01:53:59 +00003180 }
3181
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003182 if (Instruction *RHSI = dyn_cast<Instruction>(I.getOperand(1))) {
Reid Spencer0a783f72006-11-02 01:53:59 +00003183 // Turn A % (C << N), where C is 2^k, into A & ((C << N)-1)
3184 if (RHSI->getOpcode() == Instruction::Shl &&
3185 isa<ConstantInt>(RHSI->getOperand(0))) {
Zhou Sheng0fc50952007-03-25 05:01:29 +00003186 if (cast<ConstantInt>(RHSI->getOperand(0))->getValue().isPowerOf2()) {
Owen Andersona7235ea2009-07-31 20:28:14 +00003187 Constant *N1 = Constant::getAllOnesValue(I.getType());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003188 Value *Add = InsertNewInstBefore(BinaryOperator::CreateAdd(RHSI, N1,
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003189 "tmp"), I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003190 return BinaryOperator::CreateAnd(Op0, Add);
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003191 }
3192 }
Reid Spencer0a783f72006-11-02 01:53:59 +00003193 }
Chris Lattner8e49e082006-09-09 20:26:32 +00003194
Reid Spencer0a783f72006-11-02 01:53:59 +00003195 // urem X, (select Cond, 2^C1, 2^C2) --> select Cond, (and X, C1), (and X, C2)
3196 // where C1&C2 are powers of two.
3197 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
3198 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
3199 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
3200 // STO == 0 and SFO == 0 handled above.
Reid Spencerbca0e382007-03-23 20:05:17 +00003201 if ((STO->getValue().isPowerOf2()) &&
3202 (SFO->getValue().isPowerOf2())) {
Reid Spencer0a783f72006-11-02 01:53:59 +00003203 Value *TrueAnd = InsertNewInstBefore(
Dan Gohman186a6362009-08-12 16:04:34 +00003204 BinaryOperator::CreateAnd(Op0, SubOne(STO),
Owen Andersond672ecb2009-07-03 00:17:18 +00003205 SI->getName()+".t"), I);
Reid Spencer0a783f72006-11-02 01:53:59 +00003206 Value *FalseAnd = InsertNewInstBefore(
Dan Gohman186a6362009-08-12 16:04:34 +00003207 BinaryOperator::CreateAnd(Op0, SubOne(SFO),
Owen Andersond672ecb2009-07-03 00:17:18 +00003208 SI->getName()+".f"), I);
Gabor Greif051a9502008-04-06 20:25:17 +00003209 return SelectInst::Create(SI->getOperand(0), TrueAnd, FalseAnd);
Reid Spencer0a783f72006-11-02 01:53:59 +00003210 }
3211 }
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003212 }
3213
Chris Lattner3f5b8772002-05-06 16:14:14 +00003214 return 0;
3215}
3216
Reid Spencer0a783f72006-11-02 01:53:59 +00003217Instruction *InstCombiner::visitSRem(BinaryOperator &I) {
3218 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3219
Dan Gohmancff55092007-11-05 23:16:33 +00003220 // Handle the integer rem common cases
Reid Spencer0a783f72006-11-02 01:53:59 +00003221 if (Instruction *common = commonIRemTransforms(I))
3222 return common;
3223
Dan Gohman186a6362009-08-12 16:04:34 +00003224 if (Value *RHSNeg = dyn_castNegVal(Op1))
Nick Lewycky23c04302008-09-03 06:24:21 +00003225 if (!isa<Constant>(RHSNeg) ||
3226 (isa<ConstantInt>(RHSNeg) &&
3227 cast<ConstantInt>(RHSNeg)->getValue().isStrictlyPositive())) {
Reid Spencer0a783f72006-11-02 01:53:59 +00003228 // X % -Y -> X % Y
3229 AddUsesToWorkList(I);
3230 I.setOperand(1, RHSNeg);
3231 return &I;
3232 }
Nick Lewyckya06cf822008-09-30 06:08:34 +00003233
Dan Gohmancff55092007-11-05 23:16:33 +00003234 // If the sign bits of both operands are zero (i.e. we can prove they are
Reid Spencer0a783f72006-11-02 01:53:59 +00003235 // unsigned inputs), turn this into a urem.
Dan Gohmancff55092007-11-05 23:16:33 +00003236 if (I.getType()->isInteger()) {
3237 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
3238 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
3239 // X srem Y -> X urem Y, iff X and Y don't have sign bit set
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003240 return BinaryOperator::CreateURem(Op0, Op1, I.getName());
Dan Gohmancff55092007-11-05 23:16:33 +00003241 }
Reid Spencer0a783f72006-11-02 01:53:59 +00003242 }
3243
Nick Lewycky2a8f6592008-12-18 06:31:11 +00003244 // If it's a constant vector, flip any negative values positive.
Nick Lewycky9dce8732008-12-20 16:48:00 +00003245 if (ConstantVector *RHSV = dyn_cast<ConstantVector>(Op1)) {
3246 unsigned VWidth = RHSV->getNumOperands();
Nick Lewycky2a8f6592008-12-18 06:31:11 +00003247
Nick Lewycky9dce8732008-12-20 16:48:00 +00003248 bool hasNegative = false;
3249 for (unsigned i = 0; !hasNegative && i != VWidth; ++i)
3250 if (ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV->getOperand(i)))
3251 if (RHS->getValue().isNegative())
3252 hasNegative = true;
3253
3254 if (hasNegative) {
3255 std::vector<Constant *> Elts(VWidth);
Nick Lewycky2a8f6592008-12-18 06:31:11 +00003256 for (unsigned i = 0; i != VWidth; ++i) {
3257 if (ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV->getOperand(i))) {
3258 if (RHS->getValue().isNegative())
Owen Andersonbaf3c402009-07-29 18:55:55 +00003259 Elts[i] = cast<ConstantInt>(ConstantExpr::getNeg(RHS));
Nick Lewycky2a8f6592008-12-18 06:31:11 +00003260 else
3261 Elts[i] = RHS;
3262 }
3263 }
3264
Owen Andersonaf7ec972009-07-28 21:19:26 +00003265 Constant *NewRHSV = ConstantVector::get(Elts);
Nick Lewycky2a8f6592008-12-18 06:31:11 +00003266 if (NewRHSV != RHSV) {
Nick Lewycky19c28922008-12-18 06:42:28 +00003267 AddUsesToWorkList(I);
Nick Lewycky2a8f6592008-12-18 06:31:11 +00003268 I.setOperand(1, NewRHSV);
3269 return &I;
3270 }
3271 }
3272 }
3273
Reid Spencer0a783f72006-11-02 01:53:59 +00003274 return 0;
3275}
3276
3277Instruction *InstCombiner::visitFRem(BinaryOperator &I) {
Reid Spencer0a783f72006-11-02 01:53:59 +00003278 return commonRemTransforms(I);
3279}
3280
Chris Lattner457dd822004-06-09 07:59:58 +00003281// isOneBitSet - Return true if there is exactly one bit set in the specified
3282// constant.
3283static bool isOneBitSet(const ConstantInt *CI) {
Reid Spencer5f6a8952007-03-20 00:16:52 +00003284 return CI->getValue().isPowerOf2();
Chris Lattner457dd822004-06-09 07:59:58 +00003285}
3286
Chris Lattnerb20ba0a2004-09-23 21:46:38 +00003287// isHighOnes - Return true if the constant is of the form 1+0+.
3288// This is the same as lowones(~X).
3289static bool isHighOnes(const ConstantInt *CI) {
Zhou Sheng2cde46c2007-03-20 12:49:06 +00003290 return (~CI->getValue() + 1).isPowerOf2();
Chris Lattnerb20ba0a2004-09-23 21:46:38 +00003291}
3292
Reid Spencere4d87aa2006-12-23 06:05:41 +00003293/// getICmpCode - Encode a icmp predicate into a three bit mask. These bits
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003294/// are carefully arranged to allow folding of expressions such as:
3295///
3296/// (A < B) | (A > B) --> (A != B)
3297///
Reid Spencere4d87aa2006-12-23 06:05:41 +00003298/// Note that this is only valid if the first and second predicates have the
3299/// same sign. Is illegal to do: (A u< B) | (A s> B)
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003300///
Reid Spencere4d87aa2006-12-23 06:05:41 +00003301/// Three bits are used to represent the condition, as follows:
3302/// 0 A > B
3303/// 1 A == B
3304/// 2 A < B
3305///
3306/// <=> Value Definition
3307/// 000 0 Always false
3308/// 001 1 A > B
3309/// 010 2 A == B
3310/// 011 3 A >= B
3311/// 100 4 A < B
3312/// 101 5 A != B
3313/// 110 6 A <= B
3314/// 111 7 Always true
3315///
3316static unsigned getICmpCode(const ICmpInst *ICI) {
3317 switch (ICI->getPredicate()) {
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003318 // False -> 0
Reid Spencere4d87aa2006-12-23 06:05:41 +00003319 case ICmpInst::ICMP_UGT: return 1; // 001
3320 case ICmpInst::ICMP_SGT: return 1; // 001
3321 case ICmpInst::ICMP_EQ: return 2; // 010
3322 case ICmpInst::ICMP_UGE: return 3; // 011
3323 case ICmpInst::ICMP_SGE: return 3; // 011
3324 case ICmpInst::ICMP_ULT: return 4; // 100
3325 case ICmpInst::ICMP_SLT: return 4; // 100
3326 case ICmpInst::ICMP_NE: return 5; // 101
3327 case ICmpInst::ICMP_ULE: return 6; // 110
3328 case ICmpInst::ICMP_SLE: return 6; // 110
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003329 // True -> 7
3330 default:
Torok Edwinc23197a2009-07-14 16:55:14 +00003331 llvm_unreachable("Invalid ICmp predicate!");
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003332 return 0;
3333 }
3334}
3335
Evan Cheng8db90722008-10-14 17:15:11 +00003336/// getFCmpCode - Similar to getICmpCode but for FCmpInst. This encodes a fcmp
3337/// predicate into a three bit mask. It also returns whether it is an ordered
3338/// predicate by reference.
3339static unsigned getFCmpCode(FCmpInst::Predicate CC, bool &isOrdered) {
3340 isOrdered = false;
3341 switch (CC) {
3342 case FCmpInst::FCMP_ORD: isOrdered = true; return 0; // 000
3343 case FCmpInst::FCMP_UNO: return 0; // 000
Evan Cheng4990b252008-10-14 18:13:38 +00003344 case FCmpInst::FCMP_OGT: isOrdered = true; return 1; // 001
3345 case FCmpInst::FCMP_UGT: return 1; // 001
3346 case FCmpInst::FCMP_OEQ: isOrdered = true; return 2; // 010
3347 case FCmpInst::FCMP_UEQ: return 2; // 010
Evan Cheng8db90722008-10-14 17:15:11 +00003348 case FCmpInst::FCMP_OGE: isOrdered = true; return 3; // 011
3349 case FCmpInst::FCMP_UGE: return 3; // 011
3350 case FCmpInst::FCMP_OLT: isOrdered = true; return 4; // 100
3351 case FCmpInst::FCMP_ULT: return 4; // 100
Evan Cheng4990b252008-10-14 18:13:38 +00003352 case FCmpInst::FCMP_ONE: isOrdered = true; return 5; // 101
3353 case FCmpInst::FCMP_UNE: return 5; // 101
Evan Cheng8db90722008-10-14 17:15:11 +00003354 case FCmpInst::FCMP_OLE: isOrdered = true; return 6; // 110
3355 case FCmpInst::FCMP_ULE: return 6; // 110
Evan Cheng40300622008-10-14 18:44:08 +00003356 // True -> 7
Evan Cheng8db90722008-10-14 17:15:11 +00003357 default:
3358 // Not expecting FCMP_FALSE and FCMP_TRUE;
Torok Edwinc23197a2009-07-14 16:55:14 +00003359 llvm_unreachable("Unexpected FCmp predicate!");
Evan Cheng8db90722008-10-14 17:15:11 +00003360 return 0;
3361 }
3362}
3363
Reid Spencere4d87aa2006-12-23 06:05:41 +00003364/// getICmpValue - This is the complement of getICmpCode, which turns an
3365/// opcode and two operands into either a constant true or false, or a brand
Dan Gohman5d066ff2007-09-17 17:31:57 +00003366/// new ICmp instruction. The sign is passed in to determine which kind
Evan Cheng8db90722008-10-14 17:15:11 +00003367/// of predicate to use in the new icmp instruction.
Owen Andersond672ecb2009-07-03 00:17:18 +00003368static Value *getICmpValue(bool sign, unsigned code, Value *LHS, Value *RHS,
Owen Anderson07cf79e2009-07-06 23:00:19 +00003369 LLVMContext *Context) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00003370 switch (code) {
Torok Edwinc23197a2009-07-14 16:55:14 +00003371 default: llvm_unreachable("Illegal ICmp code!");
Owen Anderson5defacc2009-07-31 17:39:07 +00003372 case 0: return ConstantInt::getFalse(*Context);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003373 case 1:
3374 if (sign)
Owen Anderson333c4002009-07-09 23:48:35 +00003375 return new ICmpInst(*Context, ICmpInst::ICMP_SGT, LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003376 else
Owen Anderson333c4002009-07-09 23:48:35 +00003377 return new ICmpInst(*Context, ICmpInst::ICMP_UGT, LHS, RHS);
3378 case 2: return new ICmpInst(*Context, ICmpInst::ICMP_EQ, LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003379 case 3:
3380 if (sign)
Owen Anderson333c4002009-07-09 23:48:35 +00003381 return new ICmpInst(*Context, ICmpInst::ICMP_SGE, LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003382 else
Owen Anderson333c4002009-07-09 23:48:35 +00003383 return new ICmpInst(*Context, ICmpInst::ICMP_UGE, LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003384 case 4:
3385 if (sign)
Owen Anderson333c4002009-07-09 23:48:35 +00003386 return new ICmpInst(*Context, ICmpInst::ICMP_SLT, LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003387 else
Owen Anderson333c4002009-07-09 23:48:35 +00003388 return new ICmpInst(*Context, ICmpInst::ICMP_ULT, LHS, RHS);
3389 case 5: return new ICmpInst(*Context, ICmpInst::ICMP_NE, LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003390 case 6:
3391 if (sign)
Owen Anderson333c4002009-07-09 23:48:35 +00003392 return new ICmpInst(*Context, ICmpInst::ICMP_SLE, LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003393 else
Owen Anderson333c4002009-07-09 23:48:35 +00003394 return new ICmpInst(*Context, ICmpInst::ICMP_ULE, LHS, RHS);
Owen Anderson5defacc2009-07-31 17:39:07 +00003395 case 7: return ConstantInt::getTrue(*Context);
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003396 }
3397}
3398
Evan Cheng8db90722008-10-14 17:15:11 +00003399/// getFCmpValue - This is the complement of getFCmpCode, which turns an
3400/// opcode and two operands into either a FCmp instruction. isordered is passed
3401/// in to determine which kind of predicate to use in the new fcmp instruction.
3402static Value *getFCmpValue(bool isordered, unsigned code,
Owen Anderson07cf79e2009-07-06 23:00:19 +00003403 Value *LHS, Value *RHS, LLVMContext *Context) {
Evan Cheng8db90722008-10-14 17:15:11 +00003404 switch (code) {
Torok Edwinc23197a2009-07-14 16:55:14 +00003405 default: llvm_unreachable("Illegal FCmp code!");
Evan Cheng8db90722008-10-14 17:15:11 +00003406 case 0:
3407 if (isordered)
Owen Anderson333c4002009-07-09 23:48:35 +00003408 return new FCmpInst(*Context, FCmpInst::FCMP_ORD, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003409 else
Owen Anderson333c4002009-07-09 23:48:35 +00003410 return new FCmpInst(*Context, FCmpInst::FCMP_UNO, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003411 case 1:
3412 if (isordered)
Owen Anderson333c4002009-07-09 23:48:35 +00003413 return new FCmpInst(*Context, FCmpInst::FCMP_OGT, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003414 else
Owen Anderson333c4002009-07-09 23:48:35 +00003415 return new FCmpInst(*Context, FCmpInst::FCMP_UGT, LHS, RHS);
Evan Cheng4990b252008-10-14 18:13:38 +00003416 case 2:
3417 if (isordered)
Owen Anderson333c4002009-07-09 23:48:35 +00003418 return new FCmpInst(*Context, FCmpInst::FCMP_OEQ, LHS, RHS);
Evan Cheng4990b252008-10-14 18:13:38 +00003419 else
Owen Anderson333c4002009-07-09 23:48:35 +00003420 return new FCmpInst(*Context, FCmpInst::FCMP_UEQ, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003421 case 3:
3422 if (isordered)
Owen Anderson333c4002009-07-09 23:48:35 +00003423 return new FCmpInst(*Context, FCmpInst::FCMP_OGE, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003424 else
Owen Anderson333c4002009-07-09 23:48:35 +00003425 return new FCmpInst(*Context, FCmpInst::FCMP_UGE, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003426 case 4:
3427 if (isordered)
Owen Anderson333c4002009-07-09 23:48:35 +00003428 return new FCmpInst(*Context, FCmpInst::FCMP_OLT, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003429 else
Owen Anderson333c4002009-07-09 23:48:35 +00003430 return new FCmpInst(*Context, FCmpInst::FCMP_ULT, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003431 case 5:
3432 if (isordered)
Owen Anderson333c4002009-07-09 23:48:35 +00003433 return new FCmpInst(*Context, FCmpInst::FCMP_ONE, LHS, RHS);
Evan Cheng4990b252008-10-14 18:13:38 +00003434 else
Owen Anderson333c4002009-07-09 23:48:35 +00003435 return new FCmpInst(*Context, FCmpInst::FCMP_UNE, LHS, RHS);
Evan Cheng4990b252008-10-14 18:13:38 +00003436 case 6:
3437 if (isordered)
Owen Anderson333c4002009-07-09 23:48:35 +00003438 return new FCmpInst(*Context, FCmpInst::FCMP_OLE, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003439 else
Owen Anderson333c4002009-07-09 23:48:35 +00003440 return new FCmpInst(*Context, FCmpInst::FCMP_ULE, LHS, RHS);
Owen Anderson5defacc2009-07-31 17:39:07 +00003441 case 7: return ConstantInt::getTrue(*Context);
Evan Cheng8db90722008-10-14 17:15:11 +00003442 }
3443}
3444
Chris Lattnerb9553d62008-11-16 04:55:20 +00003445/// PredicatesFoldable - Return true if both predicates match sign or if at
3446/// least one of them is an equality comparison (which is signless).
Reid Spencere4d87aa2006-12-23 06:05:41 +00003447static bool PredicatesFoldable(ICmpInst::Predicate p1, ICmpInst::Predicate p2) {
3448 return (ICmpInst::isSignedPredicate(p1) == ICmpInst::isSignedPredicate(p2)) ||
Chris Lattnerb9553d62008-11-16 04:55:20 +00003449 (ICmpInst::isSignedPredicate(p1) && ICmpInst::isEquality(p2)) ||
3450 (ICmpInst::isSignedPredicate(p2) && ICmpInst::isEquality(p1));
Reid Spencere4d87aa2006-12-23 06:05:41 +00003451}
3452
3453namespace {
3454// FoldICmpLogical - Implements (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
3455struct FoldICmpLogical {
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003456 InstCombiner &IC;
3457 Value *LHS, *RHS;
Reid Spencere4d87aa2006-12-23 06:05:41 +00003458 ICmpInst::Predicate pred;
3459 FoldICmpLogical(InstCombiner &ic, ICmpInst *ICI)
3460 : IC(ic), LHS(ICI->getOperand(0)), RHS(ICI->getOperand(1)),
3461 pred(ICI->getPredicate()) {}
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003462 bool shouldApply(Value *V) const {
Reid Spencere4d87aa2006-12-23 06:05:41 +00003463 if (ICmpInst *ICI = dyn_cast<ICmpInst>(V))
3464 if (PredicatesFoldable(pred, ICI->getPredicate()))
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00003465 return ((ICI->getOperand(0) == LHS && ICI->getOperand(1) == RHS) ||
3466 (ICI->getOperand(0) == RHS && ICI->getOperand(1) == LHS));
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003467 return false;
3468 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00003469 Instruction *apply(Instruction &Log) const {
3470 ICmpInst *ICI = cast<ICmpInst>(Log.getOperand(0));
3471 if (ICI->getOperand(0) != LHS) {
3472 assert(ICI->getOperand(1) == LHS);
3473 ICI->swapOperands(); // Swap the LHS and RHS of the ICmp
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003474 }
3475
Chris Lattnerbc1dbfc2007-03-13 14:27:42 +00003476 ICmpInst *RHSICI = cast<ICmpInst>(Log.getOperand(1));
Reid Spencere4d87aa2006-12-23 06:05:41 +00003477 unsigned LHSCode = getICmpCode(ICI);
Chris Lattnerbc1dbfc2007-03-13 14:27:42 +00003478 unsigned RHSCode = getICmpCode(RHSICI);
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003479 unsigned Code;
3480 switch (Log.getOpcode()) {
3481 case Instruction::And: Code = LHSCode & RHSCode; break;
3482 case Instruction::Or: Code = LHSCode | RHSCode; break;
3483 case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
Torok Edwinc23197a2009-07-14 16:55:14 +00003484 default: llvm_unreachable("Illegal logical opcode!"); return 0;
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003485 }
3486
Chris Lattnerbc1dbfc2007-03-13 14:27:42 +00003487 bool isSigned = ICmpInst::isSignedPredicate(RHSICI->getPredicate()) ||
3488 ICmpInst::isSignedPredicate(ICI->getPredicate());
3489
Owen Andersond672ecb2009-07-03 00:17:18 +00003490 Value *RV = getICmpValue(isSigned, Code, LHS, RHS, IC.getContext());
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003491 if (Instruction *I = dyn_cast<Instruction>(RV))
3492 return I;
3493 // Otherwise, it's a constant boolean value...
3494 return IC.ReplaceInstUsesWith(Log, RV);
3495 }
3496};
Chris Lattnerd23b5ba2006-11-15 04:53:24 +00003497} // end anonymous namespace
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003498
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003499// OptAndOp - This handles expressions of the form ((val OP C1) & C2). Where
3500// the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'. Op is
Reid Spencer832254e2007-02-02 02:16:23 +00003501// guaranteed to be a binary operator.
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003502Instruction *InstCombiner::OptAndOp(Instruction *Op,
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003503 ConstantInt *OpRHS,
3504 ConstantInt *AndRHS,
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003505 BinaryOperator &TheAnd) {
3506 Value *X = Op->getOperand(0);
Chris Lattner76f7fe22004-01-12 19:47:05 +00003507 Constant *Together = 0;
Reid Spencer832254e2007-02-02 02:16:23 +00003508 if (!Op->isShift())
Owen Andersonbaf3c402009-07-29 18:55:55 +00003509 Together = ConstantExpr::getAnd(AndRHS, OpRHS);
Chris Lattner7c4049c2004-01-12 19:35:11 +00003510
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003511 switch (Op->getOpcode()) {
3512 case Instruction::Xor:
Chris Lattner6e7ba452005-01-01 16:22:27 +00003513 if (Op->hasOneUse()) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003514 // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003515 Instruction *And = BinaryOperator::CreateAnd(X, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003516 InsertNewInstBefore(And, TheAnd);
Chris Lattner6934a042007-02-11 01:23:03 +00003517 And->takeName(Op);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003518 return BinaryOperator::CreateXor(And, Together);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003519 }
3520 break;
3521 case Instruction::Or:
Chris Lattner6e7ba452005-01-01 16:22:27 +00003522 if (Together == AndRHS) // (X | C) & C --> C
3523 return ReplaceInstUsesWith(TheAnd, AndRHS);
Misha Brukmanfd939082005-04-21 23:48:37 +00003524
Chris Lattner6e7ba452005-01-01 16:22:27 +00003525 if (Op->hasOneUse() && Together != OpRHS) {
3526 // (X | C1) & C2 --> (X | (C1&C2)) & C2
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003527 Instruction *Or = BinaryOperator::CreateOr(X, Together);
Chris Lattner6e7ba452005-01-01 16:22:27 +00003528 InsertNewInstBefore(Or, TheAnd);
Chris Lattner6934a042007-02-11 01:23:03 +00003529 Or->takeName(Op);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003530 return BinaryOperator::CreateAnd(Or, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003531 }
3532 break;
3533 case Instruction::Add:
Chris Lattnerfd059242003-10-15 16:48:29 +00003534 if (Op->hasOneUse()) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003535 // Adding a one to a single bit bit-field should be turned into an XOR
3536 // of the bit. First thing to check is to see if this AND is with a
3537 // single bit constant.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003538 const APInt& AndRHSV = cast<ConstantInt>(AndRHS)->getValue();
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003539
3540 // If there is only one bit set...
Chris Lattner457dd822004-06-09 07:59:58 +00003541 if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003542 // Ok, at this point, we know that we are masking the result of the
3543 // ADD down to exactly one bit. If the constant we are adding has
3544 // no bits set below this bit, then we can eliminate the ADD.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003545 const APInt& AddRHS = cast<ConstantInt>(OpRHS)->getValue();
Misha Brukmanfd939082005-04-21 23:48:37 +00003546
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003547 // Check to see if any bits below the one bit set in AndRHSV are set.
3548 if ((AddRHS & (AndRHSV-1)) == 0) {
3549 // If not, the only thing that can effect the output of the AND is
3550 // the bit specified by AndRHSV. If that bit is set, the effect of
3551 // the XOR is to toggle the bit. If it is clear, then the ADD has
3552 // no effect.
3553 if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
3554 TheAnd.setOperand(0, X);
3555 return &TheAnd;
3556 } else {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003557 // Pull the XOR out of the AND.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003558 Instruction *NewAnd = BinaryOperator::CreateAnd(X, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003559 InsertNewInstBefore(NewAnd, TheAnd);
Chris Lattner6934a042007-02-11 01:23:03 +00003560 NewAnd->takeName(Op);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003561 return BinaryOperator::CreateXor(NewAnd, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003562 }
3563 }
3564 }
3565 }
3566 break;
Chris Lattner62a355c2003-09-19 19:05:02 +00003567
3568 case Instruction::Shl: {
3569 // We know that the AND will not produce any of the bits shifted in, so if
3570 // the anded constant includes them, clear them now!
3571 //
Zhou Sheng290bec52007-03-29 08:15:12 +00003572 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003573 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
Zhou Sheng290bec52007-03-29 08:15:12 +00003574 APInt ShlMask(APInt::getHighBitsSet(BitWidth, BitWidth-OpRHSVal));
Owen Andersoneed707b2009-07-24 23:12:02 +00003575 ConstantInt *CI = ConstantInt::get(*Context, AndRHS->getValue() & ShlMask);
Misha Brukmanfd939082005-04-21 23:48:37 +00003576
Zhou Sheng290bec52007-03-29 08:15:12 +00003577 if (CI->getValue() == ShlMask) {
3578 // Masking out bits that the shift already masks
Chris Lattner0c967662004-09-24 15:21:34 +00003579 return ReplaceInstUsesWith(TheAnd, Op); // No need for the and.
3580 } else if (CI != AndRHS) { // Reducing bits set in and.
Chris Lattner62a355c2003-09-19 19:05:02 +00003581 TheAnd.setOperand(1, CI);
3582 return &TheAnd;
3583 }
3584 break;
Misha Brukmanfd939082005-04-21 23:48:37 +00003585 }
Reid Spencer3822ff52006-11-08 06:47:33 +00003586 case Instruction::LShr:
3587 {
Chris Lattner62a355c2003-09-19 19:05:02 +00003588 // We know that the AND will not produce any of the bits shifted in, so if
3589 // the anded constant includes them, clear them now! This only applies to
3590 // unsigned shifts, because a signed shr may bring in set bits!
3591 //
Zhou Sheng290bec52007-03-29 08:15:12 +00003592 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003593 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
Zhou Sheng290bec52007-03-29 08:15:12 +00003594 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
Owen Andersoneed707b2009-07-24 23:12:02 +00003595 ConstantInt *CI = ConstantInt::get(*Context, AndRHS->getValue() & ShrMask);
Chris Lattner0c967662004-09-24 15:21:34 +00003596
Zhou Sheng290bec52007-03-29 08:15:12 +00003597 if (CI->getValue() == ShrMask) {
3598 // Masking out bits that the shift already masks.
Reid Spencer3822ff52006-11-08 06:47:33 +00003599 return ReplaceInstUsesWith(TheAnd, Op);
3600 } else if (CI != AndRHS) {
3601 TheAnd.setOperand(1, CI); // Reduce bits set in and cst.
3602 return &TheAnd;
3603 }
3604 break;
3605 }
3606 case Instruction::AShr:
3607 // Signed shr.
3608 // See if this is shifting in some sign extension, then masking it out
3609 // with an and.
3610 if (Op->hasOneUse()) {
Zhou Sheng290bec52007-03-29 08:15:12 +00003611 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003612 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
Zhou Sheng290bec52007-03-29 08:15:12 +00003613 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
Owen Andersoneed707b2009-07-24 23:12:02 +00003614 Constant *C = ConstantInt::get(*Context, AndRHS->getValue() & ShrMask);
Reid Spencer7eb76382006-12-13 17:19:09 +00003615 if (C == AndRHS) { // Masking out bits shifted in.
Reid Spencer17212df2006-12-12 09:18:51 +00003616 // (Val ashr C1) & C2 -> (Val lshr C1) & C2
Reid Spencer3822ff52006-11-08 06:47:33 +00003617 // Make the argument unsigned.
3618 Value *ShVal = Op->getOperand(0);
Reid Spencer832254e2007-02-02 02:16:23 +00003619 ShVal = InsertNewInstBefore(
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003620 BinaryOperator::CreateLShr(ShVal, OpRHS,
Reid Spencer832254e2007-02-02 02:16:23 +00003621 Op->getName()), TheAnd);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003622 return BinaryOperator::CreateAnd(ShVal, AndRHS, TheAnd.getName());
Chris Lattner0c967662004-09-24 15:21:34 +00003623 }
Chris Lattner62a355c2003-09-19 19:05:02 +00003624 }
3625 break;
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003626 }
3627 return 0;
3628}
3629
Chris Lattner8b170942002-08-09 23:47:40 +00003630
Chris Lattnera96879a2004-09-29 17:40:11 +00003631/// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
3632/// true, otherwise (V < Lo || V >= Hi). In pratice, we emit the more efficient
Reid Spencere4d87aa2006-12-23 06:05:41 +00003633/// (V-Lo) <u Hi-Lo. This method expects that Lo <= Hi. isSigned indicates
3634/// whether to treat the V, Lo and HI as signed or not. IB is the location to
Chris Lattnera96879a2004-09-29 17:40:11 +00003635/// insert new instructions.
3636Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
Reid Spencere4d87aa2006-12-23 06:05:41 +00003637 bool isSigned, bool Inside,
3638 Instruction &IB) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00003639 assert(cast<ConstantInt>(ConstantExpr::getICmp((isSigned ?
Reid Spencer579dca12007-01-12 04:24:46 +00003640 ICmpInst::ICMP_SLE:ICmpInst::ICMP_ULE), Lo, Hi))->getZExtValue() &&
Chris Lattnera96879a2004-09-29 17:40:11 +00003641 "Lo is not <= Hi in range emission code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00003642
Chris Lattnera96879a2004-09-29 17:40:11 +00003643 if (Inside) {
3644 if (Lo == Hi) // Trivially false.
Owen Anderson333c4002009-07-09 23:48:35 +00003645 return new ICmpInst(*Context, ICmpInst::ICMP_NE, V, V);
Misha Brukmanfd939082005-04-21 23:48:37 +00003646
Reid Spencere4d87aa2006-12-23 06:05:41 +00003647 // V >= Min && V < Hi --> V < Hi
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003648 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
Reid Spencere4e40032007-03-21 23:19:50 +00003649 ICmpInst::Predicate pred = (isSigned ?
Reid Spencere4d87aa2006-12-23 06:05:41 +00003650 ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT);
Owen Anderson333c4002009-07-09 23:48:35 +00003651 return new ICmpInst(*Context, pred, V, Hi);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003652 }
3653
3654 // Emit V-Lo <u Hi-Lo
Owen Andersonbaf3c402009-07-29 18:55:55 +00003655 Constant *NegLo = ConstantExpr::getNeg(Lo);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003656 Instruction *Add = BinaryOperator::CreateAdd(V, NegLo, V->getName()+".off");
Chris Lattnera96879a2004-09-29 17:40:11 +00003657 InsertNewInstBefore(Add, IB);
Owen Andersonbaf3c402009-07-29 18:55:55 +00003658 Constant *UpperBound = ConstantExpr::getAdd(NegLo, Hi);
Owen Anderson333c4002009-07-09 23:48:35 +00003659 return new ICmpInst(*Context, ICmpInst::ICMP_ULT, Add, UpperBound);
Chris Lattnera96879a2004-09-29 17:40:11 +00003660 }
3661
3662 if (Lo == Hi) // Trivially true.
Owen Anderson333c4002009-07-09 23:48:35 +00003663 return new ICmpInst(*Context, ICmpInst::ICMP_EQ, V, V);
Chris Lattnera96879a2004-09-29 17:40:11 +00003664
Reid Spencere4e40032007-03-21 23:19:50 +00003665 // V < Min || V >= Hi -> V > Hi-1
Dan Gohman186a6362009-08-12 16:04:34 +00003666 Hi = SubOne(cast<ConstantInt>(Hi));
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003667 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00003668 ICmpInst::Predicate pred = (isSigned ?
3669 ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT);
Owen Anderson333c4002009-07-09 23:48:35 +00003670 return new ICmpInst(*Context, pred, V, Hi);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003671 }
Reid Spencerb83eb642006-10-20 07:07:24 +00003672
Reid Spencere4e40032007-03-21 23:19:50 +00003673 // Emit V-Lo >u Hi-1-Lo
3674 // Note that Hi has already had one subtracted from it, above.
Owen Andersonbaf3c402009-07-29 18:55:55 +00003675 ConstantInt *NegLo = cast<ConstantInt>(ConstantExpr::getNeg(Lo));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003676 Instruction *Add = BinaryOperator::CreateAdd(V, NegLo, V->getName()+".off");
Chris Lattnera96879a2004-09-29 17:40:11 +00003677 InsertNewInstBefore(Add, IB);
Owen Andersonbaf3c402009-07-29 18:55:55 +00003678 Constant *LowerBound = ConstantExpr::getAdd(NegLo, Hi);
Owen Anderson333c4002009-07-09 23:48:35 +00003679 return new ICmpInst(*Context, ICmpInst::ICMP_UGT, Add, LowerBound);
Chris Lattnera96879a2004-09-29 17:40:11 +00003680}
3681
Chris Lattner7203e152005-09-18 07:22:02 +00003682// isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
3683// any number of 0s on either side. The 1s are allowed to wrap from LSB to
3684// MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs. 0x0F0F0000 is
3685// not, since all 1s are not contiguous.
Zhou Sheng4351c642007-04-02 08:20:41 +00003686static bool isRunOfOnes(ConstantInt *Val, uint32_t &MB, uint32_t &ME) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003687 const APInt& V = Val->getValue();
Reid Spencerf2442522007-03-24 00:42:08 +00003688 uint32_t BitWidth = Val->getType()->getBitWidth();
3689 if (!APIntOps::isShiftedMask(BitWidth, V)) return false;
Chris Lattner7203e152005-09-18 07:22:02 +00003690
3691 // look for the first zero bit after the run of ones
Reid Spencerf2442522007-03-24 00:42:08 +00003692 MB = BitWidth - ((V - 1) ^ V).countLeadingZeros();
Chris Lattner7203e152005-09-18 07:22:02 +00003693 // look for the first non-zero bit
Reid Spencerf2442522007-03-24 00:42:08 +00003694 ME = V.getActiveBits();
Chris Lattner7203e152005-09-18 07:22:02 +00003695 return true;
3696}
3697
Chris Lattner7203e152005-09-18 07:22:02 +00003698/// FoldLogicalPlusAnd - This is part of an expression (LHS +/- RHS) & Mask,
3699/// where isSub determines whether the operator is a sub. If we can fold one of
3700/// the following xforms:
Chris Lattnerc8e77562005-09-18 04:24:45 +00003701///
3702/// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
3703/// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3704/// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3705///
3706/// return (A +/- B).
3707///
3708Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003709 ConstantInt *Mask, bool isSub,
Chris Lattnerc8e77562005-09-18 04:24:45 +00003710 Instruction &I) {
3711 Instruction *LHSI = dyn_cast<Instruction>(LHS);
3712 if (!LHSI || LHSI->getNumOperands() != 2 ||
3713 !isa<ConstantInt>(LHSI->getOperand(1))) return 0;
3714
3715 ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
3716
3717 switch (LHSI->getOpcode()) {
3718 default: return 0;
3719 case Instruction::And:
Owen Andersonbaf3c402009-07-29 18:55:55 +00003720 if (ConstantExpr::getAnd(N, Mask) == Mask) {
Chris Lattner7203e152005-09-18 07:22:02 +00003721 // If the AndRHS is a power of two minus one (0+1+), this is simple.
Zhou Sheng00f436c2007-03-24 15:34:37 +00003722 if ((Mask->getValue().countLeadingZeros() +
3723 Mask->getValue().countPopulation()) ==
3724 Mask->getValue().getBitWidth())
Chris Lattner7203e152005-09-18 07:22:02 +00003725 break;
3726
3727 // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
3728 // part, we don't need any explicit masks to take them out of A. If that
3729 // is all N is, ignore it.
Zhou Sheng4351c642007-04-02 08:20:41 +00003730 uint32_t MB = 0, ME = 0;
Chris Lattner7203e152005-09-18 07:22:02 +00003731 if (isRunOfOnes(Mask, MB, ME)) { // begin/end bit of run, inclusive
Reid Spencerb35ae032007-03-23 18:46:34 +00003732 uint32_t BitWidth = cast<IntegerType>(RHS->getType())->getBitWidth();
Zhou Sheng290bec52007-03-29 08:15:12 +00003733 APInt Mask(APInt::getLowBitsSet(BitWidth, MB-1));
Chris Lattner3bedbd92006-02-07 07:27:52 +00003734 if (MaskedValueIsZero(RHS, Mask))
Chris Lattner7203e152005-09-18 07:22:02 +00003735 break;
3736 }
3737 }
Chris Lattnerc8e77562005-09-18 04:24:45 +00003738 return 0;
3739 case Instruction::Or:
3740 case Instruction::Xor:
Chris Lattner7203e152005-09-18 07:22:02 +00003741 // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
Zhou Sheng00f436c2007-03-24 15:34:37 +00003742 if ((Mask->getValue().countLeadingZeros() +
3743 Mask->getValue().countPopulation()) == Mask->getValue().getBitWidth()
Owen Andersonbaf3c402009-07-29 18:55:55 +00003744 && ConstantExpr::getAnd(N, Mask)->isNullValue())
Chris Lattnerc8e77562005-09-18 04:24:45 +00003745 break;
3746 return 0;
3747 }
3748
3749 Instruction *New;
3750 if (isSub)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003751 New = BinaryOperator::CreateSub(LHSI->getOperand(0), RHS, "fold");
Chris Lattnerc8e77562005-09-18 04:24:45 +00003752 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003753 New = BinaryOperator::CreateAdd(LHSI->getOperand(0), RHS, "fold");
Chris Lattnerc8e77562005-09-18 04:24:45 +00003754 return InsertNewInstBefore(New, I);
3755}
3756
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003757/// FoldAndOfICmps - Fold (icmp)&(icmp) if possible.
3758Instruction *InstCombiner::FoldAndOfICmps(Instruction &I,
3759 ICmpInst *LHS, ICmpInst *RHS) {
Chris Lattnerea065fb2008-11-16 05:10:52 +00003760 Value *Val, *Val2;
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003761 ConstantInt *LHSCst, *RHSCst;
3762 ICmpInst::Predicate LHSCC, RHSCC;
3763
Chris Lattnerea065fb2008-11-16 05:10:52 +00003764 // This only handles icmp of constants: (icmp1 A, C1) & (icmp2 B, C2).
Owen Andersonc7d2ce72009-07-10 17:35:01 +00003765 if (!match(LHS, m_ICmp(LHSCC, m_Value(Val),
3766 m_ConstantInt(LHSCst)), *Context) ||
3767 !match(RHS, m_ICmp(RHSCC, m_Value(Val2),
3768 m_ConstantInt(RHSCst)), *Context))
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003769 return 0;
Chris Lattnerea065fb2008-11-16 05:10:52 +00003770
3771 // (icmp ult A, C) & (icmp ult B, C) --> (icmp ult (A|B), C)
3772 // where C is a power of 2
3773 if (LHSCst == RHSCst && LHSCC == RHSCC && LHSCC == ICmpInst::ICMP_ULT &&
3774 LHSCst->getValue().isPowerOf2()) {
3775 Instruction *NewOr = BinaryOperator::CreateOr(Val, Val2);
3776 InsertNewInstBefore(NewOr, I);
Owen Anderson333c4002009-07-09 23:48:35 +00003777 return new ICmpInst(*Context, LHSCC, NewOr, LHSCst);
Chris Lattnerea065fb2008-11-16 05:10:52 +00003778 }
3779
3780 // From here on, we only handle:
3781 // (icmp1 A, C1) & (icmp2 A, C2) --> something simpler.
3782 if (Val != Val2) return 0;
3783
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003784 // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
3785 if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
3786 RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
3787 LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
3788 RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
3789 return 0;
3790
3791 // We can't fold (ugt x, C) & (sgt x, C2).
3792 if (!PredicatesFoldable(LHSCC, RHSCC))
3793 return 0;
3794
3795 // Ensure that the larger constant is on the RHS.
Chris Lattneraa3e1572008-11-16 05:14:43 +00003796 bool ShouldSwap;
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003797 if (ICmpInst::isSignedPredicate(LHSCC) ||
3798 (ICmpInst::isEquality(LHSCC) &&
3799 ICmpInst::isSignedPredicate(RHSCC)))
Chris Lattneraa3e1572008-11-16 05:14:43 +00003800 ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003801 else
Chris Lattneraa3e1572008-11-16 05:14:43 +00003802 ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
3803
3804 if (ShouldSwap) {
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003805 std::swap(LHS, RHS);
3806 std::swap(LHSCst, RHSCst);
3807 std::swap(LHSCC, RHSCC);
3808 }
3809
3810 // At this point, we know we have have two icmp instructions
3811 // comparing a value against two constants and and'ing the result
3812 // together. Because of the above check, we know that we only have
3813 // icmp eq, icmp ne, icmp [su]lt, and icmp [SU]gt here. We also know
3814 // (from the FoldICmpLogical check above), that the two constants
3815 // are not equal and that the larger constant is on the RHS
3816 assert(LHSCst != RHSCst && "Compares not folded above?");
3817
3818 switch (LHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00003819 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003820 case ICmpInst::ICMP_EQ:
3821 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00003822 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003823 case ICmpInst::ICMP_EQ: // (X == 13 & X == 15) -> false
3824 case ICmpInst::ICMP_UGT: // (X == 13 & X > 15) -> false
3825 case ICmpInst::ICMP_SGT: // (X == 13 & X > 15) -> false
Owen Anderson5defacc2009-07-31 17:39:07 +00003826 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003827 case ICmpInst::ICMP_NE: // (X == 13 & X != 15) -> X == 13
3828 case ICmpInst::ICMP_ULT: // (X == 13 & X < 15) -> X == 13
3829 case ICmpInst::ICMP_SLT: // (X == 13 & X < 15) -> X == 13
3830 return ReplaceInstUsesWith(I, LHS);
3831 }
3832 case ICmpInst::ICMP_NE:
3833 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00003834 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003835 case ICmpInst::ICMP_ULT:
Dan Gohman186a6362009-08-12 16:04:34 +00003836 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X u< 14) -> X < 13
Owen Anderson333c4002009-07-09 23:48:35 +00003837 return new ICmpInst(*Context, ICmpInst::ICMP_ULT, Val, LHSCst);
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003838 break; // (X != 13 & X u< 15) -> no change
3839 case ICmpInst::ICMP_SLT:
Dan Gohman186a6362009-08-12 16:04:34 +00003840 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X s< 14) -> X < 13
Owen Anderson333c4002009-07-09 23:48:35 +00003841 return new ICmpInst(*Context, ICmpInst::ICMP_SLT, Val, LHSCst);
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003842 break; // (X != 13 & X s< 15) -> no change
3843 case ICmpInst::ICMP_EQ: // (X != 13 & X == 15) -> X == 15
3844 case ICmpInst::ICMP_UGT: // (X != 13 & X u> 15) -> X u> 15
3845 case ICmpInst::ICMP_SGT: // (X != 13 & X s> 15) -> X s> 15
3846 return ReplaceInstUsesWith(I, RHS);
3847 case ICmpInst::ICMP_NE:
Dan Gohman186a6362009-08-12 16:04:34 +00003848 if (LHSCst == SubOne(RHSCst)){// (X != 13 & X != 14) -> X-13 >u 1
Owen Andersonbaf3c402009-07-29 18:55:55 +00003849 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003850 Instruction *Add = BinaryOperator::CreateAdd(Val, AddCST,
3851 Val->getName()+".off");
3852 InsertNewInstBefore(Add, I);
Owen Anderson333c4002009-07-09 23:48:35 +00003853 return new ICmpInst(*Context, ICmpInst::ICMP_UGT, Add,
Owen Andersoneed707b2009-07-24 23:12:02 +00003854 ConstantInt::get(Add->getType(), 1));
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003855 }
3856 break; // (X != 13 & X != 15) -> no change
3857 }
3858 break;
3859 case ICmpInst::ICMP_ULT:
3860 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00003861 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003862 case ICmpInst::ICMP_EQ: // (X u< 13 & X == 15) -> false
3863 case ICmpInst::ICMP_UGT: // (X u< 13 & X u> 15) -> false
Owen Anderson5defacc2009-07-31 17:39:07 +00003864 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003865 case ICmpInst::ICMP_SGT: // (X u< 13 & X s> 15) -> no change
3866 break;
3867 case ICmpInst::ICMP_NE: // (X u< 13 & X != 15) -> X u< 13
3868 case ICmpInst::ICMP_ULT: // (X u< 13 & X u< 15) -> X u< 13
3869 return ReplaceInstUsesWith(I, LHS);
3870 case ICmpInst::ICMP_SLT: // (X u< 13 & X s< 15) -> no change
3871 break;
3872 }
3873 break;
3874 case ICmpInst::ICMP_SLT:
3875 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00003876 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003877 case ICmpInst::ICMP_EQ: // (X s< 13 & X == 15) -> false
3878 case ICmpInst::ICMP_SGT: // (X s< 13 & X s> 15) -> false
Owen Anderson5defacc2009-07-31 17:39:07 +00003879 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003880 case ICmpInst::ICMP_UGT: // (X s< 13 & X u> 15) -> no change
3881 break;
3882 case ICmpInst::ICMP_NE: // (X s< 13 & X != 15) -> X < 13
3883 case ICmpInst::ICMP_SLT: // (X s< 13 & X s< 15) -> X < 13
3884 return ReplaceInstUsesWith(I, LHS);
3885 case ICmpInst::ICMP_ULT: // (X s< 13 & X u< 15) -> no change
3886 break;
3887 }
3888 break;
3889 case ICmpInst::ICMP_UGT:
3890 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00003891 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003892 case ICmpInst::ICMP_EQ: // (X u> 13 & X == 15) -> X == 15
3893 case ICmpInst::ICMP_UGT: // (X u> 13 & X u> 15) -> X u> 15
3894 return ReplaceInstUsesWith(I, RHS);
3895 case ICmpInst::ICMP_SGT: // (X u> 13 & X s> 15) -> no change
3896 break;
3897 case ICmpInst::ICMP_NE:
Dan Gohman186a6362009-08-12 16:04:34 +00003898 if (RHSCst == AddOne(LHSCst)) // (X u> 13 & X != 14) -> X u> 14
Owen Anderson333c4002009-07-09 23:48:35 +00003899 return new ICmpInst(*Context, LHSCC, Val, RHSCst);
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003900 break; // (X u> 13 & X != 15) -> no change
Chris Lattner69d4ced2008-11-16 05:20:07 +00003901 case ICmpInst::ICMP_ULT: // (X u> 13 & X u< 15) -> (X-14) <u 1
Dan Gohman186a6362009-08-12 16:04:34 +00003902 return InsertRangeTest(Val, AddOne(LHSCst),
Owen Andersond672ecb2009-07-03 00:17:18 +00003903 RHSCst, false, true, I);
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003904 case ICmpInst::ICMP_SLT: // (X u> 13 & X s< 15) -> no change
3905 break;
3906 }
3907 break;
3908 case ICmpInst::ICMP_SGT:
3909 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00003910 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003911 case ICmpInst::ICMP_EQ: // (X s> 13 & X == 15) -> X == 15
3912 case ICmpInst::ICMP_SGT: // (X s> 13 & X s> 15) -> X s> 15
3913 return ReplaceInstUsesWith(I, RHS);
3914 case ICmpInst::ICMP_UGT: // (X s> 13 & X u> 15) -> no change
3915 break;
3916 case ICmpInst::ICMP_NE:
Dan Gohman186a6362009-08-12 16:04:34 +00003917 if (RHSCst == AddOne(LHSCst)) // (X s> 13 & X != 14) -> X s> 14
Owen Anderson333c4002009-07-09 23:48:35 +00003918 return new ICmpInst(*Context, LHSCC, Val, RHSCst);
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003919 break; // (X s> 13 & X != 15) -> no change
Chris Lattner69d4ced2008-11-16 05:20:07 +00003920 case ICmpInst::ICMP_SLT: // (X s> 13 & X s< 15) -> (X-14) s< 1
Dan Gohman186a6362009-08-12 16:04:34 +00003921 return InsertRangeTest(Val, AddOne(LHSCst),
Owen Andersond672ecb2009-07-03 00:17:18 +00003922 RHSCst, true, true, I);
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003923 case ICmpInst::ICMP_ULT: // (X s> 13 & X u< 15) -> no change
3924 break;
3925 }
3926 break;
3927 }
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003928
3929 return 0;
3930}
3931
Chris Lattner42d1be02009-07-23 05:14:02 +00003932Instruction *InstCombiner::FoldAndOfFCmps(Instruction &I, FCmpInst *LHS,
3933 FCmpInst *RHS) {
3934
3935 if (LHS->getPredicate() == FCmpInst::FCMP_ORD &&
3936 RHS->getPredicate() == FCmpInst::FCMP_ORD) {
3937 // (fcmp ord x, c) & (fcmp ord y, c) -> (fcmp ord x, y)
3938 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
3939 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
3940 // If either of the constants are nans, then the whole thing returns
3941 // false.
3942 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
Owen Anderson5defacc2009-07-31 17:39:07 +00003943 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattner42d1be02009-07-23 05:14:02 +00003944 return new FCmpInst(*Context, FCmpInst::FCMP_ORD,
3945 LHS->getOperand(0), RHS->getOperand(0));
3946 }
Chris Lattnerf98d2532009-07-23 05:32:17 +00003947
3948 // Handle vector zeros. This occurs because the canonical form of
3949 // "fcmp ord x,x" is "fcmp ord x, 0".
3950 if (isa<ConstantAggregateZero>(LHS->getOperand(1)) &&
3951 isa<ConstantAggregateZero>(RHS->getOperand(1)))
3952 return new FCmpInst(*Context, FCmpInst::FCMP_ORD,
3953 LHS->getOperand(0), RHS->getOperand(0));
Chris Lattner42d1be02009-07-23 05:14:02 +00003954 return 0;
3955 }
3956
3957 Value *Op0LHS = LHS->getOperand(0), *Op0RHS = LHS->getOperand(1);
3958 Value *Op1LHS = RHS->getOperand(0), *Op1RHS = RHS->getOperand(1);
3959 FCmpInst::Predicate Op0CC = LHS->getPredicate(), Op1CC = RHS->getPredicate();
3960
3961
3962 if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
3963 // Swap RHS operands to match LHS.
3964 Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
3965 std::swap(Op1LHS, Op1RHS);
3966 }
3967
3968 if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
3969 // Simplify (fcmp cc0 x, y) & (fcmp cc1 x, y).
3970 if (Op0CC == Op1CC)
3971 return new FCmpInst(*Context, (FCmpInst::Predicate)Op0CC, Op0LHS, Op0RHS);
3972
3973 if (Op0CC == FCmpInst::FCMP_FALSE || Op1CC == FCmpInst::FCMP_FALSE)
Owen Anderson5defacc2009-07-31 17:39:07 +00003974 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattner42d1be02009-07-23 05:14:02 +00003975 if (Op0CC == FCmpInst::FCMP_TRUE)
3976 return ReplaceInstUsesWith(I, RHS);
3977 if (Op1CC == FCmpInst::FCMP_TRUE)
3978 return ReplaceInstUsesWith(I, LHS);
3979
3980 bool Op0Ordered;
3981 bool Op1Ordered;
3982 unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
3983 unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
3984 if (Op1Pred == 0) {
3985 std::swap(LHS, RHS);
3986 std::swap(Op0Pred, Op1Pred);
3987 std::swap(Op0Ordered, Op1Ordered);
3988 }
3989 if (Op0Pred == 0) {
3990 // uno && ueq -> uno && (uno || eq) -> ueq
3991 // ord && olt -> ord && (ord && lt) -> olt
3992 if (Op0Ordered == Op1Ordered)
3993 return ReplaceInstUsesWith(I, RHS);
3994
3995 // uno && oeq -> uno && (ord && eq) -> false
3996 // uno && ord -> false
3997 if (!Op0Ordered)
Owen Anderson5defacc2009-07-31 17:39:07 +00003998 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattner42d1be02009-07-23 05:14:02 +00003999 // ord && ueq -> ord && (uno || eq) -> oeq
4000 return cast<Instruction>(getFCmpValue(true, Op1Pred,
4001 Op0LHS, Op0RHS, Context));
4002 }
4003 }
4004
4005 return 0;
4006}
4007
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004008
Chris Lattner7e708292002-06-25 16:13:24 +00004009Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00004010 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00004011 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00004012
Chris Lattnere87597f2004-10-16 18:11:37 +00004013 if (isa<UndefValue>(Op1)) // X & undef -> 0
Owen Andersona7235ea2009-07-31 20:28:14 +00004014 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00004015
Chris Lattner6e7ba452005-01-01 16:22:27 +00004016 // and X, X = X
4017 if (Op0 == Op1)
Chris Lattner233f7dc2002-08-12 21:17:25 +00004018 return ReplaceInstUsesWith(I, Op1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00004019
Chris Lattnerf8c36f52006-02-12 08:02:11 +00004020 // See if we can simplify any instructions used by the instruction whose sole
Chris Lattner9ca96412006-02-08 03:25:32 +00004021 // purpose is to compute bits we don't care about.
Dan Gohman6de29f82009-06-15 22:12:54 +00004022 if (SimplifyDemandedInstructionBits(I))
4023 return &I;
4024 if (isa<VectorType>(I.getType())) {
Reid Spencer9d6565a2007-02-15 02:26:10 +00004025 if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
Chris Lattner041a6c92007-06-15 05:26:55 +00004026 if (CP->isAllOnesValue()) // X & <-1,-1> -> X
Chris Lattner696ee0a2007-01-18 22:16:33 +00004027 return ReplaceInstUsesWith(I, I.getOperand(0));
Chris Lattner041a6c92007-06-15 05:26:55 +00004028 } else if (isa<ConstantAggregateZero>(Op1)) {
4029 return ReplaceInstUsesWith(I, Op1); // X & <0,0> -> <0,0>
Chris Lattner696ee0a2007-01-18 22:16:33 +00004030 }
4031 }
Dan Gohman6de29f82009-06-15 22:12:54 +00004032
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004033 if (ConstantInt *AndRHS = dyn_cast<ConstantInt>(Op1)) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00004034 const APInt& AndRHSMask = AndRHS->getValue();
4035 APInt NotAndRHS(~AndRHSMask);
Chris Lattner6e7ba452005-01-01 16:22:27 +00004036
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00004037 // Optimize a variety of ((val OP C1) & C2) combinations...
Reid Spencer832254e2007-02-02 02:16:23 +00004038 if (isa<BinaryOperator>(Op0)) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00004039 Instruction *Op0I = cast<Instruction>(Op0);
Chris Lattner6e7ba452005-01-01 16:22:27 +00004040 Value *Op0LHS = Op0I->getOperand(0);
4041 Value *Op0RHS = Op0I->getOperand(1);
4042 switch (Op0I->getOpcode()) {
4043 case Instruction::Xor:
4044 case Instruction::Or:
Chris Lattnerad1e3022005-01-23 20:26:55 +00004045 // If the mask is only needed on one incoming arm, push it up.
4046 if (Op0I->hasOneUse()) {
4047 if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
4048 // Not masking anything out for the LHS, move to RHS.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004049 Instruction *NewRHS = BinaryOperator::CreateAnd(Op0RHS, AndRHS,
Chris Lattnerad1e3022005-01-23 20:26:55 +00004050 Op0RHS->getName()+".masked");
4051 InsertNewInstBefore(NewRHS, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004052 return BinaryOperator::Create(
Chris Lattnerad1e3022005-01-23 20:26:55 +00004053 cast<BinaryOperator>(Op0I)->getOpcode(), Op0LHS, NewRHS);
Misha Brukmanfd939082005-04-21 23:48:37 +00004054 }
Chris Lattner3bedbd92006-02-07 07:27:52 +00004055 if (!isa<Constant>(Op0RHS) &&
Chris Lattnerad1e3022005-01-23 20:26:55 +00004056 MaskedValueIsZero(Op0RHS, NotAndRHS)) {
4057 // Not masking anything out for the RHS, move to LHS.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004058 Instruction *NewLHS = BinaryOperator::CreateAnd(Op0LHS, AndRHS,
Chris Lattnerad1e3022005-01-23 20:26:55 +00004059 Op0LHS->getName()+".masked");
4060 InsertNewInstBefore(NewLHS, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004061 return BinaryOperator::Create(
Chris Lattnerad1e3022005-01-23 20:26:55 +00004062 cast<BinaryOperator>(Op0I)->getOpcode(), NewLHS, Op0RHS);
4063 }
4064 }
4065
Chris Lattner6e7ba452005-01-01 16:22:27 +00004066 break;
Chris Lattnerc8e77562005-09-18 04:24:45 +00004067 case Instruction::Add:
Chris Lattner7203e152005-09-18 07:22:02 +00004068 // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
4069 // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
4070 // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
4071 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004072 return BinaryOperator::CreateAnd(V, AndRHS);
Chris Lattner7203e152005-09-18 07:22:02 +00004073 if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004074 return BinaryOperator::CreateAnd(V, AndRHS); // Add commutes
Chris Lattnerc8e77562005-09-18 04:24:45 +00004075 break;
4076
4077 case Instruction::Sub:
Chris Lattner7203e152005-09-18 07:22:02 +00004078 // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
4079 // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
4080 // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
4081 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004082 return BinaryOperator::CreateAnd(V, AndRHS);
Nick Lewyckyb4d1bc92008-07-09 04:32:37 +00004083
Nick Lewycky5dcc41f2008-07-10 05:51:40 +00004084 // (A - N) & AndRHS -> -N & AndRHS iff A&AndRHS==0 and AndRHS
4085 // has 1's for all bits that the subtraction with A might affect.
4086 if (Op0I->hasOneUse()) {
4087 uint32_t BitWidth = AndRHSMask.getBitWidth();
4088 uint32_t Zeros = AndRHSMask.countLeadingZeros();
4089 APInt Mask = APInt::getLowBitsSet(BitWidth, BitWidth - Zeros);
4090
Nick Lewyckyb4d1bc92008-07-09 04:32:37 +00004091 ConstantInt *A = dyn_cast<ConstantInt>(Op0LHS);
Nick Lewycky5dcc41f2008-07-10 05:51:40 +00004092 if (!(A && A->isZero()) && // avoid infinite recursion.
4093 MaskedValueIsZero(Op0LHS, Mask)) {
Owen Anderson0a5372e2009-07-13 04:09:18 +00004094 Instruction *NewNeg = BinaryOperator::CreateNeg(*Context, Op0RHS);
Nick Lewyckyb4d1bc92008-07-09 04:32:37 +00004095 InsertNewInstBefore(NewNeg, I);
4096 return BinaryOperator::CreateAnd(NewNeg, AndRHS);
4097 }
4098 }
Chris Lattnerc8e77562005-09-18 04:24:45 +00004099 break;
Nick Lewyckyd1f77bf2008-07-09 05:20:13 +00004100
4101 case Instruction::Shl:
4102 case Instruction::LShr:
4103 // (1 << x) & 1 --> zext(x == 0)
4104 // (1 >> x) & 1 --> zext(x == 0)
Nick Lewyckyd8ad4922008-07-09 07:35:26 +00004105 if (AndRHSMask == 1 && Op0LHS == AndRHS) {
Owen Anderson333c4002009-07-09 23:48:35 +00004106 Instruction *NewICmp = new ICmpInst(*Context, ICmpInst::ICMP_EQ,
Owen Andersona7235ea2009-07-31 20:28:14 +00004107 Op0RHS, Constant::getNullValue(I.getType()));
Nick Lewyckyd1f77bf2008-07-09 05:20:13 +00004108 InsertNewInstBefore(NewICmp, I);
4109 return new ZExtInst(NewICmp, I.getType());
4110 }
4111 break;
Chris Lattner6e7ba452005-01-01 16:22:27 +00004112 }
4113
Chris Lattner58403262003-07-23 19:25:52 +00004114 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
Chris Lattner6e7ba452005-01-01 16:22:27 +00004115 if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00004116 return Res;
Chris Lattner6e7ba452005-01-01 16:22:27 +00004117 } else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
Chris Lattner2b83af22005-08-07 07:03:10 +00004118 // If this is an integer truncation or change from signed-to-unsigned, and
4119 // if the source is an and/or with immediate, transform it. This
4120 // frequently occurs for bitfield accesses.
4121 if (Instruction *CastOp = dyn_cast<Instruction>(CI->getOperand(0))) {
Reid Spencer3da59db2006-11-27 01:05:10 +00004122 if ((isa<TruncInst>(CI) || isa<BitCastInst>(CI)) &&
Chris Lattner2b83af22005-08-07 07:03:10 +00004123 CastOp->getNumOperands() == 2)
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00004124 if (ConstantInt *AndCI = dyn_cast<ConstantInt>(CastOp->getOperand(1))) {
Chris Lattner2b83af22005-08-07 07:03:10 +00004125 if (CastOp->getOpcode() == Instruction::And) {
4126 // Change: and (cast (and X, C1) to T), C2
Reid Spencer3da59db2006-11-27 01:05:10 +00004127 // into : and (cast X to T), trunc_or_bitcast(C1)&C2
4128 // This will fold the two constants together, which may allow
4129 // other simplifications.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004130 Instruction *NewCast = CastInst::CreateTruncOrBitCast(
Reid Spencerd977d862006-12-12 23:36:14 +00004131 CastOp->getOperand(0), I.getType(),
4132 CastOp->getName()+".shrunk");
Chris Lattner2b83af22005-08-07 07:03:10 +00004133 NewCast = InsertNewInstBefore(NewCast, I);
Reid Spencer3da59db2006-11-27 01:05:10 +00004134 // trunc_or_bitcast(C1)&C2
Owen Andersond672ecb2009-07-03 00:17:18 +00004135 Constant *C3 =
Owen Andersonbaf3c402009-07-29 18:55:55 +00004136 ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
4137 C3 = ConstantExpr::getAnd(C3, AndRHS);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004138 return BinaryOperator::CreateAnd(NewCast, C3);
Chris Lattner2b83af22005-08-07 07:03:10 +00004139 } else if (CastOp->getOpcode() == Instruction::Or) {
4140 // Change: and (cast (or X, C1) to T), C2
4141 // into : trunc(C1)&C2 iff trunc(C1)&C2 == C2
Owen Andersond672ecb2009-07-03 00:17:18 +00004142 Constant *C3 =
Owen Andersonbaf3c402009-07-29 18:55:55 +00004143 ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
4144 if (ConstantExpr::getAnd(C3, AndRHS) == AndRHS)
Owen Andersond672ecb2009-07-03 00:17:18 +00004145 // trunc(C1)&C2
Chris Lattner2b83af22005-08-07 07:03:10 +00004146 return ReplaceInstUsesWith(I, AndRHS);
4147 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00004148 }
Chris Lattner2b83af22005-08-07 07:03:10 +00004149 }
Chris Lattner06782f82003-07-23 19:36:21 +00004150 }
Chris Lattner2eefe512004-04-09 19:05:30 +00004151
4152 // Try to fold constant and into select arguments.
4153 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00004154 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00004155 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00004156 if (isa<PHINode>(Op0))
4157 if (Instruction *NV = FoldOpIntoPhi(I))
4158 return NV;
Chris Lattnerc6a8aff2003-07-23 17:57:01 +00004159 }
4160
Dan Gohman186a6362009-08-12 16:04:34 +00004161 Value *Op0NotVal = dyn_castNotVal(Op0);
4162 Value *Op1NotVal = dyn_castNotVal(Op1);
Chris Lattnera2881962003-02-18 19:28:33 +00004163
Chris Lattner5b62aa72004-06-18 06:07:51 +00004164 if (Op0NotVal == Op1 || Op1NotVal == Op0) // A & ~A == ~A & A == 0
Owen Andersona7235ea2009-07-31 20:28:14 +00004165 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner5b62aa72004-06-18 06:07:51 +00004166
Misha Brukmancb6267b2004-07-30 12:50:08 +00004167 // (~A & ~B) == (~(A | B)) - De Morgan's Law
Chris Lattner8d969642003-03-10 23:06:50 +00004168 if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004169 Instruction *Or = BinaryOperator::CreateOr(Op0NotVal, Op1NotVal,
Chris Lattner48595f12004-06-10 02:07:29 +00004170 I.getName()+".demorgan");
Chris Lattnerc6a8aff2003-07-23 17:57:01 +00004171 InsertNewInstBefore(Or, I);
Owen Anderson73c6b712009-07-13 20:58:05 +00004172 return BinaryOperator::CreateNot(*Context, Or);
Chris Lattnera2881962003-02-18 19:28:33 +00004173 }
Chris Lattner2082ad92006-02-13 23:07:23 +00004174
4175 {
Chris Lattner003b6202007-06-15 05:58:24 +00004176 Value *A = 0, *B = 0, *C = 0, *D = 0;
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004177 if (match(Op0, m_Or(m_Value(A), m_Value(B)), *Context)) {
Chris Lattner2082ad92006-02-13 23:07:23 +00004178 if (A == Op1 || B == Op1) // (A | ?) & A --> A
4179 return ReplaceInstUsesWith(I, Op1);
Chris Lattner003b6202007-06-15 05:58:24 +00004180
4181 // (A|B) & ~(A&B) -> A^B
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004182 if (match(Op1, m_Not(m_And(m_Value(C), m_Value(D))), *Context)) {
Chris Lattner003b6202007-06-15 05:58:24 +00004183 if ((A == C && B == D) || (A == D && B == C))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004184 return BinaryOperator::CreateXor(A, B);
Chris Lattner003b6202007-06-15 05:58:24 +00004185 }
4186 }
4187
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004188 if (match(Op1, m_Or(m_Value(A), m_Value(B)), *Context)) {
Chris Lattner2082ad92006-02-13 23:07:23 +00004189 if (A == Op0 || B == Op0) // A & (A | ?) --> A
4190 return ReplaceInstUsesWith(I, Op0);
Chris Lattner003b6202007-06-15 05:58:24 +00004191
4192 // ~(A&B) & (A|B) -> A^B
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004193 if (match(Op0, m_Not(m_And(m_Value(C), m_Value(D))), *Context)) {
Chris Lattner003b6202007-06-15 05:58:24 +00004194 if ((A == C && B == D) || (A == D && B == C))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004195 return BinaryOperator::CreateXor(A, B);
Chris Lattner003b6202007-06-15 05:58:24 +00004196 }
4197 }
Chris Lattner64daab52006-04-01 08:03:55 +00004198
4199 if (Op0->hasOneUse() &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004200 match(Op0, m_Xor(m_Value(A), m_Value(B)), *Context)) {
Chris Lattner64daab52006-04-01 08:03:55 +00004201 if (A == Op1) { // (A^B)&A -> A&(A^B)
4202 I.swapOperands(); // Simplify below
4203 std::swap(Op0, Op1);
4204 } else if (B == Op1) { // (A^B)&B -> B&(B^A)
4205 cast<BinaryOperator>(Op0)->swapOperands();
4206 I.swapOperands(); // Simplify below
4207 std::swap(Op0, Op1);
4208 }
4209 }
Bill Wendling7f0ef6b2008-11-30 13:08:13 +00004210
Chris Lattner64daab52006-04-01 08:03:55 +00004211 if (Op1->hasOneUse() &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004212 match(Op1, m_Xor(m_Value(A), m_Value(B)), *Context)) {
Chris Lattner64daab52006-04-01 08:03:55 +00004213 if (B == Op0) { // B&(A^B) -> B&(B^A)
4214 cast<BinaryOperator>(Op1)->swapOperands();
4215 std::swap(A, B);
4216 }
4217 if (A == Op0) { // A&(A^B) -> A & ~B
Owen Anderson73c6b712009-07-13 20:58:05 +00004218 Instruction *NotB = BinaryOperator::CreateNot(*Context, B, "tmp");
Chris Lattner64daab52006-04-01 08:03:55 +00004219 InsertNewInstBefore(NotB, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004220 return BinaryOperator::CreateAnd(A, NotB);
Chris Lattner64daab52006-04-01 08:03:55 +00004221 }
4222 }
Bill Wendling7f0ef6b2008-11-30 13:08:13 +00004223
4224 // (A&((~A)|B)) -> A&B
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004225 if (match(Op0, m_Or(m_Not(m_Specific(Op1)), m_Value(A)), *Context) ||
4226 match(Op0, m_Or(m_Value(A), m_Not(m_Specific(Op1))), *Context))
Chris Lattnerd8aafcb2008-12-01 05:16:26 +00004227 return BinaryOperator::CreateAnd(A, Op1);
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004228 if (match(Op1, m_Or(m_Not(m_Specific(Op0)), m_Value(A)), *Context) ||
4229 match(Op1, m_Or(m_Value(A), m_Not(m_Specific(Op0))), *Context))
Chris Lattnerd8aafcb2008-12-01 05:16:26 +00004230 return BinaryOperator::CreateAnd(A, Op0);
Chris Lattner2082ad92006-02-13 23:07:23 +00004231 }
4232
Reid Spencere4d87aa2006-12-23 06:05:41 +00004233 if (ICmpInst *RHS = dyn_cast<ICmpInst>(Op1)) {
4234 // (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
Dan Gohman186a6362009-08-12 16:04:34 +00004235 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Chris Lattneraa9c1f12003-08-13 20:16:26 +00004236 return R;
4237
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004238 if (ICmpInst *LHS = dyn_cast<ICmpInst>(Op0))
4239 if (Instruction *Res = FoldAndOfICmps(I, LHS, RHS))
4240 return Res;
Chris Lattner955f3312004-09-28 21:48:02 +00004241 }
4242
Chris Lattner6fc205f2006-05-05 06:39:07 +00004243 // fold (and (cast A), (cast B)) -> (cast (and A, B))
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004244 if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
4245 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
4246 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind ?
4247 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattnerf98d2532009-07-23 05:32:17 +00004248 if (SrcTy == Op1C->getOperand(0)->getType() &&
4249 SrcTy->isIntOrIntVector() &&
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004250 // Only do this if the casts both really cause code to be generated.
Reid Spencere4d87aa2006-12-23 06:05:41 +00004251 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
4252 I.getType(), TD) &&
4253 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
4254 I.getType(), TD)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004255 Instruction *NewOp = BinaryOperator::CreateAnd(Op0C->getOperand(0),
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004256 Op1C->getOperand(0),
4257 I.getName());
4258 InsertNewInstBefore(NewOp, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004259 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004260 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00004261 }
Chris Lattnere511b742006-11-14 07:46:50 +00004262
4263 // (X >> Z) & (Y >> Z) -> (X&Y) >> Z for all shifts.
Reid Spencer832254e2007-02-02 02:16:23 +00004264 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4265 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4266 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
Chris Lattnere511b742006-11-14 07:46:50 +00004267 SI0->getOperand(1) == SI1->getOperand(1) &&
4268 (SI0->hasOneUse() || SI1->hasOneUse())) {
4269 Instruction *NewOp =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004270 InsertNewInstBefore(BinaryOperator::CreateAnd(SI0->getOperand(0),
Chris Lattnere511b742006-11-14 07:46:50 +00004271 SI1->getOperand(0),
4272 SI0->getName()), I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004273 return BinaryOperator::Create(SI1->getOpcode(), NewOp,
Reid Spencer832254e2007-02-02 02:16:23 +00004274 SI1->getOperand(1));
Chris Lattnere511b742006-11-14 07:46:50 +00004275 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00004276 }
4277
Evan Cheng8db90722008-10-14 17:15:11 +00004278 // If and'ing two fcmp, try combine them into one.
Chris Lattner99c65742007-10-24 05:38:08 +00004279 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
Chris Lattner42d1be02009-07-23 05:14:02 +00004280 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1)))
4281 if (Instruction *Res = FoldAndOfFCmps(I, LHS, RHS))
4282 return Res;
Chris Lattner99c65742007-10-24 05:38:08 +00004283 }
Nick Lewyckyb4d1bc92008-07-09 04:32:37 +00004284
Chris Lattner7e708292002-06-25 16:13:24 +00004285 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00004286}
4287
Chris Lattner8c34cd22008-10-05 02:13:19 +00004288/// CollectBSwapParts - Analyze the specified subexpression and see if it is
4289/// capable of providing pieces of a bswap. The subexpression provides pieces
4290/// of a bswap if it is proven that each of the non-zero bytes in the output of
4291/// the expression came from the corresponding "byte swapped" byte in some other
4292/// value. For example, if the current subexpression is "(shl i32 %X, 24)" then
4293/// we know that the expression deposits the low byte of %X into the high byte
4294/// of the bswap result and that all other bytes are zero. This expression is
4295/// accepted, the high byte of ByteValues is set to X to indicate a correct
4296/// match.
4297///
4298/// This function returns true if the match was unsuccessful and false if so.
4299/// On entry to the function the "OverallLeftShift" is a signed integer value
4300/// indicating the number of bytes that the subexpression is later shifted. For
4301/// example, if the expression is later right shifted by 16 bits, the
4302/// OverallLeftShift value would be -2 on entry. This is used to specify which
4303/// byte of ByteValues is actually being set.
4304///
4305/// Similarly, ByteMask is a bitmask where a bit is clear if its corresponding
4306/// byte is masked to zero by a user. For example, in (X & 255), X will be
4307/// processed with a bytemask of 1. Because bytemask is 32-bits, this limits
4308/// this function to working on up to 32-byte (256 bit) values. ByteMask is
4309/// always in the local (OverallLeftShift) coordinate space.
4310///
4311static bool CollectBSwapParts(Value *V, int OverallLeftShift, uint32_t ByteMask,
4312 SmallVector<Value*, 8> &ByteValues) {
4313 if (Instruction *I = dyn_cast<Instruction>(V)) {
4314 // If this is an or instruction, it may be an inner node of the bswap.
4315 if (I->getOpcode() == Instruction::Or) {
4316 return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
4317 ByteValues) ||
4318 CollectBSwapParts(I->getOperand(1), OverallLeftShift, ByteMask,
4319 ByteValues);
Chris Lattnerafe91a52006-06-15 19:07:26 +00004320 }
Chris Lattner8c34cd22008-10-05 02:13:19 +00004321
4322 // If this is a logical shift by a constant multiple of 8, recurse with
4323 // OverallLeftShift and ByteMask adjusted.
4324 if (I->isLogicalShift() && isa<ConstantInt>(I->getOperand(1))) {
4325 unsigned ShAmt =
4326 cast<ConstantInt>(I->getOperand(1))->getLimitedValue(~0U);
4327 // Ensure the shift amount is defined and of a byte value.
4328 if ((ShAmt & 7) || (ShAmt > 8*ByteValues.size()))
4329 return true;
4330
4331 unsigned ByteShift = ShAmt >> 3;
4332 if (I->getOpcode() == Instruction::Shl) {
4333 // X << 2 -> collect(X, +2)
4334 OverallLeftShift += ByteShift;
4335 ByteMask >>= ByteShift;
4336 } else {
4337 // X >>u 2 -> collect(X, -2)
4338 OverallLeftShift -= ByteShift;
4339 ByteMask <<= ByteShift;
Chris Lattnerde17ddc2008-10-08 06:42:28 +00004340 ByteMask &= (~0U >> (32-ByteValues.size()));
Chris Lattner8c34cd22008-10-05 02:13:19 +00004341 }
4342
4343 if (OverallLeftShift >= (int)ByteValues.size()) return true;
4344 if (OverallLeftShift <= -(int)ByteValues.size()) return true;
4345
4346 return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
4347 ByteValues);
4348 }
4349
4350 // If this is a logical 'and' with a mask that clears bytes, clear the
4351 // corresponding bytes in ByteMask.
4352 if (I->getOpcode() == Instruction::And &&
4353 isa<ConstantInt>(I->getOperand(1))) {
4354 // Scan every byte of the and mask, seeing if the byte is either 0 or 255.
4355 unsigned NumBytes = ByteValues.size();
4356 APInt Byte(I->getType()->getPrimitiveSizeInBits(), 255);
4357 const APInt &AndMask = cast<ConstantInt>(I->getOperand(1))->getValue();
4358
4359 for (unsigned i = 0; i != NumBytes; ++i, Byte <<= 8) {
4360 // If this byte is masked out by a later operation, we don't care what
4361 // the and mask is.
4362 if ((ByteMask & (1 << i)) == 0)
4363 continue;
4364
4365 // If the AndMask is all zeros for this byte, clear the bit.
4366 APInt MaskB = AndMask & Byte;
4367 if (MaskB == 0) {
4368 ByteMask &= ~(1U << i);
4369 continue;
4370 }
4371
4372 // If the AndMask is not all ones for this byte, it's not a bytezap.
4373 if (MaskB != Byte)
4374 return true;
4375
4376 // Otherwise, this byte is kept.
4377 }
4378
4379 return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
4380 ByteValues);
4381 }
Chris Lattnerafe91a52006-06-15 19:07:26 +00004382 }
4383
Chris Lattner8c34cd22008-10-05 02:13:19 +00004384 // Okay, we got to something that isn't a shift, 'or' or 'and'. This must be
4385 // the input value to the bswap. Some observations: 1) if more than one byte
4386 // is demanded from this input, then it could not be successfully assembled
4387 // into a byteswap. At least one of the two bytes would not be aligned with
4388 // their ultimate destination.
4389 if (!isPowerOf2_32(ByteMask)) return true;
4390 unsigned InputByteNo = CountTrailingZeros_32(ByteMask);
Chris Lattnerafe91a52006-06-15 19:07:26 +00004391
Chris Lattner8c34cd22008-10-05 02:13:19 +00004392 // 2) The input and ultimate destinations must line up: if byte 3 of an i32
4393 // is demanded, it needs to go into byte 0 of the result. This means that the
4394 // byte needs to be shifted until it lands in the right byte bucket. The
4395 // shift amount depends on the position: if the byte is coming from the high
4396 // part of the value (e.g. byte 3) then it must be shifted right. If from the
4397 // low part, it must be shifted left.
4398 unsigned DestByteNo = InputByteNo + OverallLeftShift;
4399 if (InputByteNo < ByteValues.size()/2) {
4400 if (ByteValues.size()-1-DestByteNo != InputByteNo)
4401 return true;
4402 } else {
4403 if (ByteValues.size()-1-DestByteNo != InputByteNo)
4404 return true;
4405 }
Chris Lattnerafe91a52006-06-15 19:07:26 +00004406
4407 // If the destination byte value is already defined, the values are or'd
4408 // together, which isn't a bswap (unless it's an or of the same bits).
Chris Lattner8c34cd22008-10-05 02:13:19 +00004409 if (ByteValues[DestByteNo] && ByteValues[DestByteNo] != V)
Chris Lattnerafe91a52006-06-15 19:07:26 +00004410 return true;
Chris Lattner8c34cd22008-10-05 02:13:19 +00004411 ByteValues[DestByteNo] = V;
Chris Lattnerafe91a52006-06-15 19:07:26 +00004412 return false;
4413}
4414
4415/// MatchBSwap - Given an OR instruction, check to see if this is a bswap idiom.
4416/// If so, insert the new bswap intrinsic and return it.
4417Instruction *InstCombiner::MatchBSwap(BinaryOperator &I) {
Chris Lattner55fc8c42007-04-01 20:57:36 +00004418 const IntegerType *ITy = dyn_cast<IntegerType>(I.getType());
Chris Lattner8c34cd22008-10-05 02:13:19 +00004419 if (!ITy || ITy->getBitWidth() % 16 ||
4420 // ByteMask only allows up to 32-byte values.
4421 ITy->getBitWidth() > 32*8)
Chris Lattner55fc8c42007-04-01 20:57:36 +00004422 return 0; // Can only bswap pairs of bytes. Can't do vectors.
Chris Lattnerafe91a52006-06-15 19:07:26 +00004423
4424 /// ByteValues - For each byte of the result, we keep track of which value
4425 /// defines each byte.
Chris Lattner535014f2007-02-15 22:52:10 +00004426 SmallVector<Value*, 8> ByteValues;
Chris Lattner55fc8c42007-04-01 20:57:36 +00004427 ByteValues.resize(ITy->getBitWidth()/8);
Chris Lattnerafe91a52006-06-15 19:07:26 +00004428
4429 // Try to find all the pieces corresponding to the bswap.
Chris Lattner8c34cd22008-10-05 02:13:19 +00004430 uint32_t ByteMask = ~0U >> (32-ByteValues.size());
4431 if (CollectBSwapParts(&I, 0, ByteMask, ByteValues))
Chris Lattnerafe91a52006-06-15 19:07:26 +00004432 return 0;
4433
4434 // Check to see if all of the bytes come from the same value.
4435 Value *V = ByteValues[0];
4436 if (V == 0) return 0; // Didn't find a byte? Must be zero.
4437
4438 // Check to make sure that all of the bytes come from the same value.
4439 for (unsigned i = 1, e = ByteValues.size(); i != e; ++i)
4440 if (ByteValues[i] != V)
4441 return 0;
Chandler Carruth69940402007-08-04 01:51:18 +00004442 const Type *Tys[] = { ITy };
Chris Lattnerafe91a52006-06-15 19:07:26 +00004443 Module *M = I.getParent()->getParent()->getParent();
Chandler Carruth69940402007-08-04 01:51:18 +00004444 Function *F = Intrinsic::getDeclaration(M, Intrinsic::bswap, Tys, 1);
Gabor Greif051a9502008-04-06 20:25:17 +00004445 return CallInst::Create(F, V);
Chris Lattnerafe91a52006-06-15 19:07:26 +00004446}
4447
Chris Lattnerfaaf9512008-11-16 04:24:12 +00004448/// MatchSelectFromAndOr - We have an expression of the form (A&C)|(B&D). Check
4449/// If A is (cond?-1:0) and either B or D is ~(cond?-1,0) or (cond?0,-1), then
4450/// we can simplify this expression to "cond ? C : D or B".
4451static Instruction *MatchSelectFromAndOr(Value *A, Value *B,
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004452 Value *C, Value *D,
4453 LLVMContext *Context) {
Chris Lattnera6a474d2008-11-16 04:26:55 +00004454 // If A is not a select of -1/0, this cannot match.
Chris Lattner6046fb72008-11-16 04:46:19 +00004455 Value *Cond = 0;
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004456 if (!match(A, m_SelectCst<-1, 0>(m_Value(Cond)), *Context))
Chris Lattnerfaaf9512008-11-16 04:24:12 +00004457 return 0;
4458
Chris Lattnera6a474d2008-11-16 04:26:55 +00004459 // ((cond?-1:0)&C) | (B&(cond?0:-1)) -> cond ? C : B.
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004460 if (match(D, m_SelectCst<0, -1>(m_Specific(Cond)), *Context))
Chris Lattnera6a474d2008-11-16 04:26:55 +00004461 return SelectInst::Create(Cond, C, B);
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004462 if (match(D, m_Not(m_SelectCst<-1, 0>(m_Specific(Cond))), *Context))
Chris Lattnera6a474d2008-11-16 04:26:55 +00004463 return SelectInst::Create(Cond, C, B);
4464 // ((cond?-1:0)&C) | ((cond?0:-1)&D) -> cond ? C : D.
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004465 if (match(B, m_SelectCst<0, -1>(m_Specific(Cond)), *Context))
Chris Lattnera6a474d2008-11-16 04:26:55 +00004466 return SelectInst::Create(Cond, C, D);
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004467 if (match(B, m_Not(m_SelectCst<-1, 0>(m_Specific(Cond))), *Context))
Chris Lattnera6a474d2008-11-16 04:26:55 +00004468 return SelectInst::Create(Cond, C, D);
Chris Lattnerfaaf9512008-11-16 04:24:12 +00004469 return 0;
4470}
Chris Lattnerafe91a52006-06-15 19:07:26 +00004471
Chris Lattner69d4ced2008-11-16 05:20:07 +00004472/// FoldOrOfICmps - Fold (icmp)|(icmp) if possible.
4473Instruction *InstCombiner::FoldOrOfICmps(Instruction &I,
4474 ICmpInst *LHS, ICmpInst *RHS) {
4475 Value *Val, *Val2;
4476 ConstantInt *LHSCst, *RHSCst;
4477 ICmpInst::Predicate LHSCC, RHSCC;
4478
4479 // This only handles icmp of constants: (icmp1 A, C1) | (icmp2 B, C2).
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004480 if (!match(LHS, m_ICmp(LHSCC, m_Value(Val),
4481 m_ConstantInt(LHSCst)), *Context) ||
4482 !match(RHS, m_ICmp(RHSCC, m_Value(Val2),
4483 m_ConstantInt(RHSCst)), *Context))
Chris Lattner69d4ced2008-11-16 05:20:07 +00004484 return 0;
4485
4486 // From here on, we only handle:
4487 // (icmp1 A, C1) | (icmp2 A, C2) --> something simpler.
4488 if (Val != Val2) return 0;
4489
4490 // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
4491 if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
4492 RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
4493 LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
4494 RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
4495 return 0;
4496
4497 // We can't fold (ugt x, C) | (sgt x, C2).
4498 if (!PredicatesFoldable(LHSCC, RHSCC))
4499 return 0;
4500
4501 // Ensure that the larger constant is on the RHS.
4502 bool ShouldSwap;
4503 if (ICmpInst::isSignedPredicate(LHSCC) ||
4504 (ICmpInst::isEquality(LHSCC) &&
4505 ICmpInst::isSignedPredicate(RHSCC)))
4506 ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
4507 else
4508 ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
4509
4510 if (ShouldSwap) {
4511 std::swap(LHS, RHS);
4512 std::swap(LHSCst, RHSCst);
4513 std::swap(LHSCC, RHSCC);
4514 }
4515
4516 // At this point, we know we have have two icmp instructions
4517 // comparing a value against two constants and or'ing the result
4518 // together. Because of the above check, we know that we only have
4519 // ICMP_EQ, ICMP_NE, ICMP_LT, and ICMP_GT here. We also know (from the
4520 // FoldICmpLogical check above), that the two constants are not
4521 // equal.
4522 assert(LHSCst != RHSCst && "Compares not folded above?");
4523
4524 switch (LHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004525 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner69d4ced2008-11-16 05:20:07 +00004526 case ICmpInst::ICMP_EQ:
4527 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004528 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner69d4ced2008-11-16 05:20:07 +00004529 case ICmpInst::ICMP_EQ:
Dan Gohman186a6362009-08-12 16:04:34 +00004530 if (LHSCst == SubOne(RHSCst)) {
Owen Andersond672ecb2009-07-03 00:17:18 +00004531 // (X == 13 | X == 14) -> X-13 <u 2
Owen Andersonbaf3c402009-07-29 18:55:55 +00004532 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
Chris Lattner69d4ced2008-11-16 05:20:07 +00004533 Instruction *Add = BinaryOperator::CreateAdd(Val, AddCST,
4534 Val->getName()+".off");
4535 InsertNewInstBefore(Add, I);
Dan Gohman186a6362009-08-12 16:04:34 +00004536 AddCST = ConstantExpr::getSub(AddOne(RHSCst), LHSCst);
Owen Anderson333c4002009-07-09 23:48:35 +00004537 return new ICmpInst(*Context, ICmpInst::ICMP_ULT, Add, AddCST);
Chris Lattner69d4ced2008-11-16 05:20:07 +00004538 }
4539 break; // (X == 13 | X == 15) -> no change
4540 case ICmpInst::ICMP_UGT: // (X == 13 | X u> 14) -> no change
4541 case ICmpInst::ICMP_SGT: // (X == 13 | X s> 14) -> no change
4542 break;
4543 case ICmpInst::ICMP_NE: // (X == 13 | X != 15) -> X != 15
4544 case ICmpInst::ICMP_ULT: // (X == 13 | X u< 15) -> X u< 15
4545 case ICmpInst::ICMP_SLT: // (X == 13 | X s< 15) -> X s< 15
4546 return ReplaceInstUsesWith(I, RHS);
4547 }
4548 break;
4549 case ICmpInst::ICMP_NE:
4550 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004551 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner69d4ced2008-11-16 05:20:07 +00004552 case ICmpInst::ICMP_EQ: // (X != 13 | X == 15) -> X != 13
4553 case ICmpInst::ICMP_UGT: // (X != 13 | X u> 15) -> X != 13
4554 case ICmpInst::ICMP_SGT: // (X != 13 | X s> 15) -> X != 13
4555 return ReplaceInstUsesWith(I, LHS);
4556 case ICmpInst::ICMP_NE: // (X != 13 | X != 15) -> true
4557 case ICmpInst::ICMP_ULT: // (X != 13 | X u< 15) -> true
4558 case ICmpInst::ICMP_SLT: // (X != 13 | X s< 15) -> true
Owen Anderson5defacc2009-07-31 17:39:07 +00004559 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Chris Lattner69d4ced2008-11-16 05:20:07 +00004560 }
4561 break;
4562 case ICmpInst::ICMP_ULT:
4563 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004564 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner69d4ced2008-11-16 05:20:07 +00004565 case ICmpInst::ICMP_EQ: // (X u< 13 | X == 14) -> no change
4566 break;
4567 case ICmpInst::ICMP_UGT: // (X u< 13 | X u> 15) -> (X-13) u> 2
4568 // If RHSCst is [us]MAXINT, it is always false. Not handling
4569 // this can cause overflow.
4570 if (RHSCst->isMaxValue(false))
4571 return ReplaceInstUsesWith(I, LHS);
Dan Gohman186a6362009-08-12 16:04:34 +00004572 return InsertRangeTest(Val, LHSCst, AddOne(RHSCst),
Owen Andersond672ecb2009-07-03 00:17:18 +00004573 false, false, I);
Chris Lattner69d4ced2008-11-16 05:20:07 +00004574 case ICmpInst::ICMP_SGT: // (X u< 13 | X s> 15) -> no change
4575 break;
4576 case ICmpInst::ICMP_NE: // (X u< 13 | X != 15) -> X != 15
4577 case ICmpInst::ICMP_ULT: // (X u< 13 | X u< 15) -> X u< 15
4578 return ReplaceInstUsesWith(I, RHS);
4579 case ICmpInst::ICMP_SLT: // (X u< 13 | X s< 15) -> no change
4580 break;
4581 }
4582 break;
4583 case ICmpInst::ICMP_SLT:
4584 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004585 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner69d4ced2008-11-16 05:20:07 +00004586 case ICmpInst::ICMP_EQ: // (X s< 13 | X == 14) -> no change
4587 break;
4588 case ICmpInst::ICMP_SGT: // (X s< 13 | X s> 15) -> (X-13) s> 2
4589 // If RHSCst is [us]MAXINT, it is always false. Not handling
4590 // this can cause overflow.
4591 if (RHSCst->isMaxValue(true))
4592 return ReplaceInstUsesWith(I, LHS);
Dan Gohman186a6362009-08-12 16:04:34 +00004593 return InsertRangeTest(Val, LHSCst, AddOne(RHSCst),
Owen Andersond672ecb2009-07-03 00:17:18 +00004594 true, false, I);
Chris Lattner69d4ced2008-11-16 05:20:07 +00004595 case ICmpInst::ICMP_UGT: // (X s< 13 | X u> 15) -> no change
4596 break;
4597 case ICmpInst::ICMP_NE: // (X s< 13 | X != 15) -> X != 15
4598 case ICmpInst::ICMP_SLT: // (X s< 13 | X s< 15) -> X s< 15
4599 return ReplaceInstUsesWith(I, RHS);
4600 case ICmpInst::ICMP_ULT: // (X s< 13 | X u< 15) -> no change
4601 break;
4602 }
4603 break;
4604 case ICmpInst::ICMP_UGT:
4605 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004606 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner69d4ced2008-11-16 05:20:07 +00004607 case ICmpInst::ICMP_EQ: // (X u> 13 | X == 15) -> X u> 13
4608 case ICmpInst::ICMP_UGT: // (X u> 13 | X u> 15) -> X u> 13
4609 return ReplaceInstUsesWith(I, LHS);
4610 case ICmpInst::ICMP_SGT: // (X u> 13 | X s> 15) -> no change
4611 break;
4612 case ICmpInst::ICMP_NE: // (X u> 13 | X != 15) -> true
4613 case ICmpInst::ICMP_ULT: // (X u> 13 | X u< 15) -> true
Owen Anderson5defacc2009-07-31 17:39:07 +00004614 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Chris Lattner69d4ced2008-11-16 05:20:07 +00004615 case ICmpInst::ICMP_SLT: // (X u> 13 | X s< 15) -> no change
4616 break;
4617 }
4618 break;
4619 case ICmpInst::ICMP_SGT:
4620 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004621 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner69d4ced2008-11-16 05:20:07 +00004622 case ICmpInst::ICMP_EQ: // (X s> 13 | X == 15) -> X > 13
4623 case ICmpInst::ICMP_SGT: // (X s> 13 | X s> 15) -> X > 13
4624 return ReplaceInstUsesWith(I, LHS);
4625 case ICmpInst::ICMP_UGT: // (X s> 13 | X u> 15) -> no change
4626 break;
4627 case ICmpInst::ICMP_NE: // (X s> 13 | X != 15) -> true
4628 case ICmpInst::ICMP_SLT: // (X s> 13 | X s< 15) -> true
Owen Anderson5defacc2009-07-31 17:39:07 +00004629 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Chris Lattner69d4ced2008-11-16 05:20:07 +00004630 case ICmpInst::ICMP_ULT: // (X s> 13 | X u< 15) -> no change
4631 break;
4632 }
4633 break;
4634 }
4635 return 0;
4636}
4637
Chris Lattner5414cc52009-07-23 05:46:22 +00004638Instruction *InstCombiner::FoldOrOfFCmps(Instruction &I, FCmpInst *LHS,
4639 FCmpInst *RHS) {
4640 if (LHS->getPredicate() == FCmpInst::FCMP_UNO &&
4641 RHS->getPredicate() == FCmpInst::FCMP_UNO &&
4642 LHS->getOperand(0)->getType() == RHS->getOperand(0)->getType()) {
4643 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
4644 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
4645 // If either of the constants are nans, then the whole thing returns
4646 // true.
4647 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
Owen Anderson5defacc2009-07-31 17:39:07 +00004648 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Chris Lattner5414cc52009-07-23 05:46:22 +00004649
4650 // Otherwise, no need to compare the two constants, compare the
4651 // rest.
4652 return new FCmpInst(*Context, FCmpInst::FCMP_UNO,
4653 LHS->getOperand(0), RHS->getOperand(0));
4654 }
4655
4656 // Handle vector zeros. This occurs because the canonical form of
4657 // "fcmp uno x,x" is "fcmp uno x, 0".
4658 if (isa<ConstantAggregateZero>(LHS->getOperand(1)) &&
4659 isa<ConstantAggregateZero>(RHS->getOperand(1)))
4660 return new FCmpInst(*Context, FCmpInst::FCMP_UNO,
4661 LHS->getOperand(0), RHS->getOperand(0));
4662
4663 return 0;
4664 }
4665
4666 Value *Op0LHS = LHS->getOperand(0), *Op0RHS = LHS->getOperand(1);
4667 Value *Op1LHS = RHS->getOperand(0), *Op1RHS = RHS->getOperand(1);
4668 FCmpInst::Predicate Op0CC = LHS->getPredicate(), Op1CC = RHS->getPredicate();
4669
4670 if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
4671 // Swap RHS operands to match LHS.
4672 Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
4673 std::swap(Op1LHS, Op1RHS);
4674 }
4675 if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
4676 // Simplify (fcmp cc0 x, y) | (fcmp cc1 x, y).
4677 if (Op0CC == Op1CC)
4678 return new FCmpInst(*Context, (FCmpInst::Predicate)Op0CC,
4679 Op0LHS, Op0RHS);
4680 if (Op0CC == FCmpInst::FCMP_TRUE || Op1CC == FCmpInst::FCMP_TRUE)
Owen Anderson5defacc2009-07-31 17:39:07 +00004681 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Chris Lattner5414cc52009-07-23 05:46:22 +00004682 if (Op0CC == FCmpInst::FCMP_FALSE)
4683 return ReplaceInstUsesWith(I, RHS);
4684 if (Op1CC == FCmpInst::FCMP_FALSE)
4685 return ReplaceInstUsesWith(I, LHS);
4686 bool Op0Ordered;
4687 bool Op1Ordered;
4688 unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
4689 unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
4690 if (Op0Ordered == Op1Ordered) {
4691 // If both are ordered or unordered, return a new fcmp with
4692 // or'ed predicates.
4693 Value *RV = getFCmpValue(Op0Ordered, Op0Pred|Op1Pred,
4694 Op0LHS, Op0RHS, Context);
4695 if (Instruction *I = dyn_cast<Instruction>(RV))
4696 return I;
4697 // Otherwise, it's a constant boolean value...
4698 return ReplaceInstUsesWith(I, RV);
4699 }
4700 }
4701 return 0;
4702}
4703
Bill Wendlinga698a472008-12-01 08:23:25 +00004704/// FoldOrWithConstants - This helper function folds:
4705///
Bill Wendlinga8bb13f2008-12-02 05:09:00 +00004706/// ((A | B) & C1) | (B & C2)
Bill Wendlinga698a472008-12-01 08:23:25 +00004707///
4708/// into:
4709///
Bill Wendlinga8bb13f2008-12-02 05:09:00 +00004710/// (A & C1) | B
Bill Wendlingd54d8602008-12-01 08:32:40 +00004711///
Bill Wendlinga8bb13f2008-12-02 05:09:00 +00004712/// when the XOR of the two constants is "all ones" (-1).
Bill Wendlingd54d8602008-12-01 08:32:40 +00004713Instruction *InstCombiner::FoldOrWithConstants(BinaryOperator &I, Value *Op,
Bill Wendlinga698a472008-12-01 08:23:25 +00004714 Value *A, Value *B, Value *C) {
Bill Wendlingdda74e02008-12-02 05:06:43 +00004715 ConstantInt *CI1 = dyn_cast<ConstantInt>(C);
4716 if (!CI1) return 0;
Bill Wendlinga698a472008-12-01 08:23:25 +00004717
Bill Wendling286a0542008-12-02 06:24:20 +00004718 Value *V1 = 0;
4719 ConstantInt *CI2 = 0;
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004720 if (!match(Op, m_And(m_Value(V1), m_ConstantInt(CI2)), *Context)) return 0;
Bill Wendlinga698a472008-12-01 08:23:25 +00004721
Bill Wendling29976b92008-12-02 06:18:11 +00004722 APInt Xor = CI1->getValue() ^ CI2->getValue();
4723 if (!Xor.isAllOnesValue()) return 0;
4724
Bill Wendling286a0542008-12-02 06:24:20 +00004725 if (V1 == A || V1 == B) {
Bill Wendling29976b92008-12-02 06:18:11 +00004726 Instruction *NewOp =
Bill Wendlingd16c6e92008-12-02 06:22:04 +00004727 InsertNewInstBefore(BinaryOperator::CreateAnd((V1 == A) ? B : A, CI1), I);
4728 return BinaryOperator::CreateOr(NewOp, V1);
Bill Wendlinga698a472008-12-01 08:23:25 +00004729 }
4730
4731 return 0;
4732}
4733
Chris Lattner7e708292002-06-25 16:13:24 +00004734Instruction *InstCombiner::visitOr(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00004735 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00004736 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00004737
Chris Lattner42593e62007-03-24 23:56:43 +00004738 if (isa<UndefValue>(Op1)) // X | undef -> -1
Owen Andersona7235ea2009-07-31 20:28:14 +00004739 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00004740
Chris Lattnerf8c36f52006-02-12 08:02:11 +00004741 // or X, X = X
4742 if (Op0 == Op1)
Chris Lattner233f7dc2002-08-12 21:17:25 +00004743 return ReplaceInstUsesWith(I, Op0);
Chris Lattner3f5b8772002-05-06 16:14:14 +00004744
Chris Lattnerf8c36f52006-02-12 08:02:11 +00004745 // See if we can simplify any instructions used by the instruction whose sole
4746 // purpose is to compute bits we don't care about.
Dan Gohman6de29f82009-06-15 22:12:54 +00004747 if (SimplifyDemandedInstructionBits(I))
4748 return &I;
4749 if (isa<VectorType>(I.getType())) {
4750 if (isa<ConstantAggregateZero>(Op1)) {
4751 return ReplaceInstUsesWith(I, Op0); // X | <0,0> -> X
4752 } else if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
4753 if (CP->isAllOnesValue()) // X | <-1,-1> -> <-1,-1>
4754 return ReplaceInstUsesWith(I, I.getOperand(1));
4755 }
Chris Lattner42593e62007-03-24 23:56:43 +00004756 }
Chris Lattner041a6c92007-06-15 05:26:55 +00004757
Chris Lattner3f5b8772002-05-06 16:14:14 +00004758 // or X, -1 == -1
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004759 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner4f637d42006-01-06 17:59:59 +00004760 ConstantInt *C1 = 0; Value *X = 0;
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004761 // (X & C1) | C2 --> (X | C2) & (C1|C2)
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004762 if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1)), *Context) &&
4763 isOnlyUse(Op0)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004764 Instruction *Or = BinaryOperator::CreateOr(X, RHS);
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004765 InsertNewInstBefore(Or, I);
Chris Lattner6934a042007-02-11 01:23:03 +00004766 Or->takeName(Op0);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004767 return BinaryOperator::CreateAnd(Or,
Owen Andersoneed707b2009-07-24 23:12:02 +00004768 ConstantInt::get(*Context, RHS->getValue() | C1->getValue()));
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004769 }
Chris Lattnerad44ebf2003-07-23 18:29:44 +00004770
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004771 // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004772 if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1)), *Context) &&
4773 isOnlyUse(Op0)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004774 Instruction *Or = BinaryOperator::CreateOr(X, RHS);
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004775 InsertNewInstBefore(Or, I);
Chris Lattner6934a042007-02-11 01:23:03 +00004776 Or->takeName(Op0);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004777 return BinaryOperator::CreateXor(Or,
Owen Andersoneed707b2009-07-24 23:12:02 +00004778 ConstantInt::get(*Context, C1->getValue() & ~RHS->getValue()));
Chris Lattnerad44ebf2003-07-23 18:29:44 +00004779 }
Chris Lattner2eefe512004-04-09 19:05:30 +00004780
4781 // Try to fold constant and into select arguments.
4782 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00004783 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00004784 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00004785 if (isa<PHINode>(Op0))
4786 if (Instruction *NV = FoldOpIntoPhi(I))
4787 return NV;
Chris Lattnerad44ebf2003-07-23 18:29:44 +00004788 }
4789
Chris Lattner4f637d42006-01-06 17:59:59 +00004790 Value *A = 0, *B = 0;
4791 ConstantInt *C1 = 0, *C2 = 0;
Chris Lattnerf4d4c872005-05-07 23:49:08 +00004792
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004793 if (match(Op0, m_And(m_Value(A), m_Value(B)), *Context))
Chris Lattnerf4d4c872005-05-07 23:49:08 +00004794 if (A == Op1 || B == Op1) // (A & ?) | A --> A
4795 return ReplaceInstUsesWith(I, Op1);
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004796 if (match(Op1, m_And(m_Value(A), m_Value(B)), *Context))
Chris Lattnerf4d4c872005-05-07 23:49:08 +00004797 if (A == Op0 || B == Op0) // A | (A & ?) --> A
4798 return ReplaceInstUsesWith(I, Op0);
4799
Chris Lattner6423d4c2006-07-10 20:25:24 +00004800 // (A | B) | C and A | (B | C) -> bswap if possible.
4801 // (A >> B) | (C << D) and (A << B) | (B >> C) -> bswap if possible.
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004802 if (match(Op0, m_Or(m_Value(), m_Value()), *Context) ||
4803 match(Op1, m_Or(m_Value(), m_Value()), *Context) ||
4804 (match(Op0, m_Shift(m_Value(), m_Value()), *Context) &&
4805 match(Op1, m_Shift(m_Value(), m_Value()), *Context))) {
Chris Lattnerafe91a52006-06-15 19:07:26 +00004806 if (Instruction *BSwap = MatchBSwap(I))
4807 return BSwap;
4808 }
4809
Chris Lattner6e4c6492005-05-09 04:58:36 +00004810 // (X^C)|Y -> (X|Y)^C iff Y&C == 0
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004811 if (Op0->hasOneUse() &&
4812 match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1)), *Context) &&
Reid Spencera03d45f2007-03-22 22:19:58 +00004813 MaskedValueIsZero(Op1, C1->getValue())) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004814 Instruction *NOr = BinaryOperator::CreateOr(A, Op1);
Chris Lattner6934a042007-02-11 01:23:03 +00004815 InsertNewInstBefore(NOr, I);
4816 NOr->takeName(Op0);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004817 return BinaryOperator::CreateXor(NOr, C1);
Chris Lattner6e4c6492005-05-09 04:58:36 +00004818 }
4819
4820 // Y|(X^C) -> (X|Y)^C iff Y&C == 0
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004821 if (Op1->hasOneUse() &&
4822 match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1)), *Context) &&
Reid Spencera03d45f2007-03-22 22:19:58 +00004823 MaskedValueIsZero(Op0, C1->getValue())) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004824 Instruction *NOr = BinaryOperator::CreateOr(A, Op0);
Chris Lattner6934a042007-02-11 01:23:03 +00004825 InsertNewInstBefore(NOr, I);
4826 NOr->takeName(Op0);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004827 return BinaryOperator::CreateXor(NOr, C1);
Chris Lattner6e4c6492005-05-09 04:58:36 +00004828 }
4829
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00004830 // (A & C)|(B & D)
Chris Lattner2384d7b2007-06-19 05:43:49 +00004831 Value *C = 0, *D = 0;
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004832 if (match(Op0, m_And(m_Value(A), m_Value(C)), *Context) &&
4833 match(Op1, m_And(m_Value(B), m_Value(D)), *Context)) {
Chris Lattner6cae0e02007-04-08 07:55:22 +00004834 Value *V1 = 0, *V2 = 0, *V3 = 0;
4835 C1 = dyn_cast<ConstantInt>(C);
4836 C2 = dyn_cast<ConstantInt>(D);
4837 if (C1 && C2) { // (A & C1)|(B & C2)
4838 // If we have: ((V + N) & C1) | (V & C2)
4839 // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
4840 // replace with V+N.
4841 if (C1->getValue() == ~C2->getValue()) {
4842 if ((C2->getValue() & (C2->getValue()+1)) == 0 && // C2 == 0+1+
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004843 match(A, m_Add(m_Value(V1), m_Value(V2)), *Context)) {
Chris Lattner6cae0e02007-04-08 07:55:22 +00004844 // Add commutes, try both ways.
4845 if (V1 == B && MaskedValueIsZero(V2, C2->getValue()))
4846 return ReplaceInstUsesWith(I, A);
4847 if (V2 == B && MaskedValueIsZero(V1, C2->getValue()))
4848 return ReplaceInstUsesWith(I, A);
4849 }
4850 // Or commutes, try both ways.
4851 if ((C1->getValue() & (C1->getValue()+1)) == 0 &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004852 match(B, m_Add(m_Value(V1), m_Value(V2)), *Context)) {
Chris Lattner6cae0e02007-04-08 07:55:22 +00004853 // Add commutes, try both ways.
4854 if (V1 == A && MaskedValueIsZero(V2, C1->getValue()))
4855 return ReplaceInstUsesWith(I, B);
4856 if (V2 == A && MaskedValueIsZero(V1, C1->getValue()))
4857 return ReplaceInstUsesWith(I, B);
4858 }
4859 }
Chris Lattner044e5332007-04-08 08:01:49 +00004860 V1 = 0; V2 = 0; V3 = 0;
Chris Lattner6cae0e02007-04-08 07:55:22 +00004861 }
4862
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00004863 // Check to see if we have any common things being and'ed. If so, find the
4864 // terms for V1 & (V2|V3).
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00004865 if (isOnlyUse(Op0) || isOnlyUse(Op1)) {
4866 if (A == B) // (A & C)|(A & D) == A & (C|D)
4867 V1 = A, V2 = C, V3 = D;
4868 else if (A == D) // (A & C)|(B & A) == A & (B|C)
4869 V1 = A, V2 = B, V3 = C;
4870 else if (C == B) // (A & C)|(C & D) == C & (A|D)
4871 V1 = C, V2 = A, V3 = D;
4872 else if (C == D) // (A & C)|(B & C) == C & (A|B)
4873 V1 = C, V2 = A, V3 = B;
4874
4875 if (V1) {
4876 Value *Or =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004877 InsertNewInstBefore(BinaryOperator::CreateOr(V2, V3, "tmp"), I);
4878 return BinaryOperator::CreateAnd(V1, Or);
Chris Lattner0b7c0bf2005-09-18 06:02:59 +00004879 }
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00004880 }
Dan Gohmanb493b272008-10-28 22:38:57 +00004881
Dan Gohman1975d032008-10-30 20:40:10 +00004882 // (A & (C0?-1:0)) | (B & ~(C0?-1:0)) -> C0 ? A : B, and commuted variants
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004883 if (Instruction *Match = MatchSelectFromAndOr(A, B, C, D, Context))
Chris Lattnerfaaf9512008-11-16 04:24:12 +00004884 return Match;
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004885 if (Instruction *Match = MatchSelectFromAndOr(B, A, D, C, Context))
Chris Lattnerfaaf9512008-11-16 04:24:12 +00004886 return Match;
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004887 if (Instruction *Match = MatchSelectFromAndOr(C, B, A, D, Context))
Chris Lattnerfaaf9512008-11-16 04:24:12 +00004888 return Match;
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004889 if (Instruction *Match = MatchSelectFromAndOr(D, A, B, C, Context))
Chris Lattnerfaaf9512008-11-16 04:24:12 +00004890 return Match;
Bill Wendlingb01865c2008-11-30 13:52:49 +00004891
Bill Wendlingb01865c2008-11-30 13:52:49 +00004892 // ((A&~B)|(~A&B)) -> A^B
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004893 if ((match(C, m_Not(m_Specific(D)), *Context) &&
4894 match(B, m_Not(m_Specific(A)), *Context)))
Bill Wendling03aae5f2008-12-01 08:09:47 +00004895 return BinaryOperator::CreateXor(A, D);
Bill Wendlingb01865c2008-11-30 13:52:49 +00004896 // ((~B&A)|(~A&B)) -> A^B
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004897 if ((match(A, m_Not(m_Specific(D)), *Context) &&
4898 match(B, m_Not(m_Specific(C)), *Context)))
Bill Wendling03aae5f2008-12-01 08:09:47 +00004899 return BinaryOperator::CreateXor(C, D);
Bill Wendlingb01865c2008-11-30 13:52:49 +00004900 // ((A&~B)|(B&~A)) -> A^B
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004901 if ((match(C, m_Not(m_Specific(B)), *Context) &&
4902 match(D, m_Not(m_Specific(A)), *Context)))
Bill Wendling03aae5f2008-12-01 08:09:47 +00004903 return BinaryOperator::CreateXor(A, B);
Bill Wendlingb01865c2008-11-30 13:52:49 +00004904 // ((~B&A)|(B&~A)) -> A^B
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004905 if ((match(A, m_Not(m_Specific(B)), *Context) &&
4906 match(D, m_Not(m_Specific(C)), *Context)))
Bill Wendling03aae5f2008-12-01 08:09:47 +00004907 return BinaryOperator::CreateXor(C, B);
Chris Lattnere9bed7d2005-09-18 03:42:07 +00004908 }
Chris Lattnere511b742006-11-14 07:46:50 +00004909
4910 // (X >> Z) | (Y >> Z) -> (X|Y) >> Z for all shifts.
Reid Spencer832254e2007-02-02 02:16:23 +00004911 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4912 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4913 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
Chris Lattnere511b742006-11-14 07:46:50 +00004914 SI0->getOperand(1) == SI1->getOperand(1) &&
4915 (SI0->hasOneUse() || SI1->hasOneUse())) {
4916 Instruction *NewOp =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004917 InsertNewInstBefore(BinaryOperator::CreateOr(SI0->getOperand(0),
Chris Lattnere511b742006-11-14 07:46:50 +00004918 SI1->getOperand(0),
4919 SI0->getName()), I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004920 return BinaryOperator::Create(SI1->getOpcode(), NewOp,
Reid Spencer832254e2007-02-02 02:16:23 +00004921 SI1->getOperand(1));
Chris Lattnere511b742006-11-14 07:46:50 +00004922 }
4923 }
Chris Lattner67ca7682003-08-12 19:11:07 +00004924
Bill Wendlingb3833d12008-12-01 01:07:11 +00004925 // ((A|B)&1)|(B&-2) -> (A&1) | B
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004926 if (match(Op0, m_And(m_Or(m_Value(A), m_Value(B)), m_Value(C)), *Context) ||
4927 match(Op0, m_And(m_Value(C), m_Or(m_Value(A), m_Value(B))), *Context)) {
Bill Wendlingd54d8602008-12-01 08:32:40 +00004928 Instruction *Ret = FoldOrWithConstants(I, Op1, A, B, C);
Bill Wendlinga698a472008-12-01 08:23:25 +00004929 if (Ret) return Ret;
Bill Wendlingb3833d12008-12-01 01:07:11 +00004930 }
4931 // (B&-2)|((A|B)&1) -> (A&1) | B
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004932 if (match(Op1, m_And(m_Or(m_Value(A), m_Value(B)), m_Value(C)), *Context) ||
4933 match(Op1, m_And(m_Value(C), m_Or(m_Value(A), m_Value(B))), *Context)) {
Bill Wendlingd54d8602008-12-01 08:32:40 +00004934 Instruction *Ret = FoldOrWithConstants(I, Op0, A, B, C);
Bill Wendlinga698a472008-12-01 08:23:25 +00004935 if (Ret) return Ret;
Bill Wendlingb3833d12008-12-01 01:07:11 +00004936 }
4937
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004938 if (match(Op0, m_Not(m_Value(A)), *Context)) { // ~A | Op1
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004939 if (A == Op1) // ~A | A == -1
Owen Andersona7235ea2009-07-31 20:28:14 +00004940 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004941 } else {
4942 A = 0;
4943 }
Chris Lattnerf4d4c872005-05-07 23:49:08 +00004944 // Note, A is still live here!
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004945 if (match(Op1, m_Not(m_Value(B)), *Context)) { // Op0 | ~B
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004946 if (Op0 == B)
Owen Andersona7235ea2009-07-31 20:28:14 +00004947 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnera27231a2003-03-10 23:13:59 +00004948
Misha Brukmancb6267b2004-07-30 12:50:08 +00004949 // (~A | ~B) == (~(A & B)) - De Morgan's Law
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004950 if (A && isOnlyUse(Op0) && isOnlyUse(Op1)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004951 Value *And = InsertNewInstBefore(BinaryOperator::CreateAnd(A, B,
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004952 I.getName()+".demorgan"), I);
Owen Anderson73c6b712009-07-13 20:58:05 +00004953 return BinaryOperator::CreateNot(*Context, And);
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004954 }
Chris Lattnera27231a2003-03-10 23:13:59 +00004955 }
Chris Lattnera2881962003-02-18 19:28:33 +00004956
Reid Spencere4d87aa2006-12-23 06:05:41 +00004957 // (icmp1 A, B) | (icmp2 A, B) --> (icmp3 A, B)
4958 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1))) {
Dan Gohman186a6362009-08-12 16:04:34 +00004959 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Chris Lattneraa9c1f12003-08-13 20:16:26 +00004960 return R;
4961
Chris Lattner69d4ced2008-11-16 05:20:07 +00004962 if (ICmpInst *LHS = dyn_cast<ICmpInst>(I.getOperand(0)))
4963 if (Instruction *Res = FoldOrOfICmps(I, LHS, RHS))
4964 return Res;
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004965 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00004966
4967 // fold (or (cast A), (cast B)) -> (cast (or A, B))
Chris Lattner99c65742007-10-24 05:38:08 +00004968 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
Chris Lattner6fc205f2006-05-05 06:39:07 +00004969 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004970 if (Op0C->getOpcode() == Op1C->getOpcode()) {// same cast kind ?
Evan Chengb98a10e2008-03-24 00:21:34 +00004971 if (!isa<ICmpInst>(Op0C->getOperand(0)) ||
4972 !isa<ICmpInst>(Op1C->getOperand(0))) {
4973 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattnerf98d2532009-07-23 05:32:17 +00004974 if (SrcTy == Op1C->getOperand(0)->getType() &&
4975 SrcTy->isIntOrIntVector() &&
Evan Chengb98a10e2008-03-24 00:21:34 +00004976 // Only do this if the casts both really cause code to be
4977 // generated.
4978 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
4979 I.getType(), TD) &&
4980 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
4981 I.getType(), TD)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004982 Instruction *NewOp = BinaryOperator::CreateOr(Op0C->getOperand(0),
Evan Chengb98a10e2008-03-24 00:21:34 +00004983 Op1C->getOperand(0),
4984 I.getName());
4985 InsertNewInstBefore(NewOp, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004986 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
Evan Chengb98a10e2008-03-24 00:21:34 +00004987 }
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004988 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00004989 }
Chris Lattner99c65742007-10-24 05:38:08 +00004990 }
4991
4992
4993 // (fcmp uno x, c) | (fcmp uno y, c) -> (fcmp uno x, y)
4994 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
Chris Lattner5414cc52009-07-23 05:46:22 +00004995 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1)))
4996 if (Instruction *Res = FoldOrOfFCmps(I, LHS, RHS))
4997 return Res;
Chris Lattner99c65742007-10-24 05:38:08 +00004998 }
Chris Lattnere9bed7d2005-09-18 03:42:07 +00004999
Chris Lattner7e708292002-06-25 16:13:24 +00005000 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00005001}
5002
Dan Gohman844731a2008-05-13 00:00:25 +00005003namespace {
5004
Chris Lattnerc317d392004-02-16 01:20:27 +00005005// XorSelf - Implements: X ^ X --> 0
5006struct XorSelf {
5007 Value *RHS;
5008 XorSelf(Value *rhs) : RHS(rhs) {}
5009 bool shouldApply(Value *LHS) const { return LHS == RHS; }
5010 Instruction *apply(BinaryOperator &Xor) const {
5011 return &Xor;
5012 }
5013};
Chris Lattner3f5b8772002-05-06 16:14:14 +00005014
Dan Gohman844731a2008-05-13 00:00:25 +00005015}
Chris Lattner3f5b8772002-05-06 16:14:14 +00005016
Chris Lattner7e708292002-06-25 16:13:24 +00005017Instruction *InstCombiner::visitXor(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00005018 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00005019 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00005020
Evan Chengd34af782008-03-25 20:07:13 +00005021 if (isa<UndefValue>(Op1)) {
5022 if (isa<UndefValue>(Op0))
5023 // Handle undef ^ undef -> 0 special case. This is a common
5024 // idiom (misuse).
Owen Andersona7235ea2009-07-31 20:28:14 +00005025 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00005026 return ReplaceInstUsesWith(I, Op1); // X ^ undef -> undef
Evan Chengd34af782008-03-25 20:07:13 +00005027 }
Chris Lattnere87597f2004-10-16 18:11:37 +00005028
Chris Lattnerc317d392004-02-16 01:20:27 +00005029 // xor X, X = 0, even if X is nested in a sequence of Xor's.
Dan Gohman186a6362009-08-12 16:04:34 +00005030 if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1))) {
Chris Lattnera9ff5eb2007-08-05 08:47:58 +00005031 assert(Result == &I && "AssociativeOpt didn't work?"); Result=Result;
Owen Andersona7235ea2009-07-31 20:28:14 +00005032 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerc317d392004-02-16 01:20:27 +00005033 }
Chris Lattnerf8c36f52006-02-12 08:02:11 +00005034
5035 // See if we can simplify any instructions used by the instruction whose sole
5036 // purpose is to compute bits we don't care about.
Dan Gohman6de29f82009-06-15 22:12:54 +00005037 if (SimplifyDemandedInstructionBits(I))
5038 return &I;
5039 if (isa<VectorType>(I.getType()))
5040 if (isa<ConstantAggregateZero>(Op1))
5041 return ReplaceInstUsesWith(I, Op0); // X ^ <0,0> -> X
Chris Lattner3f5b8772002-05-06 16:14:14 +00005042
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00005043 // Is this a ~ operation?
Dan Gohman186a6362009-08-12 16:04:34 +00005044 if (Value *NotOp = dyn_castNotVal(&I)) {
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00005045 // ~(~X & Y) --> (X | ~Y) - De Morgan's Law
5046 // ~(~X | Y) === (X & ~Y) - De Morgan's Law
5047 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(NotOp)) {
5048 if (Op0I->getOpcode() == Instruction::And ||
5049 Op0I->getOpcode() == Instruction::Or) {
Dan Gohman186a6362009-08-12 16:04:34 +00005050 if (dyn_castNotVal(Op0I->getOperand(1))) Op0I->swapOperands();
5051 if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00005052 Instruction *NotY =
Owen Anderson73c6b712009-07-13 20:58:05 +00005053 BinaryOperator::CreateNot(*Context, Op0I->getOperand(1),
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00005054 Op0I->getOperand(1)->getName()+".not");
5055 InsertNewInstBefore(NotY, I);
5056 if (Op0I->getOpcode() == Instruction::And)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005057 return BinaryOperator::CreateOr(Op0NotVal, NotY);
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00005058 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005059 return BinaryOperator::CreateAnd(Op0NotVal, NotY);
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00005060 }
5061 }
5062 }
5063 }
5064
5065
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005066 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Owen Anderson5defacc2009-07-31 17:39:07 +00005067 if (RHS == ConstantInt::getTrue(*Context) && Op0->hasOneUse()) {
Bill Wendling3479be92009-01-01 01:18:23 +00005068 // xor (cmp A, B), true = not (cmp A, B) = !cmp A, B
Nick Lewyckyf947b3e2007-08-06 20:04:16 +00005069 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Op0))
Owen Anderson333c4002009-07-09 23:48:35 +00005070 return new ICmpInst(*Context, ICI->getInversePredicate(),
Reid Spencere4d87aa2006-12-23 06:05:41 +00005071 ICI->getOperand(0), ICI->getOperand(1));
Chris Lattnerad5b4fb2003-11-04 23:50:51 +00005072
Nick Lewyckyf947b3e2007-08-06 20:04:16 +00005073 if (FCmpInst *FCI = dyn_cast<FCmpInst>(Op0))
Owen Anderson333c4002009-07-09 23:48:35 +00005074 return new FCmpInst(*Context, FCI->getInversePredicate(),
Nick Lewyckyf947b3e2007-08-06 20:04:16 +00005075 FCI->getOperand(0), FCI->getOperand(1));
5076 }
5077
Nick Lewycky517e1f52008-05-31 19:01:33 +00005078 // fold (xor(zext(cmp)), 1) and (xor(sext(cmp)), -1) to ext(!cmp).
5079 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
5080 if (CmpInst *CI = dyn_cast<CmpInst>(Op0C->getOperand(0))) {
5081 if (CI->hasOneUse() && Op0C->hasOneUse()) {
5082 Instruction::CastOps Opcode = Op0C->getOpcode();
5083 if (Opcode == Instruction::ZExt || Opcode == Instruction::SExt) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00005084 if (RHS == ConstantExpr::getCast(Opcode,
Owen Anderson5defacc2009-07-31 17:39:07 +00005085 ConstantInt::getTrue(*Context),
Nick Lewycky517e1f52008-05-31 19:01:33 +00005086 Op0C->getDestTy())) {
5087 Instruction *NewCI = InsertNewInstBefore(CmpInst::Create(
Owen Anderson333c4002009-07-09 23:48:35 +00005088 *Context,
Nick Lewycky517e1f52008-05-31 19:01:33 +00005089 CI->getOpcode(), CI->getInversePredicate(),
5090 CI->getOperand(0), CI->getOperand(1)), I);
5091 NewCI->takeName(CI);
5092 return CastInst::Create(Opcode, NewCI, Op0C->getType());
5093 }
5094 }
5095 }
5096 }
5097 }
5098
Reid Spencere4d87aa2006-12-23 06:05:41 +00005099 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
Chris Lattnerd65460f2003-11-05 01:06:05 +00005100 // ~(c-X) == X-c-1 == X+(-c-1)
Chris Lattner7c4049c2004-01-12 19:35:11 +00005101 if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
5102 if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00005103 Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
5104 Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
Owen Andersoneed707b2009-07-24 23:12:02 +00005105 ConstantInt::get(I.getType(), 1));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005106 return BinaryOperator::CreateAdd(Op0I->getOperand(1), ConstantRHS);
Chris Lattner7c4049c2004-01-12 19:35:11 +00005107 }
Chris Lattner5c6e2db2007-04-02 05:36:22 +00005108
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00005109 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
Chris Lattnerf8c36f52006-02-12 08:02:11 +00005110 if (Op0I->getOpcode() == Instruction::Add) {
Chris Lattner689d24b2003-11-04 23:37:10 +00005111 // ~(X-c) --> (-c-1)-X
Chris Lattner7c4049c2004-01-12 19:35:11 +00005112 if (RHS->isAllOnesValue()) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00005113 Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005114 return BinaryOperator::CreateSub(
Owen Andersonbaf3c402009-07-29 18:55:55 +00005115 ConstantExpr::getSub(NegOp0CI,
Owen Andersoneed707b2009-07-24 23:12:02 +00005116 ConstantInt::get(I.getType(), 1)),
Owen Andersond672ecb2009-07-03 00:17:18 +00005117 Op0I->getOperand(0));
Chris Lattneracf4e072007-04-02 05:42:22 +00005118 } else if (RHS->getValue().isSignBit()) {
Chris Lattner5c6e2db2007-04-02 05:36:22 +00005119 // (X + C) ^ signbit -> (X + C + signbit)
Owen Andersoneed707b2009-07-24 23:12:02 +00005120 Constant *C = ConstantInt::get(*Context,
5121 RHS->getValue() + Op0CI->getValue());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005122 return BinaryOperator::CreateAdd(Op0I->getOperand(0), C);
Chris Lattnercd1d6d52007-04-02 05:48:58 +00005123
Chris Lattner7c4049c2004-01-12 19:35:11 +00005124 }
Chris Lattner02bd1b32006-02-26 19:57:54 +00005125 } else if (Op0I->getOpcode() == Instruction::Or) {
5126 // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
Reid Spencera03d45f2007-03-22 22:19:58 +00005127 if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getValue())) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00005128 Constant *NewRHS = ConstantExpr::getOr(Op0CI, RHS);
Chris Lattner02bd1b32006-02-26 19:57:54 +00005129 // Anything in both C1 and C2 is known to be zero, remove it from
5130 // NewRHS.
Owen Andersonbaf3c402009-07-29 18:55:55 +00005131 Constant *CommonBits = ConstantExpr::getAnd(Op0CI, RHS);
5132 NewRHS = ConstantExpr::getAnd(NewRHS,
5133 ConstantExpr::getNot(CommonBits));
Chris Lattnerdbab3862007-03-02 21:28:56 +00005134 AddToWorkList(Op0I);
Chris Lattner02bd1b32006-02-26 19:57:54 +00005135 I.setOperand(0, Op0I->getOperand(0));
5136 I.setOperand(1, NewRHS);
5137 return &I;
5138 }
Chris Lattnereca0c5c2003-07-23 21:37:07 +00005139 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00005140 }
Chris Lattner05bd1b22002-08-20 18:24:26 +00005141 }
Chris Lattner2eefe512004-04-09 19:05:30 +00005142
5143 // Try to fold constant and into select arguments.
5144 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00005145 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00005146 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00005147 if (isa<PHINode>(Op0))
5148 if (Instruction *NV = FoldOpIntoPhi(I))
5149 return NV;
Chris Lattner3f5b8772002-05-06 16:14:14 +00005150 }
5151
Dan Gohman186a6362009-08-12 16:04:34 +00005152 if (Value *X = dyn_castNotVal(Op0)) // ~A ^ A == -1
Chris Lattnera2881962003-02-18 19:28:33 +00005153 if (X == Op1)
Owen Andersona7235ea2009-07-31 20:28:14 +00005154 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnera2881962003-02-18 19:28:33 +00005155
Dan Gohman186a6362009-08-12 16:04:34 +00005156 if (Value *X = dyn_castNotVal(Op1)) // A ^ ~A == -1
Chris Lattnera2881962003-02-18 19:28:33 +00005157 if (X == Op0)
Owen Andersona7235ea2009-07-31 20:28:14 +00005158 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnera2881962003-02-18 19:28:33 +00005159
Chris Lattner318bf792007-03-18 22:51:34 +00005160
5161 BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1);
5162 if (Op1I) {
5163 Value *A, *B;
Owen Andersonc7d2ce72009-07-10 17:35:01 +00005164 if (match(Op1I, m_Or(m_Value(A), m_Value(B)), *Context)) {
Chris Lattner318bf792007-03-18 22:51:34 +00005165 if (A == Op0) { // B^(B|A) == (A|B)^B
Chris Lattner64daab52006-04-01 08:03:55 +00005166 Op1I->swapOperands();
Chris Lattnercb40a372003-03-10 18:24:17 +00005167 I.swapOperands();
5168 std::swap(Op0, Op1);
Chris Lattner318bf792007-03-18 22:51:34 +00005169 } else if (B == Op0) { // B^(A|B) == (A|B)^B
Chris Lattner64daab52006-04-01 08:03:55 +00005170 I.swapOperands(); // Simplified below.
Chris Lattnercb40a372003-03-10 18:24:17 +00005171 std::swap(Op0, Op1);
Misha Brukmanfd939082005-04-21 23:48:37 +00005172 }
Owen Andersonc7d2ce72009-07-10 17:35:01 +00005173 } else if (match(Op1I, m_Xor(m_Specific(Op0), m_Value(B)), *Context)) {
Chris Lattnercb504b92008-11-16 05:38:51 +00005174 return ReplaceInstUsesWith(I, B); // A^(A^B) == B
Owen Andersonc7d2ce72009-07-10 17:35:01 +00005175 } else if (match(Op1I, m_Xor(m_Value(A), m_Specific(Op0)), *Context)) {
Chris Lattnercb504b92008-11-16 05:38:51 +00005176 return ReplaceInstUsesWith(I, A); // A^(B^A) == B
Owen Andersonc7d2ce72009-07-10 17:35:01 +00005177 } else if (match(Op1I, m_And(m_Value(A), m_Value(B)), *Context) &&
5178 Op1I->hasOneUse()){
Chris Lattner6abbdf92007-04-01 05:36:37 +00005179 if (A == Op0) { // A^(A&B) -> A^(B&A)
Chris Lattner64daab52006-04-01 08:03:55 +00005180 Op1I->swapOperands();
Chris Lattner6abbdf92007-04-01 05:36:37 +00005181 std::swap(A, B);
5182 }
Chris Lattner318bf792007-03-18 22:51:34 +00005183 if (B == Op0) { // A^(B&A) -> (B&A)^A
Chris Lattner64daab52006-04-01 08:03:55 +00005184 I.swapOperands(); // Simplified below.
5185 std::swap(Op0, Op1);
5186 }
Chris Lattner26ca7e12004-02-16 03:54:20 +00005187 }
Chris Lattner318bf792007-03-18 22:51:34 +00005188 }
5189
5190 BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0);
5191 if (Op0I) {
5192 Value *A, *B;
Owen Andersonc7d2ce72009-07-10 17:35:01 +00005193 if (match(Op0I, m_Or(m_Value(A), m_Value(B)), *Context) &&
5194 Op0I->hasOneUse()) {
Chris Lattner318bf792007-03-18 22:51:34 +00005195 if (A == Op1) // (B|A)^B == (A|B)^B
5196 std::swap(A, B);
5197 if (B == Op1) { // (A|B)^B == A & ~B
5198 Instruction *NotB =
Owen Anderson73c6b712009-07-13 20:58:05 +00005199 InsertNewInstBefore(BinaryOperator::CreateNot(*Context,
5200 Op1, "tmp"), I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005201 return BinaryOperator::CreateAnd(A, NotB);
Chris Lattnercb40a372003-03-10 18:24:17 +00005202 }
Owen Andersonc7d2ce72009-07-10 17:35:01 +00005203 } else if (match(Op0I, m_Xor(m_Specific(Op1), m_Value(B)), *Context)) {
Chris Lattnercb504b92008-11-16 05:38:51 +00005204 return ReplaceInstUsesWith(I, B); // (A^B)^A == B
Owen Andersonc7d2ce72009-07-10 17:35:01 +00005205 } else if (match(Op0I, m_Xor(m_Value(A), m_Specific(Op1)), *Context)) {
Chris Lattnercb504b92008-11-16 05:38:51 +00005206 return ReplaceInstUsesWith(I, A); // (B^A)^A == B
Owen Andersonc7d2ce72009-07-10 17:35:01 +00005207 } else if (match(Op0I, m_And(m_Value(A), m_Value(B)), *Context) &&
5208 Op0I->hasOneUse()){
Chris Lattner318bf792007-03-18 22:51:34 +00005209 if (A == Op1) // (A&B)^A -> (B&A)^A
5210 std::swap(A, B);
5211 if (B == Op1 && // (B&A)^A == ~B & A
Chris Lattnerae1ab392006-04-01 22:05:01 +00005212 !isa<ConstantInt>(Op1)) { // Canonical form is (B&C)^C
Chris Lattner318bf792007-03-18 22:51:34 +00005213 Instruction *N =
Owen Anderson73c6b712009-07-13 20:58:05 +00005214 InsertNewInstBefore(BinaryOperator::CreateNot(*Context, A, "tmp"), I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005215 return BinaryOperator::CreateAnd(N, Op1);
Chris Lattner64daab52006-04-01 08:03:55 +00005216 }
Chris Lattnercb40a372003-03-10 18:24:17 +00005217 }
Chris Lattner318bf792007-03-18 22:51:34 +00005218 }
5219
5220 // (X >> Z) ^ (Y >> Z) -> (X^Y) >> Z for all shifts.
5221 if (Op0I && Op1I && Op0I->isShift() &&
5222 Op0I->getOpcode() == Op1I->getOpcode() &&
5223 Op0I->getOperand(1) == Op1I->getOperand(1) &&
5224 (Op1I->hasOneUse() || Op1I->hasOneUse())) {
5225 Instruction *NewOp =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005226 InsertNewInstBefore(BinaryOperator::CreateXor(Op0I->getOperand(0),
Chris Lattner318bf792007-03-18 22:51:34 +00005227 Op1I->getOperand(0),
5228 Op0I->getName()), I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005229 return BinaryOperator::Create(Op1I->getOpcode(), NewOp,
Chris Lattner318bf792007-03-18 22:51:34 +00005230 Op1I->getOperand(1));
5231 }
5232
5233 if (Op0I && Op1I) {
5234 Value *A, *B, *C, *D;
5235 // (A & B)^(A | B) -> A ^ B
Owen Andersonc7d2ce72009-07-10 17:35:01 +00005236 if (match(Op0I, m_And(m_Value(A), m_Value(B)), *Context) &&
5237 match(Op1I, m_Or(m_Value(C), m_Value(D)), *Context)) {
Chris Lattner318bf792007-03-18 22:51:34 +00005238 if ((A == C && B == D) || (A == D && B == C))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005239 return BinaryOperator::CreateXor(A, B);
Chris Lattner318bf792007-03-18 22:51:34 +00005240 }
5241 // (A | B)^(A & B) -> A ^ B
Owen Andersonc7d2ce72009-07-10 17:35:01 +00005242 if (match(Op0I, m_Or(m_Value(A), m_Value(B)), *Context) &&
5243 match(Op1I, m_And(m_Value(C), m_Value(D)), *Context)) {
Chris Lattner318bf792007-03-18 22:51:34 +00005244 if ((A == C && B == D) || (A == D && B == C))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005245 return BinaryOperator::CreateXor(A, B);
Chris Lattner318bf792007-03-18 22:51:34 +00005246 }
5247
5248 // (A & B)^(C & D)
5249 if ((Op0I->hasOneUse() || Op1I->hasOneUse()) &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00005250 match(Op0I, m_And(m_Value(A), m_Value(B)), *Context) &&
5251 match(Op1I, m_And(m_Value(C), m_Value(D)), *Context)) {
Chris Lattner318bf792007-03-18 22:51:34 +00005252 // (X & Y)^(X & Y) -> (Y^Z) & X
5253 Value *X = 0, *Y = 0, *Z = 0;
5254 if (A == C)
5255 X = A, Y = B, Z = D;
5256 else if (A == D)
5257 X = A, Y = B, Z = C;
5258 else if (B == C)
5259 X = B, Y = A, Z = D;
5260 else if (B == D)
5261 X = B, Y = A, Z = C;
5262
5263 if (X) {
5264 Instruction *NewOp =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005265 InsertNewInstBefore(BinaryOperator::CreateXor(Y, Z, Op0->getName()), I);
5266 return BinaryOperator::CreateAnd(NewOp, X);
Chris Lattner318bf792007-03-18 22:51:34 +00005267 }
5268 }
5269 }
5270
Reid Spencere4d87aa2006-12-23 06:05:41 +00005271 // (icmp1 A, B) ^ (icmp2 A, B) --> (icmp3 A, B)
5272 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
Dan Gohman186a6362009-08-12 16:04:34 +00005273 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Chris Lattneraa9c1f12003-08-13 20:16:26 +00005274 return R;
5275
Chris Lattner6fc205f2006-05-05 06:39:07 +00005276 // fold (xor (cast A), (cast B)) -> (cast (xor A, B))
Chris Lattner99c65742007-10-24 05:38:08 +00005277 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
Chris Lattner6fc205f2006-05-05 06:39:07 +00005278 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00005279 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind?
5280 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattner42a75512007-01-15 02:27:26 +00005281 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00005282 // Only do this if the casts both really cause code to be generated.
Reid Spencere4d87aa2006-12-23 06:05:41 +00005283 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
5284 I.getType(), TD) &&
5285 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
5286 I.getType(), TD)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005287 Instruction *NewOp = BinaryOperator::CreateXor(Op0C->getOperand(0),
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00005288 Op1C->getOperand(0),
5289 I.getName());
5290 InsertNewInstBefore(NewOp, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005291 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00005292 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00005293 }
Chris Lattner99c65742007-10-24 05:38:08 +00005294 }
Nick Lewycky517e1f52008-05-31 19:01:33 +00005295
Chris Lattner7e708292002-06-25 16:13:24 +00005296 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00005297}
5298
Owen Andersond672ecb2009-07-03 00:17:18 +00005299static ConstantInt *ExtractElement(Constant *V, Constant *Idx,
Owen Anderson07cf79e2009-07-06 23:00:19 +00005300 LLVMContext *Context) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00005301 return cast<ConstantInt>(ConstantExpr::getExtractElement(V, Idx));
Dan Gohman6de29f82009-06-15 22:12:54 +00005302}
Chris Lattnera96879a2004-09-29 17:40:11 +00005303
Dan Gohman6de29f82009-06-15 22:12:54 +00005304static bool HasAddOverflow(ConstantInt *Result,
5305 ConstantInt *In1, ConstantInt *In2,
5306 bool IsSigned) {
Reid Spencere4e40032007-03-21 23:19:50 +00005307 if (IsSigned)
5308 if (In2->getValue().isNegative())
5309 return Result->getValue().sgt(In1->getValue());
5310 else
5311 return Result->getValue().slt(In1->getValue());
5312 else
5313 return Result->getValue().ult(In1->getValue());
Chris Lattnera96879a2004-09-29 17:40:11 +00005314}
5315
Dan Gohman6de29f82009-06-15 22:12:54 +00005316/// AddWithOverflow - Compute Result = In1+In2, returning true if the result
Dan Gohman1df3fd62008-09-10 23:30:57 +00005317/// overflowed for this type.
Dan Gohman6de29f82009-06-15 22:12:54 +00005318static bool AddWithOverflow(Constant *&Result, Constant *In1,
Owen Anderson07cf79e2009-07-06 23:00:19 +00005319 Constant *In2, LLVMContext *Context,
Owen Andersond672ecb2009-07-03 00:17:18 +00005320 bool IsSigned = false) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00005321 Result = ConstantExpr::getAdd(In1, In2);
Dan Gohman1df3fd62008-09-10 23:30:57 +00005322
Dan Gohman6de29f82009-06-15 22:12:54 +00005323 if (const VectorType *VTy = dyn_cast<VectorType>(In1->getType())) {
5324 for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
Owen Andersoneed707b2009-07-24 23:12:02 +00005325 Constant *Idx = ConstantInt::get(Type::Int32Ty, i);
Owen Andersond672ecb2009-07-03 00:17:18 +00005326 if (HasAddOverflow(ExtractElement(Result, Idx, Context),
5327 ExtractElement(In1, Idx, Context),
5328 ExtractElement(In2, Idx, Context),
Dan Gohman6de29f82009-06-15 22:12:54 +00005329 IsSigned))
5330 return true;
5331 }
5332 return false;
5333 }
5334
5335 return HasAddOverflow(cast<ConstantInt>(Result),
5336 cast<ConstantInt>(In1), cast<ConstantInt>(In2),
5337 IsSigned);
5338}
5339
5340static bool HasSubOverflow(ConstantInt *Result,
5341 ConstantInt *In1, ConstantInt *In2,
5342 bool IsSigned) {
Dan Gohman1df3fd62008-09-10 23:30:57 +00005343 if (IsSigned)
5344 if (In2->getValue().isNegative())
5345 return Result->getValue().slt(In1->getValue());
5346 else
5347 return Result->getValue().sgt(In1->getValue());
5348 else
5349 return Result->getValue().ugt(In1->getValue());
5350}
5351
Dan Gohman6de29f82009-06-15 22:12:54 +00005352/// SubWithOverflow - Compute Result = In1-In2, returning true if the result
5353/// overflowed for this type.
5354static bool SubWithOverflow(Constant *&Result, Constant *In1,
Owen Anderson07cf79e2009-07-06 23:00:19 +00005355 Constant *In2, LLVMContext *Context,
Owen Andersond672ecb2009-07-03 00:17:18 +00005356 bool IsSigned = false) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00005357 Result = ConstantExpr::getSub(In1, In2);
Dan Gohman6de29f82009-06-15 22:12:54 +00005358
5359 if (const VectorType *VTy = dyn_cast<VectorType>(In1->getType())) {
5360 for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
Owen Andersoneed707b2009-07-24 23:12:02 +00005361 Constant *Idx = ConstantInt::get(Type::Int32Ty, i);
Owen Andersond672ecb2009-07-03 00:17:18 +00005362 if (HasSubOverflow(ExtractElement(Result, Idx, Context),
5363 ExtractElement(In1, Idx, Context),
5364 ExtractElement(In2, Idx, Context),
Dan Gohman6de29f82009-06-15 22:12:54 +00005365 IsSigned))
5366 return true;
5367 }
5368 return false;
5369 }
5370
5371 return HasSubOverflow(cast<ConstantInt>(Result),
5372 cast<ConstantInt>(In1), cast<ConstantInt>(In2),
5373 IsSigned);
5374}
5375
Chris Lattner574da9b2005-01-13 20:14:25 +00005376/// EmitGEPOffset - Given a getelementptr instruction/constantexpr, emit the
5377/// code necessary to compute the offset from the base pointer (without adding
5378/// in the base pointer). Return the result as a signed integer of intptr size.
5379static Value *EmitGEPOffset(User *GEP, Instruction &I, InstCombiner &IC) {
Dan Gohmance9fe9f2009-07-21 23:21:54 +00005380 TargetData &TD = *IC.getTargetData();
Chris Lattner574da9b2005-01-13 20:14:25 +00005381 gep_type_iterator GTI = gep_type_begin(GEP);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005382 const Type *IntPtrTy = TD.getIntPtrType();
Owen Anderson07cf79e2009-07-06 23:00:19 +00005383 LLVMContext *Context = IC.getContext();
Owen Andersona7235ea2009-07-31 20:28:14 +00005384 Value *Result = Constant::getNullValue(IntPtrTy);
Chris Lattner574da9b2005-01-13 20:14:25 +00005385
5386 // Build a mask for high order bits.
Chris Lattner10c0d912008-04-22 02:53:33 +00005387 unsigned IntPtrWidth = TD.getPointerSizeInBits();
Chris Lattnere62f0212007-04-28 04:52:43 +00005388 uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
Chris Lattner574da9b2005-01-13 20:14:25 +00005389
Gabor Greif177dd3f2008-06-12 21:37:33 +00005390 for (User::op_iterator i = GEP->op_begin() + 1, e = GEP->op_end(); i != e;
5391 ++i, ++GTI) {
5392 Value *Op = *i;
Duncan Sands777d2302009-05-09 07:06:46 +00005393 uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType()) & PtrSizeMask;
Chris Lattnere62f0212007-04-28 04:52:43 +00005394 if (ConstantInt *OpC = dyn_cast<ConstantInt>(Op)) {
5395 if (OpC->isZero()) continue;
5396
5397 // Handle a struct index, which adds its field offset to the pointer.
5398 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5399 Size = TD.getStructLayout(STy)->getElementOffset(OpC->getZExtValue());
5400
5401 if (ConstantInt *RC = dyn_cast<ConstantInt>(Result))
Owen Andersond672ecb2009-07-03 00:17:18 +00005402 Result =
Owen Andersoneed707b2009-07-24 23:12:02 +00005403 ConstantInt::get(*Context,
5404 RC->getValue() + APInt(IntPtrWidth, Size));
Chris Lattner9bc14642007-04-28 00:57:34 +00005405 else
Chris Lattnere62f0212007-04-28 04:52:43 +00005406 Result = IC.InsertNewInstBefore(
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005407 BinaryOperator::CreateAdd(Result,
Owen Andersoneed707b2009-07-24 23:12:02 +00005408 ConstantInt::get(IntPtrTy, Size),
Chris Lattnere62f0212007-04-28 04:52:43 +00005409 GEP->getName()+".offs"), I);
5410 continue;
Chris Lattner9bc14642007-04-28 00:57:34 +00005411 }
Chris Lattnere62f0212007-04-28 04:52:43 +00005412
Owen Andersoneed707b2009-07-24 23:12:02 +00005413 Constant *Scale = ConstantInt::get(IntPtrTy, Size);
Owen Andersond672ecb2009-07-03 00:17:18 +00005414 Constant *OC =
Owen Andersonbaf3c402009-07-29 18:55:55 +00005415 ConstantExpr::getIntegerCast(OpC, IntPtrTy, true /*SExt*/);
5416 Scale = ConstantExpr::getMul(OC, Scale);
Chris Lattnere62f0212007-04-28 04:52:43 +00005417 if (Constant *RC = dyn_cast<Constant>(Result))
Owen Andersonbaf3c402009-07-29 18:55:55 +00005418 Result = ConstantExpr::getAdd(RC, Scale);
Chris Lattnere62f0212007-04-28 04:52:43 +00005419 else {
5420 // Emit an add instruction.
5421 Result = IC.InsertNewInstBefore(
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005422 BinaryOperator::CreateAdd(Result, Scale,
Chris Lattnere62f0212007-04-28 04:52:43 +00005423 GEP->getName()+".offs"), I);
Chris Lattner9bc14642007-04-28 00:57:34 +00005424 }
Chris Lattnere62f0212007-04-28 04:52:43 +00005425 continue;
Chris Lattner574da9b2005-01-13 20:14:25 +00005426 }
Chris Lattnere62f0212007-04-28 04:52:43 +00005427 // Convert to correct type.
5428 if (Op->getType() != IntPtrTy) {
5429 if (Constant *OpC = dyn_cast<Constant>(Op))
Owen Andersonbaf3c402009-07-29 18:55:55 +00005430 Op = ConstantExpr::getIntegerCast(OpC, IntPtrTy, true);
Chris Lattnere62f0212007-04-28 04:52:43 +00005431 else
Chris Lattner62ce3b32009-04-07 05:03:34 +00005432 Op = IC.InsertNewInstBefore(CastInst::CreateIntegerCast(Op, IntPtrTy,
5433 true,
5434 Op->getName()+".c"), I);
Chris Lattnere62f0212007-04-28 04:52:43 +00005435 }
5436 if (Size != 1) {
Owen Andersoneed707b2009-07-24 23:12:02 +00005437 Constant *Scale = ConstantInt::get(IntPtrTy, Size);
Chris Lattnere62f0212007-04-28 04:52:43 +00005438 if (Constant *OpC = dyn_cast<Constant>(Op))
Owen Andersonbaf3c402009-07-29 18:55:55 +00005439 Op = ConstantExpr::getMul(OpC, Scale);
Chris Lattnere62f0212007-04-28 04:52:43 +00005440 else // We'll let instcombine(mul) convert this to a shl if possible.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005441 Op = IC.InsertNewInstBefore(BinaryOperator::CreateMul(Op, Scale,
Chris Lattnere62f0212007-04-28 04:52:43 +00005442 GEP->getName()+".idx"), I);
5443 }
5444
5445 // Emit an add instruction.
5446 if (isa<Constant>(Op) && isa<Constant>(Result))
Owen Andersonbaf3c402009-07-29 18:55:55 +00005447 Result = ConstantExpr::getAdd(cast<Constant>(Op),
Chris Lattnere62f0212007-04-28 04:52:43 +00005448 cast<Constant>(Result));
5449 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005450 Result = IC.InsertNewInstBefore(BinaryOperator::CreateAdd(Op, Result,
Chris Lattnere62f0212007-04-28 04:52:43 +00005451 GEP->getName()+".offs"), I);
Chris Lattner574da9b2005-01-13 20:14:25 +00005452 }
5453 return Result;
5454}
5455
Chris Lattner10c0d912008-04-22 02:53:33 +00005456
Dan Gohman8f080f02009-07-17 22:16:21 +00005457/// EvaluateGEPOffsetExpression - Return a value that can be used to compare
5458/// the *offset* implied by a GEP to zero. For example, if we have &A[i], we
5459/// want to return 'i' for "icmp ne i, 0". Note that, in general, indices can
5460/// be complex, and scales are involved. The above expression would also be
5461/// legal to codegen as "icmp ne (i*4), 0" (assuming A is a pointer to i32).
5462/// This later form is less amenable to optimization though, and we are allowed
5463/// to generate the first by knowing that pointer arithmetic doesn't overflow.
Chris Lattner10c0d912008-04-22 02:53:33 +00005464///
5465/// If we can't emit an optimized form for this expression, this returns null.
5466///
5467static Value *EvaluateGEPOffsetExpression(User *GEP, Instruction &I,
5468 InstCombiner &IC) {
Dan Gohmance9fe9f2009-07-21 23:21:54 +00005469 TargetData &TD = *IC.getTargetData();
Chris Lattner10c0d912008-04-22 02:53:33 +00005470 gep_type_iterator GTI = gep_type_begin(GEP);
5471
5472 // Check to see if this gep only has a single variable index. If so, and if
5473 // any constant indices are a multiple of its scale, then we can compute this
5474 // in terms of the scale of the variable index. For example, if the GEP
5475 // implies an offset of "12 + i*4", then we can codegen this as "3 + i",
5476 // because the expression will cross zero at the same point.
5477 unsigned i, e = GEP->getNumOperands();
5478 int64_t Offset = 0;
5479 for (i = 1; i != e; ++i, ++GTI) {
5480 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
5481 // Compute the aggregate offset of constant indices.
5482 if (CI->isZero()) continue;
5483
5484 // Handle a struct index, which adds its field offset to the pointer.
5485 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5486 Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
5487 } else {
Duncan Sands777d2302009-05-09 07:06:46 +00005488 uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType());
Chris Lattner10c0d912008-04-22 02:53:33 +00005489 Offset += Size*CI->getSExtValue();
5490 }
5491 } else {
5492 // Found our variable index.
5493 break;
5494 }
5495 }
5496
5497 // If there are no variable indices, we must have a constant offset, just
5498 // evaluate it the general way.
5499 if (i == e) return 0;
5500
5501 Value *VariableIdx = GEP->getOperand(i);
5502 // Determine the scale factor of the variable element. For example, this is
5503 // 4 if the variable index is into an array of i32.
Duncan Sands777d2302009-05-09 07:06:46 +00005504 uint64_t VariableScale = TD.getTypeAllocSize(GTI.getIndexedType());
Chris Lattner10c0d912008-04-22 02:53:33 +00005505
5506 // Verify that there are no other variable indices. If so, emit the hard way.
5507 for (++i, ++GTI; i != e; ++i, ++GTI) {
5508 ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i));
5509 if (!CI) return 0;
5510
5511 // Compute the aggregate offset of constant indices.
5512 if (CI->isZero()) continue;
5513
5514 // Handle a struct index, which adds its field offset to the pointer.
5515 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5516 Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
5517 } else {
Duncan Sands777d2302009-05-09 07:06:46 +00005518 uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType());
Chris Lattner10c0d912008-04-22 02:53:33 +00005519 Offset += Size*CI->getSExtValue();
5520 }
5521 }
5522
5523 // Okay, we know we have a single variable index, which must be a
5524 // pointer/array/vector index. If there is no offset, life is simple, return
5525 // the index.
5526 unsigned IntPtrWidth = TD.getPointerSizeInBits();
5527 if (Offset == 0) {
5528 // Cast to intptrty in case a truncation occurs. If an extension is needed,
5529 // we don't need to bother extending: the extension won't affect where the
5530 // computation crosses zero.
5531 if (VariableIdx->getType()->getPrimitiveSizeInBits() > IntPtrWidth)
5532 VariableIdx = new TruncInst(VariableIdx, TD.getIntPtrType(),
Daniel Dunbar460f6562009-07-26 09:48:23 +00005533 VariableIdx->getName(), &I);
Chris Lattner10c0d912008-04-22 02:53:33 +00005534 return VariableIdx;
5535 }
5536
5537 // Otherwise, there is an index. The computation we will do will be modulo
5538 // the pointer size, so get it.
5539 uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
5540
5541 Offset &= PtrSizeMask;
5542 VariableScale &= PtrSizeMask;
5543
5544 // To do this transformation, any constant index must be a multiple of the
5545 // variable scale factor. For example, we can evaluate "12 + 4*i" as "3 + i",
5546 // but we can't evaluate "10 + 3*i" in terms of i. Check that the offset is a
5547 // multiple of the variable scale.
5548 int64_t NewOffs = Offset / (int64_t)VariableScale;
5549 if (Offset != NewOffs*(int64_t)VariableScale)
5550 return 0;
5551
5552 // Okay, we can do this evaluation. Start by converting the index to intptr.
5553 const Type *IntPtrTy = TD.getIntPtrType();
5554 if (VariableIdx->getType() != IntPtrTy)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005555 VariableIdx = CastInst::CreateIntegerCast(VariableIdx, IntPtrTy,
Chris Lattner10c0d912008-04-22 02:53:33 +00005556 true /*SExt*/,
Daniel Dunbar460f6562009-07-26 09:48:23 +00005557 VariableIdx->getName(), &I);
Owen Andersoneed707b2009-07-24 23:12:02 +00005558 Constant *OffsetVal = ConstantInt::get(IntPtrTy, NewOffs);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005559 return BinaryOperator::CreateAdd(VariableIdx, OffsetVal, "offset", &I);
Chris Lattner10c0d912008-04-22 02:53:33 +00005560}
5561
5562
Reid Spencere4d87aa2006-12-23 06:05:41 +00005563/// FoldGEPICmp - Fold comparisons between a GEP instruction and something
Chris Lattner574da9b2005-01-13 20:14:25 +00005564/// else. At this point we know that the GEP is on the LHS of the comparison.
Dan Gohmand6aa02d2009-07-28 01:40:03 +00005565Instruction *InstCombiner::FoldGEPICmp(GEPOperator *GEPLHS, Value *RHS,
Reid Spencere4d87aa2006-12-23 06:05:41 +00005566 ICmpInst::Predicate Cond,
5567 Instruction &I) {
Chris Lattner10c0d912008-04-22 02:53:33 +00005568 // Look through bitcasts.
5569 if (BitCastInst *BCI = dyn_cast<BitCastInst>(RHS))
5570 RHS = BCI->getOperand(0);
Chris Lattnere9d782b2005-01-13 22:25:21 +00005571
Chris Lattner574da9b2005-01-13 20:14:25 +00005572 Value *PtrBase = GEPLHS->getOperand(0);
Dan Gohmand6aa02d2009-07-28 01:40:03 +00005573 if (TD && PtrBase == RHS && GEPLHS->isInBounds()) {
Chris Lattner7c95deb2008-02-05 04:45:32 +00005574 // ((gep Ptr, OFFSET) cmp Ptr) ---> (OFFSET cmp 0).
Chris Lattner10c0d912008-04-22 02:53:33 +00005575 // This transformation (ignoring the base and scales) is valid because we
Dan Gohmand6aa02d2009-07-28 01:40:03 +00005576 // know pointers can't overflow since the gep is inbounds. See if we can
5577 // output an optimized form.
Chris Lattner10c0d912008-04-22 02:53:33 +00005578 Value *Offset = EvaluateGEPOffsetExpression(GEPLHS, I, *this);
5579
5580 // If not, synthesize the offset the hard way.
5581 if (Offset == 0)
5582 Offset = EmitGEPOffset(GEPLHS, I, *this);
Owen Anderson333c4002009-07-09 23:48:35 +00005583 return new ICmpInst(*Context, ICmpInst::getSignedPredicate(Cond), Offset,
Owen Andersona7235ea2009-07-31 20:28:14 +00005584 Constant::getNullValue(Offset->getType()));
Dan Gohmand6aa02d2009-07-28 01:40:03 +00005585 } else if (GEPOperator *GEPRHS = dyn_cast<GEPOperator>(RHS)) {
Chris Lattnera70b66d2005-04-25 20:17:30 +00005586 // If the base pointers are different, but the indices are the same, just
5587 // compare the base pointer.
5588 if (PtrBase != GEPRHS->getOperand(0)) {
5589 bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
Jeff Cohen00b168892005-07-27 06:12:32 +00005590 IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
Chris Lattner93b94a62005-04-26 14:40:41 +00005591 GEPRHS->getOperand(0)->getType();
Chris Lattnera70b66d2005-04-25 20:17:30 +00005592 if (IndicesTheSame)
5593 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
5594 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
5595 IndicesTheSame = false;
5596 break;
5597 }
5598
5599 // If all indices are the same, just compare the base pointers.
5600 if (IndicesTheSame)
Owen Anderson333c4002009-07-09 23:48:35 +00005601 return new ICmpInst(*Context, ICmpInst::getSignedPredicate(Cond),
Reid Spencere4d87aa2006-12-23 06:05:41 +00005602 GEPLHS->getOperand(0), GEPRHS->getOperand(0));
Chris Lattnera70b66d2005-04-25 20:17:30 +00005603
5604 // Otherwise, the base pointers are different and the indices are
5605 // different, bail out.
Chris Lattner574da9b2005-01-13 20:14:25 +00005606 return 0;
Chris Lattnera70b66d2005-04-25 20:17:30 +00005607 }
Chris Lattner574da9b2005-01-13 20:14:25 +00005608
Chris Lattnere9d782b2005-01-13 22:25:21 +00005609 // If one of the GEPs has all zero indices, recurse.
5610 bool AllZeros = true;
5611 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
5612 if (!isa<Constant>(GEPLHS->getOperand(i)) ||
5613 !cast<Constant>(GEPLHS->getOperand(i))->isNullValue()) {
5614 AllZeros = false;
5615 break;
5616 }
5617 if (AllZeros)
Reid Spencere4d87aa2006-12-23 06:05:41 +00005618 return FoldGEPICmp(GEPRHS, GEPLHS->getOperand(0),
5619 ICmpInst::getSwappedPredicate(Cond), I);
Chris Lattner4401c9c2005-01-14 00:20:05 +00005620
5621 // If the other GEP has all zero indices, recurse.
Chris Lattnere9d782b2005-01-13 22:25:21 +00005622 AllZeros = true;
5623 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
5624 if (!isa<Constant>(GEPRHS->getOperand(i)) ||
5625 !cast<Constant>(GEPRHS->getOperand(i))->isNullValue()) {
5626 AllZeros = false;
5627 break;
5628 }
5629 if (AllZeros)
Reid Spencere4d87aa2006-12-23 06:05:41 +00005630 return FoldGEPICmp(GEPLHS, GEPRHS->getOperand(0), Cond, I);
Chris Lattnere9d782b2005-01-13 22:25:21 +00005631
Chris Lattner4401c9c2005-01-14 00:20:05 +00005632 if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
5633 // If the GEPs only differ by one index, compare it.
5634 unsigned NumDifferences = 0; // Keep track of # differences.
5635 unsigned DiffOperand = 0; // The operand that differs.
5636 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
5637 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
Chris Lattner484d3cf2005-04-24 06:59:08 +00005638 if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
5639 GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
Chris Lattner45f57b82005-01-21 23:06:49 +00005640 // Irreconcilable differences.
Chris Lattner4401c9c2005-01-14 00:20:05 +00005641 NumDifferences = 2;
5642 break;
5643 } else {
5644 if (NumDifferences++) break;
5645 DiffOperand = i;
5646 }
5647 }
5648
5649 if (NumDifferences == 0) // SAME GEP?
5650 return ReplaceInstUsesWith(I, // No comparison is needed here.
Owen Andersoneed707b2009-07-24 23:12:02 +00005651 ConstantInt::get(Type::Int1Ty,
Nick Lewyckyfc1efbb2008-05-17 07:33:39 +00005652 ICmpInst::isTrueWhenEqual(Cond)));
Nick Lewycky455e1762007-09-06 02:40:25 +00005653
Chris Lattner4401c9c2005-01-14 00:20:05 +00005654 else if (NumDifferences == 1) {
Chris Lattner45f57b82005-01-21 23:06:49 +00005655 Value *LHSV = GEPLHS->getOperand(DiffOperand);
5656 Value *RHSV = GEPRHS->getOperand(DiffOperand);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005657 // Make sure we do a signed comparison here.
Owen Anderson333c4002009-07-09 23:48:35 +00005658 return new ICmpInst(*Context,
5659 ICmpInst::getSignedPredicate(Cond), LHSV, RHSV);
Chris Lattner4401c9c2005-01-14 00:20:05 +00005660 }
5661 }
5662
Reid Spencere4d87aa2006-12-23 06:05:41 +00005663 // Only lower this if the icmp is the only user of the GEP or if we expect
Chris Lattner574da9b2005-01-13 20:14:25 +00005664 // the result to fold to a constant!
Dan Gohmance9fe9f2009-07-21 23:21:54 +00005665 if (TD &&
5666 (isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
Chris Lattner574da9b2005-01-13 20:14:25 +00005667 (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
5668 // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2) ---> (OFFSET1 cmp OFFSET2)
5669 Value *L = EmitGEPOffset(GEPLHS, I, *this);
5670 Value *R = EmitGEPOffset(GEPRHS, I, *this);
Owen Anderson333c4002009-07-09 23:48:35 +00005671 return new ICmpInst(*Context, ICmpInst::getSignedPredicate(Cond), L, R);
Chris Lattner574da9b2005-01-13 20:14:25 +00005672 }
5673 }
5674 return 0;
5675}
5676
Chris Lattnera5406232008-05-19 20:18:56 +00005677/// FoldFCmp_IntToFP_Cst - Fold fcmp ([us]itofp x, cst) if possible.
5678///
5679Instruction *InstCombiner::FoldFCmp_IntToFP_Cst(FCmpInst &I,
5680 Instruction *LHSI,
5681 Constant *RHSC) {
5682 if (!isa<ConstantFP>(RHSC)) return 0;
5683 const APFloat &RHS = cast<ConstantFP>(RHSC)->getValueAPF();
5684
5685 // Get the width of the mantissa. We don't want to hack on conversions that
5686 // might lose information from the integer, e.g. "i64 -> float"
Chris Lattner7be1c452008-05-19 21:17:23 +00005687 int MantissaWidth = LHSI->getType()->getFPMantissaWidth();
Chris Lattnera5406232008-05-19 20:18:56 +00005688 if (MantissaWidth == -1) return 0; // Unknown.
5689
5690 // Check to see that the input is converted from an integer type that is small
5691 // enough that preserves all bits. TODO: check here for "known" sign bits.
5692 // This would allow us to handle (fptosi (x >>s 62) to float) if x is i64 f.e.
Dan Gohman6de29f82009-06-15 22:12:54 +00005693 unsigned InputSize = LHSI->getOperand(0)->getType()->getScalarSizeInBits();
Chris Lattnera5406232008-05-19 20:18:56 +00005694
5695 // If this is a uitofp instruction, we need an extra bit to hold the sign.
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005696 bool LHSUnsigned = isa<UIToFPInst>(LHSI);
5697 if (LHSUnsigned)
Chris Lattnera5406232008-05-19 20:18:56 +00005698 ++InputSize;
5699
5700 // If the conversion would lose info, don't hack on this.
5701 if ((int)InputSize > MantissaWidth)
5702 return 0;
5703
5704 // Otherwise, we can potentially simplify the comparison. We know that it
5705 // will always come through as an integer value and we know the constant is
5706 // not a NAN (it would have been previously simplified).
5707 assert(!RHS.isNaN() && "NaN comparison not already folded!");
5708
5709 ICmpInst::Predicate Pred;
5710 switch (I.getPredicate()) {
Torok Edwinc23197a2009-07-14 16:55:14 +00005711 default: llvm_unreachable("Unexpected predicate!");
Chris Lattnera5406232008-05-19 20:18:56 +00005712 case FCmpInst::FCMP_UEQ:
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005713 case FCmpInst::FCMP_OEQ:
5714 Pred = ICmpInst::ICMP_EQ;
5715 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005716 case FCmpInst::FCMP_UGT:
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005717 case FCmpInst::FCMP_OGT:
5718 Pred = LHSUnsigned ? ICmpInst::ICMP_UGT : ICmpInst::ICMP_SGT;
5719 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005720 case FCmpInst::FCMP_UGE:
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005721 case FCmpInst::FCMP_OGE:
5722 Pred = LHSUnsigned ? ICmpInst::ICMP_UGE : ICmpInst::ICMP_SGE;
5723 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005724 case FCmpInst::FCMP_ULT:
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005725 case FCmpInst::FCMP_OLT:
5726 Pred = LHSUnsigned ? ICmpInst::ICMP_ULT : ICmpInst::ICMP_SLT;
5727 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005728 case FCmpInst::FCMP_ULE:
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005729 case FCmpInst::FCMP_OLE:
5730 Pred = LHSUnsigned ? ICmpInst::ICMP_ULE : ICmpInst::ICMP_SLE;
5731 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005732 case FCmpInst::FCMP_UNE:
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005733 case FCmpInst::FCMP_ONE:
5734 Pred = ICmpInst::ICMP_NE;
5735 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005736 case FCmpInst::FCMP_ORD:
Owen Anderson5defacc2009-07-31 17:39:07 +00005737 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Chris Lattnera5406232008-05-19 20:18:56 +00005738 case FCmpInst::FCMP_UNO:
Owen Anderson5defacc2009-07-31 17:39:07 +00005739 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattnera5406232008-05-19 20:18:56 +00005740 }
5741
5742 const IntegerType *IntTy = cast<IntegerType>(LHSI->getOperand(0)->getType());
5743
5744 // Now we know that the APFloat is a normal number, zero or inf.
5745
Chris Lattner85162782008-05-20 03:50:52 +00005746 // See if the FP constant is too large for the integer. For example,
Chris Lattnera5406232008-05-19 20:18:56 +00005747 // comparing an i8 to 300.0.
Dan Gohman6de29f82009-06-15 22:12:54 +00005748 unsigned IntWidth = IntTy->getScalarSizeInBits();
Chris Lattnera5406232008-05-19 20:18:56 +00005749
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005750 if (!LHSUnsigned) {
5751 // If the RHS value is > SignedMax, fold the comparison. This handles +INF
5752 // and large values.
5753 APFloat SMax(RHS.getSemantics(), APFloat::fcZero, false);
5754 SMax.convertFromAPInt(APInt::getSignedMaxValue(IntWidth), true,
5755 APFloat::rmNearestTiesToEven);
5756 if (SMax.compare(RHS) == APFloat::cmpLessThan) { // smax < 13123.0
5757 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SLT ||
5758 Pred == ICmpInst::ICMP_SLE)
Owen Anderson5defacc2009-07-31 17:39:07 +00005759 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5760 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005761 }
5762 } else {
5763 // If the RHS value is > UnsignedMax, fold the comparison. This handles
5764 // +INF and large values.
5765 APFloat UMax(RHS.getSemantics(), APFloat::fcZero, false);
5766 UMax.convertFromAPInt(APInt::getMaxValue(IntWidth), false,
5767 APFloat::rmNearestTiesToEven);
5768 if (UMax.compare(RHS) == APFloat::cmpLessThan) { // umax < 13123.0
5769 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_ULT ||
5770 Pred == ICmpInst::ICMP_ULE)
Owen Anderson5defacc2009-07-31 17:39:07 +00005771 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5772 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005773 }
Chris Lattnera5406232008-05-19 20:18:56 +00005774 }
5775
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005776 if (!LHSUnsigned) {
5777 // See if the RHS value is < SignedMin.
5778 APFloat SMin(RHS.getSemantics(), APFloat::fcZero, false);
5779 SMin.convertFromAPInt(APInt::getSignedMinValue(IntWidth), true,
5780 APFloat::rmNearestTiesToEven);
5781 if (SMin.compare(RHS) == APFloat::cmpGreaterThan) { // smin > 12312.0
5782 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SGT ||
5783 Pred == ICmpInst::ICMP_SGE)
Owen Anderson5defacc2009-07-31 17:39:07 +00005784 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5785 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005786 }
Chris Lattnera5406232008-05-19 20:18:56 +00005787 }
5788
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005789 // Okay, now we know that the FP constant fits in the range [SMIN, SMAX] or
5790 // [0, UMAX], but it may still be fractional. See if it is fractional by
5791 // casting the FP value to the integer value and back, checking for equality.
5792 // Don't do this for zero, because -0.0 is not fractional.
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005793 Constant *RHSInt = LHSUnsigned
Owen Andersonbaf3c402009-07-29 18:55:55 +00005794 ? ConstantExpr::getFPToUI(RHSC, IntTy)
5795 : ConstantExpr::getFPToSI(RHSC, IntTy);
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005796 if (!RHS.isZero()) {
5797 bool Equal = LHSUnsigned
Owen Andersonbaf3c402009-07-29 18:55:55 +00005798 ? ConstantExpr::getUIToFP(RHSInt, RHSC->getType()) == RHSC
5799 : ConstantExpr::getSIToFP(RHSInt, RHSC->getType()) == RHSC;
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005800 if (!Equal) {
5801 // If we had a comparison against a fractional value, we have to adjust
5802 // the compare predicate and sometimes the value. RHSC is rounded towards
5803 // zero at this point.
5804 switch (Pred) {
Torok Edwinc23197a2009-07-14 16:55:14 +00005805 default: llvm_unreachable("Unexpected integer comparison!");
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005806 case ICmpInst::ICMP_NE: // (float)int != 4.4 --> true
Owen Anderson5defacc2009-07-31 17:39:07 +00005807 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005808 case ICmpInst::ICMP_EQ: // (float)int == 4.4 --> false
Owen Anderson5defacc2009-07-31 17:39:07 +00005809 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005810 case ICmpInst::ICMP_ULE:
5811 // (float)int <= 4.4 --> int <= 4
5812 // (float)int <= -4.4 --> false
5813 if (RHS.isNegative())
Owen Anderson5defacc2009-07-31 17:39:07 +00005814 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005815 break;
5816 case ICmpInst::ICMP_SLE:
5817 // (float)int <= 4.4 --> int <= 4
5818 // (float)int <= -4.4 --> int < -4
5819 if (RHS.isNegative())
5820 Pred = ICmpInst::ICMP_SLT;
5821 break;
5822 case ICmpInst::ICMP_ULT:
5823 // (float)int < -4.4 --> false
5824 // (float)int < 4.4 --> int <= 4
5825 if (RHS.isNegative())
Owen Anderson5defacc2009-07-31 17:39:07 +00005826 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005827 Pred = ICmpInst::ICMP_ULE;
5828 break;
5829 case ICmpInst::ICMP_SLT:
5830 // (float)int < -4.4 --> int < -4
5831 // (float)int < 4.4 --> int <= 4
5832 if (!RHS.isNegative())
5833 Pred = ICmpInst::ICMP_SLE;
5834 break;
5835 case ICmpInst::ICMP_UGT:
5836 // (float)int > 4.4 --> int > 4
5837 // (float)int > -4.4 --> true
5838 if (RHS.isNegative())
Owen Anderson5defacc2009-07-31 17:39:07 +00005839 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005840 break;
5841 case ICmpInst::ICMP_SGT:
5842 // (float)int > 4.4 --> int > 4
5843 // (float)int > -4.4 --> int >= -4
5844 if (RHS.isNegative())
5845 Pred = ICmpInst::ICMP_SGE;
5846 break;
5847 case ICmpInst::ICMP_UGE:
5848 // (float)int >= -4.4 --> true
5849 // (float)int >= 4.4 --> int > 4
5850 if (!RHS.isNegative())
Owen Anderson5defacc2009-07-31 17:39:07 +00005851 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005852 Pred = ICmpInst::ICMP_UGT;
5853 break;
5854 case ICmpInst::ICMP_SGE:
5855 // (float)int >= -4.4 --> int >= -4
5856 // (float)int >= 4.4 --> int > 4
5857 if (!RHS.isNegative())
5858 Pred = ICmpInst::ICMP_SGT;
5859 break;
5860 }
Chris Lattnera5406232008-05-19 20:18:56 +00005861 }
5862 }
5863
5864 // Lower this FP comparison into an appropriate integer version of the
5865 // comparison.
Owen Anderson333c4002009-07-09 23:48:35 +00005866 return new ICmpInst(*Context, Pred, LHSI->getOperand(0), RHSInt);
Chris Lattnera5406232008-05-19 20:18:56 +00005867}
5868
Reid Spencere4d87aa2006-12-23 06:05:41 +00005869Instruction *InstCombiner::visitFCmpInst(FCmpInst &I) {
5870 bool Changed = SimplifyCompare(I);
Chris Lattner8b170942002-08-09 23:47:40 +00005871 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00005872
Chris Lattner58e97462007-01-14 19:42:17 +00005873 // Fold trivial predicates.
5874 if (I.getPredicate() == FCmpInst::FCMP_FALSE)
Owen Anderson5defacc2009-07-31 17:39:07 +00005875 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattner58e97462007-01-14 19:42:17 +00005876 if (I.getPredicate() == FCmpInst::FCMP_TRUE)
Owen Anderson5defacc2009-07-31 17:39:07 +00005877 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Chris Lattner58e97462007-01-14 19:42:17 +00005878
5879 // Simplify 'fcmp pred X, X'
5880 if (Op0 == Op1) {
5881 switch (I.getPredicate()) {
Torok Edwinc23197a2009-07-14 16:55:14 +00005882 default: llvm_unreachable("Unknown predicate!");
Chris Lattner58e97462007-01-14 19:42:17 +00005883 case FCmpInst::FCMP_UEQ: // True if unordered or equal
5884 case FCmpInst::FCMP_UGE: // True if unordered, greater than, or equal
5885 case FCmpInst::FCMP_ULE: // True if unordered, less than, or equal
Owen Anderson5defacc2009-07-31 17:39:07 +00005886 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Chris Lattner58e97462007-01-14 19:42:17 +00005887 case FCmpInst::FCMP_OGT: // True if ordered and greater than
5888 case FCmpInst::FCMP_OLT: // True if ordered and less than
5889 case FCmpInst::FCMP_ONE: // True if ordered and operands are unequal
Owen Anderson5defacc2009-07-31 17:39:07 +00005890 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattner58e97462007-01-14 19:42:17 +00005891
5892 case FCmpInst::FCMP_UNO: // True if unordered: isnan(X) | isnan(Y)
5893 case FCmpInst::FCMP_ULT: // True if unordered or less than
5894 case FCmpInst::FCMP_UGT: // True if unordered or greater than
5895 case FCmpInst::FCMP_UNE: // True if unordered or not equal
5896 // Canonicalize these to be 'fcmp uno %X, 0.0'.
5897 I.setPredicate(FCmpInst::FCMP_UNO);
Owen Andersona7235ea2009-07-31 20:28:14 +00005898 I.setOperand(1, Constant::getNullValue(Op0->getType()));
Chris Lattner58e97462007-01-14 19:42:17 +00005899 return &I;
5900
5901 case FCmpInst::FCMP_ORD: // True if ordered (no nans)
5902 case FCmpInst::FCMP_OEQ: // True if ordered and equal
5903 case FCmpInst::FCMP_OGE: // True if ordered and greater than or equal
5904 case FCmpInst::FCMP_OLE: // True if ordered and less than or equal
5905 // Canonicalize these to be 'fcmp ord %X, 0.0'.
5906 I.setPredicate(FCmpInst::FCMP_ORD);
Owen Andersona7235ea2009-07-31 20:28:14 +00005907 I.setOperand(1, Constant::getNullValue(Op0->getType()));
Chris Lattner58e97462007-01-14 19:42:17 +00005908 return &I;
5909 }
5910 }
5911
Reid Spencere4d87aa2006-12-23 06:05:41 +00005912 if (isa<UndefValue>(Op1)) // fcmp pred X, undef -> undef
Owen Anderson9e9a0d52009-07-30 23:03:37 +00005913 return ReplaceInstUsesWith(I, UndefValue::get(Type::Int1Ty));
Chris Lattnere87597f2004-10-16 18:11:37 +00005914
Reid Spencere4d87aa2006-12-23 06:05:41 +00005915 // Handle fcmp with constant RHS
5916 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
Chris Lattnera5406232008-05-19 20:18:56 +00005917 // If the constant is a nan, see if we can fold the comparison based on it.
5918 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
5919 if (CFP->getValueAPF().isNaN()) {
5920 if (FCmpInst::isOrdered(I.getPredicate())) // True if ordered and...
Owen Anderson5defacc2009-07-31 17:39:07 +00005921 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattner85162782008-05-20 03:50:52 +00005922 assert(FCmpInst::isUnordered(I.getPredicate()) &&
5923 "Comparison must be either ordered or unordered!");
5924 // True if unordered.
Owen Anderson5defacc2009-07-31 17:39:07 +00005925 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Chris Lattnera5406232008-05-19 20:18:56 +00005926 }
5927 }
5928
Reid Spencere4d87aa2006-12-23 06:05:41 +00005929 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5930 switch (LHSI->getOpcode()) {
5931 case Instruction::PHI:
Chris Lattner7d8ab4e2008-06-08 20:52:11 +00005932 // Only fold fcmp into the PHI if the phi and fcmp are in the same
5933 // block. If in the same block, we're encouraging jump threading. If
5934 // not, we are just pessimizing the code by making an i1 phi.
5935 if (LHSI->getParent() == I.getParent())
5936 if (Instruction *NV = FoldOpIntoPhi(I))
5937 return NV;
Reid Spencere4d87aa2006-12-23 06:05:41 +00005938 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005939 case Instruction::SIToFP:
5940 case Instruction::UIToFP:
5941 if (Instruction *NV = FoldFCmp_IntToFP_Cst(I, LHSI, RHSC))
5942 return NV;
5943 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00005944 case Instruction::Select:
5945 // If either operand of the select is a constant, we can fold the
5946 // comparison into the select arms, which will cause one to be
5947 // constant folded and the select turned into a bitwise or.
5948 Value *Op1 = 0, *Op2 = 0;
5949 if (LHSI->hasOneUse()) {
5950 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
5951 // Fold the known value into the constant operand.
Owen Andersonbaf3c402009-07-29 18:55:55 +00005952 Op1 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005953 // Insert a new FCmp of the other select operand.
Owen Anderson333c4002009-07-09 23:48:35 +00005954 Op2 = InsertNewInstBefore(new FCmpInst(*Context, I.getPredicate(),
Reid Spencere4d87aa2006-12-23 06:05:41 +00005955 LHSI->getOperand(2), RHSC,
5956 I.getName()), I);
5957 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
5958 // Fold the known value into the constant operand.
Owen Andersonbaf3c402009-07-29 18:55:55 +00005959 Op2 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005960 // Insert a new FCmp of the other select operand.
Owen Anderson333c4002009-07-09 23:48:35 +00005961 Op1 = InsertNewInstBefore(new FCmpInst(*Context, I.getPredicate(),
Reid Spencere4d87aa2006-12-23 06:05:41 +00005962 LHSI->getOperand(1), RHSC,
5963 I.getName()), I);
5964 }
5965 }
5966
5967 if (Op1)
Gabor Greif051a9502008-04-06 20:25:17 +00005968 return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005969 break;
5970 }
5971 }
5972
5973 return Changed ? &I : 0;
5974}
5975
5976Instruction *InstCombiner::visitICmpInst(ICmpInst &I) {
5977 bool Changed = SimplifyCompare(I);
5978 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5979 const Type *Ty = Op0->getType();
5980
5981 // icmp X, X
5982 if (Op0 == Op1)
Owen Andersoneed707b2009-07-24 23:12:02 +00005983 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
Nick Lewyckyfc1efbb2008-05-17 07:33:39 +00005984 I.isTrueWhenEqual()));
Reid Spencere4d87aa2006-12-23 06:05:41 +00005985
5986 if (isa<UndefValue>(Op1)) // X icmp undef -> undef
Owen Anderson9e9a0d52009-07-30 23:03:37 +00005987 return ReplaceInstUsesWith(I, UndefValue::get(Type::Int1Ty));
Christopher Lamb7a0678c2007-12-18 21:32:20 +00005988
Reid Spencere4d87aa2006-12-23 06:05:41 +00005989 // icmp <global/alloca*/null>, <global/alloca*/null> - Global/Stack value
Chris Lattner711b3402004-11-14 07:33:16 +00005990 // addresses never equal each other! We already know that Op0 != Op1.
Misha Brukmanfd939082005-04-21 23:48:37 +00005991 if ((isa<GlobalValue>(Op0) || isa<AllocaInst>(Op0) ||
5992 isa<ConstantPointerNull>(Op0)) &&
5993 (isa<GlobalValue>(Op1) || isa<AllocaInst>(Op1) ||
Chris Lattner711b3402004-11-14 07:33:16 +00005994 isa<ConstantPointerNull>(Op1)))
Owen Andersoneed707b2009-07-24 23:12:02 +00005995 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
Nick Lewyckyfc1efbb2008-05-17 07:33:39 +00005996 !I.isTrueWhenEqual()));
Chris Lattner8b170942002-08-09 23:47:40 +00005997
Reid Spencere4d87aa2006-12-23 06:05:41 +00005998 // icmp's with boolean values can always be turned into bitwise operations
Reid Spencer4fe16d62007-01-11 18:21:29 +00005999 if (Ty == Type::Int1Ty) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00006000 switch (I.getPredicate()) {
Torok Edwinc23197a2009-07-14 16:55:14 +00006001 default: llvm_unreachable("Invalid icmp instruction!");
Chris Lattner85b5eb02008-07-11 04:20:58 +00006002 case ICmpInst::ICMP_EQ: { // icmp eq i1 A, B -> ~(A^B)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006003 Instruction *Xor = BinaryOperator::CreateXor(Op0, Op1, I.getName()+"tmp");
Chris Lattner8b170942002-08-09 23:47:40 +00006004 InsertNewInstBefore(Xor, I);
Owen Anderson73c6b712009-07-13 20:58:05 +00006005 return BinaryOperator::CreateNot(*Context, Xor);
Chris Lattner8b170942002-08-09 23:47:40 +00006006 }
Chris Lattner85b5eb02008-07-11 04:20:58 +00006007 case ICmpInst::ICMP_NE: // icmp eq i1 A, B -> A^B
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006008 return BinaryOperator::CreateXor(Op0, Op1);
Chris Lattner8b170942002-08-09 23:47:40 +00006009
Reid Spencere4d87aa2006-12-23 06:05:41 +00006010 case ICmpInst::ICMP_UGT:
Chris Lattner85b5eb02008-07-11 04:20:58 +00006011 std::swap(Op0, Op1); // Change icmp ugt -> icmp ult
Chris Lattner5dbef222004-08-11 00:50:51 +00006012 // FALL THROUGH
Chris Lattner85b5eb02008-07-11 04:20:58 +00006013 case ICmpInst::ICMP_ULT:{ // icmp ult i1 A, B -> ~A & B
Owen Anderson73c6b712009-07-13 20:58:05 +00006014 Instruction *Not = BinaryOperator::CreateNot(*Context,
6015 Op0, I.getName()+"tmp");
Chris Lattner5dbef222004-08-11 00:50:51 +00006016 InsertNewInstBefore(Not, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006017 return BinaryOperator::CreateAnd(Not, Op1);
Chris Lattner5dbef222004-08-11 00:50:51 +00006018 }
Chris Lattner85b5eb02008-07-11 04:20:58 +00006019 case ICmpInst::ICMP_SGT:
6020 std::swap(Op0, Op1); // Change icmp sgt -> icmp slt
Chris Lattner5dbef222004-08-11 00:50:51 +00006021 // FALL THROUGH
Chris Lattner85b5eb02008-07-11 04:20:58 +00006022 case ICmpInst::ICMP_SLT: { // icmp slt i1 A, B -> A & ~B
Owen Anderson73c6b712009-07-13 20:58:05 +00006023 Instruction *Not = BinaryOperator::CreateNot(*Context,
6024 Op1, I.getName()+"tmp");
Chris Lattner85b5eb02008-07-11 04:20:58 +00006025 InsertNewInstBefore(Not, I);
6026 return BinaryOperator::CreateAnd(Not, Op0);
6027 }
6028 case ICmpInst::ICMP_UGE:
6029 std::swap(Op0, Op1); // Change icmp uge -> icmp ule
6030 // FALL THROUGH
6031 case ICmpInst::ICMP_ULE: { // icmp ule i1 A, B -> ~A | B
Owen Anderson73c6b712009-07-13 20:58:05 +00006032 Instruction *Not = BinaryOperator::CreateNot(*Context,
6033 Op0, I.getName()+"tmp");
Chris Lattner5dbef222004-08-11 00:50:51 +00006034 InsertNewInstBefore(Not, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006035 return BinaryOperator::CreateOr(Not, Op1);
Chris Lattner5dbef222004-08-11 00:50:51 +00006036 }
Chris Lattner85b5eb02008-07-11 04:20:58 +00006037 case ICmpInst::ICMP_SGE:
6038 std::swap(Op0, Op1); // Change icmp sge -> icmp sle
6039 // FALL THROUGH
6040 case ICmpInst::ICMP_SLE: { // icmp sle i1 A, B -> A | ~B
Owen Anderson73c6b712009-07-13 20:58:05 +00006041 Instruction *Not = BinaryOperator::CreateNot(*Context,
6042 Op1, I.getName()+"tmp");
Chris Lattner85b5eb02008-07-11 04:20:58 +00006043 InsertNewInstBefore(Not, I);
6044 return BinaryOperator::CreateOr(Not, Op0);
6045 }
Chris Lattner5dbef222004-08-11 00:50:51 +00006046 }
Chris Lattner8b170942002-08-09 23:47:40 +00006047 }
6048
Dan Gohman1c8491e2009-04-25 17:12:48 +00006049 unsigned BitWidth = 0;
6050 if (TD)
Dan Gohmanc6ac3222009-06-16 19:55:29 +00006051 BitWidth = TD->getTypeSizeInBits(Ty->getScalarType());
6052 else if (Ty->isIntOrIntVector())
6053 BitWidth = Ty->getScalarSizeInBits();
Dan Gohman1c8491e2009-04-25 17:12:48 +00006054
6055 bool isSignBit = false;
6056
Dan Gohman81b28ce2008-09-16 18:46:06 +00006057 // See if we are doing a comparison with a constant.
Chris Lattner8b170942002-08-09 23:47:40 +00006058 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Nick Lewycky579214a2009-02-27 06:37:39 +00006059 Value *A = 0, *B = 0;
Christopher Lamb103e1a32007-12-20 07:21:11 +00006060
Chris Lattnerb6566012008-01-05 01:18:20 +00006061 // (icmp ne/eq (sub A B) 0) -> (icmp ne/eq A, B)
6062 if (I.isEquality() && CI->isNullValue() &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00006063 match(Op0, m_Sub(m_Value(A), m_Value(B)), *Context)) {
Chris Lattnerb6566012008-01-05 01:18:20 +00006064 // (icmp cond A B) if cond is equality
Owen Anderson333c4002009-07-09 23:48:35 +00006065 return new ICmpInst(*Context, I.getPredicate(), A, B);
Owen Andersonf5783f82007-12-28 07:42:12 +00006066 }
Christopher Lamb103e1a32007-12-20 07:21:11 +00006067
Dan Gohman81b28ce2008-09-16 18:46:06 +00006068 // If we have an icmp le or icmp ge instruction, turn it into the
6069 // appropriate icmp lt or icmp gt instruction. This allows us to rely on
6070 // them being folded in the code below.
Chris Lattner84dff672008-07-11 05:08:55 +00006071 switch (I.getPredicate()) {
6072 default: break;
6073 case ICmpInst::ICMP_ULE:
6074 if (CI->isMaxValue(false)) // A <=u MAX -> TRUE
Owen Anderson5defacc2009-07-31 17:39:07 +00006075 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Owen Anderson333c4002009-07-09 23:48:35 +00006076 return new ICmpInst(*Context, ICmpInst::ICMP_ULT, Op0,
Dan Gohman186a6362009-08-12 16:04:34 +00006077 AddOne(CI));
Chris Lattner84dff672008-07-11 05:08:55 +00006078 case ICmpInst::ICMP_SLE:
6079 if (CI->isMaxValue(true)) // A <=s MAX -> TRUE
Owen Anderson5defacc2009-07-31 17:39:07 +00006080 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Owen Anderson333c4002009-07-09 23:48:35 +00006081 return new ICmpInst(*Context, ICmpInst::ICMP_SLT, Op0,
Dan Gohman186a6362009-08-12 16:04:34 +00006082 AddOne(CI));
Chris Lattner84dff672008-07-11 05:08:55 +00006083 case ICmpInst::ICMP_UGE:
6084 if (CI->isMinValue(false)) // A >=u MIN -> TRUE
Owen Anderson5defacc2009-07-31 17:39:07 +00006085 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Owen Anderson333c4002009-07-09 23:48:35 +00006086 return new ICmpInst(*Context, ICmpInst::ICMP_UGT, Op0,
Dan Gohman186a6362009-08-12 16:04:34 +00006087 SubOne(CI));
Chris Lattner84dff672008-07-11 05:08:55 +00006088 case ICmpInst::ICMP_SGE:
6089 if (CI->isMinValue(true)) // A >=s MIN -> TRUE
Owen Anderson5defacc2009-07-31 17:39:07 +00006090 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Owen Anderson333c4002009-07-09 23:48:35 +00006091 return new ICmpInst(*Context, ICmpInst::ICMP_SGT, Op0,
Dan Gohman186a6362009-08-12 16:04:34 +00006092 SubOne(CI));
Chris Lattner84dff672008-07-11 05:08:55 +00006093 }
6094
Chris Lattner183661e2008-07-11 05:40:05 +00006095 // If this comparison is a normal comparison, it demands all
Chris Lattner4241e4d2007-07-15 20:54:51 +00006096 // bits, if it is a sign bit comparison, it only demands the sign bit.
Chris Lattner4241e4d2007-07-15 20:54:51 +00006097 bool UnusedBit;
Dan Gohman1c8491e2009-04-25 17:12:48 +00006098 isSignBit = isSignBitCheck(I.getPredicate(), CI, UnusedBit);
6099 }
6100
6101 // See if we can fold the comparison based on range information we can get
6102 // by checking whether bits are known to be zero or one in the input.
6103 if (BitWidth != 0) {
6104 APInt Op0KnownZero(BitWidth, 0), Op0KnownOne(BitWidth, 0);
6105 APInt Op1KnownZero(BitWidth, 0), Op1KnownOne(BitWidth, 0);
6106
6107 if (SimplifyDemandedBits(I.getOperandUse(0),
Chris Lattner4241e4d2007-07-15 20:54:51 +00006108 isSignBit ? APInt::getSignBit(BitWidth)
6109 : APInt::getAllOnesValue(BitWidth),
Dan Gohman1c8491e2009-04-25 17:12:48 +00006110 Op0KnownZero, Op0KnownOne, 0))
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00006111 return &I;
Dan Gohman1c8491e2009-04-25 17:12:48 +00006112 if (SimplifyDemandedBits(I.getOperandUse(1),
6113 APInt::getAllOnesValue(BitWidth),
6114 Op1KnownZero, Op1KnownOne, 0))
6115 return &I;
6116
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00006117 // Given the known and unknown bits, compute a range that the LHS could be
Chris Lattner84dff672008-07-11 05:08:55 +00006118 // in. Compute the Min, Max and RHS values based on the known bits. For the
6119 // EQ and NE we use unsigned values.
Dan Gohman1c8491e2009-04-25 17:12:48 +00006120 APInt Op0Min(BitWidth, 0), Op0Max(BitWidth, 0);
6121 APInt Op1Min(BitWidth, 0), Op1Max(BitWidth, 0);
6122 if (ICmpInst::isSignedPredicate(I.getPredicate())) {
6123 ComputeSignedMinMaxValuesFromKnownBits(Op0KnownZero, Op0KnownOne,
6124 Op0Min, Op0Max);
6125 ComputeSignedMinMaxValuesFromKnownBits(Op1KnownZero, Op1KnownOne,
6126 Op1Min, Op1Max);
6127 } else {
6128 ComputeUnsignedMinMaxValuesFromKnownBits(Op0KnownZero, Op0KnownOne,
6129 Op0Min, Op0Max);
6130 ComputeUnsignedMinMaxValuesFromKnownBits(Op1KnownZero, Op1KnownOne,
6131 Op1Min, Op1Max);
6132 }
6133
Chris Lattner183661e2008-07-11 05:40:05 +00006134 // If Min and Max are known to be the same, then SimplifyDemandedBits
6135 // figured out that the LHS is a constant. Just constant fold this now so
6136 // that code below can assume that Min != Max.
Dan Gohman1c8491e2009-04-25 17:12:48 +00006137 if (!isa<Constant>(Op0) && Op0Min == Op0Max)
Owen Anderson333c4002009-07-09 23:48:35 +00006138 return new ICmpInst(*Context, I.getPredicate(),
Owen Andersoneed707b2009-07-24 23:12:02 +00006139 ConstantInt::get(*Context, Op0Min), Op1);
Dan Gohman1c8491e2009-04-25 17:12:48 +00006140 if (!isa<Constant>(Op1) && Op1Min == Op1Max)
Owen Anderson333c4002009-07-09 23:48:35 +00006141 return new ICmpInst(*Context, I.getPredicate(), Op0,
Owen Andersoneed707b2009-07-24 23:12:02 +00006142 ConstantInt::get(*Context, Op1Min));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006143
Chris Lattner183661e2008-07-11 05:40:05 +00006144 // Based on the range information we know about the LHS, see if we can
6145 // simplify this comparison. For example, (x&4) < 8 is always true.
Dan Gohman1c8491e2009-04-25 17:12:48 +00006146 switch (I.getPredicate()) {
Torok Edwinc23197a2009-07-14 16:55:14 +00006147 default: llvm_unreachable("Unknown icmp opcode!");
Chris Lattner84dff672008-07-11 05:08:55 +00006148 case ICmpInst::ICMP_EQ:
Dan Gohman1c8491e2009-04-25 17:12:48 +00006149 if (Op0Max.ult(Op1Min) || Op0Min.ugt(Op1Max))
Owen Anderson5defacc2009-07-31 17:39:07 +00006150 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattner84dff672008-07-11 05:08:55 +00006151 break;
6152 case ICmpInst::ICMP_NE:
Dan Gohman1c8491e2009-04-25 17:12:48 +00006153 if (Op0Max.ult(Op1Min) || Op0Min.ugt(Op1Max))
Owen Anderson5defacc2009-07-31 17:39:07 +00006154 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Chris Lattner84dff672008-07-11 05:08:55 +00006155 break;
6156 case ICmpInst::ICMP_ULT:
Dan Gohman1c8491e2009-04-25 17:12:48 +00006157 if (Op0Max.ult(Op1Min)) // A <u B -> true if max(A) < min(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006158 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006159 if (Op0Min.uge(Op1Max)) // A <u B -> false if min(A) >= max(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006160 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006161 if (Op1Min == Op0Max) // A <u B -> A != B if max(A) == min(B)
Owen Anderson333c4002009-07-09 23:48:35 +00006162 return new ICmpInst(*Context, ICmpInst::ICMP_NE, Op0, Op1);
Dan Gohman1c8491e2009-04-25 17:12:48 +00006163 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6164 if (Op1Max == Op0Min+1) // A <u C -> A == C-1 if min(A)+1 == C
Owen Anderson333c4002009-07-09 23:48:35 +00006165 return new ICmpInst(*Context, ICmpInst::ICMP_EQ, Op0,
Dan Gohman186a6362009-08-12 16:04:34 +00006166 SubOne(CI));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006167
6168 // (x <u 2147483648) -> (x >s -1) -> true if sign bit clear
6169 if (CI->isMinValue(true))
Owen Anderson333c4002009-07-09 23:48:35 +00006170 return new ICmpInst(*Context, ICmpInst::ICMP_SGT, Op0,
Owen Andersona7235ea2009-07-31 20:28:14 +00006171 Constant::getAllOnesValue(Op0->getType()));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006172 }
Chris Lattner84dff672008-07-11 05:08:55 +00006173 break;
6174 case ICmpInst::ICMP_UGT:
Dan Gohman1c8491e2009-04-25 17:12:48 +00006175 if (Op0Min.ugt(Op1Max)) // A >u B -> true if min(A) > max(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006176 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006177 if (Op0Max.ule(Op1Min)) // A >u B -> false if max(A) <= max(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006178 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006179
6180 if (Op1Max == Op0Min) // A >u B -> A != B if min(A) == max(B)
Owen Anderson333c4002009-07-09 23:48:35 +00006181 return new ICmpInst(*Context, ICmpInst::ICMP_NE, Op0, Op1);
Dan Gohman1c8491e2009-04-25 17:12:48 +00006182 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6183 if (Op1Min == Op0Max-1) // A >u C -> A == C+1 if max(a)-1 == C
Owen Anderson333c4002009-07-09 23:48:35 +00006184 return new ICmpInst(*Context, ICmpInst::ICMP_EQ, Op0,
Dan Gohman186a6362009-08-12 16:04:34 +00006185 AddOne(CI));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006186
6187 // (x >u 2147483647) -> (x <s 0) -> true if sign bit set
6188 if (CI->isMaxValue(true))
Owen Anderson333c4002009-07-09 23:48:35 +00006189 return new ICmpInst(*Context, ICmpInst::ICMP_SLT, Op0,
Owen Andersona7235ea2009-07-31 20:28:14 +00006190 Constant::getNullValue(Op0->getType()));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006191 }
Chris Lattner84dff672008-07-11 05:08:55 +00006192 break;
6193 case ICmpInst::ICMP_SLT:
Dan Gohman1c8491e2009-04-25 17:12:48 +00006194 if (Op0Max.slt(Op1Min)) // A <s B -> true if max(A) < min(C)
Owen Anderson5defacc2009-07-31 17:39:07 +00006195 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006196 if (Op0Min.sge(Op1Max)) // A <s B -> false if min(A) >= max(C)
Owen Anderson5defacc2009-07-31 17:39:07 +00006197 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006198 if (Op1Min == Op0Max) // A <s B -> A != B if max(A) == min(B)
Owen Anderson333c4002009-07-09 23:48:35 +00006199 return new ICmpInst(*Context, ICmpInst::ICMP_NE, Op0, Op1);
Dan Gohman1c8491e2009-04-25 17:12:48 +00006200 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6201 if (Op1Max == Op0Min+1) // A <s C -> A == C-1 if min(A)+1 == C
Owen Anderson333c4002009-07-09 23:48:35 +00006202 return new ICmpInst(*Context, ICmpInst::ICMP_EQ, Op0,
Dan Gohman186a6362009-08-12 16:04:34 +00006203 SubOne(CI));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006204 }
Chris Lattner84dff672008-07-11 05:08:55 +00006205 break;
Dan Gohman1c8491e2009-04-25 17:12:48 +00006206 case ICmpInst::ICMP_SGT:
6207 if (Op0Min.sgt(Op1Max)) // A >s B -> true if min(A) > max(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006208 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006209 if (Op0Max.sle(Op1Min)) // A >s B -> false if max(A) <= min(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006210 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006211
6212 if (Op1Max == Op0Min) // A >s B -> A != B if min(A) == max(B)
Owen Anderson333c4002009-07-09 23:48:35 +00006213 return new ICmpInst(*Context, ICmpInst::ICMP_NE, Op0, Op1);
Dan Gohman1c8491e2009-04-25 17:12:48 +00006214 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6215 if (Op1Min == Op0Max-1) // A >s C -> A == C+1 if max(A)-1 == C
Owen Anderson333c4002009-07-09 23:48:35 +00006216 return new ICmpInst(*Context, ICmpInst::ICMP_EQ, Op0,
Dan Gohman186a6362009-08-12 16:04:34 +00006217 AddOne(CI));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006218 }
6219 break;
6220 case ICmpInst::ICMP_SGE:
6221 assert(!isa<ConstantInt>(Op1) && "ICMP_SGE with ConstantInt not folded!");
6222 if (Op0Min.sge(Op1Max)) // A >=s B -> true if min(A) >= max(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006223 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006224 if (Op0Max.slt(Op1Min)) // A >=s B -> false if max(A) < min(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006225 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006226 break;
6227 case ICmpInst::ICMP_SLE:
6228 assert(!isa<ConstantInt>(Op1) && "ICMP_SLE with ConstantInt not folded!");
6229 if (Op0Max.sle(Op1Min)) // A <=s B -> true if max(A) <= min(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006230 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006231 if (Op0Min.sgt(Op1Max)) // A <=s B -> false if min(A) > max(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006232 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006233 break;
6234 case ICmpInst::ICMP_UGE:
6235 assert(!isa<ConstantInt>(Op1) && "ICMP_UGE with ConstantInt not folded!");
6236 if (Op0Min.uge(Op1Max)) // A >=u B -> true if min(A) >= max(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006237 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006238 if (Op0Max.ult(Op1Min)) // A >=u B -> false if max(A) < min(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006239 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006240 break;
6241 case ICmpInst::ICMP_ULE:
6242 assert(!isa<ConstantInt>(Op1) && "ICMP_ULE with ConstantInt not folded!");
6243 if (Op0Max.ule(Op1Min)) // A <=u B -> true if max(A) <= min(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006244 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006245 if (Op0Min.ugt(Op1Max)) // A <=u B -> false if min(A) > max(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006246 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattner84dff672008-07-11 05:08:55 +00006247 break;
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00006248 }
Dan Gohman1c8491e2009-04-25 17:12:48 +00006249
6250 // Turn a signed comparison into an unsigned one if both operands
6251 // are known to have the same sign.
6252 if (I.isSignedPredicate() &&
6253 ((Op0KnownZero.isNegative() && Op1KnownZero.isNegative()) ||
6254 (Op0KnownOne.isNegative() && Op1KnownOne.isNegative())))
Owen Anderson333c4002009-07-09 23:48:35 +00006255 return new ICmpInst(*Context, I.getUnsignedPredicate(), Op0, Op1);
Dan Gohman81b28ce2008-09-16 18:46:06 +00006256 }
6257
6258 // Test if the ICmpInst instruction is used exclusively by a select as
6259 // part of a minimum or maximum operation. If so, refrain from doing
6260 // any other folding. This helps out other analyses which understand
6261 // non-obfuscated minimum and maximum idioms, such as ScalarEvolution
6262 // and CodeGen. And in this case, at least one of the comparison
6263 // operands has at least one user besides the compare (the select),
6264 // which would often largely negate the benefit of folding anyway.
6265 if (I.hasOneUse())
6266 if (SelectInst *SI = dyn_cast<SelectInst>(*I.use_begin()))
6267 if ((SI->getOperand(1) == Op0 && SI->getOperand(2) == Op1) ||
6268 (SI->getOperand(2) == Op0 && SI->getOperand(1) == Op1))
6269 return 0;
6270
6271 // See if we are doing a comparison between a constant and an instruction that
6272 // can be folded into the comparison.
6273 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00006274 // Since the RHS is a ConstantInt (CI), if the left hand side is an
Reid Spencer1628cec2006-10-26 06:15:43 +00006275 // instruction, see if that instruction also has constants so that the
Reid Spencere4d87aa2006-12-23 06:05:41 +00006276 // instruction can be folded into the icmp
Chris Lattner3c6a0d42004-05-25 06:32:08 +00006277 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
Chris Lattner01deb9d2007-04-03 17:43:25 +00006278 if (Instruction *Res = visitICmpInstWithInstAndIntCst(I, LHSI, CI))
6279 return Res;
Chris Lattner3f5b8772002-05-06 16:14:14 +00006280 }
6281
Chris Lattner01deb9d2007-04-03 17:43:25 +00006282 // Handle icmp with constant (but not simple integer constant) RHS
Chris Lattner6970b662005-04-23 15:31:55 +00006283 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
6284 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
6285 switch (LHSI->getOpcode()) {
Chris Lattner9fb25db2005-05-01 04:42:15 +00006286 case Instruction::GetElementPtr:
6287 if (RHSC->isNullValue()) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00006288 // icmp pred GEP (P, int 0, int 0, int 0), null -> icmp pred P, null
Chris Lattner9fb25db2005-05-01 04:42:15 +00006289 bool isAllZeros = true;
6290 for (unsigned i = 1, e = LHSI->getNumOperands(); i != e; ++i)
6291 if (!isa<Constant>(LHSI->getOperand(i)) ||
6292 !cast<Constant>(LHSI->getOperand(i))->isNullValue()) {
6293 isAllZeros = false;
6294 break;
6295 }
6296 if (isAllZeros)
Owen Anderson333c4002009-07-09 23:48:35 +00006297 return new ICmpInst(*Context, I.getPredicate(), LHSI->getOperand(0),
Owen Andersona7235ea2009-07-31 20:28:14 +00006298 Constant::getNullValue(LHSI->getOperand(0)->getType()));
Chris Lattner9fb25db2005-05-01 04:42:15 +00006299 }
6300 break;
6301
Chris Lattner6970b662005-04-23 15:31:55 +00006302 case Instruction::PHI:
Chris Lattner7d8ab4e2008-06-08 20:52:11 +00006303 // Only fold icmp into the PHI if the phi and fcmp are in the same
6304 // block. If in the same block, we're encouraging jump threading. If
6305 // not, we are just pessimizing the code by making an i1 phi.
6306 if (LHSI->getParent() == I.getParent())
6307 if (Instruction *NV = FoldOpIntoPhi(I))
6308 return NV;
Chris Lattner6970b662005-04-23 15:31:55 +00006309 break;
Chris Lattner4802d902007-04-06 18:57:34 +00006310 case Instruction::Select: {
Chris Lattner6970b662005-04-23 15:31:55 +00006311 // If either operand of the select is a constant, we can fold the
6312 // comparison into the select arms, which will cause one to be
6313 // constant folded and the select turned into a bitwise or.
6314 Value *Op1 = 0, *Op2 = 0;
6315 if (LHSI->hasOneUse()) {
6316 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
6317 // Fold the known value into the constant operand.
Owen Andersonbaf3c402009-07-29 18:55:55 +00006318 Op1 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
Reid Spencere4d87aa2006-12-23 06:05:41 +00006319 // Insert a new ICmp of the other select operand.
Owen Anderson333c4002009-07-09 23:48:35 +00006320 Op2 = InsertNewInstBefore(new ICmpInst(*Context, I.getPredicate(),
Reid Spencere4d87aa2006-12-23 06:05:41 +00006321 LHSI->getOperand(2), RHSC,
6322 I.getName()), I);
Chris Lattner6970b662005-04-23 15:31:55 +00006323 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
6324 // Fold the known value into the constant operand.
Owen Andersonbaf3c402009-07-29 18:55:55 +00006325 Op2 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
Reid Spencere4d87aa2006-12-23 06:05:41 +00006326 // Insert a new ICmp of the other select operand.
Owen Anderson333c4002009-07-09 23:48:35 +00006327 Op1 = InsertNewInstBefore(new ICmpInst(*Context, I.getPredicate(),
Reid Spencere4d87aa2006-12-23 06:05:41 +00006328 LHSI->getOperand(1), RHSC,
6329 I.getName()), I);
Chris Lattner6970b662005-04-23 15:31:55 +00006330 }
6331 }
Jeff Cohen9d809302005-04-23 21:38:35 +00006332
Chris Lattner6970b662005-04-23 15:31:55 +00006333 if (Op1)
Gabor Greif051a9502008-04-06 20:25:17 +00006334 return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
Chris Lattner6970b662005-04-23 15:31:55 +00006335 break;
6336 }
Chris Lattner4802d902007-04-06 18:57:34 +00006337 case Instruction::Malloc:
6338 // If we have (malloc != null), and if the malloc has a single use, we
6339 // can assume it is successful and remove the malloc.
6340 if (LHSI->hasOneUse() && isa<ConstantPointerNull>(RHSC)) {
6341 AddToWorkList(LHSI);
Owen Andersoneed707b2009-07-24 23:12:02 +00006342 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
Nick Lewyckyfc1efbb2008-05-17 07:33:39 +00006343 !I.isTrueWhenEqual()));
Chris Lattner4802d902007-04-06 18:57:34 +00006344 }
6345 break;
6346 }
Chris Lattner6970b662005-04-23 15:31:55 +00006347 }
6348
Reid Spencere4d87aa2006-12-23 06:05:41 +00006349 // If we can optimize a 'icmp GEP, P' or 'icmp P, GEP', do so now.
Dan Gohmand6aa02d2009-07-28 01:40:03 +00006350 if (GEPOperator *GEP = dyn_cast<GEPOperator>(Op0))
Reid Spencere4d87aa2006-12-23 06:05:41 +00006351 if (Instruction *NI = FoldGEPICmp(GEP, Op1, I.getPredicate(), I))
Chris Lattner574da9b2005-01-13 20:14:25 +00006352 return NI;
Dan Gohmand6aa02d2009-07-28 01:40:03 +00006353 if (GEPOperator *GEP = dyn_cast<GEPOperator>(Op1))
Reid Spencere4d87aa2006-12-23 06:05:41 +00006354 if (Instruction *NI = FoldGEPICmp(GEP, Op0,
6355 ICmpInst::getSwappedPredicate(I.getPredicate()), I))
Chris Lattner574da9b2005-01-13 20:14:25 +00006356 return NI;
6357
Reid Spencere4d87aa2006-12-23 06:05:41 +00006358 // Test to see if the operands of the icmp are casted versions of other
Chris Lattner57d86372007-01-06 01:45:59 +00006359 // values. If the ptr->ptr cast can be stripped off both arguments, we do so
6360 // now.
6361 if (BitCastInst *CI = dyn_cast<BitCastInst>(Op0)) {
6362 if (isa<PointerType>(Op0->getType()) &&
6363 (isa<Constant>(Op1) || isa<BitCastInst>(Op1))) {
Chris Lattnerde90b762003-11-03 04:25:02 +00006364 // We keep moving the cast from the left operand over to the right
6365 // operand, where it can often be eliminated completely.
Chris Lattner57d86372007-01-06 01:45:59 +00006366 Op0 = CI->getOperand(0);
Misha Brukmanfd939082005-04-21 23:48:37 +00006367
Chris Lattner57d86372007-01-06 01:45:59 +00006368 // If operand #1 is a bitcast instruction, it must also be a ptr->ptr cast
6369 // so eliminate it as well.
6370 if (BitCastInst *CI2 = dyn_cast<BitCastInst>(Op1))
6371 Op1 = CI2->getOperand(0);
Misha Brukmanfd939082005-04-21 23:48:37 +00006372
Chris Lattnerde90b762003-11-03 04:25:02 +00006373 // If Op1 is a constant, we can fold the cast into the constant.
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00006374 if (Op0->getType() != Op1->getType()) {
Chris Lattnerde90b762003-11-03 04:25:02 +00006375 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00006376 Op1 = ConstantExpr::getBitCast(Op1C, Op0->getType());
Chris Lattnerde90b762003-11-03 04:25:02 +00006377 } else {
Reid Spencere4d87aa2006-12-23 06:05:41 +00006378 // Otherwise, cast the RHS right before the icmp
Chris Lattner6d0339d2008-01-13 22:23:22 +00006379 Op1 = InsertBitCastBefore(Op1, Op0->getType(), I);
Chris Lattnerde90b762003-11-03 04:25:02 +00006380 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00006381 }
Owen Anderson333c4002009-07-09 23:48:35 +00006382 return new ICmpInst(*Context, I.getPredicate(), Op0, Op1);
Chris Lattnerde90b762003-11-03 04:25:02 +00006383 }
Chris Lattner57d86372007-01-06 01:45:59 +00006384 }
6385
6386 if (isa<CastInst>(Op0)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00006387 // Handle the special case of: icmp (cast bool to X), <cst>
Chris Lattner68708052003-11-03 05:17:03 +00006388 // This comes up when you have code like
6389 // int X = A < B;
6390 // if (X) ...
6391 // For generality, we handle any zero-extension of any operand comparison
Chris Lattner484d3cf2005-04-24 06:59:08 +00006392 // with a constant or another cast from the same type.
6393 if (isa<ConstantInt>(Op1) || isa<CastInst>(Op1))
Reid Spencere4d87aa2006-12-23 06:05:41 +00006394 if (Instruction *R = visitICmpInstWithCastAndCast(I))
Chris Lattner484d3cf2005-04-24 06:59:08 +00006395 return R;
Chris Lattner68708052003-11-03 05:17:03 +00006396 }
Chris Lattner26ab9a92006-02-27 01:44:11 +00006397
Nick Lewycky4bf1e592008-07-11 07:20:53 +00006398 // See if it's the same type of instruction on the left and right.
6399 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
6400 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
Nick Lewycky5d52c452008-08-21 05:56:10 +00006401 if (Op0I->getOpcode() == Op1I->getOpcode() && Op0I->hasOneUse() &&
Nick Lewycky4333f492009-01-31 21:30:05 +00006402 Op1I->hasOneUse() && Op0I->getOperand(1) == Op1I->getOperand(1)) {
Nick Lewycky23c04302008-09-03 06:24:21 +00006403 switch (Op0I->getOpcode()) {
Nick Lewycky4bf1e592008-07-11 07:20:53 +00006404 default: break;
6405 case Instruction::Add:
6406 case Instruction::Sub:
6407 case Instruction::Xor:
Chris Lattnerf5db1fb2009-02-02 07:15:30 +00006408 if (I.isEquality()) // a+x icmp eq/ne b+x --> a icmp b
Owen Anderson333c4002009-07-09 23:48:35 +00006409 return new ICmpInst(*Context, I.getPredicate(), Op0I->getOperand(0),
Nick Lewycky4333f492009-01-31 21:30:05 +00006410 Op1I->getOperand(0));
Chris Lattnerf5db1fb2009-02-02 07:15:30 +00006411 // icmp u/s (a ^ signbit), (b ^ signbit) --> icmp s/u a, b
6412 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
6413 if (CI->getValue().isSignBit()) {
6414 ICmpInst::Predicate Pred = I.isSignedPredicate()
6415 ? I.getUnsignedPredicate()
6416 : I.getSignedPredicate();
Owen Anderson333c4002009-07-09 23:48:35 +00006417 return new ICmpInst(*Context, Pred, Op0I->getOperand(0),
Chris Lattnerf5db1fb2009-02-02 07:15:30 +00006418 Op1I->getOperand(0));
6419 }
6420
6421 if (CI->getValue().isMaxSignedValue()) {
6422 ICmpInst::Predicate Pred = I.isSignedPredicate()
6423 ? I.getUnsignedPredicate()
6424 : I.getSignedPredicate();
6425 Pred = I.getSwappedPredicate(Pred);
Owen Anderson333c4002009-07-09 23:48:35 +00006426 return new ICmpInst(*Context, Pred, Op0I->getOperand(0),
Chris Lattnerf5db1fb2009-02-02 07:15:30 +00006427 Op1I->getOperand(0));
Nick Lewycky4333f492009-01-31 21:30:05 +00006428 }
6429 }
Nick Lewycky4bf1e592008-07-11 07:20:53 +00006430 break;
6431 case Instruction::Mul:
Nick Lewycky4333f492009-01-31 21:30:05 +00006432 if (!I.isEquality())
6433 break;
6434
Nick Lewycky5d52c452008-08-21 05:56:10 +00006435 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
6436 // a * Cst icmp eq/ne b * Cst --> a & Mask icmp b & Mask
6437 // Mask = -1 >> count-trailing-zeros(Cst).
6438 if (!CI->isZero() && !CI->isOne()) {
6439 const APInt &AP = CI->getValue();
Owen Andersoneed707b2009-07-24 23:12:02 +00006440 ConstantInt *Mask = ConstantInt::get(*Context,
Nick Lewycky5d52c452008-08-21 05:56:10 +00006441 APInt::getLowBitsSet(AP.getBitWidth(),
6442 AP.getBitWidth() -
Nick Lewycky4bf1e592008-07-11 07:20:53 +00006443 AP.countTrailingZeros()));
Nick Lewycky5d52c452008-08-21 05:56:10 +00006444 Instruction *And1 = BinaryOperator::CreateAnd(Op0I->getOperand(0),
6445 Mask);
6446 Instruction *And2 = BinaryOperator::CreateAnd(Op1I->getOperand(0),
6447 Mask);
6448 InsertNewInstBefore(And1, I);
6449 InsertNewInstBefore(And2, I);
Owen Anderson333c4002009-07-09 23:48:35 +00006450 return new ICmpInst(*Context, I.getPredicate(), And1, And2);
Nick Lewycky4bf1e592008-07-11 07:20:53 +00006451 }
6452 }
6453 break;
6454 }
6455 }
6456 }
6457 }
6458
Chris Lattner7d2cbd22008-05-09 05:19:28 +00006459 // ~x < ~y --> y < x
6460 { Value *A, *B;
Owen Andersonc7d2ce72009-07-10 17:35:01 +00006461 if (match(Op0, m_Not(m_Value(A)), *Context) &&
6462 match(Op1, m_Not(m_Value(B)), *Context))
Owen Anderson333c4002009-07-09 23:48:35 +00006463 return new ICmpInst(*Context, I.getPredicate(), B, A);
Chris Lattner7d2cbd22008-05-09 05:19:28 +00006464 }
6465
Chris Lattner65b72ba2006-09-18 04:22:48 +00006466 if (I.isEquality()) {
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006467 Value *A, *B, *C, *D;
Chris Lattner7d2cbd22008-05-09 05:19:28 +00006468
6469 // -x == -y --> x == y
Owen Andersonc7d2ce72009-07-10 17:35:01 +00006470 if (match(Op0, m_Neg(m_Value(A)), *Context) &&
6471 match(Op1, m_Neg(m_Value(B)), *Context))
Owen Anderson333c4002009-07-09 23:48:35 +00006472 return new ICmpInst(*Context, I.getPredicate(), A, B);
Chris Lattner7d2cbd22008-05-09 05:19:28 +00006473
Owen Andersonc7d2ce72009-07-10 17:35:01 +00006474 if (match(Op0, m_Xor(m_Value(A), m_Value(B)), *Context)) {
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006475 if (A == Op1 || B == Op1) { // (A^B) == A -> B == 0
6476 Value *OtherVal = A == Op1 ? B : A;
Owen Anderson333c4002009-07-09 23:48:35 +00006477 return new ICmpInst(*Context, I.getPredicate(), OtherVal,
Owen Andersona7235ea2009-07-31 20:28:14 +00006478 Constant::getNullValue(A->getType()));
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006479 }
6480
Owen Andersonc7d2ce72009-07-10 17:35:01 +00006481 if (match(Op1, m_Xor(m_Value(C), m_Value(D)), *Context)) {
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006482 // A^c1 == C^c2 --> A == C^(c1^c2)
Chris Lattnercb504b92008-11-16 05:38:51 +00006483 ConstantInt *C1, *C2;
Owen Andersonc7d2ce72009-07-10 17:35:01 +00006484 if (match(B, m_ConstantInt(C1), *Context) &&
6485 match(D, m_ConstantInt(C2), *Context) && Op1->hasOneUse()) {
Owen Andersond672ecb2009-07-03 00:17:18 +00006486 Constant *NC =
Owen Andersoneed707b2009-07-24 23:12:02 +00006487 ConstantInt::get(*Context, C1->getValue() ^ C2->getValue());
Chris Lattnercb504b92008-11-16 05:38:51 +00006488 Instruction *Xor = BinaryOperator::CreateXor(C, NC, "tmp");
Owen Anderson333c4002009-07-09 23:48:35 +00006489 return new ICmpInst(*Context, I.getPredicate(), A,
Chris Lattnercb504b92008-11-16 05:38:51 +00006490 InsertNewInstBefore(Xor, I));
6491 }
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006492
6493 // A^B == A^D -> B == D
Owen Anderson333c4002009-07-09 23:48:35 +00006494 if (A == C) return new ICmpInst(*Context, I.getPredicate(), B, D);
6495 if (A == D) return new ICmpInst(*Context, I.getPredicate(), B, C);
6496 if (B == C) return new ICmpInst(*Context, I.getPredicate(), A, D);
6497 if (B == D) return new ICmpInst(*Context, I.getPredicate(), A, C);
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006498 }
6499 }
6500
Owen Andersonc7d2ce72009-07-10 17:35:01 +00006501 if (match(Op1, m_Xor(m_Value(A), m_Value(B)), *Context) &&
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006502 (A == Op0 || B == Op0)) {
Chris Lattner26ab9a92006-02-27 01:44:11 +00006503 // A == (A^B) -> B == 0
6504 Value *OtherVal = A == Op0 ? B : A;
Owen Anderson333c4002009-07-09 23:48:35 +00006505 return new ICmpInst(*Context, I.getPredicate(), OtherVal,
Owen Andersona7235ea2009-07-31 20:28:14 +00006506 Constant::getNullValue(A->getType()));
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006507 }
Chris Lattnercb504b92008-11-16 05:38:51 +00006508
6509 // (A-B) == A -> B == 0
Owen Andersonc7d2ce72009-07-10 17:35:01 +00006510 if (match(Op0, m_Sub(m_Specific(Op1), m_Value(B)), *Context))
Owen Anderson333c4002009-07-09 23:48:35 +00006511 return new ICmpInst(*Context, I.getPredicate(), B,
Owen Andersona7235ea2009-07-31 20:28:14 +00006512 Constant::getNullValue(B->getType()));
Chris Lattnercb504b92008-11-16 05:38:51 +00006513
6514 // A == (A-B) -> B == 0
Owen Andersonc7d2ce72009-07-10 17:35:01 +00006515 if (match(Op1, m_Sub(m_Specific(Op0), m_Value(B)), *Context))
Owen Anderson333c4002009-07-09 23:48:35 +00006516 return new ICmpInst(*Context, I.getPredicate(), B,
Owen Andersona7235ea2009-07-31 20:28:14 +00006517 Constant::getNullValue(B->getType()));
Chris Lattner9c2328e2006-11-14 06:06:06 +00006518
Chris Lattner9c2328e2006-11-14 06:06:06 +00006519 // (X&Z) == (Y&Z) -> (X^Y) & Z == 0
6520 if (Op0->hasOneUse() && Op1->hasOneUse() &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00006521 match(Op0, m_And(m_Value(A), m_Value(B)), *Context) &&
6522 match(Op1, m_And(m_Value(C), m_Value(D)), *Context)) {
Chris Lattner9c2328e2006-11-14 06:06:06 +00006523 Value *X = 0, *Y = 0, *Z = 0;
6524
6525 if (A == C) {
6526 X = B; Y = D; Z = A;
6527 } else if (A == D) {
6528 X = B; Y = C; Z = A;
6529 } else if (B == C) {
6530 X = A; Y = D; Z = B;
6531 } else if (B == D) {
6532 X = A; Y = C; Z = B;
6533 }
6534
6535 if (X) { // Build (X^Y) & Z
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006536 Op1 = InsertNewInstBefore(BinaryOperator::CreateXor(X, Y, "tmp"), I);
6537 Op1 = InsertNewInstBefore(BinaryOperator::CreateAnd(Op1, Z, "tmp"), I);
Chris Lattner9c2328e2006-11-14 06:06:06 +00006538 I.setOperand(0, Op1);
Owen Andersona7235ea2009-07-31 20:28:14 +00006539 I.setOperand(1, Constant::getNullValue(Op1->getType()));
Chris Lattner9c2328e2006-11-14 06:06:06 +00006540 return &I;
6541 }
6542 }
Chris Lattner26ab9a92006-02-27 01:44:11 +00006543 }
Chris Lattner7e708292002-06-25 16:13:24 +00006544 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00006545}
6546
Chris Lattner562ef782007-06-20 23:46:26 +00006547
6548/// FoldICmpDivCst - Fold "icmp pred, ([su]div X, DivRHS), CmpRHS" where DivRHS
6549/// and CmpRHS are both known to be integer constants.
6550Instruction *InstCombiner::FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
6551 ConstantInt *DivRHS) {
6552 ConstantInt *CmpRHS = cast<ConstantInt>(ICI.getOperand(1));
6553 const APInt &CmpRHSV = CmpRHS->getValue();
6554
6555 // FIXME: If the operand types don't match the type of the divide
6556 // then don't attempt this transform. The code below doesn't have the
6557 // logic to deal with a signed divide and an unsigned compare (and
6558 // vice versa). This is because (x /s C1) <s C2 produces different
6559 // results than (x /s C1) <u C2 or (x /u C1) <s C2 or even
6560 // (x /u C1) <u C2. Simply casting the operands and result won't
6561 // work. :( The if statement below tests that condition and bails
6562 // if it finds it.
6563 bool DivIsSigned = DivI->getOpcode() == Instruction::SDiv;
6564 if (!ICI.isEquality() && DivIsSigned != ICI.isSignedPredicate())
6565 return 0;
6566 if (DivRHS->isZero())
Chris Lattner1dbfd482007-06-21 18:11:19 +00006567 return 0; // The ProdOV computation fails on divide by zero.
Chris Lattnera6321b42008-10-11 22:55:00 +00006568 if (DivIsSigned && DivRHS->isAllOnesValue())
6569 return 0; // The overflow computation also screws up here
6570 if (DivRHS->isOne())
6571 return 0; // Not worth bothering, and eliminates some funny cases
6572 // with INT_MIN.
Chris Lattner562ef782007-06-20 23:46:26 +00006573
6574 // Compute Prod = CI * DivRHS. We are essentially solving an equation
6575 // of form X/C1=C2. We solve for X by multiplying C1 (DivRHS) and
6576 // C2 (CI). By solving for X we can turn this into a range check
6577 // instead of computing a divide.
Owen Andersonbaf3c402009-07-29 18:55:55 +00006578 Constant *Prod = ConstantExpr::getMul(CmpRHS, DivRHS);
Chris Lattner562ef782007-06-20 23:46:26 +00006579
6580 // Determine if the product overflows by seeing if the product is
6581 // not equal to the divide. Make sure we do the same kind of divide
6582 // as in the LHS instruction that we're folding.
Owen Andersonbaf3c402009-07-29 18:55:55 +00006583 bool ProdOV = (DivIsSigned ? ConstantExpr::getSDiv(Prod, DivRHS) :
6584 ConstantExpr::getUDiv(Prod, DivRHS)) != CmpRHS;
Chris Lattner562ef782007-06-20 23:46:26 +00006585
6586 // Get the ICmp opcode
Chris Lattner1dbfd482007-06-21 18:11:19 +00006587 ICmpInst::Predicate Pred = ICI.getPredicate();
Chris Lattner562ef782007-06-20 23:46:26 +00006588
Chris Lattner1dbfd482007-06-21 18:11:19 +00006589 // Figure out the interval that is being checked. For example, a comparison
6590 // like "X /u 5 == 0" is really checking that X is in the interval [0, 5).
6591 // Compute this interval based on the constants involved and the signedness of
6592 // the compare/divide. This computes a half-open interval, keeping track of
6593 // whether either value in the interval overflows. After analysis each
6594 // overflow variable is set to 0 if it's corresponding bound variable is valid
6595 // -1 if overflowed off the bottom end, or +1 if overflowed off the top end.
6596 int LoOverflow = 0, HiOverflow = 0;
Dan Gohman6de29f82009-06-15 22:12:54 +00006597 Constant *LoBound = 0, *HiBound = 0;
Chris Lattner1dbfd482007-06-21 18:11:19 +00006598
Chris Lattner562ef782007-06-20 23:46:26 +00006599 if (!DivIsSigned) { // udiv
Chris Lattner1dbfd482007-06-21 18:11:19 +00006600 // e.g. X/5 op 3 --> [15, 20)
Chris Lattner562ef782007-06-20 23:46:26 +00006601 LoBound = Prod;
Chris Lattner1dbfd482007-06-21 18:11:19 +00006602 HiOverflow = LoOverflow = ProdOV;
6603 if (!HiOverflow)
Owen Andersond672ecb2009-07-03 00:17:18 +00006604 HiOverflow = AddWithOverflow(HiBound, LoBound, DivRHS, Context, false);
Dan Gohman76491272008-02-13 22:09:18 +00006605 } else if (DivRHS->getValue().isStrictlyPositive()) { // Divisor is > 0.
Chris Lattner562ef782007-06-20 23:46:26 +00006606 if (CmpRHSV == 0) { // (X / pos) op 0
Chris Lattner1dbfd482007-06-21 18:11:19 +00006607 // Can't overflow. e.g. X/2 op 0 --> [-1, 2)
Dan Gohman186a6362009-08-12 16:04:34 +00006608 LoBound = cast<ConstantInt>(ConstantExpr::getNeg(SubOne(DivRHS)));
Chris Lattner562ef782007-06-20 23:46:26 +00006609 HiBound = DivRHS;
Dan Gohman76491272008-02-13 22:09:18 +00006610 } else if (CmpRHSV.isStrictlyPositive()) { // (X / pos) op pos
Chris Lattner1dbfd482007-06-21 18:11:19 +00006611 LoBound = Prod; // e.g. X/5 op 3 --> [15, 20)
6612 HiOverflow = LoOverflow = ProdOV;
6613 if (!HiOverflow)
Owen Andersond672ecb2009-07-03 00:17:18 +00006614 HiOverflow = AddWithOverflow(HiBound, Prod, DivRHS, Context, true);
Chris Lattner562ef782007-06-20 23:46:26 +00006615 } else { // (X / pos) op neg
Chris Lattner1dbfd482007-06-21 18:11:19 +00006616 // e.g. X/5 op -3 --> [-15-4, -15+1) --> [-19, -14)
Dan Gohman186a6362009-08-12 16:04:34 +00006617 HiBound = AddOne(Prod);
Chris Lattnera6321b42008-10-11 22:55:00 +00006618 LoOverflow = HiOverflow = ProdOV ? -1 : 0;
6619 if (!LoOverflow) {
Owen Andersond672ecb2009-07-03 00:17:18 +00006620 ConstantInt* DivNeg =
Owen Andersonbaf3c402009-07-29 18:55:55 +00006621 cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
Owen Andersond672ecb2009-07-03 00:17:18 +00006622 LoOverflow = AddWithOverflow(LoBound, HiBound, DivNeg, Context,
Chris Lattnera6321b42008-10-11 22:55:00 +00006623 true) ? -1 : 0;
6624 }
Chris Lattner562ef782007-06-20 23:46:26 +00006625 }
Dan Gohman76491272008-02-13 22:09:18 +00006626 } else if (DivRHS->getValue().isNegative()) { // Divisor is < 0.
Chris Lattner562ef782007-06-20 23:46:26 +00006627 if (CmpRHSV == 0) { // (X / neg) op 0
Chris Lattner1dbfd482007-06-21 18:11:19 +00006628 // e.g. X/-5 op 0 --> [-4, 5)
Dan Gohman186a6362009-08-12 16:04:34 +00006629 LoBound = AddOne(DivRHS);
Owen Andersonbaf3c402009-07-29 18:55:55 +00006630 HiBound = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
Chris Lattner1dbfd482007-06-21 18:11:19 +00006631 if (HiBound == DivRHS) { // -INTMIN = INTMIN
6632 HiOverflow = 1; // [INTMIN+1, overflow)
6633 HiBound = 0; // e.g. X/INTMIN = 0 --> X > INTMIN
6634 }
Dan Gohman76491272008-02-13 22:09:18 +00006635 } else if (CmpRHSV.isStrictlyPositive()) { // (X / neg) op pos
Chris Lattner1dbfd482007-06-21 18:11:19 +00006636 // e.g. X/-5 op 3 --> [-19, -14)
Dan Gohman186a6362009-08-12 16:04:34 +00006637 HiBound = AddOne(Prod);
Chris Lattner1dbfd482007-06-21 18:11:19 +00006638 HiOverflow = LoOverflow = ProdOV ? -1 : 0;
Chris Lattner562ef782007-06-20 23:46:26 +00006639 if (!LoOverflow)
Owen Andersond672ecb2009-07-03 00:17:18 +00006640 LoOverflow = AddWithOverflow(LoBound, HiBound,
6641 DivRHS, Context, true) ? -1 : 0;
Chris Lattner562ef782007-06-20 23:46:26 +00006642 } else { // (X / neg) op neg
Chris Lattnera6321b42008-10-11 22:55:00 +00006643 LoBound = Prod; // e.g. X/-5 op -3 --> [15, 20)
6644 LoOverflow = HiOverflow = ProdOV;
Dan Gohman7f85fbd2008-09-11 00:25:00 +00006645 if (!HiOverflow)
Owen Andersond672ecb2009-07-03 00:17:18 +00006646 HiOverflow = SubWithOverflow(HiBound, Prod, DivRHS, Context, true);
Chris Lattner562ef782007-06-20 23:46:26 +00006647 }
6648
Chris Lattner1dbfd482007-06-21 18:11:19 +00006649 // Dividing by a negative swaps the condition. LT <-> GT
6650 Pred = ICmpInst::getSwappedPredicate(Pred);
Chris Lattner562ef782007-06-20 23:46:26 +00006651 }
6652
6653 Value *X = DivI->getOperand(0);
Chris Lattner1dbfd482007-06-21 18:11:19 +00006654 switch (Pred) {
Torok Edwinc23197a2009-07-14 16:55:14 +00006655 default: llvm_unreachable("Unhandled icmp opcode!");
Chris Lattner562ef782007-06-20 23:46:26 +00006656 case ICmpInst::ICMP_EQ:
6657 if (LoOverflow && HiOverflow)
Owen Anderson5defacc2009-07-31 17:39:07 +00006658 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
Chris Lattner562ef782007-06-20 23:46:26 +00006659 else if (HiOverflow)
Owen Anderson333c4002009-07-09 23:48:35 +00006660 return new ICmpInst(*Context, DivIsSigned ? ICmpInst::ICMP_SGE :
Chris Lattner562ef782007-06-20 23:46:26 +00006661 ICmpInst::ICMP_UGE, X, LoBound);
6662 else if (LoOverflow)
Owen Anderson333c4002009-07-09 23:48:35 +00006663 return new ICmpInst(*Context, DivIsSigned ? ICmpInst::ICMP_SLT :
Chris Lattner562ef782007-06-20 23:46:26 +00006664 ICmpInst::ICMP_ULT, X, HiBound);
6665 else
Chris Lattner1dbfd482007-06-21 18:11:19 +00006666 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, true, ICI);
Chris Lattner562ef782007-06-20 23:46:26 +00006667 case ICmpInst::ICMP_NE:
6668 if (LoOverflow && HiOverflow)
Owen Anderson5defacc2009-07-31 17:39:07 +00006669 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
Chris Lattner562ef782007-06-20 23:46:26 +00006670 else if (HiOverflow)
Owen Anderson333c4002009-07-09 23:48:35 +00006671 return new ICmpInst(*Context, DivIsSigned ? ICmpInst::ICMP_SLT :
Chris Lattner562ef782007-06-20 23:46:26 +00006672 ICmpInst::ICMP_ULT, X, LoBound);
6673 else if (LoOverflow)
Owen Anderson333c4002009-07-09 23:48:35 +00006674 return new ICmpInst(*Context, DivIsSigned ? ICmpInst::ICMP_SGE :
Chris Lattner562ef782007-06-20 23:46:26 +00006675 ICmpInst::ICMP_UGE, X, HiBound);
6676 else
Chris Lattner1dbfd482007-06-21 18:11:19 +00006677 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, false, ICI);
Chris Lattner562ef782007-06-20 23:46:26 +00006678 case ICmpInst::ICMP_ULT:
6679 case ICmpInst::ICMP_SLT:
Chris Lattner1dbfd482007-06-21 18:11:19 +00006680 if (LoOverflow == +1) // Low bound is greater than input range.
Owen Anderson5defacc2009-07-31 17:39:07 +00006681 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
Chris Lattner1dbfd482007-06-21 18:11:19 +00006682 if (LoOverflow == -1) // Low bound is less than input range.
Owen Anderson5defacc2009-07-31 17:39:07 +00006683 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
Owen Anderson333c4002009-07-09 23:48:35 +00006684 return new ICmpInst(*Context, Pred, X, LoBound);
Chris Lattner562ef782007-06-20 23:46:26 +00006685 case ICmpInst::ICMP_UGT:
6686 case ICmpInst::ICMP_SGT:
Chris Lattner1dbfd482007-06-21 18:11:19 +00006687 if (HiOverflow == +1) // High bound greater than input range.
Owen Anderson5defacc2009-07-31 17:39:07 +00006688 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
Chris Lattner1dbfd482007-06-21 18:11:19 +00006689 else if (HiOverflow == -1) // High bound less than input range.
Owen Anderson5defacc2009-07-31 17:39:07 +00006690 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
Chris Lattner1dbfd482007-06-21 18:11:19 +00006691 if (Pred == ICmpInst::ICMP_UGT)
Owen Anderson333c4002009-07-09 23:48:35 +00006692 return new ICmpInst(*Context, ICmpInst::ICMP_UGE, X, HiBound);
Chris Lattner562ef782007-06-20 23:46:26 +00006693 else
Owen Anderson333c4002009-07-09 23:48:35 +00006694 return new ICmpInst(*Context, ICmpInst::ICMP_SGE, X, HiBound);
Chris Lattner562ef782007-06-20 23:46:26 +00006695 }
6696}
6697
6698
Chris Lattner01deb9d2007-04-03 17:43:25 +00006699/// visitICmpInstWithInstAndIntCst - Handle "icmp (instr, intcst)".
6700///
6701Instruction *InstCombiner::visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
6702 Instruction *LHSI,
6703 ConstantInt *RHS) {
6704 const APInt &RHSV = RHS->getValue();
6705
6706 switch (LHSI->getOpcode()) {
Chris Lattnera80d6682009-01-09 07:47:06 +00006707 case Instruction::Trunc:
6708 if (ICI.isEquality() && LHSI->hasOneUse()) {
6709 // Simplify icmp eq (trunc x to i8), 42 -> icmp eq x, 42|highbits if all
6710 // of the high bits truncated out of x are known.
6711 unsigned DstBits = LHSI->getType()->getPrimitiveSizeInBits(),
6712 SrcBits = LHSI->getOperand(0)->getType()->getPrimitiveSizeInBits();
6713 APInt Mask(APInt::getHighBitsSet(SrcBits, SrcBits-DstBits));
6714 APInt KnownZero(SrcBits, 0), KnownOne(SrcBits, 0);
6715 ComputeMaskedBits(LHSI->getOperand(0), Mask, KnownZero, KnownOne);
6716
6717 // If all the high bits are known, we can do this xform.
6718 if ((KnownZero|KnownOne).countLeadingOnes() >= SrcBits-DstBits) {
6719 // Pull in the high bits from known-ones set.
6720 APInt NewRHS(RHS->getValue());
6721 NewRHS.zext(SrcBits);
6722 NewRHS |= KnownOne;
Owen Anderson333c4002009-07-09 23:48:35 +00006723 return new ICmpInst(*Context, ICI.getPredicate(), LHSI->getOperand(0),
Owen Andersoneed707b2009-07-24 23:12:02 +00006724 ConstantInt::get(*Context, NewRHS));
Chris Lattnera80d6682009-01-09 07:47:06 +00006725 }
6726 }
6727 break;
6728
Duncan Sands0091bf22007-04-04 06:42:45 +00006729 case Instruction::Xor: // (icmp pred (xor X, XorCST), CI)
Chris Lattner01deb9d2007-04-03 17:43:25 +00006730 if (ConstantInt *XorCST = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
6731 // If this is a comparison that tests the signbit (X < 0) or (x > -1),
6732 // fold the xor.
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00006733 if ((ICI.getPredicate() == ICmpInst::ICMP_SLT && RHSV == 0) ||
6734 (ICI.getPredicate() == ICmpInst::ICMP_SGT && RHSV.isAllOnesValue())) {
Chris Lattner01deb9d2007-04-03 17:43:25 +00006735 Value *CompareVal = LHSI->getOperand(0);
6736
6737 // If the sign bit of the XorCST is not set, there is no change to
6738 // the operation, just stop using the Xor.
6739 if (!XorCST->getValue().isNegative()) {
6740 ICI.setOperand(0, CompareVal);
6741 AddToWorkList(LHSI);
6742 return &ICI;
6743 }
6744
6745 // Was the old condition true if the operand is positive?
6746 bool isTrueIfPositive = ICI.getPredicate() == ICmpInst::ICMP_SGT;
6747
6748 // If so, the new one isn't.
6749 isTrueIfPositive ^= true;
6750
6751 if (isTrueIfPositive)
Owen Anderson333c4002009-07-09 23:48:35 +00006752 return new ICmpInst(*Context, ICmpInst::ICMP_SGT, CompareVal,
Dan Gohman186a6362009-08-12 16:04:34 +00006753 SubOne(RHS));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006754 else
Owen Anderson333c4002009-07-09 23:48:35 +00006755 return new ICmpInst(*Context, ICmpInst::ICMP_SLT, CompareVal,
Dan Gohman186a6362009-08-12 16:04:34 +00006756 AddOne(RHS));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006757 }
Nick Lewycky4333f492009-01-31 21:30:05 +00006758
6759 if (LHSI->hasOneUse()) {
6760 // (icmp u/s (xor A SignBit), C) -> (icmp s/u A, (xor C SignBit))
6761 if (!ICI.isEquality() && XorCST->getValue().isSignBit()) {
6762 const APInt &SignBit = XorCST->getValue();
6763 ICmpInst::Predicate Pred = ICI.isSignedPredicate()
6764 ? ICI.getUnsignedPredicate()
6765 : ICI.getSignedPredicate();
Owen Anderson333c4002009-07-09 23:48:35 +00006766 return new ICmpInst(*Context, Pred, LHSI->getOperand(0),
Owen Andersoneed707b2009-07-24 23:12:02 +00006767 ConstantInt::get(*Context, RHSV ^ SignBit));
Nick Lewycky4333f492009-01-31 21:30:05 +00006768 }
6769
6770 // (icmp u/s (xor A ~SignBit), C) -> (icmp s/u (xor C ~SignBit), A)
Chris Lattnerf5db1fb2009-02-02 07:15:30 +00006771 if (!ICI.isEquality() && XorCST->getValue().isMaxSignedValue()) {
Nick Lewycky4333f492009-01-31 21:30:05 +00006772 const APInt &NotSignBit = XorCST->getValue();
6773 ICmpInst::Predicate Pred = ICI.isSignedPredicate()
6774 ? ICI.getUnsignedPredicate()
6775 : ICI.getSignedPredicate();
6776 Pred = ICI.getSwappedPredicate(Pred);
Owen Anderson333c4002009-07-09 23:48:35 +00006777 return new ICmpInst(*Context, Pred, LHSI->getOperand(0),
Owen Andersoneed707b2009-07-24 23:12:02 +00006778 ConstantInt::get(*Context, RHSV ^ NotSignBit));
Nick Lewycky4333f492009-01-31 21:30:05 +00006779 }
6780 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00006781 }
6782 break;
6783 case Instruction::And: // (icmp pred (and X, AndCST), RHS)
6784 if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
6785 LHSI->getOperand(0)->hasOneUse()) {
6786 ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
6787
6788 // If the LHS is an AND of a truncating cast, we can widen the
6789 // and/compare to be the input width without changing the value
6790 // produced, eliminating a cast.
6791 if (TruncInst *Cast = dyn_cast<TruncInst>(LHSI->getOperand(0))) {
6792 // We can do this transformation if either the AND constant does not
6793 // have its sign bit set or if it is an equality comparison.
6794 // Extending a relational comparison when we're checking the sign
6795 // bit would not work.
6796 if (Cast->hasOneUse() &&
Anton Korobeynikov4aefd6b2008-02-20 12:07:57 +00006797 (ICI.isEquality() ||
6798 (AndCST->getValue().isNonNegative() && RHSV.isNonNegative()))) {
Chris Lattner01deb9d2007-04-03 17:43:25 +00006799 uint32_t BitWidth =
6800 cast<IntegerType>(Cast->getOperand(0)->getType())->getBitWidth();
6801 APInt NewCST = AndCST->getValue();
6802 NewCST.zext(BitWidth);
6803 APInt NewCI = RHSV;
6804 NewCI.zext(BitWidth);
6805 Instruction *NewAnd =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006806 BinaryOperator::CreateAnd(Cast->getOperand(0),
Owen Andersoneed707b2009-07-24 23:12:02 +00006807 ConstantInt::get(*Context, NewCST), LHSI->getName());
Chris Lattner01deb9d2007-04-03 17:43:25 +00006808 InsertNewInstBefore(NewAnd, ICI);
Owen Anderson333c4002009-07-09 23:48:35 +00006809 return new ICmpInst(*Context, ICI.getPredicate(), NewAnd,
Owen Andersoneed707b2009-07-24 23:12:02 +00006810 ConstantInt::get(*Context, NewCI));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006811 }
6812 }
6813
6814 // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
6815 // could exist), turn it into (X & (C2 << C1)) != (C3 << C1). This
6816 // happens a LOT in code produced by the C front-end, for bitfield
6817 // access.
6818 BinaryOperator *Shift = dyn_cast<BinaryOperator>(LHSI->getOperand(0));
6819 if (Shift && !Shift->isShift())
6820 Shift = 0;
6821
6822 ConstantInt *ShAmt;
6823 ShAmt = Shift ? dyn_cast<ConstantInt>(Shift->getOperand(1)) : 0;
6824 const Type *Ty = Shift ? Shift->getType() : 0; // Type of the shift.
6825 const Type *AndTy = AndCST->getType(); // Type of the and.
6826
6827 // We can fold this as long as we can't shift unknown bits
6828 // into the mask. This can only happen with signed shift
6829 // rights, as they sign-extend.
6830 if (ShAmt) {
6831 bool CanFold = Shift->isLogicalShift();
6832 if (!CanFold) {
6833 // To test for the bad case of the signed shr, see if any
6834 // of the bits shifted in could be tested after the mask.
6835 uint32_t TyBits = Ty->getPrimitiveSizeInBits();
6836 int ShAmtVal = TyBits - ShAmt->getLimitedValue(TyBits);
6837
6838 uint32_t BitWidth = AndTy->getPrimitiveSizeInBits();
6839 if ((APInt::getHighBitsSet(BitWidth, BitWidth-ShAmtVal) &
6840 AndCST->getValue()) == 0)
6841 CanFold = true;
6842 }
6843
6844 if (CanFold) {
6845 Constant *NewCst;
6846 if (Shift->getOpcode() == Instruction::Shl)
Owen Andersonbaf3c402009-07-29 18:55:55 +00006847 NewCst = ConstantExpr::getLShr(RHS, ShAmt);
Chris Lattner01deb9d2007-04-03 17:43:25 +00006848 else
Owen Andersonbaf3c402009-07-29 18:55:55 +00006849 NewCst = ConstantExpr::getShl(RHS, ShAmt);
Chris Lattner01deb9d2007-04-03 17:43:25 +00006850
6851 // Check to see if we are shifting out any of the bits being
6852 // compared.
Owen Andersonbaf3c402009-07-29 18:55:55 +00006853 if (ConstantExpr::get(Shift->getOpcode(),
Owen Andersond672ecb2009-07-03 00:17:18 +00006854 NewCst, ShAmt) != RHS) {
Chris Lattner01deb9d2007-04-03 17:43:25 +00006855 // If we shifted bits out, the fold is not going to work out.
6856 // As a special case, check to see if this means that the
6857 // result is always true or false now.
6858 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
Owen Anderson5defacc2009-07-31 17:39:07 +00006859 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006860 if (ICI.getPredicate() == ICmpInst::ICMP_NE)
Owen Anderson5defacc2009-07-31 17:39:07 +00006861 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006862 } else {
6863 ICI.setOperand(1, NewCst);
6864 Constant *NewAndCST;
6865 if (Shift->getOpcode() == Instruction::Shl)
Owen Andersonbaf3c402009-07-29 18:55:55 +00006866 NewAndCST = ConstantExpr::getLShr(AndCST, ShAmt);
Chris Lattner01deb9d2007-04-03 17:43:25 +00006867 else
Owen Andersonbaf3c402009-07-29 18:55:55 +00006868 NewAndCST = ConstantExpr::getShl(AndCST, ShAmt);
Chris Lattner01deb9d2007-04-03 17:43:25 +00006869 LHSI->setOperand(1, NewAndCST);
6870 LHSI->setOperand(0, Shift->getOperand(0));
6871 AddToWorkList(Shift); // Shift is dead.
6872 AddUsesToWorkList(ICI);
6873 return &ICI;
6874 }
6875 }
6876 }
6877
6878 // Turn ((X >> Y) & C) == 0 into (X & (C << Y)) == 0. The later is
6879 // preferable because it allows the C<<Y expression to be hoisted out
6880 // of a loop if Y is invariant and X is not.
6881 if (Shift && Shift->hasOneUse() && RHSV == 0 &&
Chris Lattnere8e49212009-03-25 00:28:58 +00006882 ICI.isEquality() && !Shift->isArithmeticShift() &&
6883 !isa<Constant>(Shift->getOperand(0))) {
Chris Lattner01deb9d2007-04-03 17:43:25 +00006884 // Compute C << Y.
6885 Value *NS;
6886 if (Shift->getOpcode() == Instruction::LShr) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006887 NS = BinaryOperator::CreateShl(AndCST,
Chris Lattner01deb9d2007-04-03 17:43:25 +00006888 Shift->getOperand(1), "tmp");
6889 } else {
6890 // Insert a logical shift.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006891 NS = BinaryOperator::CreateLShr(AndCST,
Chris Lattner01deb9d2007-04-03 17:43:25 +00006892 Shift->getOperand(1), "tmp");
6893 }
6894 InsertNewInstBefore(cast<Instruction>(NS), ICI);
6895
6896 // Compute X & (C << Y).
6897 Instruction *NewAnd =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006898 BinaryOperator::CreateAnd(Shift->getOperand(0), NS, LHSI->getName());
Chris Lattner01deb9d2007-04-03 17:43:25 +00006899 InsertNewInstBefore(NewAnd, ICI);
6900
6901 ICI.setOperand(0, NewAnd);
6902 return &ICI;
6903 }
6904 }
6905 break;
6906
Chris Lattnera0141b92007-07-15 20:42:37 +00006907 case Instruction::Shl: { // (icmp pred (shl X, ShAmt), CI)
6908 ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
6909 if (!ShAmt) break;
6910
6911 uint32_t TypeBits = RHSV.getBitWidth();
6912
6913 // Check that the shift amount is in range. If not, don't perform
6914 // undefined shifts. When the shift is visited it will be
6915 // simplified.
6916 if (ShAmt->uge(TypeBits))
6917 break;
6918
6919 if (ICI.isEquality()) {
6920 // If we are comparing against bits always shifted out, the
6921 // comparison cannot succeed.
6922 Constant *Comp =
Owen Andersonbaf3c402009-07-29 18:55:55 +00006923 ConstantExpr::getShl(ConstantExpr::getLShr(RHS, ShAmt),
Owen Andersond672ecb2009-07-03 00:17:18 +00006924 ShAmt);
Chris Lattnera0141b92007-07-15 20:42:37 +00006925 if (Comp != RHS) {// Comparing against a bit that we know is zero.
6926 bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
Owen Andersoneed707b2009-07-24 23:12:02 +00006927 Constant *Cst = ConstantInt::get(Type::Int1Ty, IsICMP_NE);
Chris Lattnera0141b92007-07-15 20:42:37 +00006928 return ReplaceInstUsesWith(ICI, Cst);
6929 }
6930
6931 if (LHSI->hasOneUse()) {
6932 // Otherwise strength reduce the shift into an and.
6933 uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
6934 Constant *Mask =
Owen Andersoneed707b2009-07-24 23:12:02 +00006935 ConstantInt::get(*Context, APInt::getLowBitsSet(TypeBits,
Owen Andersond672ecb2009-07-03 00:17:18 +00006936 TypeBits-ShAmtVal));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006937
Chris Lattnera0141b92007-07-15 20:42:37 +00006938 Instruction *AndI =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006939 BinaryOperator::CreateAnd(LHSI->getOperand(0),
Chris Lattnera0141b92007-07-15 20:42:37 +00006940 Mask, LHSI->getName()+".mask");
6941 Value *And = InsertNewInstBefore(AndI, ICI);
Owen Anderson333c4002009-07-09 23:48:35 +00006942 return new ICmpInst(*Context, ICI.getPredicate(), And,
Owen Andersoneed707b2009-07-24 23:12:02 +00006943 ConstantInt::get(*Context, RHSV.lshr(ShAmtVal)));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006944 }
6945 }
Chris Lattnera0141b92007-07-15 20:42:37 +00006946
6947 // Otherwise, if this is a comparison of the sign bit, simplify to and/test.
6948 bool TrueIfSigned = false;
6949 if (LHSI->hasOneUse() &&
6950 isSignBitCheck(ICI.getPredicate(), RHS, TrueIfSigned)) {
6951 // (X << 31) <s 0 --> (X&1) != 0
Owen Andersoneed707b2009-07-24 23:12:02 +00006952 Constant *Mask = ConstantInt::get(*Context, APInt(TypeBits, 1) <<
Chris Lattnera0141b92007-07-15 20:42:37 +00006953 (TypeBits-ShAmt->getZExtValue()-1));
6954 Instruction *AndI =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006955 BinaryOperator::CreateAnd(LHSI->getOperand(0),
Chris Lattnera0141b92007-07-15 20:42:37 +00006956 Mask, LHSI->getName()+".mask");
6957 Value *And = InsertNewInstBefore(AndI, ICI);
6958
Owen Anderson333c4002009-07-09 23:48:35 +00006959 return new ICmpInst(*Context,
6960 TrueIfSigned ? ICmpInst::ICMP_NE : ICmpInst::ICMP_EQ,
Owen Andersona7235ea2009-07-31 20:28:14 +00006961 And, Constant::getNullValue(And->getType()));
Chris Lattnera0141b92007-07-15 20:42:37 +00006962 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00006963 break;
Chris Lattnera0141b92007-07-15 20:42:37 +00006964 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00006965
6966 case Instruction::LShr: // (icmp pred (shr X, ShAmt), CI)
Chris Lattnera0141b92007-07-15 20:42:37 +00006967 case Instruction::AShr: {
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006968 // Only handle equality comparisons of shift-by-constant.
Chris Lattnera0141b92007-07-15 20:42:37 +00006969 ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006970 if (!ShAmt || !ICI.isEquality()) break;
Chris Lattnera0141b92007-07-15 20:42:37 +00006971
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006972 // Check that the shift amount is in range. If not, don't perform
6973 // undefined shifts. When the shift is visited it will be
6974 // simplified.
6975 uint32_t TypeBits = RHSV.getBitWidth();
6976 if (ShAmt->uge(TypeBits))
6977 break;
6978
6979 uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
Chris Lattnera0141b92007-07-15 20:42:37 +00006980
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006981 // If we are comparing against bits always shifted out, the
6982 // comparison cannot succeed.
6983 APInt Comp = RHSV << ShAmtVal;
6984 if (LHSI->getOpcode() == Instruction::LShr)
6985 Comp = Comp.lshr(ShAmtVal);
6986 else
6987 Comp = Comp.ashr(ShAmtVal);
6988
6989 if (Comp != RHSV) { // Comparing against a bit that we know is zero.
6990 bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
Owen Andersoneed707b2009-07-24 23:12:02 +00006991 Constant *Cst = ConstantInt::get(Type::Int1Ty, IsICMP_NE);
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006992 return ReplaceInstUsesWith(ICI, Cst);
6993 }
6994
6995 // Otherwise, check to see if the bits shifted out are known to be zero.
6996 // If so, we can compare against the unshifted value:
6997 // (X & 4) >> 1 == 2 --> (X & 4) == 4.
Evan Chengf30752c2008-04-23 00:38:06 +00006998 if (LHSI->hasOneUse() &&
6999 MaskedValueIsZero(LHSI->getOperand(0),
Chris Lattner41dc0fc2008-03-21 05:19:58 +00007000 APInt::getLowBitsSet(Comp.getBitWidth(), ShAmtVal))) {
Owen Anderson333c4002009-07-09 23:48:35 +00007001 return new ICmpInst(*Context, ICI.getPredicate(), LHSI->getOperand(0),
Owen Andersonbaf3c402009-07-29 18:55:55 +00007002 ConstantExpr::getShl(RHS, ShAmt));
Chris Lattner41dc0fc2008-03-21 05:19:58 +00007003 }
Chris Lattnera0141b92007-07-15 20:42:37 +00007004
Evan Chengf30752c2008-04-23 00:38:06 +00007005 if (LHSI->hasOneUse()) {
Chris Lattner41dc0fc2008-03-21 05:19:58 +00007006 // Otherwise strength reduce the shift into an and.
7007 APInt Val(APInt::getHighBitsSet(TypeBits, TypeBits - ShAmtVal));
Owen Andersoneed707b2009-07-24 23:12:02 +00007008 Constant *Mask = ConstantInt::get(*Context, Val);
Chris Lattnera0141b92007-07-15 20:42:37 +00007009
Chris Lattner41dc0fc2008-03-21 05:19:58 +00007010 Instruction *AndI =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007011 BinaryOperator::CreateAnd(LHSI->getOperand(0),
Chris Lattner41dc0fc2008-03-21 05:19:58 +00007012 Mask, LHSI->getName()+".mask");
7013 Value *And = InsertNewInstBefore(AndI, ICI);
Owen Anderson333c4002009-07-09 23:48:35 +00007014 return new ICmpInst(*Context, ICI.getPredicate(), And,
Owen Andersonbaf3c402009-07-29 18:55:55 +00007015 ConstantExpr::getShl(RHS, ShAmt));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007016 }
7017 break;
Chris Lattnera0141b92007-07-15 20:42:37 +00007018 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00007019
7020 case Instruction::SDiv:
7021 case Instruction::UDiv:
7022 // Fold: icmp pred ([us]div X, C1), C2 -> range test
7023 // Fold this div into the comparison, producing a range check.
7024 // Determine, based on the divide type, what the range is being
7025 // checked. If there is an overflow on the low or high side, remember
7026 // it, otherwise compute the range [low, hi) bounding the new value.
7027 // See: InsertRangeTest above for the kinds of replacements possible.
Chris Lattner562ef782007-06-20 23:46:26 +00007028 if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1)))
7029 if (Instruction *R = FoldICmpDivCst(ICI, cast<BinaryOperator>(LHSI),
7030 DivRHS))
7031 return R;
Chris Lattner01deb9d2007-04-03 17:43:25 +00007032 break;
Nick Lewycky5be29202008-02-03 16:33:09 +00007033
7034 case Instruction::Add:
7035 // Fold: icmp pred (add, X, C1), C2
7036
7037 if (!ICI.isEquality()) {
7038 ConstantInt *LHSC = dyn_cast<ConstantInt>(LHSI->getOperand(1));
7039 if (!LHSC) break;
7040 const APInt &LHSV = LHSC->getValue();
7041
7042 ConstantRange CR = ICI.makeConstantRange(ICI.getPredicate(), RHSV)
7043 .subtract(LHSV);
7044
7045 if (ICI.isSignedPredicate()) {
7046 if (CR.getLower().isSignBit()) {
Owen Anderson333c4002009-07-09 23:48:35 +00007047 return new ICmpInst(*Context, ICmpInst::ICMP_SLT, LHSI->getOperand(0),
Owen Andersoneed707b2009-07-24 23:12:02 +00007048 ConstantInt::get(*Context, CR.getUpper()));
Nick Lewycky5be29202008-02-03 16:33:09 +00007049 } else if (CR.getUpper().isSignBit()) {
Owen Anderson333c4002009-07-09 23:48:35 +00007050 return new ICmpInst(*Context, ICmpInst::ICMP_SGE, LHSI->getOperand(0),
Owen Andersoneed707b2009-07-24 23:12:02 +00007051 ConstantInt::get(*Context, CR.getLower()));
Nick Lewycky5be29202008-02-03 16:33:09 +00007052 }
7053 } else {
7054 if (CR.getLower().isMinValue()) {
Owen Anderson333c4002009-07-09 23:48:35 +00007055 return new ICmpInst(*Context, ICmpInst::ICMP_ULT, LHSI->getOperand(0),
Owen Andersoneed707b2009-07-24 23:12:02 +00007056 ConstantInt::get(*Context, CR.getUpper()));
Nick Lewycky5be29202008-02-03 16:33:09 +00007057 } else if (CR.getUpper().isMinValue()) {
Owen Anderson333c4002009-07-09 23:48:35 +00007058 return new ICmpInst(*Context, ICmpInst::ICMP_UGE, LHSI->getOperand(0),
Owen Andersoneed707b2009-07-24 23:12:02 +00007059 ConstantInt::get(*Context, CR.getLower()));
Nick Lewycky5be29202008-02-03 16:33:09 +00007060 }
7061 }
7062 }
7063 break;
Chris Lattner01deb9d2007-04-03 17:43:25 +00007064 }
7065
7066 // Simplify icmp_eq and icmp_ne instructions with integer constant RHS.
7067 if (ICI.isEquality()) {
7068 bool isICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
7069
7070 // If the first operand is (add|sub|and|or|xor|rem) with a constant, and
7071 // the second operand is a constant, simplify a bit.
7072 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(LHSI)) {
7073 switch (BO->getOpcode()) {
7074 case Instruction::SRem:
7075 // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
7076 if (RHSV == 0 && isa<ConstantInt>(BO->getOperand(1)) &&BO->hasOneUse()){
7077 const APInt &V = cast<ConstantInt>(BO->getOperand(1))->getValue();
7078 if (V.sgt(APInt(V.getBitWidth(), 1)) && V.isPowerOf2()) {
7079 Instruction *NewRem =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007080 BinaryOperator::CreateURem(BO->getOperand(0), BO->getOperand(1),
Chris Lattner01deb9d2007-04-03 17:43:25 +00007081 BO->getName());
7082 InsertNewInstBefore(NewRem, ICI);
Owen Anderson333c4002009-07-09 23:48:35 +00007083 return new ICmpInst(*Context, ICI.getPredicate(), NewRem,
Owen Andersona7235ea2009-07-31 20:28:14 +00007084 Constant::getNullValue(BO->getType()));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007085 }
7086 }
7087 break;
7088 case Instruction::Add:
7089 // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
7090 if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
7091 if (BO->hasOneUse())
Owen Anderson333c4002009-07-09 23:48:35 +00007092 return new ICmpInst(*Context, ICI.getPredicate(), BO->getOperand(0),
Owen Andersonbaf3c402009-07-29 18:55:55 +00007093 ConstantExpr::getSub(RHS, BOp1C));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007094 } else if (RHSV == 0) {
7095 // Replace ((add A, B) != 0) with (A != -B) if A or B is
7096 // efficiently invertible, or if the add has just this one use.
7097 Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
7098
Dan Gohman186a6362009-08-12 16:04:34 +00007099 if (Value *NegVal = dyn_castNegVal(BOp1))
Owen Anderson333c4002009-07-09 23:48:35 +00007100 return new ICmpInst(*Context, ICI.getPredicate(), BOp0, NegVal);
Dan Gohman186a6362009-08-12 16:04:34 +00007101 else if (Value *NegVal = dyn_castNegVal(BOp0))
Owen Anderson333c4002009-07-09 23:48:35 +00007102 return new ICmpInst(*Context, ICI.getPredicate(), NegVal, BOp1);
Chris Lattner01deb9d2007-04-03 17:43:25 +00007103 else if (BO->hasOneUse()) {
Owen Anderson0a5372e2009-07-13 04:09:18 +00007104 Instruction *Neg = BinaryOperator::CreateNeg(*Context, BOp1);
Chris Lattner01deb9d2007-04-03 17:43:25 +00007105 InsertNewInstBefore(Neg, ICI);
7106 Neg->takeName(BO);
Owen Anderson333c4002009-07-09 23:48:35 +00007107 return new ICmpInst(*Context, ICI.getPredicate(), BOp0, Neg);
Chris Lattner01deb9d2007-04-03 17:43:25 +00007108 }
7109 }
7110 break;
7111 case Instruction::Xor:
7112 // For the xor case, we can xor two constants together, eliminating
7113 // the explicit xor.
7114 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
Owen Anderson333c4002009-07-09 23:48:35 +00007115 return new ICmpInst(*Context, ICI.getPredicate(), BO->getOperand(0),
Owen Andersonbaf3c402009-07-29 18:55:55 +00007116 ConstantExpr::getXor(RHS, BOC));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007117
7118 // FALLTHROUGH
7119 case Instruction::Sub:
7120 // Replace (([sub|xor] A, B) != 0) with (A != B)
7121 if (RHSV == 0)
Owen Anderson333c4002009-07-09 23:48:35 +00007122 return new ICmpInst(*Context, ICI.getPredicate(), BO->getOperand(0),
Chris Lattner01deb9d2007-04-03 17:43:25 +00007123 BO->getOperand(1));
7124 break;
7125
7126 case Instruction::Or:
7127 // If bits are being or'd in that are not present in the constant we
7128 // are comparing against, then the comparison could never succeed!
7129 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00007130 Constant *NotCI = ConstantExpr::getNot(RHS);
7131 if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
Owen Andersond672ecb2009-07-03 00:17:18 +00007132 return ReplaceInstUsesWith(ICI,
Owen Andersoneed707b2009-07-24 23:12:02 +00007133 ConstantInt::get(Type::Int1Ty,
Owen Andersond672ecb2009-07-03 00:17:18 +00007134 isICMP_NE));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007135 }
7136 break;
7137
7138 case Instruction::And:
7139 if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
7140 // If bits are being compared against that are and'd out, then the
7141 // comparison can never succeed!
7142 if ((RHSV & ~BOC->getValue()) != 0)
Owen Andersond672ecb2009-07-03 00:17:18 +00007143 return ReplaceInstUsesWith(ICI,
Owen Andersoneed707b2009-07-24 23:12:02 +00007144 ConstantInt::get(Type::Int1Ty,
Owen Andersond672ecb2009-07-03 00:17:18 +00007145 isICMP_NE));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007146
7147 // If we have ((X & C) == C), turn it into ((X & C) != 0).
7148 if (RHS == BOC && RHSV.isPowerOf2())
Owen Anderson333c4002009-07-09 23:48:35 +00007149 return new ICmpInst(*Context, isICMP_NE ? ICmpInst::ICMP_EQ :
Chris Lattner01deb9d2007-04-03 17:43:25 +00007150 ICmpInst::ICMP_NE, LHSI,
Owen Andersona7235ea2009-07-31 20:28:14 +00007151 Constant::getNullValue(RHS->getType()));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007152
7153 // Replace (and X, (1 << size(X)-1) != 0) with x s< 0
Chris Lattner833f25d2008-06-02 01:29:46 +00007154 if (BOC->getValue().isSignBit()) {
Chris Lattner01deb9d2007-04-03 17:43:25 +00007155 Value *X = BO->getOperand(0);
Owen Andersona7235ea2009-07-31 20:28:14 +00007156 Constant *Zero = Constant::getNullValue(X->getType());
Chris Lattner01deb9d2007-04-03 17:43:25 +00007157 ICmpInst::Predicate pred = isICMP_NE ?
7158 ICmpInst::ICMP_SLT : ICmpInst::ICMP_SGE;
Owen Anderson333c4002009-07-09 23:48:35 +00007159 return new ICmpInst(*Context, pred, X, Zero);
Chris Lattner01deb9d2007-04-03 17:43:25 +00007160 }
7161
7162 // ((X & ~7) == 0) --> X < 8
7163 if (RHSV == 0 && isHighOnes(BOC)) {
7164 Value *X = BO->getOperand(0);
Owen Andersonbaf3c402009-07-29 18:55:55 +00007165 Constant *NegX = ConstantExpr::getNeg(BOC);
Chris Lattner01deb9d2007-04-03 17:43:25 +00007166 ICmpInst::Predicate pred = isICMP_NE ?
7167 ICmpInst::ICMP_UGE : ICmpInst::ICMP_ULT;
Owen Anderson333c4002009-07-09 23:48:35 +00007168 return new ICmpInst(*Context, pred, X, NegX);
Chris Lattner01deb9d2007-04-03 17:43:25 +00007169 }
7170 }
7171 default: break;
7172 }
7173 } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(LHSI)) {
7174 // Handle icmp {eq|ne} <intrinsic>, intcst.
7175 if (II->getIntrinsicID() == Intrinsic::bswap) {
7176 AddToWorkList(II);
7177 ICI.setOperand(0, II->getOperand(1));
Owen Andersoneed707b2009-07-24 23:12:02 +00007178 ICI.setOperand(1, ConstantInt::get(*Context, RHSV.byteSwap()));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007179 return &ICI;
7180 }
7181 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00007182 }
7183 return 0;
7184}
7185
7186/// visitICmpInstWithCastAndCast - Handle icmp (cast x to y), (cast/cst).
7187/// We only handle extending casts so far.
7188///
Reid Spencere4d87aa2006-12-23 06:05:41 +00007189Instruction *InstCombiner::visitICmpInstWithCastAndCast(ICmpInst &ICI) {
7190 const CastInst *LHSCI = cast<CastInst>(ICI.getOperand(0));
Reid Spencer3da59db2006-11-27 01:05:10 +00007191 Value *LHSCIOp = LHSCI->getOperand(0);
7192 const Type *SrcTy = LHSCIOp->getType();
Reid Spencere4d87aa2006-12-23 06:05:41 +00007193 const Type *DestTy = LHSCI->getType();
Chris Lattner484d3cf2005-04-24 06:59:08 +00007194 Value *RHSCIOp;
7195
Chris Lattner8c756c12007-05-05 22:41:33 +00007196 // Turn icmp (ptrtoint x), (ptrtoint/c) into a compare of the input if the
7197 // integer type is the same size as the pointer type.
Dan Gohmance9fe9f2009-07-21 23:21:54 +00007198 if (TD && LHSCI->getOpcode() == Instruction::PtrToInt &&
7199 TD->getPointerSizeInBits() ==
Chris Lattner8c756c12007-05-05 22:41:33 +00007200 cast<IntegerType>(DestTy)->getBitWidth()) {
7201 Value *RHSOp = 0;
7202 if (Constant *RHSC = dyn_cast<Constant>(ICI.getOperand(1))) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00007203 RHSOp = ConstantExpr::getIntToPtr(RHSC, SrcTy);
Chris Lattner8c756c12007-05-05 22:41:33 +00007204 } else if (PtrToIntInst *RHSC = dyn_cast<PtrToIntInst>(ICI.getOperand(1))) {
7205 RHSOp = RHSC->getOperand(0);
7206 // If the pointer types don't match, insert a bitcast.
7207 if (LHSCIOp->getType() != RHSOp->getType())
Chris Lattner6d0339d2008-01-13 22:23:22 +00007208 RHSOp = InsertBitCastBefore(RHSOp, LHSCIOp->getType(), ICI);
Chris Lattner8c756c12007-05-05 22:41:33 +00007209 }
7210
7211 if (RHSOp)
Owen Anderson333c4002009-07-09 23:48:35 +00007212 return new ICmpInst(*Context, ICI.getPredicate(), LHSCIOp, RHSOp);
Chris Lattner8c756c12007-05-05 22:41:33 +00007213 }
7214
7215 // The code below only handles extension cast instructions, so far.
7216 // Enforce this.
Reid Spencere4d87aa2006-12-23 06:05:41 +00007217 if (LHSCI->getOpcode() != Instruction::ZExt &&
7218 LHSCI->getOpcode() != Instruction::SExt)
Chris Lattnerb352fa52005-01-17 03:20:02 +00007219 return 0;
7220
Reid Spencere4d87aa2006-12-23 06:05:41 +00007221 bool isSignedExt = LHSCI->getOpcode() == Instruction::SExt;
7222 bool isSignedCmp = ICI.isSignedPredicate();
Chris Lattner484d3cf2005-04-24 06:59:08 +00007223
Reid Spencere4d87aa2006-12-23 06:05:41 +00007224 if (CastInst *CI = dyn_cast<CastInst>(ICI.getOperand(1))) {
Chris Lattner484d3cf2005-04-24 06:59:08 +00007225 // Not an extension from the same type?
7226 RHSCIOp = CI->getOperand(0);
Reid Spencere4d87aa2006-12-23 06:05:41 +00007227 if (RHSCIOp->getType() != LHSCIOp->getType())
7228 return 0;
Chris Lattnera5c5e772007-01-13 23:11:38 +00007229
Nick Lewycky4189a532008-01-28 03:48:02 +00007230 // If the signedness of the two casts doesn't agree (i.e. one is a sext
Chris Lattnera5c5e772007-01-13 23:11:38 +00007231 // and the other is a zext), then we can't handle this.
7232 if (CI->getOpcode() != LHSCI->getOpcode())
7233 return 0;
7234
Nick Lewycky4189a532008-01-28 03:48:02 +00007235 // Deal with equality cases early.
7236 if (ICI.isEquality())
Owen Anderson333c4002009-07-09 23:48:35 +00007237 return new ICmpInst(*Context, ICI.getPredicate(), LHSCIOp, RHSCIOp);
Nick Lewycky4189a532008-01-28 03:48:02 +00007238
7239 // A signed comparison of sign extended values simplifies into a
7240 // signed comparison.
7241 if (isSignedCmp && isSignedExt)
Owen Anderson333c4002009-07-09 23:48:35 +00007242 return new ICmpInst(*Context, ICI.getPredicate(), LHSCIOp, RHSCIOp);
Nick Lewycky4189a532008-01-28 03:48:02 +00007243
7244 // The other three cases all fold into an unsigned comparison.
Owen Anderson333c4002009-07-09 23:48:35 +00007245 return new ICmpInst(*Context, ICI.getUnsignedPredicate(), LHSCIOp, RHSCIOp);
Reid Spencer6731d5c2004-11-28 21:31:15 +00007246 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00007247
Reid Spencere4d87aa2006-12-23 06:05:41 +00007248 // If we aren't dealing with a constant on the RHS, exit early
7249 ConstantInt *CI = dyn_cast<ConstantInt>(ICI.getOperand(1));
7250 if (!CI)
7251 return 0;
7252
7253 // Compute the constant that would happen if we truncated to SrcTy then
7254 // reextended to DestTy.
Owen Andersonbaf3c402009-07-29 18:55:55 +00007255 Constant *Res1 = ConstantExpr::getTrunc(CI, SrcTy);
7256 Constant *Res2 = ConstantExpr::getCast(LHSCI->getOpcode(),
Owen Andersond672ecb2009-07-03 00:17:18 +00007257 Res1, DestTy);
Reid Spencere4d87aa2006-12-23 06:05:41 +00007258
7259 // If the re-extended constant didn't change...
7260 if (Res2 == CI) {
7261 // Make sure that sign of the Cmp and the sign of the Cast are the same.
7262 // For example, we might have:
Dan Gohmana119de82009-06-14 23:30:43 +00007263 // %A = sext i16 %X to i32
7264 // %B = icmp ugt i32 %A, 1330
Reid Spencere4d87aa2006-12-23 06:05:41 +00007265 // It is incorrect to transform this into
Dan Gohmana119de82009-06-14 23:30:43 +00007266 // %B = icmp ugt i16 %X, 1330
Reid Spencere4d87aa2006-12-23 06:05:41 +00007267 // because %A may have negative value.
7268 //
Chris Lattnerf2991842008-07-11 04:09:09 +00007269 // However, we allow this when the compare is EQ/NE, because they are
7270 // signless.
7271 if (isSignedExt == isSignedCmp || ICI.isEquality())
Owen Anderson333c4002009-07-09 23:48:35 +00007272 return new ICmpInst(*Context, ICI.getPredicate(), LHSCIOp, Res1);
Chris Lattnerf2991842008-07-11 04:09:09 +00007273 return 0;
Reid Spencere4d87aa2006-12-23 06:05:41 +00007274 }
7275
7276 // The re-extended constant changed so the constant cannot be represented
7277 // in the shorter type. Consequently, we cannot emit a simple comparison.
7278
7279 // First, handle some easy cases. We know the result cannot be equal at this
7280 // point so handle the ICI.isEquality() cases
7281 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
Owen Anderson5defacc2009-07-31 17:39:07 +00007282 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
Reid Spencere4d87aa2006-12-23 06:05:41 +00007283 if (ICI.getPredicate() == ICmpInst::ICMP_NE)
Owen Anderson5defacc2009-07-31 17:39:07 +00007284 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
Reid Spencere4d87aa2006-12-23 06:05:41 +00007285
7286 // Evaluate the comparison for LT (we invert for GT below). LE and GE cases
7287 // should have been folded away previously and not enter in here.
7288 Value *Result;
7289 if (isSignedCmp) {
7290 // We're performing a signed comparison.
Reid Spencer0460fb32007-03-22 20:36:03 +00007291 if (cast<ConstantInt>(CI)->getValue().isNegative())
Owen Anderson5defacc2009-07-31 17:39:07 +00007292 Result = ConstantInt::getFalse(*Context); // X < (small) --> false
Reid Spencere4d87aa2006-12-23 06:05:41 +00007293 else
Owen Anderson5defacc2009-07-31 17:39:07 +00007294 Result = ConstantInt::getTrue(*Context); // X < (large) --> true
Reid Spencere4d87aa2006-12-23 06:05:41 +00007295 } else {
7296 // We're performing an unsigned comparison.
7297 if (isSignedExt) {
7298 // We're performing an unsigned comp with a sign extended value.
7299 // This is true if the input is >= 0. [aka >s -1]
Owen Andersona7235ea2009-07-31 20:28:14 +00007300 Constant *NegOne = Constant::getAllOnesValue(SrcTy);
Owen Anderson333c4002009-07-09 23:48:35 +00007301 Result = InsertNewInstBefore(new ICmpInst(*Context, ICmpInst::ICMP_SGT,
7302 LHSCIOp, NegOne, ICI.getName()), ICI);
Reid Spencere4d87aa2006-12-23 06:05:41 +00007303 } else {
7304 // Unsigned extend & unsigned compare -> always true.
Owen Anderson5defacc2009-07-31 17:39:07 +00007305 Result = ConstantInt::getTrue(*Context);
Reid Spencere4d87aa2006-12-23 06:05:41 +00007306 }
7307 }
7308
7309 // Finally, return the value computed.
7310 if (ICI.getPredicate() == ICmpInst::ICMP_ULT ||
Chris Lattnerf2991842008-07-11 04:09:09 +00007311 ICI.getPredicate() == ICmpInst::ICMP_SLT)
Reid Spencere4d87aa2006-12-23 06:05:41 +00007312 return ReplaceInstUsesWith(ICI, Result);
Chris Lattnerf2991842008-07-11 04:09:09 +00007313
7314 assert((ICI.getPredicate()==ICmpInst::ICMP_UGT ||
7315 ICI.getPredicate()==ICmpInst::ICMP_SGT) &&
7316 "ICmp should be folded!");
7317 if (Constant *CI = dyn_cast<Constant>(Result))
Owen Andersonbaf3c402009-07-29 18:55:55 +00007318 return ReplaceInstUsesWith(ICI, ConstantExpr::getNot(CI));
Owen Anderson73c6b712009-07-13 20:58:05 +00007319 return BinaryOperator::CreateNot(*Context, Result);
Chris Lattner484d3cf2005-04-24 06:59:08 +00007320}
Chris Lattner3f5b8772002-05-06 16:14:14 +00007321
Reid Spencer832254e2007-02-02 02:16:23 +00007322Instruction *InstCombiner::visitShl(BinaryOperator &I) {
7323 return commonShiftTransforms(I);
7324}
7325
7326Instruction *InstCombiner::visitLShr(BinaryOperator &I) {
7327 return commonShiftTransforms(I);
7328}
7329
7330Instruction *InstCombiner::visitAShr(BinaryOperator &I) {
Chris Lattner348f6652007-12-06 01:59:46 +00007331 if (Instruction *R = commonShiftTransforms(I))
7332 return R;
7333
7334 Value *Op0 = I.getOperand(0);
7335
7336 // ashr int -1, X = -1 (for any arithmetic shift rights of ~0)
7337 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
7338 if (CSI->isAllOnesValue())
7339 return ReplaceInstUsesWith(I, CSI);
Dan Gohman0001e562009-02-24 02:00:40 +00007340
Dan Gohmanc6ac3222009-06-16 19:55:29 +00007341 // See if we can turn a signed shr into an unsigned shr.
7342 if (MaskedValueIsZero(Op0,
7343 APInt::getSignBit(I.getType()->getScalarSizeInBits())))
7344 return BinaryOperator::CreateLShr(Op0, I.getOperand(1));
7345
7346 // Arithmetic shifting an all-sign-bit value is a no-op.
7347 unsigned NumSignBits = ComputeNumSignBits(Op0);
7348 if (NumSignBits == Op0->getType()->getScalarSizeInBits())
7349 return ReplaceInstUsesWith(I, Op0);
Dan Gohman0001e562009-02-24 02:00:40 +00007350
Chris Lattner348f6652007-12-06 01:59:46 +00007351 return 0;
Reid Spencer832254e2007-02-02 02:16:23 +00007352}
7353
7354Instruction *InstCombiner::commonShiftTransforms(BinaryOperator &I) {
7355 assert(I.getOperand(1)->getType() == I.getOperand(0)->getType());
Chris Lattner7e708292002-06-25 16:13:24 +00007356 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00007357
7358 // shl X, 0 == X and shr X, 0 == X
7359 // shl 0, X == 0 and shr 0, X == 0
Owen Andersona7235ea2009-07-31 20:28:14 +00007360 if (Op1 == Constant::getNullValue(Op1->getType()) ||
7361 Op0 == Constant::getNullValue(Op0->getType()))
Chris Lattner233f7dc2002-08-12 21:17:25 +00007362 return ReplaceInstUsesWith(I, Op0);
Chris Lattner8d6bbdb2006-02-12 08:07:37 +00007363
Reid Spencere4d87aa2006-12-23 06:05:41 +00007364 if (isa<UndefValue>(Op0)) {
7365 if (I.getOpcode() == Instruction::AShr) // undef >>s X -> undef
Chris Lattner79a564c2004-10-16 23:28:04 +00007366 return ReplaceInstUsesWith(I, Op0);
Reid Spencere4d87aa2006-12-23 06:05:41 +00007367 else // undef << X -> 0, undef >>u X -> 0
Owen Andersona7235ea2009-07-31 20:28:14 +00007368 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00007369 }
7370 if (isa<UndefValue>(Op1)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00007371 if (I.getOpcode() == Instruction::AShr) // X >>s undef -> X
7372 return ReplaceInstUsesWith(I, Op0);
7373 else // X << undef, X >>u undef -> 0
Owen Andersona7235ea2009-07-31 20:28:14 +00007374 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00007375 }
7376
Dan Gohman9004c8a2009-05-21 02:28:33 +00007377 // See if we can fold away this shift.
Dan Gohman6de29f82009-06-15 22:12:54 +00007378 if (SimplifyDemandedInstructionBits(I))
Dan Gohman9004c8a2009-05-21 02:28:33 +00007379 return &I;
7380
Chris Lattner2eefe512004-04-09 19:05:30 +00007381 // Try to fold constant and into select arguments.
7382 if (isa<Constant>(Op0))
7383 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner6e7ba452005-01-01 16:22:27 +00007384 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00007385 return R;
7386
Reid Spencerb83eb642006-10-20 07:07:24 +00007387 if (ConstantInt *CUI = dyn_cast<ConstantInt>(Op1))
Reid Spencerc5b206b2006-12-31 05:48:39 +00007388 if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
7389 return Res;
Chris Lattner4d5542c2006-01-06 07:12:35 +00007390 return 0;
7391}
7392
Reid Spencerb83eb642006-10-20 07:07:24 +00007393Instruction *InstCombiner::FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
Reid Spencer832254e2007-02-02 02:16:23 +00007394 BinaryOperator &I) {
Chris Lattner4598c942009-01-31 08:24:16 +00007395 bool isLeftShift = I.getOpcode() == Instruction::Shl;
Chris Lattner4d5542c2006-01-06 07:12:35 +00007396
Chris Lattner8d6bbdb2006-02-12 08:07:37 +00007397 // See if we can simplify any instructions used by the instruction whose sole
7398 // purpose is to compute bits we don't care about.
Dan Gohmanc6ac3222009-06-16 19:55:29 +00007399 uint32_t TypeBits = Op0->getType()->getScalarSizeInBits();
Chris Lattner8d6bbdb2006-02-12 08:07:37 +00007400
Dan Gohmana119de82009-06-14 23:30:43 +00007401 // shl i32 X, 32 = 0 and srl i8 Y, 9 = 0, ... just don't eliminate
7402 // a signed shift.
Chris Lattner4d5542c2006-01-06 07:12:35 +00007403 //
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00007404 if (Op1->uge(TypeBits)) {
Chris Lattner0737c242007-02-02 05:29:55 +00007405 if (I.getOpcode() != Instruction::AShr)
Owen Andersona7235ea2009-07-31 20:28:14 +00007406 return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
Chris Lattner4d5542c2006-01-06 07:12:35 +00007407 else {
Owen Andersoneed707b2009-07-24 23:12:02 +00007408 I.setOperand(1, ConstantInt::get(I.getType(), TypeBits-1));
Chris Lattner4d5542c2006-01-06 07:12:35 +00007409 return &I;
Chris Lattner8adac752004-02-23 20:30:06 +00007410 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007411 }
7412
7413 // ((X*C1) << C2) == (X * (C1 << C2))
7414 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
7415 if (BO->getOpcode() == Instruction::Mul && isLeftShift)
7416 if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007417 return BinaryOperator::CreateMul(BO->getOperand(0),
Owen Andersonbaf3c402009-07-29 18:55:55 +00007418 ConstantExpr::getShl(BOOp, Op1));
Chris Lattner4d5542c2006-01-06 07:12:35 +00007419
7420 // Try to fold constant and into select arguments.
7421 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
7422 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
7423 return R;
7424 if (isa<PHINode>(Op0))
7425 if (Instruction *NV = FoldOpIntoPhi(I))
7426 return NV;
7427
Chris Lattner8999dd32007-12-22 09:07:47 +00007428 // Fold shift2(trunc(shift1(x,c1)), c2) -> trunc(shift2(shift1(x,c1),c2))
7429 if (TruncInst *TI = dyn_cast<TruncInst>(Op0)) {
7430 Instruction *TrOp = dyn_cast<Instruction>(TI->getOperand(0));
7431 // If 'shift2' is an ashr, we would have to get the sign bit into a funny
7432 // place. Don't try to do this transformation in this case. Also, we
7433 // require that the input operand is a shift-by-constant so that we have
7434 // confidence that the shifts will get folded together. We could do this
7435 // xform in more cases, but it is unlikely to be profitable.
7436 if (TrOp && I.isLogicalShift() && TrOp->isShift() &&
7437 isa<ConstantInt>(TrOp->getOperand(1))) {
7438 // Okay, we'll do this xform. Make the shift of shift.
Owen Andersonbaf3c402009-07-29 18:55:55 +00007439 Constant *ShAmt = ConstantExpr::getZExt(Op1, TrOp->getType());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007440 Instruction *NSh = BinaryOperator::Create(I.getOpcode(), TrOp, ShAmt,
Chris Lattner8999dd32007-12-22 09:07:47 +00007441 I.getName());
7442 InsertNewInstBefore(NSh, I); // (shift2 (shift1 & 0x00FF), c2)
7443
7444 // For logical shifts, the truncation has the effect of making the high
7445 // part of the register be zeros. Emulate this by inserting an AND to
7446 // clear the top bits as needed. This 'and' will usually be zapped by
7447 // other xforms later if dead.
Dan Gohmanc6ac3222009-06-16 19:55:29 +00007448 unsigned SrcSize = TrOp->getType()->getScalarSizeInBits();
7449 unsigned DstSize = TI->getType()->getScalarSizeInBits();
Chris Lattner8999dd32007-12-22 09:07:47 +00007450 APInt MaskV(APInt::getLowBitsSet(SrcSize, DstSize));
7451
7452 // The mask we constructed says what the trunc would do if occurring
7453 // between the shifts. We want to know the effect *after* the second
7454 // shift. We know that it is a logical shift by a constant, so adjust the
7455 // mask as appropriate.
7456 if (I.getOpcode() == Instruction::Shl)
7457 MaskV <<= Op1->getZExtValue();
7458 else {
7459 assert(I.getOpcode() == Instruction::LShr && "Unknown logical shift");
7460 MaskV = MaskV.lshr(Op1->getZExtValue());
7461 }
7462
Owen Andersond672ecb2009-07-03 00:17:18 +00007463 Instruction *And =
Owen Andersoneed707b2009-07-24 23:12:02 +00007464 BinaryOperator::CreateAnd(NSh, ConstantInt::get(*Context, MaskV),
Owen Andersond672ecb2009-07-03 00:17:18 +00007465 TI->getName());
Chris Lattner8999dd32007-12-22 09:07:47 +00007466 InsertNewInstBefore(And, I); // shift1 & 0x00FF
7467
7468 // Return the value truncated to the interesting size.
7469 return new TruncInst(And, I.getType());
7470 }
7471 }
7472
Chris Lattner4d5542c2006-01-06 07:12:35 +00007473 if (Op0->hasOneUse()) {
Chris Lattner4d5542c2006-01-06 07:12:35 +00007474 if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
7475 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
7476 Value *V1, *V2;
7477 ConstantInt *CC;
7478 switch (Op0BO->getOpcode()) {
Chris Lattner11021cb2005-09-18 05:12:10 +00007479 default: break;
7480 case Instruction::Add:
7481 case Instruction::And:
7482 case Instruction::Or:
Reid Spencera07cb7d2007-02-02 14:41:37 +00007483 case Instruction::Xor: {
Chris Lattner11021cb2005-09-18 05:12:10 +00007484 // These operators commute.
7485 // Turn (Y + (X >> C)) << C -> (X + (Y << C)) & (~0 << C)
Chris Lattner150f12a2005-09-18 06:30:59 +00007486 if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00007487 match(Op0BO->getOperand(1), m_Shr(m_Value(V1),
7488 m_Specific(Op1)), *Context)){
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007489 Instruction *YS = BinaryOperator::CreateShl(
Chris Lattner4d5542c2006-01-06 07:12:35 +00007490 Op0BO->getOperand(0), Op1,
Chris Lattner150f12a2005-09-18 06:30:59 +00007491 Op0BO->getName());
7492 InsertNewInstBefore(YS, I); // (Y << C)
Chris Lattner9a4cacb2006-02-09 07:41:14 +00007493 Instruction *X =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007494 BinaryOperator::Create(Op0BO->getOpcode(), YS, V1,
Chris Lattner9a4cacb2006-02-09 07:41:14 +00007495 Op0BO->getOperand(1)->getName());
Chris Lattner150f12a2005-09-18 06:30:59 +00007496 InsertNewInstBefore(X, I); // (X + (Y << C))
Zhou Sheng302748d2007-03-30 17:20:39 +00007497 uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
Owen Andersoneed707b2009-07-24 23:12:02 +00007498 return BinaryOperator::CreateAnd(X, ConstantInt::get(*Context,
Zhou Sheng90b96812007-03-30 05:45:18 +00007499 APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
Chris Lattner150f12a2005-09-18 06:30:59 +00007500 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007501
Chris Lattner150f12a2005-09-18 06:30:59 +00007502 // Turn (Y + ((X >> C) & CC)) << C -> ((X & (CC << C)) + (Y << C))
Reid Spencera07cb7d2007-02-02 14:41:37 +00007503 Value *Op0BOOp1 = Op0BO->getOperand(1);
Chris Lattner3c698492007-03-05 00:11:19 +00007504 if (isLeftShift && Op0BOOp1->hasOneUse() &&
Reid Spencera07cb7d2007-02-02 14:41:37 +00007505 match(Op0BOOp1,
Chris Lattnercb504b92008-11-16 05:38:51 +00007506 m_And(m_Shr(m_Value(V1), m_Specific(Op1)),
Owen Andersonc7d2ce72009-07-10 17:35:01 +00007507 m_ConstantInt(CC)), *Context) &&
Chris Lattnercb504b92008-11-16 05:38:51 +00007508 cast<BinaryOperator>(Op0BOOp1)->getOperand(0)->hasOneUse()) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007509 Instruction *YS = BinaryOperator::CreateShl(
Reid Spencer832254e2007-02-02 02:16:23 +00007510 Op0BO->getOperand(0), Op1,
7511 Op0BO->getName());
Chris Lattner150f12a2005-09-18 06:30:59 +00007512 InsertNewInstBefore(YS, I); // (Y << C)
7513 Instruction *XM =
Owen Andersond672ecb2009-07-03 00:17:18 +00007514 BinaryOperator::CreateAnd(V1,
Owen Andersonbaf3c402009-07-29 18:55:55 +00007515 ConstantExpr::getShl(CC, Op1),
Chris Lattner150f12a2005-09-18 06:30:59 +00007516 V1->getName()+".mask");
7517 InsertNewInstBefore(XM, I); // X & (CC << C)
7518
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007519 return BinaryOperator::Create(Op0BO->getOpcode(), YS, XM);
Chris Lattner150f12a2005-09-18 06:30:59 +00007520 }
Reid Spencera07cb7d2007-02-02 14:41:37 +00007521 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007522
Reid Spencera07cb7d2007-02-02 14:41:37 +00007523 // FALL THROUGH.
7524 case Instruction::Sub: {
Chris Lattner11021cb2005-09-18 05:12:10 +00007525 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
Chris Lattner150f12a2005-09-18 06:30:59 +00007526 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00007527 match(Op0BO->getOperand(0), m_Shr(m_Value(V1),
7528 m_Specific(Op1)), *Context)){
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007529 Instruction *YS = BinaryOperator::CreateShl(
Reid Spencer832254e2007-02-02 02:16:23 +00007530 Op0BO->getOperand(1), Op1,
7531 Op0BO->getName());
Chris Lattner150f12a2005-09-18 06:30:59 +00007532 InsertNewInstBefore(YS, I); // (Y << C)
Chris Lattner9a4cacb2006-02-09 07:41:14 +00007533 Instruction *X =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007534 BinaryOperator::Create(Op0BO->getOpcode(), V1, YS,
Chris Lattner9a4cacb2006-02-09 07:41:14 +00007535 Op0BO->getOperand(0)->getName());
Chris Lattner150f12a2005-09-18 06:30:59 +00007536 InsertNewInstBefore(X, I); // (X + (Y << C))
Zhou Sheng302748d2007-03-30 17:20:39 +00007537 uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
Owen Andersoneed707b2009-07-24 23:12:02 +00007538 return BinaryOperator::CreateAnd(X, ConstantInt::get(*Context,
Zhou Sheng90b96812007-03-30 05:45:18 +00007539 APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
Chris Lattner150f12a2005-09-18 06:30:59 +00007540 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007541
Chris Lattner13d4ab42006-05-31 21:14:00 +00007542 // Turn (((X >> C)&CC) + Y) << C -> (X + (Y << C)) & (CC << C)
Chris Lattner150f12a2005-09-18 06:30:59 +00007543 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
7544 match(Op0BO->getOperand(0),
7545 m_And(m_Shr(m_Value(V1), m_Value(V2)),
Owen Andersonc7d2ce72009-07-10 17:35:01 +00007546 m_ConstantInt(CC)), *Context) && V2 == Op1 &&
Chris Lattner9a4cacb2006-02-09 07:41:14 +00007547 cast<BinaryOperator>(Op0BO->getOperand(0))
7548 ->getOperand(0)->hasOneUse()) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007549 Instruction *YS = BinaryOperator::CreateShl(
Reid Spencer832254e2007-02-02 02:16:23 +00007550 Op0BO->getOperand(1), Op1,
7551 Op0BO->getName());
Chris Lattner150f12a2005-09-18 06:30:59 +00007552 InsertNewInstBefore(YS, I); // (Y << C)
7553 Instruction *XM =
Owen Andersond672ecb2009-07-03 00:17:18 +00007554 BinaryOperator::CreateAnd(V1,
Owen Andersonbaf3c402009-07-29 18:55:55 +00007555 ConstantExpr::getShl(CC, Op1),
Chris Lattner150f12a2005-09-18 06:30:59 +00007556 V1->getName()+".mask");
7557 InsertNewInstBefore(XM, I); // X & (CC << C)
7558
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007559 return BinaryOperator::Create(Op0BO->getOpcode(), XM, YS);
Chris Lattner150f12a2005-09-18 06:30:59 +00007560 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007561
Chris Lattner11021cb2005-09-18 05:12:10 +00007562 break;
Reid Spencera07cb7d2007-02-02 14:41:37 +00007563 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007564 }
7565
7566
7567 // If the operand is an bitwise operator with a constant RHS, and the
7568 // shift is the only use, we can pull it out of the shift.
7569 if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
7570 bool isValid = true; // Valid only for And, Or, Xor
7571 bool highBitSet = false; // Transform if high bit of constant set?
7572
7573 switch (Op0BO->getOpcode()) {
Chris Lattnerdf17af12003-08-12 21:53:41 +00007574 default: isValid = false; break; // Do not perform transform!
Chris Lattner1f7e1602004-10-08 03:46:20 +00007575 case Instruction::Add:
7576 isValid = isLeftShift;
7577 break;
Chris Lattnerdf17af12003-08-12 21:53:41 +00007578 case Instruction::Or:
7579 case Instruction::Xor:
7580 highBitSet = false;
7581 break;
7582 case Instruction::And:
7583 highBitSet = true;
7584 break;
Chris Lattner4d5542c2006-01-06 07:12:35 +00007585 }
7586
7587 // If this is a signed shift right, and the high bit is modified
7588 // by the logical operation, do not perform the transformation.
7589 // The highBitSet boolean indicates the value of the high bit of
7590 // the constant which would cause it to be modified for this
7591 // operation.
7592 //
Chris Lattnerc95ba442007-12-06 06:25:04 +00007593 if (isValid && I.getOpcode() == Instruction::AShr)
Zhou Shenge9e03f62007-03-28 15:02:20 +00007594 isValid = Op0C->getValue()[TypeBits-1] == highBitSet;
Chris Lattner4d5542c2006-01-06 07:12:35 +00007595
7596 if (isValid) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00007597 Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, Op1);
Chris Lattner4d5542c2006-01-06 07:12:35 +00007598
7599 Instruction *NewShift =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007600 BinaryOperator::Create(I.getOpcode(), Op0BO->getOperand(0), Op1);
Chris Lattner4d5542c2006-01-06 07:12:35 +00007601 InsertNewInstBefore(NewShift, I);
Chris Lattner6934a042007-02-11 01:23:03 +00007602 NewShift->takeName(Op0BO);
Chris Lattner4d5542c2006-01-06 07:12:35 +00007603
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007604 return BinaryOperator::Create(Op0BO->getOpcode(), NewShift,
Chris Lattner4d5542c2006-01-06 07:12:35 +00007605 NewRHS);
7606 }
7607 }
7608 }
7609 }
7610
Chris Lattnerad0124c2006-01-06 07:52:12 +00007611 // Find out if this is a shift of a shift by a constant.
Reid Spencer832254e2007-02-02 02:16:23 +00007612 BinaryOperator *ShiftOp = dyn_cast<BinaryOperator>(Op0);
7613 if (ShiftOp && !ShiftOp->isShift())
7614 ShiftOp = 0;
Chris Lattnerad0124c2006-01-06 07:52:12 +00007615
Reid Spencerb83eb642006-10-20 07:07:24 +00007616 if (ShiftOp && isa<ConstantInt>(ShiftOp->getOperand(1))) {
Reid Spencerb83eb642006-10-20 07:07:24 +00007617 ConstantInt *ShiftAmt1C = cast<ConstantInt>(ShiftOp->getOperand(1));
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00007618 uint32_t ShiftAmt1 = ShiftAmt1C->getLimitedValue(TypeBits);
7619 uint32_t ShiftAmt2 = Op1->getLimitedValue(TypeBits);
Chris Lattnerb87056f2007-02-05 00:57:54 +00007620 assert(ShiftAmt2 != 0 && "Should have been simplified earlier");
7621 if (ShiftAmt1 == 0) return 0; // Will be simplified in the future.
7622 Value *X = ShiftOp->getOperand(0);
Chris Lattnerad0124c2006-01-06 07:52:12 +00007623
Zhou Sheng4351c642007-04-02 08:20:41 +00007624 uint32_t AmtSum = ShiftAmt1+ShiftAmt2; // Fold into one big shift.
Chris Lattnerb87056f2007-02-05 00:57:54 +00007625
7626 const IntegerType *Ty = cast<IntegerType>(I.getType());
7627
7628 // Check for (X << c1) << c2 and (X >> c1) >> c2
Chris Lattner7f3da2d2007-02-03 23:28:07 +00007629 if (I.getOpcode() == ShiftOp->getOpcode()) {
Chris Lattner344c7c52009-03-20 22:41:15 +00007630 // If this is oversized composite shift, then unsigned shifts get 0, ashr
7631 // saturates.
7632 if (AmtSum >= TypeBits) {
7633 if (I.getOpcode() != Instruction::AShr)
Owen Andersona7235ea2009-07-31 20:28:14 +00007634 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner344c7c52009-03-20 22:41:15 +00007635 AmtSum = TypeBits-1; // Saturate to 31 for i32 ashr.
7636 }
7637
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007638 return BinaryOperator::Create(I.getOpcode(), X,
Owen Andersoneed707b2009-07-24 23:12:02 +00007639 ConstantInt::get(Ty, AmtSum));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007640 } else if (ShiftOp->getOpcode() == Instruction::LShr &&
7641 I.getOpcode() == Instruction::AShr) {
Chris Lattner344c7c52009-03-20 22:41:15 +00007642 if (AmtSum >= TypeBits)
Owen Andersona7235ea2009-07-31 20:28:14 +00007643 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner344c7c52009-03-20 22:41:15 +00007644
Chris Lattnerb87056f2007-02-05 00:57:54 +00007645 // ((X >>u C1) >>s C2) -> (X >>u (C1+C2)) since C1 != 0.
Owen Andersoneed707b2009-07-24 23:12:02 +00007646 return BinaryOperator::CreateLShr(X, ConstantInt::get(Ty, AmtSum));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007647 } else if (ShiftOp->getOpcode() == Instruction::AShr &&
7648 I.getOpcode() == Instruction::LShr) {
7649 // ((X >>s C1) >>u C2) -> ((X >>s (C1+C2)) & mask) since C1 != 0.
Chris Lattner344c7c52009-03-20 22:41:15 +00007650 if (AmtSum >= TypeBits)
7651 AmtSum = TypeBits-1;
7652
Chris Lattnerb87056f2007-02-05 00:57:54 +00007653 Instruction *Shift =
Owen Andersoneed707b2009-07-24 23:12:02 +00007654 BinaryOperator::CreateAShr(X, ConstantInt::get(Ty, AmtSum));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007655 InsertNewInstBefore(Shift, I);
7656
Zhou Shenge9e03f62007-03-28 15:02:20 +00007657 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Owen Andersoneed707b2009-07-24 23:12:02 +00007658 return BinaryOperator::CreateAnd(Shift, ConstantInt::get(*Context, Mask));
Chris Lattnerad0124c2006-01-06 07:52:12 +00007659 }
7660
Chris Lattnerb87056f2007-02-05 00:57:54 +00007661 // Okay, if we get here, one shift must be left, and the other shift must be
7662 // right. See if the amounts are equal.
7663 if (ShiftAmt1 == ShiftAmt2) {
7664 // If we have ((X >>? C) << C), turn this into X & (-1 << C).
7665 if (I.getOpcode() == Instruction::Shl) {
Reid Spencer55702aa2007-03-25 21:11:44 +00007666 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt1));
Owen Andersoneed707b2009-07-24 23:12:02 +00007667 return BinaryOperator::CreateAnd(X, ConstantInt::get(*Context, Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007668 }
7669 // If we have ((X << C) >>u C), turn this into X & (-1 >>u C).
7670 if (I.getOpcode() == Instruction::LShr) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00007671 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt1));
Owen Andersoneed707b2009-07-24 23:12:02 +00007672 return BinaryOperator::CreateAnd(X, ConstantInt::get(*Context, Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007673 }
7674 // We can simplify ((X << C) >>s C) into a trunc + sext.
7675 // NOTE: we could do this for any C, but that would make 'unusual' integer
7676 // types. For now, just stick to ones well-supported by the code
7677 // generators.
7678 const Type *SExtType = 0;
7679 switch (Ty->getBitWidth() - ShiftAmt1) {
Zhou Shenge9e03f62007-03-28 15:02:20 +00007680 case 1 :
7681 case 8 :
7682 case 16 :
7683 case 32 :
7684 case 64 :
7685 case 128:
Owen Andersondebcb012009-07-29 22:17:13 +00007686 SExtType = IntegerType::get(Ty->getBitWidth() - ShiftAmt1);
Zhou Shenge9e03f62007-03-28 15:02:20 +00007687 break;
Chris Lattnerb87056f2007-02-05 00:57:54 +00007688 default: break;
7689 }
7690 if (SExtType) {
7691 Instruction *NewTrunc = new TruncInst(X, SExtType, "sext");
7692 InsertNewInstBefore(NewTrunc, I);
7693 return new SExtInst(NewTrunc, Ty);
7694 }
7695 // Otherwise, we can't handle it yet.
7696 } else if (ShiftAmt1 < ShiftAmt2) {
Zhou Sheng4351c642007-04-02 08:20:41 +00007697 uint32_t ShiftDiff = ShiftAmt2-ShiftAmt1;
Chris Lattnerad0124c2006-01-06 07:52:12 +00007698
Chris Lattnerb0b991a2007-02-05 05:57:49 +00007699 // (X >>? C1) << C2 --> X << (C2-C1) & (-1 << C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00007700 if (I.getOpcode() == Instruction::Shl) {
7701 assert(ShiftOp->getOpcode() == Instruction::LShr ||
7702 ShiftOp->getOpcode() == Instruction::AShr);
Chris Lattnere8d56c52006-01-07 01:32:28 +00007703 Instruction *Shift =
Owen Andersoneed707b2009-07-24 23:12:02 +00007704 BinaryOperator::CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
Chris Lattnere8d56c52006-01-07 01:32:28 +00007705 InsertNewInstBefore(Shift, I);
7706
Reid Spencer55702aa2007-03-25 21:11:44 +00007707 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
Owen Andersoneed707b2009-07-24 23:12:02 +00007708 return BinaryOperator::CreateAnd(Shift,
7709 ConstantInt::get(*Context, Mask));
Chris Lattnerad0124c2006-01-06 07:52:12 +00007710 }
Chris Lattnerb87056f2007-02-05 00:57:54 +00007711
Chris Lattnerb0b991a2007-02-05 05:57:49 +00007712 // (X << C1) >>u C2 --> X >>u (C2-C1) & (-1 >> C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00007713 if (I.getOpcode() == Instruction::LShr) {
7714 assert(ShiftOp->getOpcode() == Instruction::Shl);
7715 Instruction *Shift =
Owen Andersoneed707b2009-07-24 23:12:02 +00007716 BinaryOperator::CreateLShr(X, ConstantInt::get(Ty, ShiftDiff));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007717 InsertNewInstBefore(Shift, I);
Chris Lattnerad0124c2006-01-06 07:52:12 +00007718
Reid Spencerd5e30f02007-03-26 17:18:58 +00007719 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Owen Andersoneed707b2009-07-24 23:12:02 +00007720 return BinaryOperator::CreateAnd(Shift,
7721 ConstantInt::get(*Context, Mask));
Chris Lattner11021cb2005-09-18 05:12:10 +00007722 }
Chris Lattnerb87056f2007-02-05 00:57:54 +00007723
7724 // We can't handle (X << C1) >>s C2, it shifts arbitrary bits in.
7725 } else {
7726 assert(ShiftAmt2 < ShiftAmt1);
Zhou Sheng4351c642007-04-02 08:20:41 +00007727 uint32_t ShiftDiff = ShiftAmt1-ShiftAmt2;
Chris Lattnerb87056f2007-02-05 00:57:54 +00007728
Chris Lattnerb0b991a2007-02-05 05:57:49 +00007729 // (X >>? C1) << C2 --> X >>? (C1-C2) & (-1 << C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00007730 if (I.getOpcode() == Instruction::Shl) {
7731 assert(ShiftOp->getOpcode() == Instruction::LShr ||
7732 ShiftOp->getOpcode() == Instruction::AShr);
7733 Instruction *Shift =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007734 BinaryOperator::Create(ShiftOp->getOpcode(), X,
Owen Andersoneed707b2009-07-24 23:12:02 +00007735 ConstantInt::get(Ty, ShiftDiff));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007736 InsertNewInstBefore(Shift, I);
7737
Reid Spencer55702aa2007-03-25 21:11:44 +00007738 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
Owen Andersoneed707b2009-07-24 23:12:02 +00007739 return BinaryOperator::CreateAnd(Shift,
7740 ConstantInt::get(*Context, Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007741 }
7742
Chris Lattnerb0b991a2007-02-05 05:57:49 +00007743 // (X << C1) >>u C2 --> X << (C1-C2) & (-1 >> C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00007744 if (I.getOpcode() == Instruction::LShr) {
7745 assert(ShiftOp->getOpcode() == Instruction::Shl);
7746 Instruction *Shift =
Owen Andersoneed707b2009-07-24 23:12:02 +00007747 BinaryOperator::CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007748 InsertNewInstBefore(Shift, I);
7749
Reid Spencer68d27cf2007-03-26 23:45:51 +00007750 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Owen Andersoneed707b2009-07-24 23:12:02 +00007751 return BinaryOperator::CreateAnd(Shift,
7752 ConstantInt::get(*Context, Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007753 }
7754
7755 // We can't handle (X << C1) >>a C2, it shifts arbitrary bits in.
Chris Lattner6e7ba452005-01-01 16:22:27 +00007756 }
Chris Lattnerad0124c2006-01-06 07:52:12 +00007757 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00007758 return 0;
7759}
7760
Chris Lattnera1be5662002-05-02 17:06:02 +00007761
Chris Lattnercfd65102005-10-29 04:36:15 +00007762/// DecomposeSimpleLinearExpr - Analyze 'Val', seeing if it is a simple linear
7763/// expression. If so, decompose it, returning some value X, such that Val is
7764/// X*Scale+Offset.
7765///
7766static Value *DecomposeSimpleLinearExpr(Value *Val, unsigned &Scale,
Owen Anderson07cf79e2009-07-06 23:00:19 +00007767 int &Offset, LLVMContext *Context) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00007768 assert(Val->getType() == Type::Int32Ty && "Unexpected allocation size type!");
Reid Spencerb83eb642006-10-20 07:07:24 +00007769 if (ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00007770 Offset = CI->getZExtValue();
Chris Lattner6a94de22007-10-12 05:30:59 +00007771 Scale = 0;
Owen Andersoneed707b2009-07-24 23:12:02 +00007772 return ConstantInt::get(Type::Int32Ty, 0);
Chris Lattner6a94de22007-10-12 05:30:59 +00007773 } else if (BinaryOperator *I = dyn_cast<BinaryOperator>(Val)) {
7774 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
7775 if (I->getOpcode() == Instruction::Shl) {
7776 // This is a value scaled by '1 << the shift amt'.
7777 Scale = 1U << RHS->getZExtValue();
7778 Offset = 0;
7779 return I->getOperand(0);
7780 } else if (I->getOpcode() == Instruction::Mul) {
7781 // This value is scaled by 'RHS'.
7782 Scale = RHS->getZExtValue();
7783 Offset = 0;
7784 return I->getOperand(0);
7785 } else if (I->getOpcode() == Instruction::Add) {
7786 // We have X+C. Check to see if we really have (X*C2)+C1,
7787 // where C1 is divisible by C2.
7788 unsigned SubScale;
7789 Value *SubVal =
Owen Andersond672ecb2009-07-03 00:17:18 +00007790 DecomposeSimpleLinearExpr(I->getOperand(0), SubScale,
7791 Offset, Context);
Chris Lattner6a94de22007-10-12 05:30:59 +00007792 Offset += RHS->getZExtValue();
7793 Scale = SubScale;
7794 return SubVal;
Chris Lattnercfd65102005-10-29 04:36:15 +00007795 }
7796 }
7797 }
7798
7799 // Otherwise, we can't look past this.
7800 Scale = 1;
7801 Offset = 0;
7802 return Val;
7803}
7804
7805
Chris Lattnerb3f83972005-10-24 06:03:58 +00007806/// PromoteCastOfAllocation - If we find a cast of an allocation instruction,
7807/// try to eliminate the cast by moving the type information into the alloc.
Chris Lattnerd3e28342007-04-27 17:44:50 +00007808Instruction *InstCombiner::PromoteCastOfAllocation(BitCastInst &CI,
Chris Lattnerb3f83972005-10-24 06:03:58 +00007809 AllocationInst &AI) {
Chris Lattnerd3e28342007-04-27 17:44:50 +00007810 const PointerType *PTy = cast<PointerType>(CI.getType());
Chris Lattnerb3f83972005-10-24 06:03:58 +00007811
Chris Lattnerb53c2382005-10-24 06:22:12 +00007812 // Remove any uses of AI that are dead.
7813 assert(!CI.use_empty() && "Dead instructions should be removed earlier!");
Chris Lattner535014f2007-02-15 22:52:10 +00007814
Chris Lattnerb53c2382005-10-24 06:22:12 +00007815 for (Value::use_iterator UI = AI.use_begin(), E = AI.use_end(); UI != E; ) {
7816 Instruction *User = cast<Instruction>(*UI++);
7817 if (isInstructionTriviallyDead(User)) {
7818 while (UI != E && *UI == User)
7819 ++UI; // If this instruction uses AI more than once, don't break UI.
7820
Chris Lattnerb53c2382005-10-24 06:22:12 +00007821 ++NumDeadInst;
Bill Wendlingb7427032006-11-26 09:46:52 +00007822 DOUT << "IC: DCE: " << *User;
Chris Lattnerf22a5c62007-03-02 19:59:19 +00007823 EraseInstFromFunction(*User);
Chris Lattnerb53c2382005-10-24 06:22:12 +00007824 }
7825 }
Dan Gohmance9fe9f2009-07-21 23:21:54 +00007826
7827 // This requires TargetData to get the alloca alignment and size information.
7828 if (!TD) return 0;
7829
Chris Lattnerb3f83972005-10-24 06:03:58 +00007830 // Get the type really allocated and the type casted to.
7831 const Type *AllocElTy = AI.getAllocatedType();
7832 const Type *CastElTy = PTy->getElementType();
7833 if (!AllocElTy->isSized() || !CastElTy->isSized()) return 0;
Chris Lattner18e78bb2005-10-24 06:26:18 +00007834
Chris Lattnerd2b7cec2007-02-14 05:52:17 +00007835 unsigned AllocElTyAlign = TD->getABITypeAlignment(AllocElTy);
7836 unsigned CastElTyAlign = TD->getABITypeAlignment(CastElTy);
Chris Lattner18e78bb2005-10-24 06:26:18 +00007837 if (CastElTyAlign < AllocElTyAlign) return 0;
7838
Chris Lattner39387a52005-10-24 06:35:18 +00007839 // If the allocation has multiple uses, only promote it if we are strictly
7840 // increasing the alignment of the resultant allocation. If we keep it the
Dale Johannesena0a66372009-03-05 00:39:02 +00007841 // same, we open the door to infinite loops of various kinds. (A reference
7842 // from a dbg.declare doesn't count as a use for this purpose.)
7843 if (!AI.hasOneUse() && !hasOneUsePlusDeclare(&AI) &&
7844 CastElTyAlign == AllocElTyAlign) return 0;
Chris Lattner39387a52005-10-24 06:35:18 +00007845
Duncan Sands777d2302009-05-09 07:06:46 +00007846 uint64_t AllocElTySize = TD->getTypeAllocSize(AllocElTy);
7847 uint64_t CastElTySize = TD->getTypeAllocSize(CastElTy);
Chris Lattner0ddac2a2005-10-27 05:53:56 +00007848 if (CastElTySize == 0 || AllocElTySize == 0) return 0;
Chris Lattner18e78bb2005-10-24 06:26:18 +00007849
Chris Lattner455fcc82005-10-29 03:19:53 +00007850 // See if we can satisfy the modulus by pulling a scale out of the array
7851 // size argument.
Jeff Cohen86796be2007-04-04 16:58:57 +00007852 unsigned ArraySizeScale;
7853 int ArrayOffset;
Chris Lattnercfd65102005-10-29 04:36:15 +00007854 Value *NumElements = // See if the array size is a decomposable linear expr.
Owen Andersond672ecb2009-07-03 00:17:18 +00007855 DecomposeSimpleLinearExpr(AI.getOperand(0), ArraySizeScale,
7856 ArrayOffset, Context);
Chris Lattnercfd65102005-10-29 04:36:15 +00007857
Chris Lattner455fcc82005-10-29 03:19:53 +00007858 // If we can now satisfy the modulus, by using a non-1 scale, we really can
7859 // do the xform.
Chris Lattnercfd65102005-10-29 04:36:15 +00007860 if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 ||
7861 (AllocElTySize*ArrayOffset ) % CastElTySize != 0) return 0;
Chris Lattner8142b0a2005-10-27 06:12:00 +00007862
Chris Lattner455fcc82005-10-29 03:19:53 +00007863 unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize;
7864 Value *Amt = 0;
7865 if (Scale == 1) {
7866 Amt = NumElements;
7867 } else {
Reid Spencerb83eb642006-10-20 07:07:24 +00007868 // If the allocation size is constant, form a constant mul expression
Owen Andersoneed707b2009-07-24 23:12:02 +00007869 Amt = ConstantInt::get(Type::Int32Ty, Scale);
Reid Spencerc5b206b2006-12-31 05:48:39 +00007870 if (isa<ConstantInt>(NumElements))
Owen Andersonbaf3c402009-07-29 18:55:55 +00007871 Amt = ConstantExpr::getMul(cast<ConstantInt>(NumElements),
Dan Gohman6de29f82009-06-15 22:12:54 +00007872 cast<ConstantInt>(Amt));
Reid Spencerb83eb642006-10-20 07:07:24 +00007873 // otherwise multiply the amount and the number of elements
Chris Lattner46d232d2009-03-17 17:55:15 +00007874 else {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007875 Instruction *Tmp = BinaryOperator::CreateMul(Amt, NumElements, "tmp");
Chris Lattner455fcc82005-10-29 03:19:53 +00007876 Amt = InsertNewInstBefore(Tmp, AI);
Chris Lattner8142b0a2005-10-27 06:12:00 +00007877 }
Chris Lattner0ddac2a2005-10-27 05:53:56 +00007878 }
7879
Jeff Cohen86796be2007-04-04 16:58:57 +00007880 if (int Offset = (AllocElTySize*ArrayOffset)/CastElTySize) {
Owen Andersoneed707b2009-07-24 23:12:02 +00007881 Value *Off = ConstantInt::get(Type::Int32Ty, Offset, true);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007882 Instruction *Tmp = BinaryOperator::CreateAdd(Amt, Off, "tmp");
Chris Lattnercfd65102005-10-29 04:36:15 +00007883 Amt = InsertNewInstBefore(Tmp, AI);
7884 }
7885
Chris Lattnerb3f83972005-10-24 06:03:58 +00007886 AllocationInst *New;
7887 if (isa<MallocInst>(AI))
Owen Anderson50dead02009-07-15 23:53:25 +00007888 New = new MallocInst(CastElTy, Amt, AI.getAlignment());
Chris Lattnerb3f83972005-10-24 06:03:58 +00007889 else
Owen Anderson50dead02009-07-15 23:53:25 +00007890 New = new AllocaInst(CastElTy, Amt, AI.getAlignment());
Chris Lattnerb3f83972005-10-24 06:03:58 +00007891 InsertNewInstBefore(New, AI);
Chris Lattner6934a042007-02-11 01:23:03 +00007892 New->takeName(&AI);
Chris Lattner39387a52005-10-24 06:35:18 +00007893
Dale Johannesena0a66372009-03-05 00:39:02 +00007894 // If the allocation has one real use plus a dbg.declare, just remove the
7895 // declare.
7896 if (DbgDeclareInst *DI = hasOneUsePlusDeclare(&AI)) {
7897 EraseInstFromFunction(*DI);
7898 }
7899 // If the allocation has multiple real uses, insert a cast and change all
7900 // things that used it to use the new cast. This will also hack on CI, but it
7901 // will die soon.
7902 else if (!AI.hasOneUse()) {
Chris Lattner39387a52005-10-24 06:35:18 +00007903 AddUsesToWorkList(AI);
Reid Spencer3da59db2006-11-27 01:05:10 +00007904 // New is the allocation instruction, pointer typed. AI is the original
7905 // allocation instruction, also pointer typed. Thus, cast to use is BitCast.
7906 CastInst *NewCast = new BitCastInst(New, AI.getType(), "tmpcast");
Chris Lattner39387a52005-10-24 06:35:18 +00007907 InsertNewInstBefore(NewCast, AI);
7908 AI.replaceAllUsesWith(NewCast);
7909 }
Chris Lattnerb3f83972005-10-24 06:03:58 +00007910 return ReplaceInstUsesWith(CI, New);
7911}
7912
Chris Lattner70074e02006-05-13 02:06:03 +00007913/// CanEvaluateInDifferentType - Return true if we can take the specified value
Chris Lattnerc739cd62007-03-03 05:27:34 +00007914/// and return it as type Ty without inserting any new casts and without
7915/// changing the computed value. This is used by code that tries to decide
7916/// whether promoting or shrinking integer operations to wider or smaller types
7917/// will allow us to eliminate a truncate or extend.
7918///
7919/// This is a truncation operation if Ty is smaller than V->getType(), or an
7920/// extension operation if Ty is larger.
Chris Lattner8114b712008-06-18 04:00:49 +00007921///
7922/// If CastOpc is a truncation, then Ty will be a type smaller than V. We
7923/// should return true if trunc(V) can be computed by computing V in the smaller
7924/// type. If V is an instruction, then trunc(inst(x,y)) can be computed as
7925/// inst(trunc(x),trunc(y)), which only makes sense if x and y can be
7926/// efficiently truncated.
7927///
7928/// If CastOpc is a sext or zext, we are asking if the low bits of the value can
7929/// bit computed in a larger type, which is then and'd or sext_in_reg'd to get
7930/// the final result.
Dan Gohman6de29f82009-06-15 22:12:54 +00007931bool InstCombiner::CanEvaluateInDifferentType(Value *V, const Type *Ty,
Evan Cheng4e56ab22009-01-16 02:11:43 +00007932 unsigned CastOpc,
7933 int &NumCastsRemoved){
Chris Lattnerc739cd62007-03-03 05:27:34 +00007934 // We can always evaluate constants in another type.
Dan Gohman6de29f82009-06-15 22:12:54 +00007935 if (isa<Constant>(V))
Chris Lattnerc739cd62007-03-03 05:27:34 +00007936 return true;
Chris Lattner70074e02006-05-13 02:06:03 +00007937
7938 Instruction *I = dyn_cast<Instruction>(V);
Chris Lattnerc739cd62007-03-03 05:27:34 +00007939 if (!I) return false;
7940
Dan Gohman6de29f82009-06-15 22:12:54 +00007941 const Type *OrigTy = V->getType();
Chris Lattner70074e02006-05-13 02:06:03 +00007942
Chris Lattner951626b2007-08-02 06:11:14 +00007943 // If this is an extension or truncate, we can often eliminate it.
7944 if (isa<TruncInst>(I) || isa<ZExtInst>(I) || isa<SExtInst>(I)) {
7945 // If this is a cast from the destination type, we can trivially eliminate
7946 // it, and this will remove a cast overall.
7947 if (I->getOperand(0)->getType() == Ty) {
7948 // If the first operand is itself a cast, and is eliminable, do not count
7949 // this as an eliminable cast. We would prefer to eliminate those two
7950 // casts first.
Chris Lattner8114b712008-06-18 04:00:49 +00007951 if (!isa<CastInst>(I->getOperand(0)) && I->hasOneUse())
Chris Lattner951626b2007-08-02 06:11:14 +00007952 ++NumCastsRemoved;
7953 return true;
7954 }
7955 }
7956
7957 // We can't extend or shrink something that has multiple uses: doing so would
7958 // require duplicating the instruction in general, which isn't profitable.
7959 if (!I->hasOneUse()) return false;
7960
Evan Chengf35fd542009-01-15 17:01:23 +00007961 unsigned Opc = I->getOpcode();
7962 switch (Opc) {
Chris Lattnerc739cd62007-03-03 05:27:34 +00007963 case Instruction::Add:
7964 case Instruction::Sub:
Nick Lewyckyb8cd6a42008-07-05 21:19:34 +00007965 case Instruction::Mul:
Chris Lattner70074e02006-05-13 02:06:03 +00007966 case Instruction::And:
7967 case Instruction::Or:
7968 case Instruction::Xor:
7969 // These operators can all arbitrarily be extended or truncated.
Chris Lattner951626b2007-08-02 06:11:14 +00007970 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00007971 NumCastsRemoved) &&
Chris Lattner951626b2007-08-02 06:11:14 +00007972 CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00007973 NumCastsRemoved);
Chris Lattnerc739cd62007-03-03 05:27:34 +00007974
Eli Friedman070a9812009-07-13 22:46:01 +00007975 case Instruction::UDiv:
7976 case Instruction::URem: {
7977 // UDiv and URem can be truncated if all the truncated bits are zero.
7978 uint32_t OrigBitWidth = OrigTy->getScalarSizeInBits();
7979 uint32_t BitWidth = Ty->getScalarSizeInBits();
7980 if (BitWidth < OrigBitWidth) {
7981 APInt Mask = APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth);
7982 if (MaskedValueIsZero(I->getOperand(0), Mask) &&
7983 MaskedValueIsZero(I->getOperand(1), Mask)) {
7984 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
7985 NumCastsRemoved) &&
7986 CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
7987 NumCastsRemoved);
7988 }
7989 }
7990 break;
7991 }
Chris Lattner46b96052006-11-29 07:18:39 +00007992 case Instruction::Shl:
Chris Lattnerc739cd62007-03-03 05:27:34 +00007993 // If we are truncating the result of this SHL, and if it's a shift of a
7994 // constant amount, we can always perform a SHL in a smaller type.
7995 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
Dan Gohman6de29f82009-06-15 22:12:54 +00007996 uint32_t BitWidth = Ty->getScalarSizeInBits();
7997 if (BitWidth < OrigTy->getScalarSizeInBits() &&
Zhou Sheng302748d2007-03-30 17:20:39 +00007998 CI->getLimitedValue(BitWidth) < BitWidth)
Chris Lattner951626b2007-08-02 06:11:14 +00007999 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00008000 NumCastsRemoved);
Chris Lattnerc739cd62007-03-03 05:27:34 +00008001 }
8002 break;
8003 case Instruction::LShr:
Chris Lattnerc739cd62007-03-03 05:27:34 +00008004 // If this is a truncate of a logical shr, we can truncate it to a smaller
8005 // lshr iff we know that the bits we would otherwise be shifting in are
8006 // already zeros.
8007 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
Dan Gohman6de29f82009-06-15 22:12:54 +00008008 uint32_t OrigBitWidth = OrigTy->getScalarSizeInBits();
8009 uint32_t BitWidth = Ty->getScalarSizeInBits();
Zhou Sheng302748d2007-03-30 17:20:39 +00008010 if (BitWidth < OrigBitWidth &&
Chris Lattnerc739cd62007-03-03 05:27:34 +00008011 MaskedValueIsZero(I->getOperand(0),
Zhou Sheng302748d2007-03-30 17:20:39 +00008012 APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth)) &&
8013 CI->getLimitedValue(BitWidth) < BitWidth) {
Chris Lattner951626b2007-08-02 06:11:14 +00008014 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00008015 NumCastsRemoved);
Chris Lattnerc739cd62007-03-03 05:27:34 +00008016 }
8017 }
Chris Lattner46b96052006-11-29 07:18:39 +00008018 break;
Reid Spencer3da59db2006-11-27 01:05:10 +00008019 case Instruction::ZExt:
8020 case Instruction::SExt:
Chris Lattner951626b2007-08-02 06:11:14 +00008021 case Instruction::Trunc:
8022 // If this is the same kind of case as our original (e.g. zext+zext), we
Chris Lattner5543a852007-08-02 17:23:38 +00008023 // can safely replace it. Note that replacing it does not reduce the number
8024 // of casts in the input.
Evan Chengf35fd542009-01-15 17:01:23 +00008025 if (Opc == CastOpc)
8026 return true;
8027
8028 // sext (zext ty1), ty2 -> zext ty2
Evan Cheng661d9c32009-01-15 17:09:07 +00008029 if (CastOpc == Instruction::SExt && Opc == Instruction::ZExt)
Chris Lattner70074e02006-05-13 02:06:03 +00008030 return true;
Reid Spencer3da59db2006-11-27 01:05:10 +00008031 break;
Nick Lewyckyb8cd6a42008-07-05 21:19:34 +00008032 case Instruction::Select: {
8033 SelectInst *SI = cast<SelectInst>(I);
8034 return CanEvaluateInDifferentType(SI->getTrueValue(), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00008035 NumCastsRemoved) &&
Nick Lewyckyb8cd6a42008-07-05 21:19:34 +00008036 CanEvaluateInDifferentType(SI->getFalseValue(), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00008037 NumCastsRemoved);
Nick Lewyckyb8cd6a42008-07-05 21:19:34 +00008038 }
Chris Lattner8114b712008-06-18 04:00:49 +00008039 case Instruction::PHI: {
8040 // We can change a phi if we can change all operands.
8041 PHINode *PN = cast<PHINode>(I);
8042 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
8043 if (!CanEvaluateInDifferentType(PN->getIncomingValue(i), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00008044 NumCastsRemoved))
Chris Lattner8114b712008-06-18 04:00:49 +00008045 return false;
8046 return true;
8047 }
Reid Spencer3da59db2006-11-27 01:05:10 +00008048 default:
Chris Lattner70074e02006-05-13 02:06:03 +00008049 // TODO: Can handle more cases here.
8050 break;
8051 }
8052
8053 return false;
8054}
8055
8056/// EvaluateInDifferentType - Given an expression that
8057/// CanEvaluateInDifferentType returns true for, actually insert the code to
8058/// evaluate the expression.
Reid Spencerc55b2432006-12-13 18:21:21 +00008059Value *InstCombiner::EvaluateInDifferentType(Value *V, const Type *Ty,
Chris Lattnerc739cd62007-03-03 05:27:34 +00008060 bool isSigned) {
Chris Lattner70074e02006-05-13 02:06:03 +00008061 if (Constant *C = dyn_cast<Constant>(V))
Owen Andersonbaf3c402009-07-29 18:55:55 +00008062 return ConstantExpr::getIntegerCast(C, Ty,
Owen Andersond672ecb2009-07-03 00:17:18 +00008063 isSigned /*Sext or ZExt*/);
Chris Lattner70074e02006-05-13 02:06:03 +00008064
8065 // Otherwise, it must be an instruction.
8066 Instruction *I = cast<Instruction>(V);
Chris Lattner01859e82006-05-20 23:14:03 +00008067 Instruction *Res = 0;
Evan Chengf35fd542009-01-15 17:01:23 +00008068 unsigned Opc = I->getOpcode();
8069 switch (Opc) {
Chris Lattnerc739cd62007-03-03 05:27:34 +00008070 case Instruction::Add:
8071 case Instruction::Sub:
Nick Lewyckye6b0c002008-01-22 05:08:48 +00008072 case Instruction::Mul:
Chris Lattner70074e02006-05-13 02:06:03 +00008073 case Instruction::And:
8074 case Instruction::Or:
Chris Lattnerc739cd62007-03-03 05:27:34 +00008075 case Instruction::Xor:
Chris Lattner46b96052006-11-29 07:18:39 +00008076 case Instruction::AShr:
8077 case Instruction::LShr:
Eli Friedman070a9812009-07-13 22:46:01 +00008078 case Instruction::Shl:
8079 case Instruction::UDiv:
8080 case Instruction::URem: {
Reid Spencerc55b2432006-12-13 18:21:21 +00008081 Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty, isSigned);
Chris Lattnerc739cd62007-03-03 05:27:34 +00008082 Value *RHS = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
Evan Chengf35fd542009-01-15 17:01:23 +00008083 Res = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
Chris Lattner46b96052006-11-29 07:18:39 +00008084 break;
8085 }
Reid Spencer3da59db2006-11-27 01:05:10 +00008086 case Instruction::Trunc:
8087 case Instruction::ZExt:
8088 case Instruction::SExt:
Reid Spencer3da59db2006-11-27 01:05:10 +00008089 // If the source type of the cast is the type we're trying for then we can
Chris Lattner951626b2007-08-02 06:11:14 +00008090 // just return the source. There's no need to insert it because it is not
8091 // new.
Chris Lattner70074e02006-05-13 02:06:03 +00008092 if (I->getOperand(0)->getType() == Ty)
8093 return I->getOperand(0);
8094
Chris Lattner8114b712008-06-18 04:00:49 +00008095 // Otherwise, must be the same type of cast, so just reinsert a new one.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008096 Res = CastInst::Create(cast<CastInst>(I)->getOpcode(), I->getOperand(0),
Chris Lattner8114b712008-06-18 04:00:49 +00008097 Ty);
Chris Lattner951626b2007-08-02 06:11:14 +00008098 break;
Nick Lewyckyb8cd6a42008-07-05 21:19:34 +00008099 case Instruction::Select: {
8100 Value *True = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
8101 Value *False = EvaluateInDifferentType(I->getOperand(2), Ty, isSigned);
8102 Res = SelectInst::Create(I->getOperand(0), True, False);
8103 break;
8104 }
Chris Lattner8114b712008-06-18 04:00:49 +00008105 case Instruction::PHI: {
8106 PHINode *OPN = cast<PHINode>(I);
8107 PHINode *NPN = PHINode::Create(Ty);
8108 for (unsigned i = 0, e = OPN->getNumIncomingValues(); i != e; ++i) {
8109 Value *V =EvaluateInDifferentType(OPN->getIncomingValue(i), Ty, isSigned);
8110 NPN->addIncoming(V, OPN->getIncomingBlock(i));
8111 }
8112 Res = NPN;
8113 break;
8114 }
Reid Spencer3da59db2006-11-27 01:05:10 +00008115 default:
Chris Lattner70074e02006-05-13 02:06:03 +00008116 // TODO: Can handle more cases here.
Torok Edwinc23197a2009-07-14 16:55:14 +00008117 llvm_unreachable("Unreachable!");
Chris Lattner70074e02006-05-13 02:06:03 +00008118 break;
8119 }
8120
Chris Lattner8114b712008-06-18 04:00:49 +00008121 Res->takeName(I);
Chris Lattner70074e02006-05-13 02:06:03 +00008122 return InsertNewInstBefore(Res, *I);
8123}
8124
Reid Spencer3da59db2006-11-27 01:05:10 +00008125/// @brief Implement the transforms common to all CastInst visitors.
8126Instruction *InstCombiner::commonCastTransforms(CastInst &CI) {
Chris Lattner79d35b32003-06-23 21:59:52 +00008127 Value *Src = CI.getOperand(0);
8128
Dan Gohman23d9d272007-05-11 21:10:54 +00008129 // Many cases of "cast of a cast" are eliminable. If it's eliminable we just
Reid Spencer3da59db2006-11-27 01:05:10 +00008130 // eliminate it now.
Chris Lattner6e7ba452005-01-01 16:22:27 +00008131 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
Reid Spencer3da59db2006-11-27 01:05:10 +00008132 if (Instruction::CastOps opc =
8133 isEliminableCastPair(CSrc, CI.getOpcode(), CI.getType(), TD)) {
8134 // The first cast (CSrc) is eliminable so we need to fix up or replace
8135 // the second cast (CI). CSrc will then have a good chance of being dead.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008136 return CastInst::Create(opc, CSrc->getOperand(0), CI.getType());
Chris Lattner8fd217c2002-08-02 20:00:25 +00008137 }
8138 }
Chris Lattnera710ddc2004-05-25 04:29:21 +00008139
Reid Spencer3da59db2006-11-27 01:05:10 +00008140 // If we are casting a select then fold the cast into the select
Chris Lattner6e7ba452005-01-01 16:22:27 +00008141 if (SelectInst *SI = dyn_cast<SelectInst>(Src))
8142 if (Instruction *NV = FoldOpIntoSelect(CI, SI, this))
8143 return NV;
Reid Spencer3da59db2006-11-27 01:05:10 +00008144
8145 // If we are casting a PHI then fold the cast into the PHI
Chris Lattner4e998b22004-09-29 05:07:12 +00008146 if (isa<PHINode>(Src))
8147 if (Instruction *NV = FoldOpIntoPhi(CI))
8148 return NV;
Chris Lattner9fb92132006-04-12 18:09:35 +00008149
Reid Spencer3da59db2006-11-27 01:05:10 +00008150 return 0;
8151}
8152
Chris Lattner46cd5a12009-01-09 05:44:56 +00008153/// FindElementAtOffset - Given a type and a constant offset, determine whether
8154/// or not there is a sequence of GEP indices into the type that will land us at
Chris Lattner3914f722009-01-24 01:00:13 +00008155/// the specified offset. If so, fill them into NewIndices and return the
8156/// resultant element type, otherwise return null.
8157static const Type *FindElementAtOffset(const Type *Ty, int64_t Offset,
8158 SmallVectorImpl<Value*> &NewIndices,
Owen Andersond672ecb2009-07-03 00:17:18 +00008159 const TargetData *TD,
Owen Anderson07cf79e2009-07-06 23:00:19 +00008160 LLVMContext *Context) {
Dan Gohmance9fe9f2009-07-21 23:21:54 +00008161 if (!TD) return 0;
Chris Lattner3914f722009-01-24 01:00:13 +00008162 if (!Ty->isSized()) return 0;
Chris Lattner46cd5a12009-01-09 05:44:56 +00008163
8164 // Start with the index over the outer type. Note that the type size
8165 // might be zero (even if the offset isn't zero) if the indexed type
8166 // is something like [0 x {int, int}]
8167 const Type *IntPtrTy = TD->getIntPtrType();
8168 int64_t FirstIdx = 0;
Duncan Sands777d2302009-05-09 07:06:46 +00008169 if (int64_t TySize = TD->getTypeAllocSize(Ty)) {
Chris Lattner46cd5a12009-01-09 05:44:56 +00008170 FirstIdx = Offset/TySize;
Chris Lattner31a69cb2009-01-11 20:41:36 +00008171 Offset -= FirstIdx*TySize;
Chris Lattner46cd5a12009-01-09 05:44:56 +00008172
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00008173 // Handle hosts where % returns negative instead of values [0..TySize).
Chris Lattner46cd5a12009-01-09 05:44:56 +00008174 if (Offset < 0) {
8175 --FirstIdx;
8176 Offset += TySize;
8177 assert(Offset >= 0);
8178 }
8179 assert((uint64_t)Offset < (uint64_t)TySize && "Out of range offset");
8180 }
8181
Owen Andersoneed707b2009-07-24 23:12:02 +00008182 NewIndices.push_back(ConstantInt::get(IntPtrTy, FirstIdx));
Chris Lattner46cd5a12009-01-09 05:44:56 +00008183
8184 // Index into the types. If we fail, set OrigBase to null.
8185 while (Offset) {
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00008186 // Indexing into tail padding between struct/array elements.
8187 if (uint64_t(Offset*8) >= TD->getTypeSizeInBits(Ty))
Chris Lattner3914f722009-01-24 01:00:13 +00008188 return 0;
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00008189
Chris Lattner46cd5a12009-01-09 05:44:56 +00008190 if (const StructType *STy = dyn_cast<StructType>(Ty)) {
8191 const StructLayout *SL = TD->getStructLayout(STy);
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00008192 assert(Offset < (int64_t)SL->getSizeInBytes() &&
8193 "Offset must stay within the indexed type");
8194
Chris Lattner46cd5a12009-01-09 05:44:56 +00008195 unsigned Elt = SL->getElementContainingOffset(Offset);
Owen Andersoneed707b2009-07-24 23:12:02 +00008196 NewIndices.push_back(ConstantInt::get(Type::Int32Ty, Elt));
Chris Lattner46cd5a12009-01-09 05:44:56 +00008197
8198 Offset -= SL->getElementOffset(Elt);
8199 Ty = STy->getElementType(Elt);
Chris Lattner1c412d92009-01-11 20:23:52 +00008200 } else if (const ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
Duncan Sands777d2302009-05-09 07:06:46 +00008201 uint64_t EltSize = TD->getTypeAllocSize(AT->getElementType());
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00008202 assert(EltSize && "Cannot index into a zero-sized array");
Owen Andersoneed707b2009-07-24 23:12:02 +00008203 NewIndices.push_back(ConstantInt::get(IntPtrTy,Offset/EltSize));
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00008204 Offset %= EltSize;
Chris Lattner1c412d92009-01-11 20:23:52 +00008205 Ty = AT->getElementType();
Chris Lattner46cd5a12009-01-09 05:44:56 +00008206 } else {
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00008207 // Otherwise, we can't index into the middle of this atomic type, bail.
Chris Lattner3914f722009-01-24 01:00:13 +00008208 return 0;
Chris Lattner46cd5a12009-01-09 05:44:56 +00008209 }
8210 }
8211
Chris Lattner3914f722009-01-24 01:00:13 +00008212 return Ty;
Chris Lattner46cd5a12009-01-09 05:44:56 +00008213}
8214
Chris Lattnerd3e28342007-04-27 17:44:50 +00008215/// @brief Implement the transforms for cast of pointer (bitcast/ptrtoint)
8216Instruction *InstCombiner::commonPointerCastTransforms(CastInst &CI) {
8217 Value *Src = CI.getOperand(0);
8218
Chris Lattnerd3e28342007-04-27 17:44:50 +00008219 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
Chris Lattner9bc14642007-04-28 00:57:34 +00008220 // If casting the result of a getelementptr instruction with no offset, turn
8221 // this into a cast of the original pointer!
Chris Lattnerd3e28342007-04-27 17:44:50 +00008222 if (GEP->hasAllZeroIndices()) {
8223 // Changing the cast operand is usually not a good idea but it is safe
8224 // here because the pointer operand is being replaced with another
8225 // pointer operand so the opcode doesn't need to change.
Chris Lattner9bc14642007-04-28 00:57:34 +00008226 AddToWorkList(GEP);
Chris Lattnerd3e28342007-04-27 17:44:50 +00008227 CI.setOperand(0, GEP->getOperand(0));
8228 return &CI;
8229 }
Chris Lattner9bc14642007-04-28 00:57:34 +00008230
8231 // If the GEP has a single use, and the base pointer is a bitcast, and the
8232 // GEP computes a constant offset, see if we can convert these three
8233 // instructions into fewer. This typically happens with unions and other
8234 // non-type-safe code.
Dan Gohmance9fe9f2009-07-21 23:21:54 +00008235 if (TD && GEP->hasOneUse() && isa<BitCastInst>(GEP->getOperand(0))) {
Chris Lattner9bc14642007-04-28 00:57:34 +00008236 if (GEP->hasAllConstantIndices()) {
8237 // We are guaranteed to get a constant from EmitGEPOffset.
Owen Andersond672ecb2009-07-03 00:17:18 +00008238 ConstantInt *OffsetV =
8239 cast<ConstantInt>(EmitGEPOffset(GEP, CI, *this));
Chris Lattner9bc14642007-04-28 00:57:34 +00008240 int64_t Offset = OffsetV->getSExtValue();
8241
8242 // Get the base pointer input of the bitcast, and the type it points to.
8243 Value *OrigBase = cast<BitCastInst>(GEP->getOperand(0))->getOperand(0);
8244 const Type *GEPIdxTy =
8245 cast<PointerType>(OrigBase->getType())->getElementType();
Chris Lattner46cd5a12009-01-09 05:44:56 +00008246 SmallVector<Value*, 8> NewIndices;
Owen Andersond672ecb2009-07-03 00:17:18 +00008247 if (FindElementAtOffset(GEPIdxTy, Offset, NewIndices, TD, Context)) {
Chris Lattner46cd5a12009-01-09 05:44:56 +00008248 // If we were able to index down into an element, create the GEP
8249 // and bitcast the result. This eliminates one bitcast, potentially
8250 // two.
8251 Instruction *NGEP = GetElementPtrInst::Create(OrigBase,
8252 NewIndices.begin(),
8253 NewIndices.end(), "");
8254 InsertNewInstBefore(NGEP, CI);
8255 NGEP->takeName(GEP);
Dan Gohmand6aa02d2009-07-28 01:40:03 +00008256 if (cast<GEPOperator>(GEP)->isInBounds())
8257 cast<GEPOperator>(NGEP)->setIsInBounds(true);
Chris Lattner9bc14642007-04-28 00:57:34 +00008258
Chris Lattner46cd5a12009-01-09 05:44:56 +00008259 if (isa<BitCastInst>(CI))
8260 return new BitCastInst(NGEP, CI.getType());
8261 assert(isa<PtrToIntInst>(CI));
8262 return new PtrToIntInst(NGEP, CI.getType());
Chris Lattner9bc14642007-04-28 00:57:34 +00008263 }
8264 }
8265 }
Chris Lattnerd3e28342007-04-27 17:44:50 +00008266 }
8267
8268 return commonCastTransforms(CI);
8269}
8270
Chris Lattnerddfa57b2009-04-08 05:41:03 +00008271/// isSafeIntegerType - Return true if this is a basic integer type, not a crazy
8272/// type like i42. We don't want to introduce operations on random non-legal
8273/// integer types where they don't already exist in the code. In the future,
8274/// we should consider making this based off target-data, so that 32-bit targets
8275/// won't get i64 operations etc.
8276static bool isSafeIntegerType(const Type *Ty) {
8277 switch (Ty->getPrimitiveSizeInBits()) {
8278 case 8:
8279 case 16:
8280 case 32:
8281 case 64:
8282 return true;
8283 default:
8284 return false;
8285 }
8286}
Chris Lattnerd3e28342007-04-27 17:44:50 +00008287
Eli Friedmaneb7f7a82009-07-13 20:58:59 +00008288/// commonIntCastTransforms - This function implements the common transforms
8289/// for trunc, zext, and sext.
Reid Spencer3da59db2006-11-27 01:05:10 +00008290Instruction *InstCombiner::commonIntCastTransforms(CastInst &CI) {
8291 if (Instruction *Result = commonCastTransforms(CI))
8292 return Result;
8293
8294 Value *Src = CI.getOperand(0);
8295 const Type *SrcTy = Src->getType();
8296 const Type *DestTy = CI.getType();
Dan Gohman6de29f82009-06-15 22:12:54 +00008297 uint32_t SrcBitSize = SrcTy->getScalarSizeInBits();
8298 uint32_t DestBitSize = DestTy->getScalarSizeInBits();
Reid Spencer3da59db2006-11-27 01:05:10 +00008299
Reid Spencer3da59db2006-11-27 01:05:10 +00008300 // See if we can simplify any instructions used by the LHS whose sole
8301 // purpose is to compute bits we don't care about.
Chris Lattner886ab6c2009-01-31 08:15:18 +00008302 if (SimplifyDemandedInstructionBits(CI))
Reid Spencer3da59db2006-11-27 01:05:10 +00008303 return &CI;
8304
8305 // If the source isn't an instruction or has more than one use then we
8306 // can't do anything more.
Reid Spencere4d87aa2006-12-23 06:05:41 +00008307 Instruction *SrcI = dyn_cast<Instruction>(Src);
8308 if (!SrcI || !Src->hasOneUse())
Reid Spencer3da59db2006-11-27 01:05:10 +00008309 return 0;
8310
Chris Lattnerc739cd62007-03-03 05:27:34 +00008311 // Attempt to propagate the cast into the instruction for int->int casts.
Reid Spencer3da59db2006-11-27 01:05:10 +00008312 int NumCastsRemoved = 0;
Eli Friedman65445c52009-07-13 21:45:57 +00008313 // Only do this if the dest type is a simple type, don't convert the
8314 // expression tree to something weird like i93 unless the source is also
8315 // strange.
8316 if ((isSafeIntegerType(DestTy->getScalarType()) ||
Dan Gohman6de29f82009-06-15 22:12:54 +00008317 !isSafeIntegerType(SrcI->getType()->getScalarType())) &&
8318 CanEvaluateInDifferentType(SrcI, DestTy,
Evan Cheng4e56ab22009-01-16 02:11:43 +00008319 CI.getOpcode(), NumCastsRemoved)) {
Reid Spencer3da59db2006-11-27 01:05:10 +00008320 // If this cast is a truncate, evaluting in a different type always
Chris Lattner951626b2007-08-02 06:11:14 +00008321 // eliminates the cast, so it is always a win. If this is a zero-extension,
8322 // we need to do an AND to maintain the clear top-part of the computation,
8323 // so we require that the input have eliminated at least one cast. If this
8324 // is a sign extension, we insert two new casts (to do the extension) so we
Reid Spencer3da59db2006-11-27 01:05:10 +00008325 // require that two casts have been eliminated.
Evan Chengf35fd542009-01-15 17:01:23 +00008326 bool DoXForm = false;
8327 bool JustReplace = false;
Chris Lattnerc739cd62007-03-03 05:27:34 +00008328 switch (CI.getOpcode()) {
8329 default:
8330 // All the others use floating point so we shouldn't actually
8331 // get here because of the check above.
Torok Edwinc23197a2009-07-14 16:55:14 +00008332 llvm_unreachable("Unknown cast type");
Chris Lattnerc739cd62007-03-03 05:27:34 +00008333 case Instruction::Trunc:
8334 DoXForm = true;
8335 break;
Evan Cheng4e56ab22009-01-16 02:11:43 +00008336 case Instruction::ZExt: {
Chris Lattnerc739cd62007-03-03 05:27:34 +00008337 DoXForm = NumCastsRemoved >= 1;
Chris Lattner39c27ed2009-01-31 19:05:27 +00008338 if (!DoXForm && 0) {
Evan Cheng4e56ab22009-01-16 02:11:43 +00008339 // If it's unnecessary to issue an AND to clear the high bits, it's
8340 // always profitable to do this xform.
Chris Lattner39c27ed2009-01-31 19:05:27 +00008341 Value *TryRes = EvaluateInDifferentType(SrcI, DestTy, false);
Evan Cheng4e56ab22009-01-16 02:11:43 +00008342 APInt Mask(APInt::getBitsSet(DestBitSize, SrcBitSize, DestBitSize));
8343 if (MaskedValueIsZero(TryRes, Mask))
8344 return ReplaceInstUsesWith(CI, TryRes);
Chris Lattner39c27ed2009-01-31 19:05:27 +00008345
8346 if (Instruction *TryI = dyn_cast<Instruction>(TryRes))
Evan Cheng4e56ab22009-01-16 02:11:43 +00008347 if (TryI->use_empty())
8348 EraseInstFromFunction(*TryI);
8349 }
Chris Lattnerc739cd62007-03-03 05:27:34 +00008350 break;
Evan Cheng4e56ab22009-01-16 02:11:43 +00008351 }
Evan Chengf35fd542009-01-15 17:01:23 +00008352 case Instruction::SExt: {
Chris Lattnerc739cd62007-03-03 05:27:34 +00008353 DoXForm = NumCastsRemoved >= 2;
Chris Lattner39c27ed2009-01-31 19:05:27 +00008354 if (!DoXForm && !isa<TruncInst>(SrcI) && 0) {
Evan Cheng4e56ab22009-01-16 02:11:43 +00008355 // If we do not have to emit the truncate + sext pair, then it's always
8356 // profitable to do this xform.
Evan Chengf35fd542009-01-15 17:01:23 +00008357 //
8358 // It's not safe to eliminate the trunc + sext pair if one of the
8359 // eliminated cast is a truncate. e.g.
8360 // t2 = trunc i32 t1 to i16
8361 // t3 = sext i16 t2 to i32
8362 // !=
8363 // i32 t1
Chris Lattner39c27ed2009-01-31 19:05:27 +00008364 Value *TryRes = EvaluateInDifferentType(SrcI, DestTy, true);
Evan Cheng4e56ab22009-01-16 02:11:43 +00008365 unsigned NumSignBits = ComputeNumSignBits(TryRes);
8366 if (NumSignBits > (DestBitSize - SrcBitSize))
8367 return ReplaceInstUsesWith(CI, TryRes);
Chris Lattner39c27ed2009-01-31 19:05:27 +00008368
8369 if (Instruction *TryI = dyn_cast<Instruction>(TryRes))
Evan Cheng4e56ab22009-01-16 02:11:43 +00008370 if (TryI->use_empty())
8371 EraseInstFromFunction(*TryI);
Evan Chengf35fd542009-01-15 17:01:23 +00008372 }
Chris Lattnerc739cd62007-03-03 05:27:34 +00008373 break;
Reid Spencer3da59db2006-11-27 01:05:10 +00008374 }
Evan Chengf35fd542009-01-15 17:01:23 +00008375 }
Reid Spencer3da59db2006-11-27 01:05:10 +00008376
8377 if (DoXForm) {
Chris Lattner39c27ed2009-01-31 19:05:27 +00008378 DOUT << "ICE: EvaluateInDifferentType converting expression type to avoid"
8379 << " cast: " << CI;
Reid Spencerc55b2432006-12-13 18:21:21 +00008380 Value *Res = EvaluateInDifferentType(SrcI, DestTy,
8381 CI.getOpcode() == Instruction::SExt);
Evan Cheng4e56ab22009-01-16 02:11:43 +00008382 if (JustReplace)
Chris Lattner39c27ed2009-01-31 19:05:27 +00008383 // Just replace this cast with the result.
8384 return ReplaceInstUsesWith(CI, Res);
Evan Cheng4e56ab22009-01-16 02:11:43 +00008385
Reid Spencer3da59db2006-11-27 01:05:10 +00008386 assert(Res->getType() == DestTy);
8387 switch (CI.getOpcode()) {
Torok Edwinc23197a2009-07-14 16:55:14 +00008388 default: llvm_unreachable("Unknown cast type!");
Reid Spencer3da59db2006-11-27 01:05:10 +00008389 case Instruction::Trunc:
Reid Spencer3da59db2006-11-27 01:05:10 +00008390 // Just replace this cast with the result.
8391 return ReplaceInstUsesWith(CI, Res);
8392 case Instruction::ZExt: {
Reid Spencer3da59db2006-11-27 01:05:10 +00008393 assert(SrcBitSize < DestBitSize && "Not a zext?");
Evan Cheng4e56ab22009-01-16 02:11:43 +00008394
8395 // If the high bits are already zero, just replace this cast with the
8396 // result.
8397 APInt Mask(APInt::getBitsSet(DestBitSize, SrcBitSize, DestBitSize));
8398 if (MaskedValueIsZero(Res, Mask))
8399 return ReplaceInstUsesWith(CI, Res);
8400
8401 // We need to emit an AND to clear the high bits.
Owen Andersoneed707b2009-07-24 23:12:02 +00008402 Constant *C = ConstantInt::get(*Context,
8403 APInt::getLowBitsSet(DestBitSize, SrcBitSize));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008404 return BinaryOperator::CreateAnd(Res, C);
Reid Spencer3da59db2006-11-27 01:05:10 +00008405 }
Evan Cheng4e56ab22009-01-16 02:11:43 +00008406 case Instruction::SExt: {
8407 // If the high bits are already filled with sign bit, just replace this
8408 // cast with the result.
8409 unsigned NumSignBits = ComputeNumSignBits(Res);
8410 if (NumSignBits > (DestBitSize - SrcBitSize))
Evan Chengf35fd542009-01-15 17:01:23 +00008411 return ReplaceInstUsesWith(CI, Res);
8412
Reid Spencer3da59db2006-11-27 01:05:10 +00008413 // We need to emit a cast to truncate, then a cast to sext.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008414 return CastInst::Create(Instruction::SExt,
Reid Spencer17212df2006-12-12 09:18:51 +00008415 InsertCastBefore(Instruction::Trunc, Res, Src->getType(),
8416 CI), DestTy);
Reid Spencer3da59db2006-11-27 01:05:10 +00008417 }
Evan Cheng4e56ab22009-01-16 02:11:43 +00008418 }
Reid Spencer3da59db2006-11-27 01:05:10 +00008419 }
8420 }
8421
8422 Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
8423 Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
8424
8425 switch (SrcI->getOpcode()) {
8426 case Instruction::Add:
8427 case Instruction::Mul:
8428 case Instruction::And:
8429 case Instruction::Or:
8430 case Instruction::Xor:
Chris Lattner01deb9d2007-04-03 17:43:25 +00008431 // If we are discarding information, rewrite.
Eli Friedman65445c52009-07-13 21:45:57 +00008432 if (DestBitSize < SrcBitSize && DestBitSize != 1) {
8433 // Don't insert two casts unless at least one can be eliminated.
8434 if (!ValueRequiresCast(CI.getOpcode(), Op1, DestTy, TD) ||
Reid Spencere4d87aa2006-12-23 06:05:41 +00008435 !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
Eli Friedman65445c52009-07-13 21:45:57 +00008436 Value *Op0c = InsertCastBefore(Instruction::Trunc, Op0, DestTy, *SrcI);
8437 Value *Op1c = InsertCastBefore(Instruction::Trunc, Op1, DestTy, *SrcI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008438 return BinaryOperator::Create(
Reid Spencer17212df2006-12-12 09:18:51 +00008439 cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
Reid Spencer3da59db2006-11-27 01:05:10 +00008440 }
8441 }
8442
8443 // cast (xor bool X, true) to int --> xor (cast bool X to int), 1
8444 if (isa<ZExtInst>(CI) && SrcBitSize == 1 &&
8445 SrcI->getOpcode() == Instruction::Xor &&
Owen Anderson5defacc2009-07-31 17:39:07 +00008446 Op1 == ConstantInt::getTrue(*Context) &&
Reid Spencere4d87aa2006-12-23 06:05:41 +00008447 (!Op0->hasOneUse() || !isa<CmpInst>(Op0))) {
Eli Friedmand1fd1da2008-11-30 21:09:11 +00008448 Value *New = InsertCastBefore(Instruction::ZExt, Op0, DestTy, CI);
Owen Andersond672ecb2009-07-03 00:17:18 +00008449 return BinaryOperator::CreateXor(New,
Owen Andersoneed707b2009-07-24 23:12:02 +00008450 ConstantInt::get(CI.getType(), 1));
Reid Spencer3da59db2006-11-27 01:05:10 +00008451 }
8452 break;
Reid Spencer3da59db2006-11-27 01:05:10 +00008453
Eli Friedman65445c52009-07-13 21:45:57 +00008454 case Instruction::Shl: {
8455 // Canonicalize trunc inside shl, if we can.
8456 ConstantInt *CI = dyn_cast<ConstantInt>(Op1);
8457 if (CI && DestBitSize < SrcBitSize &&
8458 CI->getLimitedValue(DestBitSize) < DestBitSize) {
8459 Value *Op0c = InsertCastBefore(Instruction::Trunc, Op0, DestTy, *SrcI);
8460 Value *Op1c = InsertCastBefore(Instruction::Trunc, Op1, DestTy, *SrcI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008461 return BinaryOperator::CreateShl(Op0c, Op1c);
Reid Spencer3da59db2006-11-27 01:05:10 +00008462 }
8463 break;
Eli Friedman65445c52009-07-13 21:45:57 +00008464 }
Reid Spencer3da59db2006-11-27 01:05:10 +00008465 }
8466 return 0;
8467}
8468
Chris Lattner8a9f5712007-04-11 06:57:46 +00008469Instruction *InstCombiner::visitTrunc(TruncInst &CI) {
Chris Lattner6aa5eb12006-11-29 07:04:07 +00008470 if (Instruction *Result = commonIntCastTransforms(CI))
8471 return Result;
8472
8473 Value *Src = CI.getOperand(0);
8474 const Type *Ty = CI.getType();
Dan Gohman6de29f82009-06-15 22:12:54 +00008475 uint32_t DestBitWidth = Ty->getScalarSizeInBits();
8476 uint32_t SrcBitWidth = Src->getType()->getScalarSizeInBits();
Chris Lattner4f9797d2009-03-24 18:15:30 +00008477
8478 // Canonicalize trunc x to i1 -> (icmp ne (and x, 1), 0)
Eli Friedman191a0ae2009-07-18 09:21:25 +00008479 if (DestBitWidth == 1) {
Owen Andersoneed707b2009-07-24 23:12:02 +00008480 Constant *One = ConstantInt::get(Src->getType(), 1);
Chris Lattner4f9797d2009-03-24 18:15:30 +00008481 Src = InsertNewInstBefore(BinaryOperator::CreateAnd(Src, One, "tmp"), CI);
Owen Andersona7235ea2009-07-31 20:28:14 +00008482 Value *Zero = Constant::getNullValue(Src->getType());
Owen Anderson333c4002009-07-09 23:48:35 +00008483 return new ICmpInst(*Context, ICmpInst::ICMP_NE, Src, Zero);
Chris Lattner4f9797d2009-03-24 18:15:30 +00008484 }
Dan Gohman6de29f82009-06-15 22:12:54 +00008485
Chris Lattner4f9797d2009-03-24 18:15:30 +00008486 // Optimize trunc(lshr(), c) to pull the shift through the truncate.
8487 ConstantInt *ShAmtV = 0;
8488 Value *ShiftOp = 0;
8489 if (Src->hasOneUse() &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00008490 match(Src, m_LShr(m_Value(ShiftOp), m_ConstantInt(ShAmtV)), *Context)) {
Chris Lattner4f9797d2009-03-24 18:15:30 +00008491 uint32_t ShAmt = ShAmtV->getLimitedValue(SrcBitWidth);
8492
8493 // Get a mask for the bits shifting in.
8494 APInt Mask(APInt::getLowBitsSet(SrcBitWidth, ShAmt).shl(DestBitWidth));
8495 if (MaskedValueIsZero(ShiftOp, Mask)) {
8496 if (ShAmt >= DestBitWidth) // All zeros.
Owen Andersona7235ea2009-07-31 20:28:14 +00008497 return ReplaceInstUsesWith(CI, Constant::getNullValue(Ty));
Chris Lattner4f9797d2009-03-24 18:15:30 +00008498
8499 // Okay, we can shrink this. Truncate the input, then return a new
8500 // shift.
8501 Value *V1 = InsertCastBefore(Instruction::Trunc, ShiftOp, Ty, CI);
Owen Andersonbaf3c402009-07-29 18:55:55 +00008502 Value *V2 = ConstantExpr::getTrunc(ShAmtV, Ty);
Chris Lattner4f9797d2009-03-24 18:15:30 +00008503 return BinaryOperator::CreateLShr(V1, V2);
Chris Lattner6aa5eb12006-11-29 07:04:07 +00008504 }
8505 }
8506
8507 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00008508}
8509
Evan Chengb98a10e2008-03-24 00:21:34 +00008510/// transformZExtICmp - Transform (zext icmp) to bitwise / integer operations
8511/// in order to eliminate the icmp.
8512Instruction *InstCombiner::transformZExtICmp(ICmpInst *ICI, Instruction &CI,
8513 bool DoXform) {
8514 // If we are just checking for a icmp eq of a single bit and zext'ing it
8515 // to an integer, then shift the bit to the appropriate place and then
8516 // cast to integer to avoid the comparison.
8517 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
8518 const APInt &Op1CV = Op1C->getValue();
8519
8520 // zext (x <s 0) to i32 --> x>>u31 true if signbit set.
8521 // zext (x >s -1) to i32 --> (x>>u31)^1 true if signbit clear.
8522 if ((ICI->getPredicate() == ICmpInst::ICMP_SLT && Op1CV == 0) ||
8523 (ICI->getPredicate() == ICmpInst::ICMP_SGT &&Op1CV.isAllOnesValue())) {
8524 if (!DoXform) return ICI;
8525
8526 Value *In = ICI->getOperand(0);
Owen Andersoneed707b2009-07-24 23:12:02 +00008527 Value *Sh = ConstantInt::get(In->getType(),
Dan Gohman6de29f82009-06-15 22:12:54 +00008528 In->getType()->getScalarSizeInBits()-1);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008529 In = InsertNewInstBefore(BinaryOperator::CreateLShr(In, Sh,
Evan Chengb98a10e2008-03-24 00:21:34 +00008530 In->getName()+".lobit"),
8531 CI);
8532 if (In->getType() != CI.getType())
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008533 In = CastInst::CreateIntegerCast(In, CI.getType(),
Evan Chengb98a10e2008-03-24 00:21:34 +00008534 false/*ZExt*/, "tmp", &CI);
8535
8536 if (ICI->getPredicate() == ICmpInst::ICMP_SGT) {
Owen Andersoneed707b2009-07-24 23:12:02 +00008537 Constant *One = ConstantInt::get(In->getType(), 1);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008538 In = InsertNewInstBefore(BinaryOperator::CreateXor(In, One,
Evan Chengb98a10e2008-03-24 00:21:34 +00008539 In->getName()+".not"),
8540 CI);
8541 }
8542
8543 return ReplaceInstUsesWith(CI, In);
8544 }
8545
8546
8547
8548 // zext (X == 0) to i32 --> X^1 iff X has only the low bit set.
8549 // zext (X == 0) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
8550 // zext (X == 1) to i32 --> X iff X has only the low bit set.
8551 // zext (X == 2) to i32 --> X>>1 iff X has only the 2nd bit set.
8552 // zext (X != 0) to i32 --> X iff X has only the low bit set.
8553 // zext (X != 0) to i32 --> X>>1 iff X has only the 2nd bit set.
8554 // zext (X != 1) to i32 --> X^1 iff X has only the low bit set.
8555 // zext (X != 2) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
8556 if ((Op1CV == 0 || Op1CV.isPowerOf2()) &&
8557 // This only works for EQ and NE
8558 ICI->isEquality()) {
8559 // If Op1C some other power of two, convert:
8560 uint32_t BitWidth = Op1C->getType()->getBitWidth();
8561 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
8562 APInt TypeMask(APInt::getAllOnesValue(BitWidth));
8563 ComputeMaskedBits(ICI->getOperand(0), TypeMask, KnownZero, KnownOne);
8564
8565 APInt KnownZeroMask(~KnownZero);
8566 if (KnownZeroMask.isPowerOf2()) { // Exactly 1 possible 1?
8567 if (!DoXform) return ICI;
8568
8569 bool isNE = ICI->getPredicate() == ICmpInst::ICMP_NE;
8570 if (Op1CV != 0 && (Op1CV != KnownZeroMask)) {
8571 // (X&4) == 2 --> false
8572 // (X&4) != 2 --> true
Owen Andersoneed707b2009-07-24 23:12:02 +00008573 Constant *Res = ConstantInt::get(Type::Int1Ty, isNE);
Owen Andersonbaf3c402009-07-29 18:55:55 +00008574 Res = ConstantExpr::getZExt(Res, CI.getType());
Evan Chengb98a10e2008-03-24 00:21:34 +00008575 return ReplaceInstUsesWith(CI, Res);
8576 }
8577
8578 uint32_t ShiftAmt = KnownZeroMask.logBase2();
8579 Value *In = ICI->getOperand(0);
8580 if (ShiftAmt) {
8581 // Perform a logical shr by shiftamt.
8582 // Insert the shift to put the result in the low bit.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008583 In = InsertNewInstBefore(BinaryOperator::CreateLShr(In,
Owen Andersoneed707b2009-07-24 23:12:02 +00008584 ConstantInt::get(In->getType(), ShiftAmt),
Evan Chengb98a10e2008-03-24 00:21:34 +00008585 In->getName()+".lobit"), CI);
8586 }
8587
8588 if ((Op1CV != 0) == isNE) { // Toggle the low bit.
Owen Andersoneed707b2009-07-24 23:12:02 +00008589 Constant *One = ConstantInt::get(In->getType(), 1);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008590 In = BinaryOperator::CreateXor(In, One, "tmp");
Evan Chengb98a10e2008-03-24 00:21:34 +00008591 InsertNewInstBefore(cast<Instruction>(In), CI);
8592 }
8593
8594 if (CI.getType() == In->getType())
8595 return ReplaceInstUsesWith(CI, In);
8596 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008597 return CastInst::CreateIntegerCast(In, CI.getType(), false/*ZExt*/);
Evan Chengb98a10e2008-03-24 00:21:34 +00008598 }
8599 }
8600 }
8601
8602 return 0;
8603}
8604
Chris Lattner8a9f5712007-04-11 06:57:46 +00008605Instruction *InstCombiner::visitZExt(ZExtInst &CI) {
Reid Spencer3da59db2006-11-27 01:05:10 +00008606 // If one of the common conversion will work ..
8607 if (Instruction *Result = commonIntCastTransforms(CI))
8608 return Result;
8609
8610 Value *Src = CI.getOperand(0);
8611
Chris Lattnera84f47c2009-02-17 20:47:23 +00008612 // If this is a TRUNC followed by a ZEXT then we are dealing with integral
8613 // types and if the sizes are just right we can convert this into a logical
8614 // 'and' which will be much cheaper than the pair of casts.
8615 if (TruncInst *CSrc = dyn_cast<TruncInst>(Src)) { // A->B->C cast
8616 // Get the sizes of the types involved. We know that the intermediate type
8617 // will be smaller than A or C, but don't know the relation between A and C.
8618 Value *A = CSrc->getOperand(0);
Dan Gohman6de29f82009-06-15 22:12:54 +00008619 unsigned SrcSize = A->getType()->getScalarSizeInBits();
8620 unsigned MidSize = CSrc->getType()->getScalarSizeInBits();
8621 unsigned DstSize = CI.getType()->getScalarSizeInBits();
Chris Lattnera84f47c2009-02-17 20:47:23 +00008622 // If we're actually extending zero bits, then if
8623 // SrcSize < DstSize: zext(a & mask)
8624 // SrcSize == DstSize: a & mask
8625 // SrcSize > DstSize: trunc(a) & mask
8626 if (SrcSize < DstSize) {
8627 APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
Owen Andersoneed707b2009-07-24 23:12:02 +00008628 Constant *AndConst = ConstantInt::get(A->getType(), AndValue);
Chris Lattnera84f47c2009-02-17 20:47:23 +00008629 Instruction *And =
8630 BinaryOperator::CreateAnd(A, AndConst, CSrc->getName()+".mask");
8631 InsertNewInstBefore(And, CI);
8632 return new ZExtInst(And, CI.getType());
8633 } else if (SrcSize == DstSize) {
8634 APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
Owen Andersoneed707b2009-07-24 23:12:02 +00008635 return BinaryOperator::CreateAnd(A, ConstantInt::get(A->getType(),
Dan Gohman6de29f82009-06-15 22:12:54 +00008636 AndValue));
Chris Lattnera84f47c2009-02-17 20:47:23 +00008637 } else if (SrcSize > DstSize) {
8638 Instruction *Trunc = new TruncInst(A, CI.getType(), "tmp");
8639 InsertNewInstBefore(Trunc, CI);
8640 APInt AndValue(APInt::getLowBitsSet(DstSize, MidSize));
Owen Andersond672ecb2009-07-03 00:17:18 +00008641 return BinaryOperator::CreateAnd(Trunc,
Owen Andersoneed707b2009-07-24 23:12:02 +00008642 ConstantInt::get(Trunc->getType(),
Dan Gohman6de29f82009-06-15 22:12:54 +00008643 AndValue));
Reid Spencer3da59db2006-11-27 01:05:10 +00008644 }
8645 }
8646
Evan Chengb98a10e2008-03-24 00:21:34 +00008647 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src))
8648 return transformZExtICmp(ICI, CI);
Chris Lattnera2e2c9b2007-04-11 06:53:04 +00008649
Evan Chengb98a10e2008-03-24 00:21:34 +00008650 BinaryOperator *SrcI = dyn_cast<BinaryOperator>(Src);
8651 if (SrcI && SrcI->getOpcode() == Instruction::Or) {
8652 // zext (or icmp, icmp) --> or (zext icmp), (zext icmp) if at least one
8653 // of the (zext icmp) will be transformed.
8654 ICmpInst *LHS = dyn_cast<ICmpInst>(SrcI->getOperand(0));
8655 ICmpInst *RHS = dyn_cast<ICmpInst>(SrcI->getOperand(1));
8656 if (LHS && RHS && LHS->hasOneUse() && RHS->hasOneUse() &&
8657 (transformZExtICmp(LHS, CI, false) ||
8658 transformZExtICmp(RHS, CI, false))) {
8659 Value *LCast = InsertCastBefore(Instruction::ZExt, LHS, CI.getType(), CI);
8660 Value *RCast = InsertCastBefore(Instruction::ZExt, RHS, CI.getType(), CI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008661 return BinaryOperator::Create(Instruction::Or, LCast, RCast);
Chris Lattner66bc3252007-04-11 05:45:39 +00008662 }
Evan Chengb98a10e2008-03-24 00:21:34 +00008663 }
8664
Dan Gohmanfd3daa72009-06-18 16:30:21 +00008665 // zext(trunc(t) & C) -> (t & zext(C)).
Dan Gohmana392c782009-06-17 23:17:05 +00008666 if (SrcI && SrcI->getOpcode() == Instruction::And && SrcI->hasOneUse())
8667 if (ConstantInt *C = dyn_cast<ConstantInt>(SrcI->getOperand(1)))
8668 if (TruncInst *TI = dyn_cast<TruncInst>(SrcI->getOperand(0))) {
8669 Value *TI0 = TI->getOperand(0);
Dan Gohmanfd3daa72009-06-18 16:30:21 +00008670 if (TI0->getType() == CI.getType())
8671 return
8672 BinaryOperator::CreateAnd(TI0,
Owen Andersonbaf3c402009-07-29 18:55:55 +00008673 ConstantExpr::getZExt(C, CI.getType()));
Dan Gohmana392c782009-06-17 23:17:05 +00008674 }
8675
Dan Gohmanfd3daa72009-06-18 16:30:21 +00008676 // zext((trunc(t) & C) ^ C) -> ((t & zext(C)) ^ zext(C)).
8677 if (SrcI && SrcI->getOpcode() == Instruction::Xor && SrcI->hasOneUse())
8678 if (ConstantInt *C = dyn_cast<ConstantInt>(SrcI->getOperand(1)))
8679 if (BinaryOperator *And = dyn_cast<BinaryOperator>(SrcI->getOperand(0)))
8680 if (And->getOpcode() == Instruction::And && And->hasOneUse() &&
8681 And->getOperand(1) == C)
8682 if (TruncInst *TI = dyn_cast<TruncInst>(And->getOperand(0))) {
8683 Value *TI0 = TI->getOperand(0);
8684 if (TI0->getType() == CI.getType()) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00008685 Constant *ZC = ConstantExpr::getZExt(C, CI.getType());
Dan Gohmanfd3daa72009-06-18 16:30:21 +00008686 Instruction *NewAnd = BinaryOperator::CreateAnd(TI0, ZC, "tmp");
8687 InsertNewInstBefore(NewAnd, *And);
8688 return BinaryOperator::CreateXor(NewAnd, ZC);
8689 }
8690 }
8691
Reid Spencer3da59db2006-11-27 01:05:10 +00008692 return 0;
8693}
8694
Chris Lattner8a9f5712007-04-11 06:57:46 +00008695Instruction *InstCombiner::visitSExt(SExtInst &CI) {
Chris Lattnerba417832007-04-11 06:12:58 +00008696 if (Instruction *I = commonIntCastTransforms(CI))
8697 return I;
8698
Chris Lattner8a9f5712007-04-11 06:57:46 +00008699 Value *Src = CI.getOperand(0);
8700
Dan Gohman1975d032008-10-30 20:40:10 +00008701 // Canonicalize sign-extend from i1 to a select.
8702 if (Src->getType() == Type::Int1Ty)
8703 return SelectInst::Create(Src,
Owen Andersona7235ea2009-07-31 20:28:14 +00008704 Constant::getAllOnesValue(CI.getType()),
8705 Constant::getNullValue(CI.getType()));
Dan Gohmanf35c8822008-05-20 21:01:12 +00008706
8707 // See if the value being truncated is already sign extended. If so, just
8708 // eliminate the trunc/sext pair.
Dan Gohmanca178902009-07-17 20:47:02 +00008709 if (Operator::getOpcode(Src) == Instruction::Trunc) {
Dan Gohmanf35c8822008-05-20 21:01:12 +00008710 Value *Op = cast<User>(Src)->getOperand(0);
Dan Gohman6de29f82009-06-15 22:12:54 +00008711 unsigned OpBits = Op->getType()->getScalarSizeInBits();
8712 unsigned MidBits = Src->getType()->getScalarSizeInBits();
8713 unsigned DestBits = CI.getType()->getScalarSizeInBits();
Dan Gohmanf35c8822008-05-20 21:01:12 +00008714 unsigned NumSignBits = ComputeNumSignBits(Op);
8715
8716 if (OpBits == DestBits) {
8717 // Op is i32, Mid is i8, and Dest is i32. If Op has more than 24 sign
8718 // bits, it is already ready.
8719 if (NumSignBits > DestBits-MidBits)
8720 return ReplaceInstUsesWith(CI, Op);
8721 } else if (OpBits < DestBits) {
8722 // Op is i32, Mid is i8, and Dest is i64. If Op has more than 24 sign
8723 // bits, just sext from i32.
8724 if (NumSignBits > OpBits-MidBits)
8725 return new SExtInst(Op, CI.getType(), "tmp");
8726 } else {
8727 // Op is i64, Mid is i8, and Dest is i32. If Op has more than 56 sign
8728 // bits, just truncate to i32.
8729 if (NumSignBits > OpBits-MidBits)
8730 return new TruncInst(Op, CI.getType(), "tmp");
8731 }
8732 }
Chris Lattner46bbad22008-08-06 07:35:52 +00008733
8734 // If the input is a shl/ashr pair of a same constant, then this is a sign
8735 // extension from a smaller value. If we could trust arbitrary bitwidth
8736 // integers, we could turn this into a truncate to the smaller bit and then
8737 // use a sext for the whole extension. Since we don't, look deeper and check
8738 // for a truncate. If the source and dest are the same type, eliminate the
8739 // trunc and extend and just do shifts. For example, turn:
8740 // %a = trunc i32 %i to i8
8741 // %b = shl i8 %a, 6
8742 // %c = ashr i8 %b, 6
8743 // %d = sext i8 %c to i32
8744 // into:
8745 // %a = shl i32 %i, 30
8746 // %d = ashr i32 %a, 30
8747 Value *A = 0;
8748 ConstantInt *BA = 0, *CA = 0;
8749 if (match(Src, m_AShr(m_Shl(m_Value(A), m_ConstantInt(BA)),
Owen Andersonc7d2ce72009-07-10 17:35:01 +00008750 m_ConstantInt(CA)), *Context) &&
Chris Lattner46bbad22008-08-06 07:35:52 +00008751 BA == CA && isa<TruncInst>(A)) {
8752 Value *I = cast<TruncInst>(A)->getOperand(0);
8753 if (I->getType() == CI.getType()) {
Dan Gohman6de29f82009-06-15 22:12:54 +00008754 unsigned MidSize = Src->getType()->getScalarSizeInBits();
8755 unsigned SrcDstSize = CI.getType()->getScalarSizeInBits();
Chris Lattner46bbad22008-08-06 07:35:52 +00008756 unsigned ShAmt = CA->getZExtValue()+SrcDstSize-MidSize;
Owen Andersoneed707b2009-07-24 23:12:02 +00008757 Constant *ShAmtV = ConstantInt::get(CI.getType(), ShAmt);
Chris Lattner46bbad22008-08-06 07:35:52 +00008758 I = InsertNewInstBefore(BinaryOperator::CreateShl(I, ShAmtV,
8759 CI.getName()), CI);
8760 return BinaryOperator::CreateAShr(I, ShAmtV);
8761 }
8762 }
8763
Chris Lattnerba417832007-04-11 06:12:58 +00008764 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00008765}
8766
Chris Lattnerb7530652008-01-27 05:29:54 +00008767/// FitsInFPType - Return a Constant* for the specified FP constant if it fits
8768/// in the specified FP type without changing its value.
Owen Andersond672ecb2009-07-03 00:17:18 +00008769static Constant *FitsInFPType(ConstantFP *CFP, const fltSemantics &Sem,
Owen Anderson07cf79e2009-07-06 23:00:19 +00008770 LLVMContext *Context) {
Dale Johannesen23a98552008-10-09 23:00:39 +00008771 bool losesInfo;
Chris Lattnerb7530652008-01-27 05:29:54 +00008772 APFloat F = CFP->getValueAPF();
Dale Johannesen23a98552008-10-09 23:00:39 +00008773 (void)F.convert(Sem, APFloat::rmNearestTiesToEven, &losesInfo);
8774 if (!losesInfo)
Owen Anderson6f83c9c2009-07-27 20:59:43 +00008775 return ConstantFP::get(*Context, F);
Chris Lattnerb7530652008-01-27 05:29:54 +00008776 return 0;
8777}
8778
8779/// LookThroughFPExtensions - If this is an fp extension instruction, look
8780/// through it until we get the source value.
Owen Anderson07cf79e2009-07-06 23:00:19 +00008781static Value *LookThroughFPExtensions(Value *V, LLVMContext *Context) {
Chris Lattnerb7530652008-01-27 05:29:54 +00008782 if (Instruction *I = dyn_cast<Instruction>(V))
8783 if (I->getOpcode() == Instruction::FPExt)
Owen Andersond672ecb2009-07-03 00:17:18 +00008784 return LookThroughFPExtensions(I->getOperand(0), Context);
Chris Lattnerb7530652008-01-27 05:29:54 +00008785
8786 // If this value is a constant, return the constant in the smallest FP type
8787 // that can accurately represent it. This allows us to turn
8788 // (float)((double)X+2.0) into x+2.0f.
8789 if (ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
8790 if (CFP->getType() == Type::PPC_FP128Ty)
8791 return V; // No constant folding of this.
8792 // See if the value can be truncated to float and then reextended.
Owen Andersond672ecb2009-07-03 00:17:18 +00008793 if (Value *V = FitsInFPType(CFP, APFloat::IEEEsingle, Context))
Chris Lattnerb7530652008-01-27 05:29:54 +00008794 return V;
8795 if (CFP->getType() == Type::DoubleTy)
8796 return V; // Won't shrink.
Owen Andersond672ecb2009-07-03 00:17:18 +00008797 if (Value *V = FitsInFPType(CFP, APFloat::IEEEdouble, Context))
Chris Lattnerb7530652008-01-27 05:29:54 +00008798 return V;
8799 // Don't try to shrink to various long double types.
8800 }
8801
8802 return V;
8803}
8804
8805Instruction *InstCombiner::visitFPTrunc(FPTruncInst &CI) {
8806 if (Instruction *I = commonCastTransforms(CI))
8807 return I;
8808
Dan Gohmanae3a0be2009-06-04 22:49:04 +00008809 // If we have fptrunc(fadd (fpextend x), (fpextend y)), where x and y are
Chris Lattnerb7530652008-01-27 05:29:54 +00008810 // smaller than the destination type, we can eliminate the truncate by doing
Dan Gohmanae3a0be2009-06-04 22:49:04 +00008811 // the add as the smaller type. This applies to fadd/fsub/fmul/fdiv as well as
Chris Lattnerb7530652008-01-27 05:29:54 +00008812 // many builtins (sqrt, etc).
8813 BinaryOperator *OpI = dyn_cast<BinaryOperator>(CI.getOperand(0));
8814 if (OpI && OpI->hasOneUse()) {
8815 switch (OpI->getOpcode()) {
8816 default: break;
Dan Gohmanae3a0be2009-06-04 22:49:04 +00008817 case Instruction::FAdd:
8818 case Instruction::FSub:
8819 case Instruction::FMul:
Chris Lattnerb7530652008-01-27 05:29:54 +00008820 case Instruction::FDiv:
8821 case Instruction::FRem:
8822 const Type *SrcTy = OpI->getType();
Owen Andersond672ecb2009-07-03 00:17:18 +00008823 Value *LHSTrunc = LookThroughFPExtensions(OpI->getOperand(0), Context);
8824 Value *RHSTrunc = LookThroughFPExtensions(OpI->getOperand(1), Context);
Chris Lattnerb7530652008-01-27 05:29:54 +00008825 if (LHSTrunc->getType() != SrcTy &&
8826 RHSTrunc->getType() != SrcTy) {
Dan Gohman6de29f82009-06-15 22:12:54 +00008827 unsigned DstSize = CI.getType()->getScalarSizeInBits();
Chris Lattnerb7530652008-01-27 05:29:54 +00008828 // If the source types were both smaller than the destination type of
8829 // the cast, do this xform.
Dan Gohman6de29f82009-06-15 22:12:54 +00008830 if (LHSTrunc->getType()->getScalarSizeInBits() <= DstSize &&
8831 RHSTrunc->getType()->getScalarSizeInBits() <= DstSize) {
Chris Lattnerb7530652008-01-27 05:29:54 +00008832 LHSTrunc = InsertCastBefore(Instruction::FPExt, LHSTrunc,
8833 CI.getType(), CI);
8834 RHSTrunc = InsertCastBefore(Instruction::FPExt, RHSTrunc,
8835 CI.getType(), CI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008836 return BinaryOperator::Create(OpI->getOpcode(), LHSTrunc, RHSTrunc);
Chris Lattnerb7530652008-01-27 05:29:54 +00008837 }
8838 }
8839 break;
8840 }
8841 }
8842 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00008843}
8844
8845Instruction *InstCombiner::visitFPExt(CastInst &CI) {
8846 return commonCastTransforms(CI);
8847}
8848
Chris Lattner0c7a9a02008-05-19 20:25:04 +00008849Instruction *InstCombiner::visitFPToUI(FPToUIInst &FI) {
Chris Lattner5af5f462008-08-06 05:13:06 +00008850 Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
8851 if (OpI == 0)
8852 return commonCastTransforms(FI);
8853
8854 // fptoui(uitofp(X)) --> X
8855 // fptoui(sitofp(X)) --> X
8856 // This is safe if the intermediate type has enough bits in its mantissa to
8857 // accurately represent all values of X. For example, do not do this with
8858 // i64->float->i64. This is also safe for sitofp case, because any negative
8859 // 'X' value would cause an undefined result for the fptoui.
8860 if ((isa<UIToFPInst>(OpI) || isa<SIToFPInst>(OpI)) &&
8861 OpI->getOperand(0)->getType() == FI.getType() &&
Dan Gohman6de29f82009-06-15 22:12:54 +00008862 (int)FI.getType()->getScalarSizeInBits() < /*extra bit for sign */
Chris Lattner5af5f462008-08-06 05:13:06 +00008863 OpI->getType()->getFPMantissaWidth())
8864 return ReplaceInstUsesWith(FI, OpI->getOperand(0));
Chris Lattner0c7a9a02008-05-19 20:25:04 +00008865
8866 return commonCastTransforms(FI);
Reid Spencer3da59db2006-11-27 01:05:10 +00008867}
8868
Chris Lattner0c7a9a02008-05-19 20:25:04 +00008869Instruction *InstCombiner::visitFPToSI(FPToSIInst &FI) {
Chris Lattner5af5f462008-08-06 05:13:06 +00008870 Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
8871 if (OpI == 0)
8872 return commonCastTransforms(FI);
8873
8874 // fptosi(sitofp(X)) --> X
8875 // fptosi(uitofp(X)) --> X
8876 // This is safe if the intermediate type has enough bits in its mantissa to
8877 // accurately represent all values of X. For example, do not do this with
8878 // i64->float->i64. This is also safe for sitofp case, because any negative
8879 // 'X' value would cause an undefined result for the fptoui.
8880 if ((isa<UIToFPInst>(OpI) || isa<SIToFPInst>(OpI)) &&
8881 OpI->getOperand(0)->getType() == FI.getType() &&
Dan Gohman6de29f82009-06-15 22:12:54 +00008882 (int)FI.getType()->getScalarSizeInBits() <=
Chris Lattner5af5f462008-08-06 05:13:06 +00008883 OpI->getType()->getFPMantissaWidth())
8884 return ReplaceInstUsesWith(FI, OpI->getOperand(0));
Chris Lattner0c7a9a02008-05-19 20:25:04 +00008885
8886 return commonCastTransforms(FI);
Reid Spencer3da59db2006-11-27 01:05:10 +00008887}
8888
8889Instruction *InstCombiner::visitUIToFP(CastInst &CI) {
8890 return commonCastTransforms(CI);
8891}
8892
8893Instruction *InstCombiner::visitSIToFP(CastInst &CI) {
8894 return commonCastTransforms(CI);
8895}
8896
Chris Lattnera0e69692009-03-24 18:35:40 +00008897Instruction *InstCombiner::visitPtrToInt(PtrToIntInst &CI) {
8898 // If the destination integer type is smaller than the intptr_t type for
8899 // this target, do a ptrtoint to intptr_t then do a trunc. This allows the
8900 // trunc to be exposed to other transforms. Don't do this for extending
8901 // ptrtoint's, because we don't know if the target sign or zero extends its
8902 // pointers.
Dan Gohmance9fe9f2009-07-21 23:21:54 +00008903 if (TD &&
8904 CI.getType()->getScalarSizeInBits() < TD->getPointerSizeInBits()) {
Chris Lattnera0e69692009-03-24 18:35:40 +00008905 Value *P = InsertNewInstBefore(new PtrToIntInst(CI.getOperand(0),
8906 TD->getIntPtrType(),
8907 "tmp"), CI);
8908 return new TruncInst(P, CI.getType());
8909 }
8910
Chris Lattnerd3e28342007-04-27 17:44:50 +00008911 return commonPointerCastTransforms(CI);
Reid Spencer3da59db2006-11-27 01:05:10 +00008912}
8913
Chris Lattnerf9d9e452008-01-08 07:23:51 +00008914Instruction *InstCombiner::visitIntToPtr(IntToPtrInst &CI) {
Chris Lattnera0e69692009-03-24 18:35:40 +00008915 // If the source integer type is larger than the intptr_t type for
8916 // this target, do a trunc to the intptr_t type, then inttoptr of it. This
8917 // allows the trunc to be exposed to other transforms. Don't do this for
8918 // extending inttoptr's, because we don't know if the target sign or zero
8919 // extends to pointers.
Dan Gohmance9fe9f2009-07-21 23:21:54 +00008920 if (TD &&
8921 CI.getOperand(0)->getType()->getScalarSizeInBits() >
Chris Lattnera0e69692009-03-24 18:35:40 +00008922 TD->getPointerSizeInBits()) {
8923 Value *P = InsertNewInstBefore(new TruncInst(CI.getOperand(0),
8924 TD->getIntPtrType(),
8925 "tmp"), CI);
8926 return new IntToPtrInst(P, CI.getType());
8927 }
8928
Chris Lattnerf9d9e452008-01-08 07:23:51 +00008929 if (Instruction *I = commonCastTransforms(CI))
8930 return I;
Chris Lattnerf9d9e452008-01-08 07:23:51 +00008931
Chris Lattnerf9d9e452008-01-08 07:23:51 +00008932 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00008933}
8934
Chris Lattnerd3e28342007-04-27 17:44:50 +00008935Instruction *InstCombiner::visitBitCast(BitCastInst &CI) {
Reid Spencer3da59db2006-11-27 01:05:10 +00008936 // If the operands are integer typed then apply the integer transforms,
8937 // otherwise just apply the common ones.
8938 Value *Src = CI.getOperand(0);
8939 const Type *SrcTy = Src->getType();
8940 const Type *DestTy = CI.getType();
8941
Eli Friedman7e25d452009-07-13 20:53:00 +00008942 if (isa<PointerType>(SrcTy)) {
Chris Lattnerd3e28342007-04-27 17:44:50 +00008943 if (Instruction *I = commonPointerCastTransforms(CI))
8944 return I;
Reid Spencer3da59db2006-11-27 01:05:10 +00008945 } else {
8946 if (Instruction *Result = commonCastTransforms(CI))
8947 return Result;
8948 }
8949
8950
8951 // Get rid of casts from one type to the same type. These are useless and can
8952 // be replaced by the operand.
8953 if (DestTy == Src->getType())
8954 return ReplaceInstUsesWith(CI, Src);
8955
Reid Spencer3da59db2006-11-27 01:05:10 +00008956 if (const PointerType *DstPTy = dyn_cast<PointerType>(DestTy)) {
Chris Lattnerd3e28342007-04-27 17:44:50 +00008957 const PointerType *SrcPTy = cast<PointerType>(SrcTy);
8958 const Type *DstElTy = DstPTy->getElementType();
8959 const Type *SrcElTy = SrcPTy->getElementType();
8960
Nate Begeman83ad90a2008-03-31 00:22:16 +00008961 // If the address spaces don't match, don't eliminate the bitcast, which is
8962 // required for changing types.
8963 if (SrcPTy->getAddressSpace() != DstPTy->getAddressSpace())
8964 return 0;
8965
Chris Lattnerd3e28342007-04-27 17:44:50 +00008966 // If we are casting a malloc or alloca to a pointer to a type of the same
8967 // size, rewrite the allocation instruction to allocate the "right" type.
8968 if (AllocationInst *AI = dyn_cast<AllocationInst>(Src))
8969 if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
8970 return V;
8971
Chris Lattnerd717c182007-05-05 22:32:24 +00008972 // If the source and destination are pointers, and this cast is equivalent
8973 // to a getelementptr X, 0, 0, 0... turn it into the appropriate gep.
Chris Lattnerd3e28342007-04-27 17:44:50 +00008974 // This can enhance SROA and other transforms that want type-safe pointers.
Owen Andersona7235ea2009-07-31 20:28:14 +00008975 Constant *ZeroUInt = Constant::getNullValue(Type::Int32Ty);
Chris Lattnerd3e28342007-04-27 17:44:50 +00008976 unsigned NumZeros = 0;
8977 while (SrcElTy != DstElTy &&
8978 isa<CompositeType>(SrcElTy) && !isa<PointerType>(SrcElTy) &&
8979 SrcElTy->getNumContainedTypes() /* not "{}" */) {
8980 SrcElTy = cast<CompositeType>(SrcElTy)->getTypeAtIndex(ZeroUInt);
8981 ++NumZeros;
8982 }
Chris Lattner4e998b22004-09-29 05:07:12 +00008983
Chris Lattnerd3e28342007-04-27 17:44:50 +00008984 // If we found a path from the src to dest, create the getelementptr now.
8985 if (SrcElTy == DstElTy) {
8986 SmallVector<Value*, 8> Idxs(NumZeros+1, ZeroUInt);
Dan Gohmand6aa02d2009-07-28 01:40:03 +00008987 Instruction *GEP = GetElementPtrInst::Create(Src,
8988 Idxs.begin(), Idxs.end(), "",
8989 ((Instruction*) NULL));
8990 cast<GEPOperator>(GEP)->setIsInBounds(true);
8991 return GEP;
Chris Lattner9fb92132006-04-12 18:09:35 +00008992 }
Reid Spencer3da59db2006-11-27 01:05:10 +00008993 }
Chris Lattner24c8e382003-07-24 17:35:25 +00008994
Eli Friedman2451a642009-07-18 23:06:53 +00008995 if (const VectorType *DestVTy = dyn_cast<VectorType>(DestTy)) {
8996 if (DestVTy->getNumElements() == 1) {
8997 if (!isa<VectorType>(SrcTy)) {
8998 Value *Elem = InsertCastBefore(Instruction::BitCast, Src,
8999 DestVTy->getElementType(), CI);
Owen Anderson9e9a0d52009-07-30 23:03:37 +00009000 return InsertElementInst::Create(UndefValue::get(DestTy), Elem,
Owen Andersona7235ea2009-07-31 20:28:14 +00009001 Constant::getNullValue(Type::Int32Ty));
Eli Friedman2451a642009-07-18 23:06:53 +00009002 }
9003 // FIXME: Canonicalize bitcast(insertelement) -> insertelement(bitcast)
9004 }
9005 }
9006
9007 if (const VectorType *SrcVTy = dyn_cast<VectorType>(SrcTy)) {
9008 if (SrcVTy->getNumElements() == 1) {
9009 if (!isa<VectorType>(DestTy)) {
9010 Instruction *Elem =
Owen Andersona7235ea2009-07-31 20:28:14 +00009011 ExtractElementInst::Create(Src, Constant::getNullValue(Type::Int32Ty));
Eli Friedman2451a642009-07-18 23:06:53 +00009012 InsertNewInstBefore(Elem, CI);
9013 return CastInst::Create(Instruction::BitCast, Elem, DestTy);
9014 }
9015 }
9016 }
9017
Reid Spencer3da59db2006-11-27 01:05:10 +00009018 if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(Src)) {
9019 if (SVI->hasOneUse()) {
9020 // Okay, we have (bitconvert (shuffle ..)). Check to see if this is
9021 // a bitconvert to a vector with the same # elts.
Reid Spencer9d6565a2007-02-15 02:26:10 +00009022 if (isa<VectorType>(DestTy) &&
Mon P Wangaeb06d22008-11-10 04:46:22 +00009023 cast<VectorType>(DestTy)->getNumElements() ==
9024 SVI->getType()->getNumElements() &&
9025 SVI->getType()->getNumElements() ==
9026 cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements()) {
Reid Spencer3da59db2006-11-27 01:05:10 +00009027 CastInst *Tmp;
9028 // If either of the operands is a cast from CI.getType(), then
9029 // evaluating the shuffle in the casted destination's type will allow
9030 // us to eliminate at least one cast.
9031 if (((Tmp = dyn_cast<CastInst>(SVI->getOperand(0))) &&
9032 Tmp->getOperand(0)->getType() == DestTy) ||
9033 ((Tmp = dyn_cast<CastInst>(SVI->getOperand(1))) &&
9034 Tmp->getOperand(0)->getType() == DestTy)) {
Eli Friedmand1fd1da2008-11-30 21:09:11 +00009035 Value *LHS = InsertCastBefore(Instruction::BitCast,
9036 SVI->getOperand(0), DestTy, CI);
9037 Value *RHS = InsertCastBefore(Instruction::BitCast,
9038 SVI->getOperand(1), DestTy, CI);
Reid Spencer3da59db2006-11-27 01:05:10 +00009039 // Return a new shuffle vector. Use the same element ID's, as we
9040 // know the vector types match #elts.
9041 return new ShuffleVectorInst(LHS, RHS, SVI->getOperand(2));
Chris Lattner01575b72006-05-25 23:24:33 +00009042 }
9043 }
9044 }
9045 }
Chris Lattnerdd841ae2002-04-18 17:39:14 +00009046 return 0;
Chris Lattner8a2a3112001-12-14 16:52:21 +00009047}
9048
Chris Lattnere576b912004-04-09 23:46:01 +00009049/// GetSelectFoldableOperands - We want to turn code that looks like this:
9050/// %C = or %A, %B
9051/// %D = select %cond, %C, %A
9052/// into:
9053/// %C = select %cond, %B, 0
9054/// %D = or %A, %C
9055///
9056/// Assuming that the specified instruction is an operand to the select, return
9057/// a bitmask indicating which operands of this instruction are foldable if they
9058/// equal the other incoming value of the select.
9059///
9060static unsigned GetSelectFoldableOperands(Instruction *I) {
9061 switch (I->getOpcode()) {
9062 case Instruction::Add:
9063 case Instruction::Mul:
9064 case Instruction::And:
9065 case Instruction::Or:
9066 case Instruction::Xor:
9067 return 3; // Can fold through either operand.
9068 case Instruction::Sub: // Can only fold on the amount subtracted.
9069 case Instruction::Shl: // Can only fold on the shift amount.
Reid Spencer3822ff52006-11-08 06:47:33 +00009070 case Instruction::LShr:
9071 case Instruction::AShr:
Misha Brukmanfd939082005-04-21 23:48:37 +00009072 return 1;
Chris Lattnere576b912004-04-09 23:46:01 +00009073 default:
9074 return 0; // Cannot fold
9075 }
9076}
9077
9078/// GetSelectFoldableConstant - For the same transformation as the previous
9079/// function, return the identity constant that goes into the select.
Owen Andersond672ecb2009-07-03 00:17:18 +00009080static Constant *GetSelectFoldableConstant(Instruction *I,
Owen Anderson07cf79e2009-07-06 23:00:19 +00009081 LLVMContext *Context) {
Chris Lattnere576b912004-04-09 23:46:01 +00009082 switch (I->getOpcode()) {
Torok Edwinc23197a2009-07-14 16:55:14 +00009083 default: llvm_unreachable("This cannot happen!");
Chris Lattnere576b912004-04-09 23:46:01 +00009084 case Instruction::Add:
9085 case Instruction::Sub:
9086 case Instruction::Or:
9087 case Instruction::Xor:
Chris Lattnere576b912004-04-09 23:46:01 +00009088 case Instruction::Shl:
Reid Spencer3822ff52006-11-08 06:47:33 +00009089 case Instruction::LShr:
9090 case Instruction::AShr:
Owen Andersona7235ea2009-07-31 20:28:14 +00009091 return Constant::getNullValue(I->getType());
Chris Lattnere576b912004-04-09 23:46:01 +00009092 case Instruction::And:
Owen Andersona7235ea2009-07-31 20:28:14 +00009093 return Constant::getAllOnesValue(I->getType());
Chris Lattnere576b912004-04-09 23:46:01 +00009094 case Instruction::Mul:
Owen Andersoneed707b2009-07-24 23:12:02 +00009095 return ConstantInt::get(I->getType(), 1);
Chris Lattnere576b912004-04-09 23:46:01 +00009096 }
9097}
9098
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009099/// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI
9100/// have the same opcode and only one use each. Try to simplify this.
9101Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
9102 Instruction *FI) {
9103 if (TI->getNumOperands() == 1) {
9104 // If this is a non-volatile load or a cast from the same type,
9105 // merge.
Reid Spencer3da59db2006-11-27 01:05:10 +00009106 if (TI->isCast()) {
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009107 if (TI->getOperand(0)->getType() != FI->getOperand(0)->getType())
9108 return 0;
9109 } else {
9110 return 0; // unknown unary op.
9111 }
Misha Brukmanfd939082005-04-21 23:48:37 +00009112
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009113 // Fold this by inserting a select from the input values.
Gabor Greif051a9502008-04-06 20:25:17 +00009114 SelectInst *NewSI = SelectInst::Create(SI.getCondition(), TI->getOperand(0),
Eric Christophera66297a2009-07-25 02:45:27 +00009115 FI->getOperand(0), SI.getName()+".v");
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009116 InsertNewInstBefore(NewSI, SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009117 return CastInst::Create(Instruction::CastOps(TI->getOpcode()), NewSI,
Reid Spencer3da59db2006-11-27 01:05:10 +00009118 TI->getType());
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009119 }
9120
Reid Spencer832254e2007-02-02 02:16:23 +00009121 // Only handle binary operators here.
9122 if (!isa<BinaryOperator>(TI))
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009123 return 0;
9124
9125 // Figure out if the operations have any operands in common.
9126 Value *MatchOp, *OtherOpT, *OtherOpF;
9127 bool MatchIsOpZero;
9128 if (TI->getOperand(0) == FI->getOperand(0)) {
9129 MatchOp = TI->getOperand(0);
9130 OtherOpT = TI->getOperand(1);
9131 OtherOpF = FI->getOperand(1);
9132 MatchIsOpZero = true;
9133 } else if (TI->getOperand(1) == FI->getOperand(1)) {
9134 MatchOp = TI->getOperand(1);
9135 OtherOpT = TI->getOperand(0);
9136 OtherOpF = FI->getOperand(0);
9137 MatchIsOpZero = false;
9138 } else if (!TI->isCommutative()) {
9139 return 0;
9140 } else if (TI->getOperand(0) == FI->getOperand(1)) {
9141 MatchOp = TI->getOperand(0);
9142 OtherOpT = TI->getOperand(1);
9143 OtherOpF = FI->getOperand(0);
9144 MatchIsOpZero = true;
9145 } else if (TI->getOperand(1) == FI->getOperand(0)) {
9146 MatchOp = TI->getOperand(1);
9147 OtherOpT = TI->getOperand(0);
9148 OtherOpF = FI->getOperand(1);
9149 MatchIsOpZero = true;
9150 } else {
9151 return 0;
9152 }
9153
9154 // If we reach here, they do have operations in common.
Gabor Greif051a9502008-04-06 20:25:17 +00009155 SelectInst *NewSI = SelectInst::Create(SI.getCondition(), OtherOpT,
9156 OtherOpF, SI.getName()+".v");
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009157 InsertNewInstBefore(NewSI, SI);
9158
9159 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
9160 if (MatchIsOpZero)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009161 return BinaryOperator::Create(BO->getOpcode(), MatchOp, NewSI);
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009162 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009163 return BinaryOperator::Create(BO->getOpcode(), NewSI, MatchOp);
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009164 }
Torok Edwinc23197a2009-07-14 16:55:14 +00009165 llvm_unreachable("Shouldn't get here");
Reid Spencera07cb7d2007-02-02 14:41:37 +00009166 return 0;
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009167}
9168
Evan Chengde621922009-03-31 20:42:45 +00009169static bool isSelect01(Constant *C1, Constant *C2) {
9170 ConstantInt *C1I = dyn_cast<ConstantInt>(C1);
9171 if (!C1I)
9172 return false;
9173 ConstantInt *C2I = dyn_cast<ConstantInt>(C2);
9174 if (!C2I)
9175 return false;
9176 return (C1I->isZero() || C1I->isOne()) && (C2I->isZero() || C2I->isOne());
9177}
9178
9179/// FoldSelectIntoOp - Try fold the select into one of the operands to
9180/// facilitate further optimization.
9181Instruction *InstCombiner::FoldSelectIntoOp(SelectInst &SI, Value *TrueVal,
9182 Value *FalseVal) {
9183 // See the comment above GetSelectFoldableOperands for a description of the
9184 // transformation we are doing here.
9185 if (Instruction *TVI = dyn_cast<Instruction>(TrueVal)) {
9186 if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
9187 !isa<Constant>(FalseVal)) {
9188 if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
9189 unsigned OpToFold = 0;
9190 if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
9191 OpToFold = 1;
9192 } else if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
9193 OpToFold = 2;
9194 }
9195
9196 if (OpToFold) {
Owen Andersond672ecb2009-07-03 00:17:18 +00009197 Constant *C = GetSelectFoldableConstant(TVI, Context);
Evan Chengde621922009-03-31 20:42:45 +00009198 Value *OOp = TVI->getOperand(2-OpToFold);
9199 // Avoid creating select between 2 constants unless it's selecting
9200 // between 0 and 1.
9201 if (!isa<Constant>(OOp) || isSelect01(C, cast<Constant>(OOp))) {
9202 Instruction *NewSel = SelectInst::Create(SI.getCondition(), OOp, C);
9203 InsertNewInstBefore(NewSel, SI);
9204 NewSel->takeName(TVI);
9205 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
9206 return BinaryOperator::Create(BO->getOpcode(), FalseVal, NewSel);
Torok Edwinc23197a2009-07-14 16:55:14 +00009207 llvm_unreachable("Unknown instruction!!");
Evan Chengde621922009-03-31 20:42:45 +00009208 }
9209 }
9210 }
9211 }
9212 }
9213
9214 if (Instruction *FVI = dyn_cast<Instruction>(FalseVal)) {
9215 if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
9216 !isa<Constant>(TrueVal)) {
9217 if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
9218 unsigned OpToFold = 0;
9219 if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
9220 OpToFold = 1;
9221 } else if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
9222 OpToFold = 2;
9223 }
9224
9225 if (OpToFold) {
Owen Andersond672ecb2009-07-03 00:17:18 +00009226 Constant *C = GetSelectFoldableConstant(FVI, Context);
Evan Chengde621922009-03-31 20:42:45 +00009227 Value *OOp = FVI->getOperand(2-OpToFold);
9228 // Avoid creating select between 2 constants unless it's selecting
9229 // between 0 and 1.
9230 if (!isa<Constant>(OOp) || isSelect01(C, cast<Constant>(OOp))) {
9231 Instruction *NewSel = SelectInst::Create(SI.getCondition(), C, OOp);
9232 InsertNewInstBefore(NewSel, SI);
9233 NewSel->takeName(FVI);
9234 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
9235 return BinaryOperator::Create(BO->getOpcode(), TrueVal, NewSel);
Torok Edwinc23197a2009-07-14 16:55:14 +00009236 llvm_unreachable("Unknown instruction!!");
Evan Chengde621922009-03-31 20:42:45 +00009237 }
9238 }
9239 }
9240 }
9241 }
9242
9243 return 0;
9244}
9245
Dan Gohman81b28ce2008-09-16 18:46:06 +00009246/// visitSelectInstWithICmp - Visit a SelectInst that has an
9247/// ICmpInst as its first operand.
9248///
9249Instruction *InstCombiner::visitSelectInstWithICmp(SelectInst &SI,
9250 ICmpInst *ICI) {
9251 bool Changed = false;
9252 ICmpInst::Predicate Pred = ICI->getPredicate();
9253 Value *CmpLHS = ICI->getOperand(0);
9254 Value *CmpRHS = ICI->getOperand(1);
9255 Value *TrueVal = SI.getTrueValue();
9256 Value *FalseVal = SI.getFalseValue();
9257
9258 // Check cases where the comparison is with a constant that
9259 // can be adjusted to fit the min/max idiom. We may edit ICI in
9260 // place here, so make sure the select is the only user.
9261 if (ICI->hasOneUse())
Dan Gohman1975d032008-10-30 20:40:10 +00009262 if (ConstantInt *CI = dyn_cast<ConstantInt>(CmpRHS)) {
Dan Gohman81b28ce2008-09-16 18:46:06 +00009263 switch (Pred) {
9264 default: break;
9265 case ICmpInst::ICMP_ULT:
9266 case ICmpInst::ICMP_SLT: {
9267 // X < MIN ? T : F --> F
9268 if (CI->isMinValue(Pred == ICmpInst::ICMP_SLT))
9269 return ReplaceInstUsesWith(SI, FalseVal);
9270 // X < C ? X : C-1 --> X > C-1 ? C-1 : X
Dan Gohman186a6362009-08-12 16:04:34 +00009271 Constant *AdjustedRHS = SubOne(CI);
Dan Gohman81b28ce2008-09-16 18:46:06 +00009272 if ((CmpLHS == TrueVal && AdjustedRHS == FalseVal) ||
9273 (CmpLHS == FalseVal && AdjustedRHS == TrueVal)) {
9274 Pred = ICmpInst::getSwappedPredicate(Pred);
9275 CmpRHS = AdjustedRHS;
9276 std::swap(FalseVal, TrueVal);
9277 ICI->setPredicate(Pred);
9278 ICI->setOperand(1, CmpRHS);
9279 SI.setOperand(1, TrueVal);
9280 SI.setOperand(2, FalseVal);
9281 Changed = true;
9282 }
9283 break;
9284 }
9285 case ICmpInst::ICMP_UGT:
9286 case ICmpInst::ICMP_SGT: {
9287 // X > MAX ? T : F --> F
9288 if (CI->isMaxValue(Pred == ICmpInst::ICMP_SGT))
9289 return ReplaceInstUsesWith(SI, FalseVal);
9290 // X > C ? X : C+1 --> X < C+1 ? C+1 : X
Dan Gohman186a6362009-08-12 16:04:34 +00009291 Constant *AdjustedRHS = AddOne(CI);
Dan Gohman81b28ce2008-09-16 18:46:06 +00009292 if ((CmpLHS == TrueVal && AdjustedRHS == FalseVal) ||
9293 (CmpLHS == FalseVal && AdjustedRHS == TrueVal)) {
9294 Pred = ICmpInst::getSwappedPredicate(Pred);
9295 CmpRHS = AdjustedRHS;
9296 std::swap(FalseVal, TrueVal);
9297 ICI->setPredicate(Pred);
9298 ICI->setOperand(1, CmpRHS);
9299 SI.setOperand(1, TrueVal);
9300 SI.setOperand(2, FalseVal);
9301 Changed = true;
9302 }
9303 break;
9304 }
9305 }
9306
Dan Gohman1975d032008-10-30 20:40:10 +00009307 // (x <s 0) ? -1 : 0 -> ashr x, 31 -> all ones if signed
9308 // (x >s -1) ? -1 : 0 -> ashr x, 31 -> all ones if not signed
Chris Lattnercb504b92008-11-16 05:38:51 +00009309 CmpInst::Predicate Pred = CmpInst::BAD_ICMP_PREDICATE;
Owen Andersonc7d2ce72009-07-10 17:35:01 +00009310 if (match(TrueVal, m_ConstantInt<-1>(), *Context) &&
9311 match(FalseVal, m_ConstantInt<0>(), *Context))
Chris Lattnercb504b92008-11-16 05:38:51 +00009312 Pred = ICI->getPredicate();
Owen Andersonc7d2ce72009-07-10 17:35:01 +00009313 else if (match(TrueVal, m_ConstantInt<0>(), *Context) &&
9314 match(FalseVal, m_ConstantInt<-1>(), *Context))
Chris Lattnercb504b92008-11-16 05:38:51 +00009315 Pred = CmpInst::getInversePredicate(ICI->getPredicate());
9316
Dan Gohman1975d032008-10-30 20:40:10 +00009317 if (Pred != CmpInst::BAD_ICMP_PREDICATE) {
9318 // If we are just checking for a icmp eq of a single bit and zext'ing it
9319 // to an integer, then shift the bit to the appropriate place and then
9320 // cast to integer to avoid the comparison.
9321 const APInt &Op1CV = CI->getValue();
9322
9323 // sext (x <s 0) to i32 --> x>>s31 true if signbit set.
9324 // sext (x >s -1) to i32 --> (x>>s31)^-1 true if signbit clear.
9325 if ((Pred == ICmpInst::ICMP_SLT && Op1CV == 0) ||
Chris Lattnercb504b92008-11-16 05:38:51 +00009326 (Pred == ICmpInst::ICMP_SGT && Op1CV.isAllOnesValue())) {
Dan Gohman1975d032008-10-30 20:40:10 +00009327 Value *In = ICI->getOperand(0);
Owen Andersoneed707b2009-07-24 23:12:02 +00009328 Value *Sh = ConstantInt::get(In->getType(),
Dan Gohman6de29f82009-06-15 22:12:54 +00009329 In->getType()->getScalarSizeInBits()-1);
Dan Gohman1975d032008-10-30 20:40:10 +00009330 In = InsertNewInstBefore(BinaryOperator::CreateAShr(In, Sh,
Eric Christophera66297a2009-07-25 02:45:27 +00009331 In->getName()+".lobit"),
Dan Gohman1975d032008-10-30 20:40:10 +00009332 *ICI);
Dan Gohman21440ac2008-11-02 00:17:33 +00009333 if (In->getType() != SI.getType())
9334 In = CastInst::CreateIntegerCast(In, SI.getType(),
Dan Gohman1975d032008-10-30 20:40:10 +00009335 true/*SExt*/, "tmp", ICI);
9336
9337 if (Pred == ICmpInst::ICMP_SGT)
Owen Anderson73c6b712009-07-13 20:58:05 +00009338 In = InsertNewInstBefore(BinaryOperator::CreateNot(*Context, In,
Dan Gohman1975d032008-10-30 20:40:10 +00009339 In->getName()+".not"), *ICI);
9340
9341 return ReplaceInstUsesWith(SI, In);
9342 }
9343 }
9344 }
9345
Dan Gohman81b28ce2008-09-16 18:46:06 +00009346 if (CmpLHS == TrueVal && CmpRHS == FalseVal) {
9347 // Transform (X == Y) ? X : Y -> Y
9348 if (Pred == ICmpInst::ICMP_EQ)
9349 return ReplaceInstUsesWith(SI, FalseVal);
9350 // Transform (X != Y) ? X : Y -> X
9351 if (Pred == ICmpInst::ICMP_NE)
9352 return ReplaceInstUsesWith(SI, TrueVal);
9353 /// NOTE: if we wanted to, this is where to detect integer MIN/MAX
9354
9355 } else if (CmpLHS == FalseVal && CmpRHS == TrueVal) {
9356 // Transform (X == Y) ? Y : X -> X
9357 if (Pred == ICmpInst::ICMP_EQ)
9358 return ReplaceInstUsesWith(SI, FalseVal);
9359 // Transform (X != Y) ? Y : X -> Y
9360 if (Pred == ICmpInst::ICMP_NE)
9361 return ReplaceInstUsesWith(SI, TrueVal);
9362 /// NOTE: if we wanted to, this is where to detect integer MIN/MAX
9363 }
9364
9365 /// NOTE: if we wanted to, this is where to detect integer ABS
9366
9367 return Changed ? &SI : 0;
9368}
9369
Chris Lattner3d69f462004-03-12 05:52:32 +00009370Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
Chris Lattnerc32b30a2004-03-30 19:37:13 +00009371 Value *CondVal = SI.getCondition();
9372 Value *TrueVal = SI.getTrueValue();
9373 Value *FalseVal = SI.getFalseValue();
9374
9375 // select true, X, Y -> X
9376 // select false, X, Y -> Y
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00009377 if (ConstantInt *C = dyn_cast<ConstantInt>(CondVal))
Reid Spencer579dca12007-01-12 04:24:46 +00009378 return ReplaceInstUsesWith(SI, C->getZExtValue() ? TrueVal : FalseVal);
Chris Lattnerc32b30a2004-03-30 19:37:13 +00009379
9380 // select C, X, X -> X
9381 if (TrueVal == FalseVal)
9382 return ReplaceInstUsesWith(SI, TrueVal);
9383
Chris Lattnere87597f2004-10-16 18:11:37 +00009384 if (isa<UndefValue>(TrueVal)) // select C, undef, X -> X
9385 return ReplaceInstUsesWith(SI, FalseVal);
9386 if (isa<UndefValue>(FalseVal)) // select C, X, undef -> X
9387 return ReplaceInstUsesWith(SI, TrueVal);
9388 if (isa<UndefValue>(CondVal)) { // select undef, X, Y -> X or Y
9389 if (isa<Constant>(TrueVal))
9390 return ReplaceInstUsesWith(SI, TrueVal);
9391 else
9392 return ReplaceInstUsesWith(SI, FalseVal);
9393 }
9394
Reid Spencer4fe16d62007-01-11 18:21:29 +00009395 if (SI.getType() == Type::Int1Ty) {
Reid Spencera54b7cb2007-01-12 07:05:14 +00009396 if (ConstantInt *C = dyn_cast<ConstantInt>(TrueVal)) {
Reid Spencer579dca12007-01-12 04:24:46 +00009397 if (C->getZExtValue()) {
Chris Lattner0c199a72004-04-08 04:43:23 +00009398 // Change: A = select B, true, C --> A = or B, C
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009399 return BinaryOperator::CreateOr(CondVal, FalseVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00009400 } else {
9401 // Change: A = select B, false, C --> A = and !B, C
9402 Value *NotCond =
Owen Anderson73c6b712009-07-13 20:58:05 +00009403 InsertNewInstBefore(BinaryOperator::CreateNot(*Context, CondVal,
Chris Lattner0c199a72004-04-08 04:43:23 +00009404 "not."+CondVal->getName()), SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009405 return BinaryOperator::CreateAnd(NotCond, FalseVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00009406 }
Reid Spencera54b7cb2007-01-12 07:05:14 +00009407 } else if (ConstantInt *C = dyn_cast<ConstantInt>(FalseVal)) {
Reid Spencer579dca12007-01-12 04:24:46 +00009408 if (C->getZExtValue() == false) {
Chris Lattner0c199a72004-04-08 04:43:23 +00009409 // Change: A = select B, C, false --> A = and B, C
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009410 return BinaryOperator::CreateAnd(CondVal, TrueVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00009411 } else {
9412 // Change: A = select B, C, true --> A = or !B, C
9413 Value *NotCond =
Owen Anderson73c6b712009-07-13 20:58:05 +00009414 InsertNewInstBefore(BinaryOperator::CreateNot(*Context, CondVal,
Chris Lattner0c199a72004-04-08 04:43:23 +00009415 "not."+CondVal->getName()), SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009416 return BinaryOperator::CreateOr(NotCond, TrueVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00009417 }
9418 }
Chris Lattnercfa59752007-11-25 21:27:53 +00009419
9420 // select a, b, a -> a&b
9421 // select a, a, b -> a|b
9422 if (CondVal == TrueVal)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009423 return BinaryOperator::CreateOr(CondVal, FalseVal);
Chris Lattnercfa59752007-11-25 21:27:53 +00009424 else if (CondVal == FalseVal)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009425 return BinaryOperator::CreateAnd(CondVal, TrueVal);
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00009426 }
Chris Lattner0c199a72004-04-08 04:43:23 +00009427
Chris Lattner2eefe512004-04-09 19:05:30 +00009428 // Selecting between two integer constants?
9429 if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
9430 if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
Chris Lattnerba417832007-04-11 06:12:58 +00009431 // select C, 1, 0 -> zext C to int
Reid Spencer2ec619a2007-03-23 21:24:59 +00009432 if (FalseValC->isZero() && TrueValC->getValue() == 1) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009433 return CastInst::Create(Instruction::ZExt, CondVal, SI.getType());
Reid Spencer2ec619a2007-03-23 21:24:59 +00009434 } else if (TrueValC->isZero() && FalseValC->getValue() == 1) {
Chris Lattnerba417832007-04-11 06:12:58 +00009435 // select C, 0, 1 -> zext !C to int
Chris Lattner2eefe512004-04-09 19:05:30 +00009436 Value *NotCond =
Owen Anderson73c6b712009-07-13 20:58:05 +00009437 InsertNewInstBefore(BinaryOperator::CreateNot(*Context, CondVal,
Chris Lattner82e14fe2004-04-09 18:19:44 +00009438 "not."+CondVal->getName()), SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009439 return CastInst::Create(Instruction::ZExt, NotCond, SI.getType());
Chris Lattner82e14fe2004-04-09 18:19:44 +00009440 }
Chris Lattner457dd822004-06-09 07:59:58 +00009441
Reid Spencere4d87aa2006-12-23 06:05:41 +00009442 if (ICmpInst *IC = dyn_cast<ICmpInst>(SI.getCondition())) {
Chris Lattnerb8456462006-09-20 04:44:59 +00009443 // If one of the constants is zero (we know they can't both be) and we
Chris Lattnerba417832007-04-11 06:12:58 +00009444 // have an icmp instruction with zero, and we have an 'and' with the
Chris Lattnerb8456462006-09-20 04:44:59 +00009445 // non-constant value, eliminate this whole mess. This corresponds to
9446 // cases like this: ((X & 27) ? 27 : 0)
Reid Spencer2ec619a2007-03-23 21:24:59 +00009447 if (TrueValC->isZero() || FalseValC->isZero())
Chris Lattner65b72ba2006-09-18 04:22:48 +00009448 if (IC->isEquality() && isa<ConstantInt>(IC->getOperand(1)) &&
Chris Lattner457dd822004-06-09 07:59:58 +00009449 cast<Constant>(IC->getOperand(1))->isNullValue())
9450 if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
9451 if (ICA->getOpcode() == Instruction::And &&
Misha Brukmanfd939082005-04-21 23:48:37 +00009452 isa<ConstantInt>(ICA->getOperand(1)) &&
9453 (ICA->getOperand(1) == TrueValC ||
9454 ICA->getOperand(1) == FalseValC) &&
Chris Lattner457dd822004-06-09 07:59:58 +00009455 isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
9456 // Okay, now we know that everything is set up, we just don't
Reid Spencere4d87aa2006-12-23 06:05:41 +00009457 // know whether we have a icmp_ne or icmp_eq and whether the
9458 // true or false val is the zero.
Reid Spencer2ec619a2007-03-23 21:24:59 +00009459 bool ShouldNotVal = !TrueValC->isZero();
Reid Spencere4d87aa2006-12-23 06:05:41 +00009460 ShouldNotVal ^= IC->getPredicate() == ICmpInst::ICMP_NE;
Chris Lattner457dd822004-06-09 07:59:58 +00009461 Value *V = ICA;
9462 if (ShouldNotVal)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009463 V = InsertNewInstBefore(BinaryOperator::Create(
Chris Lattner457dd822004-06-09 07:59:58 +00009464 Instruction::Xor, V, ICA->getOperand(1)), SI);
9465 return ReplaceInstUsesWith(SI, V);
9466 }
Chris Lattnerb8456462006-09-20 04:44:59 +00009467 }
Chris Lattnerc32b30a2004-03-30 19:37:13 +00009468 }
Chris Lattnerd76956d2004-04-10 22:21:27 +00009469
9470 // See if we are selecting two values based on a comparison of the two values.
Reid Spencere4d87aa2006-12-23 06:05:41 +00009471 if (FCmpInst *FCI = dyn_cast<FCmpInst>(CondVal)) {
9472 if (FCI->getOperand(0) == TrueVal && FCI->getOperand(1) == FalseVal) {
Chris Lattnerd76956d2004-04-10 22:21:27 +00009473 // Transform (X == Y) ? X : Y -> Y
Dale Johannesen5a2174f2007-10-03 17:45:27 +00009474 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
9475 // This is not safe in general for floating point:
9476 // consider X== -0, Y== +0.
9477 // It becomes safe if either operand is a nonzero constant.
9478 ConstantFP *CFPt, *CFPf;
9479 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
9480 !CFPt->getValueAPF().isZero()) ||
9481 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
9482 !CFPf->getValueAPF().isZero()))
Chris Lattnerd76956d2004-04-10 22:21:27 +00009483 return ReplaceInstUsesWith(SI, FalseVal);
Dale Johannesen5a2174f2007-10-03 17:45:27 +00009484 }
Chris Lattnerd76956d2004-04-10 22:21:27 +00009485 // Transform (X != Y) ? X : Y -> X
Reid Spencere4d87aa2006-12-23 06:05:41 +00009486 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
Chris Lattnerd76956d2004-04-10 22:21:27 +00009487 return ReplaceInstUsesWith(SI, TrueVal);
Dan Gohman81b28ce2008-09-16 18:46:06 +00009488 // NOTE: if we wanted to, this is where to detect MIN/MAX
Chris Lattnerd76956d2004-04-10 22:21:27 +00009489
Reid Spencere4d87aa2006-12-23 06:05:41 +00009490 } else if (FCI->getOperand(0) == FalseVal && FCI->getOperand(1) == TrueVal){
Chris Lattnerd76956d2004-04-10 22:21:27 +00009491 // Transform (X == Y) ? Y : X -> X
Dale Johannesen5a2174f2007-10-03 17:45:27 +00009492 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
9493 // This is not safe in general for floating point:
9494 // consider X== -0, Y== +0.
9495 // It becomes safe if either operand is a nonzero constant.
9496 ConstantFP *CFPt, *CFPf;
9497 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
9498 !CFPt->getValueAPF().isZero()) ||
9499 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
9500 !CFPf->getValueAPF().isZero()))
9501 return ReplaceInstUsesWith(SI, FalseVal);
9502 }
Chris Lattnerd76956d2004-04-10 22:21:27 +00009503 // Transform (X != Y) ? Y : X -> Y
Reid Spencere4d87aa2006-12-23 06:05:41 +00009504 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
9505 return ReplaceInstUsesWith(SI, TrueVal);
Dan Gohman81b28ce2008-09-16 18:46:06 +00009506 // NOTE: if we wanted to, this is where to detect MIN/MAX
Reid Spencere4d87aa2006-12-23 06:05:41 +00009507 }
Dan Gohman81b28ce2008-09-16 18:46:06 +00009508 // NOTE: if we wanted to, this is where to detect ABS
Reid Spencere4d87aa2006-12-23 06:05:41 +00009509 }
9510
9511 // See if we are selecting two values based on a comparison of the two values.
Dan Gohman81b28ce2008-09-16 18:46:06 +00009512 if (ICmpInst *ICI = dyn_cast<ICmpInst>(CondVal))
9513 if (Instruction *Result = visitSelectInstWithICmp(SI, ICI))
9514 return Result;
Misha Brukmanfd939082005-04-21 23:48:37 +00009515
Chris Lattner87875da2005-01-13 22:52:24 +00009516 if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
9517 if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
9518 if (TI->hasOneUse() && FI->hasOneUse()) {
Chris Lattner87875da2005-01-13 22:52:24 +00009519 Instruction *AddOp = 0, *SubOp = 0;
9520
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009521 // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
9522 if (TI->getOpcode() == FI->getOpcode())
9523 if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
9524 return IV;
9525
9526 // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))). This is
9527 // even legal for FP.
Dan Gohmanae3a0be2009-06-04 22:49:04 +00009528 if ((TI->getOpcode() == Instruction::Sub &&
9529 FI->getOpcode() == Instruction::Add) ||
9530 (TI->getOpcode() == Instruction::FSub &&
9531 FI->getOpcode() == Instruction::FAdd)) {
Chris Lattner87875da2005-01-13 22:52:24 +00009532 AddOp = FI; SubOp = TI;
Dan Gohmanae3a0be2009-06-04 22:49:04 +00009533 } else if ((FI->getOpcode() == Instruction::Sub &&
9534 TI->getOpcode() == Instruction::Add) ||
9535 (FI->getOpcode() == Instruction::FSub &&
9536 TI->getOpcode() == Instruction::FAdd)) {
Chris Lattner87875da2005-01-13 22:52:24 +00009537 AddOp = TI; SubOp = FI;
9538 }
9539
9540 if (AddOp) {
9541 Value *OtherAddOp = 0;
9542 if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
9543 OtherAddOp = AddOp->getOperand(1);
9544 } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
9545 OtherAddOp = AddOp->getOperand(0);
9546 }
9547
9548 if (OtherAddOp) {
Chris Lattner97f37a42006-02-24 18:05:58 +00009549 // So at this point we know we have (Y -> OtherAddOp):
9550 // select C, (add X, Y), (sub X, Z)
9551 Value *NegVal; // Compute -Z
9552 if (Constant *C = dyn_cast<Constant>(SubOp->getOperand(1))) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00009553 NegVal = ConstantExpr::getNeg(C);
Chris Lattner97f37a42006-02-24 18:05:58 +00009554 } else {
9555 NegVal = InsertNewInstBefore(
Owen Anderson0a5372e2009-07-13 04:09:18 +00009556 BinaryOperator::CreateNeg(*Context, SubOp->getOperand(1),
9557 "tmp"), SI);
Chris Lattner87875da2005-01-13 22:52:24 +00009558 }
Chris Lattner97f37a42006-02-24 18:05:58 +00009559
9560 Value *NewTrueOp = OtherAddOp;
9561 Value *NewFalseOp = NegVal;
9562 if (AddOp != TI)
9563 std::swap(NewTrueOp, NewFalseOp);
9564 Instruction *NewSel =
Gabor Greifb1dbcd82008-05-15 10:04:30 +00009565 SelectInst::Create(CondVal, NewTrueOp,
9566 NewFalseOp, SI.getName() + ".p");
Chris Lattner97f37a42006-02-24 18:05:58 +00009567
9568 NewSel = InsertNewInstBefore(NewSel, SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009569 return BinaryOperator::CreateAdd(SubOp->getOperand(0), NewSel);
Chris Lattner87875da2005-01-13 22:52:24 +00009570 }
9571 }
9572 }
Misha Brukmanfd939082005-04-21 23:48:37 +00009573
Chris Lattnere576b912004-04-09 23:46:01 +00009574 // See if we can fold the select into one of our operands.
Chris Lattner42a75512007-01-15 02:27:26 +00009575 if (SI.getType()->isInteger()) {
Evan Chengde621922009-03-31 20:42:45 +00009576 Instruction *FoldI = FoldSelectIntoOp(SI, TrueVal, FalseVal);
9577 if (FoldI)
9578 return FoldI;
Chris Lattnere576b912004-04-09 23:46:01 +00009579 }
Chris Lattnera1df33c2005-04-24 07:30:14 +00009580
9581 if (BinaryOperator::isNot(CondVal)) {
9582 SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
9583 SI.setOperand(1, FalseVal);
9584 SI.setOperand(2, TrueVal);
9585 return &SI;
9586 }
9587
Chris Lattner3d69f462004-03-12 05:52:32 +00009588 return 0;
9589}
9590
Dan Gohmaneee962e2008-04-10 18:43:06 +00009591/// EnforceKnownAlignment - If the specified pointer points to an object that
9592/// we control, modify the object's alignment to PrefAlign. This isn't
9593/// often possible though. If alignment is important, a more reliable approach
9594/// is to simply align all global variables and allocation instructions to
9595/// their preferred alignment from the beginning.
9596///
9597static unsigned EnforceKnownAlignment(Value *V,
9598 unsigned Align, unsigned PrefAlign) {
Chris Lattnerf2369f22007-08-09 19:05:49 +00009599
Dan Gohmaneee962e2008-04-10 18:43:06 +00009600 User *U = dyn_cast<User>(V);
9601 if (!U) return Align;
9602
Dan Gohmanca178902009-07-17 20:47:02 +00009603 switch (Operator::getOpcode(U)) {
Dan Gohmaneee962e2008-04-10 18:43:06 +00009604 default: break;
9605 case Instruction::BitCast:
9606 return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
9607 case Instruction::GetElementPtr: {
Chris Lattner95a959d2006-03-06 20:18:44 +00009608 // If all indexes are zero, it is just the alignment of the base pointer.
9609 bool AllZeroOperands = true;
Gabor Greif52ed3632008-06-12 21:51:29 +00009610 for (User::op_iterator i = U->op_begin() + 1, e = U->op_end(); i != e; ++i)
Gabor Greif177dd3f2008-06-12 21:37:33 +00009611 if (!isa<Constant>(*i) ||
9612 !cast<Constant>(*i)->isNullValue()) {
Chris Lattner95a959d2006-03-06 20:18:44 +00009613 AllZeroOperands = false;
9614 break;
9615 }
Chris Lattnerf2369f22007-08-09 19:05:49 +00009616
9617 if (AllZeroOperands) {
9618 // Treat this like a bitcast.
Dan Gohmaneee962e2008-04-10 18:43:06 +00009619 return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
Chris Lattnerf2369f22007-08-09 19:05:49 +00009620 }
Dan Gohmaneee962e2008-04-10 18:43:06 +00009621 break;
Chris Lattner95a959d2006-03-06 20:18:44 +00009622 }
Dan Gohmaneee962e2008-04-10 18:43:06 +00009623 }
9624
9625 if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
9626 // If there is a large requested alignment and we can, bump up the alignment
9627 // of the global.
9628 if (!GV->isDeclaration()) {
Dan Gohmanecd0fb52009-02-16 23:02:21 +00009629 if (GV->getAlignment() >= PrefAlign)
9630 Align = GV->getAlignment();
9631 else {
9632 GV->setAlignment(PrefAlign);
9633 Align = PrefAlign;
9634 }
Dan Gohmaneee962e2008-04-10 18:43:06 +00009635 }
9636 } else if (AllocationInst *AI = dyn_cast<AllocationInst>(V)) {
9637 // If there is a requested alignment and if this is an alloca, round up. We
9638 // don't do this for malloc, because some systems can't respect the request.
9639 if (isa<AllocaInst>(AI)) {
Dan Gohmanecd0fb52009-02-16 23:02:21 +00009640 if (AI->getAlignment() >= PrefAlign)
9641 Align = AI->getAlignment();
9642 else {
9643 AI->setAlignment(PrefAlign);
9644 Align = PrefAlign;
9645 }
Dan Gohmaneee962e2008-04-10 18:43:06 +00009646 }
9647 }
9648
9649 return Align;
9650}
9651
9652/// GetOrEnforceKnownAlignment - If the specified pointer has an alignment that
9653/// we can determine, return it, otherwise return 0. If PrefAlign is specified,
9654/// and it is more than the alignment of the ultimate object, see if we can
9655/// increase the alignment of the ultimate object, making this check succeed.
9656unsigned InstCombiner::GetOrEnforceKnownAlignment(Value *V,
9657 unsigned PrefAlign) {
9658 unsigned BitWidth = TD ? TD->getTypeSizeInBits(V->getType()) :
9659 sizeof(PrefAlign) * CHAR_BIT;
9660 APInt Mask = APInt::getAllOnesValue(BitWidth);
9661 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
9662 ComputeMaskedBits(V, Mask, KnownZero, KnownOne);
9663 unsigned TrailZ = KnownZero.countTrailingOnes();
9664 unsigned Align = 1u << std::min(BitWidth - 1, TrailZ);
9665
9666 if (PrefAlign > Align)
9667 Align = EnforceKnownAlignment(V, Align, PrefAlign);
9668
9669 // We don't need to make any adjustment.
9670 return Align;
Chris Lattner95a959d2006-03-06 20:18:44 +00009671}
9672
Chris Lattnerf497b022008-01-13 23:50:23 +00009673Instruction *InstCombiner::SimplifyMemTransfer(MemIntrinsic *MI) {
Dan Gohmaneee962e2008-04-10 18:43:06 +00009674 unsigned DstAlign = GetOrEnforceKnownAlignment(MI->getOperand(1));
Dan Gohmanbc989d42009-02-22 18:06:32 +00009675 unsigned SrcAlign = GetOrEnforceKnownAlignment(MI->getOperand(2));
Chris Lattnerf497b022008-01-13 23:50:23 +00009676 unsigned MinAlign = std::min(DstAlign, SrcAlign);
Chris Lattnerdfe964c2009-03-08 03:59:00 +00009677 unsigned CopyAlign = MI->getAlignment();
Chris Lattnerf497b022008-01-13 23:50:23 +00009678
9679 if (CopyAlign < MinAlign) {
Owen Andersoneed707b2009-07-24 23:12:02 +00009680 MI->setAlignment(ConstantInt::get(MI->getAlignmentType(),
Owen Andersona547b472009-07-09 18:36:20 +00009681 MinAlign, false));
Chris Lattnerf497b022008-01-13 23:50:23 +00009682 return MI;
9683 }
9684
9685 // If MemCpyInst length is 1/2/4/8 bytes then replace memcpy with
9686 // load/store.
9687 ConstantInt *MemOpLength = dyn_cast<ConstantInt>(MI->getOperand(3));
9688 if (MemOpLength == 0) return 0;
9689
Chris Lattner37ac6082008-01-14 00:28:35 +00009690 // Source and destination pointer types are always "i8*" for intrinsic. See
9691 // if the size is something we can handle with a single primitive load/store.
9692 // A single load+store correctly handles overlapping memory in the memmove
9693 // case.
Chris Lattnerf497b022008-01-13 23:50:23 +00009694 unsigned Size = MemOpLength->getZExtValue();
Chris Lattner69ea9d22008-04-30 06:39:11 +00009695 if (Size == 0) return MI; // Delete this mem transfer.
9696
9697 if (Size > 8 || (Size&(Size-1)))
Chris Lattner37ac6082008-01-14 00:28:35 +00009698 return 0; // If not 1/2/4/8 bytes, exit.
Chris Lattnerf497b022008-01-13 23:50:23 +00009699
Chris Lattner37ac6082008-01-14 00:28:35 +00009700 // Use an integer load+store unless we can find something better.
Owen Andersond672ecb2009-07-03 00:17:18 +00009701 Type *NewPtrTy =
Owen Andersondebcb012009-07-29 22:17:13 +00009702 PointerType::getUnqual(IntegerType::get(Size<<3));
Chris Lattner37ac6082008-01-14 00:28:35 +00009703
9704 // Memcpy forces the use of i8* for the source and destination. That means
9705 // that if you're using memcpy to move one double around, you'll get a cast
9706 // from double* to i8*. We'd much rather use a double load+store rather than
9707 // an i64 load+store, here because this improves the odds that the source or
9708 // dest address will be promotable. See if we can find a better type than the
9709 // integer datatype.
9710 if (Value *Op = getBitCastOperand(MI->getOperand(1))) {
9711 const Type *SrcETy = cast<PointerType>(Op->getType())->getElementType();
Dan Gohmance9fe9f2009-07-21 23:21:54 +00009712 if (TD && SrcETy->isSized() && TD->getTypeStoreSize(SrcETy) == Size) {
Chris Lattner37ac6082008-01-14 00:28:35 +00009713 // The SrcETy might be something like {{{double}}} or [1 x double]. Rip
9714 // down through these levels if so.
Dan Gohman8f8e2692008-05-23 01:52:21 +00009715 while (!SrcETy->isSingleValueType()) {
Chris Lattner37ac6082008-01-14 00:28:35 +00009716 if (const StructType *STy = dyn_cast<StructType>(SrcETy)) {
9717 if (STy->getNumElements() == 1)
9718 SrcETy = STy->getElementType(0);
9719 else
9720 break;
9721 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcETy)) {
9722 if (ATy->getNumElements() == 1)
9723 SrcETy = ATy->getElementType();
9724 else
9725 break;
9726 } else
9727 break;
9728 }
9729
Dan Gohman8f8e2692008-05-23 01:52:21 +00009730 if (SrcETy->isSingleValueType())
Owen Andersondebcb012009-07-29 22:17:13 +00009731 NewPtrTy = PointerType::getUnqual(SrcETy);
Chris Lattner37ac6082008-01-14 00:28:35 +00009732 }
9733 }
9734
9735
Chris Lattnerf497b022008-01-13 23:50:23 +00009736 // If the memcpy/memmove provides better alignment info than we can
9737 // infer, use it.
9738 SrcAlign = std::max(SrcAlign, CopyAlign);
9739 DstAlign = std::max(DstAlign, CopyAlign);
9740
9741 Value *Src = InsertBitCastBefore(MI->getOperand(2), NewPtrTy, *MI);
9742 Value *Dest = InsertBitCastBefore(MI->getOperand(1), NewPtrTy, *MI);
Chris Lattner37ac6082008-01-14 00:28:35 +00009743 Instruction *L = new LoadInst(Src, "tmp", false, SrcAlign);
9744 InsertNewInstBefore(L, *MI);
9745 InsertNewInstBefore(new StoreInst(L, Dest, false, DstAlign), *MI);
9746
9747 // Set the size of the copy to 0, it will be deleted on the next iteration.
Owen Andersona7235ea2009-07-31 20:28:14 +00009748 MI->setOperand(3, Constant::getNullValue(MemOpLength->getType()));
Chris Lattner37ac6082008-01-14 00:28:35 +00009749 return MI;
Chris Lattnerf497b022008-01-13 23:50:23 +00009750}
Chris Lattner3d69f462004-03-12 05:52:32 +00009751
Chris Lattner69ea9d22008-04-30 06:39:11 +00009752Instruction *InstCombiner::SimplifyMemSet(MemSetInst *MI) {
9753 unsigned Alignment = GetOrEnforceKnownAlignment(MI->getDest());
Chris Lattnerdfe964c2009-03-08 03:59:00 +00009754 if (MI->getAlignment() < Alignment) {
Owen Andersoneed707b2009-07-24 23:12:02 +00009755 MI->setAlignment(ConstantInt::get(MI->getAlignmentType(),
Owen Andersona547b472009-07-09 18:36:20 +00009756 Alignment, false));
Chris Lattner69ea9d22008-04-30 06:39:11 +00009757 return MI;
9758 }
9759
9760 // Extract the length and alignment and fill if they are constant.
9761 ConstantInt *LenC = dyn_cast<ConstantInt>(MI->getLength());
9762 ConstantInt *FillC = dyn_cast<ConstantInt>(MI->getValue());
9763 if (!LenC || !FillC || FillC->getType() != Type::Int8Ty)
9764 return 0;
9765 uint64_t Len = LenC->getZExtValue();
Chris Lattnerdfe964c2009-03-08 03:59:00 +00009766 Alignment = MI->getAlignment();
Chris Lattner69ea9d22008-04-30 06:39:11 +00009767
9768 // If the length is zero, this is a no-op
9769 if (Len == 0) return MI; // memset(d,c,0,a) -> noop
9770
9771 // memset(s,c,n) -> store s, c (for n=1,2,4,8)
9772 if (Len <= 8 && isPowerOf2_32((uint32_t)Len)) {
Owen Andersondebcb012009-07-29 22:17:13 +00009773 const Type *ITy = IntegerType::get(Len*8); // n=1 -> i8.
Chris Lattner69ea9d22008-04-30 06:39:11 +00009774
9775 Value *Dest = MI->getDest();
Owen Andersondebcb012009-07-29 22:17:13 +00009776 Dest = InsertBitCastBefore(Dest, PointerType::getUnqual(ITy), *MI);
Chris Lattner69ea9d22008-04-30 06:39:11 +00009777
9778 // Alignment 0 is identity for alignment 1 for memset, but not store.
9779 if (Alignment == 0) Alignment = 1;
9780
9781 // Extract the fill value and store.
9782 uint64_t Fill = FillC->getZExtValue()*0x0101010101010101ULL;
Owen Andersoneed707b2009-07-24 23:12:02 +00009783 InsertNewInstBefore(new StoreInst(ConstantInt::get(ITy, Fill),
Owen Andersond672ecb2009-07-03 00:17:18 +00009784 Dest, false, Alignment), *MI);
Chris Lattner69ea9d22008-04-30 06:39:11 +00009785
9786 // Set the size of the copy to 0, it will be deleted on the next iteration.
Owen Andersona7235ea2009-07-31 20:28:14 +00009787 MI->setLength(Constant::getNullValue(LenC->getType()));
Chris Lattner69ea9d22008-04-30 06:39:11 +00009788 return MI;
9789 }
9790
9791 return 0;
9792}
9793
9794
Chris Lattner8b0ea312006-01-13 20:11:04 +00009795/// visitCallInst - CallInst simplification. This mostly only handles folding
9796/// of intrinsic instructions. For normal calls, it allows visitCallSite to do
9797/// the heavy lifting.
9798///
Chris Lattner9fe38862003-06-19 17:00:31 +00009799Instruction *InstCombiner::visitCallInst(CallInst &CI) {
Chris Lattneraab6ec42009-05-13 17:39:14 +00009800 // If the caller function is nounwind, mark the call as nounwind, even if the
9801 // callee isn't.
9802 if (CI.getParent()->getParent()->doesNotThrow() &&
9803 !CI.doesNotThrow()) {
9804 CI.setDoesNotThrow();
9805 return &CI;
9806 }
9807
9808
9809
Chris Lattner8b0ea312006-01-13 20:11:04 +00009810 IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
9811 if (!II) return visitCallSite(&CI);
9812
Chris Lattner7bcc0e72004-02-28 05:22:00 +00009813 // Intrinsics cannot occur in an invoke, so handle them here instead of in
9814 // visitCallSite.
Chris Lattner8b0ea312006-01-13 20:11:04 +00009815 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
Chris Lattner35b9e482004-10-12 04:52:52 +00009816 bool Changed = false;
9817
9818 // memmove/cpy/set of zero bytes is a noop.
9819 if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
9820 if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
9821
Chris Lattner35b9e482004-10-12 04:52:52 +00009822 if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
Reid Spencerb83eb642006-10-20 07:07:24 +00009823 if (CI->getZExtValue() == 1) {
Chris Lattner35b9e482004-10-12 04:52:52 +00009824 // Replace the instruction with just byte operations. We would
9825 // transform other cases to loads/stores, but we don't know if
9826 // alignment is sufficient.
9827 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +00009828 }
9829
Chris Lattner35b9e482004-10-12 04:52:52 +00009830 // If we have a memmove and the source operation is a constant global,
9831 // then the source and dest pointers can't alias, so we can change this
9832 // into a call to memcpy.
Chris Lattnerf497b022008-01-13 23:50:23 +00009833 if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(MI)) {
Chris Lattner35b9e482004-10-12 04:52:52 +00009834 if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
9835 if (GVSrc->isConstant()) {
9836 Module *M = CI.getParent()->getParent()->getParent();
Chris Lattner824b9582008-11-21 16:42:48 +00009837 Intrinsic::ID MemCpyID = Intrinsic::memcpy;
9838 const Type *Tys[1];
9839 Tys[0] = CI.getOperand(3)->getType();
9840 CI.setOperand(0,
9841 Intrinsic::getDeclaration(M, MemCpyID, Tys, 1));
Chris Lattner35b9e482004-10-12 04:52:52 +00009842 Changed = true;
9843 }
Chris Lattnera935db82008-05-28 05:30:41 +00009844
9845 // memmove(x,x,size) -> noop.
9846 if (MMI->getSource() == MMI->getDest())
9847 return EraseInstFromFunction(CI);
Chris Lattner95a959d2006-03-06 20:18:44 +00009848 }
Chris Lattner35b9e482004-10-12 04:52:52 +00009849
Chris Lattner95a959d2006-03-06 20:18:44 +00009850 // If we can determine a pointer alignment that is bigger than currently
9851 // set, update the alignment.
Chris Lattner3ce5e882009-03-08 03:37:16 +00009852 if (isa<MemTransferInst>(MI)) {
Chris Lattnerf497b022008-01-13 23:50:23 +00009853 if (Instruction *I = SimplifyMemTransfer(MI))
9854 return I;
Chris Lattner69ea9d22008-04-30 06:39:11 +00009855 } else if (MemSetInst *MSI = dyn_cast<MemSetInst>(MI)) {
9856 if (Instruction *I = SimplifyMemSet(MSI))
9857 return I;
Chris Lattner95a959d2006-03-06 20:18:44 +00009858 }
9859
Chris Lattner8b0ea312006-01-13 20:11:04 +00009860 if (Changed) return II;
Chris Lattner0521e3c2008-06-18 04:33:20 +00009861 }
9862
9863 switch (II->getIntrinsicID()) {
9864 default: break;
9865 case Intrinsic::bswap:
9866 // bswap(bswap(x)) -> x
9867 if (IntrinsicInst *Operand = dyn_cast<IntrinsicInst>(II->getOperand(1)))
9868 if (Operand->getIntrinsicID() == Intrinsic::bswap)
9869 return ReplaceInstUsesWith(CI, Operand->getOperand(1));
9870 break;
9871 case Intrinsic::ppc_altivec_lvx:
9872 case Intrinsic::ppc_altivec_lvxl:
9873 case Intrinsic::x86_sse_loadu_ps:
9874 case Intrinsic::x86_sse2_loadu_pd:
9875 case Intrinsic::x86_sse2_loadu_dq:
9876 // Turn PPC lvx -> load if the pointer is known aligned.
9877 // Turn X86 loadups -> load if the pointer is known aligned.
9878 if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
9879 Value *Ptr = InsertBitCastBefore(II->getOperand(1),
Owen Andersondebcb012009-07-29 22:17:13 +00009880 PointerType::getUnqual(II->getType()),
Chris Lattner0521e3c2008-06-18 04:33:20 +00009881 CI);
9882 return new LoadInst(Ptr);
Chris Lattner867b99f2006-10-05 06:55:50 +00009883 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00009884 break;
9885 case Intrinsic::ppc_altivec_stvx:
9886 case Intrinsic::ppc_altivec_stvxl:
9887 // Turn stvx -> store if the pointer is known aligned.
9888 if (GetOrEnforceKnownAlignment(II->getOperand(2), 16) >= 16) {
9889 const Type *OpPtrTy =
Owen Andersondebcb012009-07-29 22:17:13 +00009890 PointerType::getUnqual(II->getOperand(1)->getType());
Chris Lattner0521e3c2008-06-18 04:33:20 +00009891 Value *Ptr = InsertBitCastBefore(II->getOperand(2), OpPtrTy, CI);
9892 return new StoreInst(II->getOperand(1), Ptr);
9893 }
9894 break;
9895 case Intrinsic::x86_sse_storeu_ps:
9896 case Intrinsic::x86_sse2_storeu_pd:
9897 case Intrinsic::x86_sse2_storeu_dq:
Chris Lattner0521e3c2008-06-18 04:33:20 +00009898 // Turn X86 storeu -> store if the pointer is known aligned.
9899 if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
9900 const Type *OpPtrTy =
Owen Andersondebcb012009-07-29 22:17:13 +00009901 PointerType::getUnqual(II->getOperand(2)->getType());
Chris Lattner0521e3c2008-06-18 04:33:20 +00009902 Value *Ptr = InsertBitCastBefore(II->getOperand(1), OpPtrTy, CI);
9903 return new StoreInst(II->getOperand(2), Ptr);
9904 }
9905 break;
9906
9907 case Intrinsic::x86_sse_cvttss2si: {
9908 // These intrinsics only demands the 0th element of its input vector. If
9909 // we can simplify the input based on that, do so now.
Evan Cheng388df622009-02-03 10:05:09 +00009910 unsigned VWidth =
9911 cast<VectorType>(II->getOperand(1)->getType())->getNumElements();
9912 APInt DemandedElts(VWidth, 1);
9913 APInt UndefElts(VWidth, 0);
9914 if (Value *V = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
Chris Lattner0521e3c2008-06-18 04:33:20 +00009915 UndefElts)) {
9916 II->setOperand(1, V);
9917 return II;
9918 }
9919 break;
9920 }
9921
9922 case Intrinsic::ppc_altivec_vperm:
9923 // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant.
9924 if (ConstantVector *Mask = dyn_cast<ConstantVector>(II->getOperand(3))) {
9925 assert(Mask->getNumOperands() == 16 && "Bad type for intrinsic!");
Chris Lattner867b99f2006-10-05 06:55:50 +00009926
Chris Lattner0521e3c2008-06-18 04:33:20 +00009927 // Check that all of the elements are integer constants or undefs.
9928 bool AllEltsOk = true;
9929 for (unsigned i = 0; i != 16; ++i) {
9930 if (!isa<ConstantInt>(Mask->getOperand(i)) &&
9931 !isa<UndefValue>(Mask->getOperand(i))) {
9932 AllEltsOk = false;
9933 break;
9934 }
9935 }
9936
9937 if (AllEltsOk) {
9938 // Cast the input vectors to byte vectors.
9939 Value *Op0 =InsertBitCastBefore(II->getOperand(1),Mask->getType(),CI);
9940 Value *Op1 =InsertBitCastBefore(II->getOperand(2),Mask->getType(),CI);
Owen Anderson9e9a0d52009-07-30 23:03:37 +00009941 Value *Result = UndefValue::get(Op0->getType());
Chris Lattnere2ed0572006-04-06 19:19:17 +00009942
Chris Lattner0521e3c2008-06-18 04:33:20 +00009943 // Only extract each element once.
9944 Value *ExtractedElts[32];
9945 memset(ExtractedElts, 0, sizeof(ExtractedElts));
9946
Chris Lattnere2ed0572006-04-06 19:19:17 +00009947 for (unsigned i = 0; i != 16; ++i) {
Chris Lattner0521e3c2008-06-18 04:33:20 +00009948 if (isa<UndefValue>(Mask->getOperand(i)))
9949 continue;
9950 unsigned Idx=cast<ConstantInt>(Mask->getOperand(i))->getZExtValue();
9951 Idx &= 31; // Match the hardware behavior.
9952
9953 if (ExtractedElts[Idx] == 0) {
9954 Instruction *Elt =
Eric Christophera3500da2009-07-25 02:28:41 +00009955 ExtractElementInst::Create(Idx < 16 ? Op0 : Op1,
Owen Andersoneed707b2009-07-24 23:12:02 +00009956 ConstantInt::get(Type::Int32Ty, Idx&15, false), "tmp");
Chris Lattner0521e3c2008-06-18 04:33:20 +00009957 InsertNewInstBefore(Elt, CI);
9958 ExtractedElts[Idx] = Elt;
Chris Lattnere2ed0572006-04-06 19:19:17 +00009959 }
Chris Lattnere2ed0572006-04-06 19:19:17 +00009960
Chris Lattner0521e3c2008-06-18 04:33:20 +00009961 // Insert this value into the result vector.
9962 Result = InsertElementInst::Create(Result, ExtractedElts[Idx],
Owen Andersoneed707b2009-07-24 23:12:02 +00009963 ConstantInt::get(Type::Int32Ty, i, false),
Owen Anderson9adc0ab2009-07-14 23:09:55 +00009964 "tmp");
Chris Lattner0521e3c2008-06-18 04:33:20 +00009965 InsertNewInstBefore(cast<Instruction>(Result), CI);
Chris Lattnere2ed0572006-04-06 19:19:17 +00009966 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00009967 return CastInst::Create(Instruction::BitCast, Result, CI.getType());
Chris Lattnere2ed0572006-04-06 19:19:17 +00009968 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00009969 }
9970 break;
Chris Lattnere2ed0572006-04-06 19:19:17 +00009971
Chris Lattner0521e3c2008-06-18 04:33:20 +00009972 case Intrinsic::stackrestore: {
9973 // If the save is right next to the restore, remove the restore. This can
9974 // happen when variable allocas are DCE'd.
9975 if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getOperand(1))) {
9976 if (SS->getIntrinsicID() == Intrinsic::stacksave) {
9977 BasicBlock::iterator BI = SS;
9978 if (&*++BI == II)
9979 return EraseInstFromFunction(CI);
Chris Lattnera728ddc2006-01-13 21:28:09 +00009980 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00009981 }
9982
9983 // Scan down this block to see if there is another stack restore in the
9984 // same block without an intervening call/alloca.
9985 BasicBlock::iterator BI = II;
9986 TerminatorInst *TI = II->getParent()->getTerminator();
9987 bool CannotRemove = false;
9988 for (++BI; &*BI != TI; ++BI) {
9989 if (isa<AllocaInst>(BI)) {
9990 CannotRemove = true;
9991 break;
9992 }
Chris Lattneraa0bf522008-06-25 05:59:28 +00009993 if (CallInst *BCI = dyn_cast<CallInst>(BI)) {
9994 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(BCI)) {
9995 // If there is a stackrestore below this one, remove this one.
9996 if (II->getIntrinsicID() == Intrinsic::stackrestore)
9997 return EraseInstFromFunction(CI);
9998 // Otherwise, ignore the intrinsic.
9999 } else {
10000 // If we found a non-intrinsic call, we can't remove the stack
10001 // restore.
Chris Lattnerbf1d8a72008-02-18 06:12:38 +000010002 CannotRemove = true;
10003 break;
10004 }
Chris Lattner0521e3c2008-06-18 04:33:20 +000010005 }
Chris Lattnera728ddc2006-01-13 21:28:09 +000010006 }
Chris Lattner0521e3c2008-06-18 04:33:20 +000010007
10008 // If the stack restore is in a return/unwind block and if there are no
10009 // allocas or calls between the restore and the return, nuke the restore.
10010 if (!CannotRemove && (isa<ReturnInst>(TI) || isa<UnwindInst>(TI)))
10011 return EraseInstFromFunction(CI);
10012 break;
10013 }
Chris Lattner35b9e482004-10-12 04:52:52 +000010014 }
10015
Chris Lattner8b0ea312006-01-13 20:11:04 +000010016 return visitCallSite(II);
Chris Lattner9fe38862003-06-19 17:00:31 +000010017}
10018
10019// InvokeInst simplification
10020//
10021Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
Chris Lattnera44d8a22003-10-07 22:32:43 +000010022 return visitCallSite(&II);
Chris Lattner9fe38862003-06-19 17:00:31 +000010023}
10024
Dale Johannesenda30ccb2008-04-25 21:16:07 +000010025/// isSafeToEliminateVarargsCast - If this cast does not affect the value
10026/// passed through the varargs area, we can eliminate the use of the cast.
Dale Johannesen1f530a52008-04-23 18:34:37 +000010027static bool isSafeToEliminateVarargsCast(const CallSite CS,
10028 const CastInst * const CI,
10029 const TargetData * const TD,
10030 const int ix) {
10031 if (!CI->isLosslessCast())
10032 return false;
10033
10034 // The size of ByVal arguments is derived from the type, so we
10035 // can't change to a type with a different size. If the size were
10036 // passed explicitly we could avoid this check.
Devang Patel05988662008-09-25 21:00:45 +000010037 if (!CS.paramHasAttr(ix, Attribute::ByVal))
Dale Johannesen1f530a52008-04-23 18:34:37 +000010038 return true;
10039
10040 const Type* SrcTy =
10041 cast<PointerType>(CI->getOperand(0)->getType())->getElementType();
10042 const Type* DstTy = cast<PointerType>(CI->getType())->getElementType();
10043 if (!SrcTy->isSized() || !DstTy->isSized())
10044 return false;
Dan Gohmance9fe9f2009-07-21 23:21:54 +000010045 if (!TD || TD->getTypeAllocSize(SrcTy) != TD->getTypeAllocSize(DstTy))
Dale Johannesen1f530a52008-04-23 18:34:37 +000010046 return false;
10047 return true;
10048}
10049
Chris Lattnera44d8a22003-10-07 22:32:43 +000010050// visitCallSite - Improvements for call and invoke instructions.
10051//
10052Instruction *InstCombiner::visitCallSite(CallSite CS) {
Chris Lattner6c266db2003-10-07 22:54:13 +000010053 bool Changed = false;
10054
10055 // If the callee is a constexpr cast of a function, attempt to move the cast
10056 // to the arguments of the call/invoke.
Chris Lattnera44d8a22003-10-07 22:32:43 +000010057 if (transformConstExprCastCall(CS)) return 0;
10058
Chris Lattner6c266db2003-10-07 22:54:13 +000010059 Value *Callee = CS.getCalledValue();
Chris Lattnere87597f2004-10-16 18:11:37 +000010060
Chris Lattner08b22ec2005-05-13 07:09:09 +000010061 if (Function *CalleeF = dyn_cast<Function>(Callee))
10062 if (CalleeF->getCallingConv() != CS.getCallingConv()) {
10063 Instruction *OldCall = CS.getInstruction();
10064 // If the call and callee calling conventions don't match, this call must
10065 // be unreachable, as the call is undefined.
Owen Anderson5defacc2009-07-31 17:39:07 +000010066 new StoreInst(ConstantInt::getTrue(*Context),
Owen Anderson9e9a0d52009-07-30 23:03:37 +000010067 UndefValue::get(PointerType::getUnqual(Type::Int1Ty)),
Owen Andersond672ecb2009-07-03 00:17:18 +000010068 OldCall);
Chris Lattner08b22ec2005-05-13 07:09:09 +000010069 if (!OldCall->use_empty())
Owen Anderson9e9a0d52009-07-30 23:03:37 +000010070 OldCall->replaceAllUsesWith(UndefValue::get(OldCall->getType()));
Chris Lattner08b22ec2005-05-13 07:09:09 +000010071 if (isa<CallInst>(OldCall)) // Not worth removing an invoke here.
10072 return EraseInstFromFunction(*OldCall);
10073 return 0;
10074 }
10075
Chris Lattner17be6352004-10-18 02:59:09 +000010076 if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
10077 // This instruction is not reachable, just remove it. We insert a store to
10078 // undef so that we know that this code is not reachable, despite the fact
10079 // that we can't modify the CFG here.
Owen Anderson5defacc2009-07-31 17:39:07 +000010080 new StoreInst(ConstantInt::getTrue(*Context),
Owen Anderson9e9a0d52009-07-30 23:03:37 +000010081 UndefValue::get(PointerType::getUnqual(Type::Int1Ty)),
Chris Lattner17be6352004-10-18 02:59:09 +000010082 CS.getInstruction());
10083
10084 if (!CS.getInstruction()->use_empty())
10085 CS.getInstruction()->
Owen Anderson9e9a0d52009-07-30 23:03:37 +000010086 replaceAllUsesWith(UndefValue::get(CS.getInstruction()->getType()));
Chris Lattner17be6352004-10-18 02:59:09 +000010087
10088 if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
10089 // Don't break the CFG, insert a dummy cond branch.
Gabor Greif051a9502008-04-06 20:25:17 +000010090 BranchInst::Create(II->getNormalDest(), II->getUnwindDest(),
Owen Anderson5defacc2009-07-31 17:39:07 +000010091 ConstantInt::getTrue(*Context), II);
Chris Lattnere87597f2004-10-16 18:11:37 +000010092 }
Chris Lattner17be6352004-10-18 02:59:09 +000010093 return EraseInstFromFunction(*CS.getInstruction());
10094 }
Chris Lattnere87597f2004-10-16 18:11:37 +000010095
Duncan Sandscdb6d922007-09-17 10:26:40 +000010096 if (BitCastInst *BC = dyn_cast<BitCastInst>(Callee))
10097 if (IntrinsicInst *In = dyn_cast<IntrinsicInst>(BC->getOperand(0)))
10098 if (In->getIntrinsicID() == Intrinsic::init_trampoline)
10099 return transformCallThroughTrampoline(CS);
10100
Chris Lattner6c266db2003-10-07 22:54:13 +000010101 const PointerType *PTy = cast<PointerType>(Callee->getType());
10102 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
10103 if (FTy->isVarArg()) {
Dale Johannesen63e7eb42008-04-23 01:03:05 +000010104 int ix = FTy->getNumParams() + (isa<InvokeInst>(Callee) ? 3 : 1);
Chris Lattner6c266db2003-10-07 22:54:13 +000010105 // See if we can optimize any arguments passed through the varargs area of
10106 // the call.
10107 for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
Dale Johannesen1f530a52008-04-23 18:34:37 +000010108 E = CS.arg_end(); I != E; ++I, ++ix) {
10109 CastInst *CI = dyn_cast<CastInst>(*I);
10110 if (CI && isSafeToEliminateVarargsCast(CS, CI, TD, ix)) {
10111 *I = CI->getOperand(0);
10112 Changed = true;
Chris Lattner6c266db2003-10-07 22:54:13 +000010113 }
Dale Johannesen1f530a52008-04-23 18:34:37 +000010114 }
Chris Lattner6c266db2003-10-07 22:54:13 +000010115 }
Misha Brukmanfd939082005-04-21 23:48:37 +000010116
Duncan Sandsf0c33542007-12-19 21:13:37 +000010117 if (isa<InlineAsm>(Callee) && !CS.doesNotThrow()) {
Duncan Sandsece2c042007-12-16 15:51:49 +000010118 // Inline asm calls cannot throw - mark them 'nounwind'.
Duncan Sandsf0c33542007-12-19 21:13:37 +000010119 CS.setDoesNotThrow();
Duncan Sandsece2c042007-12-16 15:51:49 +000010120 Changed = true;
10121 }
10122
Chris Lattner6c266db2003-10-07 22:54:13 +000010123 return Changed ? CS.getInstruction() : 0;
Chris Lattnera44d8a22003-10-07 22:32:43 +000010124}
10125
Chris Lattner9fe38862003-06-19 17:00:31 +000010126// transformConstExprCastCall - If the callee is a constexpr cast of a function,
10127// attempt to move the cast to the arguments of the call/invoke.
10128//
10129bool InstCombiner::transformConstExprCastCall(CallSite CS) {
10130 if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
10131 ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
Reid Spencer3da59db2006-11-27 01:05:10 +000010132 if (CE->getOpcode() != Instruction::BitCast ||
10133 !isa<Function>(CE->getOperand(0)))
Chris Lattner9fe38862003-06-19 17:00:31 +000010134 return false;
Reid Spencer8863f182004-07-18 00:38:32 +000010135 Function *Callee = cast<Function>(CE->getOperand(0));
Chris Lattner9fe38862003-06-19 17:00:31 +000010136 Instruction *Caller = CS.getInstruction();
Devang Patel05988662008-09-25 21:00:45 +000010137 const AttrListPtr &CallerPAL = CS.getAttributes();
Chris Lattner9fe38862003-06-19 17:00:31 +000010138
10139 // Okay, this is a cast from a function to a different type. Unless doing so
10140 // would cause a type conversion of one of our arguments, change this call to
10141 // be a direct call with arguments casted to the appropriate types.
10142 //
10143 const FunctionType *FT = Callee->getFunctionType();
10144 const Type *OldRetTy = Caller->getType();
Duncan Sandsf413cdf2008-06-01 07:38:42 +000010145 const Type *NewRetTy = FT->getReturnType();
Chris Lattner9fe38862003-06-19 17:00:31 +000010146
Duncan Sandsf413cdf2008-06-01 07:38:42 +000010147 if (isa<StructType>(NewRetTy))
Devang Patel75e6f022008-03-11 18:04:06 +000010148 return false; // TODO: Handle multiple return values.
10149
Chris Lattnerf78616b2004-01-14 06:06:08 +000010150 // Check to see if we are changing the return type...
Duncan Sandsf413cdf2008-06-01 07:38:42 +000010151 if (OldRetTy != NewRetTy) {
Bill Wendlinga6c31122008-05-14 22:45:20 +000010152 if (Callee->isDeclaration() &&
Duncan Sandsf413cdf2008-06-01 07:38:42 +000010153 // Conversion is ok if changing from one pointer type to another or from
10154 // a pointer to an integer of the same size.
Dan Gohmance9fe9f2009-07-21 23:21:54 +000010155 !((isa<PointerType>(OldRetTy) || !TD ||
10156 OldRetTy == TD->getIntPtrType()) &&
10157 (isa<PointerType>(NewRetTy) || !TD ||
10158 NewRetTy == TD->getIntPtrType())))
Chris Lattnerec479922007-01-06 02:09:32 +000010159 return false; // Cannot transform this return value.
Chris Lattnerf78616b2004-01-14 06:06:08 +000010160
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +000010161 if (!Caller->use_empty() &&
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +000010162 // void -> non-void is handled specially
Duncan Sandsf413cdf2008-06-01 07:38:42 +000010163 NewRetTy != Type::VoidTy && !CastInst::isCastable(NewRetTy, OldRetTy))
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +000010164 return false; // Cannot transform this return value.
10165
Chris Lattner58d74912008-03-12 17:45:29 +000010166 if (!CallerPAL.isEmpty() && !Caller->use_empty()) {
Devang Patel19c87462008-09-26 22:53:05 +000010167 Attributes RAttrs = CallerPAL.getRetAttributes();
Devang Patel05988662008-09-25 21:00:45 +000010168 if (RAttrs & Attribute::typeIncompatible(NewRetTy))
Duncan Sands6c3470e2008-01-07 17:16:06 +000010169 return false; // Attribute not compatible with transformed value.
10170 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010171
Chris Lattnerf78616b2004-01-14 06:06:08 +000010172 // If the callsite is an invoke instruction, and the return value is used by
10173 // a PHI node in a successor, we cannot change the return type of the call
10174 // because there is no place to put the cast instruction (without breaking
10175 // the critical edge). Bail out in this case.
10176 if (!Caller->use_empty())
10177 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
10178 for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
10179 UI != E; ++UI)
10180 if (PHINode *PN = dyn_cast<PHINode>(*UI))
10181 if (PN->getParent() == II->getNormalDest() ||
Chris Lattneraeb2a1d2004-02-08 21:44:31 +000010182 PN->getParent() == II->getUnwindDest())
Chris Lattnerf78616b2004-01-14 06:06:08 +000010183 return false;
10184 }
Chris Lattner9fe38862003-06-19 17:00:31 +000010185
10186 unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
10187 unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
Misha Brukmanfd939082005-04-21 23:48:37 +000010188
Chris Lattner9fe38862003-06-19 17:00:31 +000010189 CallSite::arg_iterator AI = CS.arg_begin();
10190 for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
10191 const Type *ParamTy = FT->getParamType(i);
Andrew Lenharthb8e604c2006-06-28 01:01:52 +000010192 const Type *ActTy = (*AI)->getType();
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +000010193
10194 if (!CastInst::isCastable(ActTy, ParamTy))
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010195 return false; // Cannot transform this parameter value.
10196
Devang Patel19c87462008-09-26 22:53:05 +000010197 if (CallerPAL.getParamAttributes(i + 1)
10198 & Attribute::typeIncompatible(ParamTy))
Chris Lattner58d74912008-03-12 17:45:29 +000010199 return false; // Attribute not compatible with transformed value.
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +000010200
Duncan Sandsf413cdf2008-06-01 07:38:42 +000010201 // Converting from one pointer type to another or between a pointer and an
10202 // integer of the same size is safe even if we do not have a body.
Chris Lattnerec479922007-01-06 02:09:32 +000010203 bool isConvertible = ActTy == ParamTy ||
Dan Gohmance9fe9f2009-07-21 23:21:54 +000010204 (TD && ((isa<PointerType>(ParamTy) || ParamTy == TD->getIntPtrType()) &&
10205 (isa<PointerType>(ActTy) || ActTy == TD->getIntPtrType())));
Reid Spencer5cbf9852007-01-30 20:08:39 +000010206 if (Callee->isDeclaration() && !isConvertible) return false;
Chris Lattner9fe38862003-06-19 17:00:31 +000010207 }
10208
10209 if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
Reid Spencer5cbf9852007-01-30 20:08:39 +000010210 Callee->isDeclaration())
Chris Lattner58d74912008-03-12 17:45:29 +000010211 return false; // Do not delete arguments unless we have a function body.
Chris Lattner9fe38862003-06-19 17:00:31 +000010212
Chris Lattner58d74912008-03-12 17:45:29 +000010213 if (FT->getNumParams() < NumActualArgs && FT->isVarArg() &&
10214 !CallerPAL.isEmpty())
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010215 // In this case we have more arguments than the new function type, but we
Duncan Sandse1e520f2008-01-13 08:02:44 +000010216 // won't be dropping them. Check that these extra arguments have attributes
10217 // that are compatible with being a vararg call argument.
Chris Lattner58d74912008-03-12 17:45:29 +000010218 for (unsigned i = CallerPAL.getNumSlots(); i; --i) {
10219 if (CallerPAL.getSlot(i - 1).Index <= FT->getNumParams())
Duncan Sandse1e520f2008-01-13 08:02:44 +000010220 break;
Devang Pateleaf42ab2008-09-23 23:03:40 +000010221 Attributes PAttrs = CallerPAL.getSlot(i - 1).Attrs;
Devang Patel05988662008-09-25 21:00:45 +000010222 if (PAttrs & Attribute::VarArgsIncompatible)
Duncan Sandse1e520f2008-01-13 08:02:44 +000010223 return false;
10224 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010225
Chris Lattner9fe38862003-06-19 17:00:31 +000010226 // Okay, we decided that this is a safe thing to do: go ahead and start
10227 // inserting cast instructions as necessary...
10228 std::vector<Value*> Args;
10229 Args.reserve(NumActualArgs);
Devang Patel05988662008-09-25 21:00:45 +000010230 SmallVector<AttributeWithIndex, 8> attrVec;
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010231 attrVec.reserve(NumCommonArgs);
10232
10233 // Get any return attributes.
Devang Patel19c87462008-09-26 22:53:05 +000010234 Attributes RAttrs = CallerPAL.getRetAttributes();
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010235
10236 // If the return value is not being used, the type may not be compatible
10237 // with the existing attributes. Wipe out any problematic attributes.
Devang Patel05988662008-09-25 21:00:45 +000010238 RAttrs &= ~Attribute::typeIncompatible(NewRetTy);
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010239
10240 // Add the new return attributes.
10241 if (RAttrs)
Devang Patel05988662008-09-25 21:00:45 +000010242 attrVec.push_back(AttributeWithIndex::get(0, RAttrs));
Chris Lattner9fe38862003-06-19 17:00:31 +000010243
10244 AI = CS.arg_begin();
10245 for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
10246 const Type *ParamTy = FT->getParamType(i);
10247 if ((*AI)->getType() == ParamTy) {
10248 Args.push_back(*AI);
10249 } else {
Reid Spencer8a903db2006-12-18 08:47:13 +000010250 Instruction::CastOps opcode = CastInst::getCastOpcode(*AI,
Reid Spencerc5b206b2006-12-31 05:48:39 +000010251 false, ParamTy, false);
Gabor Greif7cbd8a32008-05-16 19:29:10 +000010252 CastInst *NewCast = CastInst::Create(opcode, *AI, ParamTy, "tmp");
Reid Spencer3da59db2006-11-27 01:05:10 +000010253 Args.push_back(InsertNewInstBefore(NewCast, *Caller));
Chris Lattner9fe38862003-06-19 17:00:31 +000010254 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010255
10256 // Add any parameter attributes.
Devang Patel19c87462008-09-26 22:53:05 +000010257 if (Attributes PAttrs = CallerPAL.getParamAttributes(i + 1))
Devang Patel05988662008-09-25 21:00:45 +000010258 attrVec.push_back(AttributeWithIndex::get(i + 1, PAttrs));
Chris Lattner9fe38862003-06-19 17:00:31 +000010259 }
10260
10261 // If the function takes more arguments than the call was taking, add them
10262 // now...
10263 for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
Owen Andersona7235ea2009-07-31 20:28:14 +000010264 Args.push_back(Constant::getNullValue(FT->getParamType(i)));
Chris Lattner9fe38862003-06-19 17:00:31 +000010265
10266 // If we are removing arguments to the function, emit an obnoxious warning...
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000010267 if (FT->getNumParams() < NumActualArgs) {
Chris Lattner9fe38862003-06-19 17:00:31 +000010268 if (!FT->isVarArg()) {
Daniel Dunbarce63ffb2009-07-25 00:23:56 +000010269 errs() << "WARNING: While resolving call to function '"
10270 << Callee->getName() << "' arguments were dropped!\n";
Chris Lattner9fe38862003-06-19 17:00:31 +000010271 } else {
10272 // Add all of the arguments in their promoted form to the arg list...
10273 for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
10274 const Type *PTy = getPromotedType((*AI)->getType());
10275 if (PTy != (*AI)->getType()) {
10276 // Must promote to pass through va_arg area!
Reid Spencerc5b206b2006-12-31 05:48:39 +000010277 Instruction::CastOps opcode = CastInst::getCastOpcode(*AI, false,
10278 PTy, false);
Gabor Greif7cbd8a32008-05-16 19:29:10 +000010279 Instruction *Cast = CastInst::Create(opcode, *AI, PTy, "tmp");
Chris Lattner9fe38862003-06-19 17:00:31 +000010280 InsertNewInstBefore(Cast, *Caller);
10281 Args.push_back(Cast);
10282 } else {
10283 Args.push_back(*AI);
10284 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010285
Duncan Sandse1e520f2008-01-13 08:02:44 +000010286 // Add any parameter attributes.
Devang Patel19c87462008-09-26 22:53:05 +000010287 if (Attributes PAttrs = CallerPAL.getParamAttributes(i + 1))
Devang Patel05988662008-09-25 21:00:45 +000010288 attrVec.push_back(AttributeWithIndex::get(i + 1, PAttrs));
Duncan Sandse1e520f2008-01-13 08:02:44 +000010289 }
Chris Lattner9fe38862003-06-19 17:00:31 +000010290 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000010291 }
Chris Lattner9fe38862003-06-19 17:00:31 +000010292
Devang Patel19c87462008-09-26 22:53:05 +000010293 if (Attributes FnAttrs = CallerPAL.getFnAttributes())
10294 attrVec.push_back(AttributeWithIndex::get(~0, FnAttrs));
10295
Duncan Sandsf413cdf2008-06-01 07:38:42 +000010296 if (NewRetTy == Type::VoidTy)
Chris Lattner6934a042007-02-11 01:23:03 +000010297 Caller->setName(""); // Void type should not have a name.
Chris Lattner9fe38862003-06-19 17:00:31 +000010298
Eric Christophera66297a2009-07-25 02:45:27 +000010299 const AttrListPtr &NewCallerPAL = AttrListPtr::get(attrVec.begin(),
10300 attrVec.end());
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010301
Chris Lattner9fe38862003-06-19 17:00:31 +000010302 Instruction *NC;
10303 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Gabor Greif051a9502008-04-06 20:25:17 +000010304 NC = InvokeInst::Create(Callee, II->getNormalDest(), II->getUnwindDest(),
Gabor Greifb1dbcd82008-05-15 10:04:30 +000010305 Args.begin(), Args.end(),
10306 Caller->getName(), Caller);
Reid Spencered3fa852007-07-30 19:53:57 +000010307 cast<InvokeInst>(NC)->setCallingConv(II->getCallingConv());
Devang Patel05988662008-09-25 21:00:45 +000010308 cast<InvokeInst>(NC)->setAttributes(NewCallerPAL);
Chris Lattner9fe38862003-06-19 17:00:31 +000010309 } else {
Gabor Greif051a9502008-04-06 20:25:17 +000010310 NC = CallInst::Create(Callee, Args.begin(), Args.end(),
10311 Caller->getName(), Caller);
Duncan Sandsdc024672007-11-27 13:23:08 +000010312 CallInst *CI = cast<CallInst>(Caller);
10313 if (CI->isTailCall())
Chris Lattnera9e92112005-05-06 06:48:21 +000010314 cast<CallInst>(NC)->setTailCall();
Duncan Sandsdc024672007-11-27 13:23:08 +000010315 cast<CallInst>(NC)->setCallingConv(CI->getCallingConv());
Devang Patel05988662008-09-25 21:00:45 +000010316 cast<CallInst>(NC)->setAttributes(NewCallerPAL);
Chris Lattner9fe38862003-06-19 17:00:31 +000010317 }
10318
Chris Lattner6934a042007-02-11 01:23:03 +000010319 // Insert a cast of the return type as necessary.
Chris Lattner9fe38862003-06-19 17:00:31 +000010320 Value *NV = NC;
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +000010321 if (OldRetTy != NV->getType() && !Caller->use_empty()) {
Chris Lattner9fe38862003-06-19 17:00:31 +000010322 if (NV->getType() != Type::VoidTy) {
Reid Spencerc5b206b2006-12-31 05:48:39 +000010323 Instruction::CastOps opcode = CastInst::getCastOpcode(NC, false,
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +000010324 OldRetTy, false);
Gabor Greif7cbd8a32008-05-16 19:29:10 +000010325 NV = NC = CastInst::Create(opcode, NC, OldRetTy, "tmp");
Chris Lattnerbb609042003-10-30 00:46:41 +000010326
10327 // If this is an invoke instruction, we should insert it after the first
10328 // non-phi, instruction in the normal successor block.
10329 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Dan Gohman02dea8b2008-05-23 21:05:58 +000010330 BasicBlock::iterator I = II->getNormalDest()->getFirstNonPHI();
Chris Lattnerbb609042003-10-30 00:46:41 +000010331 InsertNewInstBefore(NC, *I);
10332 } else {
10333 // Otherwise, it's a call, just insert cast right after the call instr
10334 InsertNewInstBefore(NC, *Caller);
10335 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +000010336 AddUsersToWorkList(*Caller);
Chris Lattner9fe38862003-06-19 17:00:31 +000010337 } else {
Owen Anderson9e9a0d52009-07-30 23:03:37 +000010338 NV = UndefValue::get(Caller->getType());
Chris Lattner9fe38862003-06-19 17:00:31 +000010339 }
10340 }
10341
10342 if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
10343 Caller->replaceAllUsesWith(NV);
Chris Lattnerf22a5c62007-03-02 19:59:19 +000010344 Caller->eraseFromParent();
Chris Lattnerdbab3862007-03-02 21:28:56 +000010345 RemoveFromWorkList(Caller);
Chris Lattner9fe38862003-06-19 17:00:31 +000010346 return true;
10347}
10348
Duncan Sandscdb6d922007-09-17 10:26:40 +000010349// transformCallThroughTrampoline - Turn a call to a function created by the
10350// init_trampoline intrinsic into a direct call to the underlying function.
10351//
10352Instruction *InstCombiner::transformCallThroughTrampoline(CallSite CS) {
10353 Value *Callee = CS.getCalledValue();
10354 const PointerType *PTy = cast<PointerType>(Callee->getType());
10355 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
Devang Patel05988662008-09-25 21:00:45 +000010356 const AttrListPtr &Attrs = CS.getAttributes();
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010357
10358 // If the call already has the 'nest' attribute somewhere then give up -
10359 // otherwise 'nest' would occur twice after splicing in the chain.
Devang Patel05988662008-09-25 21:00:45 +000010360 if (Attrs.hasAttrSomewhere(Attribute::Nest))
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010361 return 0;
Duncan Sandscdb6d922007-09-17 10:26:40 +000010362
10363 IntrinsicInst *Tramp =
10364 cast<IntrinsicInst>(cast<BitCastInst>(Callee)->getOperand(0));
10365
Anton Korobeynikov0b12ecf2008-05-07 22:54:15 +000010366 Function *NestF = cast<Function>(Tramp->getOperand(2)->stripPointerCasts());
Duncan Sandscdb6d922007-09-17 10:26:40 +000010367 const PointerType *NestFPTy = cast<PointerType>(NestF->getType());
10368 const FunctionType *NestFTy = cast<FunctionType>(NestFPTy->getElementType());
10369
Devang Patel05988662008-09-25 21:00:45 +000010370 const AttrListPtr &NestAttrs = NestF->getAttributes();
Chris Lattner58d74912008-03-12 17:45:29 +000010371 if (!NestAttrs.isEmpty()) {
Duncan Sandscdb6d922007-09-17 10:26:40 +000010372 unsigned NestIdx = 1;
10373 const Type *NestTy = 0;
Devang Patel05988662008-09-25 21:00:45 +000010374 Attributes NestAttr = Attribute::None;
Duncan Sandscdb6d922007-09-17 10:26:40 +000010375
10376 // Look for a parameter marked with the 'nest' attribute.
10377 for (FunctionType::param_iterator I = NestFTy->param_begin(),
10378 E = NestFTy->param_end(); I != E; ++NestIdx, ++I)
Devang Patel05988662008-09-25 21:00:45 +000010379 if (NestAttrs.paramHasAttr(NestIdx, Attribute::Nest)) {
Duncan Sandscdb6d922007-09-17 10:26:40 +000010380 // Record the parameter type and any other attributes.
10381 NestTy = *I;
Devang Patel19c87462008-09-26 22:53:05 +000010382 NestAttr = NestAttrs.getParamAttributes(NestIdx);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010383 break;
10384 }
10385
10386 if (NestTy) {
10387 Instruction *Caller = CS.getInstruction();
10388 std::vector<Value*> NewArgs;
10389 NewArgs.reserve(unsigned(CS.arg_end()-CS.arg_begin())+1);
10390
Devang Patel05988662008-09-25 21:00:45 +000010391 SmallVector<AttributeWithIndex, 8> NewAttrs;
Chris Lattner58d74912008-03-12 17:45:29 +000010392 NewAttrs.reserve(Attrs.getNumSlots() + 1);
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010393
Duncan Sandscdb6d922007-09-17 10:26:40 +000010394 // Insert the nest argument into the call argument list, which may
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010395 // mean appending it. Likewise for attributes.
10396
Devang Patel19c87462008-09-26 22:53:05 +000010397 // Add any result attributes.
10398 if (Attributes Attr = Attrs.getRetAttributes())
Devang Patel05988662008-09-25 21:00:45 +000010399 NewAttrs.push_back(AttributeWithIndex::get(0, Attr));
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010400
Duncan Sandscdb6d922007-09-17 10:26:40 +000010401 {
10402 unsigned Idx = 1;
10403 CallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
10404 do {
10405 if (Idx == NestIdx) {
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010406 // Add the chain argument and attributes.
Duncan Sandscdb6d922007-09-17 10:26:40 +000010407 Value *NestVal = Tramp->getOperand(3);
10408 if (NestVal->getType() != NestTy)
10409 NestVal = new BitCastInst(NestVal, NestTy, "nest", Caller);
10410 NewArgs.push_back(NestVal);
Devang Patel05988662008-09-25 21:00:45 +000010411 NewAttrs.push_back(AttributeWithIndex::get(NestIdx, NestAttr));
Duncan Sandscdb6d922007-09-17 10:26:40 +000010412 }
10413
10414 if (I == E)
10415 break;
10416
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010417 // Add the original argument and attributes.
Duncan Sandscdb6d922007-09-17 10:26:40 +000010418 NewArgs.push_back(*I);
Devang Patel19c87462008-09-26 22:53:05 +000010419 if (Attributes Attr = Attrs.getParamAttributes(Idx))
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010420 NewAttrs.push_back
Devang Patel05988662008-09-25 21:00:45 +000010421 (AttributeWithIndex::get(Idx + (Idx >= NestIdx), Attr));
Duncan Sandscdb6d922007-09-17 10:26:40 +000010422
10423 ++Idx, ++I;
10424 } while (1);
10425 }
10426
Devang Patel19c87462008-09-26 22:53:05 +000010427 // Add any function attributes.
10428 if (Attributes Attr = Attrs.getFnAttributes())
10429 NewAttrs.push_back(AttributeWithIndex::get(~0, Attr));
10430
Duncan Sandscdb6d922007-09-17 10:26:40 +000010431 // The trampoline may have been bitcast to a bogus type (FTy).
10432 // Handle this by synthesizing a new function type, equal to FTy
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010433 // with the chain parameter inserted.
Duncan Sandscdb6d922007-09-17 10:26:40 +000010434
Duncan Sandscdb6d922007-09-17 10:26:40 +000010435 std::vector<const Type*> NewTypes;
Duncan Sandscdb6d922007-09-17 10:26:40 +000010436 NewTypes.reserve(FTy->getNumParams()+1);
10437
Duncan Sandscdb6d922007-09-17 10:26:40 +000010438 // Insert the chain's type into the list of parameter types, which may
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010439 // mean appending it.
Duncan Sandscdb6d922007-09-17 10:26:40 +000010440 {
10441 unsigned Idx = 1;
10442 FunctionType::param_iterator I = FTy->param_begin(),
10443 E = FTy->param_end();
10444
10445 do {
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010446 if (Idx == NestIdx)
10447 // Add the chain's type.
Duncan Sandscdb6d922007-09-17 10:26:40 +000010448 NewTypes.push_back(NestTy);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010449
10450 if (I == E)
10451 break;
10452
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010453 // Add the original type.
Duncan Sandscdb6d922007-09-17 10:26:40 +000010454 NewTypes.push_back(*I);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010455
10456 ++Idx, ++I;
10457 } while (1);
10458 }
10459
10460 // Replace the trampoline call with a direct call. Let the generic
10461 // code sort out any function type mismatches.
Owen Andersondebcb012009-07-29 22:17:13 +000010462 FunctionType *NewFTy = FunctionType::get(FTy->getReturnType(), NewTypes,
Owen Andersond672ecb2009-07-03 00:17:18 +000010463 FTy->isVarArg());
10464 Constant *NewCallee =
Owen Andersondebcb012009-07-29 22:17:13 +000010465 NestF->getType() == PointerType::getUnqual(NewFTy) ?
Owen Andersonbaf3c402009-07-29 18:55:55 +000010466 NestF : ConstantExpr::getBitCast(NestF,
Owen Andersondebcb012009-07-29 22:17:13 +000010467 PointerType::getUnqual(NewFTy));
Eric Christophera66297a2009-07-25 02:45:27 +000010468 const AttrListPtr &NewPAL = AttrListPtr::get(NewAttrs.begin(),
10469 NewAttrs.end());
Duncan Sandscdb6d922007-09-17 10:26:40 +000010470
10471 Instruction *NewCaller;
10472 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Gabor Greif051a9502008-04-06 20:25:17 +000010473 NewCaller = InvokeInst::Create(NewCallee,
10474 II->getNormalDest(), II->getUnwindDest(),
10475 NewArgs.begin(), NewArgs.end(),
10476 Caller->getName(), Caller);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010477 cast<InvokeInst>(NewCaller)->setCallingConv(II->getCallingConv());
Devang Patel05988662008-09-25 21:00:45 +000010478 cast<InvokeInst>(NewCaller)->setAttributes(NewPAL);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010479 } else {
Gabor Greif051a9502008-04-06 20:25:17 +000010480 NewCaller = CallInst::Create(NewCallee, NewArgs.begin(), NewArgs.end(),
10481 Caller->getName(), Caller);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010482 if (cast<CallInst>(Caller)->isTailCall())
10483 cast<CallInst>(NewCaller)->setTailCall();
10484 cast<CallInst>(NewCaller)->
10485 setCallingConv(cast<CallInst>(Caller)->getCallingConv());
Devang Patel05988662008-09-25 21:00:45 +000010486 cast<CallInst>(NewCaller)->setAttributes(NewPAL);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010487 }
10488 if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
10489 Caller->replaceAllUsesWith(NewCaller);
10490 Caller->eraseFromParent();
10491 RemoveFromWorkList(Caller);
10492 return 0;
10493 }
10494 }
10495
10496 // Replace the trampoline call with a direct call. Since there is no 'nest'
10497 // parameter, there is no need to adjust the argument list. Let the generic
10498 // code sort out any function type mismatches.
10499 Constant *NewCallee =
Owen Andersond672ecb2009-07-03 00:17:18 +000010500 NestF->getType() == PTy ? NestF :
Owen Andersonbaf3c402009-07-29 18:55:55 +000010501 ConstantExpr::getBitCast(NestF, PTy);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010502 CS.setCalledFunction(NewCallee);
10503 return CS.getInstruction();
10504}
10505
Chris Lattner7da52b22006-11-01 04:51:18 +000010506/// FoldPHIArgBinOpIntoPHI - If we have something like phi [add (a,b), add(c,d)]
10507/// and if a/b/c/d and the add's all have a single use, turn this into two phi's
10508/// and a single binop.
10509Instruction *InstCombiner::FoldPHIArgBinOpIntoPHI(PHINode &PN) {
10510 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
Chris Lattner38b3dcc2008-12-01 03:42:51 +000010511 assert(isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst));
Chris Lattner7da52b22006-11-01 04:51:18 +000010512 unsigned Opc = FirstInst->getOpcode();
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010513 Value *LHSVal = FirstInst->getOperand(0);
10514 Value *RHSVal = FirstInst->getOperand(1);
10515
10516 const Type *LHSType = LHSVal->getType();
10517 const Type *RHSType = RHSVal->getType();
Chris Lattner7da52b22006-11-01 04:51:18 +000010518
10519 // Scan to see if all operands are the same opcode, all have one use, and all
10520 // kill their operands (i.e. the operands have one use).
Chris Lattner05f18922008-12-01 02:34:36 +000010521 for (unsigned i = 1; i != PN.getNumIncomingValues(); ++i) {
Chris Lattner7da52b22006-11-01 04:51:18 +000010522 Instruction *I = dyn_cast<Instruction>(PN.getIncomingValue(i));
Chris Lattnera90a24c2006-11-01 04:55:47 +000010523 if (!I || I->getOpcode() != Opc || !I->hasOneUse() ||
Reid Spencere4d87aa2006-12-23 06:05:41 +000010524 // Verify type of the LHS matches so we don't fold cmp's of different
Chris Lattner9c080502006-11-01 07:43:41 +000010525 // types or GEP's with different index types.
10526 I->getOperand(0)->getType() != LHSType ||
10527 I->getOperand(1)->getType() != RHSType)
Chris Lattner7da52b22006-11-01 04:51:18 +000010528 return 0;
Reid Spencere4d87aa2006-12-23 06:05:41 +000010529
10530 // If they are CmpInst instructions, check their predicates
10531 if (Opc == Instruction::ICmp || Opc == Instruction::FCmp)
10532 if (cast<CmpInst>(I)->getPredicate() !=
10533 cast<CmpInst>(FirstInst)->getPredicate())
10534 return 0;
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010535
10536 // Keep track of which operand needs a phi node.
10537 if (I->getOperand(0) != LHSVal) LHSVal = 0;
10538 if (I->getOperand(1) != RHSVal) RHSVal = 0;
Chris Lattner7da52b22006-11-01 04:51:18 +000010539 }
10540
Chris Lattner38b3dcc2008-12-01 03:42:51 +000010541 // Otherwise, this is safe to transform!
Chris Lattner53738a42006-11-08 19:42:28 +000010542
Chris Lattner7da52b22006-11-01 04:51:18 +000010543 Value *InLHS = FirstInst->getOperand(0);
Chris Lattner7da52b22006-11-01 04:51:18 +000010544 Value *InRHS = FirstInst->getOperand(1);
Chris Lattner53738a42006-11-08 19:42:28 +000010545 PHINode *NewLHS = 0, *NewRHS = 0;
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010546 if (LHSVal == 0) {
Gabor Greifb1dbcd82008-05-15 10:04:30 +000010547 NewLHS = PHINode::Create(LHSType,
10548 FirstInst->getOperand(0)->getName() + ".pn");
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010549 NewLHS->reserveOperandSpace(PN.getNumOperands()/2);
10550 NewLHS->addIncoming(InLHS, PN.getIncomingBlock(0));
Chris Lattner9c080502006-11-01 07:43:41 +000010551 InsertNewInstBefore(NewLHS, PN);
10552 LHSVal = NewLHS;
10553 }
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010554
10555 if (RHSVal == 0) {
Gabor Greifb1dbcd82008-05-15 10:04:30 +000010556 NewRHS = PHINode::Create(RHSType,
10557 FirstInst->getOperand(1)->getName() + ".pn");
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010558 NewRHS->reserveOperandSpace(PN.getNumOperands()/2);
10559 NewRHS->addIncoming(InRHS, PN.getIncomingBlock(0));
Chris Lattner9c080502006-11-01 07:43:41 +000010560 InsertNewInstBefore(NewRHS, PN);
10561 RHSVal = NewRHS;
10562 }
10563
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010564 // Add all operands to the new PHIs.
Chris Lattner05f18922008-12-01 02:34:36 +000010565 if (NewLHS || NewRHS) {
10566 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10567 Instruction *InInst = cast<Instruction>(PN.getIncomingValue(i));
10568 if (NewLHS) {
10569 Value *NewInLHS = InInst->getOperand(0);
10570 NewLHS->addIncoming(NewInLHS, PN.getIncomingBlock(i));
10571 }
10572 if (NewRHS) {
10573 Value *NewInRHS = InInst->getOperand(1);
10574 NewRHS->addIncoming(NewInRHS, PN.getIncomingBlock(i));
10575 }
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010576 }
10577 }
10578
Chris Lattner7da52b22006-11-01 04:51:18 +000010579 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Gabor Greif7cbd8a32008-05-16 19:29:10 +000010580 return BinaryOperator::Create(BinOp->getOpcode(), LHSVal, RHSVal);
Chris Lattner38b3dcc2008-12-01 03:42:51 +000010581 CmpInst *CIOp = cast<CmpInst>(FirstInst);
Owen Anderson333c4002009-07-09 23:48:35 +000010582 return CmpInst::Create(*Context, CIOp->getOpcode(), CIOp->getPredicate(),
10583 LHSVal, RHSVal);
Chris Lattner7da52b22006-11-01 04:51:18 +000010584}
10585
Chris Lattner05f18922008-12-01 02:34:36 +000010586Instruction *InstCombiner::FoldPHIArgGEPIntoPHI(PHINode &PN) {
10587 GetElementPtrInst *FirstInst =cast<GetElementPtrInst>(PN.getIncomingValue(0));
10588
10589 SmallVector<Value*, 16> FixedOperands(FirstInst->op_begin(),
10590 FirstInst->op_end());
Chris Lattner36d3e322009-02-21 00:46:50 +000010591 // This is true if all GEP bases are allocas and if all indices into them are
10592 // constants.
10593 bool AllBasePointersAreAllocas = true;
Chris Lattner05f18922008-12-01 02:34:36 +000010594
10595 // Scan to see if all operands are the same opcode, all have one use, and all
10596 // kill their operands (i.e. the operands have one use).
10597 for (unsigned i = 1; i != PN.getNumIncomingValues(); ++i) {
10598 GetElementPtrInst *GEP= dyn_cast<GetElementPtrInst>(PN.getIncomingValue(i));
10599 if (!GEP || !GEP->hasOneUse() || GEP->getType() != FirstInst->getType() ||
10600 GEP->getNumOperands() != FirstInst->getNumOperands())
10601 return 0;
10602
Chris Lattner36d3e322009-02-21 00:46:50 +000010603 // Keep track of whether or not all GEPs are of alloca pointers.
10604 if (AllBasePointersAreAllocas &&
10605 (!isa<AllocaInst>(GEP->getOperand(0)) ||
10606 !GEP->hasAllConstantIndices()))
10607 AllBasePointersAreAllocas = false;
10608
Chris Lattner05f18922008-12-01 02:34:36 +000010609 // Compare the operand lists.
10610 for (unsigned op = 0, e = FirstInst->getNumOperands(); op != e; ++op) {
10611 if (FirstInst->getOperand(op) == GEP->getOperand(op))
10612 continue;
10613
10614 // Don't merge two GEPs when two operands differ (introducing phi nodes)
10615 // if one of the PHIs has a constant for the index. The index may be
10616 // substantially cheaper to compute for the constants, so making it a
10617 // variable index could pessimize the path. This also handles the case
10618 // for struct indices, which must always be constant.
10619 if (isa<ConstantInt>(FirstInst->getOperand(op)) ||
10620 isa<ConstantInt>(GEP->getOperand(op)))
10621 return 0;
10622
10623 if (FirstInst->getOperand(op)->getType() !=GEP->getOperand(op)->getType())
10624 return 0;
10625 FixedOperands[op] = 0; // Needs a PHI.
10626 }
10627 }
10628
Chris Lattner36d3e322009-02-21 00:46:50 +000010629 // If all of the base pointers of the PHI'd GEPs are from allocas, don't
Chris Lattner21550882009-02-23 05:56:17 +000010630 // bother doing this transformation. At best, this will just save a bit of
Chris Lattner36d3e322009-02-21 00:46:50 +000010631 // offset calculation, but all the predecessors will have to materialize the
10632 // stack address into a register anyway. We'd actually rather *clone* the
10633 // load up into the predecessors so that we have a load of a gep of an alloca,
10634 // which can usually all be folded into the load.
10635 if (AllBasePointersAreAllocas)
10636 return 0;
10637
Chris Lattner05f18922008-12-01 02:34:36 +000010638 // Otherwise, this is safe to transform. Insert PHI nodes for each operand
10639 // that is variable.
10640 SmallVector<PHINode*, 16> OperandPhis(FixedOperands.size());
10641
10642 bool HasAnyPHIs = false;
10643 for (unsigned i = 0, e = FixedOperands.size(); i != e; ++i) {
10644 if (FixedOperands[i]) continue; // operand doesn't need a phi.
10645 Value *FirstOp = FirstInst->getOperand(i);
10646 PHINode *NewPN = PHINode::Create(FirstOp->getType(),
10647 FirstOp->getName()+".pn");
10648 InsertNewInstBefore(NewPN, PN);
10649
10650 NewPN->reserveOperandSpace(e);
10651 NewPN->addIncoming(FirstOp, PN.getIncomingBlock(0));
10652 OperandPhis[i] = NewPN;
10653 FixedOperands[i] = NewPN;
10654 HasAnyPHIs = true;
10655 }
10656
10657
10658 // Add all operands to the new PHIs.
10659 if (HasAnyPHIs) {
10660 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10661 GetElementPtrInst *InGEP =cast<GetElementPtrInst>(PN.getIncomingValue(i));
10662 BasicBlock *InBB = PN.getIncomingBlock(i);
10663
10664 for (unsigned op = 0, e = OperandPhis.size(); op != e; ++op)
10665 if (PHINode *OpPhi = OperandPhis[op])
10666 OpPhi->addIncoming(InGEP->getOperand(op), InBB);
10667 }
10668 }
10669
10670 Value *Base = FixedOperands[0];
Dan Gohmand6aa02d2009-07-28 01:40:03 +000010671 GetElementPtrInst *GEP =
10672 GetElementPtrInst::Create(Base, FixedOperands.begin()+1,
10673 FixedOperands.end());
10674 if (cast<GEPOperator>(FirstInst)->isInBounds())
10675 cast<GEPOperator>(GEP)->setIsInBounds(true);
10676 return GEP;
Chris Lattner05f18922008-12-01 02:34:36 +000010677}
10678
10679
Chris Lattner21550882009-02-23 05:56:17 +000010680/// isSafeAndProfitableToSinkLoad - Return true if we know that it is safe to
10681/// sink the load out of the block that defines it. This means that it must be
Chris Lattner36d3e322009-02-21 00:46:50 +000010682/// obvious the value of the load is not changed from the point of the load to
10683/// the end of the block it is in.
Chris Lattnerfd905ca2007-02-01 22:30:07 +000010684///
10685/// Finally, it is safe, but not profitable, to sink a load targetting a
10686/// non-address-taken alloca. Doing so will cause us to not promote the alloca
10687/// to a register.
Chris Lattner36d3e322009-02-21 00:46:50 +000010688static bool isSafeAndProfitableToSinkLoad(LoadInst *L) {
Chris Lattner76c73142006-11-01 07:13:54 +000010689 BasicBlock::iterator BBI = L, E = L->getParent()->end();
10690
10691 for (++BBI; BBI != E; ++BBI)
10692 if (BBI->mayWriteToMemory())
10693 return false;
Chris Lattnerfd905ca2007-02-01 22:30:07 +000010694
10695 // Check for non-address taken alloca. If not address-taken already, it isn't
10696 // profitable to do this xform.
10697 if (AllocaInst *AI = dyn_cast<AllocaInst>(L->getOperand(0))) {
10698 bool isAddressTaken = false;
10699 for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end();
10700 UI != E; ++UI) {
10701 if (isa<LoadInst>(UI)) continue;
10702 if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
10703 // If storing TO the alloca, then the address isn't taken.
10704 if (SI->getOperand(1) == AI) continue;
10705 }
10706 isAddressTaken = true;
10707 break;
10708 }
10709
Chris Lattner36d3e322009-02-21 00:46:50 +000010710 if (!isAddressTaken && AI->isStaticAlloca())
Chris Lattnerfd905ca2007-02-01 22:30:07 +000010711 return false;
10712 }
10713
Chris Lattner36d3e322009-02-21 00:46:50 +000010714 // If this load is a load from a GEP with a constant offset from an alloca,
10715 // then we don't want to sink it. In its present form, it will be
10716 // load [constant stack offset]. Sinking it will cause us to have to
10717 // materialize the stack addresses in each predecessor in a register only to
10718 // do a shared load from register in the successor.
10719 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(L->getOperand(0)))
10720 if (AllocaInst *AI = dyn_cast<AllocaInst>(GEP->getOperand(0)))
10721 if (AI->isStaticAlloca() && GEP->hasAllConstantIndices())
10722 return false;
10723
Chris Lattner76c73142006-11-01 07:13:54 +000010724 return true;
10725}
10726
Chris Lattner9fe38862003-06-19 17:00:31 +000010727
Chris Lattnerbac32862004-11-14 19:13:23 +000010728// FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
10729// operator and they all are only used by the PHI, PHI together their
10730// inputs, and do the operation once, to the result of the PHI.
10731Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
10732 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
10733
10734 // Scan the instruction, looking for input operations that can be folded away.
10735 // If all input operands to the phi are the same instruction (e.g. a cast from
10736 // the same type or "+42") we can pull the operation through the PHI, reducing
10737 // code size and simplifying code.
10738 Constant *ConstantOp = 0;
10739 const Type *CastSrcTy = 0;
Chris Lattner76c73142006-11-01 07:13:54 +000010740 bool isVolatile = false;
Chris Lattnerbac32862004-11-14 19:13:23 +000010741 if (isa<CastInst>(FirstInst)) {
10742 CastSrcTy = FirstInst->getOperand(0)->getType();
Reid Spencer832254e2007-02-02 02:16:23 +000010743 } else if (isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +000010744 // Can fold binop, compare or shift here if the RHS is a constant,
10745 // otherwise call FoldPHIArgBinOpIntoPHI.
Chris Lattnerbac32862004-11-14 19:13:23 +000010746 ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
Chris Lattner7da52b22006-11-01 04:51:18 +000010747 if (ConstantOp == 0)
10748 return FoldPHIArgBinOpIntoPHI(PN);
Chris Lattner76c73142006-11-01 07:13:54 +000010749 } else if (LoadInst *LI = dyn_cast<LoadInst>(FirstInst)) {
10750 isVolatile = LI->isVolatile();
10751 // We can't sink the load if the loaded value could be modified between the
10752 // load and the PHI.
10753 if (LI->getParent() != PN.getIncomingBlock(0) ||
Chris Lattner36d3e322009-02-21 00:46:50 +000010754 !isSafeAndProfitableToSinkLoad(LI))
Chris Lattner76c73142006-11-01 07:13:54 +000010755 return 0;
Chris Lattner71042962008-07-08 17:18:32 +000010756
10757 // If the PHI is of volatile loads and the load block has multiple
10758 // successors, sinking it would remove a load of the volatile value from
10759 // the path through the other successor.
10760 if (isVolatile &&
10761 LI->getParent()->getTerminator()->getNumSuccessors() != 1)
10762 return 0;
10763
Chris Lattner9c080502006-11-01 07:43:41 +000010764 } else if (isa<GetElementPtrInst>(FirstInst)) {
Chris Lattner05f18922008-12-01 02:34:36 +000010765 return FoldPHIArgGEPIntoPHI(PN);
Chris Lattnerbac32862004-11-14 19:13:23 +000010766 } else {
10767 return 0; // Cannot fold this operation.
10768 }
10769
10770 // Check to see if all arguments are the same operation.
10771 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10772 if (!isa<Instruction>(PN.getIncomingValue(i))) return 0;
10773 Instruction *I = cast<Instruction>(PN.getIncomingValue(i));
Reid Spencere4d87aa2006-12-23 06:05:41 +000010774 if (!I->hasOneUse() || !I->isSameOperationAs(FirstInst))
Chris Lattnerbac32862004-11-14 19:13:23 +000010775 return 0;
10776 if (CastSrcTy) {
10777 if (I->getOperand(0)->getType() != CastSrcTy)
10778 return 0; // Cast operation must match.
Chris Lattner76c73142006-11-01 07:13:54 +000010779 } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +000010780 // We can't sink the load if the loaded value could be modified between
10781 // the load and the PHI.
Chris Lattner76c73142006-11-01 07:13:54 +000010782 if (LI->isVolatile() != isVolatile ||
10783 LI->getParent() != PN.getIncomingBlock(i) ||
Chris Lattner36d3e322009-02-21 00:46:50 +000010784 !isSafeAndProfitableToSinkLoad(LI))
Chris Lattner76c73142006-11-01 07:13:54 +000010785 return 0;
Chris Lattner40700fe2008-04-29 17:28:22 +000010786
Chris Lattner71042962008-07-08 17:18:32 +000010787 // If the PHI is of volatile loads and the load block has multiple
10788 // successors, sinking it would remove a load of the volatile value from
10789 // the path through the other successor.
Chris Lattner40700fe2008-04-29 17:28:22 +000010790 if (isVolatile &&
10791 LI->getParent()->getTerminator()->getNumSuccessors() != 1)
10792 return 0;
Chris Lattner40700fe2008-04-29 17:28:22 +000010793
Chris Lattnerbac32862004-11-14 19:13:23 +000010794 } else if (I->getOperand(1) != ConstantOp) {
10795 return 0;
10796 }
10797 }
10798
10799 // Okay, they are all the same operation. Create a new PHI node of the
10800 // correct type, and PHI together all of the LHS's of the instructions.
Gabor Greif051a9502008-04-06 20:25:17 +000010801 PHINode *NewPN = PHINode::Create(FirstInst->getOperand(0)->getType(),
10802 PN.getName()+".in");
Chris Lattner55517062005-01-29 00:39:08 +000010803 NewPN->reserveOperandSpace(PN.getNumOperands()/2);
Chris Lattnerb5893442004-11-14 19:29:34 +000010804
10805 Value *InVal = FirstInst->getOperand(0);
10806 NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
Chris Lattnerbac32862004-11-14 19:13:23 +000010807
10808 // Add all operands to the new PHI.
Chris Lattnerb5893442004-11-14 19:29:34 +000010809 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10810 Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
10811 if (NewInVal != InVal)
10812 InVal = 0;
10813 NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
10814 }
10815
10816 Value *PhiVal;
10817 if (InVal) {
10818 // The new PHI unions all of the same values together. This is really
10819 // common, so we handle it intelligently here for compile-time speed.
10820 PhiVal = InVal;
10821 delete NewPN;
10822 } else {
10823 InsertNewInstBefore(NewPN, PN);
10824 PhiVal = NewPN;
10825 }
Misha Brukmanfd939082005-04-21 23:48:37 +000010826
Chris Lattnerbac32862004-11-14 19:13:23 +000010827 // Insert and return the new operation.
Reid Spencer3da59db2006-11-27 01:05:10 +000010828 if (CastInst* FirstCI = dyn_cast<CastInst>(FirstInst))
Gabor Greif7cbd8a32008-05-16 19:29:10 +000010829 return CastInst::Create(FirstCI->getOpcode(), PhiVal, PN.getType());
Chris Lattner54545ac2008-04-29 17:13:43 +000010830 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Gabor Greif7cbd8a32008-05-16 19:29:10 +000010831 return BinaryOperator::Create(BinOp->getOpcode(), PhiVal, ConstantOp);
Chris Lattner54545ac2008-04-29 17:13:43 +000010832 if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
Owen Anderson333c4002009-07-09 23:48:35 +000010833 return CmpInst::Create(*Context, CIOp->getOpcode(), CIOp->getPredicate(),
Reid Spencere4d87aa2006-12-23 06:05:41 +000010834 PhiVal, ConstantOp);
Chris Lattner54545ac2008-04-29 17:13:43 +000010835 assert(isa<LoadInst>(FirstInst) && "Unknown operation");
10836
10837 // If this was a volatile load that we are merging, make sure to loop through
10838 // and mark all the input loads as non-volatile. If we don't do this, we will
10839 // insert a new volatile load and the old ones will not be deletable.
10840 if (isVolatile)
10841 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
10842 cast<LoadInst>(PN.getIncomingValue(i))->setVolatile(false);
10843
10844 return new LoadInst(PhiVal, "", isVolatile);
Chris Lattnerbac32862004-11-14 19:13:23 +000010845}
Chris Lattnera1be5662002-05-02 17:06:02 +000010846
Chris Lattnera3fd1c52005-01-17 05:10:15 +000010847/// DeadPHICycle - Return true if this PHI node is only used by a PHI node cycle
10848/// that is dead.
Chris Lattner0e5444b2007-03-26 20:40:50 +000010849static bool DeadPHICycle(PHINode *PN,
10850 SmallPtrSet<PHINode*, 16> &PotentiallyDeadPHIs) {
Chris Lattnera3fd1c52005-01-17 05:10:15 +000010851 if (PN->use_empty()) return true;
10852 if (!PN->hasOneUse()) return false;
10853
10854 // Remember this node, and if we find the cycle, return.
Chris Lattner0e5444b2007-03-26 20:40:50 +000010855 if (!PotentiallyDeadPHIs.insert(PN))
Chris Lattnera3fd1c52005-01-17 05:10:15 +000010856 return true;
Chris Lattner92103de2007-08-28 04:23:55 +000010857
10858 // Don't scan crazily complex things.
10859 if (PotentiallyDeadPHIs.size() == 16)
10860 return false;
Chris Lattnera3fd1c52005-01-17 05:10:15 +000010861
10862 if (PHINode *PU = dyn_cast<PHINode>(PN->use_back()))
10863 return DeadPHICycle(PU, PotentiallyDeadPHIs);
Misha Brukmanfd939082005-04-21 23:48:37 +000010864
Chris Lattnera3fd1c52005-01-17 05:10:15 +000010865 return false;
10866}
10867
Chris Lattnercf5008a2007-11-06 21:52:06 +000010868/// PHIsEqualValue - Return true if this phi node is always equal to
10869/// NonPhiInVal. This happens with mutually cyclic phi nodes like:
10870/// z = some value; x = phi (y, z); y = phi (x, z)
10871static bool PHIsEqualValue(PHINode *PN, Value *NonPhiInVal,
10872 SmallPtrSet<PHINode*, 16> &ValueEqualPHIs) {
10873 // See if we already saw this PHI node.
10874 if (!ValueEqualPHIs.insert(PN))
10875 return true;
10876
10877 // Don't scan crazily complex things.
10878 if (ValueEqualPHIs.size() == 16)
10879 return false;
10880
10881 // Scan the operands to see if they are either phi nodes or are equal to
10882 // the value.
10883 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
10884 Value *Op = PN->getIncomingValue(i);
10885 if (PHINode *OpPN = dyn_cast<PHINode>(Op)) {
10886 if (!PHIsEqualValue(OpPN, NonPhiInVal, ValueEqualPHIs))
10887 return false;
10888 } else if (Op != NonPhiInVal)
10889 return false;
10890 }
10891
10892 return true;
10893}
10894
10895
Chris Lattner473945d2002-05-06 18:06:38 +000010896// PHINode simplification
10897//
Chris Lattner7e708292002-06-25 16:13:24 +000010898Instruction *InstCombiner::visitPHINode(PHINode &PN) {
Owen Andersonb64ab872006-07-10 22:15:25 +000010899 // If LCSSA is around, don't mess with Phi nodes
Chris Lattnerf964f322007-03-04 04:27:24 +000010900 if (MustPreserveLCSSA) return 0;
Owen Andersond1b78a12006-07-10 19:03:49 +000010901
Owen Anderson7e057142006-07-10 22:03:18 +000010902 if (Value *V = PN.hasConstantValue())
10903 return ReplaceInstUsesWith(PN, V);
10904
Owen Anderson7e057142006-07-10 22:03:18 +000010905 // If all PHI operands are the same operation, pull them through the PHI,
10906 // reducing code size.
10907 if (isa<Instruction>(PN.getIncomingValue(0)) &&
Chris Lattner05f18922008-12-01 02:34:36 +000010908 isa<Instruction>(PN.getIncomingValue(1)) &&
10909 cast<Instruction>(PN.getIncomingValue(0))->getOpcode() ==
10910 cast<Instruction>(PN.getIncomingValue(1))->getOpcode() &&
10911 // FIXME: The hasOneUse check will fail for PHIs that use the value more
10912 // than themselves more than once.
Owen Anderson7e057142006-07-10 22:03:18 +000010913 PN.getIncomingValue(0)->hasOneUse())
10914 if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
10915 return Result;
10916
10917 // If this is a trivial cycle in the PHI node graph, remove it. Basically, if
10918 // this PHI only has a single use (a PHI), and if that PHI only has one use (a
10919 // PHI)... break the cycle.
Chris Lattnerff9f13a2007-01-15 07:30:06 +000010920 if (PN.hasOneUse()) {
10921 Instruction *PHIUser = cast<Instruction>(PN.use_back());
10922 if (PHINode *PU = dyn_cast<PHINode>(PHIUser)) {
Chris Lattner0e5444b2007-03-26 20:40:50 +000010923 SmallPtrSet<PHINode*, 16> PotentiallyDeadPHIs;
Owen Anderson7e057142006-07-10 22:03:18 +000010924 PotentiallyDeadPHIs.insert(&PN);
10925 if (DeadPHICycle(PU, PotentiallyDeadPHIs))
Owen Anderson9e9a0d52009-07-30 23:03:37 +000010926 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
Owen Anderson7e057142006-07-10 22:03:18 +000010927 }
Chris Lattnerff9f13a2007-01-15 07:30:06 +000010928
10929 // If this phi has a single use, and if that use just computes a value for
10930 // the next iteration of a loop, delete the phi. This occurs with unused
10931 // induction variables, e.g. "for (int j = 0; ; ++j);". Detecting this
10932 // common case here is good because the only other things that catch this
10933 // are induction variable analysis (sometimes) and ADCE, which is only run
10934 // late.
10935 if (PHIUser->hasOneUse() &&
10936 (isa<BinaryOperator>(PHIUser) || isa<GetElementPtrInst>(PHIUser)) &&
10937 PHIUser->use_back() == &PN) {
Owen Anderson9e9a0d52009-07-30 23:03:37 +000010938 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
Chris Lattnerff9f13a2007-01-15 07:30:06 +000010939 }
10940 }
Owen Anderson7e057142006-07-10 22:03:18 +000010941
Chris Lattnercf5008a2007-11-06 21:52:06 +000010942 // We sometimes end up with phi cycles that non-obviously end up being the
10943 // same value, for example:
10944 // z = some value; x = phi (y, z); y = phi (x, z)
10945 // where the phi nodes don't necessarily need to be in the same block. Do a
10946 // quick check to see if the PHI node only contains a single non-phi value, if
10947 // so, scan to see if the phi cycle is actually equal to that value.
10948 {
10949 unsigned InValNo = 0, NumOperandVals = PN.getNumIncomingValues();
10950 // Scan for the first non-phi operand.
10951 while (InValNo != NumOperandVals &&
10952 isa<PHINode>(PN.getIncomingValue(InValNo)))
10953 ++InValNo;
10954
10955 if (InValNo != NumOperandVals) {
10956 Value *NonPhiInVal = PN.getOperand(InValNo);
10957
10958 // Scan the rest of the operands to see if there are any conflicts, if so
10959 // there is no need to recursively scan other phis.
10960 for (++InValNo; InValNo != NumOperandVals; ++InValNo) {
10961 Value *OpVal = PN.getIncomingValue(InValNo);
10962 if (OpVal != NonPhiInVal && !isa<PHINode>(OpVal))
10963 break;
10964 }
10965
10966 // If we scanned over all operands, then we have one unique value plus
10967 // phi values. Scan PHI nodes to see if they all merge in each other or
10968 // the value.
10969 if (InValNo == NumOperandVals) {
10970 SmallPtrSet<PHINode*, 16> ValueEqualPHIs;
10971 if (PHIsEqualValue(&PN, NonPhiInVal, ValueEqualPHIs))
10972 return ReplaceInstUsesWith(PN, NonPhiInVal);
10973 }
10974 }
10975 }
Chris Lattner60921c92003-12-19 05:58:40 +000010976 return 0;
Chris Lattner473945d2002-05-06 18:06:38 +000010977}
10978
Reid Spencer17212df2006-12-12 09:18:51 +000010979static Value *InsertCastToIntPtrTy(Value *V, const Type *DTy,
10980 Instruction *InsertPoint,
10981 InstCombiner *IC) {
Dan Gohman6de29f82009-06-15 22:12:54 +000010982 unsigned PtrSize = DTy->getScalarSizeInBits();
10983 unsigned VTySize = V->getType()->getScalarSizeInBits();
Reid Spencer17212df2006-12-12 09:18:51 +000010984 // We must cast correctly to the pointer type. Ensure that we
10985 // sign extend the integer value if it is smaller as this is
10986 // used for address computation.
10987 Instruction::CastOps opcode =
10988 (VTySize < PtrSize ? Instruction::SExt :
10989 (VTySize == PtrSize ? Instruction::BitCast : Instruction::Trunc));
10990 return IC->InsertCastBefore(opcode, V, DTy, *InsertPoint);
Chris Lattner28977af2004-04-05 01:30:19 +000010991}
10992
Chris Lattnera1be5662002-05-02 17:06:02 +000010993
Chris Lattner7e708292002-06-25 16:13:24 +000010994Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
Chris Lattner620ce142004-05-07 22:09:22 +000010995 Value *PtrOp = GEP.getOperand(0);
Chris Lattner9bc14642007-04-28 00:57:34 +000010996 // Is it 'getelementptr %P, i32 0' or 'getelementptr %P'
Chris Lattner7e708292002-06-25 16:13:24 +000010997 // If so, eliminate the noop.
Chris Lattnerc6bd1952004-02-22 05:25:17 +000010998 if (GEP.getNumOperands() == 1)
Chris Lattner620ce142004-05-07 22:09:22 +000010999 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattnerc6bd1952004-02-22 05:25:17 +000011000
Chris Lattnere87597f2004-10-16 18:11:37 +000011001 if (isa<UndefValue>(GEP.getOperand(0)))
Owen Anderson9e9a0d52009-07-30 23:03:37 +000011002 return ReplaceInstUsesWith(GEP, UndefValue::get(GEP.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +000011003
Chris Lattnerc6bd1952004-02-22 05:25:17 +000011004 bool HasZeroPointerIndex = false;
11005 if (Constant *C = dyn_cast<Constant>(GEP.getOperand(1)))
11006 HasZeroPointerIndex = C->isNullValue();
11007
11008 if (GEP.getNumOperands() == 2 && HasZeroPointerIndex)
Chris Lattner620ce142004-05-07 22:09:22 +000011009 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattnera1be5662002-05-02 17:06:02 +000011010
Chris Lattner28977af2004-04-05 01:30:19 +000011011 // Eliminate unneeded casts for indices.
11012 bool MadeChange = false;
Chris Lattnerdb9654e2007-03-25 20:43:09 +000011013
Chris Lattnercb69a4e2004-04-07 18:38:20 +000011014 gep_type_iterator GTI = gep_type_begin(GEP);
Gabor Greif177dd3f2008-06-12 21:37:33 +000011015 for (User::op_iterator i = GEP.op_begin() + 1, e = GEP.op_end();
11016 i != e; ++i, ++GTI) {
Dan Gohmance9fe9f2009-07-21 23:21:54 +000011017 if (TD && isa<SequentialType>(*GTI)) {
Gabor Greif177dd3f2008-06-12 21:37:33 +000011018 if (CastInst *CI = dyn_cast<CastInst>(*i)) {
Chris Lattner76b7a062007-01-15 07:02:54 +000011019 if (CI->getOpcode() == Instruction::ZExt ||
11020 CI->getOpcode() == Instruction::SExt) {
11021 const Type *SrcTy = CI->getOperand(0)->getType();
11022 // We can eliminate a cast from i32 to i64 iff the target
11023 // is a 32-bit pointer target.
Dan Gohman6de29f82009-06-15 22:12:54 +000011024 if (SrcTy->getScalarSizeInBits() >= TD->getPointerSizeInBits()) {
Chris Lattner76b7a062007-01-15 07:02:54 +000011025 MadeChange = true;
Gabor Greif177dd3f2008-06-12 21:37:33 +000011026 *i = CI->getOperand(0);
Chris Lattner28977af2004-04-05 01:30:19 +000011027 }
11028 }
11029 }
Chris Lattnercb69a4e2004-04-07 18:38:20 +000011030 // If we are using a wider index than needed for this platform, shrink it
Dan Gohman4f833d42008-09-11 23:06:38 +000011031 // to what we need. If narrower, sign-extend it to what we need.
11032 // If the incoming value needs a cast instruction,
Chris Lattnercb69a4e2004-04-07 18:38:20 +000011033 // insert it. This explicit cast can make subsequent optimizations more
11034 // obvious.
Gabor Greif177dd3f2008-06-12 21:37:33 +000011035 Value *Op = *i;
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000011036 if (TD->getTypeSizeInBits(Op->getType()) > TD->getPointerSizeInBits()) {
Chris Lattner4f1134e2004-04-17 18:16:10 +000011037 if (Constant *C = dyn_cast<Constant>(Op)) {
Owen Andersonbaf3c402009-07-29 18:55:55 +000011038 *i = ConstantExpr::getTrunc(C, TD->getIntPtrType());
Chris Lattner4f1134e2004-04-17 18:16:10 +000011039 MadeChange = true;
11040 } else {
Reid Spencer17212df2006-12-12 09:18:51 +000011041 Op = InsertCastBefore(Instruction::Trunc, Op, TD->getIntPtrType(),
11042 GEP);
Gabor Greif177dd3f2008-06-12 21:37:33 +000011043 *i = Op;
Chris Lattnercb69a4e2004-04-07 18:38:20 +000011044 MadeChange = true;
11045 }
Eric Christophera66297a2009-07-25 02:45:27 +000011046 } else if (TD->getTypeSizeInBits(Op->getType())
11047 < TD->getPointerSizeInBits()) {
Dan Gohman4f833d42008-09-11 23:06:38 +000011048 if (Constant *C = dyn_cast<Constant>(Op)) {
Owen Andersonbaf3c402009-07-29 18:55:55 +000011049 *i = ConstantExpr::getSExt(C, TD->getIntPtrType());
Dan Gohman4f833d42008-09-11 23:06:38 +000011050 MadeChange = true;
11051 } else {
11052 Op = InsertCastBefore(Instruction::SExt, Op, TD->getIntPtrType(),
11053 GEP);
11054 *i = Op;
11055 MadeChange = true;
11056 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000011057 }
Chris Lattner28977af2004-04-05 01:30:19 +000011058 }
Chris Lattnerdb9654e2007-03-25 20:43:09 +000011059 }
Chris Lattner28977af2004-04-05 01:30:19 +000011060 if (MadeChange) return &GEP;
11061
Chris Lattner90ac28c2002-08-02 19:29:35 +000011062 // Combine Indices - If the source pointer to this getelementptr instruction
11063 // is a getelementptr instruction, combine the indices of the two
11064 // getelementptr instructions into a single instruction.
11065 //
Chris Lattner72588fc2007-02-15 22:48:32 +000011066 SmallVector<Value*, 8> SrcGEPOperands;
Dan Gohmand6aa02d2009-07-28 01:40:03 +000011067 bool BothInBounds = cast<GEPOperator>(&GEP)->isInBounds();
11068 if (GEPOperator *Src = dyn_cast<GEPOperator>(PtrOp)) {
Chris Lattner72588fc2007-02-15 22:48:32 +000011069 SrcGEPOperands.append(Src->op_begin(), Src->op_end());
Dan Gohmand6aa02d2009-07-28 01:40:03 +000011070 if (!Src->isInBounds())
11071 BothInBounds = false;
11072 }
Chris Lattnerebd985c2004-03-25 22:59:29 +000011073
11074 if (!SrcGEPOperands.empty()) {
Chris Lattner620ce142004-05-07 22:09:22 +000011075 // Note that if our source is a gep chain itself that we wait for that
11076 // chain to be resolved before we perform this transformation. This
11077 // avoids us creating a TON of code in some cases.
11078 //
11079 if (isa<GetElementPtrInst>(SrcGEPOperands[0]) &&
11080 cast<Instruction>(SrcGEPOperands[0])->getNumOperands() == 2)
11081 return 0; // Wait until our source is folded to completion.
11082
Chris Lattner72588fc2007-02-15 22:48:32 +000011083 SmallVector<Value*, 8> Indices;
Chris Lattner620ce142004-05-07 22:09:22 +000011084
11085 // Find out whether the last index in the source GEP is a sequential idx.
11086 bool EndsWithSequential = false;
11087 for (gep_type_iterator I = gep_type_begin(*cast<User>(PtrOp)),
11088 E = gep_type_end(*cast<User>(PtrOp)); I != E; ++I)
Chris Lattnerbe97b4e2004-05-08 22:41:42 +000011089 EndsWithSequential = !isa<StructType>(*I);
Misha Brukmanfd939082005-04-21 23:48:37 +000011090
Chris Lattner90ac28c2002-08-02 19:29:35 +000011091 // Can we combine the two pointer arithmetics offsets?
Chris Lattner620ce142004-05-07 22:09:22 +000011092 if (EndsWithSequential) {
Chris Lattnerdecd0812003-03-05 22:33:14 +000011093 // Replace: gep (gep %P, long B), long A, ...
11094 // With: T = long A+B; gep %P, T, ...
11095 //
Chris Lattner620ce142004-05-07 22:09:22 +000011096 Value *Sum, *SO1 = SrcGEPOperands.back(), *GO1 = GEP.getOperand(1);
Owen Andersona7235ea2009-07-31 20:28:14 +000011097 if (SO1 == Constant::getNullValue(SO1->getType())) {
Chris Lattner28977af2004-04-05 01:30:19 +000011098 Sum = GO1;
Owen Andersona7235ea2009-07-31 20:28:14 +000011099 } else if (GO1 == Constant::getNullValue(GO1->getType())) {
Chris Lattner28977af2004-04-05 01:30:19 +000011100 Sum = SO1;
11101 } else {
11102 // If they aren't the same type, convert both to an integer of the
11103 // target's pointer size.
11104 if (SO1->getType() != GO1->getType()) {
11105 if (Constant *SO1C = dyn_cast<Constant>(SO1)) {
Owen Andersond672ecb2009-07-03 00:17:18 +000011106 SO1 =
Owen Andersonbaf3c402009-07-29 18:55:55 +000011107 ConstantExpr::getIntegerCast(SO1C, GO1->getType(), true);
Chris Lattner28977af2004-04-05 01:30:19 +000011108 } else if (Constant *GO1C = dyn_cast<Constant>(GO1)) {
Owen Andersond672ecb2009-07-03 00:17:18 +000011109 GO1 =
Owen Andersonbaf3c402009-07-29 18:55:55 +000011110 ConstantExpr::getIntegerCast(GO1C, SO1->getType(), true);
Dan Gohmance9fe9f2009-07-21 23:21:54 +000011111 } else if (TD) {
Duncan Sands514ab342007-11-01 20:53:16 +000011112 unsigned PS = TD->getPointerSizeInBits();
11113 if (TD->getTypeSizeInBits(SO1->getType()) == PS) {
Chris Lattner28977af2004-04-05 01:30:19 +000011114 // Convert GO1 to SO1's type.
Reid Spencer17212df2006-12-12 09:18:51 +000011115 GO1 = InsertCastToIntPtrTy(GO1, SO1->getType(), &GEP, this);
Chris Lattner28977af2004-04-05 01:30:19 +000011116
Duncan Sands514ab342007-11-01 20:53:16 +000011117 } else if (TD->getTypeSizeInBits(GO1->getType()) == PS) {
Chris Lattner28977af2004-04-05 01:30:19 +000011118 // Convert SO1 to GO1's type.
Reid Spencer17212df2006-12-12 09:18:51 +000011119 SO1 = InsertCastToIntPtrTy(SO1, GO1->getType(), &GEP, this);
Chris Lattner28977af2004-04-05 01:30:19 +000011120 } else {
11121 const Type *PT = TD->getIntPtrType();
Reid Spencer17212df2006-12-12 09:18:51 +000011122 SO1 = InsertCastToIntPtrTy(SO1, PT, &GEP, this);
11123 GO1 = InsertCastToIntPtrTy(GO1, PT, &GEP, this);
Chris Lattner28977af2004-04-05 01:30:19 +000011124 }
11125 }
11126 }
Chris Lattner620ce142004-05-07 22:09:22 +000011127 if (isa<Constant>(SO1) && isa<Constant>(GO1))
Owen Andersonbaf3c402009-07-29 18:55:55 +000011128 Sum = ConstantExpr::getAdd(cast<Constant>(SO1),
Owen Andersond672ecb2009-07-03 00:17:18 +000011129 cast<Constant>(GO1));
Chris Lattner620ce142004-05-07 22:09:22 +000011130 else {
Gabor Greif7cbd8a32008-05-16 19:29:10 +000011131 Sum = BinaryOperator::CreateAdd(SO1, GO1, PtrOp->getName()+".sum");
Chris Lattner48595f12004-06-10 02:07:29 +000011132 InsertNewInstBefore(cast<Instruction>(Sum), GEP);
Chris Lattner620ce142004-05-07 22:09:22 +000011133 }
Chris Lattner28977af2004-04-05 01:30:19 +000011134 }
Chris Lattner620ce142004-05-07 22:09:22 +000011135
11136 // Recycle the GEP we already have if possible.
11137 if (SrcGEPOperands.size() == 2) {
11138 GEP.setOperand(0, SrcGEPOperands[0]);
11139 GEP.setOperand(1, Sum);
11140 return &GEP;
11141 } else {
11142 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
11143 SrcGEPOperands.end()-1);
11144 Indices.push_back(Sum);
11145 Indices.insert(Indices.end(), GEP.op_begin()+2, GEP.op_end());
11146 }
Misha Brukmanfd939082005-04-21 23:48:37 +000011147 } else if (isa<Constant>(*GEP.idx_begin()) &&
Chris Lattner28977af2004-04-05 01:30:19 +000011148 cast<Constant>(*GEP.idx_begin())->isNullValue() &&
Misha Brukmanfd939082005-04-21 23:48:37 +000011149 SrcGEPOperands.size() != 1) {
Chris Lattner90ac28c2002-08-02 19:29:35 +000011150 // Otherwise we can do the fold if the first index of the GEP is a zero
Chris Lattnerebd985c2004-03-25 22:59:29 +000011151 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
11152 SrcGEPOperands.end());
Chris Lattner90ac28c2002-08-02 19:29:35 +000011153 Indices.insert(Indices.end(), GEP.idx_begin()+1, GEP.idx_end());
11154 }
11155
Dan Gohmand6aa02d2009-07-28 01:40:03 +000011156 if (!Indices.empty()) {
11157 GetElementPtrInst *NewGEP = GetElementPtrInst::Create(SrcGEPOperands[0],
11158 Indices.begin(),
11159 Indices.end(),
11160 GEP.getName());
11161 if (BothInBounds)
11162 cast<GEPOperator>(NewGEP)->setIsInBounds(true);
11163 return NewGEP;
11164 }
Chris Lattner9b761232002-08-17 22:21:59 +000011165
Chris Lattner620ce142004-05-07 22:09:22 +000011166 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(PtrOp)) {
Chris Lattner9b761232002-08-17 22:21:59 +000011167 // GEP of global variable. If all of the indices for this GEP are
11168 // constants, we can promote this to a constexpr instead of an instruction.
11169
11170 // Scan for nonconstants...
Chris Lattner55eb1c42007-01-31 04:40:53 +000011171 SmallVector<Constant*, 8> Indices;
Chris Lattner9b761232002-08-17 22:21:59 +000011172 User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end();
11173 for (; I != E && isa<Constant>(*I); ++I)
11174 Indices.push_back(cast<Constant>(*I));
11175
11176 if (I == E) { // If they are all constants...
Owen Andersonbaf3c402009-07-29 18:55:55 +000011177 Constant *CE = ConstantExpr::getGetElementPtr(GV,
Chris Lattner55eb1c42007-01-31 04:40:53 +000011178 &Indices[0],Indices.size());
Chris Lattner9b761232002-08-17 22:21:59 +000011179
11180 // Replace all uses of the GEP with the new constexpr...
11181 return ReplaceInstUsesWith(GEP, CE);
11182 }
Reid Spencer3da59db2006-11-27 01:05:10 +000011183 } else if (Value *X = getBitCastOperand(PtrOp)) { // Is the operand a cast?
Chris Lattnereed48272005-09-13 00:40:14 +000011184 if (!isa<PointerType>(X->getType())) {
11185 // Not interesting. Source pointer must be a cast from pointer.
11186 } else if (HasZeroPointerIndex) {
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000011187 // transform: GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ...
11188 // into : GEP [10 x i8]* X, i32 0, ...
Chris Lattnereed48272005-09-13 00:40:14 +000011189 //
Duncan Sands5b7cfb02009-03-02 09:18:21 +000011190 // Likewise, transform: GEP (bitcast i8* X to [0 x i8]*), i32 0, ...
11191 // into : GEP i8* X, ...
11192 //
Chris Lattnereed48272005-09-13 00:40:14 +000011193 // This occurs when the program declares an array extern like "int X[];"
Chris Lattnereed48272005-09-13 00:40:14 +000011194 const PointerType *CPTy = cast<PointerType>(PtrOp->getType());
11195 const PointerType *XTy = cast<PointerType>(X->getType());
Duncan Sands5b7cfb02009-03-02 09:18:21 +000011196 if (const ArrayType *CATy =
11197 dyn_cast<ArrayType>(CPTy->getElementType())) {
11198 // GEP (bitcast i8* X to [0 x i8]*), i32 0, ... ?
11199 if (CATy->getElementType() == XTy->getElementType()) {
11200 // -> GEP i8* X, ...
11201 SmallVector<Value*, 8> Indices(GEP.idx_begin()+1, GEP.idx_end());
Dan Gohmand6aa02d2009-07-28 01:40:03 +000011202 GetElementPtrInst *NewGEP =
11203 GetElementPtrInst::Create(X, Indices.begin(), Indices.end(),
11204 GEP.getName());
11205 if (cast<GEPOperator>(&GEP)->isInBounds())
11206 cast<GEPOperator>(NewGEP)->setIsInBounds(true);
11207 return NewGEP;
Duncan Sands5b7cfb02009-03-02 09:18:21 +000011208 } else if (const ArrayType *XATy =
11209 dyn_cast<ArrayType>(XTy->getElementType())) {
11210 // GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ... ?
Chris Lattnereed48272005-09-13 00:40:14 +000011211 if (CATy->getElementType() == XATy->getElementType()) {
Duncan Sands5b7cfb02009-03-02 09:18:21 +000011212 // -> GEP [10 x i8]* X, i32 0, ...
Chris Lattnereed48272005-09-13 00:40:14 +000011213 // At this point, we know that the cast source type is a pointer
11214 // to an array of the same type as the destination pointer
11215 // array. Because the array type is never stepped over (there
11216 // is a leading zero) we can fold the cast into this GEP.
11217 GEP.setOperand(0, X);
11218 return &GEP;
11219 }
Duncan Sands5b7cfb02009-03-02 09:18:21 +000011220 }
11221 }
Chris Lattnereed48272005-09-13 00:40:14 +000011222 } else if (GEP.getNumOperands() == 2) {
11223 // Transform things like:
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000011224 // %t = getelementptr i32* bitcast ([2 x i32]* %str to i32*), i32 %V
11225 // into: %t1 = getelementptr [2 x i32]* %str, i32 0, i32 %V; bitcast
Chris Lattnereed48272005-09-13 00:40:14 +000011226 const Type *SrcElTy = cast<PointerType>(X->getType())->getElementType();
11227 const Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
Dan Gohmance9fe9f2009-07-21 23:21:54 +000011228 if (TD && isa<ArrayType>(SrcElTy) &&
Duncan Sands777d2302009-05-09 07:06:46 +000011229 TD->getTypeAllocSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
11230 TD->getTypeAllocSize(ResElTy)) {
David Greeneb8f74792007-09-04 15:46:09 +000011231 Value *Idx[2];
Owen Andersona7235ea2009-07-31 20:28:14 +000011232 Idx[0] = Constant::getNullValue(Type::Int32Ty);
David Greeneb8f74792007-09-04 15:46:09 +000011233 Idx[1] = GEP.getOperand(1);
Dan Gohmand6aa02d2009-07-28 01:40:03 +000011234 GetElementPtrInst *NewGEP =
11235 GetElementPtrInst::Create(X, Idx, Idx + 2, GEP.getName());
11236 if (cast<GEPOperator>(&GEP)->isInBounds())
11237 cast<GEPOperator>(NewGEP)->setIsInBounds(true);
11238 Value *V = InsertNewInstBefore(NewGEP, GEP);
Reid Spencer3da59db2006-11-27 01:05:10 +000011239 // V and GEP are both pointer types --> BitCast
11240 return new BitCastInst(V, GEP.getType());
Chris Lattnerc6bd1952004-02-22 05:25:17 +000011241 }
Chris Lattner7835cdd2005-09-13 18:36:04 +000011242
11243 // Transform things like:
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000011244 // getelementptr i8* bitcast ([100 x double]* X to i8*), i32 %tmp
Chris Lattner7835cdd2005-09-13 18:36:04 +000011245 // (where tmp = 8*tmp2) into:
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000011246 // getelementptr [100 x double]* %arr, i32 0, i32 %tmp2; bitcast
Chris Lattner7835cdd2005-09-13 18:36:04 +000011247
Dan Gohmance9fe9f2009-07-21 23:21:54 +000011248 if (TD && isa<ArrayType>(SrcElTy) && ResElTy == Type::Int8Ty) {
Chris Lattner7835cdd2005-09-13 18:36:04 +000011249 uint64_t ArrayEltSize =
Duncan Sands777d2302009-05-09 07:06:46 +000011250 TD->getTypeAllocSize(cast<ArrayType>(SrcElTy)->getElementType());
Chris Lattner7835cdd2005-09-13 18:36:04 +000011251
11252 // Check to see if "tmp" is a scale by a multiple of ArrayEltSize. We
11253 // allow either a mul, shift, or constant here.
11254 Value *NewIdx = 0;
11255 ConstantInt *Scale = 0;
11256 if (ArrayEltSize == 1) {
11257 NewIdx = GEP.getOperand(1);
Owen Andersond672ecb2009-07-03 00:17:18 +000011258 Scale =
Owen Andersoneed707b2009-07-24 23:12:02 +000011259 ConstantInt::get(cast<IntegerType>(NewIdx->getType()), 1);
Chris Lattner7835cdd2005-09-13 18:36:04 +000011260 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) {
Owen Andersoneed707b2009-07-24 23:12:02 +000011261 NewIdx = ConstantInt::get(CI->getType(), 1);
Chris Lattner7835cdd2005-09-13 18:36:04 +000011262 Scale = CI;
11263 } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){
11264 if (Inst->getOpcode() == Instruction::Shl &&
11265 isa<ConstantInt>(Inst->getOperand(1))) {
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +000011266 ConstantInt *ShAmt = cast<ConstantInt>(Inst->getOperand(1));
11267 uint32_t ShAmtVal = ShAmt->getLimitedValue(64);
Owen Andersoneed707b2009-07-24 23:12:02 +000011268 Scale = ConstantInt::get(cast<IntegerType>(Inst->getType()),
Dan Gohman6de29f82009-06-15 22:12:54 +000011269 1ULL << ShAmtVal);
Chris Lattner7835cdd2005-09-13 18:36:04 +000011270 NewIdx = Inst->getOperand(0);
11271 } else if (Inst->getOpcode() == Instruction::Mul &&
11272 isa<ConstantInt>(Inst->getOperand(1))) {
11273 Scale = cast<ConstantInt>(Inst->getOperand(1));
11274 NewIdx = Inst->getOperand(0);
11275 }
11276 }
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000011277
Chris Lattner7835cdd2005-09-13 18:36:04 +000011278 // If the index will be to exactly the right offset with the scale taken
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000011279 // out, perform the transformation. Note, we don't know whether Scale is
11280 // signed or not. We'll use unsigned version of division/modulo
11281 // operation after making sure Scale doesn't have the sign bit set.
Chris Lattner58b1ac72009-02-25 18:20:01 +000011282 if (ArrayEltSize && Scale && Scale->getSExtValue() >= 0LL &&
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000011283 Scale->getZExtValue() % ArrayEltSize == 0) {
Owen Andersoneed707b2009-07-24 23:12:02 +000011284 Scale = ConstantInt::get(Scale->getType(),
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000011285 Scale->getZExtValue() / ArrayEltSize);
Reid Spencerb83eb642006-10-20 07:07:24 +000011286 if (Scale->getZExtValue() != 1) {
Owen Andersond672ecb2009-07-03 00:17:18 +000011287 Constant *C =
Owen Andersonbaf3c402009-07-29 18:55:55 +000011288 ConstantExpr::getIntegerCast(Scale, NewIdx->getType(),
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000011289 false /*ZExt*/);
Gabor Greif7cbd8a32008-05-16 19:29:10 +000011290 Instruction *Sc = BinaryOperator::CreateMul(NewIdx, C, "idxscale");
Chris Lattner7835cdd2005-09-13 18:36:04 +000011291 NewIdx = InsertNewInstBefore(Sc, GEP);
11292 }
11293
11294 // Insert the new GEP instruction.
David Greeneb8f74792007-09-04 15:46:09 +000011295 Value *Idx[2];
Owen Andersona7235ea2009-07-31 20:28:14 +000011296 Idx[0] = Constant::getNullValue(Type::Int32Ty);
David Greeneb8f74792007-09-04 15:46:09 +000011297 Idx[1] = NewIdx;
Reid Spencer3da59db2006-11-27 01:05:10 +000011298 Instruction *NewGEP =
Gabor Greif051a9502008-04-06 20:25:17 +000011299 GetElementPtrInst::Create(X, Idx, Idx + 2, GEP.getName());
Dan Gohmand6aa02d2009-07-28 01:40:03 +000011300 if (cast<GEPOperator>(&GEP)->isInBounds())
11301 cast<GEPOperator>(NewGEP)->setIsInBounds(true);
Reid Spencer3da59db2006-11-27 01:05:10 +000011302 NewGEP = InsertNewInstBefore(NewGEP, GEP);
11303 // The NewGEP must be pointer typed, so must the old one -> BitCast
11304 return new BitCastInst(NewGEP, GEP.getType());
Chris Lattner7835cdd2005-09-13 18:36:04 +000011305 }
11306 }
Chris Lattnerc6bd1952004-02-22 05:25:17 +000011307 }
Chris Lattner8a2a3112001-12-14 16:52:21 +000011308 }
Chris Lattner58407792009-01-09 04:53:57 +000011309
Chris Lattner46cd5a12009-01-09 05:44:56 +000011310 /// See if we can simplify:
11311 /// X = bitcast A to B*
11312 /// Y = gep X, <...constant indices...>
11313 /// into a gep of the original struct. This is important for SROA and alias
11314 /// analysis of unions. If "A" is also a bitcast, wait for A/X to be merged.
Chris Lattner58407792009-01-09 04:53:57 +000011315 if (BitCastInst *BCI = dyn_cast<BitCastInst>(PtrOp)) {
Dan Gohmance9fe9f2009-07-21 23:21:54 +000011316 if (TD &&
11317 !isa<BitCastInst>(BCI->getOperand(0)) && GEP.hasAllConstantIndices()) {
Chris Lattner46cd5a12009-01-09 05:44:56 +000011318 // Determine how much the GEP moves the pointer. We are guaranteed to get
11319 // a constant back from EmitGEPOffset.
Owen Andersond672ecb2009-07-03 00:17:18 +000011320 ConstantInt *OffsetV =
11321 cast<ConstantInt>(EmitGEPOffset(&GEP, GEP, *this));
Chris Lattner46cd5a12009-01-09 05:44:56 +000011322 int64_t Offset = OffsetV->getSExtValue();
11323
11324 // If this GEP instruction doesn't move the pointer, just replace the GEP
11325 // with a bitcast of the real input to the dest type.
11326 if (Offset == 0) {
11327 // If the bitcast is of an allocation, and the allocation will be
11328 // converted to match the type of the cast, don't touch this.
11329 if (isa<AllocationInst>(BCI->getOperand(0))) {
11330 // See if the bitcast simplifies, if so, don't nuke this GEP yet.
11331 if (Instruction *I = visitBitCast(*BCI)) {
11332 if (I != BCI) {
11333 I->takeName(BCI);
11334 BCI->getParent()->getInstList().insert(BCI, I);
11335 ReplaceInstUsesWith(*BCI, I);
11336 }
11337 return &GEP;
Chris Lattner58407792009-01-09 04:53:57 +000011338 }
Chris Lattner58407792009-01-09 04:53:57 +000011339 }
Chris Lattner46cd5a12009-01-09 05:44:56 +000011340 return new BitCastInst(BCI->getOperand(0), GEP.getType());
Chris Lattner58407792009-01-09 04:53:57 +000011341 }
Chris Lattner46cd5a12009-01-09 05:44:56 +000011342
11343 // Otherwise, if the offset is non-zero, we need to find out if there is a
11344 // field at Offset in 'A's type. If so, we can pull the cast through the
11345 // GEP.
11346 SmallVector<Value*, 8> NewIndices;
11347 const Type *InTy =
11348 cast<PointerType>(BCI->getOperand(0)->getType())->getElementType();
Owen Andersond672ecb2009-07-03 00:17:18 +000011349 if (FindElementAtOffset(InTy, Offset, NewIndices, TD, Context)) {
Chris Lattner46cd5a12009-01-09 05:44:56 +000011350 Instruction *NGEP =
11351 GetElementPtrInst::Create(BCI->getOperand(0), NewIndices.begin(),
11352 NewIndices.end());
11353 if (NGEP->getType() == GEP.getType()) return NGEP;
Dan Gohmand6aa02d2009-07-28 01:40:03 +000011354 if (cast<GEPOperator>(&GEP)->isInBounds())
11355 cast<GEPOperator>(NGEP)->setIsInBounds(true);
Chris Lattner46cd5a12009-01-09 05:44:56 +000011356 InsertNewInstBefore(NGEP, GEP);
11357 NGEP->takeName(&GEP);
11358 return new BitCastInst(NGEP, GEP.getType());
11359 }
Chris Lattner58407792009-01-09 04:53:57 +000011360 }
11361 }
11362
Chris Lattner8a2a3112001-12-14 16:52:21 +000011363 return 0;
11364}
11365
Chris Lattner0864acf2002-11-04 16:18:53 +000011366Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
11367 // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000011368 if (AI.isArrayAllocation()) { // Check C != 1
Reid Spencerb83eb642006-10-20 07:07:24 +000011369 if (const ConstantInt *C = dyn_cast<ConstantInt>(AI.getArraySize())) {
11370 const Type *NewTy =
Owen Andersondebcb012009-07-29 22:17:13 +000011371 ArrayType::get(AI.getAllocatedType(), C->getZExtValue());
Chris Lattner0006bd72002-11-09 00:49:43 +000011372 AllocationInst *New = 0;
Chris Lattner0864acf2002-11-04 16:18:53 +000011373
11374 // Create and insert the replacement instruction...
11375 if (isa<MallocInst>(AI))
Owen Anderson50dead02009-07-15 23:53:25 +000011376 New = new MallocInst(NewTy, 0, AI.getAlignment(), AI.getName());
Chris Lattner0006bd72002-11-09 00:49:43 +000011377 else {
11378 assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
Owen Anderson50dead02009-07-15 23:53:25 +000011379 New = new AllocaInst(NewTy, 0, AI.getAlignment(), AI.getName());
Chris Lattner0006bd72002-11-09 00:49:43 +000011380 }
Chris Lattner7c881df2004-03-19 06:08:10 +000011381
11382 InsertNewInstBefore(New, AI);
Misha Brukmanfd939082005-04-21 23:48:37 +000011383
Chris Lattner0864acf2002-11-04 16:18:53 +000011384 // Scan to the end of the allocation instructions, to skip over a block of
Dale Johannesena8915182009-03-11 22:19:43 +000011385 // allocas if possible...also skip interleaved debug info
Chris Lattner0864acf2002-11-04 16:18:53 +000011386 //
11387 BasicBlock::iterator It = New;
Dale Johannesena8915182009-03-11 22:19:43 +000011388 while (isa<AllocationInst>(*It) || isa<DbgInfoIntrinsic>(*It)) ++It;
Chris Lattner0864acf2002-11-04 16:18:53 +000011389
11390 // Now that I is pointing to the first non-allocation-inst in the block,
11391 // insert our getelementptr instruction...
11392 //
Owen Andersona7235ea2009-07-31 20:28:14 +000011393 Value *NullIdx = Constant::getNullValue(Type::Int32Ty);
David Greeneb8f74792007-09-04 15:46:09 +000011394 Value *Idx[2];
11395 Idx[0] = NullIdx;
11396 Idx[1] = NullIdx;
Gabor Greif051a9502008-04-06 20:25:17 +000011397 Value *V = GetElementPtrInst::Create(New, Idx, Idx + 2,
11398 New->getName()+".sub", It);
Dan Gohmand6aa02d2009-07-28 01:40:03 +000011399 cast<GEPOperator>(V)->setIsInBounds(true);
Chris Lattner0864acf2002-11-04 16:18:53 +000011400
11401 // Now make everything use the getelementptr instead of the original
11402 // allocation.
Chris Lattner7c881df2004-03-19 06:08:10 +000011403 return ReplaceInstUsesWith(AI, V);
Chris Lattnere87597f2004-10-16 18:11:37 +000011404 } else if (isa<UndefValue>(AI.getArraySize())) {
Owen Andersona7235ea2009-07-31 20:28:14 +000011405 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
Chris Lattner0864acf2002-11-04 16:18:53 +000011406 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000011407 }
Chris Lattner7c881df2004-03-19 06:08:10 +000011408
Dan Gohmance9fe9f2009-07-21 23:21:54 +000011409 if (TD && isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized()) {
Dan Gohman6893cd72009-01-13 20:18:38 +000011410 // If alloca'ing a zero byte object, replace the alloca with a null pointer.
Chris Lattner46d232d2009-03-17 17:55:15 +000011411 // Note that we only do this for alloca's, because malloc should allocate
11412 // and return a unique pointer, even for a zero byte allocation.
Duncan Sands777d2302009-05-09 07:06:46 +000011413 if (TD->getTypeAllocSize(AI.getAllocatedType()) == 0)
Owen Andersona7235ea2009-07-31 20:28:14 +000011414 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
Dan Gohman6893cd72009-01-13 20:18:38 +000011415
11416 // If the alignment is 0 (unspecified), assign it the preferred alignment.
11417 if (AI.getAlignment() == 0)
11418 AI.setAlignment(TD->getPrefTypeAlignment(AI.getAllocatedType()));
11419 }
Chris Lattner7c881df2004-03-19 06:08:10 +000011420
Chris Lattner0864acf2002-11-04 16:18:53 +000011421 return 0;
11422}
11423
Chris Lattner67b1e1b2003-12-07 01:24:23 +000011424Instruction *InstCombiner::visitFreeInst(FreeInst &FI) {
11425 Value *Op = FI.getOperand(0);
11426
Chris Lattner17be6352004-10-18 02:59:09 +000011427 // free undef -> unreachable.
11428 if (isa<UndefValue>(Op)) {
11429 // Insert a new store to null because we cannot modify the CFG here.
Owen Anderson5defacc2009-07-31 17:39:07 +000011430 new StoreInst(ConstantInt::getTrue(*Context),
Owen Anderson9e9a0d52009-07-30 23:03:37 +000011431 UndefValue::get(PointerType::getUnqual(Type::Int1Ty)), &FI);
Chris Lattner17be6352004-10-18 02:59:09 +000011432 return EraseInstFromFunction(FI);
11433 }
Chris Lattner6fe55412007-04-14 00:20:02 +000011434
Chris Lattner6160e852004-02-28 04:57:37 +000011435 // If we have 'free null' delete the instruction. This can happen in stl code
11436 // when lots of inlining happens.
Chris Lattner17be6352004-10-18 02:59:09 +000011437 if (isa<ConstantPointerNull>(Op))
Chris Lattner7bcc0e72004-02-28 05:22:00 +000011438 return EraseInstFromFunction(FI);
Chris Lattner6fe55412007-04-14 00:20:02 +000011439
11440 // Change free <ty>* (cast <ty2>* X to <ty>*) into free <ty2>* X
11441 if (BitCastInst *CI = dyn_cast<BitCastInst>(Op)) {
11442 FI.setOperand(0, CI->getOperand(0));
11443 return &FI;
11444 }
11445
11446 // Change free (gep X, 0,0,0,0) into free(X)
11447 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
11448 if (GEPI->hasAllZeroIndices()) {
11449 AddToWorkList(GEPI);
11450 FI.setOperand(0, GEPI->getOperand(0));
11451 return &FI;
11452 }
11453 }
11454
11455 // Change free(malloc) into nothing, if the malloc has a single use.
11456 if (MallocInst *MI = dyn_cast<MallocInst>(Op))
11457 if (MI->hasOneUse()) {
11458 EraseInstFromFunction(FI);
11459 return EraseInstFromFunction(*MI);
11460 }
Chris Lattner6160e852004-02-28 04:57:37 +000011461
Chris Lattner67b1e1b2003-12-07 01:24:23 +000011462 return 0;
11463}
11464
11465
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011466/// InstCombineLoadCast - Fold 'load (cast P)' -> cast (load P)' when possible.
Devang Patel99db6ad2007-10-18 19:52:32 +000011467static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI,
Bill Wendling587c01d2008-02-26 10:53:30 +000011468 const TargetData *TD) {
Chris Lattnerb89e0712004-07-13 01:49:43 +000011469 User *CI = cast<User>(LI.getOperand(0));
Chris Lattnerf9527852005-01-31 04:50:46 +000011470 Value *CastOp = CI->getOperand(0);
Owen Anderson07cf79e2009-07-06 23:00:19 +000011471 LLVMContext *Context = IC.getContext();
Chris Lattnerb89e0712004-07-13 01:49:43 +000011472
Nick Lewycky48f95ad2009-05-08 06:47:37 +000011473 if (TD) {
11474 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(CI)) {
11475 // Instead of loading constant c string, use corresponding integer value
11476 // directly if string length is small enough.
11477 std::string Str;
11478 if (GetConstantStringInfo(CE->getOperand(0), Str) && !Str.empty()) {
11479 unsigned len = Str.length();
11480 const Type *Ty = cast<PointerType>(CE->getType())->getElementType();
11481 unsigned numBits = Ty->getPrimitiveSizeInBits();
11482 // Replace LI with immediate integer store.
11483 if ((numBits >> 3) == len + 1) {
11484 APInt StrVal(numBits, 0);
11485 APInt SingleChar(numBits, 0);
11486 if (TD->isLittleEndian()) {
11487 for (signed i = len-1; i >= 0; i--) {
11488 SingleChar = (uint64_t) Str[i] & UCHAR_MAX;
11489 StrVal = (StrVal << 8) | SingleChar;
11490 }
11491 } else {
11492 for (unsigned i = 0; i < len; i++) {
11493 SingleChar = (uint64_t) Str[i] & UCHAR_MAX;
11494 StrVal = (StrVal << 8) | SingleChar;
11495 }
11496 // Append NULL at the end.
11497 SingleChar = 0;
Bill Wendling587c01d2008-02-26 10:53:30 +000011498 StrVal = (StrVal << 8) | SingleChar;
11499 }
Owen Andersoneed707b2009-07-24 23:12:02 +000011500 Value *NL = ConstantInt::get(*Context, StrVal);
Nick Lewycky48f95ad2009-05-08 06:47:37 +000011501 return IC.ReplaceInstUsesWith(LI, NL);
Bill Wendling587c01d2008-02-26 10:53:30 +000011502 }
Devang Patel99db6ad2007-10-18 19:52:32 +000011503 }
11504 }
11505 }
11506
Mon P Wang6753f952009-02-07 22:19:29 +000011507 const PointerType *DestTy = cast<PointerType>(CI->getType());
11508 const Type *DestPTy = DestTy->getElementType();
Chris Lattnerf9527852005-01-31 04:50:46 +000011509 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
Mon P Wang6753f952009-02-07 22:19:29 +000011510
11511 // If the address spaces don't match, don't eliminate the cast.
11512 if (DestTy->getAddressSpace() != SrcTy->getAddressSpace())
11513 return 0;
11514
Chris Lattnerb89e0712004-07-13 01:49:43 +000011515 const Type *SrcPTy = SrcTy->getElementType();
Chris Lattnerf9527852005-01-31 04:50:46 +000011516
Reid Spencer42230162007-01-22 05:51:25 +000011517 if (DestPTy->isInteger() || isa<PointerType>(DestPTy) ||
Reid Spencer9d6565a2007-02-15 02:26:10 +000011518 isa<VectorType>(DestPTy)) {
Chris Lattnerf9527852005-01-31 04:50:46 +000011519 // If the source is an array, the code below will not succeed. Check to
11520 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
11521 // constants.
11522 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
11523 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
11524 if (ASrcTy->getNumElements() != 0) {
Chris Lattner55eb1c42007-01-31 04:40:53 +000011525 Value *Idxs[2];
Owen Andersona7235ea2009-07-31 20:28:14 +000011526 Idxs[0] = Idxs[1] = Constant::getNullValue(Type::Int32Ty);
Owen Andersonbaf3c402009-07-29 18:55:55 +000011527 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs, 2);
Chris Lattnerf9527852005-01-31 04:50:46 +000011528 SrcTy = cast<PointerType>(CastOp->getType());
11529 SrcPTy = SrcTy->getElementType();
11530 }
11531
Dan Gohmance9fe9f2009-07-21 23:21:54 +000011532 if (IC.getTargetData() &&
11533 (SrcPTy->isInteger() || isa<PointerType>(SrcPTy) ||
Reid Spencer9d6565a2007-02-15 02:26:10 +000011534 isa<VectorType>(SrcPTy)) &&
Chris Lattnerb1515fe2005-03-29 06:37:47 +000011535 // Do not allow turning this into a load of an integer, which is then
11536 // casted to a pointer, this pessimizes pointer analysis a lot.
11537 (isa<PointerType>(SrcPTy) == isa<PointerType>(LI.getType())) &&
Dan Gohmance9fe9f2009-07-21 23:21:54 +000011538 IC.getTargetData()->getTypeSizeInBits(SrcPTy) ==
11539 IC.getTargetData()->getTypeSizeInBits(DestPTy)) {
Misha Brukmanfd939082005-04-21 23:48:37 +000011540
Chris Lattnerf9527852005-01-31 04:50:46 +000011541 // Okay, we are casting from one integer or pointer type to another of
11542 // the same size. Instead of casting the pointer before the load, cast
11543 // the result of the loaded value.
11544 Value *NewLoad = IC.InsertNewInstBefore(new LoadInst(CastOp,
11545 CI->getName(),
11546 LI.isVolatile()),LI);
11547 // Now cast the result of the load.
Reid Spencerd977d862006-12-12 23:36:14 +000011548 return new BitCastInst(NewLoad, LI.getType());
Chris Lattnerf9527852005-01-31 04:50:46 +000011549 }
Chris Lattnerb89e0712004-07-13 01:49:43 +000011550 }
11551 }
11552 return 0;
11553}
11554
Chris Lattner833b8a42003-06-26 05:06:25 +000011555Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
11556 Value *Op = LI.getOperand(0);
Chris Lattner5f16a132004-01-12 04:13:56 +000011557
Dan Gohman9941f742007-07-20 16:34:21 +000011558 // Attempt to improve the alignment.
Dan Gohmance9fe9f2009-07-21 23:21:54 +000011559 if (TD) {
11560 unsigned KnownAlign =
11561 GetOrEnforceKnownAlignment(Op, TD->getPrefTypeAlignment(LI.getType()));
11562 if (KnownAlign >
11563 (LI.getAlignment() == 0 ? TD->getABITypeAlignment(LI.getType()) :
11564 LI.getAlignment()))
11565 LI.setAlignment(KnownAlign);
11566 }
Dan Gohman9941f742007-07-20 16:34:21 +000011567
Chris Lattner37366c12005-05-01 04:24:53 +000011568 // load (cast X) --> cast (load X) iff safe
Reid Spencer3ed469c2006-11-02 20:25:50 +000011569 if (isa<CastInst>(Op))
Devang Patel99db6ad2007-10-18 19:52:32 +000011570 if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
Chris Lattner37366c12005-05-01 04:24:53 +000011571 return Res;
11572
11573 // None of the following transforms are legal for volatile loads.
11574 if (LI.isVolatile()) return 0;
Chris Lattner62f254d2005-09-12 22:00:15 +000011575
Dan Gohman2276a7b2008-10-15 23:19:35 +000011576 // Do really simple store-to-load forwarding and load CSE, to catch cases
11577 // where there are several consequtive memory accesses to the same location,
11578 // separated by a few arithmetic operations.
11579 BasicBlock::iterator BBI = &LI;
Chris Lattner4aebaee2008-11-27 08:56:30 +000011580 if (Value *AvailableVal = FindAvailableLoadedValue(Op, LI.getParent(), BBI,6))
11581 return ReplaceInstUsesWith(LI, AvailableVal);
Chris Lattner37366c12005-05-01 04:24:53 +000011582
Christopher Lambb15147e2007-12-29 07:56:53 +000011583 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
11584 const Value *GEPI0 = GEPI->getOperand(0);
11585 // TODO: Consider a target hook for valid address spaces for this xform.
11586 if (isa<ConstantPointerNull>(GEPI0) &&
11587 cast<PointerType>(GEPI0->getType())->getAddressSpace() == 0) {
Chris Lattner37366c12005-05-01 04:24:53 +000011588 // Insert a new store to null instruction before the load to indicate
11589 // that this code is not reachable. We do this instead of inserting
11590 // an unreachable instruction directly because we cannot modify the
11591 // CFG.
Owen Anderson9e9a0d52009-07-30 23:03:37 +000011592 new StoreInst(UndefValue::get(LI.getType()),
Owen Andersona7235ea2009-07-31 20:28:14 +000011593 Constant::getNullValue(Op->getType()), &LI);
Owen Anderson9e9a0d52009-07-30 23:03:37 +000011594 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
Chris Lattner37366c12005-05-01 04:24:53 +000011595 }
Christopher Lambb15147e2007-12-29 07:56:53 +000011596 }
Chris Lattner37366c12005-05-01 04:24:53 +000011597
Chris Lattnere87597f2004-10-16 18:11:37 +000011598 if (Constant *C = dyn_cast<Constant>(Op)) {
Chris Lattner37366c12005-05-01 04:24:53 +000011599 // load null/undef -> undef
Christopher Lambb15147e2007-12-29 07:56:53 +000011600 // TODO: Consider a target hook for valid address spaces for this xform.
11601 if (isa<UndefValue>(C) || (C->isNullValue() &&
11602 cast<PointerType>(Op->getType())->getAddressSpace() == 0)) {
Chris Lattner17be6352004-10-18 02:59:09 +000011603 // Insert a new store to null instruction before the load to indicate that
11604 // this code is not reachable. We do this instead of inserting an
11605 // unreachable instruction directly because we cannot modify the CFG.
Owen Anderson9e9a0d52009-07-30 23:03:37 +000011606 new StoreInst(UndefValue::get(LI.getType()),
Owen Andersona7235ea2009-07-31 20:28:14 +000011607 Constant::getNullValue(Op->getType()), &LI);
Owen Anderson9e9a0d52009-07-30 23:03:37 +000011608 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
Chris Lattner17be6352004-10-18 02:59:09 +000011609 }
Chris Lattner833b8a42003-06-26 05:06:25 +000011610
Chris Lattnere87597f2004-10-16 18:11:37 +000011611 // Instcombine load (constant global) into the value loaded.
11612 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op))
Duncan Sands64da9402009-03-21 21:27:31 +000011613 if (GV->isConstant() && GV->hasDefinitiveInitializer())
Chris Lattnere87597f2004-10-16 18:11:37 +000011614 return ReplaceInstUsesWith(LI, GV->getInitializer());
Misha Brukmanfd939082005-04-21 23:48:37 +000011615
Chris Lattnere87597f2004-10-16 18:11:37 +000011616 // Instcombine load (constantexpr_GEP global, 0, ...) into the value loaded.
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000011617 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op)) {
Chris Lattnere87597f2004-10-16 18:11:37 +000011618 if (CE->getOpcode() == Instruction::GetElementPtr) {
11619 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
Duncan Sands64da9402009-03-21 21:27:31 +000011620 if (GV->isConstant() && GV->hasDefinitiveInitializer())
Chris Lattner363f2a22005-09-26 05:28:06 +000011621 if (Constant *V =
Owen Anderson50895512009-07-06 18:42:36 +000011622 ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE,
Owen Andersone922c022009-07-22 00:24:57 +000011623 *Context))
Chris Lattnere87597f2004-10-16 18:11:37 +000011624 return ReplaceInstUsesWith(LI, V);
Chris Lattner37366c12005-05-01 04:24:53 +000011625 if (CE->getOperand(0)->isNullValue()) {
11626 // Insert a new store to null instruction before the load to indicate
11627 // that this code is not reachable. We do this instead of inserting
11628 // an unreachable instruction directly because we cannot modify the
11629 // CFG.
Owen Anderson9e9a0d52009-07-30 23:03:37 +000011630 new StoreInst(UndefValue::get(LI.getType()),
Owen Andersona7235ea2009-07-31 20:28:14 +000011631 Constant::getNullValue(Op->getType()), &LI);
Owen Anderson9e9a0d52009-07-30 23:03:37 +000011632 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
Chris Lattner37366c12005-05-01 04:24:53 +000011633 }
11634
Reid Spencer3da59db2006-11-27 01:05:10 +000011635 } else if (CE->isCast()) {
Devang Patel99db6ad2007-10-18 19:52:32 +000011636 if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
Chris Lattnere87597f2004-10-16 18:11:37 +000011637 return Res;
11638 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000011639 }
Chris Lattnere87597f2004-10-16 18:11:37 +000011640 }
Chris Lattner8d2e8882007-08-11 18:48:48 +000011641
11642 // If this load comes from anywhere in a constant global, and if the global
11643 // is all undef or zero, we know what it loads.
Duncan Sands5d0392c2008-10-01 15:25:41 +000011644 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op->getUnderlyingObject())){
Duncan Sands64da9402009-03-21 21:27:31 +000011645 if (GV->isConstant() && GV->hasDefinitiveInitializer()) {
Chris Lattner8d2e8882007-08-11 18:48:48 +000011646 if (GV->getInitializer()->isNullValue())
Owen Andersona7235ea2009-07-31 20:28:14 +000011647 return ReplaceInstUsesWith(LI, Constant::getNullValue(LI.getType()));
Chris Lattner8d2e8882007-08-11 18:48:48 +000011648 else if (isa<UndefValue>(GV->getInitializer()))
Owen Anderson9e9a0d52009-07-30 23:03:37 +000011649 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
Chris Lattner8d2e8882007-08-11 18:48:48 +000011650 }
11651 }
Chris Lattnerf499eac2004-04-08 20:39:49 +000011652
Chris Lattner37366c12005-05-01 04:24:53 +000011653 if (Op->hasOneUse()) {
Chris Lattnerc10aced2004-09-19 18:43:46 +000011654 // Change select and PHI nodes to select values instead of addresses: this
11655 // helps alias analysis out a lot, allows many others simplifications, and
11656 // exposes redundancy in the code.
11657 //
11658 // Note that we cannot do the transformation unless we know that the
11659 // introduced loads cannot trap! Something like this is valid as long as
11660 // the condition is always false: load (select bool %C, int* null, int* %G),
11661 // but it would not be valid if we transformed it to load from null
11662 // unconditionally.
11663 //
11664 if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
11665 // load (select (Cond, &V1, &V2)) --> select(Cond, load &V1, load &V2).
Chris Lattner8a375202004-09-19 19:18:10 +000011666 if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
11667 isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
Chris Lattnerc10aced2004-09-19 18:43:46 +000011668 Value *V1 = InsertNewInstBefore(new LoadInst(SI->getOperand(1),
Chris Lattner79f0c8e2004-09-20 10:15:10 +000011669 SI->getOperand(1)->getName()+".val"), LI);
Chris Lattnerc10aced2004-09-19 18:43:46 +000011670 Value *V2 = InsertNewInstBefore(new LoadInst(SI->getOperand(2),
Chris Lattner79f0c8e2004-09-20 10:15:10 +000011671 SI->getOperand(2)->getName()+".val"), LI);
Gabor Greif051a9502008-04-06 20:25:17 +000011672 return SelectInst::Create(SI->getCondition(), V1, V2);
Chris Lattnerc10aced2004-09-19 18:43:46 +000011673 }
11674
Chris Lattner684fe212004-09-23 15:46:00 +000011675 // load (select (cond, null, P)) -> load P
11676 if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
11677 if (C->isNullValue()) {
11678 LI.setOperand(0, SI->getOperand(2));
11679 return &LI;
11680 }
11681
11682 // load (select (cond, P, null)) -> load P
11683 if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
11684 if (C->isNullValue()) {
11685 LI.setOperand(0, SI->getOperand(1));
11686 return &LI;
11687 }
Chris Lattnerc10aced2004-09-19 18:43:46 +000011688 }
11689 }
Chris Lattner833b8a42003-06-26 05:06:25 +000011690 return 0;
11691}
11692
Reid Spencer55af2b52007-01-19 21:20:31 +000011693/// InstCombineStoreToCast - Fold store V, (cast P) -> store (cast V), P
Chris Lattner3914f722009-01-24 01:00:13 +000011694/// when possible. This makes it generally easy to do alias analysis and/or
11695/// SROA/mem2reg of the memory object.
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011696static Instruction *InstCombineStoreToCast(InstCombiner &IC, StoreInst &SI) {
11697 User *CI = cast<User>(SI.getOperand(1));
11698 Value *CastOp = CI->getOperand(0);
11699
11700 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
Chris Lattner1b8eaf52009-01-16 20:08:59 +000011701 const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType());
11702 if (SrcTy == 0) return 0;
11703
11704 const Type *SrcPTy = SrcTy->getElementType();
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011705
Chris Lattner1b8eaf52009-01-16 20:08:59 +000011706 if (!DestPTy->isInteger() && !isa<PointerType>(DestPTy))
11707 return 0;
11708
Chris Lattner3914f722009-01-24 01:00:13 +000011709 /// NewGEPIndices - If SrcPTy is an aggregate type, we can emit a "noop gep"
11710 /// to its first element. This allows us to handle things like:
11711 /// store i32 xxx, (bitcast {foo*, float}* %P to i32*)
11712 /// on 32-bit hosts.
11713 SmallVector<Value*, 4> NewGEPIndices;
11714
Chris Lattner1b8eaf52009-01-16 20:08:59 +000011715 // If the source is an array, the code below will not succeed. Check to
11716 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
11717 // constants.
Chris Lattner3914f722009-01-24 01:00:13 +000011718 if (isa<ArrayType>(SrcPTy) || isa<StructType>(SrcPTy)) {
11719 // Index through pointer.
Owen Andersona7235ea2009-07-31 20:28:14 +000011720 Constant *Zero = Constant::getNullValue(Type::Int32Ty);
Chris Lattner3914f722009-01-24 01:00:13 +000011721 NewGEPIndices.push_back(Zero);
11722
11723 while (1) {
11724 if (const StructType *STy = dyn_cast<StructType>(SrcPTy)) {
Torok Edwin08ffee52009-01-24 17:16:04 +000011725 if (!STy->getNumElements()) /* Struct can be empty {} */
Torok Edwin629e92b2009-01-24 11:30:49 +000011726 break;
Chris Lattner3914f722009-01-24 01:00:13 +000011727 NewGEPIndices.push_back(Zero);
11728 SrcPTy = STy->getElementType(0);
11729 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcPTy)) {
11730 NewGEPIndices.push_back(Zero);
11731 SrcPTy = ATy->getElementType();
11732 } else {
11733 break;
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011734 }
Chris Lattner3914f722009-01-24 01:00:13 +000011735 }
11736
Owen Andersondebcb012009-07-29 22:17:13 +000011737 SrcTy = PointerType::get(SrcPTy, SrcTy->getAddressSpace());
Chris Lattner3914f722009-01-24 01:00:13 +000011738 }
Chris Lattner1b8eaf52009-01-16 20:08:59 +000011739
11740 if (!SrcPTy->isInteger() && !isa<PointerType>(SrcPTy))
11741 return 0;
11742
Chris Lattner71759c42009-01-16 20:12:52 +000011743 // If the pointers point into different address spaces or if they point to
11744 // values with different sizes, we can't do the transformation.
Dan Gohmance9fe9f2009-07-21 23:21:54 +000011745 if (!IC.getTargetData() ||
11746 SrcTy->getAddressSpace() !=
Chris Lattner71759c42009-01-16 20:12:52 +000011747 cast<PointerType>(CI->getType())->getAddressSpace() ||
Dan Gohmance9fe9f2009-07-21 23:21:54 +000011748 IC.getTargetData()->getTypeSizeInBits(SrcPTy) !=
11749 IC.getTargetData()->getTypeSizeInBits(DestPTy))
Chris Lattner1b8eaf52009-01-16 20:08:59 +000011750 return 0;
11751
11752 // Okay, we are casting from one integer or pointer type to another of
11753 // the same size. Instead of casting the pointer before
11754 // the store, cast the value to be stored.
11755 Value *NewCast;
11756 Value *SIOp0 = SI.getOperand(0);
11757 Instruction::CastOps opcode = Instruction::BitCast;
11758 const Type* CastSrcTy = SIOp0->getType();
11759 const Type* CastDstTy = SrcPTy;
11760 if (isa<PointerType>(CastDstTy)) {
11761 if (CastSrcTy->isInteger())
11762 opcode = Instruction::IntToPtr;
11763 } else if (isa<IntegerType>(CastDstTy)) {
11764 if (isa<PointerType>(SIOp0->getType()))
11765 opcode = Instruction::PtrToInt;
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011766 }
Chris Lattner3914f722009-01-24 01:00:13 +000011767
11768 // SIOp0 is a pointer to aggregate and this is a store to the first field,
11769 // emit a GEP to index into its first field.
11770 if (!NewGEPIndices.empty()) {
11771 if (Constant *C = dyn_cast<Constant>(CastOp))
Owen Andersonbaf3c402009-07-29 18:55:55 +000011772 CastOp = ConstantExpr::getGetElementPtr(C, &NewGEPIndices[0],
Chris Lattner3914f722009-01-24 01:00:13 +000011773 NewGEPIndices.size());
11774 else
11775 CastOp = IC.InsertNewInstBefore(
11776 GetElementPtrInst::Create(CastOp, NewGEPIndices.begin(),
11777 NewGEPIndices.end()), SI);
Dan Gohmand6aa02d2009-07-28 01:40:03 +000011778 cast<GEPOperator>(CastOp)->setIsInBounds(true);
Chris Lattner3914f722009-01-24 01:00:13 +000011779 }
11780
Chris Lattner1b8eaf52009-01-16 20:08:59 +000011781 if (Constant *C = dyn_cast<Constant>(SIOp0))
Owen Andersonbaf3c402009-07-29 18:55:55 +000011782 NewCast = ConstantExpr::getCast(opcode, C, CastDstTy);
Chris Lattner1b8eaf52009-01-16 20:08:59 +000011783 else
11784 NewCast = IC.InsertNewInstBefore(
11785 CastInst::Create(opcode, SIOp0, CastDstTy, SIOp0->getName()+".c"),
11786 SI);
11787 return new StoreInst(NewCast, CastOp);
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011788}
11789
Chris Lattner4aebaee2008-11-27 08:56:30 +000011790/// equivalentAddressValues - Test if A and B will obviously have the same
11791/// value. This includes recognizing that %t0 and %t1 will have the same
11792/// value in code like this:
Dan Gohman0f8b53f2009-03-03 02:55:14 +000011793/// %t0 = getelementptr \@a, 0, 3
Chris Lattner4aebaee2008-11-27 08:56:30 +000011794/// store i32 0, i32* %t0
Dan Gohman0f8b53f2009-03-03 02:55:14 +000011795/// %t1 = getelementptr \@a, 0, 3
Chris Lattner4aebaee2008-11-27 08:56:30 +000011796/// %t2 = load i32* %t1
11797///
11798static bool equivalentAddressValues(Value *A, Value *B) {
11799 // Test if the values are trivially equivalent.
11800 if (A == B) return true;
11801
11802 // Test if the values come form identical arithmetic instructions.
11803 if (isa<BinaryOperator>(A) ||
11804 isa<CastInst>(A) ||
11805 isa<PHINode>(A) ||
11806 isa<GetElementPtrInst>(A))
11807 if (Instruction *BI = dyn_cast<Instruction>(B))
11808 if (cast<Instruction>(A)->isIdenticalTo(BI))
11809 return true;
11810
11811 // Otherwise they may not be equivalent.
11812 return false;
11813}
11814
Dale Johannesen4945c652009-03-03 21:26:39 +000011815// If this instruction has two uses, one of which is a llvm.dbg.declare,
11816// return the llvm.dbg.declare.
11817DbgDeclareInst *InstCombiner::hasOneUsePlusDeclare(Value *V) {
11818 if (!V->hasNUses(2))
11819 return 0;
11820 for (Value::use_iterator UI = V->use_begin(), E = V->use_end();
11821 UI != E; ++UI) {
11822 if (DbgDeclareInst *DI = dyn_cast<DbgDeclareInst>(UI))
11823 return DI;
11824 if (isa<BitCastInst>(UI) && UI->hasOneUse()) {
11825 if (DbgDeclareInst *DI = dyn_cast<DbgDeclareInst>(UI->use_begin()))
11826 return DI;
11827 }
11828 }
11829 return 0;
11830}
11831
Chris Lattner2f503e62005-01-31 05:36:43 +000011832Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
11833 Value *Val = SI.getOperand(0);
11834 Value *Ptr = SI.getOperand(1);
11835
11836 if (isa<UndefValue>(Ptr)) { // store X, undef -> noop (even if volatile)
Chris Lattner9ca96412006-02-08 03:25:32 +000011837 EraseInstFromFunction(SI);
Chris Lattner2f503e62005-01-31 05:36:43 +000011838 ++NumCombined;
11839 return 0;
11840 }
Chris Lattner836692d2007-01-15 06:51:56 +000011841
11842 // If the RHS is an alloca with a single use, zapify the store, making the
11843 // alloca dead.
Dale Johannesen4945c652009-03-03 21:26:39 +000011844 // If the RHS is an alloca with a two uses, the other one being a
11845 // llvm.dbg.declare, zapify the store and the declare, making the
11846 // alloca dead. We must do this to prevent declare's from affecting
11847 // codegen.
11848 if (!SI.isVolatile()) {
11849 if (Ptr->hasOneUse()) {
11850 if (isa<AllocaInst>(Ptr)) {
Chris Lattner836692d2007-01-15 06:51:56 +000011851 EraseInstFromFunction(SI);
11852 ++NumCombined;
11853 return 0;
11854 }
Dale Johannesen4945c652009-03-03 21:26:39 +000011855 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr)) {
11856 if (isa<AllocaInst>(GEP->getOperand(0))) {
11857 if (GEP->getOperand(0)->hasOneUse()) {
11858 EraseInstFromFunction(SI);
11859 ++NumCombined;
11860 return 0;
11861 }
11862 if (DbgDeclareInst *DI = hasOneUsePlusDeclare(GEP->getOperand(0))) {
11863 EraseInstFromFunction(*DI);
11864 EraseInstFromFunction(SI);
11865 ++NumCombined;
11866 return 0;
11867 }
11868 }
11869 }
11870 }
11871 if (DbgDeclareInst *DI = hasOneUsePlusDeclare(Ptr)) {
11872 EraseInstFromFunction(*DI);
11873 EraseInstFromFunction(SI);
11874 ++NumCombined;
11875 return 0;
11876 }
Chris Lattner836692d2007-01-15 06:51:56 +000011877 }
Chris Lattner2f503e62005-01-31 05:36:43 +000011878
Dan Gohman9941f742007-07-20 16:34:21 +000011879 // Attempt to improve the alignment.
Dan Gohmance9fe9f2009-07-21 23:21:54 +000011880 if (TD) {
11881 unsigned KnownAlign =
11882 GetOrEnforceKnownAlignment(Ptr, TD->getPrefTypeAlignment(Val->getType()));
11883 if (KnownAlign >
11884 (SI.getAlignment() == 0 ? TD->getABITypeAlignment(Val->getType()) :
11885 SI.getAlignment()))
11886 SI.setAlignment(KnownAlign);
11887 }
Dan Gohman9941f742007-07-20 16:34:21 +000011888
Dale Johannesenacb51a32009-03-03 01:43:03 +000011889 // Do really simple DSE, to catch cases where there are several consecutive
Chris Lattner9ca96412006-02-08 03:25:32 +000011890 // stores to the same location, separated by a few arithmetic operations. This
11891 // situation often occurs with bitfield accesses.
11892 BasicBlock::iterator BBI = &SI;
11893 for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts;
11894 --ScanInsts) {
Dale Johannesen0d6596b2009-03-04 01:20:34 +000011895 --BBI;
Dale Johannesencdb16aa2009-03-04 01:53:05 +000011896 // Don't count debug info directives, lest they affect codegen,
11897 // and we skip pointer-to-pointer bitcasts, which are NOPs.
11898 // It is necessary for correctness to skip those that feed into a
11899 // llvm.dbg.declare, as these are not present when debugging is off.
Dale Johannesen4ded40a2009-03-03 22:36:47 +000011900 if (isa<DbgInfoIntrinsic>(BBI) ||
Dale Johannesencdb16aa2009-03-04 01:53:05 +000011901 (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType()))) {
Dale Johannesenacb51a32009-03-03 01:43:03 +000011902 ScanInsts++;
Dale Johannesenacb51a32009-03-03 01:43:03 +000011903 continue;
11904 }
Chris Lattner9ca96412006-02-08 03:25:32 +000011905
11906 if (StoreInst *PrevSI = dyn_cast<StoreInst>(BBI)) {
11907 // Prev store isn't volatile, and stores to the same location?
Chris Lattner4aebaee2008-11-27 08:56:30 +000011908 if (!PrevSI->isVolatile() &&equivalentAddressValues(PrevSI->getOperand(1),
11909 SI.getOperand(1))) {
Chris Lattner9ca96412006-02-08 03:25:32 +000011910 ++NumDeadStore;
11911 ++BBI;
11912 EraseInstFromFunction(*PrevSI);
11913 continue;
11914 }
11915 break;
11916 }
11917
Chris Lattnerb4db97f2006-05-26 19:19:20 +000011918 // If this is a load, we have to stop. However, if the loaded value is from
11919 // the pointer we're loading and is producing the pointer we're storing,
11920 // then *this* store is dead (X = load P; store X -> P).
11921 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
Dan Gohman2276a7b2008-10-15 23:19:35 +000011922 if (LI == Val && equivalentAddressValues(LI->getOperand(0), Ptr) &&
11923 !SI.isVolatile()) {
Chris Lattnerb4db97f2006-05-26 19:19:20 +000011924 EraseInstFromFunction(SI);
11925 ++NumCombined;
11926 return 0;
11927 }
11928 // Otherwise, this is a load from some other location. Stores before it
11929 // may not be dead.
11930 break;
11931 }
11932
Chris Lattner9ca96412006-02-08 03:25:32 +000011933 // Don't skip over loads or things that can modify memory.
Chris Lattner0ef546e2008-05-08 17:20:30 +000011934 if (BBI->mayWriteToMemory() || BBI->mayReadFromMemory())
Chris Lattner9ca96412006-02-08 03:25:32 +000011935 break;
11936 }
11937
11938
11939 if (SI.isVolatile()) return 0; // Don't hack volatile stores.
Chris Lattner2f503e62005-01-31 05:36:43 +000011940
11941 // store X, null -> turns into 'unreachable' in SimplifyCFG
Chris Lattner3590abf2009-06-11 17:54:56 +000011942 if (isa<ConstantPointerNull>(Ptr) &&
11943 cast<PointerType>(Ptr->getType())->getAddressSpace() == 0) {
Chris Lattner2f503e62005-01-31 05:36:43 +000011944 if (!isa<UndefValue>(Val)) {
Owen Anderson9e9a0d52009-07-30 23:03:37 +000011945 SI.setOperand(0, UndefValue::get(Val->getType()));
Chris Lattner2f503e62005-01-31 05:36:43 +000011946 if (Instruction *U = dyn_cast<Instruction>(Val))
Chris Lattnerdbab3862007-03-02 21:28:56 +000011947 AddToWorkList(U); // Dropped a use.
Chris Lattner2f503e62005-01-31 05:36:43 +000011948 ++NumCombined;
11949 }
11950 return 0; // Do not modify these!
11951 }
11952
11953 // store undef, Ptr -> noop
11954 if (isa<UndefValue>(Val)) {
Chris Lattner9ca96412006-02-08 03:25:32 +000011955 EraseInstFromFunction(SI);
Chris Lattner2f503e62005-01-31 05:36:43 +000011956 ++NumCombined;
11957 return 0;
11958 }
11959
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011960 // If the pointer destination is a cast, see if we can fold the cast into the
11961 // source instead.
Reid Spencer3ed469c2006-11-02 20:25:50 +000011962 if (isa<CastInst>(Ptr))
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011963 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
11964 return Res;
11965 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
Reid Spencer3da59db2006-11-27 01:05:10 +000011966 if (CE->isCast())
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011967 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
11968 return Res;
11969
Chris Lattner408902b2005-09-12 23:23:25 +000011970
Dale Johannesen4084c4e2009-03-05 02:06:48 +000011971 // If this store is the last instruction in the basic block (possibly
11972 // excepting debug info instructions and the pointer bitcasts that feed
11973 // into them), and if the block ends with an unconditional branch, try
11974 // to move it to the successor block.
11975 BBI = &SI;
11976 do {
11977 ++BBI;
11978 } while (isa<DbgInfoIntrinsic>(BBI) ||
11979 (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType())));
Chris Lattner408902b2005-09-12 23:23:25 +000011980 if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
Chris Lattner3284d1f2007-04-15 00:07:55 +000011981 if (BI->isUnconditional())
11982 if (SimplifyStoreAtEndOfBlock(SI))
11983 return 0; // xform done!
Chris Lattner408902b2005-09-12 23:23:25 +000011984
Chris Lattner2f503e62005-01-31 05:36:43 +000011985 return 0;
11986}
11987
Chris Lattner3284d1f2007-04-15 00:07:55 +000011988/// SimplifyStoreAtEndOfBlock - Turn things like:
11989/// if () { *P = v1; } else { *P = v2 }
11990/// into a phi node with a store in the successor.
11991///
Chris Lattner31755a02007-04-15 01:02:18 +000011992/// Simplify things like:
11993/// *P = v1; if () { *P = v2; }
11994/// into a phi node with a store in the successor.
11995///
Chris Lattner3284d1f2007-04-15 00:07:55 +000011996bool InstCombiner::SimplifyStoreAtEndOfBlock(StoreInst &SI) {
11997 BasicBlock *StoreBB = SI.getParent();
11998
11999 // Check to see if the successor block has exactly two incoming edges. If
12000 // so, see if the other predecessor contains a store to the same location.
12001 // if so, insert a PHI node (if needed) and move the stores down.
Chris Lattner31755a02007-04-15 01:02:18 +000012002 BasicBlock *DestBB = StoreBB->getTerminator()->getSuccessor(0);
Chris Lattner3284d1f2007-04-15 00:07:55 +000012003
12004 // Determine whether Dest has exactly two predecessors and, if so, compute
12005 // the other predecessor.
Chris Lattner31755a02007-04-15 01:02:18 +000012006 pred_iterator PI = pred_begin(DestBB);
12007 BasicBlock *OtherBB = 0;
Chris Lattner3284d1f2007-04-15 00:07:55 +000012008 if (*PI != StoreBB)
Chris Lattner31755a02007-04-15 01:02:18 +000012009 OtherBB = *PI;
Chris Lattner3284d1f2007-04-15 00:07:55 +000012010 ++PI;
Chris Lattner31755a02007-04-15 01:02:18 +000012011 if (PI == pred_end(DestBB))
Chris Lattner3284d1f2007-04-15 00:07:55 +000012012 return false;
12013
12014 if (*PI != StoreBB) {
Chris Lattner31755a02007-04-15 01:02:18 +000012015 if (OtherBB)
Chris Lattner3284d1f2007-04-15 00:07:55 +000012016 return false;
Chris Lattner31755a02007-04-15 01:02:18 +000012017 OtherBB = *PI;
Chris Lattner3284d1f2007-04-15 00:07:55 +000012018 }
Chris Lattner31755a02007-04-15 01:02:18 +000012019 if (++PI != pred_end(DestBB))
Chris Lattner3284d1f2007-04-15 00:07:55 +000012020 return false;
Eli Friedman66fe80a2008-06-13 21:17:49 +000012021
12022 // Bail out if all the relevant blocks aren't distinct (this can happen,
12023 // for example, if SI is in an infinite loop)
12024 if (StoreBB == DestBB || OtherBB == DestBB)
12025 return false;
12026
Chris Lattner31755a02007-04-15 01:02:18 +000012027 // Verify that the other block ends in a branch and is not otherwise empty.
12028 BasicBlock::iterator BBI = OtherBB->getTerminator();
Chris Lattner3284d1f2007-04-15 00:07:55 +000012029 BranchInst *OtherBr = dyn_cast<BranchInst>(BBI);
Chris Lattner31755a02007-04-15 01:02:18 +000012030 if (!OtherBr || BBI == OtherBB->begin())
Chris Lattner3284d1f2007-04-15 00:07:55 +000012031 return false;
12032
Chris Lattner31755a02007-04-15 01:02:18 +000012033 // If the other block ends in an unconditional branch, check for the 'if then
12034 // else' case. there is an instruction before the branch.
12035 StoreInst *OtherStore = 0;
12036 if (OtherBr->isUnconditional()) {
Chris Lattner31755a02007-04-15 01:02:18 +000012037 --BBI;
Dale Johannesen4084c4e2009-03-05 02:06:48 +000012038 // Skip over debugging info.
12039 while (isa<DbgInfoIntrinsic>(BBI) ||
12040 (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType()))) {
12041 if (BBI==OtherBB->begin())
12042 return false;
12043 --BBI;
12044 }
12045 // If this isn't a store, or isn't a store to the same location, bail out.
Chris Lattner31755a02007-04-15 01:02:18 +000012046 OtherStore = dyn_cast<StoreInst>(BBI);
12047 if (!OtherStore || OtherStore->getOperand(1) != SI.getOperand(1))
12048 return false;
12049 } else {
Chris Lattnerd717c182007-05-05 22:32:24 +000012050 // Otherwise, the other block ended with a conditional branch. If one of the
Chris Lattner31755a02007-04-15 01:02:18 +000012051 // destinations is StoreBB, then we have the if/then case.
12052 if (OtherBr->getSuccessor(0) != StoreBB &&
12053 OtherBr->getSuccessor(1) != StoreBB)
12054 return false;
12055
12056 // Okay, we know that OtherBr now goes to Dest and StoreBB, so this is an
Chris Lattnerd717c182007-05-05 22:32:24 +000012057 // if/then triangle. See if there is a store to the same ptr as SI that
12058 // lives in OtherBB.
Chris Lattner31755a02007-04-15 01:02:18 +000012059 for (;; --BBI) {
12060 // Check to see if we find the matching store.
12061 if ((OtherStore = dyn_cast<StoreInst>(BBI))) {
12062 if (OtherStore->getOperand(1) != SI.getOperand(1))
12063 return false;
12064 break;
12065 }
Eli Friedman6903a242008-06-13 22:02:12 +000012066 // If we find something that may be using or overwriting the stored
12067 // value, or if we run out of instructions, we can't do the xform.
12068 if (BBI->mayReadFromMemory() || BBI->mayWriteToMemory() ||
Chris Lattner31755a02007-04-15 01:02:18 +000012069 BBI == OtherBB->begin())
12070 return false;
12071 }
12072
12073 // In order to eliminate the store in OtherBr, we have to
Eli Friedman6903a242008-06-13 22:02:12 +000012074 // make sure nothing reads or overwrites the stored value in
12075 // StoreBB.
Chris Lattner31755a02007-04-15 01:02:18 +000012076 for (BasicBlock::iterator I = StoreBB->begin(); &*I != &SI; ++I) {
12077 // FIXME: This should really be AA driven.
Eli Friedman6903a242008-06-13 22:02:12 +000012078 if (I->mayReadFromMemory() || I->mayWriteToMemory())
Chris Lattner31755a02007-04-15 01:02:18 +000012079 return false;
12080 }
12081 }
Chris Lattner3284d1f2007-04-15 00:07:55 +000012082
Chris Lattner31755a02007-04-15 01:02:18 +000012083 // Insert a PHI node now if we need it.
Chris Lattner3284d1f2007-04-15 00:07:55 +000012084 Value *MergedVal = OtherStore->getOperand(0);
12085 if (MergedVal != SI.getOperand(0)) {
Gabor Greif051a9502008-04-06 20:25:17 +000012086 PHINode *PN = PHINode::Create(MergedVal->getType(), "storemerge");
Chris Lattner3284d1f2007-04-15 00:07:55 +000012087 PN->reserveOperandSpace(2);
12088 PN->addIncoming(SI.getOperand(0), SI.getParent());
Chris Lattner31755a02007-04-15 01:02:18 +000012089 PN->addIncoming(OtherStore->getOperand(0), OtherBB);
12090 MergedVal = InsertNewInstBefore(PN, DestBB->front());
Chris Lattner3284d1f2007-04-15 00:07:55 +000012091 }
12092
12093 // Advance to a place where it is safe to insert the new store and
12094 // insert it.
Dan Gohman02dea8b2008-05-23 21:05:58 +000012095 BBI = DestBB->getFirstNonPHI();
Chris Lattner3284d1f2007-04-15 00:07:55 +000012096 InsertNewInstBefore(new StoreInst(MergedVal, SI.getOperand(1),
12097 OtherStore->isVolatile()), *BBI);
12098
12099 // Nuke the old stores.
12100 EraseInstFromFunction(SI);
12101 EraseInstFromFunction(*OtherStore);
12102 ++NumCombined;
12103 return true;
12104}
12105
Chris Lattner2f503e62005-01-31 05:36:43 +000012106
Chris Lattnerc4d10eb2003-06-04 04:46:00 +000012107Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
12108 // Change br (not X), label True, label False to: br X, label False, True
Reid Spencer4b828e62005-06-18 17:37:34 +000012109 Value *X = 0;
Chris Lattneracd1f0f2004-07-30 07:50:03 +000012110 BasicBlock *TrueDest;
12111 BasicBlock *FalseDest;
Owen Andersonc7d2ce72009-07-10 17:35:01 +000012112 if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest), *Context) &&
Chris Lattneracd1f0f2004-07-30 07:50:03 +000012113 !isa<Constant>(X)) {
12114 // Swap Destinations and condition...
12115 BI.setCondition(X);
12116 BI.setSuccessor(0, FalseDest);
12117 BI.setSuccessor(1, TrueDest);
12118 return &BI;
12119 }
12120
Reid Spencere4d87aa2006-12-23 06:05:41 +000012121 // Cannonicalize fcmp_one -> fcmp_oeq
12122 FCmpInst::Predicate FPred; Value *Y;
12123 if (match(&BI, m_Br(m_FCmp(FPred, m_Value(X), m_Value(Y)),
Owen Andersonc7d2ce72009-07-10 17:35:01 +000012124 TrueDest, FalseDest), *Context))
Reid Spencere4d87aa2006-12-23 06:05:41 +000012125 if ((FPred == FCmpInst::FCMP_ONE || FPred == FCmpInst::FCMP_OLE ||
12126 FPred == FCmpInst::FCMP_OGE) && BI.getCondition()->hasOneUse()) {
12127 FCmpInst *I = cast<FCmpInst>(BI.getCondition());
Reid Spencere4d87aa2006-12-23 06:05:41 +000012128 FCmpInst::Predicate NewPred = FCmpInst::getInversePredicate(FPred);
Owen Anderson333c4002009-07-09 23:48:35 +000012129 Instruction *NewSCC = new FCmpInst(I, NewPred, X, Y, "");
Chris Lattner6934a042007-02-11 01:23:03 +000012130 NewSCC->takeName(I);
Reid Spencere4d87aa2006-12-23 06:05:41 +000012131 // Swap Destinations and condition...
12132 BI.setCondition(NewSCC);
12133 BI.setSuccessor(0, FalseDest);
12134 BI.setSuccessor(1, TrueDest);
Chris Lattnerdbab3862007-03-02 21:28:56 +000012135 RemoveFromWorkList(I);
Chris Lattner6934a042007-02-11 01:23:03 +000012136 I->eraseFromParent();
Chris Lattnerdbab3862007-03-02 21:28:56 +000012137 AddToWorkList(NewSCC);
Reid Spencere4d87aa2006-12-23 06:05:41 +000012138 return &BI;
12139 }
12140
12141 // Cannonicalize icmp_ne -> icmp_eq
12142 ICmpInst::Predicate IPred;
12143 if (match(&BI, m_Br(m_ICmp(IPred, m_Value(X), m_Value(Y)),
Owen Andersonc7d2ce72009-07-10 17:35:01 +000012144 TrueDest, FalseDest), *Context))
Reid Spencere4d87aa2006-12-23 06:05:41 +000012145 if ((IPred == ICmpInst::ICMP_NE || IPred == ICmpInst::ICMP_ULE ||
12146 IPred == ICmpInst::ICMP_SLE || IPred == ICmpInst::ICMP_UGE ||
12147 IPred == ICmpInst::ICMP_SGE) && BI.getCondition()->hasOneUse()) {
12148 ICmpInst *I = cast<ICmpInst>(BI.getCondition());
Reid Spencere4d87aa2006-12-23 06:05:41 +000012149 ICmpInst::Predicate NewPred = ICmpInst::getInversePredicate(IPred);
Owen Anderson333c4002009-07-09 23:48:35 +000012150 Instruction *NewSCC = new ICmpInst(I, NewPred, X, Y, "");
Chris Lattner6934a042007-02-11 01:23:03 +000012151 NewSCC->takeName(I);
Chris Lattner40f5d702003-06-04 05:10:11 +000012152 // Swap Destinations and condition...
Chris Lattneracd1f0f2004-07-30 07:50:03 +000012153 BI.setCondition(NewSCC);
Chris Lattner40f5d702003-06-04 05:10:11 +000012154 BI.setSuccessor(0, FalseDest);
12155 BI.setSuccessor(1, TrueDest);
Chris Lattnerdbab3862007-03-02 21:28:56 +000012156 RemoveFromWorkList(I);
Chris Lattner6934a042007-02-11 01:23:03 +000012157 I->eraseFromParent();;
Chris Lattnerdbab3862007-03-02 21:28:56 +000012158 AddToWorkList(NewSCC);
Chris Lattner40f5d702003-06-04 05:10:11 +000012159 return &BI;
12160 }
Misha Brukmanfd939082005-04-21 23:48:37 +000012161
Chris Lattnerc4d10eb2003-06-04 04:46:00 +000012162 return 0;
12163}
Chris Lattner0864acf2002-11-04 16:18:53 +000012164
Chris Lattner46238a62004-07-03 00:26:11 +000012165Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
12166 Value *Cond = SI.getCondition();
12167 if (Instruction *I = dyn_cast<Instruction>(Cond)) {
12168 if (I->getOpcode() == Instruction::Add)
12169 if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
12170 // change 'switch (X+4) case 1:' into 'switch (X) case -3'
12171 for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
Owen Andersond672ecb2009-07-03 00:17:18 +000012172 SI.setOperand(i,
Owen Andersonbaf3c402009-07-29 18:55:55 +000012173 ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)),
Chris Lattner46238a62004-07-03 00:26:11 +000012174 AddRHS));
12175 SI.setOperand(0, I->getOperand(0));
Chris Lattnerdbab3862007-03-02 21:28:56 +000012176 AddToWorkList(I);
Chris Lattner46238a62004-07-03 00:26:11 +000012177 return &SI;
12178 }
12179 }
12180 return 0;
12181}
12182
Matthijs Kooijmana9012ec2008-06-11 14:05:05 +000012183Instruction *InstCombiner::visitExtractValueInst(ExtractValueInst &EV) {
Matthijs Kooijman780ae5e2008-07-16 12:55:45 +000012184 Value *Agg = EV.getAggregateOperand();
Matthijs Kooijmana9012ec2008-06-11 14:05:05 +000012185
Matthijs Kooijman780ae5e2008-07-16 12:55:45 +000012186 if (!EV.hasIndices())
12187 return ReplaceInstUsesWith(EV, Agg);
12188
12189 if (Constant *C = dyn_cast<Constant>(Agg)) {
12190 if (isa<UndefValue>(C))
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012191 return ReplaceInstUsesWith(EV, UndefValue::get(EV.getType()));
Matthijs Kooijman780ae5e2008-07-16 12:55:45 +000012192
12193 if (isa<ConstantAggregateZero>(C))
Owen Andersona7235ea2009-07-31 20:28:14 +000012194 return ReplaceInstUsesWith(EV, Constant::getNullValue(EV.getType()));
Matthijs Kooijman780ae5e2008-07-16 12:55:45 +000012195
12196 if (isa<ConstantArray>(C) || isa<ConstantStruct>(C)) {
12197 // Extract the element indexed by the first index out of the constant
12198 Value *V = C->getOperand(*EV.idx_begin());
12199 if (EV.getNumIndices() > 1)
12200 // Extract the remaining indices out of the constant indexed by the
12201 // first index
12202 return ExtractValueInst::Create(V, EV.idx_begin() + 1, EV.idx_end());
12203 else
12204 return ReplaceInstUsesWith(EV, V);
12205 }
12206 return 0; // Can't handle other constants
12207 }
12208 if (InsertValueInst *IV = dyn_cast<InsertValueInst>(Agg)) {
12209 // We're extracting from an insertvalue instruction, compare the indices
12210 const unsigned *exti, *exte, *insi, *inse;
12211 for (exti = EV.idx_begin(), insi = IV->idx_begin(),
12212 exte = EV.idx_end(), inse = IV->idx_end();
12213 exti != exte && insi != inse;
12214 ++exti, ++insi) {
12215 if (*insi != *exti)
12216 // The insert and extract both reference distinctly different elements.
12217 // This means the extract is not influenced by the insert, and we can
12218 // replace the aggregate operand of the extract with the aggregate
12219 // operand of the insert. i.e., replace
12220 // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
12221 // %E = extractvalue { i32, { i32 } } %I, 0
12222 // with
12223 // %E = extractvalue { i32, { i32 } } %A, 0
12224 return ExtractValueInst::Create(IV->getAggregateOperand(),
12225 EV.idx_begin(), EV.idx_end());
12226 }
12227 if (exti == exte && insi == inse)
12228 // Both iterators are at the end: Index lists are identical. Replace
12229 // %B = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
12230 // %C = extractvalue { i32, { i32 } } %B, 1, 0
12231 // with "i32 42"
12232 return ReplaceInstUsesWith(EV, IV->getInsertedValueOperand());
12233 if (exti == exte) {
12234 // The extract list is a prefix of the insert list. i.e. replace
12235 // %I = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
12236 // %E = extractvalue { i32, { i32 } } %I, 1
12237 // with
12238 // %X = extractvalue { i32, { i32 } } %A, 1
12239 // %E = insertvalue { i32 } %X, i32 42, 0
12240 // by switching the order of the insert and extract (though the
12241 // insertvalue should be left in, since it may have other uses).
12242 Value *NewEV = InsertNewInstBefore(
12243 ExtractValueInst::Create(IV->getAggregateOperand(),
12244 EV.idx_begin(), EV.idx_end()),
12245 EV);
12246 return InsertValueInst::Create(NewEV, IV->getInsertedValueOperand(),
12247 insi, inse);
12248 }
12249 if (insi == inse)
12250 // The insert list is a prefix of the extract list
12251 // We can simply remove the common indices from the extract and make it
12252 // operate on the inserted value instead of the insertvalue result.
12253 // i.e., replace
12254 // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
12255 // %E = extractvalue { i32, { i32 } } %I, 1, 0
12256 // with
12257 // %E extractvalue { i32 } { i32 42 }, 0
12258 return ExtractValueInst::Create(IV->getInsertedValueOperand(),
12259 exti, exte);
12260 }
12261 // Can't simplify extracts from other values. Note that nested extracts are
12262 // already simplified implicitely by the above (extract ( extract (insert) )
12263 // will be translated into extract ( insert ( extract ) ) first and then just
12264 // the value inserted, if appropriate).
Matthijs Kooijmana9012ec2008-06-11 14:05:05 +000012265 return 0;
12266}
12267
Chris Lattner220b0cf2006-03-05 00:22:33 +000012268/// CheapToScalarize - Return true if the value is cheaper to scalarize than it
12269/// is to leave as a vector operation.
12270static bool CheapToScalarize(Value *V, bool isConstant) {
12271 if (isa<ConstantAggregateZero>(V))
12272 return true;
Reid Spencer9d6565a2007-02-15 02:26:10 +000012273 if (ConstantVector *C = dyn_cast<ConstantVector>(V)) {
Chris Lattner220b0cf2006-03-05 00:22:33 +000012274 if (isConstant) return true;
12275 // If all elts are the same, we can extract.
12276 Constant *Op0 = C->getOperand(0);
12277 for (unsigned i = 1; i < C->getNumOperands(); ++i)
12278 if (C->getOperand(i) != Op0)
12279 return false;
12280 return true;
12281 }
12282 Instruction *I = dyn_cast<Instruction>(V);
12283 if (!I) return false;
12284
12285 // Insert element gets simplified to the inserted element or is deleted if
12286 // this is constant idx extract element and its a constant idx insertelt.
12287 if (I->getOpcode() == Instruction::InsertElement && isConstant &&
12288 isa<ConstantInt>(I->getOperand(2)))
12289 return true;
12290 if (I->getOpcode() == Instruction::Load && I->hasOneUse())
12291 return true;
12292 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I))
12293 if (BO->hasOneUse() &&
12294 (CheapToScalarize(BO->getOperand(0), isConstant) ||
12295 CheapToScalarize(BO->getOperand(1), isConstant)))
12296 return true;
Reid Spencere4d87aa2006-12-23 06:05:41 +000012297 if (CmpInst *CI = dyn_cast<CmpInst>(I))
12298 if (CI->hasOneUse() &&
12299 (CheapToScalarize(CI->getOperand(0), isConstant) ||
12300 CheapToScalarize(CI->getOperand(1), isConstant)))
12301 return true;
Chris Lattner220b0cf2006-03-05 00:22:33 +000012302
12303 return false;
12304}
12305
Chris Lattnerd2b7cec2007-02-14 05:52:17 +000012306/// Read and decode a shufflevector mask.
12307///
12308/// It turns undef elements into values that are larger than the number of
12309/// elements in the input.
Chris Lattner863bcff2006-05-25 23:48:38 +000012310static std::vector<unsigned> getShuffleMask(const ShuffleVectorInst *SVI) {
12311 unsigned NElts = SVI->getType()->getNumElements();
12312 if (isa<ConstantAggregateZero>(SVI->getOperand(2)))
12313 return std::vector<unsigned>(NElts, 0);
12314 if (isa<UndefValue>(SVI->getOperand(2)))
12315 return std::vector<unsigned>(NElts, 2*NElts);
12316
12317 std::vector<unsigned> Result;
Reid Spencer9d6565a2007-02-15 02:26:10 +000012318 const ConstantVector *CP = cast<ConstantVector>(SVI->getOperand(2));
Gabor Greif177dd3f2008-06-12 21:37:33 +000012319 for (User::const_op_iterator i = CP->op_begin(), e = CP->op_end(); i!=e; ++i)
12320 if (isa<UndefValue>(*i))
Chris Lattner863bcff2006-05-25 23:48:38 +000012321 Result.push_back(NElts*2); // undef -> 8
12322 else
Gabor Greif177dd3f2008-06-12 21:37:33 +000012323 Result.push_back(cast<ConstantInt>(*i)->getZExtValue());
Chris Lattner863bcff2006-05-25 23:48:38 +000012324 return Result;
12325}
12326
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012327/// FindScalarElement - Given a vector and an element number, see if the scalar
12328/// value is already around as a register, for example if it were inserted then
12329/// extracted from the vector.
Owen Andersond672ecb2009-07-03 00:17:18 +000012330static Value *FindScalarElement(Value *V, unsigned EltNo,
Owen Anderson07cf79e2009-07-06 23:00:19 +000012331 LLVMContext *Context) {
Reid Spencer9d6565a2007-02-15 02:26:10 +000012332 assert(isa<VectorType>(V->getType()) && "Not looking at a vector?");
12333 const VectorType *PTy = cast<VectorType>(V->getType());
Chris Lattner389a6f52006-04-10 23:06:36 +000012334 unsigned Width = PTy->getNumElements();
12335 if (EltNo >= Width) // Out of range access.
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012336 return UndefValue::get(PTy->getElementType());
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012337
12338 if (isa<UndefValue>(V))
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012339 return UndefValue::get(PTy->getElementType());
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012340 else if (isa<ConstantAggregateZero>(V))
Owen Andersona7235ea2009-07-31 20:28:14 +000012341 return Constant::getNullValue(PTy->getElementType());
Reid Spencer9d6565a2007-02-15 02:26:10 +000012342 else if (ConstantVector *CP = dyn_cast<ConstantVector>(V))
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012343 return CP->getOperand(EltNo);
12344 else if (InsertElementInst *III = dyn_cast<InsertElementInst>(V)) {
12345 // If this is an insert to a variable element, we don't know what it is.
Reid Spencerb83eb642006-10-20 07:07:24 +000012346 if (!isa<ConstantInt>(III->getOperand(2)))
12347 return 0;
12348 unsigned IIElt = cast<ConstantInt>(III->getOperand(2))->getZExtValue();
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012349
12350 // If this is an insert to the element we are looking for, return the
12351 // inserted value.
Reid Spencerb83eb642006-10-20 07:07:24 +000012352 if (EltNo == IIElt)
12353 return III->getOperand(1);
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012354
12355 // Otherwise, the insertelement doesn't modify the value, recurse on its
12356 // vector input.
Owen Andersond672ecb2009-07-03 00:17:18 +000012357 return FindScalarElement(III->getOperand(0), EltNo, Context);
Chris Lattner389a6f52006-04-10 23:06:36 +000012358 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(V)) {
Mon P Wangaeb06d22008-11-10 04:46:22 +000012359 unsigned LHSWidth =
12360 cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements();
Chris Lattner863bcff2006-05-25 23:48:38 +000012361 unsigned InEl = getShuffleMask(SVI)[EltNo];
Mon P Wangaeb06d22008-11-10 04:46:22 +000012362 if (InEl < LHSWidth)
Owen Andersond672ecb2009-07-03 00:17:18 +000012363 return FindScalarElement(SVI->getOperand(0), InEl, Context);
Mon P Wangaeb06d22008-11-10 04:46:22 +000012364 else if (InEl < LHSWidth*2)
Owen Andersond672ecb2009-07-03 00:17:18 +000012365 return FindScalarElement(SVI->getOperand(1), InEl - LHSWidth, Context);
Chris Lattner863bcff2006-05-25 23:48:38 +000012366 else
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012367 return UndefValue::get(PTy->getElementType());
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012368 }
12369
12370 // Otherwise, we don't know.
12371 return 0;
12372}
12373
Robert Bocchino1d7456d2006-01-13 22:48:06 +000012374Instruction *InstCombiner::visitExtractElementInst(ExtractElementInst &EI) {
Dan Gohman07a96762007-07-16 14:29:03 +000012375 // If vector val is undef, replace extract with scalar undef.
Chris Lattner1f13c882006-03-31 18:25:14 +000012376 if (isa<UndefValue>(EI.getOperand(0)))
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012377 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
Chris Lattner1f13c882006-03-31 18:25:14 +000012378
Dan Gohman07a96762007-07-16 14:29:03 +000012379 // If vector val is constant 0, replace extract with scalar 0.
Chris Lattner1f13c882006-03-31 18:25:14 +000012380 if (isa<ConstantAggregateZero>(EI.getOperand(0)))
Owen Andersona7235ea2009-07-31 20:28:14 +000012381 return ReplaceInstUsesWith(EI, Constant::getNullValue(EI.getType()));
Chris Lattner1f13c882006-03-31 18:25:14 +000012382
Reid Spencer9d6565a2007-02-15 02:26:10 +000012383 if (ConstantVector *C = dyn_cast<ConstantVector>(EI.getOperand(0))) {
Matthijs Kooijmanb4d6a5a2008-06-11 09:00:12 +000012384 // If vector val is constant with all elements the same, replace EI with
12385 // that element. When the elements are not identical, we cannot replace yet
12386 // (we do that below, but only when the index is constant).
Chris Lattner220b0cf2006-03-05 00:22:33 +000012387 Constant *op0 = C->getOperand(0);
Robert Bocchino1d7456d2006-01-13 22:48:06 +000012388 for (unsigned i = 1; i < C->getNumOperands(); ++i)
Chris Lattner220b0cf2006-03-05 00:22:33 +000012389 if (C->getOperand(i) != op0) {
12390 op0 = 0;
12391 break;
12392 }
12393 if (op0)
12394 return ReplaceInstUsesWith(EI, op0);
Robert Bocchino1d7456d2006-01-13 22:48:06 +000012395 }
Eli Friedman76e7ba82009-07-18 19:04:16 +000012396
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012397 // If extracting a specified index from the vector, see if we can recursively
12398 // find a previously computed scalar that was inserted into the vector.
Reid Spencerb83eb642006-10-20 07:07:24 +000012399 if (ConstantInt *IdxC = dyn_cast<ConstantInt>(EI.getOperand(1))) {
Chris Lattner85464092007-04-09 01:37:55 +000012400 unsigned IndexVal = IdxC->getZExtValue();
Eli Friedman76e7ba82009-07-18 19:04:16 +000012401 unsigned VectorWidth =
12402 cast<VectorType>(EI.getOperand(0)->getType())->getNumElements();
Chris Lattner85464092007-04-09 01:37:55 +000012403
12404 // If this is extracting an invalid index, turn this into undef, to avoid
12405 // crashing the code below.
12406 if (IndexVal >= VectorWidth)
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012407 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
Chris Lattner85464092007-04-09 01:37:55 +000012408
Chris Lattner867b99f2006-10-05 06:55:50 +000012409 // This instruction only demands the single element from the input vector.
12410 // If the input vector has a single use, simplify it based on this use
12411 // property.
Eli Friedman76e7ba82009-07-18 19:04:16 +000012412 if (EI.getOperand(0)->hasOneUse() && VectorWidth != 1) {
Evan Cheng388df622009-02-03 10:05:09 +000012413 APInt UndefElts(VectorWidth, 0);
12414 APInt DemandedMask(VectorWidth, 1 << IndexVal);
Chris Lattner867b99f2006-10-05 06:55:50 +000012415 if (Value *V = SimplifyDemandedVectorElts(EI.getOperand(0),
Evan Cheng388df622009-02-03 10:05:09 +000012416 DemandedMask, UndefElts)) {
Chris Lattner867b99f2006-10-05 06:55:50 +000012417 EI.setOperand(0, V);
12418 return &EI;
12419 }
12420 }
12421
Owen Andersond672ecb2009-07-03 00:17:18 +000012422 if (Value *Elt = FindScalarElement(EI.getOperand(0), IndexVal, Context))
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012423 return ReplaceInstUsesWith(EI, Elt);
Chris Lattnerb7300fa2007-04-14 23:02:14 +000012424
12425 // If the this extractelement is directly using a bitcast from a vector of
12426 // the same number of elements, see if we can find the source element from
12427 // it. In this case, we will end up needing to bitcast the scalars.
12428 if (BitCastInst *BCI = dyn_cast<BitCastInst>(EI.getOperand(0))) {
12429 if (const VectorType *VT =
12430 dyn_cast<VectorType>(BCI->getOperand(0)->getType()))
12431 if (VT->getNumElements() == VectorWidth)
Owen Andersond672ecb2009-07-03 00:17:18 +000012432 if (Value *Elt = FindScalarElement(BCI->getOperand(0),
12433 IndexVal, Context))
Chris Lattnerb7300fa2007-04-14 23:02:14 +000012434 return new BitCastInst(Elt, EI.getType());
12435 }
Chris Lattner389a6f52006-04-10 23:06:36 +000012436 }
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012437
Chris Lattner73fa49d2006-05-25 22:53:38 +000012438 if (Instruction *I = dyn_cast<Instruction>(EI.getOperand(0))) {
Robert Bocchino1d7456d2006-01-13 22:48:06 +000012439 if (I->hasOneUse()) {
12440 // Push extractelement into predecessor operation if legal and
12441 // profitable to do so
12442 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
Chris Lattner220b0cf2006-03-05 00:22:33 +000012443 bool isConstantElt = isa<ConstantInt>(EI.getOperand(1));
12444 if (CheapToScalarize(BO, isConstantElt)) {
12445 ExtractElementInst *newEI0 =
Eric Christophera3500da2009-07-25 02:28:41 +000012446 ExtractElementInst::Create(BO->getOperand(0), EI.getOperand(1),
Chris Lattner220b0cf2006-03-05 00:22:33 +000012447 EI.getName()+".lhs");
12448 ExtractElementInst *newEI1 =
Eric Christophera3500da2009-07-25 02:28:41 +000012449 ExtractElementInst::Create(BO->getOperand(1), EI.getOperand(1),
Chris Lattner220b0cf2006-03-05 00:22:33 +000012450 EI.getName()+".rhs");
12451 InsertNewInstBefore(newEI0, EI);
12452 InsertNewInstBefore(newEI1, EI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +000012453 return BinaryOperator::Create(BO->getOpcode(), newEI0, newEI1);
Chris Lattner220b0cf2006-03-05 00:22:33 +000012454 }
Reid Spencer3ed469c2006-11-02 20:25:50 +000012455 } else if (isa<LoadInst>(I)) {
Christopher Lamb43ad6b32007-12-17 01:12:55 +000012456 unsigned AS =
12457 cast<PointerType>(I->getOperand(0)->getType())->getAddressSpace();
Chris Lattner6d0339d2008-01-13 22:23:22 +000012458 Value *Ptr = InsertBitCastBefore(I->getOperand(0),
Owen Andersondebcb012009-07-29 22:17:13 +000012459 PointerType::get(EI.getType(), AS),EI);
Gabor Greifb1dbcd82008-05-15 10:04:30 +000012460 GetElementPtrInst *GEP =
12461 GetElementPtrInst::Create(Ptr, EI.getOperand(1), I->getName()+".gep");
Dan Gohmand6aa02d2009-07-28 01:40:03 +000012462 cast<GEPOperator>(GEP)->setIsInBounds(true);
Robert Bocchino1d7456d2006-01-13 22:48:06 +000012463 InsertNewInstBefore(GEP, EI);
12464 return new LoadInst(GEP);
Chris Lattner73fa49d2006-05-25 22:53:38 +000012465 }
12466 }
12467 if (InsertElementInst *IE = dyn_cast<InsertElementInst>(I)) {
12468 // Extracting the inserted element?
12469 if (IE->getOperand(2) == EI.getOperand(1))
12470 return ReplaceInstUsesWith(EI, IE->getOperand(1));
12471 // If the inserted and extracted elements are constants, they must not
12472 // be the same value, extract from the pre-inserted value instead.
12473 if (isa<Constant>(IE->getOperand(2)) &&
12474 isa<Constant>(EI.getOperand(1))) {
12475 AddUsesToWorkList(EI);
12476 EI.setOperand(0, IE->getOperand(0));
12477 return &EI;
12478 }
12479 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I)) {
12480 // If this is extracting an element from a shufflevector, figure out where
12481 // it came from and extract from the appropriate input element instead.
Reid Spencerb83eb642006-10-20 07:07:24 +000012482 if (ConstantInt *Elt = dyn_cast<ConstantInt>(EI.getOperand(1))) {
12483 unsigned SrcIdx = getShuffleMask(SVI)[Elt->getZExtValue()];
Chris Lattner863bcff2006-05-25 23:48:38 +000012484 Value *Src;
Mon P Wangaeb06d22008-11-10 04:46:22 +000012485 unsigned LHSWidth =
12486 cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements();
12487
12488 if (SrcIdx < LHSWidth)
Chris Lattner863bcff2006-05-25 23:48:38 +000012489 Src = SVI->getOperand(0);
Mon P Wangaeb06d22008-11-10 04:46:22 +000012490 else if (SrcIdx < LHSWidth*2) {
12491 SrcIdx -= LHSWidth;
Chris Lattner863bcff2006-05-25 23:48:38 +000012492 Src = SVI->getOperand(1);
12493 } else {
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012494 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
Chris Lattnerdf084ff2006-03-30 22:02:40 +000012495 }
Eric Christophera3500da2009-07-25 02:28:41 +000012496 return ExtractElementInst::Create(Src,
Owen Andersoneed707b2009-07-24 23:12:02 +000012497 ConstantInt::get(Type::Int32Ty, SrcIdx, false));
Robert Bocchino1d7456d2006-01-13 22:48:06 +000012498 }
12499 }
Eli Friedman2451a642009-07-18 23:06:53 +000012500 // FIXME: Canonicalize extractelement(bitcast) -> bitcast(extractelement)
Chris Lattner73fa49d2006-05-25 22:53:38 +000012501 }
Robert Bocchino1d7456d2006-01-13 22:48:06 +000012502 return 0;
12503}
12504
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012505/// CollectSingleShuffleElements - If V is a shuffle of values that ONLY returns
12506/// elements from either LHS or RHS, return the shuffle mask and true.
12507/// Otherwise, return false.
12508static bool CollectSingleShuffleElements(Value *V, Value *LHS, Value *RHS,
Owen Andersond672ecb2009-07-03 00:17:18 +000012509 std::vector<Constant*> &Mask,
Owen Anderson07cf79e2009-07-06 23:00:19 +000012510 LLVMContext *Context) {
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012511 assert(V->getType() == LHS->getType() && V->getType() == RHS->getType() &&
12512 "Invalid CollectSingleShuffleElements");
Reid Spencer9d6565a2007-02-15 02:26:10 +000012513 unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012514
12515 if (isa<UndefValue>(V)) {
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012516 Mask.assign(NumElts, UndefValue::get(Type::Int32Ty));
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012517 return true;
12518 } else if (V == LHS) {
12519 for (unsigned i = 0; i != NumElts; ++i)
Owen Andersoneed707b2009-07-24 23:12:02 +000012520 Mask.push_back(ConstantInt::get(Type::Int32Ty, i));
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012521 return true;
12522 } else if (V == RHS) {
12523 for (unsigned i = 0; i != NumElts; ++i)
Owen Andersoneed707b2009-07-24 23:12:02 +000012524 Mask.push_back(ConstantInt::get(Type::Int32Ty, i+NumElts));
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012525 return true;
12526 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
12527 // If this is an insert of an extract from some other vector, include it.
12528 Value *VecOp = IEI->getOperand(0);
12529 Value *ScalarOp = IEI->getOperand(1);
12530 Value *IdxOp = IEI->getOperand(2);
12531
Chris Lattnerd929f062006-04-27 21:14:21 +000012532 if (!isa<ConstantInt>(IdxOp))
12533 return false;
Reid Spencerb83eb642006-10-20 07:07:24 +000012534 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattnerd929f062006-04-27 21:14:21 +000012535
12536 if (isa<UndefValue>(ScalarOp)) { // inserting undef into vector.
12537 // Okay, we can handle this if the vector we are insertinting into is
12538 // transitively ok.
Owen Andersond672ecb2009-07-03 00:17:18 +000012539 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask, Context)) {
Chris Lattnerd929f062006-04-27 21:14:21 +000012540 // If so, update the mask to reflect the inserted undef.
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012541 Mask[InsertedIdx] = UndefValue::get(Type::Int32Ty);
Chris Lattnerd929f062006-04-27 21:14:21 +000012542 return true;
12543 }
12544 } else if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)){
12545 if (isa<ConstantInt>(EI->getOperand(1)) &&
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012546 EI->getOperand(0)->getType() == V->getType()) {
12547 unsigned ExtractedIdx =
Reid Spencerb83eb642006-10-20 07:07:24 +000012548 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012549
12550 // This must be extracting from either LHS or RHS.
12551 if (EI->getOperand(0) == LHS || EI->getOperand(0) == RHS) {
12552 // Okay, we can handle this if the vector we are insertinting into is
12553 // transitively ok.
Owen Andersond672ecb2009-07-03 00:17:18 +000012554 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask, Context)) {
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012555 // If so, update the mask to reflect the inserted value.
12556 if (EI->getOperand(0) == LHS) {
Mon P Wang4f5ca2c2008-08-20 02:23:25 +000012557 Mask[InsertedIdx % NumElts] =
Owen Andersoneed707b2009-07-24 23:12:02 +000012558 ConstantInt::get(Type::Int32Ty, ExtractedIdx);
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012559 } else {
12560 assert(EI->getOperand(0) == RHS);
Mon P Wang4f5ca2c2008-08-20 02:23:25 +000012561 Mask[InsertedIdx % NumElts] =
Owen Andersoneed707b2009-07-24 23:12:02 +000012562 ConstantInt::get(Type::Int32Ty, ExtractedIdx+NumElts);
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012563
12564 }
12565 return true;
12566 }
12567 }
12568 }
12569 }
12570 }
12571 // TODO: Handle shufflevector here!
12572
12573 return false;
12574}
12575
12576/// CollectShuffleElements - We are building a shuffle of V, using RHS as the
12577/// RHS of the shuffle instruction, if it is not null. Return a shuffle mask
12578/// that computes V and the LHS value of the shuffle.
Chris Lattnerefb47352006-04-15 01:39:45 +000012579static Value *CollectShuffleElements(Value *V, std::vector<Constant*> &Mask,
Owen Anderson07cf79e2009-07-06 23:00:19 +000012580 Value *&RHS, LLVMContext *Context) {
Reid Spencer9d6565a2007-02-15 02:26:10 +000012581 assert(isa<VectorType>(V->getType()) &&
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012582 (RHS == 0 || V->getType() == RHS->getType()) &&
Chris Lattnerefb47352006-04-15 01:39:45 +000012583 "Invalid shuffle!");
Reid Spencer9d6565a2007-02-15 02:26:10 +000012584 unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
Chris Lattnerefb47352006-04-15 01:39:45 +000012585
12586 if (isa<UndefValue>(V)) {
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012587 Mask.assign(NumElts, UndefValue::get(Type::Int32Ty));
Chris Lattnerefb47352006-04-15 01:39:45 +000012588 return V;
12589 } else if (isa<ConstantAggregateZero>(V)) {
Owen Andersoneed707b2009-07-24 23:12:02 +000012590 Mask.assign(NumElts, ConstantInt::get(Type::Int32Ty, 0));
Chris Lattnerefb47352006-04-15 01:39:45 +000012591 return V;
12592 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
12593 // If this is an insert of an extract from some other vector, include it.
12594 Value *VecOp = IEI->getOperand(0);
12595 Value *ScalarOp = IEI->getOperand(1);
12596 Value *IdxOp = IEI->getOperand(2);
12597
12598 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
12599 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
12600 EI->getOperand(0)->getType() == V->getType()) {
12601 unsigned ExtractedIdx =
Reid Spencerb83eb642006-10-20 07:07:24 +000012602 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
12603 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattnerefb47352006-04-15 01:39:45 +000012604
12605 // Either the extracted from or inserted into vector must be RHSVec,
12606 // otherwise we'd end up with a shuffle of three inputs.
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012607 if (EI->getOperand(0) == RHS || RHS == 0) {
12608 RHS = EI->getOperand(0);
Owen Andersond672ecb2009-07-03 00:17:18 +000012609 Value *V = CollectShuffleElements(VecOp, Mask, RHS, Context);
Mon P Wang4f5ca2c2008-08-20 02:23:25 +000012610 Mask[InsertedIdx % NumElts] =
Owen Andersoneed707b2009-07-24 23:12:02 +000012611 ConstantInt::get(Type::Int32Ty, NumElts+ExtractedIdx);
Chris Lattnerefb47352006-04-15 01:39:45 +000012612 return V;
12613 }
12614
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012615 if (VecOp == RHS) {
Owen Andersond672ecb2009-07-03 00:17:18 +000012616 Value *V = CollectShuffleElements(EI->getOperand(0), Mask,
12617 RHS, Context);
Chris Lattnerefb47352006-04-15 01:39:45 +000012618 // Everything but the extracted element is replaced with the RHS.
12619 for (unsigned i = 0; i != NumElts; ++i) {
12620 if (i != InsertedIdx)
Owen Andersoneed707b2009-07-24 23:12:02 +000012621 Mask[i] = ConstantInt::get(Type::Int32Ty, NumElts+i);
Chris Lattnerefb47352006-04-15 01:39:45 +000012622 }
12623 return V;
12624 }
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012625
12626 // If this insertelement is a chain that comes from exactly these two
12627 // vectors, return the vector and the effective shuffle.
Owen Andersond672ecb2009-07-03 00:17:18 +000012628 if (CollectSingleShuffleElements(IEI, EI->getOperand(0), RHS, Mask,
12629 Context))
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012630 return EI->getOperand(0);
12631
Chris Lattnerefb47352006-04-15 01:39:45 +000012632 }
12633 }
12634 }
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012635 // TODO: Handle shufflevector here!
Chris Lattnerefb47352006-04-15 01:39:45 +000012636
12637 // Otherwise, can't do anything fancy. Return an identity vector.
12638 for (unsigned i = 0; i != NumElts; ++i)
Owen Andersoneed707b2009-07-24 23:12:02 +000012639 Mask.push_back(ConstantInt::get(Type::Int32Ty, i));
Chris Lattnerefb47352006-04-15 01:39:45 +000012640 return V;
12641}
12642
12643Instruction *InstCombiner::visitInsertElementInst(InsertElementInst &IE) {
12644 Value *VecOp = IE.getOperand(0);
12645 Value *ScalarOp = IE.getOperand(1);
12646 Value *IdxOp = IE.getOperand(2);
12647
Chris Lattner599ded12007-04-09 01:11:16 +000012648 // Inserting an undef or into an undefined place, remove this.
12649 if (isa<UndefValue>(ScalarOp) || isa<UndefValue>(IdxOp))
12650 ReplaceInstUsesWith(IE, VecOp);
Eli Friedman76e7ba82009-07-18 19:04:16 +000012651
Chris Lattnerefb47352006-04-15 01:39:45 +000012652 // If the inserted element was extracted from some other vector, and if the
12653 // indexes are constant, try to turn this into a shufflevector operation.
12654 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
12655 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
12656 EI->getOperand(0)->getType() == IE.getType()) {
Eli Friedman76e7ba82009-07-18 19:04:16 +000012657 unsigned NumVectorElts = IE.getType()->getNumElements();
Chris Lattnere34e9a22007-04-14 23:32:02 +000012658 unsigned ExtractedIdx =
12659 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
Reid Spencerb83eb642006-10-20 07:07:24 +000012660 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattnerefb47352006-04-15 01:39:45 +000012661
12662 if (ExtractedIdx >= NumVectorElts) // Out of range extract.
12663 return ReplaceInstUsesWith(IE, VecOp);
12664
12665 if (InsertedIdx >= NumVectorElts) // Out of range insert.
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012666 return ReplaceInstUsesWith(IE, UndefValue::get(IE.getType()));
Chris Lattnerefb47352006-04-15 01:39:45 +000012667
12668 // If we are extracting a value from a vector, then inserting it right
12669 // back into the same place, just use the input vector.
12670 if (EI->getOperand(0) == VecOp && ExtractedIdx == InsertedIdx)
12671 return ReplaceInstUsesWith(IE, VecOp);
12672
12673 // We could theoretically do this for ANY input. However, doing so could
12674 // turn chains of insertelement instructions into a chain of shufflevector
12675 // instructions, and right now we do not merge shufflevectors. As such,
12676 // only do this in a situation where it is clear that there is benefit.
12677 if (isa<UndefValue>(VecOp) || isa<ConstantAggregateZero>(VecOp)) {
12678 // Turn this into shuffle(EIOp0, VecOp, Mask). The result has all of
12679 // the values of VecOp, except then one read from EIOp0.
12680 // Build a new shuffle mask.
12681 std::vector<Constant*> Mask;
12682 if (isa<UndefValue>(VecOp))
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012683 Mask.assign(NumVectorElts, UndefValue::get(Type::Int32Ty));
Chris Lattnerefb47352006-04-15 01:39:45 +000012684 else {
12685 assert(isa<ConstantAggregateZero>(VecOp) && "Unknown thing");
Owen Andersoneed707b2009-07-24 23:12:02 +000012686 Mask.assign(NumVectorElts, ConstantInt::get(Type::Int32Ty,
Chris Lattnerefb47352006-04-15 01:39:45 +000012687 NumVectorElts));
12688 }
Owen Andersond672ecb2009-07-03 00:17:18 +000012689 Mask[InsertedIdx] =
Owen Andersoneed707b2009-07-24 23:12:02 +000012690 ConstantInt::get(Type::Int32Ty, ExtractedIdx);
Chris Lattnerefb47352006-04-15 01:39:45 +000012691 return new ShuffleVectorInst(EI->getOperand(0), VecOp,
Owen Andersonaf7ec972009-07-28 21:19:26 +000012692 ConstantVector::get(Mask));
Chris Lattnerefb47352006-04-15 01:39:45 +000012693 }
12694
12695 // If this insertelement isn't used by some other insertelement, turn it
12696 // (and any insertelements it points to), into one big shuffle.
12697 if (!IE.hasOneUse() || !isa<InsertElementInst>(IE.use_back())) {
12698 std::vector<Constant*> Mask;
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012699 Value *RHS = 0;
Owen Andersond672ecb2009-07-03 00:17:18 +000012700 Value *LHS = CollectShuffleElements(&IE, Mask, RHS, Context);
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012701 if (RHS == 0) RHS = UndefValue::get(LHS->getType());
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012702 // We now have a shuffle of LHS, RHS, Mask.
Owen Andersond672ecb2009-07-03 00:17:18 +000012703 return new ShuffleVectorInst(LHS, RHS,
Owen Andersonaf7ec972009-07-28 21:19:26 +000012704 ConstantVector::get(Mask));
Chris Lattnerefb47352006-04-15 01:39:45 +000012705 }
12706 }
12707 }
12708
Eli Friedmanb9a4cac2009-06-06 20:08:03 +000012709 unsigned VWidth = cast<VectorType>(VecOp->getType())->getNumElements();
12710 APInt UndefElts(VWidth, 0);
12711 APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth));
12712 if (SimplifyDemandedVectorElts(&IE, AllOnesEltMask, UndefElts))
12713 return &IE;
12714
Chris Lattnerefb47352006-04-15 01:39:45 +000012715 return 0;
12716}
12717
12718
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012719Instruction *InstCombiner::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
12720 Value *LHS = SVI.getOperand(0);
12721 Value *RHS = SVI.getOperand(1);
Chris Lattner863bcff2006-05-25 23:48:38 +000012722 std::vector<unsigned> Mask = getShuffleMask(&SVI);
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012723
12724 bool MadeChange = false;
Mon P Wangaeb06d22008-11-10 04:46:22 +000012725
Chris Lattner867b99f2006-10-05 06:55:50 +000012726 // Undefined shuffle mask -> undefined value.
Chris Lattner863bcff2006-05-25 23:48:38 +000012727 if (isa<UndefValue>(SVI.getOperand(2)))
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012728 return ReplaceInstUsesWith(SVI, UndefValue::get(SVI.getType()));
Dan Gohman488fbfc2008-09-09 18:11:14 +000012729
Dan Gohman488fbfc2008-09-09 18:11:14 +000012730 unsigned VWidth = cast<VectorType>(SVI.getType())->getNumElements();
Mon P Wangaeb06d22008-11-10 04:46:22 +000012731
12732 if (VWidth != cast<VectorType>(LHS->getType())->getNumElements())
12733 return 0;
12734
Evan Cheng388df622009-02-03 10:05:09 +000012735 APInt UndefElts(VWidth, 0);
12736 APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth));
12737 if (SimplifyDemandedVectorElts(&SVI, AllOnesEltMask, UndefElts)) {
Dan Gohman3139ff82008-09-11 22:47:57 +000012738 LHS = SVI.getOperand(0);
12739 RHS = SVI.getOperand(1);
Dan Gohman488fbfc2008-09-09 18:11:14 +000012740 MadeChange = true;
Dan Gohman3139ff82008-09-11 22:47:57 +000012741 }
Chris Lattnerefb47352006-04-15 01:39:45 +000012742
Chris Lattner863bcff2006-05-25 23:48:38 +000012743 // Canonicalize shuffle(x ,x,mask) -> shuffle(x, undef,mask')
12744 // Canonicalize shuffle(undef,x,mask) -> shuffle(x, undef,mask').
12745 if (LHS == RHS || isa<UndefValue>(LHS)) {
12746 if (isa<UndefValue>(LHS) && LHS == RHS) {
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012747 // shuffle(undef,undef,mask) -> undef.
12748 return ReplaceInstUsesWith(SVI, LHS);
12749 }
12750
Chris Lattner863bcff2006-05-25 23:48:38 +000012751 // Remap any references to RHS to use LHS.
12752 std::vector<Constant*> Elts;
12753 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
Chris Lattner7b2e27922006-05-26 00:29:06 +000012754 if (Mask[i] >= 2*e)
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012755 Elts.push_back(UndefValue::get(Type::Int32Ty));
Chris Lattner7b2e27922006-05-26 00:29:06 +000012756 else {
12757 if ((Mask[i] >= e && isa<UndefValue>(RHS)) ||
Dan Gohman4ce96272008-08-06 18:17:32 +000012758 (Mask[i] < e && isa<UndefValue>(LHS))) {
Chris Lattner7b2e27922006-05-26 00:29:06 +000012759 Mask[i] = 2*e; // Turn into undef.
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012760 Elts.push_back(UndefValue::get(Type::Int32Ty));
Dan Gohman4ce96272008-08-06 18:17:32 +000012761 } else {
Mon P Wang4f5ca2c2008-08-20 02:23:25 +000012762 Mask[i] = Mask[i] % e; // Force to LHS.
Owen Andersoneed707b2009-07-24 23:12:02 +000012763 Elts.push_back(ConstantInt::get(Type::Int32Ty, Mask[i]));
Dan Gohman4ce96272008-08-06 18:17:32 +000012764 }
Chris Lattner7b2e27922006-05-26 00:29:06 +000012765 }
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012766 }
Chris Lattner863bcff2006-05-25 23:48:38 +000012767 SVI.setOperand(0, SVI.getOperand(1));
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012768 SVI.setOperand(1, UndefValue::get(RHS->getType()));
Owen Andersonaf7ec972009-07-28 21:19:26 +000012769 SVI.setOperand(2, ConstantVector::get(Elts));
Chris Lattner7b2e27922006-05-26 00:29:06 +000012770 LHS = SVI.getOperand(0);
12771 RHS = SVI.getOperand(1);
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012772 MadeChange = true;
12773 }
12774
Chris Lattner7b2e27922006-05-26 00:29:06 +000012775 // Analyze the shuffle, are the LHS or RHS and identity shuffles?
Chris Lattner863bcff2006-05-25 23:48:38 +000012776 bool isLHSID = true, isRHSID = true;
Chris Lattner706126d2006-04-16 00:03:56 +000012777
Chris Lattner863bcff2006-05-25 23:48:38 +000012778 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
12779 if (Mask[i] >= e*2) continue; // Ignore undef values.
12780 // Is this an identity shuffle of the LHS value?
12781 isLHSID &= (Mask[i] == i);
12782
12783 // Is this an identity shuffle of the RHS value?
12784 isRHSID &= (Mask[i]-e == i);
Chris Lattner706126d2006-04-16 00:03:56 +000012785 }
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012786
Chris Lattner863bcff2006-05-25 23:48:38 +000012787 // Eliminate identity shuffles.
12788 if (isLHSID) return ReplaceInstUsesWith(SVI, LHS);
12789 if (isRHSID) return ReplaceInstUsesWith(SVI, RHS);
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012790
Chris Lattner7b2e27922006-05-26 00:29:06 +000012791 // If the LHS is a shufflevector itself, see if we can combine it with this
12792 // one without producing an unusual shuffle. Here we are really conservative:
12793 // we are absolutely afraid of producing a shuffle mask not in the input
12794 // program, because the code gen may not be smart enough to turn a merged
12795 // shuffle into two specific shuffles: it may produce worse code. As such,
12796 // we only merge two shuffles if the result is one of the two input shuffle
12797 // masks. In this case, merging the shuffles just removes one instruction,
12798 // which we know is safe. This is good for things like turning:
12799 // (splat(splat)) -> splat.
12800 if (ShuffleVectorInst *LHSSVI = dyn_cast<ShuffleVectorInst>(LHS)) {
12801 if (isa<UndefValue>(RHS)) {
12802 std::vector<unsigned> LHSMask = getShuffleMask(LHSSVI);
12803
12804 std::vector<unsigned> NewMask;
12805 for (unsigned i = 0, e = Mask.size(); i != e; ++i)
12806 if (Mask[i] >= 2*e)
12807 NewMask.push_back(2*e);
12808 else
12809 NewMask.push_back(LHSMask[Mask[i]]);
12810
12811 // If the result mask is equal to the src shuffle or this shuffle mask, do
12812 // the replacement.
12813 if (NewMask == LHSMask || NewMask == Mask) {
Mon P Wangfe6d2cd2009-01-26 04:39:00 +000012814 unsigned LHSInNElts =
12815 cast<VectorType>(LHSSVI->getOperand(0)->getType())->getNumElements();
Chris Lattner7b2e27922006-05-26 00:29:06 +000012816 std::vector<Constant*> Elts;
12817 for (unsigned i = 0, e = NewMask.size(); i != e; ++i) {
Mon P Wangfe6d2cd2009-01-26 04:39:00 +000012818 if (NewMask[i] >= LHSInNElts*2) {
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012819 Elts.push_back(UndefValue::get(Type::Int32Ty));
Chris Lattner7b2e27922006-05-26 00:29:06 +000012820 } else {
Owen Andersoneed707b2009-07-24 23:12:02 +000012821 Elts.push_back(ConstantInt::get(Type::Int32Ty, NewMask[i]));
Chris Lattner7b2e27922006-05-26 00:29:06 +000012822 }
12823 }
12824 return new ShuffleVectorInst(LHSSVI->getOperand(0),
12825 LHSSVI->getOperand(1),
Owen Andersonaf7ec972009-07-28 21:19:26 +000012826 ConstantVector::get(Elts));
Chris Lattner7b2e27922006-05-26 00:29:06 +000012827 }
12828 }
12829 }
Chris Lattnerc5eff442007-01-30 22:32:46 +000012830
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012831 return MadeChange ? &SVI : 0;
12832}
12833
12834
Robert Bocchino1d7456d2006-01-13 22:48:06 +000012835
Chris Lattnerea1c4542004-12-08 23:43:58 +000012836
12837/// TryToSinkInstruction - Try to move the specified instruction from its
12838/// current block into the beginning of DestBlock, which can only happen if it's
12839/// safe to move the instruction past all of the instructions between it and the
12840/// end of its block.
12841static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
12842 assert(I->hasOneUse() && "Invariants didn't hold!");
12843
Chris Lattner108e9022005-10-27 17:13:11 +000012844 // Cannot move control-flow-involving, volatile loads, vaarg, etc.
Duncan Sands7af1c782009-05-06 06:49:50 +000012845 if (isa<PHINode>(I) || I->mayHaveSideEffects() || isa<TerminatorInst>(I))
Chris Lattnerbfc538c2008-05-09 15:07:33 +000012846 return false;
Misha Brukmanfd939082005-04-21 23:48:37 +000012847
Chris Lattnerea1c4542004-12-08 23:43:58 +000012848 // Do not sink alloca instructions out of the entry block.
Dan Gohmanecb7a772007-03-22 16:38:57 +000012849 if (isa<AllocaInst>(I) && I->getParent() ==
12850 &DestBlock->getParent()->getEntryBlock())
Chris Lattnerea1c4542004-12-08 23:43:58 +000012851 return false;
12852
Chris Lattner96a52a62004-12-09 07:14:34 +000012853 // We can only sink load instructions if there is nothing between the load and
12854 // the end of block that could change the value.
Chris Lattner2539e332008-05-08 17:37:37 +000012855 if (I->mayReadFromMemory()) {
12856 for (BasicBlock::iterator Scan = I, E = I->getParent()->end();
Chris Lattner96a52a62004-12-09 07:14:34 +000012857 Scan != E; ++Scan)
12858 if (Scan->mayWriteToMemory())
12859 return false;
Chris Lattner96a52a62004-12-09 07:14:34 +000012860 }
Chris Lattnerea1c4542004-12-08 23:43:58 +000012861
Dan Gohman02dea8b2008-05-23 21:05:58 +000012862 BasicBlock::iterator InsertPos = DestBlock->getFirstNonPHI();
Chris Lattnerea1c4542004-12-08 23:43:58 +000012863
Dale Johannesenbd8e6502009-03-03 01:09:07 +000012864 CopyPrecedingStopPoint(I, InsertPos);
Chris Lattner4bc5f802005-08-08 19:11:57 +000012865 I->moveBefore(InsertPos);
Chris Lattnerea1c4542004-12-08 23:43:58 +000012866 ++NumSunkInst;
12867 return true;
12868}
12869
Chris Lattnerf4f5a772006-05-10 19:00:36 +000012870
12871/// AddReachableCodeToWorklist - Walk the function in depth-first order, adding
12872/// all reachable code to the worklist.
12873///
12874/// This has a couple of tricks to make the code faster and more powerful. In
12875/// particular, we constant fold and DCE instructions as we go, to avoid adding
12876/// them to the worklist (this significantly speeds up instcombine on code where
12877/// many instructions are dead or constant). Additionally, if we find a branch
12878/// whose condition is a known constant, we only visit the reachable successors.
12879///
12880static void AddReachableCodeToWorklist(BasicBlock *BB,
Chris Lattner1f87a582007-02-15 19:41:52 +000012881 SmallPtrSet<BasicBlock*, 64> &Visited,
Chris Lattnerdbab3862007-03-02 21:28:56 +000012882 InstCombiner &IC,
Chris Lattner8c8c66a2006-05-11 17:11:52 +000012883 const TargetData *TD) {
Chris Lattner2806dff2008-08-15 04:03:01 +000012884 SmallVector<BasicBlock*, 256> Worklist;
Chris Lattner2c7718a2007-03-23 19:17:18 +000012885 Worklist.push_back(BB);
Chris Lattnerf4f5a772006-05-10 19:00:36 +000012886
Chris Lattner2c7718a2007-03-23 19:17:18 +000012887 while (!Worklist.empty()) {
12888 BB = Worklist.back();
12889 Worklist.pop_back();
12890
12891 // We have now visited this block! If we've already been here, ignore it.
12892 if (!Visited.insert(BB)) continue;
Devang Patel7fe1dec2008-11-19 18:56:50 +000012893
12894 DbgInfoIntrinsic *DBI_Prev = NULL;
Chris Lattner2c7718a2007-03-23 19:17:18 +000012895 for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
12896 Instruction *Inst = BBI++;
Chris Lattnerf4f5a772006-05-10 19:00:36 +000012897
Chris Lattner2c7718a2007-03-23 19:17:18 +000012898 // DCE instruction if trivially dead.
12899 if (isInstructionTriviallyDead(Inst)) {
12900 ++NumDeadInst;
12901 DOUT << "IC: DCE: " << *Inst;
12902 Inst->eraseFromParent();
12903 continue;
12904 }
12905
12906 // ConstantProp instruction if trivially constant.
Owen Anderson50895512009-07-06 18:42:36 +000012907 if (Constant *C = ConstantFoldInstruction(Inst, BB->getContext(), TD)) {
Chris Lattner2c7718a2007-03-23 19:17:18 +000012908 DOUT << "IC: ConstFold to: " << *C << " from: " << *Inst;
12909 Inst->replaceAllUsesWith(C);
12910 ++NumConstProp;
12911 Inst->eraseFromParent();
12912 continue;
12913 }
Chris Lattner3ccc6bc2007-07-20 22:06:41 +000012914
Devang Patel7fe1dec2008-11-19 18:56:50 +000012915 // If there are two consecutive llvm.dbg.stoppoint calls then
12916 // it is likely that the optimizer deleted code in between these
12917 // two intrinsics.
12918 DbgInfoIntrinsic *DBI_Next = dyn_cast<DbgInfoIntrinsic>(Inst);
12919 if (DBI_Next) {
12920 if (DBI_Prev
12921 && DBI_Prev->getIntrinsicID() == llvm::Intrinsic::dbg_stoppoint
12922 && DBI_Next->getIntrinsicID() == llvm::Intrinsic::dbg_stoppoint) {
12923 IC.RemoveFromWorkList(DBI_Prev);
12924 DBI_Prev->eraseFromParent();
12925 }
12926 DBI_Prev = DBI_Next;
Zhou Sheng8313ef42009-02-23 10:14:11 +000012927 } else {
12928 DBI_Prev = 0;
Devang Patel7fe1dec2008-11-19 18:56:50 +000012929 }
12930
Chris Lattner2c7718a2007-03-23 19:17:18 +000012931 IC.AddToWorkList(Inst);
Chris Lattnerf4f5a772006-05-10 19:00:36 +000012932 }
Chris Lattner2c7718a2007-03-23 19:17:18 +000012933
12934 // Recursively visit successors. If this is a branch or switch on a
12935 // constant, only visit the reachable successor.
12936 TerminatorInst *TI = BB->getTerminator();
12937 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
12938 if (BI->isConditional() && isa<ConstantInt>(BI->getCondition())) {
12939 bool CondVal = cast<ConstantInt>(BI->getCondition())->getZExtValue();
Nick Lewycky91436992008-03-09 08:50:23 +000012940 BasicBlock *ReachableBB = BI->getSuccessor(!CondVal);
Nick Lewycky280a6e62008-04-25 16:53:59 +000012941 Worklist.push_back(ReachableBB);
Chris Lattner2c7718a2007-03-23 19:17:18 +000012942 continue;
12943 }
12944 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
12945 if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
12946 // See if this is an explicit destination.
12947 for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
12948 if (SI->getCaseValue(i) == Cond) {
Nick Lewycky91436992008-03-09 08:50:23 +000012949 BasicBlock *ReachableBB = SI->getSuccessor(i);
Nick Lewycky280a6e62008-04-25 16:53:59 +000012950 Worklist.push_back(ReachableBB);
Chris Lattner2c7718a2007-03-23 19:17:18 +000012951 continue;
12952 }
12953
12954 // Otherwise it is the default destination.
12955 Worklist.push_back(SI->getSuccessor(0));
12956 continue;
12957 }
12958 }
12959
12960 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
12961 Worklist.push_back(TI->getSuccessor(i));
Chris Lattnerf4f5a772006-05-10 19:00:36 +000012962 }
Chris Lattnerf4f5a772006-05-10 19:00:36 +000012963}
12964
Chris Lattnerec9c3582007-03-03 02:04:50 +000012965bool InstCombiner::DoOneIteration(Function &F, unsigned Iteration) {
Chris Lattnerdd841ae2002-04-18 17:39:14 +000012966 bool Changed = false;
Dan Gohmance9fe9f2009-07-21 23:21:54 +000012967 TD = getAnalysisIfAvailable<TargetData>();
Chris Lattnerec9c3582007-03-03 02:04:50 +000012968
Daniel Dunbarce63ffb2009-07-25 00:23:56 +000012969 DEBUG(errs() << "\n\nINSTCOMBINE ITERATION #" << Iteration << " on "
12970 << F.getNameStr() << "\n");
Chris Lattner8a2a3112001-12-14 16:52:21 +000012971
Chris Lattnerb3d59702005-07-07 20:40:38 +000012972 {
Chris Lattnerf4f5a772006-05-10 19:00:36 +000012973 // Do a depth-first traversal of the function, populate the worklist with
12974 // the reachable instructions. Ignore blocks that are not reachable. Keep
12975 // track of which blocks we visit.
Chris Lattner1f87a582007-02-15 19:41:52 +000012976 SmallPtrSet<BasicBlock*, 64> Visited;
Chris Lattnerdbab3862007-03-02 21:28:56 +000012977 AddReachableCodeToWorklist(F.begin(), Visited, *this, TD);
Jeff Cohen00b168892005-07-27 06:12:32 +000012978
Chris Lattnerb3d59702005-07-07 20:40:38 +000012979 // Do a quick scan over the function. If we find any blocks that are
12980 // unreachable, remove any instructions inside of them. This prevents
12981 // the instcombine code from having to deal with some bad special cases.
12982 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
12983 if (!Visited.count(BB)) {
12984 Instruction *Term = BB->getTerminator();
12985 while (Term != BB->begin()) { // Remove instrs bottom-up
12986 BasicBlock::iterator I = Term; --I;
Chris Lattner6ffe5512004-04-27 15:13:33 +000012987
Bill Wendlingb7427032006-11-26 09:46:52 +000012988 DOUT << "IC: DCE: " << *I;
Dale Johannesenff278b12009-03-10 21:19:49 +000012989 // A debug intrinsic shouldn't force another iteration if we weren't
12990 // going to do one without it.
12991 if (!isa<DbgInfoIntrinsic>(I)) {
12992 ++NumDeadInst;
12993 Changed = true;
12994 }
Chris Lattnerb3d59702005-07-07 20:40:38 +000012995 if (!I->use_empty())
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012996 I->replaceAllUsesWith(UndefValue::get(I->getType()));
Chris Lattnerb3d59702005-07-07 20:40:38 +000012997 I->eraseFromParent();
12998 }
12999 }
13000 }
Chris Lattner8a2a3112001-12-14 16:52:21 +000013001
Chris Lattnerdbab3862007-03-02 21:28:56 +000013002 while (!Worklist.empty()) {
13003 Instruction *I = RemoveOneFromWorkList();
13004 if (I == 0) continue; // skip null values.
Chris Lattner8a2a3112001-12-14 16:52:21 +000013005
Chris Lattner8c8c66a2006-05-11 17:11:52 +000013006 // Check to see if we can DCE the instruction.
Chris Lattner62b14df2002-09-02 04:59:56 +000013007 if (isInstructionTriviallyDead(I)) {
Chris Lattner8c8c66a2006-05-11 17:11:52 +000013008 // Add operands to the worklist.
Chris Lattner4bb7c022003-10-06 17:11:01 +000013009 if (I->getNumOperands() < 4)
Chris Lattner7bcc0e72004-02-28 05:22:00 +000013010 AddUsesToWorkList(*I);
Chris Lattner62b14df2002-09-02 04:59:56 +000013011 ++NumDeadInst;
Chris Lattner4bb7c022003-10-06 17:11:01 +000013012
Bill Wendlingb7427032006-11-26 09:46:52 +000013013 DOUT << "IC: DCE: " << *I;
Chris Lattnerad5fec12005-01-28 19:32:01 +000013014
13015 I->eraseFromParent();
Chris Lattnerdbab3862007-03-02 21:28:56 +000013016 RemoveFromWorkList(I);
Chris Lattner1e19d602009-01-31 07:04:22 +000013017 Changed = true;
Chris Lattner4bb7c022003-10-06 17:11:01 +000013018 continue;
13019 }
Chris Lattner62b14df2002-09-02 04:59:56 +000013020
Chris Lattner8c8c66a2006-05-11 17:11:52 +000013021 // Instruction isn't dead, see if we can constant propagate it.
Owen Anderson50895512009-07-06 18:42:36 +000013022 if (Constant *C = ConstantFoldInstruction(I, F.getContext(), TD)) {
Bill Wendlingb7427032006-11-26 09:46:52 +000013023 DOUT << "IC: ConstFold to: " << *C << " from: " << *I;
Chris Lattnerad5fec12005-01-28 19:32:01 +000013024
Chris Lattner8c8c66a2006-05-11 17:11:52 +000013025 // Add operands to the worklist.
Chris Lattner7bcc0e72004-02-28 05:22:00 +000013026 AddUsesToWorkList(*I);
Chris Lattnerc736d562002-12-05 22:41:53 +000013027 ReplaceInstUsesWith(*I, C);
13028
Chris Lattner62b14df2002-09-02 04:59:56 +000013029 ++NumConstProp;
Chris Lattnerf4f5a772006-05-10 19:00:36 +000013030 I->eraseFromParent();
Chris Lattnerdbab3862007-03-02 21:28:56 +000013031 RemoveFromWorkList(I);
Chris Lattner1e19d602009-01-31 07:04:22 +000013032 Changed = true;
Chris Lattner4bb7c022003-10-06 17:11:01 +000013033 continue;
Chris Lattner62b14df2002-09-02 04:59:56 +000013034 }
Chris Lattner4bb7c022003-10-06 17:11:01 +000013035
Eli Friedmanfd2934f2009-07-15 22:13:34 +000013036 if (TD) {
Nick Lewycky3dfd7bf2008-05-25 20:56:15 +000013037 // See if we can constant fold its operands.
Chris Lattner1e19d602009-01-31 07:04:22 +000013038 for (User::op_iterator i = I->op_begin(), e = I->op_end(); i != e; ++i)
13039 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(i))
Owen Anderson50895512009-07-06 18:42:36 +000013040 if (Constant *NewC = ConstantFoldConstantExpression(CE,
13041 F.getContext(), TD))
Chris Lattner1e19d602009-01-31 07:04:22 +000013042 if (NewC != CE) {
13043 i->set(NewC);
13044 Changed = true;
13045 }
Nick Lewycky3dfd7bf2008-05-25 20:56:15 +000013046 }
13047
Chris Lattnerea1c4542004-12-08 23:43:58 +000013048 // See if we can trivially sink this instruction to a successor basic block.
Dan Gohmanfc74abf2008-07-23 00:34:11 +000013049 if (I->hasOneUse()) {
Chris Lattnerea1c4542004-12-08 23:43:58 +000013050 BasicBlock *BB = I->getParent();
13051 BasicBlock *UserParent = cast<Instruction>(I->use_back())->getParent();
13052 if (UserParent != BB) {
13053 bool UserIsSuccessor = false;
13054 // See if the user is one of our successors.
13055 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
13056 if (*SI == UserParent) {
13057 UserIsSuccessor = true;
13058 break;
13059 }
13060
13061 // If the user is one of our immediate successors, and if that successor
13062 // only has us as a predecessors (we'd have to split the critical edge
13063 // otherwise), we can keep going.
13064 if (UserIsSuccessor && !isa<PHINode>(I->use_back()) &&
13065 next(pred_begin(UserParent)) == pred_end(UserParent))
13066 // Okay, the CFG is simple enough, try to sink this instruction.
13067 Changed |= TryToSinkInstruction(I, UserParent);
13068 }
13069 }
13070
Chris Lattner8a2a3112001-12-14 16:52:21 +000013071 // Now that we have an instruction, try combining it to simplify it...
Reid Spencera9b81012007-03-26 17:44:01 +000013072#ifndef NDEBUG
13073 std::string OrigI;
13074#endif
13075 DEBUG(std::ostringstream SS; I->print(SS); OrigI = SS.str(););
Chris Lattner90ac28c2002-08-02 19:29:35 +000013076 if (Instruction *Result = visit(*I)) {
Chris Lattner3dec1f22002-05-10 15:38:35 +000013077 ++NumCombined;
Chris Lattnerdd841ae2002-04-18 17:39:14 +000013078 // Should we replace the old instruction with a new one?
Chris Lattnerb3bc8fa2002-05-14 15:24:07 +000013079 if (Result != I) {
Bill Wendlingb7427032006-11-26 09:46:52 +000013080 DOUT << "IC: Old = " << *I
13081 << " New = " << *Result;
Chris Lattner0cea42a2004-03-13 23:54:27 +000013082
Chris Lattnerf523d062004-06-09 05:08:07 +000013083 // Everything uses the new instruction now.
13084 I->replaceAllUsesWith(Result);
13085
13086 // Push the new instruction and any users onto the worklist.
Chris Lattnerdbab3862007-03-02 21:28:56 +000013087 AddToWorkList(Result);
Chris Lattnerf523d062004-06-09 05:08:07 +000013088 AddUsersToWorkList(*Result);
Chris Lattner4bb7c022003-10-06 17:11:01 +000013089
Chris Lattner6934a042007-02-11 01:23:03 +000013090 // Move the name to the new instruction first.
13091 Result->takeName(I);
Chris Lattner4bb7c022003-10-06 17:11:01 +000013092
13093 // Insert the new instruction into the basic block...
13094 BasicBlock *InstParent = I->getParent();
Chris Lattnerbac32862004-11-14 19:13:23 +000013095 BasicBlock::iterator InsertPos = I;
13096
13097 if (!isa<PHINode>(Result)) // If combining a PHI, don't insert
13098 while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
13099 ++InsertPos;
13100
13101 InstParent->getInstList().insert(InsertPos, Result);
Chris Lattner4bb7c022003-10-06 17:11:01 +000013102
Chris Lattner00d51312004-05-01 23:27:23 +000013103 // Make sure that we reprocess all operands now that we reduced their
13104 // use counts.
Chris Lattnerdbab3862007-03-02 21:28:56 +000013105 AddUsesToWorkList(*I);
Chris Lattner216d4d82004-05-01 23:19:52 +000013106
Chris Lattnerf523d062004-06-09 05:08:07 +000013107 // Instructions can end up on the worklist more than once. Make sure
13108 // we do not process an instruction that has been deleted.
Chris Lattnerdbab3862007-03-02 21:28:56 +000013109 RemoveFromWorkList(I);
Chris Lattner4bb7c022003-10-06 17:11:01 +000013110
13111 // Erase the old instruction.
13112 InstParent->getInstList().erase(I);
Chris Lattner7e708292002-06-25 16:13:24 +000013113 } else {
Evan Chengc7baf682007-03-27 16:44:48 +000013114#ifndef NDEBUG
Reid Spencera9b81012007-03-26 17:44:01 +000013115 DOUT << "IC: Mod = " << OrigI
13116 << " New = " << *I;
Evan Chengc7baf682007-03-27 16:44:48 +000013117#endif
Chris Lattner0cea42a2004-03-13 23:54:27 +000013118
Chris Lattner90ac28c2002-08-02 19:29:35 +000013119 // If the instruction was modified, it's possible that it is now dead.
13120 // if so, remove it.
Chris Lattner00d51312004-05-01 23:27:23 +000013121 if (isInstructionTriviallyDead(I)) {
13122 // Make sure we process all operands now that we are reducing their
13123 // use counts.
Chris Lattnerec9c3582007-03-03 02:04:50 +000013124 AddUsesToWorkList(*I);
Misha Brukmanfd939082005-04-21 23:48:37 +000013125
Chris Lattner00d51312004-05-01 23:27:23 +000013126 // Instructions may end up in the worklist more than once. Erase all
Robert Bocchino1d7456d2006-01-13 22:48:06 +000013127 // occurrences of this instruction.
Chris Lattnerdbab3862007-03-02 21:28:56 +000013128 RemoveFromWorkList(I);
Chris Lattner2f503e62005-01-31 05:36:43 +000013129 I->eraseFromParent();
Chris Lattnerf523d062004-06-09 05:08:07 +000013130 } else {
Chris Lattnerec9c3582007-03-03 02:04:50 +000013131 AddToWorkList(I);
13132 AddUsersToWorkList(*I);
Chris Lattner90ac28c2002-08-02 19:29:35 +000013133 }
Chris Lattnerb3bc8fa2002-05-14 15:24:07 +000013134 }
Chris Lattnerdd841ae2002-04-18 17:39:14 +000013135 Changed = true;
Chris Lattner8a2a3112001-12-14 16:52:21 +000013136 }
13137 }
13138
Chris Lattnerec9c3582007-03-03 02:04:50 +000013139 assert(WorklistMap.empty() && "Worklist empty, but map not?");
Chris Lattnera9ff5eb2007-08-05 08:47:58 +000013140
13141 // Do an explicit clear, this shrinks the map if needed.
13142 WorklistMap.clear();
Chris Lattnerdd841ae2002-04-18 17:39:14 +000013143 return Changed;
Chris Lattnerbd0ef772002-02-26 21:46:54 +000013144}
13145
Chris Lattnerec9c3582007-03-03 02:04:50 +000013146
13147bool InstCombiner::runOnFunction(Function &F) {
Chris Lattnerf964f322007-03-04 04:27:24 +000013148 MustPreserveLCSSA = mustPreserveAnalysisID(LCSSAID);
Owen Andersone922c022009-07-22 00:24:57 +000013149 Context = &F.getContext();
Chris Lattnerf964f322007-03-04 04:27:24 +000013150
Chris Lattnerec9c3582007-03-03 02:04:50 +000013151 bool EverMadeChange = false;
13152
13153 // Iterate while there is work to do.
13154 unsigned Iteration = 0;
Bill Wendlinga6c31122008-05-14 22:45:20 +000013155 while (DoOneIteration(F, Iteration++))
Chris Lattnerec9c3582007-03-03 02:04:50 +000013156 EverMadeChange = true;
13157 return EverMadeChange;
13158}
13159
Brian Gaeke96d4bf72004-07-27 17:43:21 +000013160FunctionPass *llvm::createInstructionCombiningPass() {
Chris Lattnerdd841ae2002-04-18 17:39:14 +000013161 return new InstCombiner();
Chris Lattnerbd0ef772002-02-26 21:46:54 +000013162}