blob: 9cb1875b958b35f75f6251413030432b05abaa81 [file] [log] [blame]
Chris Lattnere6794492002-08-12 21:17:25 +00001//===- InstructionCombining.cpp - Combine multiple instructions -----------===//
Misha Brukmanb1c93172005-04-21 23:48:37 +00002//
John Criswell482202a2003-10-20 19:43:21 +00003// The LLVM Compiler Infrastructure
4//
Chris Lattnerf3ebc3f2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Misha Brukmanb1c93172005-04-21 23:48:37 +00007//
John Criswell482202a2003-10-20 19:43:21 +00008//===----------------------------------------------------------------------===//
Chris Lattnerca081252001-12-14 16:52:21 +00009//
10// InstructionCombining - Combine instructions to form fewer, simple
Dan Gohmand78c4002008-05-13 00:00:25 +000011// instructions. This pass does not modify the CFG. This pass is where
12// algebraic simplification happens.
Chris Lattnerca081252001-12-14 16:52:21 +000013//
14// This pass combines things like:
Chris Lattner07418422007-03-18 22:51:34 +000015// %Y = add i32 %X, 1
16// %Z = add i32 %Y, 1
Chris Lattnerca081252001-12-14 16:52:21 +000017// into:
Chris Lattner07418422007-03-18 22:51:34 +000018// %Z = add i32 %X, 2
Chris Lattnerca081252001-12-14 16:52:21 +000019//
20// This is a simple worklist driven algorithm.
21//
Chris Lattner216c7b82003-09-10 05:29:43 +000022// This pass guarantees that the following canonicalizations are performed on
Chris Lattnerbfb1d032003-07-23 21:41:57 +000023// the program:
24// 1. If a binary operator has a constant operand, it is moved to the RHS
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +000025// 2. Bitwise operators with constant operands are always grouped so that
26// shifts are performed first, then or's, then and's, then xor's.
Reid Spencer266e42b2006-12-23 06:05:41 +000027// 3. Compare instructions are converted from <,>,<=,>= to ==,!= if possible
28// 4. All cmp instructions on boolean values are replaced with logical ops
Chris Lattnerede3fe02003-08-13 04:18:28 +000029// 5. add X, X is represented as (X*2) => (X << 1)
30// 6. Multiplies with a power-of-two constant argument are transformed into
31// shifts.
Chris Lattner7515cab2004-11-14 19:13:23 +000032// ... etc.
Chris Lattnerbfb1d032003-07-23 21:41:57 +000033//
Chris Lattnerca081252001-12-14 16:52:21 +000034//===----------------------------------------------------------------------===//
35
Chris Lattner7d2a5392004-03-13 23:54:27 +000036#define DEBUG_TYPE "instcombine"
Chris Lattnerb4cfa7f2002-05-07 20:03:00 +000037#include "llvm/Transforms/Scalar.h"
Chris Lattner00648e12004-10-12 04:52:52 +000038#include "llvm/IntrinsicInst.h"
Chris Lattner04805fa2002-02-26 21:46:54 +000039#include "llvm/Pass.h"
Chris Lattner1085bdf2002-11-04 16:18:53 +000040#include "llvm/DerivedTypes.h"
Chris Lattner0f1d8a32003-06-26 05:06:25 +000041#include "llvm/GlobalVariable.h"
Chris Lattner024f4ab2007-01-30 23:46:24 +000042#include "llvm/Analysis/ConstantFolding.h"
Chris Lattner965c7692008-06-02 01:18:21 +000043#include "llvm/Analysis/ValueTracking.h"
Chris Lattnerf4ad1652003-11-02 05:57:39 +000044#include "llvm/Target/TargetData.h"
45#include "llvm/Transforms/Utils/BasicBlockUtils.h"
46#include "llvm/Transforms/Utils/Local.h"
Chris Lattner69193f92004-04-05 01:30:19 +000047#include "llvm/Support/CallSite.h"
Nick Lewycky3b592142008-02-03 16:33:09 +000048#include "llvm/Support/ConstantRange.h"
Chris Lattner39c98bb2004-12-08 23:43:58 +000049#include "llvm/Support/Debug.h"
Chris Lattner69193f92004-04-05 01:30:19 +000050#include "llvm/Support/GetElementPtrTypeIterator.h"
Chris Lattner260ab202002-04-18 17:39:14 +000051#include "llvm/Support/InstVisitor.h"
Chris Lattner22d00a82005-08-02 19:16:58 +000052#include "llvm/Support/MathExtras.h"
Chris Lattnerd4252a72004-07-30 07:50:03 +000053#include "llvm/Support/PatternMatch.h"
Chris Lattner3d27be12006-08-27 12:54:02 +000054#include "llvm/Support/Compiler.h"
Chris Lattnerb15e2b12007-03-02 21:28:56 +000055#include "llvm/ADT/DenseMap.h"
Chris Lattnerf96f4a82007-01-31 04:40:53 +000056#include "llvm/ADT/SmallVector.h"
Chris Lattner7907e5f2007-02-15 19:41:52 +000057#include "llvm/ADT/SmallPtrSet.h"
Reid Spencer7c16caa2004-09-01 22:55:40 +000058#include "llvm/ADT/Statistic.h"
Chris Lattner39c98bb2004-12-08 23:43:58 +000059#include "llvm/ADT/STLExtras.h"
Chris Lattner053c0932002-05-14 15:24:07 +000060#include <algorithm>
Torok Edwinab207842008-04-20 08:33:11 +000061#include <climits>
Reid Spencer755d0e72007-03-26 17:44:01 +000062#include <sstream>
Chris Lattner8427bff2003-12-07 01:24:23 +000063using namespace llvm;
Chris Lattnerd4252a72004-07-30 07:50:03 +000064using namespace llvm::PatternMatch;
Brian Gaeke960707c2003-11-11 22:41:34 +000065
Chris Lattner79a42ac2006-12-19 21:40:18 +000066STATISTIC(NumCombined , "Number of insts combined");
67STATISTIC(NumConstProp, "Number of constant folds");
68STATISTIC(NumDeadInst , "Number of dead inst eliminated");
69STATISTIC(NumDeadStore, "Number of dead stores eliminated");
70STATISTIC(NumSunkInst , "Number of instructions sunk");
Chris Lattnerbf3a0992002-10-01 22:38:41 +000071
Chris Lattner79a42ac2006-12-19 21:40:18 +000072namespace {
Chris Lattner4a4c7fe2006-06-28 22:08:15 +000073 class VISIBILITY_HIDDEN InstCombiner
74 : public FunctionPass,
75 public InstVisitor<InstCombiner, Instruction*> {
Chris Lattner260ab202002-04-18 17:39:14 +000076 // Worklist of all of the instructions that need to be simplified.
Chris Lattner1d239152008-08-15 04:03:01 +000077 SmallVector<Instruction*, 256> Worklist;
Chris Lattnerb15e2b12007-03-02 21:28:56 +000078 DenseMap<Instruction*, unsigned> WorklistMap;
Chris Lattnerf4ad1652003-11-02 05:57:39 +000079 TargetData *TD;
Chris Lattner8258b442007-03-04 04:27:24 +000080 bool MustPreserveLCSSA;
Chris Lattnerb15e2b12007-03-02 21:28:56 +000081 public:
Nick Lewyckye7da2d62007-05-06 13:37:16 +000082 static char ID; // Pass identification, replacement for typeid
Dan Gohmana79db302008-09-04 17:05:41 +000083 InstCombiner() : FunctionPass(&ID) {}
Devang Patel09f162c2007-05-01 21:15:47 +000084
Chris Lattnerb15e2b12007-03-02 21:28:56 +000085 /// AddToWorkList - Add the specified instruction to the worklist if it
86 /// isn't already in it.
87 void AddToWorkList(Instruction *I) {
Dan Gohman38740a92008-07-07 17:46:23 +000088 if (WorklistMap.insert(std::make_pair(I, Worklist.size())).second)
Chris Lattnerb15e2b12007-03-02 21:28:56 +000089 Worklist.push_back(I);
90 }
91
92 // RemoveFromWorkList - remove I from the worklist if it exists.
93 void RemoveFromWorkList(Instruction *I) {
94 DenseMap<Instruction*, unsigned>::iterator It = WorklistMap.find(I);
95 if (It == WorklistMap.end()) return; // Not in worklist.
96
97 // Don't bother moving everything down, just null out the slot.
98 Worklist[It->second] = 0;
99
100 WorklistMap.erase(It);
101 }
102
103 Instruction *RemoveOneFromWorkList() {
104 Instruction *I = Worklist.back();
105 Worklist.pop_back();
106 WorklistMap.erase(I);
107 return I;
108 }
Chris Lattner260ab202002-04-18 17:39:14 +0000109
Chris Lattnerb15e2b12007-03-02 21:28:56 +0000110
Chris Lattner51ea1272004-02-28 05:22:00 +0000111 /// AddUsersToWorkList - When an instruction is simplified, add all users of
112 /// the instruction to the work lists because they might get more simplified
113 /// now.
114 ///
Chris Lattner2590e512006-02-07 06:56:34 +0000115 void AddUsersToWorkList(Value &I) {
Chris Lattner113f4f42002-06-25 16:13:24 +0000116 for (Value::use_iterator UI = I.use_begin(), UE = I.use_end();
Chris Lattner260ab202002-04-18 17:39:14 +0000117 UI != UE; ++UI)
Chris Lattnerb15e2b12007-03-02 21:28:56 +0000118 AddToWorkList(cast<Instruction>(*UI));
Chris Lattner260ab202002-04-18 17:39:14 +0000119 }
120
Chris Lattner51ea1272004-02-28 05:22:00 +0000121 /// AddUsesToWorkList - When an instruction is simplified, add operands to
122 /// the work lists because they might get more simplified now.
123 ///
124 void AddUsesToWorkList(Instruction &I) {
Gabor Greiff6d8e772008-06-12 21:37:33 +0000125 for (User::op_iterator i = I.op_begin(), e = I.op_end(); i != e; ++i)
126 if (Instruction *Op = dyn_cast<Instruction>(*i))
Chris Lattnerb15e2b12007-03-02 21:28:56 +0000127 AddToWorkList(Op);
Chris Lattner51ea1272004-02-28 05:22:00 +0000128 }
Chris Lattner2deeaea2006-10-05 06:55:50 +0000129
130 /// AddSoonDeadInstToWorklist - The specified instruction is about to become
131 /// dead. Add all of its operands to the worklist, turning them into
132 /// undef's to reduce the number of uses of those instructions.
133 ///
134 /// Return the specified operand before it is turned into an undef.
135 ///
136 Value *AddSoonDeadInstToWorklist(Instruction &I, unsigned op) {
137 Value *R = I.getOperand(op);
138
Gabor Greiff6d8e772008-06-12 21:37:33 +0000139 for (User::op_iterator i = I.op_begin(), e = I.op_end(); i != e; ++i)
140 if (Instruction *Op = dyn_cast<Instruction>(*i)) {
Chris Lattnerb15e2b12007-03-02 21:28:56 +0000141 AddToWorkList(Op);
Chris Lattner2deeaea2006-10-05 06:55:50 +0000142 // Set the operand to undef to drop the use.
Gabor Greiff6d8e772008-06-12 21:37:33 +0000143 *i = UndefValue::get(Op->getType());
Chris Lattner2deeaea2006-10-05 06:55:50 +0000144 }
145
146 return R;
147 }
Chris Lattner51ea1272004-02-28 05:22:00 +0000148
Chris Lattner260ab202002-04-18 17:39:14 +0000149 public:
Chris Lattner113f4f42002-06-25 16:13:24 +0000150 virtual bool runOnFunction(Function &F);
Chris Lattner960a5432007-03-03 02:04:50 +0000151
152 bool DoOneIteration(Function &F, unsigned ItNum);
Chris Lattner260ab202002-04-18 17:39:14 +0000153
Chris Lattnerf12cc842002-04-28 21:27:06 +0000154 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Chris Lattnerf4ad1652003-11-02 05:57:39 +0000155 AU.addRequired<TargetData>();
Owen Andersona6968f82006-07-10 19:03:49 +0000156 AU.addPreservedID(LCSSAID);
Chris Lattner820d9712002-10-21 20:00:28 +0000157 AU.setPreservesCFG();
Chris Lattnerf12cc842002-04-28 21:27:06 +0000158 }
159
Chris Lattner69193f92004-04-05 01:30:19 +0000160 TargetData &getTargetData() const { return *TD; }
161
Chris Lattner260ab202002-04-18 17:39:14 +0000162 // Visitation implementation - Implement instruction combining for different
163 // instruction types. The semantics are as follows:
164 // Return Value:
165 // null - No change was made
Chris Lattnere6794492002-08-12 21:17:25 +0000166 // I - Change was made, I is still valid, I may be dead though
Chris Lattner260ab202002-04-18 17:39:14 +0000167 // otherwise - Change was made, replace I with returned instruction
Misha Brukmanb1c93172005-04-21 23:48:37 +0000168 //
Chris Lattner113f4f42002-06-25 16:13:24 +0000169 Instruction *visitAdd(BinaryOperator &I);
170 Instruction *visitSub(BinaryOperator &I);
171 Instruction *visitMul(BinaryOperator &I);
Reid Spencer7eb55b32006-11-02 01:53:59 +0000172 Instruction *visitURem(BinaryOperator &I);
173 Instruction *visitSRem(BinaryOperator &I);
174 Instruction *visitFRem(BinaryOperator &I);
Chris Lattner16395e52008-07-14 00:15:52 +0000175 bool SimplifyDivRemOfSelect(BinaryOperator &I);
Reid Spencer7eb55b32006-11-02 01:53:59 +0000176 Instruction *commonRemTransforms(BinaryOperator &I);
177 Instruction *commonIRemTransforms(BinaryOperator &I);
Reid Spencer7e80b0b2006-10-26 06:15:43 +0000178 Instruction *commonDivTransforms(BinaryOperator &I);
179 Instruction *commonIDivTransforms(BinaryOperator &I);
180 Instruction *visitUDiv(BinaryOperator &I);
181 Instruction *visitSDiv(BinaryOperator &I);
182 Instruction *visitFDiv(BinaryOperator &I);
Chris Lattner269cbd52008-11-16 05:06:21 +0000183 Instruction *FoldAndOfICmps(Instruction &I, ICmpInst *LHS, ICmpInst *RHS);
Chris Lattner113f4f42002-06-25 16:13:24 +0000184 Instruction *visitAnd(BinaryOperator &I);
Chris Lattnerd397fef2008-11-16 05:20:07 +0000185 Instruction *FoldOrOfICmps(Instruction &I, ICmpInst *LHS, ICmpInst *RHS);
Chris Lattner113f4f42002-06-25 16:13:24 +0000186 Instruction *visitOr (BinaryOperator &I);
187 Instruction *visitXor(BinaryOperator &I);
Reid Spencer2341c222007-02-02 02:16:23 +0000188 Instruction *visitShl(BinaryOperator &I);
189 Instruction *visitAShr(BinaryOperator &I);
190 Instruction *visitLShr(BinaryOperator &I);
191 Instruction *commonShiftTransforms(BinaryOperator &I);
Chris Lattner5920a782008-05-19 20:18:56 +0000192 Instruction *FoldFCmp_IntToFP_Cst(FCmpInst &I, Instruction *LHSI,
193 Constant *RHSC);
Reid Spencer266e42b2006-12-23 06:05:41 +0000194 Instruction *visitFCmpInst(FCmpInst &I);
195 Instruction *visitICmpInst(ICmpInst &I);
196 Instruction *visitICmpInstWithCastAndCast(ICmpInst &ICI);
Chris Lattnera74deaf2007-04-03 17:43:25 +0000197 Instruction *visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
198 Instruction *LHS,
199 ConstantInt *RHS);
Chris Lattner3bbec592007-06-20 23:46:26 +0000200 Instruction *FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
201 ConstantInt *DivRHS);
Chris Lattnerd1f46d32005-04-24 06:59:08 +0000202
Reid Spencer266e42b2006-12-23 06:05:41 +0000203 Instruction *FoldGEPICmp(User *GEPLHS, Value *RHS,
204 ICmpInst::Predicate Cond, Instruction &I);
Reid Spencere0fc4df2006-10-20 07:07:24 +0000205 Instruction *FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
Reid Spencer2341c222007-02-02 02:16:23 +0000206 BinaryOperator &I);
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000207 Instruction *commonCastTransforms(CastInst &CI);
208 Instruction *commonIntCastTransforms(CastInst &CI);
Chris Lattner1db224d2007-04-27 17:44:50 +0000209 Instruction *commonPointerCastTransforms(CastInst &CI);
Chris Lattner74ff60f2007-04-11 06:57:46 +0000210 Instruction *visitTrunc(TruncInst &CI);
211 Instruction *visitZExt(ZExtInst &CI);
212 Instruction *visitSExt(SExtInst &CI);
Chris Lattnerfa1e7ee2008-01-27 05:29:54 +0000213 Instruction *visitFPTrunc(FPTruncInst &CI);
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000214 Instruction *visitFPExt(CastInst &CI);
Chris Lattnere35fe0f2008-05-19 20:25:04 +0000215 Instruction *visitFPToUI(FPToUIInst &FI);
216 Instruction *visitFPToSI(FPToSIInst &FI);
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000217 Instruction *visitUIToFP(CastInst &CI);
218 Instruction *visitSIToFP(CastInst &CI);
219 Instruction *visitPtrToInt(CastInst &CI);
Chris Lattner2940c5c2008-01-08 07:23:51 +0000220 Instruction *visitIntToPtr(IntToPtrInst &CI);
Chris Lattner1db224d2007-04-27 17:44:50 +0000221 Instruction *visitBitCast(BitCastInst &CI);
Chris Lattner411336f2005-01-19 21:50:18 +0000222 Instruction *FoldSelectOpOp(SelectInst &SI, Instruction *TI,
223 Instruction *FI);
Dan Gohmandafa9c62008-09-16 18:46:06 +0000224 Instruction *visitSelectInst(SelectInst &SI);
225 Instruction *visitSelectInstWithICmp(SelectInst &SI, ICmpInst *ICI);
Chris Lattner970c33a2003-06-19 17:00:31 +0000226 Instruction *visitCallInst(CallInst &CI);
227 Instruction *visitInvokeInst(InvokeInst &II);
Chris Lattner113f4f42002-06-25 16:13:24 +0000228 Instruction *visitPHINode(PHINode &PN);
229 Instruction *visitGetElementPtrInst(GetElementPtrInst &GEP);
Chris Lattner1085bdf2002-11-04 16:18:53 +0000230 Instruction *visitAllocationInst(AllocationInst &AI);
Chris Lattner8427bff2003-12-07 01:24:23 +0000231 Instruction *visitFreeInst(FreeInst &FI);
Chris Lattner0f1d8a32003-06-26 05:06:25 +0000232 Instruction *visitLoadInst(LoadInst &LI);
Chris Lattner31f486c2005-01-31 05:36:43 +0000233 Instruction *visitStoreInst(StoreInst &SI);
Chris Lattner9eef8a72003-06-04 04:46:00 +0000234 Instruction *visitBranchInst(BranchInst &BI);
Chris Lattner4c9c20a2004-07-03 00:26:11 +0000235 Instruction *visitSwitchInst(SwitchInst &SI);
Chris Lattner39fac442006-04-15 01:39:45 +0000236 Instruction *visitInsertElementInst(InsertElementInst &IE);
Robert Bocchinoa8352962006-01-13 22:48:06 +0000237 Instruction *visitExtractElementInst(ExtractElementInst &EI);
Chris Lattnerfbb77a42006-04-10 22:45:52 +0000238 Instruction *visitShuffleVectorInst(ShuffleVectorInst &SVI);
Matthijs Kooijmanb2fc72b2008-06-11 14:05:05 +0000239 Instruction *visitExtractValueInst(ExtractValueInst &EV);
Chris Lattner260ab202002-04-18 17:39:14 +0000240
241 // visitInstruction - Specify what to return for unhandled instructions...
Chris Lattner113f4f42002-06-25 16:13:24 +0000242 Instruction *visitInstruction(Instruction &I) { return 0; }
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000243
Chris Lattner970c33a2003-06-19 17:00:31 +0000244 private:
Chris Lattneraec3d942003-10-07 22:32:43 +0000245 Instruction *visitCallSite(CallSite CS);
Chris Lattner970c33a2003-06-19 17:00:31 +0000246 bool transformConstExprCastCall(CallSite CS);
Duncan Sands6d5da712007-09-17 10:26:40 +0000247 Instruction *transformCallThroughTrampoline(CallSite CS);
Evan Chengc3cf9f82008-03-24 00:21:34 +0000248 Instruction *transformZExtICmp(ICmpInst *ICI, Instruction &CI,
249 bool DoXform = true);
Chris Lattner7ac943f2008-05-20 05:46:13 +0000250 bool WillNotOverflowSignedAdd(Value *LHS, Value *RHS);
Chris Lattner970c33a2003-06-19 17:00:31 +0000251
Chris Lattner69193f92004-04-05 01:30:19 +0000252 public:
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000253 // InsertNewInstBefore - insert an instruction New before instruction Old
254 // in the program. Add the new instruction to the worklist.
255 //
Chris Lattner623826c2004-09-28 21:48:02 +0000256 Instruction *InsertNewInstBefore(Instruction *New, Instruction &Old) {
Chris Lattner65217ff2002-08-23 18:32:43 +0000257 assert(New && New->getParent() == 0 &&
258 "New instruction already inserted into a basic block!");
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000259 BasicBlock *BB = Old.getParent();
260 BB->getInstList().insert(&Old, New); // Insert inst
Chris Lattnerb15e2b12007-03-02 21:28:56 +0000261 AddToWorkList(New);
Chris Lattnere79e8542004-02-23 06:38:22 +0000262 return New;
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000263 }
264
Chris Lattner7e794272004-09-24 15:21:34 +0000265 /// InsertCastBefore - Insert a cast of V to TY before the instruction POS.
266 /// This also adds the cast to the worklist. Finally, this returns the
267 /// cast.
Reid Spencer13bc5d72006-12-12 09:18:51 +0000268 Value *InsertCastBefore(Instruction::CastOps opc, Value *V, const Type *Ty,
269 Instruction &Pos) {
Chris Lattner7e794272004-09-24 15:21:34 +0000270 if (V->getType() == Ty) return V;
Misha Brukmanb1c93172005-04-21 23:48:37 +0000271
Chris Lattnere79d2492006-04-06 19:19:17 +0000272 if (Constant *CV = dyn_cast<Constant>(V))
Reid Spencer13bc5d72006-12-12 09:18:51 +0000273 return ConstantExpr::getCast(opc, CV, Ty);
Chris Lattnere79d2492006-04-06 19:19:17 +0000274
Gabor Greife1f6e4b2008-05-16 19:29:10 +0000275 Instruction *C = CastInst::Create(opc, V, Ty, V->getName(), &Pos);
Chris Lattnerb15e2b12007-03-02 21:28:56 +0000276 AddToWorkList(C);
Chris Lattner7e794272004-09-24 15:21:34 +0000277 return C;
278 }
Chris Lattner5a866122008-01-13 22:23:22 +0000279
280 Value *InsertBitCastBefore(Value *V, const Type *Ty, Instruction &Pos) {
281 return InsertCastBefore(Instruction::BitCast, V, Ty, Pos);
282 }
283
Chris Lattner7e794272004-09-24 15:21:34 +0000284
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000285 // ReplaceInstUsesWith - This method is to be used when an instruction is
286 // found to be dead, replacable with another preexisting expression. Here
287 // we add all uses of I to the worklist, replace all uses of I with the new
288 // value, then return I, so that the inst combiner will know that I was
289 // modified.
290 //
291 Instruction *ReplaceInstUsesWith(Instruction &I, Value *V) {
Chris Lattner51ea1272004-02-28 05:22:00 +0000292 AddUsersToWorkList(I); // Add all modified instrs to worklist
Chris Lattner8953b902004-04-05 02:10:19 +0000293 if (&I != V) {
294 I.replaceAllUsesWith(V);
295 return &I;
296 } else {
297 // If we are replacing the instruction with itself, this must be in a
298 // segment of unreachable code, so just clobber the instruction.
Chris Lattner8ba9ec92004-10-18 02:59:09 +0000299 I.replaceAllUsesWith(UndefValue::get(I.getType()));
Chris Lattner8953b902004-04-05 02:10:19 +0000300 return &I;
301 }
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000302 }
Chris Lattner51ea1272004-02-28 05:22:00 +0000303
Chris Lattner2590e512006-02-07 06:56:34 +0000304 // UpdateValueUsesWith - This method is to be used when an value is
305 // found to be replacable with another preexisting expression or was
306 // updated. Here we add all uses of I to the worklist, replace all uses of
307 // I with the new value (unless the instruction was just updated), then
308 // return true, so that the inst combiner will know that I was modified.
309 //
310 bool UpdateValueUsesWith(Value *Old, Value *New) {
311 AddUsersToWorkList(*Old); // Add all modified instrs to worklist
312 if (Old != New)
313 Old->replaceAllUsesWith(New);
314 if (Instruction *I = dyn_cast<Instruction>(Old))
Chris Lattnerb15e2b12007-03-02 21:28:56 +0000315 AddToWorkList(I);
Chris Lattner5b2edb12006-02-12 08:02:11 +0000316 if (Instruction *I = dyn_cast<Instruction>(New))
Chris Lattnerb15e2b12007-03-02 21:28:56 +0000317 AddToWorkList(I);
Chris Lattner2590e512006-02-07 06:56:34 +0000318 return true;
319 }
320
Chris Lattner51ea1272004-02-28 05:22:00 +0000321 // EraseInstFromFunction - When dealing with an instruction that has side
322 // effects or produces a void value, we can't rely on DCE to delete the
323 // instruction. Instead, visit methods should return the value returned by
324 // this function.
325 Instruction *EraseInstFromFunction(Instruction &I) {
326 assert(I.use_empty() && "Cannot erase instruction that is used!");
327 AddUsesToWorkList(I);
Chris Lattnerb15e2b12007-03-02 21:28:56 +0000328 RemoveFromWorkList(&I);
Chris Lattner95307542004-11-18 21:41:39 +0000329 I.eraseFromParent();
Chris Lattner51ea1272004-02-28 05:22:00 +0000330 return 0; // Don't do anything with FI
331 }
Chris Lattner965c7692008-06-02 01:18:21 +0000332
333 void ComputeMaskedBits(Value *V, const APInt &Mask, APInt &KnownZero,
334 APInt &KnownOne, unsigned Depth = 0) const {
335 return llvm::ComputeMaskedBits(V, Mask, KnownZero, KnownOne, TD, Depth);
336 }
337
338 bool MaskedValueIsZero(Value *V, const APInt &Mask,
339 unsigned Depth = 0) const {
340 return llvm::MaskedValueIsZero(V, Mask, TD, Depth);
341 }
342 unsigned ComputeNumSignBits(Value *Op, unsigned Depth = 0) const {
343 return llvm::ComputeNumSignBits(Op, TD, Depth);
344 }
Chris Lattner51ea1272004-02-28 05:22:00 +0000345
Chris Lattner3ac7c262003-08-13 20:16:26 +0000346 private:
Chris Lattnerdfae8be2003-07-24 17:35:25 +0000347
Reid Spencer266e42b2006-12-23 06:05:41 +0000348 /// SimplifyCommutative - This performs a few simplifications for
349 /// commutative operators.
Chris Lattner7fb29e12003-03-11 00:12:48 +0000350 bool SimplifyCommutative(BinaryOperator &I);
Chris Lattnerba1cb382003-09-19 17:17:26 +0000351
Reid Spencer266e42b2006-12-23 06:05:41 +0000352 /// SimplifyCompare - This reorders the operands of a CmpInst to get them in
353 /// most-complex to least-complex order.
354 bool SimplifyCompare(CmpInst &I);
355
Reid Spencer959a21d2007-03-23 21:24:59 +0000356 /// SimplifyDemandedBits - Attempts to replace V with a simpler value based
357 /// on the demanded bits.
Reid Spencer1791f232007-03-12 17:25:59 +0000358 bool SimplifyDemandedBits(Value *V, APInt DemandedMask,
359 APInt& KnownZero, APInt& KnownOne,
360 unsigned Depth = 0);
361
Chris Lattner2deeaea2006-10-05 06:55:50 +0000362 Value *SimplifyDemandedVectorElts(Value *V, uint64_t DemandedElts,
363 uint64_t &UndefElts, unsigned Depth = 0);
364
Chris Lattner6a4adcd2004-09-29 05:07:12 +0000365 // FoldOpIntoPhi - Given a binary operator or cast instruction which has a
366 // PHI node as operand #0, see if we can fold the instruction into the PHI
367 // (which is only possible if all operands to the PHI are constants).
368 Instruction *FoldOpIntoPhi(Instruction &I);
369
Chris Lattner7515cab2004-11-14 19:13:23 +0000370 // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
371 // operator and they all are only used by the PHI, PHI together their
372 // inputs, and do the operation once, to the result of the PHI.
373 Instruction *FoldPHIArgOpIntoPHI(PHINode &PN);
Chris Lattnercadac0c2006-11-01 04:51:18 +0000374 Instruction *FoldPHIArgBinOpIntoPHI(PHINode &PN);
375
376
Zhou Sheng75b871f2007-01-11 12:24:14 +0000377 Instruction *OptAndOp(Instruction *Op, ConstantInt *OpRHS,
378 ConstantInt *AndRHS, BinaryOperator &TheAnd);
Chris Lattneraf517572005-09-18 04:24:45 +0000379
Zhou Sheng75b871f2007-01-11 12:24:14 +0000380 Value *FoldLogicalPlusAnd(Value *LHS, Value *RHS, ConstantInt *Mask,
Chris Lattneraf517572005-09-18 04:24:45 +0000381 bool isSub, Instruction &I);
Chris Lattner6862fbd2004-09-29 17:40:11 +0000382 Instruction *InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
Reid Spencer266e42b2006-12-23 06:05:41 +0000383 bool isSigned, bool Inside, Instruction &IB);
Chris Lattner1db224d2007-04-27 17:44:50 +0000384 Instruction *PromoteCastOfAllocation(BitCastInst &CI, AllocationInst &AI);
Chris Lattnerc482a9e2006-06-15 19:07:26 +0000385 Instruction *MatchBSwap(BinaryOperator &I);
Chris Lattner14a251b2007-04-15 00:07:55 +0000386 bool SimplifyStoreAtEndOfBlock(StoreInst &SI);
Chris Lattner57974c82008-01-13 23:50:23 +0000387 Instruction *SimplifyMemTransfer(MemIntrinsic *MI);
Chris Lattner2dc44262008-04-30 06:39:11 +0000388 Instruction *SimplifyMemSet(MemSetInst *MI);
Chris Lattner57974c82008-01-13 23:50:23 +0000389
Chris Lattnerc482a9e2006-06-15 19:07:26 +0000390
Reid Spencer74a528b2006-12-13 18:21:21 +0000391 Value *EvaluateInDifferentType(Value *V, const Type *Ty, bool isSigned);
Dan Gohman99b7b3f2008-04-10 18:43:06 +0000392
Dan Gohman99b7b3f2008-04-10 18:43:06 +0000393 bool CanEvaluateInDifferentType(Value *V, const IntegerType *Ty,
394 unsigned CastOpc,
395 int &NumCastsRemoved);
396 unsigned GetOrEnforceKnownAlignment(Value *V,
397 unsigned PrefAlign = 0);
Matthijs Kooijmanb2fc72b2008-06-11 14:05:05 +0000398
Chris Lattner260ab202002-04-18 17:39:14 +0000399 };
400}
401
Dan Gohmand78c4002008-05-13 00:00:25 +0000402char InstCombiner::ID = 0;
403static RegisterPass<InstCombiner>
404X("instcombine", "Combine redundant instructions");
405
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000406// getComplexity: Assign a complexity or rank value to LLVM Values...
Chris Lattner81a7a232004-10-16 18:11:37 +0000407// 0 -> undef, 1 -> Const, 2 -> Other, 3 -> Arg, 3 -> Unary, 4 -> OtherInst
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000408static unsigned getComplexity(Value *V) {
409 if (isa<Instruction>(V)) {
410 if (BinaryOperator::isNeg(V) || BinaryOperator::isNot(V))
Chris Lattner81a7a232004-10-16 18:11:37 +0000411 return 3;
412 return 4;
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000413 }
Chris Lattner81a7a232004-10-16 18:11:37 +0000414 if (isa<Argument>(V)) return 3;
415 return isa<Constant>(V) ? (isa<UndefValue>(V) ? 0 : 1) : 2;
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000416}
Chris Lattner260ab202002-04-18 17:39:14 +0000417
Chris Lattner7fb29e12003-03-11 00:12:48 +0000418// isOnlyUse - Return true if this instruction will be deleted if we stop using
419// it.
420static bool isOnlyUse(Value *V) {
Chris Lattnerf95d9b92003-10-15 16:48:29 +0000421 return V->hasOneUse() || isa<Constant>(V);
Chris Lattner7fb29e12003-03-11 00:12:48 +0000422}
423
Chris Lattnere79e8542004-02-23 06:38:22 +0000424// getPromotedType - Return the specified type promoted as it would be to pass
425// though a va_arg area...
426static const Type *getPromotedType(const Type *Ty) {
Reid Spencer7a9c62b2007-01-12 07:05:14 +0000427 if (const IntegerType* ITy = dyn_cast<IntegerType>(Ty)) {
428 if (ITy->getBitWidth() < 32)
429 return Type::Int32Ty;
Chris Lattnerf79577d2007-05-23 01:17:04 +0000430 }
Reid Spencer7a9c62b2007-01-12 07:05:14 +0000431 return Ty;
Chris Lattnere79e8542004-02-23 06:38:22 +0000432}
433
Matthijs Kooijmanf7d3cb52008-10-13 15:17:01 +0000434/// getBitCastOperand - If the specified operand is a CastInst, a constant
435/// expression bitcast, or a GetElementPtrInst with all zero indices, return the
436/// operand value, otherwise return null.
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000437static Value *getBitCastOperand(Value *V) {
438 if (BitCastInst *I = dyn_cast<BitCastInst>(V))
Matthijs Kooijmanf7d3cb52008-10-13 15:17:01 +0000439 // BitCastInst?
Chris Lattner567b81f2005-09-13 00:40:14 +0000440 return I->getOperand(0);
Matthijs Kooijmanf7d3cb52008-10-13 15:17:01 +0000441 else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(V)) {
442 // GetElementPtrInst?
443 if (GEP->hasAllZeroIndices())
444 return GEP->getOperand(0);
445 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V)) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000446 if (CE->getOpcode() == Instruction::BitCast)
Matthijs Kooijmanf7d3cb52008-10-13 15:17:01 +0000447 // BitCast ConstantExp?
Chris Lattner567b81f2005-09-13 00:40:14 +0000448 return CE->getOperand(0);
Matthijs Kooijmanf7d3cb52008-10-13 15:17:01 +0000449 else if (CE->getOpcode() == Instruction::GetElementPtr) {
450 // GetElementPtr ConstantExp?
451 for (User::op_iterator I = CE->op_begin() + 1, E = CE->op_end();
452 I != E; ++I) {
453 ConstantInt *CI = dyn_cast<ConstantInt>(I);
454 if (!CI || !CI->isZero())
455 // Any non-zero indices? Not cast-like.
456 return 0;
457 }
458 // All-zero indices? This is just like casting.
459 return CE->getOperand(0);
460 }
461 }
Chris Lattner567b81f2005-09-13 00:40:14 +0000462 return 0;
463}
464
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000465/// This function is a wrapper around CastInst::isEliminableCastPair. It
466/// simply extracts arguments and returns what that function returns.
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000467static Instruction::CastOps
468isEliminableCastPair(
469 const CastInst *CI, ///< The first cast instruction
470 unsigned opcode, ///< The opcode of the second cast instruction
471 const Type *DstTy, ///< The target type for the second cast instruction
472 TargetData *TD ///< The target data for pointer size
473) {
474
475 const Type *SrcTy = CI->getOperand(0)->getType(); // A from above
476 const Type *MidTy = CI->getType(); // B from above
Chris Lattner1d441ad2006-05-06 09:00:16 +0000477
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000478 // Get the opcodes of the two Cast instructions
479 Instruction::CastOps firstOp = Instruction::CastOps(CI->getOpcode());
480 Instruction::CastOps secondOp = Instruction::CastOps(opcode);
Chris Lattner1d441ad2006-05-06 09:00:16 +0000481
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000482 return Instruction::CastOps(
483 CastInst::isEliminableCastPair(firstOp, secondOp, SrcTy, MidTy,
484 DstTy, TD->getIntPtrType()));
Chris Lattner1d441ad2006-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 Spencer266e42b2006-12-23 06:05:41 +0000490static bool ValueRequiresCast(Instruction::CastOps opcode, const Value *V,
491 const Type *Ty, TargetData *TD) {
Chris Lattner1d441ad2006-05-06 09:00:16 +0000492 if (V->getType() == Ty || isa<Constant>(V)) return false;
493
Chris Lattner99155be2006-05-25 23:24:33 +0000494 // If this is another cast that can be eliminated, it isn't codegen either.
Chris Lattner1d441ad2006-05-06 09:00:16 +0000495 if (const CastInst *CI = dyn_cast<CastInst>(V))
Reid Spencer266e42b2006-12-23 06:05:41 +0000496 if (isEliminableCastPair(CI, opcode, Ty, TD))
Chris Lattner1d441ad2006-05-06 09:00:16 +0000497 return false;
498 return true;
499}
500
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000501// SimplifyCommutative - This performs a few simplifications for commutative
502// operators:
Chris Lattner260ab202002-04-18 17:39:14 +0000503//
Chris Lattnerdcf240a2003-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 Lattner7fb29e12003-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 Lattnerdcf240a2003-03-10 21:43:22 +0000510//
Chris Lattner7fb29e12003-03-11 00:12:48 +0000511bool InstCombiner::SimplifyCommutative(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000512 bool Changed = false;
513 if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1)))
514 Changed = !I.swapOperands();
Misha Brukmanb1c93172005-04-21 23:48:37 +0000515
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000516 if (!I.isAssociative()) return Changed;
517 Instruction::BinaryOps Opcode = I.getOpcode();
Chris Lattner7fb29e12003-03-11 00:12:48 +0000518 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(I.getOperand(0)))
519 if (Op->getOpcode() == Opcode && isa<Constant>(Op->getOperand(1))) {
520 if (isa<Constant>(I.getOperand(1))) {
Chris Lattner34428442003-05-27 16:40:51 +0000521 Constant *Folded = ConstantExpr::get(I.getOpcode(),
522 cast<Constant>(I.getOperand(1)),
523 cast<Constant>(Op->getOperand(1)));
Chris Lattner7fb29e12003-03-11 00:12:48 +0000524 I.setOperand(0, Op->getOperand(0));
525 I.setOperand(1, Folded);
526 return true;
527 } else if (BinaryOperator *Op1=dyn_cast<BinaryOperator>(I.getOperand(1)))
528 if (Op1->getOpcode() == Opcode && isa<Constant>(Op1->getOperand(1)) &&
529 isOnlyUse(Op) && isOnlyUse(Op1)) {
530 Constant *C1 = cast<Constant>(Op->getOperand(1));
531 Constant *C2 = cast<Constant>(Op1->getOperand(1));
532
533 // Fold (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Chris Lattner34428442003-05-27 16:40:51 +0000534 Constant *Folded = ConstantExpr::get(I.getOpcode(), C1, C2);
Gabor Greife1f6e4b2008-05-16 19:29:10 +0000535 Instruction *New = BinaryOperator::Create(Opcode, Op->getOperand(0),
Chris Lattner7fb29e12003-03-11 00:12:48 +0000536 Op1->getOperand(0),
537 Op1->getName(), &I);
Chris Lattnerb15e2b12007-03-02 21:28:56 +0000538 AddToWorkList(New);
Chris Lattner7fb29e12003-03-11 00:12:48 +0000539 I.setOperand(0, New);
540 I.setOperand(1, Folded);
541 return true;
Misha Brukmanb1c93172005-04-21 23:48:37 +0000542 }
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000543 }
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000544 return Changed;
Chris Lattner260ab202002-04-18 17:39:14 +0000545}
Chris Lattnerca081252001-12-14 16:52:21 +0000546
Reid Spencer266e42b2006-12-23 06:05:41 +0000547/// SimplifyCompare - For a CmpInst this function just orders the operands
548/// so that theyare listed from right (least complex) to left (most complex).
549/// This puts constants before unary operators before binary operators.
550bool InstCombiner::SimplifyCompare(CmpInst &I) {
551 if (getComplexity(I.getOperand(0)) >= getComplexity(I.getOperand(1)))
552 return false;
553 I.swapOperands();
554 // Compare instructions are not associative so there's nothing else we can do.
555 return true;
556}
557
Chris Lattnerbb74e222003-03-10 23:06:50 +0000558// dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
559// if the LHS is a constant zero (which is the 'negate' form).
Chris Lattner9fa53de2002-05-06 16:49:18 +0000560//
Chris Lattnerbb74e222003-03-10 23:06:50 +0000561static inline Value *dyn_castNegVal(Value *V) {
562 if (BinaryOperator::isNeg(V))
Chris Lattnerd6f636a2005-04-24 07:30:14 +0000563 return BinaryOperator::getNegArgument(V);
Chris Lattnerbb74e222003-03-10 23:06:50 +0000564
Chris Lattner9ad0d552004-12-14 20:08:06 +0000565 // Constants can be considered to be negated values if they can be folded.
566 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
567 return ConstantExpr::getNeg(C);
Nick Lewycky3bf55122008-05-23 04:54:45 +0000568
569 if (ConstantVector *C = dyn_cast<ConstantVector>(V))
570 if (C->getType()->getElementType()->isInteger())
571 return ConstantExpr::getNeg(C);
572
Chris Lattnerbb74e222003-03-10 23:06:50 +0000573 return 0;
Chris Lattner9fa53de2002-05-06 16:49:18 +0000574}
575
Chris Lattnerbb74e222003-03-10 23:06:50 +0000576static inline Value *dyn_castNotVal(Value *V) {
577 if (BinaryOperator::isNot(V))
Chris Lattnerd6f636a2005-04-24 07:30:14 +0000578 return BinaryOperator::getNotArgument(V);
Chris Lattnerbb74e222003-03-10 23:06:50 +0000579
580 // Constants can be considered to be not'ed values...
Zhou Sheng75b871f2007-01-11 12:24:14 +0000581 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
Zhou Sheng9bc8ab12007-04-02 13:45:30 +0000582 return ConstantInt::get(~C->getValue());
Chris Lattnerbb74e222003-03-10 23:06:50 +0000583 return 0;
584}
585
Chris Lattner7fb29e12003-03-11 00:12:48 +0000586// dyn_castFoldableMul - If this value is a multiply that can be folded into
587// other computations (because it has a constant operand), return the
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000588// non-constant operand of the multiply, and set CST to point to the multiplier.
589// Otherwise, return null.
Chris Lattner7fb29e12003-03-11 00:12:48 +0000590//
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000591static inline Value *dyn_castFoldableMul(Value *V, ConstantInt *&CST) {
Chris Lattner03c49532007-01-15 02:27:26 +0000592 if (V->hasOneUse() && V->getType()->isInteger())
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000593 if (Instruction *I = dyn_cast<Instruction>(V)) {
Chris Lattner7fb29e12003-03-11 00:12:48 +0000594 if (I->getOpcode() == Instruction::Mul)
Chris Lattner970136362004-11-15 05:54:07 +0000595 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1))))
Chris Lattner7fb29e12003-03-11 00:12:48 +0000596 return I->getOperand(0);
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000597 if (I->getOpcode() == Instruction::Shl)
Chris Lattner970136362004-11-15 05:54:07 +0000598 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1)))) {
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000599 // The multiplier is really 1 << CST.
Zhou Sheng4961cf12007-03-29 01:57:21 +0000600 uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
Zhou Shengb25806f2007-03-30 09:29:48 +0000601 uint32_t CSTVal = CST->getLimitedValue(BitWidth);
Zhou Sheng4961cf12007-03-29 01:57:21 +0000602 CST = ConstantInt::get(APInt(BitWidth, 1).shl(CSTVal));
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000603 return I->getOperand(0);
604 }
605 }
Chris Lattner7fb29e12003-03-11 00:12:48 +0000606 return 0;
Chris Lattner3082c5a2003-02-18 19:28:33 +0000607}
Chris Lattner31ae8632002-08-14 17:51:49 +0000608
Chris Lattner0798af32005-01-13 20:14:25 +0000609/// dyn_castGetElementPtr - If this is a getelementptr instruction or constant
610/// expression, return it.
611static User *dyn_castGetElementPtr(Value *V) {
612 if (isa<GetElementPtrInst>(V)) return cast<User>(V);
613 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
614 if (CE->getOpcode() == Instruction::GetElementPtr)
615 return cast<User>(V);
616 return false;
617}
618
Dan Gohman99b7b3f2008-04-10 18:43:06 +0000619/// getOpcode - If this is an Instruction or a ConstantExpr, return the
620/// opcode value. Otherwise return UserOp1.
Dan Gohman86ff8532008-05-29 19:53:46 +0000621static unsigned getOpcode(const Value *V) {
622 if (const Instruction *I = dyn_cast<Instruction>(V))
Dan Gohman99b7b3f2008-04-10 18:43:06 +0000623 return I->getOpcode();
Dan Gohman86ff8532008-05-29 19:53:46 +0000624 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
Dan Gohman99b7b3f2008-04-10 18:43:06 +0000625 return CE->getOpcode();
626 // Use UserOp1 to mean there's no opcode.
627 return Instruction::UserOp1;
628}
629
Reid Spencer80263aa2007-03-25 05:33:51 +0000630/// AddOne - Add one to a ConstantInt
Chris Lattner6862fbd2004-09-29 17:40:11 +0000631static ConstantInt *AddOne(ConstantInt *C) {
Reid Spencer624766f2007-03-25 19:55:33 +0000632 APInt Val(C->getValue());
633 return ConstantInt::get(++Val);
Chris Lattner623826c2004-09-28 21:48:02 +0000634}
Reid Spencer80263aa2007-03-25 05:33:51 +0000635/// SubOne - Subtract one from a ConstantInt
Chris Lattner6862fbd2004-09-29 17:40:11 +0000636static ConstantInt *SubOne(ConstantInt *C) {
Reid Spencer624766f2007-03-25 19:55:33 +0000637 APInt Val(C->getValue());
638 return ConstantInt::get(--Val);
Reid Spencer80263aa2007-03-25 05:33:51 +0000639}
640/// Add - Add two ConstantInts together
641static ConstantInt *Add(ConstantInt *C1, ConstantInt *C2) {
642 return ConstantInt::get(C1->getValue() + C2->getValue());
643}
644/// And - Bitwise AND two ConstantInts together
645static ConstantInt *And(ConstantInt *C1, ConstantInt *C2) {
646 return ConstantInt::get(C1->getValue() & C2->getValue());
647}
648/// Subtract - Subtract one ConstantInt from another
649static ConstantInt *Subtract(ConstantInt *C1, ConstantInt *C2) {
650 return ConstantInt::get(C1->getValue() - C2->getValue());
651}
652/// Multiply - Multiply two ConstantInts together
653static ConstantInt *Multiply(ConstantInt *C1, ConstantInt *C2) {
654 return ConstantInt::get(C1->getValue() * C2->getValue());
Chris Lattner623826c2004-09-28 21:48:02 +0000655}
Nick Lewyckyfefd0202008-02-18 22:48:05 +0000656/// MultiplyOverflows - True if the multiply can not be expressed in an int
657/// this size.
658static bool MultiplyOverflows(ConstantInt *C1, ConstantInt *C2, bool sign) {
659 uint32_t W = C1->getBitWidth();
660 APInt LHSExt = C1->getValue(), RHSExt = C2->getValue();
661 if (sign) {
662 LHSExt.sext(W * 2);
663 RHSExt.sext(W * 2);
664 } else {
665 LHSExt.zext(W * 2);
666 RHSExt.zext(W * 2);
667 }
668
669 APInt MulExt = LHSExt * RHSExt;
670
671 if (sign) {
672 APInt Min = APInt::getSignedMinValue(W).sext(W * 2);
673 APInt Max = APInt::getSignedMaxValue(W).sext(W * 2);
674 return MulExt.slt(Min) || MulExt.sgt(Max);
675 } else
676 return MulExt.ugt(APInt::getLowBitsSet(W * 2, W));
677}
Chris Lattner623826c2004-09-28 21:48:02 +0000678
Reid Spencerbb5741f2007-03-08 01:52:58 +0000679
Chris Lattner0157e7f2006-02-11 09:31:47 +0000680/// ShrinkDemandedConstant - Check to see if the specified operand of the
681/// specified instruction is a constant integer. If so, check to see if there
682/// are any bits set in the constant that are not demanded. If so, shrink the
683/// constant and return true.
684static bool ShrinkDemandedConstant(Instruction *I, unsigned OpNo,
Reid Spencerd9281782007-03-12 17:15:10 +0000685 APInt Demanded) {
686 assert(I && "No instruction?");
687 assert(OpNo < I->getNumOperands() && "Operand index too large");
688
689 // If the operand is not a constant integer, nothing to do.
690 ConstantInt *OpC = dyn_cast<ConstantInt>(I->getOperand(OpNo));
691 if (!OpC) return false;
692
693 // If there are no bits set that aren't demanded, nothing to do.
694 Demanded.zextOrTrunc(OpC->getValue().getBitWidth());
695 if ((~Demanded & OpC->getValue()) == 0)
696 return false;
697
698 // This instruction is producing bits that are not demanded. Shrink the RHS.
699 Demanded &= OpC->getValue();
700 I->setOperand(OpNo, ConstantInt::get(Demanded));
701 return true;
702}
703
Chris Lattneree0f2802006-02-12 02:07:56 +0000704// ComputeSignedMinMaxValuesFromKnownBits - Given a signed integer type and a
705// set of known zero and one bits, compute the maximum and minimum values that
706// could have the specified known zero and known one bits, returning them in
707// min/max.
708static void ComputeSignedMinMaxValuesFromKnownBits(const Type *Ty,
Reid Spencerc3e3b8a2007-03-22 20:36:03 +0000709 const APInt& KnownZero,
710 const APInt& KnownOne,
711 APInt& Min, APInt& Max) {
712 uint32_t BitWidth = cast<IntegerType>(Ty)->getBitWidth();
713 assert(KnownZero.getBitWidth() == BitWidth &&
714 KnownOne.getBitWidth() == BitWidth &&
715 Min.getBitWidth() == BitWidth && Max.getBitWidth() == BitWidth &&
716 "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.");
Reid Spencercd99fbd2007-03-25 04:26:16 +0000717 APInt UnknownBits = ~(KnownZero|KnownOne);
Chris Lattneree0f2802006-02-12 02:07:56 +0000718
Chris Lattneree0f2802006-02-12 02:07:56 +0000719 // The minimum value is when all unknown bits are zeros, EXCEPT for the sign
720 // bit if it is unknown.
721 Min = KnownOne;
722 Max = KnownOne|UnknownBits;
723
Zhou Shengc2d33092007-03-28 05:15:57 +0000724 if (UnknownBits[BitWidth-1]) { // Sign bit is unknown
Zhou Sheng9bc8ab12007-04-02 13:45:30 +0000725 Min.set(BitWidth-1);
726 Max.clear(BitWidth-1);
Chris Lattneree0f2802006-02-12 02:07:56 +0000727 }
Chris Lattneree0f2802006-02-12 02:07:56 +0000728}
729
730// ComputeUnsignedMinMaxValuesFromKnownBits - Given an unsigned integer type and
731// a set of known zero and one bits, compute the maximum and minimum values that
732// could have the specified known zero and known one bits, returning them in
733// min/max.
734static void ComputeUnsignedMinMaxValuesFromKnownBits(const Type *Ty,
Chris Lattnerf0da7972007-08-05 08:47:58 +0000735 const APInt &KnownZero,
736 const APInt &KnownOne,
737 APInt &Min, APInt &Max) {
738 uint32_t BitWidth = cast<IntegerType>(Ty)->getBitWidth(); BitWidth = BitWidth;
Reid Spencerc3e3b8a2007-03-22 20:36:03 +0000739 assert(KnownZero.getBitWidth() == BitWidth &&
740 KnownOne.getBitWidth() == BitWidth &&
741 Min.getBitWidth() == BitWidth && Max.getBitWidth() &&
742 "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.");
Reid Spencercd99fbd2007-03-25 04:26:16 +0000743 APInt UnknownBits = ~(KnownZero|KnownOne);
Chris Lattneree0f2802006-02-12 02:07:56 +0000744
745 // The minimum value is when the unknown bits are all zeros.
746 Min = KnownOne;
747 // The maximum value is when the unknown bits are all ones.
748 Max = KnownOne|UnknownBits;
749}
Chris Lattner0157e7f2006-02-11 09:31:47 +0000750
Reid Spencer1791f232007-03-12 17:25:59 +0000751/// SimplifyDemandedBits - This function attempts to replace V with a simpler
752/// value based on the demanded bits. When this function is called, it is known
753/// that only the bits set in DemandedMask of the result of V are ever used
754/// downstream. Consequently, depending on the mask and V, it may be possible
755/// to replace V with a constant or one of its operands. In such cases, this
756/// function does the replacement and returns true. In all other cases, it
757/// returns false after analyzing the expression and setting KnownOne and known
758/// to be one in the expression. KnownZero contains all the bits that are known
759/// to be zero in the expression. These are provided to potentially allow the
760/// caller (which might recursively be SimplifyDemandedBits itself) to simplify
761/// the expression. KnownOne and KnownZero always follow the invariant that
762/// KnownOne & KnownZero == 0. That is, a bit can't be both 1 and 0. Note that
763/// the bits in KnownOne and KnownZero may only be accurate for those bits set
764/// in DemandedMask. Note also that the bitwidth of V, DemandedMask, KnownZero
765/// and KnownOne must all be the same.
766bool InstCombiner::SimplifyDemandedBits(Value *V, APInt DemandedMask,
767 APInt& KnownZero, APInt& KnownOne,
768 unsigned Depth) {
769 assert(V != 0 && "Null pointer of Value???");
770 assert(Depth <= 6 && "Limit Search Depth");
771 uint32_t BitWidth = DemandedMask.getBitWidth();
772 const IntegerType *VTy = cast<IntegerType>(V->getType());
773 assert(VTy->getBitWidth() == BitWidth &&
774 KnownZero.getBitWidth() == BitWidth &&
775 KnownOne.getBitWidth() == BitWidth &&
776 "Value *V, DemandedMask, KnownZero and KnownOne \
777 must have same BitWidth");
778 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
779 // We know all of the bits for a constant!
780 KnownOne = CI->getValue() & DemandedMask;
781 KnownZero = ~KnownOne & DemandedMask;
782 return false;
783 }
784
Zhou Shengb9128442007-03-14 03:21:24 +0000785 KnownZero.clear();
786 KnownOne.clear();
Reid Spencer1791f232007-03-12 17:25:59 +0000787 if (!V->hasOneUse()) { // Other users may use these bits.
788 if (Depth != 0) { // Not at the root.
789 // Just compute the KnownZero/KnownOne bits to simplify things downstream.
790 ComputeMaskedBits(V, DemandedMask, KnownZero, KnownOne, Depth);
791 return false;
792 }
793 // If this is the root being simplified, allow it to have multiple uses,
794 // just set the DemandedMask to all bits.
795 DemandedMask = APInt::getAllOnesValue(BitWidth);
796 } else if (DemandedMask == 0) { // Not demanding any bits from V.
797 if (V != UndefValue::get(VTy))
798 return UpdateValueUsesWith(V, UndefValue::get(VTy));
799 return false;
800 } else if (Depth == 6) { // Limit search depth.
801 return false;
802 }
803
804 Instruction *I = dyn_cast<Instruction>(V);
805 if (!I) return false; // Only analyze instructions.
806
Reid Spencer1791f232007-03-12 17:25:59 +0000807 APInt LHSKnownZero(BitWidth, 0), LHSKnownOne(BitWidth, 0);
808 APInt &RHSKnownZero = KnownZero, &RHSKnownOne = KnownOne;
809 switch (I->getOpcode()) {
Dan Gohman72ec3f42008-04-28 17:02:21 +0000810 default:
811 ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
812 break;
Reid Spencer1791f232007-03-12 17:25:59 +0000813 case Instruction::And:
814 // If either the LHS or the RHS are Zero, the result is zero.
815 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
816 RHSKnownZero, RHSKnownOne, Depth+1))
817 return true;
818 assert((RHSKnownZero & RHSKnownOne) == 0 &&
819 "Bits known to be one AND zero?");
820
821 // If something is known zero on the RHS, the bits aren't demanded on the
822 // LHS.
823 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask & ~RHSKnownZero,
824 LHSKnownZero, LHSKnownOne, Depth+1))
825 return true;
826 assert((LHSKnownZero & LHSKnownOne) == 0 &&
827 "Bits known to be one AND zero?");
828
829 // If all of the demanded bits are known 1 on one side, return the other.
830 // These bits cannot contribute to the result of the 'and'.
831 if ((DemandedMask & ~LHSKnownZero & RHSKnownOne) ==
832 (DemandedMask & ~LHSKnownZero))
833 return UpdateValueUsesWith(I, I->getOperand(0));
834 if ((DemandedMask & ~RHSKnownZero & LHSKnownOne) ==
835 (DemandedMask & ~RHSKnownZero))
836 return UpdateValueUsesWith(I, I->getOperand(1));
837
838 // If all of the demanded bits in the inputs are known zeros, return zero.
839 if ((DemandedMask & (RHSKnownZero|LHSKnownZero)) == DemandedMask)
840 return UpdateValueUsesWith(I, Constant::getNullValue(VTy));
841
842 // If the RHS is a constant, see if we can simplify it.
843 if (ShrinkDemandedConstant(I, 1, DemandedMask & ~LHSKnownZero))
844 return UpdateValueUsesWith(I, I);
845
846 // Output known-1 bits are only known if set in both the LHS & RHS.
847 RHSKnownOne &= LHSKnownOne;
848 // Output known-0 are known to be clear if zero in either the LHS | RHS.
849 RHSKnownZero |= LHSKnownZero;
850 break;
851 case Instruction::Or:
852 // If either the LHS or the RHS are One, the result is One.
853 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
854 RHSKnownZero, RHSKnownOne, Depth+1))
855 return true;
856 assert((RHSKnownZero & RHSKnownOne) == 0 &&
857 "Bits known to be one AND zero?");
858 // If something is known one on the RHS, the bits aren't demanded on the
859 // LHS.
860 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask & ~RHSKnownOne,
861 LHSKnownZero, LHSKnownOne, Depth+1))
862 return true;
863 assert((LHSKnownZero & LHSKnownOne) == 0 &&
864 "Bits known to be one AND zero?");
865
866 // If all of the demanded bits are known zero on one side, return the other.
867 // These bits cannot contribute to the result of the 'or'.
868 if ((DemandedMask & ~LHSKnownOne & RHSKnownZero) ==
869 (DemandedMask & ~LHSKnownOne))
870 return UpdateValueUsesWith(I, I->getOperand(0));
871 if ((DemandedMask & ~RHSKnownOne & LHSKnownZero) ==
872 (DemandedMask & ~RHSKnownOne))
873 return UpdateValueUsesWith(I, I->getOperand(1));
874
875 // If all of the potentially set bits on one side are known to be set on
876 // the other side, just use the 'other' side.
877 if ((DemandedMask & (~RHSKnownZero) & LHSKnownOne) ==
878 (DemandedMask & (~RHSKnownZero)))
879 return UpdateValueUsesWith(I, I->getOperand(0));
880 if ((DemandedMask & (~LHSKnownZero) & RHSKnownOne) ==
881 (DemandedMask & (~LHSKnownZero)))
882 return UpdateValueUsesWith(I, I->getOperand(1));
883
884 // If the RHS is a constant, see if we can simplify it.
885 if (ShrinkDemandedConstant(I, 1, DemandedMask))
886 return UpdateValueUsesWith(I, I);
887
888 // Output known-0 bits are only known if clear in both the LHS & RHS.
889 RHSKnownZero &= LHSKnownZero;
890 // Output known-1 are known to be set if set in either the LHS | RHS.
891 RHSKnownOne |= LHSKnownOne;
892 break;
893 case Instruction::Xor: {
894 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
895 RHSKnownZero, RHSKnownOne, Depth+1))
896 return true;
897 assert((RHSKnownZero & RHSKnownOne) == 0 &&
898 "Bits known to be one AND zero?");
899 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
900 LHSKnownZero, LHSKnownOne, Depth+1))
901 return true;
902 assert((LHSKnownZero & LHSKnownOne) == 0 &&
903 "Bits known to be one AND zero?");
904
905 // If all of the demanded bits are known zero on one side, return the other.
906 // These bits cannot contribute to the result of the 'xor'.
907 if ((DemandedMask & RHSKnownZero) == DemandedMask)
908 return UpdateValueUsesWith(I, I->getOperand(0));
909 if ((DemandedMask & LHSKnownZero) == DemandedMask)
910 return UpdateValueUsesWith(I, I->getOperand(1));
911
912 // Output known-0 bits are known if clear or set in both the LHS & RHS.
913 APInt KnownZeroOut = (RHSKnownZero & LHSKnownZero) |
914 (RHSKnownOne & LHSKnownOne);
915 // Output known-1 are known to be set if set in only one of the LHS, RHS.
916 APInt KnownOneOut = (RHSKnownZero & LHSKnownOne) |
917 (RHSKnownOne & LHSKnownZero);
918
919 // If all of the demanded bits are known to be zero on one side or the
920 // other, turn this into an *inclusive* or.
921 // e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
922 if ((DemandedMask & ~RHSKnownZero & ~LHSKnownZero) == 0) {
923 Instruction *Or =
Gabor Greife1f6e4b2008-05-16 19:29:10 +0000924 BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1),
Reid Spencer1791f232007-03-12 17:25:59 +0000925 I->getName());
926 InsertNewInstBefore(Or, *I);
927 return UpdateValueUsesWith(I, Or);
928 }
929
930 // If all of the demanded bits on one side are known, and all of the set
931 // bits on that side are also known to be set on the other side, turn this
932 // into an AND, as we know the bits will be cleared.
933 // e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
934 if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask) {
935 // all known
936 if ((RHSKnownOne & LHSKnownOne) == RHSKnownOne) {
937 Constant *AndC = ConstantInt::get(~RHSKnownOne & DemandedMask);
938 Instruction *And =
Gabor Greife1f6e4b2008-05-16 19:29:10 +0000939 BinaryOperator::CreateAnd(I->getOperand(0), AndC, "tmp");
Reid Spencer1791f232007-03-12 17:25:59 +0000940 InsertNewInstBefore(And, *I);
941 return UpdateValueUsesWith(I, And);
942 }
943 }
944
945 // If the RHS is a constant, see if we can simplify it.
946 // FIXME: for XOR, we prefer to force bits to 1 if they will make a -1.
947 if (ShrinkDemandedConstant(I, 1, DemandedMask))
948 return UpdateValueUsesWith(I, I);
949
950 RHSKnownZero = KnownZeroOut;
951 RHSKnownOne = KnownOneOut;
952 break;
953 }
954 case Instruction::Select:
955 if (SimplifyDemandedBits(I->getOperand(2), DemandedMask,
956 RHSKnownZero, RHSKnownOne, Depth+1))
957 return true;
958 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
959 LHSKnownZero, LHSKnownOne, Depth+1))
960 return true;
961 assert((RHSKnownZero & RHSKnownOne) == 0 &&
962 "Bits known to be one AND zero?");
963 assert((LHSKnownZero & LHSKnownOne) == 0 &&
964 "Bits known to be one AND zero?");
965
966 // If the operands are constants, see if we can simplify them.
967 if (ShrinkDemandedConstant(I, 1, DemandedMask))
968 return UpdateValueUsesWith(I, I);
969 if (ShrinkDemandedConstant(I, 2, DemandedMask))
970 return UpdateValueUsesWith(I, I);
971
972 // Only known if known in both the LHS and RHS.
973 RHSKnownOne &= LHSKnownOne;
974 RHSKnownZero &= LHSKnownZero;
975 break;
976 case Instruction::Trunc: {
977 uint32_t truncBf =
978 cast<IntegerType>(I->getOperand(0)->getType())->getBitWidth();
Zhou Shenga4475572007-03-29 02:26:30 +0000979 DemandedMask.zext(truncBf);
980 RHSKnownZero.zext(truncBf);
981 RHSKnownOne.zext(truncBf);
982 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
983 RHSKnownZero, RHSKnownOne, Depth+1))
Reid Spencer1791f232007-03-12 17:25:59 +0000984 return true;
985 DemandedMask.trunc(BitWidth);
986 RHSKnownZero.trunc(BitWidth);
987 RHSKnownOne.trunc(BitWidth);
988 assert((RHSKnownZero & RHSKnownOne) == 0 &&
989 "Bits known to be one AND zero?");
990 break;
991 }
992 case Instruction::BitCast:
993 if (!I->getOperand(0)->getType()->isInteger())
994 return false;
995
996 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
997 RHSKnownZero, RHSKnownOne, Depth+1))
998 return true;
999 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1000 "Bits known to be one AND zero?");
1001 break;
1002 case Instruction::ZExt: {
1003 // Compute the bits in the result that are not present in the input.
1004 const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
Reid Spencercd99fbd2007-03-25 04:26:16 +00001005 uint32_t SrcBitWidth = SrcTy->getBitWidth();
Reid Spencer1791f232007-03-12 17:25:59 +00001006
Zhou Sheng444af492007-03-29 04:45:55 +00001007 DemandedMask.trunc(SrcBitWidth);
1008 RHSKnownZero.trunc(SrcBitWidth);
1009 RHSKnownOne.trunc(SrcBitWidth);
Zhou Shenga4475572007-03-29 02:26:30 +00001010 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1011 RHSKnownZero, RHSKnownOne, Depth+1))
Reid Spencer1791f232007-03-12 17:25:59 +00001012 return true;
1013 DemandedMask.zext(BitWidth);
1014 RHSKnownZero.zext(BitWidth);
1015 RHSKnownOne.zext(BitWidth);
1016 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1017 "Bits known to be one AND zero?");
1018 // The top bits are known to be zero.
Zhou Shenga4475572007-03-29 02:26:30 +00001019 RHSKnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
Reid Spencer1791f232007-03-12 17:25:59 +00001020 break;
1021 }
1022 case Instruction::SExt: {
1023 // Compute the bits in the result that are not present in the input.
1024 const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
Reid Spencercd99fbd2007-03-25 04:26:16 +00001025 uint32_t SrcBitWidth = SrcTy->getBitWidth();
Reid Spencer1791f232007-03-12 17:25:59 +00001026
Reid Spencer1791f232007-03-12 17:25:59 +00001027 APInt InputDemandedBits = DemandedMask &
Zhou Shenga4475572007-03-29 02:26:30 +00001028 APInt::getLowBitsSet(BitWidth, SrcBitWidth);
Reid Spencer1791f232007-03-12 17:25:59 +00001029
Zhou Shenga4475572007-03-29 02:26:30 +00001030 APInt NewBits(APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth));
Reid Spencer1791f232007-03-12 17:25:59 +00001031 // If any of the sign extended bits are demanded, we know that the sign
1032 // bit is demanded.
1033 if ((NewBits & DemandedMask) != 0)
Zhou Sheng9bc8ab12007-04-02 13:45:30 +00001034 InputDemandedBits.set(SrcBitWidth-1);
Reid Spencer1791f232007-03-12 17:25:59 +00001035
Zhou Sheng444af492007-03-29 04:45:55 +00001036 InputDemandedBits.trunc(SrcBitWidth);
1037 RHSKnownZero.trunc(SrcBitWidth);
1038 RHSKnownOne.trunc(SrcBitWidth);
Zhou Shenga4475572007-03-29 02:26:30 +00001039 if (SimplifyDemandedBits(I->getOperand(0), InputDemandedBits,
1040 RHSKnownZero, RHSKnownOne, Depth+1))
Reid Spencer1791f232007-03-12 17:25:59 +00001041 return true;
1042 InputDemandedBits.zext(BitWidth);
1043 RHSKnownZero.zext(BitWidth);
1044 RHSKnownOne.zext(BitWidth);
1045 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1046 "Bits known to be one AND zero?");
1047
1048 // If the sign bit of the input is known set or clear, then we know the
1049 // top bits of the result.
1050
1051 // If the input sign bit is known zero, or if the NewBits are not demanded
1052 // convert this into a zero extension.
Zhou Shenga4475572007-03-29 02:26:30 +00001053 if (RHSKnownZero[SrcBitWidth-1] || (NewBits & ~DemandedMask) == NewBits)
Reid Spencer1791f232007-03-12 17:25:59 +00001054 {
1055 // Convert to ZExt cast
1056 CastInst *NewCast = new ZExtInst(I->getOperand(0), VTy, I->getName(), I);
1057 return UpdateValueUsesWith(I, NewCast);
Zhou Shenga4475572007-03-29 02:26:30 +00001058 } else if (RHSKnownOne[SrcBitWidth-1]) { // Input sign bit known set
Reid Spencer1791f232007-03-12 17:25:59 +00001059 RHSKnownOne |= NewBits;
Reid Spencer1791f232007-03-12 17:25:59 +00001060 }
1061 break;
1062 }
1063 case Instruction::Add: {
1064 // Figure out what the input bits are. If the top bits of the and result
1065 // are not demanded, then the add doesn't demand them from its input
1066 // either.
Reid Spencer52830322007-03-25 21:11:44 +00001067 uint32_t NLZ = DemandedMask.countLeadingZeros();
Reid Spencer1791f232007-03-12 17:25:59 +00001068
1069 // If there is a constant on the RHS, there are a variety of xformations
1070 // we can do.
1071 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
1072 // If null, this should be simplified elsewhere. Some of the xforms here
1073 // won't work if the RHS is zero.
1074 if (RHS->isZero())
1075 break;
1076
1077 // If the top bit of the output is demanded, demand everything from the
1078 // input. Otherwise, we demand all the input bits except NLZ top bits.
Zhou Shenga4475572007-03-29 02:26:30 +00001079 APInt InDemandedBits(APInt::getLowBitsSet(BitWidth, BitWidth - NLZ));
Reid Spencer1791f232007-03-12 17:25:59 +00001080
1081 // Find information about known zero/one bits in the input.
1082 if (SimplifyDemandedBits(I->getOperand(0), InDemandedBits,
1083 LHSKnownZero, LHSKnownOne, Depth+1))
1084 return true;
1085
1086 // If the RHS of the add has bits set that can't affect the input, reduce
1087 // the constant.
1088 if (ShrinkDemandedConstant(I, 1, InDemandedBits))
1089 return UpdateValueUsesWith(I, I);
1090
1091 // Avoid excess work.
1092 if (LHSKnownZero == 0 && LHSKnownOne == 0)
1093 break;
1094
1095 // Turn it into OR if input bits are zero.
1096 if ((LHSKnownZero & RHS->getValue()) == RHS->getValue()) {
1097 Instruction *Or =
Gabor Greife1f6e4b2008-05-16 19:29:10 +00001098 BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1),
Reid Spencer1791f232007-03-12 17:25:59 +00001099 I->getName());
1100 InsertNewInstBefore(Or, *I);
1101 return UpdateValueUsesWith(I, Or);
1102 }
1103
1104 // We can say something about the output known-zero and known-one bits,
1105 // depending on potential carries from the input constant and the
1106 // unknowns. For example if the LHS is known to have at most the 0x0F0F0
1107 // bits set and the RHS constant is 0x01001, then we know we have a known
1108 // one mask of 0x00001 and a known zero mask of 0xE0F0E.
1109
1110 // To compute this, we first compute the potential carry bits. These are
1111 // the bits which may be modified. I'm not aware of a better way to do
1112 // this scan.
Zhou Sheng4f164022007-03-31 02:38:39 +00001113 const APInt& RHSVal = RHS->getValue();
1114 APInt CarryBits((~LHSKnownZero + RHSVal) ^ (~LHSKnownZero ^ RHSVal));
Reid Spencer1791f232007-03-12 17:25:59 +00001115
1116 // Now that we know which bits have carries, compute the known-1/0 sets.
1117
1118 // Bits are known one if they are known zero in one operand and one in the
1119 // other, and there is no input carry.
1120 RHSKnownOne = ((LHSKnownZero & RHSVal) |
1121 (LHSKnownOne & ~RHSVal)) & ~CarryBits;
1122
1123 // Bits are known zero if they are known zero in both operands and there
1124 // is no input carry.
1125 RHSKnownZero = LHSKnownZero & ~RHSVal & ~CarryBits;
1126 } else {
1127 // If the high-bits of this ADD are not demanded, then it does not demand
1128 // the high bits of its LHS or RHS.
Zhou Shenga4475572007-03-29 02:26:30 +00001129 if (DemandedMask[BitWidth-1] == 0) {
Reid Spencer1791f232007-03-12 17:25:59 +00001130 // Right fill the mask of bits for this ADD to demand the most
1131 // significant bit and all those below it.
Zhou Shenga4475572007-03-29 02:26:30 +00001132 APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
Reid Spencer1791f232007-03-12 17:25:59 +00001133 if (SimplifyDemandedBits(I->getOperand(0), DemandedFromOps,
1134 LHSKnownZero, LHSKnownOne, Depth+1))
1135 return true;
1136 if (SimplifyDemandedBits(I->getOperand(1), DemandedFromOps,
1137 LHSKnownZero, LHSKnownOne, Depth+1))
1138 return true;
1139 }
1140 }
1141 break;
1142 }
1143 case Instruction::Sub:
1144 // If the high-bits of this SUB are not demanded, then it does not demand
1145 // the high bits of its LHS or RHS.
Zhou Shenga4475572007-03-29 02:26:30 +00001146 if (DemandedMask[BitWidth-1] == 0) {
Reid Spencer1791f232007-03-12 17:25:59 +00001147 // Right fill the mask of bits for this SUB to demand the most
1148 // significant bit and all those below it.
Zhou Sheng56cda952007-04-02 08:20:41 +00001149 uint32_t NLZ = DemandedMask.countLeadingZeros();
Zhou Shenga4475572007-03-29 02:26:30 +00001150 APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
Reid Spencer1791f232007-03-12 17:25:59 +00001151 if (SimplifyDemandedBits(I->getOperand(0), DemandedFromOps,
1152 LHSKnownZero, LHSKnownOne, Depth+1))
1153 return true;
1154 if (SimplifyDemandedBits(I->getOperand(1), DemandedFromOps,
1155 LHSKnownZero, LHSKnownOne, Depth+1))
1156 return true;
1157 }
Dan Gohman72ec3f42008-04-28 17:02:21 +00001158 // Otherwise just hand the sub off to ComputeMaskedBits to fill in
1159 // the known zeros and ones.
1160 ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
Reid Spencer1791f232007-03-12 17:25:59 +00001161 break;
1162 case Instruction::Shl:
1163 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Shengb25806f2007-03-30 09:29:48 +00001164 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
Zhou Shenga4475572007-03-29 02:26:30 +00001165 APInt DemandedMaskIn(DemandedMask.lshr(ShiftAmt));
1166 if (SimplifyDemandedBits(I->getOperand(0), DemandedMaskIn,
Reid Spencer1791f232007-03-12 17:25:59 +00001167 RHSKnownZero, RHSKnownOne, Depth+1))
1168 return true;
1169 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1170 "Bits known to be one AND zero?");
1171 RHSKnownZero <<= ShiftAmt;
1172 RHSKnownOne <<= ShiftAmt;
1173 // low bits known zero.
Zhou Shengd8c645b2007-03-14 09:07:33 +00001174 if (ShiftAmt)
Zhou Sheng23f7a1c2007-03-28 15:02:20 +00001175 RHSKnownZero |= APInt::getLowBitsSet(BitWidth, ShiftAmt);
Reid Spencer1791f232007-03-12 17:25:59 +00001176 }
1177 break;
1178 case Instruction::LShr:
1179 // For a logical shift right
1180 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Shengb25806f2007-03-30 09:29:48 +00001181 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
Reid Spencer1791f232007-03-12 17:25:59 +00001182
Reid Spencer1791f232007-03-12 17:25:59 +00001183 // Unsigned shift right.
Zhou Shenga4475572007-03-29 02:26:30 +00001184 APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
1185 if (SimplifyDemandedBits(I->getOperand(0), DemandedMaskIn,
Reid Spencer1791f232007-03-12 17:25:59 +00001186 RHSKnownZero, RHSKnownOne, Depth+1))
1187 return true;
1188 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1189 "Bits known to be one AND zero?");
Reid Spencer1791f232007-03-12 17:25:59 +00001190 RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1191 RHSKnownOne = APIntOps::lshr(RHSKnownOne, ShiftAmt);
Zhou Shengd8c645b2007-03-14 09:07:33 +00001192 if (ShiftAmt) {
1193 // Compute the new bits that are at the top now.
Zhou Shenga4475572007-03-29 02:26:30 +00001194 APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
Zhou Shengd8c645b2007-03-14 09:07:33 +00001195 RHSKnownZero |= HighBits; // high bits known zero.
1196 }
Reid Spencer1791f232007-03-12 17:25:59 +00001197 }
1198 break;
1199 case Instruction::AShr:
1200 // If this is an arithmetic shift right and only the low-bit is set, we can
1201 // always convert this into a logical shr, even if the shift amount is
1202 // variable. The low bit of the shift cannot be an input sign bit unless
1203 // the shift amount is >= the size of the datatype, which is undefined.
1204 if (DemandedMask == 1) {
1205 // Perform the logical shift right.
Gabor Greife1f6e4b2008-05-16 19:29:10 +00001206 Value *NewVal = BinaryOperator::CreateLShr(
Reid Spencer1791f232007-03-12 17:25:59 +00001207 I->getOperand(0), I->getOperand(1), I->getName());
1208 InsertNewInstBefore(cast<Instruction>(NewVal), *I);
1209 return UpdateValueUsesWith(I, NewVal);
1210 }
Chris Lattnerd4fef8d2007-07-15 20:54:51 +00001211
1212 // If the sign bit is the only bit demanded by this ashr, then there is no
1213 // need to do it, the shift doesn't change the high bit.
1214 if (DemandedMask.isSignBit())
1215 return UpdateValueUsesWith(I, I->getOperand(0));
Reid Spencer1791f232007-03-12 17:25:59 +00001216
1217 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Shengfd28a332007-03-30 17:20:39 +00001218 uint32_t ShiftAmt = SA->getLimitedValue(BitWidth);
Reid Spencer1791f232007-03-12 17:25:59 +00001219
Reid Spencer1791f232007-03-12 17:25:59 +00001220 // Signed shift right.
Zhou Shenga4475572007-03-29 02:26:30 +00001221 APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
Lauro Ramos Venancio368e8872007-06-06 17:08:48 +00001222 // If any of the "high bits" are demanded, we should set the sign bit as
1223 // demanded.
1224 if (DemandedMask.countLeadingZeros() <= ShiftAmt)
1225 DemandedMaskIn.set(BitWidth-1);
Reid Spencer1791f232007-03-12 17:25:59 +00001226 if (SimplifyDemandedBits(I->getOperand(0),
Zhou Shenga4475572007-03-29 02:26:30 +00001227 DemandedMaskIn,
Reid Spencer1791f232007-03-12 17:25:59 +00001228 RHSKnownZero, RHSKnownOne, Depth+1))
1229 return true;
1230 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1231 "Bits known to be one AND zero?");
1232 // Compute the new bits that are at the top now.
Zhou Shenga4475572007-03-29 02:26:30 +00001233 APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
Reid Spencer1791f232007-03-12 17:25:59 +00001234 RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1235 RHSKnownOne = APIntOps::lshr(RHSKnownOne, ShiftAmt);
1236
1237 // Handle the sign bits.
1238 APInt SignBit(APInt::getSignBit(BitWidth));
1239 // Adjust to where it is now in the mask.
1240 SignBit = APIntOps::lshr(SignBit, ShiftAmt);
1241
1242 // If the input sign bit is known to be zero, or if none of the top bits
1243 // are demanded, turn this into an unsigned shift right.
Zhou Sheng1152ca92008-06-06 08:32:05 +00001244 if (BitWidth <= ShiftAmt || RHSKnownZero[BitWidth-ShiftAmt-1] ||
Reid Spencer1791f232007-03-12 17:25:59 +00001245 (HighBits & ~DemandedMask) == HighBits) {
1246 // Perform the logical shift right.
Gabor Greife1f6e4b2008-05-16 19:29:10 +00001247 Value *NewVal = BinaryOperator::CreateLShr(
Reid Spencer1791f232007-03-12 17:25:59 +00001248 I->getOperand(0), SA, I->getName());
1249 InsertNewInstBefore(cast<Instruction>(NewVal), *I);
1250 return UpdateValueUsesWith(I, NewVal);
1251 } else if ((RHSKnownOne & SignBit) != 0) { // New bits are known one.
1252 RHSKnownOne |= HighBits;
1253 }
1254 }
1255 break;
Nick Lewyckyd0b62a12008-03-06 06:48:30 +00001256 case Instruction::SRem:
1257 if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
Nick Lewycky8d8acf32008-11-02 02:41:50 +00001258 APInt RA = Rem->getValue().abs();
1259 if (RA.isPowerOf2()) {
Nick Lewyckyf76aa232008-07-12 05:04:38 +00001260 if (DemandedMask.ule(RA)) // srem won't affect demanded bits
1261 return UpdateValueUsesWith(I, I->getOperand(0));
1262
Nick Lewycky8d8acf32008-11-02 02:41:50 +00001263 APInt LowBits = RA - 1;
Nick Lewyckyd0b62a12008-03-06 06:48:30 +00001264 APInt Mask2 = LowBits | APInt::getSignBit(BitWidth);
1265 if (SimplifyDemandedBits(I->getOperand(0), Mask2,
1266 LHSKnownZero, LHSKnownOne, Depth+1))
1267 return true;
1268
1269 if (LHSKnownZero[BitWidth-1] || ((LHSKnownZero & LowBits) == LowBits))
1270 LHSKnownZero |= ~LowBits;
Nick Lewyckyd0b62a12008-03-06 06:48:30 +00001271
1272 KnownZero |= LHSKnownZero & DemandedMask;
Nick Lewyckyd0b62a12008-03-06 06:48:30 +00001273
1274 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
1275 }
1276 }
1277 break;
Dan Gohman72ec3f42008-04-28 17:02:21 +00001278 case Instruction::URem: {
Dan Gohman72ec3f42008-04-28 17:02:21 +00001279 APInt KnownZero2(BitWidth, 0), KnownOne2(BitWidth, 0);
1280 APInt AllOnes = APInt::getAllOnesValue(BitWidth);
Dan Gohman4be6ae42008-05-01 19:13:24 +00001281 if (SimplifyDemandedBits(I->getOperand(0), AllOnes,
1282 KnownZero2, KnownOne2, Depth+1))
1283 return true;
1284
Dan Gohman72ec3f42008-04-28 17:02:21 +00001285 uint32_t Leaders = KnownZero2.countLeadingOnes();
Dan Gohman4be6ae42008-05-01 19:13:24 +00001286 if (SimplifyDemandedBits(I->getOperand(1), AllOnes,
Dan Gohman72ec3f42008-04-28 17:02:21 +00001287 KnownZero2, KnownOne2, Depth+1))
1288 return true;
1289
1290 Leaders = std::max(Leaders,
1291 KnownZero2.countLeadingOnes());
1292 KnownZero = APInt::getHighBitsSet(BitWidth, Leaders) & DemandedMask;
Nick Lewyckyd0b62a12008-03-06 06:48:30 +00001293 break;
Reid Spencer1791f232007-03-12 17:25:59 +00001294 }
Chris Lattneref36dcd2008-06-18 04:33:20 +00001295 case Instruction::Call:
1296 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
1297 switch (II->getIntrinsicID()) {
1298 default: break;
1299 case Intrinsic::bswap: {
1300 // If the only bits demanded come from one byte of the bswap result,
1301 // just shift the input byte into position to eliminate the bswap.
1302 unsigned NLZ = DemandedMask.countLeadingZeros();
1303 unsigned NTZ = DemandedMask.countTrailingZeros();
1304
1305 // Round NTZ down to the next byte. If we have 11 trailing zeros, then
1306 // we need all the bits down to bit 8. Likewise, round NLZ. If we
1307 // have 14 leading zeros, round to 8.
1308 NLZ &= ~7;
1309 NTZ &= ~7;
1310 // If we need exactly one byte, we can do this transformation.
1311 if (BitWidth-NLZ-NTZ == 8) {
1312 unsigned ResultBit = NTZ;
1313 unsigned InputBit = BitWidth-NTZ-8;
1314
1315 // Replace this with either a left or right shift to get the byte into
1316 // the right place.
1317 Instruction *NewVal;
1318 if (InputBit > ResultBit)
1319 NewVal = BinaryOperator::CreateLShr(I->getOperand(1),
1320 ConstantInt::get(I->getType(), InputBit-ResultBit));
1321 else
1322 NewVal = BinaryOperator::CreateShl(I->getOperand(1),
1323 ConstantInt::get(I->getType(), ResultBit-InputBit));
1324 NewVal->takeName(I);
1325 InsertNewInstBefore(NewVal, *I);
1326 return UpdateValueUsesWith(I, NewVal);
1327 }
1328
1329 // TODO: Could compute known zero/one bits based on the input.
1330 break;
1331 }
1332 }
1333 }
Chris Lattner78119b42008-06-18 18:11:55 +00001334 ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
Chris Lattneref36dcd2008-06-18 04:33:20 +00001335 break;
Dan Gohman72ec3f42008-04-28 17:02:21 +00001336 }
Reid Spencer1791f232007-03-12 17:25:59 +00001337
1338 // If the client is only demanding bits that we know, return the known
1339 // constant.
1340 if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask)
1341 return UpdateValueUsesWith(I, ConstantInt::get(RHSKnownOne));
1342 return false;
1343}
1344
Chris Lattner2deeaea2006-10-05 06:55:50 +00001345
Mon P Wang25f01062008-11-10 04:46:22 +00001346/// SimplifyDemandedVectorElts - The specified value produces a vector with
Chris Lattner2deeaea2006-10-05 06:55:50 +00001347/// 64 or fewer elements. DemandedElts contains the set of elements that are
1348/// actually used by the caller. This method analyzes which elements of the
1349/// operand are undef and returns that information in UndefElts.
1350///
1351/// If the information about demanded elements can be used to simplify the
1352/// operation, the operation is simplified, then the resultant value is
1353/// returned. This returns null if no change was made.
1354Value *InstCombiner::SimplifyDemandedVectorElts(Value *V, uint64_t DemandedElts,
1355 uint64_t &UndefElts,
1356 unsigned Depth) {
Reid Spencerd84d35b2007-02-15 02:26:10 +00001357 unsigned VWidth = cast<VectorType>(V->getType())->getNumElements();
Chris Lattner2deeaea2006-10-05 06:55:50 +00001358 assert(VWidth <= 64 && "Vector too wide to analyze!");
1359 uint64_t EltMask = ~0ULL >> (64-VWidth);
Dan Gohman86fb5b42008-09-09 18:11:14 +00001360 assert((DemandedElts & ~EltMask) == 0 && "Invalid DemandedElts!");
Chris Lattner2deeaea2006-10-05 06:55:50 +00001361
1362 if (isa<UndefValue>(V)) {
1363 // If the entire vector is undefined, just return this info.
1364 UndefElts = EltMask;
1365 return 0;
1366 } else if (DemandedElts == 0) { // If nothing is demanded, provide undef.
1367 UndefElts = EltMask;
1368 return UndefValue::get(V->getType());
1369 }
Mon P Wang25f01062008-11-10 04:46:22 +00001370
Chris Lattner2deeaea2006-10-05 06:55:50 +00001371 UndefElts = 0;
Reid Spencerd84d35b2007-02-15 02:26:10 +00001372 if (ConstantVector *CP = dyn_cast<ConstantVector>(V)) {
1373 const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
Chris Lattner2deeaea2006-10-05 06:55:50 +00001374 Constant *Undef = UndefValue::get(EltTy);
1375
1376 std::vector<Constant*> Elts;
1377 for (unsigned i = 0; i != VWidth; ++i)
1378 if (!(DemandedElts & (1ULL << i))) { // If not demanded, set to undef.
1379 Elts.push_back(Undef);
1380 UndefElts |= (1ULL << i);
1381 } else if (isa<UndefValue>(CP->getOperand(i))) { // Already undef.
1382 Elts.push_back(Undef);
1383 UndefElts |= (1ULL << i);
1384 } else { // Otherwise, defined.
1385 Elts.push_back(CP->getOperand(i));
1386 }
Mon P Wang25f01062008-11-10 04:46:22 +00001387
Chris Lattner2deeaea2006-10-05 06:55:50 +00001388 // If we changed the constant, return it.
Reid Spencerd84d35b2007-02-15 02:26:10 +00001389 Constant *NewCP = ConstantVector::get(Elts);
Chris Lattner2deeaea2006-10-05 06:55:50 +00001390 return NewCP != CP ? NewCP : 0;
1391 } else if (isa<ConstantAggregateZero>(V)) {
Reid Spencerd84d35b2007-02-15 02:26:10 +00001392 // Simplify the CAZ to a ConstantVector where the non-demanded elements are
Chris Lattner2deeaea2006-10-05 06:55:50 +00001393 // set to undef.
Mon P Wang5ca2ec62008-11-06 22:52:21 +00001394
1395 // Check if this is identity. If so, return 0 since we are not simplifying
1396 // anything.
1397 if (DemandedElts == ((1ULL << VWidth) -1))
1398 return 0;
1399
Reid Spencerd84d35b2007-02-15 02:26:10 +00001400 const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
Chris Lattner2deeaea2006-10-05 06:55:50 +00001401 Constant *Zero = Constant::getNullValue(EltTy);
1402 Constant *Undef = UndefValue::get(EltTy);
1403 std::vector<Constant*> Elts;
1404 for (unsigned i = 0; i != VWidth; ++i)
1405 Elts.push_back((DemandedElts & (1ULL << i)) ? Zero : Undef);
1406 UndefElts = DemandedElts ^ EltMask;
Reid Spencerd84d35b2007-02-15 02:26:10 +00001407 return ConstantVector::get(Elts);
Chris Lattner2deeaea2006-10-05 06:55:50 +00001408 }
1409
Dan Gohman86fb5b42008-09-09 18:11:14 +00001410 // Limit search depth.
1411 if (Depth == 10)
1412 return false;
1413
1414 // If multiple users are using the root value, procede with
1415 // simplification conservatively assuming that all elements
1416 // are needed.
1417 if (!V->hasOneUse()) {
1418 // Quit if we find multiple users of a non-root value though.
1419 // They'll be handled when it's their turn to be visited by
1420 // the main instcombine process.
1421 if (Depth != 0)
Chris Lattner2deeaea2006-10-05 06:55:50 +00001422 // TODO: Just compute the UndefElts information recursively.
1423 return false;
Dan Gohman86fb5b42008-09-09 18:11:14 +00001424
1425 // Conservatively assume that all elements are needed.
1426 DemandedElts = EltMask;
Chris Lattner2deeaea2006-10-05 06:55:50 +00001427 }
1428
1429 Instruction *I = dyn_cast<Instruction>(V);
1430 if (!I) return false; // Only analyze instructions.
1431
1432 bool MadeChange = false;
1433 uint64_t UndefElts2;
1434 Value *TmpV;
1435 switch (I->getOpcode()) {
1436 default: break;
1437
1438 case Instruction::InsertElement: {
1439 // If this is a variable index, we don't know which element it overwrites.
1440 // demand exactly the same input as we produce.
Reid Spencere0fc4df2006-10-20 07:07:24 +00001441 ConstantInt *Idx = dyn_cast<ConstantInt>(I->getOperand(2));
Chris Lattner2deeaea2006-10-05 06:55:50 +00001442 if (Idx == 0) {
1443 // Note that we can't propagate undef elt info, because we don't know
1444 // which elt is getting updated.
1445 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1446 UndefElts2, Depth+1);
1447 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1448 break;
1449 }
1450
1451 // If this is inserting an element that isn't demanded, remove this
1452 // insertelement.
Reid Spencere0fc4df2006-10-20 07:07:24 +00001453 unsigned IdxNo = Idx->getZExtValue();
Chris Lattner2deeaea2006-10-05 06:55:50 +00001454 if (IdxNo >= VWidth || (DemandedElts & (1ULL << IdxNo)) == 0)
1455 return AddSoonDeadInstToWorklist(*I, 0);
1456
1457 // Otherwise, the element inserted overwrites whatever was there, so the
1458 // input demanded set is simpler than the output set.
1459 TmpV = SimplifyDemandedVectorElts(I->getOperand(0),
1460 DemandedElts & ~(1ULL << IdxNo),
1461 UndefElts, Depth+1);
1462 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1463
1464 // The inserted element is defined.
Dan Gohman86fb5b42008-09-09 18:11:14 +00001465 UndefElts &= ~(1ULL << IdxNo);
1466 break;
1467 }
1468 case Instruction::ShuffleVector: {
1469 ShuffleVectorInst *Shuffle = cast<ShuffleVectorInst>(I);
Mon P Wang25f01062008-11-10 04:46:22 +00001470 uint64_t LHSVWidth =
1471 cast<VectorType>(Shuffle->getOperand(0)->getType())->getNumElements();
Dan Gohman86fb5b42008-09-09 18:11:14 +00001472 uint64_t LeftDemanded = 0, RightDemanded = 0;
1473 for (unsigned i = 0; i < VWidth; i++) {
1474 if (DemandedElts & (1ULL << i)) {
1475 unsigned MaskVal = Shuffle->getMaskValue(i);
1476 if (MaskVal != -1u) {
Mon P Wang25f01062008-11-10 04:46:22 +00001477 assert(MaskVal < LHSVWidth * 2 &&
Dan Gohman86fb5b42008-09-09 18:11:14 +00001478 "shufflevector mask index out of range!");
Mon P Wang25f01062008-11-10 04:46:22 +00001479 if (MaskVal < LHSVWidth)
Dan Gohman86fb5b42008-09-09 18:11:14 +00001480 LeftDemanded |= 1ULL << MaskVal;
1481 else
Mon P Wang25f01062008-11-10 04:46:22 +00001482 RightDemanded |= 1ULL << (MaskVal - LHSVWidth);
Dan Gohman86fb5b42008-09-09 18:11:14 +00001483 }
1484 }
1485 }
1486
1487 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), LeftDemanded,
1488 UndefElts2, Depth+1);
1489 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1490
1491 uint64_t UndefElts3;
1492 TmpV = SimplifyDemandedVectorElts(I->getOperand(1), RightDemanded,
1493 UndefElts3, Depth+1);
1494 if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1495
1496 bool NewUndefElts = false;
1497 for (unsigned i = 0; i < VWidth; i++) {
1498 unsigned MaskVal = Shuffle->getMaskValue(i);
Dan Gohman97f0a0f2008-09-10 01:09:32 +00001499 if (MaskVal == -1u) {
Dan Gohman86fb5b42008-09-09 18:11:14 +00001500 uint64_t NewBit = 1ULL << i;
1501 UndefElts |= NewBit;
Mon P Wang25f01062008-11-10 04:46:22 +00001502 } else if (MaskVal < LHSVWidth) {
Dan Gohman86fb5b42008-09-09 18:11:14 +00001503 uint64_t NewBit = ((UndefElts2 >> MaskVal) & 1) << i;
1504 NewUndefElts |= NewBit;
1505 UndefElts |= NewBit;
1506 } else {
Mon P Wang25f01062008-11-10 04:46:22 +00001507 uint64_t NewBit = ((UndefElts3 >> (MaskVal - LHSVWidth)) & 1) << i;
Dan Gohman86fb5b42008-09-09 18:11:14 +00001508 NewUndefElts |= NewBit;
1509 UndefElts |= NewBit;
1510 }
1511 }
1512
1513 if (NewUndefElts) {
1514 // Add additional discovered undefs.
1515 std::vector<Constant*> Elts;
1516 for (unsigned i = 0; i < VWidth; ++i) {
1517 if (UndefElts & (1ULL << i))
1518 Elts.push_back(UndefValue::get(Type::Int32Ty));
1519 else
1520 Elts.push_back(ConstantInt::get(Type::Int32Ty,
1521 Shuffle->getMaskValue(i)));
1522 }
1523 I->setOperand(2, ConstantVector::get(Elts));
1524 MadeChange = true;
1525 }
Chris Lattner2deeaea2006-10-05 06:55:50 +00001526 break;
1527 }
Chris Lattnerb37fb6a2007-04-14 22:29:23 +00001528 case Instruction::BitCast: {
Dan Gohman06c60b62007-07-16 14:29:03 +00001529 // Vector->vector casts only.
Chris Lattnerb37fb6a2007-04-14 22:29:23 +00001530 const VectorType *VTy = dyn_cast<VectorType>(I->getOperand(0)->getType());
1531 if (!VTy) break;
1532 unsigned InVWidth = VTy->getNumElements();
1533 uint64_t InputDemandedElts = 0;
1534 unsigned Ratio;
1535
1536 if (VWidth == InVWidth) {
Dan Gohman06c60b62007-07-16 14:29:03 +00001537 // If we are converting from <4 x i32> -> <4 x f32>, we demand the same
Chris Lattnerb37fb6a2007-04-14 22:29:23 +00001538 // elements as are demanded of us.
1539 Ratio = 1;
1540 InputDemandedElts = DemandedElts;
1541 } else if (VWidth > InVWidth) {
1542 // Untested so far.
1543 break;
1544
1545 // If there are more elements in the result than there are in the source,
1546 // then an input element is live if any of the corresponding output
1547 // elements are live.
1548 Ratio = VWidth/InVWidth;
1549 for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx) {
1550 if (DemandedElts & (1ULL << OutIdx))
1551 InputDemandedElts |= 1ULL << (OutIdx/Ratio);
1552 }
1553 } else {
1554 // Untested so far.
1555 break;
1556
1557 // If there are more elements in the source than there are in the result,
1558 // then an input element is live if the corresponding output element is
1559 // live.
1560 Ratio = InVWidth/VWidth;
1561 for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
1562 if (DemandedElts & (1ULL << InIdx/Ratio))
1563 InputDemandedElts |= 1ULL << InIdx;
1564 }
Chris Lattner2deeaea2006-10-05 06:55:50 +00001565
Chris Lattnerb37fb6a2007-04-14 22:29:23 +00001566 // div/rem demand all inputs, because they don't want divide by zero.
1567 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), InputDemandedElts,
1568 UndefElts2, Depth+1);
1569 if (TmpV) {
1570 I->setOperand(0, TmpV);
1571 MadeChange = true;
1572 }
1573
1574 UndefElts = UndefElts2;
1575 if (VWidth > InVWidth) {
1576 assert(0 && "Unimp");
1577 // If there are more elements in the result than there are in the source,
1578 // then an output element is undef if the corresponding input element is
1579 // undef.
1580 for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx)
1581 if (UndefElts2 & (1ULL << (OutIdx/Ratio)))
1582 UndefElts |= 1ULL << OutIdx;
1583 } else if (VWidth < InVWidth) {
1584 assert(0 && "Unimp");
1585 // If there are more elements in the source than there are in the result,
1586 // then a result element is undef if all of the corresponding input
1587 // elements are undef.
1588 UndefElts = ~0ULL >> (64-VWidth); // Start out all undef.
1589 for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
1590 if ((UndefElts2 & (1ULL << InIdx)) == 0) // Not undef?
1591 UndefElts &= ~(1ULL << (InIdx/Ratio)); // Clear undef bit.
1592 }
1593 break;
1594 }
Chris Lattner2deeaea2006-10-05 06:55:50 +00001595 case Instruction::And:
1596 case Instruction::Or:
1597 case Instruction::Xor:
1598 case Instruction::Add:
1599 case Instruction::Sub:
1600 case Instruction::Mul:
1601 // div/rem demand all inputs, because they don't want divide by zero.
1602 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1603 UndefElts, Depth+1);
1604 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1605 TmpV = SimplifyDemandedVectorElts(I->getOperand(1), DemandedElts,
1606 UndefElts2, Depth+1);
1607 if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1608
1609 // Output elements are undefined if both are undefined. Consider things
1610 // like undef&0. The result is known zero, not undef.
1611 UndefElts &= UndefElts2;
1612 break;
1613
1614 case Instruction::Call: {
1615 IntrinsicInst *II = dyn_cast<IntrinsicInst>(I);
1616 if (!II) break;
1617 switch (II->getIntrinsicID()) {
1618 default: break;
1619
1620 // Binary vector operations that work column-wise. A dest element is a
1621 // function of the corresponding input elements from the two inputs.
1622 case Intrinsic::x86_sse_sub_ss:
1623 case Intrinsic::x86_sse_mul_ss:
1624 case Intrinsic::x86_sse_min_ss:
1625 case Intrinsic::x86_sse_max_ss:
1626 case Intrinsic::x86_sse2_sub_sd:
1627 case Intrinsic::x86_sse2_mul_sd:
1628 case Intrinsic::x86_sse2_min_sd:
1629 case Intrinsic::x86_sse2_max_sd:
1630 TmpV = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
1631 UndefElts, Depth+1);
1632 if (TmpV) { II->setOperand(1, TmpV); MadeChange = true; }
1633 TmpV = SimplifyDemandedVectorElts(II->getOperand(2), DemandedElts,
1634 UndefElts2, Depth+1);
1635 if (TmpV) { II->setOperand(2, TmpV); MadeChange = true; }
1636
1637 // If only the low elt is demanded and this is a scalarizable intrinsic,
1638 // scalarize it now.
1639 if (DemandedElts == 1) {
1640 switch (II->getIntrinsicID()) {
1641 default: break;
1642 case Intrinsic::x86_sse_sub_ss:
1643 case Intrinsic::x86_sse_mul_ss:
1644 case Intrinsic::x86_sse2_sub_sd:
1645 case Intrinsic::x86_sse2_mul_sd:
1646 // TODO: Lower MIN/MAX/ABS/etc
1647 Value *LHS = II->getOperand(1);
1648 Value *RHS = II->getOperand(2);
1649 // Extract the element as scalars.
1650 LHS = InsertNewInstBefore(new ExtractElementInst(LHS, 0U,"tmp"), *II);
1651 RHS = InsertNewInstBefore(new ExtractElementInst(RHS, 0U,"tmp"), *II);
1652
1653 switch (II->getIntrinsicID()) {
1654 default: assert(0 && "Case stmts out of sync!");
1655 case Intrinsic::x86_sse_sub_ss:
1656 case Intrinsic::x86_sse2_sub_sd:
Gabor Greife1f6e4b2008-05-16 19:29:10 +00001657 TmpV = InsertNewInstBefore(BinaryOperator::CreateSub(LHS, RHS,
Chris Lattner2deeaea2006-10-05 06:55:50 +00001658 II->getName()), *II);
1659 break;
1660 case Intrinsic::x86_sse_mul_ss:
1661 case Intrinsic::x86_sse2_mul_sd:
Gabor Greife1f6e4b2008-05-16 19:29:10 +00001662 TmpV = InsertNewInstBefore(BinaryOperator::CreateMul(LHS, RHS,
Chris Lattner2deeaea2006-10-05 06:55:50 +00001663 II->getName()), *II);
1664 break;
1665 }
1666
1667 Instruction *New =
Gabor Greife9ecc682008-04-06 20:25:17 +00001668 InsertElementInst::Create(UndefValue::get(II->getType()), TmpV, 0U,
1669 II->getName());
Chris Lattner2deeaea2006-10-05 06:55:50 +00001670 InsertNewInstBefore(New, *II);
1671 AddSoonDeadInstToWorklist(*II, 0);
1672 return New;
1673 }
1674 }
1675
1676 // Output elements are undefined if both are undefined. Consider things
1677 // like undef&0. The result is known zero, not undef.
1678 UndefElts &= UndefElts2;
1679 break;
1680 }
1681 break;
1682 }
1683 }
1684 return MadeChange ? I : 0;
1685}
1686
Dan Gohman123438c2008-05-19 22:14:15 +00001687
Chris Lattnerb8b97502003-08-13 19:01:45 +00001688/// AssociativeOpt - Perform an optimization on an associative operator. This
1689/// function is designed to check a chain of associative operators for a
1690/// potential to apply a certain optimization. Since the optimization may be
1691/// applicable if the expression was reassociated, this checks the chain, then
1692/// reassociates the expression as necessary to expose the optimization
1693/// opportunity. This makes use of a special Functor, which must define
1694/// 'shouldApply' and 'apply' methods.
1695///
1696template<typename Functor>
Dan Gohmand7177612008-05-20 01:14:05 +00001697static Instruction *AssociativeOpt(BinaryOperator &Root, const Functor &F) {
Chris Lattnerb8b97502003-08-13 19:01:45 +00001698 unsigned Opcode = Root.getOpcode();
1699 Value *LHS = Root.getOperand(0);
1700
1701 // Quick check, see if the immediate LHS matches...
1702 if (F.shouldApply(LHS))
1703 return F.apply(Root);
1704
1705 // Otherwise, if the LHS is not of the same opcode as the root, return.
1706 Instruction *LHSI = dyn_cast<Instruction>(LHS);
Chris Lattnerf95d9b92003-10-15 16:48:29 +00001707 while (LHSI && LHSI->getOpcode() == Opcode && LHSI->hasOneUse()) {
Chris Lattnerb8b97502003-08-13 19:01:45 +00001708 // Should we apply this transform to the RHS?
1709 bool ShouldApply = F.shouldApply(LHSI->getOperand(1));
1710
1711 // If not to the RHS, check to see if we should apply to the LHS...
1712 if (!ShouldApply && F.shouldApply(LHSI->getOperand(0))) {
1713 cast<BinaryOperator>(LHSI)->swapOperands(); // Make the LHS the RHS
1714 ShouldApply = true;
1715 }
1716
1717 // If the functor wants to apply the optimization to the RHS of LHSI,
1718 // reassociate the expression from ((? op A) op B) to (? op (A op B))
1719 if (ShouldApply) {
Chris Lattnerb8b97502003-08-13 19:01:45 +00001720 // Now all of the instructions are in the current basic block, go ahead
1721 // and perform the reassociation.
1722 Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
1723
1724 // First move the selected RHS to the LHS of the root...
1725 Root.setOperand(0, LHSI->getOperand(1));
1726
1727 // Make what used to be the LHS of the root be the user of the root...
1728 Value *ExtraOperand = TmpLHSI->getOperand(1);
Chris Lattner284d3b02004-04-16 18:08:07 +00001729 if (&Root == TmpLHSI) {
Chris Lattner8953b902004-04-05 02:10:19 +00001730 Root.replaceAllUsesWith(Constant::getNullValue(TmpLHSI->getType()));
1731 return 0;
1732 }
Chris Lattner284d3b02004-04-16 18:08:07 +00001733 Root.replaceAllUsesWith(TmpLHSI); // Users now use TmpLHSI
Chris Lattnerb8b97502003-08-13 19:01:45 +00001734 TmpLHSI->setOperand(1, &Root); // TmpLHSI now uses the root
Chris Lattner284d3b02004-04-16 18:08:07 +00001735 BasicBlock::iterator ARI = &Root; ++ARI;
Dan Gohmaned225092008-06-19 17:47:47 +00001736 TmpLHSI->moveBefore(ARI); // Move TmpLHSI to after Root
Chris Lattner284d3b02004-04-16 18:08:07 +00001737 ARI = Root;
Chris Lattnerb8b97502003-08-13 19:01:45 +00001738
1739 // Now propagate the ExtraOperand down the chain of instructions until we
1740 // get to LHSI.
1741 while (TmpLHSI != LHSI) {
1742 Instruction *NextLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
Chris Lattner284d3b02004-04-16 18:08:07 +00001743 // Move the instruction to immediately before the chain we are
1744 // constructing to avoid breaking dominance properties.
Dan Gohmaned225092008-06-19 17:47:47 +00001745 NextLHSI->moveBefore(ARI);
Chris Lattner284d3b02004-04-16 18:08:07 +00001746 ARI = NextLHSI;
1747
Chris Lattnerb8b97502003-08-13 19:01:45 +00001748 Value *NextOp = NextLHSI->getOperand(1);
1749 NextLHSI->setOperand(1, ExtraOperand);
1750 TmpLHSI = NextLHSI;
1751 ExtraOperand = NextOp;
1752 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00001753
Chris Lattnerb8b97502003-08-13 19:01:45 +00001754 // Now that the instructions are reassociated, have the functor perform
1755 // the transformation...
1756 return F.apply(Root);
1757 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00001758
Chris Lattnerb8b97502003-08-13 19:01:45 +00001759 LHSI = dyn_cast<Instruction>(LHSI->getOperand(0));
1760 }
1761 return 0;
1762}
1763
Dan Gohmand78c4002008-05-13 00:00:25 +00001764namespace {
Chris Lattnerb8b97502003-08-13 19:01:45 +00001765
Nick Lewycky4f3d8782008-05-23 04:34:58 +00001766// AddRHS - Implements: X + X --> X << 1
Chris Lattnerb8b97502003-08-13 19:01:45 +00001767struct AddRHS {
1768 Value *RHS;
1769 AddRHS(Value *rhs) : RHS(rhs) {}
1770 bool shouldApply(Value *LHS) const { return LHS == RHS; }
1771 Instruction *apply(BinaryOperator &Add) const {
Nick Lewycky4f3d8782008-05-23 04:34:58 +00001772 return BinaryOperator::CreateShl(Add.getOperand(0),
1773 ConstantInt::get(Add.getType(), 1));
Chris Lattnerb8b97502003-08-13 19:01:45 +00001774 }
1775};
1776
1777// AddMaskingAnd - Implements (A & C1)+(B & C2) --> (A & C1)|(B & C2)
1778// iff C1&C2 == 0
1779struct AddMaskingAnd {
1780 Constant *C2;
1781 AddMaskingAnd(Constant *c) : C2(c) {}
1782 bool shouldApply(Value *LHS) const {
Chris Lattnerd4252a72004-07-30 07:50:03 +00001783 ConstantInt *C1;
Misha Brukmanb1c93172005-04-21 23:48:37 +00001784 return match(LHS, m_And(m_Value(), m_ConstantInt(C1))) &&
Chris Lattnerd4252a72004-07-30 07:50:03 +00001785 ConstantExpr::getAnd(C1, C2)->isNullValue();
Chris Lattnerb8b97502003-08-13 19:01:45 +00001786 }
1787 Instruction *apply(BinaryOperator &Add) const {
Gabor Greife1f6e4b2008-05-16 19:29:10 +00001788 return BinaryOperator::CreateOr(Add.getOperand(0), Add.getOperand(1));
Chris Lattnerb8b97502003-08-13 19:01:45 +00001789 }
1790};
1791
Dan Gohmand78c4002008-05-13 00:00:25 +00001792}
1793
Chris Lattner86102b82005-01-01 16:22:27 +00001794static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
Chris Lattner183b3362004-04-09 19:05:30 +00001795 InstCombiner *IC) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001796 if (CastInst *CI = dyn_cast<CastInst>(&I)) {
Eli Friedman55e4bec2008-11-30 21:09:11 +00001797 return IC->InsertCastBefore(CI->getOpcode(), SO, I.getType(), I);
Chris Lattner86102b82005-01-01 16:22:27 +00001798 }
1799
Chris Lattner183b3362004-04-09 19:05:30 +00001800 // Figure out if the constant is the left or the right argument.
Chris Lattner86102b82005-01-01 16:22:27 +00001801 bool ConstIsRHS = isa<Constant>(I.getOperand(1));
1802 Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
Chris Lattnerb8b97502003-08-13 19:01:45 +00001803
Chris Lattner183b3362004-04-09 19:05:30 +00001804 if (Constant *SOC = dyn_cast<Constant>(SO)) {
1805 if (ConstIsRHS)
Chris Lattner86102b82005-01-01 16:22:27 +00001806 return ConstantExpr::get(I.getOpcode(), SOC, ConstOperand);
1807 return ConstantExpr::get(I.getOpcode(), ConstOperand, SOC);
Chris Lattner183b3362004-04-09 19:05:30 +00001808 }
1809
1810 Value *Op0 = SO, *Op1 = ConstOperand;
1811 if (!ConstIsRHS)
1812 std::swap(Op0, Op1);
1813 Instruction *New;
Chris Lattner86102b82005-01-01 16:22:27 +00001814 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
Gabor Greife1f6e4b2008-05-16 19:29:10 +00001815 New = BinaryOperator::Create(BO->getOpcode(), Op0, Op1,SO->getName()+".op");
Reid Spencer266e42b2006-12-23 06:05:41 +00001816 else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
Gabor Greife1f6e4b2008-05-16 19:29:10 +00001817 New = CmpInst::Create(CI->getOpcode(), CI->getPredicate(), Op0, Op1,
Reid Spencer266e42b2006-12-23 06:05:41 +00001818 SO->getName()+".cmp");
Chris Lattnerf9d96652004-04-10 19:15:56 +00001819 else {
Chris Lattner183b3362004-04-09 19:05:30 +00001820 assert(0 && "Unknown binary instruction type!");
Chris Lattnerf9d96652004-04-10 19:15:56 +00001821 abort();
1822 }
Chris Lattner86102b82005-01-01 16:22:27 +00001823 return IC->InsertNewInstBefore(New, I);
1824}
1825
1826// FoldOpIntoSelect - Given an instruction with a select as one operand and a
1827// constant as the other operand, try to fold the binary operator into the
1828// select arguments. This also works for Cast instructions, which obviously do
1829// not have a second operand.
1830static Instruction *FoldOpIntoSelect(Instruction &Op, SelectInst *SI,
1831 InstCombiner *IC) {
1832 // Don't modify shared select instructions
1833 if (!SI->hasOneUse()) return 0;
1834 Value *TV = SI->getOperand(1);
1835 Value *FV = SI->getOperand(2);
1836
1837 if (isa<Constant>(TV) || isa<Constant>(FV)) {
Chris Lattner374e6592005-04-21 05:43:13 +00001838 // Bool selects with constant operands can be folded to logical ops.
Reid Spencer542964f2007-01-11 18:21:29 +00001839 if (SI->getType() == Type::Int1Ty) return 0;
Chris Lattner374e6592005-04-21 05:43:13 +00001840
Chris Lattner86102b82005-01-01 16:22:27 +00001841 Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, IC);
1842 Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, IC);
1843
Gabor Greife9ecc682008-04-06 20:25:17 +00001844 return SelectInst::Create(SI->getCondition(), SelectTrueVal,
1845 SelectFalseVal);
Chris Lattner86102b82005-01-01 16:22:27 +00001846 }
1847 return 0;
Chris Lattner183b3362004-04-09 19:05:30 +00001848}
1849
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001850
1851/// FoldOpIntoPhi - Given a binary operator or cast instruction which has a PHI
1852/// node as operand #0, see if we can fold the instruction into the PHI (which
1853/// is only possible if all operands to the PHI are constants).
1854Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I) {
1855 PHINode *PN = cast<PHINode>(I.getOperand(0));
Chris Lattner7515cab2004-11-14 19:13:23 +00001856 unsigned NumPHIValues = PN->getNumIncomingValues();
Chris Lattner04689872006-09-09 22:02:56 +00001857 if (!PN->hasOneUse() || NumPHIValues == 0) return 0;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001858
Chris Lattner04689872006-09-09 22:02:56 +00001859 // Check to see if all of the operands of the PHI are constants. If there is
1860 // one non-constant value, remember the BB it is. If there is more than one
Chris Lattnerc4d8e7e2007-02-24 01:03:45 +00001861 // or if *it* is a PHI, bail out.
Chris Lattner04689872006-09-09 22:02:56 +00001862 BasicBlock *NonConstBB = 0;
1863 for (unsigned i = 0; i != NumPHIValues; ++i)
1864 if (!isa<Constant>(PN->getIncomingValue(i))) {
1865 if (NonConstBB) return 0; // More than one non-const value.
Chris Lattnerc4d8e7e2007-02-24 01:03:45 +00001866 if (isa<PHINode>(PN->getIncomingValue(i))) return 0; // Itself a phi.
Chris Lattner04689872006-09-09 22:02:56 +00001867 NonConstBB = PN->getIncomingBlock(i);
1868
1869 // If the incoming non-constant value is in I's block, we have an infinite
1870 // loop.
1871 if (NonConstBB == I.getParent())
1872 return 0;
1873 }
1874
1875 // If there is exactly one non-constant value, we can insert a copy of the
1876 // operation in that block. However, if this is a critical edge, we would be
1877 // inserting the computation one some other paths (e.g. inside a loop). Only
1878 // do this if the pred block is unconditionally branching into the phi block.
1879 if (NonConstBB) {
1880 BranchInst *BI = dyn_cast<BranchInst>(NonConstBB->getTerminator());
1881 if (!BI || !BI->isUnconditional()) return 0;
1882 }
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001883
1884 // Okay, we can do the transformation: create the new PHI node.
Gabor Greife9ecc682008-04-06 20:25:17 +00001885 PHINode *NewPN = PHINode::Create(I.getType(), "");
Chris Lattnerd8e20182005-01-29 00:39:08 +00001886 NewPN->reserveOperandSpace(PN->getNumOperands()/2);
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001887 InsertNewInstBefore(NewPN, *PN);
Chris Lattner6e0123b2007-02-11 01:23:03 +00001888 NewPN->takeName(PN);
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001889
1890 // Next, add all of the operands to the PHI.
1891 if (I.getNumOperands() == 2) {
1892 Constant *C = cast<Constant>(I.getOperand(1));
Chris Lattner7515cab2004-11-14 19:13:23 +00001893 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattnerf0da7972007-08-05 08:47:58 +00001894 Value *InV = 0;
Chris Lattner04689872006-09-09 22:02:56 +00001895 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
Reid Spencer266e42b2006-12-23 06:05:41 +00001896 if (CmpInst *CI = dyn_cast<CmpInst>(&I))
1897 InV = ConstantExpr::getCompare(CI->getPredicate(), InC, C);
1898 else
1899 InV = ConstantExpr::get(I.getOpcode(), InC, C);
Chris Lattner04689872006-09-09 22:02:56 +00001900 } else {
1901 assert(PN->getIncomingBlock(i) == NonConstBB);
1902 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
Gabor Greife1f6e4b2008-05-16 19:29:10 +00001903 InV = BinaryOperator::Create(BO->getOpcode(),
Chris Lattner04689872006-09-09 22:02:56 +00001904 PN->getIncomingValue(i), C, "phitmp",
1905 NonConstBB->getTerminator());
Reid Spencer266e42b2006-12-23 06:05:41 +00001906 else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
Gabor Greife1f6e4b2008-05-16 19:29:10 +00001907 InV = CmpInst::Create(CI->getOpcode(),
Reid Spencer266e42b2006-12-23 06:05:41 +00001908 CI->getPredicate(),
1909 PN->getIncomingValue(i), C, "phitmp",
1910 NonConstBB->getTerminator());
Chris Lattner04689872006-09-09 22:02:56 +00001911 else
1912 assert(0 && "Unknown binop!");
1913
Chris Lattnerb15e2b12007-03-02 21:28:56 +00001914 AddToWorkList(cast<Instruction>(InV));
Chris Lattner04689872006-09-09 22:02:56 +00001915 }
1916 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001917 }
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001918 } else {
1919 CastInst *CI = cast<CastInst>(&I);
1920 const Type *RetTy = CI->getType();
Chris Lattner7515cab2004-11-14 19:13:23 +00001921 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattner04689872006-09-09 22:02:56 +00001922 Value *InV;
1923 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001924 InV = ConstantExpr::getCast(CI->getOpcode(), InC, RetTy);
Chris Lattner04689872006-09-09 22:02:56 +00001925 } else {
1926 assert(PN->getIncomingBlock(i) == NonConstBB);
Gabor Greife1f6e4b2008-05-16 19:29:10 +00001927 InV = CastInst::Create(CI->getOpcode(), PN->getIncomingValue(i),
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001928 I.getType(), "phitmp",
1929 NonConstBB->getTerminator());
Chris Lattnerb15e2b12007-03-02 21:28:56 +00001930 AddToWorkList(cast<Instruction>(InV));
Chris Lattner04689872006-09-09 22:02:56 +00001931 }
1932 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001933 }
1934 }
1935 return ReplaceInstUsesWith(I, NewPN);
1936}
1937
Chris Lattner17819d92008-01-29 06:52:45 +00001938
Chris Lattner7ac943f2008-05-20 05:46:13 +00001939/// WillNotOverflowSignedAdd - Return true if we can prove that:
1940/// (sext (add LHS, RHS)) === (add (sext LHS), (sext RHS))
1941/// This basically requires proving that the add in the original type would not
1942/// overflow to change the sign bit or have a carry out.
1943bool InstCombiner::WillNotOverflowSignedAdd(Value *LHS, Value *RHS) {
1944 // There are different heuristics we can use for this. Here are some simple
1945 // ones.
1946
1947 // Add has the property that adding any two 2's complement numbers can only
1948 // have one carry bit which can change a sign. As such, if LHS and RHS each
1949 // have at least two sign bits, we know that the addition of the two values will
1950 // sign extend fine.
1951 if (ComputeNumSignBits(LHS) > 1 && ComputeNumSignBits(RHS) > 1)
1952 return true;
1953
1954
1955 // If one of the operands only has one non-zero bit, and if the other operand
1956 // has a known-zero bit in a more significant place than it (not including the
1957 // sign bit) the ripple may go up to and fill the zero, but won't change the
1958 // sign. For example, (X & ~4) + 1.
1959
1960 // TODO: Implement.
1961
1962 return false;
1963}
1964
Chris Lattner17819d92008-01-29 06:52:45 +00001965
Chris Lattner113f4f42002-06-25 16:13:24 +00001966Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00001967 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00001968 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
Chris Lattner9fa53de2002-05-06 16:49:18 +00001969
Chris Lattnercf4a9962004-04-10 22:01:55 +00001970 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
Chris Lattner81a7a232004-10-16 18:11:37 +00001971 // X + undef -> undef
1972 if (isa<UndefValue>(RHS))
1973 return ReplaceInstUsesWith(I, RHS);
1974
Chris Lattnercf4a9962004-04-10 22:01:55 +00001975 // X + 0 --> X
Chris Lattner7a002fe2006-12-02 00:13:08 +00001976 if (!I.getType()->isFPOrFPVector()) { // NOTE: -0 + +0 = +0.
Chris Lattner7fde91e2005-10-17 17:56:38 +00001977 if (RHSC->isNullValue())
1978 return ReplaceInstUsesWith(I, LHS);
Chris Lattnerda1b1522005-10-17 20:18:38 +00001979 } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
Dale Johannesen98d3a082007-09-14 22:26:36 +00001980 if (CFP->isExactlyValue(ConstantFP::getNegativeZero
1981 (I.getType())->getValueAPF()))
Chris Lattnerda1b1522005-10-17 20:18:38 +00001982 return ReplaceInstUsesWith(I, LHS);
Chris Lattner7fde91e2005-10-17 17:56:38 +00001983 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00001984
Chris Lattnercf4a9962004-04-10 22:01:55 +00001985 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHSC)) {
Chris Lattner6e2c15c2006-11-09 05:12:27 +00001986 // X + (signbit) --> X ^ signbit
Zhou Sheng150f3bb2007-04-01 17:13:37 +00001987 const APInt& Val = CI->getValue();
Zhou Sheng56cda952007-04-02 08:20:41 +00001988 uint32_t BitWidth = Val.getBitWidth();
Reid Spencer959a21d2007-03-23 21:24:59 +00001989 if (Val == APInt::getSignBit(BitWidth))
Gabor Greife1f6e4b2008-05-16 19:29:10 +00001990 return BinaryOperator::CreateXor(LHS, RHS);
Chris Lattner6e2c15c2006-11-09 05:12:27 +00001991
1992 // See if SimplifyDemandedBits can simplify this. This handles stuff like
1993 // (X & 254)+1 -> (X&254)|1
Reid Spencer959a21d2007-03-23 21:24:59 +00001994 if (!isa<VectorType>(I.getType())) {
1995 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
1996 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
1997 KnownZero, KnownOne))
1998 return &I;
1999 }
Dan Gohman13cbcf1c182008-10-30 20:40:10 +00002000
2001 // zext(i1) - 1 -> select i1, 0, -1
2002 if (ZExtInst *ZI = dyn_cast<ZExtInst>(LHS))
2003 if (CI->isAllOnesValue() &&
2004 ZI->getOperand(0)->getType() == Type::Int1Ty)
2005 return SelectInst::Create(ZI->getOperand(0),
2006 Constant::getNullValue(I.getType()),
2007 ConstantInt::getAllOnesValue(I.getType()));
Chris Lattnercf4a9962004-04-10 22:01:55 +00002008 }
Chris Lattner6a4adcd2004-09-29 05:07:12 +00002009
2010 if (isa<PHINode>(LHS))
2011 if (Instruction *NV = FoldOpIntoPhi(I))
2012 return NV;
Chris Lattner0b3557f2005-09-24 23:43:33 +00002013
Chris Lattner330628a2006-01-06 17:59:59 +00002014 ConstantInt *XorRHS = 0;
2015 Value *XorLHS = 0;
Chris Lattner4284f642007-01-30 22:32:46 +00002016 if (isa<ConstantInt>(RHSC) &&
2017 match(LHS, m_Xor(m_Value(XorLHS), m_ConstantInt(XorRHS)))) {
Zhou Sheng56cda952007-04-02 08:20:41 +00002018 uint32_t TySizeBits = I.getType()->getPrimitiveSizeInBits();
Zhou Sheng150f3bb2007-04-01 17:13:37 +00002019 const APInt& RHSVal = cast<ConstantInt>(RHSC)->getValue();
Chris Lattner0b3557f2005-09-24 23:43:33 +00002020
Zhou Sheng56cda952007-04-02 08:20:41 +00002021 uint32_t Size = TySizeBits / 2;
Reid Spencer959a21d2007-03-23 21:24:59 +00002022 APInt C0080Val(APInt(TySizeBits, 1ULL).shl(Size - 1));
2023 APInt CFF80Val(-C0080Val);
Chris Lattner0b3557f2005-09-24 23:43:33 +00002024 do {
2025 if (TySizeBits > Size) {
Chris Lattner0b3557f2005-09-24 23:43:33 +00002026 // If we have ADD(XOR(AND(X, 0xFF), 0x80), 0xF..F80), it's a sext.
2027 // If we have ADD(XOR(AND(X, 0xFF), 0xF..F80), 0x80), it's a sext.
Reid Spencer959a21d2007-03-23 21:24:59 +00002028 if ((RHSVal == CFF80Val && XorRHS->getValue() == C0080Val) ||
2029 (RHSVal == C0080Val && XorRHS->getValue() == CFF80Val)) {
Chris Lattner0b3557f2005-09-24 23:43:33 +00002030 // This is a sign extend if the top bits are known zero.
Zhou Shengb3a80b12007-03-29 08:15:12 +00002031 if (!MaskedValueIsZero(XorLHS,
2032 APInt::getHighBitsSet(TySizeBits, TySizeBits - Size)))
Chris Lattner0b3557f2005-09-24 23:43:33 +00002033 Size = 0; // Not a sign ext, but can't be any others either.
Reid Spencer959a21d2007-03-23 21:24:59 +00002034 break;
Chris Lattner0b3557f2005-09-24 23:43:33 +00002035 }
2036 }
2037 Size >>= 1;
Reid Spencer959a21d2007-03-23 21:24:59 +00002038 C0080Val = APIntOps::lshr(C0080Val, Size);
2039 CFF80Val = APIntOps::ashr(CFF80Val, Size);
2040 } while (Size >= 1);
Chris Lattner0b3557f2005-09-24 23:43:33 +00002041
Reid Spencera5c18bf2007-03-28 01:36:16 +00002042 // FIXME: This shouldn't be necessary. When the backends can handle types
Chris Lattnere35fe0f2008-05-19 20:25:04 +00002043 // with funny bit widths then this switch statement should be removed. It
2044 // is just here to get the size of the "middle" type back up to something
2045 // that the back ends can handle.
Reid Spencera5c18bf2007-03-28 01:36:16 +00002046 const Type *MiddleType = 0;
2047 switch (Size) {
2048 default: break;
2049 case 32: MiddleType = Type::Int32Ty; break;
2050 case 16: MiddleType = Type::Int16Ty; break;
2051 case 8: MiddleType = Type::Int8Ty; break;
2052 }
2053 if (MiddleType) {
Reid Spencerbb65ebf2006-12-12 23:36:14 +00002054 Instruction *NewTrunc = new TruncInst(XorLHS, MiddleType, "sext");
Chris Lattner0b3557f2005-09-24 23:43:33 +00002055 InsertNewInstBefore(NewTrunc, I);
Reid Spencera5c18bf2007-03-28 01:36:16 +00002056 return new SExtInst(NewTrunc, I.getType(), I.getName());
Chris Lattner0b3557f2005-09-24 23:43:33 +00002057 }
2058 }
Chris Lattnercf4a9962004-04-10 22:01:55 +00002059 }
Chris Lattner9fa53de2002-05-06 16:49:18 +00002060
Nick Lewycky26b8cd82008-05-31 17:59:52 +00002061 if (I.getType() == Type::Int1Ty)
2062 return BinaryOperator::CreateXor(LHS, RHS);
2063
Nick Lewycky8f3127c2008-05-23 04:39:38 +00002064 // X + X --> X << 1
Nick Lewycky26b8cd82008-05-31 17:59:52 +00002065 if (I.getType()->isInteger()) {
Chris Lattnerb8b97502003-08-13 19:01:45 +00002066 if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS))) return Result;
Chris Lattner47060462005-04-07 17:14:51 +00002067
2068 if (Instruction *RHSI = dyn_cast<Instruction>(RHS)) {
2069 if (RHSI->getOpcode() == Instruction::Sub)
2070 if (LHS == RHSI->getOperand(1)) // A + (B - A) --> B
2071 return ReplaceInstUsesWith(I, RHSI->getOperand(0));
2072 }
2073 if (Instruction *LHSI = dyn_cast<Instruction>(LHS)) {
2074 if (LHSI->getOpcode() == Instruction::Sub)
2075 if (RHS == LHSI->getOperand(1)) // (B - A) + A --> B
2076 return ReplaceInstUsesWith(I, LHSI->getOperand(0));
2077 }
Robert Bocchino7b5b86c2004-07-27 21:02:21 +00002078 }
Chris Lattnerede3fe02003-08-13 04:18:28 +00002079
Chris Lattner147e9752002-05-08 22:46:53 +00002080 // -A + B --> B - A
Chris Lattnercc226012008-02-17 21:03:36 +00002081 // -A + -B --> -(A + B)
2082 if (Value *LHSV = dyn_castNegVal(LHS)) {
Chris Lattner1e3c5012008-02-18 17:50:16 +00002083 if (LHS->getType()->isIntOrIntVector()) {
2084 if (Value *RHSV = dyn_castNegVal(RHS)) {
Gabor Greife1f6e4b2008-05-16 19:29:10 +00002085 Instruction *NewAdd = BinaryOperator::CreateAdd(LHSV, RHSV, "sum");
Chris Lattner1e3c5012008-02-18 17:50:16 +00002086 InsertNewInstBefore(NewAdd, I);
Gabor Greife1f6e4b2008-05-16 19:29:10 +00002087 return BinaryOperator::CreateNeg(NewAdd);
Chris Lattner1e3c5012008-02-18 17:50:16 +00002088 }
Chris Lattnercc226012008-02-17 21:03:36 +00002089 }
2090
Gabor Greife1f6e4b2008-05-16 19:29:10 +00002091 return BinaryOperator::CreateSub(RHS, LHSV);
Chris Lattnercc226012008-02-17 21:03:36 +00002092 }
Chris Lattner9fa53de2002-05-06 16:49:18 +00002093
2094 // A + -B --> A - B
Chris Lattnerbb74e222003-03-10 23:06:50 +00002095 if (!isa<Constant>(RHS))
2096 if (Value *V = dyn_castNegVal(RHS))
Gabor Greife1f6e4b2008-05-16 19:29:10 +00002097 return BinaryOperator::CreateSub(LHS, V);
Chris Lattner260ab202002-04-18 17:39:14 +00002098
Misha Brukmanb1c93172005-04-21 23:48:37 +00002099
Chris Lattner8c3e7b92004-11-13 19:50:12 +00002100 ConstantInt *C2;
2101 if (Value *X = dyn_castFoldableMul(LHS, C2)) {
2102 if (X == RHS) // X*C + X --> X * (C+1)
Gabor Greife1f6e4b2008-05-16 19:29:10 +00002103 return BinaryOperator::CreateMul(RHS, AddOne(C2));
Chris Lattner8c3e7b92004-11-13 19:50:12 +00002104
2105 // X*C1 + X*C2 --> X * (C1+C2)
2106 ConstantInt *C1;
2107 if (X == dyn_castFoldableMul(RHS, C1))
Gabor Greife1f6e4b2008-05-16 19:29:10 +00002108 return BinaryOperator::CreateMul(X, Add(C1, C2));
Chris Lattner57c8d992003-02-18 19:57:07 +00002109 }
2110
2111 // X + X*C --> X * (C+1)
Chris Lattner8c3e7b92004-11-13 19:50:12 +00002112 if (dyn_castFoldableMul(RHS, C2) == LHS)
Gabor Greife1f6e4b2008-05-16 19:29:10 +00002113 return BinaryOperator::CreateMul(LHS, AddOne(C2));
Chris Lattner8c3e7b92004-11-13 19:50:12 +00002114
Chris Lattner23eb8ec2007-01-05 02:17:46 +00002115 // X + ~X --> -1 since ~X = -X-1
Chris Lattner37338922007-06-15 06:23:19 +00002116 if (dyn_castNotVal(LHS) == RHS || dyn_castNotVal(RHS) == LHS)
2117 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattner23eb8ec2007-01-05 02:17:46 +00002118
Chris Lattner57c8d992003-02-18 19:57:07 +00002119
Chris Lattnerb8b97502003-08-13 19:01:45 +00002120 // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
Chris Lattnerd4252a72004-07-30 07:50:03 +00002121 if (match(RHS, m_And(m_Value(), m_ConstantInt(C2))))
Chris Lattner23eb8ec2007-01-05 02:17:46 +00002122 if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2)))
2123 return R;
Chris Lattnerfc365b62008-05-19 20:01:56 +00002124
2125 // A+B --> A|B iff A and B have no bits set in common.
2126 if (const IntegerType *IT = dyn_cast<IntegerType>(I.getType())) {
2127 APInt Mask = APInt::getAllOnesValue(IT->getBitWidth());
2128 APInt LHSKnownOne(IT->getBitWidth(), 0);
2129 APInt LHSKnownZero(IT->getBitWidth(), 0);
2130 ComputeMaskedBits(LHS, Mask, LHSKnownZero, LHSKnownOne);
2131 if (LHSKnownZero != 0) {
2132 APInt RHSKnownOne(IT->getBitWidth(), 0);
2133 APInt RHSKnownZero(IT->getBitWidth(), 0);
2134 ComputeMaskedBits(RHS, Mask, RHSKnownZero, RHSKnownOne);
2135
2136 // No bits in common -> bitwise or.
Chris Lattner6e708302008-05-19 20:03:53 +00002137 if ((LHSKnownZero|RHSKnownZero).isAllOnesValue())
Chris Lattnerfc365b62008-05-19 20:01:56 +00002138 return BinaryOperator::CreateOr(LHS, RHS);
Chris Lattnerfc365b62008-05-19 20:01:56 +00002139 }
2140 }
Chris Lattner7fb29e12003-03-11 00:12:48 +00002141
Nick Lewyckye6e3a7f2008-02-03 07:42:09 +00002142 // W*X + Y*Z --> W * (X+Z) iff W == Y
Nick Lewyckyc7a4ba02008-02-03 08:19:11 +00002143 if (I.getType()->isIntOrIntVector()) {
Nick Lewyckye6e3a7f2008-02-03 07:42:09 +00002144 Value *W, *X, *Y, *Z;
2145 if (match(LHS, m_Mul(m_Value(W), m_Value(X))) &&
2146 match(RHS, m_Mul(m_Value(Y), m_Value(Z)))) {
2147 if (W != Y) {
2148 if (W == Z) {
Bill Wendlingd188e032008-02-26 10:53:30 +00002149 std::swap(Y, Z);
Nick Lewyckye6e3a7f2008-02-03 07:42:09 +00002150 } else if (Y == X) {
Bill Wendlingd188e032008-02-26 10:53:30 +00002151 std::swap(W, X);
2152 } else if (X == Z) {
Nick Lewyckye6e3a7f2008-02-03 07:42:09 +00002153 std::swap(Y, Z);
2154 std::swap(W, X);
2155 }
2156 }
2157
2158 if (W == Y) {
Gabor Greife1f6e4b2008-05-16 19:29:10 +00002159 Value *NewAdd = InsertNewInstBefore(BinaryOperator::CreateAdd(X, Z,
Nick Lewyckye6e3a7f2008-02-03 07:42:09 +00002160 LHS->getName()), I);
Gabor Greife1f6e4b2008-05-16 19:29:10 +00002161 return BinaryOperator::CreateMul(W, NewAdd);
Nick Lewyckye6e3a7f2008-02-03 07:42:09 +00002162 }
2163 }
2164 }
2165
Chris Lattnerb9cde762003-10-02 15:11:26 +00002166 if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
Chris Lattner330628a2006-01-06 17:59:59 +00002167 Value *X = 0;
Reid Spencer80263aa2007-03-25 05:33:51 +00002168 if (match(LHS, m_Not(m_Value(X)))) // ~X + C --> (C-1) - X
Gabor Greife1f6e4b2008-05-16 19:29:10 +00002169 return BinaryOperator::CreateSub(SubOne(CRHS), X);
Chris Lattnerd4252a72004-07-30 07:50:03 +00002170
Chris Lattnerbff91d92004-10-08 05:07:56 +00002171 // (X & FF00) + xx00 -> (X+xx00) & FF00
2172 if (LHS->hasOneUse() && match(LHS, m_And(m_Value(X), m_ConstantInt(C2)))) {
Reid Spencer80263aa2007-03-25 05:33:51 +00002173 Constant *Anded = And(CRHS, C2);
Chris Lattnerbff91d92004-10-08 05:07:56 +00002174 if (Anded == CRHS) {
2175 // See if all bits from the first bit set in the Add RHS up are included
2176 // in the mask. First, get the rightmost bit.
Zhou Sheng150f3bb2007-04-01 17:13:37 +00002177 const APInt& AddRHSV = CRHS->getValue();
Chris Lattnerbff91d92004-10-08 05:07:56 +00002178
2179 // Form a mask of all bits from the lowest bit added through the top.
Zhou Sheng150f3bb2007-04-01 17:13:37 +00002180 APInt AddRHSHighBits(~((AddRHSV & -AddRHSV)-1));
Chris Lattnerbff91d92004-10-08 05:07:56 +00002181
2182 // See if the and mask includes all of these bits.
Zhou Sheng150f3bb2007-04-01 17:13:37 +00002183 APInt AddRHSHighBitsAnd(AddRHSHighBits & C2->getValue());
Misha Brukmanb1c93172005-04-21 23:48:37 +00002184
Chris Lattnerbff91d92004-10-08 05:07:56 +00002185 if (AddRHSHighBits == AddRHSHighBitsAnd) {
2186 // Okay, the xform is safe. Insert the new add pronto.
Gabor Greife1f6e4b2008-05-16 19:29:10 +00002187 Value *NewAdd = InsertNewInstBefore(BinaryOperator::CreateAdd(X, CRHS,
Chris Lattnerbff91d92004-10-08 05:07:56 +00002188 LHS->getName()), I);
Gabor Greife1f6e4b2008-05-16 19:29:10 +00002189 return BinaryOperator::CreateAnd(NewAdd, C2);
Chris Lattnerbff91d92004-10-08 05:07:56 +00002190 }
2191 }
2192 }
2193
Chris Lattnerd4252a72004-07-30 07:50:03 +00002194 // Try to fold constant add into select arguments.
2195 if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
Chris Lattner86102b82005-01-01 16:22:27 +00002196 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattnerd4252a72004-07-30 07:50:03 +00002197 return R;
Chris Lattnerb9cde762003-10-02 15:11:26 +00002198 }
2199
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002200 // add (cast *A to intptrtype) B ->
Chris Lattner16a51da2007-12-20 01:56:58 +00002201 // cast (GEP (cast *A to sbyte*) B) --> intptrtype
Andrew Lenharth4f339be2006-09-19 18:24:51 +00002202 {
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002203 CastInst *CI = dyn_cast<CastInst>(LHS);
2204 Value *Other = RHS;
Andrew Lenharth4f339be2006-09-19 18:24:51 +00002205 if (!CI) {
2206 CI = dyn_cast<CastInst>(RHS);
2207 Other = LHS;
2208 }
Andrew Lenharth44cb67a2006-09-20 15:37:57 +00002209 if (CI && CI->getType()->isSized() &&
Reid Spencer8f166b02007-01-08 16:32:00 +00002210 (CI->getType()->getPrimitiveSizeInBits() ==
2211 TD->getIntPtrType()->getPrimitiveSizeInBits())
Andrew Lenharth44cb67a2006-09-20 15:37:57 +00002212 && isa<PointerType>(CI->getOperand(0)->getType())) {
Christopher Lambedf07882007-12-17 01:12:55 +00002213 unsigned AS =
2214 cast<PointerType>(CI->getOperand(0)->getType())->getAddressSpace();
Chris Lattner5a866122008-01-13 22:23:22 +00002215 Value *I2 = InsertBitCastBefore(CI->getOperand(0),
2216 PointerType::get(Type::Int8Ty, AS), I);
Gabor Greife9ecc682008-04-06 20:25:17 +00002217 I2 = InsertNewInstBefore(GetElementPtrInst::Create(I2, Other, "ctg2"), I);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002218 return new PtrToIntInst(I2, CI->getType());
Andrew Lenharth4f339be2006-09-19 18:24:51 +00002219 }
2220 }
Christopher Lamb8b09a462007-12-18 09:34:41 +00002221
Chris Lattner16a51da2007-12-20 01:56:58 +00002222 // add (select X 0 (sub n A)) A --> select X A n
Christopher Lamb8b09a462007-12-18 09:34:41 +00002223 {
2224 SelectInst *SI = dyn_cast<SelectInst>(LHS);
Chris Lattnerf1be2852008-11-16 04:46:19 +00002225 Value *A = RHS;
Christopher Lamb8b09a462007-12-18 09:34:41 +00002226 if (!SI) {
2227 SI = dyn_cast<SelectInst>(RHS);
Chris Lattnerf1be2852008-11-16 04:46:19 +00002228 A = LHS;
Christopher Lamb8b09a462007-12-18 09:34:41 +00002229 }
Chris Lattner16a51da2007-12-20 01:56:58 +00002230 if (SI && SI->hasOneUse()) {
Christopher Lamb8b09a462007-12-18 09:34:41 +00002231 Value *TV = SI->getTrueValue();
2232 Value *FV = SI->getFalseValue();
Chris Lattnerf1be2852008-11-16 04:46:19 +00002233 Value *N;
Christopher Lamb8b09a462007-12-18 09:34:41 +00002234
2235 // Can we fold the add into the argument of the select?
2236 // We check both true and false select arguments for a matching subtract.
Chris Lattnerf1be2852008-11-16 04:46:19 +00002237 if (match(FV, m_Zero()) && match(TV, m_Sub(m_Value(N), m_Specific(A))))
2238 // Fold the add into the true select value.
Gabor Greife9ecc682008-04-06 20:25:17 +00002239 return SelectInst::Create(SI->getCondition(), N, A);
Chris Lattnerf1be2852008-11-16 04:46:19 +00002240 if (match(TV, m_Zero()) && match(FV, m_Sub(m_Value(N), m_Specific(A))))
2241 // Fold the add into the false select value.
Gabor Greife9ecc682008-04-06 20:25:17 +00002242 return SelectInst::Create(SI->getCondition(), A, N);
Christopher Lamb8b09a462007-12-18 09:34:41 +00002243 }
2244 }
Chris Lattner17819d92008-01-29 06:52:45 +00002245
2246 // Check for X+0.0. Simplify it to X if we know X is not -0.0.
2247 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS))
2248 if (CFP->getValueAPF().isPosZero() && CannotBeNegativeZero(LHS))
2249 return ReplaceInstUsesWith(I, LHS);
Andrew Lenharth4f339be2006-09-19 18:24:51 +00002250
Chris Lattner7ac943f2008-05-20 05:46:13 +00002251 // Check for (add (sext x), y), see if we can merge this into an
2252 // integer add followed by a sext.
2253 if (SExtInst *LHSConv = dyn_cast<SExtInst>(LHS)) {
2254 // (add (sext x), cst) --> (sext (add x, cst'))
2255 if (ConstantInt *RHSC = dyn_cast<ConstantInt>(RHS)) {
2256 Constant *CI =
2257 ConstantExpr::getTrunc(RHSC, LHSConv->getOperand(0)->getType());
2258 if (LHSConv->hasOneUse() &&
2259 ConstantExpr::getSExt(CI, I.getType()) == RHSC &&
2260 WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
2261 // Insert the new, smaller add.
2262 Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0),
2263 CI, "addconv");
2264 InsertNewInstBefore(NewAdd, I);
2265 return new SExtInst(NewAdd, I.getType());
2266 }
2267 }
2268
2269 // (add (sext x), (sext y)) --> (sext (add int x, y))
2270 if (SExtInst *RHSConv = dyn_cast<SExtInst>(RHS)) {
2271 // Only do this if x/y have the same type, if at last one of them has a
2272 // single use (so we don't increase the number of sexts), and if the
2273 // integer add will not overflow.
2274 if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
2275 (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
2276 WillNotOverflowSignedAdd(LHSConv->getOperand(0),
2277 RHSConv->getOperand(0))) {
2278 // Insert the new integer add.
2279 Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0),
2280 RHSConv->getOperand(0),
2281 "addconv");
2282 InsertNewInstBefore(NewAdd, I);
2283 return new SExtInst(NewAdd, I.getType());
2284 }
2285 }
2286 }
2287
2288 // Check for (add double (sitofp x), y), see if we can merge this into an
2289 // integer add followed by a promotion.
2290 if (SIToFPInst *LHSConv = dyn_cast<SIToFPInst>(LHS)) {
2291 // (add double (sitofp x), fpcst) --> (sitofp (add int x, intcst))
2292 // ... if the constant fits in the integer value. This is useful for things
2293 // like (double)(x & 1234) + 4.0 -> (double)((X & 1234)+4) which no longer
2294 // requires a constant pool load, and generally allows the add to be better
2295 // instcombined.
2296 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS)) {
2297 Constant *CI =
2298 ConstantExpr::getFPToSI(CFP, LHSConv->getOperand(0)->getType());
2299 if (LHSConv->hasOneUse() &&
2300 ConstantExpr::getSIToFP(CI, I.getType()) == CFP &&
2301 WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
2302 // Insert the new integer add.
2303 Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0),
2304 CI, "addconv");
2305 InsertNewInstBefore(NewAdd, I);
2306 return new SIToFPInst(NewAdd, I.getType());
2307 }
2308 }
2309
2310 // (add double (sitofp x), (sitofp y)) --> (sitofp (add int x, y))
2311 if (SIToFPInst *RHSConv = dyn_cast<SIToFPInst>(RHS)) {
2312 // Only do this if x/y have the same type, if at last one of them has a
2313 // single use (so we don't increase the number of int->fp conversions),
2314 // and if the integer add will not overflow.
2315 if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
2316 (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
2317 WillNotOverflowSignedAdd(LHSConv->getOperand(0),
2318 RHSConv->getOperand(0))) {
2319 // Insert the new integer add.
2320 Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0),
2321 RHSConv->getOperand(0),
2322 "addconv");
2323 InsertNewInstBefore(NewAdd, I);
2324 return new SIToFPInst(NewAdd, I.getType());
2325 }
2326 }
2327 }
2328
Chris Lattner113f4f42002-06-25 16:13:24 +00002329 return Changed ? &I : 0;
Chris Lattner260ab202002-04-18 17:39:14 +00002330}
2331
Chris Lattner113f4f42002-06-25 16:13:24 +00002332Instruction *InstCombiner::visitSub(BinaryOperator &I) {
Chris Lattner113f4f42002-06-25 16:13:24 +00002333 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002334
Chris Lattnerc600c532008-07-17 06:07:20 +00002335 if (Op0 == Op1 && // sub X, X -> 0
2336 !I.getType()->isFPOrFPVector())
Chris Lattnere6794492002-08-12 21:17:25 +00002337 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner260ab202002-04-18 17:39:14 +00002338
Chris Lattnere6794492002-08-12 21:17:25 +00002339 // If this is a 'B = x-(-A)', change to B = x+A...
Chris Lattnerbb74e222003-03-10 23:06:50 +00002340 if (Value *V = dyn_castNegVal(Op1))
Gabor Greife1f6e4b2008-05-16 19:29:10 +00002341 return BinaryOperator::CreateAdd(Op0, V);
Chris Lattner9fa53de2002-05-06 16:49:18 +00002342
Chris Lattner81a7a232004-10-16 18:11:37 +00002343 if (isa<UndefValue>(Op0))
2344 return ReplaceInstUsesWith(I, Op0); // undef - X -> undef
2345 if (isa<UndefValue>(Op1))
2346 return ReplaceInstUsesWith(I, Op1); // X - undef -> undef
2347
Chris Lattner8f2f5982003-11-05 01:06:05 +00002348 if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
2349 // Replace (-1 - A) with (~A)...
Chris Lattner3082c5a2003-02-18 19:28:33 +00002350 if (C->isAllOnesValue())
Gabor Greife1f6e4b2008-05-16 19:29:10 +00002351 return BinaryOperator::CreateNot(Op1);
Chris Lattnerad3c4952002-05-09 01:29:19 +00002352
Chris Lattner8f2f5982003-11-05 01:06:05 +00002353 // C - ~X == X + (1+C)
Reid Spencer4fdd96c2005-06-18 17:37:34 +00002354 Value *X = 0;
Chris Lattnerd4252a72004-07-30 07:50:03 +00002355 if (match(Op1, m_Not(m_Value(X))))
Gabor Greife1f6e4b2008-05-16 19:29:10 +00002356 return BinaryOperator::CreateAdd(X, AddOne(C));
Reid Spencer80263aa2007-03-25 05:33:51 +00002357
Chris Lattner27df1db2007-01-15 07:02:54 +00002358 // -(X >>u 31) -> (X >>s 31)
2359 // -(X >>s 31) -> (X >>u 31)
Zhou Shengfd28a332007-03-30 17:20:39 +00002360 if (C->isZero()) {
Anton Korobeynikov1bfd1212008-02-20 11:26:25 +00002361 if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op1)) {
Reid Spencerfdff9382006-11-08 06:47:33 +00002362 if (SI->getOpcode() == Instruction::LShr) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00002363 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
Chris Lattner92295c52004-03-12 23:53:13 +00002364 // Check to see if we are shifting out everything but the sign bit.
Zhou Shengfd28a332007-03-30 17:20:39 +00002365 if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
Reid Spencere0fc4df2006-10-20 07:07:24 +00002366 SI->getType()->getPrimitiveSizeInBits()-1) {
Reid Spencerfdff9382006-11-08 06:47:33 +00002367 // Ok, the transformation is safe. Insert AShr.
Gabor Greife1f6e4b2008-05-16 19:29:10 +00002368 return BinaryOperator::Create(Instruction::AShr,
Reid Spencer2341c222007-02-02 02:16:23 +00002369 SI->getOperand(0), CU, SI->getName());
Chris Lattner92295c52004-03-12 23:53:13 +00002370 }
2371 }
Reid Spencerfdff9382006-11-08 06:47:33 +00002372 }
2373 else if (SI->getOpcode() == Instruction::AShr) {
2374 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2375 // Check to see if we are shifting out everything but the sign bit.
Zhou Shengfd28a332007-03-30 17:20:39 +00002376 if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
Reid Spencerfdff9382006-11-08 06:47:33 +00002377 SI->getType()->getPrimitiveSizeInBits()-1) {
Reid Spencerc635f472006-12-31 05:48:39 +00002378 // Ok, the transformation is safe. Insert LShr.
Gabor Greife1f6e4b2008-05-16 19:29:10 +00002379 return BinaryOperator::CreateLShr(
Reid Spencer2341c222007-02-02 02:16:23 +00002380 SI->getOperand(0), CU, SI->getName());
Reid Spencerfdff9382006-11-08 06:47:33 +00002381 }
2382 }
Anton Korobeynikov1bfd1212008-02-20 11:26:25 +00002383 }
2384 }
Chris Lattner022167f2004-03-13 00:11:49 +00002385 }
Chris Lattner183b3362004-04-09 19:05:30 +00002386
2387 // Try to fold constant sub into select arguments.
2388 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner86102b82005-01-01 16:22:27 +00002389 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00002390 return R;
Chris Lattner8f2f5982003-11-05 01:06:05 +00002391 }
2392
Nick Lewycky26b8cd82008-05-31 17:59:52 +00002393 if (I.getType() == Type::Int1Ty)
2394 return BinaryOperator::CreateXor(Op0, Op1);
2395
Chris Lattnera9be4492005-04-07 16:15:25 +00002396 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
2397 if (Op1I->getOpcode() == Instruction::Add &&
Chris Lattner7a002fe2006-12-02 00:13:08 +00002398 !Op0->getType()->isFPOrFPVector()) {
Chris Lattnerc7f3c1a2005-04-07 16:28:01 +00002399 if (Op1I->getOperand(0) == Op0) // X-(X+Y) == -Y
Gabor Greife1f6e4b2008-05-16 19:29:10 +00002400 return BinaryOperator::CreateNeg(Op1I->getOperand(1), I.getName());
Chris Lattnerc7f3c1a2005-04-07 16:28:01 +00002401 else if (Op1I->getOperand(1) == Op0) // X-(Y+X) == -Y
Gabor Greife1f6e4b2008-05-16 19:29:10 +00002402 return BinaryOperator::CreateNeg(Op1I->getOperand(0), I.getName());
Chris Lattnerc7f3c1a2005-04-07 16:28:01 +00002403 else if (ConstantInt *CI1 = dyn_cast<ConstantInt>(I.getOperand(0))) {
2404 if (ConstantInt *CI2 = dyn_cast<ConstantInt>(Op1I->getOperand(1)))
2405 // C1-(X+C2) --> (C1-C2)-X
Gabor Greife1f6e4b2008-05-16 19:29:10 +00002406 return BinaryOperator::CreateSub(Subtract(CI1, CI2),
Chris Lattnerc7f3c1a2005-04-07 16:28:01 +00002407 Op1I->getOperand(0));
2408 }
Chris Lattnera9be4492005-04-07 16:15:25 +00002409 }
2410
Chris Lattnerf95d9b92003-10-15 16:48:29 +00002411 if (Op1I->hasOneUse()) {
Chris Lattner3082c5a2003-02-18 19:28:33 +00002412 // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
2413 // is not used by anyone else...
2414 //
Chris Lattnerc2f0aa52004-02-02 20:09:56 +00002415 if (Op1I->getOpcode() == Instruction::Sub &&
Chris Lattner7a002fe2006-12-02 00:13:08 +00002416 !Op1I->getType()->isFPOrFPVector()) {
Chris Lattner3082c5a2003-02-18 19:28:33 +00002417 // Swap the two operands of the subexpr...
2418 Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
2419 Op1I->setOperand(0, IIOp1);
2420 Op1I->setOperand(1, IIOp0);
Misha Brukmanb1c93172005-04-21 23:48:37 +00002421
Chris Lattner3082c5a2003-02-18 19:28:33 +00002422 // Create the new top level add instruction...
Gabor Greife1f6e4b2008-05-16 19:29:10 +00002423 return BinaryOperator::CreateAdd(Op0, Op1);
Chris Lattner3082c5a2003-02-18 19:28:33 +00002424 }
2425
2426 // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
2427 //
2428 if (Op1I->getOpcode() == Instruction::And &&
2429 (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
2430 Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
2431
Chris Lattner396dbfe2004-06-09 05:08:07 +00002432 Value *NewNot =
Gabor Greife1f6e4b2008-05-16 19:29:10 +00002433 InsertNewInstBefore(BinaryOperator::CreateNot(OtherOp, "B.not"), I);
2434 return BinaryOperator::CreateAnd(Op0, NewNot);
Chris Lattner3082c5a2003-02-18 19:28:33 +00002435 }
Chris Lattner57c8d992003-02-18 19:57:07 +00002436
Reid Spencer3c514952006-10-16 23:08:08 +00002437 // 0 - (X sdiv C) -> (X sdiv -C)
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002438 if (Op1I->getOpcode() == Instruction::SDiv)
Reid Spencere0fc4df2006-10-20 07:07:24 +00002439 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
Zhou Shengaafe4e22007-04-19 05:39:12 +00002440 if (CSI->isZero())
Chris Lattner0aee4b72004-10-06 15:08:25 +00002441 if (Constant *DivRHS = dyn_cast<Constant>(Op1I->getOperand(1)))
Gabor Greife1f6e4b2008-05-16 19:29:10 +00002442 return BinaryOperator::CreateSDiv(Op1I->getOperand(0),
Chris Lattner0aee4b72004-10-06 15:08:25 +00002443 ConstantExpr::getNeg(DivRHS));
2444
Chris Lattner57c8d992003-02-18 19:57:07 +00002445 // X - X*C --> X * (1-C)
Reid Spencer4fdd96c2005-06-18 17:37:34 +00002446 ConstantInt *C2 = 0;
Chris Lattner8c3e7b92004-11-13 19:50:12 +00002447 if (dyn_castFoldableMul(Op1I, C2) == Op0) {
Reid Spencer80263aa2007-03-25 05:33:51 +00002448 Constant *CP1 = Subtract(ConstantInt::get(I.getType(), 1), C2);
Gabor Greife1f6e4b2008-05-16 19:29:10 +00002449 return BinaryOperator::CreateMul(Op0, CP1);
Chris Lattner57c8d992003-02-18 19:57:07 +00002450 }
Chris Lattnerad3c4952002-05-09 01:29:19 +00002451 }
Chris Lattnera9be4492005-04-07 16:15:25 +00002452 }
Chris Lattner3082c5a2003-02-18 19:28:33 +00002453
Chris Lattner7a002fe2006-12-02 00:13:08 +00002454 if (!Op0->getType()->isFPOrFPVector())
Anton Korobeynikov1bfd1212008-02-20 11:26:25 +00002455 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
Chris Lattner47060462005-04-07 17:14:51 +00002456 if (Op0I->getOpcode() == Instruction::Add) {
Chris Lattner411336f2005-01-19 21:50:18 +00002457 if (Op0I->getOperand(0) == Op1) // (Y+X)-Y == X
2458 return ReplaceInstUsesWith(I, Op0I->getOperand(1));
2459 else if (Op0I->getOperand(1) == Op1) // (X+Y)-Y == X
2460 return ReplaceInstUsesWith(I, Op0I->getOperand(0));
Chris Lattner47060462005-04-07 17:14:51 +00002461 } else if (Op0I->getOpcode() == Instruction::Sub) {
2462 if (Op0I->getOperand(0) == Op1) // (X-Y)-X == -Y
Gabor Greife1f6e4b2008-05-16 19:29:10 +00002463 return BinaryOperator::CreateNeg(Op0I->getOperand(1), I.getName());
Chris Lattner411336f2005-01-19 21:50:18 +00002464 }
Anton Korobeynikov1bfd1212008-02-20 11:26:25 +00002465 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00002466
Chris Lattner8c3e7b92004-11-13 19:50:12 +00002467 ConstantInt *C1;
2468 if (Value *X = dyn_castFoldableMul(Op0, C1)) {
Reid Spencer80263aa2007-03-25 05:33:51 +00002469 if (X == Op1) // X*C - X --> X * (C-1)
Gabor Greife1f6e4b2008-05-16 19:29:10 +00002470 return BinaryOperator::CreateMul(Op1, SubOne(C1));
Chris Lattner57c8d992003-02-18 19:57:07 +00002471
Chris Lattner8c3e7b92004-11-13 19:50:12 +00002472 ConstantInt *C2; // X*C1 - X*C2 -> X * (C1-C2)
2473 if (X == dyn_castFoldableMul(Op1, C2))
Gabor Greife1f6e4b2008-05-16 19:29:10 +00002474 return BinaryOperator::CreateMul(X, Subtract(C1, C2));
Chris Lattner8c3e7b92004-11-13 19:50:12 +00002475 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002476 return 0;
Chris Lattner260ab202002-04-18 17:39:14 +00002477}
2478
Chris Lattner06205d52007-07-15 20:42:37 +00002479/// isSignBitCheck - Given an exploded icmp instruction, return true if the
2480/// comparison only checks the sign bit. If it only checks the sign bit, set
2481/// TrueIfSigned if the result of the comparison is true when the input value is
2482/// signed.
2483static bool isSignBitCheck(ICmpInst::Predicate pred, ConstantInt *RHS,
2484 bool &TrueIfSigned) {
Reid Spencer266e42b2006-12-23 06:05:41 +00002485 switch (pred) {
Chris Lattner06205d52007-07-15 20:42:37 +00002486 case ICmpInst::ICMP_SLT: // True if LHS s< 0
2487 TrueIfSigned = true;
2488 return RHS->isZero();
Chris Lattner640fd512007-07-16 04:15:34 +00002489 case ICmpInst::ICMP_SLE: // True if LHS s<= RHS and RHS == -1
2490 TrueIfSigned = true;
2491 return RHS->isAllOnesValue();
Chris Lattner06205d52007-07-15 20:42:37 +00002492 case ICmpInst::ICMP_SGT: // True if LHS s> -1
2493 TrueIfSigned = false;
2494 return RHS->isAllOnesValue();
Chris Lattner640fd512007-07-16 04:15:34 +00002495 case ICmpInst::ICMP_UGT:
2496 // True if LHS u> RHS and RHS == high-bit-mask - 1
2497 TrueIfSigned = true;
2498 return RHS->getValue() ==
2499 APInt::getSignedMaxValue(RHS->getType()->getPrimitiveSizeInBits());
2500 case ICmpInst::ICMP_UGE:
2501 // True if LHS u>= RHS and RHS == high-bit-mask (2^7, 2^15, 2^31, etc)
2502 TrueIfSigned = true;
Chris Lattnera12a6de2008-06-02 01:29:46 +00002503 return RHS->getValue().isSignBit();
Chris Lattner06205d52007-07-15 20:42:37 +00002504 default:
2505 return false;
Chris Lattnere79e8542004-02-23 06:38:22 +00002506 }
Chris Lattnere79e8542004-02-23 06:38:22 +00002507}
2508
Chris Lattner113f4f42002-06-25 16:13:24 +00002509Instruction *InstCombiner::visitMul(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00002510 bool Changed = SimplifyCommutative(I);
Chris Lattner3082c5a2003-02-18 19:28:33 +00002511 Value *Op0 = I.getOperand(0);
Chris Lattner260ab202002-04-18 17:39:14 +00002512
Chris Lattner81a7a232004-10-16 18:11:37 +00002513 if (isa<UndefValue>(I.getOperand(1))) // undef * X -> 0
2514 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2515
Chris Lattnere6794492002-08-12 21:17:25 +00002516 // Simplify mul instructions with a constant RHS...
Chris Lattner3082c5a2003-02-18 19:28:33 +00002517 if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
2518 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Chris Lattnerede3fe02003-08-13 04:18:28 +00002519
2520 // ((X << C1)*C2) == (X * (C2 << C1))
Reid Spencer2341c222007-02-02 02:16:23 +00002521 if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op0))
Chris Lattnerede3fe02003-08-13 04:18:28 +00002522 if (SI->getOpcode() == Instruction::Shl)
2523 if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
Gabor Greife1f6e4b2008-05-16 19:29:10 +00002524 return BinaryOperator::CreateMul(SI->getOperand(0),
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002525 ConstantExpr::getShl(CI, ShOp));
Misha Brukmanb1c93172005-04-21 23:48:37 +00002526
Zhou Shengaafe4e22007-04-19 05:39:12 +00002527 if (CI->isZero())
Chris Lattnercce81be2003-09-11 22:24:54 +00002528 return ReplaceInstUsesWith(I, Op1); // X * 0 == 0
2529 if (CI->equalsInt(1)) // X * 1 == X
2530 return ReplaceInstUsesWith(I, Op0);
2531 if (CI->isAllOnesValue()) // X * -1 == 0 - X
Gabor Greife1f6e4b2008-05-16 19:29:10 +00002532 return BinaryOperator::CreateNeg(Op0, I.getName());
Chris Lattner31ba1292002-04-29 22:24:47 +00002533
Zhou Sheng4961cf12007-03-29 01:57:21 +00002534 const APInt& Val = cast<ConstantInt>(CI)->getValue();
Reid Spencer6d392062007-03-23 20:05:17 +00002535 if (Val.isPowerOf2()) { // Replace X*(2^C) with X << C
Gabor Greife1f6e4b2008-05-16 19:29:10 +00002536 return BinaryOperator::CreateShl(Op0,
Reid Spencer6d392062007-03-23 20:05:17 +00002537 ConstantInt::get(Op0->getType(), Val.logBase2()));
Chris Lattner22d00a82005-08-02 19:16:58 +00002538 }
Robert Bocchino7b5b86c2004-07-27 21:02:21 +00002539 } else if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1)) {
Chris Lattner3082c5a2003-02-18 19:28:33 +00002540 if (Op1F->isNullValue())
2541 return ReplaceInstUsesWith(I, Op1);
Chris Lattner31ba1292002-04-29 22:24:47 +00002542
Chris Lattner3082c5a2003-02-18 19:28:33 +00002543 // "In IEEE floating point, x*1 is not equivalent to x for nans. However,
2544 // ANSI says we can drop signals, so we can do this anyway." (from GCC)
Chris Lattner2aa0ff22008-08-11 22:06:05 +00002545 if (Op1F->isExactlyValue(1.0))
2546 return ReplaceInstUsesWith(I, Op0); // Eliminate 'mul double %X, 1.0'
2547 } else if (isa<VectorType>(Op1->getType())) {
2548 if (isa<ConstantAggregateZero>(Op1))
2549 return ReplaceInstUsesWith(I, Op1);
Nick Lewycky69941fd2008-11-27 20:21:08 +00002550
2551 if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1)) {
2552 if (Op1V->isAllOnesValue()) // X * -1 == 0 - X
2553 return BinaryOperator::CreateNeg(Op0, I.getName());
2554
2555 // As above, vector X*splat(1.0) -> X in all defined cases.
2556 if (Constant *Splat = Op1V->getSplatValue()) {
2557 if (ConstantFP *F = dyn_cast<ConstantFP>(Splat))
2558 if (F->isExactlyValue(1.0))
2559 return ReplaceInstUsesWith(I, Op0);
2560 if (ConstantInt *CI = dyn_cast<ConstantInt>(Splat))
2561 if (CI->equalsInt(1))
2562 return ReplaceInstUsesWith(I, Op0);
2563 }
2564 }
Chris Lattner3082c5a2003-02-18 19:28:33 +00002565 }
Chris Lattner32c01df2006-03-04 06:04:02 +00002566
2567 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
2568 if (Op0I->getOpcode() == Instruction::Add && Op0I->hasOneUse() &&
Chris Lattner4b2a7242008-05-18 04:11:26 +00002569 isa<ConstantInt>(Op0I->getOperand(1)) && isa<ConstantInt>(Op1)) {
Chris Lattner32c01df2006-03-04 06:04:02 +00002570 // Canonicalize (X+C1)*C2 -> X*C2+C1*C2.
Gabor Greife1f6e4b2008-05-16 19:29:10 +00002571 Instruction *Add = BinaryOperator::CreateMul(Op0I->getOperand(0),
Chris Lattner32c01df2006-03-04 06:04:02 +00002572 Op1, "tmp");
2573 InsertNewInstBefore(Add, I);
2574 Value *C1C2 = ConstantExpr::getMul(Op1,
2575 cast<Constant>(Op0I->getOperand(1)));
Gabor Greife1f6e4b2008-05-16 19:29:10 +00002576 return BinaryOperator::CreateAdd(Add, C1C2);
Chris Lattner32c01df2006-03-04 06:04:02 +00002577
2578 }
Chris Lattner183b3362004-04-09 19:05:30 +00002579
2580 // Try to fold constant mul into select arguments.
2581 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner86102b82005-01-01 16:22:27 +00002582 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00002583 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00002584
2585 if (isa<PHINode>(Op0))
2586 if (Instruction *NV = FoldOpIntoPhi(I))
2587 return NV;
Chris Lattner260ab202002-04-18 17:39:14 +00002588 }
2589
Chris Lattner934a64cf2003-03-10 23:23:04 +00002590 if (Value *Op0v = dyn_castNegVal(Op0)) // -X * -Y = X*Y
2591 if (Value *Op1v = dyn_castNegVal(I.getOperand(1)))
Gabor Greife1f6e4b2008-05-16 19:29:10 +00002592 return BinaryOperator::CreateMul(Op0v, Op1v);
Chris Lattner934a64cf2003-03-10 23:23:04 +00002593
Nick Lewycky07d726e2008-11-21 07:33:58 +00002594 // (X / Y) * Y = X - (X % Y)
2595 // (X / Y) * -Y = (X % Y) - X
2596 {
2597 Value *Op1 = I.getOperand(1);
2598 BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0);
2599 if (!BO ||
2600 (BO->getOpcode() != Instruction::UDiv &&
2601 BO->getOpcode() != Instruction::SDiv)) {
2602 Op1 = Op0;
2603 BO = dyn_cast<BinaryOperator>(I.getOperand(1));
2604 }
2605 Value *Neg = dyn_castNegVal(Op1);
2606 if (BO && BO->hasOneUse() &&
2607 (BO->getOperand(1) == Op1 || BO->getOperand(1) == Neg) &&
2608 (BO->getOpcode() == Instruction::UDiv ||
2609 BO->getOpcode() == Instruction::SDiv)) {
2610 Value *Op0BO = BO->getOperand(0), *Op1BO = BO->getOperand(1);
2611
2612 Instruction *Rem;
2613 if (BO->getOpcode() == Instruction::UDiv)
2614 Rem = BinaryOperator::CreateURem(Op0BO, Op1BO);
2615 else
2616 Rem = BinaryOperator::CreateSRem(Op0BO, Op1BO);
2617
2618 InsertNewInstBefore(Rem, I);
2619 Rem->takeName(BO);
2620
2621 if (Op1BO == Op1)
2622 return BinaryOperator::CreateSub(Op0BO, Rem);
2623 else
2624 return BinaryOperator::CreateSub(Rem, Op0BO);
2625 }
2626 }
2627
Nick Lewycky26b8cd82008-05-31 17:59:52 +00002628 if (I.getType() == Type::Int1Ty)
2629 return BinaryOperator::CreateAnd(Op0, I.getOperand(1));
2630
Chris Lattner2635b522004-02-23 05:39:21 +00002631 // If one of the operands of the multiply is a cast from a boolean value, then
2632 // we know the bool is either zero or one, so this is a 'masking' multiply.
2633 // See if we can simplify things based on how the boolean was originally
2634 // formed.
2635 CastInst *BoolCast = 0;
Nick Lewycky26b8cd82008-05-31 17:59:52 +00002636 if (ZExtInst *CI = dyn_cast<ZExtInst>(Op0))
Reid Spencer542964f2007-01-11 18:21:29 +00002637 if (CI->getOperand(0)->getType() == Type::Int1Ty)
Chris Lattner2635b522004-02-23 05:39:21 +00002638 BoolCast = CI;
2639 if (!BoolCast)
Reid Spencer74a528b2006-12-13 18:21:21 +00002640 if (ZExtInst *CI = dyn_cast<ZExtInst>(I.getOperand(1)))
Reid Spencer542964f2007-01-11 18:21:29 +00002641 if (CI->getOperand(0)->getType() == Type::Int1Ty)
Chris Lattner2635b522004-02-23 05:39:21 +00002642 BoolCast = CI;
2643 if (BoolCast) {
Reid Spencer266e42b2006-12-23 06:05:41 +00002644 if (ICmpInst *SCI = dyn_cast<ICmpInst>(BoolCast->getOperand(0))) {
Chris Lattner2635b522004-02-23 05:39:21 +00002645 Value *SCIOp0 = SCI->getOperand(0), *SCIOp1 = SCI->getOperand(1);
2646 const Type *SCOpTy = SCIOp0->getType();
Chris Lattner06205d52007-07-15 20:42:37 +00002647 bool TIS = false;
2648
Reid Spencer266e42b2006-12-23 06:05:41 +00002649 // If the icmp is true iff the sign bit of X is set, then convert this
Chris Lattnere79e8542004-02-23 06:38:22 +00002650 // multiply into a shift/and combination.
2651 if (isa<ConstantInt>(SCIOp1) &&
Chris Lattner06205d52007-07-15 20:42:37 +00002652 isSignBitCheck(SCI->getPredicate(), cast<ConstantInt>(SCIOp1), TIS) &&
2653 TIS) {
Chris Lattner2635b522004-02-23 05:39:21 +00002654 // Shift the X value right to turn it into "all signbits".
Reid Spencer2341c222007-02-02 02:16:23 +00002655 Constant *Amt = ConstantInt::get(SCIOp0->getType(),
Chris Lattnerd1f46d32005-04-24 06:59:08 +00002656 SCOpTy->getPrimitiveSizeInBits()-1);
Chris Lattnere79e8542004-02-23 06:38:22 +00002657 Value *V =
Reid Spencer2341c222007-02-02 02:16:23 +00002658 InsertNewInstBefore(
Gabor Greife1f6e4b2008-05-16 19:29:10 +00002659 BinaryOperator::Create(Instruction::AShr, SCIOp0, Amt,
Chris Lattnere79e8542004-02-23 06:38:22 +00002660 BoolCast->getOperand(0)->getName()+
2661 ".mask"), I);
Chris Lattner2635b522004-02-23 05:39:21 +00002662
2663 // If the multiply type is not the same as the source type, sign extend
2664 // or truncate to the multiply type.
Reid Spencer13bc5d72006-12-12 09:18:51 +00002665 if (I.getType() != V->getType()) {
Zhou Sheng56cda952007-04-02 08:20:41 +00002666 uint32_t SrcBits = V->getType()->getPrimitiveSizeInBits();
2667 uint32_t DstBits = I.getType()->getPrimitiveSizeInBits();
Reid Spencer13bc5d72006-12-12 09:18:51 +00002668 Instruction::CastOps opcode =
2669 (SrcBits == DstBits ? Instruction::BitCast :
2670 (SrcBits < DstBits ? Instruction::SExt : Instruction::Trunc));
2671 V = InsertCastBefore(opcode, V, I.getType(), I);
2672 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00002673
Chris Lattner2635b522004-02-23 05:39:21 +00002674 Value *OtherOp = Op0 == BoolCast ? I.getOperand(1) : Op0;
Gabor Greife1f6e4b2008-05-16 19:29:10 +00002675 return BinaryOperator::CreateAnd(V, OtherOp);
Chris Lattner2635b522004-02-23 05:39:21 +00002676 }
2677 }
2678 }
2679
Chris Lattner113f4f42002-06-25 16:13:24 +00002680 return Changed ? &I : 0;
Chris Lattner260ab202002-04-18 17:39:14 +00002681}
2682
Chris Lattner16395e52008-07-14 00:15:52 +00002683/// SimplifyDivRemOfSelect - Try to fold a divide or remainder of a select
2684/// instruction.
2685bool InstCombiner::SimplifyDivRemOfSelect(BinaryOperator &I) {
2686 SelectInst *SI = cast<SelectInst>(I.getOperand(1));
2687
2688 // div/rem X, (Cond ? 0 : Y) -> div/rem X, Y
2689 int NonNullOperand = -1;
2690 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
2691 if (ST->isNullValue())
2692 NonNullOperand = 2;
2693 // div/rem X, (Cond ? Y : 0) -> div/rem X, Y
2694 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
2695 if (ST->isNullValue())
2696 NonNullOperand = 1;
2697
2698 if (NonNullOperand == -1)
2699 return false;
2700
2701 Value *SelectCond = SI->getOperand(0);
2702
2703 // Change the div/rem to use 'Y' instead of the select.
2704 I.setOperand(1, SI->getOperand(NonNullOperand));
2705
2706 // Okay, we know we replace the operand of the div/rem with 'Y' with no
2707 // problem. However, the select, or the condition of the select may have
2708 // multiple uses. Based on our knowledge that the operand must be non-zero,
2709 // propagate the known value for the select into other uses of it, and
2710 // propagate a known value of the condition into its other users.
2711
2712 // If the select and condition only have a single use, don't bother with this,
2713 // early exit.
2714 if (SI->use_empty() && SelectCond->hasOneUse())
2715 return true;
2716
2717 // Scan the current block backward, looking for other uses of SI.
2718 BasicBlock::iterator BBI = &I, BBFront = I.getParent()->begin();
2719
2720 while (BBI != BBFront) {
2721 --BBI;
2722 // If we found a call to a function, we can't assume it will return, so
2723 // information from below it cannot be propagated above it.
2724 if (isa<CallInst>(BBI) && !isa<IntrinsicInst>(BBI))
2725 break;
2726
2727 // Replace uses of the select or its condition with the known values.
2728 for (Instruction::op_iterator I = BBI->op_begin(), E = BBI->op_end();
2729 I != E; ++I) {
2730 if (*I == SI) {
2731 *I = SI->getOperand(NonNullOperand);
2732 AddToWorkList(BBI);
2733 } else if (*I == SelectCond) {
2734 *I = NonNullOperand == 1 ? ConstantInt::getTrue() :
2735 ConstantInt::getFalse();
2736 AddToWorkList(BBI);
2737 }
2738 }
2739
2740 // If we past the instruction, quit looking for it.
2741 if (&*BBI == SI)
2742 SI = 0;
2743 if (&*BBI == SelectCond)
2744 SelectCond = 0;
2745
2746 // If we ran out of things to eliminate, break out of the loop.
2747 if (SelectCond == 0 && SI == 0)
2748 break;
2749
2750 }
2751 return true;
2752}
2753
2754
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002755/// This function implements the transforms on div instructions that work
2756/// regardless of the kind of div instruction it is (udiv, sdiv, or fdiv). It is
2757/// used by the visitors to those instructions.
2758/// @brief Transforms common to all three div instructions
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002759Instruction *InstCombiner::commonDivTransforms(BinaryOperator &I) {
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00002760 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner81a7a232004-10-16 18:11:37 +00002761
Chris Lattner0fe6bce2008-02-19 06:12:18 +00002762 // undef / X -> 0 for integer.
2763 // undef / X -> undef for FP (the undef could be a snan).
2764 if (isa<UndefValue>(Op0)) {
2765 if (Op0->getType()->isFPOrFPVector())
2766 return ReplaceInstUsesWith(I, Op0);
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00002767 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner0fe6bce2008-02-19 06:12:18 +00002768 }
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002769
2770 // X / undef -> undef
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00002771 if (isa<UndefValue>(Op1))
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002772 return ReplaceInstUsesWith(I, Op1);
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00002773
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002774 return 0;
2775}
Misha Brukmanb1c93172005-04-21 23:48:37 +00002776
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002777/// This function implements the transforms common to both integer division
2778/// instructions (udiv and sdiv). It is called by the visitors to those integer
2779/// division instructions.
2780/// @brief Common integer divide transforms
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002781Instruction *InstCombiner::commonIDivTransforms(BinaryOperator &I) {
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002782 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2783
Chris Lattner5c953b72008-05-16 02:59:42 +00002784 // (sdiv X, X) --> 1 (udiv X, X) --> 1
Nick Lewycky2ec9a012008-05-23 03:26:47 +00002785 if (Op0 == Op1) {
2786 if (const VectorType *Ty = dyn_cast<VectorType>(I.getType())) {
2787 ConstantInt *CI = ConstantInt::get(Ty->getElementType(), 1);
2788 std::vector<Constant*> Elts(Ty->getNumElements(), CI);
2789 return ReplaceInstUsesWith(I, ConstantVector::get(Elts));
2790 }
2791
2792 ConstantInt *CI = ConstantInt::get(I.getType(), 1);
2793 return ReplaceInstUsesWith(I, CI);
2794 }
Chris Lattner5c953b72008-05-16 02:59:42 +00002795
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002796 if (Instruction *Common = commonDivTransforms(I))
2797 return Common;
Chris Lattner16395e52008-07-14 00:15:52 +00002798
2799 // Handle cases involving: [su]div X, (select Cond, Y, Z)
2800 // This does not apply for fdiv.
2801 if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
2802 return &I;
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002803
2804 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2805 // div X, 1 == X
2806 if (RHS->equalsInt(1))
2807 return ReplaceInstUsesWith(I, Op0);
2808
2809 // (X / C1) / C2 -> X / (C1*C2)
2810 if (Instruction *LHS = dyn_cast<Instruction>(Op0))
2811 if (Instruction::BinaryOps(LHS->getOpcode()) == I.getOpcode())
2812 if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
Nick Lewyckyfefd0202008-02-18 22:48:05 +00002813 if (MultiplyOverflows(RHS, LHSRHS, I.getOpcode()==Instruction::SDiv))
2814 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2815 else
Gabor Greife1f6e4b2008-05-16 19:29:10 +00002816 return BinaryOperator::Create(I.getOpcode(), LHS->getOperand(0),
Nick Lewyckyfefd0202008-02-18 22:48:05 +00002817 Multiply(RHS, LHSRHS));
Chris Lattner42362612005-04-08 04:03:26 +00002818 }
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002819
Reid Spencer6d392062007-03-23 20:05:17 +00002820 if (!RHS->isZero()) { // avoid X udiv 0
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002821 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2822 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2823 return R;
2824 if (isa<PHINode>(Op0))
2825 if (Instruction *NV = FoldOpIntoPhi(I))
2826 return NV;
2827 }
Chris Lattnerd79dc792006-09-09 20:26:32 +00002828 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00002829
Chris Lattner3082c5a2003-02-18 19:28:33 +00002830 // 0 / X == 0, we don't need to preserve faults!
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00002831 if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
Chris Lattner3082c5a2003-02-18 19:28:33 +00002832 if (LHS->equalsInt(0))
2833 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2834
Nick Lewycky26b8cd82008-05-31 17:59:52 +00002835 // It can't be division by zero, hence it must be division by one.
2836 if (I.getType() == Type::Int1Ty)
2837 return ReplaceInstUsesWith(I, Op0);
2838
Nick Lewycky69941fd2008-11-27 20:21:08 +00002839 if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1)) {
2840 if (ConstantInt *X = cast_or_null<ConstantInt>(Op1V->getSplatValue()))
2841 // div X, 1 == X
2842 if (X->isOne())
2843 return ReplaceInstUsesWith(I, Op0);
2844 }
2845
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002846 return 0;
2847}
2848
2849Instruction *InstCombiner::visitUDiv(BinaryOperator &I) {
2850 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2851
2852 // Handle the integer div common cases
2853 if (Instruction *Common = commonIDivTransforms(I))
2854 return Common;
2855
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002856 if (ConstantInt *C = dyn_cast<ConstantInt>(Op1)) {
Nick Lewycky4ab50b92008-11-27 22:41:10 +00002857 // X udiv C^2 -> X >> C
2858 // Check to see if this is an unsigned division with an exact power of 2,
2859 // if so, convert to a right shift.
Reid Spencer54d5b1b2007-03-26 23:58:26 +00002860 if (C->getValue().isPowerOf2()) // 0 not included in isPowerOf2
Gabor Greife1f6e4b2008-05-16 19:29:10 +00002861 return BinaryOperator::CreateLShr(Op0,
Zhou Sheng222d5eb2007-03-25 05:01:29 +00002862 ConstantInt::get(Op0->getType(), C->getValue().logBase2()));
Nick Lewycky4ab50b92008-11-27 22:41:10 +00002863
2864 // X udiv C, where C >= signbit
2865 if (C->getValue().isNegative()) {
2866 Value *IC = InsertNewInstBefore(new ICmpInst(ICmpInst::ICMP_ULT, Op0, C),
2867 I);
2868 return SelectInst::Create(IC, Constant::getNullValue(I.getType()),
2869 ConstantInt::get(I.getType(), 1));
2870 }
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002871 }
2872
2873 // X udiv (C1 << N), where C1 is "1<<C2" --> X >> (N+C2)
Reid Spencer2341c222007-02-02 02:16:23 +00002874 if (BinaryOperator *RHSI = dyn_cast<BinaryOperator>(I.getOperand(1))) {
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002875 if (RHSI->getOpcode() == Instruction::Shl &&
2876 isa<ConstantInt>(RHSI->getOperand(0))) {
Zhou Sheng150f3bb2007-04-01 17:13:37 +00002877 const APInt& C1 = cast<ConstantInt>(RHSI->getOperand(0))->getValue();
Reid Spencer6d392062007-03-23 20:05:17 +00002878 if (C1.isPowerOf2()) {
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002879 Value *N = RHSI->getOperand(1);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002880 const Type *NTy = N->getType();
Reid Spencer959a21d2007-03-23 21:24:59 +00002881 if (uint32_t C2 = C1.logBase2()) {
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002882 Constant *C2V = ConstantInt::get(NTy, C2);
Gabor Greife1f6e4b2008-05-16 19:29:10 +00002883 N = InsertNewInstBefore(BinaryOperator::CreateAdd(N, C2V, "tmp"), I);
Chris Lattner2e90b732006-02-05 07:54:04 +00002884 }
Gabor Greife1f6e4b2008-05-16 19:29:10 +00002885 return BinaryOperator::CreateLShr(Op0, N);
Chris Lattner2e90b732006-02-05 07:54:04 +00002886 }
2887 }
Chris Lattnerdd0c1742005-11-05 07:40:31 +00002888 }
2889
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002890 // udiv X, (Select Cond, C1, C2) --> Select Cond, (shr X, C1), (shr X, C2)
2891 // where C1&C2 are powers of two.
Reid Spencer3939b1a2007-03-05 23:36:13 +00002892 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002893 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
Reid Spencer3939b1a2007-03-05 23:36:13 +00002894 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
Zhou Sheng150f3bb2007-04-01 17:13:37 +00002895 const APInt &TVA = STO->getValue(), &FVA = SFO->getValue();
Reid Spencer6d392062007-03-23 20:05:17 +00002896 if (TVA.isPowerOf2() && FVA.isPowerOf2()) {
Reid Spencer3939b1a2007-03-05 23:36:13 +00002897 // Compute the shift amounts
Reid Spencer6d392062007-03-23 20:05:17 +00002898 uint32_t TSA = TVA.logBase2(), FSA = FVA.logBase2();
Reid Spencer3939b1a2007-03-05 23:36:13 +00002899 // Construct the "on true" case of the select
2900 Constant *TC = ConstantInt::get(Op0->getType(), TSA);
Gabor Greife1f6e4b2008-05-16 19:29:10 +00002901 Instruction *TSI = BinaryOperator::CreateLShr(
Reid Spencer3939b1a2007-03-05 23:36:13 +00002902 Op0, TC, SI->getName()+".t");
2903 TSI = InsertNewInstBefore(TSI, I);
2904
2905 // Construct the "on false" case of the select
2906 Constant *FC = ConstantInt::get(Op0->getType(), FSA);
Gabor Greife1f6e4b2008-05-16 19:29:10 +00002907 Instruction *FSI = BinaryOperator::CreateLShr(
Reid Spencer3939b1a2007-03-05 23:36:13 +00002908 Op0, FC, SI->getName()+".f");
2909 FSI = InsertNewInstBefore(FSI, I);
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002910
Reid Spencer3939b1a2007-03-05 23:36:13 +00002911 // construct the select instruction and return it.
Gabor Greife9ecc682008-04-06 20:25:17 +00002912 return SelectInst::Create(SI->getOperand(0), TSI, FSI, SI->getName());
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002913 }
Reid Spencer3939b1a2007-03-05 23:36:13 +00002914 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002915 return 0;
2916}
2917
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002918Instruction *InstCombiner::visitSDiv(BinaryOperator &I) {
2919 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2920
2921 // Handle the integer div common cases
2922 if (Instruction *Common = commonIDivTransforms(I))
2923 return Common;
2924
2925 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2926 // sdiv X, -1 == -X
2927 if (RHS->isAllOnesValue())
Gabor Greife1f6e4b2008-05-16 19:29:10 +00002928 return BinaryOperator::CreateNeg(Op0);
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002929
Bill Wendling70635ad2008-11-30 03:42:12 +00002930 ConstantInt *RHSNeg = cast<ConstantInt>(ConstantExpr::getNeg(RHS));
Bill Wendling2d2e7862008-11-30 12:38:24 +00002931 APInt RHSNegAPI(RHSNeg->getValue());
Bill Wendlingaf200e92008-11-30 05:01:05 +00002932
2933 APInt NegOne = -APInt(RHSNeg->getBitWidth(), 1, true);
Bill Wendling7abf3522008-11-30 05:29:33 +00002934 APInt TwoToExp(RHSNeg->getBitWidth(), 1 << (RHSNeg->getBitWidth() - 1));
Bill Wendling70635ad2008-11-30 03:42:12 +00002935
2936 // -X/C -> X/-C, if and only if negation doesn't overflow.
Bill Wendling2d2e7862008-11-30 12:38:24 +00002937 if ((RHS->getValue().isNegative() && RHSNegAPI.slt(TwoToExp - 1)) ||
2938 (RHS->getValue().isNonNegative() && RHSNegAPI.sgt(TwoToExp * NegOne))) {
Bill Wendling70635ad2008-11-30 03:42:12 +00002939 if (Value *LHSNeg = dyn_castNegVal(Op0)) {
2940 if (ConstantInt *CI = dyn_cast<ConstantInt>(LHSNeg)) {
2941 ConstantInt *CINeg = cast<ConstantInt>(ConstantExpr::getNeg(CI));
Bill Wendling2fe32292008-11-30 12:41:09 +00002942 APInt CINegAPI(CINeg->getValue());
Bill Wendling70635ad2008-11-30 03:42:12 +00002943
Bill Wendling2d2e7862008-11-30 12:38:24 +00002944 if ((CI->getValue().isNegative() && CINegAPI.slt(TwoToExp - 1)) ||
2945 (CI->getValue().isNonNegative() && CINegAPI.sgt(TwoToExp*NegOne)))
Bill Wendling70635ad2008-11-30 03:42:12 +00002946 return BinaryOperator::CreateSDiv(LHSNeg,
2947 ConstantExpr::getNeg(RHS));
2948 }
2949 }
2950 }
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002951 }
2952
2953 // If the sign bits of both operands are zero (i.e. we can prove they are
2954 // unsigned inputs), turn this into a udiv.
Chris Lattner03c49532007-01-15 02:27:26 +00002955 if (I.getType()->isInteger()) {
Reid Spencer6d392062007-03-23 20:05:17 +00002956 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002957 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
Dan Gohman4decbc52007-11-05 23:16:33 +00002958 // X sdiv Y -> X udiv Y, iff X and Y don't have sign bit set
Gabor Greife1f6e4b2008-05-16 19:29:10 +00002959 return BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002960 }
2961 }
2962
2963 return 0;
2964}
2965
2966Instruction *InstCombiner::visitFDiv(BinaryOperator &I) {
2967 return commonDivTransforms(I);
2968}
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002969
Reid Spencer7eb55b32006-11-02 01:53:59 +00002970/// This function implements the transforms on rem instructions that work
2971/// regardless of the kind of rem instruction it is (urem, srem, or frem). It
2972/// is used by the visitors to those instructions.
2973/// @brief Transforms common to all three rem instructions
2974Instruction *InstCombiner::commonRemTransforms(BinaryOperator &I) {
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00002975 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Reid Spencer7eb55b32006-11-02 01:53:59 +00002976
Chris Lattner0fe6bce2008-02-19 06:12:18 +00002977 // 0 % X == 0 for integer, we don't need to preserve faults!
Chris Lattner0de4a8d2006-02-28 05:30:45 +00002978 if (Constant *LHS = dyn_cast<Constant>(Op0))
2979 if (LHS->isNullValue())
2980 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2981
Chris Lattner0fe6bce2008-02-19 06:12:18 +00002982 if (isa<UndefValue>(Op0)) { // undef % X -> 0
2983 if (I.getType()->isFPOrFPVector())
2984 return ReplaceInstUsesWith(I, Op0); // X % undef -> undef (could be SNaN)
Chris Lattner0de4a8d2006-02-28 05:30:45 +00002985 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner0fe6bce2008-02-19 06:12:18 +00002986 }
Chris Lattner0de4a8d2006-02-28 05:30:45 +00002987 if (isa<UndefValue>(Op1))
2988 return ReplaceInstUsesWith(I, Op1); // X % undef -> undef
Reid Spencer7eb55b32006-11-02 01:53:59 +00002989
2990 // Handle cases involving: rem X, (select Cond, Y, Z)
Chris Lattner16395e52008-07-14 00:15:52 +00002991 if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
2992 return &I;
Chris Lattner7fd5f072004-07-06 07:01:22 +00002993
Reid Spencer7eb55b32006-11-02 01:53:59 +00002994 return 0;
2995}
2996
2997/// This function implements the transforms common to both integer remainder
2998/// instructions (urem and srem). It is called by the visitors to those integer
2999/// remainder instructions.
3000/// @brief Common integer remainder transforms
3001Instruction *InstCombiner::commonIRemTransforms(BinaryOperator &I) {
3002 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3003
3004 if (Instruction *common = commonRemTransforms(I))
3005 return common;
3006
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00003007 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner0de4a8d2006-02-28 05:30:45 +00003008 // X % 0 == undef, we don't need to preserve faults!
3009 if (RHS->equalsInt(0))
3010 return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
3011
Chris Lattner3082c5a2003-02-18 19:28:33 +00003012 if (RHS->equalsInt(1)) // X % 1 == 0
3013 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3014
Chris Lattnerb70f1412006-02-28 05:49:21 +00003015 if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
3016 if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
3017 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3018 return R;
3019 } else if (isa<PHINode>(Op0I)) {
3020 if (Instruction *NV = FoldOpIntoPhi(I))
3021 return NV;
Chris Lattnerb70f1412006-02-28 05:49:21 +00003022 }
Nick Lewyckyd0b62a12008-03-06 06:48:30 +00003023
3024 // See if we can fold away this rem instruction.
3025 uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
3026 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
3027 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
3028 KnownZero, KnownOne))
3029 return &I;
Chris Lattnerb70f1412006-02-28 05:49:21 +00003030 }
Chris Lattner3082c5a2003-02-18 19:28:33 +00003031 }
3032
Reid Spencer7eb55b32006-11-02 01:53:59 +00003033 return 0;
3034}
3035
3036Instruction *InstCombiner::visitURem(BinaryOperator &I) {
3037 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3038
3039 if (Instruction *common = commonIRemTransforms(I))
3040 return common;
3041
3042 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3043 // X urem C^2 -> X and C
3044 // Check to see if this is an unsigned remainder with an exact power of 2,
3045 // if so, convert to a bitwise and.
3046 if (ConstantInt *C = dyn_cast<ConstantInt>(RHS))
Reid Spencer6d392062007-03-23 20:05:17 +00003047 if (C->getValue().isPowerOf2())
Gabor Greife1f6e4b2008-05-16 19:29:10 +00003048 return BinaryOperator::CreateAnd(Op0, SubOne(C));
Reid Spencer7eb55b32006-11-02 01:53:59 +00003049 }
3050
Chris Lattner2e90b732006-02-05 07:54:04 +00003051 if (Instruction *RHSI = dyn_cast<Instruction>(I.getOperand(1))) {
Reid Spencer7eb55b32006-11-02 01:53:59 +00003052 // Turn A % (C << N), where C is 2^k, into A & ((C << N)-1)
3053 if (RHSI->getOpcode() == Instruction::Shl &&
3054 isa<ConstantInt>(RHSI->getOperand(0))) {
Zhou Sheng222d5eb2007-03-25 05:01:29 +00003055 if (cast<ConstantInt>(RHSI->getOperand(0))->getValue().isPowerOf2()) {
Chris Lattner2e90b732006-02-05 07:54:04 +00003056 Constant *N1 = ConstantInt::getAllOnesValue(I.getType());
Gabor Greife1f6e4b2008-05-16 19:29:10 +00003057 Value *Add = InsertNewInstBefore(BinaryOperator::CreateAdd(RHSI, N1,
Chris Lattner2e90b732006-02-05 07:54:04 +00003058 "tmp"), I);
Gabor Greife1f6e4b2008-05-16 19:29:10 +00003059 return BinaryOperator::CreateAnd(Op0, Add);
Chris Lattner2e90b732006-02-05 07:54:04 +00003060 }
3061 }
Reid Spencer7eb55b32006-11-02 01:53:59 +00003062 }
Chris Lattnerd79dc792006-09-09 20:26:32 +00003063
Reid Spencer7eb55b32006-11-02 01:53:59 +00003064 // urem X, (select Cond, 2^C1, 2^C2) --> select Cond, (and X, C1), (and X, C2)
3065 // where C1&C2 are powers of two.
3066 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
3067 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
3068 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
3069 // STO == 0 and SFO == 0 handled above.
Reid Spencer6d392062007-03-23 20:05:17 +00003070 if ((STO->getValue().isPowerOf2()) &&
3071 (SFO->getValue().isPowerOf2())) {
Reid Spencer7eb55b32006-11-02 01:53:59 +00003072 Value *TrueAnd = InsertNewInstBefore(
Gabor Greife1f6e4b2008-05-16 19:29:10 +00003073 BinaryOperator::CreateAnd(Op0, SubOne(STO), SI->getName()+".t"), I);
Reid Spencer7eb55b32006-11-02 01:53:59 +00003074 Value *FalseAnd = InsertNewInstBefore(
Gabor Greife1f6e4b2008-05-16 19:29:10 +00003075 BinaryOperator::CreateAnd(Op0, SubOne(SFO), SI->getName()+".f"), I);
Gabor Greife9ecc682008-04-06 20:25:17 +00003076 return SelectInst::Create(SI->getOperand(0), TrueAnd, FalseAnd);
Reid Spencer7eb55b32006-11-02 01:53:59 +00003077 }
3078 }
Chris Lattner2e90b732006-02-05 07:54:04 +00003079 }
3080
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003081 return 0;
3082}
3083
Reid Spencer7eb55b32006-11-02 01:53:59 +00003084Instruction *InstCombiner::visitSRem(BinaryOperator &I) {
3085 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3086
Dan Gohman4decbc52007-11-05 23:16:33 +00003087 // Handle the integer rem common cases
Reid Spencer7eb55b32006-11-02 01:53:59 +00003088 if (Instruction *common = commonIRemTransforms(I))
3089 return common;
3090
3091 if (Value *RHSNeg = dyn_castNegVal(Op1))
Nick Lewycky2fcb26c2008-09-03 06:24:21 +00003092 if (!isa<Constant>(RHSNeg) ||
3093 (isa<ConstantInt>(RHSNeg) &&
3094 cast<ConstantInt>(RHSNeg)->getValue().isStrictlyPositive())) {
Reid Spencer7eb55b32006-11-02 01:53:59 +00003095 // X % -Y -> X % Y
3096 AddUsesToWorkList(I);
3097 I.setOperand(1, RHSNeg);
3098 return &I;
3099 }
Nick Lewyckye8ced3e2008-09-30 06:08:34 +00003100
Dan Gohman4decbc52007-11-05 23:16:33 +00003101 // If the sign bits of both operands are zero (i.e. we can prove they are
Reid Spencer7eb55b32006-11-02 01:53:59 +00003102 // unsigned inputs), turn this into a urem.
Dan Gohman4decbc52007-11-05 23:16:33 +00003103 if (I.getType()->isInteger()) {
3104 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
3105 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
3106 // X srem Y -> X urem Y, iff X and Y don't have sign bit set
Gabor Greife1f6e4b2008-05-16 19:29:10 +00003107 return BinaryOperator::CreateURem(Op0, Op1, I.getName());
Dan Gohman4decbc52007-11-05 23:16:33 +00003108 }
Reid Spencer7eb55b32006-11-02 01:53:59 +00003109 }
3110
3111 return 0;
3112}
3113
3114Instruction *InstCombiner::visitFRem(BinaryOperator &I) {
Reid Spencer7eb55b32006-11-02 01:53:59 +00003115 return commonRemTransforms(I);
3116}
3117
Chris Lattner35167c32004-06-09 07:59:58 +00003118// isOneBitSet - Return true if there is exactly one bit set in the specified
3119// constant.
3120static bool isOneBitSet(const ConstantInt *CI) {
Reid Spencer66827212007-03-20 00:16:52 +00003121 return CI->getValue().isPowerOf2();
Chris Lattner35167c32004-06-09 07:59:58 +00003122}
3123
Chris Lattner8fc5af42004-09-23 21:46:38 +00003124// isHighOnes - Return true if the constant is of the form 1+0+.
3125// This is the same as lowones(~X).
3126static bool isHighOnes(const ConstantInt *CI) {
Zhou Shengb3949342007-03-20 12:49:06 +00003127 return (~CI->getValue() + 1).isPowerOf2();
Chris Lattner8fc5af42004-09-23 21:46:38 +00003128}
3129
Reid Spencer266e42b2006-12-23 06:05:41 +00003130/// getICmpCode - Encode a icmp predicate into a three bit mask. These bits
Chris Lattner3ac7c262003-08-13 20:16:26 +00003131/// are carefully arranged to allow folding of expressions such as:
3132///
3133/// (A < B) | (A > B) --> (A != B)
3134///
Reid Spencer266e42b2006-12-23 06:05:41 +00003135/// Note that this is only valid if the first and second predicates have the
3136/// same sign. Is illegal to do: (A u< B) | (A s> B)
Chris Lattner3ac7c262003-08-13 20:16:26 +00003137///
Reid Spencer266e42b2006-12-23 06:05:41 +00003138/// Three bits are used to represent the condition, as follows:
3139/// 0 A > B
3140/// 1 A == B
3141/// 2 A < B
3142///
3143/// <=> Value Definition
3144/// 000 0 Always false
3145/// 001 1 A > B
3146/// 010 2 A == B
3147/// 011 3 A >= B
3148/// 100 4 A < B
3149/// 101 5 A != B
3150/// 110 6 A <= B
3151/// 111 7 Always true
3152///
3153static unsigned getICmpCode(const ICmpInst *ICI) {
3154 switch (ICI->getPredicate()) {
Chris Lattner3ac7c262003-08-13 20:16:26 +00003155 // False -> 0
Reid Spencer266e42b2006-12-23 06:05:41 +00003156 case ICmpInst::ICMP_UGT: return 1; // 001
3157 case ICmpInst::ICMP_SGT: return 1; // 001
3158 case ICmpInst::ICMP_EQ: return 2; // 010
3159 case ICmpInst::ICMP_UGE: return 3; // 011
3160 case ICmpInst::ICMP_SGE: return 3; // 011
3161 case ICmpInst::ICMP_ULT: return 4; // 100
3162 case ICmpInst::ICMP_SLT: return 4; // 100
3163 case ICmpInst::ICMP_NE: return 5; // 101
3164 case ICmpInst::ICMP_ULE: return 6; // 110
3165 case ICmpInst::ICMP_SLE: return 6; // 110
Chris Lattner3ac7c262003-08-13 20:16:26 +00003166 // True -> 7
3167 default:
Reid Spencer266e42b2006-12-23 06:05:41 +00003168 assert(0 && "Invalid ICmp predicate!");
Chris Lattner3ac7c262003-08-13 20:16:26 +00003169 return 0;
3170 }
3171}
3172
Evan Cheng67786cc2008-10-14 17:15:11 +00003173/// getFCmpCode - Similar to getICmpCode but for FCmpInst. This encodes a fcmp
3174/// predicate into a three bit mask. It also returns whether it is an ordered
3175/// predicate by reference.
3176static unsigned getFCmpCode(FCmpInst::Predicate CC, bool &isOrdered) {
3177 isOrdered = false;
3178 switch (CC) {
3179 case FCmpInst::FCMP_ORD: isOrdered = true; return 0; // 000
3180 case FCmpInst::FCMP_UNO: return 0; // 000
Evan Chengce707522008-10-14 18:13:38 +00003181 case FCmpInst::FCMP_OGT: isOrdered = true; return 1; // 001
3182 case FCmpInst::FCMP_UGT: return 1; // 001
3183 case FCmpInst::FCMP_OEQ: isOrdered = true; return 2; // 010
3184 case FCmpInst::FCMP_UEQ: return 2; // 010
Evan Cheng67786cc2008-10-14 17:15:11 +00003185 case FCmpInst::FCMP_OGE: isOrdered = true; return 3; // 011
3186 case FCmpInst::FCMP_UGE: return 3; // 011
3187 case FCmpInst::FCMP_OLT: isOrdered = true; return 4; // 100
3188 case FCmpInst::FCMP_ULT: return 4; // 100
Evan Chengce707522008-10-14 18:13:38 +00003189 case FCmpInst::FCMP_ONE: isOrdered = true; return 5; // 101
3190 case FCmpInst::FCMP_UNE: return 5; // 101
Evan Cheng67786cc2008-10-14 17:15:11 +00003191 case FCmpInst::FCMP_OLE: isOrdered = true; return 6; // 110
3192 case FCmpInst::FCMP_ULE: return 6; // 110
Evan Chengd885f6e2008-10-14 18:44:08 +00003193 // True -> 7
Evan Cheng67786cc2008-10-14 17:15:11 +00003194 default:
3195 // Not expecting FCMP_FALSE and FCMP_TRUE;
3196 assert(0 && "Unexpected FCmp predicate!");
3197 return 0;
3198 }
3199}
3200
Reid Spencer266e42b2006-12-23 06:05:41 +00003201/// getICmpValue - This is the complement of getICmpCode, which turns an
3202/// opcode and two operands into either a constant true or false, or a brand
Dan Gohman2ac26522007-09-17 17:31:57 +00003203/// new ICmp instruction. The sign is passed in to determine which kind
Evan Cheng67786cc2008-10-14 17:15:11 +00003204/// of predicate to use in the new icmp instruction.
Reid Spencer266e42b2006-12-23 06:05:41 +00003205static Value *getICmpValue(bool sign, unsigned code, Value *LHS, Value *RHS) {
3206 switch (code) {
3207 default: assert(0 && "Illegal ICmp code!");
Zhou Sheng75b871f2007-01-11 12:24:14 +00003208 case 0: return ConstantInt::getFalse();
Reid Spencer266e42b2006-12-23 06:05:41 +00003209 case 1:
3210 if (sign)
3211 return new ICmpInst(ICmpInst::ICMP_SGT, LHS, RHS);
3212 else
3213 return new ICmpInst(ICmpInst::ICMP_UGT, LHS, RHS);
3214 case 2: return new ICmpInst(ICmpInst::ICMP_EQ, LHS, RHS);
3215 case 3:
3216 if (sign)
3217 return new ICmpInst(ICmpInst::ICMP_SGE, LHS, RHS);
3218 else
3219 return new ICmpInst(ICmpInst::ICMP_UGE, LHS, RHS);
3220 case 4:
3221 if (sign)
3222 return new ICmpInst(ICmpInst::ICMP_SLT, LHS, RHS);
3223 else
3224 return new ICmpInst(ICmpInst::ICMP_ULT, LHS, RHS);
3225 case 5: return new ICmpInst(ICmpInst::ICMP_NE, LHS, RHS);
3226 case 6:
3227 if (sign)
3228 return new ICmpInst(ICmpInst::ICMP_SLE, LHS, RHS);
3229 else
3230 return new ICmpInst(ICmpInst::ICMP_ULE, LHS, RHS);
Zhou Sheng75b871f2007-01-11 12:24:14 +00003231 case 7: return ConstantInt::getTrue();
Chris Lattner3ac7c262003-08-13 20:16:26 +00003232 }
3233}
3234
Evan Cheng67786cc2008-10-14 17:15:11 +00003235/// getFCmpValue - This is the complement of getFCmpCode, which turns an
3236/// opcode and two operands into either a FCmp instruction. isordered is passed
3237/// in to determine which kind of predicate to use in the new fcmp instruction.
3238static Value *getFCmpValue(bool isordered, unsigned code,
3239 Value *LHS, Value *RHS) {
3240 switch (code) {
Evan Chengce707522008-10-14 18:13:38 +00003241 default: assert(0 && "Illegal FCmp code!");
Evan Cheng67786cc2008-10-14 17:15:11 +00003242 case 0:
3243 if (isordered)
3244 return new FCmpInst(FCmpInst::FCMP_ORD, LHS, RHS);
3245 else
3246 return new FCmpInst(FCmpInst::FCMP_UNO, LHS, RHS);
3247 case 1:
3248 if (isordered)
Evan Cheng67786cc2008-10-14 17:15:11 +00003249 return new FCmpInst(FCmpInst::FCMP_OGT, LHS, RHS);
3250 else
3251 return new FCmpInst(FCmpInst::FCMP_UGT, LHS, RHS);
Evan Chengce707522008-10-14 18:13:38 +00003252 case 2:
3253 if (isordered)
3254 return new FCmpInst(FCmpInst::FCMP_OEQ, LHS, RHS);
3255 else
3256 return new FCmpInst(FCmpInst::FCMP_UEQ, LHS, RHS);
Evan Cheng67786cc2008-10-14 17:15:11 +00003257 case 3:
3258 if (isordered)
3259 return new FCmpInst(FCmpInst::FCMP_OGE, LHS, RHS);
3260 else
3261 return new FCmpInst(FCmpInst::FCMP_UGE, LHS, RHS);
3262 case 4:
3263 if (isordered)
3264 return new FCmpInst(FCmpInst::FCMP_OLT, LHS, RHS);
3265 else
3266 return new FCmpInst(FCmpInst::FCMP_ULT, LHS, RHS);
3267 case 5:
3268 if (isordered)
Evan Chengce707522008-10-14 18:13:38 +00003269 return new FCmpInst(FCmpInst::FCMP_ONE, LHS, RHS);
3270 else
3271 return new FCmpInst(FCmpInst::FCMP_UNE, LHS, RHS);
3272 case 6:
3273 if (isordered)
Evan Cheng67786cc2008-10-14 17:15:11 +00003274 return new FCmpInst(FCmpInst::FCMP_OLE, LHS, RHS);
3275 else
3276 return new FCmpInst(FCmpInst::FCMP_ULE, LHS, RHS);
Evan Chengd885f6e2008-10-14 18:44:08 +00003277 case 7: return ConstantInt::getTrue();
Evan Cheng67786cc2008-10-14 17:15:11 +00003278 }
3279}
3280
Chris Lattnerb37b6e72008-11-16 04:55:20 +00003281/// PredicatesFoldable - Return true if both predicates match sign or if at
3282/// least one of them is an equality comparison (which is signless).
Reid Spencer266e42b2006-12-23 06:05:41 +00003283static bool PredicatesFoldable(ICmpInst::Predicate p1, ICmpInst::Predicate p2) {
3284 return (ICmpInst::isSignedPredicate(p1) == ICmpInst::isSignedPredicate(p2)) ||
Chris Lattnerb37b6e72008-11-16 04:55:20 +00003285 (ICmpInst::isSignedPredicate(p1) && ICmpInst::isEquality(p2)) ||
3286 (ICmpInst::isSignedPredicate(p2) && ICmpInst::isEquality(p1));
Reid Spencer266e42b2006-12-23 06:05:41 +00003287}
3288
3289namespace {
3290// FoldICmpLogical - Implements (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
3291struct FoldICmpLogical {
Chris Lattner3ac7c262003-08-13 20:16:26 +00003292 InstCombiner &IC;
3293 Value *LHS, *RHS;
Reid Spencer266e42b2006-12-23 06:05:41 +00003294 ICmpInst::Predicate pred;
3295 FoldICmpLogical(InstCombiner &ic, ICmpInst *ICI)
3296 : IC(ic), LHS(ICI->getOperand(0)), RHS(ICI->getOperand(1)),
3297 pred(ICI->getPredicate()) {}
Chris Lattner3ac7c262003-08-13 20:16:26 +00003298 bool shouldApply(Value *V) const {
Reid Spencer266e42b2006-12-23 06:05:41 +00003299 if (ICmpInst *ICI = dyn_cast<ICmpInst>(V))
3300 if (PredicatesFoldable(pred, ICI->getPredicate()))
Anton Korobeynikov1bfd1212008-02-20 11:26:25 +00003301 return ((ICI->getOperand(0) == LHS && ICI->getOperand(1) == RHS) ||
3302 (ICI->getOperand(0) == RHS && ICI->getOperand(1) == LHS));
Chris Lattner3ac7c262003-08-13 20:16:26 +00003303 return false;
3304 }
Reid Spencer266e42b2006-12-23 06:05:41 +00003305 Instruction *apply(Instruction &Log) const {
3306 ICmpInst *ICI = cast<ICmpInst>(Log.getOperand(0));
3307 if (ICI->getOperand(0) != LHS) {
3308 assert(ICI->getOperand(1) == LHS);
3309 ICI->swapOperands(); // Swap the LHS and RHS of the ICmp
Chris Lattner3ac7c262003-08-13 20:16:26 +00003310 }
3311
Chris Lattnerd1bce952007-03-13 14:27:42 +00003312 ICmpInst *RHSICI = cast<ICmpInst>(Log.getOperand(1));
Reid Spencer266e42b2006-12-23 06:05:41 +00003313 unsigned LHSCode = getICmpCode(ICI);
Chris Lattnerd1bce952007-03-13 14:27:42 +00003314 unsigned RHSCode = getICmpCode(RHSICI);
Chris Lattner3ac7c262003-08-13 20:16:26 +00003315 unsigned Code;
3316 switch (Log.getOpcode()) {
3317 case Instruction::And: Code = LHSCode & RHSCode; break;
3318 case Instruction::Or: Code = LHSCode | RHSCode; break;
3319 case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
Chris Lattner2caaaba2003-09-22 20:33:34 +00003320 default: assert(0 && "Illegal logical opcode!"); return 0;
Chris Lattner3ac7c262003-08-13 20:16:26 +00003321 }
3322
Chris Lattnerd1bce952007-03-13 14:27:42 +00003323 bool isSigned = ICmpInst::isSignedPredicate(RHSICI->getPredicate()) ||
3324 ICmpInst::isSignedPredicate(ICI->getPredicate());
3325
3326 Value *RV = getICmpValue(isSigned, Code, LHS, RHS);
Chris Lattner3ac7c262003-08-13 20:16:26 +00003327 if (Instruction *I = dyn_cast<Instruction>(RV))
3328 return I;
3329 // Otherwise, it's a constant boolean value...
3330 return IC.ReplaceInstUsesWith(Log, RV);
3331 }
3332};
Chris Lattnere3a63d12006-11-15 04:53:24 +00003333} // end anonymous namespace
Chris Lattner3ac7c262003-08-13 20:16:26 +00003334
Chris Lattnerba1cb382003-09-19 17:17:26 +00003335// OptAndOp - This handles expressions of the form ((val OP C1) & C2). Where
3336// the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'. Op is
Reid Spencer2341c222007-02-02 02:16:23 +00003337// guaranteed to be a binary operator.
Chris Lattnerba1cb382003-09-19 17:17:26 +00003338Instruction *InstCombiner::OptAndOp(Instruction *Op,
Zhou Sheng75b871f2007-01-11 12:24:14 +00003339 ConstantInt *OpRHS,
3340 ConstantInt *AndRHS,
Chris Lattnerba1cb382003-09-19 17:17:26 +00003341 BinaryOperator &TheAnd) {
3342 Value *X = Op->getOperand(0);
Chris Lattnerfcf21a72004-01-12 19:47:05 +00003343 Constant *Together = 0;
Reid Spencer2341c222007-02-02 02:16:23 +00003344 if (!Op->isShift())
Reid Spencer80263aa2007-03-25 05:33:51 +00003345 Together = And(AndRHS, OpRHS);
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00003346
Chris Lattnerba1cb382003-09-19 17:17:26 +00003347 switch (Op->getOpcode()) {
3348 case Instruction::Xor:
Chris Lattner86102b82005-01-01 16:22:27 +00003349 if (Op->hasOneUse()) {
Chris Lattnerba1cb382003-09-19 17:17:26 +00003350 // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
Gabor Greife1f6e4b2008-05-16 19:29:10 +00003351 Instruction *And = BinaryOperator::CreateAnd(X, AndRHS);
Chris Lattnerba1cb382003-09-19 17:17:26 +00003352 InsertNewInstBefore(And, TheAnd);
Chris Lattner6e0123b2007-02-11 01:23:03 +00003353 And->takeName(Op);
Gabor Greife1f6e4b2008-05-16 19:29:10 +00003354 return BinaryOperator::CreateXor(And, Together);
Chris Lattnerba1cb382003-09-19 17:17:26 +00003355 }
3356 break;
3357 case Instruction::Or:
Chris Lattner86102b82005-01-01 16:22:27 +00003358 if (Together == AndRHS) // (X | C) & C --> C
3359 return ReplaceInstUsesWith(TheAnd, AndRHS);
Misha Brukmanb1c93172005-04-21 23:48:37 +00003360
Chris Lattner86102b82005-01-01 16:22:27 +00003361 if (Op->hasOneUse() && Together != OpRHS) {
3362 // (X | C1) & C2 --> (X | (C1&C2)) & C2
Gabor Greife1f6e4b2008-05-16 19:29:10 +00003363 Instruction *Or = BinaryOperator::CreateOr(X, Together);
Chris Lattner86102b82005-01-01 16:22:27 +00003364 InsertNewInstBefore(Or, TheAnd);
Chris Lattner6e0123b2007-02-11 01:23:03 +00003365 Or->takeName(Op);
Gabor Greife1f6e4b2008-05-16 19:29:10 +00003366 return BinaryOperator::CreateAnd(Or, AndRHS);
Chris Lattnerba1cb382003-09-19 17:17:26 +00003367 }
3368 break;
3369 case Instruction::Add:
Chris Lattnerf95d9b92003-10-15 16:48:29 +00003370 if (Op->hasOneUse()) {
Chris Lattnerba1cb382003-09-19 17:17:26 +00003371 // Adding a one to a single bit bit-field should be turned into an XOR
3372 // of the bit. First thing to check is to see if this AND is with a
3373 // single bit constant.
Zhou Sheng150f3bb2007-04-01 17:13:37 +00003374 const APInt& AndRHSV = cast<ConstantInt>(AndRHS)->getValue();
Chris Lattnerba1cb382003-09-19 17:17:26 +00003375
3376 // If there is only one bit set...
Chris Lattner35167c32004-06-09 07:59:58 +00003377 if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
Chris Lattnerba1cb382003-09-19 17:17:26 +00003378 // Ok, at this point, we know that we are masking the result of the
3379 // ADD down to exactly one bit. If the constant we are adding has
3380 // no bits set below this bit, then we can eliminate the ADD.
Zhou Sheng150f3bb2007-04-01 17:13:37 +00003381 const APInt& AddRHS = cast<ConstantInt>(OpRHS)->getValue();
Misha Brukmanb1c93172005-04-21 23:48:37 +00003382
Chris Lattnerba1cb382003-09-19 17:17:26 +00003383 // Check to see if any bits below the one bit set in AndRHSV are set.
3384 if ((AddRHS & (AndRHSV-1)) == 0) {
3385 // If not, the only thing that can effect the output of the AND is
3386 // the bit specified by AndRHSV. If that bit is set, the effect of
3387 // the XOR is to toggle the bit. If it is clear, then the ADD has
3388 // no effect.
3389 if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
3390 TheAnd.setOperand(0, X);
3391 return &TheAnd;
3392 } else {
Chris Lattnerba1cb382003-09-19 17:17:26 +00003393 // Pull the XOR out of the AND.
Gabor Greife1f6e4b2008-05-16 19:29:10 +00003394 Instruction *NewAnd = BinaryOperator::CreateAnd(X, AndRHS);
Chris Lattnerba1cb382003-09-19 17:17:26 +00003395 InsertNewInstBefore(NewAnd, TheAnd);
Chris Lattner6e0123b2007-02-11 01:23:03 +00003396 NewAnd->takeName(Op);
Gabor Greife1f6e4b2008-05-16 19:29:10 +00003397 return BinaryOperator::CreateXor(NewAnd, AndRHS);
Chris Lattnerba1cb382003-09-19 17:17:26 +00003398 }
3399 }
3400 }
3401 }
3402 break;
Chris Lattner2da29172003-09-19 19:05:02 +00003403
3404 case Instruction::Shl: {
3405 // We know that the AND will not produce any of the bits shifted in, so if
3406 // the anded constant includes them, clear them now!
3407 //
Zhou Shengb3a80b12007-03-29 08:15:12 +00003408 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
Zhou Shengb25806f2007-03-30 09:29:48 +00003409 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
Zhou Shengb3a80b12007-03-29 08:15:12 +00003410 APInt ShlMask(APInt::getHighBitsSet(BitWidth, BitWidth-OpRHSVal));
3411 ConstantInt *CI = ConstantInt::get(AndRHS->getValue() & ShlMask);
Misha Brukmanb1c93172005-04-21 23:48:37 +00003412
Zhou Shengb3a80b12007-03-29 08:15:12 +00003413 if (CI->getValue() == ShlMask) {
3414 // Masking out bits that the shift already masks
Chris Lattner7e794272004-09-24 15:21:34 +00003415 return ReplaceInstUsesWith(TheAnd, Op); // No need for the and.
3416 } else if (CI != AndRHS) { // Reducing bits set in and.
Chris Lattner2da29172003-09-19 19:05:02 +00003417 TheAnd.setOperand(1, CI);
3418 return &TheAnd;
3419 }
3420 break;
Misha Brukmanb1c93172005-04-21 23:48:37 +00003421 }
Reid Spencerfdff9382006-11-08 06:47:33 +00003422 case Instruction::LShr:
3423 {
Chris Lattner2da29172003-09-19 19:05:02 +00003424 // We know that the AND will not produce any of the bits shifted in, so if
3425 // the anded constant includes them, clear them now! This only applies to
3426 // unsigned shifts, because a signed shr may bring in set bits!
3427 //
Zhou Shengb3a80b12007-03-29 08:15:12 +00003428 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
Zhou Shengb25806f2007-03-30 09:29:48 +00003429 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
Zhou Shengb3a80b12007-03-29 08:15:12 +00003430 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
3431 ConstantInt *CI = ConstantInt::get(AndRHS->getValue() & ShrMask);
Chris Lattner7e794272004-09-24 15:21:34 +00003432
Zhou Shengb3a80b12007-03-29 08:15:12 +00003433 if (CI->getValue() == ShrMask) {
3434 // Masking out bits that the shift already masks.
Reid Spencerfdff9382006-11-08 06:47:33 +00003435 return ReplaceInstUsesWith(TheAnd, Op);
3436 } else if (CI != AndRHS) {
3437 TheAnd.setOperand(1, CI); // Reduce bits set in and cst.
3438 return &TheAnd;
3439 }
3440 break;
3441 }
3442 case Instruction::AShr:
3443 // Signed shr.
3444 // See if this is shifting in some sign extension, then masking it out
3445 // with an and.
3446 if (Op->hasOneUse()) {
Zhou Shengb3a80b12007-03-29 08:15:12 +00003447 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
Zhou Shengb25806f2007-03-30 09:29:48 +00003448 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
Zhou Shengb3a80b12007-03-29 08:15:12 +00003449 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
3450 Constant *C = ConstantInt::get(AndRHS->getValue() & ShrMask);
Reid Spencer2a499b02006-12-13 17:19:09 +00003451 if (C == AndRHS) { // Masking out bits shifted in.
Reid Spencer13bc5d72006-12-12 09:18:51 +00003452 // (Val ashr C1) & C2 -> (Val lshr C1) & C2
Reid Spencerfdff9382006-11-08 06:47:33 +00003453 // Make the argument unsigned.
3454 Value *ShVal = Op->getOperand(0);
Reid Spencer2341c222007-02-02 02:16:23 +00003455 ShVal = InsertNewInstBefore(
Gabor Greife1f6e4b2008-05-16 19:29:10 +00003456 BinaryOperator::CreateLShr(ShVal, OpRHS,
Reid Spencer2341c222007-02-02 02:16:23 +00003457 Op->getName()), TheAnd);
Gabor Greife1f6e4b2008-05-16 19:29:10 +00003458 return BinaryOperator::CreateAnd(ShVal, AndRHS, TheAnd.getName());
Chris Lattner7e794272004-09-24 15:21:34 +00003459 }
Chris Lattner2da29172003-09-19 19:05:02 +00003460 }
3461 break;
Chris Lattnerba1cb382003-09-19 17:17:26 +00003462 }
3463 return 0;
3464}
3465
Chris Lattner6d14f2a2002-08-09 23:47:40 +00003466
Chris Lattner6862fbd2004-09-29 17:40:11 +00003467/// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
3468/// true, otherwise (V < Lo || V >= Hi). In pratice, we emit the more efficient
Reid Spencer266e42b2006-12-23 06:05:41 +00003469/// (V-Lo) <u Hi-Lo. This method expects that Lo <= Hi. isSigned indicates
3470/// whether to treat the V, Lo and HI as signed or not. IB is the location to
Chris Lattner6862fbd2004-09-29 17:40:11 +00003471/// insert new instructions.
3472Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
Reid Spencer266e42b2006-12-23 06:05:41 +00003473 bool isSigned, bool Inside,
3474 Instruction &IB) {
Zhou Sheng75b871f2007-01-11 12:24:14 +00003475 assert(cast<ConstantInt>(ConstantExpr::getICmp((isSigned ?
Reid Spencercddc9df2007-01-12 04:24:46 +00003476 ICmpInst::ICMP_SLE:ICmpInst::ICMP_ULE), Lo, Hi))->getZExtValue() &&
Chris Lattner6862fbd2004-09-29 17:40:11 +00003477 "Lo is not <= Hi in range emission code!");
Reid Spencer266e42b2006-12-23 06:05:41 +00003478
Chris Lattner6862fbd2004-09-29 17:40:11 +00003479 if (Inside) {
3480 if (Lo == Hi) // Trivially false.
Reid Spencer266e42b2006-12-23 06:05:41 +00003481 return new ICmpInst(ICmpInst::ICMP_NE, V, V);
Misha Brukmanb1c93172005-04-21 23:48:37 +00003482
Reid Spencer266e42b2006-12-23 06:05:41 +00003483 // V >= Min && V < Hi --> V < Hi
Zhou Sheng75b871f2007-01-11 12:24:14 +00003484 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
Reid Spencerf4071162007-03-21 23:19:50 +00003485 ICmpInst::Predicate pred = (isSigned ?
Reid Spencer266e42b2006-12-23 06:05:41 +00003486 ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT);
3487 return new ICmpInst(pred, V, Hi);
3488 }
3489
3490 // Emit V-Lo <u Hi-Lo
3491 Constant *NegLo = ConstantExpr::getNeg(Lo);
Gabor Greife1f6e4b2008-05-16 19:29:10 +00003492 Instruction *Add = BinaryOperator::CreateAdd(V, NegLo, V->getName()+".off");
Chris Lattner6862fbd2004-09-29 17:40:11 +00003493 InsertNewInstBefore(Add, IB);
Reid Spencer266e42b2006-12-23 06:05:41 +00003494 Constant *UpperBound = ConstantExpr::getAdd(NegLo, Hi);
3495 return new ICmpInst(ICmpInst::ICMP_ULT, Add, UpperBound);
Chris Lattner6862fbd2004-09-29 17:40:11 +00003496 }
3497
3498 if (Lo == Hi) // Trivially true.
Reid Spencer266e42b2006-12-23 06:05:41 +00003499 return new ICmpInst(ICmpInst::ICMP_EQ, V, V);
Chris Lattner6862fbd2004-09-29 17:40:11 +00003500
Reid Spencerf4071162007-03-21 23:19:50 +00003501 // V < Min || V >= Hi -> V > Hi-1
Chris Lattner6862fbd2004-09-29 17:40:11 +00003502 Hi = SubOne(cast<ConstantInt>(Hi));
Zhou Sheng75b871f2007-01-11 12:24:14 +00003503 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
Reid Spencer266e42b2006-12-23 06:05:41 +00003504 ICmpInst::Predicate pred = (isSigned ?
3505 ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT);
3506 return new ICmpInst(pred, V, Hi);
3507 }
Reid Spencere0fc4df2006-10-20 07:07:24 +00003508
Reid Spencerf4071162007-03-21 23:19:50 +00003509 // Emit V-Lo >u Hi-1-Lo
3510 // Note that Hi has already had one subtracted from it, above.
3511 ConstantInt *NegLo = cast<ConstantInt>(ConstantExpr::getNeg(Lo));
Gabor Greife1f6e4b2008-05-16 19:29:10 +00003512 Instruction *Add = BinaryOperator::CreateAdd(V, NegLo, V->getName()+".off");
Chris Lattner6862fbd2004-09-29 17:40:11 +00003513 InsertNewInstBefore(Add, IB);
Reid Spencer266e42b2006-12-23 06:05:41 +00003514 Constant *LowerBound = ConstantExpr::getAdd(NegLo, Hi);
3515 return new ICmpInst(ICmpInst::ICMP_UGT, Add, LowerBound);
Chris Lattner6862fbd2004-09-29 17:40:11 +00003516}
3517
Chris Lattnerb4b25302005-09-18 07:22:02 +00003518// isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
3519// any number of 0s on either side. The 1s are allowed to wrap from LSB to
3520// MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs. 0x0F0F0000 is
3521// not, since all 1s are not contiguous.
Zhou Sheng56cda952007-04-02 08:20:41 +00003522static bool isRunOfOnes(ConstantInt *Val, uint32_t &MB, uint32_t &ME) {
Zhou Sheng150f3bb2007-04-01 17:13:37 +00003523 const APInt& V = Val->getValue();
Reid Spencera962d182007-03-24 00:42:08 +00003524 uint32_t BitWidth = Val->getType()->getBitWidth();
3525 if (!APIntOps::isShiftedMask(BitWidth, V)) return false;
Chris Lattnerb4b25302005-09-18 07:22:02 +00003526
3527 // look for the first zero bit after the run of ones
Reid Spencera962d182007-03-24 00:42:08 +00003528 MB = BitWidth - ((V - 1) ^ V).countLeadingZeros();
Chris Lattnerb4b25302005-09-18 07:22:02 +00003529 // look for the first non-zero bit
Reid Spencera962d182007-03-24 00:42:08 +00003530 ME = V.getActiveBits();
Chris Lattnerb4b25302005-09-18 07:22:02 +00003531 return true;
3532}
3533
Chris Lattnerb4b25302005-09-18 07:22:02 +00003534/// FoldLogicalPlusAnd - This is part of an expression (LHS +/- RHS) & Mask,
3535/// where isSub determines whether the operator is a sub. If we can fold one of
3536/// the following xforms:
Chris Lattneraf517572005-09-18 04:24:45 +00003537///
3538/// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
3539/// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3540/// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3541///
3542/// return (A +/- B).
3543///
3544Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
Zhou Sheng75b871f2007-01-11 12:24:14 +00003545 ConstantInt *Mask, bool isSub,
Chris Lattneraf517572005-09-18 04:24:45 +00003546 Instruction &I) {
3547 Instruction *LHSI = dyn_cast<Instruction>(LHS);
3548 if (!LHSI || LHSI->getNumOperands() != 2 ||
3549 !isa<ConstantInt>(LHSI->getOperand(1))) return 0;
3550
3551 ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
3552
3553 switch (LHSI->getOpcode()) {
3554 default: return 0;
3555 case Instruction::And:
Reid Spencer80263aa2007-03-25 05:33:51 +00003556 if (And(N, Mask) == Mask) {
Chris Lattnerb4b25302005-09-18 07:22:02 +00003557 // If the AndRHS is a power of two minus one (0+1+), this is simple.
Zhou Shenge9ebd3f2007-03-24 15:34:37 +00003558 if ((Mask->getValue().countLeadingZeros() +
3559 Mask->getValue().countPopulation()) ==
3560 Mask->getValue().getBitWidth())
Chris Lattnerb4b25302005-09-18 07:22:02 +00003561 break;
3562
3563 // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
3564 // part, we don't need any explicit masks to take them out of A. If that
3565 // is all N is, ignore it.
Zhou Sheng56cda952007-04-02 08:20:41 +00003566 uint32_t MB = 0, ME = 0;
Chris Lattnerb4b25302005-09-18 07:22:02 +00003567 if (isRunOfOnes(Mask, MB, ME)) { // begin/end bit of run, inclusive
Reid Spencer6274c722007-03-23 18:46:34 +00003568 uint32_t BitWidth = cast<IntegerType>(RHS->getType())->getBitWidth();
Zhou Shengb3a80b12007-03-29 08:15:12 +00003569 APInt Mask(APInt::getLowBitsSet(BitWidth, MB-1));
Chris Lattnerc3ebf402006-02-07 07:27:52 +00003570 if (MaskedValueIsZero(RHS, Mask))
Chris Lattnerb4b25302005-09-18 07:22:02 +00003571 break;
3572 }
3573 }
Chris Lattneraf517572005-09-18 04:24:45 +00003574 return 0;
3575 case Instruction::Or:
3576 case Instruction::Xor:
Chris Lattnerb4b25302005-09-18 07:22:02 +00003577 // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
Zhou Shenge9ebd3f2007-03-24 15:34:37 +00003578 if ((Mask->getValue().countLeadingZeros() +
3579 Mask->getValue().countPopulation()) == Mask->getValue().getBitWidth()
Reid Spencer54d5b1b2007-03-26 23:58:26 +00003580 && And(N, Mask)->isZero())
Chris Lattneraf517572005-09-18 04:24:45 +00003581 break;
3582 return 0;
3583 }
3584
3585 Instruction *New;
3586 if (isSub)
Gabor Greife1f6e4b2008-05-16 19:29:10 +00003587 New = BinaryOperator::CreateSub(LHSI->getOperand(0), RHS, "fold");
Chris Lattneraf517572005-09-18 04:24:45 +00003588 else
Gabor Greife1f6e4b2008-05-16 19:29:10 +00003589 New = BinaryOperator::CreateAdd(LHSI->getOperand(0), RHS, "fold");
Chris Lattneraf517572005-09-18 04:24:45 +00003590 return InsertNewInstBefore(New, I);
3591}
3592
Chris Lattner269cbd52008-11-16 05:06:21 +00003593/// FoldAndOfICmps - Fold (icmp)&(icmp) if possible.
3594Instruction *InstCombiner::FoldAndOfICmps(Instruction &I,
3595 ICmpInst *LHS, ICmpInst *RHS) {
Chris Lattnerfeaea9b2008-11-16 05:10:52 +00003596 Value *Val, *Val2;
Chris Lattner269cbd52008-11-16 05:06:21 +00003597 ConstantInt *LHSCst, *RHSCst;
3598 ICmpInst::Predicate LHSCC, RHSCC;
3599
Chris Lattnerfeaea9b2008-11-16 05:10:52 +00003600 // This only handles icmp of constants: (icmp1 A, C1) & (icmp2 B, C2).
Chris Lattner269cbd52008-11-16 05:06:21 +00003601 if (!match(LHS, m_ICmp(LHSCC, m_Value(Val), m_ConstantInt(LHSCst))) ||
Chris Lattnerfeaea9b2008-11-16 05:10:52 +00003602 !match(RHS, m_ICmp(RHSCC, m_Value(Val2), m_ConstantInt(RHSCst))))
Chris Lattner269cbd52008-11-16 05:06:21 +00003603 return 0;
Chris Lattnerfeaea9b2008-11-16 05:10:52 +00003604
3605 // (icmp ult A, C) & (icmp ult B, C) --> (icmp ult (A|B), C)
3606 // where C is a power of 2
3607 if (LHSCst == RHSCst && LHSCC == RHSCC && LHSCC == ICmpInst::ICMP_ULT &&
3608 LHSCst->getValue().isPowerOf2()) {
3609 Instruction *NewOr = BinaryOperator::CreateOr(Val, Val2);
3610 InsertNewInstBefore(NewOr, I);
3611 return new ICmpInst(LHSCC, NewOr, LHSCst);
3612 }
3613
3614 // From here on, we only handle:
3615 // (icmp1 A, C1) & (icmp2 A, C2) --> something simpler.
3616 if (Val != Val2) return 0;
3617
Chris Lattner269cbd52008-11-16 05:06:21 +00003618 // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
3619 if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
3620 RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
3621 LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
3622 RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
3623 return 0;
3624
3625 // We can't fold (ugt x, C) & (sgt x, C2).
3626 if (!PredicatesFoldable(LHSCC, RHSCC))
3627 return 0;
3628
3629 // Ensure that the larger constant is on the RHS.
Chris Lattner909b9692008-11-16 05:14:43 +00003630 bool ShouldSwap;
Chris Lattner269cbd52008-11-16 05:06:21 +00003631 if (ICmpInst::isSignedPredicate(LHSCC) ||
3632 (ICmpInst::isEquality(LHSCC) &&
3633 ICmpInst::isSignedPredicate(RHSCC)))
Chris Lattner909b9692008-11-16 05:14:43 +00003634 ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
Chris Lattner269cbd52008-11-16 05:06:21 +00003635 else
Chris Lattner909b9692008-11-16 05:14:43 +00003636 ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
3637
3638 if (ShouldSwap) {
Chris Lattner269cbd52008-11-16 05:06:21 +00003639 std::swap(LHS, RHS);
3640 std::swap(LHSCst, RHSCst);
3641 std::swap(LHSCC, RHSCC);
3642 }
3643
3644 // At this point, we know we have have two icmp instructions
3645 // comparing a value against two constants and and'ing the result
3646 // together. Because of the above check, we know that we only have
3647 // icmp eq, icmp ne, icmp [su]lt, and icmp [SU]gt here. We also know
3648 // (from the FoldICmpLogical check above), that the two constants
3649 // are not equal and that the larger constant is on the RHS
3650 assert(LHSCst != RHSCst && "Compares not folded above?");
3651
3652 switch (LHSCC) {
3653 default: assert(0 && "Unknown integer condition code!");
3654 case ICmpInst::ICMP_EQ:
3655 switch (RHSCC) {
3656 default: assert(0 && "Unknown integer condition code!");
3657 case ICmpInst::ICMP_EQ: // (X == 13 & X == 15) -> false
3658 case ICmpInst::ICMP_UGT: // (X == 13 & X > 15) -> false
3659 case ICmpInst::ICMP_SGT: // (X == 13 & X > 15) -> false
3660 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
3661 case ICmpInst::ICMP_NE: // (X == 13 & X != 15) -> X == 13
3662 case ICmpInst::ICMP_ULT: // (X == 13 & X < 15) -> X == 13
3663 case ICmpInst::ICMP_SLT: // (X == 13 & X < 15) -> X == 13
3664 return ReplaceInstUsesWith(I, LHS);
3665 }
3666 case ICmpInst::ICMP_NE:
3667 switch (RHSCC) {
3668 default: assert(0 && "Unknown integer condition code!");
3669 case ICmpInst::ICMP_ULT:
3670 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X u< 14) -> X < 13
3671 return new ICmpInst(ICmpInst::ICMP_ULT, Val, LHSCst);
3672 break; // (X != 13 & X u< 15) -> no change
3673 case ICmpInst::ICMP_SLT:
3674 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X s< 14) -> X < 13
3675 return new ICmpInst(ICmpInst::ICMP_SLT, Val, LHSCst);
3676 break; // (X != 13 & X s< 15) -> no change
3677 case ICmpInst::ICMP_EQ: // (X != 13 & X == 15) -> X == 15
3678 case ICmpInst::ICMP_UGT: // (X != 13 & X u> 15) -> X u> 15
3679 case ICmpInst::ICMP_SGT: // (X != 13 & X s> 15) -> X s> 15
3680 return ReplaceInstUsesWith(I, RHS);
3681 case ICmpInst::ICMP_NE:
3682 if (LHSCst == SubOne(RHSCst)){// (X != 13 & X != 14) -> X-13 >u 1
3683 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
3684 Instruction *Add = BinaryOperator::CreateAdd(Val, AddCST,
3685 Val->getName()+".off");
3686 InsertNewInstBefore(Add, I);
3687 return new ICmpInst(ICmpInst::ICMP_UGT, Add,
3688 ConstantInt::get(Add->getType(), 1));
3689 }
3690 break; // (X != 13 & X != 15) -> no change
3691 }
3692 break;
3693 case ICmpInst::ICMP_ULT:
3694 switch (RHSCC) {
3695 default: assert(0 && "Unknown integer condition code!");
3696 case ICmpInst::ICMP_EQ: // (X u< 13 & X == 15) -> false
3697 case ICmpInst::ICMP_UGT: // (X u< 13 & X u> 15) -> false
3698 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
3699 case ICmpInst::ICMP_SGT: // (X u< 13 & X s> 15) -> no change
3700 break;
3701 case ICmpInst::ICMP_NE: // (X u< 13 & X != 15) -> X u< 13
3702 case ICmpInst::ICMP_ULT: // (X u< 13 & X u< 15) -> X u< 13
3703 return ReplaceInstUsesWith(I, LHS);
3704 case ICmpInst::ICMP_SLT: // (X u< 13 & X s< 15) -> no change
3705 break;
3706 }
3707 break;
3708 case ICmpInst::ICMP_SLT:
3709 switch (RHSCC) {
3710 default: assert(0 && "Unknown integer condition code!");
3711 case ICmpInst::ICMP_EQ: // (X s< 13 & X == 15) -> false
3712 case ICmpInst::ICMP_SGT: // (X s< 13 & X s> 15) -> false
3713 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
3714 case ICmpInst::ICMP_UGT: // (X s< 13 & X u> 15) -> no change
3715 break;
3716 case ICmpInst::ICMP_NE: // (X s< 13 & X != 15) -> X < 13
3717 case ICmpInst::ICMP_SLT: // (X s< 13 & X s< 15) -> X < 13
3718 return ReplaceInstUsesWith(I, LHS);
3719 case ICmpInst::ICMP_ULT: // (X s< 13 & X u< 15) -> no change
3720 break;
3721 }
3722 break;
3723 case ICmpInst::ICMP_UGT:
3724 switch (RHSCC) {
3725 default: assert(0 && "Unknown integer condition code!");
3726 case ICmpInst::ICMP_EQ: // (X u> 13 & X == 15) -> X == 15
3727 case ICmpInst::ICMP_UGT: // (X u> 13 & X u> 15) -> X u> 15
3728 return ReplaceInstUsesWith(I, RHS);
3729 case ICmpInst::ICMP_SGT: // (X u> 13 & X s> 15) -> no change
3730 break;
3731 case ICmpInst::ICMP_NE:
3732 if (RHSCst == AddOne(LHSCst)) // (X u> 13 & X != 14) -> X u> 14
3733 return new ICmpInst(LHSCC, Val, RHSCst);
3734 break; // (X u> 13 & X != 15) -> no change
Chris Lattnerd397fef2008-11-16 05:20:07 +00003735 case ICmpInst::ICMP_ULT: // (X u> 13 & X u< 15) -> (X-14) <u 1
Chris Lattner269cbd52008-11-16 05:06:21 +00003736 return InsertRangeTest(Val, AddOne(LHSCst), RHSCst, false, true, I);
3737 case ICmpInst::ICMP_SLT: // (X u> 13 & X s< 15) -> no change
3738 break;
3739 }
3740 break;
3741 case ICmpInst::ICMP_SGT:
3742 switch (RHSCC) {
3743 default: assert(0 && "Unknown integer condition code!");
3744 case ICmpInst::ICMP_EQ: // (X s> 13 & X == 15) -> X == 15
3745 case ICmpInst::ICMP_SGT: // (X s> 13 & X s> 15) -> X s> 15
3746 return ReplaceInstUsesWith(I, RHS);
3747 case ICmpInst::ICMP_UGT: // (X s> 13 & X u> 15) -> no change
3748 break;
3749 case ICmpInst::ICMP_NE:
3750 if (RHSCst == AddOne(LHSCst)) // (X s> 13 & X != 14) -> X s> 14
3751 return new ICmpInst(LHSCC, Val, RHSCst);
3752 break; // (X s> 13 & X != 15) -> no change
Chris Lattnerd397fef2008-11-16 05:20:07 +00003753 case ICmpInst::ICMP_SLT: // (X s> 13 & X s< 15) -> (X-14) s< 1
Chris Lattner269cbd52008-11-16 05:06:21 +00003754 return InsertRangeTest(Val, AddOne(LHSCst), RHSCst, true, true, I);
3755 case ICmpInst::ICMP_ULT: // (X s> 13 & X u< 15) -> no change
3756 break;
3757 }
3758 break;
3759 }
Chris Lattner269cbd52008-11-16 05:06:21 +00003760
3761 return 0;
3762}
3763
3764
Chris Lattner113f4f42002-06-25 16:13:24 +00003765Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00003766 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00003767 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003768
Chris Lattner81a7a232004-10-16 18:11:37 +00003769 if (isa<UndefValue>(Op1)) // X & undef -> 0
3770 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3771
Chris Lattner86102b82005-01-01 16:22:27 +00003772 // and X, X = X
3773 if (Op0 == Op1)
Chris Lattnere6794492002-08-12 21:17:25 +00003774 return ReplaceInstUsesWith(I, Op1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003775
Chris Lattner5b2edb12006-02-12 08:02:11 +00003776 // See if we can simplify any instructions used by the instruction whose sole
Chris Lattner5997cf92006-02-08 03:25:32 +00003777 // purpose is to compute bits we don't care about.
Reid Spencerd84d35b2007-02-15 02:26:10 +00003778 if (!isa<VectorType>(I.getType())) {
Reid Spencerb722f2b2007-03-22 22:19:58 +00003779 uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
3780 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
3781 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
Chris Lattner120ab032007-01-18 22:16:33 +00003782 KnownZero, KnownOne))
Reid Spencer54d5b1b2007-03-26 23:58:26 +00003783 return &I;
Chris Lattner120ab032007-01-18 22:16:33 +00003784 } else {
Reid Spencerd84d35b2007-02-15 02:26:10 +00003785 if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
Chris Lattnerf14e5172007-06-15 05:26:55 +00003786 if (CP->isAllOnesValue()) // X & <-1,-1> -> X
Chris Lattner120ab032007-01-18 22:16:33 +00003787 return ReplaceInstUsesWith(I, I.getOperand(0));
Chris Lattnerf14e5172007-06-15 05:26:55 +00003788 } else if (isa<ConstantAggregateZero>(Op1)) {
3789 return ReplaceInstUsesWith(I, Op1); // X & <0,0> -> <0,0>
Chris Lattner120ab032007-01-18 22:16:33 +00003790 }
3791 }
Chris Lattner5997cf92006-02-08 03:25:32 +00003792
Zhou Sheng75b871f2007-01-11 12:24:14 +00003793 if (ConstantInt *AndRHS = dyn_cast<ConstantInt>(Op1)) {
Zhou Sheng150f3bb2007-04-01 17:13:37 +00003794 const APInt& AndRHSMask = AndRHS->getValue();
3795 APInt NotAndRHS(~AndRHSMask);
Chris Lattner86102b82005-01-01 16:22:27 +00003796
Chris Lattnerba1cb382003-09-19 17:17:26 +00003797 // Optimize a variety of ((val OP C1) & C2) combinations...
Reid Spencer2341c222007-02-02 02:16:23 +00003798 if (isa<BinaryOperator>(Op0)) {
Chris Lattnerba1cb382003-09-19 17:17:26 +00003799 Instruction *Op0I = cast<Instruction>(Op0);
Chris Lattner86102b82005-01-01 16:22:27 +00003800 Value *Op0LHS = Op0I->getOperand(0);
3801 Value *Op0RHS = Op0I->getOperand(1);
3802 switch (Op0I->getOpcode()) {
3803 case Instruction::Xor:
3804 case Instruction::Or:
Chris Lattner9e2c7fa2005-01-23 20:26:55 +00003805 // If the mask is only needed on one incoming arm, push it up.
3806 if (Op0I->hasOneUse()) {
3807 if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
3808 // Not masking anything out for the LHS, move to RHS.
Gabor Greife1f6e4b2008-05-16 19:29:10 +00003809 Instruction *NewRHS = BinaryOperator::CreateAnd(Op0RHS, AndRHS,
Chris Lattner9e2c7fa2005-01-23 20:26:55 +00003810 Op0RHS->getName()+".masked");
3811 InsertNewInstBefore(NewRHS, I);
Gabor Greife1f6e4b2008-05-16 19:29:10 +00003812 return BinaryOperator::Create(
Chris Lattner9e2c7fa2005-01-23 20:26:55 +00003813 cast<BinaryOperator>(Op0I)->getOpcode(), Op0LHS, NewRHS);
Misha Brukmanb1c93172005-04-21 23:48:37 +00003814 }
Chris Lattnerc3ebf402006-02-07 07:27:52 +00003815 if (!isa<Constant>(Op0RHS) &&
Chris Lattner9e2c7fa2005-01-23 20:26:55 +00003816 MaskedValueIsZero(Op0RHS, NotAndRHS)) {
3817 // Not masking anything out for the RHS, move to LHS.
Gabor Greife1f6e4b2008-05-16 19:29:10 +00003818 Instruction *NewLHS = BinaryOperator::CreateAnd(Op0LHS, AndRHS,
Chris Lattner9e2c7fa2005-01-23 20:26:55 +00003819 Op0LHS->getName()+".masked");
3820 InsertNewInstBefore(NewLHS, I);
Gabor Greife1f6e4b2008-05-16 19:29:10 +00003821 return BinaryOperator::Create(
Chris Lattner9e2c7fa2005-01-23 20:26:55 +00003822 cast<BinaryOperator>(Op0I)->getOpcode(), NewLHS, Op0RHS);
3823 }
3824 }
3825
Chris Lattner86102b82005-01-01 16:22:27 +00003826 break;
Chris Lattneraf517572005-09-18 04:24:45 +00003827 case Instruction::Add:
Chris Lattnerb4b25302005-09-18 07:22:02 +00003828 // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
3829 // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
3830 // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
3831 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
Gabor Greife1f6e4b2008-05-16 19:29:10 +00003832 return BinaryOperator::CreateAnd(V, AndRHS);
Chris Lattnerb4b25302005-09-18 07:22:02 +00003833 if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
Gabor Greife1f6e4b2008-05-16 19:29:10 +00003834 return BinaryOperator::CreateAnd(V, AndRHS); // Add commutes
Chris Lattneraf517572005-09-18 04:24:45 +00003835 break;
3836
3837 case Instruction::Sub:
Chris Lattnerb4b25302005-09-18 07:22:02 +00003838 // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
3839 // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
3840 // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
3841 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
Gabor Greife1f6e4b2008-05-16 19:29:10 +00003842 return BinaryOperator::CreateAnd(V, AndRHS);
Nick Lewycky0d3645e2008-07-09 04:32:37 +00003843
Nick Lewycky6193a562008-07-10 05:51:40 +00003844 // (A - N) & AndRHS -> -N & AndRHS iff A&AndRHS==0 and AndRHS
3845 // has 1's for all bits that the subtraction with A might affect.
3846 if (Op0I->hasOneUse()) {
3847 uint32_t BitWidth = AndRHSMask.getBitWidth();
3848 uint32_t Zeros = AndRHSMask.countLeadingZeros();
3849 APInt Mask = APInt::getLowBitsSet(BitWidth, BitWidth - Zeros);
3850
Nick Lewycky0d3645e2008-07-09 04:32:37 +00003851 ConstantInt *A = dyn_cast<ConstantInt>(Op0LHS);
Nick Lewycky6193a562008-07-10 05:51:40 +00003852 if (!(A && A->isZero()) && // avoid infinite recursion.
3853 MaskedValueIsZero(Op0LHS, Mask)) {
Nick Lewycky0d3645e2008-07-09 04:32:37 +00003854 Instruction *NewNeg = BinaryOperator::CreateNeg(Op0RHS);
3855 InsertNewInstBefore(NewNeg, I);
3856 return BinaryOperator::CreateAnd(NewNeg, AndRHS);
3857 }
3858 }
Chris Lattneraf517572005-09-18 04:24:45 +00003859 break;
Nick Lewycky364661c2008-07-09 05:20:13 +00003860
3861 case Instruction::Shl:
3862 case Instruction::LShr:
3863 // (1 << x) & 1 --> zext(x == 0)
3864 // (1 >> x) & 1 --> zext(x == 0)
Nick Lewyckybb89c2a2008-07-09 07:35:26 +00003865 if (AndRHSMask == 1 && Op0LHS == AndRHS) {
Nick Lewycky364661c2008-07-09 05:20:13 +00003866 Instruction *NewICmp = new ICmpInst(ICmpInst::ICMP_EQ, Op0RHS,
3867 Constant::getNullValue(I.getType()));
3868 InsertNewInstBefore(NewICmp, I);
3869 return new ZExtInst(NewICmp, I.getType());
3870 }
3871 break;
Chris Lattner86102b82005-01-01 16:22:27 +00003872 }
3873
Chris Lattner16464b32003-07-23 19:25:52 +00003874 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
Chris Lattner86102b82005-01-01 16:22:27 +00003875 if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
Chris Lattnerba1cb382003-09-19 17:17:26 +00003876 return Res;
Chris Lattner86102b82005-01-01 16:22:27 +00003877 } else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
Chris Lattner2c14cf72005-08-07 07:03:10 +00003878 // If this is an integer truncation or change from signed-to-unsigned, and
3879 // if the source is an and/or with immediate, transform it. This
3880 // frequently occurs for bitfield accesses.
3881 if (Instruction *CastOp = dyn_cast<Instruction>(CI->getOperand(0))) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +00003882 if ((isa<TruncInst>(CI) || isa<BitCastInst>(CI)) &&
Chris Lattner2c14cf72005-08-07 07:03:10 +00003883 CastOp->getNumOperands() == 2)
Anton Korobeynikov1bfd1212008-02-20 11:26:25 +00003884 if (ConstantInt *AndCI = dyn_cast<ConstantInt>(CastOp->getOperand(1))) {
Chris Lattner2c14cf72005-08-07 07:03:10 +00003885 if (CastOp->getOpcode() == Instruction::And) {
3886 // Change: and (cast (and X, C1) to T), C2
Reid Spencer6c38f0b2006-11-27 01:05:10 +00003887 // into : and (cast X to T), trunc_or_bitcast(C1)&C2
3888 // This will fold the two constants together, which may allow
3889 // other simplifications.
Gabor Greife1f6e4b2008-05-16 19:29:10 +00003890 Instruction *NewCast = CastInst::CreateTruncOrBitCast(
Reid Spencerbb65ebf2006-12-12 23:36:14 +00003891 CastOp->getOperand(0), I.getType(),
3892 CastOp->getName()+".shrunk");
Chris Lattner2c14cf72005-08-07 07:03:10 +00003893 NewCast = InsertNewInstBefore(NewCast, I);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00003894 // trunc_or_bitcast(C1)&C2
Reid Spencerbb65ebf2006-12-12 23:36:14 +00003895 Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
Reid Spencer6c38f0b2006-11-27 01:05:10 +00003896 C3 = ConstantExpr::getAnd(C3, AndRHS);
Gabor Greife1f6e4b2008-05-16 19:29:10 +00003897 return BinaryOperator::CreateAnd(NewCast, C3);
Chris Lattner2c14cf72005-08-07 07:03:10 +00003898 } else if (CastOp->getOpcode() == Instruction::Or) {
3899 // Change: and (cast (or X, C1) to T), C2
3900 // into : trunc(C1)&C2 iff trunc(C1)&C2 == C2
Chris Lattner2dc148e2006-12-12 19:11:20 +00003901 Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
Chris Lattner2c14cf72005-08-07 07:03:10 +00003902 if (ConstantExpr::getAnd(C3, AndRHS) == AndRHS) // trunc(C1)&C2
3903 return ReplaceInstUsesWith(I, AndRHS);
3904 }
Anton Korobeynikov1bfd1212008-02-20 11:26:25 +00003905 }
Chris Lattner2c14cf72005-08-07 07:03:10 +00003906 }
Chris Lattner33217db2003-07-23 19:36:21 +00003907 }
Chris Lattner183b3362004-04-09 19:05:30 +00003908
3909 // Try to fold constant and into select arguments.
3910 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner86102b82005-01-01 16:22:27 +00003911 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00003912 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00003913 if (isa<PHINode>(Op0))
3914 if (Instruction *NV = FoldOpIntoPhi(I))
3915 return NV;
Chris Lattner49b47ae2003-07-23 17:57:01 +00003916 }
3917
Chris Lattnerbb74e222003-03-10 23:06:50 +00003918 Value *Op0NotVal = dyn_castNotVal(Op0);
3919 Value *Op1NotVal = dyn_castNotVal(Op1);
Chris Lattner3082c5a2003-02-18 19:28:33 +00003920
Chris Lattner023a4832004-06-18 06:07:51 +00003921 if (Op0NotVal == Op1 || Op1NotVal == Op0) // A & ~A == ~A & A == 0
3922 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3923
Misha Brukman9c003d82004-07-30 12:50:08 +00003924 // (~A & ~B) == (~(A | B)) - De Morgan's Law
Chris Lattnerbb74e222003-03-10 23:06:50 +00003925 if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
Gabor Greife1f6e4b2008-05-16 19:29:10 +00003926 Instruction *Or = BinaryOperator::CreateOr(Op0NotVal, Op1NotVal,
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003927 I.getName()+".demorgan");
Chris Lattner49b47ae2003-07-23 17:57:01 +00003928 InsertNewInstBefore(Or, I);
Gabor Greife1f6e4b2008-05-16 19:29:10 +00003929 return BinaryOperator::CreateNot(Or);
Chris Lattner3082c5a2003-02-18 19:28:33 +00003930 }
Chris Lattner8b10ab32006-02-13 23:07:23 +00003931
3932 {
Chris Lattner481e28b2007-06-15 05:58:24 +00003933 Value *A = 0, *B = 0, *C = 0, *D = 0;
3934 if (match(Op0, m_Or(m_Value(A), m_Value(B)))) {
Chris Lattner8b10ab32006-02-13 23:07:23 +00003935 if (A == Op1 || B == Op1) // (A | ?) & A --> A
3936 return ReplaceInstUsesWith(I, Op1);
Chris Lattner481e28b2007-06-15 05:58:24 +00003937
3938 // (A|B) & ~(A&B) -> A^B
3939 if (match(Op1, m_Not(m_And(m_Value(C), m_Value(D))))) {
3940 if ((A == C && B == D) || (A == D && B == C))
Gabor Greife1f6e4b2008-05-16 19:29:10 +00003941 return BinaryOperator::CreateXor(A, B);
Chris Lattner481e28b2007-06-15 05:58:24 +00003942 }
3943 }
3944
3945 if (match(Op1, m_Or(m_Value(A), m_Value(B)))) {
Chris Lattner8b10ab32006-02-13 23:07:23 +00003946 if (A == Op0 || B == Op0) // A & (A | ?) --> A
3947 return ReplaceInstUsesWith(I, Op0);
Chris Lattner481e28b2007-06-15 05:58:24 +00003948
3949 // ~(A&B) & (A|B) -> A^B
3950 if (match(Op0, m_Not(m_And(m_Value(C), m_Value(D))))) {
3951 if ((A == C && B == D) || (A == D && B == C))
Gabor Greife1f6e4b2008-05-16 19:29:10 +00003952 return BinaryOperator::CreateXor(A, B);
Chris Lattner481e28b2007-06-15 05:58:24 +00003953 }
3954 }
Chris Lattnerdcd07922006-04-01 08:03:55 +00003955
3956 if (Op0->hasOneUse() &&
3957 match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
3958 if (A == Op1) { // (A^B)&A -> A&(A^B)
3959 I.swapOperands(); // Simplify below
3960 std::swap(Op0, Op1);
3961 } else if (B == Op1) { // (A^B)&B -> B&(B^A)
3962 cast<BinaryOperator>(Op0)->swapOperands();
3963 I.swapOperands(); // Simplify below
3964 std::swap(Op0, Op1);
3965 }
3966 }
Bill Wendling9eef4212008-11-30 13:08:13 +00003967
Chris Lattnerdcd07922006-04-01 08:03:55 +00003968 if (Op1->hasOneUse() &&
3969 match(Op1, m_Xor(m_Value(A), m_Value(B)))) {
3970 if (B == Op0) { // B&(A^B) -> B&(B^A)
3971 cast<BinaryOperator>(Op1)->swapOperands();
3972 std::swap(A, B);
3973 }
3974 if (A == Op0) { // A&(A^B) -> A & ~B
Gabor Greife1f6e4b2008-05-16 19:29:10 +00003975 Instruction *NotB = BinaryOperator::CreateNot(B, "tmp");
Chris Lattnerdcd07922006-04-01 08:03:55 +00003976 InsertNewInstBefore(NotB, I);
Gabor Greife1f6e4b2008-05-16 19:29:10 +00003977 return BinaryOperator::CreateAnd(A, NotB);
Chris Lattnerdcd07922006-04-01 08:03:55 +00003978 }
3979 }
Bill Wendling9eef4212008-11-30 13:08:13 +00003980
3981 // (A&((~A)|B)) -> A&B
3982 if (match(Op0, m_Or(m_Not(m_Value(A)), m_Value(B)))) {
3983 if (A == Op1)
3984 return BinaryOperator::CreateAnd(A, B);
3985 }
3986 if (match(Op0, m_Or(m_Value(A), m_Not(m_Value(B))))) {
3987 if (B == Op1)
3988 return BinaryOperator::CreateAnd(A, B);
3989 }
3990 if (match(Op1, m_Or(m_Not(m_Value(A)), m_Value(B)))) {
3991 if (A == Op0)
3992 return BinaryOperator::CreateAnd(A, B);
3993 }
3994 if (match(Op1, m_Or(m_Value(A), m_Not(m_Value(B))))) {
3995 if (B == Op0)
3996 return BinaryOperator::CreateAnd(A, B);
3997 }
Chris Lattner8b10ab32006-02-13 23:07:23 +00003998 }
3999
Reid Spencer266e42b2006-12-23 06:05:41 +00004000 if (ICmpInst *RHS = dyn_cast<ICmpInst>(Op1)) {
4001 // (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
4002 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Chris Lattner3ac7c262003-08-13 20:16:26 +00004003 return R;
4004
Chris Lattner269cbd52008-11-16 05:06:21 +00004005 if (ICmpInst *LHS = dyn_cast<ICmpInst>(Op0))
4006 if (Instruction *Res = FoldAndOfICmps(I, LHS, RHS))
4007 return Res;
Chris Lattner623826c2004-09-28 21:48:02 +00004008 }
4009
Chris Lattner3af10532006-05-05 06:39:07 +00004010 // fold (and (cast A), (cast B)) -> (cast (and A, B))
Reid Spencer799b5bf2006-12-13 08:27:15 +00004011 if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
4012 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
4013 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind ?
4014 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattner03c49532007-01-15 02:27:26 +00004015 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
Reid Spencer799b5bf2006-12-13 08:27:15 +00004016 // Only do this if the casts both really cause code to be generated.
Reid Spencer266e42b2006-12-23 06:05:41 +00004017 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
4018 I.getType(), TD) &&
4019 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
4020 I.getType(), TD)) {
Gabor Greife1f6e4b2008-05-16 19:29:10 +00004021 Instruction *NewOp = BinaryOperator::CreateAnd(Op0C->getOperand(0),
Reid Spencer799b5bf2006-12-13 08:27:15 +00004022 Op1C->getOperand(0),
4023 I.getName());
4024 InsertNewInstBefore(NewOp, I);
Gabor Greife1f6e4b2008-05-16 19:29:10 +00004025 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
Reid Spencer799b5bf2006-12-13 08:27:15 +00004026 }
Chris Lattner3af10532006-05-05 06:39:07 +00004027 }
Chris Lattnerf05d69a2006-11-14 07:46:50 +00004028
4029 // (X >> Z) & (Y >> Z) -> (X&Y) >> Z for all shifts.
Reid Spencer2341c222007-02-02 02:16:23 +00004030 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4031 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4032 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
Chris Lattnerf05d69a2006-11-14 07:46:50 +00004033 SI0->getOperand(1) == SI1->getOperand(1) &&
4034 (SI0->hasOneUse() || SI1->hasOneUse())) {
4035 Instruction *NewOp =
Gabor Greife1f6e4b2008-05-16 19:29:10 +00004036 InsertNewInstBefore(BinaryOperator::CreateAnd(SI0->getOperand(0),
Chris Lattnerf05d69a2006-11-14 07:46:50 +00004037 SI1->getOperand(0),
4038 SI0->getName()), I);
Gabor Greife1f6e4b2008-05-16 19:29:10 +00004039 return BinaryOperator::Create(SI1->getOpcode(), NewOp,
Reid Spencer2341c222007-02-02 02:16:23 +00004040 SI1->getOperand(1));
Chris Lattnerf05d69a2006-11-14 07:46:50 +00004041 }
Chris Lattner3af10532006-05-05 06:39:07 +00004042 }
4043
Evan Cheng67786cc2008-10-14 17:15:11 +00004044 // If and'ing two fcmp, try combine them into one.
Chris Lattnerc62877e2007-10-24 05:38:08 +00004045 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
4046 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1))) {
4047 if (LHS->getPredicate() == FCmpInst::FCMP_ORD &&
Evan Cheng67786cc2008-10-14 17:15:11 +00004048 RHS->getPredicate() == FCmpInst::FCMP_ORD) {
4049 // (fcmp ord x, c) & (fcmp ord y, c) -> (fcmp ord x, y)
Chris Lattnerc62877e2007-10-24 05:38:08 +00004050 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
4051 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
4052 // If either of the constants are nans, then the whole thing returns
4053 // false.
Chris Lattner55b83022007-10-24 18:54:45 +00004054 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
Chris Lattnerc62877e2007-10-24 05:38:08 +00004055 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
4056 return new FCmpInst(FCmpInst::FCMP_ORD, LHS->getOperand(0),
4057 RHS->getOperand(0));
4058 }
Evan Cheng67786cc2008-10-14 17:15:11 +00004059 } else {
4060 Value *Op0LHS, *Op0RHS, *Op1LHS, *Op1RHS;
4061 FCmpInst::Predicate Op0CC, Op1CC;
4062 if (match(Op0, m_FCmp(Op0CC, m_Value(Op0LHS), m_Value(Op0RHS))) &&
4063 match(Op1, m_FCmp(Op1CC, m_Value(Op1LHS), m_Value(Op1RHS)))) {
Evan Chengce707522008-10-14 18:13:38 +00004064 if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
4065 // Swap RHS operands to match LHS.
4066 Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
4067 std::swap(Op1LHS, Op1RHS);
4068 }
Evan Cheng67786cc2008-10-14 17:15:11 +00004069 if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
4070 // Simplify (fcmp cc0 x, y) & (fcmp cc1 x, y).
4071 if (Op0CC == Op1CC)
4072 return new FCmpInst((FCmpInst::Predicate)Op0CC, Op0LHS, Op0RHS);
4073 else if (Op0CC == FCmpInst::FCMP_FALSE ||
4074 Op1CC == FCmpInst::FCMP_FALSE)
4075 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
4076 else if (Op0CC == FCmpInst::FCMP_TRUE)
4077 return ReplaceInstUsesWith(I, Op1);
4078 else if (Op1CC == FCmpInst::FCMP_TRUE)
4079 return ReplaceInstUsesWith(I, Op0);
4080 bool Op0Ordered;
4081 bool Op1Ordered;
4082 unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
4083 unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
4084 if (Op1Pred == 0) {
4085 std::swap(Op0, Op1);
4086 std::swap(Op0Pred, Op1Pred);
4087 std::swap(Op0Ordered, Op1Ordered);
4088 }
4089 if (Op0Pred == 0) {
4090 // uno && ueq -> uno && (uno || eq) -> ueq
4091 // ord && olt -> ord && (ord && lt) -> olt
4092 if (Op0Ordered == Op1Ordered)
4093 return ReplaceInstUsesWith(I, Op1);
4094 // uno && oeq -> uno && (ord && eq) -> false
4095 // uno && ord -> false
4096 if (!Op0Ordered)
4097 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
4098 // ord && ueq -> ord && (uno || eq) -> oeq
4099 return cast<Instruction>(getFCmpValue(true, Op1Pred,
4100 Op0LHS, Op0RHS));
4101 }
4102 }
4103 }
4104 }
Chris Lattnerc62877e2007-10-24 05:38:08 +00004105 }
4106 }
Nick Lewycky0d3645e2008-07-09 04:32:37 +00004107
Chris Lattner113f4f42002-06-25 16:13:24 +00004108 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00004109}
4110
Chris Lattner917a6c12008-10-05 02:13:19 +00004111/// CollectBSwapParts - Analyze the specified subexpression and see if it is
4112/// capable of providing pieces of a bswap. The subexpression provides pieces
4113/// of a bswap if it is proven that each of the non-zero bytes in the output of
4114/// the expression came from the corresponding "byte swapped" byte in some other
4115/// value. For example, if the current subexpression is "(shl i32 %X, 24)" then
4116/// we know that the expression deposits the low byte of %X into the high byte
4117/// of the bswap result and that all other bytes are zero. This expression is
4118/// accepted, the high byte of ByteValues is set to X to indicate a correct
4119/// match.
4120///
4121/// This function returns true if the match was unsuccessful and false if so.
4122/// On entry to the function the "OverallLeftShift" is a signed integer value
4123/// indicating the number of bytes that the subexpression is later shifted. For
4124/// example, if the expression is later right shifted by 16 bits, the
4125/// OverallLeftShift value would be -2 on entry. This is used to specify which
4126/// byte of ByteValues is actually being set.
4127///
4128/// Similarly, ByteMask is a bitmask where a bit is clear if its corresponding
4129/// byte is masked to zero by a user. For example, in (X & 255), X will be
4130/// processed with a bytemask of 1. Because bytemask is 32-bits, this limits
4131/// this function to working on up to 32-byte (256 bit) values. ByteMask is
4132/// always in the local (OverallLeftShift) coordinate space.
4133///
4134static bool CollectBSwapParts(Value *V, int OverallLeftShift, uint32_t ByteMask,
4135 SmallVector<Value*, 8> &ByteValues) {
4136 if (Instruction *I = dyn_cast<Instruction>(V)) {
4137 // If this is an or instruction, it may be an inner node of the bswap.
4138 if (I->getOpcode() == Instruction::Or) {
4139 return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
4140 ByteValues) ||
4141 CollectBSwapParts(I->getOperand(1), OverallLeftShift, ByteMask,
4142 ByteValues);
Chris Lattnerc482a9e2006-06-15 19:07:26 +00004143 }
Chris Lattner917a6c12008-10-05 02:13:19 +00004144
4145 // If this is a logical shift by a constant multiple of 8, recurse with
4146 // OverallLeftShift and ByteMask adjusted.
4147 if (I->isLogicalShift() && isa<ConstantInt>(I->getOperand(1))) {
4148 unsigned ShAmt =
4149 cast<ConstantInt>(I->getOperand(1))->getLimitedValue(~0U);
4150 // Ensure the shift amount is defined and of a byte value.
4151 if ((ShAmt & 7) || (ShAmt > 8*ByteValues.size()))
4152 return true;
4153
4154 unsigned ByteShift = ShAmt >> 3;
4155 if (I->getOpcode() == Instruction::Shl) {
4156 // X << 2 -> collect(X, +2)
4157 OverallLeftShift += ByteShift;
4158 ByteMask >>= ByteShift;
4159 } else {
4160 // X >>u 2 -> collect(X, -2)
4161 OverallLeftShift -= ByteShift;
4162 ByteMask <<= ByteShift;
Chris Lattner42d57852008-10-08 06:42:28 +00004163 ByteMask &= (~0U >> (32-ByteValues.size()));
Chris Lattner917a6c12008-10-05 02:13:19 +00004164 }
4165
4166 if (OverallLeftShift >= (int)ByteValues.size()) return true;
4167 if (OverallLeftShift <= -(int)ByteValues.size()) return true;
4168
4169 return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
4170 ByteValues);
4171 }
4172
4173 // If this is a logical 'and' with a mask that clears bytes, clear the
4174 // corresponding bytes in ByteMask.
4175 if (I->getOpcode() == Instruction::And &&
4176 isa<ConstantInt>(I->getOperand(1))) {
4177 // Scan every byte of the and mask, seeing if the byte is either 0 or 255.
4178 unsigned NumBytes = ByteValues.size();
4179 APInt Byte(I->getType()->getPrimitiveSizeInBits(), 255);
4180 const APInt &AndMask = cast<ConstantInt>(I->getOperand(1))->getValue();
4181
4182 for (unsigned i = 0; i != NumBytes; ++i, Byte <<= 8) {
4183 // If this byte is masked out by a later operation, we don't care what
4184 // the and mask is.
4185 if ((ByteMask & (1 << i)) == 0)
4186 continue;
4187
4188 // If the AndMask is all zeros for this byte, clear the bit.
4189 APInt MaskB = AndMask & Byte;
4190 if (MaskB == 0) {
4191 ByteMask &= ~(1U << i);
4192 continue;
4193 }
4194
4195 // If the AndMask is not all ones for this byte, it's not a bytezap.
4196 if (MaskB != Byte)
4197 return true;
4198
4199 // Otherwise, this byte is kept.
4200 }
4201
4202 return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
4203 ByteValues);
4204 }
Chris Lattnerc482a9e2006-06-15 19:07:26 +00004205 }
4206
Chris Lattner917a6c12008-10-05 02:13:19 +00004207 // Okay, we got to something that isn't a shift, 'or' or 'and'. This must be
4208 // the input value to the bswap. Some observations: 1) if more than one byte
4209 // is demanded from this input, then it could not be successfully assembled
4210 // into a byteswap. At least one of the two bytes would not be aligned with
4211 // their ultimate destination.
4212 if (!isPowerOf2_32(ByteMask)) return true;
4213 unsigned InputByteNo = CountTrailingZeros_32(ByteMask);
Chris Lattnerc482a9e2006-06-15 19:07:26 +00004214
Chris Lattner917a6c12008-10-05 02:13:19 +00004215 // 2) The input and ultimate destinations must line up: if byte 3 of an i32
4216 // is demanded, it needs to go into byte 0 of the result. This means that the
4217 // byte needs to be shifted until it lands in the right byte bucket. The
4218 // shift amount depends on the position: if the byte is coming from the high
4219 // part of the value (e.g. byte 3) then it must be shifted right. If from the
4220 // low part, it must be shifted left.
4221 unsigned DestByteNo = InputByteNo + OverallLeftShift;
4222 if (InputByteNo < ByteValues.size()/2) {
4223 if (ByteValues.size()-1-DestByteNo != InputByteNo)
4224 return true;
4225 } else {
4226 if (ByteValues.size()-1-DestByteNo != InputByteNo)
4227 return true;
4228 }
Chris Lattnerc482a9e2006-06-15 19:07:26 +00004229
4230 // If the destination byte value is already defined, the values are or'd
4231 // together, which isn't a bswap (unless it's an or of the same bits).
Chris Lattner917a6c12008-10-05 02:13:19 +00004232 if (ByteValues[DestByteNo] && ByteValues[DestByteNo] != V)
Chris Lattnerc482a9e2006-06-15 19:07:26 +00004233 return true;
Chris Lattner917a6c12008-10-05 02:13:19 +00004234 ByteValues[DestByteNo] = V;
Chris Lattnerc482a9e2006-06-15 19:07:26 +00004235 return false;
4236}
4237
4238/// MatchBSwap - Given an OR instruction, check to see if this is a bswap idiom.
4239/// If so, insert the new bswap intrinsic and return it.
4240Instruction *InstCombiner::MatchBSwap(BinaryOperator &I) {
Chris Lattnerc3eeb422007-04-01 20:57:36 +00004241 const IntegerType *ITy = dyn_cast<IntegerType>(I.getType());
Chris Lattner917a6c12008-10-05 02:13:19 +00004242 if (!ITy || ITy->getBitWidth() % 16 ||
4243 // ByteMask only allows up to 32-byte values.
4244 ITy->getBitWidth() > 32*8)
Chris Lattnerc3eeb422007-04-01 20:57:36 +00004245 return 0; // Can only bswap pairs of bytes. Can't do vectors.
Chris Lattnerc482a9e2006-06-15 19:07:26 +00004246
4247 /// ByteValues - For each byte of the result, we keep track of which value
4248 /// defines each byte.
Chris Lattner99c6cf62007-02-15 22:52:10 +00004249 SmallVector<Value*, 8> ByteValues;
Chris Lattnerc3eeb422007-04-01 20:57:36 +00004250 ByteValues.resize(ITy->getBitWidth()/8);
Chris Lattnerc482a9e2006-06-15 19:07:26 +00004251
4252 // Try to find all the pieces corresponding to the bswap.
Chris Lattner917a6c12008-10-05 02:13:19 +00004253 uint32_t ByteMask = ~0U >> (32-ByteValues.size());
4254 if (CollectBSwapParts(&I, 0, ByteMask, ByteValues))
Chris Lattnerc482a9e2006-06-15 19:07:26 +00004255 return 0;
4256
4257 // Check to see if all of the bytes come from the same value.
4258 Value *V = ByteValues[0];
4259 if (V == 0) return 0; // Didn't find a byte? Must be zero.
4260
4261 // Check to make sure that all of the bytes come from the same value.
4262 for (unsigned i = 1, e = ByteValues.size(); i != e; ++i)
4263 if (ByteValues[i] != V)
4264 return 0;
Chandler Carruth7132e002007-08-04 01:51:18 +00004265 const Type *Tys[] = { ITy };
Chris Lattnerc482a9e2006-06-15 19:07:26 +00004266 Module *M = I.getParent()->getParent()->getParent();
Chandler Carruth7132e002007-08-04 01:51:18 +00004267 Function *F = Intrinsic::getDeclaration(M, Intrinsic::bswap, Tys, 1);
Gabor Greife9ecc682008-04-06 20:25:17 +00004268 return CallInst::Create(F, V);
Chris Lattnerc482a9e2006-06-15 19:07:26 +00004269}
4270
Chris Lattner5f6d9a32008-11-16 04:24:12 +00004271/// MatchSelectFromAndOr - We have an expression of the form (A&C)|(B&D). Check
4272/// If A is (cond?-1:0) and either B or D is ~(cond?-1,0) or (cond?0,-1), then
4273/// we can simplify this expression to "cond ? C : D or B".
4274static Instruction *MatchSelectFromAndOr(Value *A, Value *B,
4275 Value *C, Value *D) {
Chris Lattner569d78c2008-11-16 04:26:55 +00004276 // If A is not a select of -1/0, this cannot match.
Chris Lattnerf1be2852008-11-16 04:46:19 +00004277 Value *Cond = 0;
Chris Lattnerfae5e332008-11-16 04:33:38 +00004278 if (!match(A, m_SelectCst(m_Value(Cond), -1, 0)))
Chris Lattner5f6d9a32008-11-16 04:24:12 +00004279 return 0;
4280
Chris Lattner569d78c2008-11-16 04:26:55 +00004281 // ((cond?-1:0)&C) | (B&(cond?0:-1)) -> cond ? C : B.
Chris Lattnerf1be2852008-11-16 04:46:19 +00004282 if (match(D, m_SelectCst(m_Specific(Cond), 0, -1)))
Chris Lattner569d78c2008-11-16 04:26:55 +00004283 return SelectInst::Create(Cond, C, B);
Chris Lattnerf1be2852008-11-16 04:46:19 +00004284 if (match(D, m_Not(m_SelectCst(m_Specific(Cond), -1, 0))))
Chris Lattner569d78c2008-11-16 04:26:55 +00004285 return SelectInst::Create(Cond, C, B);
4286 // ((cond?-1:0)&C) | ((cond?0:-1)&D) -> cond ? C : D.
Chris Lattnerf1be2852008-11-16 04:46:19 +00004287 if (match(B, m_SelectCst(m_Specific(Cond), 0, -1)))
Chris Lattner569d78c2008-11-16 04:26:55 +00004288 return SelectInst::Create(Cond, C, D);
Chris Lattnerf1be2852008-11-16 04:46:19 +00004289 if (match(B, m_Not(m_SelectCst(m_Specific(Cond), -1, 0))))
Chris Lattner569d78c2008-11-16 04:26:55 +00004290 return SelectInst::Create(Cond, C, D);
Chris Lattner5f6d9a32008-11-16 04:24:12 +00004291 return 0;
4292}
Chris Lattnerc482a9e2006-06-15 19:07:26 +00004293
Chris Lattnerd397fef2008-11-16 05:20:07 +00004294/// FoldOrOfICmps - Fold (icmp)|(icmp) if possible.
4295Instruction *InstCombiner::FoldOrOfICmps(Instruction &I,
4296 ICmpInst *LHS, ICmpInst *RHS) {
4297 Value *Val, *Val2;
4298 ConstantInt *LHSCst, *RHSCst;
4299 ICmpInst::Predicate LHSCC, RHSCC;
4300
4301 // This only handles icmp of constants: (icmp1 A, C1) | (icmp2 B, C2).
4302 if (!match(LHS, m_ICmp(LHSCC, m_Value(Val), m_ConstantInt(LHSCst))) ||
4303 !match(RHS, m_ICmp(RHSCC, m_Value(Val2), m_ConstantInt(RHSCst))))
4304 return 0;
4305
4306 // From here on, we only handle:
4307 // (icmp1 A, C1) | (icmp2 A, C2) --> something simpler.
4308 if (Val != Val2) return 0;
4309
4310 // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
4311 if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
4312 RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
4313 LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
4314 RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
4315 return 0;
4316
4317 // We can't fold (ugt x, C) | (sgt x, C2).
4318 if (!PredicatesFoldable(LHSCC, RHSCC))
4319 return 0;
4320
4321 // Ensure that the larger constant is on the RHS.
4322 bool ShouldSwap;
4323 if (ICmpInst::isSignedPredicate(LHSCC) ||
4324 (ICmpInst::isEquality(LHSCC) &&
4325 ICmpInst::isSignedPredicate(RHSCC)))
4326 ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
4327 else
4328 ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
4329
4330 if (ShouldSwap) {
4331 std::swap(LHS, RHS);
4332 std::swap(LHSCst, RHSCst);
4333 std::swap(LHSCC, RHSCC);
4334 }
4335
4336 // At this point, we know we have have two icmp instructions
4337 // comparing a value against two constants and or'ing the result
4338 // together. Because of the above check, we know that we only have
4339 // ICMP_EQ, ICMP_NE, ICMP_LT, and ICMP_GT here. We also know (from the
4340 // FoldICmpLogical check above), that the two constants are not
4341 // equal.
4342 assert(LHSCst != RHSCst && "Compares not folded above?");
4343
4344 switch (LHSCC) {
4345 default: assert(0 && "Unknown integer condition code!");
4346 case ICmpInst::ICMP_EQ:
4347 switch (RHSCC) {
4348 default: assert(0 && "Unknown integer condition code!");
4349 case ICmpInst::ICMP_EQ:
4350 if (LHSCst == SubOne(RHSCst)) { // (X == 13 | X == 14) -> X-13 <u 2
4351 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
4352 Instruction *Add = BinaryOperator::CreateAdd(Val, AddCST,
4353 Val->getName()+".off");
4354 InsertNewInstBefore(Add, I);
4355 AddCST = Subtract(AddOne(RHSCst), LHSCst);
4356 return new ICmpInst(ICmpInst::ICMP_ULT, Add, AddCST);
4357 }
4358 break; // (X == 13 | X == 15) -> no change
4359 case ICmpInst::ICMP_UGT: // (X == 13 | X u> 14) -> no change
4360 case ICmpInst::ICMP_SGT: // (X == 13 | X s> 14) -> no change
4361 break;
4362 case ICmpInst::ICMP_NE: // (X == 13 | X != 15) -> X != 15
4363 case ICmpInst::ICMP_ULT: // (X == 13 | X u< 15) -> X u< 15
4364 case ICmpInst::ICMP_SLT: // (X == 13 | X s< 15) -> X s< 15
4365 return ReplaceInstUsesWith(I, RHS);
4366 }
4367 break;
4368 case ICmpInst::ICMP_NE:
4369 switch (RHSCC) {
4370 default: assert(0 && "Unknown integer condition code!");
4371 case ICmpInst::ICMP_EQ: // (X != 13 | X == 15) -> X != 13
4372 case ICmpInst::ICMP_UGT: // (X != 13 | X u> 15) -> X != 13
4373 case ICmpInst::ICMP_SGT: // (X != 13 | X s> 15) -> X != 13
4374 return ReplaceInstUsesWith(I, LHS);
4375 case ICmpInst::ICMP_NE: // (X != 13 | X != 15) -> true
4376 case ICmpInst::ICMP_ULT: // (X != 13 | X u< 15) -> true
4377 case ICmpInst::ICMP_SLT: // (X != 13 | X s< 15) -> true
4378 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4379 }
4380 break;
4381 case ICmpInst::ICMP_ULT:
4382 switch (RHSCC) {
4383 default: assert(0 && "Unknown integer condition code!");
4384 case ICmpInst::ICMP_EQ: // (X u< 13 | X == 14) -> no change
4385 break;
4386 case ICmpInst::ICMP_UGT: // (X u< 13 | X u> 15) -> (X-13) u> 2
4387 // If RHSCst is [us]MAXINT, it is always false. Not handling
4388 // this can cause overflow.
4389 if (RHSCst->isMaxValue(false))
4390 return ReplaceInstUsesWith(I, LHS);
4391 return InsertRangeTest(Val, LHSCst, AddOne(RHSCst), false, false, I);
4392 case ICmpInst::ICMP_SGT: // (X u< 13 | X s> 15) -> no change
4393 break;
4394 case ICmpInst::ICMP_NE: // (X u< 13 | X != 15) -> X != 15
4395 case ICmpInst::ICMP_ULT: // (X u< 13 | X u< 15) -> X u< 15
4396 return ReplaceInstUsesWith(I, RHS);
4397 case ICmpInst::ICMP_SLT: // (X u< 13 | X s< 15) -> no change
4398 break;
4399 }
4400 break;
4401 case ICmpInst::ICMP_SLT:
4402 switch (RHSCC) {
4403 default: assert(0 && "Unknown integer condition code!");
4404 case ICmpInst::ICMP_EQ: // (X s< 13 | X == 14) -> no change
4405 break;
4406 case ICmpInst::ICMP_SGT: // (X s< 13 | X s> 15) -> (X-13) s> 2
4407 // If RHSCst is [us]MAXINT, it is always false. Not handling
4408 // this can cause overflow.
4409 if (RHSCst->isMaxValue(true))
4410 return ReplaceInstUsesWith(I, LHS);
4411 return InsertRangeTest(Val, LHSCst, AddOne(RHSCst), true, false, I);
4412 case ICmpInst::ICMP_UGT: // (X s< 13 | X u> 15) -> no change
4413 break;
4414 case ICmpInst::ICMP_NE: // (X s< 13 | X != 15) -> X != 15
4415 case ICmpInst::ICMP_SLT: // (X s< 13 | X s< 15) -> X s< 15
4416 return ReplaceInstUsesWith(I, RHS);
4417 case ICmpInst::ICMP_ULT: // (X s< 13 | X u< 15) -> no change
4418 break;
4419 }
4420 break;
4421 case ICmpInst::ICMP_UGT:
4422 switch (RHSCC) {
4423 default: assert(0 && "Unknown integer condition code!");
4424 case ICmpInst::ICMP_EQ: // (X u> 13 | X == 15) -> X u> 13
4425 case ICmpInst::ICMP_UGT: // (X u> 13 | X u> 15) -> X u> 13
4426 return ReplaceInstUsesWith(I, LHS);
4427 case ICmpInst::ICMP_SGT: // (X u> 13 | X s> 15) -> no change
4428 break;
4429 case ICmpInst::ICMP_NE: // (X u> 13 | X != 15) -> true
4430 case ICmpInst::ICMP_ULT: // (X u> 13 | X u< 15) -> true
4431 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4432 case ICmpInst::ICMP_SLT: // (X u> 13 | X s< 15) -> no change
4433 break;
4434 }
4435 break;
4436 case ICmpInst::ICMP_SGT:
4437 switch (RHSCC) {
4438 default: assert(0 && "Unknown integer condition code!");
4439 case ICmpInst::ICMP_EQ: // (X s> 13 | X == 15) -> X > 13
4440 case ICmpInst::ICMP_SGT: // (X s> 13 | X s> 15) -> X > 13
4441 return ReplaceInstUsesWith(I, LHS);
4442 case ICmpInst::ICMP_UGT: // (X s> 13 | X u> 15) -> no change
4443 break;
4444 case ICmpInst::ICMP_NE: // (X s> 13 | X != 15) -> true
4445 case ICmpInst::ICMP_SLT: // (X s> 13 | X s< 15) -> true
4446 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4447 case ICmpInst::ICMP_ULT: // (X s> 13 | X u< 15) -> no change
4448 break;
4449 }
4450 break;
4451 }
4452 return 0;
4453}
4454
Chris Lattner113f4f42002-06-25 16:13:24 +00004455Instruction *InstCombiner::visitOr(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00004456 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00004457 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00004458
Chris Lattner3a8248f2007-03-24 23:56:43 +00004459 if (isa<UndefValue>(Op1)) // X | undef -> -1
Chris Lattner37338922007-06-15 06:23:19 +00004460 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattner81a7a232004-10-16 18:11:37 +00004461
Chris Lattner5b2edb12006-02-12 08:02:11 +00004462 // or X, X = X
4463 if (Op0 == Op1)
Chris Lattnere6794492002-08-12 21:17:25 +00004464 return ReplaceInstUsesWith(I, Op0);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00004465
Chris Lattner5b2edb12006-02-12 08:02:11 +00004466 // See if we can simplify any instructions used by the instruction whose sole
4467 // purpose is to compute bits we don't care about.
Chris Lattner3a8248f2007-03-24 23:56:43 +00004468 if (!isa<VectorType>(I.getType())) {
4469 uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
4470 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
4471 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
4472 KnownZero, KnownOne))
4473 return &I;
Chris Lattnerf14e5172007-06-15 05:26:55 +00004474 } else if (isa<ConstantAggregateZero>(Op1)) {
4475 return ReplaceInstUsesWith(I, Op0); // X | <0,0> -> X
4476 } else if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
4477 if (CP->isAllOnesValue()) // X | <-1,-1> -> <-1,-1>
4478 return ReplaceInstUsesWith(I, I.getOperand(1));
Chris Lattner3a8248f2007-03-24 23:56:43 +00004479 }
Chris Lattnerf14e5172007-06-15 05:26:55 +00004480
4481
Chris Lattner5b2edb12006-02-12 08:02:11 +00004482
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00004483 // or X, -1 == -1
Zhou Sheng75b871f2007-01-11 12:24:14 +00004484 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner330628a2006-01-06 17:59:59 +00004485 ConstantInt *C1 = 0; Value *X = 0;
Chris Lattnerd4252a72004-07-30 07:50:03 +00004486 // (X & C1) | C2 --> (X | C2) & (C1|C2)
4487 if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
Gabor Greife1f6e4b2008-05-16 19:29:10 +00004488 Instruction *Or = BinaryOperator::CreateOr(X, RHS);
Chris Lattnerd4252a72004-07-30 07:50:03 +00004489 InsertNewInstBefore(Or, I);
Chris Lattner6e0123b2007-02-11 01:23:03 +00004490 Or->takeName(Op0);
Gabor Greife1f6e4b2008-05-16 19:29:10 +00004491 return BinaryOperator::CreateAnd(Or,
Zhou Sheng9bc8ab12007-04-02 13:45:30 +00004492 ConstantInt::get(RHS->getValue() | C1->getValue()));
Chris Lattnerd4252a72004-07-30 07:50:03 +00004493 }
Chris Lattner8f0d1562003-07-23 18:29:44 +00004494
Chris Lattnerd4252a72004-07-30 07:50:03 +00004495 // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
4496 if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
Gabor Greife1f6e4b2008-05-16 19:29:10 +00004497 Instruction *Or = BinaryOperator::CreateOr(X, RHS);
Chris Lattnerd4252a72004-07-30 07:50:03 +00004498 InsertNewInstBefore(Or, I);
Chris Lattner6e0123b2007-02-11 01:23:03 +00004499 Or->takeName(Op0);
Gabor Greife1f6e4b2008-05-16 19:29:10 +00004500 return BinaryOperator::CreateXor(Or,
Zhou Sheng9bc8ab12007-04-02 13:45:30 +00004501 ConstantInt::get(C1->getValue() & ~RHS->getValue()));
Chris Lattner8f0d1562003-07-23 18:29:44 +00004502 }
Chris Lattner183b3362004-04-09 19:05:30 +00004503
4504 // Try to fold constant and into select arguments.
4505 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner86102b82005-01-01 16:22:27 +00004506 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00004507 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00004508 if (isa<PHINode>(Op0))
4509 if (Instruction *NV = FoldOpIntoPhi(I))
4510 return NV;
Chris Lattner8f0d1562003-07-23 18:29:44 +00004511 }
4512
Chris Lattner330628a2006-01-06 17:59:59 +00004513 Value *A = 0, *B = 0;
4514 ConstantInt *C1 = 0, *C2 = 0;
Chris Lattner4294cec2005-05-07 23:49:08 +00004515
4516 if (match(Op0, m_And(m_Value(A), m_Value(B))))
4517 if (A == Op1 || B == Op1) // (A & ?) | A --> A
4518 return ReplaceInstUsesWith(I, Op1);
4519 if (match(Op1, m_And(m_Value(A), m_Value(B))))
4520 if (A == Op0 || B == Op0) // A | (A & ?) --> A
4521 return ReplaceInstUsesWith(I, Op0);
4522
Chris Lattnerb7845d62006-07-10 20:25:24 +00004523 // (A | B) | C and A | (B | C) -> bswap if possible.
4524 // (A >> B) | (C << D) and (A << B) | (B >> C) -> bswap if possible.
Chris Lattnerc482a9e2006-06-15 19:07:26 +00004525 if (match(Op0, m_Or(m_Value(), m_Value())) ||
Chris Lattnerb7845d62006-07-10 20:25:24 +00004526 match(Op1, m_Or(m_Value(), m_Value())) ||
4527 (match(Op0, m_Shift(m_Value(), m_Value())) &&
4528 match(Op1, m_Shift(m_Value(), m_Value())))) {
Chris Lattnerc482a9e2006-06-15 19:07:26 +00004529 if (Instruction *BSwap = MatchBSwap(I))
4530 return BSwap;
4531 }
4532
Chris Lattnerb62f5082005-05-09 04:58:36 +00004533 // (X^C)|Y -> (X|Y)^C iff Y&C == 0
4534 if (Op0->hasOneUse() && match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
Reid Spencerb722f2b2007-03-22 22:19:58 +00004535 MaskedValueIsZero(Op1, C1->getValue())) {
Gabor Greife1f6e4b2008-05-16 19:29:10 +00004536 Instruction *NOr = BinaryOperator::CreateOr(A, Op1);
Chris Lattner6e0123b2007-02-11 01:23:03 +00004537 InsertNewInstBefore(NOr, I);
4538 NOr->takeName(Op0);
Gabor Greife1f6e4b2008-05-16 19:29:10 +00004539 return BinaryOperator::CreateXor(NOr, C1);
Chris Lattnerb62f5082005-05-09 04:58:36 +00004540 }
4541
4542 // Y|(X^C) -> (X|Y)^C iff Y&C == 0
4543 if (Op1->hasOneUse() && match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
Reid Spencerb722f2b2007-03-22 22:19:58 +00004544 MaskedValueIsZero(Op0, C1->getValue())) {
Gabor Greife1f6e4b2008-05-16 19:29:10 +00004545 Instruction *NOr = BinaryOperator::CreateOr(A, Op0);
Chris Lattner6e0123b2007-02-11 01:23:03 +00004546 InsertNewInstBefore(NOr, I);
4547 NOr->takeName(Op0);
Gabor Greife1f6e4b2008-05-16 19:29:10 +00004548 return BinaryOperator::CreateXor(NOr, C1);
Chris Lattnerb62f5082005-05-09 04:58:36 +00004549 }
4550
Chris Lattner1150df92007-04-08 07:47:01 +00004551 // (A & C)|(B & D)
Chris Lattner09a33a42007-06-19 05:43:49 +00004552 Value *C = 0, *D = 0;
Chris Lattner1150df92007-04-08 07:47:01 +00004553 if (match(Op0, m_And(m_Value(A), m_Value(C))) &&
4554 match(Op1, m_And(m_Value(B), m_Value(D)))) {
Chris Lattner7621a032007-04-08 07:55:22 +00004555 Value *V1 = 0, *V2 = 0, *V3 = 0;
4556 C1 = dyn_cast<ConstantInt>(C);
4557 C2 = dyn_cast<ConstantInt>(D);
4558 if (C1 && C2) { // (A & C1)|(B & C2)
4559 // If we have: ((V + N) & C1) | (V & C2)
4560 // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
4561 // replace with V+N.
4562 if (C1->getValue() == ~C2->getValue()) {
4563 if ((C2->getValue() & (C2->getValue()+1)) == 0 && // C2 == 0+1+
4564 match(A, m_Add(m_Value(V1), m_Value(V2)))) {
4565 // Add commutes, try both ways.
4566 if (V1 == B && MaskedValueIsZero(V2, C2->getValue()))
4567 return ReplaceInstUsesWith(I, A);
4568 if (V2 == B && MaskedValueIsZero(V1, C2->getValue()))
4569 return ReplaceInstUsesWith(I, A);
4570 }
4571 // Or commutes, try both ways.
4572 if ((C1->getValue() & (C1->getValue()+1)) == 0 &&
4573 match(B, m_Add(m_Value(V1), m_Value(V2)))) {
4574 // Add commutes, try both ways.
4575 if (V1 == A && MaskedValueIsZero(V2, C1->getValue()))
4576 return ReplaceInstUsesWith(I, B);
4577 if (V2 == A && MaskedValueIsZero(V1, C1->getValue()))
4578 return ReplaceInstUsesWith(I, B);
4579 }
4580 }
Chris Lattnerc8d37882007-04-08 08:01:49 +00004581 V1 = 0; V2 = 0; V3 = 0;
Chris Lattner7621a032007-04-08 07:55:22 +00004582 }
4583
Chris Lattner1150df92007-04-08 07:47:01 +00004584 // Check to see if we have any common things being and'ed. If so, find the
4585 // terms for V1 & (V2|V3).
Chris Lattner1150df92007-04-08 07:47:01 +00004586 if (isOnlyUse(Op0) || isOnlyUse(Op1)) {
4587 if (A == B) // (A & C)|(A & D) == A & (C|D)
4588 V1 = A, V2 = C, V3 = D;
4589 else if (A == D) // (A & C)|(B & A) == A & (B|C)
4590 V1 = A, V2 = B, V3 = C;
4591 else if (C == B) // (A & C)|(C & D) == C & (A|D)
4592 V1 = C, V2 = A, V3 = D;
4593 else if (C == D) // (A & C)|(B & C) == C & (A|B)
4594 V1 = C, V2 = A, V3 = B;
4595
4596 if (V1) {
4597 Value *Or =
Gabor Greife1f6e4b2008-05-16 19:29:10 +00004598 InsertNewInstBefore(BinaryOperator::CreateOr(V2, V3, "tmp"), I);
4599 return BinaryOperator::CreateAnd(V1, Or);
Chris Lattner01f56c62005-09-18 06:02:59 +00004600 }
Chris Lattner1150df92007-04-08 07:47:01 +00004601 }
Dan Gohman2c34c132008-10-28 22:38:57 +00004602
Dan Gohman13cbcf1c182008-10-30 20:40:10 +00004603 // (A & (C0?-1:0)) | (B & ~(C0?-1:0)) -> C0 ? A : B, and commuted variants
Chris Lattner5f6d9a32008-11-16 04:24:12 +00004604 if (Instruction *Match = MatchSelectFromAndOr(A, B, C, D))
4605 return Match;
4606 if (Instruction *Match = MatchSelectFromAndOr(B, A, D, C))
4607 return Match;
4608 if (Instruction *Match = MatchSelectFromAndOr(C, B, A, D))
4609 return Match;
4610 if (Instruction *Match = MatchSelectFromAndOr(D, A, B, C))
4611 return Match;
Bill Wendlingde89bc22008-11-30 13:52:49 +00004612
4613 V1 = V2 = 0;
4614
4615 // ((A&~B)|(~A&B)) -> A^B
4616 if ((match(C, m_Not(m_Value(V1))) &&
4617 match(B, m_Not(m_Value(V2)))))
4618 if (V1 == D && V2 == A)
4619 return BinaryOperator::CreateXor(V1, V2);
4620 // ((~B&A)|(~A&B)) -> A^B
4621 if ((match(A, m_Not(m_Value(V1))) &&
4622 match(B, m_Not(m_Value(V2)))))
4623 if (V1 == D && V2 == C)
4624 return BinaryOperator::CreateXor(V1, V2);
4625 // ((A&~B)|(B&~A)) -> A^B
4626 if ((match(C, m_Not(m_Value(V1))) &&
4627 match(D, m_Not(m_Value(V2)))))
4628 if (V1 == B && V2 == A)
4629 return BinaryOperator::CreateXor(V1, V2);
4630 // ((~B&A)|(B&~A)) -> A^B
4631 if ((match(A, m_Not(m_Value(V1))) &&
4632 match(D, m_Not(m_Value(V2)))))
4633 if (V1 == B && V2 == C)
4634 return BinaryOperator::CreateXor(V1, V2);
Chris Lattner15212982005-09-18 03:42:07 +00004635 }
Chris Lattnerf05d69a2006-11-14 07:46:50 +00004636
4637 // (X >> Z) | (Y >> Z) -> (X|Y) >> Z for all shifts.
Reid Spencer2341c222007-02-02 02:16:23 +00004638 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4639 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4640 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
Chris Lattnerf05d69a2006-11-14 07:46:50 +00004641 SI0->getOperand(1) == SI1->getOperand(1) &&
4642 (SI0->hasOneUse() || SI1->hasOneUse())) {
4643 Instruction *NewOp =
Gabor Greife1f6e4b2008-05-16 19:29:10 +00004644 InsertNewInstBefore(BinaryOperator::CreateOr(SI0->getOperand(0),
Chris Lattnerf05d69a2006-11-14 07:46:50 +00004645 SI1->getOperand(0),
4646 SI0->getName()), I);
Gabor Greife1f6e4b2008-05-16 19:29:10 +00004647 return BinaryOperator::Create(SI1->getOpcode(), NewOp,
Reid Spencer2341c222007-02-02 02:16:23 +00004648 SI1->getOperand(1));
Chris Lattnerf05d69a2006-11-14 07:46:50 +00004649 }
4650 }
Chris Lattner812aab72003-08-12 19:11:07 +00004651
Chris Lattnerd4252a72004-07-30 07:50:03 +00004652 if (match(Op0, m_Not(m_Value(A)))) { // ~A | Op1
4653 if (A == Op1) // ~A | A == -1
Chris Lattner37338922007-06-15 06:23:19 +00004654 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnerd4252a72004-07-30 07:50:03 +00004655 } else {
4656 A = 0;
4657 }
Chris Lattner4294cec2005-05-07 23:49:08 +00004658 // Note, A is still live here!
Chris Lattnerd4252a72004-07-30 07:50:03 +00004659 if (match(Op1, m_Not(m_Value(B)))) { // Op0 | ~B
4660 if (Op0 == B)
Chris Lattner37338922007-06-15 06:23:19 +00004661 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattner3e327a42003-03-10 23:13:59 +00004662
Misha Brukman9c003d82004-07-30 12:50:08 +00004663 // (~A | ~B) == (~(A & B)) - De Morgan's Law
Chris Lattnerd4252a72004-07-30 07:50:03 +00004664 if (A && isOnlyUse(Op0) && isOnlyUse(Op1)) {
Gabor Greife1f6e4b2008-05-16 19:29:10 +00004665 Value *And = InsertNewInstBefore(BinaryOperator::CreateAnd(A, B,
Chris Lattnerd4252a72004-07-30 07:50:03 +00004666 I.getName()+".demorgan"), I);
Gabor Greife1f6e4b2008-05-16 19:29:10 +00004667 return BinaryOperator::CreateNot(And);
Chris Lattnerd4252a72004-07-30 07:50:03 +00004668 }
Chris Lattner3e327a42003-03-10 23:13:59 +00004669 }
Chris Lattner3082c5a2003-02-18 19:28:33 +00004670
Reid Spencer266e42b2006-12-23 06:05:41 +00004671 // (icmp1 A, B) | (icmp2 A, B) --> (icmp3 A, B)
4672 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1))) {
4673 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Chris Lattner3ac7c262003-08-13 20:16:26 +00004674 return R;
4675
Chris Lattnerd397fef2008-11-16 05:20:07 +00004676 if (ICmpInst *LHS = dyn_cast<ICmpInst>(I.getOperand(0)))
4677 if (Instruction *Res = FoldOrOfICmps(I, LHS, RHS))
4678 return Res;
Chris Lattnerdcf756e2004-09-28 22:33:08 +00004679 }
Chris Lattner3af10532006-05-05 06:39:07 +00004680
4681 // fold (or (cast A), (cast B)) -> (cast (or A, B))
Chris Lattnerc62877e2007-10-24 05:38:08 +00004682 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
Chris Lattner3af10532006-05-05 06:39:07 +00004683 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
Reid Spencer799b5bf2006-12-13 08:27:15 +00004684 if (Op0C->getOpcode() == Op1C->getOpcode()) {// same cast kind ?
Evan Chengc3cf9f82008-03-24 00:21:34 +00004685 if (!isa<ICmpInst>(Op0C->getOperand(0)) ||
4686 !isa<ICmpInst>(Op1C->getOperand(0))) {
4687 const Type *SrcTy = Op0C->getOperand(0)->getType();
4688 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
4689 // Only do this if the casts both really cause code to be
4690 // generated.
4691 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
4692 I.getType(), TD) &&
4693 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
4694 I.getType(), TD)) {
Gabor Greife1f6e4b2008-05-16 19:29:10 +00004695 Instruction *NewOp = BinaryOperator::CreateOr(Op0C->getOperand(0),
Evan Chengc3cf9f82008-03-24 00:21:34 +00004696 Op1C->getOperand(0),
4697 I.getName());
4698 InsertNewInstBefore(NewOp, I);
Gabor Greife1f6e4b2008-05-16 19:29:10 +00004699 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
Evan Chengc3cf9f82008-03-24 00:21:34 +00004700 }
Reid Spencer799b5bf2006-12-13 08:27:15 +00004701 }
Chris Lattner3af10532006-05-05 06:39:07 +00004702 }
Chris Lattnerc62877e2007-10-24 05:38:08 +00004703 }
4704
4705
4706 // (fcmp uno x, c) | (fcmp uno y, c) -> (fcmp uno x, y)
4707 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
4708 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1))) {
4709 if (LHS->getPredicate() == FCmpInst::FCMP_UNO &&
Chris Lattnerc6125712008-02-29 06:09:11 +00004710 RHS->getPredicate() == FCmpInst::FCMP_UNO &&
Evan Chengd885f6e2008-10-14 18:44:08 +00004711 LHS->getOperand(0)->getType() == RHS->getOperand(0)->getType()) {
Chris Lattnerc62877e2007-10-24 05:38:08 +00004712 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
4713 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
4714 // If either of the constants are nans, then the whole thing returns
4715 // true.
Chris Lattner55b83022007-10-24 18:54:45 +00004716 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
Chris Lattnerc62877e2007-10-24 05:38:08 +00004717 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4718
4719 // Otherwise, no need to compare the two constants, compare the
4720 // rest.
4721 return new FCmpInst(FCmpInst::FCMP_UNO, LHS->getOperand(0),
4722 RHS->getOperand(0));
4723 }
Evan Chengd885f6e2008-10-14 18:44:08 +00004724 } else {
4725 Value *Op0LHS, *Op0RHS, *Op1LHS, *Op1RHS;
4726 FCmpInst::Predicate Op0CC, Op1CC;
4727 if (match(Op0, m_FCmp(Op0CC, m_Value(Op0LHS), m_Value(Op0RHS))) &&
4728 match(Op1, m_FCmp(Op1CC, m_Value(Op1LHS), m_Value(Op1RHS)))) {
4729 if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
4730 // Swap RHS operands to match LHS.
4731 Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
4732 std::swap(Op1LHS, Op1RHS);
4733 }
4734 if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
4735 // Simplify (fcmp cc0 x, y) | (fcmp cc1 x, y).
4736 if (Op0CC == Op1CC)
4737 return new FCmpInst((FCmpInst::Predicate)Op0CC, Op0LHS, Op0RHS);
4738 else if (Op0CC == FCmpInst::FCMP_TRUE ||
4739 Op1CC == FCmpInst::FCMP_TRUE)
4740 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4741 else if (Op0CC == FCmpInst::FCMP_FALSE)
4742 return ReplaceInstUsesWith(I, Op1);
4743 else if (Op1CC == FCmpInst::FCMP_FALSE)
4744 return ReplaceInstUsesWith(I, Op0);
4745 bool Op0Ordered;
4746 bool Op1Ordered;
4747 unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
4748 unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
4749 if (Op0Ordered == Op1Ordered) {
4750 // If both are ordered or unordered, return a new fcmp with
4751 // or'ed predicates.
4752 Value *RV = getFCmpValue(Op0Ordered, Op0Pred|Op1Pred,
4753 Op0LHS, Op0RHS);
4754 if (Instruction *I = dyn_cast<Instruction>(RV))
4755 return I;
4756 // Otherwise, it's a constant boolean value...
4757 return ReplaceInstUsesWith(I, RV);
4758 }
4759 }
4760 }
4761 }
Chris Lattnerc62877e2007-10-24 05:38:08 +00004762 }
4763 }
Chris Lattner15212982005-09-18 03:42:07 +00004764
Chris Lattner113f4f42002-06-25 16:13:24 +00004765 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00004766}
4767
Dan Gohmand78c4002008-05-13 00:00:25 +00004768namespace {
4769
Chris Lattnerc2076352004-02-16 01:20:27 +00004770// XorSelf - Implements: X ^ X --> 0
4771struct XorSelf {
4772 Value *RHS;
4773 XorSelf(Value *rhs) : RHS(rhs) {}
4774 bool shouldApply(Value *LHS) const { return LHS == RHS; }
4775 Instruction *apply(BinaryOperator &Xor) const {
4776 return &Xor;
4777 }
4778};
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00004779
Dan Gohmand78c4002008-05-13 00:00:25 +00004780}
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00004781
Chris Lattner113f4f42002-06-25 16:13:24 +00004782Instruction *InstCombiner::visitXor(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00004783 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00004784 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00004785
Evan Cheng2b72c052008-03-25 20:07:13 +00004786 if (isa<UndefValue>(Op1)) {
4787 if (isa<UndefValue>(Op0))
4788 // Handle undef ^ undef -> 0 special case. This is a common
4789 // idiom (misuse).
4790 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner81a7a232004-10-16 18:11:37 +00004791 return ReplaceInstUsesWith(I, Op1); // X ^ undef -> undef
Evan Cheng2b72c052008-03-25 20:07:13 +00004792 }
Chris Lattner81a7a232004-10-16 18:11:37 +00004793
Chris Lattnerc2076352004-02-16 01:20:27 +00004794 // xor X, X = 0, even if X is nested in a sequence of Xor's.
4795 if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1))) {
Chris Lattnerf0da7972007-08-05 08:47:58 +00004796 assert(Result == &I && "AssociativeOpt didn't work?"); Result=Result;
Chris Lattnere6794492002-08-12 21:17:25 +00004797 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerc2076352004-02-16 01:20:27 +00004798 }
Chris Lattner5b2edb12006-02-12 08:02:11 +00004799
4800 // See if we can simplify any instructions used by the instruction whose sole
4801 // purpose is to compute bits we don't care about.
Reid Spencerb722f2b2007-03-22 22:19:58 +00004802 if (!isa<VectorType>(I.getType())) {
4803 uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
4804 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
4805 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
4806 KnownZero, KnownOne))
4807 return &I;
Chris Lattnerf14e5172007-06-15 05:26:55 +00004808 } else if (isa<ConstantAggregateZero>(Op1)) {
4809 return ReplaceInstUsesWith(I, Op0); // X ^ <0,0> -> X
Reid Spencerb722f2b2007-03-22 22:19:58 +00004810 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00004811
Chris Lattner37338922007-06-15 06:23:19 +00004812 // Is this a ~ operation?
4813 if (Value *NotOp = dyn_castNotVal(&I)) {
4814 // ~(~X & Y) --> (X | ~Y) - De Morgan's Law
4815 // ~(~X | Y) === (X & ~Y) - De Morgan's Law
4816 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(NotOp)) {
4817 if (Op0I->getOpcode() == Instruction::And ||
4818 Op0I->getOpcode() == Instruction::Or) {
4819 if (dyn_castNotVal(Op0I->getOperand(1))) Op0I->swapOperands();
4820 if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
4821 Instruction *NotY =
Gabor Greife1f6e4b2008-05-16 19:29:10 +00004822 BinaryOperator::CreateNot(Op0I->getOperand(1),
Chris Lattner37338922007-06-15 06:23:19 +00004823 Op0I->getOperand(1)->getName()+".not");
4824 InsertNewInstBefore(NotY, I);
4825 if (Op0I->getOpcode() == Instruction::And)
Gabor Greife1f6e4b2008-05-16 19:29:10 +00004826 return BinaryOperator::CreateOr(Op0NotVal, NotY);
Chris Lattner37338922007-06-15 06:23:19 +00004827 else
Gabor Greife1f6e4b2008-05-16 19:29:10 +00004828 return BinaryOperator::CreateAnd(Op0NotVal, NotY);
Chris Lattner37338922007-06-15 06:23:19 +00004829 }
4830 }
4831 }
4832 }
4833
4834
Zhou Sheng75b871f2007-01-11 12:24:14 +00004835 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Nick Lewycky80520192007-08-06 20:04:16 +00004836 // xor (cmp A, B), true = not (cmp A, B) = !cmp A, B
4837 if (RHS == ConstantInt::getTrue() && Op0->hasOneUse()) {
4838 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Op0))
Reid Spencer266e42b2006-12-23 06:05:41 +00004839 return new ICmpInst(ICI->getInversePredicate(),
4840 ICI->getOperand(0), ICI->getOperand(1));
Chris Lattnere5806662003-11-04 23:50:51 +00004841
Nick Lewycky80520192007-08-06 20:04:16 +00004842 if (FCmpInst *FCI = dyn_cast<FCmpInst>(Op0))
4843 return new FCmpInst(FCI->getInversePredicate(),
4844 FCI->getOperand(0), FCI->getOperand(1));
4845 }
4846
Nick Lewycky035fe6f2008-05-31 19:01:33 +00004847 // fold (xor(zext(cmp)), 1) and (xor(sext(cmp)), -1) to ext(!cmp).
4848 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
4849 if (CmpInst *CI = dyn_cast<CmpInst>(Op0C->getOperand(0))) {
4850 if (CI->hasOneUse() && Op0C->hasOneUse()) {
4851 Instruction::CastOps Opcode = Op0C->getOpcode();
4852 if (Opcode == Instruction::ZExt || Opcode == Instruction::SExt) {
4853 if (RHS == ConstantExpr::getCast(Opcode, ConstantInt::getTrue(),
4854 Op0C->getDestTy())) {
4855 Instruction *NewCI = InsertNewInstBefore(CmpInst::Create(
4856 CI->getOpcode(), CI->getInversePredicate(),
4857 CI->getOperand(0), CI->getOperand(1)), I);
4858 NewCI->takeName(CI);
4859 return CastInst::Create(Opcode, NewCI, Op0C->getType());
4860 }
4861 }
4862 }
4863 }
4864 }
4865
Reid Spencer266e42b2006-12-23 06:05:41 +00004866 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
Chris Lattner8f2f5982003-11-05 01:06:05 +00004867 // ~(c-X) == X-c-1 == X+(-c-1)
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00004868 if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
4869 if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00004870 Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
4871 Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00004872 ConstantInt::get(I.getType(), 1));
Gabor Greife1f6e4b2008-05-16 19:29:10 +00004873 return BinaryOperator::CreateAdd(Op0I->getOperand(1), ConstantRHS);
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00004874 }
Chris Lattnerb24acc72007-04-02 05:36:22 +00004875
Anton Korobeynikov1bfd1212008-02-20 11:26:25 +00004876 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
Chris Lattner5b2edb12006-02-12 08:02:11 +00004877 if (Op0I->getOpcode() == Instruction::Add) {
Chris Lattner0f68fa62003-11-04 23:37:10 +00004878 // ~(X-c) --> (-c-1)-X
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00004879 if (RHS->isAllOnesValue()) {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00004880 Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
Gabor Greife1f6e4b2008-05-16 19:29:10 +00004881 return BinaryOperator::CreateSub(
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00004882 ConstantExpr::getSub(NegOp0CI,
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00004883 ConstantInt::get(I.getType(), 1)),
Chris Lattner0f68fa62003-11-04 23:37:10 +00004884 Op0I->getOperand(0));
Chris Lattner50490d52007-04-02 05:42:22 +00004885 } else if (RHS->getValue().isSignBit()) {
Chris Lattnerb24acc72007-04-02 05:36:22 +00004886 // (X + C) ^ signbit -> (X + C + signbit)
4887 Constant *C = ConstantInt::get(RHS->getValue() + Op0CI->getValue());
Gabor Greife1f6e4b2008-05-16 19:29:10 +00004888 return BinaryOperator::CreateAdd(Op0I->getOperand(0), C);
Chris Lattner9d5aace2007-04-02 05:48:58 +00004889
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00004890 }
Chris Lattnerf78df7c2006-02-26 19:57:54 +00004891 } else if (Op0I->getOpcode() == Instruction::Or) {
4892 // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
Reid Spencerb722f2b2007-03-22 22:19:58 +00004893 if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getValue())) {
Chris Lattnerf78df7c2006-02-26 19:57:54 +00004894 Constant *NewRHS = ConstantExpr::getOr(Op0CI, RHS);
4895 // Anything in both C1 and C2 is known to be zero, remove it from
4896 // NewRHS.
Zhou Sheng9bc8ab12007-04-02 13:45:30 +00004897 Constant *CommonBits = And(Op0CI, RHS);
Chris Lattnerf78df7c2006-02-26 19:57:54 +00004898 NewRHS = ConstantExpr::getAnd(NewRHS,
4899 ConstantExpr::getNot(CommonBits));
Chris Lattnerb15e2b12007-03-02 21:28:56 +00004900 AddToWorkList(Op0I);
Chris Lattnerf78df7c2006-02-26 19:57:54 +00004901 I.setOperand(0, Op0I->getOperand(0));
4902 I.setOperand(1, NewRHS);
4903 return &I;
4904 }
Chris Lattner97638592003-07-23 21:37:07 +00004905 }
Anton Korobeynikov1bfd1212008-02-20 11:26:25 +00004906 }
Chris Lattnerb8d6e402002-08-20 18:24:26 +00004907 }
Chris Lattner183b3362004-04-09 19:05:30 +00004908
4909 // Try to fold constant and into select arguments.
4910 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner86102b82005-01-01 16:22:27 +00004911 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00004912 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00004913 if (isa<PHINode>(Op0))
4914 if (Instruction *NV = FoldOpIntoPhi(I))
4915 return NV;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00004916 }
4917
Chris Lattnerbb74e222003-03-10 23:06:50 +00004918 if (Value *X = dyn_castNotVal(Op0)) // ~A ^ A == -1
Chris Lattner3082c5a2003-02-18 19:28:33 +00004919 if (X == Op1)
Chris Lattner37338922007-06-15 06:23:19 +00004920 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattner3082c5a2003-02-18 19:28:33 +00004921
Chris Lattnerbb74e222003-03-10 23:06:50 +00004922 if (Value *X = dyn_castNotVal(Op1)) // A ^ ~A == -1
Chris Lattner3082c5a2003-02-18 19:28:33 +00004923 if (X == Op0)
Chris Lattner37338922007-06-15 06:23:19 +00004924 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattner3082c5a2003-02-18 19:28:33 +00004925
Chris Lattner07418422007-03-18 22:51:34 +00004926
4927 BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1);
4928 if (Op1I) {
4929 Value *A, *B;
4930 if (match(Op1I, m_Or(m_Value(A), m_Value(B)))) {
4931 if (A == Op0) { // B^(B|A) == (A|B)^B
Chris Lattnerdcd07922006-04-01 08:03:55 +00004932 Op1I->swapOperands();
Chris Lattner1bbb7b62003-03-10 18:24:17 +00004933 I.swapOperands();
4934 std::swap(Op0, Op1);
Chris Lattner07418422007-03-18 22:51:34 +00004935 } else if (B == Op0) { // B^(A|B) == (A|B)^B
Chris Lattnerdcd07922006-04-01 08:03:55 +00004936 I.swapOperands(); // Simplified below.
Chris Lattner1bbb7b62003-03-10 18:24:17 +00004937 std::swap(Op0, Op1);
Misha Brukmanb1c93172005-04-21 23:48:37 +00004938 }
Chris Lattner44152742008-11-16 05:38:51 +00004939 } else if (match(Op1I, m_Xor(m_Specific(Op0), m_Value(B)))) {
4940 return ReplaceInstUsesWith(I, B); // A^(A^B) == B
4941 } else if (match(Op1I, m_Xor(m_Value(A), m_Specific(Op0)))) {
4942 return ReplaceInstUsesWith(I, A); // A^(B^A) == B
Chris Lattner07418422007-03-18 22:51:34 +00004943 } else if (match(Op1I, m_And(m_Value(A), m_Value(B))) && Op1I->hasOneUse()){
Chris Lattner04277992007-04-01 05:36:37 +00004944 if (A == Op0) { // A^(A&B) -> A^(B&A)
Chris Lattnerdcd07922006-04-01 08:03:55 +00004945 Op1I->swapOperands();
Chris Lattner04277992007-04-01 05:36:37 +00004946 std::swap(A, B);
4947 }
Chris Lattner07418422007-03-18 22:51:34 +00004948 if (B == Op0) { // A^(B&A) -> (B&A)^A
Chris Lattnerdcd07922006-04-01 08:03:55 +00004949 I.swapOperands(); // Simplified below.
4950 std::swap(Op0, Op1);
4951 }
Chris Lattnerb36d9082004-02-16 03:54:20 +00004952 }
Chris Lattner07418422007-03-18 22:51:34 +00004953 }
4954
4955 BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0);
4956 if (Op0I) {
4957 Value *A, *B;
4958 if (match(Op0I, m_Or(m_Value(A), m_Value(B))) && Op0I->hasOneUse()) {
4959 if (A == Op1) // (B|A)^B == (A|B)^B
4960 std::swap(A, B);
4961 if (B == Op1) { // (A|B)^B == A & ~B
4962 Instruction *NotB =
Gabor Greife1f6e4b2008-05-16 19:29:10 +00004963 InsertNewInstBefore(BinaryOperator::CreateNot(Op1, "tmp"), I);
4964 return BinaryOperator::CreateAnd(A, NotB);
Chris Lattner1bbb7b62003-03-10 18:24:17 +00004965 }
Chris Lattner44152742008-11-16 05:38:51 +00004966 } else if (match(Op0I, m_Xor(m_Specific(Op1), m_Value(B)))) {
4967 return ReplaceInstUsesWith(I, B); // (A^B)^A == B
4968 } else if (match(Op0I, m_Xor(m_Value(A), m_Specific(Op1)))) {
4969 return ReplaceInstUsesWith(I, A); // (B^A)^A == B
Chris Lattner07418422007-03-18 22:51:34 +00004970 } else if (match(Op0I, m_And(m_Value(A), m_Value(B))) && Op0I->hasOneUse()){
4971 if (A == Op1) // (A&B)^A -> (B&A)^A
4972 std::swap(A, B);
4973 if (B == Op1 && // (B&A)^A == ~B & A
Chris Lattner6cf49142006-04-01 22:05:01 +00004974 !isa<ConstantInt>(Op1)) { // Canonical form is (B&C)^C
Chris Lattner07418422007-03-18 22:51:34 +00004975 Instruction *N =
Gabor Greife1f6e4b2008-05-16 19:29:10 +00004976 InsertNewInstBefore(BinaryOperator::CreateNot(A, "tmp"), I);
4977 return BinaryOperator::CreateAnd(N, Op1);
Chris Lattnerdcd07922006-04-01 08:03:55 +00004978 }
Chris Lattner1bbb7b62003-03-10 18:24:17 +00004979 }
Chris Lattner07418422007-03-18 22:51:34 +00004980 }
4981
4982 // (X >> Z) ^ (Y >> Z) -> (X^Y) >> Z for all shifts.
4983 if (Op0I && Op1I && Op0I->isShift() &&
4984 Op0I->getOpcode() == Op1I->getOpcode() &&
4985 Op0I->getOperand(1) == Op1I->getOperand(1) &&
4986 (Op1I->hasOneUse() || Op1I->hasOneUse())) {
4987 Instruction *NewOp =
Gabor Greife1f6e4b2008-05-16 19:29:10 +00004988 InsertNewInstBefore(BinaryOperator::CreateXor(Op0I->getOperand(0),
Chris Lattner07418422007-03-18 22:51:34 +00004989 Op1I->getOperand(0),
4990 Op0I->getName()), I);
Gabor Greife1f6e4b2008-05-16 19:29:10 +00004991 return BinaryOperator::Create(Op1I->getOpcode(), NewOp,
Chris Lattner07418422007-03-18 22:51:34 +00004992 Op1I->getOperand(1));
4993 }
4994
4995 if (Op0I && Op1I) {
4996 Value *A, *B, *C, *D;
4997 // (A & B)^(A | B) -> A ^ B
4998 if (match(Op0I, m_And(m_Value(A), m_Value(B))) &&
4999 match(Op1I, m_Or(m_Value(C), m_Value(D)))) {
5000 if ((A == C && B == D) || (A == D && B == C))
Gabor Greife1f6e4b2008-05-16 19:29:10 +00005001 return BinaryOperator::CreateXor(A, B);
Chris Lattner07418422007-03-18 22:51:34 +00005002 }
5003 // (A | B)^(A & B) -> A ^ B
5004 if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
5005 match(Op1I, m_And(m_Value(C), m_Value(D)))) {
5006 if ((A == C && B == D) || (A == D && B == C))
Gabor Greife1f6e4b2008-05-16 19:29:10 +00005007 return BinaryOperator::CreateXor(A, B);
Chris Lattner07418422007-03-18 22:51:34 +00005008 }
5009
5010 // (A & B)^(C & D)
5011 if ((Op0I->hasOneUse() || Op1I->hasOneUse()) &&
5012 match(Op0I, m_And(m_Value(A), m_Value(B))) &&
5013 match(Op1I, m_And(m_Value(C), m_Value(D)))) {
5014 // (X & Y)^(X & Y) -> (Y^Z) & X
5015 Value *X = 0, *Y = 0, *Z = 0;
5016 if (A == C)
5017 X = A, Y = B, Z = D;
5018 else if (A == D)
5019 X = A, Y = B, Z = C;
5020 else if (B == C)
5021 X = B, Y = A, Z = D;
5022 else if (B == D)
5023 X = B, Y = A, Z = C;
5024
5025 if (X) {
5026 Instruction *NewOp =
Gabor Greife1f6e4b2008-05-16 19:29:10 +00005027 InsertNewInstBefore(BinaryOperator::CreateXor(Y, Z, Op0->getName()), I);
5028 return BinaryOperator::CreateAnd(NewOp, X);
Chris Lattner07418422007-03-18 22:51:34 +00005029 }
5030 }
5031 }
5032
Reid Spencer266e42b2006-12-23 06:05:41 +00005033 // (icmp1 A, B) ^ (icmp2 A, B) --> (icmp3 A, B)
5034 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
5035 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Chris Lattner3ac7c262003-08-13 20:16:26 +00005036 return R;
5037
Chris Lattner3af10532006-05-05 06:39:07 +00005038 // fold (xor (cast A), (cast B)) -> (cast (xor A, B))
Chris Lattnerc62877e2007-10-24 05:38:08 +00005039 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
Chris Lattner3af10532006-05-05 06:39:07 +00005040 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
Reid Spencer799b5bf2006-12-13 08:27:15 +00005041 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind?
5042 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattner03c49532007-01-15 02:27:26 +00005043 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
Reid Spencer799b5bf2006-12-13 08:27:15 +00005044 // Only do this if the casts both really cause code to be generated.
Reid Spencer266e42b2006-12-23 06:05:41 +00005045 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
5046 I.getType(), TD) &&
5047 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
5048 I.getType(), TD)) {
Gabor Greife1f6e4b2008-05-16 19:29:10 +00005049 Instruction *NewOp = BinaryOperator::CreateXor(Op0C->getOperand(0),
Reid Spencer799b5bf2006-12-13 08:27:15 +00005050 Op1C->getOperand(0),
5051 I.getName());
5052 InsertNewInstBefore(NewOp, I);
Gabor Greife1f6e4b2008-05-16 19:29:10 +00005053 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
Reid Spencer799b5bf2006-12-13 08:27:15 +00005054 }
Chris Lattner3af10532006-05-05 06:39:07 +00005055 }
Chris Lattnerc62877e2007-10-24 05:38:08 +00005056 }
Nick Lewycky035fe6f2008-05-31 19:01:33 +00005057
Chris Lattner113f4f42002-06-25 16:13:24 +00005058 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00005059}
5060
Chris Lattner6862fbd2004-09-29 17:40:11 +00005061/// AddWithOverflow - Compute Result = In1+In2, returning true if the result
5062/// overflowed for this type.
5063static bool AddWithOverflow(ConstantInt *&Result, ConstantInt *In1,
Reid Spencerf4071162007-03-21 23:19:50 +00005064 ConstantInt *In2, bool IsSigned = false) {
Zhou Sheng9bc8ab12007-04-02 13:45:30 +00005065 Result = cast<ConstantInt>(Add(In1, In2));
Chris Lattner6862fbd2004-09-29 17:40:11 +00005066
Reid Spencerf4071162007-03-21 23:19:50 +00005067 if (IsSigned)
5068 if (In2->getValue().isNegative())
5069 return Result->getValue().sgt(In1->getValue());
5070 else
5071 return Result->getValue().slt(In1->getValue());
5072 else
5073 return Result->getValue().ult(In1->getValue());
Chris Lattner6862fbd2004-09-29 17:40:11 +00005074}
5075
Dan Gohmanc1ae0162008-09-10 23:30:57 +00005076/// SubWithOverflow - Compute Result = In1-In2, returning true if the result
5077/// overflowed for this type.
5078static bool SubWithOverflow(ConstantInt *&Result, ConstantInt *In1,
5079 ConstantInt *In2, bool IsSigned = false) {
Dan Gohman9b9d5472008-09-11 18:53:02 +00005080 Result = cast<ConstantInt>(Subtract(In1, In2));
Dan Gohmanc1ae0162008-09-10 23:30:57 +00005081
5082 if (IsSigned)
5083 if (In2->getValue().isNegative())
5084 return Result->getValue().slt(In1->getValue());
5085 else
5086 return Result->getValue().sgt(In1->getValue());
5087 else
5088 return Result->getValue().ugt(In1->getValue());
5089}
5090
Chris Lattner0798af32005-01-13 20:14:25 +00005091/// EmitGEPOffset - Given a getelementptr instruction/constantexpr, emit the
5092/// code necessary to compute the offset from the base pointer (without adding
5093/// in the base pointer). Return the result as a signed integer of intptr size.
5094static Value *EmitGEPOffset(User *GEP, Instruction &I, InstCombiner &IC) {
5095 TargetData &TD = IC.getTargetData();
5096 gep_type_iterator GTI = gep_type_begin(GEP);
Reid Spencer266e42b2006-12-23 06:05:41 +00005097 const Type *IntPtrTy = TD.getIntPtrType();
5098 Value *Result = Constant::getNullValue(IntPtrTy);
Chris Lattner0798af32005-01-13 20:14:25 +00005099
5100 // Build a mask for high order bits.
Chris Lattnerc3a43932008-04-22 02:53:33 +00005101 unsigned IntPtrWidth = TD.getPointerSizeInBits();
Chris Lattner6e880872007-04-28 04:52:43 +00005102 uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
Chris Lattner0798af32005-01-13 20:14:25 +00005103
Gabor Greiff6d8e772008-06-12 21:37:33 +00005104 for (User::op_iterator i = GEP->op_begin() + 1, e = GEP->op_end(); i != e;
5105 ++i, ++GTI) {
5106 Value *Op = *i;
Duncan Sands44b87212007-11-01 20:53:16 +00005107 uint64_t Size = TD.getABITypeSize(GTI.getIndexedType()) & PtrSizeMask;
Chris Lattner6e880872007-04-28 04:52:43 +00005108 if (ConstantInt *OpC = dyn_cast<ConstantInt>(Op)) {
5109 if (OpC->isZero()) continue;
5110
5111 // Handle a struct index, which adds its field offset to the pointer.
5112 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5113 Size = TD.getStructLayout(STy)->getElementOffset(OpC->getZExtValue());
5114
5115 if (ConstantInt *RC = dyn_cast<ConstantInt>(Result))
5116 Result = ConstantInt::get(RC->getValue() + APInt(IntPtrWidth, Size));
Chris Lattneracbf6a42007-04-28 00:57:34 +00005117 else
Chris Lattner6e880872007-04-28 04:52:43 +00005118 Result = IC.InsertNewInstBefore(
Gabor Greife1f6e4b2008-05-16 19:29:10 +00005119 BinaryOperator::CreateAdd(Result,
Chris Lattner6e880872007-04-28 04:52:43 +00005120 ConstantInt::get(IntPtrTy, Size),
5121 GEP->getName()+".offs"), I);
5122 continue;
Chris Lattneracbf6a42007-04-28 00:57:34 +00005123 }
Chris Lattner6e880872007-04-28 04:52:43 +00005124
5125 Constant *Scale = ConstantInt::get(IntPtrTy, Size);
5126 Constant *OC = ConstantExpr::getIntegerCast(OpC, IntPtrTy, true /*SExt*/);
5127 Scale = ConstantExpr::getMul(OC, Scale);
5128 if (Constant *RC = dyn_cast<Constant>(Result))
5129 Result = ConstantExpr::getAdd(RC, Scale);
5130 else {
5131 // Emit an add instruction.
5132 Result = IC.InsertNewInstBefore(
Gabor Greife1f6e4b2008-05-16 19:29:10 +00005133 BinaryOperator::CreateAdd(Result, Scale,
Chris Lattner6e880872007-04-28 04:52:43 +00005134 GEP->getName()+".offs"), I);
Chris Lattneracbf6a42007-04-28 00:57:34 +00005135 }
Chris Lattner6e880872007-04-28 04:52:43 +00005136 continue;
Chris Lattner0798af32005-01-13 20:14:25 +00005137 }
Chris Lattner6e880872007-04-28 04:52:43 +00005138 // Convert to correct type.
5139 if (Op->getType() != IntPtrTy) {
5140 if (Constant *OpC = dyn_cast<Constant>(Op))
5141 Op = ConstantExpr::getSExt(OpC, IntPtrTy);
5142 else
5143 Op = IC.InsertNewInstBefore(new SExtInst(Op, IntPtrTy,
5144 Op->getName()+".c"), I);
5145 }
5146 if (Size != 1) {
5147 Constant *Scale = ConstantInt::get(IntPtrTy, Size);
5148 if (Constant *OpC = dyn_cast<Constant>(Op))
5149 Op = ConstantExpr::getMul(OpC, Scale);
5150 else // We'll let instcombine(mul) convert this to a shl if possible.
Gabor Greife1f6e4b2008-05-16 19:29:10 +00005151 Op = IC.InsertNewInstBefore(BinaryOperator::CreateMul(Op, Scale,
Chris Lattner6e880872007-04-28 04:52:43 +00005152 GEP->getName()+".idx"), I);
5153 }
5154
5155 // Emit an add instruction.
5156 if (isa<Constant>(Op) && isa<Constant>(Result))
5157 Result = ConstantExpr::getAdd(cast<Constant>(Op),
5158 cast<Constant>(Result));
5159 else
Gabor Greife1f6e4b2008-05-16 19:29:10 +00005160 Result = IC.InsertNewInstBefore(BinaryOperator::CreateAdd(Op, Result,
Chris Lattner6e880872007-04-28 04:52:43 +00005161 GEP->getName()+".offs"), I);
Chris Lattner0798af32005-01-13 20:14:25 +00005162 }
5163 return Result;
5164}
5165
Chris Lattnerc3a43932008-04-22 02:53:33 +00005166
5167/// EvaluateGEPOffsetExpression - Return an value that can be used to compare of
5168/// the *offset* implied by GEP to zero. For example, if we have &A[i], we want
5169/// to return 'i' for "icmp ne i, 0". Note that, in general, indices can be
5170/// complex, and scales are involved. The above expression would also be legal
5171/// to codegen as "icmp ne (i*4), 0" (assuming A is a pointer to i32). This
5172/// later form is less amenable to optimization though, and we are allowed to
5173/// generate the first by knowing that pointer arithmetic doesn't overflow.
5174///
5175/// If we can't emit an optimized form for this expression, this returns null.
5176///
5177static Value *EvaluateGEPOffsetExpression(User *GEP, Instruction &I,
5178 InstCombiner &IC) {
Chris Lattnerc3a43932008-04-22 02:53:33 +00005179 TargetData &TD = IC.getTargetData();
5180 gep_type_iterator GTI = gep_type_begin(GEP);
5181
5182 // Check to see if this gep only has a single variable index. If so, and if
5183 // any constant indices are a multiple of its scale, then we can compute this
5184 // in terms of the scale of the variable index. For example, if the GEP
5185 // implies an offset of "12 + i*4", then we can codegen this as "3 + i",
5186 // because the expression will cross zero at the same point.
5187 unsigned i, e = GEP->getNumOperands();
5188 int64_t Offset = 0;
5189 for (i = 1; i != e; ++i, ++GTI) {
5190 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
5191 // Compute the aggregate offset of constant indices.
5192 if (CI->isZero()) continue;
5193
5194 // Handle a struct index, which adds its field offset to the pointer.
5195 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5196 Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
5197 } else {
5198 uint64_t Size = TD.getABITypeSize(GTI.getIndexedType());
5199 Offset += Size*CI->getSExtValue();
5200 }
5201 } else {
5202 // Found our variable index.
5203 break;
5204 }
5205 }
5206
5207 // If there are no variable indices, we must have a constant offset, just
5208 // evaluate it the general way.
5209 if (i == e) return 0;
5210
5211 Value *VariableIdx = GEP->getOperand(i);
5212 // Determine the scale factor of the variable element. For example, this is
5213 // 4 if the variable index is into an array of i32.
5214 uint64_t VariableScale = TD.getABITypeSize(GTI.getIndexedType());
5215
5216 // Verify that there are no other variable indices. If so, emit the hard way.
5217 for (++i, ++GTI; i != e; ++i, ++GTI) {
5218 ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i));
5219 if (!CI) return 0;
5220
5221 // Compute the aggregate offset of constant indices.
5222 if (CI->isZero()) continue;
5223
5224 // Handle a struct index, which adds its field offset to the pointer.
5225 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5226 Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
5227 } else {
5228 uint64_t Size = TD.getABITypeSize(GTI.getIndexedType());
5229 Offset += Size*CI->getSExtValue();
5230 }
5231 }
5232
5233 // Okay, we know we have a single variable index, which must be a
5234 // pointer/array/vector index. If there is no offset, life is simple, return
5235 // the index.
5236 unsigned IntPtrWidth = TD.getPointerSizeInBits();
5237 if (Offset == 0) {
5238 // Cast to intptrty in case a truncation occurs. If an extension is needed,
5239 // we don't need to bother extending: the extension won't affect where the
5240 // computation crosses zero.
5241 if (VariableIdx->getType()->getPrimitiveSizeInBits() > IntPtrWidth)
5242 VariableIdx = new TruncInst(VariableIdx, TD.getIntPtrType(),
5243 VariableIdx->getNameStart(), &I);
5244 return VariableIdx;
5245 }
5246
5247 // Otherwise, there is an index. The computation we will do will be modulo
5248 // the pointer size, so get it.
5249 uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
5250
5251 Offset &= PtrSizeMask;
5252 VariableScale &= PtrSizeMask;
5253
5254 // To do this transformation, any constant index must be a multiple of the
5255 // variable scale factor. For example, we can evaluate "12 + 4*i" as "3 + i",
5256 // but we can't evaluate "10 + 3*i" in terms of i. Check that the offset is a
5257 // multiple of the variable scale.
5258 int64_t NewOffs = Offset / (int64_t)VariableScale;
5259 if (Offset != NewOffs*(int64_t)VariableScale)
5260 return 0;
5261
5262 // Okay, we can do this evaluation. Start by converting the index to intptr.
5263 const Type *IntPtrTy = TD.getIntPtrType();
5264 if (VariableIdx->getType() != IntPtrTy)
Gabor Greife1f6e4b2008-05-16 19:29:10 +00005265 VariableIdx = CastInst::CreateIntegerCast(VariableIdx, IntPtrTy,
Chris Lattnerc3a43932008-04-22 02:53:33 +00005266 true /*SExt*/,
5267 VariableIdx->getNameStart(), &I);
5268 Constant *OffsetVal = ConstantInt::get(IntPtrTy, NewOffs);
Gabor Greife1f6e4b2008-05-16 19:29:10 +00005269 return BinaryOperator::CreateAdd(VariableIdx, OffsetVal, "offset", &I);
Chris Lattnerc3a43932008-04-22 02:53:33 +00005270}
5271
5272
Reid Spencer266e42b2006-12-23 06:05:41 +00005273/// FoldGEPICmp - Fold comparisons between a GEP instruction and something
Chris Lattner0798af32005-01-13 20:14:25 +00005274/// else. At this point we know that the GEP is on the LHS of the comparison.
Reid Spencer266e42b2006-12-23 06:05:41 +00005275Instruction *InstCombiner::FoldGEPICmp(User *GEPLHS, Value *RHS,
5276 ICmpInst::Predicate Cond,
5277 Instruction &I) {
Chris Lattner0798af32005-01-13 20:14:25 +00005278 assert(dyn_castGetElementPtr(GEPLHS) && "LHS is not a getelementptr!");
Chris Lattner81e84172005-01-13 22:25:21 +00005279
Chris Lattnerc3a43932008-04-22 02:53:33 +00005280 // Look through bitcasts.
5281 if (BitCastInst *BCI = dyn_cast<BitCastInst>(RHS))
5282 RHS = BCI->getOperand(0);
Chris Lattner81e84172005-01-13 22:25:21 +00005283
Chris Lattner0798af32005-01-13 20:14:25 +00005284 Value *PtrBase = GEPLHS->getOperand(0);
5285 if (PtrBase == RHS) {
Chris Lattner682a7dc2008-02-05 04:45:32 +00005286 // ((gep Ptr, OFFSET) cmp Ptr) ---> (OFFSET cmp 0).
Chris Lattnerc3a43932008-04-22 02:53:33 +00005287 // This transformation (ignoring the base and scales) is valid because we
5288 // know pointers can't overflow. See if we can output an optimized form.
5289 Value *Offset = EvaluateGEPOffsetExpression(GEPLHS, I, *this);
5290
5291 // If not, synthesize the offset the hard way.
5292 if (Offset == 0)
5293 Offset = EmitGEPOffset(GEPLHS, I, *this);
Chris Lattner682a7dc2008-02-05 04:45:32 +00005294 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), Offset,
5295 Constant::getNullValue(Offset->getType()));
Chris Lattner0798af32005-01-13 20:14:25 +00005296 } else if (User *GEPRHS = dyn_castGetElementPtr(RHS)) {
Chris Lattnera21bf8d2005-04-25 20:17:30 +00005297 // If the base pointers are different, but the indices are the same, just
5298 // compare the base pointer.
5299 if (PtrBase != GEPRHS->getOperand(0)) {
5300 bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00005301 IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
Chris Lattnerbd43b9d2005-04-26 14:40:41 +00005302 GEPRHS->getOperand(0)->getType();
Chris Lattnera21bf8d2005-04-25 20:17:30 +00005303 if (IndicesTheSame)
5304 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
5305 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
5306 IndicesTheSame = false;
5307 break;
5308 }
5309
5310 // If all indices are the same, just compare the base pointers.
5311 if (IndicesTheSame)
Reid Spencer266e42b2006-12-23 06:05:41 +00005312 return new ICmpInst(ICmpInst::getSignedPredicate(Cond),
5313 GEPLHS->getOperand(0), GEPRHS->getOperand(0));
Chris Lattnera21bf8d2005-04-25 20:17:30 +00005314
5315 // Otherwise, the base pointers are different and the indices are
5316 // different, bail out.
Chris Lattner0798af32005-01-13 20:14:25 +00005317 return 0;
Chris Lattnera21bf8d2005-04-25 20:17:30 +00005318 }
Chris Lattner0798af32005-01-13 20:14:25 +00005319
Chris Lattner81e84172005-01-13 22:25:21 +00005320 // If one of the GEPs has all zero indices, recurse.
5321 bool AllZeros = true;
5322 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
5323 if (!isa<Constant>(GEPLHS->getOperand(i)) ||
5324 !cast<Constant>(GEPLHS->getOperand(i))->isNullValue()) {
5325 AllZeros = false;
5326 break;
5327 }
5328 if (AllZeros)
Reid Spencer266e42b2006-12-23 06:05:41 +00005329 return FoldGEPICmp(GEPRHS, GEPLHS->getOperand(0),
5330 ICmpInst::getSwappedPredicate(Cond), I);
Chris Lattner4fa89822005-01-14 00:20:05 +00005331
5332 // If the other GEP has all zero indices, recurse.
Chris Lattner81e84172005-01-13 22:25:21 +00005333 AllZeros = true;
5334 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
5335 if (!isa<Constant>(GEPRHS->getOperand(i)) ||
5336 !cast<Constant>(GEPRHS->getOperand(i))->isNullValue()) {
5337 AllZeros = false;
5338 break;
5339 }
5340 if (AllZeros)
Reid Spencer266e42b2006-12-23 06:05:41 +00005341 return FoldGEPICmp(GEPLHS, GEPRHS->getOperand(0), Cond, I);
Chris Lattner81e84172005-01-13 22:25:21 +00005342
Chris Lattner4fa89822005-01-14 00:20:05 +00005343 if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
5344 // If the GEPs only differ by one index, compare it.
5345 unsigned NumDifferences = 0; // Keep track of # differences.
5346 unsigned DiffOperand = 0; // The operand that differs.
5347 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
5348 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
Chris Lattnerd1f46d32005-04-24 06:59:08 +00005349 if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
5350 GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
Chris Lattnerfc4429e2005-01-21 23:06:49 +00005351 // Irreconcilable differences.
Chris Lattner4fa89822005-01-14 00:20:05 +00005352 NumDifferences = 2;
5353 break;
5354 } else {
5355 if (NumDifferences++) break;
5356 DiffOperand = i;
5357 }
5358 }
5359
5360 if (NumDifferences == 0) // SAME GEP?
5361 return ReplaceInstUsesWith(I, // No comparison is needed here.
Nick Lewycky0c5c4792007-09-06 02:40:25 +00005362 ConstantInt::get(Type::Int1Ty,
Nick Lewycky79376f42008-05-17 07:33:39 +00005363 ICmpInst::isTrueWhenEqual(Cond)));
Nick Lewycky0c5c4792007-09-06 02:40:25 +00005364
Chris Lattner4fa89822005-01-14 00:20:05 +00005365 else if (NumDifferences == 1) {
Chris Lattnerfc4429e2005-01-21 23:06:49 +00005366 Value *LHSV = GEPLHS->getOperand(DiffOperand);
5367 Value *RHSV = GEPRHS->getOperand(DiffOperand);
Reid Spencer266e42b2006-12-23 06:05:41 +00005368 // Make sure we do a signed comparison here.
5369 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), LHSV, RHSV);
Chris Lattner4fa89822005-01-14 00:20:05 +00005370 }
5371 }
5372
Reid Spencer266e42b2006-12-23 06:05:41 +00005373 // Only lower this if the icmp is the only user of the GEP or if we expect
Chris Lattner0798af32005-01-13 20:14:25 +00005374 // the result to fold to a constant!
5375 if ((isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
5376 (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
5377 // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2) ---> (OFFSET1 cmp OFFSET2)
5378 Value *L = EmitGEPOffset(GEPLHS, I, *this);
5379 Value *R = EmitGEPOffset(GEPRHS, I, *this);
Reid Spencer266e42b2006-12-23 06:05:41 +00005380 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), L, R);
Chris Lattner0798af32005-01-13 20:14:25 +00005381 }
5382 }
5383 return 0;
5384}
5385
Chris Lattner5920a782008-05-19 20:18:56 +00005386/// FoldFCmp_IntToFP_Cst - Fold fcmp ([us]itofp x, cst) if possible.
5387///
5388Instruction *InstCombiner::FoldFCmp_IntToFP_Cst(FCmpInst &I,
5389 Instruction *LHSI,
5390 Constant *RHSC) {
5391 if (!isa<ConstantFP>(RHSC)) return 0;
5392 const APFloat &RHS = cast<ConstantFP>(RHSC)->getValueAPF();
5393
5394 // Get the width of the mantissa. We don't want to hack on conversions that
5395 // might lose information from the integer, e.g. "i64 -> float"
Chris Lattnerb4271222008-05-19 21:17:23 +00005396 int MantissaWidth = LHSI->getType()->getFPMantissaWidth();
Chris Lattner5920a782008-05-19 20:18:56 +00005397 if (MantissaWidth == -1) return 0; // Unknown.
5398
5399 // Check to see that the input is converted from an integer type that is small
5400 // enough that preserves all bits. TODO: check here for "known" sign bits.
5401 // This would allow us to handle (fptosi (x >>s 62) to float) if x is i64 f.e.
5402 unsigned InputSize = LHSI->getOperand(0)->getType()->getPrimitiveSizeInBits();
5403
5404 // If this is a uitofp instruction, we need an extra bit to hold the sign.
Bill Wendling3f547be2008-11-09 04:26:50 +00005405 bool LHSUnsigned = isa<UIToFPInst>(LHSI);
5406 if (LHSUnsigned)
Chris Lattner5920a782008-05-19 20:18:56 +00005407 ++InputSize;
5408
5409 // If the conversion would lose info, don't hack on this.
5410 if ((int)InputSize > MantissaWidth)
5411 return 0;
5412
5413 // Otherwise, we can potentially simplify the comparison. We know that it
5414 // will always come through as an integer value and we know the constant is
5415 // not a NAN (it would have been previously simplified).
5416 assert(!RHS.isNaN() && "NaN comparison not already folded!");
5417
5418 ICmpInst::Predicate Pred;
5419 switch (I.getPredicate()) {
5420 default: assert(0 && "Unexpected predicate!");
5421 case FCmpInst::FCMP_UEQ:
Bill Wendling3f547be2008-11-09 04:26:50 +00005422 case FCmpInst::FCMP_OEQ:
5423 Pred = ICmpInst::ICMP_EQ;
5424 break;
Chris Lattner5920a782008-05-19 20:18:56 +00005425 case FCmpInst::FCMP_UGT:
Bill Wendling3f547be2008-11-09 04:26:50 +00005426 case FCmpInst::FCMP_OGT:
5427 Pred = LHSUnsigned ? ICmpInst::ICMP_UGT : ICmpInst::ICMP_SGT;
5428 break;
Chris Lattner5920a782008-05-19 20:18:56 +00005429 case FCmpInst::FCMP_UGE:
Bill Wendling3f547be2008-11-09 04:26:50 +00005430 case FCmpInst::FCMP_OGE:
5431 Pred = LHSUnsigned ? ICmpInst::ICMP_UGE : ICmpInst::ICMP_SGE;
5432 break;
Chris Lattner5920a782008-05-19 20:18:56 +00005433 case FCmpInst::FCMP_ULT:
Bill Wendling3f547be2008-11-09 04:26:50 +00005434 case FCmpInst::FCMP_OLT:
5435 Pred = LHSUnsigned ? ICmpInst::ICMP_ULT : ICmpInst::ICMP_SLT;
5436 break;
Chris Lattner5920a782008-05-19 20:18:56 +00005437 case FCmpInst::FCMP_ULE:
Bill Wendling3f547be2008-11-09 04:26:50 +00005438 case FCmpInst::FCMP_OLE:
5439 Pred = LHSUnsigned ? ICmpInst::ICMP_ULE : ICmpInst::ICMP_SLE;
5440 break;
Chris Lattner5920a782008-05-19 20:18:56 +00005441 case FCmpInst::FCMP_UNE:
Bill Wendling3f547be2008-11-09 04:26:50 +00005442 case FCmpInst::FCMP_ONE:
5443 Pred = ICmpInst::ICMP_NE;
5444 break;
Chris Lattner5920a782008-05-19 20:18:56 +00005445 case FCmpInst::FCMP_ORD:
Eli Friedman11c15a52008-11-30 22:48:49 +00005446 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Chris Lattner5920a782008-05-19 20:18:56 +00005447 case FCmpInst::FCMP_UNO:
Eli Friedman11c15a52008-11-30 22:48:49 +00005448 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Chris Lattner5920a782008-05-19 20:18:56 +00005449 }
5450
5451 const IntegerType *IntTy = cast<IntegerType>(LHSI->getOperand(0)->getType());
5452
5453 // Now we know that the APFloat is a normal number, zero or inf.
5454
Chris Lattner9c27f962008-05-20 03:50:52 +00005455 // See if the FP constant is too large for the integer. For example,
Chris Lattner5920a782008-05-19 20:18:56 +00005456 // comparing an i8 to 300.0.
5457 unsigned IntWidth = IntTy->getPrimitiveSizeInBits();
5458
Bill Wendling3f547be2008-11-09 04:26:50 +00005459 if (!LHSUnsigned) {
5460 // If the RHS value is > SignedMax, fold the comparison. This handles +INF
5461 // and large values.
5462 APFloat SMax(RHS.getSemantics(), APFloat::fcZero, false);
5463 SMax.convertFromAPInt(APInt::getSignedMaxValue(IntWidth), true,
5464 APFloat::rmNearestTiesToEven);
5465 if (SMax.compare(RHS) == APFloat::cmpLessThan) { // smax < 13123.0
5466 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SLT ||
5467 Pred == ICmpInst::ICMP_SLE)
Eli Friedman11c15a52008-11-30 22:48:49 +00005468 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5469 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Bill Wendling3f547be2008-11-09 04:26:50 +00005470 }
5471 } else {
5472 // If the RHS value is > UnsignedMax, fold the comparison. This handles
5473 // +INF and large values.
5474 APFloat UMax(RHS.getSemantics(), APFloat::fcZero, false);
5475 UMax.convertFromAPInt(APInt::getMaxValue(IntWidth), false,
5476 APFloat::rmNearestTiesToEven);
5477 if (UMax.compare(RHS) == APFloat::cmpLessThan) { // umax < 13123.0
5478 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_ULT ||
5479 Pred == ICmpInst::ICMP_ULE)
Eli Friedman11c15a52008-11-30 22:48:49 +00005480 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5481 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Bill Wendling3f547be2008-11-09 04:26:50 +00005482 }
Chris Lattner5920a782008-05-19 20:18:56 +00005483 }
5484
Bill Wendling3f547be2008-11-09 04:26:50 +00005485 if (!LHSUnsigned) {
5486 // See if the RHS value is < SignedMin.
5487 APFloat SMin(RHS.getSemantics(), APFloat::fcZero, false);
5488 SMin.convertFromAPInt(APInt::getSignedMinValue(IntWidth), true,
5489 APFloat::rmNearestTiesToEven);
5490 if (SMin.compare(RHS) == APFloat::cmpGreaterThan) { // smin > 12312.0
5491 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SGT ||
5492 Pred == ICmpInst::ICMP_SGE)
Eli Friedman11c15a52008-11-30 22:48:49 +00005493 return ReplaceInstUsesWith(I,ConstantInt::getTrue());
5494 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Bill Wendling3f547be2008-11-09 04:26:50 +00005495 }
Chris Lattner5920a782008-05-19 20:18:56 +00005496 }
5497
Bill Wendling3f547be2008-11-09 04:26:50 +00005498 // Okay, now we know that the FP constant fits in the range [SMIN, SMAX] or
5499 // [0, UMAX], but it may still be fractional. See if it is fractional by
5500 // casting the FP value to the integer value and back, checking for equality.
5501 // Don't do this for zero, because -0.0 is not fractional.
Chris Lattner5920a782008-05-19 20:18:56 +00005502 Constant *RHSInt = ConstantExpr::getFPToSI(RHSC, IntTy);
5503 if (!RHS.isZero() &&
5504 ConstantExpr::getSIToFP(RHSInt, RHSC->getType()) != RHSC) {
Bill Wendling3f547be2008-11-09 04:26:50 +00005505 // If we had a comparison against a fractional value, we have to adjust the
5506 // compare predicate and sometimes the value. RHSC is rounded towards zero
5507 // at this point.
Chris Lattner5920a782008-05-19 20:18:56 +00005508 switch (Pred) {
5509 default: assert(0 && "Unexpected integer comparison!");
5510 case ICmpInst::ICMP_NE: // (float)int != 4.4 --> true
Eli Friedman11c15a52008-11-30 22:48:49 +00005511 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Chris Lattner5920a782008-05-19 20:18:56 +00005512 case ICmpInst::ICMP_EQ: // (float)int == 4.4 --> false
Eli Friedman11c15a52008-11-30 22:48:49 +00005513 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Bill Wendling3f547be2008-11-09 04:26:50 +00005514 case ICmpInst::ICMP_ULE:
5515 // (float)int <= 4.4 --> int <= 4
5516 // (float)int <= -4.4 --> false
5517 if (RHS.isNegative())
Eli Friedman11c15a52008-11-30 22:48:49 +00005518 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Bill Wendling3f547be2008-11-09 04:26:50 +00005519 break;
Chris Lattner5920a782008-05-19 20:18:56 +00005520 case ICmpInst::ICMP_SLE:
5521 // (float)int <= 4.4 --> int <= 4
5522 // (float)int <= -4.4 --> int < -4
5523 if (RHS.isNegative())
5524 Pred = ICmpInst::ICMP_SLT;
5525 break;
Bill Wendling3f547be2008-11-09 04:26:50 +00005526 case ICmpInst::ICMP_ULT:
5527 // (float)int < -4.4 --> false
5528 // (float)int < 4.4 --> int <= 4
5529 if (RHS.isNegative())
Eli Friedman11c15a52008-11-30 22:48:49 +00005530 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Bill Wendling3f547be2008-11-09 04:26:50 +00005531 Pred = ICmpInst::ICMP_ULE;
5532 break;
Chris Lattner5920a782008-05-19 20:18:56 +00005533 case ICmpInst::ICMP_SLT:
5534 // (float)int < -4.4 --> int < -4
5535 // (float)int < 4.4 --> int <= 4
5536 if (!RHS.isNegative())
5537 Pred = ICmpInst::ICMP_SLE;
5538 break;
Bill Wendling3f547be2008-11-09 04:26:50 +00005539 case ICmpInst::ICMP_UGT:
5540 // (float)int > 4.4 --> int > 4
5541 // (float)int > -4.4 --> true
5542 if (RHS.isNegative())
Eli Friedman11c15a52008-11-30 22:48:49 +00005543 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Bill Wendling3f547be2008-11-09 04:26:50 +00005544 break;
Chris Lattner5920a782008-05-19 20:18:56 +00005545 case ICmpInst::ICMP_SGT:
5546 // (float)int > 4.4 --> int > 4
5547 // (float)int > -4.4 --> int >= -4
5548 if (RHS.isNegative())
5549 Pred = ICmpInst::ICMP_SGE;
5550 break;
Bill Wendling3f547be2008-11-09 04:26:50 +00005551 case ICmpInst::ICMP_UGE:
5552 // (float)int >= -4.4 --> true
5553 // (float)int >= 4.4 --> int > 4
5554 if (!RHS.isNegative())
Eli Friedman11c15a52008-11-30 22:48:49 +00005555 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Bill Wendling3f547be2008-11-09 04:26:50 +00005556 Pred = ICmpInst::ICMP_UGT;
5557 break;
Chris Lattner5920a782008-05-19 20:18:56 +00005558 case ICmpInst::ICMP_SGE:
5559 // (float)int >= -4.4 --> int >= -4
5560 // (float)int >= 4.4 --> int > 4
5561 if (!RHS.isNegative())
5562 Pred = ICmpInst::ICMP_SGT;
5563 break;
5564 }
5565 }
5566
5567 // Lower this FP comparison into an appropriate integer version of the
5568 // comparison.
5569 return new ICmpInst(Pred, LHSI->getOperand(0), RHSInt);
5570}
5571
Reid Spencer266e42b2006-12-23 06:05:41 +00005572Instruction *InstCombiner::visitFCmpInst(FCmpInst &I) {
5573 bool Changed = SimplifyCompare(I);
Chris Lattner6d14f2a2002-08-09 23:47:40 +00005574 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00005575
Chris Lattner6ee923f2007-01-14 19:42:17 +00005576 // Fold trivial predicates.
5577 if (I.getPredicate() == FCmpInst::FCMP_FALSE)
Eli Friedman11c15a52008-11-30 22:48:49 +00005578 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Chris Lattner6ee923f2007-01-14 19:42:17 +00005579 if (I.getPredicate() == FCmpInst::FCMP_TRUE)
Eli Friedman11c15a52008-11-30 22:48:49 +00005580 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Chris Lattner6ee923f2007-01-14 19:42:17 +00005581
5582 // Simplify 'fcmp pred X, X'
5583 if (Op0 == Op1) {
5584 switch (I.getPredicate()) {
5585 default: assert(0 && "Unknown predicate!");
5586 case FCmpInst::FCMP_UEQ: // True if unordered or equal
5587 case FCmpInst::FCMP_UGE: // True if unordered, greater than, or equal
5588 case FCmpInst::FCMP_ULE: // True if unordered, less than, or equal
Eli Friedman11c15a52008-11-30 22:48:49 +00005589 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Chris Lattner6ee923f2007-01-14 19:42:17 +00005590 case FCmpInst::FCMP_OGT: // True if ordered and greater than
5591 case FCmpInst::FCMP_OLT: // True if ordered and less than
5592 case FCmpInst::FCMP_ONE: // True if ordered and operands are unequal
Eli Friedman11c15a52008-11-30 22:48:49 +00005593 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Chris Lattner6ee923f2007-01-14 19:42:17 +00005594
5595 case FCmpInst::FCMP_UNO: // True if unordered: isnan(X) | isnan(Y)
5596 case FCmpInst::FCMP_ULT: // True if unordered or less than
5597 case FCmpInst::FCMP_UGT: // True if unordered or greater than
5598 case FCmpInst::FCMP_UNE: // True if unordered or not equal
5599 // Canonicalize these to be 'fcmp uno %X, 0.0'.
5600 I.setPredicate(FCmpInst::FCMP_UNO);
5601 I.setOperand(1, Constant::getNullValue(Op0->getType()));
5602 return &I;
5603
5604 case FCmpInst::FCMP_ORD: // True if ordered (no nans)
5605 case FCmpInst::FCMP_OEQ: // True if ordered and equal
5606 case FCmpInst::FCMP_OGE: // True if ordered and greater than or equal
5607 case FCmpInst::FCMP_OLE: // True if ordered and less than or equal
5608 // Canonicalize these to be 'fcmp ord %X, 0.0'.
5609 I.setPredicate(FCmpInst::FCMP_ORD);
5610 I.setOperand(1, Constant::getNullValue(Op0->getType()));
5611 return &I;
5612 }
5613 }
5614
Reid Spencer266e42b2006-12-23 06:05:41 +00005615 if (isa<UndefValue>(Op1)) // fcmp pred X, undef -> undef
Reid Spencer542964f2007-01-11 18:21:29 +00005616 return ReplaceInstUsesWith(I, UndefValue::get(Type::Int1Ty));
Chris Lattner81a7a232004-10-16 18:11:37 +00005617
Reid Spencer266e42b2006-12-23 06:05:41 +00005618 // Handle fcmp with constant RHS
5619 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
Chris Lattner5920a782008-05-19 20:18:56 +00005620 // If the constant is a nan, see if we can fold the comparison based on it.
5621 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
5622 if (CFP->getValueAPF().isNaN()) {
5623 if (FCmpInst::isOrdered(I.getPredicate())) // True if ordered and...
Eli Friedman11c15a52008-11-30 22:48:49 +00005624 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Chris Lattner9c27f962008-05-20 03:50:52 +00005625 assert(FCmpInst::isUnordered(I.getPredicate()) &&
5626 "Comparison must be either ordered or unordered!");
5627 // True if unordered.
Eli Friedman11c15a52008-11-30 22:48:49 +00005628 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Chris Lattner5920a782008-05-19 20:18:56 +00005629 }
5630 }
5631
Reid Spencer266e42b2006-12-23 06:05:41 +00005632 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5633 switch (LHSI->getOpcode()) {
5634 case Instruction::PHI:
Chris Lattnerb4866ef2008-06-08 20:52:11 +00005635 // Only fold fcmp into the PHI if the phi and fcmp are in the same
5636 // block. If in the same block, we're encouraging jump threading. If
5637 // not, we are just pessimizing the code by making an i1 phi.
5638 if (LHSI->getParent() == I.getParent())
5639 if (Instruction *NV = FoldOpIntoPhi(I))
5640 return NV;
Reid Spencer266e42b2006-12-23 06:05:41 +00005641 break;
Chris Lattner5920a782008-05-19 20:18:56 +00005642 case Instruction::SIToFP:
5643 case Instruction::UIToFP:
5644 if (Instruction *NV = FoldFCmp_IntToFP_Cst(I, LHSI, RHSC))
5645 return NV;
5646 break;
Reid Spencer266e42b2006-12-23 06:05:41 +00005647 case Instruction::Select:
5648 // If either operand of the select is a constant, we can fold the
5649 // comparison into the select arms, which will cause one to be
5650 // constant folded and the select turned into a bitwise or.
5651 Value *Op1 = 0, *Op2 = 0;
5652 if (LHSI->hasOneUse()) {
5653 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
5654 // Fold the known value into the constant operand.
5655 Op1 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
5656 // Insert a new FCmp of the other select operand.
5657 Op2 = InsertNewInstBefore(new FCmpInst(I.getPredicate(),
5658 LHSI->getOperand(2), RHSC,
5659 I.getName()), I);
5660 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
5661 // Fold the known value into the constant operand.
5662 Op2 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
5663 // Insert a new FCmp of the other select operand.
5664 Op1 = InsertNewInstBefore(new FCmpInst(I.getPredicate(),
5665 LHSI->getOperand(1), RHSC,
5666 I.getName()), I);
5667 }
5668 }
5669
5670 if (Op1)
Gabor Greife9ecc682008-04-06 20:25:17 +00005671 return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
Reid Spencer266e42b2006-12-23 06:05:41 +00005672 break;
5673 }
5674 }
5675
5676 return Changed ? &I : 0;
5677}
5678
5679Instruction *InstCombiner::visitICmpInst(ICmpInst &I) {
5680 bool Changed = SimplifyCompare(I);
5681 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5682 const Type *Ty = Op0->getType();
5683
5684 // icmp X, X
5685 if (Op0 == Op1)
Reid Spencercddc9df2007-01-12 04:24:46 +00005686 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
Nick Lewycky79376f42008-05-17 07:33:39 +00005687 I.isTrueWhenEqual()));
Reid Spencer266e42b2006-12-23 06:05:41 +00005688
5689 if (isa<UndefValue>(Op1)) // X icmp undef -> undef
Reid Spencer542964f2007-01-11 18:21:29 +00005690 return ReplaceInstUsesWith(I, UndefValue::get(Type::Int1Ty));
Christopher Lambf00ac6d2007-12-18 21:32:20 +00005691
Reid Spencer266e42b2006-12-23 06:05:41 +00005692 // icmp <global/alloca*/null>, <global/alloca*/null> - Global/Stack value
Chris Lattner15ff1e12004-11-14 07:33:16 +00005693 // addresses never equal each other! We already know that Op0 != Op1.
Misha Brukmanb1c93172005-04-21 23:48:37 +00005694 if ((isa<GlobalValue>(Op0) || isa<AllocaInst>(Op0) ||
5695 isa<ConstantPointerNull>(Op0)) &&
5696 (isa<GlobalValue>(Op1) || isa<AllocaInst>(Op1) ||
Chris Lattner15ff1e12004-11-14 07:33:16 +00005697 isa<ConstantPointerNull>(Op1)))
Reid Spencercddc9df2007-01-12 04:24:46 +00005698 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
Nick Lewycky79376f42008-05-17 07:33:39 +00005699 !I.isTrueWhenEqual()));
Chris Lattner6d14f2a2002-08-09 23:47:40 +00005700
Reid Spencer266e42b2006-12-23 06:05:41 +00005701 // icmp's with boolean values can always be turned into bitwise operations
Reid Spencer542964f2007-01-11 18:21:29 +00005702 if (Ty == Type::Int1Ty) {
Reid Spencer266e42b2006-12-23 06:05:41 +00005703 switch (I.getPredicate()) {
5704 default: assert(0 && "Invalid icmp instruction!");
Chris Lattner6af608b2008-07-11 04:20:58 +00005705 case ICmpInst::ICMP_EQ: { // icmp eq i1 A, B -> ~(A^B)
Gabor Greife1f6e4b2008-05-16 19:29:10 +00005706 Instruction *Xor = BinaryOperator::CreateXor(Op0, Op1, I.getName()+"tmp");
Chris Lattner6d14f2a2002-08-09 23:47:40 +00005707 InsertNewInstBefore(Xor, I);
Gabor Greife1f6e4b2008-05-16 19:29:10 +00005708 return BinaryOperator::CreateNot(Xor);
Chris Lattner6d14f2a2002-08-09 23:47:40 +00005709 }
Chris Lattner6af608b2008-07-11 04:20:58 +00005710 case ICmpInst::ICMP_NE: // icmp eq i1 A, B -> A^B
Gabor Greife1f6e4b2008-05-16 19:29:10 +00005711 return BinaryOperator::CreateXor(Op0, Op1);
Chris Lattner6d14f2a2002-08-09 23:47:40 +00005712
Reid Spencer266e42b2006-12-23 06:05:41 +00005713 case ICmpInst::ICMP_UGT:
Chris Lattner6af608b2008-07-11 04:20:58 +00005714 std::swap(Op0, Op1); // Change icmp ugt -> icmp ult
Chris Lattner4456da62004-08-11 00:50:51 +00005715 // FALL THROUGH
Chris Lattner6af608b2008-07-11 04:20:58 +00005716 case ICmpInst::ICMP_ULT:{ // icmp ult i1 A, B -> ~A & B
Gabor Greife1f6e4b2008-05-16 19:29:10 +00005717 Instruction *Not = BinaryOperator::CreateNot(Op0, I.getName()+"tmp");
Chris Lattner4456da62004-08-11 00:50:51 +00005718 InsertNewInstBefore(Not, I);
Gabor Greife1f6e4b2008-05-16 19:29:10 +00005719 return BinaryOperator::CreateAnd(Not, Op1);
Chris Lattner4456da62004-08-11 00:50:51 +00005720 }
Chris Lattner6af608b2008-07-11 04:20:58 +00005721 case ICmpInst::ICMP_SGT:
5722 std::swap(Op0, Op1); // Change icmp sgt -> icmp slt
Chris Lattner4456da62004-08-11 00:50:51 +00005723 // FALL THROUGH
Chris Lattner6af608b2008-07-11 04:20:58 +00005724 case ICmpInst::ICMP_SLT: { // icmp slt i1 A, B -> A & ~B
5725 Instruction *Not = BinaryOperator::CreateNot(Op1, I.getName()+"tmp");
5726 InsertNewInstBefore(Not, I);
5727 return BinaryOperator::CreateAnd(Not, Op0);
5728 }
5729 case ICmpInst::ICMP_UGE:
5730 std::swap(Op0, Op1); // Change icmp uge -> icmp ule
5731 // FALL THROUGH
5732 case ICmpInst::ICMP_ULE: { // icmp ule i1 A, B -> ~A | B
Gabor Greife1f6e4b2008-05-16 19:29:10 +00005733 Instruction *Not = BinaryOperator::CreateNot(Op0, I.getName()+"tmp");
Chris Lattner4456da62004-08-11 00:50:51 +00005734 InsertNewInstBefore(Not, I);
Gabor Greife1f6e4b2008-05-16 19:29:10 +00005735 return BinaryOperator::CreateOr(Not, Op1);
Chris Lattner4456da62004-08-11 00:50:51 +00005736 }
Chris Lattner6af608b2008-07-11 04:20:58 +00005737 case ICmpInst::ICMP_SGE:
5738 std::swap(Op0, Op1); // Change icmp sge -> icmp sle
5739 // FALL THROUGH
5740 case ICmpInst::ICMP_SLE: { // icmp sle i1 A, B -> A | ~B
5741 Instruction *Not = BinaryOperator::CreateNot(Op1, I.getName()+"tmp");
5742 InsertNewInstBefore(Not, I);
5743 return BinaryOperator::CreateOr(Not, Op0);
5744 }
Chris Lattner4456da62004-08-11 00:50:51 +00005745 }
Chris Lattner6d14f2a2002-08-09 23:47:40 +00005746 }
5747
Dan Gohmandafa9c62008-09-16 18:46:06 +00005748 // See if we are doing a comparison with a constant.
Chris Lattner6d14f2a2002-08-09 23:47:40 +00005749 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner4fa8bb32008-07-11 04:09:09 +00005750 Value *A, *B;
Christopher Lamb7d82bc42007-12-20 07:21:11 +00005751
Chris Lattnerdb026d72008-01-05 01:18:20 +00005752 // (icmp ne/eq (sub A B) 0) -> (icmp ne/eq A, B)
5753 if (I.isEquality() && CI->isNullValue() &&
5754 match(Op0, m_Sub(m_Value(A), m_Value(B)))) {
5755 // (icmp cond A B) if cond is equality
5756 return new ICmpInst(I.getPredicate(), A, B);
Owen Anderson73639142007-12-28 07:42:12 +00005757 }
Christopher Lamb7d82bc42007-12-20 07:21:11 +00005758
Dan Gohmandafa9c62008-09-16 18:46:06 +00005759 // If we have an icmp le or icmp ge instruction, turn it into the
5760 // appropriate icmp lt or icmp gt instruction. This allows us to rely on
5761 // them being folded in the code below.
Chris Lattner38a50c92008-07-11 05:08:55 +00005762 switch (I.getPredicate()) {
5763 default: break;
5764 case ICmpInst::ICMP_ULE:
5765 if (CI->isMaxValue(false)) // A <=u MAX -> TRUE
5766 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5767 return new ICmpInst(ICmpInst::ICMP_ULT, Op0, AddOne(CI));
5768 case ICmpInst::ICMP_SLE:
5769 if (CI->isMaxValue(true)) // A <=s MAX -> TRUE
5770 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5771 return new ICmpInst(ICmpInst::ICMP_SLT, Op0, AddOne(CI));
5772 case ICmpInst::ICMP_UGE:
5773 if (CI->isMinValue(false)) // A >=u MIN -> TRUE
5774 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5775 return new ICmpInst( ICmpInst::ICMP_UGT, Op0, SubOne(CI));
5776 case ICmpInst::ICMP_SGE:
5777 if (CI->isMinValue(true)) // A >=s MIN -> TRUE
5778 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5779 return new ICmpInst(ICmpInst::ICMP_SGT, Op0, SubOne(CI));
5780 }
5781
Chris Lattnerbd25b852008-07-11 05:40:05 +00005782 // See if we can fold the comparison based on range information we can get
5783 // by checking whether bits are known to be zero or one in the input.
5784 uint32_t BitWidth = cast<IntegerType>(Ty)->getBitWidth();
5785 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
5786
5787 // If this comparison is a normal comparison, it demands all
Chris Lattnerd4fef8d2007-07-15 20:54:51 +00005788 // bits, if it is a sign bit comparison, it only demands the sign bit.
Chris Lattnerd4fef8d2007-07-15 20:54:51 +00005789 bool UnusedBit;
5790 bool isSignBit = isSignBitCheck(I.getPredicate(), CI, UnusedBit);
5791
Chris Lattnerd4fef8d2007-07-15 20:54:51 +00005792 if (SimplifyDemandedBits(Op0,
5793 isSignBit ? APInt::getSignBit(BitWidth)
5794 : APInt::getAllOnesValue(BitWidth),
Chris Lattneree0f2802006-02-12 02:07:56 +00005795 KnownZero, KnownOne, 0))
5796 return &I;
5797
5798 // Given the known and unknown bits, compute a range that the LHS could be
Chris Lattner38a50c92008-07-11 05:08:55 +00005799 // in. Compute the Min, Max and RHS values based on the known bits. For the
5800 // EQ and NE we use unsigned values.
5801 APInt Min(BitWidth, 0), Max(BitWidth, 0);
Chris Lattner38a50c92008-07-11 05:08:55 +00005802 if (ICmpInst::isSignedPredicate(I.getPredicate()))
5803 ComputeSignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne, Min, Max);
5804 else
5805 ComputeUnsignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne,Min,Max);
5806
Chris Lattnerbd25b852008-07-11 05:40:05 +00005807 // If Min and Max are known to be the same, then SimplifyDemandedBits
5808 // figured out that the LHS is a constant. Just constant fold this now so
5809 // that code below can assume that Min != Max.
5810 if (Min == Max)
5811 return ReplaceInstUsesWith(I, ConstantExpr::getICmp(I.getPredicate(),
5812 ConstantInt::get(Min),
5813 CI));
5814
5815 // Based on the range information we know about the LHS, see if we can
5816 // simplify this comparison. For example, (x&4) < 8 is always true.
5817 const APInt &RHSVal = CI->getValue();
Chris Lattner38a50c92008-07-11 05:08:55 +00005818 switch (I.getPredicate()) { // LE/GE have been folded already.
5819 default: assert(0 && "Unknown icmp opcode!");
5820 case ICmpInst::ICMP_EQ:
5821 if (Max.ult(RHSVal) || Min.ugt(RHSVal))
5822 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5823 break;
5824 case ICmpInst::ICMP_NE:
5825 if (Max.ult(RHSVal) || Min.ugt(RHSVal))
5826 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5827 break;
5828 case ICmpInst::ICMP_ULT:
Chris Lattnerbd25b852008-07-11 05:40:05 +00005829 if (Max.ult(RHSVal)) // A <u C -> true iff max(A) < C
Chris Lattner38a50c92008-07-11 05:08:55 +00005830 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Chris Lattnerbd25b852008-07-11 05:40:05 +00005831 if (Min.uge(RHSVal)) // A <u C -> false iff min(A) >= C
Chris Lattner38a50c92008-07-11 05:08:55 +00005832 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Chris Lattnerbd25b852008-07-11 05:40:05 +00005833 if (RHSVal == Max) // A <u MAX -> A != MAX
5834 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
5835 if (RHSVal == Min+1) // A <u MIN+1 -> A == MIN
5836 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, SubOne(CI));
5837
5838 // (x <u 2147483648) -> (x >s -1) -> true if sign bit clear
5839 if (CI->isMinValue(true))
5840 return new ICmpInst(ICmpInst::ICMP_SGT, Op0,
5841 ConstantInt::getAllOnesValue(Op0->getType()));
Chris Lattner38a50c92008-07-11 05:08:55 +00005842 break;
5843 case ICmpInst::ICMP_UGT:
Chris Lattnerbd25b852008-07-11 05:40:05 +00005844 if (Min.ugt(RHSVal)) // A >u C -> true iff min(A) > C
Chris Lattner38a50c92008-07-11 05:08:55 +00005845 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Chris Lattnerbd25b852008-07-11 05:40:05 +00005846 if (Max.ule(RHSVal)) // A >u C -> false iff max(A) <= C
Chris Lattner38a50c92008-07-11 05:08:55 +00005847 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Chris Lattnerbd25b852008-07-11 05:40:05 +00005848
5849 if (RHSVal == Min) // A >u MIN -> A != MIN
5850 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
5851 if (RHSVal == Max-1) // A >u MAX-1 -> A == MAX
5852 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, AddOne(CI));
5853
5854 // (x >u 2147483647) -> (x <s 0) -> true if sign bit set
5855 if (CI->isMaxValue(true))
5856 return new ICmpInst(ICmpInst::ICMP_SLT, Op0,
5857 ConstantInt::getNullValue(Op0->getType()));
Chris Lattner38a50c92008-07-11 05:08:55 +00005858 break;
5859 case ICmpInst::ICMP_SLT:
Chris Lattnerbd25b852008-07-11 05:40:05 +00005860 if (Max.slt(RHSVal)) // A <s C -> true iff max(A) < C
Chris Lattner38a50c92008-07-11 05:08:55 +00005861 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Chris Lattner3994bed2008-07-11 06:40:29 +00005862 if (Min.sge(RHSVal)) // A <s C -> false iff min(A) >= C
Chris Lattner38a50c92008-07-11 05:08:55 +00005863 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Chris Lattnerbd25b852008-07-11 05:40:05 +00005864 if (RHSVal == Max) // A <s MAX -> A != MAX
5865 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
Chris Lattnerde89b502008-07-11 06:36:01 +00005866 if (RHSVal == Min+1) // A <s MIN+1 -> A == MIN
Chris Lattner13a69112008-07-11 06:38:16 +00005867 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, SubOne(CI));
Chris Lattner38a50c92008-07-11 05:08:55 +00005868 break;
5869 case ICmpInst::ICMP_SGT:
Chris Lattnerbd25b852008-07-11 05:40:05 +00005870 if (Min.sgt(RHSVal)) // A >s C -> true iff min(A) > C
Chris Lattner38a50c92008-07-11 05:08:55 +00005871 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Chris Lattnerbd25b852008-07-11 05:40:05 +00005872 if (Max.sle(RHSVal)) // A >s C -> false iff max(A) <= C
Chris Lattner38a50c92008-07-11 05:08:55 +00005873 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Chris Lattnerbd25b852008-07-11 05:40:05 +00005874
5875 if (RHSVal == Min) // A >s MIN -> A != MIN
5876 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
5877 if (RHSVal == Max-1) // A >s MAX-1 -> A == MAX
5878 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, AddOne(CI));
Chris Lattner38a50c92008-07-11 05:08:55 +00005879 break;
Chris Lattneree0f2802006-02-12 02:07:56 +00005880 }
Dan Gohmandafa9c62008-09-16 18:46:06 +00005881 }
5882
5883 // Test if the ICmpInst instruction is used exclusively by a select as
5884 // part of a minimum or maximum operation. If so, refrain from doing
5885 // any other folding. This helps out other analyses which understand
5886 // non-obfuscated minimum and maximum idioms, such as ScalarEvolution
5887 // and CodeGen. And in this case, at least one of the comparison
5888 // operands has at least one user besides the compare (the select),
5889 // which would often largely negate the benefit of folding anyway.
5890 if (I.hasOneUse())
5891 if (SelectInst *SI = dyn_cast<SelectInst>(*I.use_begin()))
5892 if ((SI->getOperand(1) == Op0 && SI->getOperand(2) == Op1) ||
5893 (SI->getOperand(2) == Op0 && SI->getOperand(1) == Op1))
5894 return 0;
5895
5896 // See if we are doing a comparison between a constant and an instruction that
5897 // can be folded into the comparison.
5898 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Reid Spencer266e42b2006-12-23 06:05:41 +00005899 // Since the RHS is a ConstantInt (CI), if the left hand side is an
Reid Spencer7e80b0b2006-10-26 06:15:43 +00005900 // instruction, see if that instruction also has constants so that the
Reid Spencer266e42b2006-12-23 06:05:41 +00005901 // instruction can be folded into the icmp
Chris Lattnere1e10e12004-05-25 06:32:08 +00005902 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
Chris Lattnera74deaf2007-04-03 17:43:25 +00005903 if (Instruction *Res = visitICmpInstWithInstAndIntCst(I, LHSI, CI))
5904 return Res;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00005905 }
5906
Chris Lattnera74deaf2007-04-03 17:43:25 +00005907 // Handle icmp with constant (but not simple integer constant) RHS
Chris Lattner77c32c32005-04-23 15:31:55 +00005908 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
5909 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5910 switch (LHSI->getOpcode()) {
Chris Lattnera816eee2005-05-01 04:42:15 +00005911 case Instruction::GetElementPtr:
5912 if (RHSC->isNullValue()) {
Reid Spencer266e42b2006-12-23 06:05:41 +00005913 // icmp pred GEP (P, int 0, int 0, int 0), null -> icmp pred P, null
Chris Lattnera816eee2005-05-01 04:42:15 +00005914 bool isAllZeros = true;
5915 for (unsigned i = 1, e = LHSI->getNumOperands(); i != e; ++i)
5916 if (!isa<Constant>(LHSI->getOperand(i)) ||
5917 !cast<Constant>(LHSI->getOperand(i))->isNullValue()) {
5918 isAllZeros = false;
5919 break;
5920 }
5921 if (isAllZeros)
Reid Spencer266e42b2006-12-23 06:05:41 +00005922 return new ICmpInst(I.getPredicate(), LHSI->getOperand(0),
Chris Lattnera816eee2005-05-01 04:42:15 +00005923 Constant::getNullValue(LHSI->getOperand(0)->getType()));
5924 }
5925 break;
5926
Chris Lattner77c32c32005-04-23 15:31:55 +00005927 case Instruction::PHI:
Chris Lattnerb4866ef2008-06-08 20:52:11 +00005928 // Only fold icmp into the PHI if the phi and fcmp are in the same
5929 // block. If in the same block, we're encouraging jump threading. If
5930 // not, we are just pessimizing the code by making an i1 phi.
5931 if (LHSI->getParent() == I.getParent())
5932 if (Instruction *NV = FoldOpIntoPhi(I))
5933 return NV;
Chris Lattner77c32c32005-04-23 15:31:55 +00005934 break;
Chris Lattner3dbe65f2007-04-06 18:57:34 +00005935 case Instruction::Select: {
Chris Lattner77c32c32005-04-23 15:31:55 +00005936 // If either operand of the select is a constant, we can fold the
5937 // comparison into the select arms, which will cause one to be
5938 // constant folded and the select turned into a bitwise or.
5939 Value *Op1 = 0, *Op2 = 0;
5940 if (LHSI->hasOneUse()) {
5941 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
5942 // Fold the known value into the constant operand.
Reid Spencer266e42b2006-12-23 06:05:41 +00005943 Op1 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
5944 // Insert a new ICmp of the other select operand.
5945 Op2 = InsertNewInstBefore(new ICmpInst(I.getPredicate(),
5946 LHSI->getOperand(2), RHSC,
5947 I.getName()), I);
Chris Lattner77c32c32005-04-23 15:31:55 +00005948 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
5949 // Fold the known value into the constant operand.
Reid Spencer266e42b2006-12-23 06:05:41 +00005950 Op2 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
5951 // Insert a new ICmp of the other select operand.
5952 Op1 = InsertNewInstBefore(new ICmpInst(I.getPredicate(),
5953 LHSI->getOperand(1), RHSC,
5954 I.getName()), I);
Chris Lattner77c32c32005-04-23 15:31:55 +00005955 }
5956 }
Jeff Cohen82639852005-04-23 21:38:35 +00005957
Chris Lattner77c32c32005-04-23 15:31:55 +00005958 if (Op1)
Gabor Greife9ecc682008-04-06 20:25:17 +00005959 return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
Chris Lattner77c32c32005-04-23 15:31:55 +00005960 break;
5961 }
Chris Lattner3dbe65f2007-04-06 18:57:34 +00005962 case Instruction::Malloc:
5963 // If we have (malloc != null), and if the malloc has a single use, we
5964 // can assume it is successful and remove the malloc.
5965 if (LHSI->hasOneUse() && isa<ConstantPointerNull>(RHSC)) {
5966 AddToWorkList(LHSI);
5967 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
Nick Lewycky79376f42008-05-17 07:33:39 +00005968 !I.isTrueWhenEqual()));
Chris Lattner3dbe65f2007-04-06 18:57:34 +00005969 }
5970 break;
5971 }
Chris Lattner77c32c32005-04-23 15:31:55 +00005972 }
5973
Reid Spencer266e42b2006-12-23 06:05:41 +00005974 // If we can optimize a 'icmp GEP, P' or 'icmp P, GEP', do so now.
Chris Lattner0798af32005-01-13 20:14:25 +00005975 if (User *GEP = dyn_castGetElementPtr(Op0))
Reid Spencer266e42b2006-12-23 06:05:41 +00005976 if (Instruction *NI = FoldGEPICmp(GEP, Op1, I.getPredicate(), I))
Chris Lattner0798af32005-01-13 20:14:25 +00005977 return NI;
5978 if (User *GEP = dyn_castGetElementPtr(Op1))
Reid Spencer266e42b2006-12-23 06:05:41 +00005979 if (Instruction *NI = FoldGEPICmp(GEP, Op0,
5980 ICmpInst::getSwappedPredicate(I.getPredicate()), I))
Chris Lattner0798af32005-01-13 20:14:25 +00005981 return NI;
5982
Reid Spencer266e42b2006-12-23 06:05:41 +00005983 // Test to see if the operands of the icmp are casted versions of other
Chris Lattner64d87b02007-01-06 01:45:59 +00005984 // values. If the ptr->ptr cast can be stripped off both arguments, we do so
5985 // now.
5986 if (BitCastInst *CI = dyn_cast<BitCastInst>(Op0)) {
5987 if (isa<PointerType>(Op0->getType()) &&
5988 (isa<Constant>(Op1) || isa<BitCastInst>(Op1))) {
Chris Lattner16930792003-11-03 04:25:02 +00005989 // We keep moving the cast from the left operand over to the right
5990 // operand, where it can often be eliminated completely.
Chris Lattner64d87b02007-01-06 01:45:59 +00005991 Op0 = CI->getOperand(0);
Misha Brukmanb1c93172005-04-21 23:48:37 +00005992
Chris Lattner64d87b02007-01-06 01:45:59 +00005993 // If operand #1 is a bitcast instruction, it must also be a ptr->ptr cast
5994 // so eliminate it as well.
5995 if (BitCastInst *CI2 = dyn_cast<BitCastInst>(Op1))
5996 Op1 = CI2->getOperand(0);
Misha Brukmanb1c93172005-04-21 23:48:37 +00005997
Chris Lattner16930792003-11-03 04:25:02 +00005998 // If Op1 is a constant, we can fold the cast into the constant.
Anton Korobeynikov1bfd1212008-02-20 11:26:25 +00005999 if (Op0->getType() != Op1->getType()) {
Chris Lattner16930792003-11-03 04:25:02 +00006000 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
Reid Spencerbb65ebf2006-12-12 23:36:14 +00006001 Op1 = ConstantExpr::getBitCast(Op1C, Op0->getType());
Chris Lattner16930792003-11-03 04:25:02 +00006002 } else {
Reid Spencer266e42b2006-12-23 06:05:41 +00006003 // Otherwise, cast the RHS right before the icmp
Chris Lattner5a866122008-01-13 22:23:22 +00006004 Op1 = InsertBitCastBefore(Op1, Op0->getType(), I);
Chris Lattner16930792003-11-03 04:25:02 +00006005 }
Anton Korobeynikov1bfd1212008-02-20 11:26:25 +00006006 }
Reid Spencer266e42b2006-12-23 06:05:41 +00006007 return new ICmpInst(I.getPredicate(), Op0, Op1);
Chris Lattner16930792003-11-03 04:25:02 +00006008 }
Chris Lattner64d87b02007-01-06 01:45:59 +00006009 }
6010
6011 if (isa<CastInst>(Op0)) {
Reid Spencer266e42b2006-12-23 06:05:41 +00006012 // Handle the special case of: icmp (cast bool to X), <cst>
Chris Lattner6444c372003-11-03 05:17:03 +00006013 // This comes up when you have code like
6014 // int X = A < B;
6015 // if (X) ...
6016 // For generality, we handle any zero-extension of any operand comparison
Chris Lattnerd1f46d32005-04-24 06:59:08 +00006017 // with a constant or another cast from the same type.
6018 if (isa<ConstantInt>(Op1) || isa<CastInst>(Op1))
Reid Spencer266e42b2006-12-23 06:05:41 +00006019 if (Instruction *R = visitICmpInstWithCastAndCast(I))
Chris Lattnerd1f46d32005-04-24 06:59:08 +00006020 return R;
Chris Lattner6444c372003-11-03 05:17:03 +00006021 }
Chris Lattnerf5c8a0b2006-02-27 01:44:11 +00006022
Nick Lewyckyf95b64a2008-07-11 07:20:53 +00006023 // See if it's the same type of instruction on the left and right.
6024 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
6025 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
Nick Lewycky99f45582008-08-21 05:56:10 +00006026 if (Op0I->getOpcode() == Op1I->getOpcode() && Op0I->hasOneUse() &&
6027 Op1I->hasOneUse() && Op0I->getOperand(1) == Op1I->getOperand(1) &&
6028 I.isEquality()) {
Nick Lewycky2fcb26c2008-09-03 06:24:21 +00006029 switch (Op0I->getOpcode()) {
Nick Lewyckyf95b64a2008-07-11 07:20:53 +00006030 default: break;
6031 case Instruction::Add:
6032 case Instruction::Sub:
6033 case Instruction::Xor:
Nick Lewycky99f45582008-08-21 05:56:10 +00006034 // a+x icmp eq/ne b+x --> a icmp b
6035 return new ICmpInst(I.getPredicate(), Op0I->getOperand(0),
6036 Op1I->getOperand(0));
Nick Lewyckyf95b64a2008-07-11 07:20:53 +00006037 break;
6038 case Instruction::Mul:
Nick Lewycky99f45582008-08-21 05:56:10 +00006039 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
6040 // a * Cst icmp eq/ne b * Cst --> a & Mask icmp b & Mask
6041 // Mask = -1 >> count-trailing-zeros(Cst).
6042 if (!CI->isZero() && !CI->isOne()) {
6043 const APInt &AP = CI->getValue();
6044 ConstantInt *Mask = ConstantInt::get(
6045 APInt::getLowBitsSet(AP.getBitWidth(),
6046 AP.getBitWidth() -
Nick Lewyckyf95b64a2008-07-11 07:20:53 +00006047 AP.countTrailingZeros()));
Nick Lewycky99f45582008-08-21 05:56:10 +00006048 Instruction *And1 = BinaryOperator::CreateAnd(Op0I->getOperand(0),
6049 Mask);
6050 Instruction *And2 = BinaryOperator::CreateAnd(Op1I->getOperand(0),
6051 Mask);
6052 InsertNewInstBefore(And1, I);
6053 InsertNewInstBefore(And2, I);
6054 return new ICmpInst(I.getPredicate(), And1, And2);
Nick Lewyckyf95b64a2008-07-11 07:20:53 +00006055 }
6056 }
6057 break;
6058 }
6059 }
6060 }
6061 }
6062
Chris Lattneraaba10e2008-05-09 05:19:28 +00006063 // ~x < ~y --> y < x
6064 { Value *A, *B;
6065 if (match(Op0, m_Not(m_Value(A))) &&
6066 match(Op1, m_Not(m_Value(B))))
6067 return new ICmpInst(I.getPredicate(), B, A);
6068 }
6069
Chris Lattnerb3f24c92006-09-18 04:22:48 +00006070 if (I.isEquality()) {
Chris Lattner17c7c032007-01-05 03:04:57 +00006071 Value *A, *B, *C, *D;
Chris Lattneraaba10e2008-05-09 05:19:28 +00006072
6073 // -x == -y --> x == y
6074 if (match(Op0, m_Neg(m_Value(A))) &&
6075 match(Op1, m_Neg(m_Value(B))))
6076 return new ICmpInst(I.getPredicate(), A, B);
6077
Chris Lattner17c7c032007-01-05 03:04:57 +00006078 if (match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
6079 if (A == Op1 || B == Op1) { // (A^B) == A -> B == 0
6080 Value *OtherVal = A == Op1 ? B : A;
6081 return new ICmpInst(I.getPredicate(), OtherVal,
6082 Constant::getNullValue(A->getType()));
6083 }
6084
6085 if (match(Op1, m_Xor(m_Value(C), m_Value(D)))) {
6086 // A^c1 == C^c2 --> A == C^(c1^c2)
Chris Lattner44152742008-11-16 05:38:51 +00006087 ConstantInt *C1, *C2;
6088 if (match(B, m_ConstantInt(C1)) &&
6089 match(D, m_ConstantInt(C2)) && Op1->hasOneUse()) {
6090 Constant *NC = ConstantInt::get(C1->getValue() ^ C2->getValue());
6091 Instruction *Xor = BinaryOperator::CreateXor(C, NC, "tmp");
6092 return new ICmpInst(I.getPredicate(), A,
6093 InsertNewInstBefore(Xor, I));
6094 }
Chris Lattner17c7c032007-01-05 03:04:57 +00006095
6096 // A^B == A^D -> B == D
6097 if (A == C) return new ICmpInst(I.getPredicate(), B, D);
6098 if (A == D) return new ICmpInst(I.getPredicate(), B, C);
6099 if (B == C) return new ICmpInst(I.getPredicate(), A, D);
6100 if (B == D) return new ICmpInst(I.getPredicate(), A, C);
6101 }
6102 }
6103
6104 if (match(Op1, m_Xor(m_Value(A), m_Value(B))) &&
6105 (A == Op0 || B == Op0)) {
Chris Lattnerf5c8a0b2006-02-27 01:44:11 +00006106 // A == (A^B) -> B == 0
6107 Value *OtherVal = A == Op0 ? B : A;
Reid Spencer266e42b2006-12-23 06:05:41 +00006108 return new ICmpInst(I.getPredicate(), OtherVal,
6109 Constant::getNullValue(A->getType()));
Chris Lattner17c7c032007-01-05 03:04:57 +00006110 }
Chris Lattner44152742008-11-16 05:38:51 +00006111
6112 // (A-B) == A -> B == 0
6113 if (match(Op0, m_Sub(m_Specific(Op1), m_Value(B))))
6114 return new ICmpInst(I.getPredicate(), B,
6115 Constant::getNullValue(B->getType()));
6116
6117 // A == (A-B) -> B == 0
6118 if (match(Op1, m_Sub(m_Specific(Op0), m_Value(B))))
Reid Spencer266e42b2006-12-23 06:05:41 +00006119 return new ICmpInst(I.getPredicate(), B,
6120 Constant::getNullValue(B->getType()));
Chris Lattnerd12a4bf2006-11-14 06:06:06 +00006121
Chris Lattnerd12a4bf2006-11-14 06:06:06 +00006122 // (X&Z) == (Y&Z) -> (X^Y) & Z == 0
6123 if (Op0->hasOneUse() && Op1->hasOneUse() &&
6124 match(Op0, m_And(m_Value(A), m_Value(B))) &&
6125 match(Op1, m_And(m_Value(C), m_Value(D)))) {
6126 Value *X = 0, *Y = 0, *Z = 0;
6127
6128 if (A == C) {
6129 X = B; Y = D; Z = A;
6130 } else if (A == D) {
6131 X = B; Y = C; Z = A;
6132 } else if (B == C) {
6133 X = A; Y = D; Z = B;
6134 } else if (B == D) {
6135 X = A; Y = C; Z = B;
6136 }
6137
6138 if (X) { // Build (X^Y) & Z
Gabor Greife1f6e4b2008-05-16 19:29:10 +00006139 Op1 = InsertNewInstBefore(BinaryOperator::CreateXor(X, Y, "tmp"), I);
6140 Op1 = InsertNewInstBefore(BinaryOperator::CreateAnd(Op1, Z, "tmp"), I);
Chris Lattnerd12a4bf2006-11-14 06:06:06 +00006141 I.setOperand(0, Op1);
6142 I.setOperand(1, Constant::getNullValue(Op1->getType()));
6143 return &I;
6144 }
6145 }
Chris Lattnerf5c8a0b2006-02-27 01:44:11 +00006146 }
Chris Lattner113f4f42002-06-25 16:13:24 +00006147 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00006148}
6149
Chris Lattner3bbec592007-06-20 23:46:26 +00006150
6151/// FoldICmpDivCst - Fold "icmp pred, ([su]div X, DivRHS), CmpRHS" where DivRHS
6152/// and CmpRHS are both known to be integer constants.
6153Instruction *InstCombiner::FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
6154 ConstantInt *DivRHS) {
6155 ConstantInt *CmpRHS = cast<ConstantInt>(ICI.getOperand(1));
6156 const APInt &CmpRHSV = CmpRHS->getValue();
6157
6158 // FIXME: If the operand types don't match the type of the divide
6159 // then don't attempt this transform. The code below doesn't have the
6160 // logic to deal with a signed divide and an unsigned compare (and
6161 // vice versa). This is because (x /s C1) <s C2 produces different
6162 // results than (x /s C1) <u C2 or (x /u C1) <s C2 or even
6163 // (x /u C1) <u C2. Simply casting the operands and result won't
6164 // work. :( The if statement below tests that condition and bails
6165 // if it finds it.
6166 bool DivIsSigned = DivI->getOpcode() == Instruction::SDiv;
6167 if (!ICI.isEquality() && DivIsSigned != ICI.isSignedPredicate())
6168 return 0;
6169 if (DivRHS->isZero())
Chris Lattnerfb032b12007-06-21 18:11:19 +00006170 return 0; // The ProdOV computation fails on divide by zero.
Chris Lattnerda435912008-10-11 22:55:00 +00006171 if (DivIsSigned && DivRHS->isAllOnesValue())
6172 return 0; // The overflow computation also screws up here
6173 if (DivRHS->isOne())
6174 return 0; // Not worth bothering, and eliminates some funny cases
6175 // with INT_MIN.
Chris Lattner3bbec592007-06-20 23:46:26 +00006176
6177 // Compute Prod = CI * DivRHS. We are essentially solving an equation
6178 // of form X/C1=C2. We solve for X by multiplying C1 (DivRHS) and
6179 // C2 (CI). By solving for X we can turn this into a range check
6180 // instead of computing a divide.
6181 ConstantInt *Prod = Multiply(CmpRHS, DivRHS);
6182
6183 // Determine if the product overflows by seeing if the product is
6184 // not equal to the divide. Make sure we do the same kind of divide
6185 // as in the LHS instruction that we're folding.
6186 bool ProdOV = (DivIsSigned ? ConstantExpr::getSDiv(Prod, DivRHS) :
6187 ConstantExpr::getUDiv(Prod, DivRHS)) != CmpRHS;
6188
6189 // Get the ICmp opcode
Chris Lattnerfb032b12007-06-21 18:11:19 +00006190 ICmpInst::Predicate Pred = ICI.getPredicate();
Chris Lattner3bbec592007-06-20 23:46:26 +00006191
Chris Lattnerfb032b12007-06-21 18:11:19 +00006192 // Figure out the interval that is being checked. For example, a comparison
6193 // like "X /u 5 == 0" is really checking that X is in the interval [0, 5).
6194 // Compute this interval based on the constants involved and the signedness of
6195 // the compare/divide. This computes a half-open interval, keeping track of
6196 // whether either value in the interval overflows. After analysis each
6197 // overflow variable is set to 0 if it's corresponding bound variable is valid
6198 // -1 if overflowed off the bottom end, or +1 if overflowed off the top end.
6199 int LoOverflow = 0, HiOverflow = 0;
6200 ConstantInt *LoBound = 0, *HiBound = 0;
6201
Chris Lattner3bbec592007-06-20 23:46:26 +00006202 if (!DivIsSigned) { // udiv
Chris Lattnerfb032b12007-06-21 18:11:19 +00006203 // e.g. X/5 op 3 --> [15, 20)
Chris Lattner3bbec592007-06-20 23:46:26 +00006204 LoBound = Prod;
Chris Lattnerfb032b12007-06-21 18:11:19 +00006205 HiOverflow = LoOverflow = ProdOV;
6206 if (!HiOverflow)
6207 HiOverflow = AddWithOverflow(HiBound, LoBound, DivRHS, false);
Dan Gohman1ee8dc92008-02-13 22:09:18 +00006208 } else if (DivRHS->getValue().isStrictlyPositive()) { // Divisor is > 0.
Chris Lattner3bbec592007-06-20 23:46:26 +00006209 if (CmpRHSV == 0) { // (X / pos) op 0
Chris Lattnerfb032b12007-06-21 18:11:19 +00006210 // Can't overflow. e.g. X/2 op 0 --> [-1, 2)
Chris Lattner3bbec592007-06-20 23:46:26 +00006211 LoBound = cast<ConstantInt>(ConstantExpr::getNeg(SubOne(DivRHS)));
6212 HiBound = DivRHS;
Dan Gohman1ee8dc92008-02-13 22:09:18 +00006213 } else if (CmpRHSV.isStrictlyPositive()) { // (X / pos) op pos
Chris Lattnerfb032b12007-06-21 18:11:19 +00006214 LoBound = Prod; // e.g. X/5 op 3 --> [15, 20)
6215 HiOverflow = LoOverflow = ProdOV;
6216 if (!HiOverflow)
6217 HiOverflow = AddWithOverflow(HiBound, Prod, DivRHS, true);
Chris Lattner3bbec592007-06-20 23:46:26 +00006218 } else { // (X / pos) op neg
Chris Lattnerfb032b12007-06-21 18:11:19 +00006219 // e.g. X/5 op -3 --> [-15-4, -15+1) --> [-19, -14)
Chris Lattner3bbec592007-06-20 23:46:26 +00006220 HiBound = AddOne(Prod);
Chris Lattnerda435912008-10-11 22:55:00 +00006221 LoOverflow = HiOverflow = ProdOV ? -1 : 0;
6222 if (!LoOverflow) {
6223 ConstantInt* DivNeg = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
6224 LoOverflow = AddWithOverflow(LoBound, HiBound, DivNeg,
6225 true) ? -1 : 0;
6226 }
Chris Lattner3bbec592007-06-20 23:46:26 +00006227 }
Dan Gohman1ee8dc92008-02-13 22:09:18 +00006228 } else if (DivRHS->getValue().isNegative()) { // Divisor is < 0.
Chris Lattner3bbec592007-06-20 23:46:26 +00006229 if (CmpRHSV == 0) { // (X / neg) op 0
Chris Lattnerfb032b12007-06-21 18:11:19 +00006230 // e.g. X/-5 op 0 --> [-4, 5)
Chris Lattner3bbec592007-06-20 23:46:26 +00006231 LoBound = AddOne(DivRHS);
6232 HiBound = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
Chris Lattnerfb032b12007-06-21 18:11:19 +00006233 if (HiBound == DivRHS) { // -INTMIN = INTMIN
6234 HiOverflow = 1; // [INTMIN+1, overflow)
6235 HiBound = 0; // e.g. X/INTMIN = 0 --> X > INTMIN
6236 }
Dan Gohman1ee8dc92008-02-13 22:09:18 +00006237 } else if (CmpRHSV.isStrictlyPositive()) { // (X / neg) op pos
Chris Lattnerfb032b12007-06-21 18:11:19 +00006238 // e.g. X/-5 op 3 --> [-19, -14)
Chris Lattnerda435912008-10-11 22:55:00 +00006239 HiBound = AddOne(Prod);
Chris Lattnerfb032b12007-06-21 18:11:19 +00006240 HiOverflow = LoOverflow = ProdOV ? -1 : 0;
Chris Lattner3bbec592007-06-20 23:46:26 +00006241 if (!LoOverflow)
Chris Lattnerda435912008-10-11 22:55:00 +00006242 LoOverflow = AddWithOverflow(LoBound, HiBound, DivRHS, true) ? -1 : 0;
Chris Lattner3bbec592007-06-20 23:46:26 +00006243 } else { // (X / neg) op neg
Chris Lattnerda435912008-10-11 22:55:00 +00006244 LoBound = Prod; // e.g. X/-5 op -3 --> [15, 20)
6245 LoOverflow = HiOverflow = ProdOV;
Dan Gohman9d9a4be2008-09-11 00:25:00 +00006246 if (!HiOverflow)
6247 HiOverflow = SubWithOverflow(HiBound, Prod, DivRHS, true);
Chris Lattner3bbec592007-06-20 23:46:26 +00006248 }
6249
Chris Lattnerfb032b12007-06-21 18:11:19 +00006250 // Dividing by a negative swaps the condition. LT <-> GT
6251 Pred = ICmpInst::getSwappedPredicate(Pred);
Chris Lattner3bbec592007-06-20 23:46:26 +00006252 }
6253
6254 Value *X = DivI->getOperand(0);
Chris Lattnerfb032b12007-06-21 18:11:19 +00006255 switch (Pred) {
Chris Lattner3bbec592007-06-20 23:46:26 +00006256 default: assert(0 && "Unhandled icmp opcode!");
6257 case ICmpInst::ICMP_EQ:
6258 if (LoOverflow && HiOverflow)
6259 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
6260 else if (HiOverflow)
Chris Lattnerfb032b12007-06-21 18:11:19 +00006261 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
Chris Lattner3bbec592007-06-20 23:46:26 +00006262 ICmpInst::ICMP_UGE, X, LoBound);
6263 else if (LoOverflow)
6264 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
6265 ICmpInst::ICMP_ULT, X, HiBound);
6266 else
Chris Lattnerfb032b12007-06-21 18:11:19 +00006267 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, true, ICI);
Chris Lattner3bbec592007-06-20 23:46:26 +00006268 case ICmpInst::ICMP_NE:
6269 if (LoOverflow && HiOverflow)
6270 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
6271 else if (HiOverflow)
Chris Lattnerfb032b12007-06-21 18:11:19 +00006272 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
Chris Lattner3bbec592007-06-20 23:46:26 +00006273 ICmpInst::ICMP_ULT, X, LoBound);
6274 else if (LoOverflow)
6275 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
6276 ICmpInst::ICMP_UGE, X, HiBound);
6277 else
Chris Lattnerfb032b12007-06-21 18:11:19 +00006278 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, false, ICI);
Chris Lattner3bbec592007-06-20 23:46:26 +00006279 case ICmpInst::ICMP_ULT:
6280 case ICmpInst::ICMP_SLT:
Chris Lattnerfb032b12007-06-21 18:11:19 +00006281 if (LoOverflow == +1) // Low bound is greater than input range.
6282 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
6283 if (LoOverflow == -1) // Low bound is less than input range.
Chris Lattner3bbec592007-06-20 23:46:26 +00006284 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
Chris Lattnerfb032b12007-06-21 18:11:19 +00006285 return new ICmpInst(Pred, X, LoBound);
Chris Lattner3bbec592007-06-20 23:46:26 +00006286 case ICmpInst::ICMP_UGT:
6287 case ICmpInst::ICMP_SGT:
Chris Lattnerfb032b12007-06-21 18:11:19 +00006288 if (HiOverflow == +1) // High bound greater than input range.
Chris Lattner3bbec592007-06-20 23:46:26 +00006289 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
Chris Lattnerfb032b12007-06-21 18:11:19 +00006290 else if (HiOverflow == -1) // High bound less than input range.
6291 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
6292 if (Pred == ICmpInst::ICMP_UGT)
Chris Lattner3bbec592007-06-20 23:46:26 +00006293 return new ICmpInst(ICmpInst::ICMP_UGE, X, HiBound);
6294 else
6295 return new ICmpInst(ICmpInst::ICMP_SGE, X, HiBound);
6296 }
6297}
6298
6299
Chris Lattnera74deaf2007-04-03 17:43:25 +00006300/// visitICmpInstWithInstAndIntCst - Handle "icmp (instr, intcst)".
6301///
6302Instruction *InstCombiner::visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
6303 Instruction *LHSI,
6304 ConstantInt *RHS) {
6305 const APInt &RHSV = RHS->getValue();
6306
6307 switch (LHSI->getOpcode()) {
Duncan Sandsf01a47c2007-04-04 06:42:45 +00006308 case Instruction::Xor: // (icmp pred (xor X, XorCST), CI)
Chris Lattnera74deaf2007-04-03 17:43:25 +00006309 if (ConstantInt *XorCST = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
6310 // If this is a comparison that tests the signbit (X < 0) or (x > -1),
6311 // fold the xor.
Anton Korobeynikov1bfd1212008-02-20 11:26:25 +00006312 if ((ICI.getPredicate() == ICmpInst::ICMP_SLT && RHSV == 0) ||
6313 (ICI.getPredicate() == ICmpInst::ICMP_SGT && RHSV.isAllOnesValue())) {
Chris Lattnera74deaf2007-04-03 17:43:25 +00006314 Value *CompareVal = LHSI->getOperand(0);
6315
6316 // If the sign bit of the XorCST is not set, there is no change to
6317 // the operation, just stop using the Xor.
6318 if (!XorCST->getValue().isNegative()) {
6319 ICI.setOperand(0, CompareVal);
6320 AddToWorkList(LHSI);
6321 return &ICI;
6322 }
6323
6324 // Was the old condition true if the operand is positive?
6325 bool isTrueIfPositive = ICI.getPredicate() == ICmpInst::ICMP_SGT;
6326
6327 // If so, the new one isn't.
6328 isTrueIfPositive ^= true;
6329
6330 if (isTrueIfPositive)
6331 return new ICmpInst(ICmpInst::ICMP_SGT, CompareVal, SubOne(RHS));
6332 else
6333 return new ICmpInst(ICmpInst::ICMP_SLT, CompareVal, AddOne(RHS));
6334 }
6335 }
6336 break;
6337 case Instruction::And: // (icmp pred (and X, AndCST), RHS)
6338 if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
6339 LHSI->getOperand(0)->hasOneUse()) {
6340 ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
6341
6342 // If the LHS is an AND of a truncating cast, we can widen the
6343 // and/compare to be the input width without changing the value
6344 // produced, eliminating a cast.
6345 if (TruncInst *Cast = dyn_cast<TruncInst>(LHSI->getOperand(0))) {
6346 // We can do this transformation if either the AND constant does not
6347 // have its sign bit set or if it is an equality comparison.
6348 // Extending a relational comparison when we're checking the sign
6349 // bit would not work.
6350 if (Cast->hasOneUse() &&
Anton Korobeynikov18991d72008-02-20 12:07:57 +00006351 (ICI.isEquality() ||
6352 (AndCST->getValue().isNonNegative() && RHSV.isNonNegative()))) {
Chris Lattnera74deaf2007-04-03 17:43:25 +00006353 uint32_t BitWidth =
6354 cast<IntegerType>(Cast->getOperand(0)->getType())->getBitWidth();
6355 APInt NewCST = AndCST->getValue();
6356 NewCST.zext(BitWidth);
6357 APInt NewCI = RHSV;
6358 NewCI.zext(BitWidth);
6359 Instruction *NewAnd =
Gabor Greife1f6e4b2008-05-16 19:29:10 +00006360 BinaryOperator::CreateAnd(Cast->getOperand(0),
Chris Lattnera74deaf2007-04-03 17:43:25 +00006361 ConstantInt::get(NewCST),LHSI->getName());
6362 InsertNewInstBefore(NewAnd, ICI);
6363 return new ICmpInst(ICI.getPredicate(), NewAnd,
6364 ConstantInt::get(NewCI));
6365 }
6366 }
6367
6368 // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
6369 // could exist), turn it into (X & (C2 << C1)) != (C3 << C1). This
6370 // happens a LOT in code produced by the C front-end, for bitfield
6371 // access.
6372 BinaryOperator *Shift = dyn_cast<BinaryOperator>(LHSI->getOperand(0));
6373 if (Shift && !Shift->isShift())
6374 Shift = 0;
6375
6376 ConstantInt *ShAmt;
6377 ShAmt = Shift ? dyn_cast<ConstantInt>(Shift->getOperand(1)) : 0;
6378 const Type *Ty = Shift ? Shift->getType() : 0; // Type of the shift.
6379 const Type *AndTy = AndCST->getType(); // Type of the and.
6380
6381 // We can fold this as long as we can't shift unknown bits
6382 // into the mask. This can only happen with signed shift
6383 // rights, as they sign-extend.
6384 if (ShAmt) {
6385 bool CanFold = Shift->isLogicalShift();
6386 if (!CanFold) {
6387 // To test for the bad case of the signed shr, see if any
6388 // of the bits shifted in could be tested after the mask.
6389 uint32_t TyBits = Ty->getPrimitiveSizeInBits();
6390 int ShAmtVal = TyBits - ShAmt->getLimitedValue(TyBits);
6391
6392 uint32_t BitWidth = AndTy->getPrimitiveSizeInBits();
6393 if ((APInt::getHighBitsSet(BitWidth, BitWidth-ShAmtVal) &
6394 AndCST->getValue()) == 0)
6395 CanFold = true;
6396 }
6397
6398 if (CanFold) {
6399 Constant *NewCst;
6400 if (Shift->getOpcode() == Instruction::Shl)
6401 NewCst = ConstantExpr::getLShr(RHS, ShAmt);
6402 else
6403 NewCst = ConstantExpr::getShl(RHS, ShAmt);
6404
6405 // Check to see if we are shifting out any of the bits being
6406 // compared.
6407 if (ConstantExpr::get(Shift->getOpcode(), NewCst, ShAmt) != RHS) {
6408 // If we shifted bits out, the fold is not going to work out.
6409 // As a special case, check to see if this means that the
6410 // result is always true or false now.
6411 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
6412 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
6413 if (ICI.getPredicate() == ICmpInst::ICMP_NE)
6414 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
6415 } else {
6416 ICI.setOperand(1, NewCst);
6417 Constant *NewAndCST;
6418 if (Shift->getOpcode() == Instruction::Shl)
6419 NewAndCST = ConstantExpr::getLShr(AndCST, ShAmt);
6420 else
6421 NewAndCST = ConstantExpr::getShl(AndCST, ShAmt);
6422 LHSI->setOperand(1, NewAndCST);
6423 LHSI->setOperand(0, Shift->getOperand(0));
6424 AddToWorkList(Shift); // Shift is dead.
6425 AddUsesToWorkList(ICI);
6426 return &ICI;
6427 }
6428 }
6429 }
6430
6431 // Turn ((X >> Y) & C) == 0 into (X & (C << Y)) == 0. The later is
6432 // preferable because it allows the C<<Y expression to be hoisted out
6433 // of a loop if Y is invariant and X is not.
6434 if (Shift && Shift->hasOneUse() && RHSV == 0 &&
6435 ICI.isEquality() && !Shift->isArithmeticShift() &&
6436 isa<Instruction>(Shift->getOperand(0))) {
6437 // Compute C << Y.
6438 Value *NS;
6439 if (Shift->getOpcode() == Instruction::LShr) {
Gabor Greife1f6e4b2008-05-16 19:29:10 +00006440 NS = BinaryOperator::CreateShl(AndCST,
Chris Lattnera74deaf2007-04-03 17:43:25 +00006441 Shift->getOperand(1), "tmp");
6442 } else {
6443 // Insert a logical shift.
Gabor Greife1f6e4b2008-05-16 19:29:10 +00006444 NS = BinaryOperator::CreateLShr(AndCST,
Chris Lattnera74deaf2007-04-03 17:43:25 +00006445 Shift->getOperand(1), "tmp");
6446 }
6447 InsertNewInstBefore(cast<Instruction>(NS), ICI);
6448
6449 // Compute X & (C << Y).
6450 Instruction *NewAnd =
Gabor Greife1f6e4b2008-05-16 19:29:10 +00006451 BinaryOperator::CreateAnd(Shift->getOperand(0), NS, LHSI->getName());
Chris Lattnera74deaf2007-04-03 17:43:25 +00006452 InsertNewInstBefore(NewAnd, ICI);
6453
6454 ICI.setOperand(0, NewAnd);
6455 return &ICI;
6456 }
6457 }
6458 break;
6459
Chris Lattner06205d52007-07-15 20:42:37 +00006460 case Instruction::Shl: { // (icmp pred (shl X, ShAmt), CI)
6461 ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
6462 if (!ShAmt) break;
6463
6464 uint32_t TypeBits = RHSV.getBitWidth();
6465
6466 // Check that the shift amount is in range. If not, don't perform
6467 // undefined shifts. When the shift is visited it will be
6468 // simplified.
6469 if (ShAmt->uge(TypeBits))
6470 break;
6471
6472 if (ICI.isEquality()) {
6473 // If we are comparing against bits always shifted out, the
6474 // comparison cannot succeed.
6475 Constant *Comp =
6476 ConstantExpr::getShl(ConstantExpr::getLShr(RHS, ShAmt), ShAmt);
6477 if (Comp != RHS) {// Comparing against a bit that we know is zero.
6478 bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
6479 Constant *Cst = ConstantInt::get(Type::Int1Ty, IsICMP_NE);
6480 return ReplaceInstUsesWith(ICI, Cst);
6481 }
6482
6483 if (LHSI->hasOneUse()) {
6484 // Otherwise strength reduce the shift into an and.
6485 uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
6486 Constant *Mask =
6487 ConstantInt::get(APInt::getLowBitsSet(TypeBits, TypeBits-ShAmtVal));
Chris Lattnera74deaf2007-04-03 17:43:25 +00006488
Chris Lattner06205d52007-07-15 20:42:37 +00006489 Instruction *AndI =
Gabor Greife1f6e4b2008-05-16 19:29:10 +00006490 BinaryOperator::CreateAnd(LHSI->getOperand(0),
Chris Lattner06205d52007-07-15 20:42:37 +00006491 Mask, LHSI->getName()+".mask");
6492 Value *And = InsertNewInstBefore(AndI, ICI);
6493 return new ICmpInst(ICI.getPredicate(), And,
6494 ConstantInt::get(RHSV.lshr(ShAmtVal)));
Chris Lattnera74deaf2007-04-03 17:43:25 +00006495 }
6496 }
Chris Lattner06205d52007-07-15 20:42:37 +00006497
6498 // Otherwise, if this is a comparison of the sign bit, simplify to and/test.
6499 bool TrueIfSigned = false;
6500 if (LHSI->hasOneUse() &&
6501 isSignBitCheck(ICI.getPredicate(), RHS, TrueIfSigned)) {
6502 // (X << 31) <s 0 --> (X&1) != 0
6503 Constant *Mask = ConstantInt::get(APInt(TypeBits, 1) <<
6504 (TypeBits-ShAmt->getZExtValue()-1));
6505 Instruction *AndI =
Gabor Greife1f6e4b2008-05-16 19:29:10 +00006506 BinaryOperator::CreateAnd(LHSI->getOperand(0),
Chris Lattner06205d52007-07-15 20:42:37 +00006507 Mask, LHSI->getName()+".mask");
6508 Value *And = InsertNewInstBefore(AndI, ICI);
6509
6510 return new ICmpInst(TrueIfSigned ? ICmpInst::ICMP_NE : ICmpInst::ICMP_EQ,
6511 And, Constant::getNullValue(And->getType()));
6512 }
Chris Lattnera74deaf2007-04-03 17:43:25 +00006513 break;
Chris Lattner06205d52007-07-15 20:42:37 +00006514 }
Chris Lattnera74deaf2007-04-03 17:43:25 +00006515
6516 case Instruction::LShr: // (icmp pred (shr X, ShAmt), CI)
Chris Lattner06205d52007-07-15 20:42:37 +00006517 case Instruction::AShr: {
Chris Lattnerc44160c2008-03-21 05:19:58 +00006518 // Only handle equality comparisons of shift-by-constant.
Chris Lattner06205d52007-07-15 20:42:37 +00006519 ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
Chris Lattnerc44160c2008-03-21 05:19:58 +00006520 if (!ShAmt || !ICI.isEquality()) break;
Chris Lattner06205d52007-07-15 20:42:37 +00006521
Chris Lattnerc44160c2008-03-21 05:19:58 +00006522 // Check that the shift amount is in range. If not, don't perform
6523 // undefined shifts. When the shift is visited it will be
6524 // simplified.
6525 uint32_t TypeBits = RHSV.getBitWidth();
6526 if (ShAmt->uge(TypeBits))
6527 break;
6528
6529 uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
Chris Lattner06205d52007-07-15 20:42:37 +00006530
Chris Lattnerc44160c2008-03-21 05:19:58 +00006531 // If we are comparing against bits always shifted out, the
6532 // comparison cannot succeed.
6533 APInt Comp = RHSV << ShAmtVal;
6534 if (LHSI->getOpcode() == Instruction::LShr)
6535 Comp = Comp.lshr(ShAmtVal);
6536 else
6537 Comp = Comp.ashr(ShAmtVal);
6538
6539 if (Comp != RHSV) { // Comparing against a bit that we know is zero.
6540 bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
6541 Constant *Cst = ConstantInt::get(Type::Int1Ty, IsICMP_NE);
6542 return ReplaceInstUsesWith(ICI, Cst);
6543 }
6544
6545 // Otherwise, check to see if the bits shifted out are known to be zero.
6546 // If so, we can compare against the unshifted value:
6547 // (X & 4) >> 1 == 2 --> (X & 4) == 4.
Evan Cheng1c89ca72008-04-23 00:38:06 +00006548 if (LHSI->hasOneUse() &&
6549 MaskedValueIsZero(LHSI->getOperand(0),
Chris Lattnerc44160c2008-03-21 05:19:58 +00006550 APInt::getLowBitsSet(Comp.getBitWidth(), ShAmtVal))) {
6551 return new ICmpInst(ICI.getPredicate(), LHSI->getOperand(0),
6552 ConstantExpr::getShl(RHS, ShAmt));
6553 }
Chris Lattner06205d52007-07-15 20:42:37 +00006554
Evan Cheng1c89ca72008-04-23 00:38:06 +00006555 if (LHSI->hasOneUse()) {
Chris Lattnerc44160c2008-03-21 05:19:58 +00006556 // Otherwise strength reduce the shift into an and.
6557 APInt Val(APInt::getHighBitsSet(TypeBits, TypeBits - ShAmtVal));
6558 Constant *Mask = ConstantInt::get(Val);
Chris Lattner06205d52007-07-15 20:42:37 +00006559
Chris Lattnerc44160c2008-03-21 05:19:58 +00006560 Instruction *AndI =
Gabor Greife1f6e4b2008-05-16 19:29:10 +00006561 BinaryOperator::CreateAnd(LHSI->getOperand(0),
Chris Lattnerc44160c2008-03-21 05:19:58 +00006562 Mask, LHSI->getName()+".mask");
6563 Value *And = InsertNewInstBefore(AndI, ICI);
6564 return new ICmpInst(ICI.getPredicate(), And,
6565 ConstantExpr::getShl(RHS, ShAmt));
Chris Lattnera74deaf2007-04-03 17:43:25 +00006566 }
6567 break;
Chris Lattner06205d52007-07-15 20:42:37 +00006568 }
Chris Lattnera74deaf2007-04-03 17:43:25 +00006569
6570 case Instruction::SDiv:
6571 case Instruction::UDiv:
6572 // Fold: icmp pred ([us]div X, C1), C2 -> range test
6573 // Fold this div into the comparison, producing a range check.
6574 // Determine, based on the divide type, what the range is being
6575 // checked. If there is an overflow on the low or high side, remember
6576 // it, otherwise compute the range [low, hi) bounding the new value.
6577 // See: InsertRangeTest above for the kinds of replacements possible.
Chris Lattner3bbec592007-06-20 23:46:26 +00006578 if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1)))
6579 if (Instruction *R = FoldICmpDivCst(ICI, cast<BinaryOperator>(LHSI),
6580 DivRHS))
6581 return R;
Chris Lattnera74deaf2007-04-03 17:43:25 +00006582 break;
Nick Lewycky3b592142008-02-03 16:33:09 +00006583
6584 case Instruction::Add:
6585 // Fold: icmp pred (add, X, C1), C2
6586
6587 if (!ICI.isEquality()) {
6588 ConstantInt *LHSC = dyn_cast<ConstantInt>(LHSI->getOperand(1));
6589 if (!LHSC) break;
6590 const APInt &LHSV = LHSC->getValue();
6591
6592 ConstantRange CR = ICI.makeConstantRange(ICI.getPredicate(), RHSV)
6593 .subtract(LHSV);
6594
6595 if (ICI.isSignedPredicate()) {
6596 if (CR.getLower().isSignBit()) {
6597 return new ICmpInst(ICmpInst::ICMP_SLT, LHSI->getOperand(0),
6598 ConstantInt::get(CR.getUpper()));
6599 } else if (CR.getUpper().isSignBit()) {
6600 return new ICmpInst(ICmpInst::ICMP_SGE, LHSI->getOperand(0),
6601 ConstantInt::get(CR.getLower()));
6602 }
6603 } else {
6604 if (CR.getLower().isMinValue()) {
6605 return new ICmpInst(ICmpInst::ICMP_ULT, LHSI->getOperand(0),
6606 ConstantInt::get(CR.getUpper()));
6607 } else if (CR.getUpper().isMinValue()) {
6608 return new ICmpInst(ICmpInst::ICMP_UGE, LHSI->getOperand(0),
6609 ConstantInt::get(CR.getLower()));
6610 }
6611 }
6612 }
6613 break;
Chris Lattnera74deaf2007-04-03 17:43:25 +00006614 }
6615
6616 // Simplify icmp_eq and icmp_ne instructions with integer constant RHS.
6617 if (ICI.isEquality()) {
6618 bool isICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
6619
6620 // If the first operand is (add|sub|and|or|xor|rem) with a constant, and
6621 // the second operand is a constant, simplify a bit.
6622 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(LHSI)) {
6623 switch (BO->getOpcode()) {
6624 case Instruction::SRem:
6625 // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
6626 if (RHSV == 0 && isa<ConstantInt>(BO->getOperand(1)) &&BO->hasOneUse()){
6627 const APInt &V = cast<ConstantInt>(BO->getOperand(1))->getValue();
6628 if (V.sgt(APInt(V.getBitWidth(), 1)) && V.isPowerOf2()) {
6629 Instruction *NewRem =
Gabor Greife1f6e4b2008-05-16 19:29:10 +00006630 BinaryOperator::CreateURem(BO->getOperand(0), BO->getOperand(1),
Chris Lattnera74deaf2007-04-03 17:43:25 +00006631 BO->getName());
6632 InsertNewInstBefore(NewRem, ICI);
6633 return new ICmpInst(ICI.getPredicate(), NewRem,
6634 Constant::getNullValue(BO->getType()));
6635 }
6636 }
6637 break;
6638 case Instruction::Add:
6639 // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
6640 if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
6641 if (BO->hasOneUse())
6642 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
6643 Subtract(RHS, BOp1C));
6644 } else if (RHSV == 0) {
6645 // Replace ((add A, B) != 0) with (A != -B) if A or B is
6646 // efficiently invertible, or if the add has just this one use.
6647 Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
6648
6649 if (Value *NegVal = dyn_castNegVal(BOp1))
6650 return new ICmpInst(ICI.getPredicate(), BOp0, NegVal);
6651 else if (Value *NegVal = dyn_castNegVal(BOp0))
6652 return new ICmpInst(ICI.getPredicate(), NegVal, BOp1);
6653 else if (BO->hasOneUse()) {
Gabor Greife1f6e4b2008-05-16 19:29:10 +00006654 Instruction *Neg = BinaryOperator::CreateNeg(BOp1);
Chris Lattnera74deaf2007-04-03 17:43:25 +00006655 InsertNewInstBefore(Neg, ICI);
6656 Neg->takeName(BO);
6657 return new ICmpInst(ICI.getPredicate(), BOp0, Neg);
6658 }
6659 }
6660 break;
6661 case Instruction::Xor:
6662 // For the xor case, we can xor two constants together, eliminating
6663 // the explicit xor.
6664 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
6665 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
6666 ConstantExpr::getXor(RHS, BOC));
6667
6668 // FALLTHROUGH
6669 case Instruction::Sub:
6670 // Replace (([sub|xor] A, B) != 0) with (A != B)
6671 if (RHSV == 0)
6672 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
6673 BO->getOperand(1));
6674 break;
6675
6676 case Instruction::Or:
6677 // If bits are being or'd in that are not present in the constant we
6678 // are comparing against, then the comparison could never succeed!
6679 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
6680 Constant *NotCI = ConstantExpr::getNot(RHS);
6681 if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
6682 return ReplaceInstUsesWith(ICI, ConstantInt::get(Type::Int1Ty,
6683 isICMP_NE));
6684 }
6685 break;
6686
6687 case Instruction::And:
6688 if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
6689 // If bits are being compared against that are and'd out, then the
6690 // comparison can never succeed!
6691 if ((RHSV & ~BOC->getValue()) != 0)
6692 return ReplaceInstUsesWith(ICI, ConstantInt::get(Type::Int1Ty,
6693 isICMP_NE));
6694
6695 // If we have ((X & C) == C), turn it into ((X & C) != 0).
6696 if (RHS == BOC && RHSV.isPowerOf2())
6697 return new ICmpInst(isICMP_NE ? ICmpInst::ICMP_EQ :
6698 ICmpInst::ICMP_NE, LHSI,
6699 Constant::getNullValue(RHS->getType()));
6700
6701 // Replace (and X, (1 << size(X)-1) != 0) with x s< 0
Chris Lattnera12a6de2008-06-02 01:29:46 +00006702 if (BOC->getValue().isSignBit()) {
Chris Lattnera74deaf2007-04-03 17:43:25 +00006703 Value *X = BO->getOperand(0);
6704 Constant *Zero = Constant::getNullValue(X->getType());
6705 ICmpInst::Predicate pred = isICMP_NE ?
6706 ICmpInst::ICMP_SLT : ICmpInst::ICMP_SGE;
6707 return new ICmpInst(pred, X, Zero);
6708 }
6709
6710 // ((X & ~7) == 0) --> X < 8
6711 if (RHSV == 0 && isHighOnes(BOC)) {
6712 Value *X = BO->getOperand(0);
6713 Constant *NegX = ConstantExpr::getNeg(BOC);
6714 ICmpInst::Predicate pred = isICMP_NE ?
6715 ICmpInst::ICMP_UGE : ICmpInst::ICMP_ULT;
6716 return new ICmpInst(pred, X, NegX);
6717 }
6718 }
6719 default: break;
6720 }
6721 } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(LHSI)) {
6722 // Handle icmp {eq|ne} <intrinsic>, intcst.
6723 if (II->getIntrinsicID() == Intrinsic::bswap) {
6724 AddToWorkList(II);
6725 ICI.setOperand(0, II->getOperand(1));
6726 ICI.setOperand(1, ConstantInt::get(RHSV.byteSwap()));
6727 return &ICI;
6728 }
6729 }
6730 } else { // Not a ICMP_EQ/ICMP_NE
Chris Lattner28d921d2007-04-14 23:32:02 +00006731 // If the LHS is a cast from an integral value of the same size,
6732 // then since we know the RHS is a constant, try to simlify.
Chris Lattnera74deaf2007-04-03 17:43:25 +00006733 if (CastInst *Cast = dyn_cast<CastInst>(LHSI)) {
6734 Value *CastOp = Cast->getOperand(0);
6735 const Type *SrcTy = CastOp->getType();
6736 uint32_t SrcTySize = SrcTy->getPrimitiveSizeInBits();
6737 if (SrcTy->isInteger() &&
6738 SrcTySize == Cast->getType()->getPrimitiveSizeInBits()) {
6739 // If this is an unsigned comparison, try to make the comparison use
6740 // smaller constant values.
6741 if (ICI.getPredicate() == ICmpInst::ICMP_ULT && RHSV.isSignBit()) {
6742 // X u< 128 => X s> -1
6743 return new ICmpInst(ICmpInst::ICMP_SGT, CastOp,
6744 ConstantInt::get(APInt::getAllOnesValue(SrcTySize)));
6745 } else if (ICI.getPredicate() == ICmpInst::ICMP_UGT &&
6746 RHSV == APInt::getSignedMaxValue(SrcTySize)) {
6747 // X u> 127 => X s< 0
6748 return new ICmpInst(ICmpInst::ICMP_SLT, CastOp,
6749 Constant::getNullValue(SrcTy));
6750 }
6751 }
6752 }
6753 }
6754 return 0;
6755}
6756
6757/// visitICmpInstWithCastAndCast - Handle icmp (cast x to y), (cast/cst).
6758/// We only handle extending casts so far.
6759///
Reid Spencer266e42b2006-12-23 06:05:41 +00006760Instruction *InstCombiner::visitICmpInstWithCastAndCast(ICmpInst &ICI) {
6761 const CastInst *LHSCI = cast<CastInst>(ICI.getOperand(0));
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006762 Value *LHSCIOp = LHSCI->getOperand(0);
6763 const Type *SrcTy = LHSCIOp->getType();
Reid Spencer266e42b2006-12-23 06:05:41 +00006764 const Type *DestTy = LHSCI->getType();
Chris Lattnerd1f46d32005-04-24 06:59:08 +00006765 Value *RHSCIOp;
6766
Chris Lattner5aa73fe2007-05-05 22:41:33 +00006767 // Turn icmp (ptrtoint x), (ptrtoint/c) into a compare of the input if the
6768 // integer type is the same size as the pointer type.
6769 if (LHSCI->getOpcode() == Instruction::PtrToInt &&
6770 getTargetData().getPointerSizeInBits() ==
6771 cast<IntegerType>(DestTy)->getBitWidth()) {
6772 Value *RHSOp = 0;
6773 if (Constant *RHSC = dyn_cast<Constant>(ICI.getOperand(1))) {
Chris Lattner9b35b3e2007-05-06 07:24:03 +00006774 RHSOp = ConstantExpr::getIntToPtr(RHSC, SrcTy);
Chris Lattner5aa73fe2007-05-05 22:41:33 +00006775 } else if (PtrToIntInst *RHSC = dyn_cast<PtrToIntInst>(ICI.getOperand(1))) {
6776 RHSOp = RHSC->getOperand(0);
6777 // If the pointer types don't match, insert a bitcast.
6778 if (LHSCIOp->getType() != RHSOp->getType())
Chris Lattner5a866122008-01-13 22:23:22 +00006779 RHSOp = InsertBitCastBefore(RHSOp, LHSCIOp->getType(), ICI);
Chris Lattner5aa73fe2007-05-05 22:41:33 +00006780 }
6781
6782 if (RHSOp)
6783 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSOp);
6784 }
6785
6786 // The code below only handles extension cast instructions, so far.
6787 // Enforce this.
Reid Spencer266e42b2006-12-23 06:05:41 +00006788 if (LHSCI->getOpcode() != Instruction::ZExt &&
6789 LHSCI->getOpcode() != Instruction::SExt)
Chris Lattner03f06f12005-01-17 03:20:02 +00006790 return 0;
6791
Reid Spencer266e42b2006-12-23 06:05:41 +00006792 bool isSignedExt = LHSCI->getOpcode() == Instruction::SExt;
6793 bool isSignedCmp = ICI.isSignedPredicate();
Chris Lattnerd1f46d32005-04-24 06:59:08 +00006794
Reid Spencer266e42b2006-12-23 06:05:41 +00006795 if (CastInst *CI = dyn_cast<CastInst>(ICI.getOperand(1))) {
Chris Lattnerd1f46d32005-04-24 06:59:08 +00006796 // Not an extension from the same type?
6797 RHSCIOp = CI->getOperand(0);
Reid Spencer266e42b2006-12-23 06:05:41 +00006798 if (RHSCIOp->getType() != LHSCIOp->getType())
6799 return 0;
Chris Lattner387bf3f2007-01-13 23:11:38 +00006800
Nick Lewycky8ea81e82008-01-28 03:48:02 +00006801 // If the signedness of the two casts doesn't agree (i.e. one is a sext
Chris Lattner387bf3f2007-01-13 23:11:38 +00006802 // and the other is a zext), then we can't handle this.
6803 if (CI->getOpcode() != LHSCI->getOpcode())
6804 return 0;
6805
Nick Lewycky8ea81e82008-01-28 03:48:02 +00006806 // Deal with equality cases early.
6807 if (ICI.isEquality())
6808 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
6809
6810 // A signed comparison of sign extended values simplifies into a
6811 // signed comparison.
6812 if (isSignedCmp && isSignedExt)
6813 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
6814
6815 // The other three cases all fold into an unsigned comparison.
6816 return new ICmpInst(ICI.getUnsignedPredicate(), LHSCIOp, RHSCIOp);
Reid Spencer279fa252004-11-28 21:31:15 +00006817 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00006818
Reid Spencer266e42b2006-12-23 06:05:41 +00006819 // If we aren't dealing with a constant on the RHS, exit early
6820 ConstantInt *CI = dyn_cast<ConstantInt>(ICI.getOperand(1));
6821 if (!CI)
6822 return 0;
6823
6824 // Compute the constant that would happen if we truncated to SrcTy then
6825 // reextended to DestTy.
6826 Constant *Res1 = ConstantExpr::getTrunc(CI, SrcTy);
6827 Constant *Res2 = ConstantExpr::getCast(LHSCI->getOpcode(), Res1, DestTy);
6828
6829 // If the re-extended constant didn't change...
6830 if (Res2 == CI) {
6831 // Make sure that sign of the Cmp and the sign of the Cast are the same.
6832 // For example, we might have:
6833 // %A = sext short %X to uint
6834 // %B = icmp ugt uint %A, 1330
6835 // It is incorrect to transform this into
6836 // %B = icmp ugt short %X, 1330
6837 // because %A may have negative value.
6838 //
Chris Lattner4fa8bb32008-07-11 04:09:09 +00006839 // However, we allow this when the compare is EQ/NE, because they are
6840 // signless.
6841 if (isSignedExt == isSignedCmp || ICI.isEquality())
Reid Spencer266e42b2006-12-23 06:05:41 +00006842 return new ICmpInst(ICI.getPredicate(), LHSCIOp, Res1);
Chris Lattner4fa8bb32008-07-11 04:09:09 +00006843 return 0;
Reid Spencer266e42b2006-12-23 06:05:41 +00006844 }
6845
6846 // The re-extended constant changed so the constant cannot be represented
6847 // in the shorter type. Consequently, we cannot emit a simple comparison.
6848
6849 // First, handle some easy cases. We know the result cannot be equal at this
6850 // point so handle the ICI.isEquality() cases
6851 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
Zhou Sheng75b871f2007-01-11 12:24:14 +00006852 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
Reid Spencer266e42b2006-12-23 06:05:41 +00006853 if (ICI.getPredicate() == ICmpInst::ICMP_NE)
Zhou Sheng75b871f2007-01-11 12:24:14 +00006854 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
Reid Spencer266e42b2006-12-23 06:05:41 +00006855
6856 // Evaluate the comparison for LT (we invert for GT below). LE and GE cases
6857 // should have been folded away previously and not enter in here.
6858 Value *Result;
6859 if (isSignedCmp) {
6860 // We're performing a signed comparison.
Reid Spencerc3e3b8a2007-03-22 20:36:03 +00006861 if (cast<ConstantInt>(CI)->getValue().isNegative())
Zhou Sheng75b871f2007-01-11 12:24:14 +00006862 Result = ConstantInt::getFalse(); // X < (small) --> false
Reid Spencer266e42b2006-12-23 06:05:41 +00006863 else
Zhou Sheng75b871f2007-01-11 12:24:14 +00006864 Result = ConstantInt::getTrue(); // X < (large) --> true
Reid Spencer266e42b2006-12-23 06:05:41 +00006865 } else {
6866 // We're performing an unsigned comparison.
6867 if (isSignedExt) {
6868 // We're performing an unsigned comp with a sign extended value.
6869 // This is true if the input is >= 0. [aka >s -1]
Zhou Sheng75b871f2007-01-11 12:24:14 +00006870 Constant *NegOne = ConstantInt::getAllOnesValue(SrcTy);
Reid Spencer266e42b2006-12-23 06:05:41 +00006871 Result = InsertNewInstBefore(new ICmpInst(ICmpInst::ICMP_SGT, LHSCIOp,
6872 NegOne, ICI.getName()), ICI);
6873 } else {
6874 // Unsigned extend & unsigned compare -> always true.
Zhou Sheng75b871f2007-01-11 12:24:14 +00006875 Result = ConstantInt::getTrue();
Reid Spencer266e42b2006-12-23 06:05:41 +00006876 }
6877 }
6878
6879 // Finally, return the value computed.
6880 if (ICI.getPredicate() == ICmpInst::ICMP_ULT ||
Chris Lattner4fa8bb32008-07-11 04:09:09 +00006881 ICI.getPredicate() == ICmpInst::ICMP_SLT)
Reid Spencer266e42b2006-12-23 06:05:41 +00006882 return ReplaceInstUsesWith(ICI, Result);
Chris Lattner4fa8bb32008-07-11 04:09:09 +00006883
6884 assert((ICI.getPredicate()==ICmpInst::ICMP_UGT ||
6885 ICI.getPredicate()==ICmpInst::ICMP_SGT) &&
6886 "ICmp should be folded!");
6887 if (Constant *CI = dyn_cast<Constant>(Result))
6888 return ReplaceInstUsesWith(ICI, ConstantExpr::getNot(CI));
6889 return BinaryOperator::CreateNot(Result);
Chris Lattnerd1f46d32005-04-24 06:59:08 +00006890}
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00006891
Reid Spencer2341c222007-02-02 02:16:23 +00006892Instruction *InstCombiner::visitShl(BinaryOperator &I) {
6893 return commonShiftTransforms(I);
6894}
6895
6896Instruction *InstCombiner::visitLShr(BinaryOperator &I) {
6897 return commonShiftTransforms(I);
6898}
6899
6900Instruction *InstCombiner::visitAShr(BinaryOperator &I) {
Chris Lattner0ccb6632007-12-06 01:59:46 +00006901 if (Instruction *R = commonShiftTransforms(I))
6902 return R;
6903
6904 Value *Op0 = I.getOperand(0);
6905
6906 // ashr int -1, X = -1 (for any arithmetic shift rights of ~0)
6907 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
6908 if (CSI->isAllOnesValue())
6909 return ReplaceInstUsesWith(I, CSI);
6910
6911 // See if we can turn a signed shr into an unsigned shr.
Nate Begemanfecbc8c2008-07-29 15:49:41 +00006912 if (!isa<VectorType>(I.getType()) &&
6913 MaskedValueIsZero(Op0,
Chris Lattner0ccb6632007-12-06 01:59:46 +00006914 APInt::getSignBit(I.getType()->getPrimitiveSizeInBits())))
Gabor Greife1f6e4b2008-05-16 19:29:10 +00006915 return BinaryOperator::CreateLShr(Op0, I.getOperand(1));
Chris Lattner0ccb6632007-12-06 01:59:46 +00006916
6917 return 0;
Reid Spencer2341c222007-02-02 02:16:23 +00006918}
6919
6920Instruction *InstCombiner::commonShiftTransforms(BinaryOperator &I) {
6921 assert(I.getOperand(1)->getType() == I.getOperand(0)->getType());
Chris Lattner113f4f42002-06-25 16:13:24 +00006922 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00006923
6924 // shl X, 0 == X and shr X, 0 == X
6925 // shl 0, X == 0 and shr 0, X == 0
Reid Spencer2341c222007-02-02 02:16:23 +00006926 if (Op1 == Constant::getNullValue(Op1->getType()) ||
Chris Lattnere6794492002-08-12 21:17:25 +00006927 Op0 == Constant::getNullValue(Op0->getType()))
6928 return ReplaceInstUsesWith(I, Op0);
Chris Lattnerf5b4ef72006-02-12 08:07:37 +00006929
Reid Spencer266e42b2006-12-23 06:05:41 +00006930 if (isa<UndefValue>(Op0)) {
6931 if (I.getOpcode() == Instruction::AShr) // undef >>s X -> undef
Chris Lattner67f05452004-10-16 23:28:04 +00006932 return ReplaceInstUsesWith(I, Op0);
Reid Spencer266e42b2006-12-23 06:05:41 +00006933 else // undef << X -> 0, undef >>u X -> 0
Chris Lattner81a7a232004-10-16 18:11:37 +00006934 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
6935 }
6936 if (isa<UndefValue>(Op1)) {
Reid Spencer266e42b2006-12-23 06:05:41 +00006937 if (I.getOpcode() == Instruction::AShr) // X >>s undef -> X
6938 return ReplaceInstUsesWith(I, Op0);
6939 else // X << undef, X >>u undef -> 0
Chris Lattner81a7a232004-10-16 18:11:37 +00006940 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner81a7a232004-10-16 18:11:37 +00006941 }
6942
Chris Lattner183b3362004-04-09 19:05:30 +00006943 // Try to fold constant and into select arguments.
6944 if (isa<Constant>(Op0))
6945 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner86102b82005-01-01 16:22:27 +00006946 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00006947 return R;
6948
Reid Spencere0fc4df2006-10-20 07:07:24 +00006949 if (ConstantInt *CUI = dyn_cast<ConstantInt>(Op1))
Reid Spencerc635f472006-12-31 05:48:39 +00006950 if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
6951 return Res;
Chris Lattner14553932006-01-06 07:12:35 +00006952 return 0;
6953}
6954
Reid Spencere0fc4df2006-10-20 07:07:24 +00006955Instruction *InstCombiner::FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
Reid Spencer2341c222007-02-02 02:16:23 +00006956 BinaryOperator &I) {
Reid Spencer266e42b2006-12-23 06:05:41 +00006957 bool isLeftShift = I.getOpcode() == Instruction::Shl;
Chris Lattner14553932006-01-06 07:12:35 +00006958
Chris Lattnerf5b4ef72006-02-12 08:07:37 +00006959 // See if we can simplify any instructions used by the instruction whose sole
6960 // purpose is to compute bits we don't care about.
Reid Spencer6274c722007-03-23 18:46:34 +00006961 uint32_t TypeBits = Op0->getType()->getPrimitiveSizeInBits();
6962 APInt KnownZero(TypeBits, 0), KnownOne(TypeBits, 0);
6963 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(TypeBits),
Chris Lattnerf5b4ef72006-02-12 08:07:37 +00006964 KnownZero, KnownOne))
6965 return &I;
6966
Chris Lattner14553932006-01-06 07:12:35 +00006967 // shl uint X, 32 = 0 and shr ubyte Y, 9 = 0, ... just don't eliminate shr
6968 // of a signed value.
6969 //
Zhou Shengb25806f2007-03-30 09:29:48 +00006970 if (Op1->uge(TypeBits)) {
Chris Lattnerd5fea612007-02-02 05:29:55 +00006971 if (I.getOpcode() != Instruction::AShr)
Chris Lattner14553932006-01-06 07:12:35 +00006972 return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
6973 else {
Chris Lattnerd5fea612007-02-02 05:29:55 +00006974 I.setOperand(1, ConstantInt::get(I.getType(), TypeBits-1));
Chris Lattner14553932006-01-06 07:12:35 +00006975 return &I;
Chris Lattnerf5ce2542004-02-23 20:30:06 +00006976 }
Chris Lattner14553932006-01-06 07:12:35 +00006977 }
6978
6979 // ((X*C1) << C2) == (X * (C1 << C2))
6980 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
6981 if (BO->getOpcode() == Instruction::Mul && isLeftShift)
6982 if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
Gabor Greife1f6e4b2008-05-16 19:29:10 +00006983 return BinaryOperator::CreateMul(BO->getOperand(0),
Chris Lattner14553932006-01-06 07:12:35 +00006984 ConstantExpr::getShl(BOOp, Op1));
6985
6986 // Try to fold constant and into select arguments.
6987 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
6988 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
6989 return R;
6990 if (isa<PHINode>(Op0))
6991 if (Instruction *NV = FoldOpIntoPhi(I))
6992 return NV;
6993
Chris Lattner74b2ab52007-12-22 09:07:47 +00006994 // Fold shift2(trunc(shift1(x,c1)), c2) -> trunc(shift2(shift1(x,c1),c2))
6995 if (TruncInst *TI = dyn_cast<TruncInst>(Op0)) {
6996 Instruction *TrOp = dyn_cast<Instruction>(TI->getOperand(0));
6997 // If 'shift2' is an ashr, we would have to get the sign bit into a funny
6998 // place. Don't try to do this transformation in this case. Also, we
6999 // require that the input operand is a shift-by-constant so that we have
7000 // confidence that the shifts will get folded together. We could do this
7001 // xform in more cases, but it is unlikely to be profitable.
7002 if (TrOp && I.isLogicalShift() && TrOp->isShift() &&
7003 isa<ConstantInt>(TrOp->getOperand(1))) {
7004 // Okay, we'll do this xform. Make the shift of shift.
7005 Constant *ShAmt = ConstantExpr::getZExt(Op1, TrOp->getType());
Gabor Greife1f6e4b2008-05-16 19:29:10 +00007006 Instruction *NSh = BinaryOperator::Create(I.getOpcode(), TrOp, ShAmt,
Chris Lattner74b2ab52007-12-22 09:07:47 +00007007 I.getName());
7008 InsertNewInstBefore(NSh, I); // (shift2 (shift1 & 0x00FF), c2)
7009
7010 // For logical shifts, the truncation has the effect of making the high
7011 // part of the register be zeros. Emulate this by inserting an AND to
7012 // clear the top bits as needed. This 'and' will usually be zapped by
7013 // other xforms later if dead.
7014 unsigned SrcSize = TrOp->getType()->getPrimitiveSizeInBits();
7015 unsigned DstSize = TI->getType()->getPrimitiveSizeInBits();
7016 APInt MaskV(APInt::getLowBitsSet(SrcSize, DstSize));
7017
7018 // The mask we constructed says what the trunc would do if occurring
7019 // between the shifts. We want to know the effect *after* the second
7020 // shift. We know that it is a logical shift by a constant, so adjust the
7021 // mask as appropriate.
7022 if (I.getOpcode() == Instruction::Shl)
7023 MaskV <<= Op1->getZExtValue();
7024 else {
7025 assert(I.getOpcode() == Instruction::LShr && "Unknown logical shift");
7026 MaskV = MaskV.lshr(Op1->getZExtValue());
7027 }
7028
Gabor Greife1f6e4b2008-05-16 19:29:10 +00007029 Instruction *And = BinaryOperator::CreateAnd(NSh, ConstantInt::get(MaskV),
Chris Lattner74b2ab52007-12-22 09:07:47 +00007030 TI->getName());
7031 InsertNewInstBefore(And, I); // shift1 & 0x00FF
7032
7033 // Return the value truncated to the interesting size.
7034 return new TruncInst(And, I.getType());
7035 }
7036 }
7037
Chris Lattner14553932006-01-06 07:12:35 +00007038 if (Op0->hasOneUse()) {
Chris Lattner14553932006-01-06 07:12:35 +00007039 if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
7040 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
7041 Value *V1, *V2;
7042 ConstantInt *CC;
7043 switch (Op0BO->getOpcode()) {
Chris Lattner27cb9db2005-09-18 05:12:10 +00007044 default: break;
7045 case Instruction::Add:
7046 case Instruction::And:
7047 case Instruction::Or:
Reid Spencer2f34b982007-02-02 14:41:37 +00007048 case Instruction::Xor: {
Chris Lattner27cb9db2005-09-18 05:12:10 +00007049 // These operators commute.
7050 // Turn (Y + (X >> C)) << C -> (X + (Y << C)) & (~0 << C)
Chris Lattner797dee72005-09-18 06:30:59 +00007051 if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
Chris Lattner44152742008-11-16 05:38:51 +00007052 match(Op0BO->getOperand(1), m_Shr(m_Value(V1), m_Specific(Op1)))){
Gabor Greife1f6e4b2008-05-16 19:29:10 +00007053 Instruction *YS = BinaryOperator::CreateShl(
Chris Lattner14553932006-01-06 07:12:35 +00007054 Op0BO->getOperand(0), Op1,
Chris Lattner797dee72005-09-18 06:30:59 +00007055 Op0BO->getName());
7056 InsertNewInstBefore(YS, I); // (Y << C)
Chris Lattner24cd2fa2006-02-09 07:41:14 +00007057 Instruction *X =
Gabor Greife1f6e4b2008-05-16 19:29:10 +00007058 BinaryOperator::Create(Op0BO->getOpcode(), YS, V1,
Chris Lattner24cd2fa2006-02-09 07:41:14 +00007059 Op0BO->getOperand(1)->getName());
Chris Lattner797dee72005-09-18 06:30:59 +00007060 InsertNewInstBefore(X, I); // (X + (Y << C))
Zhou Shengfd28a332007-03-30 17:20:39 +00007061 uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
Gabor Greife1f6e4b2008-05-16 19:29:10 +00007062 return BinaryOperator::CreateAnd(X, ConstantInt::get(
Zhou Sheng5e60a4a2007-03-30 05:45:18 +00007063 APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
Chris Lattner797dee72005-09-18 06:30:59 +00007064 }
Chris Lattner14553932006-01-06 07:12:35 +00007065
Chris Lattner797dee72005-09-18 06:30:59 +00007066 // Turn (Y + ((X >> C) & CC)) << C -> ((X & (CC << C)) + (Y << C))
Reid Spencer2f34b982007-02-02 14:41:37 +00007067 Value *Op0BOOp1 = Op0BO->getOperand(1);
Chris Lattnerfe53cf22007-03-05 00:11:19 +00007068 if (isLeftShift && Op0BOOp1->hasOneUse() &&
Reid Spencer2f34b982007-02-02 14:41:37 +00007069 match(Op0BOOp1,
Chris Lattner44152742008-11-16 05:38:51 +00007070 m_And(m_Shr(m_Value(V1), m_Specific(Op1)),
7071 m_ConstantInt(CC))) &&
7072 cast<BinaryOperator>(Op0BOOp1)->getOperand(0)->hasOneUse()) {
Gabor Greife1f6e4b2008-05-16 19:29:10 +00007073 Instruction *YS = BinaryOperator::CreateShl(
Reid Spencer2341c222007-02-02 02:16:23 +00007074 Op0BO->getOperand(0), Op1,
7075 Op0BO->getName());
Chris Lattner797dee72005-09-18 06:30:59 +00007076 InsertNewInstBefore(YS, I); // (Y << C)
7077 Instruction *XM =
Gabor Greife1f6e4b2008-05-16 19:29:10 +00007078 BinaryOperator::CreateAnd(V1, ConstantExpr::getShl(CC, Op1),
Chris Lattner797dee72005-09-18 06:30:59 +00007079 V1->getName()+".mask");
7080 InsertNewInstBefore(XM, I); // X & (CC << C)
7081
Gabor Greife1f6e4b2008-05-16 19:29:10 +00007082 return BinaryOperator::Create(Op0BO->getOpcode(), YS, XM);
Chris Lattner797dee72005-09-18 06:30:59 +00007083 }
Reid Spencer2f34b982007-02-02 14:41:37 +00007084 }
Chris Lattner14553932006-01-06 07:12:35 +00007085
Reid Spencer2f34b982007-02-02 14:41:37 +00007086 // FALL THROUGH.
7087 case Instruction::Sub: {
Chris Lattner27cb9db2005-09-18 05:12:10 +00007088 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
Chris Lattner797dee72005-09-18 06:30:59 +00007089 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
Chris Lattner44152742008-11-16 05:38:51 +00007090 match(Op0BO->getOperand(0), m_Shr(m_Value(V1), m_Specific(Op1)))){
Gabor Greife1f6e4b2008-05-16 19:29:10 +00007091 Instruction *YS = BinaryOperator::CreateShl(
Reid Spencer2341c222007-02-02 02:16:23 +00007092 Op0BO->getOperand(1), Op1,
7093 Op0BO->getName());
Chris Lattner797dee72005-09-18 06:30:59 +00007094 InsertNewInstBefore(YS, I); // (Y << C)
Chris Lattner24cd2fa2006-02-09 07:41:14 +00007095 Instruction *X =
Gabor Greife1f6e4b2008-05-16 19:29:10 +00007096 BinaryOperator::Create(Op0BO->getOpcode(), V1, YS,
Chris Lattner24cd2fa2006-02-09 07:41:14 +00007097 Op0BO->getOperand(0)->getName());
Chris Lattner797dee72005-09-18 06:30:59 +00007098 InsertNewInstBefore(X, I); // (X + (Y << C))
Zhou Shengfd28a332007-03-30 17:20:39 +00007099 uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
Gabor Greife1f6e4b2008-05-16 19:29:10 +00007100 return BinaryOperator::CreateAnd(X, ConstantInt::get(
Zhou Sheng5e60a4a2007-03-30 05:45:18 +00007101 APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
Chris Lattner797dee72005-09-18 06:30:59 +00007102 }
Chris Lattner14553932006-01-06 07:12:35 +00007103
Chris Lattner1df0e982006-05-31 21:14:00 +00007104 // Turn (((X >> C)&CC) + Y) << C -> (X + (Y << C)) & (CC << C)
Chris Lattner797dee72005-09-18 06:30:59 +00007105 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
7106 match(Op0BO->getOperand(0),
7107 m_And(m_Shr(m_Value(V1), m_Value(V2)),
Chris Lattner14553932006-01-06 07:12:35 +00007108 m_ConstantInt(CC))) && V2 == Op1 &&
Chris Lattner24cd2fa2006-02-09 07:41:14 +00007109 cast<BinaryOperator>(Op0BO->getOperand(0))
7110 ->getOperand(0)->hasOneUse()) {
Gabor Greife1f6e4b2008-05-16 19:29:10 +00007111 Instruction *YS = BinaryOperator::CreateShl(
Reid Spencer2341c222007-02-02 02:16:23 +00007112 Op0BO->getOperand(1), Op1,
7113 Op0BO->getName());
Chris Lattner797dee72005-09-18 06:30:59 +00007114 InsertNewInstBefore(YS, I); // (Y << C)
7115 Instruction *XM =
Gabor Greife1f6e4b2008-05-16 19:29:10 +00007116 BinaryOperator::CreateAnd(V1, ConstantExpr::getShl(CC, Op1),
Chris Lattner797dee72005-09-18 06:30:59 +00007117 V1->getName()+".mask");
7118 InsertNewInstBefore(XM, I); // X & (CC << C)
7119
Gabor Greife1f6e4b2008-05-16 19:29:10 +00007120 return BinaryOperator::Create(Op0BO->getOpcode(), XM, YS);
Chris Lattner797dee72005-09-18 06:30:59 +00007121 }
Chris Lattner14553932006-01-06 07:12:35 +00007122
Chris Lattner27cb9db2005-09-18 05:12:10 +00007123 break;
Reid Spencer2f34b982007-02-02 14:41:37 +00007124 }
Chris Lattner14553932006-01-06 07:12:35 +00007125 }
7126
7127
7128 // If the operand is an bitwise operator with a constant RHS, and the
7129 // shift is the only use, we can pull it out of the shift.
7130 if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
7131 bool isValid = true; // Valid only for And, Or, Xor
7132 bool highBitSet = false; // Transform if high bit of constant set?
7133
7134 switch (Op0BO->getOpcode()) {
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00007135 default: isValid = false; break; // Do not perform transform!
Chris Lattner44bd3922004-10-08 03:46:20 +00007136 case Instruction::Add:
7137 isValid = isLeftShift;
7138 break;
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00007139 case Instruction::Or:
7140 case Instruction::Xor:
7141 highBitSet = false;
7142 break;
7143 case Instruction::And:
7144 highBitSet = true;
7145 break;
Chris Lattner14553932006-01-06 07:12:35 +00007146 }
7147
7148 // If this is a signed shift right, and the high bit is modified
7149 // by the logical operation, do not perform the transformation.
7150 // The highBitSet boolean indicates the value of the high bit of
7151 // the constant which would cause it to be modified for this
7152 // operation.
7153 //
Chris Lattnerd2bbbab2007-12-06 06:25:04 +00007154 if (isValid && I.getOpcode() == Instruction::AShr)
Zhou Sheng23f7a1c2007-03-28 15:02:20 +00007155 isValid = Op0C->getValue()[TypeBits-1] == highBitSet;
Chris Lattner14553932006-01-06 07:12:35 +00007156
7157 if (isValid) {
7158 Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, Op1);
7159
7160 Instruction *NewShift =
Gabor Greife1f6e4b2008-05-16 19:29:10 +00007161 BinaryOperator::Create(I.getOpcode(), Op0BO->getOperand(0), Op1);
Chris Lattner14553932006-01-06 07:12:35 +00007162 InsertNewInstBefore(NewShift, I);
Chris Lattner6e0123b2007-02-11 01:23:03 +00007163 NewShift->takeName(Op0BO);
Chris Lattner14553932006-01-06 07:12:35 +00007164
Gabor Greife1f6e4b2008-05-16 19:29:10 +00007165 return BinaryOperator::Create(Op0BO->getOpcode(), NewShift,
Chris Lattner14553932006-01-06 07:12:35 +00007166 NewRHS);
7167 }
7168 }
7169 }
7170 }
7171
Chris Lattnereb372a02006-01-06 07:52:12 +00007172 // Find out if this is a shift of a shift by a constant.
Reid Spencer2341c222007-02-02 02:16:23 +00007173 BinaryOperator *ShiftOp = dyn_cast<BinaryOperator>(Op0);
7174 if (ShiftOp && !ShiftOp->isShift())
7175 ShiftOp = 0;
Chris Lattnereb372a02006-01-06 07:52:12 +00007176
Reid Spencere0fc4df2006-10-20 07:07:24 +00007177 if (ShiftOp && isa<ConstantInt>(ShiftOp->getOperand(1))) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00007178 ConstantInt *ShiftAmt1C = cast<ConstantInt>(ShiftOp->getOperand(1));
Zhou Shengb25806f2007-03-30 09:29:48 +00007179 uint32_t ShiftAmt1 = ShiftAmt1C->getLimitedValue(TypeBits);
7180 uint32_t ShiftAmt2 = Op1->getLimitedValue(TypeBits);
Chris Lattner3e009e82007-02-05 00:57:54 +00007181 assert(ShiftAmt2 != 0 && "Should have been simplified earlier");
7182 if (ShiftAmt1 == 0) return 0; // Will be simplified in the future.
7183 Value *X = ShiftOp->getOperand(0);
Chris Lattnereb372a02006-01-06 07:52:12 +00007184
Zhou Sheng56cda952007-04-02 08:20:41 +00007185 uint32_t AmtSum = ShiftAmt1+ShiftAmt2; // Fold into one big shift.
Reid Spencer6274c722007-03-23 18:46:34 +00007186 if (AmtSum > TypeBits)
7187 AmtSum = TypeBits;
Chris Lattner3e009e82007-02-05 00:57:54 +00007188
7189 const IntegerType *Ty = cast<IntegerType>(I.getType());
7190
7191 // Check for (X << c1) << c2 and (X >> c1) >> c2
Chris Lattner6c344e52007-02-03 23:28:07 +00007192 if (I.getOpcode() == ShiftOp->getOpcode()) {
Gabor Greife1f6e4b2008-05-16 19:29:10 +00007193 return BinaryOperator::Create(I.getOpcode(), X,
Chris Lattner3e009e82007-02-05 00:57:54 +00007194 ConstantInt::get(Ty, AmtSum));
7195 } else if (ShiftOp->getOpcode() == Instruction::LShr &&
7196 I.getOpcode() == Instruction::AShr) {
7197 // ((X >>u C1) >>s C2) -> (X >>u (C1+C2)) since C1 != 0.
Gabor Greife1f6e4b2008-05-16 19:29:10 +00007198 return BinaryOperator::CreateLShr(X, ConstantInt::get(Ty, AmtSum));
Chris Lattner3e009e82007-02-05 00:57:54 +00007199 } else if (ShiftOp->getOpcode() == Instruction::AShr &&
7200 I.getOpcode() == Instruction::LShr) {
7201 // ((X >>s C1) >>u C2) -> ((X >>s (C1+C2)) & mask) since C1 != 0.
7202 Instruction *Shift =
Gabor Greife1f6e4b2008-05-16 19:29:10 +00007203 BinaryOperator::CreateAShr(X, ConstantInt::get(Ty, AmtSum));
Chris Lattner3e009e82007-02-05 00:57:54 +00007204 InsertNewInstBefore(Shift, I);
7205
Zhou Sheng23f7a1c2007-03-28 15:02:20 +00007206 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Gabor Greife1f6e4b2008-05-16 19:29:10 +00007207 return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
Chris Lattnereb372a02006-01-06 07:52:12 +00007208 }
7209
Chris Lattner3e009e82007-02-05 00:57:54 +00007210 // Okay, if we get here, one shift must be left, and the other shift must be
7211 // right. See if the amounts are equal.
7212 if (ShiftAmt1 == ShiftAmt2) {
7213 // If we have ((X >>? C) << C), turn this into X & (-1 << C).
7214 if (I.getOpcode() == Instruction::Shl) {
Reid Spencer52830322007-03-25 21:11:44 +00007215 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt1));
Gabor Greife1f6e4b2008-05-16 19:29:10 +00007216 return BinaryOperator::CreateAnd(X, ConstantInt::get(Mask));
Chris Lattner3e009e82007-02-05 00:57:54 +00007217 }
7218 // If we have ((X << C) >>u C), turn this into X & (-1 >>u C).
7219 if (I.getOpcode() == Instruction::LShr) {
Zhou Sheng150f3bb2007-04-01 17:13:37 +00007220 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt1));
Gabor Greife1f6e4b2008-05-16 19:29:10 +00007221 return BinaryOperator::CreateAnd(X, ConstantInt::get(Mask));
Chris Lattner3e009e82007-02-05 00:57:54 +00007222 }
7223 // We can simplify ((X << C) >>s C) into a trunc + sext.
7224 // NOTE: we could do this for any C, but that would make 'unusual' integer
7225 // types. For now, just stick to ones well-supported by the code
7226 // generators.
7227 const Type *SExtType = 0;
7228 switch (Ty->getBitWidth() - ShiftAmt1) {
Zhou Sheng23f7a1c2007-03-28 15:02:20 +00007229 case 1 :
7230 case 8 :
7231 case 16 :
7232 case 32 :
7233 case 64 :
7234 case 128:
7235 SExtType = IntegerType::get(Ty->getBitWidth() - ShiftAmt1);
7236 break;
Chris Lattner3e009e82007-02-05 00:57:54 +00007237 default: break;
7238 }
7239 if (SExtType) {
7240 Instruction *NewTrunc = new TruncInst(X, SExtType, "sext");
7241 InsertNewInstBefore(NewTrunc, I);
7242 return new SExtInst(NewTrunc, Ty);
7243 }
7244 // Otherwise, we can't handle it yet.
7245 } else if (ShiftAmt1 < ShiftAmt2) {
Zhou Sheng56cda952007-04-02 08:20:41 +00007246 uint32_t ShiftDiff = ShiftAmt2-ShiftAmt1;
Chris Lattnereb372a02006-01-06 07:52:12 +00007247
Chris Lattner83ac5ae92007-02-05 05:57:49 +00007248 // (X >>? C1) << C2 --> X << (C2-C1) & (-1 << C2)
Chris Lattner3e009e82007-02-05 00:57:54 +00007249 if (I.getOpcode() == Instruction::Shl) {
7250 assert(ShiftOp->getOpcode() == Instruction::LShr ||
7251 ShiftOp->getOpcode() == Instruction::AShr);
Chris Lattner9cbfbc22006-01-07 01:32:28 +00007252 Instruction *Shift =
Gabor Greife1f6e4b2008-05-16 19:29:10 +00007253 BinaryOperator::CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
Chris Lattner9cbfbc22006-01-07 01:32:28 +00007254 InsertNewInstBefore(Shift, I);
7255
Reid Spencer52830322007-03-25 21:11:44 +00007256 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
Gabor Greife1f6e4b2008-05-16 19:29:10 +00007257 return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
Chris Lattnereb372a02006-01-06 07:52:12 +00007258 }
Chris Lattner3e009e82007-02-05 00:57:54 +00007259
Chris Lattner83ac5ae92007-02-05 05:57:49 +00007260 // (X << C1) >>u C2 --> X >>u (C2-C1) & (-1 >> C2)
Chris Lattner3e009e82007-02-05 00:57:54 +00007261 if (I.getOpcode() == Instruction::LShr) {
7262 assert(ShiftOp->getOpcode() == Instruction::Shl);
7263 Instruction *Shift =
Gabor Greife1f6e4b2008-05-16 19:29:10 +00007264 BinaryOperator::CreateLShr(X, ConstantInt::get(Ty, ShiftDiff));
Chris Lattner3e009e82007-02-05 00:57:54 +00007265 InsertNewInstBefore(Shift, I);
Chris Lattnereb372a02006-01-06 07:52:12 +00007266
Reid Spencer769a5a82007-03-26 17:18:58 +00007267 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Gabor Greife1f6e4b2008-05-16 19:29:10 +00007268 return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
Chris Lattner27cb9db2005-09-18 05:12:10 +00007269 }
Chris Lattner3e009e82007-02-05 00:57:54 +00007270
7271 // We can't handle (X << C1) >>s C2, it shifts arbitrary bits in.
7272 } else {
7273 assert(ShiftAmt2 < ShiftAmt1);
Zhou Sheng56cda952007-04-02 08:20:41 +00007274 uint32_t ShiftDiff = ShiftAmt1-ShiftAmt2;
Chris Lattner3e009e82007-02-05 00:57:54 +00007275
Chris Lattner83ac5ae92007-02-05 05:57:49 +00007276 // (X >>? C1) << C2 --> X >>? (C1-C2) & (-1 << C2)
Chris Lattner3e009e82007-02-05 00:57:54 +00007277 if (I.getOpcode() == Instruction::Shl) {
7278 assert(ShiftOp->getOpcode() == Instruction::LShr ||
7279 ShiftOp->getOpcode() == Instruction::AShr);
7280 Instruction *Shift =
Gabor Greife1f6e4b2008-05-16 19:29:10 +00007281 BinaryOperator::Create(ShiftOp->getOpcode(), X,
Chris Lattner3e009e82007-02-05 00:57:54 +00007282 ConstantInt::get(Ty, ShiftDiff));
7283 InsertNewInstBefore(Shift, I);
7284
Reid Spencer52830322007-03-25 21:11:44 +00007285 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
Gabor Greife1f6e4b2008-05-16 19:29:10 +00007286 return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
Chris Lattner3e009e82007-02-05 00:57:54 +00007287 }
7288
Chris Lattner83ac5ae92007-02-05 05:57:49 +00007289 // (X << C1) >>u C2 --> X << (C1-C2) & (-1 >> C2)
Chris Lattner3e009e82007-02-05 00:57:54 +00007290 if (I.getOpcode() == Instruction::LShr) {
7291 assert(ShiftOp->getOpcode() == Instruction::Shl);
7292 Instruction *Shift =
Gabor Greife1f6e4b2008-05-16 19:29:10 +00007293 BinaryOperator::CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
Chris Lattner3e009e82007-02-05 00:57:54 +00007294 InsertNewInstBefore(Shift, I);
7295
Reid Spencer441486c2007-03-26 23:45:51 +00007296 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Gabor Greife1f6e4b2008-05-16 19:29:10 +00007297 return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
Chris Lattner3e009e82007-02-05 00:57:54 +00007298 }
7299
7300 // We can't handle (X << C1) >>a C2, it shifts arbitrary bits in.
Chris Lattner86102b82005-01-01 16:22:27 +00007301 }
Chris Lattnereb372a02006-01-06 07:52:12 +00007302 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00007303 return 0;
7304}
7305
Chris Lattner48a44f72002-05-02 17:06:02 +00007306
Chris Lattner8f663e82005-10-29 04:36:15 +00007307/// DecomposeSimpleLinearExpr - Analyze 'Val', seeing if it is a simple linear
7308/// expression. If so, decompose it, returning some value X, such that Val is
7309/// X*Scale+Offset.
7310///
7311static Value *DecomposeSimpleLinearExpr(Value *Val, unsigned &Scale,
Jeff Cohen5a1c7502007-04-04 16:58:57 +00007312 int &Offset) {
Reid Spencerc635f472006-12-31 05:48:39 +00007313 assert(Val->getType() == Type::Int32Ty && "Unexpected allocation size type!");
Reid Spencere0fc4df2006-10-20 07:07:24 +00007314 if (ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
Reid Spencerc635f472006-12-31 05:48:39 +00007315 Offset = CI->getZExtValue();
Chris Lattnerd8675e42007-10-12 05:30:59 +00007316 Scale = 0;
Reid Spencerc635f472006-12-31 05:48:39 +00007317 return ConstantInt::get(Type::Int32Ty, 0);
Chris Lattnerd8675e42007-10-12 05:30:59 +00007318 } else if (BinaryOperator *I = dyn_cast<BinaryOperator>(Val)) {
7319 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
7320 if (I->getOpcode() == Instruction::Shl) {
7321 // This is a value scaled by '1 << the shift amt'.
7322 Scale = 1U << RHS->getZExtValue();
7323 Offset = 0;
7324 return I->getOperand(0);
7325 } else if (I->getOpcode() == Instruction::Mul) {
7326 // This value is scaled by 'RHS'.
7327 Scale = RHS->getZExtValue();
7328 Offset = 0;
7329 return I->getOperand(0);
7330 } else if (I->getOpcode() == Instruction::Add) {
7331 // We have X+C. Check to see if we really have (X*C2)+C1,
7332 // where C1 is divisible by C2.
7333 unsigned SubScale;
7334 Value *SubVal =
7335 DecomposeSimpleLinearExpr(I->getOperand(0), SubScale, Offset);
7336 Offset += RHS->getZExtValue();
7337 Scale = SubScale;
7338 return SubVal;
Chris Lattner8f663e82005-10-29 04:36:15 +00007339 }
7340 }
7341 }
7342
7343 // Otherwise, we can't look past this.
7344 Scale = 1;
7345 Offset = 0;
7346 return Val;
7347}
7348
7349
Chris Lattner216be912005-10-24 06:03:58 +00007350/// PromoteCastOfAllocation - If we find a cast of an allocation instruction,
7351/// try to eliminate the cast by moving the type information into the alloc.
Chris Lattner1db224d2007-04-27 17:44:50 +00007352Instruction *InstCombiner::PromoteCastOfAllocation(BitCastInst &CI,
Chris Lattner216be912005-10-24 06:03:58 +00007353 AllocationInst &AI) {
Chris Lattner1db224d2007-04-27 17:44:50 +00007354 const PointerType *PTy = cast<PointerType>(CI.getType());
Chris Lattner216be912005-10-24 06:03:58 +00007355
Chris Lattnerac87beb2005-10-24 06:22:12 +00007356 // Remove any uses of AI that are dead.
7357 assert(!CI.use_empty() && "Dead instructions should be removed earlier!");
Chris Lattner99c6cf62007-02-15 22:52:10 +00007358
Chris Lattnerac87beb2005-10-24 06:22:12 +00007359 for (Value::use_iterator UI = AI.use_begin(), E = AI.use_end(); UI != E; ) {
7360 Instruction *User = cast<Instruction>(*UI++);
7361 if (isInstructionTriviallyDead(User)) {
7362 while (UI != E && *UI == User)
7363 ++UI; // If this instruction uses AI more than once, don't break UI.
7364
Chris Lattnerac87beb2005-10-24 06:22:12 +00007365 ++NumDeadInst;
Bill Wendling5dbf43c2006-11-26 09:46:52 +00007366 DOUT << "IC: DCE: " << *User;
Chris Lattner51f54572007-03-02 19:59:19 +00007367 EraseInstFromFunction(*User);
Chris Lattnerac87beb2005-10-24 06:22:12 +00007368 }
7369 }
7370
Chris Lattner216be912005-10-24 06:03:58 +00007371 // Get the type really allocated and the type casted to.
7372 const Type *AllocElTy = AI.getAllocatedType();
7373 const Type *CastElTy = PTy->getElementType();
7374 if (!AllocElTy->isSized() || !CastElTy->isSized()) return 0;
Chris Lattner355ecc02005-10-24 06:26:18 +00007375
Chris Lattner945e4372007-02-14 05:52:17 +00007376 unsigned AllocElTyAlign = TD->getABITypeAlignment(AllocElTy);
7377 unsigned CastElTyAlign = TD->getABITypeAlignment(CastElTy);
Chris Lattner355ecc02005-10-24 06:26:18 +00007378 if (CastElTyAlign < AllocElTyAlign) return 0;
7379
Chris Lattner46705b22005-10-24 06:35:18 +00007380 // If the allocation has multiple uses, only promote it if we are strictly
7381 // increasing the alignment of the resultant allocation. If we keep it the
7382 // same, we open the door to infinite loops of various kinds.
7383 if (!AI.hasOneUse() && CastElTyAlign == AllocElTyAlign) return 0;
7384
Duncan Sands44b87212007-11-01 20:53:16 +00007385 uint64_t AllocElTySize = TD->getABITypeSize(AllocElTy);
7386 uint64_t CastElTySize = TD->getABITypeSize(CastElTy);
Chris Lattnerbb171802005-10-27 05:53:56 +00007387 if (CastElTySize == 0 || AllocElTySize == 0) return 0;
Chris Lattner355ecc02005-10-24 06:26:18 +00007388
Chris Lattner8270c332005-10-29 03:19:53 +00007389 // See if we can satisfy the modulus by pulling a scale out of the array
7390 // size argument.
Jeff Cohen5a1c7502007-04-04 16:58:57 +00007391 unsigned ArraySizeScale;
7392 int ArrayOffset;
Chris Lattner8f663e82005-10-29 04:36:15 +00007393 Value *NumElements = // See if the array size is a decomposable linear expr.
7394 DecomposeSimpleLinearExpr(AI.getOperand(0), ArraySizeScale, ArrayOffset);
7395
Chris Lattner8270c332005-10-29 03:19:53 +00007396 // If we can now satisfy the modulus, by using a non-1 scale, we really can
7397 // do the xform.
Chris Lattner8f663e82005-10-29 04:36:15 +00007398 if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 ||
7399 (AllocElTySize*ArrayOffset ) % CastElTySize != 0) return 0;
Chris Lattnerb3ecf962005-10-27 06:12:00 +00007400
Chris Lattner8270c332005-10-29 03:19:53 +00007401 unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize;
7402 Value *Amt = 0;
7403 if (Scale == 1) {
7404 Amt = NumElements;
7405 } else {
Reid Spencere0fc4df2006-10-20 07:07:24 +00007406 // If the allocation size is constant, form a constant mul expression
Reid Spencerc635f472006-12-31 05:48:39 +00007407 Amt = ConstantInt::get(Type::Int32Ty, Scale);
7408 if (isa<ConstantInt>(NumElements))
Zhou Sheng9bc8ab12007-04-02 13:45:30 +00007409 Amt = Multiply(cast<ConstantInt>(NumElements), cast<ConstantInt>(Amt));
Reid Spencere0fc4df2006-10-20 07:07:24 +00007410 // otherwise multiply the amount and the number of elements
Chris Lattner8270c332005-10-29 03:19:53 +00007411 else if (Scale != 1) {
Gabor Greife1f6e4b2008-05-16 19:29:10 +00007412 Instruction *Tmp = BinaryOperator::CreateMul(Amt, NumElements, "tmp");
Chris Lattner8270c332005-10-29 03:19:53 +00007413 Amt = InsertNewInstBefore(Tmp, AI);
Chris Lattnerb3ecf962005-10-27 06:12:00 +00007414 }
Chris Lattnerbb171802005-10-27 05:53:56 +00007415 }
7416
Jeff Cohen5a1c7502007-04-04 16:58:57 +00007417 if (int Offset = (AllocElTySize*ArrayOffset)/CastElTySize) {
7418 Value *Off = ConstantInt::get(Type::Int32Ty, Offset, true);
Gabor Greife1f6e4b2008-05-16 19:29:10 +00007419 Instruction *Tmp = BinaryOperator::CreateAdd(Amt, Off, "tmp");
Chris Lattner8f663e82005-10-29 04:36:15 +00007420 Amt = InsertNewInstBefore(Tmp, AI);
7421 }
7422
Chris Lattner216be912005-10-24 06:03:58 +00007423 AllocationInst *New;
7424 if (isa<MallocInst>(AI))
Chris Lattner6e0123b2007-02-11 01:23:03 +00007425 New = new MallocInst(CastElTy, Amt, AI.getAlignment());
Chris Lattner216be912005-10-24 06:03:58 +00007426 else
Chris Lattner6e0123b2007-02-11 01:23:03 +00007427 New = new AllocaInst(CastElTy, Amt, AI.getAlignment());
Chris Lattner216be912005-10-24 06:03:58 +00007428 InsertNewInstBefore(New, AI);
Chris Lattner6e0123b2007-02-11 01:23:03 +00007429 New->takeName(&AI);
Chris Lattner46705b22005-10-24 06:35:18 +00007430
7431 // If the allocation has multiple uses, insert a cast and change all things
7432 // that used it to use the new cast. This will also hack on CI, but it will
7433 // die soon.
7434 if (!AI.hasOneUse()) {
7435 AddUsesToWorkList(AI);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007436 // New is the allocation instruction, pointer typed. AI is the original
7437 // allocation instruction, also pointer typed. Thus, cast to use is BitCast.
7438 CastInst *NewCast = new BitCastInst(New, AI.getType(), "tmpcast");
Chris Lattner46705b22005-10-24 06:35:18 +00007439 InsertNewInstBefore(NewCast, AI);
7440 AI.replaceAllUsesWith(NewCast);
7441 }
Chris Lattner216be912005-10-24 06:03:58 +00007442 return ReplaceInstUsesWith(CI, New);
7443}
7444
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00007445/// CanEvaluateInDifferentType - Return true if we can take the specified value
Chris Lattnerda1d04a2007-03-03 05:27:34 +00007446/// and return it as type Ty without inserting any new casts and without
7447/// changing the computed value. This is used by code that tries to decide
7448/// whether promoting or shrinking integer operations to wider or smaller types
7449/// will allow us to eliminate a truncate or extend.
7450///
7451/// This is a truncation operation if Ty is smaller than V->getType(), or an
7452/// extension operation if Ty is larger.
Chris Lattnerb5ee8b32008-06-18 04:00:49 +00007453///
7454/// If CastOpc is a truncation, then Ty will be a type smaller than V. We
7455/// should return true if trunc(V) can be computed by computing V in the smaller
7456/// type. If V is an instruction, then trunc(inst(x,y)) can be computed as
7457/// inst(trunc(x),trunc(y)), which only makes sense if x and y can be
7458/// efficiently truncated.
7459///
7460/// If CastOpc is a sext or zext, we are asking if the low bits of the value can
7461/// bit computed in a larger type, which is then and'd or sext_in_reg'd to get
7462/// the final result.
Dan Gohman99b7b3f2008-04-10 18:43:06 +00007463bool InstCombiner::CanEvaluateInDifferentType(Value *V, const IntegerType *Ty,
7464 unsigned CastOpc,
7465 int &NumCastsRemoved) {
Chris Lattnerda1d04a2007-03-03 05:27:34 +00007466 // We can always evaluate constants in another type.
7467 if (isa<ConstantInt>(V))
7468 return true;
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00007469
7470 Instruction *I = dyn_cast<Instruction>(V);
Chris Lattnerda1d04a2007-03-03 05:27:34 +00007471 if (!I) return false;
7472
7473 const IntegerType *OrigTy = cast<IntegerType>(V->getType());
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00007474
Chris Lattnerb0418fc2007-08-02 06:11:14 +00007475 // If this is an extension or truncate, we can often eliminate it.
7476 if (isa<TruncInst>(I) || isa<ZExtInst>(I) || isa<SExtInst>(I)) {
7477 // If this is a cast from the destination type, we can trivially eliminate
7478 // it, and this will remove a cast overall.
7479 if (I->getOperand(0)->getType() == Ty) {
7480 // If the first operand is itself a cast, and is eliminable, do not count
7481 // this as an eliminable cast. We would prefer to eliminate those two
7482 // casts first.
Chris Lattnerb5ee8b32008-06-18 04:00:49 +00007483 if (!isa<CastInst>(I->getOperand(0)) && I->hasOneUse())
Chris Lattnerb0418fc2007-08-02 06:11:14 +00007484 ++NumCastsRemoved;
7485 return true;
7486 }
7487 }
7488
7489 // We can't extend or shrink something that has multiple uses: doing so would
7490 // require duplicating the instruction in general, which isn't profitable.
7491 if (!I->hasOneUse()) return false;
7492
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00007493 switch (I->getOpcode()) {
Chris Lattnerda1d04a2007-03-03 05:27:34 +00007494 case Instruction::Add:
7495 case Instruction::Sub:
Nick Lewycky9f1a4dc2008-07-05 21:19:34 +00007496 case Instruction::Mul:
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00007497 case Instruction::And:
7498 case Instruction::Or:
7499 case Instruction::Xor:
7500 // These operators can all arbitrarily be extended or truncated.
Chris Lattnerb0418fc2007-08-02 06:11:14 +00007501 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
7502 NumCastsRemoved) &&
7503 CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
7504 NumCastsRemoved);
Chris Lattnerda1d04a2007-03-03 05:27:34 +00007505
Chris Lattner960acb02006-11-29 07:18:39 +00007506 case Instruction::Shl:
Chris Lattnerda1d04a2007-03-03 05:27:34 +00007507 // If we are truncating the result of this SHL, and if it's a shift of a
7508 // constant amount, we can always perform a SHL in a smaller type.
7509 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Shengfd28a332007-03-30 17:20:39 +00007510 uint32_t BitWidth = Ty->getBitWidth();
7511 if (BitWidth < OrigTy->getBitWidth() &&
7512 CI->getLimitedValue(BitWidth) < BitWidth)
Chris Lattnerb0418fc2007-08-02 06:11:14 +00007513 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
7514 NumCastsRemoved);
Chris Lattnerda1d04a2007-03-03 05:27:34 +00007515 }
7516 break;
7517 case Instruction::LShr:
Chris Lattnerda1d04a2007-03-03 05:27:34 +00007518 // If this is a truncate of a logical shr, we can truncate it to a smaller
7519 // lshr iff we know that the bits we would otherwise be shifting in are
7520 // already zeros.
7521 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Shengfd28a332007-03-30 17:20:39 +00007522 uint32_t OrigBitWidth = OrigTy->getBitWidth();
7523 uint32_t BitWidth = Ty->getBitWidth();
7524 if (BitWidth < OrigBitWidth &&
Chris Lattnerda1d04a2007-03-03 05:27:34 +00007525 MaskedValueIsZero(I->getOperand(0),
Zhou Shengfd28a332007-03-30 17:20:39 +00007526 APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth)) &&
7527 CI->getLimitedValue(BitWidth) < BitWidth) {
Chris Lattnerb0418fc2007-08-02 06:11:14 +00007528 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
7529 NumCastsRemoved);
Chris Lattnerda1d04a2007-03-03 05:27:34 +00007530 }
7531 }
Chris Lattner960acb02006-11-29 07:18:39 +00007532 break;
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007533 case Instruction::ZExt:
7534 case Instruction::SExt:
Chris Lattnerb0418fc2007-08-02 06:11:14 +00007535 case Instruction::Trunc:
7536 // If this is the same kind of case as our original (e.g. zext+zext), we
Chris Lattnerdc2cf222007-08-02 17:23:38 +00007537 // can safely replace it. Note that replacing it does not reduce the number
7538 // of casts in the input.
7539 if (I->getOpcode() == CastOpc)
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00007540 return true;
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007541 break;
Nick Lewycky9f1a4dc2008-07-05 21:19:34 +00007542 case Instruction::Select: {
7543 SelectInst *SI = cast<SelectInst>(I);
7544 return CanEvaluateInDifferentType(SI->getTrueValue(), Ty, CastOpc,
7545 NumCastsRemoved) &&
7546 CanEvaluateInDifferentType(SI->getFalseValue(), Ty, CastOpc,
7547 NumCastsRemoved);
7548 }
Chris Lattnerb5ee8b32008-06-18 04:00:49 +00007549 case Instruction::PHI: {
7550 // We can change a phi if we can change all operands.
7551 PHINode *PN = cast<PHINode>(I);
7552 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
7553 if (!CanEvaluateInDifferentType(PN->getIncomingValue(i), Ty, CastOpc,
7554 NumCastsRemoved))
7555 return false;
7556 return true;
7557 }
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007558 default:
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00007559 // TODO: Can handle more cases here.
7560 break;
7561 }
7562
7563 return false;
7564}
7565
7566/// EvaluateInDifferentType - Given an expression that
7567/// CanEvaluateInDifferentType returns true for, actually insert the code to
7568/// evaluate the expression.
Reid Spencer74a528b2006-12-13 18:21:21 +00007569Value *InstCombiner::EvaluateInDifferentType(Value *V, const Type *Ty,
Chris Lattnerda1d04a2007-03-03 05:27:34 +00007570 bool isSigned) {
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00007571 if (Constant *C = dyn_cast<Constant>(V))
Reid Spencer74a528b2006-12-13 18:21:21 +00007572 return ConstantExpr::getIntegerCast(C, Ty, isSigned /*Sext or ZExt*/);
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00007573
7574 // Otherwise, it must be an instruction.
7575 Instruction *I = cast<Instruction>(V);
Chris Lattnerd0622b62006-05-20 23:14:03 +00007576 Instruction *Res = 0;
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00007577 switch (I->getOpcode()) {
Chris Lattnerda1d04a2007-03-03 05:27:34 +00007578 case Instruction::Add:
7579 case Instruction::Sub:
Nick Lewycky78712e52008-01-22 05:08:48 +00007580 case Instruction::Mul:
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00007581 case Instruction::And:
7582 case Instruction::Or:
Chris Lattnerda1d04a2007-03-03 05:27:34 +00007583 case Instruction::Xor:
Chris Lattner960acb02006-11-29 07:18:39 +00007584 case Instruction::AShr:
7585 case Instruction::LShr:
7586 case Instruction::Shl: {
Reid Spencer74a528b2006-12-13 18:21:21 +00007587 Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty, isSigned);
Chris Lattnerda1d04a2007-03-03 05:27:34 +00007588 Value *RHS = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
Gabor Greife1f6e4b2008-05-16 19:29:10 +00007589 Res = BinaryOperator::Create((Instruction::BinaryOps)I->getOpcode(),
Chris Lattnerb5ee8b32008-06-18 04:00:49 +00007590 LHS, RHS);
Chris Lattner960acb02006-11-29 07:18:39 +00007591 break;
7592 }
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007593 case Instruction::Trunc:
7594 case Instruction::ZExt:
7595 case Instruction::SExt:
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007596 // If the source type of the cast is the type we're trying for then we can
Chris Lattnerb0418fc2007-08-02 06:11:14 +00007597 // just return the source. There's no need to insert it because it is not
7598 // new.
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00007599 if (I->getOperand(0)->getType() == Ty)
7600 return I->getOperand(0);
7601
Chris Lattnerb5ee8b32008-06-18 04:00:49 +00007602 // Otherwise, must be the same type of cast, so just reinsert a new one.
Gabor Greife1f6e4b2008-05-16 19:29:10 +00007603 Res = CastInst::Create(cast<CastInst>(I)->getOpcode(), I->getOperand(0),
Chris Lattnerb5ee8b32008-06-18 04:00:49 +00007604 Ty);
Chris Lattnerb0418fc2007-08-02 06:11:14 +00007605 break;
Nick Lewycky9f1a4dc2008-07-05 21:19:34 +00007606 case Instruction::Select: {
7607 Value *True = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
7608 Value *False = EvaluateInDifferentType(I->getOperand(2), Ty, isSigned);
7609 Res = SelectInst::Create(I->getOperand(0), True, False);
7610 break;
7611 }
Chris Lattnerb5ee8b32008-06-18 04:00:49 +00007612 case Instruction::PHI: {
7613 PHINode *OPN = cast<PHINode>(I);
7614 PHINode *NPN = PHINode::Create(Ty);
7615 for (unsigned i = 0, e = OPN->getNumIncomingValues(); i != e; ++i) {
7616 Value *V =EvaluateInDifferentType(OPN->getIncomingValue(i), Ty, isSigned);
7617 NPN->addIncoming(V, OPN->getIncomingBlock(i));
7618 }
7619 Res = NPN;
7620 break;
7621 }
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007622 default:
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00007623 // TODO: Can handle more cases here.
7624 assert(0 && "Unreachable!");
7625 break;
7626 }
7627
Chris Lattnerb5ee8b32008-06-18 04:00:49 +00007628 Res->takeName(I);
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00007629 return InsertNewInstBefore(Res, *I);
7630}
7631
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007632/// @brief Implement the transforms common to all CastInst visitors.
7633Instruction *InstCombiner::commonCastTransforms(CastInst &CI) {
Chris Lattner55d4bda2003-06-23 21:59:52 +00007634 Value *Src = CI.getOperand(0);
7635
Dan Gohmanb5650eb2007-05-11 21:10:54 +00007636 // Many cases of "cast of a cast" are eliminable. If it's eliminable we just
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007637 // eliminate it now.
Chris Lattner86102b82005-01-01 16:22:27 +00007638 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007639 if (Instruction::CastOps opc =
7640 isEliminableCastPair(CSrc, CI.getOpcode(), CI.getType(), TD)) {
7641 // The first cast (CSrc) is eliminable so we need to fix up or replace
7642 // the second cast (CI). CSrc will then have a good chance of being dead.
Gabor Greife1f6e4b2008-05-16 19:29:10 +00007643 return CastInst::Create(opc, CSrc->getOperand(0), CI.getType());
Chris Lattner650b6da2002-08-02 20:00:25 +00007644 }
7645 }
Chris Lattner03841652004-05-25 04:29:21 +00007646
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007647 // If we are casting a select then fold the cast into the select
Chris Lattner86102b82005-01-01 16:22:27 +00007648 if (SelectInst *SI = dyn_cast<SelectInst>(Src))
7649 if (Instruction *NV = FoldOpIntoSelect(CI, SI, this))
7650 return NV;
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007651
7652 // If we are casting a PHI then fold the cast into the PHI
Chris Lattner6a4adcd2004-09-29 05:07:12 +00007653 if (isa<PHINode>(Src))
7654 if (Instruction *NV = FoldOpIntoPhi(CI))
7655 return NV;
Chris Lattnerb19a5c62006-04-12 18:09:35 +00007656
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007657 return 0;
7658}
7659
Chris Lattner1db224d2007-04-27 17:44:50 +00007660/// @brief Implement the transforms for cast of pointer (bitcast/ptrtoint)
7661Instruction *InstCombiner::commonPointerCastTransforms(CastInst &CI) {
7662 Value *Src = CI.getOperand(0);
7663
Chris Lattner1db224d2007-04-27 17:44:50 +00007664 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
Chris Lattneracbf6a42007-04-28 00:57:34 +00007665 // If casting the result of a getelementptr instruction with no offset, turn
7666 // this into a cast of the original pointer!
Chris Lattner1db224d2007-04-27 17:44:50 +00007667 if (GEP->hasAllZeroIndices()) {
7668 // Changing the cast operand is usually not a good idea but it is safe
7669 // here because the pointer operand is being replaced with another
7670 // pointer operand so the opcode doesn't need to change.
Chris Lattneracbf6a42007-04-28 00:57:34 +00007671 AddToWorkList(GEP);
Chris Lattner1db224d2007-04-27 17:44:50 +00007672 CI.setOperand(0, GEP->getOperand(0));
7673 return &CI;
7674 }
Chris Lattneracbf6a42007-04-28 00:57:34 +00007675
7676 // If the GEP has a single use, and the base pointer is a bitcast, and the
7677 // GEP computes a constant offset, see if we can convert these three
7678 // instructions into fewer. This typically happens with unions and other
7679 // non-type-safe code.
7680 if (GEP->hasOneUse() && isa<BitCastInst>(GEP->getOperand(0))) {
7681 if (GEP->hasAllConstantIndices()) {
7682 // We are guaranteed to get a constant from EmitGEPOffset.
7683 ConstantInt *OffsetV = cast<ConstantInt>(EmitGEPOffset(GEP, CI, *this));
7684 int64_t Offset = OffsetV->getSExtValue();
7685
7686 // Get the base pointer input of the bitcast, and the type it points to.
7687 Value *OrigBase = cast<BitCastInst>(GEP->getOperand(0))->getOperand(0);
7688 const Type *GEPIdxTy =
7689 cast<PointerType>(OrigBase->getType())->getElementType();
7690 if (GEPIdxTy->isSized()) {
7691 SmallVector<Value*, 8> NewIndices;
7692
Chris Lattner5c827bd2007-05-05 01:59:31 +00007693 // Start with the index over the outer type. Note that the type size
7694 // might be zero (even if the offset isn't zero) if the indexed type
7695 // is something like [0 x {int, int}]
Chris Lattneracbf6a42007-04-28 00:57:34 +00007696 const Type *IntPtrTy = TD->getIntPtrType();
Chris Lattner5c827bd2007-05-05 01:59:31 +00007697 int64_t FirstIdx = 0;
Duncan Sands44b87212007-11-01 20:53:16 +00007698 if (int64_t TySize = TD->getABITypeSize(GEPIdxTy)) {
Chris Lattner5c827bd2007-05-05 01:59:31 +00007699 FirstIdx = Offset/TySize;
7700 Offset %= TySize;
Chris Lattneracbf6a42007-04-28 00:57:34 +00007701
Chris Lattner5c827bd2007-05-05 01:59:31 +00007702 // Handle silly modulus not returning values values [0..TySize).
7703 if (Offset < 0) {
7704 --FirstIdx;
7705 Offset += TySize;
7706 assert(Offset >= 0);
7707 }
Chris Lattner361e9812007-05-05 22:32:24 +00007708 assert((uint64_t)Offset < (uint64_t)TySize &&"Out of range offset");
Chris Lattneracbf6a42007-04-28 00:57:34 +00007709 }
7710
7711 NewIndices.push_back(ConstantInt::get(IntPtrTy, FirstIdx));
Chris Lattneracbf6a42007-04-28 00:57:34 +00007712
7713 // Index into the types. If we fail, set OrigBase to null.
7714 while (Offset) {
7715 if (const StructType *STy = dyn_cast<StructType>(GEPIdxTy)) {
7716 const StructLayout *SL = TD->getStructLayout(STy);
Chris Lattner234f96d2007-05-15 00:16:00 +00007717 if (Offset < (int64_t)SL->getSizeInBytes()) {
7718 unsigned Elt = SL->getElementContainingOffset(Offset);
7719 NewIndices.push_back(ConstantInt::get(Type::Int32Ty, Elt));
Chris Lattneracbf6a42007-04-28 00:57:34 +00007720
Chris Lattner234f96d2007-05-15 00:16:00 +00007721 Offset -= SL->getElementOffset(Elt);
7722 GEPIdxTy = STy->getElementType(Elt);
7723 } else {
7724 // Otherwise, we can't index into this, bail out.
7725 Offset = 0;
7726 OrigBase = 0;
7727 }
Chris Lattneracbf6a42007-04-28 00:57:34 +00007728 } else if (isa<ArrayType>(GEPIdxTy) || isa<VectorType>(GEPIdxTy)) {
7729 const SequentialType *STy = cast<SequentialType>(GEPIdxTy);
Duncan Sands44b87212007-11-01 20:53:16 +00007730 if (uint64_t EltSize = TD->getABITypeSize(STy->getElementType())){
Chris Lattner234f96d2007-05-15 00:16:00 +00007731 NewIndices.push_back(ConstantInt::get(IntPtrTy,Offset/EltSize));
7732 Offset %= EltSize;
7733 } else {
7734 NewIndices.push_back(ConstantInt::get(IntPtrTy, 0));
7735 }
Chris Lattneracbf6a42007-04-28 00:57:34 +00007736 GEPIdxTy = STy->getElementType();
7737 } else {
7738 // Otherwise, we can't index into this, bail out.
7739 Offset = 0;
7740 OrigBase = 0;
7741 }
7742 }
7743 if (OrigBase) {
7744 // If we were able to index down into an element, create the GEP
7745 // and bitcast the result. This eliminates one bitcast, potentially
7746 // two.
Gabor Greife9ecc682008-04-06 20:25:17 +00007747 Instruction *NGEP = GetElementPtrInst::Create(OrigBase,
7748 NewIndices.begin(),
7749 NewIndices.end(), "");
Chris Lattneracbf6a42007-04-28 00:57:34 +00007750 InsertNewInstBefore(NGEP, CI);
7751 NGEP->takeName(GEP);
7752
Chris Lattneracbf6a42007-04-28 00:57:34 +00007753 if (isa<BitCastInst>(CI))
7754 return new BitCastInst(NGEP, CI.getType());
7755 assert(isa<PtrToIntInst>(CI));
7756 return new PtrToIntInst(NGEP, CI.getType());
7757 }
7758 }
7759 }
7760 }
Chris Lattner1db224d2007-04-27 17:44:50 +00007761 }
7762
7763 return commonCastTransforms(CI);
7764}
7765
7766
7767
Chris Lattnerda1d04a2007-03-03 05:27:34 +00007768/// Only the TRUNC, ZEXT, SEXT, and BITCAST can both operand and result as
7769/// integer types. This function implements the common transforms for all those
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007770/// cases.
7771/// @brief Implement the transforms common to CastInst with integer operands
7772Instruction *InstCombiner::commonIntCastTransforms(CastInst &CI) {
7773 if (Instruction *Result = commonCastTransforms(CI))
7774 return Result;
7775
7776 Value *Src = CI.getOperand(0);
7777 const Type *SrcTy = Src->getType();
7778 const Type *DestTy = CI.getType();
Zhou Sheng56cda952007-04-02 08:20:41 +00007779 uint32_t SrcBitSize = SrcTy->getPrimitiveSizeInBits();
7780 uint32_t DestBitSize = DestTy->getPrimitiveSizeInBits();
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007781
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007782 // See if we can simplify any instructions used by the LHS whose sole
7783 // purpose is to compute bits we don't care about.
Reid Spencer4154e732007-03-22 20:56:53 +00007784 APInt KnownZero(DestBitSize, 0), KnownOne(DestBitSize, 0);
7785 if (SimplifyDemandedBits(&CI, APInt::getAllOnesValue(DestBitSize),
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007786 KnownZero, KnownOne))
7787 return &CI;
7788
7789 // If the source isn't an instruction or has more than one use then we
7790 // can't do anything more.
Reid Spencer266e42b2006-12-23 06:05:41 +00007791 Instruction *SrcI = dyn_cast<Instruction>(Src);
7792 if (!SrcI || !Src->hasOneUse())
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007793 return 0;
7794
Chris Lattnerda1d04a2007-03-03 05:27:34 +00007795 // Attempt to propagate the cast into the instruction for int->int casts.
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007796 int NumCastsRemoved = 0;
Chris Lattnerda1d04a2007-03-03 05:27:34 +00007797 if (!isa<BitCastInst>(CI) &&
7798 CanEvaluateInDifferentType(SrcI, cast<IntegerType>(DestTy),
Chris Lattnerb0418fc2007-08-02 06:11:14 +00007799 CI.getOpcode(), NumCastsRemoved)) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007800 // If this cast is a truncate, evaluting in a different type always
Chris Lattnerb0418fc2007-08-02 06:11:14 +00007801 // eliminates the cast, so it is always a win. If this is a zero-extension,
7802 // we need to do an AND to maintain the clear top-part of the computation,
7803 // so we require that the input have eliminated at least one cast. If this
7804 // is a sign extension, we insert two new casts (to do the extension) so we
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007805 // require that two casts have been eliminated.
Chris Lattnerda1d04a2007-03-03 05:27:34 +00007806 bool DoXForm;
7807 switch (CI.getOpcode()) {
7808 default:
7809 // All the others use floating point so we shouldn't actually
7810 // get here because of the check above.
7811 assert(0 && "Unknown cast type");
7812 case Instruction::Trunc:
7813 DoXForm = true;
7814 break;
7815 case Instruction::ZExt:
7816 DoXForm = NumCastsRemoved >= 1;
7817 break;
7818 case Instruction::SExt:
7819 DoXForm = NumCastsRemoved >= 2;
7820 break;
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007821 }
7822
7823 if (DoXForm) {
Reid Spencer74a528b2006-12-13 18:21:21 +00007824 Value *Res = EvaluateInDifferentType(SrcI, DestTy,
7825 CI.getOpcode() == Instruction::SExt);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007826 assert(Res->getType() == DestTy);
7827 switch (CI.getOpcode()) {
7828 default: assert(0 && "Unknown cast type!");
7829 case Instruction::Trunc:
7830 case Instruction::BitCast:
7831 // Just replace this cast with the result.
7832 return ReplaceInstUsesWith(CI, Res);
7833 case Instruction::ZExt: {
7834 // We need to emit an AND to clear the high bits.
7835 assert(SrcBitSize < DestBitSize && "Not a zext?");
Chris Lattner9d5aace2007-04-02 05:48:58 +00007836 Constant *C = ConstantInt::get(APInt::getLowBitsSet(DestBitSize,
7837 SrcBitSize));
Gabor Greife1f6e4b2008-05-16 19:29:10 +00007838 return BinaryOperator::CreateAnd(Res, C);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007839 }
7840 case Instruction::SExt:
7841 // We need to emit a cast to truncate, then a cast to sext.
Gabor Greife1f6e4b2008-05-16 19:29:10 +00007842 return CastInst::Create(Instruction::SExt,
Reid Spencer13bc5d72006-12-12 09:18:51 +00007843 InsertCastBefore(Instruction::Trunc, Res, Src->getType(),
7844 CI), DestTy);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007845 }
7846 }
7847 }
7848
7849 Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
7850 Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
7851
7852 switch (SrcI->getOpcode()) {
7853 case Instruction::Add:
7854 case Instruction::Mul:
7855 case Instruction::And:
7856 case Instruction::Or:
7857 case Instruction::Xor:
Chris Lattnera74deaf2007-04-03 17:43:25 +00007858 // If we are discarding information, rewrite.
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007859 if (DestBitSize <= SrcBitSize && DestBitSize != 1) {
7860 // Don't insert two casts if they cannot be eliminated. We allow
7861 // two casts to be inserted if the sizes are the same. This could
7862 // only be converting signedness, which is a noop.
7863 if (DestBitSize == SrcBitSize ||
Reid Spencer266e42b2006-12-23 06:05:41 +00007864 !ValueRequiresCast(CI.getOpcode(), Op1, DestTy,TD) ||
7865 !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
Reid Spencer2a499b02006-12-13 17:19:09 +00007866 Instruction::CastOps opcode = CI.getOpcode();
Eli Friedman55e4bec2008-11-30 21:09:11 +00007867 Value *Op0c = InsertCastBefore(opcode, Op0, DestTy, *SrcI);
7868 Value *Op1c = InsertCastBefore(opcode, Op1, DestTy, *SrcI);
Gabor Greife1f6e4b2008-05-16 19:29:10 +00007869 return BinaryOperator::Create(
Reid Spencer13bc5d72006-12-12 09:18:51 +00007870 cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007871 }
7872 }
7873
7874 // cast (xor bool X, true) to int --> xor (cast bool X to int), 1
7875 if (isa<ZExtInst>(CI) && SrcBitSize == 1 &&
7876 SrcI->getOpcode() == Instruction::Xor &&
Zhou Sheng75b871f2007-01-11 12:24:14 +00007877 Op1 == ConstantInt::getTrue() &&
Reid Spencer266e42b2006-12-23 06:05:41 +00007878 (!Op0->hasOneUse() || !isa<CmpInst>(Op0))) {
Eli Friedman55e4bec2008-11-30 21:09:11 +00007879 Value *New = InsertCastBefore(Instruction::ZExt, Op0, DestTy, CI);
Gabor Greife1f6e4b2008-05-16 19:29:10 +00007880 return BinaryOperator::CreateXor(New, ConstantInt::get(CI.getType(), 1));
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007881 }
7882 break;
7883 case Instruction::SDiv:
7884 case Instruction::UDiv:
7885 case Instruction::SRem:
7886 case Instruction::URem:
7887 // If we are just changing the sign, rewrite.
7888 if (DestBitSize == SrcBitSize) {
7889 // Don't insert two casts if they cannot be eliminated. We allow
7890 // two casts to be inserted if the sizes are the same. This could
7891 // only be converting signedness, which is a noop.
Reid Spencer266e42b2006-12-23 06:05:41 +00007892 if (!ValueRequiresCast(CI.getOpcode(), Op1, DestTy, TD) ||
7893 !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
Eli Friedman55e4bec2008-11-30 21:09:11 +00007894 Value *Op0c = InsertCastBefore(Instruction::BitCast,
7895 Op0, DestTy, *SrcI);
7896 Value *Op1c = InsertCastBefore(Instruction::BitCast,
7897 Op1, DestTy, *SrcI);
Gabor Greife1f6e4b2008-05-16 19:29:10 +00007898 return BinaryOperator::Create(
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007899 cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
7900 }
7901 }
7902 break;
7903
7904 case Instruction::Shl:
7905 // Allow changing the sign of the source operand. Do not allow
7906 // changing the size of the shift, UNLESS the shift amount is a
7907 // constant. We must not change variable sized shifts to a smaller
7908 // size, because it is undefined to shift more bits out than exist
7909 // in the value.
7910 if (DestBitSize == SrcBitSize ||
7911 (DestBitSize < SrcBitSize && isa<Constant>(Op1))) {
Reid Spencer13bc5d72006-12-12 09:18:51 +00007912 Instruction::CastOps opcode = (DestBitSize == SrcBitSize ?
7913 Instruction::BitCast : Instruction::Trunc);
Eli Friedman55e4bec2008-11-30 21:09:11 +00007914 Value *Op0c = InsertCastBefore(opcode, Op0, DestTy, *SrcI);
7915 Value *Op1c = InsertCastBefore(opcode, Op1, DestTy, *SrcI);
Gabor Greife1f6e4b2008-05-16 19:29:10 +00007916 return BinaryOperator::CreateShl(Op0c, Op1c);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007917 }
7918 break;
7919 case Instruction::AShr:
7920 // If this is a signed shr, and if all bits shifted in are about to be
7921 // truncated off, turn it into an unsigned shr to allow greater
7922 // simplifications.
7923 if (DestBitSize < SrcBitSize &&
7924 isa<ConstantInt>(Op1)) {
Zhou Shengfd28a332007-03-30 17:20:39 +00007925 uint32_t ShiftAmt = cast<ConstantInt>(Op1)->getLimitedValue(SrcBitSize);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007926 if (SrcBitSize > ShiftAmt && SrcBitSize-ShiftAmt >= DestBitSize) {
7927 // Insert the new logical shift right.
Gabor Greife1f6e4b2008-05-16 19:29:10 +00007928 return BinaryOperator::CreateLShr(Op0, Op1);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007929 }
7930 }
7931 break;
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007932 }
7933 return 0;
7934}
7935
Chris Lattner74ff60f2007-04-11 06:57:46 +00007936Instruction *InstCombiner::visitTrunc(TruncInst &CI) {
Chris Lattnerd747f012006-11-29 07:04:07 +00007937 if (Instruction *Result = commonIntCastTransforms(CI))
7938 return Result;
7939
7940 Value *Src = CI.getOperand(0);
7941 const Type *Ty = CI.getType();
Zhou Sheng56cda952007-04-02 08:20:41 +00007942 uint32_t DestBitWidth = Ty->getPrimitiveSizeInBits();
7943 uint32_t SrcBitWidth = cast<IntegerType>(Src->getType())->getBitWidth();
Chris Lattnerd747f012006-11-29 07:04:07 +00007944
7945 if (Instruction *SrcI = dyn_cast<Instruction>(Src)) {
7946 switch (SrcI->getOpcode()) {
7947 default: break;
7948 case Instruction::LShr:
7949 // We can shrink lshr to something smaller if we know the bits shifted in
7950 // are already zeros.
7951 if (ConstantInt *ShAmtV = dyn_cast<ConstantInt>(SrcI->getOperand(1))) {
Zhou Shengfd28a332007-03-30 17:20:39 +00007952 uint32_t ShAmt = ShAmtV->getLimitedValue(SrcBitWidth);
Chris Lattnerd747f012006-11-29 07:04:07 +00007953
7954 // Get a mask for the bits shifting in.
Zhou Sheng2777a312007-03-28 09:19:01 +00007955 APInt Mask(APInt::getLowBitsSet(SrcBitWidth, ShAmt).shl(DestBitWidth));
Reid Spencer13bc5d72006-12-12 09:18:51 +00007956 Value* SrcIOp0 = SrcI->getOperand(0);
7957 if (SrcI->hasOneUse() && MaskedValueIsZero(SrcIOp0, Mask)) {
Chris Lattnerd747f012006-11-29 07:04:07 +00007958 if (ShAmt >= DestBitWidth) // All zeros.
7959 return ReplaceInstUsesWith(CI, Constant::getNullValue(Ty));
7960
7961 // Okay, we can shrink this. Truncate the input, then return a new
7962 // shift.
Reid Spencer2341c222007-02-02 02:16:23 +00007963 Value *V1 = InsertCastBefore(Instruction::Trunc, SrcIOp0, Ty, CI);
7964 Value *V2 = InsertCastBefore(Instruction::Trunc, SrcI->getOperand(1),
7965 Ty, CI);
Gabor Greife1f6e4b2008-05-16 19:29:10 +00007966 return BinaryOperator::CreateLShr(V1, V2);
Chris Lattnerd747f012006-11-29 07:04:07 +00007967 }
Chris Lattnerc209b582006-12-05 01:26:29 +00007968 } else { // This is a variable shr.
7969
7970 // Turn 'trunc (lshr X, Y) to bool' into '(X & (1 << Y)) != 0'. This is
7971 // more LLVM instructions, but allows '1 << Y' to be hoisted if
7972 // loop-invariant and CSE'd.
Reid Spencer542964f2007-01-11 18:21:29 +00007973 if (CI.getType() == Type::Int1Ty && SrcI->hasOneUse()) {
Chris Lattnerc209b582006-12-05 01:26:29 +00007974 Value *One = ConstantInt::get(SrcI->getType(), 1);
7975
Reid Spencer2341c222007-02-02 02:16:23 +00007976 Value *V = InsertNewInstBefore(
Gabor Greife1f6e4b2008-05-16 19:29:10 +00007977 BinaryOperator::CreateShl(One, SrcI->getOperand(1),
Reid Spencer2341c222007-02-02 02:16:23 +00007978 "tmp"), CI);
Gabor Greife1f6e4b2008-05-16 19:29:10 +00007979 V = InsertNewInstBefore(BinaryOperator::CreateAnd(V,
Chris Lattnerc209b582006-12-05 01:26:29 +00007980 SrcI->getOperand(0),
7981 "tmp"), CI);
7982 Value *Zero = Constant::getNullValue(V->getType());
Reid Spencer266e42b2006-12-23 06:05:41 +00007983 return new ICmpInst(ICmpInst::ICMP_NE, V, Zero);
Chris Lattnerc209b582006-12-05 01:26:29 +00007984 }
Chris Lattnerd747f012006-11-29 07:04:07 +00007985 }
7986 break;
7987 }
7988 }
7989
7990 return 0;
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007991}
7992
Evan Chengc3cf9f82008-03-24 00:21:34 +00007993/// transformZExtICmp - Transform (zext icmp) to bitwise / integer operations
7994/// in order to eliminate the icmp.
7995Instruction *InstCombiner::transformZExtICmp(ICmpInst *ICI, Instruction &CI,
7996 bool DoXform) {
7997 // If we are just checking for a icmp eq of a single bit and zext'ing it
7998 // to an integer, then shift the bit to the appropriate place and then
7999 // cast to integer to avoid the comparison.
8000 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
8001 const APInt &Op1CV = Op1C->getValue();
8002
8003 // zext (x <s 0) to i32 --> x>>u31 true if signbit set.
8004 // zext (x >s -1) to i32 --> (x>>u31)^1 true if signbit clear.
8005 if ((ICI->getPredicate() == ICmpInst::ICMP_SLT && Op1CV == 0) ||
8006 (ICI->getPredicate() == ICmpInst::ICMP_SGT &&Op1CV.isAllOnesValue())) {
8007 if (!DoXform) return ICI;
8008
8009 Value *In = ICI->getOperand(0);
8010 Value *Sh = ConstantInt::get(In->getType(),
8011 In->getType()->getPrimitiveSizeInBits()-1);
Gabor Greife1f6e4b2008-05-16 19:29:10 +00008012 In = InsertNewInstBefore(BinaryOperator::CreateLShr(In, Sh,
Evan Chengc3cf9f82008-03-24 00:21:34 +00008013 In->getName()+".lobit"),
8014 CI);
8015 if (In->getType() != CI.getType())
Gabor Greife1f6e4b2008-05-16 19:29:10 +00008016 In = CastInst::CreateIntegerCast(In, CI.getType(),
Evan Chengc3cf9f82008-03-24 00:21:34 +00008017 false/*ZExt*/, "tmp", &CI);
8018
8019 if (ICI->getPredicate() == ICmpInst::ICMP_SGT) {
8020 Constant *One = ConstantInt::get(In->getType(), 1);
Gabor Greife1f6e4b2008-05-16 19:29:10 +00008021 In = InsertNewInstBefore(BinaryOperator::CreateXor(In, One,
Evan Chengc3cf9f82008-03-24 00:21:34 +00008022 In->getName()+".not"),
8023 CI);
8024 }
8025
8026 return ReplaceInstUsesWith(CI, In);
8027 }
8028
8029
8030
8031 // zext (X == 0) to i32 --> X^1 iff X has only the low bit set.
8032 // zext (X == 0) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
8033 // zext (X == 1) to i32 --> X iff X has only the low bit set.
8034 // zext (X == 2) to i32 --> X>>1 iff X has only the 2nd bit set.
8035 // zext (X != 0) to i32 --> X iff X has only the low bit set.
8036 // zext (X != 0) to i32 --> X>>1 iff X has only the 2nd bit set.
8037 // zext (X != 1) to i32 --> X^1 iff X has only the low bit set.
8038 // zext (X != 2) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
8039 if ((Op1CV == 0 || Op1CV.isPowerOf2()) &&
8040 // This only works for EQ and NE
8041 ICI->isEquality()) {
8042 // If Op1C some other power of two, convert:
8043 uint32_t BitWidth = Op1C->getType()->getBitWidth();
8044 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
8045 APInt TypeMask(APInt::getAllOnesValue(BitWidth));
8046 ComputeMaskedBits(ICI->getOperand(0), TypeMask, KnownZero, KnownOne);
8047
8048 APInt KnownZeroMask(~KnownZero);
8049 if (KnownZeroMask.isPowerOf2()) { // Exactly 1 possible 1?
8050 if (!DoXform) return ICI;
8051
8052 bool isNE = ICI->getPredicate() == ICmpInst::ICMP_NE;
8053 if (Op1CV != 0 && (Op1CV != KnownZeroMask)) {
8054 // (X&4) == 2 --> false
8055 // (X&4) != 2 --> true
8056 Constant *Res = ConstantInt::get(Type::Int1Ty, isNE);
8057 Res = ConstantExpr::getZExt(Res, CI.getType());
8058 return ReplaceInstUsesWith(CI, Res);
8059 }
8060
8061 uint32_t ShiftAmt = KnownZeroMask.logBase2();
8062 Value *In = ICI->getOperand(0);
8063 if (ShiftAmt) {
8064 // Perform a logical shr by shiftamt.
8065 // Insert the shift to put the result in the low bit.
Gabor Greife1f6e4b2008-05-16 19:29:10 +00008066 In = InsertNewInstBefore(BinaryOperator::CreateLShr(In,
Evan Chengc3cf9f82008-03-24 00:21:34 +00008067 ConstantInt::get(In->getType(), ShiftAmt),
8068 In->getName()+".lobit"), CI);
8069 }
8070
8071 if ((Op1CV != 0) == isNE) { // Toggle the low bit.
8072 Constant *One = ConstantInt::get(In->getType(), 1);
Gabor Greife1f6e4b2008-05-16 19:29:10 +00008073 In = BinaryOperator::CreateXor(In, One, "tmp");
Evan Chengc3cf9f82008-03-24 00:21:34 +00008074 InsertNewInstBefore(cast<Instruction>(In), CI);
8075 }
8076
8077 if (CI.getType() == In->getType())
8078 return ReplaceInstUsesWith(CI, In);
8079 else
Gabor Greife1f6e4b2008-05-16 19:29:10 +00008080 return CastInst::CreateIntegerCast(In, CI.getType(), false/*ZExt*/);
Evan Chengc3cf9f82008-03-24 00:21:34 +00008081 }
8082 }
8083 }
8084
8085 return 0;
8086}
8087
Chris Lattner74ff60f2007-04-11 06:57:46 +00008088Instruction *InstCombiner::visitZExt(ZExtInst &CI) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +00008089 // If one of the common conversion will work ..
8090 if (Instruction *Result = commonIntCastTransforms(CI))
8091 return Result;
8092
8093 Value *Src = CI.getOperand(0);
8094
8095 // If this is a cast of a cast
8096 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
Reid Spencer6c38f0b2006-11-27 01:05:10 +00008097 // If this is a TRUNC followed by a ZEXT then we are dealing with integral
8098 // types and if the sizes are just right we can convert this into a logical
8099 // 'and' which will be much cheaper than the pair of casts.
8100 if (isa<TruncInst>(CSrc)) {
8101 // Get the sizes of the types involved
8102 Value *A = CSrc->getOperand(0);
Zhou Sheng56cda952007-04-02 08:20:41 +00008103 uint32_t SrcSize = A->getType()->getPrimitiveSizeInBits();
8104 uint32_t MidSize = CSrc->getType()->getPrimitiveSizeInBits();
8105 uint32_t DstSize = CI.getType()->getPrimitiveSizeInBits();
Reid Spencer6c38f0b2006-11-27 01:05:10 +00008106 // If we're actually extending zero bits and the trunc is a no-op
8107 if (MidSize < DstSize && SrcSize == DstSize) {
8108 // Replace both of the casts with an And of the type mask.
Zhou Sheng2777a312007-03-28 09:19:01 +00008109 APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
Reid Spencer4154e732007-03-22 20:56:53 +00008110 Constant *AndConst = ConstantInt::get(AndValue);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00008111 Instruction *And =
Gabor Greife1f6e4b2008-05-16 19:29:10 +00008112 BinaryOperator::CreateAnd(CSrc->getOperand(0), AndConst);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00008113 // Unfortunately, if the type changed, we need to cast it back.
8114 if (And->getType() != CI.getType()) {
8115 And->setName(CSrc->getName()+".mask");
8116 InsertNewInstBefore(And, CI);
Gabor Greife1f6e4b2008-05-16 19:29:10 +00008117 And = CastInst::CreateIntegerCast(And, CI.getType(), false/*ZExt*/);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00008118 }
8119 return And;
8120 }
8121 }
8122 }
8123
Evan Chengc3cf9f82008-03-24 00:21:34 +00008124 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src))
8125 return transformZExtICmp(ICI, CI);
Chris Lattnerd0f79422007-04-11 06:53:04 +00008126
Evan Chengc3cf9f82008-03-24 00:21:34 +00008127 BinaryOperator *SrcI = dyn_cast<BinaryOperator>(Src);
8128 if (SrcI && SrcI->getOpcode() == Instruction::Or) {
8129 // zext (or icmp, icmp) --> or (zext icmp), (zext icmp) if at least one
8130 // of the (zext icmp) will be transformed.
8131 ICmpInst *LHS = dyn_cast<ICmpInst>(SrcI->getOperand(0));
8132 ICmpInst *RHS = dyn_cast<ICmpInst>(SrcI->getOperand(1));
8133 if (LHS && RHS && LHS->hasOneUse() && RHS->hasOneUse() &&
8134 (transformZExtICmp(LHS, CI, false) ||
8135 transformZExtICmp(RHS, CI, false))) {
8136 Value *LCast = InsertCastBefore(Instruction::ZExt, LHS, CI.getType(), CI);
8137 Value *RCast = InsertCastBefore(Instruction::ZExt, RHS, CI.getType(), CI);
Gabor Greife1f6e4b2008-05-16 19:29:10 +00008138 return BinaryOperator::Create(Instruction::Or, LCast, RCast);
Chris Lattner7ddbff02007-04-11 05:45:39 +00008139 }
Evan Chengc3cf9f82008-03-24 00:21:34 +00008140 }
8141
Reid Spencer6c38f0b2006-11-27 01:05:10 +00008142 return 0;
8143}
8144
Chris Lattner74ff60f2007-04-11 06:57:46 +00008145Instruction *InstCombiner::visitSExt(SExtInst &CI) {
Chris Lattner20f23722007-04-11 06:12:58 +00008146 if (Instruction *I = commonIntCastTransforms(CI))
8147 return I;
8148
Chris Lattner74ff60f2007-04-11 06:57:46 +00008149 Value *Src = CI.getOperand(0);
8150
Dan Gohman13cbcf1c182008-10-30 20:40:10 +00008151 // Canonicalize sign-extend from i1 to a select.
8152 if (Src->getType() == Type::Int1Ty)
8153 return SelectInst::Create(Src,
8154 ConstantInt::getAllOnesValue(CI.getType()),
8155 Constant::getNullValue(CI.getType()));
Dan Gohman81ab7532008-05-20 21:01:12 +00008156
8157 // See if the value being truncated is already sign extended. If so, just
8158 // eliminate the trunc/sext pair.
8159 if (getOpcode(Src) == Instruction::Trunc) {
8160 Value *Op = cast<User>(Src)->getOperand(0);
8161 unsigned OpBits = cast<IntegerType>(Op->getType())->getBitWidth();
8162 unsigned MidBits = cast<IntegerType>(Src->getType())->getBitWidth();
8163 unsigned DestBits = cast<IntegerType>(CI.getType())->getBitWidth();
8164 unsigned NumSignBits = ComputeNumSignBits(Op);
8165
8166 if (OpBits == DestBits) {
8167 // Op is i32, Mid is i8, and Dest is i32. If Op has more than 24 sign
8168 // bits, it is already ready.
8169 if (NumSignBits > DestBits-MidBits)
8170 return ReplaceInstUsesWith(CI, Op);
8171 } else if (OpBits < DestBits) {
8172 // Op is i32, Mid is i8, and Dest is i64. If Op has more than 24 sign
8173 // bits, just sext from i32.
8174 if (NumSignBits > OpBits-MidBits)
8175 return new SExtInst(Op, CI.getType(), "tmp");
8176 } else {
8177 // Op is i64, Mid is i8, and Dest is i32. If Op has more than 56 sign
8178 // bits, just truncate to i32.
8179 if (NumSignBits > OpBits-MidBits)
8180 return new TruncInst(Op, CI.getType(), "tmp");
8181 }
8182 }
Chris Lattnerf5b353c2008-08-06 07:35:52 +00008183
8184 // If the input is a shl/ashr pair of a same constant, then this is a sign
8185 // extension from a smaller value. If we could trust arbitrary bitwidth
8186 // integers, we could turn this into a truncate to the smaller bit and then
8187 // use a sext for the whole extension. Since we don't, look deeper and check
8188 // for a truncate. If the source and dest are the same type, eliminate the
8189 // trunc and extend and just do shifts. For example, turn:
8190 // %a = trunc i32 %i to i8
8191 // %b = shl i8 %a, 6
8192 // %c = ashr i8 %b, 6
8193 // %d = sext i8 %c to i32
8194 // into:
8195 // %a = shl i32 %i, 30
8196 // %d = ashr i32 %a, 30
8197 Value *A = 0;
8198 ConstantInt *BA = 0, *CA = 0;
8199 if (match(Src, m_AShr(m_Shl(m_Value(A), m_ConstantInt(BA)),
8200 m_ConstantInt(CA))) &&
8201 BA == CA && isa<TruncInst>(A)) {
8202 Value *I = cast<TruncInst>(A)->getOperand(0);
8203 if (I->getType() == CI.getType()) {
8204 unsigned MidSize = Src->getType()->getPrimitiveSizeInBits();
8205 unsigned SrcDstSize = CI.getType()->getPrimitiveSizeInBits();
8206 unsigned ShAmt = CA->getZExtValue()+SrcDstSize-MidSize;
8207 Constant *ShAmtV = ConstantInt::get(CI.getType(), ShAmt);
8208 I = InsertNewInstBefore(BinaryOperator::CreateShl(I, ShAmtV,
8209 CI.getName()), CI);
8210 return BinaryOperator::CreateAShr(I, ShAmtV);
8211 }
8212 }
8213
Chris Lattner20f23722007-04-11 06:12:58 +00008214 return 0;
Reid Spencer6c38f0b2006-11-27 01:05:10 +00008215}
8216
Chris Lattnerfa1e7ee2008-01-27 05:29:54 +00008217/// FitsInFPType - Return a Constant* for the specified FP constant if it fits
8218/// in the specified FP type without changing its value.
Chris Lattner3b187622008-04-20 00:41:09 +00008219static Constant *FitsInFPType(ConstantFP *CFP, const fltSemantics &Sem) {
Dale Johannesen4f0bd682008-10-09 23:00:39 +00008220 bool losesInfo;
Chris Lattnerfa1e7ee2008-01-27 05:29:54 +00008221 APFloat F = CFP->getValueAPF();
Dale Johannesen4f0bd682008-10-09 23:00:39 +00008222 (void)F.convert(Sem, APFloat::rmNearestTiesToEven, &losesInfo);
8223 if (!losesInfo)
Chris Lattner3b187622008-04-20 00:41:09 +00008224 return ConstantFP::get(F);
Chris Lattnerfa1e7ee2008-01-27 05:29:54 +00008225 return 0;
8226}
8227
8228/// LookThroughFPExtensions - If this is an fp extension instruction, look
8229/// through it until we get the source value.
8230static Value *LookThroughFPExtensions(Value *V) {
8231 if (Instruction *I = dyn_cast<Instruction>(V))
8232 if (I->getOpcode() == Instruction::FPExt)
8233 return LookThroughFPExtensions(I->getOperand(0));
8234
8235 // If this value is a constant, return the constant in the smallest FP type
8236 // that can accurately represent it. This allows us to turn
8237 // (float)((double)X+2.0) into x+2.0f.
8238 if (ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
8239 if (CFP->getType() == Type::PPC_FP128Ty)
8240 return V; // No constant folding of this.
8241 // See if the value can be truncated to float and then reextended.
Chris Lattner3b187622008-04-20 00:41:09 +00008242 if (Value *V = FitsInFPType(CFP, APFloat::IEEEsingle))
Chris Lattnerfa1e7ee2008-01-27 05:29:54 +00008243 return V;
8244 if (CFP->getType() == Type::DoubleTy)
8245 return V; // Won't shrink.
Chris Lattner3b187622008-04-20 00:41:09 +00008246 if (Value *V = FitsInFPType(CFP, APFloat::IEEEdouble))
Chris Lattnerfa1e7ee2008-01-27 05:29:54 +00008247 return V;
8248 // Don't try to shrink to various long double types.
8249 }
8250
8251 return V;
8252}
8253
8254Instruction *InstCombiner::visitFPTrunc(FPTruncInst &CI) {
8255 if (Instruction *I = commonCastTransforms(CI))
8256 return I;
8257
8258 // If we have fptrunc(add (fpextend x), (fpextend y)), where x and y are
8259 // smaller than the destination type, we can eliminate the truncate by doing
8260 // the add as the smaller type. This applies to add/sub/mul/div as well as
8261 // many builtins (sqrt, etc).
8262 BinaryOperator *OpI = dyn_cast<BinaryOperator>(CI.getOperand(0));
8263 if (OpI && OpI->hasOneUse()) {
8264 switch (OpI->getOpcode()) {
8265 default: break;
8266 case Instruction::Add:
8267 case Instruction::Sub:
8268 case Instruction::Mul:
8269 case Instruction::FDiv:
8270 case Instruction::FRem:
8271 const Type *SrcTy = OpI->getType();
8272 Value *LHSTrunc = LookThroughFPExtensions(OpI->getOperand(0));
8273 Value *RHSTrunc = LookThroughFPExtensions(OpI->getOperand(1));
8274 if (LHSTrunc->getType() != SrcTy &&
8275 RHSTrunc->getType() != SrcTy) {
8276 unsigned DstSize = CI.getType()->getPrimitiveSizeInBits();
8277 // If the source types were both smaller than the destination type of
8278 // the cast, do this xform.
8279 if (LHSTrunc->getType()->getPrimitiveSizeInBits() <= DstSize &&
8280 RHSTrunc->getType()->getPrimitiveSizeInBits() <= DstSize) {
8281 LHSTrunc = InsertCastBefore(Instruction::FPExt, LHSTrunc,
8282 CI.getType(), CI);
8283 RHSTrunc = InsertCastBefore(Instruction::FPExt, RHSTrunc,
8284 CI.getType(), CI);
Gabor Greife1f6e4b2008-05-16 19:29:10 +00008285 return BinaryOperator::Create(OpI->getOpcode(), LHSTrunc, RHSTrunc);
Chris Lattnerfa1e7ee2008-01-27 05:29:54 +00008286 }
8287 }
8288 break;
8289 }
8290 }
8291 return 0;
Reid Spencer6c38f0b2006-11-27 01:05:10 +00008292}
8293
8294Instruction *InstCombiner::visitFPExt(CastInst &CI) {
8295 return commonCastTransforms(CI);
8296}
8297
Chris Lattnere35fe0f2008-05-19 20:25:04 +00008298Instruction *InstCombiner::visitFPToUI(FPToUIInst &FI) {
Chris Lattner7bdaecb2008-08-06 05:13:06 +00008299 Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
8300 if (OpI == 0)
8301 return commonCastTransforms(FI);
8302
8303 // fptoui(uitofp(X)) --> X
8304 // fptoui(sitofp(X)) --> X
8305 // This is safe if the intermediate type has enough bits in its mantissa to
8306 // accurately represent all values of X. For example, do not do this with
8307 // i64->float->i64. This is also safe for sitofp case, because any negative
8308 // 'X' value would cause an undefined result for the fptoui.
8309 if ((isa<UIToFPInst>(OpI) || isa<SIToFPInst>(OpI)) &&
8310 OpI->getOperand(0)->getType() == FI.getType() &&
8311 (int)FI.getType()->getPrimitiveSizeInBits() < /*extra bit for sign */
8312 OpI->getType()->getFPMantissaWidth())
8313 return ReplaceInstUsesWith(FI, OpI->getOperand(0));
Chris Lattnere35fe0f2008-05-19 20:25:04 +00008314
8315 return commonCastTransforms(FI);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00008316}
8317
Chris Lattnere35fe0f2008-05-19 20:25:04 +00008318Instruction *InstCombiner::visitFPToSI(FPToSIInst &FI) {
Chris Lattner7bdaecb2008-08-06 05:13:06 +00008319 Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
8320 if (OpI == 0)
8321 return commonCastTransforms(FI);
8322
8323 // fptosi(sitofp(X)) --> X
8324 // fptosi(uitofp(X)) --> X
8325 // This is safe if the intermediate type has enough bits in its mantissa to
8326 // accurately represent all values of X. For example, do not do this with
8327 // i64->float->i64. This is also safe for sitofp case, because any negative
8328 // 'X' value would cause an undefined result for the fptoui.
8329 if ((isa<UIToFPInst>(OpI) || isa<SIToFPInst>(OpI)) &&
8330 OpI->getOperand(0)->getType() == FI.getType() &&
8331 (int)FI.getType()->getPrimitiveSizeInBits() <=
8332 OpI->getType()->getFPMantissaWidth())
8333 return ReplaceInstUsesWith(FI, OpI->getOperand(0));
Chris Lattnere35fe0f2008-05-19 20:25:04 +00008334
8335 return commonCastTransforms(FI);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00008336}
8337
8338Instruction *InstCombiner::visitUIToFP(CastInst &CI) {
8339 return commonCastTransforms(CI);
8340}
8341
8342Instruction *InstCombiner::visitSIToFP(CastInst &CI) {
8343 return commonCastTransforms(CI);
8344}
8345
8346Instruction *InstCombiner::visitPtrToInt(CastInst &CI) {
Chris Lattner1db224d2007-04-27 17:44:50 +00008347 return commonPointerCastTransforms(CI);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00008348}
8349
Chris Lattner2940c5c2008-01-08 07:23:51 +00008350Instruction *InstCombiner::visitIntToPtr(IntToPtrInst &CI) {
8351 if (Instruction *I = commonCastTransforms(CI))
8352 return I;
8353
8354 const Type *DestPointee = cast<PointerType>(CI.getType())->getElementType();
8355 if (!DestPointee->isSized()) return 0;
8356
8357 // If this is inttoptr(add (ptrtoint x), cst), try to turn this into a GEP.
8358 ConstantInt *Cst;
8359 Value *X;
8360 if (match(CI.getOperand(0), m_Add(m_Cast<PtrToIntInst>(m_Value(X)),
8361 m_ConstantInt(Cst)))) {
8362 // If the source and destination operands have the same type, see if this
8363 // is a single-index GEP.
8364 if (X->getType() == CI.getType()) {
8365 // Get the size of the pointee type.
Bill Wendling68a930b2008-03-14 05:12:19 +00008366 uint64_t Size = TD->getABITypeSize(DestPointee);
Chris Lattner2940c5c2008-01-08 07:23:51 +00008367
8368 // Convert the constant to intptr type.
8369 APInt Offset = Cst->getValue();
8370 Offset.sextOrTrunc(TD->getPointerSizeInBits());
8371
8372 // If Offset is evenly divisible by Size, we can do this xform.
8373 if (Size && !APIntOps::srem(Offset, APInt(Offset.getBitWidth(), Size))){
8374 Offset = APIntOps::sdiv(Offset, APInt(Offset.getBitWidth(), Size));
Gabor Greife9ecc682008-04-06 20:25:17 +00008375 return GetElementPtrInst::Create(X, ConstantInt::get(Offset));
Chris Lattner2940c5c2008-01-08 07:23:51 +00008376 }
8377 }
8378 // TODO: Could handle other cases, e.g. where add is indexing into field of
8379 // struct etc.
8380 } else if (CI.getOperand(0)->hasOneUse() &&
8381 match(CI.getOperand(0), m_Add(m_Value(X), m_ConstantInt(Cst)))) {
8382 // Otherwise, if this is inttoptr(add x, cst), try to turn this into an
8383 // "inttoptr+GEP" instead of "add+intptr".
8384
8385 // Get the size of the pointee type.
8386 uint64_t Size = TD->getABITypeSize(DestPointee);
8387
8388 // Convert the constant to intptr type.
8389 APInt Offset = Cst->getValue();
8390 Offset.sextOrTrunc(TD->getPointerSizeInBits());
8391
8392 // If Offset is evenly divisible by Size, we can do this xform.
8393 if (Size && !APIntOps::srem(Offset, APInt(Offset.getBitWidth(), Size))){
8394 Offset = APIntOps::sdiv(Offset, APInt(Offset.getBitWidth(), Size));
8395
8396 Instruction *P = InsertNewInstBefore(new IntToPtrInst(X, CI.getType(),
8397 "tmp"), CI);
Gabor Greife9ecc682008-04-06 20:25:17 +00008398 return GetElementPtrInst::Create(P, ConstantInt::get(Offset), "tmp");
Chris Lattner2940c5c2008-01-08 07:23:51 +00008399 }
8400 }
8401 return 0;
Reid Spencer6c38f0b2006-11-27 01:05:10 +00008402}
8403
Chris Lattner1db224d2007-04-27 17:44:50 +00008404Instruction *InstCombiner::visitBitCast(BitCastInst &CI) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +00008405 // If the operands are integer typed then apply the integer transforms,
8406 // otherwise just apply the common ones.
8407 Value *Src = CI.getOperand(0);
8408 const Type *SrcTy = Src->getType();
8409 const Type *DestTy = CI.getType();
8410
Chris Lattner03c49532007-01-15 02:27:26 +00008411 if (SrcTy->isInteger() && DestTy->isInteger()) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +00008412 if (Instruction *Result = commonIntCastTransforms(CI))
8413 return Result;
Chris Lattner1db224d2007-04-27 17:44:50 +00008414 } else if (isa<PointerType>(SrcTy)) {
8415 if (Instruction *I = commonPointerCastTransforms(CI))
8416 return I;
Reid Spencer6c38f0b2006-11-27 01:05:10 +00008417 } else {
8418 if (Instruction *Result = commonCastTransforms(CI))
8419 return Result;
8420 }
8421
8422
8423 // Get rid of casts from one type to the same type. These are useless and can
8424 // be replaced by the operand.
8425 if (DestTy == Src->getType())
8426 return ReplaceInstUsesWith(CI, Src);
8427
Reid Spencer6c38f0b2006-11-27 01:05:10 +00008428 if (const PointerType *DstPTy = dyn_cast<PointerType>(DestTy)) {
Chris Lattner1db224d2007-04-27 17:44:50 +00008429 const PointerType *SrcPTy = cast<PointerType>(SrcTy);
8430 const Type *DstElTy = DstPTy->getElementType();
8431 const Type *SrcElTy = SrcPTy->getElementType();
8432
Nate Begemanf2b0b0e2008-03-31 00:22:16 +00008433 // If the address spaces don't match, don't eliminate the bitcast, which is
8434 // required for changing types.
8435 if (SrcPTy->getAddressSpace() != DstPTy->getAddressSpace())
8436 return 0;
8437
Chris Lattner1db224d2007-04-27 17:44:50 +00008438 // If we are casting a malloc or alloca to a pointer to a type of the same
8439 // size, rewrite the allocation instruction to allocate the "right" type.
8440 if (AllocationInst *AI = dyn_cast<AllocationInst>(Src))
8441 if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
8442 return V;
8443
Chris Lattner361e9812007-05-05 22:32:24 +00008444 // If the source and destination are pointers, and this cast is equivalent
8445 // to a getelementptr X, 0, 0, 0... turn it into the appropriate gep.
Chris Lattner1db224d2007-04-27 17:44:50 +00008446 // This can enhance SROA and other transforms that want type-safe pointers.
8447 Constant *ZeroUInt = Constant::getNullValue(Type::Int32Ty);
8448 unsigned NumZeros = 0;
8449 while (SrcElTy != DstElTy &&
8450 isa<CompositeType>(SrcElTy) && !isa<PointerType>(SrcElTy) &&
8451 SrcElTy->getNumContainedTypes() /* not "{}" */) {
8452 SrcElTy = cast<CompositeType>(SrcElTy)->getTypeAtIndex(ZeroUInt);
8453 ++NumZeros;
8454 }
Chris Lattner6a4adcd2004-09-29 05:07:12 +00008455
Chris Lattner1db224d2007-04-27 17:44:50 +00008456 // If we found a path from the src to dest, create the getelementptr now.
8457 if (SrcElTy == DstElTy) {
8458 SmallVector<Value*, 8> Idxs(NumZeros+1, ZeroUInt);
Gabor Greife9ecc682008-04-06 20:25:17 +00008459 return GetElementPtrInst::Create(Src, Idxs.begin(), Idxs.end(), "",
8460 ((Instruction*) NULL));
Chris Lattnerb19a5c62006-04-12 18:09:35 +00008461 }
Reid Spencer6c38f0b2006-11-27 01:05:10 +00008462 }
Chris Lattnerdfae8be2003-07-24 17:35:25 +00008463
Reid Spencer6c38f0b2006-11-27 01:05:10 +00008464 if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(Src)) {
8465 if (SVI->hasOneUse()) {
8466 // Okay, we have (bitconvert (shuffle ..)). Check to see if this is
8467 // a bitconvert to a vector with the same # elts.
Reid Spencerd84d35b2007-02-15 02:26:10 +00008468 if (isa<VectorType>(DestTy) &&
Mon P Wang25f01062008-11-10 04:46:22 +00008469 cast<VectorType>(DestTy)->getNumElements() ==
8470 SVI->getType()->getNumElements() &&
8471 SVI->getType()->getNumElements() ==
8472 cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements()) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +00008473 CastInst *Tmp;
8474 // If either of the operands is a cast from CI.getType(), then
8475 // evaluating the shuffle in the casted destination's type will allow
8476 // us to eliminate at least one cast.
8477 if (((Tmp = dyn_cast<CastInst>(SVI->getOperand(0))) &&
8478 Tmp->getOperand(0)->getType() == DestTy) ||
8479 ((Tmp = dyn_cast<CastInst>(SVI->getOperand(1))) &&
8480 Tmp->getOperand(0)->getType() == DestTy)) {
Eli Friedman55e4bec2008-11-30 21:09:11 +00008481 Value *LHS = InsertCastBefore(Instruction::BitCast,
8482 SVI->getOperand(0), DestTy, CI);
8483 Value *RHS = InsertCastBefore(Instruction::BitCast,
8484 SVI->getOperand(1), DestTy, CI);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00008485 // Return a new shuffle vector. Use the same element ID's, as we
8486 // know the vector types match #elts.
8487 return new ShuffleVectorInst(LHS, RHS, SVI->getOperand(2));
Chris Lattner99155be2006-05-25 23:24:33 +00008488 }
8489 }
8490 }
8491 }
Chris Lattner260ab202002-04-18 17:39:14 +00008492 return 0;
Chris Lattnerca081252001-12-14 16:52:21 +00008493}
8494
Chris Lattner56e4d3d2004-04-09 23:46:01 +00008495/// GetSelectFoldableOperands - We want to turn code that looks like this:
8496/// %C = or %A, %B
8497/// %D = select %cond, %C, %A
8498/// into:
8499/// %C = select %cond, %B, 0
8500/// %D = or %A, %C
8501///
8502/// Assuming that the specified instruction is an operand to the select, return
8503/// a bitmask indicating which operands of this instruction are foldable if they
8504/// equal the other incoming value of the select.
8505///
8506static unsigned GetSelectFoldableOperands(Instruction *I) {
8507 switch (I->getOpcode()) {
8508 case Instruction::Add:
8509 case Instruction::Mul:
8510 case Instruction::And:
8511 case Instruction::Or:
8512 case Instruction::Xor:
8513 return 3; // Can fold through either operand.
8514 case Instruction::Sub: // Can only fold on the amount subtracted.
8515 case Instruction::Shl: // Can only fold on the shift amount.
Reid Spencerfdff9382006-11-08 06:47:33 +00008516 case Instruction::LShr:
8517 case Instruction::AShr:
Misha Brukmanb1c93172005-04-21 23:48:37 +00008518 return 1;
Chris Lattner56e4d3d2004-04-09 23:46:01 +00008519 default:
8520 return 0; // Cannot fold
8521 }
8522}
8523
8524/// GetSelectFoldableConstant - For the same transformation as the previous
8525/// function, return the identity constant that goes into the select.
8526static Constant *GetSelectFoldableConstant(Instruction *I) {
8527 switch (I->getOpcode()) {
8528 default: assert(0 && "This cannot happen!"); abort();
8529 case Instruction::Add:
8530 case Instruction::Sub:
8531 case Instruction::Or:
8532 case Instruction::Xor:
Chris Lattner56e4d3d2004-04-09 23:46:01 +00008533 case Instruction::Shl:
Reid Spencerfdff9382006-11-08 06:47:33 +00008534 case Instruction::LShr:
8535 case Instruction::AShr:
Reid Spencer2341c222007-02-02 02:16:23 +00008536 return Constant::getNullValue(I->getType());
Chris Lattner56e4d3d2004-04-09 23:46:01 +00008537 case Instruction::And:
Chris Lattner37338922007-06-15 06:23:19 +00008538 return Constant::getAllOnesValue(I->getType());
Chris Lattner56e4d3d2004-04-09 23:46:01 +00008539 case Instruction::Mul:
8540 return ConstantInt::get(I->getType(), 1);
8541 }
8542}
8543
Chris Lattner411336f2005-01-19 21:50:18 +00008544/// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI
8545/// have the same opcode and only one use each. Try to simplify this.
8546Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
8547 Instruction *FI) {
8548 if (TI->getNumOperands() == 1) {
8549 // If this is a non-volatile load or a cast from the same type,
8550 // merge.
Reid Spencer6c38f0b2006-11-27 01:05:10 +00008551 if (TI->isCast()) {
Chris Lattner411336f2005-01-19 21:50:18 +00008552 if (TI->getOperand(0)->getType() != FI->getOperand(0)->getType())
8553 return 0;
8554 } else {
8555 return 0; // unknown unary op.
8556 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00008557
Chris Lattner411336f2005-01-19 21:50:18 +00008558 // Fold this by inserting a select from the input values.
Gabor Greife9ecc682008-04-06 20:25:17 +00008559 SelectInst *NewSI = SelectInst::Create(SI.getCondition(), TI->getOperand(0),
8560 FI->getOperand(0), SI.getName()+".v");
Chris Lattner411336f2005-01-19 21:50:18 +00008561 InsertNewInstBefore(NewSI, SI);
Gabor Greife1f6e4b2008-05-16 19:29:10 +00008562 return CastInst::Create(Instruction::CastOps(TI->getOpcode()), NewSI,
Reid Spencer6c38f0b2006-11-27 01:05:10 +00008563 TI->getType());
Chris Lattner411336f2005-01-19 21:50:18 +00008564 }
8565
Reid Spencer2341c222007-02-02 02:16:23 +00008566 // Only handle binary operators here.
8567 if (!isa<BinaryOperator>(TI))
Chris Lattner411336f2005-01-19 21:50:18 +00008568 return 0;
8569
8570 // Figure out if the operations have any operands in common.
8571 Value *MatchOp, *OtherOpT, *OtherOpF;
8572 bool MatchIsOpZero;
8573 if (TI->getOperand(0) == FI->getOperand(0)) {
8574 MatchOp = TI->getOperand(0);
8575 OtherOpT = TI->getOperand(1);
8576 OtherOpF = FI->getOperand(1);
8577 MatchIsOpZero = true;
8578 } else if (TI->getOperand(1) == FI->getOperand(1)) {
8579 MatchOp = TI->getOperand(1);
8580 OtherOpT = TI->getOperand(0);
8581 OtherOpF = FI->getOperand(0);
8582 MatchIsOpZero = false;
8583 } else if (!TI->isCommutative()) {
8584 return 0;
8585 } else if (TI->getOperand(0) == FI->getOperand(1)) {
8586 MatchOp = TI->getOperand(0);
8587 OtherOpT = TI->getOperand(1);
8588 OtherOpF = FI->getOperand(0);
8589 MatchIsOpZero = true;
8590 } else if (TI->getOperand(1) == FI->getOperand(0)) {
8591 MatchOp = TI->getOperand(1);
8592 OtherOpT = TI->getOperand(0);
8593 OtherOpF = FI->getOperand(1);
8594 MatchIsOpZero = true;
8595 } else {
8596 return 0;
8597 }
8598
8599 // If we reach here, they do have operations in common.
Gabor Greife9ecc682008-04-06 20:25:17 +00008600 SelectInst *NewSI = SelectInst::Create(SI.getCondition(), OtherOpT,
8601 OtherOpF, SI.getName()+".v");
Chris Lattner411336f2005-01-19 21:50:18 +00008602 InsertNewInstBefore(NewSI, SI);
8603
8604 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
8605 if (MatchIsOpZero)
Gabor Greife1f6e4b2008-05-16 19:29:10 +00008606 return BinaryOperator::Create(BO->getOpcode(), MatchOp, NewSI);
Chris Lattner411336f2005-01-19 21:50:18 +00008607 else
Gabor Greife1f6e4b2008-05-16 19:29:10 +00008608 return BinaryOperator::Create(BO->getOpcode(), NewSI, MatchOp);
Chris Lattner411336f2005-01-19 21:50:18 +00008609 }
Reid Spencer2f34b982007-02-02 14:41:37 +00008610 assert(0 && "Shouldn't get here");
8611 return 0;
Chris Lattner411336f2005-01-19 21:50:18 +00008612}
8613
Dan Gohmandafa9c62008-09-16 18:46:06 +00008614/// visitSelectInstWithICmp - Visit a SelectInst that has an
8615/// ICmpInst as its first operand.
8616///
8617Instruction *InstCombiner::visitSelectInstWithICmp(SelectInst &SI,
8618 ICmpInst *ICI) {
8619 bool Changed = false;
8620 ICmpInst::Predicate Pred = ICI->getPredicate();
8621 Value *CmpLHS = ICI->getOperand(0);
8622 Value *CmpRHS = ICI->getOperand(1);
8623 Value *TrueVal = SI.getTrueValue();
8624 Value *FalseVal = SI.getFalseValue();
8625
8626 // Check cases where the comparison is with a constant that
8627 // can be adjusted to fit the min/max idiom. We may edit ICI in
8628 // place here, so make sure the select is the only user.
8629 if (ICI->hasOneUse())
Dan Gohman13cbcf1c182008-10-30 20:40:10 +00008630 if (ConstantInt *CI = dyn_cast<ConstantInt>(CmpRHS)) {
Dan Gohmandafa9c62008-09-16 18:46:06 +00008631 switch (Pred) {
8632 default: break;
8633 case ICmpInst::ICMP_ULT:
8634 case ICmpInst::ICMP_SLT: {
8635 // X < MIN ? T : F --> F
8636 if (CI->isMinValue(Pred == ICmpInst::ICMP_SLT))
8637 return ReplaceInstUsesWith(SI, FalseVal);
8638 // X < C ? X : C-1 --> X > C-1 ? C-1 : X
8639 Constant *AdjustedRHS = SubOne(CI);
8640 if ((CmpLHS == TrueVal && AdjustedRHS == FalseVal) ||
8641 (CmpLHS == FalseVal && AdjustedRHS == TrueVal)) {
8642 Pred = ICmpInst::getSwappedPredicate(Pred);
8643 CmpRHS = AdjustedRHS;
8644 std::swap(FalseVal, TrueVal);
8645 ICI->setPredicate(Pred);
8646 ICI->setOperand(1, CmpRHS);
8647 SI.setOperand(1, TrueVal);
8648 SI.setOperand(2, FalseVal);
8649 Changed = true;
8650 }
8651 break;
8652 }
8653 case ICmpInst::ICMP_UGT:
8654 case ICmpInst::ICMP_SGT: {
8655 // X > MAX ? T : F --> F
8656 if (CI->isMaxValue(Pred == ICmpInst::ICMP_SGT))
8657 return ReplaceInstUsesWith(SI, FalseVal);
8658 // X > C ? X : C+1 --> X < C+1 ? C+1 : X
8659 Constant *AdjustedRHS = AddOne(CI);
8660 if ((CmpLHS == TrueVal && AdjustedRHS == FalseVal) ||
8661 (CmpLHS == FalseVal && AdjustedRHS == TrueVal)) {
8662 Pred = ICmpInst::getSwappedPredicate(Pred);
8663 CmpRHS = AdjustedRHS;
8664 std::swap(FalseVal, TrueVal);
8665 ICI->setPredicate(Pred);
8666 ICI->setOperand(1, CmpRHS);
8667 SI.setOperand(1, TrueVal);
8668 SI.setOperand(2, FalseVal);
8669 Changed = true;
8670 }
8671 break;
8672 }
8673 }
8674
Dan Gohman13cbcf1c182008-10-30 20:40:10 +00008675 // (x <s 0) ? -1 : 0 -> ashr x, 31 -> all ones if signed
8676 // (x >s -1) ? -1 : 0 -> ashr x, 31 -> all ones if not signed
Chris Lattner44152742008-11-16 05:38:51 +00008677 CmpInst::Predicate Pred = CmpInst::BAD_ICMP_PREDICATE;
8678 if (match(TrueVal, m_ConstantInt(-1)) &&
8679 match(FalseVal, m_ConstantInt(0)))
8680 Pred = ICI->getPredicate();
8681 else if (match(TrueVal, m_ConstantInt(0)) &&
8682 match(FalseVal, m_ConstantInt(-1)))
8683 Pred = CmpInst::getInversePredicate(ICI->getPredicate());
8684
Dan Gohman13cbcf1c182008-10-30 20:40:10 +00008685 if (Pred != CmpInst::BAD_ICMP_PREDICATE) {
8686 // If we are just checking for a icmp eq of a single bit and zext'ing it
8687 // to an integer, then shift the bit to the appropriate place and then
8688 // cast to integer to avoid the comparison.
8689 const APInt &Op1CV = CI->getValue();
8690
8691 // sext (x <s 0) to i32 --> x>>s31 true if signbit set.
8692 // sext (x >s -1) to i32 --> (x>>s31)^-1 true if signbit clear.
8693 if ((Pred == ICmpInst::ICMP_SLT && Op1CV == 0) ||
Chris Lattner44152742008-11-16 05:38:51 +00008694 (Pred == ICmpInst::ICMP_SGT && Op1CV.isAllOnesValue())) {
Dan Gohman13cbcf1c182008-10-30 20:40:10 +00008695 Value *In = ICI->getOperand(0);
8696 Value *Sh = ConstantInt::get(In->getType(),
8697 In->getType()->getPrimitiveSizeInBits()-1);
8698 In = InsertNewInstBefore(BinaryOperator::CreateAShr(In, Sh,
8699 In->getName()+".lobit"),
8700 *ICI);
Dan Gohman83eea0b2008-11-02 00:17:33 +00008701 if (In->getType() != SI.getType())
8702 In = CastInst::CreateIntegerCast(In, SI.getType(),
Dan Gohman13cbcf1c182008-10-30 20:40:10 +00008703 true/*SExt*/, "tmp", ICI);
8704
8705 if (Pred == ICmpInst::ICMP_SGT)
8706 In = InsertNewInstBefore(BinaryOperator::CreateNot(In,
8707 In->getName()+".not"), *ICI);
8708
8709 return ReplaceInstUsesWith(SI, In);
8710 }
8711 }
8712 }
8713
Dan Gohmandafa9c62008-09-16 18:46:06 +00008714 if (CmpLHS == TrueVal && CmpRHS == FalseVal) {
8715 // Transform (X == Y) ? X : Y -> Y
8716 if (Pred == ICmpInst::ICMP_EQ)
8717 return ReplaceInstUsesWith(SI, FalseVal);
8718 // Transform (X != Y) ? X : Y -> X
8719 if (Pred == ICmpInst::ICMP_NE)
8720 return ReplaceInstUsesWith(SI, TrueVal);
8721 /// NOTE: if we wanted to, this is where to detect integer MIN/MAX
8722
8723 } else if (CmpLHS == FalseVal && CmpRHS == TrueVal) {
8724 // Transform (X == Y) ? Y : X -> X
8725 if (Pred == ICmpInst::ICMP_EQ)
8726 return ReplaceInstUsesWith(SI, FalseVal);
8727 // Transform (X != Y) ? Y : X -> Y
8728 if (Pred == ICmpInst::ICMP_NE)
8729 return ReplaceInstUsesWith(SI, TrueVal);
8730 /// NOTE: if we wanted to, this is where to detect integer MIN/MAX
8731 }
8732
8733 /// NOTE: if we wanted to, this is where to detect integer ABS
8734
8735 return Changed ? &SI : 0;
8736}
8737
Chris Lattnerb909e8b2004-03-12 05:52:32 +00008738Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
Chris Lattner533bc492004-03-30 19:37:13 +00008739 Value *CondVal = SI.getCondition();
8740 Value *TrueVal = SI.getTrueValue();
8741 Value *FalseVal = SI.getFalseValue();
8742
8743 // select true, X, Y -> X
8744 // select false, X, Y -> Y
Zhou Sheng75b871f2007-01-11 12:24:14 +00008745 if (ConstantInt *C = dyn_cast<ConstantInt>(CondVal))
Reid Spencercddc9df2007-01-12 04:24:46 +00008746 return ReplaceInstUsesWith(SI, C->getZExtValue() ? TrueVal : FalseVal);
Chris Lattner533bc492004-03-30 19:37:13 +00008747
8748 // select C, X, X -> X
8749 if (TrueVal == FalseVal)
8750 return ReplaceInstUsesWith(SI, TrueVal);
8751
Chris Lattner81a7a232004-10-16 18:11:37 +00008752 if (isa<UndefValue>(TrueVal)) // select C, undef, X -> X
8753 return ReplaceInstUsesWith(SI, FalseVal);
8754 if (isa<UndefValue>(FalseVal)) // select C, X, undef -> X
8755 return ReplaceInstUsesWith(SI, TrueVal);
8756 if (isa<UndefValue>(CondVal)) { // select undef, X, Y -> X or Y
8757 if (isa<Constant>(TrueVal))
8758 return ReplaceInstUsesWith(SI, TrueVal);
8759 else
8760 return ReplaceInstUsesWith(SI, FalseVal);
8761 }
8762
Reid Spencer542964f2007-01-11 18:21:29 +00008763 if (SI.getType() == Type::Int1Ty) {
Reid Spencer7a9c62b2007-01-12 07:05:14 +00008764 if (ConstantInt *C = dyn_cast<ConstantInt>(TrueVal)) {
Reid Spencercddc9df2007-01-12 04:24:46 +00008765 if (C->getZExtValue()) {
Chris Lattner1c631e82004-04-08 04:43:23 +00008766 // Change: A = select B, true, C --> A = or B, C
Gabor Greife1f6e4b2008-05-16 19:29:10 +00008767 return BinaryOperator::CreateOr(CondVal, FalseVal);
Chris Lattner1c631e82004-04-08 04:43:23 +00008768 } else {
8769 // Change: A = select B, false, C --> A = and !B, C
8770 Value *NotCond =
Gabor Greife1f6e4b2008-05-16 19:29:10 +00008771 InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
Chris Lattner1c631e82004-04-08 04:43:23 +00008772 "not."+CondVal->getName()), SI);
Gabor Greife1f6e4b2008-05-16 19:29:10 +00008773 return BinaryOperator::CreateAnd(NotCond, FalseVal);
Chris Lattner1c631e82004-04-08 04:43:23 +00008774 }
Reid Spencer7a9c62b2007-01-12 07:05:14 +00008775 } else if (ConstantInt *C = dyn_cast<ConstantInt>(FalseVal)) {
Reid Spencercddc9df2007-01-12 04:24:46 +00008776 if (C->getZExtValue() == false) {
Chris Lattner1c631e82004-04-08 04:43:23 +00008777 // Change: A = select B, C, false --> A = and B, C
Gabor Greife1f6e4b2008-05-16 19:29:10 +00008778 return BinaryOperator::CreateAnd(CondVal, TrueVal);
Chris Lattner1c631e82004-04-08 04:43:23 +00008779 } else {
8780 // Change: A = select B, C, true --> A = or !B, C
8781 Value *NotCond =
Gabor Greife1f6e4b2008-05-16 19:29:10 +00008782 InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
Chris Lattner1c631e82004-04-08 04:43:23 +00008783 "not."+CondVal->getName()), SI);
Gabor Greife1f6e4b2008-05-16 19:29:10 +00008784 return BinaryOperator::CreateOr(NotCond, TrueVal);
Chris Lattner1c631e82004-04-08 04:43:23 +00008785 }
8786 }
Chris Lattnerc00e8ad2007-11-25 21:27:53 +00008787
8788 // select a, b, a -> a&b
8789 // select a, a, b -> a|b
8790 if (CondVal == TrueVal)
Gabor Greife1f6e4b2008-05-16 19:29:10 +00008791 return BinaryOperator::CreateOr(CondVal, FalseVal);
Chris Lattnerc00e8ad2007-11-25 21:27:53 +00008792 else if (CondVal == FalseVal)
Gabor Greife1f6e4b2008-05-16 19:29:10 +00008793 return BinaryOperator::CreateAnd(CondVal, TrueVal);
Zhou Sheng75b871f2007-01-11 12:24:14 +00008794 }
Chris Lattner1c631e82004-04-08 04:43:23 +00008795
Chris Lattner183b3362004-04-09 19:05:30 +00008796 // Selecting between two integer constants?
8797 if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
8798 if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
Chris Lattner20f23722007-04-11 06:12:58 +00008799 // select C, 1, 0 -> zext C to int
Reid Spencer959a21d2007-03-23 21:24:59 +00008800 if (FalseValC->isZero() && TrueValC->getValue() == 1) {
Gabor Greife1f6e4b2008-05-16 19:29:10 +00008801 return CastInst::Create(Instruction::ZExt, CondVal, SI.getType());
Reid Spencer959a21d2007-03-23 21:24:59 +00008802 } else if (TrueValC->isZero() && FalseValC->getValue() == 1) {
Chris Lattner20f23722007-04-11 06:12:58 +00008803 // select C, 0, 1 -> zext !C to int
Chris Lattner183b3362004-04-09 19:05:30 +00008804 Value *NotCond =
Gabor Greife1f6e4b2008-05-16 19:29:10 +00008805 InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
Chris Lattnercf7baf32004-04-09 18:19:44 +00008806 "not."+CondVal->getName()), SI);
Gabor Greife1f6e4b2008-05-16 19:29:10 +00008807 return CastInst::Create(Instruction::ZExt, NotCond, SI.getType());
Chris Lattnercf7baf32004-04-09 18:19:44 +00008808 }
Chris Lattner35167c32004-06-09 07:59:58 +00008809
Reid Spencer266e42b2006-12-23 06:05:41 +00008810 if (ICmpInst *IC = dyn_cast<ICmpInst>(SI.getCondition())) {
Chris Lattner380c7e92006-09-20 04:44:59 +00008811
Reid Spencer266e42b2006-12-23 06:05:41 +00008812 // (x <s 0) ? -1 : 0 -> ashr x, 31
Reid Spencer959a21d2007-03-23 21:24:59 +00008813 if (TrueValC->isAllOnesValue() && FalseValC->isZero())
Chris Lattner380c7e92006-09-20 04:44:59 +00008814 if (ConstantInt *CmpCst = dyn_cast<ConstantInt>(IC->getOperand(1))) {
Chris Lattner20f23722007-04-11 06:12:58 +00008815 if (IC->getPredicate() == ICmpInst::ICMP_SLT && CmpCst->isZero()) {
Chris Lattner380c7e92006-09-20 04:44:59 +00008816 // The comparison constant and the result are not neccessarily the
Reid Spencer6c38f0b2006-11-27 01:05:10 +00008817 // same width. Make an all-ones value by inserting a AShr.
Chris Lattner380c7e92006-09-20 04:44:59 +00008818 Value *X = IC->getOperand(0);
Zhou Sheng56cda952007-04-02 08:20:41 +00008819 uint32_t Bits = X->getType()->getPrimitiveSizeInBits();
Reid Spencer2341c222007-02-02 02:16:23 +00008820 Constant *ShAmt = ConstantInt::get(X->getType(), Bits-1);
Gabor Greife1f6e4b2008-05-16 19:29:10 +00008821 Instruction *SRA = BinaryOperator::Create(Instruction::AShr, X,
Reid Spencer2341c222007-02-02 02:16:23 +00008822 ShAmt, "ones");
Chris Lattner380c7e92006-09-20 04:44:59 +00008823 InsertNewInstBefore(SRA, SI);
Eli Friedman55e4bec2008-11-30 21:09:11 +00008824
8825 // Then cast to the appropriate width.
8826 return CastInst::CreateIntegerCast(SRA, SI.getType(), true);
Chris Lattner380c7e92006-09-20 04:44:59 +00008827 }
8828 }
8829
8830
8831 // If one of the constants is zero (we know they can't both be) and we
Chris Lattner20f23722007-04-11 06:12:58 +00008832 // have an icmp instruction with zero, and we have an 'and' with the
Chris Lattner380c7e92006-09-20 04:44:59 +00008833 // non-constant value, eliminate this whole mess. This corresponds to
8834 // cases like this: ((X & 27) ? 27 : 0)
Reid Spencer959a21d2007-03-23 21:24:59 +00008835 if (TrueValC->isZero() || FalseValC->isZero())
Chris Lattnerb3f24c92006-09-18 04:22:48 +00008836 if (IC->isEquality() && isa<ConstantInt>(IC->getOperand(1)) &&
Chris Lattner35167c32004-06-09 07:59:58 +00008837 cast<Constant>(IC->getOperand(1))->isNullValue())
8838 if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
8839 if (ICA->getOpcode() == Instruction::And &&
Misha Brukmanb1c93172005-04-21 23:48:37 +00008840 isa<ConstantInt>(ICA->getOperand(1)) &&
8841 (ICA->getOperand(1) == TrueValC ||
8842 ICA->getOperand(1) == FalseValC) &&
Chris Lattner35167c32004-06-09 07:59:58 +00008843 isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
8844 // Okay, now we know that everything is set up, we just don't
Reid Spencer266e42b2006-12-23 06:05:41 +00008845 // know whether we have a icmp_ne or icmp_eq and whether the
8846 // true or false val is the zero.
Reid Spencer959a21d2007-03-23 21:24:59 +00008847 bool ShouldNotVal = !TrueValC->isZero();
Reid Spencer266e42b2006-12-23 06:05:41 +00008848 ShouldNotVal ^= IC->getPredicate() == ICmpInst::ICMP_NE;
Chris Lattner35167c32004-06-09 07:59:58 +00008849 Value *V = ICA;
8850 if (ShouldNotVal)
Gabor Greife1f6e4b2008-05-16 19:29:10 +00008851 V = InsertNewInstBefore(BinaryOperator::Create(
Chris Lattner35167c32004-06-09 07:59:58 +00008852 Instruction::Xor, V, ICA->getOperand(1)), SI);
8853 return ReplaceInstUsesWith(SI, V);
8854 }
Chris Lattner380c7e92006-09-20 04:44:59 +00008855 }
Chris Lattner533bc492004-03-30 19:37:13 +00008856 }
Chris Lattner623fba12004-04-10 22:21:27 +00008857
8858 // See if we are selecting two values based on a comparison of the two values.
Reid Spencer266e42b2006-12-23 06:05:41 +00008859 if (FCmpInst *FCI = dyn_cast<FCmpInst>(CondVal)) {
8860 if (FCI->getOperand(0) == TrueVal && FCI->getOperand(1) == FalseVal) {
Chris Lattner623fba12004-04-10 22:21:27 +00008861 // Transform (X == Y) ? X : Y -> Y
Dale Johannesen9d559cf2007-10-03 17:45:27 +00008862 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
8863 // This is not safe in general for floating point:
8864 // consider X== -0, Y== +0.
8865 // It becomes safe if either operand is a nonzero constant.
8866 ConstantFP *CFPt, *CFPf;
8867 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
8868 !CFPt->getValueAPF().isZero()) ||
8869 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
8870 !CFPf->getValueAPF().isZero()))
Chris Lattner623fba12004-04-10 22:21:27 +00008871 return ReplaceInstUsesWith(SI, FalseVal);
Dale Johannesen9d559cf2007-10-03 17:45:27 +00008872 }
Chris Lattner623fba12004-04-10 22:21:27 +00008873 // Transform (X != Y) ? X : Y -> X
Reid Spencer266e42b2006-12-23 06:05:41 +00008874 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
Chris Lattner623fba12004-04-10 22:21:27 +00008875 return ReplaceInstUsesWith(SI, TrueVal);
Dan Gohmandafa9c62008-09-16 18:46:06 +00008876 // NOTE: if we wanted to, this is where to detect MIN/MAX
Chris Lattner623fba12004-04-10 22:21:27 +00008877
Reid Spencer266e42b2006-12-23 06:05:41 +00008878 } else if (FCI->getOperand(0) == FalseVal && FCI->getOperand(1) == TrueVal){
Chris Lattner623fba12004-04-10 22:21:27 +00008879 // Transform (X == Y) ? Y : X -> X
Dale Johannesen9d559cf2007-10-03 17:45:27 +00008880 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
8881 // This is not safe in general for floating point:
8882 // consider X== -0, Y== +0.
8883 // It becomes safe if either operand is a nonzero constant.
8884 ConstantFP *CFPt, *CFPf;
8885 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
8886 !CFPt->getValueAPF().isZero()) ||
8887 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
8888 !CFPf->getValueAPF().isZero()))
8889 return ReplaceInstUsesWith(SI, FalseVal);
8890 }
Chris Lattner623fba12004-04-10 22:21:27 +00008891 // Transform (X != Y) ? Y : X -> Y
Reid Spencer266e42b2006-12-23 06:05:41 +00008892 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
8893 return ReplaceInstUsesWith(SI, TrueVal);
Dan Gohmandafa9c62008-09-16 18:46:06 +00008894 // NOTE: if we wanted to, this is where to detect MIN/MAX
Reid Spencer266e42b2006-12-23 06:05:41 +00008895 }
Dan Gohmandafa9c62008-09-16 18:46:06 +00008896 // NOTE: if we wanted to, this is where to detect ABS
Reid Spencer266e42b2006-12-23 06:05:41 +00008897 }
8898
8899 // See if we are selecting two values based on a comparison of the two values.
Dan Gohmandafa9c62008-09-16 18:46:06 +00008900 if (ICmpInst *ICI = dyn_cast<ICmpInst>(CondVal))
8901 if (Instruction *Result = visitSelectInstWithICmp(SI, ICI))
8902 return Result;
Misha Brukmanb1c93172005-04-21 23:48:37 +00008903
Chris Lattnera04c9042005-01-13 22:52:24 +00008904 if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
8905 if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
8906 if (TI->hasOneUse() && FI->hasOneUse()) {
Chris Lattnera04c9042005-01-13 22:52:24 +00008907 Instruction *AddOp = 0, *SubOp = 0;
8908
Chris Lattner411336f2005-01-19 21:50:18 +00008909 // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
8910 if (TI->getOpcode() == FI->getOpcode())
8911 if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
8912 return IV;
8913
8914 // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))). This is
8915 // even legal for FP.
Chris Lattnera04c9042005-01-13 22:52:24 +00008916 if (TI->getOpcode() == Instruction::Sub &&
8917 FI->getOpcode() == Instruction::Add) {
8918 AddOp = FI; SubOp = TI;
8919 } else if (FI->getOpcode() == Instruction::Sub &&
8920 TI->getOpcode() == Instruction::Add) {
8921 AddOp = TI; SubOp = FI;
8922 }
8923
8924 if (AddOp) {
8925 Value *OtherAddOp = 0;
8926 if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
8927 OtherAddOp = AddOp->getOperand(1);
8928 } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
8929 OtherAddOp = AddOp->getOperand(0);
8930 }
8931
8932 if (OtherAddOp) {
Chris Lattnerb580d262006-02-24 18:05:58 +00008933 // So at this point we know we have (Y -> OtherAddOp):
8934 // select C, (add X, Y), (sub X, Z)
8935 Value *NegVal; // Compute -Z
8936 if (Constant *C = dyn_cast<Constant>(SubOp->getOperand(1))) {
8937 NegVal = ConstantExpr::getNeg(C);
8938 } else {
8939 NegVal = InsertNewInstBefore(
Gabor Greife1f6e4b2008-05-16 19:29:10 +00008940 BinaryOperator::CreateNeg(SubOp->getOperand(1), "tmp"), SI);
Chris Lattnera04c9042005-01-13 22:52:24 +00008941 }
Chris Lattnerb580d262006-02-24 18:05:58 +00008942
8943 Value *NewTrueOp = OtherAddOp;
8944 Value *NewFalseOp = NegVal;
8945 if (AddOp != TI)
8946 std::swap(NewTrueOp, NewFalseOp);
8947 Instruction *NewSel =
Gabor Greif697e94c2008-05-15 10:04:30 +00008948 SelectInst::Create(CondVal, NewTrueOp,
8949 NewFalseOp, SI.getName() + ".p");
Chris Lattnerb580d262006-02-24 18:05:58 +00008950
8951 NewSel = InsertNewInstBefore(NewSel, SI);
Gabor Greife1f6e4b2008-05-16 19:29:10 +00008952 return BinaryOperator::CreateAdd(SubOp->getOperand(0), NewSel);
Chris Lattnera04c9042005-01-13 22:52:24 +00008953 }
8954 }
8955 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00008956
Chris Lattner56e4d3d2004-04-09 23:46:01 +00008957 // See if we can fold the select into one of our operands.
Chris Lattner03c49532007-01-15 02:27:26 +00008958 if (SI.getType()->isInteger()) {
Chris Lattner56e4d3d2004-04-09 23:46:01 +00008959 // See the comment above GetSelectFoldableOperands for a description of the
8960 // transformation we are doing here.
8961 if (Instruction *TVI = dyn_cast<Instruction>(TrueVal))
8962 if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
8963 !isa<Constant>(FalseVal))
8964 if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
8965 unsigned OpToFold = 0;
8966 if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
8967 OpToFold = 1;
8968 } else if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
8969 OpToFold = 2;
8970 }
8971
8972 if (OpToFold) {
8973 Constant *C = GetSelectFoldableConstant(TVI);
Chris Lattner56e4d3d2004-04-09 23:46:01 +00008974 Instruction *NewSel =
Gabor Greif697e94c2008-05-15 10:04:30 +00008975 SelectInst::Create(SI.getCondition(),
8976 TVI->getOperand(2-OpToFold), C);
Chris Lattner56e4d3d2004-04-09 23:46:01 +00008977 InsertNewInstBefore(NewSel, SI);
Chris Lattner6e0123b2007-02-11 01:23:03 +00008978 NewSel->takeName(TVI);
Chris Lattner56e4d3d2004-04-09 23:46:01 +00008979 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
Gabor Greife1f6e4b2008-05-16 19:29:10 +00008980 return BinaryOperator::Create(BO->getOpcode(), FalseVal, NewSel);
Chris Lattner56e4d3d2004-04-09 23:46:01 +00008981 else {
8982 assert(0 && "Unknown instruction!!");
8983 }
8984 }
8985 }
Chris Lattner6862fbd2004-09-29 17:40:11 +00008986
Chris Lattner56e4d3d2004-04-09 23:46:01 +00008987 if (Instruction *FVI = dyn_cast<Instruction>(FalseVal))
8988 if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
8989 !isa<Constant>(TrueVal))
8990 if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
8991 unsigned OpToFold = 0;
8992 if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
8993 OpToFold = 1;
8994 } else if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
8995 OpToFold = 2;
8996 }
8997
8998 if (OpToFold) {
8999 Constant *C = GetSelectFoldableConstant(FVI);
Chris Lattner56e4d3d2004-04-09 23:46:01 +00009000 Instruction *NewSel =
Gabor Greif697e94c2008-05-15 10:04:30 +00009001 SelectInst::Create(SI.getCondition(), C,
9002 FVI->getOperand(2-OpToFold));
Chris Lattner56e4d3d2004-04-09 23:46:01 +00009003 InsertNewInstBefore(NewSel, SI);
Chris Lattner6e0123b2007-02-11 01:23:03 +00009004 NewSel->takeName(FVI);
Chris Lattner56e4d3d2004-04-09 23:46:01 +00009005 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
Gabor Greife1f6e4b2008-05-16 19:29:10 +00009006 return BinaryOperator::Create(BO->getOpcode(), TrueVal, NewSel);
Reid Spencer2341c222007-02-02 02:16:23 +00009007 else
Chris Lattner56e4d3d2004-04-09 23:46:01 +00009008 assert(0 && "Unknown instruction!!");
Chris Lattner56e4d3d2004-04-09 23:46:01 +00009009 }
9010 }
9011 }
Chris Lattnerd6f636a2005-04-24 07:30:14 +00009012
9013 if (BinaryOperator::isNot(CondVal)) {
9014 SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
9015 SI.setOperand(1, FalseVal);
9016 SI.setOperand(2, TrueVal);
9017 return &SI;
9018 }
9019
Chris Lattnerb909e8b2004-03-12 05:52:32 +00009020 return 0;
9021}
9022
Dan Gohman99b7b3f2008-04-10 18:43:06 +00009023/// EnforceKnownAlignment - If the specified pointer points to an object that
9024/// we control, modify the object's alignment to PrefAlign. This isn't
9025/// often possible though. If alignment is important, a more reliable approach
9026/// is to simply align all global variables and allocation instructions to
9027/// their preferred alignment from the beginning.
9028///
9029static unsigned EnforceKnownAlignment(Value *V,
9030 unsigned Align, unsigned PrefAlign) {
Chris Lattnera8e4b4b2007-08-09 19:05:49 +00009031
Dan Gohman99b7b3f2008-04-10 18:43:06 +00009032 User *U = dyn_cast<User>(V);
9033 if (!U) return Align;
9034
9035 switch (getOpcode(U)) {
9036 default: break;
9037 case Instruction::BitCast:
9038 return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
9039 case Instruction::GetElementPtr: {
Chris Lattner82f2ef22006-03-06 20:18:44 +00009040 // If all indexes are zero, it is just the alignment of the base pointer.
9041 bool AllZeroOperands = true;
Gabor Greif431e9562008-06-12 21:51:29 +00009042 for (User::op_iterator i = U->op_begin() + 1, e = U->op_end(); i != e; ++i)
Gabor Greiff6d8e772008-06-12 21:37:33 +00009043 if (!isa<Constant>(*i) ||
9044 !cast<Constant>(*i)->isNullValue()) {
Chris Lattner82f2ef22006-03-06 20:18:44 +00009045 AllZeroOperands = false;
9046 break;
9047 }
Chris Lattnera8e4b4b2007-08-09 19:05:49 +00009048
9049 if (AllZeroOperands) {
9050 // Treat this like a bitcast.
Dan Gohman99b7b3f2008-04-10 18:43:06 +00009051 return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
Chris Lattnera8e4b4b2007-08-09 19:05:49 +00009052 }
Dan Gohman99b7b3f2008-04-10 18:43:06 +00009053 break;
Chris Lattner82f2ef22006-03-06 20:18:44 +00009054 }
Dan Gohman99b7b3f2008-04-10 18:43:06 +00009055 }
9056
9057 if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
9058 // If there is a large requested alignment and we can, bump up the alignment
9059 // of the global.
9060 if (!GV->isDeclaration()) {
9061 GV->setAlignment(PrefAlign);
9062 Align = PrefAlign;
9063 }
9064 } else if (AllocationInst *AI = dyn_cast<AllocationInst>(V)) {
9065 // If there is a requested alignment and if this is an alloca, round up. We
9066 // don't do this for malloc, because some systems can't respect the request.
9067 if (isa<AllocaInst>(AI)) {
9068 AI->setAlignment(PrefAlign);
9069 Align = PrefAlign;
9070 }
9071 }
9072
9073 return Align;
9074}
9075
9076/// GetOrEnforceKnownAlignment - If the specified pointer has an alignment that
9077/// we can determine, return it, otherwise return 0. If PrefAlign is specified,
9078/// and it is more than the alignment of the ultimate object, see if we can
9079/// increase the alignment of the ultimate object, making this check succeed.
9080unsigned InstCombiner::GetOrEnforceKnownAlignment(Value *V,
9081 unsigned PrefAlign) {
9082 unsigned BitWidth = TD ? TD->getTypeSizeInBits(V->getType()) :
9083 sizeof(PrefAlign) * CHAR_BIT;
9084 APInt Mask = APInt::getAllOnesValue(BitWidth);
9085 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
9086 ComputeMaskedBits(V, Mask, KnownZero, KnownOne);
9087 unsigned TrailZ = KnownZero.countTrailingOnes();
9088 unsigned Align = 1u << std::min(BitWidth - 1, TrailZ);
9089
9090 if (PrefAlign > Align)
9091 Align = EnforceKnownAlignment(V, Align, PrefAlign);
9092
9093 // We don't need to make any adjustment.
9094 return Align;
Chris Lattner82f2ef22006-03-06 20:18:44 +00009095}
9096
Chris Lattner57974c82008-01-13 23:50:23 +00009097Instruction *InstCombiner::SimplifyMemTransfer(MemIntrinsic *MI) {
Dan Gohman99b7b3f2008-04-10 18:43:06 +00009098 unsigned DstAlign = GetOrEnforceKnownAlignment(MI->getOperand(1));
9099 unsigned SrcAlign = GetOrEnforceKnownAlignment(MI->getOperand(2));
Chris Lattner57974c82008-01-13 23:50:23 +00009100 unsigned MinAlign = std::min(DstAlign, SrcAlign);
9101 unsigned CopyAlign = MI->getAlignment()->getZExtValue();
9102
9103 if (CopyAlign < MinAlign) {
9104 MI->setAlignment(ConstantInt::get(Type::Int32Ty, MinAlign));
9105 return MI;
9106 }
9107
9108 // If MemCpyInst length is 1/2/4/8 bytes then replace memcpy with
9109 // load/store.
9110 ConstantInt *MemOpLength = dyn_cast<ConstantInt>(MI->getOperand(3));
9111 if (MemOpLength == 0) return 0;
9112
Chris Lattner92bd7852008-01-14 00:28:35 +00009113 // Source and destination pointer types are always "i8*" for intrinsic. See
9114 // if the size is something we can handle with a single primitive load/store.
9115 // A single load+store correctly handles overlapping memory in the memmove
9116 // case.
Chris Lattner57974c82008-01-13 23:50:23 +00009117 unsigned Size = MemOpLength->getZExtValue();
Chris Lattner2dc44262008-04-30 06:39:11 +00009118 if (Size == 0) return MI; // Delete this mem transfer.
9119
9120 if (Size > 8 || (Size&(Size-1)))
Chris Lattner92bd7852008-01-14 00:28:35 +00009121 return 0; // If not 1/2/4/8 bytes, exit.
Chris Lattner57974c82008-01-13 23:50:23 +00009122
Chris Lattner92bd7852008-01-14 00:28:35 +00009123 // Use an integer load+store unless we can find something better.
Chris Lattner57974c82008-01-13 23:50:23 +00009124 Type *NewPtrTy = PointerType::getUnqual(IntegerType::get(Size<<3));
Chris Lattner92bd7852008-01-14 00:28:35 +00009125
9126 // Memcpy forces the use of i8* for the source and destination. That means
9127 // that if you're using memcpy to move one double around, you'll get a cast
9128 // from double* to i8*. We'd much rather use a double load+store rather than
9129 // an i64 load+store, here because this improves the odds that the source or
9130 // dest address will be promotable. See if we can find a better type than the
9131 // integer datatype.
9132 if (Value *Op = getBitCastOperand(MI->getOperand(1))) {
9133 const Type *SrcETy = cast<PointerType>(Op->getType())->getElementType();
9134 if (SrcETy->isSized() && TD->getTypeStoreSize(SrcETy) == Size) {
9135 // The SrcETy might be something like {{{double}}} or [1 x double]. Rip
9136 // down through these levels if so.
Dan Gohman53b26982008-05-23 01:52:21 +00009137 while (!SrcETy->isSingleValueType()) {
Chris Lattner92bd7852008-01-14 00:28:35 +00009138 if (const StructType *STy = dyn_cast<StructType>(SrcETy)) {
9139 if (STy->getNumElements() == 1)
9140 SrcETy = STy->getElementType(0);
9141 else
9142 break;
9143 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcETy)) {
9144 if (ATy->getNumElements() == 1)
9145 SrcETy = ATy->getElementType();
9146 else
9147 break;
9148 } else
9149 break;
9150 }
9151
Dan Gohman53b26982008-05-23 01:52:21 +00009152 if (SrcETy->isSingleValueType())
Chris Lattner92bd7852008-01-14 00:28:35 +00009153 NewPtrTy = PointerType::getUnqual(SrcETy);
9154 }
9155 }
9156
9157
Chris Lattner57974c82008-01-13 23:50:23 +00009158 // If the memcpy/memmove provides better alignment info than we can
9159 // infer, use it.
9160 SrcAlign = std::max(SrcAlign, CopyAlign);
9161 DstAlign = std::max(DstAlign, CopyAlign);
9162
9163 Value *Src = InsertBitCastBefore(MI->getOperand(2), NewPtrTy, *MI);
9164 Value *Dest = InsertBitCastBefore(MI->getOperand(1), NewPtrTy, *MI);
Chris Lattner92bd7852008-01-14 00:28:35 +00009165 Instruction *L = new LoadInst(Src, "tmp", false, SrcAlign);
9166 InsertNewInstBefore(L, *MI);
9167 InsertNewInstBefore(new StoreInst(L, Dest, false, DstAlign), *MI);
9168
9169 // Set the size of the copy to 0, it will be deleted on the next iteration.
9170 MI->setOperand(3, Constant::getNullValue(MemOpLength->getType()));
9171 return MI;
Chris Lattner57974c82008-01-13 23:50:23 +00009172}
Chris Lattnerb909e8b2004-03-12 05:52:32 +00009173
Chris Lattner2dc44262008-04-30 06:39:11 +00009174Instruction *InstCombiner::SimplifyMemSet(MemSetInst *MI) {
9175 unsigned Alignment = GetOrEnforceKnownAlignment(MI->getDest());
9176 if (MI->getAlignment()->getZExtValue() < Alignment) {
9177 MI->setAlignment(ConstantInt::get(Type::Int32Ty, Alignment));
9178 return MI;
9179 }
9180
9181 // Extract the length and alignment and fill if they are constant.
9182 ConstantInt *LenC = dyn_cast<ConstantInt>(MI->getLength());
9183 ConstantInt *FillC = dyn_cast<ConstantInt>(MI->getValue());
9184 if (!LenC || !FillC || FillC->getType() != Type::Int8Ty)
9185 return 0;
9186 uint64_t Len = LenC->getZExtValue();
9187 Alignment = MI->getAlignment()->getZExtValue();
9188
9189 // If the length is zero, this is a no-op
9190 if (Len == 0) return MI; // memset(d,c,0,a) -> noop
9191
9192 // memset(s,c,n) -> store s, c (for n=1,2,4,8)
9193 if (Len <= 8 && isPowerOf2_32((uint32_t)Len)) {
9194 const Type *ITy = IntegerType::get(Len*8); // n=1 -> i8.
9195
9196 Value *Dest = MI->getDest();
9197 Dest = InsertBitCastBefore(Dest, PointerType::getUnqual(ITy), *MI);
9198
9199 // Alignment 0 is identity for alignment 1 for memset, but not store.
9200 if (Alignment == 0) Alignment = 1;
9201
9202 // Extract the fill value and store.
9203 uint64_t Fill = FillC->getZExtValue()*0x0101010101010101ULL;
9204 InsertNewInstBefore(new StoreInst(ConstantInt::get(ITy, Fill), Dest, false,
9205 Alignment), *MI);
9206
9207 // Set the size of the copy to 0, it will be deleted on the next iteration.
9208 MI->setLength(Constant::getNullValue(LenC->getType()));
9209 return MI;
9210 }
9211
9212 return 0;
9213}
9214
9215
Chris Lattnerc66b2232006-01-13 20:11:04 +00009216/// visitCallInst - CallInst simplification. This mostly only handles folding
9217/// of intrinsic instructions. For normal calls, it allows visitCallSite to do
9218/// the heavy lifting.
9219///
Chris Lattner970c33a2003-06-19 17:00:31 +00009220Instruction *InstCombiner::visitCallInst(CallInst &CI) {
Chris Lattnerc66b2232006-01-13 20:11:04 +00009221 IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
9222 if (!II) return visitCallSite(&CI);
9223
Chris Lattner51ea1272004-02-28 05:22:00 +00009224 // Intrinsics cannot occur in an invoke, so handle them here instead of in
9225 // visitCallSite.
Chris Lattnerc66b2232006-01-13 20:11:04 +00009226 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
Chris Lattner00648e12004-10-12 04:52:52 +00009227 bool Changed = false;
9228
9229 // memmove/cpy/set of zero bytes is a noop.
9230 if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
9231 if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
9232
Chris Lattner00648e12004-10-12 04:52:52 +00009233 if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
Reid Spencere0fc4df2006-10-20 07:07:24 +00009234 if (CI->getZExtValue() == 1) {
Chris Lattner00648e12004-10-12 04:52:52 +00009235 // Replace the instruction with just byte operations. We would
9236 // transform other cases to loads/stores, but we don't know if
9237 // alignment is sufficient.
9238 }
Chris Lattner51ea1272004-02-28 05:22:00 +00009239 }
9240
Chris Lattner00648e12004-10-12 04:52:52 +00009241 // If we have a memmove and the source operation is a constant global,
9242 // then the source and dest pointers can't alias, so we can change this
9243 // into a call to memcpy.
Chris Lattner57974c82008-01-13 23:50:23 +00009244 if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(MI)) {
Chris Lattner00648e12004-10-12 04:52:52 +00009245 if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
9246 if (GVSrc->isConstant()) {
9247 Module *M = CI.getParent()->getParent()->getParent();
Chris Lattnerdd708342008-11-21 16:42:48 +00009248 Intrinsic::ID MemCpyID = Intrinsic::memcpy;
9249 const Type *Tys[1];
9250 Tys[0] = CI.getOperand(3)->getType();
9251 CI.setOperand(0,
9252 Intrinsic::getDeclaration(M, MemCpyID, Tys, 1));
Chris Lattner00648e12004-10-12 04:52:52 +00009253 Changed = true;
9254 }
Chris Lattnerecdefb52008-05-28 05:30:41 +00009255
9256 // memmove(x,x,size) -> noop.
9257 if (MMI->getSource() == MMI->getDest())
9258 return EraseInstFromFunction(CI);
Chris Lattner82f2ef22006-03-06 20:18:44 +00009259 }
Chris Lattner00648e12004-10-12 04:52:52 +00009260
Chris Lattner82f2ef22006-03-06 20:18:44 +00009261 // If we can determine a pointer alignment that is bigger than currently
9262 // set, update the alignment.
9263 if (isa<MemCpyInst>(MI) || isa<MemMoveInst>(MI)) {
Chris Lattner57974c82008-01-13 23:50:23 +00009264 if (Instruction *I = SimplifyMemTransfer(MI))
9265 return I;
Chris Lattner2dc44262008-04-30 06:39:11 +00009266 } else if (MemSetInst *MSI = dyn_cast<MemSetInst>(MI)) {
9267 if (Instruction *I = SimplifyMemSet(MSI))
9268 return I;
Chris Lattner82f2ef22006-03-06 20:18:44 +00009269 }
9270
Chris Lattnerc66b2232006-01-13 20:11:04 +00009271 if (Changed) return II;
Chris Lattneref36dcd2008-06-18 04:33:20 +00009272 }
9273
9274 switch (II->getIntrinsicID()) {
9275 default: break;
9276 case Intrinsic::bswap:
9277 // bswap(bswap(x)) -> x
9278 if (IntrinsicInst *Operand = dyn_cast<IntrinsicInst>(II->getOperand(1)))
9279 if (Operand->getIntrinsicID() == Intrinsic::bswap)
9280 return ReplaceInstUsesWith(CI, Operand->getOperand(1));
9281 break;
9282 case Intrinsic::ppc_altivec_lvx:
9283 case Intrinsic::ppc_altivec_lvxl:
9284 case Intrinsic::x86_sse_loadu_ps:
9285 case Intrinsic::x86_sse2_loadu_pd:
9286 case Intrinsic::x86_sse2_loadu_dq:
9287 // Turn PPC lvx -> load if the pointer is known aligned.
9288 // Turn X86 loadups -> load if the pointer is known aligned.
9289 if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
9290 Value *Ptr = InsertBitCastBefore(II->getOperand(1),
9291 PointerType::getUnqual(II->getType()),
9292 CI);
9293 return new LoadInst(Ptr);
Chris Lattner2deeaea2006-10-05 06:55:50 +00009294 }
Chris Lattneref36dcd2008-06-18 04:33:20 +00009295 break;
9296 case Intrinsic::ppc_altivec_stvx:
9297 case Intrinsic::ppc_altivec_stvxl:
9298 // Turn stvx -> store if the pointer is known aligned.
9299 if (GetOrEnforceKnownAlignment(II->getOperand(2), 16) >= 16) {
9300 const Type *OpPtrTy =
9301 PointerType::getUnqual(II->getOperand(1)->getType());
9302 Value *Ptr = InsertBitCastBefore(II->getOperand(2), OpPtrTy, CI);
9303 return new StoreInst(II->getOperand(1), Ptr);
9304 }
9305 break;
9306 case Intrinsic::x86_sse_storeu_ps:
9307 case Intrinsic::x86_sse2_storeu_pd:
9308 case Intrinsic::x86_sse2_storeu_dq:
Chris Lattneref36dcd2008-06-18 04:33:20 +00009309 // Turn X86 storeu -> store if the pointer is known aligned.
9310 if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
9311 const Type *OpPtrTy =
9312 PointerType::getUnqual(II->getOperand(2)->getType());
9313 Value *Ptr = InsertBitCastBefore(II->getOperand(1), OpPtrTy, CI);
9314 return new StoreInst(II->getOperand(2), Ptr);
9315 }
9316 break;
9317
9318 case Intrinsic::x86_sse_cvttss2si: {
9319 // These intrinsics only demands the 0th element of its input vector. If
9320 // we can simplify the input based on that, do so now.
9321 uint64_t UndefElts;
9322 if (Value *V = SimplifyDemandedVectorElts(II->getOperand(1), 1,
9323 UndefElts)) {
9324 II->setOperand(1, V);
9325 return II;
9326 }
9327 break;
9328 }
9329
9330 case Intrinsic::ppc_altivec_vperm:
9331 // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant.
9332 if (ConstantVector *Mask = dyn_cast<ConstantVector>(II->getOperand(3))) {
9333 assert(Mask->getNumOperands() == 16 && "Bad type for intrinsic!");
Chris Lattner2deeaea2006-10-05 06:55:50 +00009334
Chris Lattneref36dcd2008-06-18 04:33:20 +00009335 // Check that all of the elements are integer constants or undefs.
9336 bool AllEltsOk = true;
9337 for (unsigned i = 0; i != 16; ++i) {
9338 if (!isa<ConstantInt>(Mask->getOperand(i)) &&
9339 !isa<UndefValue>(Mask->getOperand(i))) {
9340 AllEltsOk = false;
9341 break;
9342 }
9343 }
9344
9345 if (AllEltsOk) {
9346 // Cast the input vectors to byte vectors.
9347 Value *Op0 =InsertBitCastBefore(II->getOperand(1),Mask->getType(),CI);
9348 Value *Op1 =InsertBitCastBefore(II->getOperand(2),Mask->getType(),CI);
9349 Value *Result = UndefValue::get(Op0->getType());
Chris Lattnere79d2492006-04-06 19:19:17 +00009350
Chris Lattneref36dcd2008-06-18 04:33:20 +00009351 // Only extract each element once.
9352 Value *ExtractedElts[32];
9353 memset(ExtractedElts, 0, sizeof(ExtractedElts));
9354
Chris Lattnere79d2492006-04-06 19:19:17 +00009355 for (unsigned i = 0; i != 16; ++i) {
Chris Lattneref36dcd2008-06-18 04:33:20 +00009356 if (isa<UndefValue>(Mask->getOperand(i)))
9357 continue;
9358 unsigned Idx=cast<ConstantInt>(Mask->getOperand(i))->getZExtValue();
9359 Idx &= 31; // Match the hardware behavior.
9360
9361 if (ExtractedElts[Idx] == 0) {
9362 Instruction *Elt =
9363 new ExtractElementInst(Idx < 16 ? Op0 : Op1, Idx&15, "tmp");
9364 InsertNewInstBefore(Elt, CI);
9365 ExtractedElts[Idx] = Elt;
Chris Lattnere79d2492006-04-06 19:19:17 +00009366 }
Chris Lattnere79d2492006-04-06 19:19:17 +00009367
Chris Lattneref36dcd2008-06-18 04:33:20 +00009368 // Insert this value into the result vector.
9369 Result = InsertElementInst::Create(Result, ExtractedElts[Idx],
9370 i, "tmp");
9371 InsertNewInstBefore(cast<Instruction>(Result), CI);
Chris Lattnere79d2492006-04-06 19:19:17 +00009372 }
Chris Lattneref36dcd2008-06-18 04:33:20 +00009373 return CastInst::Create(Instruction::BitCast, Result, CI.getType());
Chris Lattnere79d2492006-04-06 19:19:17 +00009374 }
Chris Lattneref36dcd2008-06-18 04:33:20 +00009375 }
9376 break;
Chris Lattnere79d2492006-04-06 19:19:17 +00009377
Chris Lattneref36dcd2008-06-18 04:33:20 +00009378 case Intrinsic::stackrestore: {
9379 // If the save is right next to the restore, remove the restore. This can
9380 // happen when variable allocas are DCE'd.
9381 if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getOperand(1))) {
9382 if (SS->getIntrinsicID() == Intrinsic::stacksave) {
9383 BasicBlock::iterator BI = SS;
9384 if (&*++BI == II)
9385 return EraseInstFromFunction(CI);
Chris Lattner503221f2006-01-13 21:28:09 +00009386 }
Chris Lattneref36dcd2008-06-18 04:33:20 +00009387 }
9388
9389 // Scan down this block to see if there is another stack restore in the
9390 // same block without an intervening call/alloca.
9391 BasicBlock::iterator BI = II;
9392 TerminatorInst *TI = II->getParent()->getTerminator();
9393 bool CannotRemove = false;
9394 for (++BI; &*BI != TI; ++BI) {
9395 if (isa<AllocaInst>(BI)) {
9396 CannotRemove = true;
9397 break;
9398 }
Chris Lattnerc9c81fb2008-06-25 05:59:28 +00009399 if (CallInst *BCI = dyn_cast<CallInst>(BI)) {
9400 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(BCI)) {
9401 // If there is a stackrestore below this one, remove this one.
9402 if (II->getIntrinsicID() == Intrinsic::stackrestore)
9403 return EraseInstFromFunction(CI);
9404 // Otherwise, ignore the intrinsic.
9405 } else {
9406 // If we found a non-intrinsic call, we can't remove the stack
9407 // restore.
Chris Lattner024f8c82008-02-18 06:12:38 +00009408 CannotRemove = true;
9409 break;
9410 }
Chris Lattneref36dcd2008-06-18 04:33:20 +00009411 }
Chris Lattner503221f2006-01-13 21:28:09 +00009412 }
Chris Lattneref36dcd2008-06-18 04:33:20 +00009413
9414 // If the stack restore is in a return/unwind block and if there are no
9415 // allocas or calls between the restore and the return, nuke the restore.
9416 if (!CannotRemove && (isa<ReturnInst>(TI) || isa<UnwindInst>(TI)))
9417 return EraseInstFromFunction(CI);
9418 break;
9419 }
Chris Lattner00648e12004-10-12 04:52:52 +00009420 }
9421
Chris Lattnerc66b2232006-01-13 20:11:04 +00009422 return visitCallSite(II);
Chris Lattner970c33a2003-06-19 17:00:31 +00009423}
9424
9425// InvokeInst simplification
9426//
9427Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
Chris Lattneraec3d942003-10-07 22:32:43 +00009428 return visitCallSite(&II);
Chris Lattner970c33a2003-06-19 17:00:31 +00009429}
9430
Dale Johannesen0d1d3df2008-04-25 21:16:07 +00009431/// isSafeToEliminateVarargsCast - If this cast does not affect the value
9432/// passed through the varargs area, we can eliminate the use of the cast.
Dale Johannesenf6e15a42008-04-23 18:34:37 +00009433static bool isSafeToEliminateVarargsCast(const CallSite CS,
9434 const CastInst * const CI,
9435 const TargetData * const TD,
9436 const int ix) {
9437 if (!CI->isLosslessCast())
9438 return false;
9439
9440 // The size of ByVal arguments is derived from the type, so we
9441 // can't change to a type with a different size. If the size were
9442 // passed explicitly we could avoid this check.
Devang Patel4c758ea2008-09-25 21:00:45 +00009443 if (!CS.paramHasAttr(ix, Attribute::ByVal))
Dale Johannesenf6e15a42008-04-23 18:34:37 +00009444 return true;
9445
9446 const Type* SrcTy =
9447 cast<PointerType>(CI->getOperand(0)->getType())->getElementType();
9448 const Type* DstTy = cast<PointerType>(CI->getType())->getElementType();
9449 if (!SrcTy->isSized() || !DstTy->isSized())
9450 return false;
9451 if (TD->getABITypeSize(SrcTy) != TD->getABITypeSize(DstTy))
9452 return false;
9453 return true;
9454}
9455
Chris Lattneraec3d942003-10-07 22:32:43 +00009456// visitCallSite - Improvements for call and invoke instructions.
9457//
9458Instruction *InstCombiner::visitCallSite(CallSite CS) {
Chris Lattner75b4d1d2003-10-07 22:54:13 +00009459 bool Changed = false;
9460
9461 // If the callee is a constexpr cast of a function, attempt to move the cast
9462 // to the arguments of the call/invoke.
Chris Lattneraec3d942003-10-07 22:32:43 +00009463 if (transformConstExprCastCall(CS)) return 0;
9464
Chris Lattner75b4d1d2003-10-07 22:54:13 +00009465 Value *Callee = CS.getCalledValue();
Chris Lattner81a7a232004-10-16 18:11:37 +00009466
Chris Lattner61d9d812005-05-13 07:09:09 +00009467 if (Function *CalleeF = dyn_cast<Function>(Callee))
9468 if (CalleeF->getCallingConv() != CS.getCallingConv()) {
9469 Instruction *OldCall = CS.getInstruction();
9470 // If the call and callee calling conventions don't match, this call must
9471 // be unreachable, as the call is undefined.
Zhou Sheng75b871f2007-01-11 12:24:14 +00009472 new StoreInst(ConstantInt::getTrue(),
Christopher Lambedf07882007-12-17 01:12:55 +00009473 UndefValue::get(PointerType::getUnqual(Type::Int1Ty)),
9474 OldCall);
Chris Lattner61d9d812005-05-13 07:09:09 +00009475 if (!OldCall->use_empty())
9476 OldCall->replaceAllUsesWith(UndefValue::get(OldCall->getType()));
9477 if (isa<CallInst>(OldCall)) // Not worth removing an invoke here.
9478 return EraseInstFromFunction(*OldCall);
9479 return 0;
9480 }
9481
Chris Lattner8ba9ec92004-10-18 02:59:09 +00009482 if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
9483 // This instruction is not reachable, just remove it. We insert a store to
9484 // undef so that we know that this code is not reachable, despite the fact
9485 // that we can't modify the CFG here.
Zhou Sheng75b871f2007-01-11 12:24:14 +00009486 new StoreInst(ConstantInt::getTrue(),
Christopher Lambedf07882007-12-17 01:12:55 +00009487 UndefValue::get(PointerType::getUnqual(Type::Int1Ty)),
Chris Lattner8ba9ec92004-10-18 02:59:09 +00009488 CS.getInstruction());
9489
9490 if (!CS.getInstruction()->use_empty())
9491 CS.getInstruction()->
9492 replaceAllUsesWith(UndefValue::get(CS.getInstruction()->getType()));
9493
9494 if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
9495 // Don't break the CFG, insert a dummy cond branch.
Gabor Greife9ecc682008-04-06 20:25:17 +00009496 BranchInst::Create(II->getNormalDest(), II->getUnwindDest(),
9497 ConstantInt::getTrue(), II);
Chris Lattner81a7a232004-10-16 18:11:37 +00009498 }
Chris Lattner8ba9ec92004-10-18 02:59:09 +00009499 return EraseInstFromFunction(*CS.getInstruction());
9500 }
Chris Lattner81a7a232004-10-16 18:11:37 +00009501
Duncan Sands6d5da712007-09-17 10:26:40 +00009502 if (BitCastInst *BC = dyn_cast<BitCastInst>(Callee))
9503 if (IntrinsicInst *In = dyn_cast<IntrinsicInst>(BC->getOperand(0)))
9504 if (In->getIntrinsicID() == Intrinsic::init_trampoline)
9505 return transformCallThroughTrampoline(CS);
9506
Chris Lattner75b4d1d2003-10-07 22:54:13 +00009507 const PointerType *PTy = cast<PointerType>(Callee->getType());
9508 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
9509 if (FTy->isVarArg()) {
Dale Johannesen493527d2008-04-23 01:03:05 +00009510 int ix = FTy->getNumParams() + (isa<InvokeInst>(Callee) ? 3 : 1);
Chris Lattner75b4d1d2003-10-07 22:54:13 +00009511 // See if we can optimize any arguments passed through the varargs area of
9512 // the call.
9513 for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
Dale Johannesenf6e15a42008-04-23 18:34:37 +00009514 E = CS.arg_end(); I != E; ++I, ++ix) {
9515 CastInst *CI = dyn_cast<CastInst>(*I);
9516 if (CI && isSafeToEliminateVarargsCast(CS, CI, TD, ix)) {
9517 *I = CI->getOperand(0);
9518 Changed = true;
Chris Lattner75b4d1d2003-10-07 22:54:13 +00009519 }
Dale Johannesenf6e15a42008-04-23 18:34:37 +00009520 }
Chris Lattner75b4d1d2003-10-07 22:54:13 +00009521 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00009522
Duncan Sandsaa31b922007-12-19 21:13:37 +00009523 if (isa<InlineAsm>(Callee) && !CS.doesNotThrow()) {
Duncan Sands8e4847e2007-12-16 15:51:49 +00009524 // Inline asm calls cannot throw - mark them 'nounwind'.
Duncan Sandsaa31b922007-12-19 21:13:37 +00009525 CS.setDoesNotThrow();
Duncan Sands8e4847e2007-12-16 15:51:49 +00009526 Changed = true;
9527 }
9528
Chris Lattner75b4d1d2003-10-07 22:54:13 +00009529 return Changed ? CS.getInstruction() : 0;
Chris Lattneraec3d942003-10-07 22:32:43 +00009530}
9531
Chris Lattner970c33a2003-06-19 17:00:31 +00009532// transformConstExprCastCall - If the callee is a constexpr cast of a function,
9533// attempt to move the cast to the arguments of the call/invoke.
9534//
9535bool InstCombiner::transformConstExprCastCall(CallSite CS) {
9536 if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
9537 ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
Reid Spencer6c38f0b2006-11-27 01:05:10 +00009538 if (CE->getOpcode() != Instruction::BitCast ||
9539 !isa<Function>(CE->getOperand(0)))
Chris Lattner970c33a2003-06-19 17:00:31 +00009540 return false;
Reid Spencer87436872004-07-18 00:38:32 +00009541 Function *Callee = cast<Function>(CE->getOperand(0));
Chris Lattner970c33a2003-06-19 17:00:31 +00009542 Instruction *Caller = CS.getInstruction();
Devang Patel4c758ea2008-09-25 21:00:45 +00009543 const AttrListPtr &CallerPAL = CS.getAttributes();
Chris Lattner970c33a2003-06-19 17:00:31 +00009544
9545 // Okay, this is a cast from a function to a different type. Unless doing so
9546 // would cause a type conversion of one of our arguments, change this call to
9547 // be a direct call with arguments casted to the appropriate types.
9548 //
9549 const FunctionType *FT = Callee->getFunctionType();
9550 const Type *OldRetTy = Caller->getType();
Duncan Sands0397cd22008-06-01 07:38:42 +00009551 const Type *NewRetTy = FT->getReturnType();
Chris Lattner970c33a2003-06-19 17:00:31 +00009552
Duncan Sands0397cd22008-06-01 07:38:42 +00009553 if (isa<StructType>(NewRetTy))
Devang Patel70c238a2008-03-11 18:04:06 +00009554 return false; // TODO: Handle multiple return values.
9555
Chris Lattner1f7942f2004-01-14 06:06:08 +00009556 // Check to see if we are changing the return type...
Duncan Sands0397cd22008-06-01 07:38:42 +00009557 if (OldRetTy != NewRetTy) {
Bill Wendling37169522008-05-14 22:45:20 +00009558 if (Callee->isDeclaration() &&
Duncan Sands0397cd22008-06-01 07:38:42 +00009559 // Conversion is ok if changing from one pointer type to another or from
9560 // a pointer to an integer of the same size.
9561 !((isa<PointerType>(OldRetTy) || OldRetTy == TD->getIntPtrType()) &&
Duncan Sands4b50fde2008-06-17 15:55:30 +00009562 (isa<PointerType>(NewRetTy) || NewRetTy == TD->getIntPtrType())))
Chris Lattner400f9592007-01-06 02:09:32 +00009563 return false; // Cannot transform this return value.
Chris Lattner1f7942f2004-01-14 06:06:08 +00009564
Duncan Sands55e50902008-01-06 10:12:28 +00009565 if (!Caller->use_empty() &&
Duncan Sands55e50902008-01-06 10:12:28 +00009566 // void -> non-void is handled specially
Duncan Sands0397cd22008-06-01 07:38:42 +00009567 NewRetTy != Type::VoidTy && !CastInst::isCastable(NewRetTy, OldRetTy))
Duncan Sands55e50902008-01-06 10:12:28 +00009568 return false; // Cannot transform this return value.
9569
Chris Lattner8a923e72008-03-12 17:45:29 +00009570 if (!CallerPAL.isEmpty() && !Caller->use_empty()) {
Devang Patela05633e2008-09-26 22:53:05 +00009571 Attributes RAttrs = CallerPAL.getRetAttributes();
Devang Patel4c758ea2008-09-25 21:00:45 +00009572 if (RAttrs & Attribute::typeIncompatible(NewRetTy))
Duncan Sandsb18c30a2008-01-07 17:16:06 +00009573 return false; // Attribute not compatible with transformed value.
9574 }
Duncan Sands404eb052008-01-06 18:27:01 +00009575
Chris Lattner1f7942f2004-01-14 06:06:08 +00009576 // If the callsite is an invoke instruction, and the return value is used by
9577 // a PHI node in a successor, we cannot change the return type of the call
9578 // because there is no place to put the cast instruction (without breaking
9579 // the critical edge). Bail out in this case.
9580 if (!Caller->use_empty())
9581 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
9582 for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
9583 UI != E; ++UI)
9584 if (PHINode *PN = dyn_cast<PHINode>(*UI))
9585 if (PN->getParent() == II->getNormalDest() ||
Chris Lattnerfae8ab32004-02-08 21:44:31 +00009586 PN->getParent() == II->getUnwindDest())
Chris Lattner1f7942f2004-01-14 06:06:08 +00009587 return false;
9588 }
Chris Lattner970c33a2003-06-19 17:00:31 +00009589
9590 unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
9591 unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
Misha Brukmanb1c93172005-04-21 23:48:37 +00009592
Chris Lattner970c33a2003-06-19 17:00:31 +00009593 CallSite::arg_iterator AI = CS.arg_begin();
9594 for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
9595 const Type *ParamTy = FT->getParamType(i);
Andrew Lenharthebfa24e2006-06-28 01:01:52 +00009596 const Type *ActTy = (*AI)->getType();
Duncan Sands55e50902008-01-06 10:12:28 +00009597
9598 if (!CastInst::isCastable(ActTy, ParamTy))
Duncan Sands404eb052008-01-06 18:27:01 +00009599 return false; // Cannot transform this parameter value.
9600
Devang Patela05633e2008-09-26 22:53:05 +00009601 if (CallerPAL.getParamAttributes(i + 1)
9602 & Attribute::typeIncompatible(ParamTy))
Chris Lattner8a923e72008-03-12 17:45:29 +00009603 return false; // Attribute not compatible with transformed value.
Duncan Sands55e50902008-01-06 10:12:28 +00009604
Duncan Sands0397cd22008-06-01 07:38:42 +00009605 // Converting from one pointer type to another or between a pointer and an
9606 // integer of the same size is safe even if we do not have a body.
Chris Lattner400f9592007-01-06 02:09:32 +00009607 bool isConvertible = ActTy == ParamTy ||
Duncan Sands0397cd22008-06-01 07:38:42 +00009608 ((isa<PointerType>(ParamTy) || ParamTy == TD->getIntPtrType()) &&
9609 (isa<PointerType>(ActTy) || ActTy == TD->getIntPtrType()));
Reid Spencer5301e7c2007-01-30 20:08:39 +00009610 if (Callee->isDeclaration() && !isConvertible) return false;
Chris Lattner970c33a2003-06-19 17:00:31 +00009611 }
9612
9613 if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
Reid Spencer5301e7c2007-01-30 20:08:39 +00009614 Callee->isDeclaration())
Chris Lattner8a923e72008-03-12 17:45:29 +00009615 return false; // Do not delete arguments unless we have a function body.
Chris Lattner970c33a2003-06-19 17:00:31 +00009616
Chris Lattner8a923e72008-03-12 17:45:29 +00009617 if (FT->getNumParams() < NumActualArgs && FT->isVarArg() &&
9618 !CallerPAL.isEmpty())
Duncan Sands404eb052008-01-06 18:27:01 +00009619 // In this case we have more arguments than the new function type, but we
Duncan Sands781f6542008-01-13 08:02:44 +00009620 // won't be dropping them. Check that these extra arguments have attributes
9621 // that are compatible with being a vararg call argument.
Chris Lattner8a923e72008-03-12 17:45:29 +00009622 for (unsigned i = CallerPAL.getNumSlots(); i; --i) {
9623 if (CallerPAL.getSlot(i - 1).Index <= FT->getNumParams())
Duncan Sands781f6542008-01-13 08:02:44 +00009624 break;
Devang Patelba3fa6c2008-09-23 23:03:40 +00009625 Attributes PAttrs = CallerPAL.getSlot(i - 1).Attrs;
Devang Patel4c758ea2008-09-25 21:00:45 +00009626 if (PAttrs & Attribute::VarArgsIncompatible)
Duncan Sands781f6542008-01-13 08:02:44 +00009627 return false;
9628 }
Duncan Sands404eb052008-01-06 18:27:01 +00009629
Chris Lattner970c33a2003-06-19 17:00:31 +00009630 // Okay, we decided that this is a safe thing to do: go ahead and start
9631 // inserting cast instructions as necessary...
9632 std::vector<Value*> Args;
9633 Args.reserve(NumActualArgs);
Devang Patel4c758ea2008-09-25 21:00:45 +00009634 SmallVector<AttributeWithIndex, 8> attrVec;
Duncan Sands404eb052008-01-06 18:27:01 +00009635 attrVec.reserve(NumCommonArgs);
9636
9637 // Get any return attributes.
Devang Patela05633e2008-09-26 22:53:05 +00009638 Attributes RAttrs = CallerPAL.getRetAttributes();
Duncan Sands404eb052008-01-06 18:27:01 +00009639
9640 // If the return value is not being used, the type may not be compatible
9641 // with the existing attributes. Wipe out any problematic attributes.
Devang Patel4c758ea2008-09-25 21:00:45 +00009642 RAttrs &= ~Attribute::typeIncompatible(NewRetTy);
Duncan Sands404eb052008-01-06 18:27:01 +00009643
9644 // Add the new return attributes.
9645 if (RAttrs)
Devang Patel4c758ea2008-09-25 21:00:45 +00009646 attrVec.push_back(AttributeWithIndex::get(0, RAttrs));
Chris Lattner970c33a2003-06-19 17:00:31 +00009647
9648 AI = CS.arg_begin();
9649 for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
9650 const Type *ParamTy = FT->getParamType(i);
9651 if ((*AI)->getType() == ParamTy) {
9652 Args.push_back(*AI);
9653 } else {
Reid Spencer668d90f2006-12-18 08:47:13 +00009654 Instruction::CastOps opcode = CastInst::getCastOpcode(*AI,
Reid Spencerc635f472006-12-31 05:48:39 +00009655 false, ParamTy, false);
Gabor Greife1f6e4b2008-05-16 19:29:10 +00009656 CastInst *NewCast = CastInst::Create(opcode, *AI, ParamTy, "tmp");
Reid Spencer6c38f0b2006-11-27 01:05:10 +00009657 Args.push_back(InsertNewInstBefore(NewCast, *Caller));
Chris Lattner970c33a2003-06-19 17:00:31 +00009658 }
Duncan Sands404eb052008-01-06 18:27:01 +00009659
9660 // Add any parameter attributes.
Devang Patela05633e2008-09-26 22:53:05 +00009661 if (Attributes PAttrs = CallerPAL.getParamAttributes(i + 1))
Devang Patel4c758ea2008-09-25 21:00:45 +00009662 attrVec.push_back(AttributeWithIndex::get(i + 1, PAttrs));
Chris Lattner970c33a2003-06-19 17:00:31 +00009663 }
9664
9665 // If the function takes more arguments than the call was taking, add them
9666 // now...
9667 for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
9668 Args.push_back(Constant::getNullValue(FT->getParamType(i)));
9669
9670 // If we are removing arguments to the function, emit an obnoxious warning...
Anton Korobeynikov1bfd1212008-02-20 11:26:25 +00009671 if (FT->getNumParams() < NumActualArgs) {
Chris Lattner970c33a2003-06-19 17:00:31 +00009672 if (!FT->isVarArg()) {
Bill Wendlingf3baad32006-12-07 01:30:32 +00009673 cerr << "WARNING: While resolving call to function '"
9674 << Callee->getName() << "' arguments were dropped!\n";
Chris Lattner970c33a2003-06-19 17:00:31 +00009675 } else {
9676 // Add all of the arguments in their promoted form to the arg list...
9677 for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
9678 const Type *PTy = getPromotedType((*AI)->getType());
9679 if (PTy != (*AI)->getType()) {
9680 // Must promote to pass through va_arg area!
Reid Spencerc635f472006-12-31 05:48:39 +00009681 Instruction::CastOps opcode = CastInst::getCastOpcode(*AI, false,
9682 PTy, false);
Gabor Greife1f6e4b2008-05-16 19:29:10 +00009683 Instruction *Cast = CastInst::Create(opcode, *AI, PTy, "tmp");
Chris Lattner970c33a2003-06-19 17:00:31 +00009684 InsertNewInstBefore(Cast, *Caller);
9685 Args.push_back(Cast);
9686 } else {
9687 Args.push_back(*AI);
9688 }
Duncan Sands404eb052008-01-06 18:27:01 +00009689
Duncan Sands781f6542008-01-13 08:02:44 +00009690 // Add any parameter attributes.
Devang Patela05633e2008-09-26 22:53:05 +00009691 if (Attributes PAttrs = CallerPAL.getParamAttributes(i + 1))
Devang Patel4c758ea2008-09-25 21:00:45 +00009692 attrVec.push_back(AttributeWithIndex::get(i + 1, PAttrs));
Duncan Sands781f6542008-01-13 08:02:44 +00009693 }
Chris Lattner970c33a2003-06-19 17:00:31 +00009694 }
Anton Korobeynikov1bfd1212008-02-20 11:26:25 +00009695 }
Chris Lattner970c33a2003-06-19 17:00:31 +00009696
Devang Patela05633e2008-09-26 22:53:05 +00009697 if (Attributes FnAttrs = CallerPAL.getFnAttributes())
9698 attrVec.push_back(AttributeWithIndex::get(~0, FnAttrs));
9699
Duncan Sands0397cd22008-06-01 07:38:42 +00009700 if (NewRetTy == Type::VoidTy)
Chris Lattner6e0123b2007-02-11 01:23:03 +00009701 Caller->setName(""); // Void type should not have a name.
Chris Lattner970c33a2003-06-19 17:00:31 +00009702
Devang Patel4c758ea2008-09-25 21:00:45 +00009703 const AttrListPtr &NewCallerPAL = AttrListPtr::get(attrVec.begin(),attrVec.end());
Duncan Sands404eb052008-01-06 18:27:01 +00009704
Chris Lattner970c33a2003-06-19 17:00:31 +00009705 Instruction *NC;
9706 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Gabor Greife9ecc682008-04-06 20:25:17 +00009707 NC = InvokeInst::Create(Callee, II->getNormalDest(), II->getUnwindDest(),
Gabor Greif697e94c2008-05-15 10:04:30 +00009708 Args.begin(), Args.end(),
9709 Caller->getName(), Caller);
Reid Spencerdff9d692007-07-30 19:53:57 +00009710 cast<InvokeInst>(NC)->setCallingConv(II->getCallingConv());
Devang Patel4c758ea2008-09-25 21:00:45 +00009711 cast<InvokeInst>(NC)->setAttributes(NewCallerPAL);
Chris Lattner970c33a2003-06-19 17:00:31 +00009712 } else {
Gabor Greife9ecc682008-04-06 20:25:17 +00009713 NC = CallInst::Create(Callee, Args.begin(), Args.end(),
9714 Caller->getName(), Caller);
Duncan Sandsad0ea2d2007-11-27 13:23:08 +00009715 CallInst *CI = cast<CallInst>(Caller);
9716 if (CI->isTailCall())
Chris Lattner6aacb0f2005-05-06 06:48:21 +00009717 cast<CallInst>(NC)->setTailCall();
Duncan Sandsad0ea2d2007-11-27 13:23:08 +00009718 cast<CallInst>(NC)->setCallingConv(CI->getCallingConv());
Devang Patel4c758ea2008-09-25 21:00:45 +00009719 cast<CallInst>(NC)->setAttributes(NewCallerPAL);
Chris Lattner970c33a2003-06-19 17:00:31 +00009720 }
9721
Chris Lattner6e0123b2007-02-11 01:23:03 +00009722 // Insert a cast of the return type as necessary.
Chris Lattner970c33a2003-06-19 17:00:31 +00009723 Value *NV = NC;
Duncan Sands55e50902008-01-06 10:12:28 +00009724 if (OldRetTy != NV->getType() && !Caller->use_empty()) {
Chris Lattner970c33a2003-06-19 17:00:31 +00009725 if (NV->getType() != Type::VoidTy) {
Reid Spencerc635f472006-12-31 05:48:39 +00009726 Instruction::CastOps opcode = CastInst::getCastOpcode(NC, false,
Duncan Sands55e50902008-01-06 10:12:28 +00009727 OldRetTy, false);
Gabor Greife1f6e4b2008-05-16 19:29:10 +00009728 NV = NC = CastInst::Create(opcode, NC, OldRetTy, "tmp");
Chris Lattner686767f2003-10-30 00:46:41 +00009729
9730 // If this is an invoke instruction, we should insert it after the first
9731 // non-phi, instruction in the normal successor block.
9732 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Dan Gohmanf96e1372008-05-23 21:05:58 +00009733 BasicBlock::iterator I = II->getNormalDest()->getFirstNonPHI();
Chris Lattner686767f2003-10-30 00:46:41 +00009734 InsertNewInstBefore(NC, *I);
9735 } else {
9736 // Otherwise, it's a call, just insert cast right after the call instr
9737 InsertNewInstBefore(NC, *Caller);
9738 }
Chris Lattner51ea1272004-02-28 05:22:00 +00009739 AddUsersToWorkList(*Caller);
Chris Lattner970c33a2003-06-19 17:00:31 +00009740 } else {
Chris Lattnere29d6342004-10-17 21:22:38 +00009741 NV = UndefValue::get(Caller->getType());
Chris Lattner970c33a2003-06-19 17:00:31 +00009742 }
9743 }
9744
9745 if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
9746 Caller->replaceAllUsesWith(NV);
Chris Lattner51f54572007-03-02 19:59:19 +00009747 Caller->eraseFromParent();
Chris Lattnerb15e2b12007-03-02 21:28:56 +00009748 RemoveFromWorkList(Caller);
Chris Lattner970c33a2003-06-19 17:00:31 +00009749 return true;
9750}
9751
Duncan Sands6d5da712007-09-17 10:26:40 +00009752// transformCallThroughTrampoline - Turn a call to a function created by the
9753// init_trampoline intrinsic into a direct call to the underlying function.
9754//
9755Instruction *InstCombiner::transformCallThroughTrampoline(CallSite CS) {
9756 Value *Callee = CS.getCalledValue();
9757 const PointerType *PTy = cast<PointerType>(Callee->getType());
9758 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
Devang Patel4c758ea2008-09-25 21:00:45 +00009759 const AttrListPtr &Attrs = CS.getAttributes();
Duncan Sandsb5ca2e92008-01-14 19:52:09 +00009760
9761 // If the call already has the 'nest' attribute somewhere then give up -
9762 // otherwise 'nest' would occur twice after splicing in the chain.
Devang Patel4c758ea2008-09-25 21:00:45 +00009763 if (Attrs.hasAttrSomewhere(Attribute::Nest))
Duncan Sandsb5ca2e92008-01-14 19:52:09 +00009764 return 0;
Duncan Sands6d5da712007-09-17 10:26:40 +00009765
9766 IntrinsicInst *Tramp =
9767 cast<IntrinsicInst>(cast<BitCastInst>(Callee)->getOperand(0));
9768
Anton Korobeynikovfc2edad2008-05-07 22:54:15 +00009769 Function *NestF = cast<Function>(Tramp->getOperand(2)->stripPointerCasts());
Duncan Sands6d5da712007-09-17 10:26:40 +00009770 const PointerType *NestFPTy = cast<PointerType>(NestF->getType());
9771 const FunctionType *NestFTy = cast<FunctionType>(NestFPTy->getElementType());
9772
Devang Patel4c758ea2008-09-25 21:00:45 +00009773 const AttrListPtr &NestAttrs = NestF->getAttributes();
Chris Lattner8a923e72008-03-12 17:45:29 +00009774 if (!NestAttrs.isEmpty()) {
Duncan Sands6d5da712007-09-17 10:26:40 +00009775 unsigned NestIdx = 1;
9776 const Type *NestTy = 0;
Devang Patel4c758ea2008-09-25 21:00:45 +00009777 Attributes NestAttr = Attribute::None;
Duncan Sands6d5da712007-09-17 10:26:40 +00009778
9779 // Look for a parameter marked with the 'nest' attribute.
9780 for (FunctionType::param_iterator I = NestFTy->param_begin(),
9781 E = NestFTy->param_end(); I != E; ++NestIdx, ++I)
Devang Patel4c758ea2008-09-25 21:00:45 +00009782 if (NestAttrs.paramHasAttr(NestIdx, Attribute::Nest)) {
Duncan Sands6d5da712007-09-17 10:26:40 +00009783 // Record the parameter type and any other attributes.
9784 NestTy = *I;
Devang Patela05633e2008-09-26 22:53:05 +00009785 NestAttr = NestAttrs.getParamAttributes(NestIdx);
Duncan Sands6d5da712007-09-17 10:26:40 +00009786 break;
9787 }
9788
9789 if (NestTy) {
9790 Instruction *Caller = CS.getInstruction();
9791 std::vector<Value*> NewArgs;
9792 NewArgs.reserve(unsigned(CS.arg_end()-CS.arg_begin())+1);
9793
Devang Patel4c758ea2008-09-25 21:00:45 +00009794 SmallVector<AttributeWithIndex, 8> NewAttrs;
Chris Lattner8a923e72008-03-12 17:45:29 +00009795 NewAttrs.reserve(Attrs.getNumSlots() + 1);
Duncan Sandsb5ca2e92008-01-14 19:52:09 +00009796
Duncan Sands6d5da712007-09-17 10:26:40 +00009797 // Insert the nest argument into the call argument list, which may
Duncan Sandsb5ca2e92008-01-14 19:52:09 +00009798 // mean appending it. Likewise for attributes.
9799
Devang Patela05633e2008-09-26 22:53:05 +00009800 // Add any result attributes.
9801 if (Attributes Attr = Attrs.getRetAttributes())
Devang Patel4c758ea2008-09-25 21:00:45 +00009802 NewAttrs.push_back(AttributeWithIndex::get(0, Attr));
Duncan Sandsb5ca2e92008-01-14 19:52:09 +00009803
Duncan Sands6d5da712007-09-17 10:26:40 +00009804 {
9805 unsigned Idx = 1;
9806 CallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
9807 do {
9808 if (Idx == NestIdx) {
Duncan Sandsb5ca2e92008-01-14 19:52:09 +00009809 // Add the chain argument and attributes.
Duncan Sands6d5da712007-09-17 10:26:40 +00009810 Value *NestVal = Tramp->getOperand(3);
9811 if (NestVal->getType() != NestTy)
9812 NestVal = new BitCastInst(NestVal, NestTy, "nest", Caller);
9813 NewArgs.push_back(NestVal);
Devang Patel4c758ea2008-09-25 21:00:45 +00009814 NewAttrs.push_back(AttributeWithIndex::get(NestIdx, NestAttr));
Duncan Sands6d5da712007-09-17 10:26:40 +00009815 }
9816
9817 if (I == E)
9818 break;
9819
Duncan Sandsb5ca2e92008-01-14 19:52:09 +00009820 // Add the original argument and attributes.
Duncan Sands6d5da712007-09-17 10:26:40 +00009821 NewArgs.push_back(*I);
Devang Patela05633e2008-09-26 22:53:05 +00009822 if (Attributes Attr = Attrs.getParamAttributes(Idx))
Duncan Sandsb5ca2e92008-01-14 19:52:09 +00009823 NewAttrs.push_back
Devang Patel4c758ea2008-09-25 21:00:45 +00009824 (AttributeWithIndex::get(Idx + (Idx >= NestIdx), Attr));
Duncan Sands6d5da712007-09-17 10:26:40 +00009825
9826 ++Idx, ++I;
9827 } while (1);
9828 }
9829
Devang Patela05633e2008-09-26 22:53:05 +00009830 // Add any function attributes.
9831 if (Attributes Attr = Attrs.getFnAttributes())
9832 NewAttrs.push_back(AttributeWithIndex::get(~0, Attr));
9833
Duncan Sands6d5da712007-09-17 10:26:40 +00009834 // The trampoline may have been bitcast to a bogus type (FTy).
9835 // Handle this by synthesizing a new function type, equal to FTy
Duncan Sandsb5ca2e92008-01-14 19:52:09 +00009836 // with the chain parameter inserted.
Duncan Sands6d5da712007-09-17 10:26:40 +00009837
Duncan Sands6d5da712007-09-17 10:26:40 +00009838 std::vector<const Type*> NewTypes;
Duncan Sands6d5da712007-09-17 10:26:40 +00009839 NewTypes.reserve(FTy->getNumParams()+1);
9840
Duncan Sands6d5da712007-09-17 10:26:40 +00009841 // Insert the chain's type into the list of parameter types, which may
Duncan Sandsb5ca2e92008-01-14 19:52:09 +00009842 // mean appending it.
Duncan Sands6d5da712007-09-17 10:26:40 +00009843 {
9844 unsigned Idx = 1;
9845 FunctionType::param_iterator I = FTy->param_begin(),
9846 E = FTy->param_end();
9847
9848 do {
Duncan Sandsb5ca2e92008-01-14 19:52:09 +00009849 if (Idx == NestIdx)
9850 // Add the chain's type.
Duncan Sands6d5da712007-09-17 10:26:40 +00009851 NewTypes.push_back(NestTy);
Duncan Sands6d5da712007-09-17 10:26:40 +00009852
9853 if (I == E)
9854 break;
9855
Duncan Sandsb5ca2e92008-01-14 19:52:09 +00009856 // Add the original type.
Duncan Sands6d5da712007-09-17 10:26:40 +00009857 NewTypes.push_back(*I);
Duncan Sands6d5da712007-09-17 10:26:40 +00009858
9859 ++Idx, ++I;
9860 } while (1);
9861 }
9862
9863 // Replace the trampoline call with a direct call. Let the generic
9864 // code sort out any function type mismatches.
9865 FunctionType *NewFTy =
Duncan Sandsad0ea2d2007-11-27 13:23:08 +00009866 FunctionType::get(FTy->getReturnType(), NewTypes, FTy->isVarArg());
Christopher Lambedf07882007-12-17 01:12:55 +00009867 Constant *NewCallee = NestF->getType() == PointerType::getUnqual(NewFTy) ?
9868 NestF : ConstantExpr::getBitCast(NestF, PointerType::getUnqual(NewFTy));
Devang Patel4c758ea2008-09-25 21:00:45 +00009869 const AttrListPtr &NewPAL = AttrListPtr::get(NewAttrs.begin(),NewAttrs.end());
Duncan Sands6d5da712007-09-17 10:26:40 +00009870
9871 Instruction *NewCaller;
9872 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Gabor Greife9ecc682008-04-06 20:25:17 +00009873 NewCaller = InvokeInst::Create(NewCallee,
9874 II->getNormalDest(), II->getUnwindDest(),
9875 NewArgs.begin(), NewArgs.end(),
9876 Caller->getName(), Caller);
Duncan Sands6d5da712007-09-17 10:26:40 +00009877 cast<InvokeInst>(NewCaller)->setCallingConv(II->getCallingConv());
Devang Patel4c758ea2008-09-25 21:00:45 +00009878 cast<InvokeInst>(NewCaller)->setAttributes(NewPAL);
Duncan Sands6d5da712007-09-17 10:26:40 +00009879 } else {
Gabor Greife9ecc682008-04-06 20:25:17 +00009880 NewCaller = CallInst::Create(NewCallee, NewArgs.begin(), NewArgs.end(),
9881 Caller->getName(), Caller);
Duncan Sands6d5da712007-09-17 10:26:40 +00009882 if (cast<CallInst>(Caller)->isTailCall())
9883 cast<CallInst>(NewCaller)->setTailCall();
9884 cast<CallInst>(NewCaller)->
9885 setCallingConv(cast<CallInst>(Caller)->getCallingConv());
Devang Patel4c758ea2008-09-25 21:00:45 +00009886 cast<CallInst>(NewCaller)->setAttributes(NewPAL);
Duncan Sands6d5da712007-09-17 10:26:40 +00009887 }
9888 if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
9889 Caller->replaceAllUsesWith(NewCaller);
9890 Caller->eraseFromParent();
9891 RemoveFromWorkList(Caller);
9892 return 0;
9893 }
9894 }
9895
9896 // Replace the trampoline call with a direct call. Since there is no 'nest'
9897 // parameter, there is no need to adjust the argument list. Let the generic
9898 // code sort out any function type mismatches.
9899 Constant *NewCallee =
9900 NestF->getType() == PTy ? NestF : ConstantExpr::getBitCast(NestF, PTy);
9901 CS.setCalledFunction(NewCallee);
9902 return CS.getInstruction();
9903}
9904
Chris Lattnercadac0c2006-11-01 04:51:18 +00009905/// FoldPHIArgBinOpIntoPHI - If we have something like phi [add (a,b), add(c,d)]
9906/// and if a/b/c/d and the add's all have a single use, turn this into two phi's
9907/// and a single binop.
9908Instruction *InstCombiner::FoldPHIArgBinOpIntoPHI(PHINode &PN) {
9909 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
Reid Spencer2341c222007-02-02 02:16:23 +00009910 assert(isa<BinaryOperator>(FirstInst) || isa<GetElementPtrInst>(FirstInst) ||
9911 isa<CmpInst>(FirstInst));
Chris Lattnercadac0c2006-11-01 04:51:18 +00009912 unsigned Opc = FirstInst->getOpcode();
Chris Lattnercd62f112006-11-08 19:29:23 +00009913 Value *LHSVal = FirstInst->getOperand(0);
9914 Value *RHSVal = FirstInst->getOperand(1);
9915
9916 const Type *LHSType = LHSVal->getType();
9917 const Type *RHSType = RHSVal->getType();
Chris Lattnercadac0c2006-11-01 04:51:18 +00009918
9919 // Scan to see if all operands are the same opcode, all have one use, and all
9920 // kill their operands (i.e. the operands have one use).
Chris Lattnerdc826fc2006-11-01 04:55:47 +00009921 for (unsigned i = 0; i != PN.getNumIncomingValues(); ++i) {
Chris Lattnercadac0c2006-11-01 04:51:18 +00009922 Instruction *I = dyn_cast<Instruction>(PN.getIncomingValue(i));
Chris Lattnerdc826fc2006-11-01 04:55:47 +00009923 if (!I || I->getOpcode() != Opc || !I->hasOneUse() ||
Reid Spencer266e42b2006-12-23 06:05:41 +00009924 // Verify type of the LHS matches so we don't fold cmp's of different
Chris Lattnereebea432006-11-01 07:43:41 +00009925 // types or GEP's with different index types.
9926 I->getOperand(0)->getType() != LHSType ||
9927 I->getOperand(1)->getType() != RHSType)
Chris Lattnercadac0c2006-11-01 04:51:18 +00009928 return 0;
Reid Spencer266e42b2006-12-23 06:05:41 +00009929
9930 // If they are CmpInst instructions, check their predicates
9931 if (Opc == Instruction::ICmp || Opc == Instruction::FCmp)
9932 if (cast<CmpInst>(I)->getPredicate() !=
9933 cast<CmpInst>(FirstInst)->getPredicate())
9934 return 0;
Chris Lattnercd62f112006-11-08 19:29:23 +00009935
9936 // Keep track of which operand needs a phi node.
9937 if (I->getOperand(0) != LHSVal) LHSVal = 0;
9938 if (I->getOperand(1) != RHSVal) RHSVal = 0;
Chris Lattnercadac0c2006-11-01 04:51:18 +00009939 }
9940
Chris Lattner4f218d52006-11-08 19:42:28 +00009941 // Otherwise, this is safe to transform, determine if it is profitable.
9942
9943 // If this is a GEP, and if the index (not the pointer) needs a PHI, bail out.
9944 // Indexes are often folded into load/store instructions, so we don't want to
9945 // hide them behind a phi.
9946 if (isa<GetElementPtrInst>(FirstInst) && RHSVal == 0)
9947 return 0;
9948
Chris Lattnercadac0c2006-11-01 04:51:18 +00009949 Value *InLHS = FirstInst->getOperand(0);
Chris Lattnercadac0c2006-11-01 04:51:18 +00009950 Value *InRHS = FirstInst->getOperand(1);
Chris Lattner4f218d52006-11-08 19:42:28 +00009951 PHINode *NewLHS = 0, *NewRHS = 0;
Chris Lattnercd62f112006-11-08 19:29:23 +00009952 if (LHSVal == 0) {
Gabor Greif697e94c2008-05-15 10:04:30 +00009953 NewLHS = PHINode::Create(LHSType,
9954 FirstInst->getOperand(0)->getName() + ".pn");
Chris Lattnercd62f112006-11-08 19:29:23 +00009955 NewLHS->reserveOperandSpace(PN.getNumOperands()/2);
9956 NewLHS->addIncoming(InLHS, PN.getIncomingBlock(0));
Chris Lattnereebea432006-11-01 07:43:41 +00009957 InsertNewInstBefore(NewLHS, PN);
9958 LHSVal = NewLHS;
9959 }
Chris Lattnercd62f112006-11-08 19:29:23 +00009960
9961 if (RHSVal == 0) {
Gabor Greif697e94c2008-05-15 10:04:30 +00009962 NewRHS = PHINode::Create(RHSType,
9963 FirstInst->getOperand(1)->getName() + ".pn");
Chris Lattnercd62f112006-11-08 19:29:23 +00009964 NewRHS->reserveOperandSpace(PN.getNumOperands()/2);
9965 NewRHS->addIncoming(InRHS, PN.getIncomingBlock(0));
Chris Lattnereebea432006-11-01 07:43:41 +00009966 InsertNewInstBefore(NewRHS, PN);
9967 RHSVal = NewRHS;
9968 }
9969
Chris Lattnercd62f112006-11-08 19:29:23 +00009970 // Add all operands to the new PHIs.
9971 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
9972 if (NewLHS) {
9973 Value *NewInLHS =cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
9974 NewLHS->addIncoming(NewInLHS, PN.getIncomingBlock(i));
9975 }
9976 if (NewRHS) {
9977 Value *NewInRHS =cast<Instruction>(PN.getIncomingValue(i))->getOperand(1);
9978 NewRHS->addIncoming(NewInRHS, PN.getIncomingBlock(i));
9979 }
9980 }
9981
Chris Lattnercadac0c2006-11-01 04:51:18 +00009982 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Gabor Greife1f6e4b2008-05-16 19:29:10 +00009983 return BinaryOperator::Create(BinOp->getOpcode(), LHSVal, RHSVal);
Reid Spencer266e42b2006-12-23 06:05:41 +00009984 else if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
Gabor Greife1f6e4b2008-05-16 19:29:10 +00009985 return CmpInst::Create(CIOp->getOpcode(), CIOp->getPredicate(), LHSVal,
Reid Spencer266e42b2006-12-23 06:05:41 +00009986 RHSVal);
Chris Lattnereebea432006-11-01 07:43:41 +00009987 else {
9988 assert(isa<GetElementPtrInst>(FirstInst));
Gabor Greife9ecc682008-04-06 20:25:17 +00009989 return GetElementPtrInst::Create(LHSVal, RHSVal);
Chris Lattnereebea432006-11-01 07:43:41 +00009990 }
Chris Lattnercadac0c2006-11-01 04:51:18 +00009991}
9992
Chris Lattner14f82c72006-11-01 07:13:54 +00009993/// isSafeToSinkLoad - Return true if we know that it is safe sink the load out
9994/// of the block that defines it. This means that it must be obvious the value
9995/// of the load is not changed from the point of the load to the end of the
9996/// block it is in.
Chris Lattnerc9042052007-02-01 22:30:07 +00009997///
9998/// Finally, it is safe, but not profitable, to sink a load targetting a
9999/// non-address-taken alloca. Doing so will cause us to not promote the alloca
10000/// to a register.
Chris Lattner14f82c72006-11-01 07:13:54 +000010001static bool isSafeToSinkLoad(LoadInst *L) {
10002 BasicBlock::iterator BBI = L, E = L->getParent()->end();
10003
10004 for (++BBI; BBI != E; ++BBI)
10005 if (BBI->mayWriteToMemory())
10006 return false;
Chris Lattnerc9042052007-02-01 22:30:07 +000010007
10008 // Check for non-address taken alloca. If not address-taken already, it isn't
10009 // profitable to do this xform.
10010 if (AllocaInst *AI = dyn_cast<AllocaInst>(L->getOperand(0))) {
10011 bool isAddressTaken = false;
10012 for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end();
10013 UI != E; ++UI) {
10014 if (isa<LoadInst>(UI)) continue;
10015 if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
10016 // If storing TO the alloca, then the address isn't taken.
10017 if (SI->getOperand(1) == AI) continue;
10018 }
10019 isAddressTaken = true;
10020 break;
10021 }
10022
10023 if (!isAddressTaken)
10024 return false;
10025 }
10026
Chris Lattner14f82c72006-11-01 07:13:54 +000010027 return true;
10028}
10029
Chris Lattner970c33a2003-06-19 17:00:31 +000010030
Chris Lattner7515cab2004-11-14 19:13:23 +000010031// FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
10032// operator and they all are only used by the PHI, PHI together their
10033// inputs, and do the operation once, to the result of the PHI.
10034Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
10035 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
10036
10037 // Scan the instruction, looking for input operations that can be folded away.
10038 // If all input operands to the phi are the same instruction (e.g. a cast from
10039 // the same type or "+42") we can pull the operation through the PHI, reducing
10040 // code size and simplifying code.
10041 Constant *ConstantOp = 0;
10042 const Type *CastSrcTy = 0;
Chris Lattner14f82c72006-11-01 07:13:54 +000010043 bool isVolatile = false;
Chris Lattner7515cab2004-11-14 19:13:23 +000010044 if (isa<CastInst>(FirstInst)) {
10045 CastSrcTy = FirstInst->getOperand(0)->getType();
Reid Spencer2341c222007-02-02 02:16:23 +000010046 } else if (isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst)) {
Reid Spencer266e42b2006-12-23 06:05:41 +000010047 // Can fold binop, compare or shift here if the RHS is a constant,
10048 // otherwise call FoldPHIArgBinOpIntoPHI.
Chris Lattner7515cab2004-11-14 19:13:23 +000010049 ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
Chris Lattnercadac0c2006-11-01 04:51:18 +000010050 if (ConstantOp == 0)
10051 return FoldPHIArgBinOpIntoPHI(PN);
Chris Lattner14f82c72006-11-01 07:13:54 +000010052 } else if (LoadInst *LI = dyn_cast<LoadInst>(FirstInst)) {
10053 isVolatile = LI->isVolatile();
10054 // We can't sink the load if the loaded value could be modified between the
10055 // load and the PHI.
10056 if (LI->getParent() != PN.getIncomingBlock(0) ||
10057 !isSafeToSinkLoad(LI))
10058 return 0;
Chris Lattner501d78f2008-07-08 17:18:32 +000010059
10060 // If the PHI is of volatile loads and the load block has multiple
10061 // successors, sinking it would remove a load of the volatile value from
10062 // the path through the other successor.
10063 if (isVolatile &&
10064 LI->getParent()->getTerminator()->getNumSuccessors() != 1)
10065 return 0;
10066
Chris Lattnereebea432006-11-01 07:43:41 +000010067 } else if (isa<GetElementPtrInst>(FirstInst)) {
Chris Lattner4f218d52006-11-08 19:42:28 +000010068 if (FirstInst->getNumOperands() == 2)
Chris Lattnereebea432006-11-01 07:43:41 +000010069 return FoldPHIArgBinOpIntoPHI(PN);
10070 // Can't handle general GEPs yet.
10071 return 0;
Chris Lattner7515cab2004-11-14 19:13:23 +000010072 } else {
10073 return 0; // Cannot fold this operation.
10074 }
10075
10076 // Check to see if all arguments are the same operation.
10077 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10078 if (!isa<Instruction>(PN.getIncomingValue(i))) return 0;
10079 Instruction *I = cast<Instruction>(PN.getIncomingValue(i));
Reid Spencer266e42b2006-12-23 06:05:41 +000010080 if (!I->hasOneUse() || !I->isSameOperationAs(FirstInst))
Chris Lattner7515cab2004-11-14 19:13:23 +000010081 return 0;
10082 if (CastSrcTy) {
10083 if (I->getOperand(0)->getType() != CastSrcTy)
10084 return 0; // Cast operation must match.
Chris Lattner14f82c72006-11-01 07:13:54 +000010085 } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Reid Spencer266e42b2006-12-23 06:05:41 +000010086 // We can't sink the load if the loaded value could be modified between
10087 // the load and the PHI.
Chris Lattner14f82c72006-11-01 07:13:54 +000010088 if (LI->isVolatile() != isVolatile ||
10089 LI->getParent() != PN.getIncomingBlock(i) ||
10090 !isSafeToSinkLoad(LI))
10091 return 0;
Chris Lattnerd9e3b5c2008-04-29 17:28:22 +000010092
Chris Lattner501d78f2008-07-08 17:18:32 +000010093 // If the PHI is of volatile loads and the load block has multiple
10094 // successors, sinking it would remove a load of the volatile value from
10095 // the path through the other successor.
Chris Lattnerd9e3b5c2008-04-29 17:28:22 +000010096 if (isVolatile &&
10097 LI->getParent()->getTerminator()->getNumSuccessors() != 1)
10098 return 0;
10099
10100
Chris Lattner7515cab2004-11-14 19:13:23 +000010101 } else if (I->getOperand(1) != ConstantOp) {
10102 return 0;
10103 }
10104 }
10105
10106 // Okay, they are all the same operation. Create a new PHI node of the
10107 // correct type, and PHI together all of the LHS's of the instructions.
Gabor Greife9ecc682008-04-06 20:25:17 +000010108 PHINode *NewPN = PHINode::Create(FirstInst->getOperand(0)->getType(),
10109 PN.getName()+".in");
Chris Lattnerd8e20182005-01-29 00:39:08 +000010110 NewPN->reserveOperandSpace(PN.getNumOperands()/2);
Chris Lattner46dd5a62004-11-14 19:29:34 +000010111
10112 Value *InVal = FirstInst->getOperand(0);
10113 NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
Chris Lattner7515cab2004-11-14 19:13:23 +000010114
10115 // Add all operands to the new PHI.
Chris Lattner46dd5a62004-11-14 19:29:34 +000010116 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10117 Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
10118 if (NewInVal != InVal)
10119 InVal = 0;
10120 NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
10121 }
10122
10123 Value *PhiVal;
10124 if (InVal) {
10125 // The new PHI unions all of the same values together. This is really
10126 // common, so we handle it intelligently here for compile-time speed.
10127 PhiVal = InVal;
10128 delete NewPN;
10129 } else {
10130 InsertNewInstBefore(NewPN, PN);
10131 PhiVal = NewPN;
10132 }
Misha Brukmanb1c93172005-04-21 23:48:37 +000010133
Chris Lattner7515cab2004-11-14 19:13:23 +000010134 // Insert and return the new operation.
Reid Spencer6c38f0b2006-11-27 01:05:10 +000010135 if (CastInst* FirstCI = dyn_cast<CastInst>(FirstInst))
Gabor Greife1f6e4b2008-05-16 19:29:10 +000010136 return CastInst::Create(FirstCI->getOpcode(), PhiVal, PN.getType());
Chris Lattner9233c122008-04-29 17:13:43 +000010137 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Gabor Greife1f6e4b2008-05-16 19:29:10 +000010138 return BinaryOperator::Create(BinOp->getOpcode(), PhiVal, ConstantOp);
Chris Lattner9233c122008-04-29 17:13:43 +000010139 if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
Gabor Greife1f6e4b2008-05-16 19:29:10 +000010140 return CmpInst::Create(CIOp->getOpcode(), CIOp->getPredicate(),
Reid Spencer266e42b2006-12-23 06:05:41 +000010141 PhiVal, ConstantOp);
Chris Lattner9233c122008-04-29 17:13:43 +000010142 assert(isa<LoadInst>(FirstInst) && "Unknown operation");
10143
10144 // If this was a volatile load that we are merging, make sure to loop through
10145 // and mark all the input loads as non-volatile. If we don't do this, we will
10146 // insert a new volatile load and the old ones will not be deletable.
10147 if (isVolatile)
10148 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
10149 cast<LoadInst>(PN.getIncomingValue(i))->setVolatile(false);
10150
10151 return new LoadInst(PhiVal, "", isVolatile);
Chris Lattner7515cab2004-11-14 19:13:23 +000010152}
Chris Lattner48a44f72002-05-02 17:06:02 +000010153
Chris Lattner71536432005-01-17 05:10:15 +000010154/// DeadPHICycle - Return true if this PHI node is only used by a PHI node cycle
10155/// that is dead.
Chris Lattnerd2602d52007-03-26 20:40:50 +000010156static bool DeadPHICycle(PHINode *PN,
10157 SmallPtrSet<PHINode*, 16> &PotentiallyDeadPHIs) {
Chris Lattner71536432005-01-17 05:10:15 +000010158 if (PN->use_empty()) return true;
10159 if (!PN->hasOneUse()) return false;
10160
10161 // Remember this node, and if we find the cycle, return.
Chris Lattnerd2602d52007-03-26 20:40:50 +000010162 if (!PotentiallyDeadPHIs.insert(PN))
Chris Lattner71536432005-01-17 05:10:15 +000010163 return true;
Chris Lattner0e258b82007-08-28 04:23:55 +000010164
10165 // Don't scan crazily complex things.
10166 if (PotentiallyDeadPHIs.size() == 16)
10167 return false;
Chris Lattner71536432005-01-17 05:10:15 +000010168
10169 if (PHINode *PU = dyn_cast<PHINode>(PN->use_back()))
10170 return DeadPHICycle(PU, PotentiallyDeadPHIs);
Misha Brukmanb1c93172005-04-21 23:48:37 +000010171
Chris Lattner71536432005-01-17 05:10:15 +000010172 return false;
10173}
10174
Chris Lattnerd8515f82007-11-06 21:52:06 +000010175/// PHIsEqualValue - Return true if this phi node is always equal to
10176/// NonPhiInVal. This happens with mutually cyclic phi nodes like:
10177/// z = some value; x = phi (y, z); y = phi (x, z)
10178static bool PHIsEqualValue(PHINode *PN, Value *NonPhiInVal,
10179 SmallPtrSet<PHINode*, 16> &ValueEqualPHIs) {
10180 // See if we already saw this PHI node.
10181 if (!ValueEqualPHIs.insert(PN))
10182 return true;
10183
10184 // Don't scan crazily complex things.
10185 if (ValueEqualPHIs.size() == 16)
10186 return false;
10187
10188 // Scan the operands to see if they are either phi nodes or are equal to
10189 // the value.
10190 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
10191 Value *Op = PN->getIncomingValue(i);
10192 if (PHINode *OpPN = dyn_cast<PHINode>(Op)) {
10193 if (!PHIsEqualValue(OpPN, NonPhiInVal, ValueEqualPHIs))
10194 return false;
10195 } else if (Op != NonPhiInVal)
10196 return false;
10197 }
10198
10199 return true;
10200}
10201
10202
Chris Lattnerbbbdd852002-05-06 18:06:38 +000010203// PHINode simplification
10204//
Chris Lattner113f4f42002-06-25 16:13:24 +000010205Instruction *InstCombiner::visitPHINode(PHINode &PN) {
Owen Andersonbbf89902006-07-10 22:15:25 +000010206 // If LCSSA is around, don't mess with Phi nodes
Chris Lattner8258b442007-03-04 04:27:24 +000010207 if (MustPreserveLCSSA) return 0;
Owen Andersona6968f82006-07-10 19:03:49 +000010208
Owen Andersonae8aa642006-07-10 22:03:18 +000010209 if (Value *V = PN.hasConstantValue())
10210 return ReplaceInstUsesWith(PN, V);
10211
Owen Andersonae8aa642006-07-10 22:03:18 +000010212 // If all PHI operands are the same operation, pull them through the PHI,
10213 // reducing code size.
10214 if (isa<Instruction>(PN.getIncomingValue(0)) &&
10215 PN.getIncomingValue(0)->hasOneUse())
10216 if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
10217 return Result;
10218
10219 // If this is a trivial cycle in the PHI node graph, remove it. Basically, if
10220 // this PHI only has a single use (a PHI), and if that PHI only has one use (a
10221 // PHI)... break the cycle.
Chris Lattnerc8dcede2007-01-15 07:30:06 +000010222 if (PN.hasOneUse()) {
10223 Instruction *PHIUser = cast<Instruction>(PN.use_back());
10224 if (PHINode *PU = dyn_cast<PHINode>(PHIUser)) {
Chris Lattnerd2602d52007-03-26 20:40:50 +000010225 SmallPtrSet<PHINode*, 16> PotentiallyDeadPHIs;
Owen Andersonae8aa642006-07-10 22:03:18 +000010226 PotentiallyDeadPHIs.insert(&PN);
10227 if (DeadPHICycle(PU, PotentiallyDeadPHIs))
10228 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
10229 }
Chris Lattnerc8dcede2007-01-15 07:30:06 +000010230
10231 // If this phi has a single use, and if that use just computes a value for
10232 // the next iteration of a loop, delete the phi. This occurs with unused
10233 // induction variables, e.g. "for (int j = 0; ; ++j);". Detecting this
10234 // common case here is good because the only other things that catch this
10235 // are induction variable analysis (sometimes) and ADCE, which is only run
10236 // late.
10237 if (PHIUser->hasOneUse() &&
10238 (isa<BinaryOperator>(PHIUser) || isa<GetElementPtrInst>(PHIUser)) &&
10239 PHIUser->use_back() == &PN) {
10240 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
10241 }
10242 }
Owen Andersonae8aa642006-07-10 22:03:18 +000010243
Chris Lattnerd8515f82007-11-06 21:52:06 +000010244 // We sometimes end up with phi cycles that non-obviously end up being the
10245 // same value, for example:
10246 // z = some value; x = phi (y, z); y = phi (x, z)
10247 // where the phi nodes don't necessarily need to be in the same block. Do a
10248 // quick check to see if the PHI node only contains a single non-phi value, if
10249 // so, scan to see if the phi cycle is actually equal to that value.
10250 {
10251 unsigned InValNo = 0, NumOperandVals = PN.getNumIncomingValues();
10252 // Scan for the first non-phi operand.
10253 while (InValNo != NumOperandVals &&
10254 isa<PHINode>(PN.getIncomingValue(InValNo)))
10255 ++InValNo;
10256
10257 if (InValNo != NumOperandVals) {
10258 Value *NonPhiInVal = PN.getOperand(InValNo);
10259
10260 // Scan the rest of the operands to see if there are any conflicts, if so
10261 // there is no need to recursively scan other phis.
10262 for (++InValNo; InValNo != NumOperandVals; ++InValNo) {
10263 Value *OpVal = PN.getIncomingValue(InValNo);
10264 if (OpVal != NonPhiInVal && !isa<PHINode>(OpVal))
10265 break;
10266 }
10267
10268 // If we scanned over all operands, then we have one unique value plus
10269 // phi values. Scan PHI nodes to see if they all merge in each other or
10270 // the value.
10271 if (InValNo == NumOperandVals) {
10272 SmallPtrSet<PHINode*, 16> ValueEqualPHIs;
10273 if (PHIsEqualValue(&PN, NonPhiInVal, ValueEqualPHIs))
10274 return ReplaceInstUsesWith(PN, NonPhiInVal);
10275 }
10276 }
10277 }
Chris Lattner91daeb52003-12-19 05:58:40 +000010278 return 0;
Chris Lattnerbbbdd852002-05-06 18:06:38 +000010279}
10280
Reid Spencer13bc5d72006-12-12 09:18:51 +000010281static Value *InsertCastToIntPtrTy(Value *V, const Type *DTy,
10282 Instruction *InsertPoint,
10283 InstCombiner *IC) {
Reid Spencer8f166b02007-01-08 16:32:00 +000010284 unsigned PtrSize = DTy->getPrimitiveSizeInBits();
10285 unsigned VTySize = V->getType()->getPrimitiveSizeInBits();
Reid Spencer13bc5d72006-12-12 09:18:51 +000010286 // We must cast correctly to the pointer type. Ensure that we
10287 // sign extend the integer value if it is smaller as this is
10288 // used for address computation.
10289 Instruction::CastOps opcode =
10290 (VTySize < PtrSize ? Instruction::SExt :
10291 (VTySize == PtrSize ? Instruction::BitCast : Instruction::Trunc));
10292 return IC->InsertCastBefore(opcode, V, DTy, *InsertPoint);
Chris Lattner69193f92004-04-05 01:30:19 +000010293}
10294
Chris Lattner48a44f72002-05-02 17:06:02 +000010295
Chris Lattner113f4f42002-06-25 16:13:24 +000010296Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
Chris Lattner5f667a62004-05-07 22:09:22 +000010297 Value *PtrOp = GEP.getOperand(0);
Chris Lattneracbf6a42007-04-28 00:57:34 +000010298 // Is it 'getelementptr %P, i32 0' or 'getelementptr %P'
Chris Lattner113f4f42002-06-25 16:13:24 +000010299 // If so, eliminate the noop.
Chris Lattner8d0bacb2004-02-22 05:25:17 +000010300 if (GEP.getNumOperands() == 1)
Chris Lattner5f667a62004-05-07 22:09:22 +000010301 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattner8d0bacb2004-02-22 05:25:17 +000010302
Chris Lattner81a7a232004-10-16 18:11:37 +000010303 if (isa<UndefValue>(GEP.getOperand(0)))
10304 return ReplaceInstUsesWith(GEP, UndefValue::get(GEP.getType()));
10305
Chris Lattner8d0bacb2004-02-22 05:25:17 +000010306 bool HasZeroPointerIndex = false;
10307 if (Constant *C = dyn_cast<Constant>(GEP.getOperand(1)))
10308 HasZeroPointerIndex = C->isNullValue();
10309
10310 if (GEP.getNumOperands() == 2 && HasZeroPointerIndex)
Chris Lattner5f667a62004-05-07 22:09:22 +000010311 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattner48a44f72002-05-02 17:06:02 +000010312
Chris Lattner69193f92004-04-05 01:30:19 +000010313 // Eliminate unneeded casts for indices.
10314 bool MadeChange = false;
Chris Lattner9bf53ff2007-03-25 20:43:09 +000010315
Chris Lattner2b2412d2004-04-07 18:38:20 +000010316 gep_type_iterator GTI = gep_type_begin(GEP);
Gabor Greiff6d8e772008-06-12 21:37:33 +000010317 for (User::op_iterator i = GEP.op_begin() + 1, e = GEP.op_end();
10318 i != e; ++i, ++GTI) {
Chris Lattner2b2412d2004-04-07 18:38:20 +000010319 if (isa<SequentialType>(*GTI)) {
Gabor Greiff6d8e772008-06-12 21:37:33 +000010320 if (CastInst *CI = dyn_cast<CastInst>(*i)) {
Chris Lattner27df1db2007-01-15 07:02:54 +000010321 if (CI->getOpcode() == Instruction::ZExt ||
10322 CI->getOpcode() == Instruction::SExt) {
10323 const Type *SrcTy = CI->getOperand(0)->getType();
10324 // We can eliminate a cast from i32 to i64 iff the target
10325 // is a 32-bit pointer target.
10326 if (SrcTy->getPrimitiveSizeInBits() >= TD->getPointerSizeInBits()) {
10327 MadeChange = true;
Gabor Greiff6d8e772008-06-12 21:37:33 +000010328 *i = CI->getOperand(0);
Chris Lattner69193f92004-04-05 01:30:19 +000010329 }
10330 }
10331 }
Chris Lattner2b2412d2004-04-07 18:38:20 +000010332 // If we are using a wider index than needed for this platform, shrink it
Dan Gohmaneff71f22008-09-11 23:06:38 +000010333 // to what we need. If narrower, sign-extend it to what we need.
10334 // If the incoming value needs a cast instruction,
Chris Lattner2b2412d2004-04-07 18:38:20 +000010335 // insert it. This explicit cast can make subsequent optimizations more
10336 // obvious.
Gabor Greiff6d8e772008-06-12 21:37:33 +000010337 Value *Op = *i;
Anton Korobeynikov1bfd1212008-02-20 11:26:25 +000010338 if (TD->getTypeSizeInBits(Op->getType()) > TD->getPointerSizeInBits()) {
Chris Lattner1e9ac1a2004-04-17 18:16:10 +000010339 if (Constant *C = dyn_cast<Constant>(Op)) {
Gabor Greiff6d8e772008-06-12 21:37:33 +000010340 *i = ConstantExpr::getTrunc(C, TD->getIntPtrType());
Chris Lattner1e9ac1a2004-04-17 18:16:10 +000010341 MadeChange = true;
10342 } else {
Reid Spencer13bc5d72006-12-12 09:18:51 +000010343 Op = InsertCastBefore(Instruction::Trunc, Op, TD->getIntPtrType(),
10344 GEP);
Gabor Greiff6d8e772008-06-12 21:37:33 +000010345 *i = Op;
Chris Lattner2b2412d2004-04-07 18:38:20 +000010346 MadeChange = true;
10347 }
Dan Gohmaneff71f22008-09-11 23:06:38 +000010348 } else if (TD->getTypeSizeInBits(Op->getType()) < TD->getPointerSizeInBits()) {
10349 if (Constant *C = dyn_cast<Constant>(Op)) {
10350 *i = ConstantExpr::getSExt(C, TD->getIntPtrType());
10351 MadeChange = true;
10352 } else {
10353 Op = InsertCastBefore(Instruction::SExt, Op, TD->getIntPtrType(),
10354 GEP);
10355 *i = Op;
10356 MadeChange = true;
10357 }
Anton Korobeynikov1bfd1212008-02-20 11:26:25 +000010358 }
Chris Lattner69193f92004-04-05 01:30:19 +000010359 }
Chris Lattner9bf53ff2007-03-25 20:43:09 +000010360 }
Chris Lattner69193f92004-04-05 01:30:19 +000010361 if (MadeChange) return &GEP;
10362
Chris Lattner9bf53ff2007-03-25 20:43:09 +000010363 // If this GEP instruction doesn't move the pointer, and if the input operand
10364 // is a bitcast of another pointer, just replace the GEP with a bitcast of the
10365 // real input to the dest type.
Chris Lattnerd8675e42007-10-12 05:30:59 +000010366 if (GEP.hasAllZeroIndices()) {
10367 if (BitCastInst *BCI = dyn_cast<BitCastInst>(GEP.getOperand(0))) {
10368 // If the bitcast is of an allocation, and the allocation will be
10369 // converted to match the type of the cast, don't touch this.
10370 if (isa<AllocationInst>(BCI->getOperand(0))) {
10371 // See if the bitcast simplifies, if so, don't nuke this GEP yet.
Chris Lattnerad618f62007-10-12 18:05:47 +000010372 if (Instruction *I = visitBitCast(*BCI)) {
10373 if (I != BCI) {
10374 I->takeName(BCI);
10375 BCI->getParent()->getInstList().insert(BCI, I);
10376 ReplaceInstUsesWith(*BCI, I);
10377 }
Chris Lattnerd8675e42007-10-12 05:30:59 +000010378 return &GEP;
Chris Lattnerad618f62007-10-12 18:05:47 +000010379 }
Chris Lattnerd8675e42007-10-12 05:30:59 +000010380 }
10381 return new BitCastInst(BCI->getOperand(0), GEP.getType());
10382 }
10383 }
10384
Chris Lattnerae7a0d32002-08-02 19:29:35 +000010385 // Combine Indices - If the source pointer to this getelementptr instruction
10386 // is a getelementptr instruction, combine the indices of the two
10387 // getelementptr instructions into a single instruction.
10388 //
Chris Lattneraf6094f2007-02-15 22:48:32 +000010389 SmallVector<Value*, 8> SrcGEPOperands;
Chris Lattner0798af32005-01-13 20:14:25 +000010390 if (User *Src = dyn_castGetElementPtr(PtrOp))
Chris Lattneraf6094f2007-02-15 22:48:32 +000010391 SrcGEPOperands.append(Src->op_begin(), Src->op_end());
Chris Lattner57c67b02004-03-25 22:59:29 +000010392
10393 if (!SrcGEPOperands.empty()) {
Chris Lattner5f667a62004-05-07 22:09:22 +000010394 // Note that if our source is a gep chain itself that we wait for that
10395 // chain to be resolved before we perform this transformation. This
10396 // avoids us creating a TON of code in some cases.
10397 //
10398 if (isa<GetElementPtrInst>(SrcGEPOperands[0]) &&
10399 cast<Instruction>(SrcGEPOperands[0])->getNumOperands() == 2)
10400 return 0; // Wait until our source is folded to completion.
10401
Chris Lattneraf6094f2007-02-15 22:48:32 +000010402 SmallVector<Value*, 8> Indices;
Chris Lattner5f667a62004-05-07 22:09:22 +000010403
10404 // Find out whether the last index in the source GEP is a sequential idx.
10405 bool EndsWithSequential = false;
10406 for (gep_type_iterator I = gep_type_begin(*cast<User>(PtrOp)),
10407 E = gep_type_end(*cast<User>(PtrOp)); I != E; ++I)
Chris Lattner8ec5f882004-05-08 22:41:42 +000010408 EndsWithSequential = !isa<StructType>(*I);
Misha Brukmanb1c93172005-04-21 23:48:37 +000010409
Chris Lattnerae7a0d32002-08-02 19:29:35 +000010410 // Can we combine the two pointer arithmetics offsets?
Chris Lattner5f667a62004-05-07 22:09:22 +000010411 if (EndsWithSequential) {
Chris Lattner235af562003-03-05 22:33:14 +000010412 // Replace: gep (gep %P, long B), long A, ...
10413 // With: T = long A+B; gep %P, T, ...
10414 //
Chris Lattner5f667a62004-05-07 22:09:22 +000010415 Value *Sum, *SO1 = SrcGEPOperands.back(), *GO1 = GEP.getOperand(1);
Chris Lattner69193f92004-04-05 01:30:19 +000010416 if (SO1 == Constant::getNullValue(SO1->getType())) {
10417 Sum = GO1;
10418 } else if (GO1 == Constant::getNullValue(GO1->getType())) {
10419 Sum = SO1;
10420 } else {
10421 // If they aren't the same type, convert both to an integer of the
10422 // target's pointer size.
10423 if (SO1->getType() != GO1->getType()) {
10424 if (Constant *SO1C = dyn_cast<Constant>(SO1)) {
Reid Spencer13bc5d72006-12-12 09:18:51 +000010425 SO1 = ConstantExpr::getIntegerCast(SO1C, GO1->getType(), true);
Chris Lattner69193f92004-04-05 01:30:19 +000010426 } else if (Constant *GO1C = dyn_cast<Constant>(GO1)) {
Reid Spencer13bc5d72006-12-12 09:18:51 +000010427 GO1 = ConstantExpr::getIntegerCast(GO1C, SO1->getType(), true);
Chris Lattner69193f92004-04-05 01:30:19 +000010428 } else {
Duncan Sands44b87212007-11-01 20:53:16 +000010429 unsigned PS = TD->getPointerSizeInBits();
10430 if (TD->getTypeSizeInBits(SO1->getType()) == PS) {
Chris Lattner69193f92004-04-05 01:30:19 +000010431 // Convert GO1 to SO1's type.
Reid Spencer13bc5d72006-12-12 09:18:51 +000010432 GO1 = InsertCastToIntPtrTy(GO1, SO1->getType(), &GEP, this);
Chris Lattner69193f92004-04-05 01:30:19 +000010433
Duncan Sands44b87212007-11-01 20:53:16 +000010434 } else if (TD->getTypeSizeInBits(GO1->getType()) == PS) {
Chris Lattner69193f92004-04-05 01:30:19 +000010435 // Convert SO1 to GO1's type.
Reid Spencer13bc5d72006-12-12 09:18:51 +000010436 SO1 = InsertCastToIntPtrTy(SO1, GO1->getType(), &GEP, this);
Chris Lattner69193f92004-04-05 01:30:19 +000010437 } else {
10438 const Type *PT = TD->getIntPtrType();
Reid Spencer13bc5d72006-12-12 09:18:51 +000010439 SO1 = InsertCastToIntPtrTy(SO1, PT, &GEP, this);
10440 GO1 = InsertCastToIntPtrTy(GO1, PT, &GEP, this);
Chris Lattner69193f92004-04-05 01:30:19 +000010441 }
10442 }
10443 }
Chris Lattner5f667a62004-05-07 22:09:22 +000010444 if (isa<Constant>(SO1) && isa<Constant>(GO1))
10445 Sum = ConstantExpr::getAdd(cast<Constant>(SO1), cast<Constant>(GO1));
10446 else {
Gabor Greife1f6e4b2008-05-16 19:29:10 +000010447 Sum = BinaryOperator::CreateAdd(SO1, GO1, PtrOp->getName()+".sum");
Chris Lattnerdf20a4d2004-06-10 02:07:29 +000010448 InsertNewInstBefore(cast<Instruction>(Sum), GEP);
Chris Lattner5f667a62004-05-07 22:09:22 +000010449 }
Chris Lattner69193f92004-04-05 01:30:19 +000010450 }
Chris Lattner5f667a62004-05-07 22:09:22 +000010451
10452 // Recycle the GEP we already have if possible.
10453 if (SrcGEPOperands.size() == 2) {
10454 GEP.setOperand(0, SrcGEPOperands[0]);
10455 GEP.setOperand(1, Sum);
10456 return &GEP;
10457 } else {
10458 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
10459 SrcGEPOperands.end()-1);
10460 Indices.push_back(Sum);
10461 Indices.insert(Indices.end(), GEP.op_begin()+2, GEP.op_end());
10462 }
Misha Brukmanb1c93172005-04-21 23:48:37 +000010463 } else if (isa<Constant>(*GEP.idx_begin()) &&
Chris Lattner69193f92004-04-05 01:30:19 +000010464 cast<Constant>(*GEP.idx_begin())->isNullValue() &&
Misha Brukmanb1c93172005-04-21 23:48:37 +000010465 SrcGEPOperands.size() != 1) {
Chris Lattnerae7a0d32002-08-02 19:29:35 +000010466 // Otherwise we can do the fold if the first index of the GEP is a zero
Chris Lattner57c67b02004-03-25 22:59:29 +000010467 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
10468 SrcGEPOperands.end());
Chris Lattnerae7a0d32002-08-02 19:29:35 +000010469 Indices.insert(Indices.end(), GEP.idx_begin()+1, GEP.idx_end());
10470 }
10471
10472 if (!Indices.empty())
Gabor Greife9ecc682008-04-06 20:25:17 +000010473 return GetElementPtrInst::Create(SrcGEPOperands[0], Indices.begin(),
10474 Indices.end(), GEP.getName());
Chris Lattnerc59af1d2002-08-17 22:21:59 +000010475
Chris Lattner5f667a62004-05-07 22:09:22 +000010476 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(PtrOp)) {
Chris Lattnerc59af1d2002-08-17 22:21:59 +000010477 // GEP of global variable. If all of the indices for this GEP are
10478 // constants, we can promote this to a constexpr instead of an instruction.
10479
10480 // Scan for nonconstants...
Chris Lattnerf96f4a82007-01-31 04:40:53 +000010481 SmallVector<Constant*, 8> Indices;
Chris Lattnerc59af1d2002-08-17 22:21:59 +000010482 User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end();
10483 for (; I != E && isa<Constant>(*I); ++I)
10484 Indices.push_back(cast<Constant>(*I));
10485
10486 if (I == E) { // If they are all constants...
Chris Lattnerf96f4a82007-01-31 04:40:53 +000010487 Constant *CE = ConstantExpr::getGetElementPtr(GV,
10488 &Indices[0],Indices.size());
Chris Lattnerc59af1d2002-08-17 22:21:59 +000010489
10490 // Replace all uses of the GEP with the new constexpr...
10491 return ReplaceInstUsesWith(GEP, CE);
10492 }
Reid Spencer6c38f0b2006-11-27 01:05:10 +000010493 } else if (Value *X = getBitCastOperand(PtrOp)) { // Is the operand a cast?
Chris Lattner567b81f2005-09-13 00:40:14 +000010494 if (!isa<PointerType>(X->getType())) {
10495 // Not interesting. Source pointer must be a cast from pointer.
10496 } else if (HasZeroPointerIndex) {
Wojciech Matyjewicz309e5a72007-12-12 15:21:32 +000010497 // transform: GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ...
10498 // into : GEP [10 x i8]* X, i32 0, ...
Chris Lattner567b81f2005-09-13 00:40:14 +000010499 //
10500 // This occurs when the program declares an array extern like "int X[];"
10501 //
10502 const PointerType *CPTy = cast<PointerType>(PtrOp->getType());
10503 const PointerType *XTy = cast<PointerType>(X->getType());
10504 if (const ArrayType *XATy =
10505 dyn_cast<ArrayType>(XTy->getElementType()))
10506 if (const ArrayType *CATy =
10507 dyn_cast<ArrayType>(CPTy->getElementType()))
10508 if (CATy->getElementType() == XATy->getElementType()) {
10509 // At this point, we know that the cast source type is a pointer
10510 // to an array of the same type as the destination pointer
10511 // array. Because the array type is never stepped over (there
10512 // is a leading zero) we can fold the cast into this GEP.
10513 GEP.setOperand(0, X);
10514 return &GEP;
10515 }
10516 } else if (GEP.getNumOperands() == 2) {
10517 // Transform things like:
Wojciech Matyjewicz309e5a72007-12-12 15:21:32 +000010518 // %t = getelementptr i32* bitcast ([2 x i32]* %str to i32*), i32 %V
10519 // into: %t1 = getelementptr [2 x i32]* %str, i32 0, i32 %V; bitcast
Chris Lattner567b81f2005-09-13 00:40:14 +000010520 const Type *SrcElTy = cast<PointerType>(X->getType())->getElementType();
10521 const Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
10522 if (isa<ArrayType>(SrcElTy) &&
Duncan Sands44b87212007-11-01 20:53:16 +000010523 TD->getABITypeSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
10524 TD->getABITypeSize(ResElTy)) {
David Greenec656cbb2007-09-04 15:46:09 +000010525 Value *Idx[2];
10526 Idx[0] = Constant::getNullValue(Type::Int32Ty);
10527 Idx[1] = GEP.getOperand(1);
Chris Lattner567b81f2005-09-13 00:40:14 +000010528 Value *V = InsertNewInstBefore(
Gabor Greife9ecc682008-04-06 20:25:17 +000010529 GetElementPtrInst::Create(X, Idx, Idx + 2, GEP.getName()), GEP);
Reid Spencer6c38f0b2006-11-27 01:05:10 +000010530 // V and GEP are both pointer types --> BitCast
10531 return new BitCastInst(V, GEP.getType());
Chris Lattner8d0bacb2004-02-22 05:25:17 +000010532 }
Chris Lattner2a893292005-09-13 18:36:04 +000010533
10534 // Transform things like:
Wojciech Matyjewicz309e5a72007-12-12 15:21:32 +000010535 // getelementptr i8* bitcast ([100 x double]* X to i8*), i32 %tmp
Chris Lattner2a893292005-09-13 18:36:04 +000010536 // (where tmp = 8*tmp2) into:
Wojciech Matyjewicz309e5a72007-12-12 15:21:32 +000010537 // getelementptr [100 x double]* %arr, i32 0, i32 %tmp2; bitcast
Chris Lattner2a893292005-09-13 18:36:04 +000010538
Wojciech Matyjewicz309e5a72007-12-12 15:21:32 +000010539 if (isa<ArrayType>(SrcElTy) && ResElTy == Type::Int8Ty) {
Chris Lattner2a893292005-09-13 18:36:04 +000010540 uint64_t ArrayEltSize =
Duncan Sands44b87212007-11-01 20:53:16 +000010541 TD->getABITypeSize(cast<ArrayType>(SrcElTy)->getElementType());
Chris Lattner2a893292005-09-13 18:36:04 +000010542
10543 // Check to see if "tmp" is a scale by a multiple of ArrayEltSize. We
10544 // allow either a mul, shift, or constant here.
10545 Value *NewIdx = 0;
10546 ConstantInt *Scale = 0;
10547 if (ArrayEltSize == 1) {
10548 NewIdx = GEP.getOperand(1);
10549 Scale = ConstantInt::get(NewIdx->getType(), 1);
10550 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) {
Chris Lattnera393e4d2005-09-14 17:32:56 +000010551 NewIdx = ConstantInt::get(CI->getType(), 1);
Chris Lattner2a893292005-09-13 18:36:04 +000010552 Scale = CI;
10553 } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){
10554 if (Inst->getOpcode() == Instruction::Shl &&
10555 isa<ConstantInt>(Inst->getOperand(1))) {
Zhou Shengb25806f2007-03-30 09:29:48 +000010556 ConstantInt *ShAmt = cast<ConstantInt>(Inst->getOperand(1));
10557 uint32_t ShAmtVal = ShAmt->getLimitedValue(64);
10558 Scale = ConstantInt::get(Inst->getType(), 1ULL << ShAmtVal);
Chris Lattner2a893292005-09-13 18:36:04 +000010559 NewIdx = Inst->getOperand(0);
10560 } else if (Inst->getOpcode() == Instruction::Mul &&
10561 isa<ConstantInt>(Inst->getOperand(1))) {
10562 Scale = cast<ConstantInt>(Inst->getOperand(1));
10563 NewIdx = Inst->getOperand(0);
10564 }
10565 }
Wojciech Matyjewicz309e5a72007-12-12 15:21:32 +000010566
Chris Lattner2a893292005-09-13 18:36:04 +000010567 // If the index will be to exactly the right offset with the scale taken
Wojciech Matyjewicz309e5a72007-12-12 15:21:32 +000010568 // out, perform the transformation. Note, we don't know whether Scale is
10569 // signed or not. We'll use unsigned version of division/modulo
10570 // operation after making sure Scale doesn't have the sign bit set.
10571 if (Scale && Scale->getSExtValue() >= 0LL &&
10572 Scale->getZExtValue() % ArrayEltSize == 0) {
10573 Scale = ConstantInt::get(Scale->getType(),
10574 Scale->getZExtValue() / ArrayEltSize);
Reid Spencere0fc4df2006-10-20 07:07:24 +000010575 if (Scale->getZExtValue() != 1) {
Reid Spencer13bc5d72006-12-12 09:18:51 +000010576 Constant *C = ConstantExpr::getIntegerCast(Scale, NewIdx->getType(),
Wojciech Matyjewicz309e5a72007-12-12 15:21:32 +000010577 false /*ZExt*/);
Gabor Greife1f6e4b2008-05-16 19:29:10 +000010578 Instruction *Sc = BinaryOperator::CreateMul(NewIdx, C, "idxscale");
Chris Lattner2a893292005-09-13 18:36:04 +000010579 NewIdx = InsertNewInstBefore(Sc, GEP);
10580 }
10581
10582 // Insert the new GEP instruction.
David Greenec656cbb2007-09-04 15:46:09 +000010583 Value *Idx[2];
10584 Idx[0] = Constant::getNullValue(Type::Int32Ty);
10585 Idx[1] = NewIdx;
Reid Spencer6c38f0b2006-11-27 01:05:10 +000010586 Instruction *NewGEP =
Gabor Greife9ecc682008-04-06 20:25:17 +000010587 GetElementPtrInst::Create(X, Idx, Idx + 2, GEP.getName());
Reid Spencer6c38f0b2006-11-27 01:05:10 +000010588 NewGEP = InsertNewInstBefore(NewGEP, GEP);
10589 // The NewGEP must be pointer typed, so must the old one -> BitCast
10590 return new BitCastInst(NewGEP, GEP.getType());
Chris Lattner2a893292005-09-13 18:36:04 +000010591 }
10592 }
Chris Lattner8d0bacb2004-02-22 05:25:17 +000010593 }
Chris Lattnerca081252001-12-14 16:52:21 +000010594 }
10595
Chris Lattnerca081252001-12-14 16:52:21 +000010596 return 0;
10597}
10598
Chris Lattner1085bdf2002-11-04 16:18:53 +000010599Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
10600 // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
Anton Korobeynikov1bfd1212008-02-20 11:26:25 +000010601 if (AI.isArrayAllocation()) { // Check C != 1
Reid Spencere0fc4df2006-10-20 07:07:24 +000010602 if (const ConstantInt *C = dyn_cast<ConstantInt>(AI.getArraySize())) {
10603 const Type *NewTy =
10604 ArrayType::get(AI.getAllocatedType(), C->getZExtValue());
Chris Lattnera2620ac2002-11-09 00:49:43 +000010605 AllocationInst *New = 0;
Chris Lattner1085bdf2002-11-04 16:18:53 +000010606
10607 // Create and insert the replacement instruction...
10608 if (isa<MallocInst>(AI))
Nate Begeman848622f2005-11-05 09:21:28 +000010609 New = new MallocInst(NewTy, 0, AI.getAlignment(), AI.getName());
Chris Lattnera2620ac2002-11-09 00:49:43 +000010610 else {
10611 assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
Nate Begeman848622f2005-11-05 09:21:28 +000010612 New = new AllocaInst(NewTy, 0, AI.getAlignment(), AI.getName());
Chris Lattnera2620ac2002-11-09 00:49:43 +000010613 }
Chris Lattnerabb77c92004-03-19 06:08:10 +000010614
10615 InsertNewInstBefore(New, AI);
Misha Brukmanb1c93172005-04-21 23:48:37 +000010616
Chris Lattner1085bdf2002-11-04 16:18:53 +000010617 // Scan to the end of the allocation instructions, to skip over a block of
10618 // allocas if possible...
10619 //
10620 BasicBlock::iterator It = New;
10621 while (isa<AllocationInst>(*It)) ++It;
10622
10623 // Now that I is pointing to the first non-allocation-inst in the block,
10624 // insert our getelementptr instruction...
10625 //
Reid Spencerc635f472006-12-31 05:48:39 +000010626 Value *NullIdx = Constant::getNullValue(Type::Int32Ty);
David Greenec656cbb2007-09-04 15:46:09 +000010627 Value *Idx[2];
10628 Idx[0] = NullIdx;
10629 Idx[1] = NullIdx;
Gabor Greife9ecc682008-04-06 20:25:17 +000010630 Value *V = GetElementPtrInst::Create(New, Idx, Idx + 2,
10631 New->getName()+".sub", It);
Chris Lattner1085bdf2002-11-04 16:18:53 +000010632
10633 // Now make everything use the getelementptr instead of the original
10634 // allocation.
Chris Lattnerabb77c92004-03-19 06:08:10 +000010635 return ReplaceInstUsesWith(AI, V);
Chris Lattner81a7a232004-10-16 18:11:37 +000010636 } else if (isa<UndefValue>(AI.getArraySize())) {
10637 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
Chris Lattner1085bdf2002-11-04 16:18:53 +000010638 }
Anton Korobeynikov1bfd1212008-02-20 11:26:25 +000010639 }
Chris Lattnerabb77c92004-03-19 06:08:10 +000010640
10641 // If alloca'ing a zero byte object, replace the alloca with a null pointer.
10642 // Note that we only do this for alloca's, because malloc should allocate and
10643 // return a unique pointer, even for a zero byte allocation.
Misha Brukmanb1c93172005-04-21 23:48:37 +000010644 if (isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized() &&
Duncan Sands44b87212007-11-01 20:53:16 +000010645 TD->getABITypeSize(AI.getAllocatedType()) == 0)
Chris Lattnerabb77c92004-03-19 06:08:10 +000010646 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
10647
Chris Lattner1085bdf2002-11-04 16:18:53 +000010648 return 0;
10649}
10650
Chris Lattner8427bff2003-12-07 01:24:23 +000010651Instruction *InstCombiner::visitFreeInst(FreeInst &FI) {
10652 Value *Op = FI.getOperand(0);
10653
Chris Lattner8ba9ec92004-10-18 02:59:09 +000010654 // free undef -> unreachable.
10655 if (isa<UndefValue>(Op)) {
10656 // Insert a new store to null because we cannot modify the CFG here.
Zhou Sheng75b871f2007-01-11 12:24:14 +000010657 new StoreInst(ConstantInt::getTrue(),
Christopher Lambedf07882007-12-17 01:12:55 +000010658 UndefValue::get(PointerType::getUnqual(Type::Int1Ty)), &FI);
Chris Lattner8ba9ec92004-10-18 02:59:09 +000010659 return EraseInstFromFunction(FI);
10660 }
Chris Lattnerefb33d22007-04-14 00:20:02 +000010661
Chris Lattnerf3a36602004-02-28 04:57:37 +000010662 // If we have 'free null' delete the instruction. This can happen in stl code
10663 // when lots of inlining happens.
Chris Lattner8ba9ec92004-10-18 02:59:09 +000010664 if (isa<ConstantPointerNull>(Op))
Chris Lattner51ea1272004-02-28 05:22:00 +000010665 return EraseInstFromFunction(FI);
Chris Lattnerefb33d22007-04-14 00:20:02 +000010666
10667 // Change free <ty>* (cast <ty2>* X to <ty>*) into free <ty2>* X
10668 if (BitCastInst *CI = dyn_cast<BitCastInst>(Op)) {
10669 FI.setOperand(0, CI->getOperand(0));
10670 return &FI;
10671 }
10672
10673 // Change free (gep X, 0,0,0,0) into free(X)
10674 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
10675 if (GEPI->hasAllZeroIndices()) {
10676 AddToWorkList(GEPI);
10677 FI.setOperand(0, GEPI->getOperand(0));
10678 return &FI;
10679 }
10680 }
10681
10682 // Change free(malloc) into nothing, if the malloc has a single use.
10683 if (MallocInst *MI = dyn_cast<MallocInst>(Op))
10684 if (MI->hasOneUse()) {
10685 EraseInstFromFunction(FI);
10686 return EraseInstFromFunction(*MI);
10687 }
Chris Lattnerf3a36602004-02-28 04:57:37 +000010688
Chris Lattner8427bff2003-12-07 01:24:23 +000010689 return 0;
10690}
10691
10692
Chris Lattner72684fe2005-01-31 05:51:45 +000010693/// InstCombineLoadCast - Fold 'load (cast P)' -> cast (load P)' when possible.
Devang Pateldf49cf52007-10-18 19:52:32 +000010694static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI,
Bill Wendlingd188e032008-02-26 10:53:30 +000010695 const TargetData *TD) {
Chris Lattner35e24772004-07-13 01:49:43 +000010696 User *CI = cast<User>(LI.getOperand(0));
Chris Lattnerfe1b0b82005-01-31 04:50:46 +000010697 Value *CastOp = CI->getOperand(0);
Chris Lattner35e24772004-07-13 01:49:43 +000010698
Devang Pateldf49cf52007-10-18 19:52:32 +000010699 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(CI)) {
10700 // Instead of loading constant c string, use corresponding integer value
10701 // directly if string length is small enough.
Evan Chengda3db112008-06-30 07:31:25 +000010702 std::string Str;
10703 if (GetConstantStringInfo(CE->getOperand(0), Str) && !Str.empty()) {
Devang Pateldf49cf52007-10-18 19:52:32 +000010704 unsigned len = Str.length();
10705 const Type *Ty = cast<PointerType>(CE->getType())->getElementType();
10706 unsigned numBits = Ty->getPrimitiveSizeInBits();
10707 // Replace LI with immediate integer store.
10708 if ((numBits >> 3) == len + 1) {
Bill Wendlingd188e032008-02-26 10:53:30 +000010709 APInt StrVal(numBits, 0);
10710 APInt SingleChar(numBits, 0);
10711 if (TD->isLittleEndian()) {
10712 for (signed i = len-1; i >= 0; i--) {
10713 SingleChar = (uint64_t) Str[i];
10714 StrVal = (StrVal << 8) | SingleChar;
10715 }
10716 } else {
10717 for (unsigned i = 0; i < len; i++) {
10718 SingleChar = (uint64_t) Str[i];
10719 StrVal = (StrVal << 8) | SingleChar;
10720 }
10721 // Append NULL at the end.
10722 SingleChar = 0;
10723 StrVal = (StrVal << 8) | SingleChar;
10724 }
10725 Value *NL = ConstantInt::get(StrVal);
10726 return IC.ReplaceInstUsesWith(LI, NL);
Devang Pateldf49cf52007-10-18 19:52:32 +000010727 }
10728 }
10729 }
10730
Chris Lattner35e24772004-07-13 01:49:43 +000010731 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
Chris Lattnerfe1b0b82005-01-31 04:50:46 +000010732 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
Chris Lattner35e24772004-07-13 01:49:43 +000010733 const Type *SrcPTy = SrcTy->getElementType();
Chris Lattnerfe1b0b82005-01-31 04:50:46 +000010734
Reid Spencer31a4ef42007-01-22 05:51:25 +000010735 if (DestPTy->isInteger() || isa<PointerType>(DestPTy) ||
Reid Spencerd84d35b2007-02-15 02:26:10 +000010736 isa<VectorType>(DestPTy)) {
Chris Lattnerfe1b0b82005-01-31 04:50:46 +000010737 // If the source is an array, the code below will not succeed. Check to
10738 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
10739 // constants.
10740 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
10741 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
10742 if (ASrcTy->getNumElements() != 0) {
Chris Lattnerf96f4a82007-01-31 04:40:53 +000010743 Value *Idxs[2];
10744 Idxs[0] = Idxs[1] = Constant::getNullValue(Type::Int32Ty);
10745 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs, 2);
Chris Lattnerfe1b0b82005-01-31 04:50:46 +000010746 SrcTy = cast<PointerType>(CastOp->getType());
10747 SrcPTy = SrcTy->getElementType();
10748 }
10749
Reid Spencer31a4ef42007-01-22 05:51:25 +000010750 if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy) ||
Reid Spencerd84d35b2007-02-15 02:26:10 +000010751 isa<VectorType>(SrcPTy)) &&
Chris Lattnerecfa9b52005-03-29 06:37:47 +000010752 // Do not allow turning this into a load of an integer, which is then
10753 // casted to a pointer, this pessimizes pointer analysis a lot.
10754 (isa<PointerType>(SrcPTy) == isa<PointerType>(LI.getType())) &&
Reid Spencer31a4ef42007-01-22 05:51:25 +000010755 IC.getTargetData().getTypeSizeInBits(SrcPTy) ==
10756 IC.getTargetData().getTypeSizeInBits(DestPTy)) {
Misha Brukmanb1c93172005-04-21 23:48:37 +000010757
Chris Lattnerfe1b0b82005-01-31 04:50:46 +000010758 // Okay, we are casting from one integer or pointer type to another of
10759 // the same size. Instead of casting the pointer before the load, cast
10760 // the result of the loaded value.
10761 Value *NewLoad = IC.InsertNewInstBefore(new LoadInst(CastOp,
10762 CI->getName(),
10763 LI.isVolatile()),LI);
10764 // Now cast the result of the load.
Reid Spencerbb65ebf2006-12-12 23:36:14 +000010765 return new BitCastInst(NewLoad, LI.getType());
Chris Lattnerfe1b0b82005-01-31 04:50:46 +000010766 }
Chris Lattner35e24772004-07-13 01:49:43 +000010767 }
10768 }
10769 return 0;
10770}
10771
Chris Lattnerf62ea8e2004-09-19 18:43:46 +000010772/// isSafeToLoadUnconditionally - Return true if we know that executing a load
Chris Lattnere6f13092004-09-19 19:18:10 +000010773/// from this value cannot trap. If it is not obviously safe to load from the
10774/// specified pointer, we do a quick local scan of the basic block containing
10775/// ScanFrom, to determine if the address is already accessed.
10776static bool isSafeToLoadUnconditionally(Value *V, Instruction *ScanFrom) {
Duncan Sands56df7de2007-09-19 10:10:31 +000010777 // If it is an alloca it is always safe to load from.
10778 if (isa<AllocaInst>(V)) return true;
10779
Duncan Sandsd31649b2007-09-19 10:25:38 +000010780 // If it is a global variable it is mostly safe to load from.
Duncan Sands56df7de2007-09-19 10:10:31 +000010781 if (const GlobalValue *GV = dyn_cast<GlobalVariable>(V))
Duncan Sandsd31649b2007-09-19 10:25:38 +000010782 // Don't try to evaluate aliases. External weak GV can be null.
Duncan Sands56df7de2007-09-19 10:10:31 +000010783 return !isa<GlobalAlias>(GV) && !GV->hasExternalWeakLinkage();
Chris Lattnere6f13092004-09-19 19:18:10 +000010784
10785 // Otherwise, be a little bit agressive by scanning the local block where we
10786 // want to check to see if the pointer is already being loaded or stored
Alkis Evlogimenosd59cebf2004-09-20 06:42:58 +000010787 // from/to. If so, the previous load or store would have already trapped,
10788 // so there is no harm doing an extra load (also, CSE will later eliminate
10789 // the load entirely).
Chris Lattnere6f13092004-09-19 19:18:10 +000010790 BasicBlock::iterator BBI = ScanFrom, E = ScanFrom->getParent()->begin();
10791
Alkis Evlogimenosd59cebf2004-09-20 06:42:58 +000010792 while (BBI != E) {
Chris Lattnere6f13092004-09-19 19:18:10 +000010793 --BBI;
10794
Chris Lattnerf3ecd2d2008-06-20 05:12:56 +000010795 // If we see a free or a call (which might do a free) the pointer could be
10796 // marked invalid.
10797 if (isa<FreeInst>(BBI) || isa<CallInst>(BBI))
10798 return false;
10799
Chris Lattnere6f13092004-09-19 19:18:10 +000010800 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
10801 if (LI->getOperand(0) == V) return true;
Chris Lattnerf3ecd2d2008-06-20 05:12:56 +000010802 } else if (StoreInst *SI = dyn_cast<StoreInst>(BBI)) {
Chris Lattnere6f13092004-09-19 19:18:10 +000010803 if (SI->getOperand(1) == V) return true;
Chris Lattnerf3ecd2d2008-06-20 05:12:56 +000010804 }
Misha Brukmanb1c93172005-04-21 23:48:37 +000010805
Alkis Evlogimenosd59cebf2004-09-20 06:42:58 +000010806 }
Chris Lattnere6f13092004-09-19 19:18:10 +000010807 return false;
Chris Lattnerf62ea8e2004-09-19 18:43:46 +000010808}
10809
Chris Lattner0f1d8a32003-06-26 05:06:25 +000010810Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
10811 Value *Op = LI.getOperand(0);
Chris Lattner7e8af382004-01-12 04:13:56 +000010812
Dan Gohmane31a61e2007-07-20 16:34:21 +000010813 // Attempt to improve the alignment.
Dan Gohman99b7b3f2008-04-10 18:43:06 +000010814 unsigned KnownAlign = GetOrEnforceKnownAlignment(Op);
10815 if (KnownAlign >
10816 (LI.getAlignment() == 0 ? TD->getABITypeAlignment(LI.getType()) :
10817 LI.getAlignment()))
Dan Gohmane31a61e2007-07-20 16:34:21 +000010818 LI.setAlignment(KnownAlign);
10819
Chris Lattnera9d84e32005-05-01 04:24:53 +000010820 // load (cast X) --> cast (load X) iff safe
Reid Spencerde46e482006-11-02 20:25:50 +000010821 if (isa<CastInst>(Op))
Devang Pateldf49cf52007-10-18 19:52:32 +000010822 if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
Chris Lattnera9d84e32005-05-01 04:24:53 +000010823 return Res;
10824
10825 // None of the following transforms are legal for volatile loads.
10826 if (LI.isVolatile()) return 0;
Chris Lattnerb990f7d2005-09-12 22:00:15 +000010827
Dan Gohmanbc027842008-10-15 23:19:35 +000010828 // Do really simple store-to-load forwarding and load CSE, to catch cases
10829 // where there are several consequtive memory accesses to the same location,
10830 // separated by a few arithmetic operations.
10831 BasicBlock::iterator BBI = &LI;
Chris Lattnere0d019d2008-11-27 08:56:30 +000010832 if (Value *AvailableVal = FindAvailableLoadedValue(Op, LI.getParent(), BBI,6))
10833 return ReplaceInstUsesWith(LI, AvailableVal);
Chris Lattnera9d84e32005-05-01 04:24:53 +000010834
Christopher Lambb053b802007-12-29 07:56:53 +000010835 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
10836 const Value *GEPI0 = GEPI->getOperand(0);
10837 // TODO: Consider a target hook for valid address spaces for this xform.
10838 if (isa<ConstantPointerNull>(GEPI0) &&
10839 cast<PointerType>(GEPI0->getType())->getAddressSpace() == 0) {
Chris Lattnera9d84e32005-05-01 04:24:53 +000010840 // Insert a new store to null instruction before the load to indicate
10841 // that this code is not reachable. We do this instead of inserting
10842 // an unreachable instruction directly because we cannot modify the
10843 // CFG.
10844 new StoreInst(UndefValue::get(LI.getType()),
10845 Constant::getNullValue(Op->getType()), &LI);
10846 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
10847 }
Christopher Lambb053b802007-12-29 07:56:53 +000010848 }
Chris Lattnera9d84e32005-05-01 04:24:53 +000010849
Chris Lattner81a7a232004-10-16 18:11:37 +000010850 if (Constant *C = dyn_cast<Constant>(Op)) {
Chris Lattnera9d84e32005-05-01 04:24:53 +000010851 // load null/undef -> undef
Christopher Lambb053b802007-12-29 07:56:53 +000010852 // TODO: Consider a target hook for valid address spaces for this xform.
10853 if (isa<UndefValue>(C) || (C->isNullValue() &&
10854 cast<PointerType>(Op->getType())->getAddressSpace() == 0)) {
Chris Lattner8ba9ec92004-10-18 02:59:09 +000010855 // Insert a new store to null instruction before the load to indicate that
10856 // this code is not reachable. We do this instead of inserting an
10857 // unreachable instruction directly because we cannot modify the CFG.
Chris Lattnera9d84e32005-05-01 04:24:53 +000010858 new StoreInst(UndefValue::get(LI.getType()),
10859 Constant::getNullValue(Op->getType()), &LI);
Chris Lattner81a7a232004-10-16 18:11:37 +000010860 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
Chris Lattner8ba9ec92004-10-18 02:59:09 +000010861 }
Chris Lattner0f1d8a32003-06-26 05:06:25 +000010862
Chris Lattner81a7a232004-10-16 18:11:37 +000010863 // Instcombine load (constant global) into the value loaded.
10864 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op))
Reid Spencer5301e7c2007-01-30 20:08:39 +000010865 if (GV->isConstant() && !GV->isDeclaration())
Chris Lattner81a7a232004-10-16 18:11:37 +000010866 return ReplaceInstUsesWith(LI, GV->getInitializer());
Misha Brukmanb1c93172005-04-21 23:48:37 +000010867
Chris Lattner81a7a232004-10-16 18:11:37 +000010868 // Instcombine load (constantexpr_GEP global, 0, ...) into the value loaded.
Anton Korobeynikov1bfd1212008-02-20 11:26:25 +000010869 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op)) {
Chris Lattner81a7a232004-10-16 18:11:37 +000010870 if (CE->getOpcode() == Instruction::GetElementPtr) {
10871 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
Reid Spencer5301e7c2007-01-30 20:08:39 +000010872 if (GV->isConstant() && !GV->isDeclaration())
Chris Lattner0b011ec2005-09-26 05:28:06 +000010873 if (Constant *V =
10874 ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE))
Chris Lattner81a7a232004-10-16 18:11:37 +000010875 return ReplaceInstUsesWith(LI, V);
Chris Lattnera9d84e32005-05-01 04:24:53 +000010876 if (CE->getOperand(0)->isNullValue()) {
10877 // Insert a new store to null instruction before the load to indicate
10878 // that this code is not reachable. We do this instead of inserting
10879 // an unreachable instruction directly because we cannot modify the
10880 // CFG.
10881 new StoreInst(UndefValue::get(LI.getType()),
10882 Constant::getNullValue(Op->getType()), &LI);
10883 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
10884 }
10885
Reid Spencer6c38f0b2006-11-27 01:05:10 +000010886 } else if (CE->isCast()) {
Devang Pateldf49cf52007-10-18 19:52:32 +000010887 if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
Chris Lattner81a7a232004-10-16 18:11:37 +000010888 return Res;
10889 }
Anton Korobeynikov1bfd1212008-02-20 11:26:25 +000010890 }
Chris Lattner81a7a232004-10-16 18:11:37 +000010891 }
Chris Lattner99c8ee22007-08-11 18:48:48 +000010892
10893 // If this load comes from anywhere in a constant global, and if the global
10894 // is all undef or zero, we know what it loads.
Duncan Sandsd65a4da2008-10-01 15:25:41 +000010895 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op->getUnderlyingObject())){
Chris Lattner99c8ee22007-08-11 18:48:48 +000010896 if (GV->isConstant() && GV->hasInitializer()) {
10897 if (GV->getInitializer()->isNullValue())
10898 return ReplaceInstUsesWith(LI, Constant::getNullValue(LI.getType()));
10899 else if (isa<UndefValue>(GV->getInitializer()))
10900 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
10901 }
10902 }
Chris Lattnere228ee52004-04-08 20:39:49 +000010903
Chris Lattnera9d84e32005-05-01 04:24:53 +000010904 if (Op->hasOneUse()) {
Chris Lattnerf62ea8e2004-09-19 18:43:46 +000010905 // Change select and PHI nodes to select values instead of addresses: this
10906 // helps alias analysis out a lot, allows many others simplifications, and
10907 // exposes redundancy in the code.
10908 //
10909 // Note that we cannot do the transformation unless we know that the
10910 // introduced loads cannot trap! Something like this is valid as long as
10911 // the condition is always false: load (select bool %C, int* null, int* %G),
10912 // but it would not be valid if we transformed it to load from null
10913 // unconditionally.
10914 //
10915 if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
10916 // load (select (Cond, &V1, &V2)) --> select(Cond, load &V1, load &V2).
Chris Lattnere6f13092004-09-19 19:18:10 +000010917 if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
10918 isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
Chris Lattnerf62ea8e2004-09-19 18:43:46 +000010919 Value *V1 = InsertNewInstBefore(new LoadInst(SI->getOperand(1),
Chris Lattner42618552004-09-20 10:15:10 +000010920 SI->getOperand(1)->getName()+".val"), LI);
Chris Lattnerf62ea8e2004-09-19 18:43:46 +000010921 Value *V2 = InsertNewInstBefore(new LoadInst(SI->getOperand(2),
Chris Lattner42618552004-09-20 10:15:10 +000010922 SI->getOperand(2)->getName()+".val"), LI);
Gabor Greife9ecc682008-04-06 20:25:17 +000010923 return SelectInst::Create(SI->getCondition(), V1, V2);
Chris Lattnerf62ea8e2004-09-19 18:43:46 +000010924 }
10925
Chris Lattnerbdcf41a2004-09-23 15:46:00 +000010926 // load (select (cond, null, P)) -> load P
10927 if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
10928 if (C->isNullValue()) {
10929 LI.setOperand(0, SI->getOperand(2));
10930 return &LI;
10931 }
10932
10933 // load (select (cond, P, null)) -> load P
10934 if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
10935 if (C->isNullValue()) {
10936 LI.setOperand(0, SI->getOperand(1));
10937 return &LI;
10938 }
Chris Lattnerf62ea8e2004-09-19 18:43:46 +000010939 }
10940 }
Chris Lattner0f1d8a32003-06-26 05:06:25 +000010941 return 0;
10942}
10943
Reid Spencere928a152007-01-19 21:20:31 +000010944/// InstCombineStoreToCast - Fold store V, (cast P) -> store (cast V), P
Chris Lattner72684fe2005-01-31 05:51:45 +000010945/// when possible.
10946static Instruction *InstCombineStoreToCast(InstCombiner &IC, StoreInst &SI) {
10947 User *CI = cast<User>(SI.getOperand(1));
10948 Value *CastOp = CI->getOperand(0);
10949
10950 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
10951 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
10952 const Type *SrcPTy = SrcTy->getElementType();
10953
Reid Spencer31a4ef42007-01-22 05:51:25 +000010954 if (DestPTy->isInteger() || isa<PointerType>(DestPTy)) {
Chris Lattner72684fe2005-01-31 05:51:45 +000010955 // If the source is an array, the code below will not succeed. Check to
10956 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
10957 // constants.
10958 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
10959 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
10960 if (ASrcTy->getNumElements() != 0) {
Chris Lattnerf96f4a82007-01-31 04:40:53 +000010961 Value* Idxs[2];
10962 Idxs[0] = Idxs[1] = Constant::getNullValue(Type::Int32Ty);
10963 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs, 2);
Chris Lattner72684fe2005-01-31 05:51:45 +000010964 SrcTy = cast<PointerType>(CastOp->getType());
10965 SrcPTy = SrcTy->getElementType();
10966 }
10967
Reid Spencer9a4bed02007-01-20 23:35:48 +000010968 if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy)) &&
10969 IC.getTargetData().getTypeSizeInBits(SrcPTy) ==
10970 IC.getTargetData().getTypeSizeInBits(DestPTy)) {
Chris Lattner72684fe2005-01-31 05:51:45 +000010971
10972 // Okay, we are casting from one integer or pointer type to another of
Reid Spencerc050af92007-01-18 18:54:33 +000010973 // the same size. Instead of casting the pointer before
10974 // the store, cast the value to be stored.
Chris Lattner72684fe2005-01-31 05:51:45 +000010975 Value *NewCast;
Reid Spencerbb65ebf2006-12-12 23:36:14 +000010976 Value *SIOp0 = SI.getOperand(0);
Reid Spencerc050af92007-01-18 18:54:33 +000010977 Instruction::CastOps opcode = Instruction::BitCast;
10978 const Type* CastSrcTy = SIOp0->getType();
10979 const Type* CastDstTy = SrcPTy;
10980 if (isa<PointerType>(CastDstTy)) {
10981 if (CastSrcTy->isInteger())
Reid Spencerbb65ebf2006-12-12 23:36:14 +000010982 opcode = Instruction::IntToPtr;
Reid Spencer9a4bed02007-01-20 23:35:48 +000010983 } else if (isa<IntegerType>(CastDstTy)) {
Reid Spencer74a528b2006-12-13 18:21:21 +000010984 if (isa<PointerType>(SIOp0->getType()))
Reid Spencerbb65ebf2006-12-12 23:36:14 +000010985 opcode = Instruction::PtrToInt;
10986 }
10987 if (Constant *C = dyn_cast<Constant>(SIOp0))
Reid Spencerc050af92007-01-18 18:54:33 +000010988 NewCast = ConstantExpr::getCast(opcode, C, CastDstTy);
Chris Lattner72684fe2005-01-31 05:51:45 +000010989 else
Reid Spencer6c38f0b2006-11-27 01:05:10 +000010990 NewCast = IC.InsertNewInstBefore(
Gabor Greife1f6e4b2008-05-16 19:29:10 +000010991 CastInst::Create(opcode, SIOp0, CastDstTy, SIOp0->getName()+".c"),
Reid Spencerc050af92007-01-18 18:54:33 +000010992 SI);
Chris Lattner72684fe2005-01-31 05:51:45 +000010993 return new StoreInst(NewCast, CastOp);
10994 }
10995 }
10996 }
10997 return 0;
10998}
10999
Chris Lattnere0d019d2008-11-27 08:56:30 +000011000/// equivalentAddressValues - Test if A and B will obviously have the same
11001/// value. This includes recognizing that %t0 and %t1 will have the same
11002/// value in code like this:
11003/// %t0 = getelementptr @a, 0, 3
11004/// store i32 0, i32* %t0
11005/// %t1 = getelementptr @a, 0, 3
11006/// %t2 = load i32* %t1
11007///
11008static bool equivalentAddressValues(Value *A, Value *B) {
11009 // Test if the values are trivially equivalent.
11010 if (A == B) return true;
11011
11012 // Test if the values come form identical arithmetic instructions.
11013 if (isa<BinaryOperator>(A) ||
11014 isa<CastInst>(A) ||
11015 isa<PHINode>(A) ||
11016 isa<GetElementPtrInst>(A))
11017 if (Instruction *BI = dyn_cast<Instruction>(B))
11018 if (cast<Instruction>(A)->isIdenticalTo(BI))
11019 return true;
11020
11021 // Otherwise they may not be equivalent.
11022 return false;
11023}
11024
Chris Lattner31f486c2005-01-31 05:36:43 +000011025Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
11026 Value *Val = SI.getOperand(0);
11027 Value *Ptr = SI.getOperand(1);
11028
11029 if (isa<UndefValue>(Ptr)) { // store X, undef -> noop (even if volatile)
Chris Lattner5997cf92006-02-08 03:25:32 +000011030 EraseInstFromFunction(SI);
Chris Lattner31f486c2005-01-31 05:36:43 +000011031 ++NumCombined;
11032 return 0;
11033 }
Chris Lattnera4beeef2007-01-15 06:51:56 +000011034
11035 // If the RHS is an alloca with a single use, zapify the store, making the
11036 // alloca dead.
Chris Lattnere331a652008-04-29 04:58:38 +000011037 if (Ptr->hasOneUse() && !SI.isVolatile()) {
Chris Lattnera4beeef2007-01-15 06:51:56 +000011038 if (isa<AllocaInst>(Ptr)) {
11039 EraseInstFromFunction(SI);
11040 ++NumCombined;
11041 return 0;
11042 }
11043
11044 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr))
11045 if (isa<AllocaInst>(GEP->getOperand(0)) &&
11046 GEP->getOperand(0)->hasOneUse()) {
11047 EraseInstFromFunction(SI);
11048 ++NumCombined;
11049 return 0;
11050 }
11051 }
Chris Lattner31f486c2005-01-31 05:36:43 +000011052
Dan Gohmane31a61e2007-07-20 16:34:21 +000011053 // Attempt to improve the alignment.
Dan Gohman99b7b3f2008-04-10 18:43:06 +000011054 unsigned KnownAlign = GetOrEnforceKnownAlignment(Ptr);
11055 if (KnownAlign >
11056 (SI.getAlignment() == 0 ? TD->getABITypeAlignment(Val->getType()) :
11057 SI.getAlignment()))
Dan Gohmane31a61e2007-07-20 16:34:21 +000011058 SI.setAlignment(KnownAlign);
11059
Chris Lattner5997cf92006-02-08 03:25:32 +000011060 // Do really simple DSE, to catch cases where there are several consequtive
11061 // stores to the same location, separated by a few arithmetic operations. This
11062 // situation often occurs with bitfield accesses.
11063 BasicBlock::iterator BBI = &SI;
11064 for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts;
11065 --ScanInsts) {
11066 --BBI;
11067
11068 if (StoreInst *PrevSI = dyn_cast<StoreInst>(BBI)) {
11069 // Prev store isn't volatile, and stores to the same location?
Chris Lattnere0d019d2008-11-27 08:56:30 +000011070 if (!PrevSI->isVolatile() &&equivalentAddressValues(PrevSI->getOperand(1),
11071 SI.getOperand(1))) {
Chris Lattner5997cf92006-02-08 03:25:32 +000011072 ++NumDeadStore;
11073 ++BBI;
11074 EraseInstFromFunction(*PrevSI);
11075 continue;
11076 }
11077 break;
11078 }
11079
Chris Lattnerdab43b22006-05-26 19:19:20 +000011080 // If this is a load, we have to stop. However, if the loaded value is from
11081 // the pointer we're loading and is producing the pointer we're storing,
11082 // then *this* store is dead (X = load P; store X -> P).
11083 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
Dan Gohmanbc027842008-10-15 23:19:35 +000011084 if (LI == Val && equivalentAddressValues(LI->getOperand(0), Ptr) &&
11085 !SI.isVolatile()) {
Chris Lattnerdab43b22006-05-26 19:19:20 +000011086 EraseInstFromFunction(SI);
11087 ++NumCombined;
11088 return 0;
11089 }
11090 // Otherwise, this is a load from some other location. Stores before it
11091 // may not be dead.
11092 break;
11093 }
11094
Chris Lattner5997cf92006-02-08 03:25:32 +000011095 // Don't skip over loads or things that can modify memory.
Chris Lattner4fa09662008-05-08 17:20:30 +000011096 if (BBI->mayWriteToMemory() || BBI->mayReadFromMemory())
Chris Lattner5997cf92006-02-08 03:25:32 +000011097 break;
11098 }
11099
11100
11101 if (SI.isVolatile()) return 0; // Don't hack volatile stores.
Chris Lattner31f486c2005-01-31 05:36:43 +000011102
11103 // store X, null -> turns into 'unreachable' in SimplifyCFG
11104 if (isa<ConstantPointerNull>(Ptr)) {
11105 if (!isa<UndefValue>(Val)) {
11106 SI.setOperand(0, UndefValue::get(Val->getType()));
11107 if (Instruction *U = dyn_cast<Instruction>(Val))
Chris Lattnerb15e2b12007-03-02 21:28:56 +000011108 AddToWorkList(U); // Dropped a use.
Chris Lattner31f486c2005-01-31 05:36:43 +000011109 ++NumCombined;
11110 }
11111 return 0; // Do not modify these!
11112 }
11113
11114 // store undef, Ptr -> noop
11115 if (isa<UndefValue>(Val)) {
Chris Lattner5997cf92006-02-08 03:25:32 +000011116 EraseInstFromFunction(SI);
Chris Lattner31f486c2005-01-31 05:36:43 +000011117 ++NumCombined;
11118 return 0;
11119 }
11120
Chris Lattner72684fe2005-01-31 05:51:45 +000011121 // If the pointer destination is a cast, see if we can fold the cast into the
11122 // source instead.
Reid Spencerde46e482006-11-02 20:25:50 +000011123 if (isa<CastInst>(Ptr))
Chris Lattner72684fe2005-01-31 05:51:45 +000011124 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
11125 return Res;
11126 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
Reid Spencer6c38f0b2006-11-27 01:05:10 +000011127 if (CE->isCast())
Chris Lattner72684fe2005-01-31 05:51:45 +000011128 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
11129 return Res;
11130
Chris Lattner219175c2005-09-12 23:23:25 +000011131
11132 // If this store is the last instruction in the basic block, and if the block
11133 // ends with an unconditional branch, try to move it to the successor block.
Chris Lattner5997cf92006-02-08 03:25:32 +000011134 BBI = &SI; ++BBI;
Chris Lattner219175c2005-09-12 23:23:25 +000011135 if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
Chris Lattner14a251b2007-04-15 00:07:55 +000011136 if (BI->isUnconditional())
11137 if (SimplifyStoreAtEndOfBlock(SI))
11138 return 0; // xform done!
Chris Lattner219175c2005-09-12 23:23:25 +000011139
Chris Lattner31f486c2005-01-31 05:36:43 +000011140 return 0;
11141}
11142
Chris Lattner14a251b2007-04-15 00:07:55 +000011143/// SimplifyStoreAtEndOfBlock - Turn things like:
11144/// if () { *P = v1; } else { *P = v2 }
11145/// into a phi node with a store in the successor.
11146///
Chris Lattner4a6e0cb2007-04-15 01:02:18 +000011147/// Simplify things like:
11148/// *P = v1; if () { *P = v2; }
11149/// into a phi node with a store in the successor.
11150///
Chris Lattner14a251b2007-04-15 00:07:55 +000011151bool InstCombiner::SimplifyStoreAtEndOfBlock(StoreInst &SI) {
11152 BasicBlock *StoreBB = SI.getParent();
11153
11154 // Check to see if the successor block has exactly two incoming edges. If
11155 // so, see if the other predecessor contains a store to the same location.
11156 // if so, insert a PHI node (if needed) and move the stores down.
Chris Lattner4a6e0cb2007-04-15 01:02:18 +000011157 BasicBlock *DestBB = StoreBB->getTerminator()->getSuccessor(0);
Chris Lattner14a251b2007-04-15 00:07:55 +000011158
11159 // Determine whether Dest has exactly two predecessors and, if so, compute
11160 // the other predecessor.
Chris Lattner4a6e0cb2007-04-15 01:02:18 +000011161 pred_iterator PI = pred_begin(DestBB);
11162 BasicBlock *OtherBB = 0;
Chris Lattner14a251b2007-04-15 00:07:55 +000011163 if (*PI != StoreBB)
Chris Lattner4a6e0cb2007-04-15 01:02:18 +000011164 OtherBB = *PI;
Chris Lattner14a251b2007-04-15 00:07:55 +000011165 ++PI;
Chris Lattner4a6e0cb2007-04-15 01:02:18 +000011166 if (PI == pred_end(DestBB))
Chris Lattner14a251b2007-04-15 00:07:55 +000011167 return false;
11168
11169 if (*PI != StoreBB) {
Chris Lattner4a6e0cb2007-04-15 01:02:18 +000011170 if (OtherBB)
Chris Lattner14a251b2007-04-15 00:07:55 +000011171 return false;
Chris Lattner4a6e0cb2007-04-15 01:02:18 +000011172 OtherBB = *PI;
Chris Lattner14a251b2007-04-15 00:07:55 +000011173 }
Chris Lattner4a6e0cb2007-04-15 01:02:18 +000011174 if (++PI != pred_end(DestBB))
Chris Lattner14a251b2007-04-15 00:07:55 +000011175 return false;
Eli Friedman9833a1b2008-06-13 21:17:49 +000011176
11177 // Bail out if all the relevant blocks aren't distinct (this can happen,
11178 // for example, if SI is in an infinite loop)
11179 if (StoreBB == DestBB || OtherBB == DestBB)
11180 return false;
11181
Chris Lattner4a6e0cb2007-04-15 01:02:18 +000011182 // Verify that the other block ends in a branch and is not otherwise empty.
11183 BasicBlock::iterator BBI = OtherBB->getTerminator();
Chris Lattner14a251b2007-04-15 00:07:55 +000011184 BranchInst *OtherBr = dyn_cast<BranchInst>(BBI);
Chris Lattner4a6e0cb2007-04-15 01:02:18 +000011185 if (!OtherBr || BBI == OtherBB->begin())
Chris Lattner14a251b2007-04-15 00:07:55 +000011186 return false;
11187
Chris Lattner4a6e0cb2007-04-15 01:02:18 +000011188 // If the other block ends in an unconditional branch, check for the 'if then
11189 // else' case. there is an instruction before the branch.
11190 StoreInst *OtherStore = 0;
11191 if (OtherBr->isUnconditional()) {
11192 // If this isn't a store, or isn't a store to the same location, bail out.
11193 --BBI;
11194 OtherStore = dyn_cast<StoreInst>(BBI);
11195 if (!OtherStore || OtherStore->getOperand(1) != SI.getOperand(1))
11196 return false;
11197 } else {
Chris Lattner361e9812007-05-05 22:32:24 +000011198 // Otherwise, the other block ended with a conditional branch. If one of the
Chris Lattner4a6e0cb2007-04-15 01:02:18 +000011199 // destinations is StoreBB, then we have the if/then case.
11200 if (OtherBr->getSuccessor(0) != StoreBB &&
11201 OtherBr->getSuccessor(1) != StoreBB)
11202 return false;
11203
11204 // Okay, we know that OtherBr now goes to Dest and StoreBB, so this is an
Chris Lattner361e9812007-05-05 22:32:24 +000011205 // if/then triangle. See if there is a store to the same ptr as SI that
11206 // lives in OtherBB.
Chris Lattner4a6e0cb2007-04-15 01:02:18 +000011207 for (;; --BBI) {
11208 // Check to see if we find the matching store.
11209 if ((OtherStore = dyn_cast<StoreInst>(BBI))) {
11210 if (OtherStore->getOperand(1) != SI.getOperand(1))
11211 return false;
11212 break;
11213 }
Eli Friedman5de0a772008-06-13 22:02:12 +000011214 // If we find something that may be using or overwriting the stored
11215 // value, or if we run out of instructions, we can't do the xform.
11216 if (BBI->mayReadFromMemory() || BBI->mayWriteToMemory() ||
Chris Lattner4a6e0cb2007-04-15 01:02:18 +000011217 BBI == OtherBB->begin())
11218 return false;
11219 }
11220
11221 // In order to eliminate the store in OtherBr, we have to
Eli Friedman5de0a772008-06-13 22:02:12 +000011222 // make sure nothing reads or overwrites the stored value in
11223 // StoreBB.
Chris Lattner4a6e0cb2007-04-15 01:02:18 +000011224 for (BasicBlock::iterator I = StoreBB->begin(); &*I != &SI; ++I) {
11225 // FIXME: This should really be AA driven.
Eli Friedman5de0a772008-06-13 22:02:12 +000011226 if (I->mayReadFromMemory() || I->mayWriteToMemory())
Chris Lattner4a6e0cb2007-04-15 01:02:18 +000011227 return false;
11228 }
11229 }
Chris Lattner14a251b2007-04-15 00:07:55 +000011230
Chris Lattner4a6e0cb2007-04-15 01:02:18 +000011231 // Insert a PHI node now if we need it.
Chris Lattner14a251b2007-04-15 00:07:55 +000011232 Value *MergedVal = OtherStore->getOperand(0);
11233 if (MergedVal != SI.getOperand(0)) {
Gabor Greife9ecc682008-04-06 20:25:17 +000011234 PHINode *PN = PHINode::Create(MergedVal->getType(), "storemerge");
Chris Lattner14a251b2007-04-15 00:07:55 +000011235 PN->reserveOperandSpace(2);
11236 PN->addIncoming(SI.getOperand(0), SI.getParent());
Chris Lattner4a6e0cb2007-04-15 01:02:18 +000011237 PN->addIncoming(OtherStore->getOperand(0), OtherBB);
11238 MergedVal = InsertNewInstBefore(PN, DestBB->front());
Chris Lattner14a251b2007-04-15 00:07:55 +000011239 }
11240
11241 // Advance to a place where it is safe to insert the new store and
11242 // insert it.
Dan Gohmanf96e1372008-05-23 21:05:58 +000011243 BBI = DestBB->getFirstNonPHI();
Chris Lattner14a251b2007-04-15 00:07:55 +000011244 InsertNewInstBefore(new StoreInst(MergedVal, SI.getOperand(1),
11245 OtherStore->isVolatile()), *BBI);
11246
11247 // Nuke the old stores.
11248 EraseInstFromFunction(SI);
11249 EraseInstFromFunction(*OtherStore);
11250 ++NumCombined;
11251 return true;
11252}
11253
Chris Lattner31f486c2005-01-31 05:36:43 +000011254
Chris Lattner9eef8a72003-06-04 04:46:00 +000011255Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
11256 // Change br (not X), label True, label False to: br X, label False, True
Reid Spencer4fdd96c2005-06-18 17:37:34 +000011257 Value *X = 0;
Chris Lattnerd4252a72004-07-30 07:50:03 +000011258 BasicBlock *TrueDest;
11259 BasicBlock *FalseDest;
11260 if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
11261 !isa<Constant>(X)) {
11262 // Swap Destinations and condition...
11263 BI.setCondition(X);
11264 BI.setSuccessor(0, FalseDest);
11265 BI.setSuccessor(1, TrueDest);
11266 return &BI;
11267 }
11268
Reid Spencer266e42b2006-12-23 06:05:41 +000011269 // Cannonicalize fcmp_one -> fcmp_oeq
11270 FCmpInst::Predicate FPred; Value *Y;
11271 if (match(&BI, m_Br(m_FCmp(FPred, m_Value(X), m_Value(Y)),
11272 TrueDest, FalseDest)))
11273 if ((FPred == FCmpInst::FCMP_ONE || FPred == FCmpInst::FCMP_OLE ||
11274 FPred == FCmpInst::FCMP_OGE) && BI.getCondition()->hasOneUse()) {
11275 FCmpInst *I = cast<FCmpInst>(BI.getCondition());
Reid Spencer266e42b2006-12-23 06:05:41 +000011276 FCmpInst::Predicate NewPred = FCmpInst::getInversePredicate(FPred);
Chris Lattner6e0123b2007-02-11 01:23:03 +000011277 Instruction *NewSCC = new FCmpInst(NewPred, X, Y, "", I);
11278 NewSCC->takeName(I);
Reid Spencer266e42b2006-12-23 06:05:41 +000011279 // Swap Destinations and condition...
11280 BI.setCondition(NewSCC);
11281 BI.setSuccessor(0, FalseDest);
11282 BI.setSuccessor(1, TrueDest);
Chris Lattnerb15e2b12007-03-02 21:28:56 +000011283 RemoveFromWorkList(I);
Chris Lattner6e0123b2007-02-11 01:23:03 +000011284 I->eraseFromParent();
Chris Lattnerb15e2b12007-03-02 21:28:56 +000011285 AddToWorkList(NewSCC);
Reid Spencer266e42b2006-12-23 06:05:41 +000011286 return &BI;
11287 }
11288
11289 // Cannonicalize icmp_ne -> icmp_eq
11290 ICmpInst::Predicate IPred;
11291 if (match(&BI, m_Br(m_ICmp(IPred, m_Value(X), m_Value(Y)),
11292 TrueDest, FalseDest)))
11293 if ((IPred == ICmpInst::ICMP_NE || IPred == ICmpInst::ICMP_ULE ||
11294 IPred == ICmpInst::ICMP_SLE || IPred == ICmpInst::ICMP_UGE ||
11295 IPred == ICmpInst::ICMP_SGE) && BI.getCondition()->hasOneUse()) {
11296 ICmpInst *I = cast<ICmpInst>(BI.getCondition());
Reid Spencer266e42b2006-12-23 06:05:41 +000011297 ICmpInst::Predicate NewPred = ICmpInst::getInversePredicate(IPred);
Chris Lattner6e0123b2007-02-11 01:23:03 +000011298 Instruction *NewSCC = new ICmpInst(NewPred, X, Y, "", I);
11299 NewSCC->takeName(I);
Chris Lattnere967b342003-06-04 05:10:11 +000011300 // Swap Destinations and condition...
Chris Lattnerd4252a72004-07-30 07:50:03 +000011301 BI.setCondition(NewSCC);
Chris Lattnere967b342003-06-04 05:10:11 +000011302 BI.setSuccessor(0, FalseDest);
11303 BI.setSuccessor(1, TrueDest);
Chris Lattnerb15e2b12007-03-02 21:28:56 +000011304 RemoveFromWorkList(I);
Chris Lattner6e0123b2007-02-11 01:23:03 +000011305 I->eraseFromParent();;
Chris Lattnerb15e2b12007-03-02 21:28:56 +000011306 AddToWorkList(NewSCC);
Chris Lattnere967b342003-06-04 05:10:11 +000011307 return &BI;
11308 }
Misha Brukmanb1c93172005-04-21 23:48:37 +000011309
Chris Lattner9eef8a72003-06-04 04:46:00 +000011310 return 0;
11311}
Chris Lattner1085bdf2002-11-04 16:18:53 +000011312
Chris Lattner4c9c20a2004-07-03 00:26:11 +000011313Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
11314 Value *Cond = SI.getCondition();
11315 if (Instruction *I = dyn_cast<Instruction>(Cond)) {
11316 if (I->getOpcode() == Instruction::Add)
11317 if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
11318 // change 'switch (X+4) case 1:' into 'switch (X) case -3'
11319 for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
Chris Lattner81a7a232004-10-16 18:11:37 +000011320 SI.setOperand(i,ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)),
Chris Lattner4c9c20a2004-07-03 00:26:11 +000011321 AddRHS));
11322 SI.setOperand(0, I->getOperand(0));
Chris Lattnerb15e2b12007-03-02 21:28:56 +000011323 AddToWorkList(I);
Chris Lattner4c9c20a2004-07-03 00:26:11 +000011324 return &SI;
11325 }
11326 }
11327 return 0;
11328}
11329
Matthijs Kooijmanb2fc72b2008-06-11 14:05:05 +000011330Instruction *InstCombiner::visitExtractValueInst(ExtractValueInst &EV) {
Matthijs Kooijmanc1d74772008-07-16 12:55:45 +000011331 Value *Agg = EV.getAggregateOperand();
Matthijs Kooijmanb2fc72b2008-06-11 14:05:05 +000011332
Matthijs Kooijmanc1d74772008-07-16 12:55:45 +000011333 if (!EV.hasIndices())
11334 return ReplaceInstUsesWith(EV, Agg);
11335
11336 if (Constant *C = dyn_cast<Constant>(Agg)) {
11337 if (isa<UndefValue>(C))
11338 return ReplaceInstUsesWith(EV, UndefValue::get(EV.getType()));
11339
11340 if (isa<ConstantAggregateZero>(C))
11341 return ReplaceInstUsesWith(EV, Constant::getNullValue(EV.getType()));
11342
11343 if (isa<ConstantArray>(C) || isa<ConstantStruct>(C)) {
11344 // Extract the element indexed by the first index out of the constant
11345 Value *V = C->getOperand(*EV.idx_begin());
11346 if (EV.getNumIndices() > 1)
11347 // Extract the remaining indices out of the constant indexed by the
11348 // first index
11349 return ExtractValueInst::Create(V, EV.idx_begin() + 1, EV.idx_end());
11350 else
11351 return ReplaceInstUsesWith(EV, V);
11352 }
11353 return 0; // Can't handle other constants
11354 }
11355 if (InsertValueInst *IV = dyn_cast<InsertValueInst>(Agg)) {
11356 // We're extracting from an insertvalue instruction, compare the indices
11357 const unsigned *exti, *exte, *insi, *inse;
11358 for (exti = EV.idx_begin(), insi = IV->idx_begin(),
11359 exte = EV.idx_end(), inse = IV->idx_end();
11360 exti != exte && insi != inse;
11361 ++exti, ++insi) {
11362 if (*insi != *exti)
11363 // The insert and extract both reference distinctly different elements.
11364 // This means the extract is not influenced by the insert, and we can
11365 // replace the aggregate operand of the extract with the aggregate
11366 // operand of the insert. i.e., replace
11367 // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
11368 // %E = extractvalue { i32, { i32 } } %I, 0
11369 // with
11370 // %E = extractvalue { i32, { i32 } } %A, 0
11371 return ExtractValueInst::Create(IV->getAggregateOperand(),
11372 EV.idx_begin(), EV.idx_end());
11373 }
11374 if (exti == exte && insi == inse)
11375 // Both iterators are at the end: Index lists are identical. Replace
11376 // %B = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
11377 // %C = extractvalue { i32, { i32 } } %B, 1, 0
11378 // with "i32 42"
11379 return ReplaceInstUsesWith(EV, IV->getInsertedValueOperand());
11380 if (exti == exte) {
11381 // The extract list is a prefix of the insert list. i.e. replace
11382 // %I = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
11383 // %E = extractvalue { i32, { i32 } } %I, 1
11384 // with
11385 // %X = extractvalue { i32, { i32 } } %A, 1
11386 // %E = insertvalue { i32 } %X, i32 42, 0
11387 // by switching the order of the insert and extract (though the
11388 // insertvalue should be left in, since it may have other uses).
11389 Value *NewEV = InsertNewInstBefore(
11390 ExtractValueInst::Create(IV->getAggregateOperand(),
11391 EV.idx_begin(), EV.idx_end()),
11392 EV);
11393 return InsertValueInst::Create(NewEV, IV->getInsertedValueOperand(),
11394 insi, inse);
11395 }
11396 if (insi == inse)
11397 // The insert list is a prefix of the extract list
11398 // We can simply remove the common indices from the extract and make it
11399 // operate on the inserted value instead of the insertvalue result.
11400 // i.e., replace
11401 // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
11402 // %E = extractvalue { i32, { i32 } } %I, 1, 0
11403 // with
11404 // %E extractvalue { i32 } { i32 42 }, 0
11405 return ExtractValueInst::Create(IV->getInsertedValueOperand(),
11406 exti, exte);
11407 }
11408 // Can't simplify extracts from other values. Note that nested extracts are
11409 // already simplified implicitely by the above (extract ( extract (insert) )
11410 // will be translated into extract ( insert ( extract ) ) first and then just
11411 // the value inserted, if appropriate).
Matthijs Kooijmanb2fc72b2008-06-11 14:05:05 +000011412 return 0;
11413}
11414
Chris Lattner6bc98652006-03-05 00:22:33 +000011415/// CheapToScalarize - Return true if the value is cheaper to scalarize than it
11416/// is to leave as a vector operation.
11417static bool CheapToScalarize(Value *V, bool isConstant) {
11418 if (isa<ConstantAggregateZero>(V))
11419 return true;
Reid Spencerd84d35b2007-02-15 02:26:10 +000011420 if (ConstantVector *C = dyn_cast<ConstantVector>(V)) {
Chris Lattner6bc98652006-03-05 00:22:33 +000011421 if (isConstant) return true;
11422 // If all elts are the same, we can extract.
11423 Constant *Op0 = C->getOperand(0);
11424 for (unsigned i = 1; i < C->getNumOperands(); ++i)
11425 if (C->getOperand(i) != Op0)
11426 return false;
11427 return true;
11428 }
11429 Instruction *I = dyn_cast<Instruction>(V);
11430 if (!I) return false;
11431
11432 // Insert element gets simplified to the inserted element or is deleted if
11433 // this is constant idx extract element and its a constant idx insertelt.
11434 if (I->getOpcode() == Instruction::InsertElement && isConstant &&
11435 isa<ConstantInt>(I->getOperand(2)))
11436 return true;
11437 if (I->getOpcode() == Instruction::Load && I->hasOneUse())
11438 return true;
11439 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I))
11440 if (BO->hasOneUse() &&
11441 (CheapToScalarize(BO->getOperand(0), isConstant) ||
11442 CheapToScalarize(BO->getOperand(1), isConstant)))
11443 return true;
Reid Spencer266e42b2006-12-23 06:05:41 +000011444 if (CmpInst *CI = dyn_cast<CmpInst>(I))
11445 if (CI->hasOneUse() &&
11446 (CheapToScalarize(CI->getOperand(0), isConstant) ||
11447 CheapToScalarize(CI->getOperand(1), isConstant)))
11448 return true;
Chris Lattner6bc98652006-03-05 00:22:33 +000011449
11450 return false;
11451}
11452
Chris Lattner945e4372007-02-14 05:52:17 +000011453/// Read and decode a shufflevector mask.
11454///
11455/// It turns undef elements into values that are larger than the number of
11456/// elements in the input.
Chris Lattner12249be2006-05-25 23:48:38 +000011457static std::vector<unsigned> getShuffleMask(const ShuffleVectorInst *SVI) {
11458 unsigned NElts = SVI->getType()->getNumElements();
11459 if (isa<ConstantAggregateZero>(SVI->getOperand(2)))
11460 return std::vector<unsigned>(NElts, 0);
11461 if (isa<UndefValue>(SVI->getOperand(2)))
11462 return std::vector<unsigned>(NElts, 2*NElts);
11463
11464 std::vector<unsigned> Result;
Reid Spencerd84d35b2007-02-15 02:26:10 +000011465 const ConstantVector *CP = cast<ConstantVector>(SVI->getOperand(2));
Gabor Greiff6d8e772008-06-12 21:37:33 +000011466 for (User::const_op_iterator i = CP->op_begin(), e = CP->op_end(); i!=e; ++i)
11467 if (isa<UndefValue>(*i))
Chris Lattner12249be2006-05-25 23:48:38 +000011468 Result.push_back(NElts*2); // undef -> 8
11469 else
Gabor Greiff6d8e772008-06-12 21:37:33 +000011470 Result.push_back(cast<ConstantInt>(*i)->getZExtValue());
Chris Lattner12249be2006-05-25 23:48:38 +000011471 return Result;
11472}
11473
Chris Lattner8d1d8d32006-03-31 23:01:56 +000011474/// FindScalarElement - Given a vector and an element number, see if the scalar
11475/// value is already around as a register, for example if it were inserted then
11476/// extracted from the vector.
11477static Value *FindScalarElement(Value *V, unsigned EltNo) {
Reid Spencerd84d35b2007-02-15 02:26:10 +000011478 assert(isa<VectorType>(V->getType()) && "Not looking at a vector?");
11479 const VectorType *PTy = cast<VectorType>(V->getType());
Chris Lattner2d37f922006-04-10 23:06:36 +000011480 unsigned Width = PTy->getNumElements();
11481 if (EltNo >= Width) // Out of range access.
Chris Lattner8d1d8d32006-03-31 23:01:56 +000011482 return UndefValue::get(PTy->getElementType());
11483
11484 if (isa<UndefValue>(V))
11485 return UndefValue::get(PTy->getElementType());
11486 else if (isa<ConstantAggregateZero>(V))
11487 return Constant::getNullValue(PTy->getElementType());
Reid Spencerd84d35b2007-02-15 02:26:10 +000011488 else if (ConstantVector *CP = dyn_cast<ConstantVector>(V))
Chris Lattner8d1d8d32006-03-31 23:01:56 +000011489 return CP->getOperand(EltNo);
11490 else if (InsertElementInst *III = dyn_cast<InsertElementInst>(V)) {
11491 // If this is an insert to a variable element, we don't know what it is.
Reid Spencere0fc4df2006-10-20 07:07:24 +000011492 if (!isa<ConstantInt>(III->getOperand(2)))
11493 return 0;
11494 unsigned IIElt = cast<ConstantInt>(III->getOperand(2))->getZExtValue();
Chris Lattner8d1d8d32006-03-31 23:01:56 +000011495
11496 // If this is an insert to the element we are looking for, return the
11497 // inserted value.
Reid Spencere0fc4df2006-10-20 07:07:24 +000011498 if (EltNo == IIElt)
11499 return III->getOperand(1);
Chris Lattner8d1d8d32006-03-31 23:01:56 +000011500
11501 // Otherwise, the insertelement doesn't modify the value, recurse on its
11502 // vector input.
11503 return FindScalarElement(III->getOperand(0), EltNo);
Chris Lattner2d37f922006-04-10 23:06:36 +000011504 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(V)) {
Mon P Wang25f01062008-11-10 04:46:22 +000011505 unsigned LHSWidth =
11506 cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements();
Chris Lattner12249be2006-05-25 23:48:38 +000011507 unsigned InEl = getShuffleMask(SVI)[EltNo];
Mon P Wang25f01062008-11-10 04:46:22 +000011508 if (InEl < LHSWidth)
Chris Lattner12249be2006-05-25 23:48:38 +000011509 return FindScalarElement(SVI->getOperand(0), InEl);
Mon P Wang25f01062008-11-10 04:46:22 +000011510 else if (InEl < LHSWidth*2)
11511 return FindScalarElement(SVI->getOperand(1), InEl - LHSWidth);
Chris Lattner12249be2006-05-25 23:48:38 +000011512 else
11513 return UndefValue::get(PTy->getElementType());
Chris Lattner8d1d8d32006-03-31 23:01:56 +000011514 }
11515
11516 // Otherwise, we don't know.
11517 return 0;
11518}
11519
Robert Bocchinoa8352962006-01-13 22:48:06 +000011520Instruction *InstCombiner::visitExtractElementInst(ExtractElementInst &EI) {
Dan Gohman06c60b62007-07-16 14:29:03 +000011521 // If vector val is undef, replace extract with scalar undef.
Chris Lattner92346c32006-03-31 18:25:14 +000011522 if (isa<UndefValue>(EI.getOperand(0)))
11523 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
11524
Dan Gohman06c60b62007-07-16 14:29:03 +000011525 // If vector val is constant 0, replace extract with scalar 0.
Chris Lattner92346c32006-03-31 18:25:14 +000011526 if (isa<ConstantAggregateZero>(EI.getOperand(0)))
11527 return ReplaceInstUsesWith(EI, Constant::getNullValue(EI.getType()));
11528
Reid Spencerd84d35b2007-02-15 02:26:10 +000011529 if (ConstantVector *C = dyn_cast<ConstantVector>(EI.getOperand(0))) {
Matthijs Kooijman3453c7b2008-06-11 09:00:12 +000011530 // If vector val is constant with all elements the same, replace EI with
11531 // that element. When the elements are not identical, we cannot replace yet
11532 // (we do that below, but only when the index is constant).
Chris Lattner6bc98652006-03-05 00:22:33 +000011533 Constant *op0 = C->getOperand(0);
Robert Bocchinoa8352962006-01-13 22:48:06 +000011534 for (unsigned i = 1; i < C->getNumOperands(); ++i)
Chris Lattner6bc98652006-03-05 00:22:33 +000011535 if (C->getOperand(i) != op0) {
11536 op0 = 0;
11537 break;
11538 }
11539 if (op0)
11540 return ReplaceInstUsesWith(EI, op0);
Robert Bocchinoa8352962006-01-13 22:48:06 +000011541 }
Chris Lattner6bc98652006-03-05 00:22:33 +000011542
Chris Lattner8d1d8d32006-03-31 23:01:56 +000011543 // If extracting a specified index from the vector, see if we can recursively
11544 // find a previously computed scalar that was inserted into the vector.
Reid Spencere0fc4df2006-10-20 07:07:24 +000011545 if (ConstantInt *IdxC = dyn_cast<ConstantInt>(EI.getOperand(1))) {
Chris Lattnera87c9f62007-04-09 01:37:55 +000011546 unsigned IndexVal = IdxC->getZExtValue();
11547 unsigned VectorWidth =
11548 cast<VectorType>(EI.getOperand(0)->getType())->getNumElements();
11549
11550 // If this is extracting an invalid index, turn this into undef, to avoid
11551 // crashing the code below.
11552 if (IndexVal >= VectorWidth)
11553 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
11554
Chris Lattner2deeaea2006-10-05 06:55:50 +000011555 // This instruction only demands the single element from the input vector.
11556 // If the input vector has a single use, simplify it based on this use
11557 // property.
Chris Lattnera87c9f62007-04-09 01:37:55 +000011558 if (EI.getOperand(0)->hasOneUse() && VectorWidth != 1) {
Chris Lattner2deeaea2006-10-05 06:55:50 +000011559 uint64_t UndefElts;
11560 if (Value *V = SimplifyDemandedVectorElts(EI.getOperand(0),
Reid Spencere0fc4df2006-10-20 07:07:24 +000011561 1 << IndexVal,
Chris Lattner2deeaea2006-10-05 06:55:50 +000011562 UndefElts)) {
11563 EI.setOperand(0, V);
11564 return &EI;
11565 }
11566 }
11567
Reid Spencere0fc4df2006-10-20 07:07:24 +000011568 if (Value *Elt = FindScalarElement(EI.getOperand(0), IndexVal))
Chris Lattner8d1d8d32006-03-31 23:01:56 +000011569 return ReplaceInstUsesWith(EI, Elt);
Chris Lattner7bfdd0a2007-04-14 23:02:14 +000011570
11571 // If the this extractelement is directly using a bitcast from a vector of
11572 // the same number of elements, see if we can find the source element from
11573 // it. In this case, we will end up needing to bitcast the scalars.
11574 if (BitCastInst *BCI = dyn_cast<BitCastInst>(EI.getOperand(0))) {
11575 if (const VectorType *VT =
11576 dyn_cast<VectorType>(BCI->getOperand(0)->getType()))
11577 if (VT->getNumElements() == VectorWidth)
11578 if (Value *Elt = FindScalarElement(BCI->getOperand(0), IndexVal))
11579 return new BitCastInst(Elt, EI.getType());
11580 }
Chris Lattner2d37f922006-04-10 23:06:36 +000011581 }
Chris Lattner8d1d8d32006-03-31 23:01:56 +000011582
Chris Lattner83f65782006-05-25 22:53:38 +000011583 if (Instruction *I = dyn_cast<Instruction>(EI.getOperand(0))) {
Robert Bocchinoa8352962006-01-13 22:48:06 +000011584 if (I->hasOneUse()) {
11585 // Push extractelement into predecessor operation if legal and
11586 // profitable to do so
11587 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
Chris Lattner6bc98652006-03-05 00:22:33 +000011588 bool isConstantElt = isa<ConstantInt>(EI.getOperand(1));
11589 if (CheapToScalarize(BO, isConstantElt)) {
11590 ExtractElementInst *newEI0 =
11591 new ExtractElementInst(BO->getOperand(0), EI.getOperand(1),
11592 EI.getName()+".lhs");
11593 ExtractElementInst *newEI1 =
11594 new ExtractElementInst(BO->getOperand(1), EI.getOperand(1),
11595 EI.getName()+".rhs");
11596 InsertNewInstBefore(newEI0, EI);
11597 InsertNewInstBefore(newEI1, EI);
Gabor Greife1f6e4b2008-05-16 19:29:10 +000011598 return BinaryOperator::Create(BO->getOpcode(), newEI0, newEI1);
Chris Lattner6bc98652006-03-05 00:22:33 +000011599 }
Reid Spencerde46e482006-11-02 20:25:50 +000011600 } else if (isa<LoadInst>(I)) {
Christopher Lambedf07882007-12-17 01:12:55 +000011601 unsigned AS =
11602 cast<PointerType>(I->getOperand(0)->getType())->getAddressSpace();
Chris Lattner5a866122008-01-13 22:23:22 +000011603 Value *Ptr = InsertBitCastBefore(I->getOperand(0),
11604 PointerType::get(EI.getType(), AS),EI);
Gabor Greif697e94c2008-05-15 10:04:30 +000011605 GetElementPtrInst *GEP =
11606 GetElementPtrInst::Create(Ptr, EI.getOperand(1), I->getName()+".gep");
Robert Bocchinoa8352962006-01-13 22:48:06 +000011607 InsertNewInstBefore(GEP, EI);
11608 return new LoadInst(GEP);
Chris Lattner83f65782006-05-25 22:53:38 +000011609 }
11610 }
11611 if (InsertElementInst *IE = dyn_cast<InsertElementInst>(I)) {
11612 // Extracting the inserted element?
11613 if (IE->getOperand(2) == EI.getOperand(1))
11614 return ReplaceInstUsesWith(EI, IE->getOperand(1));
11615 // If the inserted and extracted elements are constants, they must not
11616 // be the same value, extract from the pre-inserted value instead.
11617 if (isa<Constant>(IE->getOperand(2)) &&
11618 isa<Constant>(EI.getOperand(1))) {
11619 AddUsesToWorkList(EI);
11620 EI.setOperand(0, IE->getOperand(0));
11621 return &EI;
11622 }
11623 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I)) {
11624 // If this is extracting an element from a shufflevector, figure out where
11625 // it came from and extract from the appropriate input element instead.
Reid Spencere0fc4df2006-10-20 07:07:24 +000011626 if (ConstantInt *Elt = dyn_cast<ConstantInt>(EI.getOperand(1))) {
11627 unsigned SrcIdx = getShuffleMask(SVI)[Elt->getZExtValue()];
Chris Lattner12249be2006-05-25 23:48:38 +000011628 Value *Src;
Mon P Wang25f01062008-11-10 04:46:22 +000011629 unsigned LHSWidth =
11630 cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements();
11631
11632 if (SrcIdx < LHSWidth)
Chris Lattner12249be2006-05-25 23:48:38 +000011633 Src = SVI->getOperand(0);
Mon P Wang25f01062008-11-10 04:46:22 +000011634 else if (SrcIdx < LHSWidth*2) {
11635 SrcIdx -= LHSWidth;
Chris Lattner12249be2006-05-25 23:48:38 +000011636 Src = SVI->getOperand(1);
11637 } else {
11638 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
Chris Lattner612fa8e2006-03-30 22:02:40 +000011639 }
Chris Lattner2deeaea2006-10-05 06:55:50 +000011640 return new ExtractElementInst(Src, SrcIdx);
Robert Bocchinoa8352962006-01-13 22:48:06 +000011641 }
11642 }
Chris Lattner83f65782006-05-25 22:53:38 +000011643 }
Robert Bocchinoa8352962006-01-13 22:48:06 +000011644 return 0;
11645}
11646
Chris Lattner90951862006-04-16 00:51:47 +000011647/// CollectSingleShuffleElements - If V is a shuffle of values that ONLY returns
11648/// elements from either LHS or RHS, return the shuffle mask and true.
11649/// Otherwise, return false.
11650static bool CollectSingleShuffleElements(Value *V, Value *LHS, Value *RHS,
11651 std::vector<Constant*> &Mask) {
11652 assert(V->getType() == LHS->getType() && V->getType() == RHS->getType() &&
11653 "Invalid CollectSingleShuffleElements");
Reid Spencerd84d35b2007-02-15 02:26:10 +000011654 unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
Chris Lattner90951862006-04-16 00:51:47 +000011655
11656 if (isa<UndefValue>(V)) {
Reid Spencerc635f472006-12-31 05:48:39 +000011657 Mask.assign(NumElts, UndefValue::get(Type::Int32Ty));
Chris Lattner90951862006-04-16 00:51:47 +000011658 return true;
11659 } else if (V == LHS) {
11660 for (unsigned i = 0; i != NumElts; ++i)
Reid Spencerc635f472006-12-31 05:48:39 +000011661 Mask.push_back(ConstantInt::get(Type::Int32Ty, i));
Chris Lattner90951862006-04-16 00:51:47 +000011662 return true;
11663 } else if (V == RHS) {
11664 for (unsigned i = 0; i != NumElts; ++i)
Reid Spencerc635f472006-12-31 05:48:39 +000011665 Mask.push_back(ConstantInt::get(Type::Int32Ty, i+NumElts));
Chris Lattner90951862006-04-16 00:51:47 +000011666 return true;
11667 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
11668 // If this is an insert of an extract from some other vector, include it.
11669 Value *VecOp = IEI->getOperand(0);
11670 Value *ScalarOp = IEI->getOperand(1);
11671 Value *IdxOp = IEI->getOperand(2);
11672
Chris Lattnerb6cb64b2006-04-27 21:14:21 +000011673 if (!isa<ConstantInt>(IdxOp))
11674 return false;
Reid Spencere0fc4df2006-10-20 07:07:24 +000011675 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattnerb6cb64b2006-04-27 21:14:21 +000011676
11677 if (isa<UndefValue>(ScalarOp)) { // inserting undef into vector.
11678 // Okay, we can handle this if the vector we are insertinting into is
11679 // transitively ok.
11680 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
11681 // If so, update the mask to reflect the inserted undef.
Reid Spencerc635f472006-12-31 05:48:39 +000011682 Mask[InsertedIdx] = UndefValue::get(Type::Int32Ty);
Chris Lattnerb6cb64b2006-04-27 21:14:21 +000011683 return true;
11684 }
11685 } else if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)){
11686 if (isa<ConstantInt>(EI->getOperand(1)) &&
Chris Lattner90951862006-04-16 00:51:47 +000011687 EI->getOperand(0)->getType() == V->getType()) {
11688 unsigned ExtractedIdx =
Reid Spencere0fc4df2006-10-20 07:07:24 +000011689 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
Chris Lattner90951862006-04-16 00:51:47 +000011690
11691 // This must be extracting from either LHS or RHS.
11692 if (EI->getOperand(0) == LHS || EI->getOperand(0) == RHS) {
11693 // Okay, we can handle this if the vector we are insertinting into is
11694 // transitively ok.
11695 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
11696 // If so, update the mask to reflect the inserted value.
11697 if (EI->getOperand(0) == LHS) {
Mon P Wang1b2c0612008-08-20 02:23:25 +000011698 Mask[InsertedIdx % NumElts] =
Reid Spencerc635f472006-12-31 05:48:39 +000011699 ConstantInt::get(Type::Int32Ty, ExtractedIdx);
Chris Lattner90951862006-04-16 00:51:47 +000011700 } else {
11701 assert(EI->getOperand(0) == RHS);
Mon P Wang1b2c0612008-08-20 02:23:25 +000011702 Mask[InsertedIdx % NumElts] =
Reid Spencerc635f472006-12-31 05:48:39 +000011703 ConstantInt::get(Type::Int32Ty, ExtractedIdx+NumElts);
Chris Lattner90951862006-04-16 00:51:47 +000011704
11705 }
11706 return true;
11707 }
11708 }
11709 }
11710 }
11711 }
11712 // TODO: Handle shufflevector here!
11713
11714 return false;
11715}
11716
11717/// CollectShuffleElements - We are building a shuffle of V, using RHS as the
11718/// RHS of the shuffle instruction, if it is not null. Return a shuffle mask
11719/// that computes V and the LHS value of the shuffle.
Chris Lattner39fac442006-04-15 01:39:45 +000011720static Value *CollectShuffleElements(Value *V, std::vector<Constant*> &Mask,
Chris Lattner90951862006-04-16 00:51:47 +000011721 Value *&RHS) {
Reid Spencerd84d35b2007-02-15 02:26:10 +000011722 assert(isa<VectorType>(V->getType()) &&
Chris Lattner90951862006-04-16 00:51:47 +000011723 (RHS == 0 || V->getType() == RHS->getType()) &&
Chris Lattner39fac442006-04-15 01:39:45 +000011724 "Invalid shuffle!");
Reid Spencerd84d35b2007-02-15 02:26:10 +000011725 unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
Chris Lattner39fac442006-04-15 01:39:45 +000011726
11727 if (isa<UndefValue>(V)) {
Reid Spencerc635f472006-12-31 05:48:39 +000011728 Mask.assign(NumElts, UndefValue::get(Type::Int32Ty));
Chris Lattner39fac442006-04-15 01:39:45 +000011729 return V;
11730 } else if (isa<ConstantAggregateZero>(V)) {
Reid Spencerc635f472006-12-31 05:48:39 +000011731 Mask.assign(NumElts, ConstantInt::get(Type::Int32Ty, 0));
Chris Lattner39fac442006-04-15 01:39:45 +000011732 return V;
11733 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
11734 // If this is an insert of an extract from some other vector, include it.
11735 Value *VecOp = IEI->getOperand(0);
11736 Value *ScalarOp = IEI->getOperand(1);
11737 Value *IdxOp = IEI->getOperand(2);
11738
11739 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
11740 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
11741 EI->getOperand(0)->getType() == V->getType()) {
11742 unsigned ExtractedIdx =
Reid Spencere0fc4df2006-10-20 07:07:24 +000011743 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
11744 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattner39fac442006-04-15 01:39:45 +000011745
11746 // Either the extracted from or inserted into vector must be RHSVec,
11747 // otherwise we'd end up with a shuffle of three inputs.
Chris Lattner90951862006-04-16 00:51:47 +000011748 if (EI->getOperand(0) == RHS || RHS == 0) {
11749 RHS = EI->getOperand(0);
11750 Value *V = CollectShuffleElements(VecOp, Mask, RHS);
Mon P Wang1b2c0612008-08-20 02:23:25 +000011751 Mask[InsertedIdx % NumElts] =
Reid Spencerc635f472006-12-31 05:48:39 +000011752 ConstantInt::get(Type::Int32Ty, NumElts+ExtractedIdx);
Chris Lattner39fac442006-04-15 01:39:45 +000011753 return V;
11754 }
11755
Chris Lattner90951862006-04-16 00:51:47 +000011756 if (VecOp == RHS) {
11757 Value *V = CollectShuffleElements(EI->getOperand(0), Mask, RHS);
Chris Lattner39fac442006-04-15 01:39:45 +000011758 // Everything but the extracted element is replaced with the RHS.
11759 for (unsigned i = 0; i != NumElts; ++i) {
11760 if (i != InsertedIdx)
Reid Spencerc635f472006-12-31 05:48:39 +000011761 Mask[i] = ConstantInt::get(Type::Int32Ty, NumElts+i);
Chris Lattner39fac442006-04-15 01:39:45 +000011762 }
11763 return V;
11764 }
Chris Lattner90951862006-04-16 00:51:47 +000011765
11766 // If this insertelement is a chain that comes from exactly these two
11767 // vectors, return the vector and the effective shuffle.
11768 if (CollectSingleShuffleElements(IEI, EI->getOperand(0), RHS, Mask))
11769 return EI->getOperand(0);
11770
Chris Lattner39fac442006-04-15 01:39:45 +000011771 }
11772 }
11773 }
Chris Lattner90951862006-04-16 00:51:47 +000011774 // TODO: Handle shufflevector here!
Chris Lattner39fac442006-04-15 01:39:45 +000011775
11776 // Otherwise, can't do anything fancy. Return an identity vector.
11777 for (unsigned i = 0; i != NumElts; ++i)
Reid Spencerc635f472006-12-31 05:48:39 +000011778 Mask.push_back(ConstantInt::get(Type::Int32Ty, i));
Chris Lattner39fac442006-04-15 01:39:45 +000011779 return V;
11780}
11781
11782Instruction *InstCombiner::visitInsertElementInst(InsertElementInst &IE) {
11783 Value *VecOp = IE.getOperand(0);
11784 Value *ScalarOp = IE.getOperand(1);
11785 Value *IdxOp = IE.getOperand(2);
11786
Chris Lattner4ca9cbb2007-04-09 01:11:16 +000011787 // Inserting an undef or into an undefined place, remove this.
11788 if (isa<UndefValue>(ScalarOp) || isa<UndefValue>(IdxOp))
11789 ReplaceInstUsesWith(IE, VecOp);
11790
Chris Lattner39fac442006-04-15 01:39:45 +000011791 // If the inserted element was extracted from some other vector, and if the
11792 // indexes are constant, try to turn this into a shufflevector operation.
11793 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
11794 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
11795 EI->getOperand(0)->getType() == IE.getType()) {
11796 unsigned NumVectorElts = IE.getType()->getNumElements();
Chris Lattner28d921d2007-04-14 23:32:02 +000011797 unsigned ExtractedIdx =
11798 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
Reid Spencere0fc4df2006-10-20 07:07:24 +000011799 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattner39fac442006-04-15 01:39:45 +000011800
11801 if (ExtractedIdx >= NumVectorElts) // Out of range extract.
11802 return ReplaceInstUsesWith(IE, VecOp);
11803
11804 if (InsertedIdx >= NumVectorElts) // Out of range insert.
11805 return ReplaceInstUsesWith(IE, UndefValue::get(IE.getType()));
11806
11807 // If we are extracting a value from a vector, then inserting it right
11808 // back into the same place, just use the input vector.
11809 if (EI->getOperand(0) == VecOp && ExtractedIdx == InsertedIdx)
11810 return ReplaceInstUsesWith(IE, VecOp);
11811
11812 // We could theoretically do this for ANY input. However, doing so could
11813 // turn chains of insertelement instructions into a chain of shufflevector
11814 // instructions, and right now we do not merge shufflevectors. As such,
11815 // only do this in a situation where it is clear that there is benefit.
11816 if (isa<UndefValue>(VecOp) || isa<ConstantAggregateZero>(VecOp)) {
11817 // Turn this into shuffle(EIOp0, VecOp, Mask). The result has all of
11818 // the values of VecOp, except then one read from EIOp0.
11819 // Build a new shuffle mask.
11820 std::vector<Constant*> Mask;
11821 if (isa<UndefValue>(VecOp))
Reid Spencerc635f472006-12-31 05:48:39 +000011822 Mask.assign(NumVectorElts, UndefValue::get(Type::Int32Ty));
Chris Lattner39fac442006-04-15 01:39:45 +000011823 else {
11824 assert(isa<ConstantAggregateZero>(VecOp) && "Unknown thing");
Reid Spencerc635f472006-12-31 05:48:39 +000011825 Mask.assign(NumVectorElts, ConstantInt::get(Type::Int32Ty,
Chris Lattner39fac442006-04-15 01:39:45 +000011826 NumVectorElts));
11827 }
Reid Spencerc635f472006-12-31 05:48:39 +000011828 Mask[InsertedIdx] = ConstantInt::get(Type::Int32Ty, ExtractedIdx);
Chris Lattner39fac442006-04-15 01:39:45 +000011829 return new ShuffleVectorInst(EI->getOperand(0), VecOp,
Reid Spencerd84d35b2007-02-15 02:26:10 +000011830 ConstantVector::get(Mask));
Chris Lattner39fac442006-04-15 01:39:45 +000011831 }
11832
11833 // If this insertelement isn't used by some other insertelement, turn it
11834 // (and any insertelements it points to), into one big shuffle.
11835 if (!IE.hasOneUse() || !isa<InsertElementInst>(IE.use_back())) {
11836 std::vector<Constant*> Mask;
Chris Lattner90951862006-04-16 00:51:47 +000011837 Value *RHS = 0;
11838 Value *LHS = CollectShuffleElements(&IE, Mask, RHS);
11839 if (RHS == 0) RHS = UndefValue::get(LHS->getType());
11840 // We now have a shuffle of LHS, RHS, Mask.
Reid Spencerd84d35b2007-02-15 02:26:10 +000011841 return new ShuffleVectorInst(LHS, RHS, ConstantVector::get(Mask));
Chris Lattner39fac442006-04-15 01:39:45 +000011842 }
11843 }
11844 }
11845
11846 return 0;
11847}
11848
11849
Chris Lattnerfbb77a42006-04-10 22:45:52 +000011850Instruction *InstCombiner::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
11851 Value *LHS = SVI.getOperand(0);
11852 Value *RHS = SVI.getOperand(1);
Chris Lattner12249be2006-05-25 23:48:38 +000011853 std::vector<unsigned> Mask = getShuffleMask(&SVI);
Chris Lattnerfbb77a42006-04-10 22:45:52 +000011854
11855 bool MadeChange = false;
Mon P Wang25f01062008-11-10 04:46:22 +000011856
Chris Lattner2deeaea2006-10-05 06:55:50 +000011857 // Undefined shuffle mask -> undefined value.
Chris Lattner12249be2006-05-25 23:48:38 +000011858 if (isa<UndefValue>(SVI.getOperand(2)))
Chris Lattnerfbb77a42006-04-10 22:45:52 +000011859 return ReplaceInstUsesWith(SVI, UndefValue::get(SVI.getType()));
Dan Gohman86fb5b42008-09-09 18:11:14 +000011860
11861 uint64_t UndefElts;
11862 unsigned VWidth = cast<VectorType>(SVI.getType())->getNumElements();
Mon P Wang25f01062008-11-10 04:46:22 +000011863
11864 if (VWidth != cast<VectorType>(LHS->getType())->getNumElements())
11865 return 0;
11866
Dan Gohman86fb5b42008-09-09 18:11:14 +000011867 uint64_t AllOnesEltMask = ~0ULL >> (64-VWidth);
11868 if (VWidth <= 64 &&
Dan Gohman7d01c062008-09-11 22:47:57 +000011869 SimplifyDemandedVectorElts(&SVI, AllOnesEltMask, UndefElts)) {
11870 LHS = SVI.getOperand(0);
11871 RHS = SVI.getOperand(1);
Dan Gohman86fb5b42008-09-09 18:11:14 +000011872 MadeChange = true;
Dan Gohman7d01c062008-09-11 22:47:57 +000011873 }
Chris Lattner39fac442006-04-15 01:39:45 +000011874
Chris Lattner12249be2006-05-25 23:48:38 +000011875 // Canonicalize shuffle(x ,x,mask) -> shuffle(x, undef,mask')
11876 // Canonicalize shuffle(undef,x,mask) -> shuffle(x, undef,mask').
11877 if (LHS == RHS || isa<UndefValue>(LHS)) {
11878 if (isa<UndefValue>(LHS) && LHS == RHS) {
Chris Lattnerfbb77a42006-04-10 22:45:52 +000011879 // shuffle(undef,undef,mask) -> undef.
11880 return ReplaceInstUsesWith(SVI, LHS);
11881 }
11882
Chris Lattner12249be2006-05-25 23:48:38 +000011883 // Remap any references to RHS to use LHS.
11884 std::vector<Constant*> Elts;
11885 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
Chris Lattner0e477162006-05-26 00:29:06 +000011886 if (Mask[i] >= 2*e)
Reid Spencerc635f472006-12-31 05:48:39 +000011887 Elts.push_back(UndefValue::get(Type::Int32Ty));
Chris Lattner0e477162006-05-26 00:29:06 +000011888 else {
11889 if ((Mask[i] >= e && isa<UndefValue>(RHS)) ||
Dan Gohmanac22cfc2008-08-06 18:17:32 +000011890 (Mask[i] < e && isa<UndefValue>(LHS))) {
Chris Lattner0e477162006-05-26 00:29:06 +000011891 Mask[i] = 2*e; // Turn into undef.
Dan Gohmanac22cfc2008-08-06 18:17:32 +000011892 Elts.push_back(UndefValue::get(Type::Int32Ty));
11893 } else {
Mon P Wang1b2c0612008-08-20 02:23:25 +000011894 Mask[i] = Mask[i] % e; // Force to LHS.
Dan Gohmanac22cfc2008-08-06 18:17:32 +000011895 Elts.push_back(ConstantInt::get(Type::Int32Ty, Mask[i]));
11896 }
Chris Lattner0e477162006-05-26 00:29:06 +000011897 }
Chris Lattnerfbb77a42006-04-10 22:45:52 +000011898 }
Chris Lattner12249be2006-05-25 23:48:38 +000011899 SVI.setOperand(0, SVI.getOperand(1));
Chris Lattnerfbb77a42006-04-10 22:45:52 +000011900 SVI.setOperand(1, UndefValue::get(RHS->getType()));
Reid Spencerd84d35b2007-02-15 02:26:10 +000011901 SVI.setOperand(2, ConstantVector::get(Elts));
Chris Lattner0e477162006-05-26 00:29:06 +000011902 LHS = SVI.getOperand(0);
11903 RHS = SVI.getOperand(1);
Chris Lattnerfbb77a42006-04-10 22:45:52 +000011904 MadeChange = true;
11905 }
11906
Chris Lattner0e477162006-05-26 00:29:06 +000011907 // Analyze the shuffle, are the LHS or RHS and identity shuffles?
Chris Lattner12249be2006-05-25 23:48:38 +000011908 bool isLHSID = true, isRHSID = true;
Chris Lattner34cebe72006-04-16 00:03:56 +000011909
Chris Lattner12249be2006-05-25 23:48:38 +000011910 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
11911 if (Mask[i] >= e*2) continue; // Ignore undef values.
11912 // Is this an identity shuffle of the LHS value?
11913 isLHSID &= (Mask[i] == i);
11914
11915 // Is this an identity shuffle of the RHS value?
11916 isRHSID &= (Mask[i]-e == i);
Chris Lattner34cebe72006-04-16 00:03:56 +000011917 }
Chris Lattnerfbb77a42006-04-10 22:45:52 +000011918
Chris Lattner12249be2006-05-25 23:48:38 +000011919 // Eliminate identity shuffles.
11920 if (isLHSID) return ReplaceInstUsesWith(SVI, LHS);
11921 if (isRHSID) return ReplaceInstUsesWith(SVI, RHS);
Chris Lattnerfbb77a42006-04-10 22:45:52 +000011922
Chris Lattner0e477162006-05-26 00:29:06 +000011923 // If the LHS is a shufflevector itself, see if we can combine it with this
11924 // one without producing an unusual shuffle. Here we are really conservative:
11925 // we are absolutely afraid of producing a shuffle mask not in the input
11926 // program, because the code gen may not be smart enough to turn a merged
11927 // shuffle into two specific shuffles: it may produce worse code. As such,
11928 // we only merge two shuffles if the result is one of the two input shuffle
11929 // masks. In this case, merging the shuffles just removes one instruction,
11930 // which we know is safe. This is good for things like turning:
11931 // (splat(splat)) -> splat.
11932 if (ShuffleVectorInst *LHSSVI = dyn_cast<ShuffleVectorInst>(LHS)) {
11933 if (isa<UndefValue>(RHS)) {
11934 std::vector<unsigned> LHSMask = getShuffleMask(LHSSVI);
11935
11936 std::vector<unsigned> NewMask;
11937 for (unsigned i = 0, e = Mask.size(); i != e; ++i)
11938 if (Mask[i] >= 2*e)
11939 NewMask.push_back(2*e);
11940 else
11941 NewMask.push_back(LHSMask[Mask[i]]);
11942
11943 // If the result mask is equal to the src shuffle or this shuffle mask, do
11944 // the replacement.
11945 if (NewMask == LHSMask || NewMask == Mask) {
11946 std::vector<Constant*> Elts;
11947 for (unsigned i = 0, e = NewMask.size(); i != e; ++i) {
11948 if (NewMask[i] >= e*2) {
Reid Spencerc635f472006-12-31 05:48:39 +000011949 Elts.push_back(UndefValue::get(Type::Int32Ty));
Chris Lattner0e477162006-05-26 00:29:06 +000011950 } else {
Reid Spencerc635f472006-12-31 05:48:39 +000011951 Elts.push_back(ConstantInt::get(Type::Int32Ty, NewMask[i]));
Chris Lattner0e477162006-05-26 00:29:06 +000011952 }
11953 }
11954 return new ShuffleVectorInst(LHSSVI->getOperand(0),
11955 LHSSVI->getOperand(1),
Reid Spencerd84d35b2007-02-15 02:26:10 +000011956 ConstantVector::get(Elts));
Chris Lattner0e477162006-05-26 00:29:06 +000011957 }
11958 }
11959 }
Chris Lattner4284f642007-01-30 22:32:46 +000011960
Chris Lattnerfbb77a42006-04-10 22:45:52 +000011961 return MadeChange ? &SVI : 0;
11962}
11963
11964
Robert Bocchinoa8352962006-01-13 22:48:06 +000011965
Chris Lattner39c98bb2004-12-08 23:43:58 +000011966
11967/// TryToSinkInstruction - Try to move the specified instruction from its
11968/// current block into the beginning of DestBlock, which can only happen if it's
11969/// safe to move the instruction past all of the instructions between it and the
11970/// end of its block.
11971static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
11972 assert(I->hasOneUse() && "Invariants didn't hold!");
11973
Chris Lattnerc4f67e62005-10-27 17:13:11 +000011974 // Cannot move control-flow-involving, volatile loads, vaarg, etc.
Chris Lattnera4ee1f52008-05-09 15:07:33 +000011975 if (isa<PHINode>(I) || I->mayWriteToMemory() || isa<TerminatorInst>(I))
11976 return false;
Misha Brukmanb1c93172005-04-21 23:48:37 +000011977
Chris Lattner39c98bb2004-12-08 23:43:58 +000011978 // Do not sink alloca instructions out of the entry block.
Dan Gohmandcb291f2007-03-22 16:38:57 +000011979 if (isa<AllocaInst>(I) && I->getParent() ==
11980 &DestBlock->getParent()->getEntryBlock())
Chris Lattner39c98bb2004-12-08 23:43:58 +000011981 return false;
11982
Chris Lattnerf17a2fb2004-12-09 07:14:34 +000011983 // We can only sink load instructions if there is nothing between the load and
11984 // the end of block that could change the value.
Chris Lattner49a594e2008-05-08 17:37:37 +000011985 if (I->mayReadFromMemory()) {
11986 for (BasicBlock::iterator Scan = I, E = I->getParent()->end();
Chris Lattnerf17a2fb2004-12-09 07:14:34 +000011987 Scan != E; ++Scan)
11988 if (Scan->mayWriteToMemory())
11989 return false;
Chris Lattnerf17a2fb2004-12-09 07:14:34 +000011990 }
Chris Lattner39c98bb2004-12-08 23:43:58 +000011991
Dan Gohmanf96e1372008-05-23 21:05:58 +000011992 BasicBlock::iterator InsertPos = DestBlock->getFirstNonPHI();
Chris Lattner39c98bb2004-12-08 23:43:58 +000011993
Chris Lattner9f269e42005-08-08 19:11:57 +000011994 I->moveBefore(InsertPos);
Chris Lattner39c98bb2004-12-08 23:43:58 +000011995 ++NumSunkInst;
11996 return true;
11997}
11998
Chris Lattnera36ee4e2006-05-10 19:00:36 +000011999
12000/// AddReachableCodeToWorklist - Walk the function in depth-first order, adding
12001/// all reachable code to the worklist.
12002///
12003/// This has a couple of tricks to make the code faster and more powerful. In
12004/// particular, we constant fold and DCE instructions as we go, to avoid adding
12005/// them to the worklist (this significantly speeds up instcombine on code where
12006/// many instructions are dead or constant). Additionally, if we find a branch
12007/// whose condition is a known constant, we only visit the reachable successors.
12008///
12009static void AddReachableCodeToWorklist(BasicBlock *BB,
Chris Lattner7907e5f2007-02-15 19:41:52 +000012010 SmallPtrSet<BasicBlock*, 64> &Visited,
Chris Lattnerb15e2b12007-03-02 21:28:56 +000012011 InstCombiner &IC,
Chris Lattner1443bc52006-05-11 17:11:52 +000012012 const TargetData *TD) {
Chris Lattner1d239152008-08-15 04:03:01 +000012013 SmallVector<BasicBlock*, 256> Worklist;
Chris Lattner12b89cc2007-03-23 19:17:18 +000012014 Worklist.push_back(BB);
Chris Lattnera36ee4e2006-05-10 19:00:36 +000012015
Chris Lattner12b89cc2007-03-23 19:17:18 +000012016 while (!Worklist.empty()) {
12017 BB = Worklist.back();
12018 Worklist.pop_back();
12019
12020 // We have now visited this block! If we've already been here, ignore it.
12021 if (!Visited.insert(BB)) continue;
Devang Patel7ed6c532008-11-19 18:56:50 +000012022
12023 DbgInfoIntrinsic *DBI_Prev = NULL;
Chris Lattner12b89cc2007-03-23 19:17:18 +000012024 for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
12025 Instruction *Inst = BBI++;
Chris Lattnera36ee4e2006-05-10 19:00:36 +000012026
Chris Lattner12b89cc2007-03-23 19:17:18 +000012027 // DCE instruction if trivially dead.
12028 if (isInstructionTriviallyDead(Inst)) {
12029 ++NumDeadInst;
12030 DOUT << "IC: DCE: " << *Inst;
12031 Inst->eraseFromParent();
12032 continue;
12033 }
12034
12035 // ConstantProp instruction if trivially constant.
12036 if (Constant *C = ConstantFoldInstruction(Inst, TD)) {
12037 DOUT << "IC: ConstFold to: " << *C << " from: " << *Inst;
12038 Inst->replaceAllUsesWith(C);
12039 ++NumConstProp;
12040 Inst->eraseFromParent();
12041 continue;
12042 }
Chris Lattnerd82e4a12007-07-20 22:06:41 +000012043
Devang Patel7ed6c532008-11-19 18:56:50 +000012044 // If there are two consecutive llvm.dbg.stoppoint calls then
12045 // it is likely that the optimizer deleted code in between these
12046 // two intrinsics.
12047 DbgInfoIntrinsic *DBI_Next = dyn_cast<DbgInfoIntrinsic>(Inst);
12048 if (DBI_Next) {
12049 if (DBI_Prev
12050 && DBI_Prev->getIntrinsicID() == llvm::Intrinsic::dbg_stoppoint
12051 && DBI_Next->getIntrinsicID() == llvm::Intrinsic::dbg_stoppoint) {
12052 IC.RemoveFromWorkList(DBI_Prev);
12053 DBI_Prev->eraseFromParent();
12054 }
12055 DBI_Prev = DBI_Next;
12056 }
12057
Chris Lattner12b89cc2007-03-23 19:17:18 +000012058 IC.AddToWorkList(Inst);
Chris Lattnera36ee4e2006-05-10 19:00:36 +000012059 }
Chris Lattner12b89cc2007-03-23 19:17:18 +000012060
12061 // Recursively visit successors. If this is a branch or switch on a
12062 // constant, only visit the reachable successor.
12063 TerminatorInst *TI = BB->getTerminator();
12064 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
12065 if (BI->isConditional() && isa<ConstantInt>(BI->getCondition())) {
12066 bool CondVal = cast<ConstantInt>(BI->getCondition())->getZExtValue();
Nick Lewycky271506f2008-03-09 08:50:23 +000012067 BasicBlock *ReachableBB = BI->getSuccessor(!CondVal);
Nick Lewycky4d43d3c2008-04-25 16:53:59 +000012068 Worklist.push_back(ReachableBB);
Chris Lattner12b89cc2007-03-23 19:17:18 +000012069 continue;
12070 }
12071 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
12072 if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
12073 // See if this is an explicit destination.
12074 for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
12075 if (SI->getCaseValue(i) == Cond) {
Nick Lewycky271506f2008-03-09 08:50:23 +000012076 BasicBlock *ReachableBB = SI->getSuccessor(i);
Nick Lewycky4d43d3c2008-04-25 16:53:59 +000012077 Worklist.push_back(ReachableBB);
Chris Lattner12b89cc2007-03-23 19:17:18 +000012078 continue;
12079 }
12080
12081 // Otherwise it is the default destination.
12082 Worklist.push_back(SI->getSuccessor(0));
12083 continue;
12084 }
12085 }
12086
12087 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
12088 Worklist.push_back(TI->getSuccessor(i));
Chris Lattnera36ee4e2006-05-10 19:00:36 +000012089 }
Chris Lattnera36ee4e2006-05-10 19:00:36 +000012090}
12091
Chris Lattner960a5432007-03-03 02:04:50 +000012092bool InstCombiner::DoOneIteration(Function &F, unsigned Iteration) {
Chris Lattner260ab202002-04-18 17:39:14 +000012093 bool Changed = false;
Chris Lattnerf4ad1652003-11-02 05:57:39 +000012094 TD = &getAnalysis<TargetData>();
Chris Lattner960a5432007-03-03 02:04:50 +000012095
12096 DEBUG(DOUT << "\n\nINSTCOMBINE ITERATION #" << Iteration << " on "
12097 << F.getNameStr() << "\n");
Chris Lattnerca081252001-12-14 16:52:21 +000012098
Chris Lattner4ed40f72005-07-07 20:40:38 +000012099 {
Chris Lattnera36ee4e2006-05-10 19:00:36 +000012100 // Do a depth-first traversal of the function, populate the worklist with
12101 // the reachable instructions. Ignore blocks that are not reachable. Keep
12102 // track of which blocks we visit.
Chris Lattner7907e5f2007-02-15 19:41:52 +000012103 SmallPtrSet<BasicBlock*, 64> Visited;
Chris Lattnerb15e2b12007-03-02 21:28:56 +000012104 AddReachableCodeToWorklist(F.begin(), Visited, *this, TD);
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +000012105
Chris Lattner4ed40f72005-07-07 20:40:38 +000012106 // Do a quick scan over the function. If we find any blocks that are
12107 // unreachable, remove any instructions inside of them. This prevents
12108 // the instcombine code from having to deal with some bad special cases.
12109 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
12110 if (!Visited.count(BB)) {
12111 Instruction *Term = BB->getTerminator();
12112 while (Term != BB->begin()) { // Remove instrs bottom-up
12113 BasicBlock::iterator I = Term; --I;
Chris Lattner2d3a7a62004-04-27 15:13:33 +000012114
Bill Wendling5dbf43c2006-11-26 09:46:52 +000012115 DOUT << "IC: DCE: " << *I;
Chris Lattner4ed40f72005-07-07 20:40:38 +000012116 ++NumDeadInst;
12117
12118 if (!I->use_empty())
12119 I->replaceAllUsesWith(UndefValue::get(I->getType()));
12120 I->eraseFromParent();
12121 }
12122 }
12123 }
Chris Lattnerca081252001-12-14 16:52:21 +000012124
Chris Lattnerb15e2b12007-03-02 21:28:56 +000012125 while (!Worklist.empty()) {
12126 Instruction *I = RemoveOneFromWorkList();
12127 if (I == 0) continue; // skip null values.
Chris Lattnerca081252001-12-14 16:52:21 +000012128
Chris Lattner1443bc52006-05-11 17:11:52 +000012129 // Check to see if we can DCE the instruction.
Chris Lattner99f48c62002-09-02 04:59:56 +000012130 if (isInstructionTriviallyDead(I)) {
Chris Lattner1443bc52006-05-11 17:11:52 +000012131 // Add operands to the worklist.
Chris Lattnere8ed4ef2003-10-06 17:11:01 +000012132 if (I->getNumOperands() < 4)
Chris Lattner51ea1272004-02-28 05:22:00 +000012133 AddUsesToWorkList(*I);
Chris Lattner99f48c62002-09-02 04:59:56 +000012134 ++NumDeadInst;
Chris Lattnere8ed4ef2003-10-06 17:11:01 +000012135
Bill Wendling5dbf43c2006-11-26 09:46:52 +000012136 DOUT << "IC: DCE: " << *I;
Chris Lattnercd517ff2005-01-28 19:32:01 +000012137
12138 I->eraseFromParent();
Chris Lattnerb15e2b12007-03-02 21:28:56 +000012139 RemoveFromWorkList(I);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +000012140 continue;
12141 }
Chris Lattner99f48c62002-09-02 04:59:56 +000012142
Chris Lattner1443bc52006-05-11 17:11:52 +000012143 // Instruction isn't dead, see if we can constant propagate it.
Chris Lattnere3eda252007-01-30 23:16:15 +000012144 if (Constant *C = ConstantFoldInstruction(I, TD)) {
Bill Wendling5dbf43c2006-11-26 09:46:52 +000012145 DOUT << "IC: ConstFold to: " << *C << " from: " << *I;
Chris Lattnercd517ff2005-01-28 19:32:01 +000012146
Chris Lattner1443bc52006-05-11 17:11:52 +000012147 // Add operands to the worklist.
Chris Lattner51ea1272004-02-28 05:22:00 +000012148 AddUsesToWorkList(*I);
Chris Lattnerc6509f42002-12-05 22:41:53 +000012149 ReplaceInstUsesWith(*I, C);
12150
Chris Lattner99f48c62002-09-02 04:59:56 +000012151 ++NumConstProp;
Chris Lattnera36ee4e2006-05-10 19:00:36 +000012152 I->eraseFromParent();
Chris Lattnerb15e2b12007-03-02 21:28:56 +000012153 RemoveFromWorkList(I);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +000012154 continue;
Chris Lattner99f48c62002-09-02 04:59:56 +000012155 }
Chris Lattnere8ed4ef2003-10-06 17:11:01 +000012156
Nick Lewyckyf6ccd252008-05-25 20:56:15 +000012157 if (TD && I->getType()->getTypeID() == Type::VoidTyID) {
12158 // See if we can constant fold its operands.
12159 for (User::op_iterator i = I->op_begin(), e = I->op_end(); i != e; ++i) {
12160 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(i)) {
12161 if (Constant *NewC = ConstantFoldConstantExpression(CE, TD))
12162 i->set(NewC);
12163 }
12164 }
12165 }
12166
Chris Lattner39c98bb2004-12-08 23:43:58 +000012167 // See if we can trivially sink this instruction to a successor basic block.
Dan Gohmanfa1211f2008-07-23 00:34:11 +000012168 if (I->hasOneUse()) {
Chris Lattner39c98bb2004-12-08 23:43:58 +000012169 BasicBlock *BB = I->getParent();
12170 BasicBlock *UserParent = cast<Instruction>(I->use_back())->getParent();
12171 if (UserParent != BB) {
12172 bool UserIsSuccessor = false;
12173 // See if the user is one of our successors.
12174 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
12175 if (*SI == UserParent) {
12176 UserIsSuccessor = true;
12177 break;
12178 }
12179
12180 // If the user is one of our immediate successors, and if that successor
12181 // only has us as a predecessors (we'd have to split the critical edge
12182 // otherwise), we can keep going.
12183 if (UserIsSuccessor && !isa<PHINode>(I->use_back()) &&
12184 next(pred_begin(UserParent)) == pred_end(UserParent))
12185 // Okay, the CFG is simple enough, try to sink this instruction.
12186 Changed |= TryToSinkInstruction(I, UserParent);
12187 }
12188 }
12189
Chris Lattnerca081252001-12-14 16:52:21 +000012190 // Now that we have an instruction, try combining it to simplify it...
Reid Spencer755d0e72007-03-26 17:44:01 +000012191#ifndef NDEBUG
12192 std::string OrigI;
12193#endif
12194 DEBUG(std::ostringstream SS; I->print(SS); OrigI = SS.str(););
Chris Lattnerae7a0d32002-08-02 19:29:35 +000012195 if (Instruction *Result = visit(*I)) {
Chris Lattner0b18c1d2002-05-10 15:38:35 +000012196 ++NumCombined;
Chris Lattner260ab202002-04-18 17:39:14 +000012197 // Should we replace the old instruction with a new one?
Chris Lattner053c0932002-05-14 15:24:07 +000012198 if (Result != I) {
Bill Wendling5dbf43c2006-11-26 09:46:52 +000012199 DOUT << "IC: Old = " << *I
12200 << " New = " << *Result;
Chris Lattner7d2a5392004-03-13 23:54:27 +000012201
Chris Lattner396dbfe2004-06-09 05:08:07 +000012202 // Everything uses the new instruction now.
12203 I->replaceAllUsesWith(Result);
12204
12205 // Push the new instruction and any users onto the worklist.
Chris Lattnerb15e2b12007-03-02 21:28:56 +000012206 AddToWorkList(Result);
Chris Lattner396dbfe2004-06-09 05:08:07 +000012207 AddUsersToWorkList(*Result);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +000012208
Chris Lattner6e0123b2007-02-11 01:23:03 +000012209 // Move the name to the new instruction first.
12210 Result->takeName(I);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +000012211
12212 // Insert the new instruction into the basic block...
12213 BasicBlock *InstParent = I->getParent();
Chris Lattner7515cab2004-11-14 19:13:23 +000012214 BasicBlock::iterator InsertPos = I;
12215
12216 if (!isa<PHINode>(Result)) // If combining a PHI, don't insert
12217 while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
12218 ++InsertPos;
12219
12220 InstParent->getInstList().insert(InsertPos, Result);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +000012221
Chris Lattner63d75af2004-05-01 23:27:23 +000012222 // Make sure that we reprocess all operands now that we reduced their
12223 // use counts.
Chris Lattnerb15e2b12007-03-02 21:28:56 +000012224 AddUsesToWorkList(*I);
Chris Lattnerb643a9e2004-05-01 23:19:52 +000012225
Chris Lattner396dbfe2004-06-09 05:08:07 +000012226 // Instructions can end up on the worklist more than once. Make sure
12227 // we do not process an instruction that has been deleted.
Chris Lattnerb15e2b12007-03-02 21:28:56 +000012228 RemoveFromWorkList(I);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +000012229
12230 // Erase the old instruction.
12231 InstParent->getInstList().erase(I);
Chris Lattner113f4f42002-06-25 16:13:24 +000012232 } else {
Evan Chenga4ed8a52007-03-27 16:44:48 +000012233#ifndef NDEBUG
Reid Spencer755d0e72007-03-26 17:44:01 +000012234 DOUT << "IC: Mod = " << OrigI
12235 << " New = " << *I;
Evan Chenga4ed8a52007-03-27 16:44:48 +000012236#endif
Chris Lattner7d2a5392004-03-13 23:54:27 +000012237
Chris Lattnerae7a0d32002-08-02 19:29:35 +000012238 // If the instruction was modified, it's possible that it is now dead.
12239 // if so, remove it.
Chris Lattner63d75af2004-05-01 23:27:23 +000012240 if (isInstructionTriviallyDead(I)) {
12241 // Make sure we process all operands now that we are reducing their
12242 // use counts.
Chris Lattner960a5432007-03-03 02:04:50 +000012243 AddUsesToWorkList(*I);
Misha Brukmanb1c93172005-04-21 23:48:37 +000012244
Chris Lattner63d75af2004-05-01 23:27:23 +000012245 // Instructions may end up in the worklist more than once. Erase all
Robert Bocchinoa8352962006-01-13 22:48:06 +000012246 // occurrences of this instruction.
Chris Lattnerb15e2b12007-03-02 21:28:56 +000012247 RemoveFromWorkList(I);
Chris Lattner31f486c2005-01-31 05:36:43 +000012248 I->eraseFromParent();
Chris Lattner396dbfe2004-06-09 05:08:07 +000012249 } else {
Chris Lattner960a5432007-03-03 02:04:50 +000012250 AddToWorkList(I);
12251 AddUsersToWorkList(*I);
Chris Lattnerae7a0d32002-08-02 19:29:35 +000012252 }
Chris Lattner053c0932002-05-14 15:24:07 +000012253 }
Chris Lattner260ab202002-04-18 17:39:14 +000012254 Changed = true;
Chris Lattnerca081252001-12-14 16:52:21 +000012255 }
12256 }
12257
Chris Lattner960a5432007-03-03 02:04:50 +000012258 assert(WorklistMap.empty() && "Worklist empty, but map not?");
Chris Lattnerf0da7972007-08-05 08:47:58 +000012259
12260 // Do an explicit clear, this shrinks the map if needed.
12261 WorklistMap.clear();
Chris Lattner260ab202002-04-18 17:39:14 +000012262 return Changed;
Chris Lattner04805fa2002-02-26 21:46:54 +000012263}
12264
Chris Lattner960a5432007-03-03 02:04:50 +000012265
12266bool InstCombiner::runOnFunction(Function &F) {
Chris Lattner8258b442007-03-04 04:27:24 +000012267 MustPreserveLCSSA = mustPreserveAnalysisID(LCSSAID);
12268
Chris Lattner960a5432007-03-03 02:04:50 +000012269 bool EverMadeChange = false;
12270
12271 // Iterate while there is work to do.
12272 unsigned Iteration = 0;
Bill Wendling37169522008-05-14 22:45:20 +000012273 while (DoOneIteration(F, Iteration++))
Chris Lattner960a5432007-03-03 02:04:50 +000012274 EverMadeChange = true;
12275 return EverMadeChange;
12276}
12277
Brian Gaeke38b79e82004-07-27 17:43:21 +000012278FunctionPass *llvm::createInstructionCombiningPass() {
Chris Lattner260ab202002-04-18 17:39:14 +000012279 return new InstCombiner();
Chris Lattner04805fa2002-02-26 21:46:54 +000012280}
Brian Gaeke960707c2003-11-11 22:41:34 +000012281
Chris Lattner2aa0ff22008-08-11 22:06:05 +000012282