blob: a8dcfa447da0430b26ee1f077a2447fca0ba97e1 [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);
185 Instruction *visitOr (BinaryOperator &I);
186 Instruction *visitXor(BinaryOperator &I);
Reid Spencer2341c222007-02-02 02:16:23 +0000187 Instruction *visitShl(BinaryOperator &I);
188 Instruction *visitAShr(BinaryOperator &I);
189 Instruction *visitLShr(BinaryOperator &I);
190 Instruction *commonShiftTransforms(BinaryOperator &I);
Chris Lattner5920a782008-05-19 20:18:56 +0000191 Instruction *FoldFCmp_IntToFP_Cst(FCmpInst &I, Instruction *LHSI,
192 Constant *RHSC);
Reid Spencer266e42b2006-12-23 06:05:41 +0000193 Instruction *visitFCmpInst(FCmpInst &I);
194 Instruction *visitICmpInst(ICmpInst &I);
195 Instruction *visitICmpInstWithCastAndCast(ICmpInst &ICI);
Chris Lattnera74deaf2007-04-03 17:43:25 +0000196 Instruction *visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
197 Instruction *LHS,
198 ConstantInt *RHS);
Chris Lattner3bbec592007-06-20 23:46:26 +0000199 Instruction *FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
200 ConstantInt *DivRHS);
Chris Lattnerd1f46d32005-04-24 06:59:08 +0000201
Reid Spencer266e42b2006-12-23 06:05:41 +0000202 Instruction *FoldGEPICmp(User *GEPLHS, Value *RHS,
203 ICmpInst::Predicate Cond, Instruction &I);
Reid Spencere0fc4df2006-10-20 07:07:24 +0000204 Instruction *FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
Reid Spencer2341c222007-02-02 02:16:23 +0000205 BinaryOperator &I);
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000206 Instruction *commonCastTransforms(CastInst &CI);
207 Instruction *commonIntCastTransforms(CastInst &CI);
Chris Lattner1db224d2007-04-27 17:44:50 +0000208 Instruction *commonPointerCastTransforms(CastInst &CI);
Chris Lattner74ff60f2007-04-11 06:57:46 +0000209 Instruction *visitTrunc(TruncInst &CI);
210 Instruction *visitZExt(ZExtInst &CI);
211 Instruction *visitSExt(SExtInst &CI);
Chris Lattnerfa1e7ee2008-01-27 05:29:54 +0000212 Instruction *visitFPTrunc(FPTruncInst &CI);
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000213 Instruction *visitFPExt(CastInst &CI);
Chris Lattnere35fe0f2008-05-19 20:25:04 +0000214 Instruction *visitFPToUI(FPToUIInst &FI);
215 Instruction *visitFPToSI(FPToSIInst &FI);
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000216 Instruction *visitUIToFP(CastInst &CI);
217 Instruction *visitSIToFP(CastInst &CI);
218 Instruction *visitPtrToInt(CastInst &CI);
Chris Lattner2940c5c2008-01-08 07:23:51 +0000219 Instruction *visitIntToPtr(IntToPtrInst &CI);
Chris Lattner1db224d2007-04-27 17:44:50 +0000220 Instruction *visitBitCast(BitCastInst &CI);
Chris Lattner411336f2005-01-19 21:50:18 +0000221 Instruction *FoldSelectOpOp(SelectInst &SI, Instruction *TI,
222 Instruction *FI);
Dan Gohmandafa9c62008-09-16 18:46:06 +0000223 Instruction *visitSelectInst(SelectInst &SI);
224 Instruction *visitSelectInstWithICmp(SelectInst &SI, ICmpInst *ICI);
Chris Lattner970c33a2003-06-19 17:00:31 +0000225 Instruction *visitCallInst(CallInst &CI);
226 Instruction *visitInvokeInst(InvokeInst &II);
Chris Lattner113f4f42002-06-25 16:13:24 +0000227 Instruction *visitPHINode(PHINode &PN);
228 Instruction *visitGetElementPtrInst(GetElementPtrInst &GEP);
Chris Lattner1085bdf2002-11-04 16:18:53 +0000229 Instruction *visitAllocationInst(AllocationInst &AI);
Chris Lattner8427bff2003-12-07 01:24:23 +0000230 Instruction *visitFreeInst(FreeInst &FI);
Chris Lattner0f1d8a32003-06-26 05:06:25 +0000231 Instruction *visitLoadInst(LoadInst &LI);
Chris Lattner31f486c2005-01-31 05:36:43 +0000232 Instruction *visitStoreInst(StoreInst &SI);
Chris Lattner9eef8a72003-06-04 04:46:00 +0000233 Instruction *visitBranchInst(BranchInst &BI);
Chris Lattner4c9c20a2004-07-03 00:26:11 +0000234 Instruction *visitSwitchInst(SwitchInst &SI);
Chris Lattner39fac442006-04-15 01:39:45 +0000235 Instruction *visitInsertElementInst(InsertElementInst &IE);
Robert Bocchinoa8352962006-01-13 22:48:06 +0000236 Instruction *visitExtractElementInst(ExtractElementInst &EI);
Chris Lattnerfbb77a42006-04-10 22:45:52 +0000237 Instruction *visitShuffleVectorInst(ShuffleVectorInst &SVI);
Matthijs Kooijmanb2fc72b2008-06-11 14:05:05 +0000238 Instruction *visitExtractValueInst(ExtractValueInst &EV);
Chris Lattner260ab202002-04-18 17:39:14 +0000239
240 // visitInstruction - Specify what to return for unhandled instructions...
Chris Lattner113f4f42002-06-25 16:13:24 +0000241 Instruction *visitInstruction(Instruction &I) { return 0; }
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000242
Chris Lattner970c33a2003-06-19 17:00:31 +0000243 private:
Chris Lattneraec3d942003-10-07 22:32:43 +0000244 Instruction *visitCallSite(CallSite CS);
Chris Lattner970c33a2003-06-19 17:00:31 +0000245 bool transformConstExprCastCall(CallSite CS);
Duncan Sands6d5da712007-09-17 10:26:40 +0000246 Instruction *transformCallThroughTrampoline(CallSite CS);
Evan Chengc3cf9f82008-03-24 00:21:34 +0000247 Instruction *transformZExtICmp(ICmpInst *ICI, Instruction &CI,
248 bool DoXform = true);
Chris Lattner7ac943f2008-05-20 05:46:13 +0000249 bool WillNotOverflowSignedAdd(Value *LHS, Value *RHS);
Chris Lattner970c33a2003-06-19 17:00:31 +0000250
Chris Lattner69193f92004-04-05 01:30:19 +0000251 public:
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000252 // InsertNewInstBefore - insert an instruction New before instruction Old
253 // in the program. Add the new instruction to the worklist.
254 //
Chris Lattner623826c2004-09-28 21:48:02 +0000255 Instruction *InsertNewInstBefore(Instruction *New, Instruction &Old) {
Chris Lattner65217ff2002-08-23 18:32:43 +0000256 assert(New && New->getParent() == 0 &&
257 "New instruction already inserted into a basic block!");
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000258 BasicBlock *BB = Old.getParent();
259 BB->getInstList().insert(&Old, New); // Insert inst
Chris Lattnerb15e2b12007-03-02 21:28:56 +0000260 AddToWorkList(New);
Chris Lattnere79e8542004-02-23 06:38:22 +0000261 return New;
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000262 }
263
Chris Lattner7e794272004-09-24 15:21:34 +0000264 /// InsertCastBefore - Insert a cast of V to TY before the instruction POS.
265 /// This also adds the cast to the worklist. Finally, this returns the
266 /// cast.
Reid Spencer13bc5d72006-12-12 09:18:51 +0000267 Value *InsertCastBefore(Instruction::CastOps opc, Value *V, const Type *Ty,
268 Instruction &Pos) {
Chris Lattner7e794272004-09-24 15:21:34 +0000269 if (V->getType() == Ty) return V;
Misha Brukmanb1c93172005-04-21 23:48:37 +0000270
Chris Lattnere79d2492006-04-06 19:19:17 +0000271 if (Constant *CV = dyn_cast<Constant>(V))
Reid Spencer13bc5d72006-12-12 09:18:51 +0000272 return ConstantExpr::getCast(opc, CV, Ty);
Chris Lattnere79d2492006-04-06 19:19:17 +0000273
Gabor Greife1f6e4b2008-05-16 19:29:10 +0000274 Instruction *C = CastInst::Create(opc, V, Ty, V->getName(), &Pos);
Chris Lattnerb15e2b12007-03-02 21:28:56 +0000275 AddToWorkList(C);
Chris Lattner7e794272004-09-24 15:21:34 +0000276 return C;
277 }
Chris Lattner5a866122008-01-13 22:23:22 +0000278
279 Value *InsertBitCastBefore(Value *V, const Type *Ty, Instruction &Pos) {
280 return InsertCastBefore(Instruction::BitCast, V, Ty, Pos);
281 }
282
Chris Lattner7e794272004-09-24 15:21:34 +0000283
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000284 // ReplaceInstUsesWith - This method is to be used when an instruction is
285 // found to be dead, replacable with another preexisting expression. Here
286 // we add all uses of I to the worklist, replace all uses of I with the new
287 // value, then return I, so that the inst combiner will know that I was
288 // modified.
289 //
290 Instruction *ReplaceInstUsesWith(Instruction &I, Value *V) {
Chris Lattner51ea1272004-02-28 05:22:00 +0000291 AddUsersToWorkList(I); // Add all modified instrs to worklist
Chris Lattner8953b902004-04-05 02:10:19 +0000292 if (&I != V) {
293 I.replaceAllUsesWith(V);
294 return &I;
295 } else {
296 // If we are replacing the instruction with itself, this must be in a
297 // segment of unreachable code, so just clobber the instruction.
Chris Lattner8ba9ec92004-10-18 02:59:09 +0000298 I.replaceAllUsesWith(UndefValue::get(I.getType()));
Chris Lattner8953b902004-04-05 02:10:19 +0000299 return &I;
300 }
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000301 }
Chris Lattner51ea1272004-02-28 05:22:00 +0000302
Chris Lattner2590e512006-02-07 06:56:34 +0000303 // UpdateValueUsesWith - This method is to be used when an value is
304 // found to be replacable with another preexisting expression or was
305 // updated. Here we add all uses of I to the worklist, replace all uses of
306 // I with the new value (unless the instruction was just updated), then
307 // return true, so that the inst combiner will know that I was modified.
308 //
309 bool UpdateValueUsesWith(Value *Old, Value *New) {
310 AddUsersToWorkList(*Old); // Add all modified instrs to worklist
311 if (Old != New)
312 Old->replaceAllUsesWith(New);
313 if (Instruction *I = dyn_cast<Instruction>(Old))
Chris Lattnerb15e2b12007-03-02 21:28:56 +0000314 AddToWorkList(I);
Chris Lattner5b2edb12006-02-12 08:02:11 +0000315 if (Instruction *I = dyn_cast<Instruction>(New))
Chris Lattnerb15e2b12007-03-02 21:28:56 +0000316 AddToWorkList(I);
Chris Lattner2590e512006-02-07 06:56:34 +0000317 return true;
318 }
319
Chris Lattner51ea1272004-02-28 05:22:00 +0000320 // EraseInstFromFunction - When dealing with an instruction that has side
321 // effects or produces a void value, we can't rely on DCE to delete the
322 // instruction. Instead, visit methods should return the value returned by
323 // this function.
324 Instruction *EraseInstFromFunction(Instruction &I) {
325 assert(I.use_empty() && "Cannot erase instruction that is used!");
326 AddUsesToWorkList(I);
Chris Lattnerb15e2b12007-03-02 21:28:56 +0000327 RemoveFromWorkList(&I);
Chris Lattner95307542004-11-18 21:41:39 +0000328 I.eraseFromParent();
Chris Lattner51ea1272004-02-28 05:22:00 +0000329 return 0; // Don't do anything with FI
330 }
Chris Lattner965c7692008-06-02 01:18:21 +0000331
332 void ComputeMaskedBits(Value *V, const APInt &Mask, APInt &KnownZero,
333 APInt &KnownOne, unsigned Depth = 0) const {
334 return llvm::ComputeMaskedBits(V, Mask, KnownZero, KnownOne, TD, Depth);
335 }
336
337 bool MaskedValueIsZero(Value *V, const APInt &Mask,
338 unsigned Depth = 0) const {
339 return llvm::MaskedValueIsZero(V, Mask, TD, Depth);
340 }
341 unsigned ComputeNumSignBits(Value *Op, unsigned Depth = 0) const {
342 return llvm::ComputeNumSignBits(Op, TD, Depth);
343 }
Chris Lattner51ea1272004-02-28 05:22:00 +0000344
Chris Lattner3ac7c262003-08-13 20:16:26 +0000345 private:
Chris Lattnerdfae8be2003-07-24 17:35:25 +0000346 /// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
347 /// InsertBefore instruction. This is specialized a bit to avoid inserting
348 /// casts that are known to not do anything...
349 ///
Reid Spencer13bc5d72006-12-12 09:18:51 +0000350 Value *InsertOperandCastBefore(Instruction::CastOps opcode,
351 Value *V, const Type *DestTy,
Chris Lattnerdfae8be2003-07-24 17:35:25 +0000352 Instruction *InsertBefore);
353
Reid Spencer266e42b2006-12-23 06:05:41 +0000354 /// SimplifyCommutative - This performs a few simplifications for
355 /// commutative operators.
Chris Lattner7fb29e12003-03-11 00:12:48 +0000356 bool SimplifyCommutative(BinaryOperator &I);
Chris Lattnerba1cb382003-09-19 17:17:26 +0000357
Reid Spencer266e42b2006-12-23 06:05:41 +0000358 /// SimplifyCompare - This reorders the operands of a CmpInst to get them in
359 /// most-complex to least-complex order.
360 bool SimplifyCompare(CmpInst &I);
361
Reid Spencer959a21d2007-03-23 21:24:59 +0000362 /// SimplifyDemandedBits - Attempts to replace V with a simpler value based
363 /// on the demanded bits.
Reid Spencer1791f232007-03-12 17:25:59 +0000364 bool SimplifyDemandedBits(Value *V, APInt DemandedMask,
365 APInt& KnownZero, APInt& KnownOne,
366 unsigned Depth = 0);
367
Chris Lattner2deeaea2006-10-05 06:55:50 +0000368 Value *SimplifyDemandedVectorElts(Value *V, uint64_t DemandedElts,
369 uint64_t &UndefElts, unsigned Depth = 0);
370
Chris Lattner6a4adcd2004-09-29 05:07:12 +0000371 // FoldOpIntoPhi - Given a binary operator or cast instruction which has a
372 // PHI node as operand #0, see if we can fold the instruction into the PHI
373 // (which is only possible if all operands to the PHI are constants).
374 Instruction *FoldOpIntoPhi(Instruction &I);
375
Chris Lattner7515cab2004-11-14 19:13:23 +0000376 // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
377 // operator and they all are only used by the PHI, PHI together their
378 // inputs, and do the operation once, to the result of the PHI.
379 Instruction *FoldPHIArgOpIntoPHI(PHINode &PN);
Chris Lattnercadac0c2006-11-01 04:51:18 +0000380 Instruction *FoldPHIArgBinOpIntoPHI(PHINode &PN);
381
382
Zhou Sheng75b871f2007-01-11 12:24:14 +0000383 Instruction *OptAndOp(Instruction *Op, ConstantInt *OpRHS,
384 ConstantInt *AndRHS, BinaryOperator &TheAnd);
Chris Lattneraf517572005-09-18 04:24:45 +0000385
Zhou Sheng75b871f2007-01-11 12:24:14 +0000386 Value *FoldLogicalPlusAnd(Value *LHS, Value *RHS, ConstantInt *Mask,
Chris Lattneraf517572005-09-18 04:24:45 +0000387 bool isSub, Instruction &I);
Chris Lattner6862fbd2004-09-29 17:40:11 +0000388 Instruction *InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
Reid Spencer266e42b2006-12-23 06:05:41 +0000389 bool isSigned, bool Inside, Instruction &IB);
Chris Lattner1db224d2007-04-27 17:44:50 +0000390 Instruction *PromoteCastOfAllocation(BitCastInst &CI, AllocationInst &AI);
Chris Lattnerc482a9e2006-06-15 19:07:26 +0000391 Instruction *MatchBSwap(BinaryOperator &I);
Chris Lattner14a251b2007-04-15 00:07:55 +0000392 bool SimplifyStoreAtEndOfBlock(StoreInst &SI);
Chris Lattner57974c82008-01-13 23:50:23 +0000393 Instruction *SimplifyMemTransfer(MemIntrinsic *MI);
Chris Lattner2dc44262008-04-30 06:39:11 +0000394 Instruction *SimplifyMemSet(MemSetInst *MI);
Chris Lattner57974c82008-01-13 23:50:23 +0000395
Chris Lattnerc482a9e2006-06-15 19:07:26 +0000396
Reid Spencer74a528b2006-12-13 18:21:21 +0000397 Value *EvaluateInDifferentType(Value *V, const Type *Ty, bool isSigned);
Dan Gohman99b7b3f2008-04-10 18:43:06 +0000398
Dan Gohman99b7b3f2008-04-10 18:43:06 +0000399 bool CanEvaluateInDifferentType(Value *V, const IntegerType *Ty,
400 unsigned CastOpc,
401 int &NumCastsRemoved);
402 unsigned GetOrEnforceKnownAlignment(Value *V,
403 unsigned PrefAlign = 0);
Matthijs Kooijmanb2fc72b2008-06-11 14:05:05 +0000404
Chris Lattner260ab202002-04-18 17:39:14 +0000405 };
406}
407
Dan Gohmand78c4002008-05-13 00:00:25 +0000408char InstCombiner::ID = 0;
409static RegisterPass<InstCombiner>
410X("instcombine", "Combine redundant instructions");
411
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000412// getComplexity: Assign a complexity or rank value to LLVM Values...
Chris Lattner81a7a232004-10-16 18:11:37 +0000413// 0 -> undef, 1 -> Const, 2 -> Other, 3 -> Arg, 3 -> Unary, 4 -> OtherInst
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000414static unsigned getComplexity(Value *V) {
415 if (isa<Instruction>(V)) {
416 if (BinaryOperator::isNeg(V) || BinaryOperator::isNot(V))
Chris Lattner81a7a232004-10-16 18:11:37 +0000417 return 3;
418 return 4;
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000419 }
Chris Lattner81a7a232004-10-16 18:11:37 +0000420 if (isa<Argument>(V)) return 3;
421 return isa<Constant>(V) ? (isa<UndefValue>(V) ? 0 : 1) : 2;
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000422}
Chris Lattner260ab202002-04-18 17:39:14 +0000423
Chris Lattner7fb29e12003-03-11 00:12:48 +0000424// isOnlyUse - Return true if this instruction will be deleted if we stop using
425// it.
426static bool isOnlyUse(Value *V) {
Chris Lattnerf95d9b92003-10-15 16:48:29 +0000427 return V->hasOneUse() || isa<Constant>(V);
Chris Lattner7fb29e12003-03-11 00:12:48 +0000428}
429
Chris Lattnere79e8542004-02-23 06:38:22 +0000430// getPromotedType - Return the specified type promoted as it would be to pass
431// though a va_arg area...
432static const Type *getPromotedType(const Type *Ty) {
Reid Spencer7a9c62b2007-01-12 07:05:14 +0000433 if (const IntegerType* ITy = dyn_cast<IntegerType>(Ty)) {
434 if (ITy->getBitWidth() < 32)
435 return Type::Int32Ty;
Chris Lattnerf79577d2007-05-23 01:17:04 +0000436 }
Reid Spencer7a9c62b2007-01-12 07:05:14 +0000437 return Ty;
Chris Lattnere79e8542004-02-23 06:38:22 +0000438}
439
Matthijs Kooijmanf7d3cb52008-10-13 15:17:01 +0000440/// getBitCastOperand - If the specified operand is a CastInst, a constant
441/// expression bitcast, or a GetElementPtrInst with all zero indices, return the
442/// operand value, otherwise return null.
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000443static Value *getBitCastOperand(Value *V) {
444 if (BitCastInst *I = dyn_cast<BitCastInst>(V))
Matthijs Kooijmanf7d3cb52008-10-13 15:17:01 +0000445 // BitCastInst?
Chris Lattner567b81f2005-09-13 00:40:14 +0000446 return I->getOperand(0);
Matthijs Kooijmanf7d3cb52008-10-13 15:17:01 +0000447 else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(V)) {
448 // GetElementPtrInst?
449 if (GEP->hasAllZeroIndices())
450 return GEP->getOperand(0);
451 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V)) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000452 if (CE->getOpcode() == Instruction::BitCast)
Matthijs Kooijmanf7d3cb52008-10-13 15:17:01 +0000453 // BitCast ConstantExp?
Chris Lattner567b81f2005-09-13 00:40:14 +0000454 return CE->getOperand(0);
Matthijs Kooijmanf7d3cb52008-10-13 15:17:01 +0000455 else if (CE->getOpcode() == Instruction::GetElementPtr) {
456 // GetElementPtr ConstantExp?
457 for (User::op_iterator I = CE->op_begin() + 1, E = CE->op_end();
458 I != E; ++I) {
459 ConstantInt *CI = dyn_cast<ConstantInt>(I);
460 if (!CI || !CI->isZero())
461 // Any non-zero indices? Not cast-like.
462 return 0;
463 }
464 // All-zero indices? This is just like casting.
465 return CE->getOperand(0);
466 }
467 }
Chris Lattner567b81f2005-09-13 00:40:14 +0000468 return 0;
469}
470
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000471/// This function is a wrapper around CastInst::isEliminableCastPair. It
472/// simply extracts arguments and returns what that function returns.
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000473static Instruction::CastOps
474isEliminableCastPair(
475 const CastInst *CI, ///< The first cast instruction
476 unsigned opcode, ///< The opcode of the second cast instruction
477 const Type *DstTy, ///< The target type for the second cast instruction
478 TargetData *TD ///< The target data for pointer size
479) {
480
481 const Type *SrcTy = CI->getOperand(0)->getType(); // A from above
482 const Type *MidTy = CI->getType(); // B from above
Chris Lattner1d441ad2006-05-06 09:00:16 +0000483
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000484 // Get the opcodes of the two Cast instructions
485 Instruction::CastOps firstOp = Instruction::CastOps(CI->getOpcode());
486 Instruction::CastOps secondOp = Instruction::CastOps(opcode);
Chris Lattner1d441ad2006-05-06 09:00:16 +0000487
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000488 return Instruction::CastOps(
489 CastInst::isEliminableCastPair(firstOp, secondOp, SrcTy, MidTy,
490 DstTy, TD->getIntPtrType()));
Chris Lattner1d441ad2006-05-06 09:00:16 +0000491}
492
493/// ValueRequiresCast - Return true if the cast from "V to Ty" actually results
494/// in any code being generated. It does not require codegen if V is simple
495/// enough or if the cast can be folded into other casts.
Reid Spencer266e42b2006-12-23 06:05:41 +0000496static bool ValueRequiresCast(Instruction::CastOps opcode, const Value *V,
497 const Type *Ty, TargetData *TD) {
Chris Lattner1d441ad2006-05-06 09:00:16 +0000498 if (V->getType() == Ty || isa<Constant>(V)) return false;
499
Chris Lattner99155be2006-05-25 23:24:33 +0000500 // If this is another cast that can be eliminated, it isn't codegen either.
Chris Lattner1d441ad2006-05-06 09:00:16 +0000501 if (const CastInst *CI = dyn_cast<CastInst>(V))
Reid Spencer266e42b2006-12-23 06:05:41 +0000502 if (isEliminableCastPair(CI, opcode, Ty, TD))
Chris Lattner1d441ad2006-05-06 09:00:16 +0000503 return false;
504 return true;
505}
506
507/// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
508/// InsertBefore instruction. This is specialized a bit to avoid inserting
509/// casts that are known to not do anything...
510///
Reid Spencer13bc5d72006-12-12 09:18:51 +0000511Value *InstCombiner::InsertOperandCastBefore(Instruction::CastOps opcode,
512 Value *V, const Type *DestTy,
Chris Lattner1d441ad2006-05-06 09:00:16 +0000513 Instruction *InsertBefore) {
514 if (V->getType() == DestTy) return V;
515 if (Constant *C = dyn_cast<Constant>(V))
Reid Spencer13bc5d72006-12-12 09:18:51 +0000516 return ConstantExpr::getCast(opcode, C, DestTy);
Chris Lattner1d441ad2006-05-06 09:00:16 +0000517
Reid Spencer13bc5d72006-12-12 09:18:51 +0000518 return InsertCastBefore(opcode, V, DestTy, *InsertBefore);
Chris Lattner1d441ad2006-05-06 09:00:16 +0000519}
520
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000521// SimplifyCommutative - This performs a few simplifications for commutative
522// operators:
Chris Lattner260ab202002-04-18 17:39:14 +0000523//
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000524// 1. Order operands such that they are listed from right (least complex) to
525// left (most complex). This puts constants before unary operators before
526// binary operators.
527//
Chris Lattner7fb29e12003-03-11 00:12:48 +0000528// 2. Transform: (op (op V, C1), C2) ==> (op V, (op C1, C2))
529// 3. Transform: (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000530//
Chris Lattner7fb29e12003-03-11 00:12:48 +0000531bool InstCombiner::SimplifyCommutative(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000532 bool Changed = false;
533 if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1)))
534 Changed = !I.swapOperands();
Misha Brukmanb1c93172005-04-21 23:48:37 +0000535
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000536 if (!I.isAssociative()) return Changed;
537 Instruction::BinaryOps Opcode = I.getOpcode();
Chris Lattner7fb29e12003-03-11 00:12:48 +0000538 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(I.getOperand(0)))
539 if (Op->getOpcode() == Opcode && isa<Constant>(Op->getOperand(1))) {
540 if (isa<Constant>(I.getOperand(1))) {
Chris Lattner34428442003-05-27 16:40:51 +0000541 Constant *Folded = ConstantExpr::get(I.getOpcode(),
542 cast<Constant>(I.getOperand(1)),
543 cast<Constant>(Op->getOperand(1)));
Chris Lattner7fb29e12003-03-11 00:12:48 +0000544 I.setOperand(0, Op->getOperand(0));
545 I.setOperand(1, Folded);
546 return true;
547 } else if (BinaryOperator *Op1=dyn_cast<BinaryOperator>(I.getOperand(1)))
548 if (Op1->getOpcode() == Opcode && isa<Constant>(Op1->getOperand(1)) &&
549 isOnlyUse(Op) && isOnlyUse(Op1)) {
550 Constant *C1 = cast<Constant>(Op->getOperand(1));
551 Constant *C2 = cast<Constant>(Op1->getOperand(1));
552
553 // Fold (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Chris Lattner34428442003-05-27 16:40:51 +0000554 Constant *Folded = ConstantExpr::get(I.getOpcode(), C1, C2);
Gabor Greife1f6e4b2008-05-16 19:29:10 +0000555 Instruction *New = BinaryOperator::Create(Opcode, Op->getOperand(0),
Chris Lattner7fb29e12003-03-11 00:12:48 +0000556 Op1->getOperand(0),
557 Op1->getName(), &I);
Chris Lattnerb15e2b12007-03-02 21:28:56 +0000558 AddToWorkList(New);
Chris Lattner7fb29e12003-03-11 00:12:48 +0000559 I.setOperand(0, New);
560 I.setOperand(1, Folded);
561 return true;
Misha Brukmanb1c93172005-04-21 23:48:37 +0000562 }
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000563 }
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000564 return Changed;
Chris Lattner260ab202002-04-18 17:39:14 +0000565}
Chris Lattnerca081252001-12-14 16:52:21 +0000566
Reid Spencer266e42b2006-12-23 06:05:41 +0000567/// SimplifyCompare - For a CmpInst this function just orders the operands
568/// so that theyare listed from right (least complex) to left (most complex).
569/// This puts constants before unary operators before binary operators.
570bool InstCombiner::SimplifyCompare(CmpInst &I) {
571 if (getComplexity(I.getOperand(0)) >= getComplexity(I.getOperand(1)))
572 return false;
573 I.swapOperands();
574 // Compare instructions are not associative so there's nothing else we can do.
575 return true;
576}
577
Chris Lattnerbb74e222003-03-10 23:06:50 +0000578// dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
579// if the LHS is a constant zero (which is the 'negate' form).
Chris Lattner9fa53de2002-05-06 16:49:18 +0000580//
Chris Lattnerbb74e222003-03-10 23:06:50 +0000581static inline Value *dyn_castNegVal(Value *V) {
582 if (BinaryOperator::isNeg(V))
Chris Lattnerd6f636a2005-04-24 07:30:14 +0000583 return BinaryOperator::getNegArgument(V);
Chris Lattnerbb74e222003-03-10 23:06:50 +0000584
Chris Lattner9ad0d552004-12-14 20:08:06 +0000585 // Constants can be considered to be negated values if they can be folded.
586 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
587 return ConstantExpr::getNeg(C);
Nick Lewycky3bf55122008-05-23 04:54:45 +0000588
589 if (ConstantVector *C = dyn_cast<ConstantVector>(V))
590 if (C->getType()->getElementType()->isInteger())
591 return ConstantExpr::getNeg(C);
592
Chris Lattnerbb74e222003-03-10 23:06:50 +0000593 return 0;
Chris Lattner9fa53de2002-05-06 16:49:18 +0000594}
595
Chris Lattnerbb74e222003-03-10 23:06:50 +0000596static inline Value *dyn_castNotVal(Value *V) {
597 if (BinaryOperator::isNot(V))
Chris Lattnerd6f636a2005-04-24 07:30:14 +0000598 return BinaryOperator::getNotArgument(V);
Chris Lattnerbb74e222003-03-10 23:06:50 +0000599
600 // Constants can be considered to be not'ed values...
Zhou Sheng75b871f2007-01-11 12:24:14 +0000601 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
Zhou Sheng9bc8ab12007-04-02 13:45:30 +0000602 return ConstantInt::get(~C->getValue());
Chris Lattnerbb74e222003-03-10 23:06:50 +0000603 return 0;
604}
605
Chris Lattner7fb29e12003-03-11 00:12:48 +0000606// dyn_castFoldableMul - If this value is a multiply that can be folded into
607// other computations (because it has a constant operand), return the
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000608// non-constant operand of the multiply, and set CST to point to the multiplier.
609// Otherwise, return null.
Chris Lattner7fb29e12003-03-11 00:12:48 +0000610//
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000611static inline Value *dyn_castFoldableMul(Value *V, ConstantInt *&CST) {
Chris Lattner03c49532007-01-15 02:27:26 +0000612 if (V->hasOneUse() && V->getType()->isInteger())
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000613 if (Instruction *I = dyn_cast<Instruction>(V)) {
Chris Lattner7fb29e12003-03-11 00:12:48 +0000614 if (I->getOpcode() == Instruction::Mul)
Chris Lattner970136362004-11-15 05:54:07 +0000615 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1))))
Chris Lattner7fb29e12003-03-11 00:12:48 +0000616 return I->getOperand(0);
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000617 if (I->getOpcode() == Instruction::Shl)
Chris Lattner970136362004-11-15 05:54:07 +0000618 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1)))) {
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000619 // The multiplier is really 1 << CST.
Zhou Sheng4961cf12007-03-29 01:57:21 +0000620 uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
Zhou Shengb25806f2007-03-30 09:29:48 +0000621 uint32_t CSTVal = CST->getLimitedValue(BitWidth);
Zhou Sheng4961cf12007-03-29 01:57:21 +0000622 CST = ConstantInt::get(APInt(BitWidth, 1).shl(CSTVal));
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000623 return I->getOperand(0);
624 }
625 }
Chris Lattner7fb29e12003-03-11 00:12:48 +0000626 return 0;
Chris Lattner3082c5a2003-02-18 19:28:33 +0000627}
Chris Lattner31ae8632002-08-14 17:51:49 +0000628
Chris Lattner0798af32005-01-13 20:14:25 +0000629/// dyn_castGetElementPtr - If this is a getelementptr instruction or constant
630/// expression, return it.
631static User *dyn_castGetElementPtr(Value *V) {
632 if (isa<GetElementPtrInst>(V)) return cast<User>(V);
633 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
634 if (CE->getOpcode() == Instruction::GetElementPtr)
635 return cast<User>(V);
636 return false;
637}
638
Dan Gohman99b7b3f2008-04-10 18:43:06 +0000639/// getOpcode - If this is an Instruction or a ConstantExpr, return the
640/// opcode value. Otherwise return UserOp1.
Dan Gohman86ff8532008-05-29 19:53:46 +0000641static unsigned getOpcode(const Value *V) {
642 if (const Instruction *I = dyn_cast<Instruction>(V))
Dan Gohman99b7b3f2008-04-10 18:43:06 +0000643 return I->getOpcode();
Dan Gohman86ff8532008-05-29 19:53:46 +0000644 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
Dan Gohman99b7b3f2008-04-10 18:43:06 +0000645 return CE->getOpcode();
646 // Use UserOp1 to mean there's no opcode.
647 return Instruction::UserOp1;
648}
649
Reid Spencer80263aa2007-03-25 05:33:51 +0000650/// AddOne - Add one to a ConstantInt
Chris Lattner6862fbd2004-09-29 17:40:11 +0000651static ConstantInt *AddOne(ConstantInt *C) {
Reid Spencer624766f2007-03-25 19:55:33 +0000652 APInt Val(C->getValue());
653 return ConstantInt::get(++Val);
Chris Lattner623826c2004-09-28 21:48:02 +0000654}
Reid Spencer80263aa2007-03-25 05:33:51 +0000655/// SubOne - Subtract one from a ConstantInt
Chris Lattner6862fbd2004-09-29 17:40:11 +0000656static ConstantInt *SubOne(ConstantInt *C) {
Reid Spencer624766f2007-03-25 19:55:33 +0000657 APInt Val(C->getValue());
658 return ConstantInt::get(--Val);
Reid Spencer80263aa2007-03-25 05:33:51 +0000659}
660/// Add - Add two ConstantInts together
661static ConstantInt *Add(ConstantInt *C1, ConstantInt *C2) {
662 return ConstantInt::get(C1->getValue() + C2->getValue());
663}
664/// And - Bitwise AND two ConstantInts together
665static ConstantInt *And(ConstantInt *C1, ConstantInt *C2) {
666 return ConstantInt::get(C1->getValue() & C2->getValue());
667}
668/// Subtract - Subtract one ConstantInt from another
669static ConstantInt *Subtract(ConstantInt *C1, ConstantInt *C2) {
670 return ConstantInt::get(C1->getValue() - C2->getValue());
671}
672/// Multiply - Multiply two ConstantInts together
673static ConstantInt *Multiply(ConstantInt *C1, ConstantInt *C2) {
674 return ConstantInt::get(C1->getValue() * C2->getValue());
Chris Lattner623826c2004-09-28 21:48:02 +0000675}
Nick Lewyckyfefd0202008-02-18 22:48:05 +0000676/// MultiplyOverflows - True if the multiply can not be expressed in an int
677/// this size.
678static bool MultiplyOverflows(ConstantInt *C1, ConstantInt *C2, bool sign) {
679 uint32_t W = C1->getBitWidth();
680 APInt LHSExt = C1->getValue(), RHSExt = C2->getValue();
681 if (sign) {
682 LHSExt.sext(W * 2);
683 RHSExt.sext(W * 2);
684 } else {
685 LHSExt.zext(W * 2);
686 RHSExt.zext(W * 2);
687 }
688
689 APInt MulExt = LHSExt * RHSExt;
690
691 if (sign) {
692 APInt Min = APInt::getSignedMinValue(W).sext(W * 2);
693 APInt Max = APInt::getSignedMaxValue(W).sext(W * 2);
694 return MulExt.slt(Min) || MulExt.sgt(Max);
695 } else
696 return MulExt.ugt(APInt::getLowBitsSet(W * 2, W));
697}
Chris Lattner623826c2004-09-28 21:48:02 +0000698
Reid Spencerbb5741f2007-03-08 01:52:58 +0000699
Chris Lattner0157e7f2006-02-11 09:31:47 +0000700/// ShrinkDemandedConstant - Check to see if the specified operand of the
701/// specified instruction is a constant integer. If so, check to see if there
702/// are any bits set in the constant that are not demanded. If so, shrink the
703/// constant and return true.
704static bool ShrinkDemandedConstant(Instruction *I, unsigned OpNo,
Reid Spencerd9281782007-03-12 17:15:10 +0000705 APInt Demanded) {
706 assert(I && "No instruction?");
707 assert(OpNo < I->getNumOperands() && "Operand index too large");
708
709 // If the operand is not a constant integer, nothing to do.
710 ConstantInt *OpC = dyn_cast<ConstantInt>(I->getOperand(OpNo));
711 if (!OpC) return false;
712
713 // If there are no bits set that aren't demanded, nothing to do.
714 Demanded.zextOrTrunc(OpC->getValue().getBitWidth());
715 if ((~Demanded & OpC->getValue()) == 0)
716 return false;
717
718 // This instruction is producing bits that are not demanded. Shrink the RHS.
719 Demanded &= OpC->getValue();
720 I->setOperand(OpNo, ConstantInt::get(Demanded));
721 return true;
722}
723
Chris Lattneree0f2802006-02-12 02:07:56 +0000724// ComputeSignedMinMaxValuesFromKnownBits - Given a signed integer type and a
725// set of known zero and one bits, compute the maximum and minimum values that
726// could have the specified known zero and known one bits, returning them in
727// min/max.
728static void ComputeSignedMinMaxValuesFromKnownBits(const Type *Ty,
Reid Spencerc3e3b8a2007-03-22 20:36:03 +0000729 const APInt& KnownZero,
730 const APInt& KnownOne,
731 APInt& Min, APInt& Max) {
732 uint32_t BitWidth = cast<IntegerType>(Ty)->getBitWidth();
733 assert(KnownZero.getBitWidth() == BitWidth &&
734 KnownOne.getBitWidth() == BitWidth &&
735 Min.getBitWidth() == BitWidth && Max.getBitWidth() == BitWidth &&
736 "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.");
Reid Spencercd99fbd2007-03-25 04:26:16 +0000737 APInt UnknownBits = ~(KnownZero|KnownOne);
Chris Lattneree0f2802006-02-12 02:07:56 +0000738
Chris Lattneree0f2802006-02-12 02:07:56 +0000739 // The minimum value is when all unknown bits are zeros, EXCEPT for the sign
740 // bit if it is unknown.
741 Min = KnownOne;
742 Max = KnownOne|UnknownBits;
743
Zhou Shengc2d33092007-03-28 05:15:57 +0000744 if (UnknownBits[BitWidth-1]) { // Sign bit is unknown
Zhou Sheng9bc8ab12007-04-02 13:45:30 +0000745 Min.set(BitWidth-1);
746 Max.clear(BitWidth-1);
Chris Lattneree0f2802006-02-12 02:07:56 +0000747 }
Chris Lattneree0f2802006-02-12 02:07:56 +0000748}
749
750// ComputeUnsignedMinMaxValuesFromKnownBits - Given an unsigned integer type and
751// a set of known zero and one bits, compute the maximum and minimum values that
752// could have the specified known zero and known one bits, returning them in
753// min/max.
754static void ComputeUnsignedMinMaxValuesFromKnownBits(const Type *Ty,
Chris Lattnerf0da7972007-08-05 08:47:58 +0000755 const APInt &KnownZero,
756 const APInt &KnownOne,
757 APInt &Min, APInt &Max) {
758 uint32_t BitWidth = cast<IntegerType>(Ty)->getBitWidth(); BitWidth = BitWidth;
Reid Spencerc3e3b8a2007-03-22 20:36:03 +0000759 assert(KnownZero.getBitWidth() == BitWidth &&
760 KnownOne.getBitWidth() == BitWidth &&
761 Min.getBitWidth() == BitWidth && Max.getBitWidth() &&
762 "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.");
Reid Spencercd99fbd2007-03-25 04:26:16 +0000763 APInt UnknownBits = ~(KnownZero|KnownOne);
Chris Lattneree0f2802006-02-12 02:07:56 +0000764
765 // The minimum value is when the unknown bits are all zeros.
766 Min = KnownOne;
767 // The maximum value is when the unknown bits are all ones.
768 Max = KnownOne|UnknownBits;
769}
Chris Lattner0157e7f2006-02-11 09:31:47 +0000770
Reid Spencer1791f232007-03-12 17:25:59 +0000771/// SimplifyDemandedBits - This function attempts to replace V with a simpler
772/// value based on the demanded bits. When this function is called, it is known
773/// that only the bits set in DemandedMask of the result of V are ever used
774/// downstream. Consequently, depending on the mask and V, it may be possible
775/// to replace V with a constant or one of its operands. In such cases, this
776/// function does the replacement and returns true. In all other cases, it
777/// returns false after analyzing the expression and setting KnownOne and known
778/// to be one in the expression. KnownZero contains all the bits that are known
779/// to be zero in the expression. These are provided to potentially allow the
780/// caller (which might recursively be SimplifyDemandedBits itself) to simplify
781/// the expression. KnownOne and KnownZero always follow the invariant that
782/// KnownOne & KnownZero == 0. That is, a bit can't be both 1 and 0. Note that
783/// the bits in KnownOne and KnownZero may only be accurate for those bits set
784/// in DemandedMask. Note also that the bitwidth of V, DemandedMask, KnownZero
785/// and KnownOne must all be the same.
786bool InstCombiner::SimplifyDemandedBits(Value *V, APInt DemandedMask,
787 APInt& KnownZero, APInt& KnownOne,
788 unsigned Depth) {
789 assert(V != 0 && "Null pointer of Value???");
790 assert(Depth <= 6 && "Limit Search Depth");
791 uint32_t BitWidth = DemandedMask.getBitWidth();
792 const IntegerType *VTy = cast<IntegerType>(V->getType());
793 assert(VTy->getBitWidth() == BitWidth &&
794 KnownZero.getBitWidth() == BitWidth &&
795 KnownOne.getBitWidth() == BitWidth &&
796 "Value *V, DemandedMask, KnownZero and KnownOne \
797 must have same BitWidth");
798 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
799 // We know all of the bits for a constant!
800 KnownOne = CI->getValue() & DemandedMask;
801 KnownZero = ~KnownOne & DemandedMask;
802 return false;
803 }
804
Zhou Shengb9128442007-03-14 03:21:24 +0000805 KnownZero.clear();
806 KnownOne.clear();
Reid Spencer1791f232007-03-12 17:25:59 +0000807 if (!V->hasOneUse()) { // Other users may use these bits.
808 if (Depth != 0) { // Not at the root.
809 // Just compute the KnownZero/KnownOne bits to simplify things downstream.
810 ComputeMaskedBits(V, DemandedMask, KnownZero, KnownOne, Depth);
811 return false;
812 }
813 // If this is the root being simplified, allow it to have multiple uses,
814 // just set the DemandedMask to all bits.
815 DemandedMask = APInt::getAllOnesValue(BitWidth);
816 } else if (DemandedMask == 0) { // Not demanding any bits from V.
817 if (V != UndefValue::get(VTy))
818 return UpdateValueUsesWith(V, UndefValue::get(VTy));
819 return false;
820 } else if (Depth == 6) { // Limit search depth.
821 return false;
822 }
823
824 Instruction *I = dyn_cast<Instruction>(V);
825 if (!I) return false; // Only analyze instructions.
826
Reid Spencer1791f232007-03-12 17:25:59 +0000827 APInt LHSKnownZero(BitWidth, 0), LHSKnownOne(BitWidth, 0);
828 APInt &RHSKnownZero = KnownZero, &RHSKnownOne = KnownOne;
829 switch (I->getOpcode()) {
Dan Gohman72ec3f42008-04-28 17:02:21 +0000830 default:
831 ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
832 break;
Reid Spencer1791f232007-03-12 17:25:59 +0000833 case Instruction::And:
834 // If either the LHS or the RHS are Zero, the result is zero.
835 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
836 RHSKnownZero, RHSKnownOne, Depth+1))
837 return true;
838 assert((RHSKnownZero & RHSKnownOne) == 0 &&
839 "Bits known to be one AND zero?");
840
841 // If something is known zero on the RHS, the bits aren't demanded on the
842 // LHS.
843 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask & ~RHSKnownZero,
844 LHSKnownZero, LHSKnownOne, Depth+1))
845 return true;
846 assert((LHSKnownZero & LHSKnownOne) == 0 &&
847 "Bits known to be one AND zero?");
848
849 // If all of the demanded bits are known 1 on one side, return the other.
850 // These bits cannot contribute to the result of the 'and'.
851 if ((DemandedMask & ~LHSKnownZero & RHSKnownOne) ==
852 (DemandedMask & ~LHSKnownZero))
853 return UpdateValueUsesWith(I, I->getOperand(0));
854 if ((DemandedMask & ~RHSKnownZero & LHSKnownOne) ==
855 (DemandedMask & ~RHSKnownZero))
856 return UpdateValueUsesWith(I, I->getOperand(1));
857
858 // If all of the demanded bits in the inputs are known zeros, return zero.
859 if ((DemandedMask & (RHSKnownZero|LHSKnownZero)) == DemandedMask)
860 return UpdateValueUsesWith(I, Constant::getNullValue(VTy));
861
862 // If the RHS is a constant, see if we can simplify it.
863 if (ShrinkDemandedConstant(I, 1, DemandedMask & ~LHSKnownZero))
864 return UpdateValueUsesWith(I, I);
865
866 // Output known-1 bits are only known if set in both the LHS & RHS.
867 RHSKnownOne &= LHSKnownOne;
868 // Output known-0 are known to be clear if zero in either the LHS | RHS.
869 RHSKnownZero |= LHSKnownZero;
870 break;
871 case Instruction::Or:
872 // If either the LHS or the RHS are One, the result is One.
873 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
874 RHSKnownZero, RHSKnownOne, Depth+1))
875 return true;
876 assert((RHSKnownZero & RHSKnownOne) == 0 &&
877 "Bits known to be one AND zero?");
878 // If something is known one on the RHS, the bits aren't demanded on the
879 // LHS.
880 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask & ~RHSKnownOne,
881 LHSKnownZero, LHSKnownOne, Depth+1))
882 return true;
883 assert((LHSKnownZero & LHSKnownOne) == 0 &&
884 "Bits known to be one AND zero?");
885
886 // If all of the demanded bits are known zero on one side, return the other.
887 // These bits cannot contribute to the result of the 'or'.
888 if ((DemandedMask & ~LHSKnownOne & RHSKnownZero) ==
889 (DemandedMask & ~LHSKnownOne))
890 return UpdateValueUsesWith(I, I->getOperand(0));
891 if ((DemandedMask & ~RHSKnownOne & LHSKnownZero) ==
892 (DemandedMask & ~RHSKnownOne))
893 return UpdateValueUsesWith(I, I->getOperand(1));
894
895 // If all of the potentially set bits on one side are known to be set on
896 // the other side, just use the 'other' side.
897 if ((DemandedMask & (~RHSKnownZero) & LHSKnownOne) ==
898 (DemandedMask & (~RHSKnownZero)))
899 return UpdateValueUsesWith(I, I->getOperand(0));
900 if ((DemandedMask & (~LHSKnownZero) & RHSKnownOne) ==
901 (DemandedMask & (~LHSKnownZero)))
902 return UpdateValueUsesWith(I, I->getOperand(1));
903
904 // If the RHS is a constant, see if we can simplify it.
905 if (ShrinkDemandedConstant(I, 1, DemandedMask))
906 return UpdateValueUsesWith(I, I);
907
908 // Output known-0 bits are only known if clear in both the LHS & RHS.
909 RHSKnownZero &= LHSKnownZero;
910 // Output known-1 are known to be set if set in either the LHS | RHS.
911 RHSKnownOne |= LHSKnownOne;
912 break;
913 case Instruction::Xor: {
914 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
915 RHSKnownZero, RHSKnownOne, Depth+1))
916 return true;
917 assert((RHSKnownZero & RHSKnownOne) == 0 &&
918 "Bits known to be one AND zero?");
919 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
920 LHSKnownZero, LHSKnownOne, Depth+1))
921 return true;
922 assert((LHSKnownZero & LHSKnownOne) == 0 &&
923 "Bits known to be one AND zero?");
924
925 // If all of the demanded bits are known zero on one side, return the other.
926 // These bits cannot contribute to the result of the 'xor'.
927 if ((DemandedMask & RHSKnownZero) == DemandedMask)
928 return UpdateValueUsesWith(I, I->getOperand(0));
929 if ((DemandedMask & LHSKnownZero) == DemandedMask)
930 return UpdateValueUsesWith(I, I->getOperand(1));
931
932 // Output known-0 bits are known if clear or set in both the LHS & RHS.
933 APInt KnownZeroOut = (RHSKnownZero & LHSKnownZero) |
934 (RHSKnownOne & LHSKnownOne);
935 // Output known-1 are known to be set if set in only one of the LHS, RHS.
936 APInt KnownOneOut = (RHSKnownZero & LHSKnownOne) |
937 (RHSKnownOne & LHSKnownZero);
938
939 // If all of the demanded bits are known to be zero on one side or the
940 // other, turn this into an *inclusive* or.
941 // e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
942 if ((DemandedMask & ~RHSKnownZero & ~LHSKnownZero) == 0) {
943 Instruction *Or =
Gabor Greife1f6e4b2008-05-16 19:29:10 +0000944 BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1),
Reid Spencer1791f232007-03-12 17:25:59 +0000945 I->getName());
946 InsertNewInstBefore(Or, *I);
947 return UpdateValueUsesWith(I, Or);
948 }
949
950 // If all of the demanded bits on one side are known, and all of the set
951 // bits on that side are also known to be set on the other side, turn this
952 // into an AND, as we know the bits will be cleared.
953 // e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
954 if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask) {
955 // all known
956 if ((RHSKnownOne & LHSKnownOne) == RHSKnownOne) {
957 Constant *AndC = ConstantInt::get(~RHSKnownOne & DemandedMask);
958 Instruction *And =
Gabor Greife1f6e4b2008-05-16 19:29:10 +0000959 BinaryOperator::CreateAnd(I->getOperand(0), AndC, "tmp");
Reid Spencer1791f232007-03-12 17:25:59 +0000960 InsertNewInstBefore(And, *I);
961 return UpdateValueUsesWith(I, And);
962 }
963 }
964
965 // If the RHS is a constant, see if we can simplify it.
966 // FIXME: for XOR, we prefer to force bits to 1 if they will make a -1.
967 if (ShrinkDemandedConstant(I, 1, DemandedMask))
968 return UpdateValueUsesWith(I, I);
969
970 RHSKnownZero = KnownZeroOut;
971 RHSKnownOne = KnownOneOut;
972 break;
973 }
974 case Instruction::Select:
975 if (SimplifyDemandedBits(I->getOperand(2), DemandedMask,
976 RHSKnownZero, RHSKnownOne, Depth+1))
977 return true;
978 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
979 LHSKnownZero, LHSKnownOne, Depth+1))
980 return true;
981 assert((RHSKnownZero & RHSKnownOne) == 0 &&
982 "Bits known to be one AND zero?");
983 assert((LHSKnownZero & LHSKnownOne) == 0 &&
984 "Bits known to be one AND zero?");
985
986 // If the operands are constants, see if we can simplify them.
987 if (ShrinkDemandedConstant(I, 1, DemandedMask))
988 return UpdateValueUsesWith(I, I);
989 if (ShrinkDemandedConstant(I, 2, DemandedMask))
990 return UpdateValueUsesWith(I, I);
991
992 // Only known if known in both the LHS and RHS.
993 RHSKnownOne &= LHSKnownOne;
994 RHSKnownZero &= LHSKnownZero;
995 break;
996 case Instruction::Trunc: {
997 uint32_t truncBf =
998 cast<IntegerType>(I->getOperand(0)->getType())->getBitWidth();
Zhou Shenga4475572007-03-29 02:26:30 +0000999 DemandedMask.zext(truncBf);
1000 RHSKnownZero.zext(truncBf);
1001 RHSKnownOne.zext(truncBf);
1002 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1003 RHSKnownZero, RHSKnownOne, Depth+1))
Reid Spencer1791f232007-03-12 17:25:59 +00001004 return true;
1005 DemandedMask.trunc(BitWidth);
1006 RHSKnownZero.trunc(BitWidth);
1007 RHSKnownOne.trunc(BitWidth);
1008 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1009 "Bits known to be one AND zero?");
1010 break;
1011 }
1012 case Instruction::BitCast:
1013 if (!I->getOperand(0)->getType()->isInteger())
1014 return false;
1015
1016 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1017 RHSKnownZero, RHSKnownOne, Depth+1))
1018 return true;
1019 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1020 "Bits known to be one AND zero?");
1021 break;
1022 case Instruction::ZExt: {
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
Zhou Sheng444af492007-03-29 04:45:55 +00001027 DemandedMask.trunc(SrcBitWidth);
1028 RHSKnownZero.trunc(SrcBitWidth);
1029 RHSKnownOne.trunc(SrcBitWidth);
Zhou Shenga4475572007-03-29 02:26:30 +00001030 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1031 RHSKnownZero, RHSKnownOne, Depth+1))
Reid Spencer1791f232007-03-12 17:25:59 +00001032 return true;
1033 DemandedMask.zext(BitWidth);
1034 RHSKnownZero.zext(BitWidth);
1035 RHSKnownOne.zext(BitWidth);
1036 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1037 "Bits known to be one AND zero?");
1038 // The top bits are known to be zero.
Zhou Shenga4475572007-03-29 02:26:30 +00001039 RHSKnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
Reid Spencer1791f232007-03-12 17:25:59 +00001040 break;
1041 }
1042 case Instruction::SExt: {
1043 // Compute the bits in the result that are not present in the input.
1044 const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
Reid Spencercd99fbd2007-03-25 04:26:16 +00001045 uint32_t SrcBitWidth = SrcTy->getBitWidth();
Reid Spencer1791f232007-03-12 17:25:59 +00001046
Reid Spencer1791f232007-03-12 17:25:59 +00001047 APInt InputDemandedBits = DemandedMask &
Zhou Shenga4475572007-03-29 02:26:30 +00001048 APInt::getLowBitsSet(BitWidth, SrcBitWidth);
Reid Spencer1791f232007-03-12 17:25:59 +00001049
Zhou Shenga4475572007-03-29 02:26:30 +00001050 APInt NewBits(APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth));
Reid Spencer1791f232007-03-12 17:25:59 +00001051 // If any of the sign extended bits are demanded, we know that the sign
1052 // bit is demanded.
1053 if ((NewBits & DemandedMask) != 0)
Zhou Sheng9bc8ab12007-04-02 13:45:30 +00001054 InputDemandedBits.set(SrcBitWidth-1);
Reid Spencer1791f232007-03-12 17:25:59 +00001055
Zhou Sheng444af492007-03-29 04:45:55 +00001056 InputDemandedBits.trunc(SrcBitWidth);
1057 RHSKnownZero.trunc(SrcBitWidth);
1058 RHSKnownOne.trunc(SrcBitWidth);
Zhou Shenga4475572007-03-29 02:26:30 +00001059 if (SimplifyDemandedBits(I->getOperand(0), InputDemandedBits,
1060 RHSKnownZero, RHSKnownOne, Depth+1))
Reid Spencer1791f232007-03-12 17:25:59 +00001061 return true;
1062 InputDemandedBits.zext(BitWidth);
1063 RHSKnownZero.zext(BitWidth);
1064 RHSKnownOne.zext(BitWidth);
1065 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1066 "Bits known to be one AND zero?");
1067
1068 // If the sign bit of the input is known set or clear, then we know the
1069 // top bits of the result.
1070
1071 // If the input sign bit is known zero, or if the NewBits are not demanded
1072 // convert this into a zero extension.
Zhou Shenga4475572007-03-29 02:26:30 +00001073 if (RHSKnownZero[SrcBitWidth-1] || (NewBits & ~DemandedMask) == NewBits)
Reid Spencer1791f232007-03-12 17:25:59 +00001074 {
1075 // Convert to ZExt cast
1076 CastInst *NewCast = new ZExtInst(I->getOperand(0), VTy, I->getName(), I);
1077 return UpdateValueUsesWith(I, NewCast);
Zhou Shenga4475572007-03-29 02:26:30 +00001078 } else if (RHSKnownOne[SrcBitWidth-1]) { // Input sign bit known set
Reid Spencer1791f232007-03-12 17:25:59 +00001079 RHSKnownOne |= NewBits;
Reid Spencer1791f232007-03-12 17:25:59 +00001080 }
1081 break;
1082 }
1083 case Instruction::Add: {
1084 // Figure out what the input bits are. If the top bits of the and result
1085 // are not demanded, then the add doesn't demand them from its input
1086 // either.
Reid Spencer52830322007-03-25 21:11:44 +00001087 uint32_t NLZ = DemandedMask.countLeadingZeros();
Reid Spencer1791f232007-03-12 17:25:59 +00001088
1089 // If there is a constant on the RHS, there are a variety of xformations
1090 // we can do.
1091 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
1092 // If null, this should be simplified elsewhere. Some of the xforms here
1093 // won't work if the RHS is zero.
1094 if (RHS->isZero())
1095 break;
1096
1097 // If the top bit of the output is demanded, demand everything from the
1098 // input. Otherwise, we demand all the input bits except NLZ top bits.
Zhou Shenga4475572007-03-29 02:26:30 +00001099 APInt InDemandedBits(APInt::getLowBitsSet(BitWidth, BitWidth - NLZ));
Reid Spencer1791f232007-03-12 17:25:59 +00001100
1101 // Find information about known zero/one bits in the input.
1102 if (SimplifyDemandedBits(I->getOperand(0), InDemandedBits,
1103 LHSKnownZero, LHSKnownOne, Depth+1))
1104 return true;
1105
1106 // If the RHS of the add has bits set that can't affect the input, reduce
1107 // the constant.
1108 if (ShrinkDemandedConstant(I, 1, InDemandedBits))
1109 return UpdateValueUsesWith(I, I);
1110
1111 // Avoid excess work.
1112 if (LHSKnownZero == 0 && LHSKnownOne == 0)
1113 break;
1114
1115 // Turn it into OR if input bits are zero.
1116 if ((LHSKnownZero & RHS->getValue()) == RHS->getValue()) {
1117 Instruction *Or =
Gabor Greife1f6e4b2008-05-16 19:29:10 +00001118 BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1),
Reid Spencer1791f232007-03-12 17:25:59 +00001119 I->getName());
1120 InsertNewInstBefore(Or, *I);
1121 return UpdateValueUsesWith(I, Or);
1122 }
1123
1124 // We can say something about the output known-zero and known-one bits,
1125 // depending on potential carries from the input constant and the
1126 // unknowns. For example if the LHS is known to have at most the 0x0F0F0
1127 // bits set and the RHS constant is 0x01001, then we know we have a known
1128 // one mask of 0x00001 and a known zero mask of 0xE0F0E.
1129
1130 // To compute this, we first compute the potential carry bits. These are
1131 // the bits which may be modified. I'm not aware of a better way to do
1132 // this scan.
Zhou Sheng4f164022007-03-31 02:38:39 +00001133 const APInt& RHSVal = RHS->getValue();
1134 APInt CarryBits((~LHSKnownZero + RHSVal) ^ (~LHSKnownZero ^ RHSVal));
Reid Spencer1791f232007-03-12 17:25:59 +00001135
1136 // Now that we know which bits have carries, compute the known-1/0 sets.
1137
1138 // Bits are known one if they are known zero in one operand and one in the
1139 // other, and there is no input carry.
1140 RHSKnownOne = ((LHSKnownZero & RHSVal) |
1141 (LHSKnownOne & ~RHSVal)) & ~CarryBits;
1142
1143 // Bits are known zero if they are known zero in both operands and there
1144 // is no input carry.
1145 RHSKnownZero = LHSKnownZero & ~RHSVal & ~CarryBits;
1146 } else {
1147 // If the high-bits of this ADD are not demanded, then it does not demand
1148 // the high bits of its LHS or RHS.
Zhou Shenga4475572007-03-29 02:26:30 +00001149 if (DemandedMask[BitWidth-1] == 0) {
Reid Spencer1791f232007-03-12 17:25:59 +00001150 // Right fill the mask of bits for this ADD to demand the most
1151 // significant bit and all those below it.
Zhou Shenga4475572007-03-29 02:26:30 +00001152 APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
Reid Spencer1791f232007-03-12 17:25:59 +00001153 if (SimplifyDemandedBits(I->getOperand(0), DemandedFromOps,
1154 LHSKnownZero, LHSKnownOne, Depth+1))
1155 return true;
1156 if (SimplifyDemandedBits(I->getOperand(1), DemandedFromOps,
1157 LHSKnownZero, LHSKnownOne, Depth+1))
1158 return true;
1159 }
1160 }
1161 break;
1162 }
1163 case Instruction::Sub:
1164 // If the high-bits of this SUB are not demanded, then it does not demand
1165 // the high bits of its LHS or RHS.
Zhou Shenga4475572007-03-29 02:26:30 +00001166 if (DemandedMask[BitWidth-1] == 0) {
Reid Spencer1791f232007-03-12 17:25:59 +00001167 // Right fill the mask of bits for this SUB to demand the most
1168 // significant bit and all those below it.
Zhou Sheng56cda952007-04-02 08:20:41 +00001169 uint32_t NLZ = DemandedMask.countLeadingZeros();
Zhou Shenga4475572007-03-29 02:26:30 +00001170 APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
Reid Spencer1791f232007-03-12 17:25:59 +00001171 if (SimplifyDemandedBits(I->getOperand(0), DemandedFromOps,
1172 LHSKnownZero, LHSKnownOne, Depth+1))
1173 return true;
1174 if (SimplifyDemandedBits(I->getOperand(1), DemandedFromOps,
1175 LHSKnownZero, LHSKnownOne, Depth+1))
1176 return true;
1177 }
Dan Gohman72ec3f42008-04-28 17:02:21 +00001178 // Otherwise just hand the sub off to ComputeMaskedBits to fill in
1179 // the known zeros and ones.
1180 ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
Reid Spencer1791f232007-03-12 17:25:59 +00001181 break;
1182 case Instruction::Shl:
1183 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Shengb25806f2007-03-30 09:29:48 +00001184 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
Zhou Shenga4475572007-03-29 02:26:30 +00001185 APInt DemandedMaskIn(DemandedMask.lshr(ShiftAmt));
1186 if (SimplifyDemandedBits(I->getOperand(0), DemandedMaskIn,
Reid Spencer1791f232007-03-12 17:25:59 +00001187 RHSKnownZero, RHSKnownOne, Depth+1))
1188 return true;
1189 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1190 "Bits known to be one AND zero?");
1191 RHSKnownZero <<= ShiftAmt;
1192 RHSKnownOne <<= ShiftAmt;
1193 // low bits known zero.
Zhou Shengd8c645b2007-03-14 09:07:33 +00001194 if (ShiftAmt)
Zhou Sheng23f7a1c2007-03-28 15:02:20 +00001195 RHSKnownZero |= APInt::getLowBitsSet(BitWidth, ShiftAmt);
Reid Spencer1791f232007-03-12 17:25:59 +00001196 }
1197 break;
1198 case Instruction::LShr:
1199 // For a logical shift right
1200 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Shengb25806f2007-03-30 09:29:48 +00001201 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
Reid Spencer1791f232007-03-12 17:25:59 +00001202
Reid Spencer1791f232007-03-12 17:25:59 +00001203 // Unsigned shift right.
Zhou Shenga4475572007-03-29 02:26:30 +00001204 APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
1205 if (SimplifyDemandedBits(I->getOperand(0), DemandedMaskIn,
Reid Spencer1791f232007-03-12 17:25:59 +00001206 RHSKnownZero, RHSKnownOne, Depth+1))
1207 return true;
1208 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1209 "Bits known to be one AND zero?");
Reid Spencer1791f232007-03-12 17:25:59 +00001210 RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1211 RHSKnownOne = APIntOps::lshr(RHSKnownOne, ShiftAmt);
Zhou Shengd8c645b2007-03-14 09:07:33 +00001212 if (ShiftAmt) {
1213 // Compute the new bits that are at the top now.
Zhou Shenga4475572007-03-29 02:26:30 +00001214 APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
Zhou Shengd8c645b2007-03-14 09:07:33 +00001215 RHSKnownZero |= HighBits; // high bits known zero.
1216 }
Reid Spencer1791f232007-03-12 17:25:59 +00001217 }
1218 break;
1219 case Instruction::AShr:
1220 // If this is an arithmetic shift right and only the low-bit is set, we can
1221 // always convert this into a logical shr, even if the shift amount is
1222 // variable. The low bit of the shift cannot be an input sign bit unless
1223 // the shift amount is >= the size of the datatype, which is undefined.
1224 if (DemandedMask == 1) {
1225 // Perform the logical shift right.
Gabor Greife1f6e4b2008-05-16 19:29:10 +00001226 Value *NewVal = BinaryOperator::CreateLShr(
Reid Spencer1791f232007-03-12 17:25:59 +00001227 I->getOperand(0), I->getOperand(1), I->getName());
1228 InsertNewInstBefore(cast<Instruction>(NewVal), *I);
1229 return UpdateValueUsesWith(I, NewVal);
1230 }
Chris Lattnerd4fef8d2007-07-15 20:54:51 +00001231
1232 // If the sign bit is the only bit demanded by this ashr, then there is no
1233 // need to do it, the shift doesn't change the high bit.
1234 if (DemandedMask.isSignBit())
1235 return UpdateValueUsesWith(I, I->getOperand(0));
Reid Spencer1791f232007-03-12 17:25:59 +00001236
1237 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Shengfd28a332007-03-30 17:20:39 +00001238 uint32_t ShiftAmt = SA->getLimitedValue(BitWidth);
Reid Spencer1791f232007-03-12 17:25:59 +00001239
Reid Spencer1791f232007-03-12 17:25:59 +00001240 // Signed shift right.
Zhou Shenga4475572007-03-29 02:26:30 +00001241 APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
Lauro Ramos Venancio368e8872007-06-06 17:08:48 +00001242 // If any of the "high bits" are demanded, we should set the sign bit as
1243 // demanded.
1244 if (DemandedMask.countLeadingZeros() <= ShiftAmt)
1245 DemandedMaskIn.set(BitWidth-1);
Reid Spencer1791f232007-03-12 17:25:59 +00001246 if (SimplifyDemandedBits(I->getOperand(0),
Zhou Shenga4475572007-03-29 02:26:30 +00001247 DemandedMaskIn,
Reid Spencer1791f232007-03-12 17:25:59 +00001248 RHSKnownZero, RHSKnownOne, Depth+1))
1249 return true;
1250 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1251 "Bits known to be one AND zero?");
1252 // Compute the new bits that are at the top now.
Zhou Shenga4475572007-03-29 02:26:30 +00001253 APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
Reid Spencer1791f232007-03-12 17:25:59 +00001254 RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1255 RHSKnownOne = APIntOps::lshr(RHSKnownOne, ShiftAmt);
1256
1257 // Handle the sign bits.
1258 APInt SignBit(APInt::getSignBit(BitWidth));
1259 // Adjust to where it is now in the mask.
1260 SignBit = APIntOps::lshr(SignBit, ShiftAmt);
1261
1262 // If the input sign bit is known to be zero, or if none of the top bits
1263 // are demanded, turn this into an unsigned shift right.
Zhou Sheng1152ca92008-06-06 08:32:05 +00001264 if (BitWidth <= ShiftAmt || RHSKnownZero[BitWidth-ShiftAmt-1] ||
Reid Spencer1791f232007-03-12 17:25:59 +00001265 (HighBits & ~DemandedMask) == HighBits) {
1266 // Perform the logical shift right.
Gabor Greife1f6e4b2008-05-16 19:29:10 +00001267 Value *NewVal = BinaryOperator::CreateLShr(
Reid Spencer1791f232007-03-12 17:25:59 +00001268 I->getOperand(0), SA, I->getName());
1269 InsertNewInstBefore(cast<Instruction>(NewVal), *I);
1270 return UpdateValueUsesWith(I, NewVal);
1271 } else if ((RHSKnownOne & SignBit) != 0) { // New bits are known one.
1272 RHSKnownOne |= HighBits;
1273 }
1274 }
1275 break;
Nick Lewyckyd0b62a12008-03-06 06:48:30 +00001276 case Instruction::SRem:
1277 if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
Nick Lewycky8d8acf32008-11-02 02:41:50 +00001278 APInt RA = Rem->getValue().abs();
1279 if (RA.isPowerOf2()) {
Nick Lewyckyf76aa232008-07-12 05:04:38 +00001280 if (DemandedMask.ule(RA)) // srem won't affect demanded bits
1281 return UpdateValueUsesWith(I, I->getOperand(0));
1282
Nick Lewycky8d8acf32008-11-02 02:41:50 +00001283 APInt LowBits = RA - 1;
Nick Lewyckyd0b62a12008-03-06 06:48:30 +00001284 APInt Mask2 = LowBits | APInt::getSignBit(BitWidth);
1285 if (SimplifyDemandedBits(I->getOperand(0), Mask2,
1286 LHSKnownZero, LHSKnownOne, Depth+1))
1287 return true;
1288
1289 if (LHSKnownZero[BitWidth-1] || ((LHSKnownZero & LowBits) == LowBits))
1290 LHSKnownZero |= ~LowBits;
Nick Lewyckyd0b62a12008-03-06 06:48:30 +00001291
1292 KnownZero |= LHSKnownZero & DemandedMask;
Nick Lewyckyd0b62a12008-03-06 06:48:30 +00001293
1294 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
1295 }
1296 }
1297 break;
Dan Gohman72ec3f42008-04-28 17:02:21 +00001298 case Instruction::URem: {
Dan Gohman72ec3f42008-04-28 17:02:21 +00001299 APInt KnownZero2(BitWidth, 0), KnownOne2(BitWidth, 0);
1300 APInt AllOnes = APInt::getAllOnesValue(BitWidth);
Dan Gohman4be6ae42008-05-01 19:13:24 +00001301 if (SimplifyDemandedBits(I->getOperand(0), AllOnes,
1302 KnownZero2, KnownOne2, Depth+1))
1303 return true;
1304
Dan Gohman72ec3f42008-04-28 17:02:21 +00001305 uint32_t Leaders = KnownZero2.countLeadingOnes();
Dan Gohman4be6ae42008-05-01 19:13:24 +00001306 if (SimplifyDemandedBits(I->getOperand(1), AllOnes,
Dan Gohman72ec3f42008-04-28 17:02:21 +00001307 KnownZero2, KnownOne2, Depth+1))
1308 return true;
1309
1310 Leaders = std::max(Leaders,
1311 KnownZero2.countLeadingOnes());
1312 KnownZero = APInt::getHighBitsSet(BitWidth, Leaders) & DemandedMask;
Nick Lewyckyd0b62a12008-03-06 06:48:30 +00001313 break;
Reid Spencer1791f232007-03-12 17:25:59 +00001314 }
Chris Lattneref36dcd2008-06-18 04:33:20 +00001315 case Instruction::Call:
1316 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
1317 switch (II->getIntrinsicID()) {
1318 default: break;
1319 case Intrinsic::bswap: {
1320 // If the only bits demanded come from one byte of the bswap result,
1321 // just shift the input byte into position to eliminate the bswap.
1322 unsigned NLZ = DemandedMask.countLeadingZeros();
1323 unsigned NTZ = DemandedMask.countTrailingZeros();
1324
1325 // Round NTZ down to the next byte. If we have 11 trailing zeros, then
1326 // we need all the bits down to bit 8. Likewise, round NLZ. If we
1327 // have 14 leading zeros, round to 8.
1328 NLZ &= ~7;
1329 NTZ &= ~7;
1330 // If we need exactly one byte, we can do this transformation.
1331 if (BitWidth-NLZ-NTZ == 8) {
1332 unsigned ResultBit = NTZ;
1333 unsigned InputBit = BitWidth-NTZ-8;
1334
1335 // Replace this with either a left or right shift to get the byte into
1336 // the right place.
1337 Instruction *NewVal;
1338 if (InputBit > ResultBit)
1339 NewVal = BinaryOperator::CreateLShr(I->getOperand(1),
1340 ConstantInt::get(I->getType(), InputBit-ResultBit));
1341 else
1342 NewVal = BinaryOperator::CreateShl(I->getOperand(1),
1343 ConstantInt::get(I->getType(), ResultBit-InputBit));
1344 NewVal->takeName(I);
1345 InsertNewInstBefore(NewVal, *I);
1346 return UpdateValueUsesWith(I, NewVal);
1347 }
1348
1349 // TODO: Could compute known zero/one bits based on the input.
1350 break;
1351 }
1352 }
1353 }
Chris Lattner78119b42008-06-18 18:11:55 +00001354 ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
Chris Lattneref36dcd2008-06-18 04:33:20 +00001355 break;
Dan Gohman72ec3f42008-04-28 17:02:21 +00001356 }
Reid Spencer1791f232007-03-12 17:25:59 +00001357
1358 // If the client is only demanding bits that we know, return the known
1359 // constant.
1360 if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask)
1361 return UpdateValueUsesWith(I, ConstantInt::get(RHSKnownOne));
1362 return false;
1363}
1364
Chris Lattner2deeaea2006-10-05 06:55:50 +00001365
Mon P Wang25f01062008-11-10 04:46:22 +00001366/// SimplifyDemandedVectorElts - The specified value produces a vector with
Chris Lattner2deeaea2006-10-05 06:55:50 +00001367/// 64 or fewer elements. DemandedElts contains the set of elements that are
1368/// actually used by the caller. This method analyzes which elements of the
1369/// operand are undef and returns that information in UndefElts.
1370///
1371/// If the information about demanded elements can be used to simplify the
1372/// operation, the operation is simplified, then the resultant value is
1373/// returned. This returns null if no change was made.
1374Value *InstCombiner::SimplifyDemandedVectorElts(Value *V, uint64_t DemandedElts,
1375 uint64_t &UndefElts,
1376 unsigned Depth) {
Reid Spencerd84d35b2007-02-15 02:26:10 +00001377 unsigned VWidth = cast<VectorType>(V->getType())->getNumElements();
Chris Lattner2deeaea2006-10-05 06:55:50 +00001378 assert(VWidth <= 64 && "Vector too wide to analyze!");
1379 uint64_t EltMask = ~0ULL >> (64-VWidth);
Dan Gohman86fb5b42008-09-09 18:11:14 +00001380 assert((DemandedElts & ~EltMask) == 0 && "Invalid DemandedElts!");
Chris Lattner2deeaea2006-10-05 06:55:50 +00001381
1382 if (isa<UndefValue>(V)) {
1383 // If the entire vector is undefined, just return this info.
1384 UndefElts = EltMask;
1385 return 0;
1386 } else if (DemandedElts == 0) { // If nothing is demanded, provide undef.
1387 UndefElts = EltMask;
1388 return UndefValue::get(V->getType());
1389 }
Mon P Wang25f01062008-11-10 04:46:22 +00001390
Chris Lattner2deeaea2006-10-05 06:55:50 +00001391 UndefElts = 0;
Reid Spencerd84d35b2007-02-15 02:26:10 +00001392 if (ConstantVector *CP = dyn_cast<ConstantVector>(V)) {
1393 const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
Chris Lattner2deeaea2006-10-05 06:55:50 +00001394 Constant *Undef = UndefValue::get(EltTy);
1395
1396 std::vector<Constant*> Elts;
1397 for (unsigned i = 0; i != VWidth; ++i)
1398 if (!(DemandedElts & (1ULL << i))) { // If not demanded, set to undef.
1399 Elts.push_back(Undef);
1400 UndefElts |= (1ULL << i);
1401 } else if (isa<UndefValue>(CP->getOperand(i))) { // Already undef.
1402 Elts.push_back(Undef);
1403 UndefElts |= (1ULL << i);
1404 } else { // Otherwise, defined.
1405 Elts.push_back(CP->getOperand(i));
1406 }
Mon P Wang25f01062008-11-10 04:46:22 +00001407
Chris Lattner2deeaea2006-10-05 06:55:50 +00001408 // If we changed the constant, return it.
Reid Spencerd84d35b2007-02-15 02:26:10 +00001409 Constant *NewCP = ConstantVector::get(Elts);
Chris Lattner2deeaea2006-10-05 06:55:50 +00001410 return NewCP != CP ? NewCP : 0;
1411 } else if (isa<ConstantAggregateZero>(V)) {
Reid Spencerd84d35b2007-02-15 02:26:10 +00001412 // Simplify the CAZ to a ConstantVector where the non-demanded elements are
Chris Lattner2deeaea2006-10-05 06:55:50 +00001413 // set to undef.
Mon P Wang5ca2ec62008-11-06 22:52:21 +00001414
1415 // Check if this is identity. If so, return 0 since we are not simplifying
1416 // anything.
1417 if (DemandedElts == ((1ULL << VWidth) -1))
1418 return 0;
1419
Reid Spencerd84d35b2007-02-15 02:26:10 +00001420 const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
Chris Lattner2deeaea2006-10-05 06:55:50 +00001421 Constant *Zero = Constant::getNullValue(EltTy);
1422 Constant *Undef = UndefValue::get(EltTy);
1423 std::vector<Constant*> Elts;
1424 for (unsigned i = 0; i != VWidth; ++i)
1425 Elts.push_back((DemandedElts & (1ULL << i)) ? Zero : Undef);
1426 UndefElts = DemandedElts ^ EltMask;
Reid Spencerd84d35b2007-02-15 02:26:10 +00001427 return ConstantVector::get(Elts);
Chris Lattner2deeaea2006-10-05 06:55:50 +00001428 }
1429
Dan Gohman86fb5b42008-09-09 18:11:14 +00001430 // Limit search depth.
1431 if (Depth == 10)
1432 return false;
1433
1434 // If multiple users are using the root value, procede with
1435 // simplification conservatively assuming that all elements
1436 // are needed.
1437 if (!V->hasOneUse()) {
1438 // Quit if we find multiple users of a non-root value though.
1439 // They'll be handled when it's their turn to be visited by
1440 // the main instcombine process.
1441 if (Depth != 0)
Chris Lattner2deeaea2006-10-05 06:55:50 +00001442 // TODO: Just compute the UndefElts information recursively.
1443 return false;
Dan Gohman86fb5b42008-09-09 18:11:14 +00001444
1445 // Conservatively assume that all elements are needed.
1446 DemandedElts = EltMask;
Chris Lattner2deeaea2006-10-05 06:55:50 +00001447 }
1448
1449 Instruction *I = dyn_cast<Instruction>(V);
1450 if (!I) return false; // Only analyze instructions.
1451
1452 bool MadeChange = false;
1453 uint64_t UndefElts2;
1454 Value *TmpV;
1455 switch (I->getOpcode()) {
1456 default: break;
1457
1458 case Instruction::InsertElement: {
1459 // If this is a variable index, we don't know which element it overwrites.
1460 // demand exactly the same input as we produce.
Reid Spencere0fc4df2006-10-20 07:07:24 +00001461 ConstantInt *Idx = dyn_cast<ConstantInt>(I->getOperand(2));
Chris Lattner2deeaea2006-10-05 06:55:50 +00001462 if (Idx == 0) {
1463 // Note that we can't propagate undef elt info, because we don't know
1464 // which elt is getting updated.
1465 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1466 UndefElts2, Depth+1);
1467 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1468 break;
1469 }
1470
1471 // If this is inserting an element that isn't demanded, remove this
1472 // insertelement.
Reid Spencere0fc4df2006-10-20 07:07:24 +00001473 unsigned IdxNo = Idx->getZExtValue();
Chris Lattner2deeaea2006-10-05 06:55:50 +00001474 if (IdxNo >= VWidth || (DemandedElts & (1ULL << IdxNo)) == 0)
1475 return AddSoonDeadInstToWorklist(*I, 0);
1476
1477 // Otherwise, the element inserted overwrites whatever was there, so the
1478 // input demanded set is simpler than the output set.
1479 TmpV = SimplifyDemandedVectorElts(I->getOperand(0),
1480 DemandedElts & ~(1ULL << IdxNo),
1481 UndefElts, Depth+1);
1482 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1483
1484 // The inserted element is defined.
Dan Gohman86fb5b42008-09-09 18:11:14 +00001485 UndefElts &= ~(1ULL << IdxNo);
1486 break;
1487 }
1488 case Instruction::ShuffleVector: {
1489 ShuffleVectorInst *Shuffle = cast<ShuffleVectorInst>(I);
Mon P Wang25f01062008-11-10 04:46:22 +00001490 uint64_t LHSVWidth =
1491 cast<VectorType>(Shuffle->getOperand(0)->getType())->getNumElements();
Dan Gohman86fb5b42008-09-09 18:11:14 +00001492 uint64_t LeftDemanded = 0, RightDemanded = 0;
1493 for (unsigned i = 0; i < VWidth; i++) {
1494 if (DemandedElts & (1ULL << i)) {
1495 unsigned MaskVal = Shuffle->getMaskValue(i);
1496 if (MaskVal != -1u) {
Mon P Wang25f01062008-11-10 04:46:22 +00001497 assert(MaskVal < LHSVWidth * 2 &&
Dan Gohman86fb5b42008-09-09 18:11:14 +00001498 "shufflevector mask index out of range!");
Mon P Wang25f01062008-11-10 04:46:22 +00001499 if (MaskVal < LHSVWidth)
Dan Gohman86fb5b42008-09-09 18:11:14 +00001500 LeftDemanded |= 1ULL << MaskVal;
1501 else
Mon P Wang25f01062008-11-10 04:46:22 +00001502 RightDemanded |= 1ULL << (MaskVal - LHSVWidth);
Dan Gohman86fb5b42008-09-09 18:11:14 +00001503 }
1504 }
1505 }
1506
1507 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), LeftDemanded,
1508 UndefElts2, Depth+1);
1509 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1510
1511 uint64_t UndefElts3;
1512 TmpV = SimplifyDemandedVectorElts(I->getOperand(1), RightDemanded,
1513 UndefElts3, Depth+1);
1514 if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1515
1516 bool NewUndefElts = false;
1517 for (unsigned i = 0; i < VWidth; i++) {
1518 unsigned MaskVal = Shuffle->getMaskValue(i);
Dan Gohman97f0a0f2008-09-10 01:09:32 +00001519 if (MaskVal == -1u) {
Dan Gohman86fb5b42008-09-09 18:11:14 +00001520 uint64_t NewBit = 1ULL << i;
1521 UndefElts |= NewBit;
Mon P Wang25f01062008-11-10 04:46:22 +00001522 } else if (MaskVal < LHSVWidth) {
Dan Gohman86fb5b42008-09-09 18:11:14 +00001523 uint64_t NewBit = ((UndefElts2 >> MaskVal) & 1) << i;
1524 NewUndefElts |= NewBit;
1525 UndefElts |= NewBit;
1526 } else {
Mon P Wang25f01062008-11-10 04:46:22 +00001527 uint64_t NewBit = ((UndefElts3 >> (MaskVal - LHSVWidth)) & 1) << i;
Dan Gohman86fb5b42008-09-09 18:11:14 +00001528 NewUndefElts |= NewBit;
1529 UndefElts |= NewBit;
1530 }
1531 }
1532
1533 if (NewUndefElts) {
1534 // Add additional discovered undefs.
1535 std::vector<Constant*> Elts;
1536 for (unsigned i = 0; i < VWidth; ++i) {
1537 if (UndefElts & (1ULL << i))
1538 Elts.push_back(UndefValue::get(Type::Int32Ty));
1539 else
1540 Elts.push_back(ConstantInt::get(Type::Int32Ty,
1541 Shuffle->getMaskValue(i)));
1542 }
1543 I->setOperand(2, ConstantVector::get(Elts));
1544 MadeChange = true;
1545 }
Chris Lattner2deeaea2006-10-05 06:55:50 +00001546 break;
1547 }
Chris Lattnerb37fb6a2007-04-14 22:29:23 +00001548 case Instruction::BitCast: {
Dan Gohman06c60b62007-07-16 14:29:03 +00001549 // Vector->vector casts only.
Chris Lattnerb37fb6a2007-04-14 22:29:23 +00001550 const VectorType *VTy = dyn_cast<VectorType>(I->getOperand(0)->getType());
1551 if (!VTy) break;
1552 unsigned InVWidth = VTy->getNumElements();
1553 uint64_t InputDemandedElts = 0;
1554 unsigned Ratio;
1555
1556 if (VWidth == InVWidth) {
Dan Gohman06c60b62007-07-16 14:29:03 +00001557 // If we are converting from <4 x i32> -> <4 x f32>, we demand the same
Chris Lattnerb37fb6a2007-04-14 22:29:23 +00001558 // elements as are demanded of us.
1559 Ratio = 1;
1560 InputDemandedElts = DemandedElts;
1561 } else if (VWidth > InVWidth) {
1562 // Untested so far.
1563 break;
1564
1565 // If there are more elements in the result than there are in the source,
1566 // then an input element is live if any of the corresponding output
1567 // elements are live.
1568 Ratio = VWidth/InVWidth;
1569 for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx) {
1570 if (DemandedElts & (1ULL << OutIdx))
1571 InputDemandedElts |= 1ULL << (OutIdx/Ratio);
1572 }
1573 } else {
1574 // Untested so far.
1575 break;
1576
1577 // If there are more elements in the source than there are in the result,
1578 // then an input element is live if the corresponding output element is
1579 // live.
1580 Ratio = InVWidth/VWidth;
1581 for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
1582 if (DemandedElts & (1ULL << InIdx/Ratio))
1583 InputDemandedElts |= 1ULL << InIdx;
1584 }
Chris Lattner2deeaea2006-10-05 06:55:50 +00001585
Chris Lattnerb37fb6a2007-04-14 22:29:23 +00001586 // div/rem demand all inputs, because they don't want divide by zero.
1587 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), InputDemandedElts,
1588 UndefElts2, Depth+1);
1589 if (TmpV) {
1590 I->setOperand(0, TmpV);
1591 MadeChange = true;
1592 }
1593
1594 UndefElts = UndefElts2;
1595 if (VWidth > InVWidth) {
1596 assert(0 && "Unimp");
1597 // If there are more elements in the result than there are in the source,
1598 // then an output element is undef if the corresponding input element is
1599 // undef.
1600 for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx)
1601 if (UndefElts2 & (1ULL << (OutIdx/Ratio)))
1602 UndefElts |= 1ULL << OutIdx;
1603 } else if (VWidth < InVWidth) {
1604 assert(0 && "Unimp");
1605 // If there are more elements in the source than there are in the result,
1606 // then a result element is undef if all of the corresponding input
1607 // elements are undef.
1608 UndefElts = ~0ULL >> (64-VWidth); // Start out all undef.
1609 for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
1610 if ((UndefElts2 & (1ULL << InIdx)) == 0) // Not undef?
1611 UndefElts &= ~(1ULL << (InIdx/Ratio)); // Clear undef bit.
1612 }
1613 break;
1614 }
Chris Lattner2deeaea2006-10-05 06:55:50 +00001615 case Instruction::And:
1616 case Instruction::Or:
1617 case Instruction::Xor:
1618 case Instruction::Add:
1619 case Instruction::Sub:
1620 case Instruction::Mul:
1621 // div/rem demand all inputs, because they don't want divide by zero.
1622 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1623 UndefElts, Depth+1);
1624 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1625 TmpV = SimplifyDemandedVectorElts(I->getOperand(1), DemandedElts,
1626 UndefElts2, Depth+1);
1627 if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1628
1629 // Output elements are undefined if both are undefined. Consider things
1630 // like undef&0. The result is known zero, not undef.
1631 UndefElts &= UndefElts2;
1632 break;
1633
1634 case Instruction::Call: {
1635 IntrinsicInst *II = dyn_cast<IntrinsicInst>(I);
1636 if (!II) break;
1637 switch (II->getIntrinsicID()) {
1638 default: break;
1639
1640 // Binary vector operations that work column-wise. A dest element is a
1641 // function of the corresponding input elements from the two inputs.
1642 case Intrinsic::x86_sse_sub_ss:
1643 case Intrinsic::x86_sse_mul_ss:
1644 case Intrinsic::x86_sse_min_ss:
1645 case Intrinsic::x86_sse_max_ss:
1646 case Intrinsic::x86_sse2_sub_sd:
1647 case Intrinsic::x86_sse2_mul_sd:
1648 case Intrinsic::x86_sse2_min_sd:
1649 case Intrinsic::x86_sse2_max_sd:
1650 TmpV = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
1651 UndefElts, Depth+1);
1652 if (TmpV) { II->setOperand(1, TmpV); MadeChange = true; }
1653 TmpV = SimplifyDemandedVectorElts(II->getOperand(2), DemandedElts,
1654 UndefElts2, Depth+1);
1655 if (TmpV) { II->setOperand(2, TmpV); MadeChange = true; }
1656
1657 // If only the low elt is demanded and this is a scalarizable intrinsic,
1658 // scalarize it now.
1659 if (DemandedElts == 1) {
1660 switch (II->getIntrinsicID()) {
1661 default: break;
1662 case Intrinsic::x86_sse_sub_ss:
1663 case Intrinsic::x86_sse_mul_ss:
1664 case Intrinsic::x86_sse2_sub_sd:
1665 case Intrinsic::x86_sse2_mul_sd:
1666 // TODO: Lower MIN/MAX/ABS/etc
1667 Value *LHS = II->getOperand(1);
1668 Value *RHS = II->getOperand(2);
1669 // Extract the element as scalars.
1670 LHS = InsertNewInstBefore(new ExtractElementInst(LHS, 0U,"tmp"), *II);
1671 RHS = InsertNewInstBefore(new ExtractElementInst(RHS, 0U,"tmp"), *II);
1672
1673 switch (II->getIntrinsicID()) {
1674 default: assert(0 && "Case stmts out of sync!");
1675 case Intrinsic::x86_sse_sub_ss:
1676 case Intrinsic::x86_sse2_sub_sd:
Gabor Greife1f6e4b2008-05-16 19:29:10 +00001677 TmpV = InsertNewInstBefore(BinaryOperator::CreateSub(LHS, RHS,
Chris Lattner2deeaea2006-10-05 06:55:50 +00001678 II->getName()), *II);
1679 break;
1680 case Intrinsic::x86_sse_mul_ss:
1681 case Intrinsic::x86_sse2_mul_sd:
Gabor Greife1f6e4b2008-05-16 19:29:10 +00001682 TmpV = InsertNewInstBefore(BinaryOperator::CreateMul(LHS, RHS,
Chris Lattner2deeaea2006-10-05 06:55:50 +00001683 II->getName()), *II);
1684 break;
1685 }
1686
1687 Instruction *New =
Gabor Greife9ecc682008-04-06 20:25:17 +00001688 InsertElementInst::Create(UndefValue::get(II->getType()), TmpV, 0U,
1689 II->getName());
Chris Lattner2deeaea2006-10-05 06:55:50 +00001690 InsertNewInstBefore(New, *II);
1691 AddSoonDeadInstToWorklist(*II, 0);
1692 return New;
1693 }
1694 }
1695
1696 // Output elements are undefined if both are undefined. Consider things
1697 // like undef&0. The result is known zero, not undef.
1698 UndefElts &= UndefElts2;
1699 break;
1700 }
1701 break;
1702 }
1703 }
1704 return MadeChange ? I : 0;
1705}
1706
Dan Gohman123438c2008-05-19 22:14:15 +00001707
Chris Lattnerb8b97502003-08-13 19:01:45 +00001708/// AssociativeOpt - Perform an optimization on an associative operator. This
1709/// function is designed to check a chain of associative operators for a
1710/// potential to apply a certain optimization. Since the optimization may be
1711/// applicable if the expression was reassociated, this checks the chain, then
1712/// reassociates the expression as necessary to expose the optimization
1713/// opportunity. This makes use of a special Functor, which must define
1714/// 'shouldApply' and 'apply' methods.
1715///
1716template<typename Functor>
Dan Gohmand7177612008-05-20 01:14:05 +00001717static Instruction *AssociativeOpt(BinaryOperator &Root, const Functor &F) {
Chris Lattnerb8b97502003-08-13 19:01:45 +00001718 unsigned Opcode = Root.getOpcode();
1719 Value *LHS = Root.getOperand(0);
1720
1721 // Quick check, see if the immediate LHS matches...
1722 if (F.shouldApply(LHS))
1723 return F.apply(Root);
1724
1725 // Otherwise, if the LHS is not of the same opcode as the root, return.
1726 Instruction *LHSI = dyn_cast<Instruction>(LHS);
Chris Lattnerf95d9b92003-10-15 16:48:29 +00001727 while (LHSI && LHSI->getOpcode() == Opcode && LHSI->hasOneUse()) {
Chris Lattnerb8b97502003-08-13 19:01:45 +00001728 // Should we apply this transform to the RHS?
1729 bool ShouldApply = F.shouldApply(LHSI->getOperand(1));
1730
1731 // If not to the RHS, check to see if we should apply to the LHS...
1732 if (!ShouldApply && F.shouldApply(LHSI->getOperand(0))) {
1733 cast<BinaryOperator>(LHSI)->swapOperands(); // Make the LHS the RHS
1734 ShouldApply = true;
1735 }
1736
1737 // If the functor wants to apply the optimization to the RHS of LHSI,
1738 // reassociate the expression from ((? op A) op B) to (? op (A op B))
1739 if (ShouldApply) {
Chris Lattnerb8b97502003-08-13 19:01:45 +00001740 // Now all of the instructions are in the current basic block, go ahead
1741 // and perform the reassociation.
1742 Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
1743
1744 // First move the selected RHS to the LHS of the root...
1745 Root.setOperand(0, LHSI->getOperand(1));
1746
1747 // Make what used to be the LHS of the root be the user of the root...
1748 Value *ExtraOperand = TmpLHSI->getOperand(1);
Chris Lattner284d3b02004-04-16 18:08:07 +00001749 if (&Root == TmpLHSI) {
Chris Lattner8953b902004-04-05 02:10:19 +00001750 Root.replaceAllUsesWith(Constant::getNullValue(TmpLHSI->getType()));
1751 return 0;
1752 }
Chris Lattner284d3b02004-04-16 18:08:07 +00001753 Root.replaceAllUsesWith(TmpLHSI); // Users now use TmpLHSI
Chris Lattnerb8b97502003-08-13 19:01:45 +00001754 TmpLHSI->setOperand(1, &Root); // TmpLHSI now uses the root
Chris Lattner284d3b02004-04-16 18:08:07 +00001755 BasicBlock::iterator ARI = &Root; ++ARI;
Dan Gohmaned225092008-06-19 17:47:47 +00001756 TmpLHSI->moveBefore(ARI); // Move TmpLHSI to after Root
Chris Lattner284d3b02004-04-16 18:08:07 +00001757 ARI = Root;
Chris Lattnerb8b97502003-08-13 19:01:45 +00001758
1759 // Now propagate the ExtraOperand down the chain of instructions until we
1760 // get to LHSI.
1761 while (TmpLHSI != LHSI) {
1762 Instruction *NextLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
Chris Lattner284d3b02004-04-16 18:08:07 +00001763 // Move the instruction to immediately before the chain we are
1764 // constructing to avoid breaking dominance properties.
Dan Gohmaned225092008-06-19 17:47:47 +00001765 NextLHSI->moveBefore(ARI);
Chris Lattner284d3b02004-04-16 18:08:07 +00001766 ARI = NextLHSI;
1767
Chris Lattnerb8b97502003-08-13 19:01:45 +00001768 Value *NextOp = NextLHSI->getOperand(1);
1769 NextLHSI->setOperand(1, ExtraOperand);
1770 TmpLHSI = NextLHSI;
1771 ExtraOperand = NextOp;
1772 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00001773
Chris Lattnerb8b97502003-08-13 19:01:45 +00001774 // Now that the instructions are reassociated, have the functor perform
1775 // the transformation...
1776 return F.apply(Root);
1777 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00001778
Chris Lattnerb8b97502003-08-13 19:01:45 +00001779 LHSI = dyn_cast<Instruction>(LHSI->getOperand(0));
1780 }
1781 return 0;
1782}
1783
Dan Gohmand78c4002008-05-13 00:00:25 +00001784namespace {
Chris Lattnerb8b97502003-08-13 19:01:45 +00001785
Nick Lewycky4f3d8782008-05-23 04:34:58 +00001786// AddRHS - Implements: X + X --> X << 1
Chris Lattnerb8b97502003-08-13 19:01:45 +00001787struct AddRHS {
1788 Value *RHS;
1789 AddRHS(Value *rhs) : RHS(rhs) {}
1790 bool shouldApply(Value *LHS) const { return LHS == RHS; }
1791 Instruction *apply(BinaryOperator &Add) const {
Nick Lewycky4f3d8782008-05-23 04:34:58 +00001792 return BinaryOperator::CreateShl(Add.getOperand(0),
1793 ConstantInt::get(Add.getType(), 1));
Chris Lattnerb8b97502003-08-13 19:01:45 +00001794 }
1795};
1796
1797// AddMaskingAnd - Implements (A & C1)+(B & C2) --> (A & C1)|(B & C2)
1798// iff C1&C2 == 0
1799struct AddMaskingAnd {
1800 Constant *C2;
1801 AddMaskingAnd(Constant *c) : C2(c) {}
1802 bool shouldApply(Value *LHS) const {
Chris Lattnerd4252a72004-07-30 07:50:03 +00001803 ConstantInt *C1;
Misha Brukmanb1c93172005-04-21 23:48:37 +00001804 return match(LHS, m_And(m_Value(), m_ConstantInt(C1))) &&
Chris Lattnerd4252a72004-07-30 07:50:03 +00001805 ConstantExpr::getAnd(C1, C2)->isNullValue();
Chris Lattnerb8b97502003-08-13 19:01:45 +00001806 }
1807 Instruction *apply(BinaryOperator &Add) const {
Gabor Greife1f6e4b2008-05-16 19:29:10 +00001808 return BinaryOperator::CreateOr(Add.getOperand(0), Add.getOperand(1));
Chris Lattnerb8b97502003-08-13 19:01:45 +00001809 }
1810};
1811
Dan Gohmand78c4002008-05-13 00:00:25 +00001812}
1813
Chris Lattner86102b82005-01-01 16:22:27 +00001814static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
Chris Lattner183b3362004-04-09 19:05:30 +00001815 InstCombiner *IC) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001816 if (CastInst *CI = dyn_cast<CastInst>(&I)) {
Chris Lattner86102b82005-01-01 16:22:27 +00001817 if (Constant *SOC = dyn_cast<Constant>(SO))
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001818 return ConstantExpr::getCast(CI->getOpcode(), SOC, I.getType());
Misha Brukmanb1c93172005-04-21 23:48:37 +00001819
Gabor Greife1f6e4b2008-05-16 19:29:10 +00001820 return IC->InsertNewInstBefore(CastInst::Create(
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001821 CI->getOpcode(), SO, I.getType(), SO->getName() + ".cast"), I);
Chris Lattner86102b82005-01-01 16:22:27 +00001822 }
1823
Chris Lattner183b3362004-04-09 19:05:30 +00001824 // Figure out if the constant is the left or the right argument.
Chris Lattner86102b82005-01-01 16:22:27 +00001825 bool ConstIsRHS = isa<Constant>(I.getOperand(1));
1826 Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
Chris Lattnerb8b97502003-08-13 19:01:45 +00001827
Chris Lattner183b3362004-04-09 19:05:30 +00001828 if (Constant *SOC = dyn_cast<Constant>(SO)) {
1829 if (ConstIsRHS)
Chris Lattner86102b82005-01-01 16:22:27 +00001830 return ConstantExpr::get(I.getOpcode(), SOC, ConstOperand);
1831 return ConstantExpr::get(I.getOpcode(), ConstOperand, SOC);
Chris Lattner183b3362004-04-09 19:05:30 +00001832 }
1833
1834 Value *Op0 = SO, *Op1 = ConstOperand;
1835 if (!ConstIsRHS)
1836 std::swap(Op0, Op1);
1837 Instruction *New;
Chris Lattner86102b82005-01-01 16:22:27 +00001838 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
Gabor Greife1f6e4b2008-05-16 19:29:10 +00001839 New = BinaryOperator::Create(BO->getOpcode(), Op0, Op1,SO->getName()+".op");
Reid Spencer266e42b2006-12-23 06:05:41 +00001840 else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
Gabor Greife1f6e4b2008-05-16 19:29:10 +00001841 New = CmpInst::Create(CI->getOpcode(), CI->getPredicate(), Op0, Op1,
Reid Spencer266e42b2006-12-23 06:05:41 +00001842 SO->getName()+".cmp");
Chris Lattnerf9d96652004-04-10 19:15:56 +00001843 else {
Chris Lattner183b3362004-04-09 19:05:30 +00001844 assert(0 && "Unknown binary instruction type!");
Chris Lattnerf9d96652004-04-10 19:15:56 +00001845 abort();
1846 }
Chris Lattner86102b82005-01-01 16:22:27 +00001847 return IC->InsertNewInstBefore(New, I);
1848}
1849
1850// FoldOpIntoSelect - Given an instruction with a select as one operand and a
1851// constant as the other operand, try to fold the binary operator into the
1852// select arguments. This also works for Cast instructions, which obviously do
1853// not have a second operand.
1854static Instruction *FoldOpIntoSelect(Instruction &Op, SelectInst *SI,
1855 InstCombiner *IC) {
1856 // Don't modify shared select instructions
1857 if (!SI->hasOneUse()) return 0;
1858 Value *TV = SI->getOperand(1);
1859 Value *FV = SI->getOperand(2);
1860
1861 if (isa<Constant>(TV) || isa<Constant>(FV)) {
Chris Lattner374e6592005-04-21 05:43:13 +00001862 // Bool selects with constant operands can be folded to logical ops.
Reid Spencer542964f2007-01-11 18:21:29 +00001863 if (SI->getType() == Type::Int1Ty) return 0;
Chris Lattner374e6592005-04-21 05:43:13 +00001864
Chris Lattner86102b82005-01-01 16:22:27 +00001865 Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, IC);
1866 Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, IC);
1867
Gabor Greife9ecc682008-04-06 20:25:17 +00001868 return SelectInst::Create(SI->getCondition(), SelectTrueVal,
1869 SelectFalseVal);
Chris Lattner86102b82005-01-01 16:22:27 +00001870 }
1871 return 0;
Chris Lattner183b3362004-04-09 19:05:30 +00001872}
1873
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001874
1875/// FoldOpIntoPhi - Given a binary operator or cast instruction which has a PHI
1876/// node as operand #0, see if we can fold the instruction into the PHI (which
1877/// is only possible if all operands to the PHI are constants).
1878Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I) {
1879 PHINode *PN = cast<PHINode>(I.getOperand(0));
Chris Lattner7515cab2004-11-14 19:13:23 +00001880 unsigned NumPHIValues = PN->getNumIncomingValues();
Chris Lattner04689872006-09-09 22:02:56 +00001881 if (!PN->hasOneUse() || NumPHIValues == 0) return 0;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001882
Chris Lattner04689872006-09-09 22:02:56 +00001883 // Check to see if all of the operands of the PHI are constants. If there is
1884 // one non-constant value, remember the BB it is. If there is more than one
Chris Lattnerc4d8e7e2007-02-24 01:03:45 +00001885 // or if *it* is a PHI, bail out.
Chris Lattner04689872006-09-09 22:02:56 +00001886 BasicBlock *NonConstBB = 0;
1887 for (unsigned i = 0; i != NumPHIValues; ++i)
1888 if (!isa<Constant>(PN->getIncomingValue(i))) {
1889 if (NonConstBB) return 0; // More than one non-const value.
Chris Lattnerc4d8e7e2007-02-24 01:03:45 +00001890 if (isa<PHINode>(PN->getIncomingValue(i))) return 0; // Itself a phi.
Chris Lattner04689872006-09-09 22:02:56 +00001891 NonConstBB = PN->getIncomingBlock(i);
1892
1893 // If the incoming non-constant value is in I's block, we have an infinite
1894 // loop.
1895 if (NonConstBB == I.getParent())
1896 return 0;
1897 }
1898
1899 // If there is exactly one non-constant value, we can insert a copy of the
1900 // operation in that block. However, if this is a critical edge, we would be
1901 // inserting the computation one some other paths (e.g. inside a loop). Only
1902 // do this if the pred block is unconditionally branching into the phi block.
1903 if (NonConstBB) {
1904 BranchInst *BI = dyn_cast<BranchInst>(NonConstBB->getTerminator());
1905 if (!BI || !BI->isUnconditional()) return 0;
1906 }
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001907
1908 // Okay, we can do the transformation: create the new PHI node.
Gabor Greife9ecc682008-04-06 20:25:17 +00001909 PHINode *NewPN = PHINode::Create(I.getType(), "");
Chris Lattnerd8e20182005-01-29 00:39:08 +00001910 NewPN->reserveOperandSpace(PN->getNumOperands()/2);
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001911 InsertNewInstBefore(NewPN, *PN);
Chris Lattner6e0123b2007-02-11 01:23:03 +00001912 NewPN->takeName(PN);
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001913
1914 // Next, add all of the operands to the PHI.
1915 if (I.getNumOperands() == 2) {
1916 Constant *C = cast<Constant>(I.getOperand(1));
Chris Lattner7515cab2004-11-14 19:13:23 +00001917 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattnerf0da7972007-08-05 08:47:58 +00001918 Value *InV = 0;
Chris Lattner04689872006-09-09 22:02:56 +00001919 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
Reid Spencer266e42b2006-12-23 06:05:41 +00001920 if (CmpInst *CI = dyn_cast<CmpInst>(&I))
1921 InV = ConstantExpr::getCompare(CI->getPredicate(), InC, C);
1922 else
1923 InV = ConstantExpr::get(I.getOpcode(), InC, C);
Chris Lattner04689872006-09-09 22:02:56 +00001924 } else {
1925 assert(PN->getIncomingBlock(i) == NonConstBB);
1926 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
Gabor Greife1f6e4b2008-05-16 19:29:10 +00001927 InV = BinaryOperator::Create(BO->getOpcode(),
Chris Lattner04689872006-09-09 22:02:56 +00001928 PN->getIncomingValue(i), C, "phitmp",
1929 NonConstBB->getTerminator());
Reid Spencer266e42b2006-12-23 06:05:41 +00001930 else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
Gabor Greife1f6e4b2008-05-16 19:29:10 +00001931 InV = CmpInst::Create(CI->getOpcode(),
Reid Spencer266e42b2006-12-23 06:05:41 +00001932 CI->getPredicate(),
1933 PN->getIncomingValue(i), C, "phitmp",
1934 NonConstBB->getTerminator());
Chris Lattner04689872006-09-09 22:02:56 +00001935 else
1936 assert(0 && "Unknown binop!");
1937
Chris Lattnerb15e2b12007-03-02 21:28:56 +00001938 AddToWorkList(cast<Instruction>(InV));
Chris Lattner04689872006-09-09 22:02:56 +00001939 }
1940 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001941 }
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001942 } else {
1943 CastInst *CI = cast<CastInst>(&I);
1944 const Type *RetTy = CI->getType();
Chris Lattner7515cab2004-11-14 19:13:23 +00001945 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattner04689872006-09-09 22:02:56 +00001946 Value *InV;
1947 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001948 InV = ConstantExpr::getCast(CI->getOpcode(), InC, RetTy);
Chris Lattner04689872006-09-09 22:02:56 +00001949 } else {
1950 assert(PN->getIncomingBlock(i) == NonConstBB);
Gabor Greife1f6e4b2008-05-16 19:29:10 +00001951 InV = CastInst::Create(CI->getOpcode(), PN->getIncomingValue(i),
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001952 I.getType(), "phitmp",
1953 NonConstBB->getTerminator());
Chris Lattnerb15e2b12007-03-02 21:28:56 +00001954 AddToWorkList(cast<Instruction>(InV));
Chris Lattner04689872006-09-09 22:02:56 +00001955 }
1956 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001957 }
1958 }
1959 return ReplaceInstUsesWith(I, NewPN);
1960}
1961
Chris Lattner17819d92008-01-29 06:52:45 +00001962
Chris Lattner7ac943f2008-05-20 05:46:13 +00001963/// WillNotOverflowSignedAdd - Return true if we can prove that:
1964/// (sext (add LHS, RHS)) === (add (sext LHS), (sext RHS))
1965/// This basically requires proving that the add in the original type would not
1966/// overflow to change the sign bit or have a carry out.
1967bool InstCombiner::WillNotOverflowSignedAdd(Value *LHS, Value *RHS) {
1968 // There are different heuristics we can use for this. Here are some simple
1969 // ones.
1970
1971 // Add has the property that adding any two 2's complement numbers can only
1972 // have one carry bit which can change a sign. As such, if LHS and RHS each
1973 // have at least two sign bits, we know that the addition of the two values will
1974 // sign extend fine.
1975 if (ComputeNumSignBits(LHS) > 1 && ComputeNumSignBits(RHS) > 1)
1976 return true;
1977
1978
1979 // If one of the operands only has one non-zero bit, and if the other operand
1980 // has a known-zero bit in a more significant place than it (not including the
1981 // sign bit) the ripple may go up to and fill the zero, but won't change the
1982 // sign. For example, (X & ~4) + 1.
1983
1984 // TODO: Implement.
1985
1986 return false;
1987}
1988
Chris Lattner17819d92008-01-29 06:52:45 +00001989
Chris Lattner113f4f42002-06-25 16:13:24 +00001990Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00001991 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00001992 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
Chris Lattner9fa53de2002-05-06 16:49:18 +00001993
Chris Lattnercf4a9962004-04-10 22:01:55 +00001994 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
Chris Lattner81a7a232004-10-16 18:11:37 +00001995 // X + undef -> undef
1996 if (isa<UndefValue>(RHS))
1997 return ReplaceInstUsesWith(I, RHS);
1998
Chris Lattnercf4a9962004-04-10 22:01:55 +00001999 // X + 0 --> X
Chris Lattner7a002fe2006-12-02 00:13:08 +00002000 if (!I.getType()->isFPOrFPVector()) { // NOTE: -0 + +0 = +0.
Chris Lattner7fde91e2005-10-17 17:56:38 +00002001 if (RHSC->isNullValue())
2002 return ReplaceInstUsesWith(I, LHS);
Chris Lattnerda1b1522005-10-17 20:18:38 +00002003 } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
Dale Johannesen98d3a082007-09-14 22:26:36 +00002004 if (CFP->isExactlyValue(ConstantFP::getNegativeZero
2005 (I.getType())->getValueAPF()))
Chris Lattnerda1b1522005-10-17 20:18:38 +00002006 return ReplaceInstUsesWith(I, LHS);
Chris Lattner7fde91e2005-10-17 17:56:38 +00002007 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00002008
Chris Lattnercf4a9962004-04-10 22:01:55 +00002009 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHSC)) {
Chris Lattner6e2c15c2006-11-09 05:12:27 +00002010 // X + (signbit) --> X ^ signbit
Zhou Sheng150f3bb2007-04-01 17:13:37 +00002011 const APInt& Val = CI->getValue();
Zhou Sheng56cda952007-04-02 08:20:41 +00002012 uint32_t BitWidth = Val.getBitWidth();
Reid Spencer959a21d2007-03-23 21:24:59 +00002013 if (Val == APInt::getSignBit(BitWidth))
Gabor Greife1f6e4b2008-05-16 19:29:10 +00002014 return BinaryOperator::CreateXor(LHS, RHS);
Chris Lattner6e2c15c2006-11-09 05:12:27 +00002015
2016 // See if SimplifyDemandedBits can simplify this. This handles stuff like
2017 // (X & 254)+1 -> (X&254)|1
Reid Spencer959a21d2007-03-23 21:24:59 +00002018 if (!isa<VectorType>(I.getType())) {
2019 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
2020 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
2021 KnownZero, KnownOne))
2022 return &I;
2023 }
Dan Gohman13cbcf1c182008-10-30 20:40:10 +00002024
2025 // zext(i1) - 1 -> select i1, 0, -1
2026 if (ZExtInst *ZI = dyn_cast<ZExtInst>(LHS))
2027 if (CI->isAllOnesValue() &&
2028 ZI->getOperand(0)->getType() == Type::Int1Ty)
2029 return SelectInst::Create(ZI->getOperand(0),
2030 Constant::getNullValue(I.getType()),
2031 ConstantInt::getAllOnesValue(I.getType()));
Chris Lattnercf4a9962004-04-10 22:01:55 +00002032 }
Chris Lattner6a4adcd2004-09-29 05:07:12 +00002033
2034 if (isa<PHINode>(LHS))
2035 if (Instruction *NV = FoldOpIntoPhi(I))
2036 return NV;
Chris Lattner0b3557f2005-09-24 23:43:33 +00002037
Chris Lattner330628a2006-01-06 17:59:59 +00002038 ConstantInt *XorRHS = 0;
2039 Value *XorLHS = 0;
Chris Lattner4284f642007-01-30 22:32:46 +00002040 if (isa<ConstantInt>(RHSC) &&
2041 match(LHS, m_Xor(m_Value(XorLHS), m_ConstantInt(XorRHS)))) {
Zhou Sheng56cda952007-04-02 08:20:41 +00002042 uint32_t TySizeBits = I.getType()->getPrimitiveSizeInBits();
Zhou Sheng150f3bb2007-04-01 17:13:37 +00002043 const APInt& RHSVal = cast<ConstantInt>(RHSC)->getValue();
Chris Lattner0b3557f2005-09-24 23:43:33 +00002044
Zhou Sheng56cda952007-04-02 08:20:41 +00002045 uint32_t Size = TySizeBits / 2;
Reid Spencer959a21d2007-03-23 21:24:59 +00002046 APInt C0080Val(APInt(TySizeBits, 1ULL).shl(Size - 1));
2047 APInt CFF80Val(-C0080Val);
Chris Lattner0b3557f2005-09-24 23:43:33 +00002048 do {
2049 if (TySizeBits > Size) {
Chris Lattner0b3557f2005-09-24 23:43:33 +00002050 // If we have ADD(XOR(AND(X, 0xFF), 0x80), 0xF..F80), it's a sext.
2051 // If we have ADD(XOR(AND(X, 0xFF), 0xF..F80), 0x80), it's a sext.
Reid Spencer959a21d2007-03-23 21:24:59 +00002052 if ((RHSVal == CFF80Val && XorRHS->getValue() == C0080Val) ||
2053 (RHSVal == C0080Val && XorRHS->getValue() == CFF80Val)) {
Chris Lattner0b3557f2005-09-24 23:43:33 +00002054 // This is a sign extend if the top bits are known zero.
Zhou Shengb3a80b12007-03-29 08:15:12 +00002055 if (!MaskedValueIsZero(XorLHS,
2056 APInt::getHighBitsSet(TySizeBits, TySizeBits - Size)))
Chris Lattner0b3557f2005-09-24 23:43:33 +00002057 Size = 0; // Not a sign ext, but can't be any others either.
Reid Spencer959a21d2007-03-23 21:24:59 +00002058 break;
Chris Lattner0b3557f2005-09-24 23:43:33 +00002059 }
2060 }
2061 Size >>= 1;
Reid Spencer959a21d2007-03-23 21:24:59 +00002062 C0080Val = APIntOps::lshr(C0080Val, Size);
2063 CFF80Val = APIntOps::ashr(CFF80Val, Size);
2064 } while (Size >= 1);
Chris Lattner0b3557f2005-09-24 23:43:33 +00002065
Reid Spencera5c18bf2007-03-28 01:36:16 +00002066 // FIXME: This shouldn't be necessary. When the backends can handle types
Chris Lattnere35fe0f2008-05-19 20:25:04 +00002067 // with funny bit widths then this switch statement should be removed. It
2068 // is just here to get the size of the "middle" type back up to something
2069 // that the back ends can handle.
Reid Spencera5c18bf2007-03-28 01:36:16 +00002070 const Type *MiddleType = 0;
2071 switch (Size) {
2072 default: break;
2073 case 32: MiddleType = Type::Int32Ty; break;
2074 case 16: MiddleType = Type::Int16Ty; break;
2075 case 8: MiddleType = Type::Int8Ty; break;
2076 }
2077 if (MiddleType) {
Reid Spencerbb65ebf2006-12-12 23:36:14 +00002078 Instruction *NewTrunc = new TruncInst(XorLHS, MiddleType, "sext");
Chris Lattner0b3557f2005-09-24 23:43:33 +00002079 InsertNewInstBefore(NewTrunc, I);
Reid Spencera5c18bf2007-03-28 01:36:16 +00002080 return new SExtInst(NewTrunc, I.getType(), I.getName());
Chris Lattner0b3557f2005-09-24 23:43:33 +00002081 }
2082 }
Chris Lattnercf4a9962004-04-10 22:01:55 +00002083 }
Chris Lattner9fa53de2002-05-06 16:49:18 +00002084
Nick Lewycky26b8cd82008-05-31 17:59:52 +00002085 if (I.getType() == Type::Int1Ty)
2086 return BinaryOperator::CreateXor(LHS, RHS);
2087
Nick Lewycky8f3127c2008-05-23 04:39:38 +00002088 // X + X --> X << 1
Nick Lewycky26b8cd82008-05-31 17:59:52 +00002089 if (I.getType()->isInteger()) {
Chris Lattnerb8b97502003-08-13 19:01:45 +00002090 if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS))) return Result;
Chris Lattner47060462005-04-07 17:14:51 +00002091
2092 if (Instruction *RHSI = dyn_cast<Instruction>(RHS)) {
2093 if (RHSI->getOpcode() == Instruction::Sub)
2094 if (LHS == RHSI->getOperand(1)) // A + (B - A) --> B
2095 return ReplaceInstUsesWith(I, RHSI->getOperand(0));
2096 }
2097 if (Instruction *LHSI = dyn_cast<Instruction>(LHS)) {
2098 if (LHSI->getOpcode() == Instruction::Sub)
2099 if (RHS == LHSI->getOperand(1)) // (B - A) + A --> B
2100 return ReplaceInstUsesWith(I, LHSI->getOperand(0));
2101 }
Robert Bocchino7b5b86c2004-07-27 21:02:21 +00002102 }
Chris Lattnerede3fe02003-08-13 04:18:28 +00002103
Chris Lattner147e9752002-05-08 22:46:53 +00002104 // -A + B --> B - A
Chris Lattnercc226012008-02-17 21:03:36 +00002105 // -A + -B --> -(A + B)
2106 if (Value *LHSV = dyn_castNegVal(LHS)) {
Chris Lattner1e3c5012008-02-18 17:50:16 +00002107 if (LHS->getType()->isIntOrIntVector()) {
2108 if (Value *RHSV = dyn_castNegVal(RHS)) {
Gabor Greife1f6e4b2008-05-16 19:29:10 +00002109 Instruction *NewAdd = BinaryOperator::CreateAdd(LHSV, RHSV, "sum");
Chris Lattner1e3c5012008-02-18 17:50:16 +00002110 InsertNewInstBefore(NewAdd, I);
Gabor Greife1f6e4b2008-05-16 19:29:10 +00002111 return BinaryOperator::CreateNeg(NewAdd);
Chris Lattner1e3c5012008-02-18 17:50:16 +00002112 }
Chris Lattnercc226012008-02-17 21:03:36 +00002113 }
2114
Gabor Greife1f6e4b2008-05-16 19:29:10 +00002115 return BinaryOperator::CreateSub(RHS, LHSV);
Chris Lattnercc226012008-02-17 21:03:36 +00002116 }
Chris Lattner9fa53de2002-05-06 16:49:18 +00002117
2118 // A + -B --> A - B
Chris Lattnerbb74e222003-03-10 23:06:50 +00002119 if (!isa<Constant>(RHS))
2120 if (Value *V = dyn_castNegVal(RHS))
Gabor Greife1f6e4b2008-05-16 19:29:10 +00002121 return BinaryOperator::CreateSub(LHS, V);
Chris Lattner260ab202002-04-18 17:39:14 +00002122
Misha Brukmanb1c93172005-04-21 23:48:37 +00002123
Chris Lattner8c3e7b92004-11-13 19:50:12 +00002124 ConstantInt *C2;
2125 if (Value *X = dyn_castFoldableMul(LHS, C2)) {
2126 if (X == RHS) // X*C + X --> X * (C+1)
Gabor Greife1f6e4b2008-05-16 19:29:10 +00002127 return BinaryOperator::CreateMul(RHS, AddOne(C2));
Chris Lattner8c3e7b92004-11-13 19:50:12 +00002128
2129 // X*C1 + X*C2 --> X * (C1+C2)
2130 ConstantInt *C1;
2131 if (X == dyn_castFoldableMul(RHS, C1))
Gabor Greife1f6e4b2008-05-16 19:29:10 +00002132 return BinaryOperator::CreateMul(X, Add(C1, C2));
Chris Lattner57c8d992003-02-18 19:57:07 +00002133 }
2134
2135 // X + X*C --> X * (C+1)
Chris Lattner8c3e7b92004-11-13 19:50:12 +00002136 if (dyn_castFoldableMul(RHS, C2) == LHS)
Gabor Greife1f6e4b2008-05-16 19:29:10 +00002137 return BinaryOperator::CreateMul(LHS, AddOne(C2));
Chris Lattner8c3e7b92004-11-13 19:50:12 +00002138
Chris Lattner23eb8ec2007-01-05 02:17:46 +00002139 // X + ~X --> -1 since ~X = -X-1
Chris Lattner37338922007-06-15 06:23:19 +00002140 if (dyn_castNotVal(LHS) == RHS || dyn_castNotVal(RHS) == LHS)
2141 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattner23eb8ec2007-01-05 02:17:46 +00002142
Chris Lattner57c8d992003-02-18 19:57:07 +00002143
Chris Lattnerb8b97502003-08-13 19:01:45 +00002144 // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
Chris Lattnerd4252a72004-07-30 07:50:03 +00002145 if (match(RHS, m_And(m_Value(), m_ConstantInt(C2))))
Chris Lattner23eb8ec2007-01-05 02:17:46 +00002146 if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2)))
2147 return R;
Chris Lattnerfc365b62008-05-19 20:01:56 +00002148
2149 // A+B --> A|B iff A and B have no bits set in common.
2150 if (const IntegerType *IT = dyn_cast<IntegerType>(I.getType())) {
2151 APInt Mask = APInt::getAllOnesValue(IT->getBitWidth());
2152 APInt LHSKnownOne(IT->getBitWidth(), 0);
2153 APInt LHSKnownZero(IT->getBitWidth(), 0);
2154 ComputeMaskedBits(LHS, Mask, LHSKnownZero, LHSKnownOne);
2155 if (LHSKnownZero != 0) {
2156 APInt RHSKnownOne(IT->getBitWidth(), 0);
2157 APInt RHSKnownZero(IT->getBitWidth(), 0);
2158 ComputeMaskedBits(RHS, Mask, RHSKnownZero, RHSKnownOne);
2159
2160 // No bits in common -> bitwise or.
Chris Lattner6e708302008-05-19 20:03:53 +00002161 if ((LHSKnownZero|RHSKnownZero).isAllOnesValue())
Chris Lattnerfc365b62008-05-19 20:01:56 +00002162 return BinaryOperator::CreateOr(LHS, RHS);
Chris Lattnerfc365b62008-05-19 20:01:56 +00002163 }
2164 }
Chris Lattner7fb29e12003-03-11 00:12:48 +00002165
Nick Lewyckye6e3a7f2008-02-03 07:42:09 +00002166 // W*X + Y*Z --> W * (X+Z) iff W == Y
Nick Lewyckyc7a4ba02008-02-03 08:19:11 +00002167 if (I.getType()->isIntOrIntVector()) {
Nick Lewyckye6e3a7f2008-02-03 07:42:09 +00002168 Value *W, *X, *Y, *Z;
2169 if (match(LHS, m_Mul(m_Value(W), m_Value(X))) &&
2170 match(RHS, m_Mul(m_Value(Y), m_Value(Z)))) {
2171 if (W != Y) {
2172 if (W == Z) {
Bill Wendlingd188e032008-02-26 10:53:30 +00002173 std::swap(Y, Z);
Nick Lewyckye6e3a7f2008-02-03 07:42:09 +00002174 } else if (Y == X) {
Bill Wendlingd188e032008-02-26 10:53:30 +00002175 std::swap(W, X);
2176 } else if (X == Z) {
Nick Lewyckye6e3a7f2008-02-03 07:42:09 +00002177 std::swap(Y, Z);
2178 std::swap(W, X);
2179 }
2180 }
2181
2182 if (W == Y) {
Gabor Greife1f6e4b2008-05-16 19:29:10 +00002183 Value *NewAdd = InsertNewInstBefore(BinaryOperator::CreateAdd(X, Z,
Nick Lewyckye6e3a7f2008-02-03 07:42:09 +00002184 LHS->getName()), I);
Gabor Greife1f6e4b2008-05-16 19:29:10 +00002185 return BinaryOperator::CreateMul(W, NewAdd);
Nick Lewyckye6e3a7f2008-02-03 07:42:09 +00002186 }
2187 }
2188 }
2189
Chris Lattnerb9cde762003-10-02 15:11:26 +00002190 if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
Chris Lattner330628a2006-01-06 17:59:59 +00002191 Value *X = 0;
Reid Spencer80263aa2007-03-25 05:33:51 +00002192 if (match(LHS, m_Not(m_Value(X)))) // ~X + C --> (C-1) - X
Gabor Greife1f6e4b2008-05-16 19:29:10 +00002193 return BinaryOperator::CreateSub(SubOne(CRHS), X);
Chris Lattnerd4252a72004-07-30 07:50:03 +00002194
Chris Lattnerbff91d92004-10-08 05:07:56 +00002195 // (X & FF00) + xx00 -> (X+xx00) & FF00
2196 if (LHS->hasOneUse() && match(LHS, m_And(m_Value(X), m_ConstantInt(C2)))) {
Reid Spencer80263aa2007-03-25 05:33:51 +00002197 Constant *Anded = And(CRHS, C2);
Chris Lattnerbff91d92004-10-08 05:07:56 +00002198 if (Anded == CRHS) {
2199 // See if all bits from the first bit set in the Add RHS up are included
2200 // in the mask. First, get the rightmost bit.
Zhou Sheng150f3bb2007-04-01 17:13:37 +00002201 const APInt& AddRHSV = CRHS->getValue();
Chris Lattnerbff91d92004-10-08 05:07:56 +00002202
2203 // Form a mask of all bits from the lowest bit added through the top.
Zhou Sheng150f3bb2007-04-01 17:13:37 +00002204 APInt AddRHSHighBits(~((AddRHSV & -AddRHSV)-1));
Chris Lattnerbff91d92004-10-08 05:07:56 +00002205
2206 // See if the and mask includes all of these bits.
Zhou Sheng150f3bb2007-04-01 17:13:37 +00002207 APInt AddRHSHighBitsAnd(AddRHSHighBits & C2->getValue());
Misha Brukmanb1c93172005-04-21 23:48:37 +00002208
Chris Lattnerbff91d92004-10-08 05:07:56 +00002209 if (AddRHSHighBits == AddRHSHighBitsAnd) {
2210 // Okay, the xform is safe. Insert the new add pronto.
Gabor Greife1f6e4b2008-05-16 19:29:10 +00002211 Value *NewAdd = InsertNewInstBefore(BinaryOperator::CreateAdd(X, CRHS,
Chris Lattnerbff91d92004-10-08 05:07:56 +00002212 LHS->getName()), I);
Gabor Greife1f6e4b2008-05-16 19:29:10 +00002213 return BinaryOperator::CreateAnd(NewAdd, C2);
Chris Lattnerbff91d92004-10-08 05:07:56 +00002214 }
2215 }
2216 }
2217
Chris Lattnerd4252a72004-07-30 07:50:03 +00002218 // Try to fold constant add into select arguments.
2219 if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
Chris Lattner86102b82005-01-01 16:22:27 +00002220 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattnerd4252a72004-07-30 07:50:03 +00002221 return R;
Chris Lattnerb9cde762003-10-02 15:11:26 +00002222 }
2223
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002224 // add (cast *A to intptrtype) B ->
Chris Lattner16a51da2007-12-20 01:56:58 +00002225 // cast (GEP (cast *A to sbyte*) B) --> intptrtype
Andrew Lenharth4f339be2006-09-19 18:24:51 +00002226 {
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002227 CastInst *CI = dyn_cast<CastInst>(LHS);
2228 Value *Other = RHS;
Andrew Lenharth4f339be2006-09-19 18:24:51 +00002229 if (!CI) {
2230 CI = dyn_cast<CastInst>(RHS);
2231 Other = LHS;
2232 }
Andrew Lenharth44cb67a2006-09-20 15:37:57 +00002233 if (CI && CI->getType()->isSized() &&
Reid Spencer8f166b02007-01-08 16:32:00 +00002234 (CI->getType()->getPrimitiveSizeInBits() ==
2235 TD->getIntPtrType()->getPrimitiveSizeInBits())
Andrew Lenharth44cb67a2006-09-20 15:37:57 +00002236 && isa<PointerType>(CI->getOperand(0)->getType())) {
Christopher Lambedf07882007-12-17 01:12:55 +00002237 unsigned AS =
2238 cast<PointerType>(CI->getOperand(0)->getType())->getAddressSpace();
Chris Lattner5a866122008-01-13 22:23:22 +00002239 Value *I2 = InsertBitCastBefore(CI->getOperand(0),
2240 PointerType::get(Type::Int8Ty, AS), I);
Gabor Greife9ecc682008-04-06 20:25:17 +00002241 I2 = InsertNewInstBefore(GetElementPtrInst::Create(I2, Other, "ctg2"), I);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002242 return new PtrToIntInst(I2, CI->getType());
Andrew Lenharth4f339be2006-09-19 18:24:51 +00002243 }
2244 }
Christopher Lamb8b09a462007-12-18 09:34:41 +00002245
Chris Lattner16a51da2007-12-20 01:56:58 +00002246 // add (select X 0 (sub n A)) A --> select X A n
Christopher Lamb8b09a462007-12-18 09:34:41 +00002247 {
2248 SelectInst *SI = dyn_cast<SelectInst>(LHS);
Chris Lattnerf1be2852008-11-16 04:46:19 +00002249 Value *A = RHS;
Christopher Lamb8b09a462007-12-18 09:34:41 +00002250 if (!SI) {
2251 SI = dyn_cast<SelectInst>(RHS);
Chris Lattnerf1be2852008-11-16 04:46:19 +00002252 A = LHS;
Christopher Lamb8b09a462007-12-18 09:34:41 +00002253 }
Chris Lattner16a51da2007-12-20 01:56:58 +00002254 if (SI && SI->hasOneUse()) {
Christopher Lamb8b09a462007-12-18 09:34:41 +00002255 Value *TV = SI->getTrueValue();
2256 Value *FV = SI->getFalseValue();
Chris Lattnerf1be2852008-11-16 04:46:19 +00002257 Value *N;
Christopher Lamb8b09a462007-12-18 09:34:41 +00002258
2259 // Can we fold the add into the argument of the select?
2260 // We check both true and false select arguments for a matching subtract.
Chris Lattnerf1be2852008-11-16 04:46:19 +00002261 if (match(FV, m_Zero()) && match(TV, m_Sub(m_Value(N), m_Specific(A))))
2262 // Fold the add into the true select value.
Gabor Greife9ecc682008-04-06 20:25:17 +00002263 return SelectInst::Create(SI->getCondition(), N, A);
Chris Lattnerf1be2852008-11-16 04:46:19 +00002264 if (match(TV, m_Zero()) && match(FV, m_Sub(m_Value(N), m_Specific(A))))
2265 // Fold the add into the false select value.
Gabor Greife9ecc682008-04-06 20:25:17 +00002266 return SelectInst::Create(SI->getCondition(), A, N);
Christopher Lamb8b09a462007-12-18 09:34:41 +00002267 }
2268 }
Chris Lattner17819d92008-01-29 06:52:45 +00002269
2270 // Check for X+0.0. Simplify it to X if we know X is not -0.0.
2271 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS))
2272 if (CFP->getValueAPF().isPosZero() && CannotBeNegativeZero(LHS))
2273 return ReplaceInstUsesWith(I, LHS);
Andrew Lenharth4f339be2006-09-19 18:24:51 +00002274
Chris Lattner7ac943f2008-05-20 05:46:13 +00002275 // Check for (add (sext x), y), see if we can merge this into an
2276 // integer add followed by a sext.
2277 if (SExtInst *LHSConv = dyn_cast<SExtInst>(LHS)) {
2278 // (add (sext x), cst) --> (sext (add x, cst'))
2279 if (ConstantInt *RHSC = dyn_cast<ConstantInt>(RHS)) {
2280 Constant *CI =
2281 ConstantExpr::getTrunc(RHSC, LHSConv->getOperand(0)->getType());
2282 if (LHSConv->hasOneUse() &&
2283 ConstantExpr::getSExt(CI, I.getType()) == RHSC &&
2284 WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
2285 // Insert the new, smaller add.
2286 Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0),
2287 CI, "addconv");
2288 InsertNewInstBefore(NewAdd, I);
2289 return new SExtInst(NewAdd, I.getType());
2290 }
2291 }
2292
2293 // (add (sext x), (sext y)) --> (sext (add int x, y))
2294 if (SExtInst *RHSConv = dyn_cast<SExtInst>(RHS)) {
2295 // Only do this if x/y have the same type, if at last one of them has a
2296 // single use (so we don't increase the number of sexts), and if the
2297 // integer add will not overflow.
2298 if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
2299 (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
2300 WillNotOverflowSignedAdd(LHSConv->getOperand(0),
2301 RHSConv->getOperand(0))) {
2302 // Insert the new integer add.
2303 Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0),
2304 RHSConv->getOperand(0),
2305 "addconv");
2306 InsertNewInstBefore(NewAdd, I);
2307 return new SExtInst(NewAdd, I.getType());
2308 }
2309 }
2310 }
2311
2312 // Check for (add double (sitofp x), y), see if we can merge this into an
2313 // integer add followed by a promotion.
2314 if (SIToFPInst *LHSConv = dyn_cast<SIToFPInst>(LHS)) {
2315 // (add double (sitofp x), fpcst) --> (sitofp (add int x, intcst))
2316 // ... if the constant fits in the integer value. This is useful for things
2317 // like (double)(x & 1234) + 4.0 -> (double)((X & 1234)+4) which no longer
2318 // requires a constant pool load, and generally allows the add to be better
2319 // instcombined.
2320 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS)) {
2321 Constant *CI =
2322 ConstantExpr::getFPToSI(CFP, LHSConv->getOperand(0)->getType());
2323 if (LHSConv->hasOneUse() &&
2324 ConstantExpr::getSIToFP(CI, I.getType()) == CFP &&
2325 WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
2326 // Insert the new integer add.
2327 Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0),
2328 CI, "addconv");
2329 InsertNewInstBefore(NewAdd, I);
2330 return new SIToFPInst(NewAdd, I.getType());
2331 }
2332 }
2333
2334 // (add double (sitofp x), (sitofp y)) --> (sitofp (add int x, y))
2335 if (SIToFPInst *RHSConv = dyn_cast<SIToFPInst>(RHS)) {
2336 // Only do this if x/y have the same type, if at last one of them has a
2337 // single use (so we don't increase the number of int->fp conversions),
2338 // and if the integer add will not overflow.
2339 if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
2340 (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
2341 WillNotOverflowSignedAdd(LHSConv->getOperand(0),
2342 RHSConv->getOperand(0))) {
2343 // Insert the new integer add.
2344 Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0),
2345 RHSConv->getOperand(0),
2346 "addconv");
2347 InsertNewInstBefore(NewAdd, I);
2348 return new SIToFPInst(NewAdd, I.getType());
2349 }
2350 }
2351 }
2352
Chris Lattner113f4f42002-06-25 16:13:24 +00002353 return Changed ? &I : 0;
Chris Lattner260ab202002-04-18 17:39:14 +00002354}
2355
Chris Lattner113f4f42002-06-25 16:13:24 +00002356Instruction *InstCombiner::visitSub(BinaryOperator &I) {
Chris Lattner113f4f42002-06-25 16:13:24 +00002357 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002358
Chris Lattnerc600c532008-07-17 06:07:20 +00002359 if (Op0 == Op1 && // sub X, X -> 0
2360 !I.getType()->isFPOrFPVector())
Chris Lattnere6794492002-08-12 21:17:25 +00002361 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner260ab202002-04-18 17:39:14 +00002362
Chris Lattnere6794492002-08-12 21:17:25 +00002363 // If this is a 'B = x-(-A)', change to B = x+A...
Chris Lattnerbb74e222003-03-10 23:06:50 +00002364 if (Value *V = dyn_castNegVal(Op1))
Gabor Greife1f6e4b2008-05-16 19:29:10 +00002365 return BinaryOperator::CreateAdd(Op0, V);
Chris Lattner9fa53de2002-05-06 16:49:18 +00002366
Chris Lattner81a7a232004-10-16 18:11:37 +00002367 if (isa<UndefValue>(Op0))
2368 return ReplaceInstUsesWith(I, Op0); // undef - X -> undef
2369 if (isa<UndefValue>(Op1))
2370 return ReplaceInstUsesWith(I, Op1); // X - undef -> undef
2371
Chris Lattner8f2f5982003-11-05 01:06:05 +00002372 if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
2373 // Replace (-1 - A) with (~A)...
Chris Lattner3082c5a2003-02-18 19:28:33 +00002374 if (C->isAllOnesValue())
Gabor Greife1f6e4b2008-05-16 19:29:10 +00002375 return BinaryOperator::CreateNot(Op1);
Chris Lattnerad3c4952002-05-09 01:29:19 +00002376
Chris Lattner8f2f5982003-11-05 01:06:05 +00002377 // C - ~X == X + (1+C)
Reid Spencer4fdd96c2005-06-18 17:37:34 +00002378 Value *X = 0;
Chris Lattnerd4252a72004-07-30 07:50:03 +00002379 if (match(Op1, m_Not(m_Value(X))))
Gabor Greife1f6e4b2008-05-16 19:29:10 +00002380 return BinaryOperator::CreateAdd(X, AddOne(C));
Reid Spencer80263aa2007-03-25 05:33:51 +00002381
Chris Lattner27df1db2007-01-15 07:02:54 +00002382 // -(X >>u 31) -> (X >>s 31)
2383 // -(X >>s 31) -> (X >>u 31)
Zhou Shengfd28a332007-03-30 17:20:39 +00002384 if (C->isZero()) {
Anton Korobeynikov1bfd1212008-02-20 11:26:25 +00002385 if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op1)) {
Reid Spencerfdff9382006-11-08 06:47:33 +00002386 if (SI->getOpcode() == Instruction::LShr) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00002387 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
Chris Lattner92295c52004-03-12 23:53:13 +00002388 // Check to see if we are shifting out everything but the sign bit.
Zhou Shengfd28a332007-03-30 17:20:39 +00002389 if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
Reid Spencere0fc4df2006-10-20 07:07:24 +00002390 SI->getType()->getPrimitiveSizeInBits()-1) {
Reid Spencerfdff9382006-11-08 06:47:33 +00002391 // Ok, the transformation is safe. Insert AShr.
Gabor Greife1f6e4b2008-05-16 19:29:10 +00002392 return BinaryOperator::Create(Instruction::AShr,
Reid Spencer2341c222007-02-02 02:16:23 +00002393 SI->getOperand(0), CU, SI->getName());
Chris Lattner92295c52004-03-12 23:53:13 +00002394 }
2395 }
Reid Spencerfdff9382006-11-08 06:47:33 +00002396 }
2397 else if (SI->getOpcode() == Instruction::AShr) {
2398 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2399 // Check to see if we are shifting out everything but the sign bit.
Zhou Shengfd28a332007-03-30 17:20:39 +00002400 if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
Reid Spencerfdff9382006-11-08 06:47:33 +00002401 SI->getType()->getPrimitiveSizeInBits()-1) {
Reid Spencerc635f472006-12-31 05:48:39 +00002402 // Ok, the transformation is safe. Insert LShr.
Gabor Greife1f6e4b2008-05-16 19:29:10 +00002403 return BinaryOperator::CreateLShr(
Reid Spencer2341c222007-02-02 02:16:23 +00002404 SI->getOperand(0), CU, SI->getName());
Reid Spencerfdff9382006-11-08 06:47:33 +00002405 }
2406 }
Anton Korobeynikov1bfd1212008-02-20 11:26:25 +00002407 }
2408 }
Chris Lattner022167f2004-03-13 00:11:49 +00002409 }
Chris Lattner183b3362004-04-09 19:05:30 +00002410
2411 // Try to fold constant sub into select arguments.
2412 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner86102b82005-01-01 16:22:27 +00002413 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00002414 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00002415
2416 if (isa<PHINode>(Op0))
2417 if (Instruction *NV = FoldOpIntoPhi(I))
2418 return NV;
Chris Lattner8f2f5982003-11-05 01:06:05 +00002419 }
2420
Nick Lewycky26b8cd82008-05-31 17:59:52 +00002421 if (I.getType() == Type::Int1Ty)
2422 return BinaryOperator::CreateXor(Op0, Op1);
2423
Chris Lattnera9be4492005-04-07 16:15:25 +00002424 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
2425 if (Op1I->getOpcode() == Instruction::Add &&
Chris Lattner7a002fe2006-12-02 00:13:08 +00002426 !Op0->getType()->isFPOrFPVector()) {
Chris Lattnerc7f3c1a2005-04-07 16:28:01 +00002427 if (Op1I->getOperand(0) == Op0) // X-(X+Y) == -Y
Gabor Greife1f6e4b2008-05-16 19:29:10 +00002428 return BinaryOperator::CreateNeg(Op1I->getOperand(1), I.getName());
Chris Lattnerc7f3c1a2005-04-07 16:28:01 +00002429 else if (Op1I->getOperand(1) == Op0) // X-(Y+X) == -Y
Gabor Greife1f6e4b2008-05-16 19:29:10 +00002430 return BinaryOperator::CreateNeg(Op1I->getOperand(0), I.getName());
Chris Lattnerc7f3c1a2005-04-07 16:28:01 +00002431 else if (ConstantInt *CI1 = dyn_cast<ConstantInt>(I.getOperand(0))) {
2432 if (ConstantInt *CI2 = dyn_cast<ConstantInt>(Op1I->getOperand(1)))
2433 // C1-(X+C2) --> (C1-C2)-X
Gabor Greife1f6e4b2008-05-16 19:29:10 +00002434 return BinaryOperator::CreateSub(Subtract(CI1, CI2),
Chris Lattnerc7f3c1a2005-04-07 16:28:01 +00002435 Op1I->getOperand(0));
2436 }
Chris Lattnera9be4492005-04-07 16:15:25 +00002437 }
2438
Chris Lattnerf95d9b92003-10-15 16:48:29 +00002439 if (Op1I->hasOneUse()) {
Chris Lattner3082c5a2003-02-18 19:28:33 +00002440 // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
2441 // is not used by anyone else...
2442 //
Chris Lattnerc2f0aa52004-02-02 20:09:56 +00002443 if (Op1I->getOpcode() == Instruction::Sub &&
Chris Lattner7a002fe2006-12-02 00:13:08 +00002444 !Op1I->getType()->isFPOrFPVector()) {
Chris Lattner3082c5a2003-02-18 19:28:33 +00002445 // Swap the two operands of the subexpr...
2446 Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
2447 Op1I->setOperand(0, IIOp1);
2448 Op1I->setOperand(1, IIOp0);
Misha Brukmanb1c93172005-04-21 23:48:37 +00002449
Chris Lattner3082c5a2003-02-18 19:28:33 +00002450 // Create the new top level add instruction...
Gabor Greife1f6e4b2008-05-16 19:29:10 +00002451 return BinaryOperator::CreateAdd(Op0, Op1);
Chris Lattner3082c5a2003-02-18 19:28:33 +00002452 }
2453
2454 // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
2455 //
2456 if (Op1I->getOpcode() == Instruction::And &&
2457 (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
2458 Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
2459
Chris Lattner396dbfe2004-06-09 05:08:07 +00002460 Value *NewNot =
Gabor Greife1f6e4b2008-05-16 19:29:10 +00002461 InsertNewInstBefore(BinaryOperator::CreateNot(OtherOp, "B.not"), I);
2462 return BinaryOperator::CreateAnd(Op0, NewNot);
Chris Lattner3082c5a2003-02-18 19:28:33 +00002463 }
Chris Lattner57c8d992003-02-18 19:57:07 +00002464
Reid Spencer3c514952006-10-16 23:08:08 +00002465 // 0 - (X sdiv C) -> (X sdiv -C)
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002466 if (Op1I->getOpcode() == Instruction::SDiv)
Reid Spencere0fc4df2006-10-20 07:07:24 +00002467 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
Zhou Shengaafe4e22007-04-19 05:39:12 +00002468 if (CSI->isZero())
Chris Lattner0aee4b72004-10-06 15:08:25 +00002469 if (Constant *DivRHS = dyn_cast<Constant>(Op1I->getOperand(1)))
Gabor Greife1f6e4b2008-05-16 19:29:10 +00002470 return BinaryOperator::CreateSDiv(Op1I->getOperand(0),
Chris Lattner0aee4b72004-10-06 15:08:25 +00002471 ConstantExpr::getNeg(DivRHS));
2472
Chris Lattner57c8d992003-02-18 19:57:07 +00002473 // X - X*C --> X * (1-C)
Reid Spencer4fdd96c2005-06-18 17:37:34 +00002474 ConstantInt *C2 = 0;
Chris Lattner8c3e7b92004-11-13 19:50:12 +00002475 if (dyn_castFoldableMul(Op1I, C2) == Op0) {
Reid Spencer80263aa2007-03-25 05:33:51 +00002476 Constant *CP1 = Subtract(ConstantInt::get(I.getType(), 1), C2);
Gabor Greife1f6e4b2008-05-16 19:29:10 +00002477 return BinaryOperator::CreateMul(Op0, CP1);
Chris Lattner57c8d992003-02-18 19:57:07 +00002478 }
Dan Gohman2ac26522007-09-17 17:31:57 +00002479
2480 // X - ((X / Y) * Y) --> X % Y
2481 if (Op1I->getOpcode() == Instruction::Mul)
2482 if (Instruction *I = dyn_cast<Instruction>(Op1I->getOperand(0)))
2483 if (Op0 == I->getOperand(0) &&
2484 Op1I->getOperand(1) == I->getOperand(1)) {
2485 if (I->getOpcode() == Instruction::SDiv)
Gabor Greife1f6e4b2008-05-16 19:29:10 +00002486 return BinaryOperator::CreateSRem(Op0, Op1I->getOperand(1));
Dan Gohman2ac26522007-09-17 17:31:57 +00002487 if (I->getOpcode() == Instruction::UDiv)
Gabor Greife1f6e4b2008-05-16 19:29:10 +00002488 return BinaryOperator::CreateURem(Op0, Op1I->getOperand(1));
Dan Gohman2ac26522007-09-17 17:31:57 +00002489 }
Chris Lattnerad3c4952002-05-09 01:29:19 +00002490 }
Chris Lattnera9be4492005-04-07 16:15:25 +00002491 }
Chris Lattner3082c5a2003-02-18 19:28:33 +00002492
Chris Lattner7a002fe2006-12-02 00:13:08 +00002493 if (!Op0->getType()->isFPOrFPVector())
Anton Korobeynikov1bfd1212008-02-20 11:26:25 +00002494 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
Chris Lattner47060462005-04-07 17:14:51 +00002495 if (Op0I->getOpcode() == Instruction::Add) {
Chris Lattner411336f2005-01-19 21:50:18 +00002496 if (Op0I->getOperand(0) == Op1) // (Y+X)-Y == X
2497 return ReplaceInstUsesWith(I, Op0I->getOperand(1));
2498 else if (Op0I->getOperand(1) == Op1) // (X+Y)-Y == X
2499 return ReplaceInstUsesWith(I, Op0I->getOperand(0));
Chris Lattner47060462005-04-07 17:14:51 +00002500 } else if (Op0I->getOpcode() == Instruction::Sub) {
2501 if (Op0I->getOperand(0) == Op1) // (X-Y)-X == -Y
Gabor Greife1f6e4b2008-05-16 19:29:10 +00002502 return BinaryOperator::CreateNeg(Op0I->getOperand(1), I.getName());
Chris Lattner411336f2005-01-19 21:50:18 +00002503 }
Anton Korobeynikov1bfd1212008-02-20 11:26:25 +00002504 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00002505
Chris Lattner8c3e7b92004-11-13 19:50:12 +00002506 ConstantInt *C1;
2507 if (Value *X = dyn_castFoldableMul(Op0, C1)) {
Reid Spencer80263aa2007-03-25 05:33:51 +00002508 if (X == Op1) // X*C - X --> X * (C-1)
Gabor Greife1f6e4b2008-05-16 19:29:10 +00002509 return BinaryOperator::CreateMul(Op1, SubOne(C1));
Chris Lattner57c8d992003-02-18 19:57:07 +00002510
Chris Lattner8c3e7b92004-11-13 19:50:12 +00002511 ConstantInt *C2; // X*C1 - X*C2 -> X * (C1-C2)
2512 if (X == dyn_castFoldableMul(Op1, C2))
Gabor Greife1f6e4b2008-05-16 19:29:10 +00002513 return BinaryOperator::CreateMul(X, Subtract(C1, C2));
Chris Lattner8c3e7b92004-11-13 19:50:12 +00002514 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002515 return 0;
Chris Lattner260ab202002-04-18 17:39:14 +00002516}
2517
Chris Lattner06205d52007-07-15 20:42:37 +00002518/// isSignBitCheck - Given an exploded icmp instruction, return true if the
2519/// comparison only checks the sign bit. If it only checks the sign bit, set
2520/// TrueIfSigned if the result of the comparison is true when the input value is
2521/// signed.
2522static bool isSignBitCheck(ICmpInst::Predicate pred, ConstantInt *RHS,
2523 bool &TrueIfSigned) {
Reid Spencer266e42b2006-12-23 06:05:41 +00002524 switch (pred) {
Chris Lattner06205d52007-07-15 20:42:37 +00002525 case ICmpInst::ICMP_SLT: // True if LHS s< 0
2526 TrueIfSigned = true;
2527 return RHS->isZero();
Chris Lattner640fd512007-07-16 04:15:34 +00002528 case ICmpInst::ICMP_SLE: // True if LHS s<= RHS and RHS == -1
2529 TrueIfSigned = true;
2530 return RHS->isAllOnesValue();
Chris Lattner06205d52007-07-15 20:42:37 +00002531 case ICmpInst::ICMP_SGT: // True if LHS s> -1
2532 TrueIfSigned = false;
2533 return RHS->isAllOnesValue();
Chris Lattner640fd512007-07-16 04:15:34 +00002534 case ICmpInst::ICMP_UGT:
2535 // True if LHS u> RHS and RHS == high-bit-mask - 1
2536 TrueIfSigned = true;
2537 return RHS->getValue() ==
2538 APInt::getSignedMaxValue(RHS->getType()->getPrimitiveSizeInBits());
2539 case ICmpInst::ICMP_UGE:
2540 // True if LHS u>= RHS and RHS == high-bit-mask (2^7, 2^15, 2^31, etc)
2541 TrueIfSigned = true;
Chris Lattnera12a6de2008-06-02 01:29:46 +00002542 return RHS->getValue().isSignBit();
Chris Lattner06205d52007-07-15 20:42:37 +00002543 default:
2544 return false;
Chris Lattnere79e8542004-02-23 06:38:22 +00002545 }
Chris Lattnere79e8542004-02-23 06:38:22 +00002546}
2547
Chris Lattner113f4f42002-06-25 16:13:24 +00002548Instruction *InstCombiner::visitMul(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00002549 bool Changed = SimplifyCommutative(I);
Chris Lattner3082c5a2003-02-18 19:28:33 +00002550 Value *Op0 = I.getOperand(0);
Chris Lattner260ab202002-04-18 17:39:14 +00002551
Chris Lattner81a7a232004-10-16 18:11:37 +00002552 if (isa<UndefValue>(I.getOperand(1))) // undef * X -> 0
2553 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2554
Chris Lattnere6794492002-08-12 21:17:25 +00002555 // Simplify mul instructions with a constant RHS...
Chris Lattner3082c5a2003-02-18 19:28:33 +00002556 if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
2557 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Chris Lattnerede3fe02003-08-13 04:18:28 +00002558
2559 // ((X << C1)*C2) == (X * (C2 << C1))
Reid Spencer2341c222007-02-02 02:16:23 +00002560 if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op0))
Chris Lattnerede3fe02003-08-13 04:18:28 +00002561 if (SI->getOpcode() == Instruction::Shl)
2562 if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
Gabor Greife1f6e4b2008-05-16 19:29:10 +00002563 return BinaryOperator::CreateMul(SI->getOperand(0),
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002564 ConstantExpr::getShl(CI, ShOp));
Misha Brukmanb1c93172005-04-21 23:48:37 +00002565
Zhou Shengaafe4e22007-04-19 05:39:12 +00002566 if (CI->isZero())
Chris Lattnercce81be2003-09-11 22:24:54 +00002567 return ReplaceInstUsesWith(I, Op1); // X * 0 == 0
2568 if (CI->equalsInt(1)) // X * 1 == X
2569 return ReplaceInstUsesWith(I, Op0);
2570 if (CI->isAllOnesValue()) // X * -1 == 0 - X
Gabor Greife1f6e4b2008-05-16 19:29:10 +00002571 return BinaryOperator::CreateNeg(Op0, I.getName());
Chris Lattner31ba1292002-04-29 22:24:47 +00002572
Zhou Sheng4961cf12007-03-29 01:57:21 +00002573 const APInt& Val = cast<ConstantInt>(CI)->getValue();
Reid Spencer6d392062007-03-23 20:05:17 +00002574 if (Val.isPowerOf2()) { // Replace X*(2^C) with X << C
Gabor Greife1f6e4b2008-05-16 19:29:10 +00002575 return BinaryOperator::CreateShl(Op0,
Reid Spencer6d392062007-03-23 20:05:17 +00002576 ConstantInt::get(Op0->getType(), Val.logBase2()));
Chris Lattner22d00a82005-08-02 19:16:58 +00002577 }
Robert Bocchino7b5b86c2004-07-27 21:02:21 +00002578 } else if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1)) {
Chris Lattner3082c5a2003-02-18 19:28:33 +00002579 if (Op1F->isNullValue())
2580 return ReplaceInstUsesWith(I, Op1);
Chris Lattner31ba1292002-04-29 22:24:47 +00002581
Chris Lattner3082c5a2003-02-18 19:28:33 +00002582 // "In IEEE floating point, x*1 is not equivalent to x for nans. However,
2583 // ANSI says we can drop signals, so we can do this anyway." (from GCC)
Chris Lattner2aa0ff22008-08-11 22:06:05 +00002584 if (Op1F->isExactlyValue(1.0))
2585 return ReplaceInstUsesWith(I, Op0); // Eliminate 'mul double %X, 1.0'
2586 } else if (isa<VectorType>(Op1->getType())) {
2587 if (isa<ConstantAggregateZero>(Op1))
2588 return ReplaceInstUsesWith(I, Op1);
2589
2590 // As above, vector X*splat(1.0) -> X in all defined cases.
2591 if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1))
2592 if (ConstantFP *F = dyn_cast_or_null<ConstantFP>(Op1V->getSplatValue()))
2593 if (F->isExactlyValue(1.0))
2594 return ReplaceInstUsesWith(I, Op0);
Chris Lattner3082c5a2003-02-18 19:28:33 +00002595 }
Chris Lattner32c01df2006-03-04 06:04:02 +00002596
2597 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
2598 if (Op0I->getOpcode() == Instruction::Add && Op0I->hasOneUse() &&
Chris Lattner4b2a7242008-05-18 04:11:26 +00002599 isa<ConstantInt>(Op0I->getOperand(1)) && isa<ConstantInt>(Op1)) {
Chris Lattner32c01df2006-03-04 06:04:02 +00002600 // Canonicalize (X+C1)*C2 -> X*C2+C1*C2.
Gabor Greife1f6e4b2008-05-16 19:29:10 +00002601 Instruction *Add = BinaryOperator::CreateMul(Op0I->getOperand(0),
Chris Lattner32c01df2006-03-04 06:04:02 +00002602 Op1, "tmp");
2603 InsertNewInstBefore(Add, I);
2604 Value *C1C2 = ConstantExpr::getMul(Op1,
2605 cast<Constant>(Op0I->getOperand(1)));
Gabor Greife1f6e4b2008-05-16 19:29:10 +00002606 return BinaryOperator::CreateAdd(Add, C1C2);
Chris Lattner32c01df2006-03-04 06:04:02 +00002607
2608 }
Chris Lattner183b3362004-04-09 19:05:30 +00002609
2610 // Try to fold constant mul into select arguments.
2611 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner86102b82005-01-01 16:22:27 +00002612 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00002613 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00002614
2615 if (isa<PHINode>(Op0))
2616 if (Instruction *NV = FoldOpIntoPhi(I))
2617 return NV;
Chris Lattner260ab202002-04-18 17:39:14 +00002618 }
2619
Chris Lattner934a64cf2003-03-10 23:23:04 +00002620 if (Value *Op0v = dyn_castNegVal(Op0)) // -X * -Y = X*Y
2621 if (Value *Op1v = dyn_castNegVal(I.getOperand(1)))
Gabor Greife1f6e4b2008-05-16 19:29:10 +00002622 return BinaryOperator::CreateMul(Op0v, Op1v);
Chris Lattner934a64cf2003-03-10 23:23:04 +00002623
Nick Lewycky26b8cd82008-05-31 17:59:52 +00002624 if (I.getType() == Type::Int1Ty)
2625 return BinaryOperator::CreateAnd(Op0, I.getOperand(1));
2626
Chris Lattner2635b522004-02-23 05:39:21 +00002627 // If one of the operands of the multiply is a cast from a boolean value, then
2628 // we know the bool is either zero or one, so this is a 'masking' multiply.
2629 // See if we can simplify things based on how the boolean was originally
2630 // formed.
2631 CastInst *BoolCast = 0;
Nick Lewycky26b8cd82008-05-31 17:59:52 +00002632 if (ZExtInst *CI = dyn_cast<ZExtInst>(Op0))
Reid Spencer542964f2007-01-11 18:21:29 +00002633 if (CI->getOperand(0)->getType() == Type::Int1Ty)
Chris Lattner2635b522004-02-23 05:39:21 +00002634 BoolCast = CI;
2635 if (!BoolCast)
Reid Spencer74a528b2006-12-13 18:21:21 +00002636 if (ZExtInst *CI = dyn_cast<ZExtInst>(I.getOperand(1)))
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 Spencer266e42b2006-12-23 06:05:41 +00002640 if (ICmpInst *SCI = dyn_cast<ICmpInst>(BoolCast->getOperand(0))) {
Chris Lattner2635b522004-02-23 05:39:21 +00002641 Value *SCIOp0 = SCI->getOperand(0), *SCIOp1 = SCI->getOperand(1);
2642 const Type *SCOpTy = SCIOp0->getType();
Chris Lattner06205d52007-07-15 20:42:37 +00002643 bool TIS = false;
2644
Reid Spencer266e42b2006-12-23 06:05:41 +00002645 // If the icmp is true iff the sign bit of X is set, then convert this
Chris Lattnere79e8542004-02-23 06:38:22 +00002646 // multiply into a shift/and combination.
2647 if (isa<ConstantInt>(SCIOp1) &&
Chris Lattner06205d52007-07-15 20:42:37 +00002648 isSignBitCheck(SCI->getPredicate(), cast<ConstantInt>(SCIOp1), TIS) &&
2649 TIS) {
Chris Lattner2635b522004-02-23 05:39:21 +00002650 // Shift the X value right to turn it into "all signbits".
Reid Spencer2341c222007-02-02 02:16:23 +00002651 Constant *Amt = ConstantInt::get(SCIOp0->getType(),
Chris Lattnerd1f46d32005-04-24 06:59:08 +00002652 SCOpTy->getPrimitiveSizeInBits()-1);
Chris Lattnere79e8542004-02-23 06:38:22 +00002653 Value *V =
Reid Spencer2341c222007-02-02 02:16:23 +00002654 InsertNewInstBefore(
Gabor Greife1f6e4b2008-05-16 19:29:10 +00002655 BinaryOperator::Create(Instruction::AShr, SCIOp0, Amt,
Chris Lattnere79e8542004-02-23 06:38:22 +00002656 BoolCast->getOperand(0)->getName()+
2657 ".mask"), I);
Chris Lattner2635b522004-02-23 05:39:21 +00002658
2659 // If the multiply type is not the same as the source type, sign extend
2660 // or truncate to the multiply type.
Reid Spencer13bc5d72006-12-12 09:18:51 +00002661 if (I.getType() != V->getType()) {
Zhou Sheng56cda952007-04-02 08:20:41 +00002662 uint32_t SrcBits = V->getType()->getPrimitiveSizeInBits();
2663 uint32_t DstBits = I.getType()->getPrimitiveSizeInBits();
Reid Spencer13bc5d72006-12-12 09:18:51 +00002664 Instruction::CastOps opcode =
2665 (SrcBits == DstBits ? Instruction::BitCast :
2666 (SrcBits < DstBits ? Instruction::SExt : Instruction::Trunc));
2667 V = InsertCastBefore(opcode, V, I.getType(), I);
2668 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00002669
Chris Lattner2635b522004-02-23 05:39:21 +00002670 Value *OtherOp = Op0 == BoolCast ? I.getOperand(1) : Op0;
Gabor Greife1f6e4b2008-05-16 19:29:10 +00002671 return BinaryOperator::CreateAnd(V, OtherOp);
Chris Lattner2635b522004-02-23 05:39:21 +00002672 }
2673 }
2674 }
2675
Chris Lattner113f4f42002-06-25 16:13:24 +00002676 return Changed ? &I : 0;
Chris Lattner260ab202002-04-18 17:39:14 +00002677}
2678
Chris Lattner16395e52008-07-14 00:15:52 +00002679/// SimplifyDivRemOfSelect - Try to fold a divide or remainder of a select
2680/// instruction.
2681bool InstCombiner::SimplifyDivRemOfSelect(BinaryOperator &I) {
2682 SelectInst *SI = cast<SelectInst>(I.getOperand(1));
2683
2684 // div/rem X, (Cond ? 0 : Y) -> div/rem X, Y
2685 int NonNullOperand = -1;
2686 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
2687 if (ST->isNullValue())
2688 NonNullOperand = 2;
2689 // div/rem X, (Cond ? Y : 0) -> div/rem X, Y
2690 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
2691 if (ST->isNullValue())
2692 NonNullOperand = 1;
2693
2694 if (NonNullOperand == -1)
2695 return false;
2696
2697 Value *SelectCond = SI->getOperand(0);
2698
2699 // Change the div/rem to use 'Y' instead of the select.
2700 I.setOperand(1, SI->getOperand(NonNullOperand));
2701
2702 // Okay, we know we replace the operand of the div/rem with 'Y' with no
2703 // problem. However, the select, or the condition of the select may have
2704 // multiple uses. Based on our knowledge that the operand must be non-zero,
2705 // propagate the known value for the select into other uses of it, and
2706 // propagate a known value of the condition into its other users.
2707
2708 // If the select and condition only have a single use, don't bother with this,
2709 // early exit.
2710 if (SI->use_empty() && SelectCond->hasOneUse())
2711 return true;
2712
2713 // Scan the current block backward, looking for other uses of SI.
2714 BasicBlock::iterator BBI = &I, BBFront = I.getParent()->begin();
2715
2716 while (BBI != BBFront) {
2717 --BBI;
2718 // If we found a call to a function, we can't assume it will return, so
2719 // information from below it cannot be propagated above it.
2720 if (isa<CallInst>(BBI) && !isa<IntrinsicInst>(BBI))
2721 break;
2722
2723 // Replace uses of the select or its condition with the known values.
2724 for (Instruction::op_iterator I = BBI->op_begin(), E = BBI->op_end();
2725 I != E; ++I) {
2726 if (*I == SI) {
2727 *I = SI->getOperand(NonNullOperand);
2728 AddToWorkList(BBI);
2729 } else if (*I == SelectCond) {
2730 *I = NonNullOperand == 1 ? ConstantInt::getTrue() :
2731 ConstantInt::getFalse();
2732 AddToWorkList(BBI);
2733 }
2734 }
2735
2736 // If we past the instruction, quit looking for it.
2737 if (&*BBI == SI)
2738 SI = 0;
2739 if (&*BBI == SelectCond)
2740 SelectCond = 0;
2741
2742 // If we ran out of things to eliminate, break out of the loop.
2743 if (SelectCond == 0 && SI == 0)
2744 break;
2745
2746 }
2747 return true;
2748}
2749
2750
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002751/// This function implements the transforms on div instructions that work
2752/// regardless of the kind of div instruction it is (udiv, sdiv, or fdiv). It is
2753/// used by the visitors to those instructions.
2754/// @brief Transforms common to all three div instructions
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002755Instruction *InstCombiner::commonDivTransforms(BinaryOperator &I) {
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00002756 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner81a7a232004-10-16 18:11:37 +00002757
Chris Lattner0fe6bce2008-02-19 06:12:18 +00002758 // undef / X -> 0 for integer.
2759 // undef / X -> undef for FP (the undef could be a snan).
2760 if (isa<UndefValue>(Op0)) {
2761 if (Op0->getType()->isFPOrFPVector())
2762 return ReplaceInstUsesWith(I, Op0);
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00002763 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner0fe6bce2008-02-19 06:12:18 +00002764 }
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002765
2766 // X / undef -> undef
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00002767 if (isa<UndefValue>(Op1))
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002768 return ReplaceInstUsesWith(I, Op1);
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00002769
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002770 return 0;
2771}
Misha Brukmanb1c93172005-04-21 23:48:37 +00002772
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002773/// This function implements the transforms common to both integer division
2774/// instructions (udiv and sdiv). It is called by the visitors to those integer
2775/// division instructions.
2776/// @brief Common integer divide transforms
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002777Instruction *InstCombiner::commonIDivTransforms(BinaryOperator &I) {
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002778 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2779
Chris Lattner5c953b72008-05-16 02:59:42 +00002780 // (sdiv X, X) --> 1 (udiv X, X) --> 1
Nick Lewycky2ec9a012008-05-23 03:26:47 +00002781 if (Op0 == Op1) {
2782 if (const VectorType *Ty = dyn_cast<VectorType>(I.getType())) {
2783 ConstantInt *CI = ConstantInt::get(Ty->getElementType(), 1);
2784 std::vector<Constant*> Elts(Ty->getNumElements(), CI);
2785 return ReplaceInstUsesWith(I, ConstantVector::get(Elts));
2786 }
2787
2788 ConstantInt *CI = ConstantInt::get(I.getType(), 1);
2789 return ReplaceInstUsesWith(I, CI);
2790 }
Chris Lattner5c953b72008-05-16 02:59:42 +00002791
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002792 if (Instruction *Common = commonDivTransforms(I))
2793 return Common;
Chris Lattner16395e52008-07-14 00:15:52 +00002794
2795 // Handle cases involving: [su]div X, (select Cond, Y, Z)
2796 // This does not apply for fdiv.
2797 if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
2798 return &I;
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002799
2800 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2801 // div X, 1 == X
2802 if (RHS->equalsInt(1))
2803 return ReplaceInstUsesWith(I, Op0);
2804
2805 // (X / C1) / C2 -> X / (C1*C2)
2806 if (Instruction *LHS = dyn_cast<Instruction>(Op0))
2807 if (Instruction::BinaryOps(LHS->getOpcode()) == I.getOpcode())
2808 if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
Nick Lewyckyfefd0202008-02-18 22:48:05 +00002809 if (MultiplyOverflows(RHS, LHSRHS, I.getOpcode()==Instruction::SDiv))
2810 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2811 else
Gabor Greife1f6e4b2008-05-16 19:29:10 +00002812 return BinaryOperator::Create(I.getOpcode(), LHS->getOperand(0),
Nick Lewyckyfefd0202008-02-18 22:48:05 +00002813 Multiply(RHS, LHSRHS));
Chris Lattner42362612005-04-08 04:03:26 +00002814 }
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002815
Reid Spencer6d392062007-03-23 20:05:17 +00002816 if (!RHS->isZero()) { // avoid X udiv 0
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002817 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2818 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2819 return R;
2820 if (isa<PHINode>(Op0))
2821 if (Instruction *NV = FoldOpIntoPhi(I))
2822 return NV;
2823 }
Chris Lattnerd79dc792006-09-09 20:26:32 +00002824 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00002825
Chris Lattner3082c5a2003-02-18 19:28:33 +00002826 // 0 / X == 0, we don't need to preserve faults!
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00002827 if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
Chris Lattner3082c5a2003-02-18 19:28:33 +00002828 if (LHS->equalsInt(0))
2829 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2830
Nick Lewycky26b8cd82008-05-31 17:59:52 +00002831 // It can't be division by zero, hence it must be division by one.
2832 if (I.getType() == Type::Int1Ty)
2833 return ReplaceInstUsesWith(I, Op0);
2834
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002835 return 0;
2836}
2837
2838Instruction *InstCombiner::visitUDiv(BinaryOperator &I) {
2839 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2840
2841 // Handle the integer div common cases
2842 if (Instruction *Common = commonIDivTransforms(I))
2843 return Common;
2844
2845 // X udiv C^2 -> X >> C
2846 // Check to see if this is an unsigned division with an exact power of 2,
2847 // if so, convert to a right shift.
2848 if (ConstantInt *C = dyn_cast<ConstantInt>(Op1)) {
Reid Spencer54d5b1b2007-03-26 23:58:26 +00002849 if (C->getValue().isPowerOf2()) // 0 not included in isPowerOf2
Gabor Greife1f6e4b2008-05-16 19:29:10 +00002850 return BinaryOperator::CreateLShr(Op0,
Zhou Sheng222d5eb2007-03-25 05:01:29 +00002851 ConstantInt::get(Op0->getType(), C->getValue().logBase2()));
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002852 }
2853
2854 // X udiv (C1 << N), where C1 is "1<<C2" --> X >> (N+C2)
Reid Spencer2341c222007-02-02 02:16:23 +00002855 if (BinaryOperator *RHSI = dyn_cast<BinaryOperator>(I.getOperand(1))) {
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002856 if (RHSI->getOpcode() == Instruction::Shl &&
2857 isa<ConstantInt>(RHSI->getOperand(0))) {
Zhou Sheng150f3bb2007-04-01 17:13:37 +00002858 const APInt& C1 = cast<ConstantInt>(RHSI->getOperand(0))->getValue();
Reid Spencer6d392062007-03-23 20:05:17 +00002859 if (C1.isPowerOf2()) {
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002860 Value *N = RHSI->getOperand(1);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002861 const Type *NTy = N->getType();
Reid Spencer959a21d2007-03-23 21:24:59 +00002862 if (uint32_t C2 = C1.logBase2()) {
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002863 Constant *C2V = ConstantInt::get(NTy, C2);
Gabor Greife1f6e4b2008-05-16 19:29:10 +00002864 N = InsertNewInstBefore(BinaryOperator::CreateAdd(N, C2V, "tmp"), I);
Chris Lattner2e90b732006-02-05 07:54:04 +00002865 }
Gabor Greife1f6e4b2008-05-16 19:29:10 +00002866 return BinaryOperator::CreateLShr(Op0, N);
Chris Lattner2e90b732006-02-05 07:54:04 +00002867 }
2868 }
Chris Lattnerdd0c1742005-11-05 07:40:31 +00002869 }
2870
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002871 // udiv X, (Select Cond, C1, C2) --> Select Cond, (shr X, C1), (shr X, C2)
2872 // where C1&C2 are powers of two.
Reid Spencer3939b1a2007-03-05 23:36:13 +00002873 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002874 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
Reid Spencer3939b1a2007-03-05 23:36:13 +00002875 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
Zhou Sheng150f3bb2007-04-01 17:13:37 +00002876 const APInt &TVA = STO->getValue(), &FVA = SFO->getValue();
Reid Spencer6d392062007-03-23 20:05:17 +00002877 if (TVA.isPowerOf2() && FVA.isPowerOf2()) {
Reid Spencer3939b1a2007-03-05 23:36:13 +00002878 // Compute the shift amounts
Reid Spencer6d392062007-03-23 20:05:17 +00002879 uint32_t TSA = TVA.logBase2(), FSA = FVA.logBase2();
Reid Spencer3939b1a2007-03-05 23:36:13 +00002880 // Construct the "on true" case of the select
2881 Constant *TC = ConstantInt::get(Op0->getType(), TSA);
Gabor Greife1f6e4b2008-05-16 19:29:10 +00002882 Instruction *TSI = BinaryOperator::CreateLShr(
Reid Spencer3939b1a2007-03-05 23:36:13 +00002883 Op0, TC, SI->getName()+".t");
2884 TSI = InsertNewInstBefore(TSI, I);
2885
2886 // Construct the "on false" case of the select
2887 Constant *FC = ConstantInt::get(Op0->getType(), FSA);
Gabor Greife1f6e4b2008-05-16 19:29:10 +00002888 Instruction *FSI = BinaryOperator::CreateLShr(
Reid Spencer3939b1a2007-03-05 23:36:13 +00002889 Op0, FC, SI->getName()+".f");
2890 FSI = InsertNewInstBefore(FSI, I);
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002891
Reid Spencer3939b1a2007-03-05 23:36:13 +00002892 // construct the select instruction and return it.
Gabor Greife9ecc682008-04-06 20:25:17 +00002893 return SelectInst::Create(SI->getOperand(0), TSI, FSI, SI->getName());
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002894 }
Reid Spencer3939b1a2007-03-05 23:36:13 +00002895 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002896 return 0;
2897}
2898
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002899Instruction *InstCombiner::visitSDiv(BinaryOperator &I) {
2900 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2901
2902 // Handle the integer div common cases
2903 if (Instruction *Common = commonIDivTransforms(I))
2904 return Common;
2905
2906 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2907 // sdiv X, -1 == -X
2908 if (RHS->isAllOnesValue())
Gabor Greife1f6e4b2008-05-16 19:29:10 +00002909 return BinaryOperator::CreateNeg(Op0);
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002910
2911 // -X/C -> X/-C
2912 if (Value *LHSNeg = dyn_castNegVal(Op0))
Gabor Greife1f6e4b2008-05-16 19:29:10 +00002913 return BinaryOperator::CreateSDiv(LHSNeg, ConstantExpr::getNeg(RHS));
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002914 }
2915
2916 // If the sign bits of both operands are zero (i.e. we can prove they are
2917 // unsigned inputs), turn this into a udiv.
Chris Lattner03c49532007-01-15 02:27:26 +00002918 if (I.getType()->isInteger()) {
Reid Spencer6d392062007-03-23 20:05:17 +00002919 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002920 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
Dan Gohman4decbc52007-11-05 23:16:33 +00002921 // X sdiv Y -> X udiv Y, iff X and Y don't have sign bit set
Gabor Greife1f6e4b2008-05-16 19:29:10 +00002922 return BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002923 }
2924 }
2925
2926 return 0;
2927}
2928
2929Instruction *InstCombiner::visitFDiv(BinaryOperator &I) {
2930 return commonDivTransforms(I);
2931}
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002932
Reid Spencer7eb55b32006-11-02 01:53:59 +00002933/// This function implements the transforms on rem instructions that work
2934/// regardless of the kind of rem instruction it is (urem, srem, or frem). It
2935/// is used by the visitors to those instructions.
2936/// @brief Transforms common to all three rem instructions
2937Instruction *InstCombiner::commonRemTransforms(BinaryOperator &I) {
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00002938 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Reid Spencer7eb55b32006-11-02 01:53:59 +00002939
Chris Lattner0fe6bce2008-02-19 06:12:18 +00002940 // 0 % X == 0 for integer, we don't need to preserve faults!
Chris Lattner0de4a8d2006-02-28 05:30:45 +00002941 if (Constant *LHS = dyn_cast<Constant>(Op0))
2942 if (LHS->isNullValue())
2943 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2944
Chris Lattner0fe6bce2008-02-19 06:12:18 +00002945 if (isa<UndefValue>(Op0)) { // undef % X -> 0
2946 if (I.getType()->isFPOrFPVector())
2947 return ReplaceInstUsesWith(I, Op0); // X % undef -> undef (could be SNaN)
Chris Lattner0de4a8d2006-02-28 05:30:45 +00002948 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner0fe6bce2008-02-19 06:12:18 +00002949 }
Chris Lattner0de4a8d2006-02-28 05:30:45 +00002950 if (isa<UndefValue>(Op1))
2951 return ReplaceInstUsesWith(I, Op1); // X % undef -> undef
Reid Spencer7eb55b32006-11-02 01:53:59 +00002952
2953 // Handle cases involving: rem X, (select Cond, Y, Z)
Chris Lattner16395e52008-07-14 00:15:52 +00002954 if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
2955 return &I;
Chris Lattner7fd5f072004-07-06 07:01:22 +00002956
Reid Spencer7eb55b32006-11-02 01:53:59 +00002957 return 0;
2958}
2959
2960/// This function implements the transforms common to both integer remainder
2961/// instructions (urem and srem). It is called by the visitors to those integer
2962/// remainder instructions.
2963/// @brief Common integer remainder transforms
2964Instruction *InstCombiner::commonIRemTransforms(BinaryOperator &I) {
2965 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2966
2967 if (Instruction *common = commonRemTransforms(I))
2968 return common;
2969
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00002970 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner0de4a8d2006-02-28 05:30:45 +00002971 // X % 0 == undef, we don't need to preserve faults!
2972 if (RHS->equalsInt(0))
2973 return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
2974
Chris Lattner3082c5a2003-02-18 19:28:33 +00002975 if (RHS->equalsInt(1)) // X % 1 == 0
2976 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2977
Chris Lattnerb70f1412006-02-28 05:49:21 +00002978 if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
2979 if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
2980 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2981 return R;
2982 } else if (isa<PHINode>(Op0I)) {
2983 if (Instruction *NV = FoldOpIntoPhi(I))
2984 return NV;
Chris Lattnerb70f1412006-02-28 05:49:21 +00002985 }
Nick Lewyckyd0b62a12008-03-06 06:48:30 +00002986
2987 // See if we can fold away this rem instruction.
2988 uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
2989 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
2990 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
2991 KnownZero, KnownOne))
2992 return &I;
Chris Lattnerb70f1412006-02-28 05:49:21 +00002993 }
Chris Lattner3082c5a2003-02-18 19:28:33 +00002994 }
2995
Reid Spencer7eb55b32006-11-02 01:53:59 +00002996 return 0;
2997}
2998
2999Instruction *InstCombiner::visitURem(BinaryOperator &I) {
3000 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3001
3002 if (Instruction *common = commonIRemTransforms(I))
3003 return common;
3004
3005 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3006 // X urem C^2 -> X and C
3007 // Check to see if this is an unsigned remainder with an exact power of 2,
3008 // if so, convert to a bitwise and.
3009 if (ConstantInt *C = dyn_cast<ConstantInt>(RHS))
Reid Spencer6d392062007-03-23 20:05:17 +00003010 if (C->getValue().isPowerOf2())
Gabor Greife1f6e4b2008-05-16 19:29:10 +00003011 return BinaryOperator::CreateAnd(Op0, SubOne(C));
Reid Spencer7eb55b32006-11-02 01:53:59 +00003012 }
3013
Chris Lattner2e90b732006-02-05 07:54:04 +00003014 if (Instruction *RHSI = dyn_cast<Instruction>(I.getOperand(1))) {
Reid Spencer7eb55b32006-11-02 01:53:59 +00003015 // Turn A % (C << N), where C is 2^k, into A & ((C << N)-1)
3016 if (RHSI->getOpcode() == Instruction::Shl &&
3017 isa<ConstantInt>(RHSI->getOperand(0))) {
Zhou Sheng222d5eb2007-03-25 05:01:29 +00003018 if (cast<ConstantInt>(RHSI->getOperand(0))->getValue().isPowerOf2()) {
Chris Lattner2e90b732006-02-05 07:54:04 +00003019 Constant *N1 = ConstantInt::getAllOnesValue(I.getType());
Gabor Greife1f6e4b2008-05-16 19:29:10 +00003020 Value *Add = InsertNewInstBefore(BinaryOperator::CreateAdd(RHSI, N1,
Chris Lattner2e90b732006-02-05 07:54:04 +00003021 "tmp"), I);
Gabor Greife1f6e4b2008-05-16 19:29:10 +00003022 return BinaryOperator::CreateAnd(Op0, Add);
Chris Lattner2e90b732006-02-05 07:54:04 +00003023 }
3024 }
Reid Spencer7eb55b32006-11-02 01:53:59 +00003025 }
Chris Lattnerd79dc792006-09-09 20:26:32 +00003026
Reid Spencer7eb55b32006-11-02 01:53:59 +00003027 // urem X, (select Cond, 2^C1, 2^C2) --> select Cond, (and X, C1), (and X, C2)
3028 // where C1&C2 are powers of two.
3029 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
3030 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
3031 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
3032 // STO == 0 and SFO == 0 handled above.
Reid Spencer6d392062007-03-23 20:05:17 +00003033 if ((STO->getValue().isPowerOf2()) &&
3034 (SFO->getValue().isPowerOf2())) {
Reid Spencer7eb55b32006-11-02 01:53:59 +00003035 Value *TrueAnd = InsertNewInstBefore(
Gabor Greife1f6e4b2008-05-16 19:29:10 +00003036 BinaryOperator::CreateAnd(Op0, SubOne(STO), SI->getName()+".t"), I);
Reid Spencer7eb55b32006-11-02 01:53:59 +00003037 Value *FalseAnd = InsertNewInstBefore(
Gabor Greife1f6e4b2008-05-16 19:29:10 +00003038 BinaryOperator::CreateAnd(Op0, SubOne(SFO), SI->getName()+".f"), I);
Gabor Greife9ecc682008-04-06 20:25:17 +00003039 return SelectInst::Create(SI->getOperand(0), TrueAnd, FalseAnd);
Reid Spencer7eb55b32006-11-02 01:53:59 +00003040 }
3041 }
Chris Lattner2e90b732006-02-05 07:54:04 +00003042 }
3043
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003044 return 0;
3045}
3046
Reid Spencer7eb55b32006-11-02 01:53:59 +00003047Instruction *InstCombiner::visitSRem(BinaryOperator &I) {
3048 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3049
Dan Gohman4decbc52007-11-05 23:16:33 +00003050 // Handle the integer rem common cases
Reid Spencer7eb55b32006-11-02 01:53:59 +00003051 if (Instruction *common = commonIRemTransforms(I))
3052 return common;
3053
3054 if (Value *RHSNeg = dyn_castNegVal(Op1))
Nick Lewycky2fcb26c2008-09-03 06:24:21 +00003055 if (!isa<Constant>(RHSNeg) ||
3056 (isa<ConstantInt>(RHSNeg) &&
3057 cast<ConstantInt>(RHSNeg)->getValue().isStrictlyPositive())) {
Reid Spencer7eb55b32006-11-02 01:53:59 +00003058 // X % -Y -> X % Y
3059 AddUsesToWorkList(I);
3060 I.setOperand(1, RHSNeg);
3061 return &I;
3062 }
Nick Lewyckye8ced3e2008-09-30 06:08:34 +00003063
Dan Gohman4decbc52007-11-05 23:16:33 +00003064 // If the sign bits of both operands are zero (i.e. we can prove they are
Reid Spencer7eb55b32006-11-02 01:53:59 +00003065 // unsigned inputs), turn this into a urem.
Dan Gohman4decbc52007-11-05 23:16:33 +00003066 if (I.getType()->isInteger()) {
3067 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
3068 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
3069 // X srem Y -> X urem Y, iff X and Y don't have sign bit set
Gabor Greife1f6e4b2008-05-16 19:29:10 +00003070 return BinaryOperator::CreateURem(Op0, Op1, I.getName());
Dan Gohman4decbc52007-11-05 23:16:33 +00003071 }
Reid Spencer7eb55b32006-11-02 01:53:59 +00003072 }
3073
3074 return 0;
3075}
3076
3077Instruction *InstCombiner::visitFRem(BinaryOperator &I) {
Reid Spencer7eb55b32006-11-02 01:53:59 +00003078 return commonRemTransforms(I);
3079}
3080
Chris Lattner35167c32004-06-09 07:59:58 +00003081// isOneBitSet - Return true if there is exactly one bit set in the specified
3082// constant.
3083static bool isOneBitSet(const ConstantInt *CI) {
Reid Spencer66827212007-03-20 00:16:52 +00003084 return CI->getValue().isPowerOf2();
Chris Lattner35167c32004-06-09 07:59:58 +00003085}
3086
Chris Lattner8fc5af42004-09-23 21:46:38 +00003087// isHighOnes - Return true if the constant is of the form 1+0+.
3088// This is the same as lowones(~X).
3089static bool isHighOnes(const ConstantInt *CI) {
Zhou Shengb3949342007-03-20 12:49:06 +00003090 return (~CI->getValue() + 1).isPowerOf2();
Chris Lattner8fc5af42004-09-23 21:46:38 +00003091}
3092
Reid Spencer266e42b2006-12-23 06:05:41 +00003093/// getICmpCode - Encode a icmp predicate into a three bit mask. These bits
Chris Lattner3ac7c262003-08-13 20:16:26 +00003094/// are carefully arranged to allow folding of expressions such as:
3095///
3096/// (A < B) | (A > B) --> (A != B)
3097///
Reid Spencer266e42b2006-12-23 06:05:41 +00003098/// Note that this is only valid if the first and second predicates have the
3099/// same sign. Is illegal to do: (A u< B) | (A s> B)
Chris Lattner3ac7c262003-08-13 20:16:26 +00003100///
Reid Spencer266e42b2006-12-23 06:05:41 +00003101/// Three bits are used to represent the condition, as follows:
3102/// 0 A > B
3103/// 1 A == B
3104/// 2 A < B
3105///
3106/// <=> Value Definition
3107/// 000 0 Always false
3108/// 001 1 A > B
3109/// 010 2 A == B
3110/// 011 3 A >= B
3111/// 100 4 A < B
3112/// 101 5 A != B
3113/// 110 6 A <= B
3114/// 111 7 Always true
3115///
3116static unsigned getICmpCode(const ICmpInst *ICI) {
3117 switch (ICI->getPredicate()) {
Chris Lattner3ac7c262003-08-13 20:16:26 +00003118 // False -> 0
Reid Spencer266e42b2006-12-23 06:05:41 +00003119 case ICmpInst::ICMP_UGT: return 1; // 001
3120 case ICmpInst::ICMP_SGT: return 1; // 001
3121 case ICmpInst::ICMP_EQ: return 2; // 010
3122 case ICmpInst::ICMP_UGE: return 3; // 011
3123 case ICmpInst::ICMP_SGE: return 3; // 011
3124 case ICmpInst::ICMP_ULT: return 4; // 100
3125 case ICmpInst::ICMP_SLT: return 4; // 100
3126 case ICmpInst::ICMP_NE: return 5; // 101
3127 case ICmpInst::ICMP_ULE: return 6; // 110
3128 case ICmpInst::ICMP_SLE: return 6; // 110
Chris Lattner3ac7c262003-08-13 20:16:26 +00003129 // True -> 7
3130 default:
Reid Spencer266e42b2006-12-23 06:05:41 +00003131 assert(0 && "Invalid ICmp predicate!");
Chris Lattner3ac7c262003-08-13 20:16:26 +00003132 return 0;
3133 }
3134}
3135
Evan Cheng67786cc2008-10-14 17:15:11 +00003136/// getFCmpCode - Similar to getICmpCode but for FCmpInst. This encodes a fcmp
3137/// predicate into a three bit mask. It also returns whether it is an ordered
3138/// predicate by reference.
3139static unsigned getFCmpCode(FCmpInst::Predicate CC, bool &isOrdered) {
3140 isOrdered = false;
3141 switch (CC) {
3142 case FCmpInst::FCMP_ORD: isOrdered = true; return 0; // 000
3143 case FCmpInst::FCMP_UNO: return 0; // 000
Evan Chengce707522008-10-14 18:13:38 +00003144 case FCmpInst::FCMP_OGT: isOrdered = true; return 1; // 001
3145 case FCmpInst::FCMP_UGT: return 1; // 001
3146 case FCmpInst::FCMP_OEQ: isOrdered = true; return 2; // 010
3147 case FCmpInst::FCMP_UEQ: return 2; // 010
Evan Cheng67786cc2008-10-14 17:15:11 +00003148 case FCmpInst::FCMP_OGE: isOrdered = true; return 3; // 011
3149 case FCmpInst::FCMP_UGE: return 3; // 011
3150 case FCmpInst::FCMP_OLT: isOrdered = true; return 4; // 100
3151 case FCmpInst::FCMP_ULT: return 4; // 100
Evan Chengce707522008-10-14 18:13:38 +00003152 case FCmpInst::FCMP_ONE: isOrdered = true; return 5; // 101
3153 case FCmpInst::FCMP_UNE: return 5; // 101
Evan Cheng67786cc2008-10-14 17:15:11 +00003154 case FCmpInst::FCMP_OLE: isOrdered = true; return 6; // 110
3155 case FCmpInst::FCMP_ULE: return 6; // 110
Evan Chengd885f6e2008-10-14 18:44:08 +00003156 // True -> 7
Evan Cheng67786cc2008-10-14 17:15:11 +00003157 default:
3158 // Not expecting FCMP_FALSE and FCMP_TRUE;
3159 assert(0 && "Unexpected FCmp predicate!");
3160 return 0;
3161 }
3162}
3163
Reid Spencer266e42b2006-12-23 06:05:41 +00003164/// getICmpValue - This is the complement of getICmpCode, which turns an
3165/// opcode and two operands into either a constant true or false, or a brand
Dan Gohman2ac26522007-09-17 17:31:57 +00003166/// new ICmp instruction. The sign is passed in to determine which kind
Evan Cheng67786cc2008-10-14 17:15:11 +00003167/// of predicate to use in the new icmp instruction.
Reid Spencer266e42b2006-12-23 06:05:41 +00003168static Value *getICmpValue(bool sign, unsigned code, Value *LHS, Value *RHS) {
3169 switch (code) {
3170 default: assert(0 && "Illegal ICmp code!");
Zhou Sheng75b871f2007-01-11 12:24:14 +00003171 case 0: return ConstantInt::getFalse();
Reid Spencer266e42b2006-12-23 06:05:41 +00003172 case 1:
3173 if (sign)
3174 return new ICmpInst(ICmpInst::ICMP_SGT, LHS, RHS);
3175 else
3176 return new ICmpInst(ICmpInst::ICMP_UGT, LHS, RHS);
3177 case 2: return new ICmpInst(ICmpInst::ICMP_EQ, LHS, RHS);
3178 case 3:
3179 if (sign)
3180 return new ICmpInst(ICmpInst::ICMP_SGE, LHS, RHS);
3181 else
3182 return new ICmpInst(ICmpInst::ICMP_UGE, LHS, RHS);
3183 case 4:
3184 if (sign)
3185 return new ICmpInst(ICmpInst::ICMP_SLT, LHS, RHS);
3186 else
3187 return new ICmpInst(ICmpInst::ICMP_ULT, LHS, RHS);
3188 case 5: return new ICmpInst(ICmpInst::ICMP_NE, LHS, RHS);
3189 case 6:
3190 if (sign)
3191 return new ICmpInst(ICmpInst::ICMP_SLE, LHS, RHS);
3192 else
3193 return new ICmpInst(ICmpInst::ICMP_ULE, LHS, RHS);
Zhou Sheng75b871f2007-01-11 12:24:14 +00003194 case 7: return ConstantInt::getTrue();
Chris Lattner3ac7c262003-08-13 20:16:26 +00003195 }
3196}
3197
Evan Cheng67786cc2008-10-14 17:15:11 +00003198/// getFCmpValue - This is the complement of getFCmpCode, which turns an
3199/// opcode and two operands into either a FCmp instruction. isordered is passed
3200/// in to determine which kind of predicate to use in the new fcmp instruction.
3201static Value *getFCmpValue(bool isordered, unsigned code,
3202 Value *LHS, Value *RHS) {
3203 switch (code) {
Evan Chengce707522008-10-14 18:13:38 +00003204 default: assert(0 && "Illegal FCmp code!");
Evan Cheng67786cc2008-10-14 17:15:11 +00003205 case 0:
3206 if (isordered)
3207 return new FCmpInst(FCmpInst::FCMP_ORD, LHS, RHS);
3208 else
3209 return new FCmpInst(FCmpInst::FCMP_UNO, LHS, RHS);
3210 case 1:
3211 if (isordered)
Evan Cheng67786cc2008-10-14 17:15:11 +00003212 return new FCmpInst(FCmpInst::FCMP_OGT, LHS, RHS);
3213 else
3214 return new FCmpInst(FCmpInst::FCMP_UGT, LHS, RHS);
Evan Chengce707522008-10-14 18:13:38 +00003215 case 2:
3216 if (isordered)
3217 return new FCmpInst(FCmpInst::FCMP_OEQ, LHS, RHS);
3218 else
3219 return new FCmpInst(FCmpInst::FCMP_UEQ, LHS, RHS);
Evan Cheng67786cc2008-10-14 17:15:11 +00003220 case 3:
3221 if (isordered)
3222 return new FCmpInst(FCmpInst::FCMP_OGE, LHS, RHS);
3223 else
3224 return new FCmpInst(FCmpInst::FCMP_UGE, LHS, RHS);
3225 case 4:
3226 if (isordered)
3227 return new FCmpInst(FCmpInst::FCMP_OLT, LHS, RHS);
3228 else
3229 return new FCmpInst(FCmpInst::FCMP_ULT, LHS, RHS);
3230 case 5:
3231 if (isordered)
Evan Chengce707522008-10-14 18:13:38 +00003232 return new FCmpInst(FCmpInst::FCMP_ONE, LHS, RHS);
3233 else
3234 return new FCmpInst(FCmpInst::FCMP_UNE, LHS, RHS);
3235 case 6:
3236 if (isordered)
Evan Cheng67786cc2008-10-14 17:15:11 +00003237 return new FCmpInst(FCmpInst::FCMP_OLE, LHS, RHS);
3238 else
3239 return new FCmpInst(FCmpInst::FCMP_ULE, LHS, RHS);
Evan Chengd885f6e2008-10-14 18:44:08 +00003240 case 7: return ConstantInt::getTrue();
Evan Cheng67786cc2008-10-14 17:15:11 +00003241 }
3242}
3243
Chris Lattnerb37b6e72008-11-16 04:55:20 +00003244/// PredicatesFoldable - Return true if both predicates match sign or if at
3245/// least one of them is an equality comparison (which is signless).
Reid Spencer266e42b2006-12-23 06:05:41 +00003246static bool PredicatesFoldable(ICmpInst::Predicate p1, ICmpInst::Predicate p2) {
3247 return (ICmpInst::isSignedPredicate(p1) == ICmpInst::isSignedPredicate(p2)) ||
Chris Lattnerb37b6e72008-11-16 04:55:20 +00003248 (ICmpInst::isSignedPredicate(p1) && ICmpInst::isEquality(p2)) ||
3249 (ICmpInst::isSignedPredicate(p2) && ICmpInst::isEquality(p1));
Reid Spencer266e42b2006-12-23 06:05:41 +00003250}
3251
3252namespace {
3253// FoldICmpLogical - Implements (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
3254struct FoldICmpLogical {
Chris Lattner3ac7c262003-08-13 20:16:26 +00003255 InstCombiner &IC;
3256 Value *LHS, *RHS;
Reid Spencer266e42b2006-12-23 06:05:41 +00003257 ICmpInst::Predicate pred;
3258 FoldICmpLogical(InstCombiner &ic, ICmpInst *ICI)
3259 : IC(ic), LHS(ICI->getOperand(0)), RHS(ICI->getOperand(1)),
3260 pred(ICI->getPredicate()) {}
Chris Lattner3ac7c262003-08-13 20:16:26 +00003261 bool shouldApply(Value *V) const {
Reid Spencer266e42b2006-12-23 06:05:41 +00003262 if (ICmpInst *ICI = dyn_cast<ICmpInst>(V))
3263 if (PredicatesFoldable(pred, ICI->getPredicate()))
Anton Korobeynikov1bfd1212008-02-20 11:26:25 +00003264 return ((ICI->getOperand(0) == LHS && ICI->getOperand(1) == RHS) ||
3265 (ICI->getOperand(0) == RHS && ICI->getOperand(1) == LHS));
Chris Lattner3ac7c262003-08-13 20:16:26 +00003266 return false;
3267 }
Reid Spencer266e42b2006-12-23 06:05:41 +00003268 Instruction *apply(Instruction &Log) const {
3269 ICmpInst *ICI = cast<ICmpInst>(Log.getOperand(0));
3270 if (ICI->getOperand(0) != LHS) {
3271 assert(ICI->getOperand(1) == LHS);
3272 ICI->swapOperands(); // Swap the LHS and RHS of the ICmp
Chris Lattner3ac7c262003-08-13 20:16:26 +00003273 }
3274
Chris Lattnerd1bce952007-03-13 14:27:42 +00003275 ICmpInst *RHSICI = cast<ICmpInst>(Log.getOperand(1));
Reid Spencer266e42b2006-12-23 06:05:41 +00003276 unsigned LHSCode = getICmpCode(ICI);
Chris Lattnerd1bce952007-03-13 14:27:42 +00003277 unsigned RHSCode = getICmpCode(RHSICI);
Chris Lattner3ac7c262003-08-13 20:16:26 +00003278 unsigned Code;
3279 switch (Log.getOpcode()) {
3280 case Instruction::And: Code = LHSCode & RHSCode; break;
3281 case Instruction::Or: Code = LHSCode | RHSCode; break;
3282 case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
Chris Lattner2caaaba2003-09-22 20:33:34 +00003283 default: assert(0 && "Illegal logical opcode!"); return 0;
Chris Lattner3ac7c262003-08-13 20:16:26 +00003284 }
3285
Chris Lattnerd1bce952007-03-13 14:27:42 +00003286 bool isSigned = ICmpInst::isSignedPredicate(RHSICI->getPredicate()) ||
3287 ICmpInst::isSignedPredicate(ICI->getPredicate());
3288
3289 Value *RV = getICmpValue(isSigned, Code, LHS, RHS);
Chris Lattner3ac7c262003-08-13 20:16:26 +00003290 if (Instruction *I = dyn_cast<Instruction>(RV))
3291 return I;
3292 // Otherwise, it's a constant boolean value...
3293 return IC.ReplaceInstUsesWith(Log, RV);
3294 }
3295};
Chris Lattnere3a63d12006-11-15 04:53:24 +00003296} // end anonymous namespace
Chris Lattner3ac7c262003-08-13 20:16:26 +00003297
Chris Lattnerba1cb382003-09-19 17:17:26 +00003298// OptAndOp - This handles expressions of the form ((val OP C1) & C2). Where
3299// the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'. Op is
Reid Spencer2341c222007-02-02 02:16:23 +00003300// guaranteed to be a binary operator.
Chris Lattnerba1cb382003-09-19 17:17:26 +00003301Instruction *InstCombiner::OptAndOp(Instruction *Op,
Zhou Sheng75b871f2007-01-11 12:24:14 +00003302 ConstantInt *OpRHS,
3303 ConstantInt *AndRHS,
Chris Lattnerba1cb382003-09-19 17:17:26 +00003304 BinaryOperator &TheAnd) {
3305 Value *X = Op->getOperand(0);
Chris Lattnerfcf21a72004-01-12 19:47:05 +00003306 Constant *Together = 0;
Reid Spencer2341c222007-02-02 02:16:23 +00003307 if (!Op->isShift())
Reid Spencer80263aa2007-03-25 05:33:51 +00003308 Together = And(AndRHS, OpRHS);
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00003309
Chris Lattnerba1cb382003-09-19 17:17:26 +00003310 switch (Op->getOpcode()) {
3311 case Instruction::Xor:
Chris Lattner86102b82005-01-01 16:22:27 +00003312 if (Op->hasOneUse()) {
Chris Lattnerba1cb382003-09-19 17:17:26 +00003313 // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
Gabor Greife1f6e4b2008-05-16 19:29:10 +00003314 Instruction *And = BinaryOperator::CreateAnd(X, AndRHS);
Chris Lattnerba1cb382003-09-19 17:17:26 +00003315 InsertNewInstBefore(And, TheAnd);
Chris Lattner6e0123b2007-02-11 01:23:03 +00003316 And->takeName(Op);
Gabor Greife1f6e4b2008-05-16 19:29:10 +00003317 return BinaryOperator::CreateXor(And, Together);
Chris Lattnerba1cb382003-09-19 17:17:26 +00003318 }
3319 break;
3320 case Instruction::Or:
Chris Lattner86102b82005-01-01 16:22:27 +00003321 if (Together == AndRHS) // (X | C) & C --> C
3322 return ReplaceInstUsesWith(TheAnd, AndRHS);
Misha Brukmanb1c93172005-04-21 23:48:37 +00003323
Chris Lattner86102b82005-01-01 16:22:27 +00003324 if (Op->hasOneUse() && Together != OpRHS) {
3325 // (X | C1) & C2 --> (X | (C1&C2)) & C2
Gabor Greife1f6e4b2008-05-16 19:29:10 +00003326 Instruction *Or = BinaryOperator::CreateOr(X, Together);
Chris Lattner86102b82005-01-01 16:22:27 +00003327 InsertNewInstBefore(Or, TheAnd);
Chris Lattner6e0123b2007-02-11 01:23:03 +00003328 Or->takeName(Op);
Gabor Greife1f6e4b2008-05-16 19:29:10 +00003329 return BinaryOperator::CreateAnd(Or, AndRHS);
Chris Lattnerba1cb382003-09-19 17:17:26 +00003330 }
3331 break;
3332 case Instruction::Add:
Chris Lattnerf95d9b92003-10-15 16:48:29 +00003333 if (Op->hasOneUse()) {
Chris Lattnerba1cb382003-09-19 17:17:26 +00003334 // Adding a one to a single bit bit-field should be turned into an XOR
3335 // of the bit. First thing to check is to see if this AND is with a
3336 // single bit constant.
Zhou Sheng150f3bb2007-04-01 17:13:37 +00003337 const APInt& AndRHSV = cast<ConstantInt>(AndRHS)->getValue();
Chris Lattnerba1cb382003-09-19 17:17:26 +00003338
3339 // If there is only one bit set...
Chris Lattner35167c32004-06-09 07:59:58 +00003340 if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
Chris Lattnerba1cb382003-09-19 17:17:26 +00003341 // Ok, at this point, we know that we are masking the result of the
3342 // ADD down to exactly one bit. If the constant we are adding has
3343 // no bits set below this bit, then we can eliminate the ADD.
Zhou Sheng150f3bb2007-04-01 17:13:37 +00003344 const APInt& AddRHS = cast<ConstantInt>(OpRHS)->getValue();
Misha Brukmanb1c93172005-04-21 23:48:37 +00003345
Chris Lattnerba1cb382003-09-19 17:17:26 +00003346 // Check to see if any bits below the one bit set in AndRHSV are set.
3347 if ((AddRHS & (AndRHSV-1)) == 0) {
3348 // If not, the only thing that can effect the output of the AND is
3349 // the bit specified by AndRHSV. If that bit is set, the effect of
3350 // the XOR is to toggle the bit. If it is clear, then the ADD has
3351 // no effect.
3352 if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
3353 TheAnd.setOperand(0, X);
3354 return &TheAnd;
3355 } else {
Chris Lattnerba1cb382003-09-19 17:17:26 +00003356 // Pull the XOR out of the AND.
Gabor Greife1f6e4b2008-05-16 19:29:10 +00003357 Instruction *NewAnd = BinaryOperator::CreateAnd(X, AndRHS);
Chris Lattnerba1cb382003-09-19 17:17:26 +00003358 InsertNewInstBefore(NewAnd, TheAnd);
Chris Lattner6e0123b2007-02-11 01:23:03 +00003359 NewAnd->takeName(Op);
Gabor Greife1f6e4b2008-05-16 19:29:10 +00003360 return BinaryOperator::CreateXor(NewAnd, AndRHS);
Chris Lattnerba1cb382003-09-19 17:17:26 +00003361 }
3362 }
3363 }
3364 }
3365 break;
Chris Lattner2da29172003-09-19 19:05:02 +00003366
3367 case Instruction::Shl: {
3368 // We know that the AND will not produce any of the bits shifted in, so if
3369 // the anded constant includes them, clear them now!
3370 //
Zhou Shengb3a80b12007-03-29 08:15:12 +00003371 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
Zhou Shengb25806f2007-03-30 09:29:48 +00003372 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
Zhou Shengb3a80b12007-03-29 08:15:12 +00003373 APInt ShlMask(APInt::getHighBitsSet(BitWidth, BitWidth-OpRHSVal));
3374 ConstantInt *CI = ConstantInt::get(AndRHS->getValue() & ShlMask);
Misha Brukmanb1c93172005-04-21 23:48:37 +00003375
Zhou Shengb3a80b12007-03-29 08:15:12 +00003376 if (CI->getValue() == ShlMask) {
3377 // Masking out bits that the shift already masks
Chris Lattner7e794272004-09-24 15:21:34 +00003378 return ReplaceInstUsesWith(TheAnd, Op); // No need for the and.
3379 } else if (CI != AndRHS) { // Reducing bits set in and.
Chris Lattner2da29172003-09-19 19:05:02 +00003380 TheAnd.setOperand(1, CI);
3381 return &TheAnd;
3382 }
3383 break;
Misha Brukmanb1c93172005-04-21 23:48:37 +00003384 }
Reid Spencerfdff9382006-11-08 06:47:33 +00003385 case Instruction::LShr:
3386 {
Chris Lattner2da29172003-09-19 19:05:02 +00003387 // We know that the AND will not produce any of the bits shifted in, so if
3388 // the anded constant includes them, clear them now! This only applies to
3389 // unsigned shifts, because a signed shr may bring in set bits!
3390 //
Zhou Shengb3a80b12007-03-29 08:15:12 +00003391 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
Zhou Shengb25806f2007-03-30 09:29:48 +00003392 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
Zhou Shengb3a80b12007-03-29 08:15:12 +00003393 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
3394 ConstantInt *CI = ConstantInt::get(AndRHS->getValue() & ShrMask);
Chris Lattner7e794272004-09-24 15:21:34 +00003395
Zhou Shengb3a80b12007-03-29 08:15:12 +00003396 if (CI->getValue() == ShrMask) {
3397 // Masking out bits that the shift already masks.
Reid Spencerfdff9382006-11-08 06:47:33 +00003398 return ReplaceInstUsesWith(TheAnd, Op);
3399 } else if (CI != AndRHS) {
3400 TheAnd.setOperand(1, CI); // Reduce bits set in and cst.
3401 return &TheAnd;
3402 }
3403 break;
3404 }
3405 case Instruction::AShr:
3406 // Signed shr.
3407 // See if this is shifting in some sign extension, then masking it out
3408 // with an and.
3409 if (Op->hasOneUse()) {
Zhou Shengb3a80b12007-03-29 08:15:12 +00003410 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
Zhou Shengb25806f2007-03-30 09:29:48 +00003411 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
Zhou Shengb3a80b12007-03-29 08:15:12 +00003412 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
3413 Constant *C = ConstantInt::get(AndRHS->getValue() & ShrMask);
Reid Spencer2a499b02006-12-13 17:19:09 +00003414 if (C == AndRHS) { // Masking out bits shifted in.
Reid Spencer13bc5d72006-12-12 09:18:51 +00003415 // (Val ashr C1) & C2 -> (Val lshr C1) & C2
Reid Spencerfdff9382006-11-08 06:47:33 +00003416 // Make the argument unsigned.
3417 Value *ShVal = Op->getOperand(0);
Reid Spencer2341c222007-02-02 02:16:23 +00003418 ShVal = InsertNewInstBefore(
Gabor Greife1f6e4b2008-05-16 19:29:10 +00003419 BinaryOperator::CreateLShr(ShVal, OpRHS,
Reid Spencer2341c222007-02-02 02:16:23 +00003420 Op->getName()), TheAnd);
Gabor Greife1f6e4b2008-05-16 19:29:10 +00003421 return BinaryOperator::CreateAnd(ShVal, AndRHS, TheAnd.getName());
Chris Lattner7e794272004-09-24 15:21:34 +00003422 }
Chris Lattner2da29172003-09-19 19:05:02 +00003423 }
3424 break;
Chris Lattnerba1cb382003-09-19 17:17:26 +00003425 }
3426 return 0;
3427}
3428
Chris Lattner6d14f2a2002-08-09 23:47:40 +00003429
Chris Lattner6862fbd2004-09-29 17:40:11 +00003430/// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
3431/// true, otherwise (V < Lo || V >= Hi). In pratice, we emit the more efficient
Reid Spencer266e42b2006-12-23 06:05:41 +00003432/// (V-Lo) <u Hi-Lo. This method expects that Lo <= Hi. isSigned indicates
3433/// whether to treat the V, Lo and HI as signed or not. IB is the location to
Chris Lattner6862fbd2004-09-29 17:40:11 +00003434/// insert new instructions.
3435Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
Reid Spencer266e42b2006-12-23 06:05:41 +00003436 bool isSigned, bool Inside,
3437 Instruction &IB) {
Zhou Sheng75b871f2007-01-11 12:24:14 +00003438 assert(cast<ConstantInt>(ConstantExpr::getICmp((isSigned ?
Reid Spencercddc9df2007-01-12 04:24:46 +00003439 ICmpInst::ICMP_SLE:ICmpInst::ICMP_ULE), Lo, Hi))->getZExtValue() &&
Chris Lattner6862fbd2004-09-29 17:40:11 +00003440 "Lo is not <= Hi in range emission code!");
Reid Spencer266e42b2006-12-23 06:05:41 +00003441
Chris Lattner6862fbd2004-09-29 17:40:11 +00003442 if (Inside) {
3443 if (Lo == Hi) // Trivially false.
Reid Spencer266e42b2006-12-23 06:05:41 +00003444 return new ICmpInst(ICmpInst::ICMP_NE, V, V);
Misha Brukmanb1c93172005-04-21 23:48:37 +00003445
Reid Spencer266e42b2006-12-23 06:05:41 +00003446 // V >= Min && V < Hi --> V < Hi
Zhou Sheng75b871f2007-01-11 12:24:14 +00003447 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
Reid Spencerf4071162007-03-21 23:19:50 +00003448 ICmpInst::Predicate pred = (isSigned ?
Reid Spencer266e42b2006-12-23 06:05:41 +00003449 ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT);
3450 return new ICmpInst(pred, V, Hi);
3451 }
3452
3453 // Emit V-Lo <u Hi-Lo
3454 Constant *NegLo = ConstantExpr::getNeg(Lo);
Gabor Greife1f6e4b2008-05-16 19:29:10 +00003455 Instruction *Add = BinaryOperator::CreateAdd(V, NegLo, V->getName()+".off");
Chris Lattner6862fbd2004-09-29 17:40:11 +00003456 InsertNewInstBefore(Add, IB);
Reid Spencer266e42b2006-12-23 06:05:41 +00003457 Constant *UpperBound = ConstantExpr::getAdd(NegLo, Hi);
3458 return new ICmpInst(ICmpInst::ICMP_ULT, Add, UpperBound);
Chris Lattner6862fbd2004-09-29 17:40:11 +00003459 }
3460
3461 if (Lo == Hi) // Trivially true.
Reid Spencer266e42b2006-12-23 06:05:41 +00003462 return new ICmpInst(ICmpInst::ICMP_EQ, V, V);
Chris Lattner6862fbd2004-09-29 17:40:11 +00003463
Reid Spencerf4071162007-03-21 23:19:50 +00003464 // V < Min || V >= Hi -> V > Hi-1
Chris Lattner6862fbd2004-09-29 17:40:11 +00003465 Hi = SubOne(cast<ConstantInt>(Hi));
Zhou Sheng75b871f2007-01-11 12:24:14 +00003466 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
Reid Spencer266e42b2006-12-23 06:05:41 +00003467 ICmpInst::Predicate pred = (isSigned ?
3468 ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT);
3469 return new ICmpInst(pred, V, Hi);
3470 }
Reid Spencere0fc4df2006-10-20 07:07:24 +00003471
Reid Spencerf4071162007-03-21 23:19:50 +00003472 // Emit V-Lo >u Hi-1-Lo
3473 // Note that Hi has already had one subtracted from it, above.
3474 ConstantInt *NegLo = cast<ConstantInt>(ConstantExpr::getNeg(Lo));
Gabor Greife1f6e4b2008-05-16 19:29:10 +00003475 Instruction *Add = BinaryOperator::CreateAdd(V, NegLo, V->getName()+".off");
Chris Lattner6862fbd2004-09-29 17:40:11 +00003476 InsertNewInstBefore(Add, IB);
Reid Spencer266e42b2006-12-23 06:05:41 +00003477 Constant *LowerBound = ConstantExpr::getAdd(NegLo, Hi);
3478 return new ICmpInst(ICmpInst::ICMP_UGT, Add, LowerBound);
Chris Lattner6862fbd2004-09-29 17:40:11 +00003479}
3480
Chris Lattnerb4b25302005-09-18 07:22:02 +00003481// isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
3482// any number of 0s on either side. The 1s are allowed to wrap from LSB to
3483// MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs. 0x0F0F0000 is
3484// not, since all 1s are not contiguous.
Zhou Sheng56cda952007-04-02 08:20:41 +00003485static bool isRunOfOnes(ConstantInt *Val, uint32_t &MB, uint32_t &ME) {
Zhou Sheng150f3bb2007-04-01 17:13:37 +00003486 const APInt& V = Val->getValue();
Reid Spencera962d182007-03-24 00:42:08 +00003487 uint32_t BitWidth = Val->getType()->getBitWidth();
3488 if (!APIntOps::isShiftedMask(BitWidth, V)) return false;
Chris Lattnerb4b25302005-09-18 07:22:02 +00003489
3490 // look for the first zero bit after the run of ones
Reid Spencera962d182007-03-24 00:42:08 +00003491 MB = BitWidth - ((V - 1) ^ V).countLeadingZeros();
Chris Lattnerb4b25302005-09-18 07:22:02 +00003492 // look for the first non-zero bit
Reid Spencera962d182007-03-24 00:42:08 +00003493 ME = V.getActiveBits();
Chris Lattnerb4b25302005-09-18 07:22:02 +00003494 return true;
3495}
3496
Chris Lattnerb4b25302005-09-18 07:22:02 +00003497/// FoldLogicalPlusAnd - This is part of an expression (LHS +/- RHS) & Mask,
3498/// where isSub determines whether the operator is a sub. If we can fold one of
3499/// the following xforms:
Chris Lattneraf517572005-09-18 04:24:45 +00003500///
3501/// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
3502/// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3503/// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3504///
3505/// return (A +/- B).
3506///
3507Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
Zhou Sheng75b871f2007-01-11 12:24:14 +00003508 ConstantInt *Mask, bool isSub,
Chris Lattneraf517572005-09-18 04:24:45 +00003509 Instruction &I) {
3510 Instruction *LHSI = dyn_cast<Instruction>(LHS);
3511 if (!LHSI || LHSI->getNumOperands() != 2 ||
3512 !isa<ConstantInt>(LHSI->getOperand(1))) return 0;
3513
3514 ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
3515
3516 switch (LHSI->getOpcode()) {
3517 default: return 0;
3518 case Instruction::And:
Reid Spencer80263aa2007-03-25 05:33:51 +00003519 if (And(N, Mask) == Mask) {
Chris Lattnerb4b25302005-09-18 07:22:02 +00003520 // If the AndRHS is a power of two minus one (0+1+), this is simple.
Zhou Shenge9ebd3f2007-03-24 15:34:37 +00003521 if ((Mask->getValue().countLeadingZeros() +
3522 Mask->getValue().countPopulation()) ==
3523 Mask->getValue().getBitWidth())
Chris Lattnerb4b25302005-09-18 07:22:02 +00003524 break;
3525
3526 // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
3527 // part, we don't need any explicit masks to take them out of A. If that
3528 // is all N is, ignore it.
Zhou Sheng56cda952007-04-02 08:20:41 +00003529 uint32_t MB = 0, ME = 0;
Chris Lattnerb4b25302005-09-18 07:22:02 +00003530 if (isRunOfOnes(Mask, MB, ME)) { // begin/end bit of run, inclusive
Reid Spencer6274c722007-03-23 18:46:34 +00003531 uint32_t BitWidth = cast<IntegerType>(RHS->getType())->getBitWidth();
Zhou Shengb3a80b12007-03-29 08:15:12 +00003532 APInt Mask(APInt::getLowBitsSet(BitWidth, MB-1));
Chris Lattnerc3ebf402006-02-07 07:27:52 +00003533 if (MaskedValueIsZero(RHS, Mask))
Chris Lattnerb4b25302005-09-18 07:22:02 +00003534 break;
3535 }
3536 }
Chris Lattneraf517572005-09-18 04:24:45 +00003537 return 0;
3538 case Instruction::Or:
3539 case Instruction::Xor:
Chris Lattnerb4b25302005-09-18 07:22:02 +00003540 // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
Zhou Shenge9ebd3f2007-03-24 15:34:37 +00003541 if ((Mask->getValue().countLeadingZeros() +
3542 Mask->getValue().countPopulation()) == Mask->getValue().getBitWidth()
Reid Spencer54d5b1b2007-03-26 23:58:26 +00003543 && And(N, Mask)->isZero())
Chris Lattneraf517572005-09-18 04:24:45 +00003544 break;
3545 return 0;
3546 }
3547
3548 Instruction *New;
3549 if (isSub)
Gabor Greife1f6e4b2008-05-16 19:29:10 +00003550 New = BinaryOperator::CreateSub(LHSI->getOperand(0), RHS, "fold");
Chris Lattneraf517572005-09-18 04:24:45 +00003551 else
Gabor Greife1f6e4b2008-05-16 19:29:10 +00003552 New = BinaryOperator::CreateAdd(LHSI->getOperand(0), RHS, "fold");
Chris Lattneraf517572005-09-18 04:24:45 +00003553 return InsertNewInstBefore(New, I);
3554}
3555
Chris Lattner269cbd52008-11-16 05:06:21 +00003556/// FoldAndOfICmps - Fold (icmp)&(icmp) if possible.
3557Instruction *InstCombiner::FoldAndOfICmps(Instruction &I,
3558 ICmpInst *LHS, ICmpInst *RHS) {
Chris Lattnerfeaea9b2008-11-16 05:10:52 +00003559 Value *Val, *Val2;
Chris Lattner269cbd52008-11-16 05:06:21 +00003560 ConstantInt *LHSCst, *RHSCst;
3561 ICmpInst::Predicate LHSCC, RHSCC;
3562
Chris Lattnerfeaea9b2008-11-16 05:10:52 +00003563 // This only handles icmp of constants: (icmp1 A, C1) & (icmp2 B, C2).
Chris Lattner269cbd52008-11-16 05:06:21 +00003564 if (!match(LHS, m_ICmp(LHSCC, m_Value(Val), m_ConstantInt(LHSCst))) ||
Chris Lattnerfeaea9b2008-11-16 05:10:52 +00003565 !match(RHS, m_ICmp(RHSCC, m_Value(Val2), m_ConstantInt(RHSCst))))
Chris Lattner269cbd52008-11-16 05:06:21 +00003566 return 0;
Chris Lattnerfeaea9b2008-11-16 05:10:52 +00003567
3568 // (icmp ult A, C) & (icmp ult B, C) --> (icmp ult (A|B), C)
3569 // where C is a power of 2
3570 if (LHSCst == RHSCst && LHSCC == RHSCC && LHSCC == ICmpInst::ICMP_ULT &&
3571 LHSCst->getValue().isPowerOf2()) {
3572 Instruction *NewOr = BinaryOperator::CreateOr(Val, Val2);
3573 InsertNewInstBefore(NewOr, I);
3574 return new ICmpInst(LHSCC, NewOr, LHSCst);
3575 }
3576
3577 // From here on, we only handle:
3578 // (icmp1 A, C1) & (icmp2 A, C2) --> something simpler.
3579 if (Val != Val2) return 0;
3580
Chris Lattner269cbd52008-11-16 05:06:21 +00003581 // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
3582 if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
3583 RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
3584 LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
3585 RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
3586 return 0;
3587
3588 // We can't fold (ugt x, C) & (sgt x, C2).
3589 if (!PredicatesFoldable(LHSCC, RHSCC))
3590 return 0;
3591
3592 // Ensure that the larger constant is on the RHS.
3593 ICmpInst::Predicate GT;
3594 if (ICmpInst::isSignedPredicate(LHSCC) ||
3595 (ICmpInst::isEquality(LHSCC) &&
3596 ICmpInst::isSignedPredicate(RHSCC)))
3597 GT = ICmpInst::ICMP_SGT;
3598 else
3599 GT = ICmpInst::ICMP_UGT;
3600
3601 Constant *Cmp = ConstantExpr::getICmp(GT, LHSCst, RHSCst);
3602 if (cast<ConstantInt>(Cmp)->getZExtValue()) {
3603 std::swap(LHS, RHS);
3604 std::swap(LHSCst, RHSCst);
3605 std::swap(LHSCC, RHSCC);
3606 }
3607
3608 // At this point, we know we have have two icmp instructions
3609 // comparing a value against two constants and and'ing the result
3610 // together. Because of the above check, we know that we only have
3611 // icmp eq, icmp ne, icmp [su]lt, and icmp [SU]gt here. We also know
3612 // (from the FoldICmpLogical check above), that the two constants
3613 // are not equal and that the larger constant is on the RHS
3614 assert(LHSCst != RHSCst && "Compares not folded above?");
3615
3616 switch (LHSCC) {
3617 default: assert(0 && "Unknown integer condition code!");
3618 case ICmpInst::ICMP_EQ:
3619 switch (RHSCC) {
3620 default: assert(0 && "Unknown integer condition code!");
3621 case ICmpInst::ICMP_EQ: // (X == 13 & X == 15) -> false
3622 case ICmpInst::ICMP_UGT: // (X == 13 & X > 15) -> false
3623 case ICmpInst::ICMP_SGT: // (X == 13 & X > 15) -> false
3624 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
3625 case ICmpInst::ICMP_NE: // (X == 13 & X != 15) -> X == 13
3626 case ICmpInst::ICMP_ULT: // (X == 13 & X < 15) -> X == 13
3627 case ICmpInst::ICMP_SLT: // (X == 13 & X < 15) -> X == 13
3628 return ReplaceInstUsesWith(I, LHS);
3629 }
3630 case ICmpInst::ICMP_NE:
3631 switch (RHSCC) {
3632 default: assert(0 && "Unknown integer condition code!");
3633 case ICmpInst::ICMP_ULT:
3634 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X u< 14) -> X < 13
3635 return new ICmpInst(ICmpInst::ICMP_ULT, Val, LHSCst);
3636 break; // (X != 13 & X u< 15) -> no change
3637 case ICmpInst::ICMP_SLT:
3638 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X s< 14) -> X < 13
3639 return new ICmpInst(ICmpInst::ICMP_SLT, Val, LHSCst);
3640 break; // (X != 13 & X s< 15) -> no change
3641 case ICmpInst::ICMP_EQ: // (X != 13 & X == 15) -> X == 15
3642 case ICmpInst::ICMP_UGT: // (X != 13 & X u> 15) -> X u> 15
3643 case ICmpInst::ICMP_SGT: // (X != 13 & X s> 15) -> X s> 15
3644 return ReplaceInstUsesWith(I, RHS);
3645 case ICmpInst::ICMP_NE:
3646 if (LHSCst == SubOne(RHSCst)){// (X != 13 & X != 14) -> X-13 >u 1
3647 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
3648 Instruction *Add = BinaryOperator::CreateAdd(Val, AddCST,
3649 Val->getName()+".off");
3650 InsertNewInstBefore(Add, I);
3651 return new ICmpInst(ICmpInst::ICMP_UGT, Add,
3652 ConstantInt::get(Add->getType(), 1));
3653 }
3654 break; // (X != 13 & X != 15) -> no change
3655 }
3656 break;
3657 case ICmpInst::ICMP_ULT:
3658 switch (RHSCC) {
3659 default: assert(0 && "Unknown integer condition code!");
3660 case ICmpInst::ICMP_EQ: // (X u< 13 & X == 15) -> false
3661 case ICmpInst::ICMP_UGT: // (X u< 13 & X u> 15) -> false
3662 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
3663 case ICmpInst::ICMP_SGT: // (X u< 13 & X s> 15) -> no change
3664 break;
3665 case ICmpInst::ICMP_NE: // (X u< 13 & X != 15) -> X u< 13
3666 case ICmpInst::ICMP_ULT: // (X u< 13 & X u< 15) -> X u< 13
3667 return ReplaceInstUsesWith(I, LHS);
3668 case ICmpInst::ICMP_SLT: // (X u< 13 & X s< 15) -> no change
3669 break;
3670 }
3671 break;
3672 case ICmpInst::ICMP_SLT:
3673 switch (RHSCC) {
3674 default: assert(0 && "Unknown integer condition code!");
3675 case ICmpInst::ICMP_EQ: // (X s< 13 & X == 15) -> false
3676 case ICmpInst::ICMP_SGT: // (X s< 13 & X s> 15) -> false
3677 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
3678 case ICmpInst::ICMP_UGT: // (X s< 13 & X u> 15) -> no change
3679 break;
3680 case ICmpInst::ICMP_NE: // (X s< 13 & X != 15) -> X < 13
3681 case ICmpInst::ICMP_SLT: // (X s< 13 & X s< 15) -> X < 13
3682 return ReplaceInstUsesWith(I, LHS);
3683 case ICmpInst::ICMP_ULT: // (X s< 13 & X u< 15) -> no change
3684 break;
3685 }
3686 break;
3687 case ICmpInst::ICMP_UGT:
3688 switch (RHSCC) {
3689 default: assert(0 && "Unknown integer condition code!");
3690 case ICmpInst::ICMP_EQ: // (X u> 13 & X == 15) -> X == 15
3691 case ICmpInst::ICMP_UGT: // (X u> 13 & X u> 15) -> X u> 15
3692 return ReplaceInstUsesWith(I, RHS);
3693 case ICmpInst::ICMP_SGT: // (X u> 13 & X s> 15) -> no change
3694 break;
3695 case ICmpInst::ICMP_NE:
3696 if (RHSCst == AddOne(LHSCst)) // (X u> 13 & X != 14) -> X u> 14
3697 return new ICmpInst(LHSCC, Val, RHSCst);
3698 break; // (X u> 13 & X != 15) -> no change
3699 case ICmpInst::ICMP_ULT: // (X u> 13 & X u< 15) ->(X-14) <u 1
3700 return InsertRangeTest(Val, AddOne(LHSCst), RHSCst, false, true, I);
3701 case ICmpInst::ICMP_SLT: // (X u> 13 & X s< 15) -> no change
3702 break;
3703 }
3704 break;
3705 case ICmpInst::ICMP_SGT:
3706 switch (RHSCC) {
3707 default: assert(0 && "Unknown integer condition code!");
3708 case ICmpInst::ICMP_EQ: // (X s> 13 & X == 15) -> X == 15
3709 case ICmpInst::ICMP_SGT: // (X s> 13 & X s> 15) -> X s> 15
3710 return ReplaceInstUsesWith(I, RHS);
3711 case ICmpInst::ICMP_UGT: // (X s> 13 & X u> 15) -> no change
3712 break;
3713 case ICmpInst::ICMP_NE:
3714 if (RHSCst == AddOne(LHSCst)) // (X s> 13 & X != 14) -> X s> 14
3715 return new ICmpInst(LHSCC, Val, RHSCst);
3716 break; // (X s> 13 & X != 15) -> no change
3717 case ICmpInst::ICMP_SLT: // (X s> 13 & X s< 15) ->(X-14) s< 1
3718 return InsertRangeTest(Val, AddOne(LHSCst), RHSCst, true, true, I);
3719 case ICmpInst::ICMP_ULT: // (X s> 13 & X u< 15) -> no change
3720 break;
3721 }
3722 break;
3723 }
3724
3725
3726
3727 return 0;
3728}
3729
3730
Chris Lattner113f4f42002-06-25 16:13:24 +00003731Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00003732 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00003733 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003734
Chris Lattner81a7a232004-10-16 18:11:37 +00003735 if (isa<UndefValue>(Op1)) // X & undef -> 0
3736 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3737
Chris Lattner86102b82005-01-01 16:22:27 +00003738 // and X, X = X
3739 if (Op0 == Op1)
Chris Lattnere6794492002-08-12 21:17:25 +00003740 return ReplaceInstUsesWith(I, Op1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003741
Chris Lattner5b2edb12006-02-12 08:02:11 +00003742 // See if we can simplify any instructions used by the instruction whose sole
Chris Lattner5997cf92006-02-08 03:25:32 +00003743 // purpose is to compute bits we don't care about.
Reid Spencerd84d35b2007-02-15 02:26:10 +00003744 if (!isa<VectorType>(I.getType())) {
Reid Spencerb722f2b2007-03-22 22:19:58 +00003745 uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
3746 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
3747 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
Chris Lattner120ab032007-01-18 22:16:33 +00003748 KnownZero, KnownOne))
Reid Spencer54d5b1b2007-03-26 23:58:26 +00003749 return &I;
Chris Lattner120ab032007-01-18 22:16:33 +00003750 } else {
Reid Spencerd84d35b2007-02-15 02:26:10 +00003751 if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
Chris Lattnerf14e5172007-06-15 05:26:55 +00003752 if (CP->isAllOnesValue()) // X & <-1,-1> -> X
Chris Lattner120ab032007-01-18 22:16:33 +00003753 return ReplaceInstUsesWith(I, I.getOperand(0));
Chris Lattnerf14e5172007-06-15 05:26:55 +00003754 } else if (isa<ConstantAggregateZero>(Op1)) {
3755 return ReplaceInstUsesWith(I, Op1); // X & <0,0> -> <0,0>
Chris Lattner120ab032007-01-18 22:16:33 +00003756 }
3757 }
Chris Lattner5997cf92006-02-08 03:25:32 +00003758
Zhou Sheng75b871f2007-01-11 12:24:14 +00003759 if (ConstantInt *AndRHS = dyn_cast<ConstantInt>(Op1)) {
Zhou Sheng150f3bb2007-04-01 17:13:37 +00003760 const APInt& AndRHSMask = AndRHS->getValue();
3761 APInt NotAndRHS(~AndRHSMask);
Chris Lattner86102b82005-01-01 16:22:27 +00003762
Chris Lattnerba1cb382003-09-19 17:17:26 +00003763 // Optimize a variety of ((val OP C1) & C2) combinations...
Reid Spencer2341c222007-02-02 02:16:23 +00003764 if (isa<BinaryOperator>(Op0)) {
Chris Lattnerba1cb382003-09-19 17:17:26 +00003765 Instruction *Op0I = cast<Instruction>(Op0);
Chris Lattner86102b82005-01-01 16:22:27 +00003766 Value *Op0LHS = Op0I->getOperand(0);
3767 Value *Op0RHS = Op0I->getOperand(1);
3768 switch (Op0I->getOpcode()) {
3769 case Instruction::Xor:
3770 case Instruction::Or:
Chris Lattner9e2c7fa2005-01-23 20:26:55 +00003771 // If the mask is only needed on one incoming arm, push it up.
3772 if (Op0I->hasOneUse()) {
3773 if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
3774 // Not masking anything out for the LHS, move to RHS.
Gabor Greife1f6e4b2008-05-16 19:29:10 +00003775 Instruction *NewRHS = BinaryOperator::CreateAnd(Op0RHS, AndRHS,
Chris Lattner9e2c7fa2005-01-23 20:26:55 +00003776 Op0RHS->getName()+".masked");
3777 InsertNewInstBefore(NewRHS, I);
Gabor Greife1f6e4b2008-05-16 19:29:10 +00003778 return BinaryOperator::Create(
Chris Lattner9e2c7fa2005-01-23 20:26:55 +00003779 cast<BinaryOperator>(Op0I)->getOpcode(), Op0LHS, NewRHS);
Misha Brukmanb1c93172005-04-21 23:48:37 +00003780 }
Chris Lattnerc3ebf402006-02-07 07:27:52 +00003781 if (!isa<Constant>(Op0RHS) &&
Chris Lattner9e2c7fa2005-01-23 20:26:55 +00003782 MaskedValueIsZero(Op0RHS, NotAndRHS)) {
3783 // Not masking anything out for the RHS, move to LHS.
Gabor Greife1f6e4b2008-05-16 19:29:10 +00003784 Instruction *NewLHS = BinaryOperator::CreateAnd(Op0LHS, AndRHS,
Chris Lattner9e2c7fa2005-01-23 20:26:55 +00003785 Op0LHS->getName()+".masked");
3786 InsertNewInstBefore(NewLHS, I);
Gabor Greife1f6e4b2008-05-16 19:29:10 +00003787 return BinaryOperator::Create(
Chris Lattner9e2c7fa2005-01-23 20:26:55 +00003788 cast<BinaryOperator>(Op0I)->getOpcode(), NewLHS, Op0RHS);
3789 }
3790 }
3791
Chris Lattner86102b82005-01-01 16:22:27 +00003792 break;
Chris Lattneraf517572005-09-18 04:24:45 +00003793 case Instruction::Add:
Chris Lattnerb4b25302005-09-18 07:22:02 +00003794 // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
3795 // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
3796 // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
3797 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
Gabor Greife1f6e4b2008-05-16 19:29:10 +00003798 return BinaryOperator::CreateAnd(V, AndRHS);
Chris Lattnerb4b25302005-09-18 07:22:02 +00003799 if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
Gabor Greife1f6e4b2008-05-16 19:29:10 +00003800 return BinaryOperator::CreateAnd(V, AndRHS); // Add commutes
Chris Lattneraf517572005-09-18 04:24:45 +00003801 break;
3802
3803 case Instruction::Sub:
Chris Lattnerb4b25302005-09-18 07:22:02 +00003804 // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
3805 // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
3806 // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
3807 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
Gabor Greife1f6e4b2008-05-16 19:29:10 +00003808 return BinaryOperator::CreateAnd(V, AndRHS);
Nick Lewycky0d3645e2008-07-09 04:32:37 +00003809
Nick Lewycky6193a562008-07-10 05:51:40 +00003810 // (A - N) & AndRHS -> -N & AndRHS iff A&AndRHS==0 and AndRHS
3811 // has 1's for all bits that the subtraction with A might affect.
3812 if (Op0I->hasOneUse()) {
3813 uint32_t BitWidth = AndRHSMask.getBitWidth();
3814 uint32_t Zeros = AndRHSMask.countLeadingZeros();
3815 APInt Mask = APInt::getLowBitsSet(BitWidth, BitWidth - Zeros);
3816
Nick Lewycky0d3645e2008-07-09 04:32:37 +00003817 ConstantInt *A = dyn_cast<ConstantInt>(Op0LHS);
Nick Lewycky6193a562008-07-10 05:51:40 +00003818 if (!(A && A->isZero()) && // avoid infinite recursion.
3819 MaskedValueIsZero(Op0LHS, Mask)) {
Nick Lewycky0d3645e2008-07-09 04:32:37 +00003820 Instruction *NewNeg = BinaryOperator::CreateNeg(Op0RHS);
3821 InsertNewInstBefore(NewNeg, I);
3822 return BinaryOperator::CreateAnd(NewNeg, AndRHS);
3823 }
3824 }
Chris Lattneraf517572005-09-18 04:24:45 +00003825 break;
Nick Lewycky364661c2008-07-09 05:20:13 +00003826
3827 case Instruction::Shl:
3828 case Instruction::LShr:
3829 // (1 << x) & 1 --> zext(x == 0)
3830 // (1 >> x) & 1 --> zext(x == 0)
Nick Lewyckybb89c2a2008-07-09 07:35:26 +00003831 if (AndRHSMask == 1 && Op0LHS == AndRHS) {
Nick Lewycky364661c2008-07-09 05:20:13 +00003832 Instruction *NewICmp = new ICmpInst(ICmpInst::ICMP_EQ, Op0RHS,
3833 Constant::getNullValue(I.getType()));
3834 InsertNewInstBefore(NewICmp, I);
3835 return new ZExtInst(NewICmp, I.getType());
3836 }
3837 break;
Chris Lattner86102b82005-01-01 16:22:27 +00003838 }
3839
Chris Lattner16464b32003-07-23 19:25:52 +00003840 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
Chris Lattner86102b82005-01-01 16:22:27 +00003841 if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
Chris Lattnerba1cb382003-09-19 17:17:26 +00003842 return Res;
Chris Lattner86102b82005-01-01 16:22:27 +00003843 } else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
Chris Lattner2c14cf72005-08-07 07:03:10 +00003844 // If this is an integer truncation or change from signed-to-unsigned, and
3845 // if the source is an and/or with immediate, transform it. This
3846 // frequently occurs for bitfield accesses.
3847 if (Instruction *CastOp = dyn_cast<Instruction>(CI->getOperand(0))) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +00003848 if ((isa<TruncInst>(CI) || isa<BitCastInst>(CI)) &&
Chris Lattner2c14cf72005-08-07 07:03:10 +00003849 CastOp->getNumOperands() == 2)
Anton Korobeynikov1bfd1212008-02-20 11:26:25 +00003850 if (ConstantInt *AndCI = dyn_cast<ConstantInt>(CastOp->getOperand(1))) {
Chris Lattner2c14cf72005-08-07 07:03:10 +00003851 if (CastOp->getOpcode() == Instruction::And) {
3852 // Change: and (cast (and X, C1) to T), C2
Reid Spencer6c38f0b2006-11-27 01:05:10 +00003853 // into : and (cast X to T), trunc_or_bitcast(C1)&C2
3854 // This will fold the two constants together, which may allow
3855 // other simplifications.
Gabor Greife1f6e4b2008-05-16 19:29:10 +00003856 Instruction *NewCast = CastInst::CreateTruncOrBitCast(
Reid Spencerbb65ebf2006-12-12 23:36:14 +00003857 CastOp->getOperand(0), I.getType(),
3858 CastOp->getName()+".shrunk");
Chris Lattner2c14cf72005-08-07 07:03:10 +00003859 NewCast = InsertNewInstBefore(NewCast, I);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00003860 // trunc_or_bitcast(C1)&C2
Reid Spencerbb65ebf2006-12-12 23:36:14 +00003861 Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
Reid Spencer6c38f0b2006-11-27 01:05:10 +00003862 C3 = ConstantExpr::getAnd(C3, AndRHS);
Gabor Greife1f6e4b2008-05-16 19:29:10 +00003863 return BinaryOperator::CreateAnd(NewCast, C3);
Chris Lattner2c14cf72005-08-07 07:03:10 +00003864 } else if (CastOp->getOpcode() == Instruction::Or) {
3865 // Change: and (cast (or X, C1) to T), C2
3866 // into : trunc(C1)&C2 iff trunc(C1)&C2 == C2
Chris Lattner2dc148e2006-12-12 19:11:20 +00003867 Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
Chris Lattner2c14cf72005-08-07 07:03:10 +00003868 if (ConstantExpr::getAnd(C3, AndRHS) == AndRHS) // trunc(C1)&C2
3869 return ReplaceInstUsesWith(I, AndRHS);
3870 }
Anton Korobeynikov1bfd1212008-02-20 11:26:25 +00003871 }
Chris Lattner2c14cf72005-08-07 07:03:10 +00003872 }
Chris Lattner33217db2003-07-23 19:36:21 +00003873 }
Chris Lattner183b3362004-04-09 19:05:30 +00003874
3875 // Try to fold constant and into select arguments.
3876 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner86102b82005-01-01 16:22:27 +00003877 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00003878 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00003879 if (isa<PHINode>(Op0))
3880 if (Instruction *NV = FoldOpIntoPhi(I))
3881 return NV;
Chris Lattner49b47ae2003-07-23 17:57:01 +00003882 }
3883
Chris Lattnerbb74e222003-03-10 23:06:50 +00003884 Value *Op0NotVal = dyn_castNotVal(Op0);
3885 Value *Op1NotVal = dyn_castNotVal(Op1);
Chris Lattner3082c5a2003-02-18 19:28:33 +00003886
Chris Lattner023a4832004-06-18 06:07:51 +00003887 if (Op0NotVal == Op1 || Op1NotVal == Op0) // A & ~A == ~A & A == 0
3888 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3889
Misha Brukman9c003d82004-07-30 12:50:08 +00003890 // (~A & ~B) == (~(A | B)) - De Morgan's Law
Chris Lattnerbb74e222003-03-10 23:06:50 +00003891 if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
Gabor Greife1f6e4b2008-05-16 19:29:10 +00003892 Instruction *Or = BinaryOperator::CreateOr(Op0NotVal, Op1NotVal,
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003893 I.getName()+".demorgan");
Chris Lattner49b47ae2003-07-23 17:57:01 +00003894 InsertNewInstBefore(Or, I);
Gabor Greife1f6e4b2008-05-16 19:29:10 +00003895 return BinaryOperator::CreateNot(Or);
Chris Lattner3082c5a2003-02-18 19:28:33 +00003896 }
Chris Lattner8b10ab32006-02-13 23:07:23 +00003897
3898 {
Chris Lattner481e28b2007-06-15 05:58:24 +00003899 Value *A = 0, *B = 0, *C = 0, *D = 0;
3900 if (match(Op0, m_Or(m_Value(A), m_Value(B)))) {
Chris Lattner8b10ab32006-02-13 23:07:23 +00003901 if (A == Op1 || B == Op1) // (A | ?) & A --> A
3902 return ReplaceInstUsesWith(I, Op1);
Chris Lattner481e28b2007-06-15 05:58:24 +00003903
3904 // (A|B) & ~(A&B) -> A^B
3905 if (match(Op1, m_Not(m_And(m_Value(C), m_Value(D))))) {
3906 if ((A == C && B == D) || (A == D && B == C))
Gabor Greife1f6e4b2008-05-16 19:29:10 +00003907 return BinaryOperator::CreateXor(A, B);
Chris Lattner481e28b2007-06-15 05:58:24 +00003908 }
3909 }
3910
3911 if (match(Op1, m_Or(m_Value(A), m_Value(B)))) {
Chris Lattner8b10ab32006-02-13 23:07:23 +00003912 if (A == Op0 || B == Op0) // A & (A | ?) --> A
3913 return ReplaceInstUsesWith(I, Op0);
Chris Lattner481e28b2007-06-15 05:58:24 +00003914
3915 // ~(A&B) & (A|B) -> A^B
3916 if (match(Op0, m_Not(m_And(m_Value(C), m_Value(D))))) {
3917 if ((A == C && B == D) || (A == D && B == C))
Gabor Greife1f6e4b2008-05-16 19:29:10 +00003918 return BinaryOperator::CreateXor(A, B);
Chris Lattner481e28b2007-06-15 05:58:24 +00003919 }
3920 }
Chris Lattnerdcd07922006-04-01 08:03:55 +00003921
3922 if (Op0->hasOneUse() &&
3923 match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
3924 if (A == Op1) { // (A^B)&A -> A&(A^B)
3925 I.swapOperands(); // Simplify below
3926 std::swap(Op0, Op1);
3927 } else if (B == Op1) { // (A^B)&B -> B&(B^A)
3928 cast<BinaryOperator>(Op0)->swapOperands();
3929 I.swapOperands(); // Simplify below
3930 std::swap(Op0, Op1);
3931 }
3932 }
3933 if (Op1->hasOneUse() &&
3934 match(Op1, m_Xor(m_Value(A), m_Value(B)))) {
3935 if (B == Op0) { // B&(A^B) -> B&(B^A)
3936 cast<BinaryOperator>(Op1)->swapOperands();
3937 std::swap(A, B);
3938 }
3939 if (A == Op0) { // A&(A^B) -> A & ~B
Gabor Greife1f6e4b2008-05-16 19:29:10 +00003940 Instruction *NotB = BinaryOperator::CreateNot(B, "tmp");
Chris Lattnerdcd07922006-04-01 08:03:55 +00003941 InsertNewInstBefore(NotB, I);
Gabor Greife1f6e4b2008-05-16 19:29:10 +00003942 return BinaryOperator::CreateAnd(A, NotB);
Chris Lattnerdcd07922006-04-01 08:03:55 +00003943 }
3944 }
Chris Lattner8b10ab32006-02-13 23:07:23 +00003945 }
3946
Reid Spencer266e42b2006-12-23 06:05:41 +00003947 if (ICmpInst *RHS = dyn_cast<ICmpInst>(Op1)) {
3948 // (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
3949 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Chris Lattner3ac7c262003-08-13 20:16:26 +00003950 return R;
3951
Chris Lattner269cbd52008-11-16 05:06:21 +00003952 if (ICmpInst *LHS = dyn_cast<ICmpInst>(Op0))
3953 if (Instruction *Res = FoldAndOfICmps(I, LHS, RHS))
3954 return Res;
Chris Lattner623826c2004-09-28 21:48:02 +00003955 }
3956
Chris Lattner3af10532006-05-05 06:39:07 +00003957 // fold (and (cast A), (cast B)) -> (cast (and A, B))
Reid Spencer799b5bf2006-12-13 08:27:15 +00003958 if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
3959 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
3960 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind ?
3961 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattner03c49532007-01-15 02:27:26 +00003962 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
Reid Spencer799b5bf2006-12-13 08:27:15 +00003963 // Only do this if the casts both really cause code to be generated.
Reid Spencer266e42b2006-12-23 06:05:41 +00003964 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
3965 I.getType(), TD) &&
3966 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
3967 I.getType(), TD)) {
Gabor Greife1f6e4b2008-05-16 19:29:10 +00003968 Instruction *NewOp = BinaryOperator::CreateAnd(Op0C->getOperand(0),
Reid Spencer799b5bf2006-12-13 08:27:15 +00003969 Op1C->getOperand(0),
3970 I.getName());
3971 InsertNewInstBefore(NewOp, I);
Gabor Greife1f6e4b2008-05-16 19:29:10 +00003972 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
Reid Spencer799b5bf2006-12-13 08:27:15 +00003973 }
Chris Lattner3af10532006-05-05 06:39:07 +00003974 }
Chris Lattnerf05d69a2006-11-14 07:46:50 +00003975
3976 // (X >> Z) & (Y >> Z) -> (X&Y) >> Z for all shifts.
Reid Spencer2341c222007-02-02 02:16:23 +00003977 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
3978 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
3979 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
Chris Lattnerf05d69a2006-11-14 07:46:50 +00003980 SI0->getOperand(1) == SI1->getOperand(1) &&
3981 (SI0->hasOneUse() || SI1->hasOneUse())) {
3982 Instruction *NewOp =
Gabor Greife1f6e4b2008-05-16 19:29:10 +00003983 InsertNewInstBefore(BinaryOperator::CreateAnd(SI0->getOperand(0),
Chris Lattnerf05d69a2006-11-14 07:46:50 +00003984 SI1->getOperand(0),
3985 SI0->getName()), I);
Gabor Greife1f6e4b2008-05-16 19:29:10 +00003986 return BinaryOperator::Create(SI1->getOpcode(), NewOp,
Reid Spencer2341c222007-02-02 02:16:23 +00003987 SI1->getOperand(1));
Chris Lattnerf05d69a2006-11-14 07:46:50 +00003988 }
Chris Lattner3af10532006-05-05 06:39:07 +00003989 }
3990
Evan Cheng67786cc2008-10-14 17:15:11 +00003991 // If and'ing two fcmp, try combine them into one.
Chris Lattnerc62877e2007-10-24 05:38:08 +00003992 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
3993 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1))) {
3994 if (LHS->getPredicate() == FCmpInst::FCMP_ORD &&
Evan Cheng67786cc2008-10-14 17:15:11 +00003995 RHS->getPredicate() == FCmpInst::FCMP_ORD) {
3996 // (fcmp ord x, c) & (fcmp ord y, c) -> (fcmp ord x, y)
Chris Lattnerc62877e2007-10-24 05:38:08 +00003997 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
3998 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
3999 // If either of the constants are nans, then the whole thing returns
4000 // false.
Chris Lattner55b83022007-10-24 18:54:45 +00004001 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
Chris Lattnerc62877e2007-10-24 05:38:08 +00004002 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
4003 return new FCmpInst(FCmpInst::FCMP_ORD, LHS->getOperand(0),
4004 RHS->getOperand(0));
4005 }
Evan Cheng67786cc2008-10-14 17:15:11 +00004006 } else {
4007 Value *Op0LHS, *Op0RHS, *Op1LHS, *Op1RHS;
4008 FCmpInst::Predicate Op0CC, Op1CC;
4009 if (match(Op0, m_FCmp(Op0CC, m_Value(Op0LHS), m_Value(Op0RHS))) &&
4010 match(Op1, m_FCmp(Op1CC, m_Value(Op1LHS), m_Value(Op1RHS)))) {
Evan Chengce707522008-10-14 18:13:38 +00004011 if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
4012 // Swap RHS operands to match LHS.
4013 Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
4014 std::swap(Op1LHS, Op1RHS);
4015 }
Evan Cheng67786cc2008-10-14 17:15:11 +00004016 if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
4017 // Simplify (fcmp cc0 x, y) & (fcmp cc1 x, y).
4018 if (Op0CC == Op1CC)
4019 return new FCmpInst((FCmpInst::Predicate)Op0CC, Op0LHS, Op0RHS);
4020 else if (Op0CC == FCmpInst::FCMP_FALSE ||
4021 Op1CC == FCmpInst::FCMP_FALSE)
4022 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
4023 else if (Op0CC == FCmpInst::FCMP_TRUE)
4024 return ReplaceInstUsesWith(I, Op1);
4025 else if (Op1CC == FCmpInst::FCMP_TRUE)
4026 return ReplaceInstUsesWith(I, Op0);
4027 bool Op0Ordered;
4028 bool Op1Ordered;
4029 unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
4030 unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
4031 if (Op1Pred == 0) {
4032 std::swap(Op0, Op1);
4033 std::swap(Op0Pred, Op1Pred);
4034 std::swap(Op0Ordered, Op1Ordered);
4035 }
4036 if (Op0Pred == 0) {
4037 // uno && ueq -> uno && (uno || eq) -> ueq
4038 // ord && olt -> ord && (ord && lt) -> olt
4039 if (Op0Ordered == Op1Ordered)
4040 return ReplaceInstUsesWith(I, Op1);
4041 // uno && oeq -> uno && (ord && eq) -> false
4042 // uno && ord -> false
4043 if (!Op0Ordered)
4044 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
4045 // ord && ueq -> ord && (uno || eq) -> oeq
4046 return cast<Instruction>(getFCmpValue(true, Op1Pred,
4047 Op0LHS, Op0RHS));
4048 }
4049 }
4050 }
4051 }
Chris Lattnerc62877e2007-10-24 05:38:08 +00004052 }
4053 }
Nick Lewycky0d3645e2008-07-09 04:32:37 +00004054
Chris Lattner113f4f42002-06-25 16:13:24 +00004055 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00004056}
4057
Chris Lattner917a6c12008-10-05 02:13:19 +00004058/// CollectBSwapParts - Analyze the specified subexpression and see if it is
4059/// capable of providing pieces of a bswap. The subexpression provides pieces
4060/// of a bswap if it is proven that each of the non-zero bytes in the output of
4061/// the expression came from the corresponding "byte swapped" byte in some other
4062/// value. For example, if the current subexpression is "(shl i32 %X, 24)" then
4063/// we know that the expression deposits the low byte of %X into the high byte
4064/// of the bswap result and that all other bytes are zero. This expression is
4065/// accepted, the high byte of ByteValues is set to X to indicate a correct
4066/// match.
4067///
4068/// This function returns true if the match was unsuccessful and false if so.
4069/// On entry to the function the "OverallLeftShift" is a signed integer value
4070/// indicating the number of bytes that the subexpression is later shifted. For
4071/// example, if the expression is later right shifted by 16 bits, the
4072/// OverallLeftShift value would be -2 on entry. This is used to specify which
4073/// byte of ByteValues is actually being set.
4074///
4075/// Similarly, ByteMask is a bitmask where a bit is clear if its corresponding
4076/// byte is masked to zero by a user. For example, in (X & 255), X will be
4077/// processed with a bytemask of 1. Because bytemask is 32-bits, this limits
4078/// this function to working on up to 32-byte (256 bit) values. ByteMask is
4079/// always in the local (OverallLeftShift) coordinate space.
4080///
4081static bool CollectBSwapParts(Value *V, int OverallLeftShift, uint32_t ByteMask,
4082 SmallVector<Value*, 8> &ByteValues) {
4083 if (Instruction *I = dyn_cast<Instruction>(V)) {
4084 // If this is an or instruction, it may be an inner node of the bswap.
4085 if (I->getOpcode() == Instruction::Or) {
4086 return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
4087 ByteValues) ||
4088 CollectBSwapParts(I->getOperand(1), OverallLeftShift, ByteMask,
4089 ByteValues);
Chris Lattnerc482a9e2006-06-15 19:07:26 +00004090 }
Chris Lattner917a6c12008-10-05 02:13:19 +00004091
4092 // If this is a logical shift by a constant multiple of 8, recurse with
4093 // OverallLeftShift and ByteMask adjusted.
4094 if (I->isLogicalShift() && isa<ConstantInt>(I->getOperand(1))) {
4095 unsigned ShAmt =
4096 cast<ConstantInt>(I->getOperand(1))->getLimitedValue(~0U);
4097 // Ensure the shift amount is defined and of a byte value.
4098 if ((ShAmt & 7) || (ShAmt > 8*ByteValues.size()))
4099 return true;
4100
4101 unsigned ByteShift = ShAmt >> 3;
4102 if (I->getOpcode() == Instruction::Shl) {
4103 // X << 2 -> collect(X, +2)
4104 OverallLeftShift += ByteShift;
4105 ByteMask >>= ByteShift;
4106 } else {
4107 // X >>u 2 -> collect(X, -2)
4108 OverallLeftShift -= ByteShift;
4109 ByteMask <<= ByteShift;
Chris Lattner42d57852008-10-08 06:42:28 +00004110 ByteMask &= (~0U >> (32-ByteValues.size()));
Chris Lattner917a6c12008-10-05 02:13:19 +00004111 }
4112
4113 if (OverallLeftShift >= (int)ByteValues.size()) return true;
4114 if (OverallLeftShift <= -(int)ByteValues.size()) return true;
4115
4116 return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
4117 ByteValues);
4118 }
4119
4120 // If this is a logical 'and' with a mask that clears bytes, clear the
4121 // corresponding bytes in ByteMask.
4122 if (I->getOpcode() == Instruction::And &&
4123 isa<ConstantInt>(I->getOperand(1))) {
4124 // Scan every byte of the and mask, seeing if the byte is either 0 or 255.
4125 unsigned NumBytes = ByteValues.size();
4126 APInt Byte(I->getType()->getPrimitiveSizeInBits(), 255);
4127 const APInt &AndMask = cast<ConstantInt>(I->getOperand(1))->getValue();
4128
4129 for (unsigned i = 0; i != NumBytes; ++i, Byte <<= 8) {
4130 // If this byte is masked out by a later operation, we don't care what
4131 // the and mask is.
4132 if ((ByteMask & (1 << i)) == 0)
4133 continue;
4134
4135 // If the AndMask is all zeros for this byte, clear the bit.
4136 APInt MaskB = AndMask & Byte;
4137 if (MaskB == 0) {
4138 ByteMask &= ~(1U << i);
4139 continue;
4140 }
4141
4142 // If the AndMask is not all ones for this byte, it's not a bytezap.
4143 if (MaskB != Byte)
4144 return true;
4145
4146 // Otherwise, this byte is kept.
4147 }
4148
4149 return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
4150 ByteValues);
4151 }
Chris Lattnerc482a9e2006-06-15 19:07:26 +00004152 }
4153
Chris Lattner917a6c12008-10-05 02:13:19 +00004154 // Okay, we got to something that isn't a shift, 'or' or 'and'. This must be
4155 // the input value to the bswap. Some observations: 1) if more than one byte
4156 // is demanded from this input, then it could not be successfully assembled
4157 // into a byteswap. At least one of the two bytes would not be aligned with
4158 // their ultimate destination.
4159 if (!isPowerOf2_32(ByteMask)) return true;
4160 unsigned InputByteNo = CountTrailingZeros_32(ByteMask);
Chris Lattnerc482a9e2006-06-15 19:07:26 +00004161
Chris Lattner917a6c12008-10-05 02:13:19 +00004162 // 2) The input and ultimate destinations must line up: if byte 3 of an i32
4163 // is demanded, it needs to go into byte 0 of the result. This means that the
4164 // byte needs to be shifted until it lands in the right byte bucket. The
4165 // shift amount depends on the position: if the byte is coming from the high
4166 // part of the value (e.g. byte 3) then it must be shifted right. If from the
4167 // low part, it must be shifted left.
4168 unsigned DestByteNo = InputByteNo + OverallLeftShift;
4169 if (InputByteNo < ByteValues.size()/2) {
4170 if (ByteValues.size()-1-DestByteNo != InputByteNo)
4171 return true;
4172 } else {
4173 if (ByteValues.size()-1-DestByteNo != InputByteNo)
4174 return true;
4175 }
Chris Lattnerc482a9e2006-06-15 19:07:26 +00004176
4177 // If the destination byte value is already defined, the values are or'd
4178 // together, which isn't a bswap (unless it's an or of the same bits).
Chris Lattner917a6c12008-10-05 02:13:19 +00004179 if (ByteValues[DestByteNo] && ByteValues[DestByteNo] != V)
Chris Lattnerc482a9e2006-06-15 19:07:26 +00004180 return true;
Chris Lattner917a6c12008-10-05 02:13:19 +00004181 ByteValues[DestByteNo] = V;
Chris Lattnerc482a9e2006-06-15 19:07:26 +00004182 return false;
4183}
4184
4185/// MatchBSwap - Given an OR instruction, check to see if this is a bswap idiom.
4186/// If so, insert the new bswap intrinsic and return it.
4187Instruction *InstCombiner::MatchBSwap(BinaryOperator &I) {
Chris Lattnerc3eeb422007-04-01 20:57:36 +00004188 const IntegerType *ITy = dyn_cast<IntegerType>(I.getType());
Chris Lattner917a6c12008-10-05 02:13:19 +00004189 if (!ITy || ITy->getBitWidth() % 16 ||
4190 // ByteMask only allows up to 32-byte values.
4191 ITy->getBitWidth() > 32*8)
Chris Lattnerc3eeb422007-04-01 20:57:36 +00004192 return 0; // Can only bswap pairs of bytes. Can't do vectors.
Chris Lattnerc482a9e2006-06-15 19:07:26 +00004193
4194 /// ByteValues - For each byte of the result, we keep track of which value
4195 /// defines each byte.
Chris Lattner99c6cf62007-02-15 22:52:10 +00004196 SmallVector<Value*, 8> ByteValues;
Chris Lattnerc3eeb422007-04-01 20:57:36 +00004197 ByteValues.resize(ITy->getBitWidth()/8);
Chris Lattnerc482a9e2006-06-15 19:07:26 +00004198
4199 // Try to find all the pieces corresponding to the bswap.
Chris Lattner917a6c12008-10-05 02:13:19 +00004200 uint32_t ByteMask = ~0U >> (32-ByteValues.size());
4201 if (CollectBSwapParts(&I, 0, ByteMask, ByteValues))
Chris Lattnerc482a9e2006-06-15 19:07:26 +00004202 return 0;
4203
4204 // Check to see if all of the bytes come from the same value.
4205 Value *V = ByteValues[0];
4206 if (V == 0) return 0; // Didn't find a byte? Must be zero.
4207
4208 // Check to make sure that all of the bytes come from the same value.
4209 for (unsigned i = 1, e = ByteValues.size(); i != e; ++i)
4210 if (ByteValues[i] != V)
4211 return 0;
Chandler Carruth7132e002007-08-04 01:51:18 +00004212 const Type *Tys[] = { ITy };
Chris Lattnerc482a9e2006-06-15 19:07:26 +00004213 Module *M = I.getParent()->getParent()->getParent();
Chandler Carruth7132e002007-08-04 01:51:18 +00004214 Function *F = Intrinsic::getDeclaration(M, Intrinsic::bswap, Tys, 1);
Gabor Greife9ecc682008-04-06 20:25:17 +00004215 return CallInst::Create(F, V);
Chris Lattnerc482a9e2006-06-15 19:07:26 +00004216}
4217
Chris Lattner5f6d9a32008-11-16 04:24:12 +00004218/// MatchSelectFromAndOr - We have an expression of the form (A&C)|(B&D). Check
4219/// If A is (cond?-1:0) and either B or D is ~(cond?-1,0) or (cond?0,-1), then
4220/// we can simplify this expression to "cond ? C : D or B".
4221static Instruction *MatchSelectFromAndOr(Value *A, Value *B,
4222 Value *C, Value *D) {
Chris Lattner569d78c2008-11-16 04:26:55 +00004223 // If A is not a select of -1/0, this cannot match.
Chris Lattnerf1be2852008-11-16 04:46:19 +00004224 Value *Cond = 0;
Chris Lattnerfae5e332008-11-16 04:33:38 +00004225 if (!match(A, m_SelectCst(m_Value(Cond), -1, 0)))
Chris Lattner5f6d9a32008-11-16 04:24:12 +00004226 return 0;
4227
Chris Lattner569d78c2008-11-16 04:26:55 +00004228 // ((cond?-1:0)&C) | (B&(cond?0:-1)) -> cond ? C : B.
Chris Lattnerf1be2852008-11-16 04:46:19 +00004229 if (match(D, m_SelectCst(m_Specific(Cond), 0, -1)))
Chris Lattner569d78c2008-11-16 04:26:55 +00004230 return SelectInst::Create(Cond, C, B);
Chris Lattnerf1be2852008-11-16 04:46:19 +00004231 if (match(D, m_Not(m_SelectCst(m_Specific(Cond), -1, 0))))
Chris Lattner569d78c2008-11-16 04:26:55 +00004232 return SelectInst::Create(Cond, C, B);
4233 // ((cond?-1:0)&C) | ((cond?0:-1)&D) -> cond ? C : D.
Chris Lattnerf1be2852008-11-16 04:46:19 +00004234 if (match(B, m_SelectCst(m_Specific(Cond), 0, -1)))
Chris Lattner569d78c2008-11-16 04:26:55 +00004235 return SelectInst::Create(Cond, C, D);
Chris Lattnerf1be2852008-11-16 04:46:19 +00004236 if (match(B, m_Not(m_SelectCst(m_Specific(Cond), -1, 0))))
Chris Lattner569d78c2008-11-16 04:26:55 +00004237 return SelectInst::Create(Cond, C, D);
Chris Lattner5f6d9a32008-11-16 04:24:12 +00004238 return 0;
4239}
Chris Lattnerc482a9e2006-06-15 19:07:26 +00004240
Chris Lattner113f4f42002-06-25 16:13:24 +00004241Instruction *InstCombiner::visitOr(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00004242 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00004243 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00004244
Chris Lattner3a8248f2007-03-24 23:56:43 +00004245 if (isa<UndefValue>(Op1)) // X | undef -> -1
Chris Lattner37338922007-06-15 06:23:19 +00004246 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattner81a7a232004-10-16 18:11:37 +00004247
Chris Lattner5b2edb12006-02-12 08:02:11 +00004248 // or X, X = X
4249 if (Op0 == Op1)
Chris Lattnere6794492002-08-12 21:17:25 +00004250 return ReplaceInstUsesWith(I, Op0);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00004251
Chris Lattner5b2edb12006-02-12 08:02:11 +00004252 // See if we can simplify any instructions used by the instruction whose sole
4253 // purpose is to compute bits we don't care about.
Chris Lattner3a8248f2007-03-24 23:56:43 +00004254 if (!isa<VectorType>(I.getType())) {
4255 uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
4256 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
4257 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
4258 KnownZero, KnownOne))
4259 return &I;
Chris Lattnerf14e5172007-06-15 05:26:55 +00004260 } else if (isa<ConstantAggregateZero>(Op1)) {
4261 return ReplaceInstUsesWith(I, Op0); // X | <0,0> -> X
4262 } else if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
4263 if (CP->isAllOnesValue()) // X | <-1,-1> -> <-1,-1>
4264 return ReplaceInstUsesWith(I, I.getOperand(1));
Chris Lattner3a8248f2007-03-24 23:56:43 +00004265 }
Chris Lattnerf14e5172007-06-15 05:26:55 +00004266
4267
Chris Lattner5b2edb12006-02-12 08:02:11 +00004268
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00004269 // or X, -1 == -1
Zhou Sheng75b871f2007-01-11 12:24:14 +00004270 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner330628a2006-01-06 17:59:59 +00004271 ConstantInt *C1 = 0; Value *X = 0;
Chris Lattnerd4252a72004-07-30 07:50:03 +00004272 // (X & C1) | C2 --> (X | C2) & (C1|C2)
4273 if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
Gabor Greife1f6e4b2008-05-16 19:29:10 +00004274 Instruction *Or = BinaryOperator::CreateOr(X, RHS);
Chris Lattnerd4252a72004-07-30 07:50:03 +00004275 InsertNewInstBefore(Or, I);
Chris Lattner6e0123b2007-02-11 01:23:03 +00004276 Or->takeName(Op0);
Gabor Greife1f6e4b2008-05-16 19:29:10 +00004277 return BinaryOperator::CreateAnd(Or,
Zhou Sheng9bc8ab12007-04-02 13:45:30 +00004278 ConstantInt::get(RHS->getValue() | C1->getValue()));
Chris Lattnerd4252a72004-07-30 07:50:03 +00004279 }
Chris Lattner8f0d1562003-07-23 18:29:44 +00004280
Chris Lattnerd4252a72004-07-30 07:50:03 +00004281 // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
4282 if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
Gabor Greife1f6e4b2008-05-16 19:29:10 +00004283 Instruction *Or = BinaryOperator::CreateOr(X, RHS);
Chris Lattnerd4252a72004-07-30 07:50:03 +00004284 InsertNewInstBefore(Or, I);
Chris Lattner6e0123b2007-02-11 01:23:03 +00004285 Or->takeName(Op0);
Gabor Greife1f6e4b2008-05-16 19:29:10 +00004286 return BinaryOperator::CreateXor(Or,
Zhou Sheng9bc8ab12007-04-02 13:45:30 +00004287 ConstantInt::get(C1->getValue() & ~RHS->getValue()));
Chris Lattner8f0d1562003-07-23 18:29:44 +00004288 }
Chris Lattner183b3362004-04-09 19:05:30 +00004289
4290 // Try to fold constant and into select arguments.
4291 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner86102b82005-01-01 16:22:27 +00004292 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00004293 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00004294 if (isa<PHINode>(Op0))
4295 if (Instruction *NV = FoldOpIntoPhi(I))
4296 return NV;
Chris Lattner8f0d1562003-07-23 18:29:44 +00004297 }
4298
Chris Lattner330628a2006-01-06 17:59:59 +00004299 Value *A = 0, *B = 0;
4300 ConstantInt *C1 = 0, *C2 = 0;
Chris Lattner4294cec2005-05-07 23:49:08 +00004301
4302 if (match(Op0, m_And(m_Value(A), m_Value(B))))
4303 if (A == Op1 || B == Op1) // (A & ?) | A --> A
4304 return ReplaceInstUsesWith(I, Op1);
4305 if (match(Op1, m_And(m_Value(A), m_Value(B))))
4306 if (A == Op0 || B == Op0) // A | (A & ?) --> A
4307 return ReplaceInstUsesWith(I, Op0);
4308
Chris Lattnerb7845d62006-07-10 20:25:24 +00004309 // (A | B) | C and A | (B | C) -> bswap if possible.
4310 // (A >> B) | (C << D) and (A << B) | (B >> C) -> bswap if possible.
Chris Lattnerc482a9e2006-06-15 19:07:26 +00004311 if (match(Op0, m_Or(m_Value(), m_Value())) ||
Chris Lattnerb7845d62006-07-10 20:25:24 +00004312 match(Op1, m_Or(m_Value(), m_Value())) ||
4313 (match(Op0, m_Shift(m_Value(), m_Value())) &&
4314 match(Op1, m_Shift(m_Value(), m_Value())))) {
Chris Lattnerc482a9e2006-06-15 19:07:26 +00004315 if (Instruction *BSwap = MatchBSwap(I))
4316 return BSwap;
4317 }
4318
Chris Lattnerb62f5082005-05-09 04:58:36 +00004319 // (X^C)|Y -> (X|Y)^C iff Y&C == 0
4320 if (Op0->hasOneUse() && match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
Reid Spencerb722f2b2007-03-22 22:19:58 +00004321 MaskedValueIsZero(Op1, C1->getValue())) {
Gabor Greife1f6e4b2008-05-16 19:29:10 +00004322 Instruction *NOr = BinaryOperator::CreateOr(A, Op1);
Chris Lattner6e0123b2007-02-11 01:23:03 +00004323 InsertNewInstBefore(NOr, I);
4324 NOr->takeName(Op0);
Gabor Greife1f6e4b2008-05-16 19:29:10 +00004325 return BinaryOperator::CreateXor(NOr, C1);
Chris Lattnerb62f5082005-05-09 04:58:36 +00004326 }
4327
4328 // Y|(X^C) -> (X|Y)^C iff Y&C == 0
4329 if (Op1->hasOneUse() && match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
Reid Spencerb722f2b2007-03-22 22:19:58 +00004330 MaskedValueIsZero(Op0, C1->getValue())) {
Gabor Greife1f6e4b2008-05-16 19:29:10 +00004331 Instruction *NOr = BinaryOperator::CreateOr(A, Op0);
Chris Lattner6e0123b2007-02-11 01:23:03 +00004332 InsertNewInstBefore(NOr, I);
4333 NOr->takeName(Op0);
Gabor Greife1f6e4b2008-05-16 19:29:10 +00004334 return BinaryOperator::CreateXor(NOr, C1);
Chris Lattnerb62f5082005-05-09 04:58:36 +00004335 }
4336
Chris Lattner1150df92007-04-08 07:47:01 +00004337 // (A & C)|(B & D)
Chris Lattner09a33a42007-06-19 05:43:49 +00004338 Value *C = 0, *D = 0;
Chris Lattner1150df92007-04-08 07:47:01 +00004339 if (match(Op0, m_And(m_Value(A), m_Value(C))) &&
4340 match(Op1, m_And(m_Value(B), m_Value(D)))) {
Chris Lattner7621a032007-04-08 07:55:22 +00004341 Value *V1 = 0, *V2 = 0, *V3 = 0;
4342 C1 = dyn_cast<ConstantInt>(C);
4343 C2 = dyn_cast<ConstantInt>(D);
4344 if (C1 && C2) { // (A & C1)|(B & C2)
4345 // If we have: ((V + N) & C1) | (V & C2)
4346 // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
4347 // replace with V+N.
4348 if (C1->getValue() == ~C2->getValue()) {
4349 if ((C2->getValue() & (C2->getValue()+1)) == 0 && // C2 == 0+1+
4350 match(A, m_Add(m_Value(V1), m_Value(V2)))) {
4351 // Add commutes, try both ways.
4352 if (V1 == B && MaskedValueIsZero(V2, C2->getValue()))
4353 return ReplaceInstUsesWith(I, A);
4354 if (V2 == B && MaskedValueIsZero(V1, C2->getValue()))
4355 return ReplaceInstUsesWith(I, A);
4356 }
4357 // Or commutes, try both ways.
4358 if ((C1->getValue() & (C1->getValue()+1)) == 0 &&
4359 match(B, m_Add(m_Value(V1), m_Value(V2)))) {
4360 // Add commutes, try both ways.
4361 if (V1 == A && MaskedValueIsZero(V2, C1->getValue()))
4362 return ReplaceInstUsesWith(I, B);
4363 if (V2 == A && MaskedValueIsZero(V1, C1->getValue()))
4364 return ReplaceInstUsesWith(I, B);
4365 }
4366 }
Chris Lattnerc8d37882007-04-08 08:01:49 +00004367 V1 = 0; V2 = 0; V3 = 0;
Chris Lattner7621a032007-04-08 07:55:22 +00004368 }
4369
Chris Lattner1150df92007-04-08 07:47:01 +00004370 // Check to see if we have any common things being and'ed. If so, find the
4371 // terms for V1 & (V2|V3).
Chris Lattner1150df92007-04-08 07:47:01 +00004372 if (isOnlyUse(Op0) || isOnlyUse(Op1)) {
4373 if (A == B) // (A & C)|(A & D) == A & (C|D)
4374 V1 = A, V2 = C, V3 = D;
4375 else if (A == D) // (A & C)|(B & A) == A & (B|C)
4376 V1 = A, V2 = B, V3 = C;
4377 else if (C == B) // (A & C)|(C & D) == C & (A|D)
4378 V1 = C, V2 = A, V3 = D;
4379 else if (C == D) // (A & C)|(B & C) == C & (A|B)
4380 V1 = C, V2 = A, V3 = B;
4381
4382 if (V1) {
4383 Value *Or =
Gabor Greife1f6e4b2008-05-16 19:29:10 +00004384 InsertNewInstBefore(BinaryOperator::CreateOr(V2, V3, "tmp"), I);
4385 return BinaryOperator::CreateAnd(V1, Or);
Chris Lattner01f56c62005-09-18 06:02:59 +00004386 }
Chris Lattner1150df92007-04-08 07:47:01 +00004387 }
Dan Gohman2c34c132008-10-28 22:38:57 +00004388
Dan Gohman13cbcf1c182008-10-30 20:40:10 +00004389 // (A & (C0?-1:0)) | (B & ~(C0?-1:0)) -> C0 ? A : B, and commuted variants
Chris Lattner5f6d9a32008-11-16 04:24:12 +00004390 if (Instruction *Match = MatchSelectFromAndOr(A, B, C, D))
4391 return Match;
4392 if (Instruction *Match = MatchSelectFromAndOr(B, A, D, C))
4393 return Match;
4394 if (Instruction *Match = MatchSelectFromAndOr(C, B, A, D))
4395 return Match;
4396 if (Instruction *Match = MatchSelectFromAndOr(D, A, B, C))
4397 return Match;
Chris Lattner15212982005-09-18 03:42:07 +00004398 }
Chris Lattnerf05d69a2006-11-14 07:46:50 +00004399
4400 // (X >> Z) | (Y >> Z) -> (X|Y) >> Z for all shifts.
Reid Spencer2341c222007-02-02 02:16:23 +00004401 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4402 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4403 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
Chris Lattnerf05d69a2006-11-14 07:46:50 +00004404 SI0->getOperand(1) == SI1->getOperand(1) &&
4405 (SI0->hasOneUse() || SI1->hasOneUse())) {
4406 Instruction *NewOp =
Gabor Greife1f6e4b2008-05-16 19:29:10 +00004407 InsertNewInstBefore(BinaryOperator::CreateOr(SI0->getOperand(0),
Chris Lattnerf05d69a2006-11-14 07:46:50 +00004408 SI1->getOperand(0),
4409 SI0->getName()), I);
Gabor Greife1f6e4b2008-05-16 19:29:10 +00004410 return BinaryOperator::Create(SI1->getOpcode(), NewOp,
Reid Spencer2341c222007-02-02 02:16:23 +00004411 SI1->getOperand(1));
Chris Lattnerf05d69a2006-11-14 07:46:50 +00004412 }
4413 }
Chris Lattner812aab72003-08-12 19:11:07 +00004414
Chris Lattnerd4252a72004-07-30 07:50:03 +00004415 if (match(Op0, m_Not(m_Value(A)))) { // ~A | Op1
4416 if (A == Op1) // ~A | A == -1
Chris Lattner37338922007-06-15 06:23:19 +00004417 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnerd4252a72004-07-30 07:50:03 +00004418 } else {
4419 A = 0;
4420 }
Chris Lattner4294cec2005-05-07 23:49:08 +00004421 // Note, A is still live here!
Chris Lattnerd4252a72004-07-30 07:50:03 +00004422 if (match(Op1, m_Not(m_Value(B)))) { // Op0 | ~B
4423 if (Op0 == B)
Chris Lattner37338922007-06-15 06:23:19 +00004424 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattner3e327a42003-03-10 23:13:59 +00004425
Misha Brukman9c003d82004-07-30 12:50:08 +00004426 // (~A | ~B) == (~(A & B)) - De Morgan's Law
Chris Lattnerd4252a72004-07-30 07:50:03 +00004427 if (A && isOnlyUse(Op0) && isOnlyUse(Op1)) {
Gabor Greife1f6e4b2008-05-16 19:29:10 +00004428 Value *And = InsertNewInstBefore(BinaryOperator::CreateAnd(A, B,
Chris Lattnerd4252a72004-07-30 07:50:03 +00004429 I.getName()+".demorgan"), I);
Gabor Greife1f6e4b2008-05-16 19:29:10 +00004430 return BinaryOperator::CreateNot(And);
Chris Lattnerd4252a72004-07-30 07:50:03 +00004431 }
Chris Lattner3e327a42003-03-10 23:13:59 +00004432 }
Chris Lattner3082c5a2003-02-18 19:28:33 +00004433
Reid Spencer266e42b2006-12-23 06:05:41 +00004434 // (icmp1 A, B) | (icmp2 A, B) --> (icmp3 A, B)
4435 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1))) {
4436 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Chris Lattner3ac7c262003-08-13 20:16:26 +00004437 return R;
4438
Chris Lattnerf1be2852008-11-16 04:46:19 +00004439 Value *Val;
Chris Lattnerdcf756e2004-09-28 22:33:08 +00004440 ConstantInt *LHSCst, *RHSCst;
Reid Spencer266e42b2006-12-23 06:05:41 +00004441 ICmpInst::Predicate LHSCC, RHSCC;
Chris Lattnerb37b6e72008-11-16 04:55:20 +00004442 // (icmp1 A, C1) | (icmp2 A, C2) --> something simpler.
4443 if (match(Op0, m_ICmp(LHSCC, m_Value(Val), m_ConstantInt(LHSCst))) &&
4444 match(RHS, m_ICmp(RHSCC, m_Specific(Val), m_ConstantInt(RHSCst))) &&
4445
4446 // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
4447 LHSCC != ICmpInst::ICMP_UGE && LHSCC != ICmpInst::ICMP_ULE &&
4448 RHSCC != ICmpInst::ICMP_UGE && RHSCC != ICmpInst::ICMP_ULE &&
4449 LHSCC != ICmpInst::ICMP_SGE && LHSCC != ICmpInst::ICMP_SLE &&
4450 RHSCC != ICmpInst::ICMP_SGE && RHSCC != ICmpInst::ICMP_SLE &&
4451
4452 // We can't fold (ugt x, C) | (sgt x, C2).
4453 PredicatesFoldable(LHSCC, RHSCC)) {
4454 // Ensure that the larger constant is on the RHS.
4455 ICmpInst *LHS = cast<ICmpInst>(Op0);
4456 bool NeedsSwap;
4457 if (ICmpInst::isEquality(LHSCC) ? ICmpInst::isSignedPredicate(RHSCC)
4458 : ICmpInst::isSignedPredicate(LHSCC))
4459 NeedsSwap = LHSCst->getValue().sgt(RHSCst->getValue());
4460 else
4461 NeedsSwap = LHSCst->getValue().ugt(RHSCst->getValue());
4462
4463 if (NeedsSwap) {
4464 std::swap(LHS, RHS);
4465 std::swap(LHSCst, RHSCst);
4466 std::swap(LHSCC, RHSCC);
4467 }
Chris Lattnerdcf756e2004-09-28 22:33:08 +00004468
Chris Lattnerb37b6e72008-11-16 04:55:20 +00004469 // At this point, we know we have have two icmp instructions
4470 // comparing a value against two constants and or'ing the result
4471 // together. Because of the above check, we know that we only have
4472 // ICMP_EQ, ICMP_NE, ICMP_LT, and ICMP_GT here. We also know (from the
4473 // FoldICmpLogical check above), that the two constants are not
4474 // equal.
4475 assert(LHSCst != RHSCst && "Compares not folded above?");
Chris Lattnerdcf756e2004-09-28 22:33:08 +00004476
Chris Lattnerb37b6e72008-11-16 04:55:20 +00004477 switch (LHSCC) {
4478 default: assert(0 && "Unknown integer condition code!");
4479 case ICmpInst::ICMP_EQ:
4480 switch (RHSCC) {
4481 default: assert(0 && "Unknown integer condition code!");
4482 case ICmpInst::ICMP_EQ:
4483 if (LHSCst == SubOne(RHSCst)) { // (X == 13 | X == 14) -> X-13 <u 2
4484 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
4485 Instruction *Add = BinaryOperator::CreateAdd(Val, AddCST,
4486 Val->getName()+".off");
4487 InsertNewInstBefore(Add, I);
4488 AddCST = Subtract(AddOne(RHSCst), LHSCst);
4489 return new ICmpInst(ICmpInst::ICMP_ULT, Add, AddCST);
Chris Lattnerdcf756e2004-09-28 22:33:08 +00004490 }
Chris Lattnerb37b6e72008-11-16 04:55:20 +00004491 break; // (X == 13 | X == 15) -> no change
4492 case ICmpInst::ICMP_UGT: // (X == 13 | X u> 14) -> no change
4493 case ICmpInst::ICMP_SGT: // (X == 13 | X s> 14) -> no change
4494 break;
4495 case ICmpInst::ICMP_NE: // (X == 13 | X != 15) -> X != 15
4496 case ICmpInst::ICMP_ULT: // (X == 13 | X u< 15) -> X u< 15
4497 case ICmpInst::ICMP_SLT: // (X == 13 | X s< 15) -> X s< 15
4498 return ReplaceInstUsesWith(I, RHS);
Chris Lattnerdcf756e2004-09-28 22:33:08 +00004499 }
Chris Lattnerb37b6e72008-11-16 04:55:20 +00004500 break;
4501 case ICmpInst::ICMP_NE:
4502 switch (RHSCC) {
4503 default: assert(0 && "Unknown integer condition code!");
4504 case ICmpInst::ICMP_EQ: // (X != 13 | X == 15) -> X != 13
4505 case ICmpInst::ICMP_UGT: // (X != 13 | X u> 15) -> X != 13
4506 case ICmpInst::ICMP_SGT: // (X != 13 | X s> 15) -> X != 13
4507 return ReplaceInstUsesWith(I, LHS);
4508 case ICmpInst::ICMP_NE: // (X != 13 | X != 15) -> true
4509 case ICmpInst::ICMP_ULT: // (X != 13 | X u< 15) -> true
4510 case ICmpInst::ICMP_SLT: // (X != 13 | X s< 15) -> true
4511 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4512 }
4513 break;
4514 case ICmpInst::ICMP_ULT:
4515 switch (RHSCC) {
4516 default: assert(0 && "Unknown integer condition code!");
4517 case ICmpInst::ICMP_EQ: // (X u< 13 | X == 14) -> no change
4518 break;
4519 case ICmpInst::ICMP_UGT: // (X u< 13 | X u> 15) -> (X-13) u> 2
4520 // If RHSCst is [us]MAXINT, it is always false. Not handling
4521 // this can cause overflow.
4522 if (RHSCst->isMaxValue(false))
4523 return ReplaceInstUsesWith(I, LHS);
4524 return InsertRangeTest(Val, LHSCst, AddOne(RHSCst), false, false, I);
4525 case ICmpInst::ICMP_SGT: // (X u< 13 | X s> 15) -> no change
4526 break;
4527 case ICmpInst::ICMP_NE: // (X u< 13 | X != 15) -> X != 15
4528 case ICmpInst::ICMP_ULT: // (X u< 13 | X u< 15) -> X u< 15
4529 return ReplaceInstUsesWith(I, RHS);
4530 case ICmpInst::ICMP_SLT: // (X u< 13 | X s< 15) -> no change
4531 break;
4532 }
4533 break;
4534 case ICmpInst::ICMP_SLT:
4535 switch (RHSCC) {
4536 default: assert(0 && "Unknown integer condition code!");
4537 case ICmpInst::ICMP_EQ: // (X s< 13 | X == 14) -> no change
4538 break;
4539 case ICmpInst::ICMP_SGT: // (X s< 13 | X s> 15) -> (X-13) s> 2
4540 // If RHSCst is [us]MAXINT, it is always false. Not handling
4541 // this can cause overflow.
4542 if (RHSCst->isMaxValue(true))
4543 return ReplaceInstUsesWith(I, LHS);
4544 return InsertRangeTest(Val, LHSCst, AddOne(RHSCst), true, false, I);
4545 case ICmpInst::ICMP_UGT: // (X s< 13 | X u> 15) -> no change
4546 break;
4547 case ICmpInst::ICMP_NE: // (X s< 13 | X != 15) -> X != 15
4548 case ICmpInst::ICMP_SLT: // (X s< 13 | X s< 15) -> X s< 15
4549 return ReplaceInstUsesWith(I, RHS);
4550 case ICmpInst::ICMP_ULT: // (X s< 13 | X u< 15) -> no change
4551 break;
4552 }
4553 break;
4554 case ICmpInst::ICMP_UGT:
4555 switch (RHSCC) {
4556 default: assert(0 && "Unknown integer condition code!");
4557 case ICmpInst::ICMP_EQ: // (X u> 13 | X == 15) -> X u> 13
4558 case ICmpInst::ICMP_UGT: // (X u> 13 | X u> 15) -> X u> 13
4559 return ReplaceInstUsesWith(I, LHS);
4560 case ICmpInst::ICMP_SGT: // (X u> 13 | X s> 15) -> no change
4561 break;
4562 case ICmpInst::ICMP_NE: // (X u> 13 | X != 15) -> true
4563 case ICmpInst::ICMP_ULT: // (X u> 13 | X u< 15) -> true
4564 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4565 case ICmpInst::ICMP_SLT: // (X u> 13 | X s< 15) -> no change
4566 break;
4567 }
4568 break;
4569 case ICmpInst::ICMP_SGT:
4570 switch (RHSCC) {
4571 default: assert(0 && "Unknown integer condition code!");
4572 case ICmpInst::ICMP_EQ: // (X s> 13 | X == 15) -> X > 13
4573 case ICmpInst::ICMP_SGT: // (X s> 13 | X s> 15) -> X > 13
4574 return ReplaceInstUsesWith(I, LHS);
4575 case ICmpInst::ICMP_UGT: // (X s> 13 | X u> 15) -> no change
4576 break;
4577 case ICmpInst::ICMP_NE: // (X s> 13 | X != 15) -> true
4578 case ICmpInst::ICMP_SLT: // (X s> 13 | X s< 15) -> true
4579 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4580 case ICmpInst::ICMP_ULT: // (X s> 13 | X u< 15) -> no change
4581 break;
4582 }
4583 break;
4584 }
4585 }
Chris Lattnerdcf756e2004-09-28 22:33:08 +00004586 }
Chris Lattner3af10532006-05-05 06:39:07 +00004587
4588 // fold (or (cast A), (cast B)) -> (cast (or A, B))
Chris Lattnerc62877e2007-10-24 05:38:08 +00004589 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
Chris Lattner3af10532006-05-05 06:39:07 +00004590 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
Reid Spencer799b5bf2006-12-13 08:27:15 +00004591 if (Op0C->getOpcode() == Op1C->getOpcode()) {// same cast kind ?
Evan Chengc3cf9f82008-03-24 00:21:34 +00004592 if (!isa<ICmpInst>(Op0C->getOperand(0)) ||
4593 !isa<ICmpInst>(Op1C->getOperand(0))) {
4594 const Type *SrcTy = Op0C->getOperand(0)->getType();
4595 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
4596 // Only do this if the casts both really cause code to be
4597 // generated.
4598 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
4599 I.getType(), TD) &&
4600 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
4601 I.getType(), TD)) {
Gabor Greife1f6e4b2008-05-16 19:29:10 +00004602 Instruction *NewOp = BinaryOperator::CreateOr(Op0C->getOperand(0),
Evan Chengc3cf9f82008-03-24 00:21:34 +00004603 Op1C->getOperand(0),
4604 I.getName());
4605 InsertNewInstBefore(NewOp, I);
Gabor Greife1f6e4b2008-05-16 19:29:10 +00004606 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
Evan Chengc3cf9f82008-03-24 00:21:34 +00004607 }
Reid Spencer799b5bf2006-12-13 08:27:15 +00004608 }
Chris Lattner3af10532006-05-05 06:39:07 +00004609 }
Chris Lattnerc62877e2007-10-24 05:38:08 +00004610 }
4611
4612
4613 // (fcmp uno x, c) | (fcmp uno y, c) -> (fcmp uno x, y)
4614 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
4615 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1))) {
4616 if (LHS->getPredicate() == FCmpInst::FCMP_UNO &&
Chris Lattnerc6125712008-02-29 06:09:11 +00004617 RHS->getPredicate() == FCmpInst::FCMP_UNO &&
Evan Chengd885f6e2008-10-14 18:44:08 +00004618 LHS->getOperand(0)->getType() == RHS->getOperand(0)->getType()) {
Chris Lattnerc62877e2007-10-24 05:38:08 +00004619 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
4620 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
4621 // If either of the constants are nans, then the whole thing returns
4622 // true.
Chris Lattner55b83022007-10-24 18:54:45 +00004623 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
Chris Lattnerc62877e2007-10-24 05:38:08 +00004624 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4625
4626 // Otherwise, no need to compare the two constants, compare the
4627 // rest.
4628 return new FCmpInst(FCmpInst::FCMP_UNO, LHS->getOperand(0),
4629 RHS->getOperand(0));
4630 }
Evan Chengd885f6e2008-10-14 18:44:08 +00004631 } else {
4632 Value *Op0LHS, *Op0RHS, *Op1LHS, *Op1RHS;
4633 FCmpInst::Predicate Op0CC, Op1CC;
4634 if (match(Op0, m_FCmp(Op0CC, m_Value(Op0LHS), m_Value(Op0RHS))) &&
4635 match(Op1, m_FCmp(Op1CC, m_Value(Op1LHS), m_Value(Op1RHS)))) {
4636 if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
4637 // Swap RHS operands to match LHS.
4638 Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
4639 std::swap(Op1LHS, Op1RHS);
4640 }
4641 if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
4642 // Simplify (fcmp cc0 x, y) | (fcmp cc1 x, y).
4643 if (Op0CC == Op1CC)
4644 return new FCmpInst((FCmpInst::Predicate)Op0CC, Op0LHS, Op0RHS);
4645 else if (Op0CC == FCmpInst::FCMP_TRUE ||
4646 Op1CC == FCmpInst::FCMP_TRUE)
4647 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4648 else if (Op0CC == FCmpInst::FCMP_FALSE)
4649 return ReplaceInstUsesWith(I, Op1);
4650 else if (Op1CC == FCmpInst::FCMP_FALSE)
4651 return ReplaceInstUsesWith(I, Op0);
4652 bool Op0Ordered;
4653 bool Op1Ordered;
4654 unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
4655 unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
4656 if (Op0Ordered == Op1Ordered) {
4657 // If both are ordered or unordered, return a new fcmp with
4658 // or'ed predicates.
4659 Value *RV = getFCmpValue(Op0Ordered, Op0Pred|Op1Pred,
4660 Op0LHS, Op0RHS);
4661 if (Instruction *I = dyn_cast<Instruction>(RV))
4662 return I;
4663 // Otherwise, it's a constant boolean value...
4664 return ReplaceInstUsesWith(I, RV);
4665 }
4666 }
4667 }
4668 }
Chris Lattnerc62877e2007-10-24 05:38:08 +00004669 }
4670 }
Chris Lattner15212982005-09-18 03:42:07 +00004671
Chris Lattner113f4f42002-06-25 16:13:24 +00004672 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00004673}
4674
Dan Gohmand78c4002008-05-13 00:00:25 +00004675namespace {
4676
Chris Lattnerc2076352004-02-16 01:20:27 +00004677// XorSelf - Implements: X ^ X --> 0
4678struct XorSelf {
4679 Value *RHS;
4680 XorSelf(Value *rhs) : RHS(rhs) {}
4681 bool shouldApply(Value *LHS) const { return LHS == RHS; }
4682 Instruction *apply(BinaryOperator &Xor) const {
4683 return &Xor;
4684 }
4685};
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00004686
Dan Gohmand78c4002008-05-13 00:00:25 +00004687}
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00004688
Chris Lattner113f4f42002-06-25 16:13:24 +00004689Instruction *InstCombiner::visitXor(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00004690 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00004691 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00004692
Evan Cheng2b72c052008-03-25 20:07:13 +00004693 if (isa<UndefValue>(Op1)) {
4694 if (isa<UndefValue>(Op0))
4695 // Handle undef ^ undef -> 0 special case. This is a common
4696 // idiom (misuse).
4697 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner81a7a232004-10-16 18:11:37 +00004698 return ReplaceInstUsesWith(I, Op1); // X ^ undef -> undef
Evan Cheng2b72c052008-03-25 20:07:13 +00004699 }
Chris Lattner81a7a232004-10-16 18:11:37 +00004700
Chris Lattnerc2076352004-02-16 01:20:27 +00004701 // xor X, X = 0, even if X is nested in a sequence of Xor's.
4702 if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1))) {
Chris Lattnerf0da7972007-08-05 08:47:58 +00004703 assert(Result == &I && "AssociativeOpt didn't work?"); Result=Result;
Chris Lattnere6794492002-08-12 21:17:25 +00004704 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerc2076352004-02-16 01:20:27 +00004705 }
Chris Lattner5b2edb12006-02-12 08:02:11 +00004706
4707 // See if we can simplify any instructions used by the instruction whose sole
4708 // purpose is to compute bits we don't care about.
Reid Spencerb722f2b2007-03-22 22:19:58 +00004709 if (!isa<VectorType>(I.getType())) {
4710 uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
4711 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
4712 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
4713 KnownZero, KnownOne))
4714 return &I;
Chris Lattnerf14e5172007-06-15 05:26:55 +00004715 } else if (isa<ConstantAggregateZero>(Op1)) {
4716 return ReplaceInstUsesWith(I, Op0); // X ^ <0,0> -> X
Reid Spencerb722f2b2007-03-22 22:19:58 +00004717 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00004718
Chris Lattner37338922007-06-15 06:23:19 +00004719 // Is this a ~ operation?
4720 if (Value *NotOp = dyn_castNotVal(&I)) {
4721 // ~(~X & Y) --> (X | ~Y) - De Morgan's Law
4722 // ~(~X | Y) === (X & ~Y) - De Morgan's Law
4723 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(NotOp)) {
4724 if (Op0I->getOpcode() == Instruction::And ||
4725 Op0I->getOpcode() == Instruction::Or) {
4726 if (dyn_castNotVal(Op0I->getOperand(1))) Op0I->swapOperands();
4727 if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
4728 Instruction *NotY =
Gabor Greife1f6e4b2008-05-16 19:29:10 +00004729 BinaryOperator::CreateNot(Op0I->getOperand(1),
Chris Lattner37338922007-06-15 06:23:19 +00004730 Op0I->getOperand(1)->getName()+".not");
4731 InsertNewInstBefore(NotY, I);
4732 if (Op0I->getOpcode() == Instruction::And)
Gabor Greife1f6e4b2008-05-16 19:29:10 +00004733 return BinaryOperator::CreateOr(Op0NotVal, NotY);
Chris Lattner37338922007-06-15 06:23:19 +00004734 else
Gabor Greife1f6e4b2008-05-16 19:29:10 +00004735 return BinaryOperator::CreateAnd(Op0NotVal, NotY);
Chris Lattner37338922007-06-15 06:23:19 +00004736 }
4737 }
4738 }
4739 }
4740
4741
Zhou Sheng75b871f2007-01-11 12:24:14 +00004742 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Nick Lewycky80520192007-08-06 20:04:16 +00004743 // xor (cmp A, B), true = not (cmp A, B) = !cmp A, B
4744 if (RHS == ConstantInt::getTrue() && Op0->hasOneUse()) {
4745 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Op0))
Reid Spencer266e42b2006-12-23 06:05:41 +00004746 return new ICmpInst(ICI->getInversePredicate(),
4747 ICI->getOperand(0), ICI->getOperand(1));
Chris Lattnere5806662003-11-04 23:50:51 +00004748
Nick Lewycky80520192007-08-06 20:04:16 +00004749 if (FCmpInst *FCI = dyn_cast<FCmpInst>(Op0))
4750 return new FCmpInst(FCI->getInversePredicate(),
4751 FCI->getOperand(0), FCI->getOperand(1));
4752 }
4753
Nick Lewycky035fe6f2008-05-31 19:01:33 +00004754 // fold (xor(zext(cmp)), 1) and (xor(sext(cmp)), -1) to ext(!cmp).
4755 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
4756 if (CmpInst *CI = dyn_cast<CmpInst>(Op0C->getOperand(0))) {
4757 if (CI->hasOneUse() && Op0C->hasOneUse()) {
4758 Instruction::CastOps Opcode = Op0C->getOpcode();
4759 if (Opcode == Instruction::ZExt || Opcode == Instruction::SExt) {
4760 if (RHS == ConstantExpr::getCast(Opcode, ConstantInt::getTrue(),
4761 Op0C->getDestTy())) {
4762 Instruction *NewCI = InsertNewInstBefore(CmpInst::Create(
4763 CI->getOpcode(), CI->getInversePredicate(),
4764 CI->getOperand(0), CI->getOperand(1)), I);
4765 NewCI->takeName(CI);
4766 return CastInst::Create(Opcode, NewCI, Op0C->getType());
4767 }
4768 }
4769 }
4770 }
4771 }
4772
Reid Spencer266e42b2006-12-23 06:05:41 +00004773 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
Chris Lattner8f2f5982003-11-05 01:06:05 +00004774 // ~(c-X) == X-c-1 == X+(-c-1)
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00004775 if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
4776 if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00004777 Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
4778 Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00004779 ConstantInt::get(I.getType(), 1));
Gabor Greife1f6e4b2008-05-16 19:29:10 +00004780 return BinaryOperator::CreateAdd(Op0I->getOperand(1), ConstantRHS);
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00004781 }
Chris Lattnerb24acc72007-04-02 05:36:22 +00004782
Anton Korobeynikov1bfd1212008-02-20 11:26:25 +00004783 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
Chris Lattner5b2edb12006-02-12 08:02:11 +00004784 if (Op0I->getOpcode() == Instruction::Add) {
Chris Lattner0f68fa62003-11-04 23:37:10 +00004785 // ~(X-c) --> (-c-1)-X
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00004786 if (RHS->isAllOnesValue()) {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00004787 Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
Gabor Greife1f6e4b2008-05-16 19:29:10 +00004788 return BinaryOperator::CreateSub(
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00004789 ConstantExpr::getSub(NegOp0CI,
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00004790 ConstantInt::get(I.getType(), 1)),
Chris Lattner0f68fa62003-11-04 23:37:10 +00004791 Op0I->getOperand(0));
Chris Lattner50490d52007-04-02 05:42:22 +00004792 } else if (RHS->getValue().isSignBit()) {
Chris Lattnerb24acc72007-04-02 05:36:22 +00004793 // (X + C) ^ signbit -> (X + C + signbit)
4794 Constant *C = ConstantInt::get(RHS->getValue() + Op0CI->getValue());
Gabor Greife1f6e4b2008-05-16 19:29:10 +00004795 return BinaryOperator::CreateAdd(Op0I->getOperand(0), C);
Chris Lattner9d5aace2007-04-02 05:48:58 +00004796
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00004797 }
Chris Lattnerf78df7c2006-02-26 19:57:54 +00004798 } else if (Op0I->getOpcode() == Instruction::Or) {
4799 // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
Reid Spencerb722f2b2007-03-22 22:19:58 +00004800 if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getValue())) {
Chris Lattnerf78df7c2006-02-26 19:57:54 +00004801 Constant *NewRHS = ConstantExpr::getOr(Op0CI, RHS);
4802 // Anything in both C1 and C2 is known to be zero, remove it from
4803 // NewRHS.
Zhou Sheng9bc8ab12007-04-02 13:45:30 +00004804 Constant *CommonBits = And(Op0CI, RHS);
Chris Lattnerf78df7c2006-02-26 19:57:54 +00004805 NewRHS = ConstantExpr::getAnd(NewRHS,
4806 ConstantExpr::getNot(CommonBits));
Chris Lattnerb15e2b12007-03-02 21:28:56 +00004807 AddToWorkList(Op0I);
Chris Lattnerf78df7c2006-02-26 19:57:54 +00004808 I.setOperand(0, Op0I->getOperand(0));
4809 I.setOperand(1, NewRHS);
4810 return &I;
4811 }
Chris Lattner97638592003-07-23 21:37:07 +00004812 }
Anton Korobeynikov1bfd1212008-02-20 11:26:25 +00004813 }
Chris Lattnerb8d6e402002-08-20 18:24:26 +00004814 }
Chris Lattner183b3362004-04-09 19:05:30 +00004815
4816 // Try to fold constant and into select arguments.
4817 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner86102b82005-01-01 16:22:27 +00004818 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00004819 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00004820 if (isa<PHINode>(Op0))
4821 if (Instruction *NV = FoldOpIntoPhi(I))
4822 return NV;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00004823 }
4824
Chris Lattnerbb74e222003-03-10 23:06:50 +00004825 if (Value *X = dyn_castNotVal(Op0)) // ~A ^ A == -1
Chris Lattner3082c5a2003-02-18 19:28:33 +00004826 if (X == Op1)
Chris Lattner37338922007-06-15 06:23:19 +00004827 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattner3082c5a2003-02-18 19:28:33 +00004828
Chris Lattnerbb74e222003-03-10 23:06:50 +00004829 if (Value *X = dyn_castNotVal(Op1)) // A ^ ~A == -1
Chris Lattner3082c5a2003-02-18 19:28:33 +00004830 if (X == Op0)
Chris Lattner37338922007-06-15 06:23:19 +00004831 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattner3082c5a2003-02-18 19:28:33 +00004832
Chris Lattner07418422007-03-18 22:51:34 +00004833
4834 BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1);
4835 if (Op1I) {
4836 Value *A, *B;
4837 if (match(Op1I, m_Or(m_Value(A), m_Value(B)))) {
4838 if (A == Op0) { // B^(B|A) == (A|B)^B
Chris Lattnerdcd07922006-04-01 08:03:55 +00004839 Op1I->swapOperands();
Chris Lattner1bbb7b62003-03-10 18:24:17 +00004840 I.swapOperands();
4841 std::swap(Op0, Op1);
Chris Lattner07418422007-03-18 22:51:34 +00004842 } else if (B == Op0) { // B^(A|B) == (A|B)^B
Chris Lattnerdcd07922006-04-01 08:03:55 +00004843 I.swapOperands(); // Simplified below.
Chris Lattner1bbb7b62003-03-10 18:24:17 +00004844 std::swap(Op0, Op1);
Misha Brukmanb1c93172005-04-21 23:48:37 +00004845 }
Chris Lattner07418422007-03-18 22:51:34 +00004846 } else if (match(Op1I, m_Xor(m_Value(A), m_Value(B)))) {
4847 if (Op0 == A) // A^(A^B) == B
4848 return ReplaceInstUsesWith(I, B);
4849 else if (Op0 == B) // A^(B^A) == B
4850 return ReplaceInstUsesWith(I, A);
4851 } else if (match(Op1I, m_And(m_Value(A), m_Value(B))) && Op1I->hasOneUse()){
Chris Lattner04277992007-04-01 05:36:37 +00004852 if (A == Op0) { // A^(A&B) -> A^(B&A)
Chris Lattnerdcd07922006-04-01 08:03:55 +00004853 Op1I->swapOperands();
Chris Lattner04277992007-04-01 05:36:37 +00004854 std::swap(A, B);
4855 }
Chris Lattner07418422007-03-18 22:51:34 +00004856 if (B == Op0) { // A^(B&A) -> (B&A)^A
Chris Lattnerdcd07922006-04-01 08:03:55 +00004857 I.swapOperands(); // Simplified below.
4858 std::swap(Op0, Op1);
4859 }
Chris Lattnerb36d9082004-02-16 03:54:20 +00004860 }
Chris Lattner07418422007-03-18 22:51:34 +00004861 }
4862
4863 BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0);
4864 if (Op0I) {
4865 Value *A, *B;
4866 if (match(Op0I, m_Or(m_Value(A), m_Value(B))) && Op0I->hasOneUse()) {
4867 if (A == Op1) // (B|A)^B == (A|B)^B
4868 std::swap(A, B);
4869 if (B == Op1) { // (A|B)^B == A & ~B
4870 Instruction *NotB =
Gabor Greife1f6e4b2008-05-16 19:29:10 +00004871 InsertNewInstBefore(BinaryOperator::CreateNot(Op1, "tmp"), I);
4872 return BinaryOperator::CreateAnd(A, NotB);
Chris Lattner1bbb7b62003-03-10 18:24:17 +00004873 }
Chris Lattner07418422007-03-18 22:51:34 +00004874 } else if (match(Op0I, m_Xor(m_Value(A), m_Value(B)))) {
4875 if (Op1 == A) // (A^B)^A == B
4876 return ReplaceInstUsesWith(I, B);
4877 else if (Op1 == B) // (B^A)^A == B
4878 return ReplaceInstUsesWith(I, A);
4879 } else if (match(Op0I, m_And(m_Value(A), m_Value(B))) && Op0I->hasOneUse()){
4880 if (A == Op1) // (A&B)^A -> (B&A)^A
4881 std::swap(A, B);
4882 if (B == Op1 && // (B&A)^A == ~B & A
Chris Lattner6cf49142006-04-01 22:05:01 +00004883 !isa<ConstantInt>(Op1)) { // Canonical form is (B&C)^C
Chris Lattner07418422007-03-18 22:51:34 +00004884 Instruction *N =
Gabor Greife1f6e4b2008-05-16 19:29:10 +00004885 InsertNewInstBefore(BinaryOperator::CreateNot(A, "tmp"), I);
4886 return BinaryOperator::CreateAnd(N, Op1);
Chris Lattnerdcd07922006-04-01 08:03:55 +00004887 }
Chris Lattner1bbb7b62003-03-10 18:24:17 +00004888 }
Chris Lattner07418422007-03-18 22:51:34 +00004889 }
4890
4891 // (X >> Z) ^ (Y >> Z) -> (X^Y) >> Z for all shifts.
4892 if (Op0I && Op1I && Op0I->isShift() &&
4893 Op0I->getOpcode() == Op1I->getOpcode() &&
4894 Op0I->getOperand(1) == Op1I->getOperand(1) &&
4895 (Op1I->hasOneUse() || Op1I->hasOneUse())) {
4896 Instruction *NewOp =
Gabor Greife1f6e4b2008-05-16 19:29:10 +00004897 InsertNewInstBefore(BinaryOperator::CreateXor(Op0I->getOperand(0),
Chris Lattner07418422007-03-18 22:51:34 +00004898 Op1I->getOperand(0),
4899 Op0I->getName()), I);
Gabor Greife1f6e4b2008-05-16 19:29:10 +00004900 return BinaryOperator::Create(Op1I->getOpcode(), NewOp,
Chris Lattner07418422007-03-18 22:51:34 +00004901 Op1I->getOperand(1));
4902 }
4903
4904 if (Op0I && Op1I) {
4905 Value *A, *B, *C, *D;
4906 // (A & B)^(A | B) -> A ^ B
4907 if (match(Op0I, m_And(m_Value(A), m_Value(B))) &&
4908 match(Op1I, m_Or(m_Value(C), m_Value(D)))) {
4909 if ((A == C && B == D) || (A == D && B == C))
Gabor Greife1f6e4b2008-05-16 19:29:10 +00004910 return BinaryOperator::CreateXor(A, B);
Chris Lattner07418422007-03-18 22:51:34 +00004911 }
4912 // (A | B)^(A & B) -> A ^ B
4913 if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
4914 match(Op1I, m_And(m_Value(C), m_Value(D)))) {
4915 if ((A == C && B == D) || (A == D && B == C))
Gabor Greife1f6e4b2008-05-16 19:29:10 +00004916 return BinaryOperator::CreateXor(A, B);
Chris Lattner07418422007-03-18 22:51:34 +00004917 }
4918
4919 // (A & B)^(C & D)
4920 if ((Op0I->hasOneUse() || Op1I->hasOneUse()) &&
4921 match(Op0I, m_And(m_Value(A), m_Value(B))) &&
4922 match(Op1I, m_And(m_Value(C), m_Value(D)))) {
4923 // (X & Y)^(X & Y) -> (Y^Z) & X
4924 Value *X = 0, *Y = 0, *Z = 0;
4925 if (A == C)
4926 X = A, Y = B, Z = D;
4927 else if (A == D)
4928 X = A, Y = B, Z = C;
4929 else if (B == C)
4930 X = B, Y = A, Z = D;
4931 else if (B == D)
4932 X = B, Y = A, Z = C;
4933
4934 if (X) {
4935 Instruction *NewOp =
Gabor Greife1f6e4b2008-05-16 19:29:10 +00004936 InsertNewInstBefore(BinaryOperator::CreateXor(Y, Z, Op0->getName()), I);
4937 return BinaryOperator::CreateAnd(NewOp, X);
Chris Lattner07418422007-03-18 22:51:34 +00004938 }
4939 }
4940 }
4941
Reid Spencer266e42b2006-12-23 06:05:41 +00004942 // (icmp1 A, B) ^ (icmp2 A, B) --> (icmp3 A, B)
4943 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
4944 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Chris Lattner3ac7c262003-08-13 20:16:26 +00004945 return R;
4946
Chris Lattner3af10532006-05-05 06:39:07 +00004947 // fold (xor (cast A), (cast B)) -> (cast (xor A, B))
Chris Lattnerc62877e2007-10-24 05:38:08 +00004948 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
Chris Lattner3af10532006-05-05 06:39:07 +00004949 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
Reid Spencer799b5bf2006-12-13 08:27:15 +00004950 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind?
4951 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattner03c49532007-01-15 02:27:26 +00004952 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
Reid Spencer799b5bf2006-12-13 08:27:15 +00004953 // Only do this if the casts both really cause code to be generated.
Reid Spencer266e42b2006-12-23 06:05:41 +00004954 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
4955 I.getType(), TD) &&
4956 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
4957 I.getType(), TD)) {
Gabor Greife1f6e4b2008-05-16 19:29:10 +00004958 Instruction *NewOp = BinaryOperator::CreateXor(Op0C->getOperand(0),
Reid Spencer799b5bf2006-12-13 08:27:15 +00004959 Op1C->getOperand(0),
4960 I.getName());
4961 InsertNewInstBefore(NewOp, I);
Gabor Greife1f6e4b2008-05-16 19:29:10 +00004962 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
Reid Spencer799b5bf2006-12-13 08:27:15 +00004963 }
Chris Lattner3af10532006-05-05 06:39:07 +00004964 }
Chris Lattnerc62877e2007-10-24 05:38:08 +00004965 }
Nick Lewycky035fe6f2008-05-31 19:01:33 +00004966
Chris Lattner113f4f42002-06-25 16:13:24 +00004967 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00004968}
4969
Chris Lattner6862fbd2004-09-29 17:40:11 +00004970/// AddWithOverflow - Compute Result = In1+In2, returning true if the result
4971/// overflowed for this type.
4972static bool AddWithOverflow(ConstantInt *&Result, ConstantInt *In1,
Reid Spencerf4071162007-03-21 23:19:50 +00004973 ConstantInt *In2, bool IsSigned = false) {
Zhou Sheng9bc8ab12007-04-02 13:45:30 +00004974 Result = cast<ConstantInt>(Add(In1, In2));
Chris Lattner6862fbd2004-09-29 17:40:11 +00004975
Reid Spencerf4071162007-03-21 23:19:50 +00004976 if (IsSigned)
4977 if (In2->getValue().isNegative())
4978 return Result->getValue().sgt(In1->getValue());
4979 else
4980 return Result->getValue().slt(In1->getValue());
4981 else
4982 return Result->getValue().ult(In1->getValue());
Chris Lattner6862fbd2004-09-29 17:40:11 +00004983}
4984
Dan Gohmanc1ae0162008-09-10 23:30:57 +00004985/// SubWithOverflow - Compute Result = In1-In2, returning true if the result
4986/// overflowed for this type.
4987static bool SubWithOverflow(ConstantInt *&Result, ConstantInt *In1,
4988 ConstantInt *In2, bool IsSigned = false) {
Dan Gohman9b9d5472008-09-11 18:53:02 +00004989 Result = cast<ConstantInt>(Subtract(In1, In2));
Dan Gohmanc1ae0162008-09-10 23:30:57 +00004990
4991 if (IsSigned)
4992 if (In2->getValue().isNegative())
4993 return Result->getValue().slt(In1->getValue());
4994 else
4995 return Result->getValue().sgt(In1->getValue());
4996 else
4997 return Result->getValue().ugt(In1->getValue());
4998}
4999
Chris Lattner0798af32005-01-13 20:14:25 +00005000/// EmitGEPOffset - Given a getelementptr instruction/constantexpr, emit the
5001/// code necessary to compute the offset from the base pointer (without adding
5002/// in the base pointer). Return the result as a signed integer of intptr size.
5003static Value *EmitGEPOffset(User *GEP, Instruction &I, InstCombiner &IC) {
5004 TargetData &TD = IC.getTargetData();
5005 gep_type_iterator GTI = gep_type_begin(GEP);
Reid Spencer266e42b2006-12-23 06:05:41 +00005006 const Type *IntPtrTy = TD.getIntPtrType();
5007 Value *Result = Constant::getNullValue(IntPtrTy);
Chris Lattner0798af32005-01-13 20:14:25 +00005008
5009 // Build a mask for high order bits.
Chris Lattnerc3a43932008-04-22 02:53:33 +00005010 unsigned IntPtrWidth = TD.getPointerSizeInBits();
Chris Lattner6e880872007-04-28 04:52:43 +00005011 uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
Chris Lattner0798af32005-01-13 20:14:25 +00005012
Gabor Greiff6d8e772008-06-12 21:37:33 +00005013 for (User::op_iterator i = GEP->op_begin() + 1, e = GEP->op_end(); i != e;
5014 ++i, ++GTI) {
5015 Value *Op = *i;
Duncan Sands44b87212007-11-01 20:53:16 +00005016 uint64_t Size = TD.getABITypeSize(GTI.getIndexedType()) & PtrSizeMask;
Chris Lattner6e880872007-04-28 04:52:43 +00005017 if (ConstantInt *OpC = dyn_cast<ConstantInt>(Op)) {
5018 if (OpC->isZero()) continue;
5019
5020 // Handle a struct index, which adds its field offset to the pointer.
5021 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5022 Size = TD.getStructLayout(STy)->getElementOffset(OpC->getZExtValue());
5023
5024 if (ConstantInt *RC = dyn_cast<ConstantInt>(Result))
5025 Result = ConstantInt::get(RC->getValue() + APInt(IntPtrWidth, Size));
Chris Lattneracbf6a42007-04-28 00:57:34 +00005026 else
Chris Lattner6e880872007-04-28 04:52:43 +00005027 Result = IC.InsertNewInstBefore(
Gabor Greife1f6e4b2008-05-16 19:29:10 +00005028 BinaryOperator::CreateAdd(Result,
Chris Lattner6e880872007-04-28 04:52:43 +00005029 ConstantInt::get(IntPtrTy, Size),
5030 GEP->getName()+".offs"), I);
5031 continue;
Chris Lattneracbf6a42007-04-28 00:57:34 +00005032 }
Chris Lattner6e880872007-04-28 04:52:43 +00005033
5034 Constant *Scale = ConstantInt::get(IntPtrTy, Size);
5035 Constant *OC = ConstantExpr::getIntegerCast(OpC, IntPtrTy, true /*SExt*/);
5036 Scale = ConstantExpr::getMul(OC, Scale);
5037 if (Constant *RC = dyn_cast<Constant>(Result))
5038 Result = ConstantExpr::getAdd(RC, Scale);
5039 else {
5040 // Emit an add instruction.
5041 Result = IC.InsertNewInstBefore(
Gabor Greife1f6e4b2008-05-16 19:29:10 +00005042 BinaryOperator::CreateAdd(Result, Scale,
Chris Lattner6e880872007-04-28 04:52:43 +00005043 GEP->getName()+".offs"), I);
Chris Lattneracbf6a42007-04-28 00:57:34 +00005044 }
Chris Lattner6e880872007-04-28 04:52:43 +00005045 continue;
Chris Lattner0798af32005-01-13 20:14:25 +00005046 }
Chris Lattner6e880872007-04-28 04:52:43 +00005047 // Convert to correct type.
5048 if (Op->getType() != IntPtrTy) {
5049 if (Constant *OpC = dyn_cast<Constant>(Op))
5050 Op = ConstantExpr::getSExt(OpC, IntPtrTy);
5051 else
5052 Op = IC.InsertNewInstBefore(new SExtInst(Op, IntPtrTy,
5053 Op->getName()+".c"), I);
5054 }
5055 if (Size != 1) {
5056 Constant *Scale = ConstantInt::get(IntPtrTy, Size);
5057 if (Constant *OpC = dyn_cast<Constant>(Op))
5058 Op = ConstantExpr::getMul(OpC, Scale);
5059 else // We'll let instcombine(mul) convert this to a shl if possible.
Gabor Greife1f6e4b2008-05-16 19:29:10 +00005060 Op = IC.InsertNewInstBefore(BinaryOperator::CreateMul(Op, Scale,
Chris Lattner6e880872007-04-28 04:52:43 +00005061 GEP->getName()+".idx"), I);
5062 }
5063
5064 // Emit an add instruction.
5065 if (isa<Constant>(Op) && isa<Constant>(Result))
5066 Result = ConstantExpr::getAdd(cast<Constant>(Op),
5067 cast<Constant>(Result));
5068 else
Gabor Greife1f6e4b2008-05-16 19:29:10 +00005069 Result = IC.InsertNewInstBefore(BinaryOperator::CreateAdd(Op, Result,
Chris Lattner6e880872007-04-28 04:52:43 +00005070 GEP->getName()+".offs"), I);
Chris Lattner0798af32005-01-13 20:14:25 +00005071 }
5072 return Result;
5073}
5074
Chris Lattnerc3a43932008-04-22 02:53:33 +00005075
5076/// EvaluateGEPOffsetExpression - Return an value that can be used to compare of
5077/// the *offset* implied by GEP to zero. For example, if we have &A[i], we want
5078/// to return 'i' for "icmp ne i, 0". Note that, in general, indices can be
5079/// complex, and scales are involved. The above expression would also be legal
5080/// to codegen as "icmp ne (i*4), 0" (assuming A is a pointer to i32). This
5081/// later form is less amenable to optimization though, and we are allowed to
5082/// generate the first by knowing that pointer arithmetic doesn't overflow.
5083///
5084/// If we can't emit an optimized form for this expression, this returns null.
5085///
5086static Value *EvaluateGEPOffsetExpression(User *GEP, Instruction &I,
5087 InstCombiner &IC) {
Chris Lattnerc3a43932008-04-22 02:53:33 +00005088 TargetData &TD = IC.getTargetData();
5089 gep_type_iterator GTI = gep_type_begin(GEP);
5090
5091 // Check to see if this gep only has a single variable index. If so, and if
5092 // any constant indices are a multiple of its scale, then we can compute this
5093 // in terms of the scale of the variable index. For example, if the GEP
5094 // implies an offset of "12 + i*4", then we can codegen this as "3 + i",
5095 // because the expression will cross zero at the same point.
5096 unsigned i, e = GEP->getNumOperands();
5097 int64_t Offset = 0;
5098 for (i = 1; i != e; ++i, ++GTI) {
5099 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
5100 // Compute the aggregate offset of constant indices.
5101 if (CI->isZero()) continue;
5102
5103 // Handle a struct index, which adds its field offset to the pointer.
5104 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5105 Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
5106 } else {
5107 uint64_t Size = TD.getABITypeSize(GTI.getIndexedType());
5108 Offset += Size*CI->getSExtValue();
5109 }
5110 } else {
5111 // Found our variable index.
5112 break;
5113 }
5114 }
5115
5116 // If there are no variable indices, we must have a constant offset, just
5117 // evaluate it the general way.
5118 if (i == e) return 0;
5119
5120 Value *VariableIdx = GEP->getOperand(i);
5121 // Determine the scale factor of the variable element. For example, this is
5122 // 4 if the variable index is into an array of i32.
5123 uint64_t VariableScale = TD.getABITypeSize(GTI.getIndexedType());
5124
5125 // Verify that there are no other variable indices. If so, emit the hard way.
5126 for (++i, ++GTI; i != e; ++i, ++GTI) {
5127 ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i));
5128 if (!CI) return 0;
5129
5130 // Compute the aggregate offset of constant indices.
5131 if (CI->isZero()) continue;
5132
5133 // Handle a struct index, which adds its field offset to the pointer.
5134 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5135 Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
5136 } else {
5137 uint64_t Size = TD.getABITypeSize(GTI.getIndexedType());
5138 Offset += Size*CI->getSExtValue();
5139 }
5140 }
5141
5142 // Okay, we know we have a single variable index, which must be a
5143 // pointer/array/vector index. If there is no offset, life is simple, return
5144 // the index.
5145 unsigned IntPtrWidth = TD.getPointerSizeInBits();
5146 if (Offset == 0) {
5147 // Cast to intptrty in case a truncation occurs. If an extension is needed,
5148 // we don't need to bother extending: the extension won't affect where the
5149 // computation crosses zero.
5150 if (VariableIdx->getType()->getPrimitiveSizeInBits() > IntPtrWidth)
5151 VariableIdx = new TruncInst(VariableIdx, TD.getIntPtrType(),
5152 VariableIdx->getNameStart(), &I);
5153 return VariableIdx;
5154 }
5155
5156 // Otherwise, there is an index. The computation we will do will be modulo
5157 // the pointer size, so get it.
5158 uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
5159
5160 Offset &= PtrSizeMask;
5161 VariableScale &= PtrSizeMask;
5162
5163 // To do this transformation, any constant index must be a multiple of the
5164 // variable scale factor. For example, we can evaluate "12 + 4*i" as "3 + i",
5165 // but we can't evaluate "10 + 3*i" in terms of i. Check that the offset is a
5166 // multiple of the variable scale.
5167 int64_t NewOffs = Offset / (int64_t)VariableScale;
5168 if (Offset != NewOffs*(int64_t)VariableScale)
5169 return 0;
5170
5171 // Okay, we can do this evaluation. Start by converting the index to intptr.
5172 const Type *IntPtrTy = TD.getIntPtrType();
5173 if (VariableIdx->getType() != IntPtrTy)
Gabor Greife1f6e4b2008-05-16 19:29:10 +00005174 VariableIdx = CastInst::CreateIntegerCast(VariableIdx, IntPtrTy,
Chris Lattnerc3a43932008-04-22 02:53:33 +00005175 true /*SExt*/,
5176 VariableIdx->getNameStart(), &I);
5177 Constant *OffsetVal = ConstantInt::get(IntPtrTy, NewOffs);
Gabor Greife1f6e4b2008-05-16 19:29:10 +00005178 return BinaryOperator::CreateAdd(VariableIdx, OffsetVal, "offset", &I);
Chris Lattnerc3a43932008-04-22 02:53:33 +00005179}
5180
5181
Reid Spencer266e42b2006-12-23 06:05:41 +00005182/// FoldGEPICmp - Fold comparisons between a GEP instruction and something
Chris Lattner0798af32005-01-13 20:14:25 +00005183/// else. At this point we know that the GEP is on the LHS of the comparison.
Reid Spencer266e42b2006-12-23 06:05:41 +00005184Instruction *InstCombiner::FoldGEPICmp(User *GEPLHS, Value *RHS,
5185 ICmpInst::Predicate Cond,
5186 Instruction &I) {
Chris Lattner0798af32005-01-13 20:14:25 +00005187 assert(dyn_castGetElementPtr(GEPLHS) && "LHS is not a getelementptr!");
Chris Lattner81e84172005-01-13 22:25:21 +00005188
Chris Lattnerc3a43932008-04-22 02:53:33 +00005189 // Look through bitcasts.
5190 if (BitCastInst *BCI = dyn_cast<BitCastInst>(RHS))
5191 RHS = BCI->getOperand(0);
Chris Lattner81e84172005-01-13 22:25:21 +00005192
Chris Lattner0798af32005-01-13 20:14:25 +00005193 Value *PtrBase = GEPLHS->getOperand(0);
5194 if (PtrBase == RHS) {
Chris Lattner682a7dc2008-02-05 04:45:32 +00005195 // ((gep Ptr, OFFSET) cmp Ptr) ---> (OFFSET cmp 0).
Chris Lattnerc3a43932008-04-22 02:53:33 +00005196 // This transformation (ignoring the base and scales) is valid because we
5197 // know pointers can't overflow. See if we can output an optimized form.
5198 Value *Offset = EvaluateGEPOffsetExpression(GEPLHS, I, *this);
5199
5200 // If not, synthesize the offset the hard way.
5201 if (Offset == 0)
5202 Offset = EmitGEPOffset(GEPLHS, I, *this);
Chris Lattner682a7dc2008-02-05 04:45:32 +00005203 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), Offset,
5204 Constant::getNullValue(Offset->getType()));
Chris Lattner0798af32005-01-13 20:14:25 +00005205 } else if (User *GEPRHS = dyn_castGetElementPtr(RHS)) {
Chris Lattnera21bf8d2005-04-25 20:17:30 +00005206 // If the base pointers are different, but the indices are the same, just
5207 // compare the base pointer.
5208 if (PtrBase != GEPRHS->getOperand(0)) {
5209 bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00005210 IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
Chris Lattnerbd43b9d2005-04-26 14:40:41 +00005211 GEPRHS->getOperand(0)->getType();
Chris Lattnera21bf8d2005-04-25 20:17:30 +00005212 if (IndicesTheSame)
5213 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
5214 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
5215 IndicesTheSame = false;
5216 break;
5217 }
5218
5219 // If all indices are the same, just compare the base pointers.
5220 if (IndicesTheSame)
Reid Spencer266e42b2006-12-23 06:05:41 +00005221 return new ICmpInst(ICmpInst::getSignedPredicate(Cond),
5222 GEPLHS->getOperand(0), GEPRHS->getOperand(0));
Chris Lattnera21bf8d2005-04-25 20:17:30 +00005223
5224 // Otherwise, the base pointers are different and the indices are
5225 // different, bail out.
Chris Lattner0798af32005-01-13 20:14:25 +00005226 return 0;
Chris Lattnera21bf8d2005-04-25 20:17:30 +00005227 }
Chris Lattner0798af32005-01-13 20:14:25 +00005228
Chris Lattner81e84172005-01-13 22:25:21 +00005229 // If one of the GEPs has all zero indices, recurse.
5230 bool AllZeros = true;
5231 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
5232 if (!isa<Constant>(GEPLHS->getOperand(i)) ||
5233 !cast<Constant>(GEPLHS->getOperand(i))->isNullValue()) {
5234 AllZeros = false;
5235 break;
5236 }
5237 if (AllZeros)
Reid Spencer266e42b2006-12-23 06:05:41 +00005238 return FoldGEPICmp(GEPRHS, GEPLHS->getOperand(0),
5239 ICmpInst::getSwappedPredicate(Cond), I);
Chris Lattner4fa89822005-01-14 00:20:05 +00005240
5241 // If the other GEP has all zero indices, recurse.
Chris Lattner81e84172005-01-13 22:25:21 +00005242 AllZeros = true;
5243 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
5244 if (!isa<Constant>(GEPRHS->getOperand(i)) ||
5245 !cast<Constant>(GEPRHS->getOperand(i))->isNullValue()) {
5246 AllZeros = false;
5247 break;
5248 }
5249 if (AllZeros)
Reid Spencer266e42b2006-12-23 06:05:41 +00005250 return FoldGEPICmp(GEPLHS, GEPRHS->getOperand(0), Cond, I);
Chris Lattner81e84172005-01-13 22:25:21 +00005251
Chris Lattner4fa89822005-01-14 00:20:05 +00005252 if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
5253 // If the GEPs only differ by one index, compare it.
5254 unsigned NumDifferences = 0; // Keep track of # differences.
5255 unsigned DiffOperand = 0; // The operand that differs.
5256 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
5257 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
Chris Lattnerd1f46d32005-04-24 06:59:08 +00005258 if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
5259 GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
Chris Lattnerfc4429e2005-01-21 23:06:49 +00005260 // Irreconcilable differences.
Chris Lattner4fa89822005-01-14 00:20:05 +00005261 NumDifferences = 2;
5262 break;
5263 } else {
5264 if (NumDifferences++) break;
5265 DiffOperand = i;
5266 }
5267 }
5268
5269 if (NumDifferences == 0) // SAME GEP?
5270 return ReplaceInstUsesWith(I, // No comparison is needed here.
Nick Lewycky0c5c4792007-09-06 02:40:25 +00005271 ConstantInt::get(Type::Int1Ty,
Nick Lewycky79376f42008-05-17 07:33:39 +00005272 ICmpInst::isTrueWhenEqual(Cond)));
Nick Lewycky0c5c4792007-09-06 02:40:25 +00005273
Chris Lattner4fa89822005-01-14 00:20:05 +00005274 else if (NumDifferences == 1) {
Chris Lattnerfc4429e2005-01-21 23:06:49 +00005275 Value *LHSV = GEPLHS->getOperand(DiffOperand);
5276 Value *RHSV = GEPRHS->getOperand(DiffOperand);
Reid Spencer266e42b2006-12-23 06:05:41 +00005277 // Make sure we do a signed comparison here.
5278 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), LHSV, RHSV);
Chris Lattner4fa89822005-01-14 00:20:05 +00005279 }
5280 }
5281
Reid Spencer266e42b2006-12-23 06:05:41 +00005282 // Only lower this if the icmp is the only user of the GEP or if we expect
Chris Lattner0798af32005-01-13 20:14:25 +00005283 // the result to fold to a constant!
5284 if ((isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
5285 (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
5286 // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2) ---> (OFFSET1 cmp OFFSET2)
5287 Value *L = EmitGEPOffset(GEPLHS, I, *this);
5288 Value *R = EmitGEPOffset(GEPRHS, I, *this);
Reid Spencer266e42b2006-12-23 06:05:41 +00005289 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), L, R);
Chris Lattner0798af32005-01-13 20:14:25 +00005290 }
5291 }
5292 return 0;
5293}
5294
Chris Lattner5920a782008-05-19 20:18:56 +00005295/// FoldFCmp_IntToFP_Cst - Fold fcmp ([us]itofp x, cst) if possible.
5296///
5297Instruction *InstCombiner::FoldFCmp_IntToFP_Cst(FCmpInst &I,
5298 Instruction *LHSI,
5299 Constant *RHSC) {
5300 if (!isa<ConstantFP>(RHSC)) return 0;
5301 const APFloat &RHS = cast<ConstantFP>(RHSC)->getValueAPF();
5302
5303 // Get the width of the mantissa. We don't want to hack on conversions that
5304 // might lose information from the integer, e.g. "i64 -> float"
Chris Lattnerb4271222008-05-19 21:17:23 +00005305 int MantissaWidth = LHSI->getType()->getFPMantissaWidth();
Chris Lattner5920a782008-05-19 20:18:56 +00005306 if (MantissaWidth == -1) return 0; // Unknown.
5307
5308 // Check to see that the input is converted from an integer type that is small
5309 // enough that preserves all bits. TODO: check here for "known" sign bits.
5310 // This would allow us to handle (fptosi (x >>s 62) to float) if x is i64 f.e.
5311 unsigned InputSize = LHSI->getOperand(0)->getType()->getPrimitiveSizeInBits();
5312
5313 // If this is a uitofp instruction, we need an extra bit to hold the sign.
Bill Wendling3f547be2008-11-09 04:26:50 +00005314 bool LHSUnsigned = isa<UIToFPInst>(LHSI);
5315 if (LHSUnsigned)
Chris Lattner5920a782008-05-19 20:18:56 +00005316 ++InputSize;
5317
5318 // If the conversion would lose info, don't hack on this.
5319 if ((int)InputSize > MantissaWidth)
5320 return 0;
5321
5322 // Otherwise, we can potentially simplify the comparison. We know that it
5323 // will always come through as an integer value and we know the constant is
5324 // not a NAN (it would have been previously simplified).
5325 assert(!RHS.isNaN() && "NaN comparison not already folded!");
5326
5327 ICmpInst::Predicate Pred;
5328 switch (I.getPredicate()) {
5329 default: assert(0 && "Unexpected predicate!");
5330 case FCmpInst::FCMP_UEQ:
Bill Wendling3f547be2008-11-09 04:26:50 +00005331 case FCmpInst::FCMP_OEQ:
5332 Pred = ICmpInst::ICMP_EQ;
5333 break;
Chris Lattner5920a782008-05-19 20:18:56 +00005334 case FCmpInst::FCMP_UGT:
Bill Wendling3f547be2008-11-09 04:26:50 +00005335 case FCmpInst::FCMP_OGT:
5336 Pred = LHSUnsigned ? ICmpInst::ICMP_UGT : ICmpInst::ICMP_SGT;
5337 break;
Chris Lattner5920a782008-05-19 20:18:56 +00005338 case FCmpInst::FCMP_UGE:
Bill Wendling3f547be2008-11-09 04:26:50 +00005339 case FCmpInst::FCMP_OGE:
5340 Pred = LHSUnsigned ? ICmpInst::ICMP_UGE : ICmpInst::ICMP_SGE;
5341 break;
Chris Lattner5920a782008-05-19 20:18:56 +00005342 case FCmpInst::FCMP_ULT:
Bill Wendling3f547be2008-11-09 04:26:50 +00005343 case FCmpInst::FCMP_OLT:
5344 Pred = LHSUnsigned ? ICmpInst::ICMP_ULT : ICmpInst::ICMP_SLT;
5345 break;
Chris Lattner5920a782008-05-19 20:18:56 +00005346 case FCmpInst::FCMP_ULE:
Bill Wendling3f547be2008-11-09 04:26:50 +00005347 case FCmpInst::FCMP_OLE:
5348 Pred = LHSUnsigned ? ICmpInst::ICMP_ULE : ICmpInst::ICMP_SLE;
5349 break;
Chris Lattner5920a782008-05-19 20:18:56 +00005350 case FCmpInst::FCMP_UNE:
Bill Wendling3f547be2008-11-09 04:26:50 +00005351 case FCmpInst::FCMP_ONE:
5352 Pred = ICmpInst::ICMP_NE;
5353 break;
Chris Lattner5920a782008-05-19 20:18:56 +00005354 case FCmpInst::FCMP_ORD:
5355 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
5356 case FCmpInst::FCMP_UNO:
5357 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
5358 }
5359
5360 const IntegerType *IntTy = cast<IntegerType>(LHSI->getOperand(0)->getType());
5361
5362 // Now we know that the APFloat is a normal number, zero or inf.
5363
Chris Lattner9c27f962008-05-20 03:50:52 +00005364 // See if the FP constant is too large for the integer. For example,
Chris Lattner5920a782008-05-19 20:18:56 +00005365 // comparing an i8 to 300.0.
5366 unsigned IntWidth = IntTy->getPrimitiveSizeInBits();
5367
Bill Wendling3f547be2008-11-09 04:26:50 +00005368 if (!LHSUnsigned) {
5369 // If the RHS value is > SignedMax, fold the comparison. This handles +INF
5370 // and large values.
5371 APFloat SMax(RHS.getSemantics(), APFloat::fcZero, false);
5372 SMax.convertFromAPInt(APInt::getSignedMaxValue(IntWidth), true,
5373 APFloat::rmNearestTiesToEven);
5374 if (SMax.compare(RHS) == APFloat::cmpLessThan) { // smax < 13123.0
5375 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SLT ||
5376 Pred == ICmpInst::ICMP_SLE)
5377 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
5378 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
5379 }
5380 } else {
5381 // If the RHS value is > UnsignedMax, fold the comparison. This handles
5382 // +INF and large values.
5383 APFloat UMax(RHS.getSemantics(), APFloat::fcZero, false);
5384 UMax.convertFromAPInt(APInt::getMaxValue(IntWidth), false,
5385 APFloat::rmNearestTiesToEven);
5386 if (UMax.compare(RHS) == APFloat::cmpLessThan) { // umax < 13123.0
5387 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_ULT ||
5388 Pred == ICmpInst::ICMP_ULE)
5389 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
5390 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
5391 }
Chris Lattner5920a782008-05-19 20:18:56 +00005392 }
5393
Bill Wendling3f547be2008-11-09 04:26:50 +00005394 if (!LHSUnsigned) {
5395 // See if the RHS value is < SignedMin.
5396 APFloat SMin(RHS.getSemantics(), APFloat::fcZero, false);
5397 SMin.convertFromAPInt(APInt::getSignedMinValue(IntWidth), true,
5398 APFloat::rmNearestTiesToEven);
5399 if (SMin.compare(RHS) == APFloat::cmpGreaterThan) { // smin > 12312.0
5400 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SGT ||
5401 Pred == ICmpInst::ICMP_SGE)
5402 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
5403 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
5404 }
Chris Lattner5920a782008-05-19 20:18:56 +00005405 }
5406
Bill Wendling3f547be2008-11-09 04:26:50 +00005407 // Okay, now we know that the FP constant fits in the range [SMIN, SMAX] or
5408 // [0, UMAX], but it may still be fractional. See if it is fractional by
5409 // casting the FP value to the integer value and back, checking for equality.
5410 // Don't do this for zero, because -0.0 is not fractional.
Chris Lattner5920a782008-05-19 20:18:56 +00005411 Constant *RHSInt = ConstantExpr::getFPToSI(RHSC, IntTy);
5412 if (!RHS.isZero() &&
5413 ConstantExpr::getSIToFP(RHSInt, RHSC->getType()) != RHSC) {
Bill Wendling3f547be2008-11-09 04:26:50 +00005414 // If we had a comparison against a fractional value, we have to adjust the
5415 // compare predicate and sometimes the value. RHSC is rounded towards zero
5416 // at this point.
Chris Lattner5920a782008-05-19 20:18:56 +00005417 switch (Pred) {
5418 default: assert(0 && "Unexpected integer comparison!");
5419 case ICmpInst::ICMP_NE: // (float)int != 4.4 --> true
5420 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
5421 case ICmpInst::ICMP_EQ: // (float)int == 4.4 --> false
5422 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
Bill Wendling3f547be2008-11-09 04:26:50 +00005423 case ICmpInst::ICMP_ULE:
5424 // (float)int <= 4.4 --> int <= 4
5425 // (float)int <= -4.4 --> false
5426 if (RHS.isNegative())
5427 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
5428 break;
Chris Lattner5920a782008-05-19 20:18:56 +00005429 case ICmpInst::ICMP_SLE:
5430 // (float)int <= 4.4 --> int <= 4
5431 // (float)int <= -4.4 --> int < -4
5432 if (RHS.isNegative())
5433 Pred = ICmpInst::ICMP_SLT;
5434 break;
Bill Wendling3f547be2008-11-09 04:26:50 +00005435 case ICmpInst::ICMP_ULT:
5436 // (float)int < -4.4 --> false
5437 // (float)int < 4.4 --> int <= 4
5438 if (RHS.isNegative())
5439 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
5440 Pred = ICmpInst::ICMP_ULE;
5441 break;
Chris Lattner5920a782008-05-19 20:18:56 +00005442 case ICmpInst::ICMP_SLT:
5443 // (float)int < -4.4 --> int < -4
5444 // (float)int < 4.4 --> int <= 4
5445 if (!RHS.isNegative())
5446 Pred = ICmpInst::ICMP_SLE;
5447 break;
Bill Wendling3f547be2008-11-09 04:26:50 +00005448 case ICmpInst::ICMP_UGT:
5449 // (float)int > 4.4 --> int > 4
5450 // (float)int > -4.4 --> true
5451 if (RHS.isNegative())
5452 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
5453 break;
Chris Lattner5920a782008-05-19 20:18:56 +00005454 case ICmpInst::ICMP_SGT:
5455 // (float)int > 4.4 --> int > 4
5456 // (float)int > -4.4 --> int >= -4
5457 if (RHS.isNegative())
5458 Pred = ICmpInst::ICMP_SGE;
5459 break;
Bill Wendling3f547be2008-11-09 04:26:50 +00005460 case ICmpInst::ICMP_UGE:
5461 // (float)int >= -4.4 --> true
5462 // (float)int >= 4.4 --> int > 4
5463 if (!RHS.isNegative())
5464 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
5465 Pred = ICmpInst::ICMP_UGT;
5466 break;
Chris Lattner5920a782008-05-19 20:18:56 +00005467 case ICmpInst::ICMP_SGE:
5468 // (float)int >= -4.4 --> int >= -4
5469 // (float)int >= 4.4 --> int > 4
5470 if (!RHS.isNegative())
5471 Pred = ICmpInst::ICMP_SGT;
5472 break;
5473 }
5474 }
5475
5476 // Lower this FP comparison into an appropriate integer version of the
5477 // comparison.
5478 return new ICmpInst(Pred, LHSI->getOperand(0), RHSInt);
5479}
5480
Reid Spencer266e42b2006-12-23 06:05:41 +00005481Instruction *InstCombiner::visitFCmpInst(FCmpInst &I) {
5482 bool Changed = SimplifyCompare(I);
Chris Lattner6d14f2a2002-08-09 23:47:40 +00005483 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00005484
Chris Lattner6ee923f2007-01-14 19:42:17 +00005485 // Fold trivial predicates.
5486 if (I.getPredicate() == FCmpInst::FCMP_FALSE)
5487 return ReplaceInstUsesWith(I, Constant::getNullValue(Type::Int1Ty));
5488 if (I.getPredicate() == FCmpInst::FCMP_TRUE)
5489 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
5490
5491 // Simplify 'fcmp pred X, X'
5492 if (Op0 == Op1) {
5493 switch (I.getPredicate()) {
5494 default: assert(0 && "Unknown predicate!");
5495 case FCmpInst::FCMP_UEQ: // True if unordered or equal
5496 case FCmpInst::FCMP_UGE: // True if unordered, greater than, or equal
5497 case FCmpInst::FCMP_ULE: // True if unordered, less than, or equal
5498 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
5499 case FCmpInst::FCMP_OGT: // True if ordered and greater than
5500 case FCmpInst::FCMP_OLT: // True if ordered and less than
5501 case FCmpInst::FCMP_ONE: // True if ordered and operands are unequal
5502 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
5503
5504 case FCmpInst::FCMP_UNO: // True if unordered: isnan(X) | isnan(Y)
5505 case FCmpInst::FCMP_ULT: // True if unordered or less than
5506 case FCmpInst::FCMP_UGT: // True if unordered or greater than
5507 case FCmpInst::FCMP_UNE: // True if unordered or not equal
5508 // Canonicalize these to be 'fcmp uno %X, 0.0'.
5509 I.setPredicate(FCmpInst::FCMP_UNO);
5510 I.setOperand(1, Constant::getNullValue(Op0->getType()));
5511 return &I;
5512
5513 case FCmpInst::FCMP_ORD: // True if ordered (no nans)
5514 case FCmpInst::FCMP_OEQ: // True if ordered and equal
5515 case FCmpInst::FCMP_OGE: // True if ordered and greater than or equal
5516 case FCmpInst::FCMP_OLE: // True if ordered and less than or equal
5517 // Canonicalize these to be 'fcmp ord %X, 0.0'.
5518 I.setPredicate(FCmpInst::FCMP_ORD);
5519 I.setOperand(1, Constant::getNullValue(Op0->getType()));
5520 return &I;
5521 }
5522 }
5523
Reid Spencer266e42b2006-12-23 06:05:41 +00005524 if (isa<UndefValue>(Op1)) // fcmp pred X, undef -> undef
Reid Spencer542964f2007-01-11 18:21:29 +00005525 return ReplaceInstUsesWith(I, UndefValue::get(Type::Int1Ty));
Chris Lattner81a7a232004-10-16 18:11:37 +00005526
Reid Spencer266e42b2006-12-23 06:05:41 +00005527 // Handle fcmp with constant RHS
5528 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
Chris Lattner5920a782008-05-19 20:18:56 +00005529 // If the constant is a nan, see if we can fold the comparison based on it.
5530 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
5531 if (CFP->getValueAPF().isNaN()) {
5532 if (FCmpInst::isOrdered(I.getPredicate())) // True if ordered and...
5533 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
Chris Lattner9c27f962008-05-20 03:50:52 +00005534 assert(FCmpInst::isUnordered(I.getPredicate()) &&
5535 "Comparison must be either ordered or unordered!");
5536 // True if unordered.
5537 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
Chris Lattner5920a782008-05-19 20:18:56 +00005538 }
5539 }
5540
Reid Spencer266e42b2006-12-23 06:05:41 +00005541 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5542 switch (LHSI->getOpcode()) {
5543 case Instruction::PHI:
Chris Lattnerb4866ef2008-06-08 20:52:11 +00005544 // Only fold fcmp into the PHI if the phi and fcmp are in the same
5545 // block. If in the same block, we're encouraging jump threading. If
5546 // not, we are just pessimizing the code by making an i1 phi.
5547 if (LHSI->getParent() == I.getParent())
5548 if (Instruction *NV = FoldOpIntoPhi(I))
5549 return NV;
Reid Spencer266e42b2006-12-23 06:05:41 +00005550 break;
Chris Lattner5920a782008-05-19 20:18:56 +00005551 case Instruction::SIToFP:
5552 case Instruction::UIToFP:
5553 if (Instruction *NV = FoldFCmp_IntToFP_Cst(I, LHSI, RHSC))
5554 return NV;
5555 break;
Reid Spencer266e42b2006-12-23 06:05:41 +00005556 case Instruction::Select:
5557 // If either operand of the select is a constant, we can fold the
5558 // comparison into the select arms, which will cause one to be
5559 // constant folded and the select turned into a bitwise or.
5560 Value *Op1 = 0, *Op2 = 0;
5561 if (LHSI->hasOneUse()) {
5562 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
5563 // Fold the known value into the constant operand.
5564 Op1 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
5565 // Insert a new FCmp of the other select operand.
5566 Op2 = InsertNewInstBefore(new FCmpInst(I.getPredicate(),
5567 LHSI->getOperand(2), RHSC,
5568 I.getName()), I);
5569 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
5570 // Fold the known value into the constant operand.
5571 Op2 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
5572 // Insert a new FCmp of the other select operand.
5573 Op1 = InsertNewInstBefore(new FCmpInst(I.getPredicate(),
5574 LHSI->getOperand(1), RHSC,
5575 I.getName()), I);
5576 }
5577 }
5578
5579 if (Op1)
Gabor Greife9ecc682008-04-06 20:25:17 +00005580 return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
Reid Spencer266e42b2006-12-23 06:05:41 +00005581 break;
5582 }
5583 }
5584
5585 return Changed ? &I : 0;
5586}
5587
5588Instruction *InstCombiner::visitICmpInst(ICmpInst &I) {
5589 bool Changed = SimplifyCompare(I);
5590 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5591 const Type *Ty = Op0->getType();
5592
5593 // icmp X, X
5594 if (Op0 == Op1)
Reid Spencercddc9df2007-01-12 04:24:46 +00005595 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
Nick Lewycky79376f42008-05-17 07:33:39 +00005596 I.isTrueWhenEqual()));
Reid Spencer266e42b2006-12-23 06:05:41 +00005597
5598 if (isa<UndefValue>(Op1)) // X icmp undef -> undef
Reid Spencer542964f2007-01-11 18:21:29 +00005599 return ReplaceInstUsesWith(I, UndefValue::get(Type::Int1Ty));
Christopher Lambf00ac6d2007-12-18 21:32:20 +00005600
Reid Spencer266e42b2006-12-23 06:05:41 +00005601 // icmp <global/alloca*/null>, <global/alloca*/null> - Global/Stack value
Chris Lattner15ff1e12004-11-14 07:33:16 +00005602 // addresses never equal each other! We already know that Op0 != Op1.
Misha Brukmanb1c93172005-04-21 23:48:37 +00005603 if ((isa<GlobalValue>(Op0) || isa<AllocaInst>(Op0) ||
5604 isa<ConstantPointerNull>(Op0)) &&
5605 (isa<GlobalValue>(Op1) || isa<AllocaInst>(Op1) ||
Chris Lattner15ff1e12004-11-14 07:33:16 +00005606 isa<ConstantPointerNull>(Op1)))
Reid Spencercddc9df2007-01-12 04:24:46 +00005607 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
Nick Lewycky79376f42008-05-17 07:33:39 +00005608 !I.isTrueWhenEqual()));
Chris Lattner6d14f2a2002-08-09 23:47:40 +00005609
Reid Spencer266e42b2006-12-23 06:05:41 +00005610 // icmp's with boolean values can always be turned into bitwise operations
Reid Spencer542964f2007-01-11 18:21:29 +00005611 if (Ty == Type::Int1Ty) {
Reid Spencer266e42b2006-12-23 06:05:41 +00005612 switch (I.getPredicate()) {
5613 default: assert(0 && "Invalid icmp instruction!");
Chris Lattner6af608b2008-07-11 04:20:58 +00005614 case ICmpInst::ICMP_EQ: { // icmp eq i1 A, B -> ~(A^B)
Gabor Greife1f6e4b2008-05-16 19:29:10 +00005615 Instruction *Xor = BinaryOperator::CreateXor(Op0, Op1, I.getName()+"tmp");
Chris Lattner6d14f2a2002-08-09 23:47:40 +00005616 InsertNewInstBefore(Xor, I);
Gabor Greife1f6e4b2008-05-16 19:29:10 +00005617 return BinaryOperator::CreateNot(Xor);
Chris Lattner6d14f2a2002-08-09 23:47:40 +00005618 }
Chris Lattner6af608b2008-07-11 04:20:58 +00005619 case ICmpInst::ICMP_NE: // icmp eq i1 A, B -> A^B
Gabor Greife1f6e4b2008-05-16 19:29:10 +00005620 return BinaryOperator::CreateXor(Op0, Op1);
Chris Lattner6d14f2a2002-08-09 23:47:40 +00005621
Reid Spencer266e42b2006-12-23 06:05:41 +00005622 case ICmpInst::ICMP_UGT:
Chris Lattner6af608b2008-07-11 04:20:58 +00005623 std::swap(Op0, Op1); // Change icmp ugt -> icmp ult
Chris Lattner4456da62004-08-11 00:50:51 +00005624 // FALL THROUGH
Chris Lattner6af608b2008-07-11 04:20:58 +00005625 case ICmpInst::ICMP_ULT:{ // icmp ult i1 A, B -> ~A & B
Gabor Greife1f6e4b2008-05-16 19:29:10 +00005626 Instruction *Not = BinaryOperator::CreateNot(Op0, I.getName()+"tmp");
Chris Lattner4456da62004-08-11 00:50:51 +00005627 InsertNewInstBefore(Not, I);
Gabor Greife1f6e4b2008-05-16 19:29:10 +00005628 return BinaryOperator::CreateAnd(Not, Op1);
Chris Lattner4456da62004-08-11 00:50:51 +00005629 }
Chris Lattner6af608b2008-07-11 04:20:58 +00005630 case ICmpInst::ICMP_SGT:
5631 std::swap(Op0, Op1); // Change icmp sgt -> icmp slt
Chris Lattner4456da62004-08-11 00:50:51 +00005632 // FALL THROUGH
Chris Lattner6af608b2008-07-11 04:20:58 +00005633 case ICmpInst::ICMP_SLT: { // icmp slt i1 A, B -> A & ~B
5634 Instruction *Not = BinaryOperator::CreateNot(Op1, I.getName()+"tmp");
5635 InsertNewInstBefore(Not, I);
5636 return BinaryOperator::CreateAnd(Not, Op0);
5637 }
5638 case ICmpInst::ICMP_UGE:
5639 std::swap(Op0, Op1); // Change icmp uge -> icmp ule
5640 // FALL THROUGH
5641 case ICmpInst::ICMP_ULE: { // icmp ule i1 A, B -> ~A | B
Gabor Greife1f6e4b2008-05-16 19:29:10 +00005642 Instruction *Not = BinaryOperator::CreateNot(Op0, I.getName()+"tmp");
Chris Lattner4456da62004-08-11 00:50:51 +00005643 InsertNewInstBefore(Not, I);
Gabor Greife1f6e4b2008-05-16 19:29:10 +00005644 return BinaryOperator::CreateOr(Not, Op1);
Chris Lattner4456da62004-08-11 00:50:51 +00005645 }
Chris Lattner6af608b2008-07-11 04:20:58 +00005646 case ICmpInst::ICMP_SGE:
5647 std::swap(Op0, Op1); // Change icmp sge -> icmp sle
5648 // FALL THROUGH
5649 case ICmpInst::ICMP_SLE: { // icmp sle i1 A, B -> A | ~B
5650 Instruction *Not = BinaryOperator::CreateNot(Op1, I.getName()+"tmp");
5651 InsertNewInstBefore(Not, I);
5652 return BinaryOperator::CreateOr(Not, Op0);
5653 }
Chris Lattner4456da62004-08-11 00:50:51 +00005654 }
Chris Lattner6d14f2a2002-08-09 23:47:40 +00005655 }
5656
Dan Gohmandafa9c62008-09-16 18:46:06 +00005657 // See if we are doing a comparison with a constant.
Chris Lattner6d14f2a2002-08-09 23:47:40 +00005658 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner4fa8bb32008-07-11 04:09:09 +00005659 Value *A, *B;
Christopher Lamb7d82bc42007-12-20 07:21:11 +00005660
Chris Lattnerdb026d72008-01-05 01:18:20 +00005661 // (icmp ne/eq (sub A B) 0) -> (icmp ne/eq A, B)
5662 if (I.isEquality() && CI->isNullValue() &&
5663 match(Op0, m_Sub(m_Value(A), m_Value(B)))) {
5664 // (icmp cond A B) if cond is equality
5665 return new ICmpInst(I.getPredicate(), A, B);
Owen Anderson73639142007-12-28 07:42:12 +00005666 }
Christopher Lamb7d82bc42007-12-20 07:21:11 +00005667
Dan Gohmandafa9c62008-09-16 18:46:06 +00005668 // If we have an icmp le or icmp ge instruction, turn it into the
5669 // appropriate icmp lt or icmp gt instruction. This allows us to rely on
5670 // them being folded in the code below.
Chris Lattner38a50c92008-07-11 05:08:55 +00005671 switch (I.getPredicate()) {
5672 default: break;
5673 case ICmpInst::ICMP_ULE:
5674 if (CI->isMaxValue(false)) // A <=u MAX -> TRUE
5675 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5676 return new ICmpInst(ICmpInst::ICMP_ULT, Op0, AddOne(CI));
5677 case ICmpInst::ICMP_SLE:
5678 if (CI->isMaxValue(true)) // A <=s MAX -> TRUE
5679 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5680 return new ICmpInst(ICmpInst::ICMP_SLT, Op0, AddOne(CI));
5681 case ICmpInst::ICMP_UGE:
5682 if (CI->isMinValue(false)) // A >=u MIN -> TRUE
5683 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5684 return new ICmpInst( ICmpInst::ICMP_UGT, Op0, SubOne(CI));
5685 case ICmpInst::ICMP_SGE:
5686 if (CI->isMinValue(true)) // A >=s MIN -> TRUE
5687 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5688 return new ICmpInst(ICmpInst::ICMP_SGT, Op0, SubOne(CI));
5689 }
5690
Chris Lattnerbd25b852008-07-11 05:40:05 +00005691 // See if we can fold the comparison based on range information we can get
5692 // by checking whether bits are known to be zero or one in the input.
5693 uint32_t BitWidth = cast<IntegerType>(Ty)->getBitWidth();
5694 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
5695
5696 // If this comparison is a normal comparison, it demands all
Chris Lattnerd4fef8d2007-07-15 20:54:51 +00005697 // bits, if it is a sign bit comparison, it only demands the sign bit.
Chris Lattnerd4fef8d2007-07-15 20:54:51 +00005698 bool UnusedBit;
5699 bool isSignBit = isSignBitCheck(I.getPredicate(), CI, UnusedBit);
5700
Chris Lattnerd4fef8d2007-07-15 20:54:51 +00005701 if (SimplifyDemandedBits(Op0,
5702 isSignBit ? APInt::getSignBit(BitWidth)
5703 : APInt::getAllOnesValue(BitWidth),
Chris Lattneree0f2802006-02-12 02:07:56 +00005704 KnownZero, KnownOne, 0))
5705 return &I;
5706
5707 // Given the known and unknown bits, compute a range that the LHS could be
Chris Lattner38a50c92008-07-11 05:08:55 +00005708 // in. Compute the Min, Max and RHS values based on the known bits. For the
5709 // EQ and NE we use unsigned values.
5710 APInt Min(BitWidth, 0), Max(BitWidth, 0);
Chris Lattner38a50c92008-07-11 05:08:55 +00005711 if (ICmpInst::isSignedPredicate(I.getPredicate()))
5712 ComputeSignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne, Min, Max);
5713 else
5714 ComputeUnsignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne,Min,Max);
5715
Chris Lattnerbd25b852008-07-11 05:40:05 +00005716 // If Min and Max are known to be the same, then SimplifyDemandedBits
5717 // figured out that the LHS is a constant. Just constant fold this now so
5718 // that code below can assume that Min != Max.
5719 if (Min == Max)
5720 return ReplaceInstUsesWith(I, ConstantExpr::getICmp(I.getPredicate(),
5721 ConstantInt::get(Min),
5722 CI));
5723
5724 // Based on the range information we know about the LHS, see if we can
5725 // simplify this comparison. For example, (x&4) < 8 is always true.
5726 const APInt &RHSVal = CI->getValue();
Chris Lattner38a50c92008-07-11 05:08:55 +00005727 switch (I.getPredicate()) { // LE/GE have been folded already.
5728 default: assert(0 && "Unknown icmp opcode!");
5729 case ICmpInst::ICMP_EQ:
5730 if (Max.ult(RHSVal) || Min.ugt(RHSVal))
5731 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5732 break;
5733 case ICmpInst::ICMP_NE:
5734 if (Max.ult(RHSVal) || Min.ugt(RHSVal))
5735 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5736 break;
5737 case ICmpInst::ICMP_ULT:
Chris Lattnerbd25b852008-07-11 05:40:05 +00005738 if (Max.ult(RHSVal)) // A <u C -> true iff max(A) < C
Chris Lattner38a50c92008-07-11 05:08:55 +00005739 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Chris Lattnerbd25b852008-07-11 05:40:05 +00005740 if (Min.uge(RHSVal)) // A <u C -> false iff min(A) >= C
Chris Lattner38a50c92008-07-11 05:08:55 +00005741 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Chris Lattnerbd25b852008-07-11 05:40:05 +00005742 if (RHSVal == Max) // A <u MAX -> A != MAX
5743 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
5744 if (RHSVal == Min+1) // A <u MIN+1 -> A == MIN
5745 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, SubOne(CI));
5746
5747 // (x <u 2147483648) -> (x >s -1) -> true if sign bit clear
5748 if (CI->isMinValue(true))
5749 return new ICmpInst(ICmpInst::ICMP_SGT, Op0,
5750 ConstantInt::getAllOnesValue(Op0->getType()));
Chris Lattner38a50c92008-07-11 05:08:55 +00005751 break;
5752 case ICmpInst::ICMP_UGT:
Chris Lattnerbd25b852008-07-11 05:40:05 +00005753 if (Min.ugt(RHSVal)) // A >u C -> true iff min(A) > C
Chris Lattner38a50c92008-07-11 05:08:55 +00005754 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Chris Lattnerbd25b852008-07-11 05:40:05 +00005755 if (Max.ule(RHSVal)) // A >u C -> false iff max(A) <= C
Chris Lattner38a50c92008-07-11 05:08:55 +00005756 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Chris Lattnerbd25b852008-07-11 05:40:05 +00005757
5758 if (RHSVal == Min) // A >u MIN -> A != MIN
5759 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
5760 if (RHSVal == Max-1) // A >u MAX-1 -> A == MAX
5761 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, AddOne(CI));
5762
5763 // (x >u 2147483647) -> (x <s 0) -> true if sign bit set
5764 if (CI->isMaxValue(true))
5765 return new ICmpInst(ICmpInst::ICMP_SLT, Op0,
5766 ConstantInt::getNullValue(Op0->getType()));
Chris Lattner38a50c92008-07-11 05:08:55 +00005767 break;
5768 case ICmpInst::ICMP_SLT:
Chris Lattnerbd25b852008-07-11 05:40:05 +00005769 if (Max.slt(RHSVal)) // A <s C -> true iff max(A) < C
Chris Lattner38a50c92008-07-11 05:08:55 +00005770 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Chris Lattner3994bed2008-07-11 06:40:29 +00005771 if (Min.sge(RHSVal)) // A <s C -> false iff min(A) >= C
Chris Lattner38a50c92008-07-11 05:08:55 +00005772 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Chris Lattnerbd25b852008-07-11 05:40:05 +00005773 if (RHSVal == Max) // A <s MAX -> A != MAX
5774 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
Chris Lattnerde89b502008-07-11 06:36:01 +00005775 if (RHSVal == Min+1) // A <s MIN+1 -> A == MIN
Chris Lattner13a69112008-07-11 06:38:16 +00005776 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, SubOne(CI));
Chris Lattner38a50c92008-07-11 05:08:55 +00005777 break;
5778 case ICmpInst::ICMP_SGT:
Chris Lattnerbd25b852008-07-11 05:40:05 +00005779 if (Min.sgt(RHSVal)) // A >s C -> true iff min(A) > C
Chris Lattner38a50c92008-07-11 05:08:55 +00005780 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Chris Lattnerbd25b852008-07-11 05:40:05 +00005781 if (Max.sle(RHSVal)) // A >s C -> false iff max(A) <= C
Chris Lattner38a50c92008-07-11 05:08:55 +00005782 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Chris Lattnerbd25b852008-07-11 05:40:05 +00005783
5784 if (RHSVal == Min) // A >s MIN -> A != MIN
5785 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
5786 if (RHSVal == Max-1) // A >s MAX-1 -> A == MAX
5787 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, AddOne(CI));
Chris Lattner38a50c92008-07-11 05:08:55 +00005788 break;
Chris Lattneree0f2802006-02-12 02:07:56 +00005789 }
Dan Gohmandafa9c62008-09-16 18:46:06 +00005790 }
5791
5792 // Test if the ICmpInst instruction is used exclusively by a select as
5793 // part of a minimum or maximum operation. If so, refrain from doing
5794 // any other folding. This helps out other analyses which understand
5795 // non-obfuscated minimum and maximum idioms, such as ScalarEvolution
5796 // and CodeGen. And in this case, at least one of the comparison
5797 // operands has at least one user besides the compare (the select),
5798 // which would often largely negate the benefit of folding anyway.
5799 if (I.hasOneUse())
5800 if (SelectInst *SI = dyn_cast<SelectInst>(*I.use_begin()))
5801 if ((SI->getOperand(1) == Op0 && SI->getOperand(2) == Op1) ||
5802 (SI->getOperand(2) == Op0 && SI->getOperand(1) == Op1))
5803 return 0;
5804
5805 // See if we are doing a comparison between a constant and an instruction that
5806 // can be folded into the comparison.
5807 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Reid Spencer266e42b2006-12-23 06:05:41 +00005808 // Since the RHS is a ConstantInt (CI), if the left hand side is an
Reid Spencer7e80b0b2006-10-26 06:15:43 +00005809 // instruction, see if that instruction also has constants so that the
Reid Spencer266e42b2006-12-23 06:05:41 +00005810 // instruction can be folded into the icmp
Chris Lattnere1e10e12004-05-25 06:32:08 +00005811 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
Chris Lattnera74deaf2007-04-03 17:43:25 +00005812 if (Instruction *Res = visitICmpInstWithInstAndIntCst(I, LHSI, CI))
5813 return Res;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00005814 }
5815
Chris Lattnera74deaf2007-04-03 17:43:25 +00005816 // Handle icmp with constant (but not simple integer constant) RHS
Chris Lattner77c32c32005-04-23 15:31:55 +00005817 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
5818 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5819 switch (LHSI->getOpcode()) {
Chris Lattnera816eee2005-05-01 04:42:15 +00005820 case Instruction::GetElementPtr:
5821 if (RHSC->isNullValue()) {
Reid Spencer266e42b2006-12-23 06:05:41 +00005822 // icmp pred GEP (P, int 0, int 0, int 0), null -> icmp pred P, null
Chris Lattnera816eee2005-05-01 04:42:15 +00005823 bool isAllZeros = true;
5824 for (unsigned i = 1, e = LHSI->getNumOperands(); i != e; ++i)
5825 if (!isa<Constant>(LHSI->getOperand(i)) ||
5826 !cast<Constant>(LHSI->getOperand(i))->isNullValue()) {
5827 isAllZeros = false;
5828 break;
5829 }
5830 if (isAllZeros)
Reid Spencer266e42b2006-12-23 06:05:41 +00005831 return new ICmpInst(I.getPredicate(), LHSI->getOperand(0),
Chris Lattnera816eee2005-05-01 04:42:15 +00005832 Constant::getNullValue(LHSI->getOperand(0)->getType()));
5833 }
5834 break;
5835
Chris Lattner77c32c32005-04-23 15:31:55 +00005836 case Instruction::PHI:
Chris Lattnerb4866ef2008-06-08 20:52:11 +00005837 // Only fold icmp into the PHI if the phi and fcmp are in the same
5838 // block. If in the same block, we're encouraging jump threading. If
5839 // not, we are just pessimizing the code by making an i1 phi.
5840 if (LHSI->getParent() == I.getParent())
5841 if (Instruction *NV = FoldOpIntoPhi(I))
5842 return NV;
Chris Lattner77c32c32005-04-23 15:31:55 +00005843 break;
Chris Lattner3dbe65f2007-04-06 18:57:34 +00005844 case Instruction::Select: {
Chris Lattner77c32c32005-04-23 15:31:55 +00005845 // If either operand of the select is a constant, we can fold the
5846 // comparison into the select arms, which will cause one to be
5847 // constant folded and the select turned into a bitwise or.
5848 Value *Op1 = 0, *Op2 = 0;
5849 if (LHSI->hasOneUse()) {
5850 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
5851 // Fold the known value into the constant operand.
Reid Spencer266e42b2006-12-23 06:05:41 +00005852 Op1 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
5853 // Insert a new ICmp of the other select operand.
5854 Op2 = InsertNewInstBefore(new ICmpInst(I.getPredicate(),
5855 LHSI->getOperand(2), RHSC,
5856 I.getName()), I);
Chris Lattner77c32c32005-04-23 15:31:55 +00005857 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
5858 // Fold the known value into the constant operand.
Reid Spencer266e42b2006-12-23 06:05:41 +00005859 Op2 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
5860 // Insert a new ICmp of the other select operand.
5861 Op1 = InsertNewInstBefore(new ICmpInst(I.getPredicate(),
5862 LHSI->getOperand(1), RHSC,
5863 I.getName()), I);
Chris Lattner77c32c32005-04-23 15:31:55 +00005864 }
5865 }
Jeff Cohen82639852005-04-23 21:38:35 +00005866
Chris Lattner77c32c32005-04-23 15:31:55 +00005867 if (Op1)
Gabor Greife9ecc682008-04-06 20:25:17 +00005868 return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
Chris Lattner77c32c32005-04-23 15:31:55 +00005869 break;
5870 }
Chris Lattner3dbe65f2007-04-06 18:57:34 +00005871 case Instruction::Malloc:
5872 // If we have (malloc != null), and if the malloc has a single use, we
5873 // can assume it is successful and remove the malloc.
5874 if (LHSI->hasOneUse() && isa<ConstantPointerNull>(RHSC)) {
5875 AddToWorkList(LHSI);
5876 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
Nick Lewycky79376f42008-05-17 07:33:39 +00005877 !I.isTrueWhenEqual()));
Chris Lattner3dbe65f2007-04-06 18:57:34 +00005878 }
5879 break;
5880 }
Chris Lattner77c32c32005-04-23 15:31:55 +00005881 }
5882
Reid Spencer266e42b2006-12-23 06:05:41 +00005883 // If we can optimize a 'icmp GEP, P' or 'icmp P, GEP', do so now.
Chris Lattner0798af32005-01-13 20:14:25 +00005884 if (User *GEP = dyn_castGetElementPtr(Op0))
Reid Spencer266e42b2006-12-23 06:05:41 +00005885 if (Instruction *NI = FoldGEPICmp(GEP, Op1, I.getPredicate(), I))
Chris Lattner0798af32005-01-13 20:14:25 +00005886 return NI;
5887 if (User *GEP = dyn_castGetElementPtr(Op1))
Reid Spencer266e42b2006-12-23 06:05:41 +00005888 if (Instruction *NI = FoldGEPICmp(GEP, Op0,
5889 ICmpInst::getSwappedPredicate(I.getPredicate()), I))
Chris Lattner0798af32005-01-13 20:14:25 +00005890 return NI;
5891
Reid Spencer266e42b2006-12-23 06:05:41 +00005892 // Test to see if the operands of the icmp are casted versions of other
Chris Lattner64d87b02007-01-06 01:45:59 +00005893 // values. If the ptr->ptr cast can be stripped off both arguments, we do so
5894 // now.
5895 if (BitCastInst *CI = dyn_cast<BitCastInst>(Op0)) {
5896 if (isa<PointerType>(Op0->getType()) &&
5897 (isa<Constant>(Op1) || isa<BitCastInst>(Op1))) {
Chris Lattner16930792003-11-03 04:25:02 +00005898 // We keep moving the cast from the left operand over to the right
5899 // operand, where it can often be eliminated completely.
Chris Lattner64d87b02007-01-06 01:45:59 +00005900 Op0 = CI->getOperand(0);
Misha Brukmanb1c93172005-04-21 23:48:37 +00005901
Chris Lattner64d87b02007-01-06 01:45:59 +00005902 // If operand #1 is a bitcast instruction, it must also be a ptr->ptr cast
5903 // so eliminate it as well.
5904 if (BitCastInst *CI2 = dyn_cast<BitCastInst>(Op1))
5905 Op1 = CI2->getOperand(0);
Misha Brukmanb1c93172005-04-21 23:48:37 +00005906
Chris Lattner16930792003-11-03 04:25:02 +00005907 // If Op1 is a constant, we can fold the cast into the constant.
Anton Korobeynikov1bfd1212008-02-20 11:26:25 +00005908 if (Op0->getType() != Op1->getType()) {
Chris Lattner16930792003-11-03 04:25:02 +00005909 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
Reid Spencerbb65ebf2006-12-12 23:36:14 +00005910 Op1 = ConstantExpr::getBitCast(Op1C, Op0->getType());
Chris Lattner16930792003-11-03 04:25:02 +00005911 } else {
Reid Spencer266e42b2006-12-23 06:05:41 +00005912 // Otherwise, cast the RHS right before the icmp
Chris Lattner5a866122008-01-13 22:23:22 +00005913 Op1 = InsertBitCastBefore(Op1, Op0->getType(), I);
Chris Lattner16930792003-11-03 04:25:02 +00005914 }
Anton Korobeynikov1bfd1212008-02-20 11:26:25 +00005915 }
Reid Spencer266e42b2006-12-23 06:05:41 +00005916 return new ICmpInst(I.getPredicate(), Op0, Op1);
Chris Lattner16930792003-11-03 04:25:02 +00005917 }
Chris Lattner64d87b02007-01-06 01:45:59 +00005918 }
5919
5920 if (isa<CastInst>(Op0)) {
Reid Spencer266e42b2006-12-23 06:05:41 +00005921 // Handle the special case of: icmp (cast bool to X), <cst>
Chris Lattner6444c372003-11-03 05:17:03 +00005922 // This comes up when you have code like
5923 // int X = A < B;
5924 // if (X) ...
5925 // For generality, we handle any zero-extension of any operand comparison
Chris Lattnerd1f46d32005-04-24 06:59:08 +00005926 // with a constant or another cast from the same type.
5927 if (isa<ConstantInt>(Op1) || isa<CastInst>(Op1))
Reid Spencer266e42b2006-12-23 06:05:41 +00005928 if (Instruction *R = visitICmpInstWithCastAndCast(I))
Chris Lattnerd1f46d32005-04-24 06:59:08 +00005929 return R;
Chris Lattner6444c372003-11-03 05:17:03 +00005930 }
Chris Lattnerf5c8a0b2006-02-27 01:44:11 +00005931
Nick Lewyckyf95b64a2008-07-11 07:20:53 +00005932 // See if it's the same type of instruction on the left and right.
5933 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
5934 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
Nick Lewycky99f45582008-08-21 05:56:10 +00005935 if (Op0I->getOpcode() == Op1I->getOpcode() && Op0I->hasOneUse() &&
5936 Op1I->hasOneUse() && Op0I->getOperand(1) == Op1I->getOperand(1) &&
5937 I.isEquality()) {
Nick Lewycky2fcb26c2008-09-03 06:24:21 +00005938 switch (Op0I->getOpcode()) {
Nick Lewyckyf95b64a2008-07-11 07:20:53 +00005939 default: break;
5940 case Instruction::Add:
5941 case Instruction::Sub:
5942 case Instruction::Xor:
Nick Lewycky99f45582008-08-21 05:56:10 +00005943 // a+x icmp eq/ne b+x --> a icmp b
5944 return new ICmpInst(I.getPredicate(), Op0I->getOperand(0),
5945 Op1I->getOperand(0));
Nick Lewyckyf95b64a2008-07-11 07:20:53 +00005946 break;
5947 case Instruction::Mul:
Nick Lewycky99f45582008-08-21 05:56:10 +00005948 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
5949 // a * Cst icmp eq/ne b * Cst --> a & Mask icmp b & Mask
5950 // Mask = -1 >> count-trailing-zeros(Cst).
5951 if (!CI->isZero() && !CI->isOne()) {
5952 const APInt &AP = CI->getValue();
5953 ConstantInt *Mask = ConstantInt::get(
5954 APInt::getLowBitsSet(AP.getBitWidth(),
5955 AP.getBitWidth() -
Nick Lewyckyf95b64a2008-07-11 07:20:53 +00005956 AP.countTrailingZeros()));
Nick Lewycky99f45582008-08-21 05:56:10 +00005957 Instruction *And1 = BinaryOperator::CreateAnd(Op0I->getOperand(0),
5958 Mask);
5959 Instruction *And2 = BinaryOperator::CreateAnd(Op1I->getOperand(0),
5960 Mask);
5961 InsertNewInstBefore(And1, I);
5962 InsertNewInstBefore(And2, I);
5963 return new ICmpInst(I.getPredicate(), And1, And2);
Nick Lewyckyf95b64a2008-07-11 07:20:53 +00005964 }
5965 }
5966 break;
5967 }
5968 }
5969 }
5970 }
5971
Chris Lattneraaba10e2008-05-09 05:19:28 +00005972 // ~x < ~y --> y < x
5973 { Value *A, *B;
5974 if (match(Op0, m_Not(m_Value(A))) &&
5975 match(Op1, m_Not(m_Value(B))))
5976 return new ICmpInst(I.getPredicate(), B, A);
5977 }
5978
Chris Lattnerb3f24c92006-09-18 04:22:48 +00005979 if (I.isEquality()) {
Chris Lattner17c7c032007-01-05 03:04:57 +00005980 Value *A, *B, *C, *D;
Chris Lattneraaba10e2008-05-09 05:19:28 +00005981
5982 // -x == -y --> x == y
5983 if (match(Op0, m_Neg(m_Value(A))) &&
5984 match(Op1, m_Neg(m_Value(B))))
5985 return new ICmpInst(I.getPredicate(), A, B);
5986
Chris Lattner17c7c032007-01-05 03:04:57 +00005987 if (match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
5988 if (A == Op1 || B == Op1) { // (A^B) == A -> B == 0
5989 Value *OtherVal = A == Op1 ? B : A;
5990 return new ICmpInst(I.getPredicate(), OtherVal,
5991 Constant::getNullValue(A->getType()));
5992 }
5993
5994 if (match(Op1, m_Xor(m_Value(C), m_Value(D)))) {
5995 // A^c1 == C^c2 --> A == C^(c1^c2)
5996 if (ConstantInt *C1 = dyn_cast<ConstantInt>(B))
5997 if (ConstantInt *C2 = dyn_cast<ConstantInt>(D))
5998 if (Op1->hasOneUse()) {
Zhou Sheng9bc8ab12007-04-02 13:45:30 +00005999 Constant *NC = ConstantInt::get(C1->getValue() ^ C2->getValue());
Gabor Greife1f6e4b2008-05-16 19:29:10 +00006000 Instruction *Xor = BinaryOperator::CreateXor(C, NC, "tmp");
Chris Lattner17c7c032007-01-05 03:04:57 +00006001 return new ICmpInst(I.getPredicate(), A,
6002 InsertNewInstBefore(Xor, I));
6003 }
6004
6005 // A^B == A^D -> B == D
6006 if (A == C) return new ICmpInst(I.getPredicate(), B, D);
6007 if (A == D) return new ICmpInst(I.getPredicate(), B, C);
6008 if (B == C) return new ICmpInst(I.getPredicate(), A, D);
6009 if (B == D) return new ICmpInst(I.getPredicate(), A, C);
6010 }
6011 }
6012
6013 if (match(Op1, m_Xor(m_Value(A), m_Value(B))) &&
6014 (A == Op0 || B == Op0)) {
Chris Lattnerf5c8a0b2006-02-27 01:44:11 +00006015 // A == (A^B) -> B == 0
6016 Value *OtherVal = A == Op0 ? B : A;
Reid Spencer266e42b2006-12-23 06:05:41 +00006017 return new ICmpInst(I.getPredicate(), OtherVal,
6018 Constant::getNullValue(A->getType()));
Chris Lattner17c7c032007-01-05 03:04:57 +00006019 }
6020 if (match(Op0, m_Sub(m_Value(A), m_Value(B))) && A == Op1) {
Chris Lattnerf5c8a0b2006-02-27 01:44:11 +00006021 // (A-B) == A -> B == 0
Reid Spencer266e42b2006-12-23 06:05:41 +00006022 return new ICmpInst(I.getPredicate(), B,
6023 Constant::getNullValue(B->getType()));
Chris Lattner17c7c032007-01-05 03:04:57 +00006024 }
6025 if (match(Op1, m_Sub(m_Value(A), m_Value(B))) && A == Op0) {
Chris Lattnerf5c8a0b2006-02-27 01:44:11 +00006026 // A == (A-B) -> B == 0
Reid Spencer266e42b2006-12-23 06:05:41 +00006027 return new ICmpInst(I.getPredicate(), B,
6028 Constant::getNullValue(B->getType()));
Chris Lattnerf5c8a0b2006-02-27 01:44:11 +00006029 }
Chris Lattnerd12a4bf2006-11-14 06:06:06 +00006030
Chris Lattnerd12a4bf2006-11-14 06:06:06 +00006031 // (X&Z) == (Y&Z) -> (X^Y) & Z == 0
6032 if (Op0->hasOneUse() && Op1->hasOneUse() &&
6033 match(Op0, m_And(m_Value(A), m_Value(B))) &&
6034 match(Op1, m_And(m_Value(C), m_Value(D)))) {
6035 Value *X = 0, *Y = 0, *Z = 0;
6036
6037 if (A == C) {
6038 X = B; Y = D; Z = A;
6039 } else if (A == D) {
6040 X = B; Y = C; Z = A;
6041 } else if (B == C) {
6042 X = A; Y = D; Z = B;
6043 } else if (B == D) {
6044 X = A; Y = C; Z = B;
6045 }
6046
6047 if (X) { // Build (X^Y) & Z
Gabor Greife1f6e4b2008-05-16 19:29:10 +00006048 Op1 = InsertNewInstBefore(BinaryOperator::CreateXor(X, Y, "tmp"), I);
6049 Op1 = InsertNewInstBefore(BinaryOperator::CreateAnd(Op1, Z, "tmp"), I);
Chris Lattnerd12a4bf2006-11-14 06:06:06 +00006050 I.setOperand(0, Op1);
6051 I.setOperand(1, Constant::getNullValue(Op1->getType()));
6052 return &I;
6053 }
6054 }
Chris Lattnerf5c8a0b2006-02-27 01:44:11 +00006055 }
Chris Lattner113f4f42002-06-25 16:13:24 +00006056 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00006057}
6058
Chris Lattner3bbec592007-06-20 23:46:26 +00006059
6060/// FoldICmpDivCst - Fold "icmp pred, ([su]div X, DivRHS), CmpRHS" where DivRHS
6061/// and CmpRHS are both known to be integer constants.
6062Instruction *InstCombiner::FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
6063 ConstantInt *DivRHS) {
6064 ConstantInt *CmpRHS = cast<ConstantInt>(ICI.getOperand(1));
6065 const APInt &CmpRHSV = CmpRHS->getValue();
6066
6067 // FIXME: If the operand types don't match the type of the divide
6068 // then don't attempt this transform. The code below doesn't have the
6069 // logic to deal with a signed divide and an unsigned compare (and
6070 // vice versa). This is because (x /s C1) <s C2 produces different
6071 // results than (x /s C1) <u C2 or (x /u C1) <s C2 or even
6072 // (x /u C1) <u C2. Simply casting the operands and result won't
6073 // work. :( The if statement below tests that condition and bails
6074 // if it finds it.
6075 bool DivIsSigned = DivI->getOpcode() == Instruction::SDiv;
6076 if (!ICI.isEquality() && DivIsSigned != ICI.isSignedPredicate())
6077 return 0;
6078 if (DivRHS->isZero())
Chris Lattnerfb032b12007-06-21 18:11:19 +00006079 return 0; // The ProdOV computation fails on divide by zero.
Chris Lattnerda435912008-10-11 22:55:00 +00006080 if (DivIsSigned && DivRHS->isAllOnesValue())
6081 return 0; // The overflow computation also screws up here
6082 if (DivRHS->isOne())
6083 return 0; // Not worth bothering, and eliminates some funny cases
6084 // with INT_MIN.
Chris Lattner3bbec592007-06-20 23:46:26 +00006085
6086 // Compute Prod = CI * DivRHS. We are essentially solving an equation
6087 // of form X/C1=C2. We solve for X by multiplying C1 (DivRHS) and
6088 // C2 (CI). By solving for X we can turn this into a range check
6089 // instead of computing a divide.
6090 ConstantInt *Prod = Multiply(CmpRHS, DivRHS);
6091
6092 // Determine if the product overflows by seeing if the product is
6093 // not equal to the divide. Make sure we do the same kind of divide
6094 // as in the LHS instruction that we're folding.
6095 bool ProdOV = (DivIsSigned ? ConstantExpr::getSDiv(Prod, DivRHS) :
6096 ConstantExpr::getUDiv(Prod, DivRHS)) != CmpRHS;
6097
6098 // Get the ICmp opcode
Chris Lattnerfb032b12007-06-21 18:11:19 +00006099 ICmpInst::Predicate Pred = ICI.getPredicate();
Chris Lattner3bbec592007-06-20 23:46:26 +00006100
Chris Lattnerfb032b12007-06-21 18:11:19 +00006101 // Figure out the interval that is being checked. For example, a comparison
6102 // like "X /u 5 == 0" is really checking that X is in the interval [0, 5).
6103 // Compute this interval based on the constants involved and the signedness of
6104 // the compare/divide. This computes a half-open interval, keeping track of
6105 // whether either value in the interval overflows. After analysis each
6106 // overflow variable is set to 0 if it's corresponding bound variable is valid
6107 // -1 if overflowed off the bottom end, or +1 if overflowed off the top end.
6108 int LoOverflow = 0, HiOverflow = 0;
6109 ConstantInt *LoBound = 0, *HiBound = 0;
6110
Chris Lattner3bbec592007-06-20 23:46:26 +00006111 if (!DivIsSigned) { // udiv
Chris Lattnerfb032b12007-06-21 18:11:19 +00006112 // e.g. X/5 op 3 --> [15, 20)
Chris Lattner3bbec592007-06-20 23:46:26 +00006113 LoBound = Prod;
Chris Lattnerfb032b12007-06-21 18:11:19 +00006114 HiOverflow = LoOverflow = ProdOV;
6115 if (!HiOverflow)
6116 HiOverflow = AddWithOverflow(HiBound, LoBound, DivRHS, false);
Dan Gohman1ee8dc92008-02-13 22:09:18 +00006117 } else if (DivRHS->getValue().isStrictlyPositive()) { // Divisor is > 0.
Chris Lattner3bbec592007-06-20 23:46:26 +00006118 if (CmpRHSV == 0) { // (X / pos) op 0
Chris Lattnerfb032b12007-06-21 18:11:19 +00006119 // Can't overflow. e.g. X/2 op 0 --> [-1, 2)
Chris Lattner3bbec592007-06-20 23:46:26 +00006120 LoBound = cast<ConstantInt>(ConstantExpr::getNeg(SubOne(DivRHS)));
6121 HiBound = DivRHS;
Dan Gohman1ee8dc92008-02-13 22:09:18 +00006122 } else if (CmpRHSV.isStrictlyPositive()) { // (X / pos) op pos
Chris Lattnerfb032b12007-06-21 18:11:19 +00006123 LoBound = Prod; // e.g. X/5 op 3 --> [15, 20)
6124 HiOverflow = LoOverflow = ProdOV;
6125 if (!HiOverflow)
6126 HiOverflow = AddWithOverflow(HiBound, Prod, DivRHS, true);
Chris Lattner3bbec592007-06-20 23:46:26 +00006127 } else { // (X / pos) op neg
Chris Lattnerfb032b12007-06-21 18:11:19 +00006128 // e.g. X/5 op -3 --> [-15-4, -15+1) --> [-19, -14)
Chris Lattner3bbec592007-06-20 23:46:26 +00006129 HiBound = AddOne(Prod);
Chris Lattnerda435912008-10-11 22:55:00 +00006130 LoOverflow = HiOverflow = ProdOV ? -1 : 0;
6131 if (!LoOverflow) {
6132 ConstantInt* DivNeg = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
6133 LoOverflow = AddWithOverflow(LoBound, HiBound, DivNeg,
6134 true) ? -1 : 0;
6135 }
Chris Lattner3bbec592007-06-20 23:46:26 +00006136 }
Dan Gohman1ee8dc92008-02-13 22:09:18 +00006137 } else if (DivRHS->getValue().isNegative()) { // Divisor is < 0.
Chris Lattner3bbec592007-06-20 23:46:26 +00006138 if (CmpRHSV == 0) { // (X / neg) op 0
Chris Lattnerfb032b12007-06-21 18:11:19 +00006139 // e.g. X/-5 op 0 --> [-4, 5)
Chris Lattner3bbec592007-06-20 23:46:26 +00006140 LoBound = AddOne(DivRHS);
6141 HiBound = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
Chris Lattnerfb032b12007-06-21 18:11:19 +00006142 if (HiBound == DivRHS) { // -INTMIN = INTMIN
6143 HiOverflow = 1; // [INTMIN+1, overflow)
6144 HiBound = 0; // e.g. X/INTMIN = 0 --> X > INTMIN
6145 }
Dan Gohman1ee8dc92008-02-13 22:09:18 +00006146 } else if (CmpRHSV.isStrictlyPositive()) { // (X / neg) op pos
Chris Lattnerfb032b12007-06-21 18:11:19 +00006147 // e.g. X/-5 op 3 --> [-19, -14)
Chris Lattnerda435912008-10-11 22:55:00 +00006148 HiBound = AddOne(Prod);
Chris Lattnerfb032b12007-06-21 18:11:19 +00006149 HiOverflow = LoOverflow = ProdOV ? -1 : 0;
Chris Lattner3bbec592007-06-20 23:46:26 +00006150 if (!LoOverflow)
Chris Lattnerda435912008-10-11 22:55:00 +00006151 LoOverflow = AddWithOverflow(LoBound, HiBound, DivRHS, true) ? -1 : 0;
Chris Lattner3bbec592007-06-20 23:46:26 +00006152 } else { // (X / neg) op neg
Chris Lattnerda435912008-10-11 22:55:00 +00006153 LoBound = Prod; // e.g. X/-5 op -3 --> [15, 20)
6154 LoOverflow = HiOverflow = ProdOV;
Dan Gohman9d9a4be2008-09-11 00:25:00 +00006155 if (!HiOverflow)
6156 HiOverflow = SubWithOverflow(HiBound, Prod, DivRHS, true);
Chris Lattner3bbec592007-06-20 23:46:26 +00006157 }
6158
Chris Lattnerfb032b12007-06-21 18:11:19 +00006159 // Dividing by a negative swaps the condition. LT <-> GT
6160 Pred = ICmpInst::getSwappedPredicate(Pred);
Chris Lattner3bbec592007-06-20 23:46:26 +00006161 }
6162
6163 Value *X = DivI->getOperand(0);
Chris Lattnerfb032b12007-06-21 18:11:19 +00006164 switch (Pred) {
Chris Lattner3bbec592007-06-20 23:46:26 +00006165 default: assert(0 && "Unhandled icmp opcode!");
6166 case ICmpInst::ICMP_EQ:
6167 if (LoOverflow && HiOverflow)
6168 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
6169 else if (HiOverflow)
Chris Lattnerfb032b12007-06-21 18:11:19 +00006170 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
Chris Lattner3bbec592007-06-20 23:46:26 +00006171 ICmpInst::ICMP_UGE, X, LoBound);
6172 else if (LoOverflow)
6173 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
6174 ICmpInst::ICMP_ULT, X, HiBound);
6175 else
Chris Lattnerfb032b12007-06-21 18:11:19 +00006176 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, true, ICI);
Chris Lattner3bbec592007-06-20 23:46:26 +00006177 case ICmpInst::ICMP_NE:
6178 if (LoOverflow && HiOverflow)
6179 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
6180 else if (HiOverflow)
Chris Lattnerfb032b12007-06-21 18:11:19 +00006181 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
Chris Lattner3bbec592007-06-20 23:46:26 +00006182 ICmpInst::ICMP_ULT, X, LoBound);
6183 else if (LoOverflow)
6184 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
6185 ICmpInst::ICMP_UGE, X, HiBound);
6186 else
Chris Lattnerfb032b12007-06-21 18:11:19 +00006187 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, false, ICI);
Chris Lattner3bbec592007-06-20 23:46:26 +00006188 case ICmpInst::ICMP_ULT:
6189 case ICmpInst::ICMP_SLT:
Chris Lattnerfb032b12007-06-21 18:11:19 +00006190 if (LoOverflow == +1) // Low bound is greater than input range.
6191 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
6192 if (LoOverflow == -1) // Low bound is less than input range.
Chris Lattner3bbec592007-06-20 23:46:26 +00006193 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
Chris Lattnerfb032b12007-06-21 18:11:19 +00006194 return new ICmpInst(Pred, X, LoBound);
Chris Lattner3bbec592007-06-20 23:46:26 +00006195 case ICmpInst::ICMP_UGT:
6196 case ICmpInst::ICMP_SGT:
Chris Lattnerfb032b12007-06-21 18:11:19 +00006197 if (HiOverflow == +1) // High bound greater than input range.
Chris Lattner3bbec592007-06-20 23:46:26 +00006198 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
Chris Lattnerfb032b12007-06-21 18:11:19 +00006199 else if (HiOverflow == -1) // High bound less than input range.
6200 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
6201 if (Pred == ICmpInst::ICMP_UGT)
Chris Lattner3bbec592007-06-20 23:46:26 +00006202 return new ICmpInst(ICmpInst::ICMP_UGE, X, HiBound);
6203 else
6204 return new ICmpInst(ICmpInst::ICMP_SGE, X, HiBound);
6205 }
6206}
6207
6208
Chris Lattnera74deaf2007-04-03 17:43:25 +00006209/// visitICmpInstWithInstAndIntCst - Handle "icmp (instr, intcst)".
6210///
6211Instruction *InstCombiner::visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
6212 Instruction *LHSI,
6213 ConstantInt *RHS) {
6214 const APInt &RHSV = RHS->getValue();
6215
6216 switch (LHSI->getOpcode()) {
Duncan Sandsf01a47c2007-04-04 06:42:45 +00006217 case Instruction::Xor: // (icmp pred (xor X, XorCST), CI)
Chris Lattnera74deaf2007-04-03 17:43:25 +00006218 if (ConstantInt *XorCST = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
6219 // If this is a comparison that tests the signbit (X < 0) or (x > -1),
6220 // fold the xor.
Anton Korobeynikov1bfd1212008-02-20 11:26:25 +00006221 if ((ICI.getPredicate() == ICmpInst::ICMP_SLT && RHSV == 0) ||
6222 (ICI.getPredicate() == ICmpInst::ICMP_SGT && RHSV.isAllOnesValue())) {
Chris Lattnera74deaf2007-04-03 17:43:25 +00006223 Value *CompareVal = LHSI->getOperand(0);
6224
6225 // If the sign bit of the XorCST is not set, there is no change to
6226 // the operation, just stop using the Xor.
6227 if (!XorCST->getValue().isNegative()) {
6228 ICI.setOperand(0, CompareVal);
6229 AddToWorkList(LHSI);
6230 return &ICI;
6231 }
6232
6233 // Was the old condition true if the operand is positive?
6234 bool isTrueIfPositive = ICI.getPredicate() == ICmpInst::ICMP_SGT;
6235
6236 // If so, the new one isn't.
6237 isTrueIfPositive ^= true;
6238
6239 if (isTrueIfPositive)
6240 return new ICmpInst(ICmpInst::ICMP_SGT, CompareVal, SubOne(RHS));
6241 else
6242 return new ICmpInst(ICmpInst::ICMP_SLT, CompareVal, AddOne(RHS));
6243 }
6244 }
6245 break;
6246 case Instruction::And: // (icmp pred (and X, AndCST), RHS)
6247 if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
6248 LHSI->getOperand(0)->hasOneUse()) {
6249 ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
6250
6251 // If the LHS is an AND of a truncating cast, we can widen the
6252 // and/compare to be the input width without changing the value
6253 // produced, eliminating a cast.
6254 if (TruncInst *Cast = dyn_cast<TruncInst>(LHSI->getOperand(0))) {
6255 // We can do this transformation if either the AND constant does not
6256 // have its sign bit set or if it is an equality comparison.
6257 // Extending a relational comparison when we're checking the sign
6258 // bit would not work.
6259 if (Cast->hasOneUse() &&
Anton Korobeynikov18991d72008-02-20 12:07:57 +00006260 (ICI.isEquality() ||
6261 (AndCST->getValue().isNonNegative() && RHSV.isNonNegative()))) {
Chris Lattnera74deaf2007-04-03 17:43:25 +00006262 uint32_t BitWidth =
6263 cast<IntegerType>(Cast->getOperand(0)->getType())->getBitWidth();
6264 APInt NewCST = AndCST->getValue();
6265 NewCST.zext(BitWidth);
6266 APInt NewCI = RHSV;
6267 NewCI.zext(BitWidth);
6268 Instruction *NewAnd =
Gabor Greife1f6e4b2008-05-16 19:29:10 +00006269 BinaryOperator::CreateAnd(Cast->getOperand(0),
Chris Lattnera74deaf2007-04-03 17:43:25 +00006270 ConstantInt::get(NewCST),LHSI->getName());
6271 InsertNewInstBefore(NewAnd, ICI);
6272 return new ICmpInst(ICI.getPredicate(), NewAnd,
6273 ConstantInt::get(NewCI));
6274 }
6275 }
6276
6277 // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
6278 // could exist), turn it into (X & (C2 << C1)) != (C3 << C1). This
6279 // happens a LOT in code produced by the C front-end, for bitfield
6280 // access.
6281 BinaryOperator *Shift = dyn_cast<BinaryOperator>(LHSI->getOperand(0));
6282 if (Shift && !Shift->isShift())
6283 Shift = 0;
6284
6285 ConstantInt *ShAmt;
6286 ShAmt = Shift ? dyn_cast<ConstantInt>(Shift->getOperand(1)) : 0;
6287 const Type *Ty = Shift ? Shift->getType() : 0; // Type of the shift.
6288 const Type *AndTy = AndCST->getType(); // Type of the and.
6289
6290 // We can fold this as long as we can't shift unknown bits
6291 // into the mask. This can only happen with signed shift
6292 // rights, as they sign-extend.
6293 if (ShAmt) {
6294 bool CanFold = Shift->isLogicalShift();
6295 if (!CanFold) {
6296 // To test for the bad case of the signed shr, see if any
6297 // of the bits shifted in could be tested after the mask.
6298 uint32_t TyBits = Ty->getPrimitiveSizeInBits();
6299 int ShAmtVal = TyBits - ShAmt->getLimitedValue(TyBits);
6300
6301 uint32_t BitWidth = AndTy->getPrimitiveSizeInBits();
6302 if ((APInt::getHighBitsSet(BitWidth, BitWidth-ShAmtVal) &
6303 AndCST->getValue()) == 0)
6304 CanFold = true;
6305 }
6306
6307 if (CanFold) {
6308 Constant *NewCst;
6309 if (Shift->getOpcode() == Instruction::Shl)
6310 NewCst = ConstantExpr::getLShr(RHS, ShAmt);
6311 else
6312 NewCst = ConstantExpr::getShl(RHS, ShAmt);
6313
6314 // Check to see if we are shifting out any of the bits being
6315 // compared.
6316 if (ConstantExpr::get(Shift->getOpcode(), NewCst, ShAmt) != RHS) {
6317 // If we shifted bits out, the fold is not going to work out.
6318 // As a special case, check to see if this means that the
6319 // result is always true or false now.
6320 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
6321 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
6322 if (ICI.getPredicate() == ICmpInst::ICMP_NE)
6323 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
6324 } else {
6325 ICI.setOperand(1, NewCst);
6326 Constant *NewAndCST;
6327 if (Shift->getOpcode() == Instruction::Shl)
6328 NewAndCST = ConstantExpr::getLShr(AndCST, ShAmt);
6329 else
6330 NewAndCST = ConstantExpr::getShl(AndCST, ShAmt);
6331 LHSI->setOperand(1, NewAndCST);
6332 LHSI->setOperand(0, Shift->getOperand(0));
6333 AddToWorkList(Shift); // Shift is dead.
6334 AddUsesToWorkList(ICI);
6335 return &ICI;
6336 }
6337 }
6338 }
6339
6340 // Turn ((X >> Y) & C) == 0 into (X & (C << Y)) == 0. The later is
6341 // preferable because it allows the C<<Y expression to be hoisted out
6342 // of a loop if Y is invariant and X is not.
6343 if (Shift && Shift->hasOneUse() && RHSV == 0 &&
6344 ICI.isEquality() && !Shift->isArithmeticShift() &&
6345 isa<Instruction>(Shift->getOperand(0))) {
6346 // Compute C << Y.
6347 Value *NS;
6348 if (Shift->getOpcode() == Instruction::LShr) {
Gabor Greife1f6e4b2008-05-16 19:29:10 +00006349 NS = BinaryOperator::CreateShl(AndCST,
Chris Lattnera74deaf2007-04-03 17:43:25 +00006350 Shift->getOperand(1), "tmp");
6351 } else {
6352 // Insert a logical shift.
Gabor Greife1f6e4b2008-05-16 19:29:10 +00006353 NS = BinaryOperator::CreateLShr(AndCST,
Chris Lattnera74deaf2007-04-03 17:43:25 +00006354 Shift->getOperand(1), "tmp");
6355 }
6356 InsertNewInstBefore(cast<Instruction>(NS), ICI);
6357
6358 // Compute X & (C << Y).
6359 Instruction *NewAnd =
Gabor Greife1f6e4b2008-05-16 19:29:10 +00006360 BinaryOperator::CreateAnd(Shift->getOperand(0), NS, LHSI->getName());
Chris Lattnera74deaf2007-04-03 17:43:25 +00006361 InsertNewInstBefore(NewAnd, ICI);
6362
6363 ICI.setOperand(0, NewAnd);
6364 return &ICI;
6365 }
6366 }
6367 break;
6368
Chris Lattner06205d52007-07-15 20:42:37 +00006369 case Instruction::Shl: { // (icmp pred (shl X, ShAmt), CI)
6370 ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
6371 if (!ShAmt) break;
6372
6373 uint32_t TypeBits = RHSV.getBitWidth();
6374
6375 // Check that the shift amount is in range. If not, don't perform
6376 // undefined shifts. When the shift is visited it will be
6377 // simplified.
6378 if (ShAmt->uge(TypeBits))
6379 break;
6380
6381 if (ICI.isEquality()) {
6382 // If we are comparing against bits always shifted out, the
6383 // comparison cannot succeed.
6384 Constant *Comp =
6385 ConstantExpr::getShl(ConstantExpr::getLShr(RHS, ShAmt), ShAmt);
6386 if (Comp != RHS) {// Comparing against a bit that we know is zero.
6387 bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
6388 Constant *Cst = ConstantInt::get(Type::Int1Ty, IsICMP_NE);
6389 return ReplaceInstUsesWith(ICI, Cst);
6390 }
6391
6392 if (LHSI->hasOneUse()) {
6393 // Otherwise strength reduce the shift into an and.
6394 uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
6395 Constant *Mask =
6396 ConstantInt::get(APInt::getLowBitsSet(TypeBits, TypeBits-ShAmtVal));
Chris Lattnera74deaf2007-04-03 17:43:25 +00006397
Chris Lattner06205d52007-07-15 20:42:37 +00006398 Instruction *AndI =
Gabor Greife1f6e4b2008-05-16 19:29:10 +00006399 BinaryOperator::CreateAnd(LHSI->getOperand(0),
Chris Lattner06205d52007-07-15 20:42:37 +00006400 Mask, LHSI->getName()+".mask");
6401 Value *And = InsertNewInstBefore(AndI, ICI);
6402 return new ICmpInst(ICI.getPredicate(), And,
6403 ConstantInt::get(RHSV.lshr(ShAmtVal)));
Chris Lattnera74deaf2007-04-03 17:43:25 +00006404 }
6405 }
Chris Lattner06205d52007-07-15 20:42:37 +00006406
6407 // Otherwise, if this is a comparison of the sign bit, simplify to and/test.
6408 bool TrueIfSigned = false;
6409 if (LHSI->hasOneUse() &&
6410 isSignBitCheck(ICI.getPredicate(), RHS, TrueIfSigned)) {
6411 // (X << 31) <s 0 --> (X&1) != 0
6412 Constant *Mask = ConstantInt::get(APInt(TypeBits, 1) <<
6413 (TypeBits-ShAmt->getZExtValue()-1));
6414 Instruction *AndI =
Gabor Greife1f6e4b2008-05-16 19:29:10 +00006415 BinaryOperator::CreateAnd(LHSI->getOperand(0),
Chris Lattner06205d52007-07-15 20:42:37 +00006416 Mask, LHSI->getName()+".mask");
6417 Value *And = InsertNewInstBefore(AndI, ICI);
6418
6419 return new ICmpInst(TrueIfSigned ? ICmpInst::ICMP_NE : ICmpInst::ICMP_EQ,
6420 And, Constant::getNullValue(And->getType()));
6421 }
Chris Lattnera74deaf2007-04-03 17:43:25 +00006422 break;
Chris Lattner06205d52007-07-15 20:42:37 +00006423 }
Chris Lattnera74deaf2007-04-03 17:43:25 +00006424
6425 case Instruction::LShr: // (icmp pred (shr X, ShAmt), CI)
Chris Lattner06205d52007-07-15 20:42:37 +00006426 case Instruction::AShr: {
Chris Lattnerc44160c2008-03-21 05:19:58 +00006427 // Only handle equality comparisons of shift-by-constant.
Chris Lattner06205d52007-07-15 20:42:37 +00006428 ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
Chris Lattnerc44160c2008-03-21 05:19:58 +00006429 if (!ShAmt || !ICI.isEquality()) break;
Chris Lattner06205d52007-07-15 20:42:37 +00006430
Chris Lattnerc44160c2008-03-21 05:19:58 +00006431 // Check that the shift amount is in range. If not, don't perform
6432 // undefined shifts. When the shift is visited it will be
6433 // simplified.
6434 uint32_t TypeBits = RHSV.getBitWidth();
6435 if (ShAmt->uge(TypeBits))
6436 break;
6437
6438 uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
Chris Lattner06205d52007-07-15 20:42:37 +00006439
Chris Lattnerc44160c2008-03-21 05:19:58 +00006440 // If we are comparing against bits always shifted out, the
6441 // comparison cannot succeed.
6442 APInt Comp = RHSV << ShAmtVal;
6443 if (LHSI->getOpcode() == Instruction::LShr)
6444 Comp = Comp.lshr(ShAmtVal);
6445 else
6446 Comp = Comp.ashr(ShAmtVal);
6447
6448 if (Comp != RHSV) { // Comparing against a bit that we know is zero.
6449 bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
6450 Constant *Cst = ConstantInt::get(Type::Int1Ty, IsICMP_NE);
6451 return ReplaceInstUsesWith(ICI, Cst);
6452 }
6453
6454 // Otherwise, check to see if the bits shifted out are known to be zero.
6455 // If so, we can compare against the unshifted value:
6456 // (X & 4) >> 1 == 2 --> (X & 4) == 4.
Evan Cheng1c89ca72008-04-23 00:38:06 +00006457 if (LHSI->hasOneUse() &&
6458 MaskedValueIsZero(LHSI->getOperand(0),
Chris Lattnerc44160c2008-03-21 05:19:58 +00006459 APInt::getLowBitsSet(Comp.getBitWidth(), ShAmtVal))) {
6460 return new ICmpInst(ICI.getPredicate(), LHSI->getOperand(0),
6461 ConstantExpr::getShl(RHS, ShAmt));
6462 }
Chris Lattner06205d52007-07-15 20:42:37 +00006463
Evan Cheng1c89ca72008-04-23 00:38:06 +00006464 if (LHSI->hasOneUse()) {
Chris Lattnerc44160c2008-03-21 05:19:58 +00006465 // Otherwise strength reduce the shift into an and.
6466 APInt Val(APInt::getHighBitsSet(TypeBits, TypeBits - ShAmtVal));
6467 Constant *Mask = ConstantInt::get(Val);
Chris Lattner06205d52007-07-15 20:42:37 +00006468
Chris Lattnerc44160c2008-03-21 05:19:58 +00006469 Instruction *AndI =
Gabor Greife1f6e4b2008-05-16 19:29:10 +00006470 BinaryOperator::CreateAnd(LHSI->getOperand(0),
Chris Lattnerc44160c2008-03-21 05:19:58 +00006471 Mask, LHSI->getName()+".mask");
6472 Value *And = InsertNewInstBefore(AndI, ICI);
6473 return new ICmpInst(ICI.getPredicate(), And,
6474 ConstantExpr::getShl(RHS, ShAmt));
Chris Lattnera74deaf2007-04-03 17:43:25 +00006475 }
6476 break;
Chris Lattner06205d52007-07-15 20:42:37 +00006477 }
Chris Lattnera74deaf2007-04-03 17:43:25 +00006478
6479 case Instruction::SDiv:
6480 case Instruction::UDiv:
6481 // Fold: icmp pred ([us]div X, C1), C2 -> range test
6482 // Fold this div into the comparison, producing a range check.
6483 // Determine, based on the divide type, what the range is being
6484 // checked. If there is an overflow on the low or high side, remember
6485 // it, otherwise compute the range [low, hi) bounding the new value.
6486 // See: InsertRangeTest above for the kinds of replacements possible.
Chris Lattner3bbec592007-06-20 23:46:26 +00006487 if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1)))
6488 if (Instruction *R = FoldICmpDivCst(ICI, cast<BinaryOperator>(LHSI),
6489 DivRHS))
6490 return R;
Chris Lattnera74deaf2007-04-03 17:43:25 +00006491 break;
Nick Lewycky3b592142008-02-03 16:33:09 +00006492
6493 case Instruction::Add:
6494 // Fold: icmp pred (add, X, C1), C2
6495
6496 if (!ICI.isEquality()) {
6497 ConstantInt *LHSC = dyn_cast<ConstantInt>(LHSI->getOperand(1));
6498 if (!LHSC) break;
6499 const APInt &LHSV = LHSC->getValue();
6500
6501 ConstantRange CR = ICI.makeConstantRange(ICI.getPredicate(), RHSV)
6502 .subtract(LHSV);
6503
6504 if (ICI.isSignedPredicate()) {
6505 if (CR.getLower().isSignBit()) {
6506 return new ICmpInst(ICmpInst::ICMP_SLT, LHSI->getOperand(0),
6507 ConstantInt::get(CR.getUpper()));
6508 } else if (CR.getUpper().isSignBit()) {
6509 return new ICmpInst(ICmpInst::ICMP_SGE, LHSI->getOperand(0),
6510 ConstantInt::get(CR.getLower()));
6511 }
6512 } else {
6513 if (CR.getLower().isMinValue()) {
6514 return new ICmpInst(ICmpInst::ICMP_ULT, LHSI->getOperand(0),
6515 ConstantInt::get(CR.getUpper()));
6516 } else if (CR.getUpper().isMinValue()) {
6517 return new ICmpInst(ICmpInst::ICMP_UGE, LHSI->getOperand(0),
6518 ConstantInt::get(CR.getLower()));
6519 }
6520 }
6521 }
6522 break;
Chris Lattnera74deaf2007-04-03 17:43:25 +00006523 }
6524
6525 // Simplify icmp_eq and icmp_ne instructions with integer constant RHS.
6526 if (ICI.isEquality()) {
6527 bool isICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
6528
6529 // If the first operand is (add|sub|and|or|xor|rem) with a constant, and
6530 // the second operand is a constant, simplify a bit.
6531 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(LHSI)) {
6532 switch (BO->getOpcode()) {
6533 case Instruction::SRem:
6534 // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
6535 if (RHSV == 0 && isa<ConstantInt>(BO->getOperand(1)) &&BO->hasOneUse()){
6536 const APInt &V = cast<ConstantInt>(BO->getOperand(1))->getValue();
6537 if (V.sgt(APInt(V.getBitWidth(), 1)) && V.isPowerOf2()) {
6538 Instruction *NewRem =
Gabor Greife1f6e4b2008-05-16 19:29:10 +00006539 BinaryOperator::CreateURem(BO->getOperand(0), BO->getOperand(1),
Chris Lattnera74deaf2007-04-03 17:43:25 +00006540 BO->getName());
6541 InsertNewInstBefore(NewRem, ICI);
6542 return new ICmpInst(ICI.getPredicate(), NewRem,
6543 Constant::getNullValue(BO->getType()));
6544 }
6545 }
6546 break;
6547 case Instruction::Add:
6548 // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
6549 if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
6550 if (BO->hasOneUse())
6551 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
6552 Subtract(RHS, BOp1C));
6553 } else if (RHSV == 0) {
6554 // Replace ((add A, B) != 0) with (A != -B) if A or B is
6555 // efficiently invertible, or if the add has just this one use.
6556 Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
6557
6558 if (Value *NegVal = dyn_castNegVal(BOp1))
6559 return new ICmpInst(ICI.getPredicate(), BOp0, NegVal);
6560 else if (Value *NegVal = dyn_castNegVal(BOp0))
6561 return new ICmpInst(ICI.getPredicate(), NegVal, BOp1);
6562 else if (BO->hasOneUse()) {
Gabor Greife1f6e4b2008-05-16 19:29:10 +00006563 Instruction *Neg = BinaryOperator::CreateNeg(BOp1);
Chris Lattnera74deaf2007-04-03 17:43:25 +00006564 InsertNewInstBefore(Neg, ICI);
6565 Neg->takeName(BO);
6566 return new ICmpInst(ICI.getPredicate(), BOp0, Neg);
6567 }
6568 }
6569 break;
6570 case Instruction::Xor:
6571 // For the xor case, we can xor two constants together, eliminating
6572 // the explicit xor.
6573 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
6574 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
6575 ConstantExpr::getXor(RHS, BOC));
6576
6577 // FALLTHROUGH
6578 case Instruction::Sub:
6579 // Replace (([sub|xor] A, B) != 0) with (A != B)
6580 if (RHSV == 0)
6581 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
6582 BO->getOperand(1));
6583 break;
6584
6585 case Instruction::Or:
6586 // If bits are being or'd in that are not present in the constant we
6587 // are comparing against, then the comparison could never succeed!
6588 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
6589 Constant *NotCI = ConstantExpr::getNot(RHS);
6590 if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
6591 return ReplaceInstUsesWith(ICI, ConstantInt::get(Type::Int1Ty,
6592 isICMP_NE));
6593 }
6594 break;
6595
6596 case Instruction::And:
6597 if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
6598 // If bits are being compared against that are and'd out, then the
6599 // comparison can never succeed!
6600 if ((RHSV & ~BOC->getValue()) != 0)
6601 return ReplaceInstUsesWith(ICI, ConstantInt::get(Type::Int1Ty,
6602 isICMP_NE));
6603
6604 // If we have ((X & C) == C), turn it into ((X & C) != 0).
6605 if (RHS == BOC && RHSV.isPowerOf2())
6606 return new ICmpInst(isICMP_NE ? ICmpInst::ICMP_EQ :
6607 ICmpInst::ICMP_NE, LHSI,
6608 Constant::getNullValue(RHS->getType()));
6609
6610 // Replace (and X, (1 << size(X)-1) != 0) with x s< 0
Chris Lattnera12a6de2008-06-02 01:29:46 +00006611 if (BOC->getValue().isSignBit()) {
Chris Lattnera74deaf2007-04-03 17:43:25 +00006612 Value *X = BO->getOperand(0);
6613 Constant *Zero = Constant::getNullValue(X->getType());
6614 ICmpInst::Predicate pred = isICMP_NE ?
6615 ICmpInst::ICMP_SLT : ICmpInst::ICMP_SGE;
6616 return new ICmpInst(pred, X, Zero);
6617 }
6618
6619 // ((X & ~7) == 0) --> X < 8
6620 if (RHSV == 0 && isHighOnes(BOC)) {
6621 Value *X = BO->getOperand(0);
6622 Constant *NegX = ConstantExpr::getNeg(BOC);
6623 ICmpInst::Predicate pred = isICMP_NE ?
6624 ICmpInst::ICMP_UGE : ICmpInst::ICMP_ULT;
6625 return new ICmpInst(pred, X, NegX);
6626 }
6627 }
6628 default: break;
6629 }
6630 } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(LHSI)) {
6631 // Handle icmp {eq|ne} <intrinsic>, intcst.
6632 if (II->getIntrinsicID() == Intrinsic::bswap) {
6633 AddToWorkList(II);
6634 ICI.setOperand(0, II->getOperand(1));
6635 ICI.setOperand(1, ConstantInt::get(RHSV.byteSwap()));
6636 return &ICI;
6637 }
6638 }
6639 } else { // Not a ICMP_EQ/ICMP_NE
Chris Lattner28d921d2007-04-14 23:32:02 +00006640 // If the LHS is a cast from an integral value of the same size,
6641 // then since we know the RHS is a constant, try to simlify.
Chris Lattnera74deaf2007-04-03 17:43:25 +00006642 if (CastInst *Cast = dyn_cast<CastInst>(LHSI)) {
6643 Value *CastOp = Cast->getOperand(0);
6644 const Type *SrcTy = CastOp->getType();
6645 uint32_t SrcTySize = SrcTy->getPrimitiveSizeInBits();
6646 if (SrcTy->isInteger() &&
6647 SrcTySize == Cast->getType()->getPrimitiveSizeInBits()) {
6648 // If this is an unsigned comparison, try to make the comparison use
6649 // smaller constant values.
6650 if (ICI.getPredicate() == ICmpInst::ICMP_ULT && RHSV.isSignBit()) {
6651 // X u< 128 => X s> -1
6652 return new ICmpInst(ICmpInst::ICMP_SGT, CastOp,
6653 ConstantInt::get(APInt::getAllOnesValue(SrcTySize)));
6654 } else if (ICI.getPredicate() == ICmpInst::ICMP_UGT &&
6655 RHSV == APInt::getSignedMaxValue(SrcTySize)) {
6656 // X u> 127 => X s< 0
6657 return new ICmpInst(ICmpInst::ICMP_SLT, CastOp,
6658 Constant::getNullValue(SrcTy));
6659 }
6660 }
6661 }
6662 }
6663 return 0;
6664}
6665
6666/// visitICmpInstWithCastAndCast - Handle icmp (cast x to y), (cast/cst).
6667/// We only handle extending casts so far.
6668///
Reid Spencer266e42b2006-12-23 06:05:41 +00006669Instruction *InstCombiner::visitICmpInstWithCastAndCast(ICmpInst &ICI) {
6670 const CastInst *LHSCI = cast<CastInst>(ICI.getOperand(0));
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006671 Value *LHSCIOp = LHSCI->getOperand(0);
6672 const Type *SrcTy = LHSCIOp->getType();
Reid Spencer266e42b2006-12-23 06:05:41 +00006673 const Type *DestTy = LHSCI->getType();
Chris Lattnerd1f46d32005-04-24 06:59:08 +00006674 Value *RHSCIOp;
6675
Chris Lattner5aa73fe2007-05-05 22:41:33 +00006676 // Turn icmp (ptrtoint x), (ptrtoint/c) into a compare of the input if the
6677 // integer type is the same size as the pointer type.
6678 if (LHSCI->getOpcode() == Instruction::PtrToInt &&
6679 getTargetData().getPointerSizeInBits() ==
6680 cast<IntegerType>(DestTy)->getBitWidth()) {
6681 Value *RHSOp = 0;
6682 if (Constant *RHSC = dyn_cast<Constant>(ICI.getOperand(1))) {
Chris Lattner9b35b3e2007-05-06 07:24:03 +00006683 RHSOp = ConstantExpr::getIntToPtr(RHSC, SrcTy);
Chris Lattner5aa73fe2007-05-05 22:41:33 +00006684 } else if (PtrToIntInst *RHSC = dyn_cast<PtrToIntInst>(ICI.getOperand(1))) {
6685 RHSOp = RHSC->getOperand(0);
6686 // If the pointer types don't match, insert a bitcast.
6687 if (LHSCIOp->getType() != RHSOp->getType())
Chris Lattner5a866122008-01-13 22:23:22 +00006688 RHSOp = InsertBitCastBefore(RHSOp, LHSCIOp->getType(), ICI);
Chris Lattner5aa73fe2007-05-05 22:41:33 +00006689 }
6690
6691 if (RHSOp)
6692 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSOp);
6693 }
6694
6695 // The code below only handles extension cast instructions, so far.
6696 // Enforce this.
Reid Spencer266e42b2006-12-23 06:05:41 +00006697 if (LHSCI->getOpcode() != Instruction::ZExt &&
6698 LHSCI->getOpcode() != Instruction::SExt)
Chris Lattner03f06f12005-01-17 03:20:02 +00006699 return 0;
6700
Reid Spencer266e42b2006-12-23 06:05:41 +00006701 bool isSignedExt = LHSCI->getOpcode() == Instruction::SExt;
6702 bool isSignedCmp = ICI.isSignedPredicate();
Chris Lattnerd1f46d32005-04-24 06:59:08 +00006703
Reid Spencer266e42b2006-12-23 06:05:41 +00006704 if (CastInst *CI = dyn_cast<CastInst>(ICI.getOperand(1))) {
Chris Lattnerd1f46d32005-04-24 06:59:08 +00006705 // Not an extension from the same type?
6706 RHSCIOp = CI->getOperand(0);
Reid Spencer266e42b2006-12-23 06:05:41 +00006707 if (RHSCIOp->getType() != LHSCIOp->getType())
6708 return 0;
Chris Lattner387bf3f2007-01-13 23:11:38 +00006709
Nick Lewycky8ea81e82008-01-28 03:48:02 +00006710 // If the signedness of the two casts doesn't agree (i.e. one is a sext
Chris Lattner387bf3f2007-01-13 23:11:38 +00006711 // and the other is a zext), then we can't handle this.
6712 if (CI->getOpcode() != LHSCI->getOpcode())
6713 return 0;
6714
Nick Lewycky8ea81e82008-01-28 03:48:02 +00006715 // Deal with equality cases early.
6716 if (ICI.isEquality())
6717 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
6718
6719 // A signed comparison of sign extended values simplifies into a
6720 // signed comparison.
6721 if (isSignedCmp && isSignedExt)
6722 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
6723
6724 // The other three cases all fold into an unsigned comparison.
6725 return new ICmpInst(ICI.getUnsignedPredicate(), LHSCIOp, RHSCIOp);
Reid Spencer279fa252004-11-28 21:31:15 +00006726 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00006727
Reid Spencer266e42b2006-12-23 06:05:41 +00006728 // If we aren't dealing with a constant on the RHS, exit early
6729 ConstantInt *CI = dyn_cast<ConstantInt>(ICI.getOperand(1));
6730 if (!CI)
6731 return 0;
6732
6733 // Compute the constant that would happen if we truncated to SrcTy then
6734 // reextended to DestTy.
6735 Constant *Res1 = ConstantExpr::getTrunc(CI, SrcTy);
6736 Constant *Res2 = ConstantExpr::getCast(LHSCI->getOpcode(), Res1, DestTy);
6737
6738 // If the re-extended constant didn't change...
6739 if (Res2 == CI) {
6740 // Make sure that sign of the Cmp and the sign of the Cast are the same.
6741 // For example, we might have:
6742 // %A = sext short %X to uint
6743 // %B = icmp ugt uint %A, 1330
6744 // It is incorrect to transform this into
6745 // %B = icmp ugt short %X, 1330
6746 // because %A may have negative value.
6747 //
Chris Lattner4fa8bb32008-07-11 04:09:09 +00006748 // However, we allow this when the compare is EQ/NE, because they are
6749 // signless.
6750 if (isSignedExt == isSignedCmp || ICI.isEquality())
Reid Spencer266e42b2006-12-23 06:05:41 +00006751 return new ICmpInst(ICI.getPredicate(), LHSCIOp, Res1);
Chris Lattner4fa8bb32008-07-11 04:09:09 +00006752 return 0;
Reid Spencer266e42b2006-12-23 06:05:41 +00006753 }
6754
6755 // The re-extended constant changed so the constant cannot be represented
6756 // in the shorter type. Consequently, we cannot emit a simple comparison.
6757
6758 // First, handle some easy cases. We know the result cannot be equal at this
6759 // point so handle the ICI.isEquality() cases
6760 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
Zhou Sheng75b871f2007-01-11 12:24:14 +00006761 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
Reid Spencer266e42b2006-12-23 06:05:41 +00006762 if (ICI.getPredicate() == ICmpInst::ICMP_NE)
Zhou Sheng75b871f2007-01-11 12:24:14 +00006763 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
Reid Spencer266e42b2006-12-23 06:05:41 +00006764
6765 // Evaluate the comparison for LT (we invert for GT below). LE and GE cases
6766 // should have been folded away previously and not enter in here.
6767 Value *Result;
6768 if (isSignedCmp) {
6769 // We're performing a signed comparison.
Reid Spencerc3e3b8a2007-03-22 20:36:03 +00006770 if (cast<ConstantInt>(CI)->getValue().isNegative())
Zhou Sheng75b871f2007-01-11 12:24:14 +00006771 Result = ConstantInt::getFalse(); // X < (small) --> false
Reid Spencer266e42b2006-12-23 06:05:41 +00006772 else
Zhou Sheng75b871f2007-01-11 12:24:14 +00006773 Result = ConstantInt::getTrue(); // X < (large) --> true
Reid Spencer266e42b2006-12-23 06:05:41 +00006774 } else {
6775 // We're performing an unsigned comparison.
6776 if (isSignedExt) {
6777 // We're performing an unsigned comp with a sign extended value.
6778 // This is true if the input is >= 0. [aka >s -1]
Zhou Sheng75b871f2007-01-11 12:24:14 +00006779 Constant *NegOne = ConstantInt::getAllOnesValue(SrcTy);
Reid Spencer266e42b2006-12-23 06:05:41 +00006780 Result = InsertNewInstBefore(new ICmpInst(ICmpInst::ICMP_SGT, LHSCIOp,
6781 NegOne, ICI.getName()), ICI);
6782 } else {
6783 // Unsigned extend & unsigned compare -> always true.
Zhou Sheng75b871f2007-01-11 12:24:14 +00006784 Result = ConstantInt::getTrue();
Reid Spencer266e42b2006-12-23 06:05:41 +00006785 }
6786 }
6787
6788 // Finally, return the value computed.
6789 if (ICI.getPredicate() == ICmpInst::ICMP_ULT ||
Chris Lattner4fa8bb32008-07-11 04:09:09 +00006790 ICI.getPredicate() == ICmpInst::ICMP_SLT)
Reid Spencer266e42b2006-12-23 06:05:41 +00006791 return ReplaceInstUsesWith(ICI, Result);
Chris Lattner4fa8bb32008-07-11 04:09:09 +00006792
6793 assert((ICI.getPredicate()==ICmpInst::ICMP_UGT ||
6794 ICI.getPredicate()==ICmpInst::ICMP_SGT) &&
6795 "ICmp should be folded!");
6796 if (Constant *CI = dyn_cast<Constant>(Result))
6797 return ReplaceInstUsesWith(ICI, ConstantExpr::getNot(CI));
6798 return BinaryOperator::CreateNot(Result);
Chris Lattnerd1f46d32005-04-24 06:59:08 +00006799}
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00006800
Reid Spencer2341c222007-02-02 02:16:23 +00006801Instruction *InstCombiner::visitShl(BinaryOperator &I) {
6802 return commonShiftTransforms(I);
6803}
6804
6805Instruction *InstCombiner::visitLShr(BinaryOperator &I) {
6806 return commonShiftTransforms(I);
6807}
6808
6809Instruction *InstCombiner::visitAShr(BinaryOperator &I) {
Chris Lattner0ccb6632007-12-06 01:59:46 +00006810 if (Instruction *R = commonShiftTransforms(I))
6811 return R;
6812
6813 Value *Op0 = I.getOperand(0);
6814
6815 // ashr int -1, X = -1 (for any arithmetic shift rights of ~0)
6816 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
6817 if (CSI->isAllOnesValue())
6818 return ReplaceInstUsesWith(I, CSI);
6819
6820 // See if we can turn a signed shr into an unsigned shr.
Nate Begemanfecbc8c2008-07-29 15:49:41 +00006821 if (!isa<VectorType>(I.getType()) &&
6822 MaskedValueIsZero(Op0,
Chris Lattner0ccb6632007-12-06 01:59:46 +00006823 APInt::getSignBit(I.getType()->getPrimitiveSizeInBits())))
Gabor Greife1f6e4b2008-05-16 19:29:10 +00006824 return BinaryOperator::CreateLShr(Op0, I.getOperand(1));
Chris Lattner0ccb6632007-12-06 01:59:46 +00006825
6826 return 0;
Reid Spencer2341c222007-02-02 02:16:23 +00006827}
6828
6829Instruction *InstCombiner::commonShiftTransforms(BinaryOperator &I) {
6830 assert(I.getOperand(1)->getType() == I.getOperand(0)->getType());
Chris Lattner113f4f42002-06-25 16:13:24 +00006831 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00006832
6833 // shl X, 0 == X and shr X, 0 == X
6834 // shl 0, X == 0 and shr 0, X == 0
Reid Spencer2341c222007-02-02 02:16:23 +00006835 if (Op1 == Constant::getNullValue(Op1->getType()) ||
Chris Lattnere6794492002-08-12 21:17:25 +00006836 Op0 == Constant::getNullValue(Op0->getType()))
6837 return ReplaceInstUsesWith(I, Op0);
Chris Lattnerf5b4ef72006-02-12 08:07:37 +00006838
Reid Spencer266e42b2006-12-23 06:05:41 +00006839 if (isa<UndefValue>(Op0)) {
6840 if (I.getOpcode() == Instruction::AShr) // undef >>s X -> undef
Chris Lattner67f05452004-10-16 23:28:04 +00006841 return ReplaceInstUsesWith(I, Op0);
Reid Spencer266e42b2006-12-23 06:05:41 +00006842 else // undef << X -> 0, undef >>u X -> 0
Chris Lattner81a7a232004-10-16 18:11:37 +00006843 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
6844 }
6845 if (isa<UndefValue>(Op1)) {
Reid Spencer266e42b2006-12-23 06:05:41 +00006846 if (I.getOpcode() == Instruction::AShr) // X >>s undef -> X
6847 return ReplaceInstUsesWith(I, Op0);
6848 else // X << undef, X >>u undef -> 0
Chris Lattner81a7a232004-10-16 18:11:37 +00006849 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner81a7a232004-10-16 18:11:37 +00006850 }
6851
Chris Lattner183b3362004-04-09 19:05:30 +00006852 // Try to fold constant and into select arguments.
6853 if (isa<Constant>(Op0))
6854 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner86102b82005-01-01 16:22:27 +00006855 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00006856 return R;
6857
Reid Spencere0fc4df2006-10-20 07:07:24 +00006858 if (ConstantInt *CUI = dyn_cast<ConstantInt>(Op1))
Reid Spencerc635f472006-12-31 05:48:39 +00006859 if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
6860 return Res;
Chris Lattner14553932006-01-06 07:12:35 +00006861 return 0;
6862}
6863
Reid Spencere0fc4df2006-10-20 07:07:24 +00006864Instruction *InstCombiner::FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
Reid Spencer2341c222007-02-02 02:16:23 +00006865 BinaryOperator &I) {
Reid Spencer266e42b2006-12-23 06:05:41 +00006866 bool isLeftShift = I.getOpcode() == Instruction::Shl;
Chris Lattner14553932006-01-06 07:12:35 +00006867
Chris Lattnerf5b4ef72006-02-12 08:07:37 +00006868 // See if we can simplify any instructions used by the instruction whose sole
6869 // purpose is to compute bits we don't care about.
Reid Spencer6274c722007-03-23 18:46:34 +00006870 uint32_t TypeBits = Op0->getType()->getPrimitiveSizeInBits();
6871 APInt KnownZero(TypeBits, 0), KnownOne(TypeBits, 0);
6872 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(TypeBits),
Chris Lattnerf5b4ef72006-02-12 08:07:37 +00006873 KnownZero, KnownOne))
6874 return &I;
6875
Chris Lattner14553932006-01-06 07:12:35 +00006876 // shl uint X, 32 = 0 and shr ubyte Y, 9 = 0, ... just don't eliminate shr
6877 // of a signed value.
6878 //
Zhou Shengb25806f2007-03-30 09:29:48 +00006879 if (Op1->uge(TypeBits)) {
Chris Lattnerd5fea612007-02-02 05:29:55 +00006880 if (I.getOpcode() != Instruction::AShr)
Chris Lattner14553932006-01-06 07:12:35 +00006881 return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
6882 else {
Chris Lattnerd5fea612007-02-02 05:29:55 +00006883 I.setOperand(1, ConstantInt::get(I.getType(), TypeBits-1));
Chris Lattner14553932006-01-06 07:12:35 +00006884 return &I;
Chris Lattnerf5ce2542004-02-23 20:30:06 +00006885 }
Chris Lattner14553932006-01-06 07:12:35 +00006886 }
6887
6888 // ((X*C1) << C2) == (X * (C1 << C2))
6889 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
6890 if (BO->getOpcode() == Instruction::Mul && isLeftShift)
6891 if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
Gabor Greife1f6e4b2008-05-16 19:29:10 +00006892 return BinaryOperator::CreateMul(BO->getOperand(0),
Chris Lattner14553932006-01-06 07:12:35 +00006893 ConstantExpr::getShl(BOOp, Op1));
6894
6895 // Try to fold constant and into select arguments.
6896 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
6897 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
6898 return R;
6899 if (isa<PHINode>(Op0))
6900 if (Instruction *NV = FoldOpIntoPhi(I))
6901 return NV;
6902
Chris Lattner74b2ab52007-12-22 09:07:47 +00006903 // Fold shift2(trunc(shift1(x,c1)), c2) -> trunc(shift2(shift1(x,c1),c2))
6904 if (TruncInst *TI = dyn_cast<TruncInst>(Op0)) {
6905 Instruction *TrOp = dyn_cast<Instruction>(TI->getOperand(0));
6906 // If 'shift2' is an ashr, we would have to get the sign bit into a funny
6907 // place. Don't try to do this transformation in this case. Also, we
6908 // require that the input operand is a shift-by-constant so that we have
6909 // confidence that the shifts will get folded together. We could do this
6910 // xform in more cases, but it is unlikely to be profitable.
6911 if (TrOp && I.isLogicalShift() && TrOp->isShift() &&
6912 isa<ConstantInt>(TrOp->getOperand(1))) {
6913 // Okay, we'll do this xform. Make the shift of shift.
6914 Constant *ShAmt = ConstantExpr::getZExt(Op1, TrOp->getType());
Gabor Greife1f6e4b2008-05-16 19:29:10 +00006915 Instruction *NSh = BinaryOperator::Create(I.getOpcode(), TrOp, ShAmt,
Chris Lattner74b2ab52007-12-22 09:07:47 +00006916 I.getName());
6917 InsertNewInstBefore(NSh, I); // (shift2 (shift1 & 0x00FF), c2)
6918
6919 // For logical shifts, the truncation has the effect of making the high
6920 // part of the register be zeros. Emulate this by inserting an AND to
6921 // clear the top bits as needed. This 'and' will usually be zapped by
6922 // other xforms later if dead.
6923 unsigned SrcSize = TrOp->getType()->getPrimitiveSizeInBits();
6924 unsigned DstSize = TI->getType()->getPrimitiveSizeInBits();
6925 APInt MaskV(APInt::getLowBitsSet(SrcSize, DstSize));
6926
6927 // The mask we constructed says what the trunc would do if occurring
6928 // between the shifts. We want to know the effect *after* the second
6929 // shift. We know that it is a logical shift by a constant, so adjust the
6930 // mask as appropriate.
6931 if (I.getOpcode() == Instruction::Shl)
6932 MaskV <<= Op1->getZExtValue();
6933 else {
6934 assert(I.getOpcode() == Instruction::LShr && "Unknown logical shift");
6935 MaskV = MaskV.lshr(Op1->getZExtValue());
6936 }
6937
Gabor Greife1f6e4b2008-05-16 19:29:10 +00006938 Instruction *And = BinaryOperator::CreateAnd(NSh, ConstantInt::get(MaskV),
Chris Lattner74b2ab52007-12-22 09:07:47 +00006939 TI->getName());
6940 InsertNewInstBefore(And, I); // shift1 & 0x00FF
6941
6942 // Return the value truncated to the interesting size.
6943 return new TruncInst(And, I.getType());
6944 }
6945 }
6946
Chris Lattner14553932006-01-06 07:12:35 +00006947 if (Op0->hasOneUse()) {
Chris Lattner14553932006-01-06 07:12:35 +00006948 if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
6949 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
6950 Value *V1, *V2;
6951 ConstantInt *CC;
6952 switch (Op0BO->getOpcode()) {
Chris Lattner27cb9db2005-09-18 05:12:10 +00006953 default: break;
6954 case Instruction::Add:
6955 case Instruction::And:
6956 case Instruction::Or:
Reid Spencer2f34b982007-02-02 14:41:37 +00006957 case Instruction::Xor: {
Chris Lattner27cb9db2005-09-18 05:12:10 +00006958 // These operators commute.
6959 // Turn (Y + (X >> C)) << C -> (X + (Y << C)) & (~0 << C)
Chris Lattner797dee72005-09-18 06:30:59 +00006960 if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
6961 match(Op0BO->getOperand(1),
Chris Lattner14553932006-01-06 07:12:35 +00006962 m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
Gabor Greife1f6e4b2008-05-16 19:29:10 +00006963 Instruction *YS = BinaryOperator::CreateShl(
Chris Lattner14553932006-01-06 07:12:35 +00006964 Op0BO->getOperand(0), Op1,
Chris Lattner797dee72005-09-18 06:30:59 +00006965 Op0BO->getName());
6966 InsertNewInstBefore(YS, I); // (Y << C)
Chris Lattner24cd2fa2006-02-09 07:41:14 +00006967 Instruction *X =
Gabor Greife1f6e4b2008-05-16 19:29:10 +00006968 BinaryOperator::Create(Op0BO->getOpcode(), YS, V1,
Chris Lattner24cd2fa2006-02-09 07:41:14 +00006969 Op0BO->getOperand(1)->getName());
Chris Lattner797dee72005-09-18 06:30:59 +00006970 InsertNewInstBefore(X, I); // (X + (Y << C))
Zhou Shengfd28a332007-03-30 17:20:39 +00006971 uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
Gabor Greife1f6e4b2008-05-16 19:29:10 +00006972 return BinaryOperator::CreateAnd(X, ConstantInt::get(
Zhou Sheng5e60a4a2007-03-30 05:45:18 +00006973 APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
Chris Lattner797dee72005-09-18 06:30:59 +00006974 }
Chris Lattner14553932006-01-06 07:12:35 +00006975
Chris Lattner797dee72005-09-18 06:30:59 +00006976 // Turn (Y + ((X >> C) & CC)) << C -> ((X & (CC << C)) + (Y << C))
Reid Spencer2f34b982007-02-02 14:41:37 +00006977 Value *Op0BOOp1 = Op0BO->getOperand(1);
Chris Lattnerfe53cf22007-03-05 00:11:19 +00006978 if (isLeftShift && Op0BOOp1->hasOneUse() &&
Reid Spencer2f34b982007-02-02 14:41:37 +00006979 match(Op0BOOp1,
6980 m_And(m_Shr(m_Value(V1), m_Value(V2)),m_ConstantInt(CC))) &&
Chris Lattnerfe53cf22007-03-05 00:11:19 +00006981 cast<BinaryOperator>(Op0BOOp1)->getOperand(0)->hasOneUse() &&
6982 V2 == Op1) {
Gabor Greife1f6e4b2008-05-16 19:29:10 +00006983 Instruction *YS = BinaryOperator::CreateShl(
Reid Spencer2341c222007-02-02 02:16:23 +00006984 Op0BO->getOperand(0), Op1,
6985 Op0BO->getName());
Chris Lattner797dee72005-09-18 06:30:59 +00006986 InsertNewInstBefore(YS, I); // (Y << C)
6987 Instruction *XM =
Gabor Greife1f6e4b2008-05-16 19:29:10 +00006988 BinaryOperator::CreateAnd(V1, ConstantExpr::getShl(CC, Op1),
Chris Lattner797dee72005-09-18 06:30:59 +00006989 V1->getName()+".mask");
6990 InsertNewInstBefore(XM, I); // X & (CC << C)
6991
Gabor Greife1f6e4b2008-05-16 19:29:10 +00006992 return BinaryOperator::Create(Op0BO->getOpcode(), YS, XM);
Chris Lattner797dee72005-09-18 06:30:59 +00006993 }
Reid Spencer2f34b982007-02-02 14:41:37 +00006994 }
Chris Lattner14553932006-01-06 07:12:35 +00006995
Reid Spencer2f34b982007-02-02 14:41:37 +00006996 // FALL THROUGH.
6997 case Instruction::Sub: {
Chris Lattner27cb9db2005-09-18 05:12:10 +00006998 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
Chris Lattner797dee72005-09-18 06:30:59 +00006999 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
7000 match(Op0BO->getOperand(0),
Chris Lattner14553932006-01-06 07:12:35 +00007001 m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
Gabor Greife1f6e4b2008-05-16 19:29:10 +00007002 Instruction *YS = BinaryOperator::CreateShl(
Reid Spencer2341c222007-02-02 02:16:23 +00007003 Op0BO->getOperand(1), Op1,
7004 Op0BO->getName());
Chris Lattner797dee72005-09-18 06:30:59 +00007005 InsertNewInstBefore(YS, I); // (Y << C)
Chris Lattner24cd2fa2006-02-09 07:41:14 +00007006 Instruction *X =
Gabor Greife1f6e4b2008-05-16 19:29:10 +00007007 BinaryOperator::Create(Op0BO->getOpcode(), V1, YS,
Chris Lattner24cd2fa2006-02-09 07:41:14 +00007008 Op0BO->getOperand(0)->getName());
Chris Lattner797dee72005-09-18 06:30:59 +00007009 InsertNewInstBefore(X, I); // (X + (Y << C))
Zhou Shengfd28a332007-03-30 17:20:39 +00007010 uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
Gabor Greife1f6e4b2008-05-16 19:29:10 +00007011 return BinaryOperator::CreateAnd(X, ConstantInt::get(
Zhou Sheng5e60a4a2007-03-30 05:45:18 +00007012 APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
Chris Lattner797dee72005-09-18 06:30:59 +00007013 }
Chris Lattner14553932006-01-06 07:12:35 +00007014
Chris Lattner1df0e982006-05-31 21:14:00 +00007015 // Turn (((X >> C)&CC) + Y) << C -> (X + (Y << C)) & (CC << C)
Chris Lattner797dee72005-09-18 06:30:59 +00007016 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
7017 match(Op0BO->getOperand(0),
7018 m_And(m_Shr(m_Value(V1), m_Value(V2)),
Chris Lattner14553932006-01-06 07:12:35 +00007019 m_ConstantInt(CC))) && V2 == Op1 &&
Chris Lattner24cd2fa2006-02-09 07:41:14 +00007020 cast<BinaryOperator>(Op0BO->getOperand(0))
7021 ->getOperand(0)->hasOneUse()) {
Gabor Greife1f6e4b2008-05-16 19:29:10 +00007022 Instruction *YS = BinaryOperator::CreateShl(
Reid Spencer2341c222007-02-02 02:16:23 +00007023 Op0BO->getOperand(1), Op1,
7024 Op0BO->getName());
Chris Lattner797dee72005-09-18 06:30:59 +00007025 InsertNewInstBefore(YS, I); // (Y << C)
7026 Instruction *XM =
Gabor Greife1f6e4b2008-05-16 19:29:10 +00007027 BinaryOperator::CreateAnd(V1, ConstantExpr::getShl(CC, Op1),
Chris Lattner797dee72005-09-18 06:30:59 +00007028 V1->getName()+".mask");
7029 InsertNewInstBefore(XM, I); // X & (CC << C)
7030
Gabor Greife1f6e4b2008-05-16 19:29:10 +00007031 return BinaryOperator::Create(Op0BO->getOpcode(), XM, YS);
Chris Lattner797dee72005-09-18 06:30:59 +00007032 }
Chris Lattner14553932006-01-06 07:12:35 +00007033
Chris Lattner27cb9db2005-09-18 05:12:10 +00007034 break;
Reid Spencer2f34b982007-02-02 14:41:37 +00007035 }
Chris Lattner14553932006-01-06 07:12:35 +00007036 }
7037
7038
7039 // If the operand is an bitwise operator with a constant RHS, and the
7040 // shift is the only use, we can pull it out of the shift.
7041 if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
7042 bool isValid = true; // Valid only for And, Or, Xor
7043 bool highBitSet = false; // Transform if high bit of constant set?
7044
7045 switch (Op0BO->getOpcode()) {
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00007046 default: isValid = false; break; // Do not perform transform!
Chris Lattner44bd3922004-10-08 03:46:20 +00007047 case Instruction::Add:
7048 isValid = isLeftShift;
7049 break;
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00007050 case Instruction::Or:
7051 case Instruction::Xor:
7052 highBitSet = false;
7053 break;
7054 case Instruction::And:
7055 highBitSet = true;
7056 break;
Chris Lattner14553932006-01-06 07:12:35 +00007057 }
7058
7059 // If this is a signed shift right, and the high bit is modified
7060 // by the logical operation, do not perform the transformation.
7061 // The highBitSet boolean indicates the value of the high bit of
7062 // the constant which would cause it to be modified for this
7063 // operation.
7064 //
Chris Lattnerd2bbbab2007-12-06 06:25:04 +00007065 if (isValid && I.getOpcode() == Instruction::AShr)
Zhou Sheng23f7a1c2007-03-28 15:02:20 +00007066 isValid = Op0C->getValue()[TypeBits-1] == highBitSet;
Chris Lattner14553932006-01-06 07:12:35 +00007067
7068 if (isValid) {
7069 Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, Op1);
7070
7071 Instruction *NewShift =
Gabor Greife1f6e4b2008-05-16 19:29:10 +00007072 BinaryOperator::Create(I.getOpcode(), Op0BO->getOperand(0), Op1);
Chris Lattner14553932006-01-06 07:12:35 +00007073 InsertNewInstBefore(NewShift, I);
Chris Lattner6e0123b2007-02-11 01:23:03 +00007074 NewShift->takeName(Op0BO);
Chris Lattner14553932006-01-06 07:12:35 +00007075
Gabor Greife1f6e4b2008-05-16 19:29:10 +00007076 return BinaryOperator::Create(Op0BO->getOpcode(), NewShift,
Chris Lattner14553932006-01-06 07:12:35 +00007077 NewRHS);
7078 }
7079 }
7080 }
7081 }
7082
Chris Lattnereb372a02006-01-06 07:52:12 +00007083 // Find out if this is a shift of a shift by a constant.
Reid Spencer2341c222007-02-02 02:16:23 +00007084 BinaryOperator *ShiftOp = dyn_cast<BinaryOperator>(Op0);
7085 if (ShiftOp && !ShiftOp->isShift())
7086 ShiftOp = 0;
Chris Lattnereb372a02006-01-06 07:52:12 +00007087
Reid Spencere0fc4df2006-10-20 07:07:24 +00007088 if (ShiftOp && isa<ConstantInt>(ShiftOp->getOperand(1))) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00007089 ConstantInt *ShiftAmt1C = cast<ConstantInt>(ShiftOp->getOperand(1));
Zhou Shengb25806f2007-03-30 09:29:48 +00007090 uint32_t ShiftAmt1 = ShiftAmt1C->getLimitedValue(TypeBits);
7091 uint32_t ShiftAmt2 = Op1->getLimitedValue(TypeBits);
Chris Lattner3e009e82007-02-05 00:57:54 +00007092 assert(ShiftAmt2 != 0 && "Should have been simplified earlier");
7093 if (ShiftAmt1 == 0) return 0; // Will be simplified in the future.
7094 Value *X = ShiftOp->getOperand(0);
Chris Lattnereb372a02006-01-06 07:52:12 +00007095
Zhou Sheng56cda952007-04-02 08:20:41 +00007096 uint32_t AmtSum = ShiftAmt1+ShiftAmt2; // Fold into one big shift.
Reid Spencer6274c722007-03-23 18:46:34 +00007097 if (AmtSum > TypeBits)
7098 AmtSum = TypeBits;
Chris Lattner3e009e82007-02-05 00:57:54 +00007099
7100 const IntegerType *Ty = cast<IntegerType>(I.getType());
7101
7102 // Check for (X << c1) << c2 and (X >> c1) >> c2
Chris Lattner6c344e52007-02-03 23:28:07 +00007103 if (I.getOpcode() == ShiftOp->getOpcode()) {
Gabor Greife1f6e4b2008-05-16 19:29:10 +00007104 return BinaryOperator::Create(I.getOpcode(), X,
Chris Lattner3e009e82007-02-05 00:57:54 +00007105 ConstantInt::get(Ty, AmtSum));
7106 } else if (ShiftOp->getOpcode() == Instruction::LShr &&
7107 I.getOpcode() == Instruction::AShr) {
7108 // ((X >>u C1) >>s C2) -> (X >>u (C1+C2)) since C1 != 0.
Gabor Greife1f6e4b2008-05-16 19:29:10 +00007109 return BinaryOperator::CreateLShr(X, ConstantInt::get(Ty, AmtSum));
Chris Lattner3e009e82007-02-05 00:57:54 +00007110 } else if (ShiftOp->getOpcode() == Instruction::AShr &&
7111 I.getOpcode() == Instruction::LShr) {
7112 // ((X >>s C1) >>u C2) -> ((X >>s (C1+C2)) & mask) since C1 != 0.
7113 Instruction *Shift =
Gabor Greife1f6e4b2008-05-16 19:29:10 +00007114 BinaryOperator::CreateAShr(X, ConstantInt::get(Ty, AmtSum));
Chris Lattner3e009e82007-02-05 00:57:54 +00007115 InsertNewInstBefore(Shift, I);
7116
Zhou Sheng23f7a1c2007-03-28 15:02:20 +00007117 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Gabor Greife1f6e4b2008-05-16 19:29:10 +00007118 return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
Chris Lattnereb372a02006-01-06 07:52:12 +00007119 }
7120
Chris Lattner3e009e82007-02-05 00:57:54 +00007121 // Okay, if we get here, one shift must be left, and the other shift must be
7122 // right. See if the amounts are equal.
7123 if (ShiftAmt1 == ShiftAmt2) {
7124 // If we have ((X >>? C) << C), turn this into X & (-1 << C).
7125 if (I.getOpcode() == Instruction::Shl) {
Reid Spencer52830322007-03-25 21:11:44 +00007126 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt1));
Gabor Greife1f6e4b2008-05-16 19:29:10 +00007127 return BinaryOperator::CreateAnd(X, ConstantInt::get(Mask));
Chris Lattner3e009e82007-02-05 00:57:54 +00007128 }
7129 // If we have ((X << C) >>u C), turn this into X & (-1 >>u C).
7130 if (I.getOpcode() == Instruction::LShr) {
Zhou Sheng150f3bb2007-04-01 17:13:37 +00007131 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt1));
Gabor Greife1f6e4b2008-05-16 19:29:10 +00007132 return BinaryOperator::CreateAnd(X, ConstantInt::get(Mask));
Chris Lattner3e009e82007-02-05 00:57:54 +00007133 }
7134 // We can simplify ((X << C) >>s C) into a trunc + sext.
7135 // NOTE: we could do this for any C, but that would make 'unusual' integer
7136 // types. For now, just stick to ones well-supported by the code
7137 // generators.
7138 const Type *SExtType = 0;
7139 switch (Ty->getBitWidth() - ShiftAmt1) {
Zhou Sheng23f7a1c2007-03-28 15:02:20 +00007140 case 1 :
7141 case 8 :
7142 case 16 :
7143 case 32 :
7144 case 64 :
7145 case 128:
7146 SExtType = IntegerType::get(Ty->getBitWidth() - ShiftAmt1);
7147 break;
Chris Lattner3e009e82007-02-05 00:57:54 +00007148 default: break;
7149 }
7150 if (SExtType) {
7151 Instruction *NewTrunc = new TruncInst(X, SExtType, "sext");
7152 InsertNewInstBefore(NewTrunc, I);
7153 return new SExtInst(NewTrunc, Ty);
7154 }
7155 // Otherwise, we can't handle it yet.
7156 } else if (ShiftAmt1 < ShiftAmt2) {
Zhou Sheng56cda952007-04-02 08:20:41 +00007157 uint32_t ShiftDiff = ShiftAmt2-ShiftAmt1;
Chris Lattnereb372a02006-01-06 07:52:12 +00007158
Chris Lattner83ac5ae92007-02-05 05:57:49 +00007159 // (X >>? C1) << C2 --> X << (C2-C1) & (-1 << C2)
Chris Lattner3e009e82007-02-05 00:57:54 +00007160 if (I.getOpcode() == Instruction::Shl) {
7161 assert(ShiftOp->getOpcode() == Instruction::LShr ||
7162 ShiftOp->getOpcode() == Instruction::AShr);
Chris Lattner9cbfbc22006-01-07 01:32:28 +00007163 Instruction *Shift =
Gabor Greife1f6e4b2008-05-16 19:29:10 +00007164 BinaryOperator::CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
Chris Lattner9cbfbc22006-01-07 01:32:28 +00007165 InsertNewInstBefore(Shift, I);
7166
Reid Spencer52830322007-03-25 21:11:44 +00007167 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
Gabor Greife1f6e4b2008-05-16 19:29:10 +00007168 return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
Chris Lattnereb372a02006-01-06 07:52:12 +00007169 }
Chris Lattner3e009e82007-02-05 00:57:54 +00007170
Chris Lattner83ac5ae92007-02-05 05:57:49 +00007171 // (X << C1) >>u C2 --> X >>u (C2-C1) & (-1 >> C2)
Chris Lattner3e009e82007-02-05 00:57:54 +00007172 if (I.getOpcode() == Instruction::LShr) {
7173 assert(ShiftOp->getOpcode() == Instruction::Shl);
7174 Instruction *Shift =
Gabor Greife1f6e4b2008-05-16 19:29:10 +00007175 BinaryOperator::CreateLShr(X, ConstantInt::get(Ty, ShiftDiff));
Chris Lattner3e009e82007-02-05 00:57:54 +00007176 InsertNewInstBefore(Shift, I);
Chris Lattnereb372a02006-01-06 07:52:12 +00007177
Reid Spencer769a5a82007-03-26 17:18:58 +00007178 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Gabor Greife1f6e4b2008-05-16 19:29:10 +00007179 return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
Chris Lattner27cb9db2005-09-18 05:12:10 +00007180 }
Chris Lattner3e009e82007-02-05 00:57:54 +00007181
7182 // We can't handle (X << C1) >>s C2, it shifts arbitrary bits in.
7183 } else {
7184 assert(ShiftAmt2 < ShiftAmt1);
Zhou Sheng56cda952007-04-02 08:20:41 +00007185 uint32_t ShiftDiff = ShiftAmt1-ShiftAmt2;
Chris Lattner3e009e82007-02-05 00:57:54 +00007186
Chris Lattner83ac5ae92007-02-05 05:57:49 +00007187 // (X >>? C1) << C2 --> X >>? (C1-C2) & (-1 << C2)
Chris Lattner3e009e82007-02-05 00:57:54 +00007188 if (I.getOpcode() == Instruction::Shl) {
7189 assert(ShiftOp->getOpcode() == Instruction::LShr ||
7190 ShiftOp->getOpcode() == Instruction::AShr);
7191 Instruction *Shift =
Gabor Greife1f6e4b2008-05-16 19:29:10 +00007192 BinaryOperator::Create(ShiftOp->getOpcode(), X,
Chris Lattner3e009e82007-02-05 00:57:54 +00007193 ConstantInt::get(Ty, ShiftDiff));
7194 InsertNewInstBefore(Shift, I);
7195
Reid Spencer52830322007-03-25 21:11:44 +00007196 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
Gabor Greife1f6e4b2008-05-16 19:29:10 +00007197 return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
Chris Lattner3e009e82007-02-05 00:57:54 +00007198 }
7199
Chris Lattner83ac5ae92007-02-05 05:57:49 +00007200 // (X << C1) >>u C2 --> X << (C1-C2) & (-1 >> C2)
Chris Lattner3e009e82007-02-05 00:57:54 +00007201 if (I.getOpcode() == Instruction::LShr) {
7202 assert(ShiftOp->getOpcode() == Instruction::Shl);
7203 Instruction *Shift =
Gabor Greife1f6e4b2008-05-16 19:29:10 +00007204 BinaryOperator::CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
Chris Lattner3e009e82007-02-05 00:57:54 +00007205 InsertNewInstBefore(Shift, I);
7206
Reid Spencer441486c2007-03-26 23:45:51 +00007207 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Gabor Greife1f6e4b2008-05-16 19:29:10 +00007208 return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
Chris Lattner3e009e82007-02-05 00:57:54 +00007209 }
7210
7211 // We can't handle (X << C1) >>a C2, it shifts arbitrary bits in.
Chris Lattner86102b82005-01-01 16:22:27 +00007212 }
Chris Lattnereb372a02006-01-06 07:52:12 +00007213 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00007214 return 0;
7215}
7216
Chris Lattner48a44f72002-05-02 17:06:02 +00007217
Chris Lattner8f663e82005-10-29 04:36:15 +00007218/// DecomposeSimpleLinearExpr - Analyze 'Val', seeing if it is a simple linear
7219/// expression. If so, decompose it, returning some value X, such that Val is
7220/// X*Scale+Offset.
7221///
7222static Value *DecomposeSimpleLinearExpr(Value *Val, unsigned &Scale,
Jeff Cohen5a1c7502007-04-04 16:58:57 +00007223 int &Offset) {
Reid Spencerc635f472006-12-31 05:48:39 +00007224 assert(Val->getType() == Type::Int32Ty && "Unexpected allocation size type!");
Reid Spencere0fc4df2006-10-20 07:07:24 +00007225 if (ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
Reid Spencerc635f472006-12-31 05:48:39 +00007226 Offset = CI->getZExtValue();
Chris Lattnerd8675e42007-10-12 05:30:59 +00007227 Scale = 0;
Reid Spencerc635f472006-12-31 05:48:39 +00007228 return ConstantInt::get(Type::Int32Ty, 0);
Chris Lattnerd8675e42007-10-12 05:30:59 +00007229 } else if (BinaryOperator *I = dyn_cast<BinaryOperator>(Val)) {
7230 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
7231 if (I->getOpcode() == Instruction::Shl) {
7232 // This is a value scaled by '1 << the shift amt'.
7233 Scale = 1U << RHS->getZExtValue();
7234 Offset = 0;
7235 return I->getOperand(0);
7236 } else if (I->getOpcode() == Instruction::Mul) {
7237 // This value is scaled by 'RHS'.
7238 Scale = RHS->getZExtValue();
7239 Offset = 0;
7240 return I->getOperand(0);
7241 } else if (I->getOpcode() == Instruction::Add) {
7242 // We have X+C. Check to see if we really have (X*C2)+C1,
7243 // where C1 is divisible by C2.
7244 unsigned SubScale;
7245 Value *SubVal =
7246 DecomposeSimpleLinearExpr(I->getOperand(0), SubScale, Offset);
7247 Offset += RHS->getZExtValue();
7248 Scale = SubScale;
7249 return SubVal;
Chris Lattner8f663e82005-10-29 04:36:15 +00007250 }
7251 }
7252 }
7253
7254 // Otherwise, we can't look past this.
7255 Scale = 1;
7256 Offset = 0;
7257 return Val;
7258}
7259
7260
Chris Lattner216be912005-10-24 06:03:58 +00007261/// PromoteCastOfAllocation - If we find a cast of an allocation instruction,
7262/// try to eliminate the cast by moving the type information into the alloc.
Chris Lattner1db224d2007-04-27 17:44:50 +00007263Instruction *InstCombiner::PromoteCastOfAllocation(BitCastInst &CI,
Chris Lattner216be912005-10-24 06:03:58 +00007264 AllocationInst &AI) {
Chris Lattner1db224d2007-04-27 17:44:50 +00007265 const PointerType *PTy = cast<PointerType>(CI.getType());
Chris Lattner216be912005-10-24 06:03:58 +00007266
Chris Lattnerac87beb2005-10-24 06:22:12 +00007267 // Remove any uses of AI that are dead.
7268 assert(!CI.use_empty() && "Dead instructions should be removed earlier!");
Chris Lattner99c6cf62007-02-15 22:52:10 +00007269
Chris Lattnerac87beb2005-10-24 06:22:12 +00007270 for (Value::use_iterator UI = AI.use_begin(), E = AI.use_end(); UI != E; ) {
7271 Instruction *User = cast<Instruction>(*UI++);
7272 if (isInstructionTriviallyDead(User)) {
7273 while (UI != E && *UI == User)
7274 ++UI; // If this instruction uses AI more than once, don't break UI.
7275
Chris Lattnerac87beb2005-10-24 06:22:12 +00007276 ++NumDeadInst;
Bill Wendling5dbf43c2006-11-26 09:46:52 +00007277 DOUT << "IC: DCE: " << *User;
Chris Lattner51f54572007-03-02 19:59:19 +00007278 EraseInstFromFunction(*User);
Chris Lattnerac87beb2005-10-24 06:22:12 +00007279 }
7280 }
7281
Chris Lattner216be912005-10-24 06:03:58 +00007282 // Get the type really allocated and the type casted to.
7283 const Type *AllocElTy = AI.getAllocatedType();
7284 const Type *CastElTy = PTy->getElementType();
7285 if (!AllocElTy->isSized() || !CastElTy->isSized()) return 0;
Chris Lattner355ecc02005-10-24 06:26:18 +00007286
Chris Lattner945e4372007-02-14 05:52:17 +00007287 unsigned AllocElTyAlign = TD->getABITypeAlignment(AllocElTy);
7288 unsigned CastElTyAlign = TD->getABITypeAlignment(CastElTy);
Chris Lattner355ecc02005-10-24 06:26:18 +00007289 if (CastElTyAlign < AllocElTyAlign) return 0;
7290
Chris Lattner46705b22005-10-24 06:35:18 +00007291 // If the allocation has multiple uses, only promote it if we are strictly
7292 // increasing the alignment of the resultant allocation. If we keep it the
7293 // same, we open the door to infinite loops of various kinds.
7294 if (!AI.hasOneUse() && CastElTyAlign == AllocElTyAlign) return 0;
7295
Duncan Sands44b87212007-11-01 20:53:16 +00007296 uint64_t AllocElTySize = TD->getABITypeSize(AllocElTy);
7297 uint64_t CastElTySize = TD->getABITypeSize(CastElTy);
Chris Lattnerbb171802005-10-27 05:53:56 +00007298 if (CastElTySize == 0 || AllocElTySize == 0) return 0;
Chris Lattner355ecc02005-10-24 06:26:18 +00007299
Chris Lattner8270c332005-10-29 03:19:53 +00007300 // See if we can satisfy the modulus by pulling a scale out of the array
7301 // size argument.
Jeff Cohen5a1c7502007-04-04 16:58:57 +00007302 unsigned ArraySizeScale;
7303 int ArrayOffset;
Chris Lattner8f663e82005-10-29 04:36:15 +00007304 Value *NumElements = // See if the array size is a decomposable linear expr.
7305 DecomposeSimpleLinearExpr(AI.getOperand(0), ArraySizeScale, ArrayOffset);
7306
Chris Lattner8270c332005-10-29 03:19:53 +00007307 // If we can now satisfy the modulus, by using a non-1 scale, we really can
7308 // do the xform.
Chris Lattner8f663e82005-10-29 04:36:15 +00007309 if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 ||
7310 (AllocElTySize*ArrayOffset ) % CastElTySize != 0) return 0;
Chris Lattnerb3ecf962005-10-27 06:12:00 +00007311
Chris Lattner8270c332005-10-29 03:19:53 +00007312 unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize;
7313 Value *Amt = 0;
7314 if (Scale == 1) {
7315 Amt = NumElements;
7316 } else {
Reid Spencere0fc4df2006-10-20 07:07:24 +00007317 // If the allocation size is constant, form a constant mul expression
Reid Spencerc635f472006-12-31 05:48:39 +00007318 Amt = ConstantInt::get(Type::Int32Ty, Scale);
7319 if (isa<ConstantInt>(NumElements))
Zhou Sheng9bc8ab12007-04-02 13:45:30 +00007320 Amt = Multiply(cast<ConstantInt>(NumElements), cast<ConstantInt>(Amt));
Reid Spencere0fc4df2006-10-20 07:07:24 +00007321 // otherwise multiply the amount and the number of elements
Chris Lattner8270c332005-10-29 03:19:53 +00007322 else if (Scale != 1) {
Gabor Greife1f6e4b2008-05-16 19:29:10 +00007323 Instruction *Tmp = BinaryOperator::CreateMul(Amt, NumElements, "tmp");
Chris Lattner8270c332005-10-29 03:19:53 +00007324 Amt = InsertNewInstBefore(Tmp, AI);
Chris Lattnerb3ecf962005-10-27 06:12:00 +00007325 }
Chris Lattnerbb171802005-10-27 05:53:56 +00007326 }
7327
Jeff Cohen5a1c7502007-04-04 16:58:57 +00007328 if (int Offset = (AllocElTySize*ArrayOffset)/CastElTySize) {
7329 Value *Off = ConstantInt::get(Type::Int32Ty, Offset, true);
Gabor Greife1f6e4b2008-05-16 19:29:10 +00007330 Instruction *Tmp = BinaryOperator::CreateAdd(Amt, Off, "tmp");
Chris Lattner8f663e82005-10-29 04:36:15 +00007331 Amt = InsertNewInstBefore(Tmp, AI);
7332 }
7333
Chris Lattner216be912005-10-24 06:03:58 +00007334 AllocationInst *New;
7335 if (isa<MallocInst>(AI))
Chris Lattner6e0123b2007-02-11 01:23:03 +00007336 New = new MallocInst(CastElTy, Amt, AI.getAlignment());
Chris Lattner216be912005-10-24 06:03:58 +00007337 else
Chris Lattner6e0123b2007-02-11 01:23:03 +00007338 New = new AllocaInst(CastElTy, Amt, AI.getAlignment());
Chris Lattner216be912005-10-24 06:03:58 +00007339 InsertNewInstBefore(New, AI);
Chris Lattner6e0123b2007-02-11 01:23:03 +00007340 New->takeName(&AI);
Chris Lattner46705b22005-10-24 06:35:18 +00007341
7342 // If the allocation has multiple uses, insert a cast and change all things
7343 // that used it to use the new cast. This will also hack on CI, but it will
7344 // die soon.
7345 if (!AI.hasOneUse()) {
7346 AddUsesToWorkList(AI);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007347 // New is the allocation instruction, pointer typed. AI is the original
7348 // allocation instruction, also pointer typed. Thus, cast to use is BitCast.
7349 CastInst *NewCast = new BitCastInst(New, AI.getType(), "tmpcast");
Chris Lattner46705b22005-10-24 06:35:18 +00007350 InsertNewInstBefore(NewCast, AI);
7351 AI.replaceAllUsesWith(NewCast);
7352 }
Chris Lattner216be912005-10-24 06:03:58 +00007353 return ReplaceInstUsesWith(CI, New);
7354}
7355
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00007356/// CanEvaluateInDifferentType - Return true if we can take the specified value
Chris Lattnerda1d04a2007-03-03 05:27:34 +00007357/// and return it as type Ty without inserting any new casts and without
7358/// changing the computed value. This is used by code that tries to decide
7359/// whether promoting or shrinking integer operations to wider or smaller types
7360/// will allow us to eliminate a truncate or extend.
7361///
7362/// This is a truncation operation if Ty is smaller than V->getType(), or an
7363/// extension operation if Ty is larger.
Chris Lattnerb5ee8b32008-06-18 04:00:49 +00007364///
7365/// If CastOpc is a truncation, then Ty will be a type smaller than V. We
7366/// should return true if trunc(V) can be computed by computing V in the smaller
7367/// type. If V is an instruction, then trunc(inst(x,y)) can be computed as
7368/// inst(trunc(x),trunc(y)), which only makes sense if x and y can be
7369/// efficiently truncated.
7370///
7371/// If CastOpc is a sext or zext, we are asking if the low bits of the value can
7372/// bit computed in a larger type, which is then and'd or sext_in_reg'd to get
7373/// the final result.
Dan Gohman99b7b3f2008-04-10 18:43:06 +00007374bool InstCombiner::CanEvaluateInDifferentType(Value *V, const IntegerType *Ty,
7375 unsigned CastOpc,
7376 int &NumCastsRemoved) {
Chris Lattnerda1d04a2007-03-03 05:27:34 +00007377 // We can always evaluate constants in another type.
7378 if (isa<ConstantInt>(V))
7379 return true;
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00007380
7381 Instruction *I = dyn_cast<Instruction>(V);
Chris Lattnerda1d04a2007-03-03 05:27:34 +00007382 if (!I) return false;
7383
7384 const IntegerType *OrigTy = cast<IntegerType>(V->getType());
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00007385
Chris Lattnerb0418fc2007-08-02 06:11:14 +00007386 // If this is an extension or truncate, we can often eliminate it.
7387 if (isa<TruncInst>(I) || isa<ZExtInst>(I) || isa<SExtInst>(I)) {
7388 // If this is a cast from the destination type, we can trivially eliminate
7389 // it, and this will remove a cast overall.
7390 if (I->getOperand(0)->getType() == Ty) {
7391 // If the first operand is itself a cast, and is eliminable, do not count
7392 // this as an eliminable cast. We would prefer to eliminate those two
7393 // casts first.
Chris Lattnerb5ee8b32008-06-18 04:00:49 +00007394 if (!isa<CastInst>(I->getOperand(0)) && I->hasOneUse())
Chris Lattnerb0418fc2007-08-02 06:11:14 +00007395 ++NumCastsRemoved;
7396 return true;
7397 }
7398 }
7399
7400 // We can't extend or shrink something that has multiple uses: doing so would
7401 // require duplicating the instruction in general, which isn't profitable.
7402 if (!I->hasOneUse()) return false;
7403
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00007404 switch (I->getOpcode()) {
Chris Lattnerda1d04a2007-03-03 05:27:34 +00007405 case Instruction::Add:
7406 case Instruction::Sub:
Nick Lewycky9f1a4dc2008-07-05 21:19:34 +00007407 case Instruction::Mul:
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00007408 case Instruction::And:
7409 case Instruction::Or:
7410 case Instruction::Xor:
7411 // These operators can all arbitrarily be extended or truncated.
Chris Lattnerb0418fc2007-08-02 06:11:14 +00007412 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
7413 NumCastsRemoved) &&
7414 CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
7415 NumCastsRemoved);
Chris Lattnerda1d04a2007-03-03 05:27:34 +00007416
Chris Lattner960acb02006-11-29 07:18:39 +00007417 case Instruction::Shl:
Chris Lattnerda1d04a2007-03-03 05:27:34 +00007418 // If we are truncating the result of this SHL, and if it's a shift of a
7419 // constant amount, we can always perform a SHL in a smaller type.
7420 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Shengfd28a332007-03-30 17:20:39 +00007421 uint32_t BitWidth = Ty->getBitWidth();
7422 if (BitWidth < OrigTy->getBitWidth() &&
7423 CI->getLimitedValue(BitWidth) < BitWidth)
Chris Lattnerb0418fc2007-08-02 06:11:14 +00007424 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
7425 NumCastsRemoved);
Chris Lattnerda1d04a2007-03-03 05:27:34 +00007426 }
7427 break;
7428 case Instruction::LShr:
Chris Lattnerda1d04a2007-03-03 05:27:34 +00007429 // If this is a truncate of a logical shr, we can truncate it to a smaller
7430 // lshr iff we know that the bits we would otherwise be shifting in are
7431 // already zeros.
7432 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Shengfd28a332007-03-30 17:20:39 +00007433 uint32_t OrigBitWidth = OrigTy->getBitWidth();
7434 uint32_t BitWidth = Ty->getBitWidth();
7435 if (BitWidth < OrigBitWidth &&
Chris Lattnerda1d04a2007-03-03 05:27:34 +00007436 MaskedValueIsZero(I->getOperand(0),
Zhou Shengfd28a332007-03-30 17:20:39 +00007437 APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth)) &&
7438 CI->getLimitedValue(BitWidth) < BitWidth) {
Chris Lattnerb0418fc2007-08-02 06:11:14 +00007439 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
7440 NumCastsRemoved);
Chris Lattnerda1d04a2007-03-03 05:27:34 +00007441 }
7442 }
Chris Lattner960acb02006-11-29 07:18:39 +00007443 break;
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007444 case Instruction::ZExt:
7445 case Instruction::SExt:
Chris Lattnerb0418fc2007-08-02 06:11:14 +00007446 case Instruction::Trunc:
7447 // If this is the same kind of case as our original (e.g. zext+zext), we
Chris Lattnerdc2cf222007-08-02 17:23:38 +00007448 // can safely replace it. Note that replacing it does not reduce the number
7449 // of casts in the input.
7450 if (I->getOpcode() == CastOpc)
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00007451 return true;
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007452 break;
Nick Lewycky9f1a4dc2008-07-05 21:19:34 +00007453 case Instruction::Select: {
7454 SelectInst *SI = cast<SelectInst>(I);
7455 return CanEvaluateInDifferentType(SI->getTrueValue(), Ty, CastOpc,
7456 NumCastsRemoved) &&
7457 CanEvaluateInDifferentType(SI->getFalseValue(), Ty, CastOpc,
7458 NumCastsRemoved);
7459 }
Chris Lattnerb5ee8b32008-06-18 04:00:49 +00007460 case Instruction::PHI: {
7461 // We can change a phi if we can change all operands.
7462 PHINode *PN = cast<PHINode>(I);
7463 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
7464 if (!CanEvaluateInDifferentType(PN->getIncomingValue(i), Ty, CastOpc,
7465 NumCastsRemoved))
7466 return false;
7467 return true;
7468 }
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007469 default:
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00007470 // TODO: Can handle more cases here.
7471 break;
7472 }
7473
7474 return false;
7475}
7476
7477/// EvaluateInDifferentType - Given an expression that
7478/// CanEvaluateInDifferentType returns true for, actually insert the code to
7479/// evaluate the expression.
Reid Spencer74a528b2006-12-13 18:21:21 +00007480Value *InstCombiner::EvaluateInDifferentType(Value *V, const Type *Ty,
Chris Lattnerda1d04a2007-03-03 05:27:34 +00007481 bool isSigned) {
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00007482 if (Constant *C = dyn_cast<Constant>(V))
Reid Spencer74a528b2006-12-13 18:21:21 +00007483 return ConstantExpr::getIntegerCast(C, Ty, isSigned /*Sext or ZExt*/);
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00007484
7485 // Otherwise, it must be an instruction.
7486 Instruction *I = cast<Instruction>(V);
Chris Lattnerd0622b62006-05-20 23:14:03 +00007487 Instruction *Res = 0;
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00007488 switch (I->getOpcode()) {
Chris Lattnerda1d04a2007-03-03 05:27:34 +00007489 case Instruction::Add:
7490 case Instruction::Sub:
Nick Lewycky78712e52008-01-22 05:08:48 +00007491 case Instruction::Mul:
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00007492 case Instruction::And:
7493 case Instruction::Or:
Chris Lattnerda1d04a2007-03-03 05:27:34 +00007494 case Instruction::Xor:
Chris Lattner960acb02006-11-29 07:18:39 +00007495 case Instruction::AShr:
7496 case Instruction::LShr:
7497 case Instruction::Shl: {
Reid Spencer74a528b2006-12-13 18:21:21 +00007498 Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty, isSigned);
Chris Lattnerda1d04a2007-03-03 05:27:34 +00007499 Value *RHS = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
Gabor Greife1f6e4b2008-05-16 19:29:10 +00007500 Res = BinaryOperator::Create((Instruction::BinaryOps)I->getOpcode(),
Chris Lattnerb5ee8b32008-06-18 04:00:49 +00007501 LHS, RHS);
Chris Lattner960acb02006-11-29 07:18:39 +00007502 break;
7503 }
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007504 case Instruction::Trunc:
7505 case Instruction::ZExt:
7506 case Instruction::SExt:
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007507 // If the source type of the cast is the type we're trying for then we can
Chris Lattnerb0418fc2007-08-02 06:11:14 +00007508 // just return the source. There's no need to insert it because it is not
7509 // new.
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00007510 if (I->getOperand(0)->getType() == Ty)
7511 return I->getOperand(0);
7512
Chris Lattnerb5ee8b32008-06-18 04:00:49 +00007513 // Otherwise, must be the same type of cast, so just reinsert a new one.
Gabor Greife1f6e4b2008-05-16 19:29:10 +00007514 Res = CastInst::Create(cast<CastInst>(I)->getOpcode(), I->getOperand(0),
Chris Lattnerb5ee8b32008-06-18 04:00:49 +00007515 Ty);
Chris Lattnerb0418fc2007-08-02 06:11:14 +00007516 break;
Nick Lewycky9f1a4dc2008-07-05 21:19:34 +00007517 case Instruction::Select: {
7518 Value *True = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
7519 Value *False = EvaluateInDifferentType(I->getOperand(2), Ty, isSigned);
7520 Res = SelectInst::Create(I->getOperand(0), True, False);
7521 break;
7522 }
Chris Lattnerb5ee8b32008-06-18 04:00:49 +00007523 case Instruction::PHI: {
7524 PHINode *OPN = cast<PHINode>(I);
7525 PHINode *NPN = PHINode::Create(Ty);
7526 for (unsigned i = 0, e = OPN->getNumIncomingValues(); i != e; ++i) {
7527 Value *V =EvaluateInDifferentType(OPN->getIncomingValue(i), Ty, isSigned);
7528 NPN->addIncoming(V, OPN->getIncomingBlock(i));
7529 }
7530 Res = NPN;
7531 break;
7532 }
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007533 default:
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00007534 // TODO: Can handle more cases here.
7535 assert(0 && "Unreachable!");
7536 break;
7537 }
7538
Chris Lattnerb5ee8b32008-06-18 04:00:49 +00007539 Res->takeName(I);
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00007540 return InsertNewInstBefore(Res, *I);
7541}
7542
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007543/// @brief Implement the transforms common to all CastInst visitors.
7544Instruction *InstCombiner::commonCastTransforms(CastInst &CI) {
Chris Lattner55d4bda2003-06-23 21:59:52 +00007545 Value *Src = CI.getOperand(0);
7546
Dan Gohmanb5650eb2007-05-11 21:10:54 +00007547 // Many cases of "cast of a cast" are eliminable. If it's eliminable we just
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007548 // eliminate it now.
Chris Lattner86102b82005-01-01 16:22:27 +00007549 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007550 if (Instruction::CastOps opc =
7551 isEliminableCastPair(CSrc, CI.getOpcode(), CI.getType(), TD)) {
7552 // The first cast (CSrc) is eliminable so we need to fix up or replace
7553 // the second cast (CI). CSrc will then have a good chance of being dead.
Gabor Greife1f6e4b2008-05-16 19:29:10 +00007554 return CastInst::Create(opc, CSrc->getOperand(0), CI.getType());
Chris Lattner650b6da2002-08-02 20:00:25 +00007555 }
7556 }
Chris Lattner03841652004-05-25 04:29:21 +00007557
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007558 // If we are casting a select then fold the cast into the select
Chris Lattner86102b82005-01-01 16:22:27 +00007559 if (SelectInst *SI = dyn_cast<SelectInst>(Src))
7560 if (Instruction *NV = FoldOpIntoSelect(CI, SI, this))
7561 return NV;
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007562
7563 // If we are casting a PHI then fold the cast into the PHI
Chris Lattner6a4adcd2004-09-29 05:07:12 +00007564 if (isa<PHINode>(Src))
7565 if (Instruction *NV = FoldOpIntoPhi(CI))
7566 return NV;
Chris Lattnerb19a5c62006-04-12 18:09:35 +00007567
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007568 return 0;
7569}
7570
Chris Lattner1db224d2007-04-27 17:44:50 +00007571/// @brief Implement the transforms for cast of pointer (bitcast/ptrtoint)
7572Instruction *InstCombiner::commonPointerCastTransforms(CastInst &CI) {
7573 Value *Src = CI.getOperand(0);
7574
Chris Lattner1db224d2007-04-27 17:44:50 +00007575 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
Chris Lattneracbf6a42007-04-28 00:57:34 +00007576 // If casting the result of a getelementptr instruction with no offset, turn
7577 // this into a cast of the original pointer!
Chris Lattner1db224d2007-04-27 17:44:50 +00007578 if (GEP->hasAllZeroIndices()) {
7579 // Changing the cast operand is usually not a good idea but it is safe
7580 // here because the pointer operand is being replaced with another
7581 // pointer operand so the opcode doesn't need to change.
Chris Lattneracbf6a42007-04-28 00:57:34 +00007582 AddToWorkList(GEP);
Chris Lattner1db224d2007-04-27 17:44:50 +00007583 CI.setOperand(0, GEP->getOperand(0));
7584 return &CI;
7585 }
Chris Lattneracbf6a42007-04-28 00:57:34 +00007586
7587 // If the GEP has a single use, and the base pointer is a bitcast, and the
7588 // GEP computes a constant offset, see if we can convert these three
7589 // instructions into fewer. This typically happens with unions and other
7590 // non-type-safe code.
7591 if (GEP->hasOneUse() && isa<BitCastInst>(GEP->getOperand(0))) {
7592 if (GEP->hasAllConstantIndices()) {
7593 // We are guaranteed to get a constant from EmitGEPOffset.
7594 ConstantInt *OffsetV = cast<ConstantInt>(EmitGEPOffset(GEP, CI, *this));
7595 int64_t Offset = OffsetV->getSExtValue();
7596
7597 // Get the base pointer input of the bitcast, and the type it points to.
7598 Value *OrigBase = cast<BitCastInst>(GEP->getOperand(0))->getOperand(0);
7599 const Type *GEPIdxTy =
7600 cast<PointerType>(OrigBase->getType())->getElementType();
7601 if (GEPIdxTy->isSized()) {
7602 SmallVector<Value*, 8> NewIndices;
7603
Chris Lattner5c827bd2007-05-05 01:59:31 +00007604 // Start with the index over the outer type. Note that the type size
7605 // might be zero (even if the offset isn't zero) if the indexed type
7606 // is something like [0 x {int, int}]
Chris Lattneracbf6a42007-04-28 00:57:34 +00007607 const Type *IntPtrTy = TD->getIntPtrType();
Chris Lattner5c827bd2007-05-05 01:59:31 +00007608 int64_t FirstIdx = 0;
Duncan Sands44b87212007-11-01 20:53:16 +00007609 if (int64_t TySize = TD->getABITypeSize(GEPIdxTy)) {
Chris Lattner5c827bd2007-05-05 01:59:31 +00007610 FirstIdx = Offset/TySize;
7611 Offset %= TySize;
Chris Lattneracbf6a42007-04-28 00:57:34 +00007612
Chris Lattner5c827bd2007-05-05 01:59:31 +00007613 // Handle silly modulus not returning values values [0..TySize).
7614 if (Offset < 0) {
7615 --FirstIdx;
7616 Offset += TySize;
7617 assert(Offset >= 0);
7618 }
Chris Lattner361e9812007-05-05 22:32:24 +00007619 assert((uint64_t)Offset < (uint64_t)TySize &&"Out of range offset");
Chris Lattneracbf6a42007-04-28 00:57:34 +00007620 }
7621
7622 NewIndices.push_back(ConstantInt::get(IntPtrTy, FirstIdx));
Chris Lattneracbf6a42007-04-28 00:57:34 +00007623
7624 // Index into the types. If we fail, set OrigBase to null.
7625 while (Offset) {
7626 if (const StructType *STy = dyn_cast<StructType>(GEPIdxTy)) {
7627 const StructLayout *SL = TD->getStructLayout(STy);
Chris Lattner234f96d2007-05-15 00:16:00 +00007628 if (Offset < (int64_t)SL->getSizeInBytes()) {
7629 unsigned Elt = SL->getElementContainingOffset(Offset);
7630 NewIndices.push_back(ConstantInt::get(Type::Int32Ty, Elt));
Chris Lattneracbf6a42007-04-28 00:57:34 +00007631
Chris Lattner234f96d2007-05-15 00:16:00 +00007632 Offset -= SL->getElementOffset(Elt);
7633 GEPIdxTy = STy->getElementType(Elt);
7634 } else {
7635 // Otherwise, we can't index into this, bail out.
7636 Offset = 0;
7637 OrigBase = 0;
7638 }
Chris Lattneracbf6a42007-04-28 00:57:34 +00007639 } else if (isa<ArrayType>(GEPIdxTy) || isa<VectorType>(GEPIdxTy)) {
7640 const SequentialType *STy = cast<SequentialType>(GEPIdxTy);
Duncan Sands44b87212007-11-01 20:53:16 +00007641 if (uint64_t EltSize = TD->getABITypeSize(STy->getElementType())){
Chris Lattner234f96d2007-05-15 00:16:00 +00007642 NewIndices.push_back(ConstantInt::get(IntPtrTy,Offset/EltSize));
7643 Offset %= EltSize;
7644 } else {
7645 NewIndices.push_back(ConstantInt::get(IntPtrTy, 0));
7646 }
Chris Lattneracbf6a42007-04-28 00:57:34 +00007647 GEPIdxTy = STy->getElementType();
7648 } else {
7649 // Otherwise, we can't index into this, bail out.
7650 Offset = 0;
7651 OrigBase = 0;
7652 }
7653 }
7654 if (OrigBase) {
7655 // If we were able to index down into an element, create the GEP
7656 // and bitcast the result. This eliminates one bitcast, potentially
7657 // two.
Gabor Greife9ecc682008-04-06 20:25:17 +00007658 Instruction *NGEP = GetElementPtrInst::Create(OrigBase,
7659 NewIndices.begin(),
7660 NewIndices.end(), "");
Chris Lattneracbf6a42007-04-28 00:57:34 +00007661 InsertNewInstBefore(NGEP, CI);
7662 NGEP->takeName(GEP);
7663
Chris Lattneracbf6a42007-04-28 00:57:34 +00007664 if (isa<BitCastInst>(CI))
7665 return new BitCastInst(NGEP, CI.getType());
7666 assert(isa<PtrToIntInst>(CI));
7667 return new PtrToIntInst(NGEP, CI.getType());
7668 }
7669 }
7670 }
7671 }
Chris Lattner1db224d2007-04-27 17:44:50 +00007672 }
7673
7674 return commonCastTransforms(CI);
7675}
7676
7677
7678
Chris Lattnerda1d04a2007-03-03 05:27:34 +00007679/// Only the TRUNC, ZEXT, SEXT, and BITCAST can both operand and result as
7680/// integer types. This function implements the common transforms for all those
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007681/// cases.
7682/// @brief Implement the transforms common to CastInst with integer operands
7683Instruction *InstCombiner::commonIntCastTransforms(CastInst &CI) {
7684 if (Instruction *Result = commonCastTransforms(CI))
7685 return Result;
7686
7687 Value *Src = CI.getOperand(0);
7688 const Type *SrcTy = Src->getType();
7689 const Type *DestTy = CI.getType();
Zhou Sheng56cda952007-04-02 08:20:41 +00007690 uint32_t SrcBitSize = SrcTy->getPrimitiveSizeInBits();
7691 uint32_t DestBitSize = DestTy->getPrimitiveSizeInBits();
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007692
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007693 // See if we can simplify any instructions used by the LHS whose sole
7694 // purpose is to compute bits we don't care about.
Reid Spencer4154e732007-03-22 20:56:53 +00007695 APInt KnownZero(DestBitSize, 0), KnownOne(DestBitSize, 0);
7696 if (SimplifyDemandedBits(&CI, APInt::getAllOnesValue(DestBitSize),
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007697 KnownZero, KnownOne))
7698 return &CI;
7699
7700 // If the source isn't an instruction or has more than one use then we
7701 // can't do anything more.
Reid Spencer266e42b2006-12-23 06:05:41 +00007702 Instruction *SrcI = dyn_cast<Instruction>(Src);
7703 if (!SrcI || !Src->hasOneUse())
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007704 return 0;
7705
Chris Lattnerda1d04a2007-03-03 05:27:34 +00007706 // Attempt to propagate the cast into the instruction for int->int casts.
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007707 int NumCastsRemoved = 0;
Chris Lattnerda1d04a2007-03-03 05:27:34 +00007708 if (!isa<BitCastInst>(CI) &&
7709 CanEvaluateInDifferentType(SrcI, cast<IntegerType>(DestTy),
Chris Lattnerb0418fc2007-08-02 06:11:14 +00007710 CI.getOpcode(), NumCastsRemoved)) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007711 // If this cast is a truncate, evaluting in a different type always
Chris Lattnerb0418fc2007-08-02 06:11:14 +00007712 // eliminates the cast, so it is always a win. If this is a zero-extension,
7713 // we need to do an AND to maintain the clear top-part of the computation,
7714 // so we require that the input have eliminated at least one cast. If this
7715 // is a sign extension, we insert two new casts (to do the extension) so we
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007716 // require that two casts have been eliminated.
Chris Lattnerda1d04a2007-03-03 05:27:34 +00007717 bool DoXForm;
7718 switch (CI.getOpcode()) {
7719 default:
7720 // All the others use floating point so we shouldn't actually
7721 // get here because of the check above.
7722 assert(0 && "Unknown cast type");
7723 case Instruction::Trunc:
7724 DoXForm = true;
7725 break;
7726 case Instruction::ZExt:
7727 DoXForm = NumCastsRemoved >= 1;
7728 break;
7729 case Instruction::SExt:
7730 DoXForm = NumCastsRemoved >= 2;
7731 break;
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007732 }
7733
7734 if (DoXForm) {
Reid Spencer74a528b2006-12-13 18:21:21 +00007735 Value *Res = EvaluateInDifferentType(SrcI, DestTy,
7736 CI.getOpcode() == Instruction::SExt);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007737 assert(Res->getType() == DestTy);
7738 switch (CI.getOpcode()) {
7739 default: assert(0 && "Unknown cast type!");
7740 case Instruction::Trunc:
7741 case Instruction::BitCast:
7742 // Just replace this cast with the result.
7743 return ReplaceInstUsesWith(CI, Res);
7744 case Instruction::ZExt: {
7745 // We need to emit an AND to clear the high bits.
7746 assert(SrcBitSize < DestBitSize && "Not a zext?");
Chris Lattner9d5aace2007-04-02 05:48:58 +00007747 Constant *C = ConstantInt::get(APInt::getLowBitsSet(DestBitSize,
7748 SrcBitSize));
Gabor Greife1f6e4b2008-05-16 19:29:10 +00007749 return BinaryOperator::CreateAnd(Res, C);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007750 }
7751 case Instruction::SExt:
7752 // We need to emit a cast to truncate, then a cast to sext.
Gabor Greife1f6e4b2008-05-16 19:29:10 +00007753 return CastInst::Create(Instruction::SExt,
Reid Spencer13bc5d72006-12-12 09:18:51 +00007754 InsertCastBefore(Instruction::Trunc, Res, Src->getType(),
7755 CI), DestTy);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007756 }
7757 }
7758 }
7759
7760 Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
7761 Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
7762
7763 switch (SrcI->getOpcode()) {
7764 case Instruction::Add:
7765 case Instruction::Mul:
7766 case Instruction::And:
7767 case Instruction::Or:
7768 case Instruction::Xor:
Chris Lattnera74deaf2007-04-03 17:43:25 +00007769 // If we are discarding information, rewrite.
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007770 if (DestBitSize <= SrcBitSize && DestBitSize != 1) {
7771 // Don't insert two casts if they cannot be eliminated. We allow
7772 // two casts to be inserted if the sizes are the same. This could
7773 // only be converting signedness, which is a noop.
7774 if (DestBitSize == SrcBitSize ||
Reid Spencer266e42b2006-12-23 06:05:41 +00007775 !ValueRequiresCast(CI.getOpcode(), Op1, DestTy,TD) ||
7776 !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
Reid Spencer2a499b02006-12-13 17:19:09 +00007777 Instruction::CastOps opcode = CI.getOpcode();
Reid Spencer13bc5d72006-12-12 09:18:51 +00007778 Value *Op0c = InsertOperandCastBefore(opcode, Op0, DestTy, SrcI);
7779 Value *Op1c = InsertOperandCastBefore(opcode, Op1, DestTy, SrcI);
Gabor Greife1f6e4b2008-05-16 19:29:10 +00007780 return BinaryOperator::Create(
Reid Spencer13bc5d72006-12-12 09:18:51 +00007781 cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007782 }
7783 }
7784
7785 // cast (xor bool X, true) to int --> xor (cast bool X to int), 1
7786 if (isa<ZExtInst>(CI) && SrcBitSize == 1 &&
7787 SrcI->getOpcode() == Instruction::Xor &&
Zhou Sheng75b871f2007-01-11 12:24:14 +00007788 Op1 == ConstantInt::getTrue() &&
Reid Spencer266e42b2006-12-23 06:05:41 +00007789 (!Op0->hasOneUse() || !isa<CmpInst>(Op0))) {
Reid Spencer13bc5d72006-12-12 09:18:51 +00007790 Value *New = InsertOperandCastBefore(Instruction::ZExt, Op0, DestTy, &CI);
Gabor Greife1f6e4b2008-05-16 19:29:10 +00007791 return BinaryOperator::CreateXor(New, ConstantInt::get(CI.getType(), 1));
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007792 }
7793 break;
7794 case Instruction::SDiv:
7795 case Instruction::UDiv:
7796 case Instruction::SRem:
7797 case Instruction::URem:
7798 // If we are just changing the sign, rewrite.
7799 if (DestBitSize == SrcBitSize) {
7800 // Don't insert two casts if they cannot be eliminated. We allow
7801 // two casts to be inserted if the sizes are the same. This could
7802 // only be converting signedness, which is a noop.
Reid Spencer266e42b2006-12-23 06:05:41 +00007803 if (!ValueRequiresCast(CI.getOpcode(), Op1, DestTy, TD) ||
7804 !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
Reid Spencer13bc5d72006-12-12 09:18:51 +00007805 Value *Op0c = InsertOperandCastBefore(Instruction::BitCast,
7806 Op0, DestTy, SrcI);
7807 Value *Op1c = InsertOperandCastBefore(Instruction::BitCast,
7808 Op1, DestTy, SrcI);
Gabor Greife1f6e4b2008-05-16 19:29:10 +00007809 return BinaryOperator::Create(
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007810 cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
7811 }
7812 }
7813 break;
7814
7815 case Instruction::Shl:
7816 // Allow changing the sign of the source operand. Do not allow
7817 // changing the size of the shift, UNLESS the shift amount is a
7818 // constant. We must not change variable sized shifts to a smaller
7819 // size, because it is undefined to shift more bits out than exist
7820 // in the value.
7821 if (DestBitSize == SrcBitSize ||
7822 (DestBitSize < SrcBitSize && isa<Constant>(Op1))) {
Reid Spencer13bc5d72006-12-12 09:18:51 +00007823 Instruction::CastOps opcode = (DestBitSize == SrcBitSize ?
7824 Instruction::BitCast : Instruction::Trunc);
7825 Value *Op0c = InsertOperandCastBefore(opcode, Op0, DestTy, SrcI);
Reid Spencer2341c222007-02-02 02:16:23 +00007826 Value *Op1c = InsertOperandCastBefore(opcode, Op1, DestTy, SrcI);
Gabor Greife1f6e4b2008-05-16 19:29:10 +00007827 return BinaryOperator::CreateShl(Op0c, Op1c);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007828 }
7829 break;
7830 case Instruction::AShr:
7831 // If this is a signed shr, and if all bits shifted in are about to be
7832 // truncated off, turn it into an unsigned shr to allow greater
7833 // simplifications.
7834 if (DestBitSize < SrcBitSize &&
7835 isa<ConstantInt>(Op1)) {
Zhou Shengfd28a332007-03-30 17:20:39 +00007836 uint32_t ShiftAmt = cast<ConstantInt>(Op1)->getLimitedValue(SrcBitSize);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007837 if (SrcBitSize > ShiftAmt && SrcBitSize-ShiftAmt >= DestBitSize) {
7838 // Insert the new logical shift right.
Gabor Greife1f6e4b2008-05-16 19:29:10 +00007839 return BinaryOperator::CreateLShr(Op0, Op1);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007840 }
7841 }
7842 break;
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007843 }
7844 return 0;
7845}
7846
Chris Lattner74ff60f2007-04-11 06:57:46 +00007847Instruction *InstCombiner::visitTrunc(TruncInst &CI) {
Chris Lattnerd747f012006-11-29 07:04:07 +00007848 if (Instruction *Result = commonIntCastTransforms(CI))
7849 return Result;
7850
7851 Value *Src = CI.getOperand(0);
7852 const Type *Ty = CI.getType();
Zhou Sheng56cda952007-04-02 08:20:41 +00007853 uint32_t DestBitWidth = Ty->getPrimitiveSizeInBits();
7854 uint32_t SrcBitWidth = cast<IntegerType>(Src->getType())->getBitWidth();
Chris Lattnerd747f012006-11-29 07:04:07 +00007855
7856 if (Instruction *SrcI = dyn_cast<Instruction>(Src)) {
7857 switch (SrcI->getOpcode()) {
7858 default: break;
7859 case Instruction::LShr:
7860 // We can shrink lshr to something smaller if we know the bits shifted in
7861 // are already zeros.
7862 if (ConstantInt *ShAmtV = dyn_cast<ConstantInt>(SrcI->getOperand(1))) {
Zhou Shengfd28a332007-03-30 17:20:39 +00007863 uint32_t ShAmt = ShAmtV->getLimitedValue(SrcBitWidth);
Chris Lattnerd747f012006-11-29 07:04:07 +00007864
7865 // Get a mask for the bits shifting in.
Zhou Sheng2777a312007-03-28 09:19:01 +00007866 APInt Mask(APInt::getLowBitsSet(SrcBitWidth, ShAmt).shl(DestBitWidth));
Reid Spencer13bc5d72006-12-12 09:18:51 +00007867 Value* SrcIOp0 = SrcI->getOperand(0);
7868 if (SrcI->hasOneUse() && MaskedValueIsZero(SrcIOp0, Mask)) {
Chris Lattnerd747f012006-11-29 07:04:07 +00007869 if (ShAmt >= DestBitWidth) // All zeros.
7870 return ReplaceInstUsesWith(CI, Constant::getNullValue(Ty));
7871
7872 // Okay, we can shrink this. Truncate the input, then return a new
7873 // shift.
Reid Spencer2341c222007-02-02 02:16:23 +00007874 Value *V1 = InsertCastBefore(Instruction::Trunc, SrcIOp0, Ty, CI);
7875 Value *V2 = InsertCastBefore(Instruction::Trunc, SrcI->getOperand(1),
7876 Ty, CI);
Gabor Greife1f6e4b2008-05-16 19:29:10 +00007877 return BinaryOperator::CreateLShr(V1, V2);
Chris Lattnerd747f012006-11-29 07:04:07 +00007878 }
Chris Lattnerc209b582006-12-05 01:26:29 +00007879 } else { // This is a variable shr.
7880
7881 // Turn 'trunc (lshr X, Y) to bool' into '(X & (1 << Y)) != 0'. This is
7882 // more LLVM instructions, but allows '1 << Y' to be hoisted if
7883 // loop-invariant and CSE'd.
Reid Spencer542964f2007-01-11 18:21:29 +00007884 if (CI.getType() == Type::Int1Ty && SrcI->hasOneUse()) {
Chris Lattnerc209b582006-12-05 01:26:29 +00007885 Value *One = ConstantInt::get(SrcI->getType(), 1);
7886
Reid Spencer2341c222007-02-02 02:16:23 +00007887 Value *V = InsertNewInstBefore(
Gabor Greife1f6e4b2008-05-16 19:29:10 +00007888 BinaryOperator::CreateShl(One, SrcI->getOperand(1),
Reid Spencer2341c222007-02-02 02:16:23 +00007889 "tmp"), CI);
Gabor Greife1f6e4b2008-05-16 19:29:10 +00007890 V = InsertNewInstBefore(BinaryOperator::CreateAnd(V,
Chris Lattnerc209b582006-12-05 01:26:29 +00007891 SrcI->getOperand(0),
7892 "tmp"), CI);
7893 Value *Zero = Constant::getNullValue(V->getType());
Reid Spencer266e42b2006-12-23 06:05:41 +00007894 return new ICmpInst(ICmpInst::ICMP_NE, V, Zero);
Chris Lattnerc209b582006-12-05 01:26:29 +00007895 }
Chris Lattnerd747f012006-11-29 07:04:07 +00007896 }
7897 break;
7898 }
7899 }
7900
7901 return 0;
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007902}
7903
Evan Chengc3cf9f82008-03-24 00:21:34 +00007904/// transformZExtICmp - Transform (zext icmp) to bitwise / integer operations
7905/// in order to eliminate the icmp.
7906Instruction *InstCombiner::transformZExtICmp(ICmpInst *ICI, Instruction &CI,
7907 bool DoXform) {
7908 // If we are just checking for a icmp eq of a single bit and zext'ing it
7909 // to an integer, then shift the bit to the appropriate place and then
7910 // cast to integer to avoid the comparison.
7911 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
7912 const APInt &Op1CV = Op1C->getValue();
7913
7914 // zext (x <s 0) to i32 --> x>>u31 true if signbit set.
7915 // zext (x >s -1) to i32 --> (x>>u31)^1 true if signbit clear.
7916 if ((ICI->getPredicate() == ICmpInst::ICMP_SLT && Op1CV == 0) ||
7917 (ICI->getPredicate() == ICmpInst::ICMP_SGT &&Op1CV.isAllOnesValue())) {
7918 if (!DoXform) return ICI;
7919
7920 Value *In = ICI->getOperand(0);
7921 Value *Sh = ConstantInt::get(In->getType(),
7922 In->getType()->getPrimitiveSizeInBits()-1);
Gabor Greife1f6e4b2008-05-16 19:29:10 +00007923 In = InsertNewInstBefore(BinaryOperator::CreateLShr(In, Sh,
Evan Chengc3cf9f82008-03-24 00:21:34 +00007924 In->getName()+".lobit"),
7925 CI);
7926 if (In->getType() != CI.getType())
Gabor Greife1f6e4b2008-05-16 19:29:10 +00007927 In = CastInst::CreateIntegerCast(In, CI.getType(),
Evan Chengc3cf9f82008-03-24 00:21:34 +00007928 false/*ZExt*/, "tmp", &CI);
7929
7930 if (ICI->getPredicate() == ICmpInst::ICMP_SGT) {
7931 Constant *One = ConstantInt::get(In->getType(), 1);
Gabor Greife1f6e4b2008-05-16 19:29:10 +00007932 In = InsertNewInstBefore(BinaryOperator::CreateXor(In, One,
Evan Chengc3cf9f82008-03-24 00:21:34 +00007933 In->getName()+".not"),
7934 CI);
7935 }
7936
7937 return ReplaceInstUsesWith(CI, In);
7938 }
7939
7940
7941
7942 // zext (X == 0) to i32 --> X^1 iff X has only the low bit set.
7943 // zext (X == 0) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
7944 // zext (X == 1) to i32 --> X iff X has only the low bit set.
7945 // zext (X == 2) to i32 --> X>>1 iff X has only the 2nd bit set.
7946 // zext (X != 0) to i32 --> X iff X has only the low bit set.
7947 // zext (X != 0) to i32 --> X>>1 iff X has only the 2nd bit set.
7948 // zext (X != 1) to i32 --> X^1 iff X has only the low bit set.
7949 // zext (X != 2) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
7950 if ((Op1CV == 0 || Op1CV.isPowerOf2()) &&
7951 // This only works for EQ and NE
7952 ICI->isEquality()) {
7953 // If Op1C some other power of two, convert:
7954 uint32_t BitWidth = Op1C->getType()->getBitWidth();
7955 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
7956 APInt TypeMask(APInt::getAllOnesValue(BitWidth));
7957 ComputeMaskedBits(ICI->getOperand(0), TypeMask, KnownZero, KnownOne);
7958
7959 APInt KnownZeroMask(~KnownZero);
7960 if (KnownZeroMask.isPowerOf2()) { // Exactly 1 possible 1?
7961 if (!DoXform) return ICI;
7962
7963 bool isNE = ICI->getPredicate() == ICmpInst::ICMP_NE;
7964 if (Op1CV != 0 && (Op1CV != KnownZeroMask)) {
7965 // (X&4) == 2 --> false
7966 // (X&4) != 2 --> true
7967 Constant *Res = ConstantInt::get(Type::Int1Ty, isNE);
7968 Res = ConstantExpr::getZExt(Res, CI.getType());
7969 return ReplaceInstUsesWith(CI, Res);
7970 }
7971
7972 uint32_t ShiftAmt = KnownZeroMask.logBase2();
7973 Value *In = ICI->getOperand(0);
7974 if (ShiftAmt) {
7975 // Perform a logical shr by shiftamt.
7976 // Insert the shift to put the result in the low bit.
Gabor Greife1f6e4b2008-05-16 19:29:10 +00007977 In = InsertNewInstBefore(BinaryOperator::CreateLShr(In,
Evan Chengc3cf9f82008-03-24 00:21:34 +00007978 ConstantInt::get(In->getType(), ShiftAmt),
7979 In->getName()+".lobit"), CI);
7980 }
7981
7982 if ((Op1CV != 0) == isNE) { // Toggle the low bit.
7983 Constant *One = ConstantInt::get(In->getType(), 1);
Gabor Greife1f6e4b2008-05-16 19:29:10 +00007984 In = BinaryOperator::CreateXor(In, One, "tmp");
Evan Chengc3cf9f82008-03-24 00:21:34 +00007985 InsertNewInstBefore(cast<Instruction>(In), CI);
7986 }
7987
7988 if (CI.getType() == In->getType())
7989 return ReplaceInstUsesWith(CI, In);
7990 else
Gabor Greife1f6e4b2008-05-16 19:29:10 +00007991 return CastInst::CreateIntegerCast(In, CI.getType(), false/*ZExt*/);
Evan Chengc3cf9f82008-03-24 00:21:34 +00007992 }
7993 }
7994 }
7995
7996 return 0;
7997}
7998
Chris Lattner74ff60f2007-04-11 06:57:46 +00007999Instruction *InstCombiner::visitZExt(ZExtInst &CI) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +00008000 // If one of the common conversion will work ..
8001 if (Instruction *Result = commonIntCastTransforms(CI))
8002 return Result;
8003
8004 Value *Src = CI.getOperand(0);
8005
8006 // If this is a cast of a cast
8007 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
Reid Spencer6c38f0b2006-11-27 01:05:10 +00008008 // If this is a TRUNC followed by a ZEXT then we are dealing with integral
8009 // types and if the sizes are just right we can convert this into a logical
8010 // 'and' which will be much cheaper than the pair of casts.
8011 if (isa<TruncInst>(CSrc)) {
8012 // Get the sizes of the types involved
8013 Value *A = CSrc->getOperand(0);
Zhou Sheng56cda952007-04-02 08:20:41 +00008014 uint32_t SrcSize = A->getType()->getPrimitiveSizeInBits();
8015 uint32_t MidSize = CSrc->getType()->getPrimitiveSizeInBits();
8016 uint32_t DstSize = CI.getType()->getPrimitiveSizeInBits();
Reid Spencer6c38f0b2006-11-27 01:05:10 +00008017 // If we're actually extending zero bits and the trunc is a no-op
8018 if (MidSize < DstSize && SrcSize == DstSize) {
8019 // Replace both of the casts with an And of the type mask.
Zhou Sheng2777a312007-03-28 09:19:01 +00008020 APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
Reid Spencer4154e732007-03-22 20:56:53 +00008021 Constant *AndConst = ConstantInt::get(AndValue);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00008022 Instruction *And =
Gabor Greife1f6e4b2008-05-16 19:29:10 +00008023 BinaryOperator::CreateAnd(CSrc->getOperand(0), AndConst);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00008024 // Unfortunately, if the type changed, we need to cast it back.
8025 if (And->getType() != CI.getType()) {
8026 And->setName(CSrc->getName()+".mask");
8027 InsertNewInstBefore(And, CI);
Gabor Greife1f6e4b2008-05-16 19:29:10 +00008028 And = CastInst::CreateIntegerCast(And, CI.getType(), false/*ZExt*/);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00008029 }
8030 return And;
8031 }
8032 }
8033 }
8034
Evan Chengc3cf9f82008-03-24 00:21:34 +00008035 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src))
8036 return transformZExtICmp(ICI, CI);
Chris Lattnerd0f79422007-04-11 06:53:04 +00008037
Evan Chengc3cf9f82008-03-24 00:21:34 +00008038 BinaryOperator *SrcI = dyn_cast<BinaryOperator>(Src);
8039 if (SrcI && SrcI->getOpcode() == Instruction::Or) {
8040 // zext (or icmp, icmp) --> or (zext icmp), (zext icmp) if at least one
8041 // of the (zext icmp) will be transformed.
8042 ICmpInst *LHS = dyn_cast<ICmpInst>(SrcI->getOperand(0));
8043 ICmpInst *RHS = dyn_cast<ICmpInst>(SrcI->getOperand(1));
8044 if (LHS && RHS && LHS->hasOneUse() && RHS->hasOneUse() &&
8045 (transformZExtICmp(LHS, CI, false) ||
8046 transformZExtICmp(RHS, CI, false))) {
8047 Value *LCast = InsertCastBefore(Instruction::ZExt, LHS, CI.getType(), CI);
8048 Value *RCast = InsertCastBefore(Instruction::ZExt, RHS, CI.getType(), CI);
Gabor Greife1f6e4b2008-05-16 19:29:10 +00008049 return BinaryOperator::Create(Instruction::Or, LCast, RCast);
Chris Lattner7ddbff02007-04-11 05:45:39 +00008050 }
Evan Chengc3cf9f82008-03-24 00:21:34 +00008051 }
8052
Reid Spencer6c38f0b2006-11-27 01:05:10 +00008053 return 0;
8054}
8055
Chris Lattner74ff60f2007-04-11 06:57:46 +00008056Instruction *InstCombiner::visitSExt(SExtInst &CI) {
Chris Lattner20f23722007-04-11 06:12:58 +00008057 if (Instruction *I = commonIntCastTransforms(CI))
8058 return I;
8059
Chris Lattner74ff60f2007-04-11 06:57:46 +00008060 Value *Src = CI.getOperand(0);
8061
Dan Gohman13cbcf1c182008-10-30 20:40:10 +00008062 // Canonicalize sign-extend from i1 to a select.
8063 if (Src->getType() == Type::Int1Ty)
8064 return SelectInst::Create(Src,
8065 ConstantInt::getAllOnesValue(CI.getType()),
8066 Constant::getNullValue(CI.getType()));
Dan Gohman81ab7532008-05-20 21:01:12 +00008067
8068 // See if the value being truncated is already sign extended. If so, just
8069 // eliminate the trunc/sext pair.
8070 if (getOpcode(Src) == Instruction::Trunc) {
8071 Value *Op = cast<User>(Src)->getOperand(0);
8072 unsigned OpBits = cast<IntegerType>(Op->getType())->getBitWidth();
8073 unsigned MidBits = cast<IntegerType>(Src->getType())->getBitWidth();
8074 unsigned DestBits = cast<IntegerType>(CI.getType())->getBitWidth();
8075 unsigned NumSignBits = ComputeNumSignBits(Op);
8076
8077 if (OpBits == DestBits) {
8078 // Op is i32, Mid is i8, and Dest is i32. If Op has more than 24 sign
8079 // bits, it is already ready.
8080 if (NumSignBits > DestBits-MidBits)
8081 return ReplaceInstUsesWith(CI, Op);
8082 } else if (OpBits < DestBits) {
8083 // Op is i32, Mid is i8, and Dest is i64. If Op has more than 24 sign
8084 // bits, just sext from i32.
8085 if (NumSignBits > OpBits-MidBits)
8086 return new SExtInst(Op, CI.getType(), "tmp");
8087 } else {
8088 // Op is i64, Mid is i8, and Dest is i32. If Op has more than 56 sign
8089 // bits, just truncate to i32.
8090 if (NumSignBits > OpBits-MidBits)
8091 return new TruncInst(Op, CI.getType(), "tmp");
8092 }
8093 }
Chris Lattnerf5b353c2008-08-06 07:35:52 +00008094
8095 // If the input is a shl/ashr pair of a same constant, then this is a sign
8096 // extension from a smaller value. If we could trust arbitrary bitwidth
8097 // integers, we could turn this into a truncate to the smaller bit and then
8098 // use a sext for the whole extension. Since we don't, look deeper and check
8099 // for a truncate. If the source and dest are the same type, eliminate the
8100 // trunc and extend and just do shifts. For example, turn:
8101 // %a = trunc i32 %i to i8
8102 // %b = shl i8 %a, 6
8103 // %c = ashr i8 %b, 6
8104 // %d = sext i8 %c to i32
8105 // into:
8106 // %a = shl i32 %i, 30
8107 // %d = ashr i32 %a, 30
8108 Value *A = 0;
8109 ConstantInt *BA = 0, *CA = 0;
8110 if (match(Src, m_AShr(m_Shl(m_Value(A), m_ConstantInt(BA)),
8111 m_ConstantInt(CA))) &&
8112 BA == CA && isa<TruncInst>(A)) {
8113 Value *I = cast<TruncInst>(A)->getOperand(0);
8114 if (I->getType() == CI.getType()) {
8115 unsigned MidSize = Src->getType()->getPrimitiveSizeInBits();
8116 unsigned SrcDstSize = CI.getType()->getPrimitiveSizeInBits();
8117 unsigned ShAmt = CA->getZExtValue()+SrcDstSize-MidSize;
8118 Constant *ShAmtV = ConstantInt::get(CI.getType(), ShAmt);
8119 I = InsertNewInstBefore(BinaryOperator::CreateShl(I, ShAmtV,
8120 CI.getName()), CI);
8121 return BinaryOperator::CreateAShr(I, ShAmtV);
8122 }
8123 }
8124
Chris Lattner20f23722007-04-11 06:12:58 +00008125 return 0;
Reid Spencer6c38f0b2006-11-27 01:05:10 +00008126}
8127
Chris Lattnerfa1e7ee2008-01-27 05:29:54 +00008128/// FitsInFPType - Return a Constant* for the specified FP constant if it fits
8129/// in the specified FP type without changing its value.
Chris Lattner3b187622008-04-20 00:41:09 +00008130static Constant *FitsInFPType(ConstantFP *CFP, const fltSemantics &Sem) {
Dale Johannesen4f0bd682008-10-09 23:00:39 +00008131 bool losesInfo;
Chris Lattnerfa1e7ee2008-01-27 05:29:54 +00008132 APFloat F = CFP->getValueAPF();
Dale Johannesen4f0bd682008-10-09 23:00:39 +00008133 (void)F.convert(Sem, APFloat::rmNearestTiesToEven, &losesInfo);
8134 if (!losesInfo)
Chris Lattner3b187622008-04-20 00:41:09 +00008135 return ConstantFP::get(F);
Chris Lattnerfa1e7ee2008-01-27 05:29:54 +00008136 return 0;
8137}
8138
8139/// LookThroughFPExtensions - If this is an fp extension instruction, look
8140/// through it until we get the source value.
8141static Value *LookThroughFPExtensions(Value *V) {
8142 if (Instruction *I = dyn_cast<Instruction>(V))
8143 if (I->getOpcode() == Instruction::FPExt)
8144 return LookThroughFPExtensions(I->getOperand(0));
8145
8146 // If this value is a constant, return the constant in the smallest FP type
8147 // that can accurately represent it. This allows us to turn
8148 // (float)((double)X+2.0) into x+2.0f.
8149 if (ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
8150 if (CFP->getType() == Type::PPC_FP128Ty)
8151 return V; // No constant folding of this.
8152 // See if the value can be truncated to float and then reextended.
Chris Lattner3b187622008-04-20 00:41:09 +00008153 if (Value *V = FitsInFPType(CFP, APFloat::IEEEsingle))
Chris Lattnerfa1e7ee2008-01-27 05:29:54 +00008154 return V;
8155 if (CFP->getType() == Type::DoubleTy)
8156 return V; // Won't shrink.
Chris Lattner3b187622008-04-20 00:41:09 +00008157 if (Value *V = FitsInFPType(CFP, APFloat::IEEEdouble))
Chris Lattnerfa1e7ee2008-01-27 05:29:54 +00008158 return V;
8159 // Don't try to shrink to various long double types.
8160 }
8161
8162 return V;
8163}
8164
8165Instruction *InstCombiner::visitFPTrunc(FPTruncInst &CI) {
8166 if (Instruction *I = commonCastTransforms(CI))
8167 return I;
8168
8169 // If we have fptrunc(add (fpextend x), (fpextend y)), where x and y are
8170 // smaller than the destination type, we can eliminate the truncate by doing
8171 // the add as the smaller type. This applies to add/sub/mul/div as well as
8172 // many builtins (sqrt, etc).
8173 BinaryOperator *OpI = dyn_cast<BinaryOperator>(CI.getOperand(0));
8174 if (OpI && OpI->hasOneUse()) {
8175 switch (OpI->getOpcode()) {
8176 default: break;
8177 case Instruction::Add:
8178 case Instruction::Sub:
8179 case Instruction::Mul:
8180 case Instruction::FDiv:
8181 case Instruction::FRem:
8182 const Type *SrcTy = OpI->getType();
8183 Value *LHSTrunc = LookThroughFPExtensions(OpI->getOperand(0));
8184 Value *RHSTrunc = LookThroughFPExtensions(OpI->getOperand(1));
8185 if (LHSTrunc->getType() != SrcTy &&
8186 RHSTrunc->getType() != SrcTy) {
8187 unsigned DstSize = CI.getType()->getPrimitiveSizeInBits();
8188 // If the source types were both smaller than the destination type of
8189 // the cast, do this xform.
8190 if (LHSTrunc->getType()->getPrimitiveSizeInBits() <= DstSize &&
8191 RHSTrunc->getType()->getPrimitiveSizeInBits() <= DstSize) {
8192 LHSTrunc = InsertCastBefore(Instruction::FPExt, LHSTrunc,
8193 CI.getType(), CI);
8194 RHSTrunc = InsertCastBefore(Instruction::FPExt, RHSTrunc,
8195 CI.getType(), CI);
Gabor Greife1f6e4b2008-05-16 19:29:10 +00008196 return BinaryOperator::Create(OpI->getOpcode(), LHSTrunc, RHSTrunc);
Chris Lattnerfa1e7ee2008-01-27 05:29:54 +00008197 }
8198 }
8199 break;
8200 }
8201 }
8202 return 0;
Reid Spencer6c38f0b2006-11-27 01:05:10 +00008203}
8204
8205Instruction *InstCombiner::visitFPExt(CastInst &CI) {
8206 return commonCastTransforms(CI);
8207}
8208
Chris Lattnere35fe0f2008-05-19 20:25:04 +00008209Instruction *InstCombiner::visitFPToUI(FPToUIInst &FI) {
Chris Lattner7bdaecb2008-08-06 05:13:06 +00008210 Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
8211 if (OpI == 0)
8212 return commonCastTransforms(FI);
8213
8214 // fptoui(uitofp(X)) --> X
8215 // fptoui(sitofp(X)) --> X
8216 // This is safe if the intermediate type has enough bits in its mantissa to
8217 // accurately represent all values of X. For example, do not do this with
8218 // i64->float->i64. This is also safe for sitofp case, because any negative
8219 // 'X' value would cause an undefined result for the fptoui.
8220 if ((isa<UIToFPInst>(OpI) || isa<SIToFPInst>(OpI)) &&
8221 OpI->getOperand(0)->getType() == FI.getType() &&
8222 (int)FI.getType()->getPrimitiveSizeInBits() < /*extra bit for sign */
8223 OpI->getType()->getFPMantissaWidth())
8224 return ReplaceInstUsesWith(FI, OpI->getOperand(0));
Chris Lattnere35fe0f2008-05-19 20:25:04 +00008225
8226 return commonCastTransforms(FI);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00008227}
8228
Chris Lattnere35fe0f2008-05-19 20:25:04 +00008229Instruction *InstCombiner::visitFPToSI(FPToSIInst &FI) {
Chris Lattner7bdaecb2008-08-06 05:13:06 +00008230 Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
8231 if (OpI == 0)
8232 return commonCastTransforms(FI);
8233
8234 // fptosi(sitofp(X)) --> X
8235 // fptosi(uitofp(X)) --> X
8236 // This is safe if the intermediate type has enough bits in its mantissa to
8237 // accurately represent all values of X. For example, do not do this with
8238 // i64->float->i64. This is also safe for sitofp case, because any negative
8239 // 'X' value would cause an undefined result for the fptoui.
8240 if ((isa<UIToFPInst>(OpI) || isa<SIToFPInst>(OpI)) &&
8241 OpI->getOperand(0)->getType() == FI.getType() &&
8242 (int)FI.getType()->getPrimitiveSizeInBits() <=
8243 OpI->getType()->getFPMantissaWidth())
8244 return ReplaceInstUsesWith(FI, OpI->getOperand(0));
Chris Lattnere35fe0f2008-05-19 20:25:04 +00008245
8246 return commonCastTransforms(FI);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00008247}
8248
8249Instruction *InstCombiner::visitUIToFP(CastInst &CI) {
8250 return commonCastTransforms(CI);
8251}
8252
8253Instruction *InstCombiner::visitSIToFP(CastInst &CI) {
8254 return commonCastTransforms(CI);
8255}
8256
8257Instruction *InstCombiner::visitPtrToInt(CastInst &CI) {
Chris Lattner1db224d2007-04-27 17:44:50 +00008258 return commonPointerCastTransforms(CI);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00008259}
8260
Chris Lattner2940c5c2008-01-08 07:23:51 +00008261Instruction *InstCombiner::visitIntToPtr(IntToPtrInst &CI) {
8262 if (Instruction *I = commonCastTransforms(CI))
8263 return I;
8264
8265 const Type *DestPointee = cast<PointerType>(CI.getType())->getElementType();
8266 if (!DestPointee->isSized()) return 0;
8267
8268 // If this is inttoptr(add (ptrtoint x), cst), try to turn this into a GEP.
8269 ConstantInt *Cst;
8270 Value *X;
8271 if (match(CI.getOperand(0), m_Add(m_Cast<PtrToIntInst>(m_Value(X)),
8272 m_ConstantInt(Cst)))) {
8273 // If the source and destination operands have the same type, see if this
8274 // is a single-index GEP.
8275 if (X->getType() == CI.getType()) {
8276 // Get the size of the pointee type.
Bill Wendling68a930b2008-03-14 05:12:19 +00008277 uint64_t Size = TD->getABITypeSize(DestPointee);
Chris Lattner2940c5c2008-01-08 07:23:51 +00008278
8279 // Convert the constant to intptr type.
8280 APInt Offset = Cst->getValue();
8281 Offset.sextOrTrunc(TD->getPointerSizeInBits());
8282
8283 // If Offset is evenly divisible by Size, we can do this xform.
8284 if (Size && !APIntOps::srem(Offset, APInt(Offset.getBitWidth(), Size))){
8285 Offset = APIntOps::sdiv(Offset, APInt(Offset.getBitWidth(), Size));
Gabor Greife9ecc682008-04-06 20:25:17 +00008286 return GetElementPtrInst::Create(X, ConstantInt::get(Offset));
Chris Lattner2940c5c2008-01-08 07:23:51 +00008287 }
8288 }
8289 // TODO: Could handle other cases, e.g. where add is indexing into field of
8290 // struct etc.
8291 } else if (CI.getOperand(0)->hasOneUse() &&
8292 match(CI.getOperand(0), m_Add(m_Value(X), m_ConstantInt(Cst)))) {
8293 // Otherwise, if this is inttoptr(add x, cst), try to turn this into an
8294 // "inttoptr+GEP" instead of "add+intptr".
8295
8296 // Get the size of the pointee type.
8297 uint64_t Size = TD->getABITypeSize(DestPointee);
8298
8299 // Convert the constant to intptr type.
8300 APInt Offset = Cst->getValue();
8301 Offset.sextOrTrunc(TD->getPointerSizeInBits());
8302
8303 // If Offset is evenly divisible by Size, we can do this xform.
8304 if (Size && !APIntOps::srem(Offset, APInt(Offset.getBitWidth(), Size))){
8305 Offset = APIntOps::sdiv(Offset, APInt(Offset.getBitWidth(), Size));
8306
8307 Instruction *P = InsertNewInstBefore(new IntToPtrInst(X, CI.getType(),
8308 "tmp"), CI);
Gabor Greife9ecc682008-04-06 20:25:17 +00008309 return GetElementPtrInst::Create(P, ConstantInt::get(Offset), "tmp");
Chris Lattner2940c5c2008-01-08 07:23:51 +00008310 }
8311 }
8312 return 0;
Reid Spencer6c38f0b2006-11-27 01:05:10 +00008313}
8314
Chris Lattner1db224d2007-04-27 17:44:50 +00008315Instruction *InstCombiner::visitBitCast(BitCastInst &CI) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +00008316 // If the operands are integer typed then apply the integer transforms,
8317 // otherwise just apply the common ones.
8318 Value *Src = CI.getOperand(0);
8319 const Type *SrcTy = Src->getType();
8320 const Type *DestTy = CI.getType();
8321
Chris Lattner03c49532007-01-15 02:27:26 +00008322 if (SrcTy->isInteger() && DestTy->isInteger()) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +00008323 if (Instruction *Result = commonIntCastTransforms(CI))
8324 return Result;
Chris Lattner1db224d2007-04-27 17:44:50 +00008325 } else if (isa<PointerType>(SrcTy)) {
8326 if (Instruction *I = commonPointerCastTransforms(CI))
8327 return I;
Reid Spencer6c38f0b2006-11-27 01:05:10 +00008328 } else {
8329 if (Instruction *Result = commonCastTransforms(CI))
8330 return Result;
8331 }
8332
8333
8334 // Get rid of casts from one type to the same type. These are useless and can
8335 // be replaced by the operand.
8336 if (DestTy == Src->getType())
8337 return ReplaceInstUsesWith(CI, Src);
8338
Reid Spencer6c38f0b2006-11-27 01:05:10 +00008339 if (const PointerType *DstPTy = dyn_cast<PointerType>(DestTy)) {
Chris Lattner1db224d2007-04-27 17:44:50 +00008340 const PointerType *SrcPTy = cast<PointerType>(SrcTy);
8341 const Type *DstElTy = DstPTy->getElementType();
8342 const Type *SrcElTy = SrcPTy->getElementType();
8343
Nate Begemanf2b0b0e2008-03-31 00:22:16 +00008344 // If the address spaces don't match, don't eliminate the bitcast, which is
8345 // required for changing types.
8346 if (SrcPTy->getAddressSpace() != DstPTy->getAddressSpace())
8347 return 0;
8348
Chris Lattner1db224d2007-04-27 17:44:50 +00008349 // If we are casting a malloc or alloca to a pointer to a type of the same
8350 // size, rewrite the allocation instruction to allocate the "right" type.
8351 if (AllocationInst *AI = dyn_cast<AllocationInst>(Src))
8352 if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
8353 return V;
8354
Chris Lattner361e9812007-05-05 22:32:24 +00008355 // If the source and destination are pointers, and this cast is equivalent
8356 // to a getelementptr X, 0, 0, 0... turn it into the appropriate gep.
Chris Lattner1db224d2007-04-27 17:44:50 +00008357 // This can enhance SROA and other transforms that want type-safe pointers.
8358 Constant *ZeroUInt = Constant::getNullValue(Type::Int32Ty);
8359 unsigned NumZeros = 0;
8360 while (SrcElTy != DstElTy &&
8361 isa<CompositeType>(SrcElTy) && !isa<PointerType>(SrcElTy) &&
8362 SrcElTy->getNumContainedTypes() /* not "{}" */) {
8363 SrcElTy = cast<CompositeType>(SrcElTy)->getTypeAtIndex(ZeroUInt);
8364 ++NumZeros;
8365 }
Chris Lattner6a4adcd2004-09-29 05:07:12 +00008366
Chris Lattner1db224d2007-04-27 17:44:50 +00008367 // If we found a path from the src to dest, create the getelementptr now.
8368 if (SrcElTy == DstElTy) {
8369 SmallVector<Value*, 8> Idxs(NumZeros+1, ZeroUInt);
Gabor Greife9ecc682008-04-06 20:25:17 +00008370 return GetElementPtrInst::Create(Src, Idxs.begin(), Idxs.end(), "",
8371 ((Instruction*) NULL));
Chris Lattnerb19a5c62006-04-12 18:09:35 +00008372 }
Reid Spencer6c38f0b2006-11-27 01:05:10 +00008373 }
Chris Lattnerdfae8be2003-07-24 17:35:25 +00008374
Reid Spencer6c38f0b2006-11-27 01:05:10 +00008375 if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(Src)) {
8376 if (SVI->hasOneUse()) {
8377 // Okay, we have (bitconvert (shuffle ..)). Check to see if this is
8378 // a bitconvert to a vector with the same # elts.
Reid Spencerd84d35b2007-02-15 02:26:10 +00008379 if (isa<VectorType>(DestTy) &&
Mon P Wang25f01062008-11-10 04:46:22 +00008380 cast<VectorType>(DestTy)->getNumElements() ==
8381 SVI->getType()->getNumElements() &&
8382 SVI->getType()->getNumElements() ==
8383 cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements()) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +00008384 CastInst *Tmp;
8385 // If either of the operands is a cast from CI.getType(), then
8386 // evaluating the shuffle in the casted destination's type will allow
8387 // us to eliminate at least one cast.
8388 if (((Tmp = dyn_cast<CastInst>(SVI->getOperand(0))) &&
8389 Tmp->getOperand(0)->getType() == DestTy) ||
8390 ((Tmp = dyn_cast<CastInst>(SVI->getOperand(1))) &&
8391 Tmp->getOperand(0)->getType() == DestTy)) {
Reid Spencer13bc5d72006-12-12 09:18:51 +00008392 Value *LHS = InsertOperandCastBefore(Instruction::BitCast,
8393 SVI->getOperand(0), DestTy, &CI);
8394 Value *RHS = InsertOperandCastBefore(Instruction::BitCast,
8395 SVI->getOperand(1), DestTy, &CI);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00008396 // Return a new shuffle vector. Use the same element ID's, as we
8397 // know the vector types match #elts.
8398 return new ShuffleVectorInst(LHS, RHS, SVI->getOperand(2));
Chris Lattner99155be2006-05-25 23:24:33 +00008399 }
8400 }
8401 }
8402 }
Chris Lattner260ab202002-04-18 17:39:14 +00008403 return 0;
Chris Lattnerca081252001-12-14 16:52:21 +00008404}
8405
Chris Lattner56e4d3d2004-04-09 23:46:01 +00008406/// GetSelectFoldableOperands - We want to turn code that looks like this:
8407/// %C = or %A, %B
8408/// %D = select %cond, %C, %A
8409/// into:
8410/// %C = select %cond, %B, 0
8411/// %D = or %A, %C
8412///
8413/// Assuming that the specified instruction is an operand to the select, return
8414/// a bitmask indicating which operands of this instruction are foldable if they
8415/// equal the other incoming value of the select.
8416///
8417static unsigned GetSelectFoldableOperands(Instruction *I) {
8418 switch (I->getOpcode()) {
8419 case Instruction::Add:
8420 case Instruction::Mul:
8421 case Instruction::And:
8422 case Instruction::Or:
8423 case Instruction::Xor:
8424 return 3; // Can fold through either operand.
8425 case Instruction::Sub: // Can only fold on the amount subtracted.
8426 case Instruction::Shl: // Can only fold on the shift amount.
Reid Spencerfdff9382006-11-08 06:47:33 +00008427 case Instruction::LShr:
8428 case Instruction::AShr:
Misha Brukmanb1c93172005-04-21 23:48:37 +00008429 return 1;
Chris Lattner56e4d3d2004-04-09 23:46:01 +00008430 default:
8431 return 0; // Cannot fold
8432 }
8433}
8434
8435/// GetSelectFoldableConstant - For the same transformation as the previous
8436/// function, return the identity constant that goes into the select.
8437static Constant *GetSelectFoldableConstant(Instruction *I) {
8438 switch (I->getOpcode()) {
8439 default: assert(0 && "This cannot happen!"); abort();
8440 case Instruction::Add:
8441 case Instruction::Sub:
8442 case Instruction::Or:
8443 case Instruction::Xor:
Chris Lattner56e4d3d2004-04-09 23:46:01 +00008444 case Instruction::Shl:
Reid Spencerfdff9382006-11-08 06:47:33 +00008445 case Instruction::LShr:
8446 case Instruction::AShr:
Reid Spencer2341c222007-02-02 02:16:23 +00008447 return Constant::getNullValue(I->getType());
Chris Lattner56e4d3d2004-04-09 23:46:01 +00008448 case Instruction::And:
Chris Lattner37338922007-06-15 06:23:19 +00008449 return Constant::getAllOnesValue(I->getType());
Chris Lattner56e4d3d2004-04-09 23:46:01 +00008450 case Instruction::Mul:
8451 return ConstantInt::get(I->getType(), 1);
8452 }
8453}
8454
Chris Lattner411336f2005-01-19 21:50:18 +00008455/// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI
8456/// have the same opcode and only one use each. Try to simplify this.
8457Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
8458 Instruction *FI) {
8459 if (TI->getNumOperands() == 1) {
8460 // If this is a non-volatile load or a cast from the same type,
8461 // merge.
Reid Spencer6c38f0b2006-11-27 01:05:10 +00008462 if (TI->isCast()) {
Chris Lattner411336f2005-01-19 21:50:18 +00008463 if (TI->getOperand(0)->getType() != FI->getOperand(0)->getType())
8464 return 0;
8465 } else {
8466 return 0; // unknown unary op.
8467 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00008468
Chris Lattner411336f2005-01-19 21:50:18 +00008469 // Fold this by inserting a select from the input values.
Gabor Greife9ecc682008-04-06 20:25:17 +00008470 SelectInst *NewSI = SelectInst::Create(SI.getCondition(), TI->getOperand(0),
8471 FI->getOperand(0), SI.getName()+".v");
Chris Lattner411336f2005-01-19 21:50:18 +00008472 InsertNewInstBefore(NewSI, SI);
Gabor Greife1f6e4b2008-05-16 19:29:10 +00008473 return CastInst::Create(Instruction::CastOps(TI->getOpcode()), NewSI,
Reid Spencer6c38f0b2006-11-27 01:05:10 +00008474 TI->getType());
Chris Lattner411336f2005-01-19 21:50:18 +00008475 }
8476
Reid Spencer2341c222007-02-02 02:16:23 +00008477 // Only handle binary operators here.
8478 if (!isa<BinaryOperator>(TI))
Chris Lattner411336f2005-01-19 21:50:18 +00008479 return 0;
8480
8481 // Figure out if the operations have any operands in common.
8482 Value *MatchOp, *OtherOpT, *OtherOpF;
8483 bool MatchIsOpZero;
8484 if (TI->getOperand(0) == FI->getOperand(0)) {
8485 MatchOp = TI->getOperand(0);
8486 OtherOpT = TI->getOperand(1);
8487 OtherOpF = FI->getOperand(1);
8488 MatchIsOpZero = true;
8489 } else if (TI->getOperand(1) == FI->getOperand(1)) {
8490 MatchOp = TI->getOperand(1);
8491 OtherOpT = TI->getOperand(0);
8492 OtherOpF = FI->getOperand(0);
8493 MatchIsOpZero = false;
8494 } else if (!TI->isCommutative()) {
8495 return 0;
8496 } else if (TI->getOperand(0) == FI->getOperand(1)) {
8497 MatchOp = TI->getOperand(0);
8498 OtherOpT = TI->getOperand(1);
8499 OtherOpF = FI->getOperand(0);
8500 MatchIsOpZero = true;
8501 } else if (TI->getOperand(1) == FI->getOperand(0)) {
8502 MatchOp = TI->getOperand(1);
8503 OtherOpT = TI->getOperand(0);
8504 OtherOpF = FI->getOperand(1);
8505 MatchIsOpZero = true;
8506 } else {
8507 return 0;
8508 }
8509
8510 // If we reach here, they do have operations in common.
Gabor Greife9ecc682008-04-06 20:25:17 +00008511 SelectInst *NewSI = SelectInst::Create(SI.getCondition(), OtherOpT,
8512 OtherOpF, SI.getName()+".v");
Chris Lattner411336f2005-01-19 21:50:18 +00008513 InsertNewInstBefore(NewSI, SI);
8514
8515 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
8516 if (MatchIsOpZero)
Gabor Greife1f6e4b2008-05-16 19:29:10 +00008517 return BinaryOperator::Create(BO->getOpcode(), MatchOp, NewSI);
Chris Lattner411336f2005-01-19 21:50:18 +00008518 else
Gabor Greife1f6e4b2008-05-16 19:29:10 +00008519 return BinaryOperator::Create(BO->getOpcode(), NewSI, MatchOp);
Chris Lattner411336f2005-01-19 21:50:18 +00008520 }
Reid Spencer2f34b982007-02-02 14:41:37 +00008521 assert(0 && "Shouldn't get here");
8522 return 0;
Chris Lattner411336f2005-01-19 21:50:18 +00008523}
8524
Dan Gohmandafa9c62008-09-16 18:46:06 +00008525/// visitSelectInstWithICmp - Visit a SelectInst that has an
8526/// ICmpInst as its first operand.
8527///
8528Instruction *InstCombiner::visitSelectInstWithICmp(SelectInst &SI,
8529 ICmpInst *ICI) {
8530 bool Changed = false;
8531 ICmpInst::Predicate Pred = ICI->getPredicate();
8532 Value *CmpLHS = ICI->getOperand(0);
8533 Value *CmpRHS = ICI->getOperand(1);
8534 Value *TrueVal = SI.getTrueValue();
8535 Value *FalseVal = SI.getFalseValue();
8536
8537 // Check cases where the comparison is with a constant that
8538 // can be adjusted to fit the min/max idiom. We may edit ICI in
8539 // place here, so make sure the select is the only user.
8540 if (ICI->hasOneUse())
Dan Gohman13cbcf1c182008-10-30 20:40:10 +00008541 if (ConstantInt *CI = dyn_cast<ConstantInt>(CmpRHS)) {
Dan Gohmandafa9c62008-09-16 18:46:06 +00008542 switch (Pred) {
8543 default: break;
8544 case ICmpInst::ICMP_ULT:
8545 case ICmpInst::ICMP_SLT: {
8546 // X < MIN ? T : F --> F
8547 if (CI->isMinValue(Pred == ICmpInst::ICMP_SLT))
8548 return ReplaceInstUsesWith(SI, FalseVal);
8549 // X < C ? X : C-1 --> X > C-1 ? C-1 : X
8550 Constant *AdjustedRHS = SubOne(CI);
8551 if ((CmpLHS == TrueVal && AdjustedRHS == FalseVal) ||
8552 (CmpLHS == FalseVal && AdjustedRHS == TrueVal)) {
8553 Pred = ICmpInst::getSwappedPredicate(Pred);
8554 CmpRHS = AdjustedRHS;
8555 std::swap(FalseVal, TrueVal);
8556 ICI->setPredicate(Pred);
8557 ICI->setOperand(1, CmpRHS);
8558 SI.setOperand(1, TrueVal);
8559 SI.setOperand(2, FalseVal);
8560 Changed = true;
8561 }
8562 break;
8563 }
8564 case ICmpInst::ICMP_UGT:
8565 case ICmpInst::ICMP_SGT: {
8566 // X > MAX ? T : F --> F
8567 if (CI->isMaxValue(Pred == ICmpInst::ICMP_SGT))
8568 return ReplaceInstUsesWith(SI, FalseVal);
8569 // X > C ? X : C+1 --> X < C+1 ? C+1 : X
8570 Constant *AdjustedRHS = AddOne(CI);
8571 if ((CmpLHS == TrueVal && AdjustedRHS == FalseVal) ||
8572 (CmpLHS == FalseVal && AdjustedRHS == TrueVal)) {
8573 Pred = ICmpInst::getSwappedPredicate(Pred);
8574 CmpRHS = AdjustedRHS;
8575 std::swap(FalseVal, TrueVal);
8576 ICI->setPredicate(Pred);
8577 ICI->setOperand(1, CmpRHS);
8578 SI.setOperand(1, TrueVal);
8579 SI.setOperand(2, FalseVal);
8580 Changed = true;
8581 }
8582 break;
8583 }
8584 }
8585
Dan Gohman13cbcf1c182008-10-30 20:40:10 +00008586 // (x <s 0) ? -1 : 0 -> ashr x, 31 -> all ones if signed
8587 // (x >s -1) ? -1 : 0 -> ashr x, 31 -> all ones if not signed
8588 CmpInst::Predicate Pred = ICI->getPredicate();
8589 if (match(TrueVal, m_ConstantInt(0)) &&
8590 match(FalseVal, m_ConstantInt(-1)))
8591 Pred = CmpInst::getInversePredicate(Pred);
8592 else if (!match(TrueVal, m_ConstantInt(-1)) ||
8593 !match(FalseVal, m_ConstantInt(0)))
8594 Pred = CmpInst::BAD_ICMP_PREDICATE;
8595 if (Pred != CmpInst::BAD_ICMP_PREDICATE) {
8596 // If we are just checking for a icmp eq of a single bit and zext'ing it
8597 // to an integer, then shift the bit to the appropriate place and then
8598 // cast to integer to avoid the comparison.
8599 const APInt &Op1CV = CI->getValue();
8600
8601 // sext (x <s 0) to i32 --> x>>s31 true if signbit set.
8602 // sext (x >s -1) to i32 --> (x>>s31)^-1 true if signbit clear.
8603 if ((Pred == ICmpInst::ICMP_SLT && Op1CV == 0) ||
8604 (Pred == ICmpInst::ICMP_SGT &&Op1CV.isAllOnesValue())) {
8605 Value *In = ICI->getOperand(0);
8606 Value *Sh = ConstantInt::get(In->getType(),
8607 In->getType()->getPrimitiveSizeInBits()-1);
8608 In = InsertNewInstBefore(BinaryOperator::CreateAShr(In, Sh,
8609 In->getName()+".lobit"),
8610 *ICI);
Dan Gohman83eea0b2008-11-02 00:17:33 +00008611 if (In->getType() != SI.getType())
8612 In = CastInst::CreateIntegerCast(In, SI.getType(),
Dan Gohman13cbcf1c182008-10-30 20:40:10 +00008613 true/*SExt*/, "tmp", ICI);
8614
8615 if (Pred == ICmpInst::ICMP_SGT)
8616 In = InsertNewInstBefore(BinaryOperator::CreateNot(In,
8617 In->getName()+".not"), *ICI);
8618
8619 return ReplaceInstUsesWith(SI, In);
8620 }
8621 }
8622 }
8623
Dan Gohmandafa9c62008-09-16 18:46:06 +00008624 if (CmpLHS == TrueVal && CmpRHS == FalseVal) {
8625 // Transform (X == Y) ? X : Y -> Y
8626 if (Pred == ICmpInst::ICMP_EQ)
8627 return ReplaceInstUsesWith(SI, FalseVal);
8628 // Transform (X != Y) ? X : Y -> X
8629 if (Pred == ICmpInst::ICMP_NE)
8630 return ReplaceInstUsesWith(SI, TrueVal);
8631 /// NOTE: if we wanted to, this is where to detect integer MIN/MAX
8632
8633 } else if (CmpLHS == FalseVal && CmpRHS == TrueVal) {
8634 // Transform (X == Y) ? Y : X -> X
8635 if (Pred == ICmpInst::ICMP_EQ)
8636 return ReplaceInstUsesWith(SI, FalseVal);
8637 // Transform (X != Y) ? Y : X -> Y
8638 if (Pred == ICmpInst::ICMP_NE)
8639 return ReplaceInstUsesWith(SI, TrueVal);
8640 /// NOTE: if we wanted to, this is where to detect integer MIN/MAX
8641 }
8642
8643 /// NOTE: if we wanted to, this is where to detect integer ABS
8644
8645 return Changed ? &SI : 0;
8646}
8647
Chris Lattnerb909e8b2004-03-12 05:52:32 +00008648Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
Chris Lattner533bc492004-03-30 19:37:13 +00008649 Value *CondVal = SI.getCondition();
8650 Value *TrueVal = SI.getTrueValue();
8651 Value *FalseVal = SI.getFalseValue();
8652
8653 // select true, X, Y -> X
8654 // select false, X, Y -> Y
Zhou Sheng75b871f2007-01-11 12:24:14 +00008655 if (ConstantInt *C = dyn_cast<ConstantInt>(CondVal))
Reid Spencercddc9df2007-01-12 04:24:46 +00008656 return ReplaceInstUsesWith(SI, C->getZExtValue() ? TrueVal : FalseVal);
Chris Lattner533bc492004-03-30 19:37:13 +00008657
8658 // select C, X, X -> X
8659 if (TrueVal == FalseVal)
8660 return ReplaceInstUsesWith(SI, TrueVal);
8661
Chris Lattner81a7a232004-10-16 18:11:37 +00008662 if (isa<UndefValue>(TrueVal)) // select C, undef, X -> X
8663 return ReplaceInstUsesWith(SI, FalseVal);
8664 if (isa<UndefValue>(FalseVal)) // select C, X, undef -> X
8665 return ReplaceInstUsesWith(SI, TrueVal);
8666 if (isa<UndefValue>(CondVal)) { // select undef, X, Y -> X or Y
8667 if (isa<Constant>(TrueVal))
8668 return ReplaceInstUsesWith(SI, TrueVal);
8669 else
8670 return ReplaceInstUsesWith(SI, FalseVal);
8671 }
8672
Reid Spencer542964f2007-01-11 18:21:29 +00008673 if (SI.getType() == Type::Int1Ty) {
Reid Spencer7a9c62b2007-01-12 07:05:14 +00008674 if (ConstantInt *C = dyn_cast<ConstantInt>(TrueVal)) {
Reid Spencercddc9df2007-01-12 04:24:46 +00008675 if (C->getZExtValue()) {
Chris Lattner1c631e82004-04-08 04:43:23 +00008676 // Change: A = select B, true, C --> A = or B, C
Gabor Greife1f6e4b2008-05-16 19:29:10 +00008677 return BinaryOperator::CreateOr(CondVal, FalseVal);
Chris Lattner1c631e82004-04-08 04:43:23 +00008678 } else {
8679 // Change: A = select B, false, C --> A = and !B, C
8680 Value *NotCond =
Gabor Greife1f6e4b2008-05-16 19:29:10 +00008681 InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
Chris Lattner1c631e82004-04-08 04:43:23 +00008682 "not."+CondVal->getName()), SI);
Gabor Greife1f6e4b2008-05-16 19:29:10 +00008683 return BinaryOperator::CreateAnd(NotCond, FalseVal);
Chris Lattner1c631e82004-04-08 04:43:23 +00008684 }
Reid Spencer7a9c62b2007-01-12 07:05:14 +00008685 } else if (ConstantInt *C = dyn_cast<ConstantInt>(FalseVal)) {
Reid Spencercddc9df2007-01-12 04:24:46 +00008686 if (C->getZExtValue() == false) {
Chris Lattner1c631e82004-04-08 04:43:23 +00008687 // Change: A = select B, C, false --> A = and B, C
Gabor Greife1f6e4b2008-05-16 19:29:10 +00008688 return BinaryOperator::CreateAnd(CondVal, TrueVal);
Chris Lattner1c631e82004-04-08 04:43:23 +00008689 } else {
8690 // Change: A = select B, C, true --> A = or !B, C
8691 Value *NotCond =
Gabor Greife1f6e4b2008-05-16 19:29:10 +00008692 InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
Chris Lattner1c631e82004-04-08 04:43:23 +00008693 "not."+CondVal->getName()), SI);
Gabor Greife1f6e4b2008-05-16 19:29:10 +00008694 return BinaryOperator::CreateOr(NotCond, TrueVal);
Chris Lattner1c631e82004-04-08 04:43:23 +00008695 }
8696 }
Chris Lattnerc00e8ad2007-11-25 21:27:53 +00008697
8698 // select a, b, a -> a&b
8699 // select a, a, b -> a|b
8700 if (CondVal == TrueVal)
Gabor Greife1f6e4b2008-05-16 19:29:10 +00008701 return BinaryOperator::CreateOr(CondVal, FalseVal);
Chris Lattnerc00e8ad2007-11-25 21:27:53 +00008702 else if (CondVal == FalseVal)
Gabor Greife1f6e4b2008-05-16 19:29:10 +00008703 return BinaryOperator::CreateAnd(CondVal, TrueVal);
Zhou Sheng75b871f2007-01-11 12:24:14 +00008704 }
Chris Lattner1c631e82004-04-08 04:43:23 +00008705
Chris Lattner183b3362004-04-09 19:05:30 +00008706 // Selecting between two integer constants?
8707 if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
8708 if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
Chris Lattner20f23722007-04-11 06:12:58 +00008709 // select C, 1, 0 -> zext C to int
Reid Spencer959a21d2007-03-23 21:24:59 +00008710 if (FalseValC->isZero() && TrueValC->getValue() == 1) {
Gabor Greife1f6e4b2008-05-16 19:29:10 +00008711 return CastInst::Create(Instruction::ZExt, CondVal, SI.getType());
Reid Spencer959a21d2007-03-23 21:24:59 +00008712 } else if (TrueValC->isZero() && FalseValC->getValue() == 1) {
Chris Lattner20f23722007-04-11 06:12:58 +00008713 // select C, 0, 1 -> zext !C to int
Chris Lattner183b3362004-04-09 19:05:30 +00008714 Value *NotCond =
Gabor Greife1f6e4b2008-05-16 19:29:10 +00008715 InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
Chris Lattnercf7baf32004-04-09 18:19:44 +00008716 "not."+CondVal->getName()), SI);
Gabor Greife1f6e4b2008-05-16 19:29:10 +00008717 return CastInst::Create(Instruction::ZExt, NotCond, SI.getType());
Chris Lattnercf7baf32004-04-09 18:19:44 +00008718 }
Chris Lattner20f23722007-04-11 06:12:58 +00008719
8720 // FIXME: Turn select 0/-1 and -1/0 into sext from condition!
Chris Lattner35167c32004-06-09 07:59:58 +00008721
Reid Spencer266e42b2006-12-23 06:05:41 +00008722 if (ICmpInst *IC = dyn_cast<ICmpInst>(SI.getCondition())) {
Chris Lattner380c7e92006-09-20 04:44:59 +00008723
Reid Spencer266e42b2006-12-23 06:05:41 +00008724 // (x <s 0) ? -1 : 0 -> ashr x, 31
Reid Spencer959a21d2007-03-23 21:24:59 +00008725 if (TrueValC->isAllOnesValue() && FalseValC->isZero())
Chris Lattner380c7e92006-09-20 04:44:59 +00008726 if (ConstantInt *CmpCst = dyn_cast<ConstantInt>(IC->getOperand(1))) {
Chris Lattner20f23722007-04-11 06:12:58 +00008727 if (IC->getPredicate() == ICmpInst::ICMP_SLT && CmpCst->isZero()) {
Chris Lattner380c7e92006-09-20 04:44:59 +00008728 // The comparison constant and the result are not neccessarily the
Reid Spencer6c38f0b2006-11-27 01:05:10 +00008729 // same width. Make an all-ones value by inserting a AShr.
Chris Lattner380c7e92006-09-20 04:44:59 +00008730 Value *X = IC->getOperand(0);
Zhou Sheng56cda952007-04-02 08:20:41 +00008731 uint32_t Bits = X->getType()->getPrimitiveSizeInBits();
Reid Spencer2341c222007-02-02 02:16:23 +00008732 Constant *ShAmt = ConstantInt::get(X->getType(), Bits-1);
Gabor Greife1f6e4b2008-05-16 19:29:10 +00008733 Instruction *SRA = BinaryOperator::Create(Instruction::AShr, X,
Reid Spencer2341c222007-02-02 02:16:23 +00008734 ShAmt, "ones");
Chris Lattner380c7e92006-09-20 04:44:59 +00008735 InsertNewInstBefore(SRA, SI);
8736
Reid Spencer6c38f0b2006-11-27 01:05:10 +00008737 // Finally, convert to the type of the select RHS. We figure out
8738 // if this requires a SExt, Trunc or BitCast based on the sizes.
8739 Instruction::CastOps opc = Instruction::BitCast;
Zhou Sheng56cda952007-04-02 08:20:41 +00008740 uint32_t SRASize = SRA->getType()->getPrimitiveSizeInBits();
8741 uint32_t SISize = SI.getType()->getPrimitiveSizeInBits();
Reid Spencer6c38f0b2006-11-27 01:05:10 +00008742 if (SRASize < SISize)
8743 opc = Instruction::SExt;
8744 else if (SRASize > SISize)
8745 opc = Instruction::Trunc;
Gabor Greife1f6e4b2008-05-16 19:29:10 +00008746 return CastInst::Create(opc, SRA, SI.getType());
Chris Lattner380c7e92006-09-20 04:44:59 +00008747 }
8748 }
8749
8750
8751 // If one of the constants is zero (we know they can't both be) and we
Chris Lattner20f23722007-04-11 06:12:58 +00008752 // have an icmp instruction with zero, and we have an 'and' with the
Chris Lattner380c7e92006-09-20 04:44:59 +00008753 // non-constant value, eliminate this whole mess. This corresponds to
8754 // cases like this: ((X & 27) ? 27 : 0)
Reid Spencer959a21d2007-03-23 21:24:59 +00008755 if (TrueValC->isZero() || FalseValC->isZero())
Chris Lattnerb3f24c92006-09-18 04:22:48 +00008756 if (IC->isEquality() && isa<ConstantInt>(IC->getOperand(1)) &&
Chris Lattner35167c32004-06-09 07:59:58 +00008757 cast<Constant>(IC->getOperand(1))->isNullValue())
8758 if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
8759 if (ICA->getOpcode() == Instruction::And &&
Misha Brukmanb1c93172005-04-21 23:48:37 +00008760 isa<ConstantInt>(ICA->getOperand(1)) &&
8761 (ICA->getOperand(1) == TrueValC ||
8762 ICA->getOperand(1) == FalseValC) &&
Chris Lattner35167c32004-06-09 07:59:58 +00008763 isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
8764 // Okay, now we know that everything is set up, we just don't
Reid Spencer266e42b2006-12-23 06:05:41 +00008765 // know whether we have a icmp_ne or icmp_eq and whether the
8766 // true or false val is the zero.
Reid Spencer959a21d2007-03-23 21:24:59 +00008767 bool ShouldNotVal = !TrueValC->isZero();
Reid Spencer266e42b2006-12-23 06:05:41 +00008768 ShouldNotVal ^= IC->getPredicate() == ICmpInst::ICMP_NE;
Chris Lattner35167c32004-06-09 07:59:58 +00008769 Value *V = ICA;
8770 if (ShouldNotVal)
Gabor Greife1f6e4b2008-05-16 19:29:10 +00008771 V = InsertNewInstBefore(BinaryOperator::Create(
Chris Lattner35167c32004-06-09 07:59:58 +00008772 Instruction::Xor, V, ICA->getOperand(1)), SI);
8773 return ReplaceInstUsesWith(SI, V);
8774 }
Chris Lattner380c7e92006-09-20 04:44:59 +00008775 }
Chris Lattner533bc492004-03-30 19:37:13 +00008776 }
Chris Lattner623fba12004-04-10 22:21:27 +00008777
8778 // See if we are selecting two values based on a comparison of the two values.
Reid Spencer266e42b2006-12-23 06:05:41 +00008779 if (FCmpInst *FCI = dyn_cast<FCmpInst>(CondVal)) {
8780 if (FCI->getOperand(0) == TrueVal && FCI->getOperand(1) == FalseVal) {
Chris Lattner623fba12004-04-10 22:21:27 +00008781 // Transform (X == Y) ? X : Y -> Y
Dale Johannesen9d559cf2007-10-03 17:45:27 +00008782 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
8783 // This is not safe in general for floating point:
8784 // consider X== -0, Y== +0.
8785 // It becomes safe if either operand is a nonzero constant.
8786 ConstantFP *CFPt, *CFPf;
8787 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
8788 !CFPt->getValueAPF().isZero()) ||
8789 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
8790 !CFPf->getValueAPF().isZero()))
Chris Lattner623fba12004-04-10 22:21:27 +00008791 return ReplaceInstUsesWith(SI, FalseVal);
Dale Johannesen9d559cf2007-10-03 17:45:27 +00008792 }
Chris Lattner623fba12004-04-10 22:21:27 +00008793 // Transform (X != Y) ? X : Y -> X
Reid Spencer266e42b2006-12-23 06:05:41 +00008794 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
Chris Lattner623fba12004-04-10 22:21:27 +00008795 return ReplaceInstUsesWith(SI, TrueVal);
Dan Gohmandafa9c62008-09-16 18:46:06 +00008796 // NOTE: if we wanted to, this is where to detect MIN/MAX
Chris Lattner623fba12004-04-10 22:21:27 +00008797
Reid Spencer266e42b2006-12-23 06:05:41 +00008798 } else if (FCI->getOperand(0) == FalseVal && FCI->getOperand(1) == TrueVal){
Chris Lattner623fba12004-04-10 22:21:27 +00008799 // Transform (X == Y) ? Y : X -> X
Dale Johannesen9d559cf2007-10-03 17:45:27 +00008800 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
8801 // This is not safe in general for floating point:
8802 // consider X== -0, Y== +0.
8803 // It becomes safe if either operand is a nonzero constant.
8804 ConstantFP *CFPt, *CFPf;
8805 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
8806 !CFPt->getValueAPF().isZero()) ||
8807 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
8808 !CFPf->getValueAPF().isZero()))
8809 return ReplaceInstUsesWith(SI, FalseVal);
8810 }
Chris Lattner623fba12004-04-10 22:21:27 +00008811 // Transform (X != Y) ? Y : X -> Y
Reid Spencer266e42b2006-12-23 06:05:41 +00008812 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
8813 return ReplaceInstUsesWith(SI, TrueVal);
Dan Gohmandafa9c62008-09-16 18:46:06 +00008814 // NOTE: if we wanted to, this is where to detect MIN/MAX
Reid Spencer266e42b2006-12-23 06:05:41 +00008815 }
Dan Gohmandafa9c62008-09-16 18:46:06 +00008816 // NOTE: if we wanted to, this is where to detect ABS
Reid Spencer266e42b2006-12-23 06:05:41 +00008817 }
8818
8819 // See if we are selecting two values based on a comparison of the two values.
Dan Gohmandafa9c62008-09-16 18:46:06 +00008820 if (ICmpInst *ICI = dyn_cast<ICmpInst>(CondVal))
8821 if (Instruction *Result = visitSelectInstWithICmp(SI, ICI))
8822 return Result;
Misha Brukmanb1c93172005-04-21 23:48:37 +00008823
Chris Lattnera04c9042005-01-13 22:52:24 +00008824 if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
8825 if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
8826 if (TI->hasOneUse() && FI->hasOneUse()) {
Chris Lattnera04c9042005-01-13 22:52:24 +00008827 Instruction *AddOp = 0, *SubOp = 0;
8828
Chris Lattner411336f2005-01-19 21:50:18 +00008829 // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
8830 if (TI->getOpcode() == FI->getOpcode())
8831 if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
8832 return IV;
8833
8834 // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))). This is
8835 // even legal for FP.
Chris Lattnera04c9042005-01-13 22:52:24 +00008836 if (TI->getOpcode() == Instruction::Sub &&
8837 FI->getOpcode() == Instruction::Add) {
8838 AddOp = FI; SubOp = TI;
8839 } else if (FI->getOpcode() == Instruction::Sub &&
8840 TI->getOpcode() == Instruction::Add) {
8841 AddOp = TI; SubOp = FI;
8842 }
8843
8844 if (AddOp) {
8845 Value *OtherAddOp = 0;
8846 if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
8847 OtherAddOp = AddOp->getOperand(1);
8848 } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
8849 OtherAddOp = AddOp->getOperand(0);
8850 }
8851
8852 if (OtherAddOp) {
Chris Lattnerb580d262006-02-24 18:05:58 +00008853 // So at this point we know we have (Y -> OtherAddOp):
8854 // select C, (add X, Y), (sub X, Z)
8855 Value *NegVal; // Compute -Z
8856 if (Constant *C = dyn_cast<Constant>(SubOp->getOperand(1))) {
8857 NegVal = ConstantExpr::getNeg(C);
8858 } else {
8859 NegVal = InsertNewInstBefore(
Gabor Greife1f6e4b2008-05-16 19:29:10 +00008860 BinaryOperator::CreateNeg(SubOp->getOperand(1), "tmp"), SI);
Chris Lattnera04c9042005-01-13 22:52:24 +00008861 }
Chris Lattnerb580d262006-02-24 18:05:58 +00008862
8863 Value *NewTrueOp = OtherAddOp;
8864 Value *NewFalseOp = NegVal;
8865 if (AddOp != TI)
8866 std::swap(NewTrueOp, NewFalseOp);
8867 Instruction *NewSel =
Gabor Greif697e94c2008-05-15 10:04:30 +00008868 SelectInst::Create(CondVal, NewTrueOp,
8869 NewFalseOp, SI.getName() + ".p");
Chris Lattnerb580d262006-02-24 18:05:58 +00008870
8871 NewSel = InsertNewInstBefore(NewSel, SI);
Gabor Greife1f6e4b2008-05-16 19:29:10 +00008872 return BinaryOperator::CreateAdd(SubOp->getOperand(0), NewSel);
Chris Lattnera04c9042005-01-13 22:52:24 +00008873 }
8874 }
8875 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00008876
Chris Lattner56e4d3d2004-04-09 23:46:01 +00008877 // See if we can fold the select into one of our operands.
Chris Lattner03c49532007-01-15 02:27:26 +00008878 if (SI.getType()->isInteger()) {
Chris Lattner56e4d3d2004-04-09 23:46:01 +00008879 // See the comment above GetSelectFoldableOperands for a description of the
8880 // transformation we are doing here.
8881 if (Instruction *TVI = dyn_cast<Instruction>(TrueVal))
8882 if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
8883 !isa<Constant>(FalseVal))
8884 if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
8885 unsigned OpToFold = 0;
8886 if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
8887 OpToFold = 1;
8888 } else if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
8889 OpToFold = 2;
8890 }
8891
8892 if (OpToFold) {
8893 Constant *C = GetSelectFoldableConstant(TVI);
Chris Lattner56e4d3d2004-04-09 23:46:01 +00008894 Instruction *NewSel =
Gabor Greif697e94c2008-05-15 10:04:30 +00008895 SelectInst::Create(SI.getCondition(),
8896 TVI->getOperand(2-OpToFold), C);
Chris Lattner56e4d3d2004-04-09 23:46:01 +00008897 InsertNewInstBefore(NewSel, SI);
Chris Lattner6e0123b2007-02-11 01:23:03 +00008898 NewSel->takeName(TVI);
Chris Lattner56e4d3d2004-04-09 23:46:01 +00008899 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
Gabor Greife1f6e4b2008-05-16 19:29:10 +00008900 return BinaryOperator::Create(BO->getOpcode(), FalseVal, NewSel);
Chris Lattner56e4d3d2004-04-09 23:46:01 +00008901 else {
8902 assert(0 && "Unknown instruction!!");
8903 }
8904 }
8905 }
Chris Lattner6862fbd2004-09-29 17:40:11 +00008906
Chris Lattner56e4d3d2004-04-09 23:46:01 +00008907 if (Instruction *FVI = dyn_cast<Instruction>(FalseVal))
8908 if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
8909 !isa<Constant>(TrueVal))
8910 if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
8911 unsigned OpToFold = 0;
8912 if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
8913 OpToFold = 1;
8914 } else if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
8915 OpToFold = 2;
8916 }
8917
8918 if (OpToFold) {
8919 Constant *C = GetSelectFoldableConstant(FVI);
Chris Lattner56e4d3d2004-04-09 23:46:01 +00008920 Instruction *NewSel =
Gabor Greif697e94c2008-05-15 10:04:30 +00008921 SelectInst::Create(SI.getCondition(), C,
8922 FVI->getOperand(2-OpToFold));
Chris Lattner56e4d3d2004-04-09 23:46:01 +00008923 InsertNewInstBefore(NewSel, SI);
Chris Lattner6e0123b2007-02-11 01:23:03 +00008924 NewSel->takeName(FVI);
Chris Lattner56e4d3d2004-04-09 23:46:01 +00008925 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
Gabor Greife1f6e4b2008-05-16 19:29:10 +00008926 return BinaryOperator::Create(BO->getOpcode(), TrueVal, NewSel);
Reid Spencer2341c222007-02-02 02:16:23 +00008927 else
Chris Lattner56e4d3d2004-04-09 23:46:01 +00008928 assert(0 && "Unknown instruction!!");
Chris Lattner56e4d3d2004-04-09 23:46:01 +00008929 }
8930 }
8931 }
Chris Lattnerd6f636a2005-04-24 07:30:14 +00008932
8933 if (BinaryOperator::isNot(CondVal)) {
8934 SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
8935 SI.setOperand(1, FalseVal);
8936 SI.setOperand(2, TrueVal);
8937 return &SI;
8938 }
8939
Chris Lattnerb909e8b2004-03-12 05:52:32 +00008940 return 0;
8941}
8942
Dan Gohman99b7b3f2008-04-10 18:43:06 +00008943/// EnforceKnownAlignment - If the specified pointer points to an object that
8944/// we control, modify the object's alignment to PrefAlign. This isn't
8945/// often possible though. If alignment is important, a more reliable approach
8946/// is to simply align all global variables and allocation instructions to
8947/// their preferred alignment from the beginning.
8948///
8949static unsigned EnforceKnownAlignment(Value *V,
8950 unsigned Align, unsigned PrefAlign) {
Chris Lattnera8e4b4b2007-08-09 19:05:49 +00008951
Dan Gohman99b7b3f2008-04-10 18:43:06 +00008952 User *U = dyn_cast<User>(V);
8953 if (!U) return Align;
8954
8955 switch (getOpcode(U)) {
8956 default: break;
8957 case Instruction::BitCast:
8958 return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
8959 case Instruction::GetElementPtr: {
Chris Lattner82f2ef22006-03-06 20:18:44 +00008960 // If all indexes are zero, it is just the alignment of the base pointer.
8961 bool AllZeroOperands = true;
Gabor Greif431e9562008-06-12 21:51:29 +00008962 for (User::op_iterator i = U->op_begin() + 1, e = U->op_end(); i != e; ++i)
Gabor Greiff6d8e772008-06-12 21:37:33 +00008963 if (!isa<Constant>(*i) ||
8964 !cast<Constant>(*i)->isNullValue()) {
Chris Lattner82f2ef22006-03-06 20:18:44 +00008965 AllZeroOperands = false;
8966 break;
8967 }
Chris Lattnera8e4b4b2007-08-09 19:05:49 +00008968
8969 if (AllZeroOperands) {
8970 // Treat this like a bitcast.
Dan Gohman99b7b3f2008-04-10 18:43:06 +00008971 return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
Chris Lattnera8e4b4b2007-08-09 19:05:49 +00008972 }
Dan Gohman99b7b3f2008-04-10 18:43:06 +00008973 break;
Chris Lattner82f2ef22006-03-06 20:18:44 +00008974 }
Dan Gohman99b7b3f2008-04-10 18:43:06 +00008975 }
8976
8977 if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
8978 // If there is a large requested alignment and we can, bump up the alignment
8979 // of the global.
8980 if (!GV->isDeclaration()) {
8981 GV->setAlignment(PrefAlign);
8982 Align = PrefAlign;
8983 }
8984 } else if (AllocationInst *AI = dyn_cast<AllocationInst>(V)) {
8985 // If there is a requested alignment and if this is an alloca, round up. We
8986 // don't do this for malloc, because some systems can't respect the request.
8987 if (isa<AllocaInst>(AI)) {
8988 AI->setAlignment(PrefAlign);
8989 Align = PrefAlign;
8990 }
8991 }
8992
8993 return Align;
8994}
8995
8996/// GetOrEnforceKnownAlignment - If the specified pointer has an alignment that
8997/// we can determine, return it, otherwise return 0. If PrefAlign is specified,
8998/// and it is more than the alignment of the ultimate object, see if we can
8999/// increase the alignment of the ultimate object, making this check succeed.
9000unsigned InstCombiner::GetOrEnforceKnownAlignment(Value *V,
9001 unsigned PrefAlign) {
9002 unsigned BitWidth = TD ? TD->getTypeSizeInBits(V->getType()) :
9003 sizeof(PrefAlign) * CHAR_BIT;
9004 APInt Mask = APInt::getAllOnesValue(BitWidth);
9005 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
9006 ComputeMaskedBits(V, Mask, KnownZero, KnownOne);
9007 unsigned TrailZ = KnownZero.countTrailingOnes();
9008 unsigned Align = 1u << std::min(BitWidth - 1, TrailZ);
9009
9010 if (PrefAlign > Align)
9011 Align = EnforceKnownAlignment(V, Align, PrefAlign);
9012
9013 // We don't need to make any adjustment.
9014 return Align;
Chris Lattner82f2ef22006-03-06 20:18:44 +00009015}
9016
Chris Lattner57974c82008-01-13 23:50:23 +00009017Instruction *InstCombiner::SimplifyMemTransfer(MemIntrinsic *MI) {
Dan Gohman99b7b3f2008-04-10 18:43:06 +00009018 unsigned DstAlign = GetOrEnforceKnownAlignment(MI->getOperand(1));
9019 unsigned SrcAlign = GetOrEnforceKnownAlignment(MI->getOperand(2));
Chris Lattner57974c82008-01-13 23:50:23 +00009020 unsigned MinAlign = std::min(DstAlign, SrcAlign);
9021 unsigned CopyAlign = MI->getAlignment()->getZExtValue();
9022
9023 if (CopyAlign < MinAlign) {
9024 MI->setAlignment(ConstantInt::get(Type::Int32Ty, MinAlign));
9025 return MI;
9026 }
9027
9028 // If MemCpyInst length is 1/2/4/8 bytes then replace memcpy with
9029 // load/store.
9030 ConstantInt *MemOpLength = dyn_cast<ConstantInt>(MI->getOperand(3));
9031 if (MemOpLength == 0) return 0;
9032
Chris Lattner92bd7852008-01-14 00:28:35 +00009033 // Source and destination pointer types are always "i8*" for intrinsic. See
9034 // if the size is something we can handle with a single primitive load/store.
9035 // A single load+store correctly handles overlapping memory in the memmove
9036 // case.
Chris Lattner57974c82008-01-13 23:50:23 +00009037 unsigned Size = MemOpLength->getZExtValue();
Chris Lattner2dc44262008-04-30 06:39:11 +00009038 if (Size == 0) return MI; // Delete this mem transfer.
9039
9040 if (Size > 8 || (Size&(Size-1)))
Chris Lattner92bd7852008-01-14 00:28:35 +00009041 return 0; // If not 1/2/4/8 bytes, exit.
Chris Lattner57974c82008-01-13 23:50:23 +00009042
Chris Lattner92bd7852008-01-14 00:28:35 +00009043 // Use an integer load+store unless we can find something better.
Chris Lattner57974c82008-01-13 23:50:23 +00009044 Type *NewPtrTy = PointerType::getUnqual(IntegerType::get(Size<<3));
Chris Lattner92bd7852008-01-14 00:28:35 +00009045
9046 // Memcpy forces the use of i8* for the source and destination. That means
9047 // that if you're using memcpy to move one double around, you'll get a cast
9048 // from double* to i8*. We'd much rather use a double load+store rather than
9049 // an i64 load+store, here because this improves the odds that the source or
9050 // dest address will be promotable. See if we can find a better type than the
9051 // integer datatype.
9052 if (Value *Op = getBitCastOperand(MI->getOperand(1))) {
9053 const Type *SrcETy = cast<PointerType>(Op->getType())->getElementType();
9054 if (SrcETy->isSized() && TD->getTypeStoreSize(SrcETy) == Size) {
9055 // The SrcETy might be something like {{{double}}} or [1 x double]. Rip
9056 // down through these levels if so.
Dan Gohman53b26982008-05-23 01:52:21 +00009057 while (!SrcETy->isSingleValueType()) {
Chris Lattner92bd7852008-01-14 00:28:35 +00009058 if (const StructType *STy = dyn_cast<StructType>(SrcETy)) {
9059 if (STy->getNumElements() == 1)
9060 SrcETy = STy->getElementType(0);
9061 else
9062 break;
9063 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcETy)) {
9064 if (ATy->getNumElements() == 1)
9065 SrcETy = ATy->getElementType();
9066 else
9067 break;
9068 } else
9069 break;
9070 }
9071
Dan Gohman53b26982008-05-23 01:52:21 +00009072 if (SrcETy->isSingleValueType())
Chris Lattner92bd7852008-01-14 00:28:35 +00009073 NewPtrTy = PointerType::getUnqual(SrcETy);
9074 }
9075 }
9076
9077
Chris Lattner57974c82008-01-13 23:50:23 +00009078 // If the memcpy/memmove provides better alignment info than we can
9079 // infer, use it.
9080 SrcAlign = std::max(SrcAlign, CopyAlign);
9081 DstAlign = std::max(DstAlign, CopyAlign);
9082
9083 Value *Src = InsertBitCastBefore(MI->getOperand(2), NewPtrTy, *MI);
9084 Value *Dest = InsertBitCastBefore(MI->getOperand(1), NewPtrTy, *MI);
Chris Lattner92bd7852008-01-14 00:28:35 +00009085 Instruction *L = new LoadInst(Src, "tmp", false, SrcAlign);
9086 InsertNewInstBefore(L, *MI);
9087 InsertNewInstBefore(new StoreInst(L, Dest, false, DstAlign), *MI);
9088
9089 // Set the size of the copy to 0, it will be deleted on the next iteration.
9090 MI->setOperand(3, Constant::getNullValue(MemOpLength->getType()));
9091 return MI;
Chris Lattner57974c82008-01-13 23:50:23 +00009092}
Chris Lattnerb909e8b2004-03-12 05:52:32 +00009093
Chris Lattner2dc44262008-04-30 06:39:11 +00009094Instruction *InstCombiner::SimplifyMemSet(MemSetInst *MI) {
9095 unsigned Alignment = GetOrEnforceKnownAlignment(MI->getDest());
9096 if (MI->getAlignment()->getZExtValue() < Alignment) {
9097 MI->setAlignment(ConstantInt::get(Type::Int32Ty, Alignment));
9098 return MI;
9099 }
9100
9101 // Extract the length and alignment and fill if they are constant.
9102 ConstantInt *LenC = dyn_cast<ConstantInt>(MI->getLength());
9103 ConstantInt *FillC = dyn_cast<ConstantInt>(MI->getValue());
9104 if (!LenC || !FillC || FillC->getType() != Type::Int8Ty)
9105 return 0;
9106 uint64_t Len = LenC->getZExtValue();
9107 Alignment = MI->getAlignment()->getZExtValue();
9108
9109 // If the length is zero, this is a no-op
9110 if (Len == 0) return MI; // memset(d,c,0,a) -> noop
9111
9112 // memset(s,c,n) -> store s, c (for n=1,2,4,8)
9113 if (Len <= 8 && isPowerOf2_32((uint32_t)Len)) {
9114 const Type *ITy = IntegerType::get(Len*8); // n=1 -> i8.
9115
9116 Value *Dest = MI->getDest();
9117 Dest = InsertBitCastBefore(Dest, PointerType::getUnqual(ITy), *MI);
9118
9119 // Alignment 0 is identity for alignment 1 for memset, but not store.
9120 if (Alignment == 0) Alignment = 1;
9121
9122 // Extract the fill value and store.
9123 uint64_t Fill = FillC->getZExtValue()*0x0101010101010101ULL;
9124 InsertNewInstBefore(new StoreInst(ConstantInt::get(ITy, Fill), Dest, false,
9125 Alignment), *MI);
9126
9127 // Set the size of the copy to 0, it will be deleted on the next iteration.
9128 MI->setLength(Constant::getNullValue(LenC->getType()));
9129 return MI;
9130 }
9131
9132 return 0;
9133}
9134
9135
Chris Lattnerc66b2232006-01-13 20:11:04 +00009136/// visitCallInst - CallInst simplification. This mostly only handles folding
9137/// of intrinsic instructions. For normal calls, it allows visitCallSite to do
9138/// the heavy lifting.
9139///
Chris Lattner970c33a2003-06-19 17:00:31 +00009140Instruction *InstCombiner::visitCallInst(CallInst &CI) {
Chris Lattnerc66b2232006-01-13 20:11:04 +00009141 IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
9142 if (!II) return visitCallSite(&CI);
9143
Chris Lattner51ea1272004-02-28 05:22:00 +00009144 // Intrinsics cannot occur in an invoke, so handle them here instead of in
9145 // visitCallSite.
Chris Lattnerc66b2232006-01-13 20:11:04 +00009146 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
Chris Lattner00648e12004-10-12 04:52:52 +00009147 bool Changed = false;
9148
9149 // memmove/cpy/set of zero bytes is a noop.
9150 if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
9151 if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
9152
Chris Lattner00648e12004-10-12 04:52:52 +00009153 if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
Reid Spencere0fc4df2006-10-20 07:07:24 +00009154 if (CI->getZExtValue() == 1) {
Chris Lattner00648e12004-10-12 04:52:52 +00009155 // Replace the instruction with just byte operations. We would
9156 // transform other cases to loads/stores, but we don't know if
9157 // alignment is sufficient.
9158 }
Chris Lattner51ea1272004-02-28 05:22:00 +00009159 }
9160
Chris Lattner00648e12004-10-12 04:52:52 +00009161 // If we have a memmove and the source operation is a constant global,
9162 // then the source and dest pointers can't alias, so we can change this
9163 // into a call to memcpy.
Chris Lattner57974c82008-01-13 23:50:23 +00009164 if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(MI)) {
Chris Lattner00648e12004-10-12 04:52:52 +00009165 if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
9166 if (GVSrc->isConstant()) {
9167 Module *M = CI.getParent()->getParent()->getParent();
Chris Lattner5a866122008-01-13 22:23:22 +00009168 Intrinsic::ID MemCpyID;
9169 if (CI.getOperand(3)->getType() == Type::Int32Ty)
9170 MemCpyID = Intrinsic::memcpy_i32;
Chris Lattner681ef2f2006-03-03 01:34:17 +00009171 else
Chris Lattner5a866122008-01-13 22:23:22 +00009172 MemCpyID = Intrinsic::memcpy_i64;
9173 CI.setOperand(0, Intrinsic::getDeclaration(M, MemCpyID));
Chris Lattner00648e12004-10-12 04:52:52 +00009174 Changed = true;
9175 }
Chris Lattnerecdefb52008-05-28 05:30:41 +00009176
9177 // memmove(x,x,size) -> noop.
9178 if (MMI->getSource() == MMI->getDest())
9179 return EraseInstFromFunction(CI);
Chris Lattner82f2ef22006-03-06 20:18:44 +00009180 }
Chris Lattner00648e12004-10-12 04:52:52 +00009181
Chris Lattner82f2ef22006-03-06 20:18:44 +00009182 // If we can determine a pointer alignment that is bigger than currently
9183 // set, update the alignment.
9184 if (isa<MemCpyInst>(MI) || isa<MemMoveInst>(MI)) {
Chris Lattner57974c82008-01-13 23:50:23 +00009185 if (Instruction *I = SimplifyMemTransfer(MI))
9186 return I;
Chris Lattner2dc44262008-04-30 06:39:11 +00009187 } else if (MemSetInst *MSI = dyn_cast<MemSetInst>(MI)) {
9188 if (Instruction *I = SimplifyMemSet(MSI))
9189 return I;
Chris Lattner82f2ef22006-03-06 20:18:44 +00009190 }
9191
Chris Lattnerc66b2232006-01-13 20:11:04 +00009192 if (Changed) return II;
Chris Lattneref36dcd2008-06-18 04:33:20 +00009193 }
9194
9195 switch (II->getIntrinsicID()) {
9196 default: break;
9197 case Intrinsic::bswap:
9198 // bswap(bswap(x)) -> x
9199 if (IntrinsicInst *Operand = dyn_cast<IntrinsicInst>(II->getOperand(1)))
9200 if (Operand->getIntrinsicID() == Intrinsic::bswap)
9201 return ReplaceInstUsesWith(CI, Operand->getOperand(1));
9202 break;
9203 case Intrinsic::ppc_altivec_lvx:
9204 case Intrinsic::ppc_altivec_lvxl:
9205 case Intrinsic::x86_sse_loadu_ps:
9206 case Intrinsic::x86_sse2_loadu_pd:
9207 case Intrinsic::x86_sse2_loadu_dq:
9208 // Turn PPC lvx -> load if the pointer is known aligned.
9209 // Turn X86 loadups -> load if the pointer is known aligned.
9210 if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
9211 Value *Ptr = InsertBitCastBefore(II->getOperand(1),
9212 PointerType::getUnqual(II->getType()),
9213 CI);
9214 return new LoadInst(Ptr);
Chris Lattner2deeaea2006-10-05 06:55:50 +00009215 }
Chris Lattneref36dcd2008-06-18 04:33:20 +00009216 break;
9217 case Intrinsic::ppc_altivec_stvx:
9218 case Intrinsic::ppc_altivec_stvxl:
9219 // Turn stvx -> store if the pointer is known aligned.
9220 if (GetOrEnforceKnownAlignment(II->getOperand(2), 16) >= 16) {
9221 const Type *OpPtrTy =
9222 PointerType::getUnqual(II->getOperand(1)->getType());
9223 Value *Ptr = InsertBitCastBefore(II->getOperand(2), OpPtrTy, CI);
9224 return new StoreInst(II->getOperand(1), Ptr);
9225 }
9226 break;
9227 case Intrinsic::x86_sse_storeu_ps:
9228 case Intrinsic::x86_sse2_storeu_pd:
9229 case Intrinsic::x86_sse2_storeu_dq:
Chris Lattneref36dcd2008-06-18 04:33:20 +00009230 // Turn X86 storeu -> store if the pointer is known aligned.
9231 if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
9232 const Type *OpPtrTy =
9233 PointerType::getUnqual(II->getOperand(2)->getType());
9234 Value *Ptr = InsertBitCastBefore(II->getOperand(1), OpPtrTy, CI);
9235 return new StoreInst(II->getOperand(2), Ptr);
9236 }
9237 break;
9238
9239 case Intrinsic::x86_sse_cvttss2si: {
9240 // These intrinsics only demands the 0th element of its input vector. If
9241 // we can simplify the input based on that, do so now.
9242 uint64_t UndefElts;
9243 if (Value *V = SimplifyDemandedVectorElts(II->getOperand(1), 1,
9244 UndefElts)) {
9245 II->setOperand(1, V);
9246 return II;
9247 }
9248 break;
9249 }
9250
9251 case Intrinsic::ppc_altivec_vperm:
9252 // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant.
9253 if (ConstantVector *Mask = dyn_cast<ConstantVector>(II->getOperand(3))) {
9254 assert(Mask->getNumOperands() == 16 && "Bad type for intrinsic!");
Chris Lattner2deeaea2006-10-05 06:55:50 +00009255
Chris Lattneref36dcd2008-06-18 04:33:20 +00009256 // Check that all of the elements are integer constants or undefs.
9257 bool AllEltsOk = true;
9258 for (unsigned i = 0; i != 16; ++i) {
9259 if (!isa<ConstantInt>(Mask->getOperand(i)) &&
9260 !isa<UndefValue>(Mask->getOperand(i))) {
9261 AllEltsOk = false;
9262 break;
9263 }
9264 }
9265
9266 if (AllEltsOk) {
9267 // Cast the input vectors to byte vectors.
9268 Value *Op0 =InsertBitCastBefore(II->getOperand(1),Mask->getType(),CI);
9269 Value *Op1 =InsertBitCastBefore(II->getOperand(2),Mask->getType(),CI);
9270 Value *Result = UndefValue::get(Op0->getType());
Chris Lattnere79d2492006-04-06 19:19:17 +00009271
Chris Lattneref36dcd2008-06-18 04:33:20 +00009272 // Only extract each element once.
9273 Value *ExtractedElts[32];
9274 memset(ExtractedElts, 0, sizeof(ExtractedElts));
9275
Chris Lattnere79d2492006-04-06 19:19:17 +00009276 for (unsigned i = 0; i != 16; ++i) {
Chris Lattneref36dcd2008-06-18 04:33:20 +00009277 if (isa<UndefValue>(Mask->getOperand(i)))
9278 continue;
9279 unsigned Idx=cast<ConstantInt>(Mask->getOperand(i))->getZExtValue();
9280 Idx &= 31; // Match the hardware behavior.
9281
9282 if (ExtractedElts[Idx] == 0) {
9283 Instruction *Elt =
9284 new ExtractElementInst(Idx < 16 ? Op0 : Op1, Idx&15, "tmp");
9285 InsertNewInstBefore(Elt, CI);
9286 ExtractedElts[Idx] = Elt;
Chris Lattnere79d2492006-04-06 19:19:17 +00009287 }
Chris Lattnere79d2492006-04-06 19:19:17 +00009288
Chris Lattneref36dcd2008-06-18 04:33:20 +00009289 // Insert this value into the result vector.
9290 Result = InsertElementInst::Create(Result, ExtractedElts[Idx],
9291 i, "tmp");
9292 InsertNewInstBefore(cast<Instruction>(Result), CI);
Chris Lattnere79d2492006-04-06 19:19:17 +00009293 }
Chris Lattneref36dcd2008-06-18 04:33:20 +00009294 return CastInst::Create(Instruction::BitCast, Result, CI.getType());
Chris Lattnere79d2492006-04-06 19:19:17 +00009295 }
Chris Lattneref36dcd2008-06-18 04:33:20 +00009296 }
9297 break;
Chris Lattnere79d2492006-04-06 19:19:17 +00009298
Chris Lattneref36dcd2008-06-18 04:33:20 +00009299 case Intrinsic::stackrestore: {
9300 // If the save is right next to the restore, remove the restore. This can
9301 // happen when variable allocas are DCE'd.
9302 if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getOperand(1))) {
9303 if (SS->getIntrinsicID() == Intrinsic::stacksave) {
9304 BasicBlock::iterator BI = SS;
9305 if (&*++BI == II)
9306 return EraseInstFromFunction(CI);
Chris Lattner503221f2006-01-13 21:28:09 +00009307 }
Chris Lattneref36dcd2008-06-18 04:33:20 +00009308 }
9309
9310 // Scan down this block to see if there is another stack restore in the
9311 // same block without an intervening call/alloca.
9312 BasicBlock::iterator BI = II;
9313 TerminatorInst *TI = II->getParent()->getTerminator();
9314 bool CannotRemove = false;
9315 for (++BI; &*BI != TI; ++BI) {
9316 if (isa<AllocaInst>(BI)) {
9317 CannotRemove = true;
9318 break;
9319 }
Chris Lattnerc9c81fb2008-06-25 05:59:28 +00009320 if (CallInst *BCI = dyn_cast<CallInst>(BI)) {
9321 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(BCI)) {
9322 // If there is a stackrestore below this one, remove this one.
9323 if (II->getIntrinsicID() == Intrinsic::stackrestore)
9324 return EraseInstFromFunction(CI);
9325 // Otherwise, ignore the intrinsic.
9326 } else {
9327 // If we found a non-intrinsic call, we can't remove the stack
9328 // restore.
Chris Lattner024f8c82008-02-18 06:12:38 +00009329 CannotRemove = true;
9330 break;
9331 }
Chris Lattneref36dcd2008-06-18 04:33:20 +00009332 }
Chris Lattner503221f2006-01-13 21:28:09 +00009333 }
Chris Lattneref36dcd2008-06-18 04:33:20 +00009334
9335 // If the stack restore is in a return/unwind block and if there are no
9336 // allocas or calls between the restore and the return, nuke the restore.
9337 if (!CannotRemove && (isa<ReturnInst>(TI) || isa<UnwindInst>(TI)))
9338 return EraseInstFromFunction(CI);
9339 break;
9340 }
Chris Lattner00648e12004-10-12 04:52:52 +00009341 }
9342
Chris Lattnerc66b2232006-01-13 20:11:04 +00009343 return visitCallSite(II);
Chris Lattner970c33a2003-06-19 17:00:31 +00009344}
9345
9346// InvokeInst simplification
9347//
9348Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
Chris Lattneraec3d942003-10-07 22:32:43 +00009349 return visitCallSite(&II);
Chris Lattner970c33a2003-06-19 17:00:31 +00009350}
9351
Dale Johannesen0d1d3df2008-04-25 21:16:07 +00009352/// isSafeToEliminateVarargsCast - If this cast does not affect the value
9353/// passed through the varargs area, we can eliminate the use of the cast.
Dale Johannesenf6e15a42008-04-23 18:34:37 +00009354static bool isSafeToEliminateVarargsCast(const CallSite CS,
9355 const CastInst * const CI,
9356 const TargetData * const TD,
9357 const int ix) {
9358 if (!CI->isLosslessCast())
9359 return false;
9360
9361 // The size of ByVal arguments is derived from the type, so we
9362 // can't change to a type with a different size. If the size were
9363 // passed explicitly we could avoid this check.
Devang Patel4c758ea2008-09-25 21:00:45 +00009364 if (!CS.paramHasAttr(ix, Attribute::ByVal))
Dale Johannesenf6e15a42008-04-23 18:34:37 +00009365 return true;
9366
9367 const Type* SrcTy =
9368 cast<PointerType>(CI->getOperand(0)->getType())->getElementType();
9369 const Type* DstTy = cast<PointerType>(CI->getType())->getElementType();
9370 if (!SrcTy->isSized() || !DstTy->isSized())
9371 return false;
9372 if (TD->getABITypeSize(SrcTy) != TD->getABITypeSize(DstTy))
9373 return false;
9374 return true;
9375}
9376
Chris Lattneraec3d942003-10-07 22:32:43 +00009377// visitCallSite - Improvements for call and invoke instructions.
9378//
9379Instruction *InstCombiner::visitCallSite(CallSite CS) {
Chris Lattner75b4d1d2003-10-07 22:54:13 +00009380 bool Changed = false;
9381
9382 // If the callee is a constexpr cast of a function, attempt to move the cast
9383 // to the arguments of the call/invoke.
Chris Lattneraec3d942003-10-07 22:32:43 +00009384 if (transformConstExprCastCall(CS)) return 0;
9385
Chris Lattner75b4d1d2003-10-07 22:54:13 +00009386 Value *Callee = CS.getCalledValue();
Chris Lattner81a7a232004-10-16 18:11:37 +00009387
Chris Lattner61d9d812005-05-13 07:09:09 +00009388 if (Function *CalleeF = dyn_cast<Function>(Callee))
9389 if (CalleeF->getCallingConv() != CS.getCallingConv()) {
9390 Instruction *OldCall = CS.getInstruction();
9391 // If the call and callee calling conventions don't match, this call must
9392 // be unreachable, as the call is undefined.
Zhou Sheng75b871f2007-01-11 12:24:14 +00009393 new StoreInst(ConstantInt::getTrue(),
Christopher Lambedf07882007-12-17 01:12:55 +00009394 UndefValue::get(PointerType::getUnqual(Type::Int1Ty)),
9395 OldCall);
Chris Lattner61d9d812005-05-13 07:09:09 +00009396 if (!OldCall->use_empty())
9397 OldCall->replaceAllUsesWith(UndefValue::get(OldCall->getType()));
9398 if (isa<CallInst>(OldCall)) // Not worth removing an invoke here.
9399 return EraseInstFromFunction(*OldCall);
9400 return 0;
9401 }
9402
Chris Lattner8ba9ec92004-10-18 02:59:09 +00009403 if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
9404 // This instruction is not reachable, just remove it. We insert a store to
9405 // undef so that we know that this code is not reachable, despite the fact
9406 // that we can't modify the CFG here.
Zhou Sheng75b871f2007-01-11 12:24:14 +00009407 new StoreInst(ConstantInt::getTrue(),
Christopher Lambedf07882007-12-17 01:12:55 +00009408 UndefValue::get(PointerType::getUnqual(Type::Int1Ty)),
Chris Lattner8ba9ec92004-10-18 02:59:09 +00009409 CS.getInstruction());
9410
9411 if (!CS.getInstruction()->use_empty())
9412 CS.getInstruction()->
9413 replaceAllUsesWith(UndefValue::get(CS.getInstruction()->getType()));
9414
9415 if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
9416 // Don't break the CFG, insert a dummy cond branch.
Gabor Greife9ecc682008-04-06 20:25:17 +00009417 BranchInst::Create(II->getNormalDest(), II->getUnwindDest(),
9418 ConstantInt::getTrue(), II);
Chris Lattner81a7a232004-10-16 18:11:37 +00009419 }
Chris Lattner8ba9ec92004-10-18 02:59:09 +00009420 return EraseInstFromFunction(*CS.getInstruction());
9421 }
Chris Lattner81a7a232004-10-16 18:11:37 +00009422
Duncan Sands6d5da712007-09-17 10:26:40 +00009423 if (BitCastInst *BC = dyn_cast<BitCastInst>(Callee))
9424 if (IntrinsicInst *In = dyn_cast<IntrinsicInst>(BC->getOperand(0)))
9425 if (In->getIntrinsicID() == Intrinsic::init_trampoline)
9426 return transformCallThroughTrampoline(CS);
9427
Chris Lattner75b4d1d2003-10-07 22:54:13 +00009428 const PointerType *PTy = cast<PointerType>(Callee->getType());
9429 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
9430 if (FTy->isVarArg()) {
Dale Johannesen493527d2008-04-23 01:03:05 +00009431 int ix = FTy->getNumParams() + (isa<InvokeInst>(Callee) ? 3 : 1);
Chris Lattner75b4d1d2003-10-07 22:54:13 +00009432 // See if we can optimize any arguments passed through the varargs area of
9433 // the call.
9434 for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
Dale Johannesenf6e15a42008-04-23 18:34:37 +00009435 E = CS.arg_end(); I != E; ++I, ++ix) {
9436 CastInst *CI = dyn_cast<CastInst>(*I);
9437 if (CI && isSafeToEliminateVarargsCast(CS, CI, TD, ix)) {
9438 *I = CI->getOperand(0);
9439 Changed = true;
Chris Lattner75b4d1d2003-10-07 22:54:13 +00009440 }
Dale Johannesenf6e15a42008-04-23 18:34:37 +00009441 }
Chris Lattner75b4d1d2003-10-07 22:54:13 +00009442 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00009443
Duncan Sandsaa31b922007-12-19 21:13:37 +00009444 if (isa<InlineAsm>(Callee) && !CS.doesNotThrow()) {
Duncan Sands8e4847e2007-12-16 15:51:49 +00009445 // Inline asm calls cannot throw - mark them 'nounwind'.
Duncan Sandsaa31b922007-12-19 21:13:37 +00009446 CS.setDoesNotThrow();
Duncan Sands8e4847e2007-12-16 15:51:49 +00009447 Changed = true;
9448 }
9449
Chris Lattner75b4d1d2003-10-07 22:54:13 +00009450 return Changed ? CS.getInstruction() : 0;
Chris Lattneraec3d942003-10-07 22:32:43 +00009451}
9452
Chris Lattner970c33a2003-06-19 17:00:31 +00009453// transformConstExprCastCall - If the callee is a constexpr cast of a function,
9454// attempt to move the cast to the arguments of the call/invoke.
9455//
9456bool InstCombiner::transformConstExprCastCall(CallSite CS) {
9457 if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
9458 ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
Reid Spencer6c38f0b2006-11-27 01:05:10 +00009459 if (CE->getOpcode() != Instruction::BitCast ||
9460 !isa<Function>(CE->getOperand(0)))
Chris Lattner970c33a2003-06-19 17:00:31 +00009461 return false;
Reid Spencer87436872004-07-18 00:38:32 +00009462 Function *Callee = cast<Function>(CE->getOperand(0));
Chris Lattner970c33a2003-06-19 17:00:31 +00009463 Instruction *Caller = CS.getInstruction();
Devang Patel4c758ea2008-09-25 21:00:45 +00009464 const AttrListPtr &CallerPAL = CS.getAttributes();
Chris Lattner970c33a2003-06-19 17:00:31 +00009465
9466 // Okay, this is a cast from a function to a different type. Unless doing so
9467 // would cause a type conversion of one of our arguments, change this call to
9468 // be a direct call with arguments casted to the appropriate types.
9469 //
9470 const FunctionType *FT = Callee->getFunctionType();
9471 const Type *OldRetTy = Caller->getType();
Duncan Sands0397cd22008-06-01 07:38:42 +00009472 const Type *NewRetTy = FT->getReturnType();
Chris Lattner970c33a2003-06-19 17:00:31 +00009473
Duncan Sands0397cd22008-06-01 07:38:42 +00009474 if (isa<StructType>(NewRetTy))
Devang Patel70c238a2008-03-11 18:04:06 +00009475 return false; // TODO: Handle multiple return values.
9476
Chris Lattner1f7942f2004-01-14 06:06:08 +00009477 // Check to see if we are changing the return type...
Duncan Sands0397cd22008-06-01 07:38:42 +00009478 if (OldRetTy != NewRetTy) {
Bill Wendling37169522008-05-14 22:45:20 +00009479 if (Callee->isDeclaration() &&
Duncan Sands0397cd22008-06-01 07:38:42 +00009480 // Conversion is ok if changing from one pointer type to another or from
9481 // a pointer to an integer of the same size.
9482 !((isa<PointerType>(OldRetTy) || OldRetTy == TD->getIntPtrType()) &&
Duncan Sands4b50fde2008-06-17 15:55:30 +00009483 (isa<PointerType>(NewRetTy) || NewRetTy == TD->getIntPtrType())))
Chris Lattner400f9592007-01-06 02:09:32 +00009484 return false; // Cannot transform this return value.
Chris Lattner1f7942f2004-01-14 06:06:08 +00009485
Duncan Sands55e50902008-01-06 10:12:28 +00009486 if (!Caller->use_empty() &&
Duncan Sands55e50902008-01-06 10:12:28 +00009487 // void -> non-void is handled specially
Duncan Sands0397cd22008-06-01 07:38:42 +00009488 NewRetTy != Type::VoidTy && !CastInst::isCastable(NewRetTy, OldRetTy))
Duncan Sands55e50902008-01-06 10:12:28 +00009489 return false; // Cannot transform this return value.
9490
Chris Lattner8a923e72008-03-12 17:45:29 +00009491 if (!CallerPAL.isEmpty() && !Caller->use_empty()) {
Devang Patela05633e2008-09-26 22:53:05 +00009492 Attributes RAttrs = CallerPAL.getRetAttributes();
Devang Patel4c758ea2008-09-25 21:00:45 +00009493 if (RAttrs & Attribute::typeIncompatible(NewRetTy))
Duncan Sandsb18c30a2008-01-07 17:16:06 +00009494 return false; // Attribute not compatible with transformed value.
9495 }
Duncan Sands404eb052008-01-06 18:27:01 +00009496
Chris Lattner1f7942f2004-01-14 06:06:08 +00009497 // If the callsite is an invoke instruction, and the return value is used by
9498 // a PHI node in a successor, we cannot change the return type of the call
9499 // because there is no place to put the cast instruction (without breaking
9500 // the critical edge). Bail out in this case.
9501 if (!Caller->use_empty())
9502 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
9503 for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
9504 UI != E; ++UI)
9505 if (PHINode *PN = dyn_cast<PHINode>(*UI))
9506 if (PN->getParent() == II->getNormalDest() ||
Chris Lattnerfae8ab32004-02-08 21:44:31 +00009507 PN->getParent() == II->getUnwindDest())
Chris Lattner1f7942f2004-01-14 06:06:08 +00009508 return false;
9509 }
Chris Lattner970c33a2003-06-19 17:00:31 +00009510
9511 unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
9512 unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
Misha Brukmanb1c93172005-04-21 23:48:37 +00009513
Chris Lattner970c33a2003-06-19 17:00:31 +00009514 CallSite::arg_iterator AI = CS.arg_begin();
9515 for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
9516 const Type *ParamTy = FT->getParamType(i);
Andrew Lenharthebfa24e2006-06-28 01:01:52 +00009517 const Type *ActTy = (*AI)->getType();
Duncan Sands55e50902008-01-06 10:12:28 +00009518
9519 if (!CastInst::isCastable(ActTy, ParamTy))
Duncan Sands404eb052008-01-06 18:27:01 +00009520 return false; // Cannot transform this parameter value.
9521
Devang Patela05633e2008-09-26 22:53:05 +00009522 if (CallerPAL.getParamAttributes(i + 1)
9523 & Attribute::typeIncompatible(ParamTy))
Chris Lattner8a923e72008-03-12 17:45:29 +00009524 return false; // Attribute not compatible with transformed value.
Duncan Sands55e50902008-01-06 10:12:28 +00009525
Duncan Sands0397cd22008-06-01 07:38:42 +00009526 // Converting from one pointer type to another or between a pointer and an
9527 // integer of the same size is safe even if we do not have a body.
Chris Lattner400f9592007-01-06 02:09:32 +00009528 bool isConvertible = ActTy == ParamTy ||
Duncan Sands0397cd22008-06-01 07:38:42 +00009529 ((isa<PointerType>(ParamTy) || ParamTy == TD->getIntPtrType()) &&
9530 (isa<PointerType>(ActTy) || ActTy == TD->getIntPtrType()));
Reid Spencer5301e7c2007-01-30 20:08:39 +00009531 if (Callee->isDeclaration() && !isConvertible) return false;
Chris Lattner970c33a2003-06-19 17:00:31 +00009532 }
9533
9534 if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
Reid Spencer5301e7c2007-01-30 20:08:39 +00009535 Callee->isDeclaration())
Chris Lattner8a923e72008-03-12 17:45:29 +00009536 return false; // Do not delete arguments unless we have a function body.
Chris Lattner970c33a2003-06-19 17:00:31 +00009537
Chris Lattner8a923e72008-03-12 17:45:29 +00009538 if (FT->getNumParams() < NumActualArgs && FT->isVarArg() &&
9539 !CallerPAL.isEmpty())
Duncan Sands404eb052008-01-06 18:27:01 +00009540 // In this case we have more arguments than the new function type, but we
Duncan Sands781f6542008-01-13 08:02:44 +00009541 // won't be dropping them. Check that these extra arguments have attributes
9542 // that are compatible with being a vararg call argument.
Chris Lattner8a923e72008-03-12 17:45:29 +00009543 for (unsigned i = CallerPAL.getNumSlots(); i; --i) {
9544 if (CallerPAL.getSlot(i - 1).Index <= FT->getNumParams())
Duncan Sands781f6542008-01-13 08:02:44 +00009545 break;
Devang Patelba3fa6c2008-09-23 23:03:40 +00009546 Attributes PAttrs = CallerPAL.getSlot(i - 1).Attrs;
Devang Patel4c758ea2008-09-25 21:00:45 +00009547 if (PAttrs & Attribute::VarArgsIncompatible)
Duncan Sands781f6542008-01-13 08:02:44 +00009548 return false;
9549 }
Duncan Sands404eb052008-01-06 18:27:01 +00009550
Chris Lattner970c33a2003-06-19 17:00:31 +00009551 // Okay, we decided that this is a safe thing to do: go ahead and start
9552 // inserting cast instructions as necessary...
9553 std::vector<Value*> Args;
9554 Args.reserve(NumActualArgs);
Devang Patel4c758ea2008-09-25 21:00:45 +00009555 SmallVector<AttributeWithIndex, 8> attrVec;
Duncan Sands404eb052008-01-06 18:27:01 +00009556 attrVec.reserve(NumCommonArgs);
9557
9558 // Get any return attributes.
Devang Patela05633e2008-09-26 22:53:05 +00009559 Attributes RAttrs = CallerPAL.getRetAttributes();
Duncan Sands404eb052008-01-06 18:27:01 +00009560
9561 // If the return value is not being used, the type may not be compatible
9562 // with the existing attributes. Wipe out any problematic attributes.
Devang Patel4c758ea2008-09-25 21:00:45 +00009563 RAttrs &= ~Attribute::typeIncompatible(NewRetTy);
Duncan Sands404eb052008-01-06 18:27:01 +00009564
9565 // Add the new return attributes.
9566 if (RAttrs)
Devang Patel4c758ea2008-09-25 21:00:45 +00009567 attrVec.push_back(AttributeWithIndex::get(0, RAttrs));
Chris Lattner970c33a2003-06-19 17:00:31 +00009568
9569 AI = CS.arg_begin();
9570 for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
9571 const Type *ParamTy = FT->getParamType(i);
9572 if ((*AI)->getType() == ParamTy) {
9573 Args.push_back(*AI);
9574 } else {
Reid Spencer668d90f2006-12-18 08:47:13 +00009575 Instruction::CastOps opcode = CastInst::getCastOpcode(*AI,
Reid Spencerc635f472006-12-31 05:48:39 +00009576 false, ParamTy, false);
Gabor Greife1f6e4b2008-05-16 19:29:10 +00009577 CastInst *NewCast = CastInst::Create(opcode, *AI, ParamTy, "tmp");
Reid Spencer6c38f0b2006-11-27 01:05:10 +00009578 Args.push_back(InsertNewInstBefore(NewCast, *Caller));
Chris Lattner970c33a2003-06-19 17:00:31 +00009579 }
Duncan Sands404eb052008-01-06 18:27:01 +00009580
9581 // Add any parameter attributes.
Devang Patela05633e2008-09-26 22:53:05 +00009582 if (Attributes PAttrs = CallerPAL.getParamAttributes(i + 1))
Devang Patel4c758ea2008-09-25 21:00:45 +00009583 attrVec.push_back(AttributeWithIndex::get(i + 1, PAttrs));
Chris Lattner970c33a2003-06-19 17:00:31 +00009584 }
9585
9586 // If the function takes more arguments than the call was taking, add them
9587 // now...
9588 for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
9589 Args.push_back(Constant::getNullValue(FT->getParamType(i)));
9590
9591 // If we are removing arguments to the function, emit an obnoxious warning...
Anton Korobeynikov1bfd1212008-02-20 11:26:25 +00009592 if (FT->getNumParams() < NumActualArgs) {
Chris Lattner970c33a2003-06-19 17:00:31 +00009593 if (!FT->isVarArg()) {
Bill Wendlingf3baad32006-12-07 01:30:32 +00009594 cerr << "WARNING: While resolving call to function '"
9595 << Callee->getName() << "' arguments were dropped!\n";
Chris Lattner970c33a2003-06-19 17:00:31 +00009596 } else {
9597 // Add all of the arguments in their promoted form to the arg list...
9598 for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
9599 const Type *PTy = getPromotedType((*AI)->getType());
9600 if (PTy != (*AI)->getType()) {
9601 // Must promote to pass through va_arg area!
Reid Spencerc635f472006-12-31 05:48:39 +00009602 Instruction::CastOps opcode = CastInst::getCastOpcode(*AI, false,
9603 PTy, false);
Gabor Greife1f6e4b2008-05-16 19:29:10 +00009604 Instruction *Cast = CastInst::Create(opcode, *AI, PTy, "tmp");
Chris Lattner970c33a2003-06-19 17:00:31 +00009605 InsertNewInstBefore(Cast, *Caller);
9606 Args.push_back(Cast);
9607 } else {
9608 Args.push_back(*AI);
9609 }
Duncan Sands404eb052008-01-06 18:27:01 +00009610
Duncan Sands781f6542008-01-13 08:02:44 +00009611 // Add any parameter attributes.
Devang Patela05633e2008-09-26 22:53:05 +00009612 if (Attributes PAttrs = CallerPAL.getParamAttributes(i + 1))
Devang Patel4c758ea2008-09-25 21:00:45 +00009613 attrVec.push_back(AttributeWithIndex::get(i + 1, PAttrs));
Duncan Sands781f6542008-01-13 08:02:44 +00009614 }
Chris Lattner970c33a2003-06-19 17:00:31 +00009615 }
Anton Korobeynikov1bfd1212008-02-20 11:26:25 +00009616 }
Chris Lattner970c33a2003-06-19 17:00:31 +00009617
Devang Patela05633e2008-09-26 22:53:05 +00009618 if (Attributes FnAttrs = CallerPAL.getFnAttributes())
9619 attrVec.push_back(AttributeWithIndex::get(~0, FnAttrs));
9620
Duncan Sands0397cd22008-06-01 07:38:42 +00009621 if (NewRetTy == Type::VoidTy)
Chris Lattner6e0123b2007-02-11 01:23:03 +00009622 Caller->setName(""); // Void type should not have a name.
Chris Lattner970c33a2003-06-19 17:00:31 +00009623
Devang Patel4c758ea2008-09-25 21:00:45 +00009624 const AttrListPtr &NewCallerPAL = AttrListPtr::get(attrVec.begin(),attrVec.end());
Duncan Sands404eb052008-01-06 18:27:01 +00009625
Chris Lattner970c33a2003-06-19 17:00:31 +00009626 Instruction *NC;
9627 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Gabor Greife9ecc682008-04-06 20:25:17 +00009628 NC = InvokeInst::Create(Callee, II->getNormalDest(), II->getUnwindDest(),
Gabor Greif697e94c2008-05-15 10:04:30 +00009629 Args.begin(), Args.end(),
9630 Caller->getName(), Caller);
Reid Spencerdff9d692007-07-30 19:53:57 +00009631 cast<InvokeInst>(NC)->setCallingConv(II->getCallingConv());
Devang Patel4c758ea2008-09-25 21:00:45 +00009632 cast<InvokeInst>(NC)->setAttributes(NewCallerPAL);
Chris Lattner970c33a2003-06-19 17:00:31 +00009633 } else {
Gabor Greife9ecc682008-04-06 20:25:17 +00009634 NC = CallInst::Create(Callee, Args.begin(), Args.end(),
9635 Caller->getName(), Caller);
Duncan Sandsad0ea2d2007-11-27 13:23:08 +00009636 CallInst *CI = cast<CallInst>(Caller);
9637 if (CI->isTailCall())
Chris Lattner6aacb0f2005-05-06 06:48:21 +00009638 cast<CallInst>(NC)->setTailCall();
Duncan Sandsad0ea2d2007-11-27 13:23:08 +00009639 cast<CallInst>(NC)->setCallingConv(CI->getCallingConv());
Devang Patel4c758ea2008-09-25 21:00:45 +00009640 cast<CallInst>(NC)->setAttributes(NewCallerPAL);
Chris Lattner970c33a2003-06-19 17:00:31 +00009641 }
9642
Chris Lattner6e0123b2007-02-11 01:23:03 +00009643 // Insert a cast of the return type as necessary.
Chris Lattner970c33a2003-06-19 17:00:31 +00009644 Value *NV = NC;
Duncan Sands55e50902008-01-06 10:12:28 +00009645 if (OldRetTy != NV->getType() && !Caller->use_empty()) {
Chris Lattner970c33a2003-06-19 17:00:31 +00009646 if (NV->getType() != Type::VoidTy) {
Reid Spencerc635f472006-12-31 05:48:39 +00009647 Instruction::CastOps opcode = CastInst::getCastOpcode(NC, false,
Duncan Sands55e50902008-01-06 10:12:28 +00009648 OldRetTy, false);
Gabor Greife1f6e4b2008-05-16 19:29:10 +00009649 NV = NC = CastInst::Create(opcode, NC, OldRetTy, "tmp");
Chris Lattner686767f2003-10-30 00:46:41 +00009650
9651 // If this is an invoke instruction, we should insert it after the first
9652 // non-phi, instruction in the normal successor block.
9653 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Dan Gohmanf96e1372008-05-23 21:05:58 +00009654 BasicBlock::iterator I = II->getNormalDest()->getFirstNonPHI();
Chris Lattner686767f2003-10-30 00:46:41 +00009655 InsertNewInstBefore(NC, *I);
9656 } else {
9657 // Otherwise, it's a call, just insert cast right after the call instr
9658 InsertNewInstBefore(NC, *Caller);
9659 }
Chris Lattner51ea1272004-02-28 05:22:00 +00009660 AddUsersToWorkList(*Caller);
Chris Lattner970c33a2003-06-19 17:00:31 +00009661 } else {
Chris Lattnere29d6342004-10-17 21:22:38 +00009662 NV = UndefValue::get(Caller->getType());
Chris Lattner970c33a2003-06-19 17:00:31 +00009663 }
9664 }
9665
9666 if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
9667 Caller->replaceAllUsesWith(NV);
Chris Lattner51f54572007-03-02 19:59:19 +00009668 Caller->eraseFromParent();
Chris Lattnerb15e2b12007-03-02 21:28:56 +00009669 RemoveFromWorkList(Caller);
Chris Lattner970c33a2003-06-19 17:00:31 +00009670 return true;
9671}
9672
Duncan Sands6d5da712007-09-17 10:26:40 +00009673// transformCallThroughTrampoline - Turn a call to a function created by the
9674// init_trampoline intrinsic into a direct call to the underlying function.
9675//
9676Instruction *InstCombiner::transformCallThroughTrampoline(CallSite CS) {
9677 Value *Callee = CS.getCalledValue();
9678 const PointerType *PTy = cast<PointerType>(Callee->getType());
9679 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
Devang Patel4c758ea2008-09-25 21:00:45 +00009680 const AttrListPtr &Attrs = CS.getAttributes();
Duncan Sandsb5ca2e92008-01-14 19:52:09 +00009681
9682 // If the call already has the 'nest' attribute somewhere then give up -
9683 // otherwise 'nest' would occur twice after splicing in the chain.
Devang Patel4c758ea2008-09-25 21:00:45 +00009684 if (Attrs.hasAttrSomewhere(Attribute::Nest))
Duncan Sandsb5ca2e92008-01-14 19:52:09 +00009685 return 0;
Duncan Sands6d5da712007-09-17 10:26:40 +00009686
9687 IntrinsicInst *Tramp =
9688 cast<IntrinsicInst>(cast<BitCastInst>(Callee)->getOperand(0));
9689
Anton Korobeynikovfc2edad2008-05-07 22:54:15 +00009690 Function *NestF = cast<Function>(Tramp->getOperand(2)->stripPointerCasts());
Duncan Sands6d5da712007-09-17 10:26:40 +00009691 const PointerType *NestFPTy = cast<PointerType>(NestF->getType());
9692 const FunctionType *NestFTy = cast<FunctionType>(NestFPTy->getElementType());
9693
Devang Patel4c758ea2008-09-25 21:00:45 +00009694 const AttrListPtr &NestAttrs = NestF->getAttributes();
Chris Lattner8a923e72008-03-12 17:45:29 +00009695 if (!NestAttrs.isEmpty()) {
Duncan Sands6d5da712007-09-17 10:26:40 +00009696 unsigned NestIdx = 1;
9697 const Type *NestTy = 0;
Devang Patel4c758ea2008-09-25 21:00:45 +00009698 Attributes NestAttr = Attribute::None;
Duncan Sands6d5da712007-09-17 10:26:40 +00009699
9700 // Look for a parameter marked with the 'nest' attribute.
9701 for (FunctionType::param_iterator I = NestFTy->param_begin(),
9702 E = NestFTy->param_end(); I != E; ++NestIdx, ++I)
Devang Patel4c758ea2008-09-25 21:00:45 +00009703 if (NestAttrs.paramHasAttr(NestIdx, Attribute::Nest)) {
Duncan Sands6d5da712007-09-17 10:26:40 +00009704 // Record the parameter type and any other attributes.
9705 NestTy = *I;
Devang Patela05633e2008-09-26 22:53:05 +00009706 NestAttr = NestAttrs.getParamAttributes(NestIdx);
Duncan Sands6d5da712007-09-17 10:26:40 +00009707 break;
9708 }
9709
9710 if (NestTy) {
9711 Instruction *Caller = CS.getInstruction();
9712 std::vector<Value*> NewArgs;
9713 NewArgs.reserve(unsigned(CS.arg_end()-CS.arg_begin())+1);
9714
Devang Patel4c758ea2008-09-25 21:00:45 +00009715 SmallVector<AttributeWithIndex, 8> NewAttrs;
Chris Lattner8a923e72008-03-12 17:45:29 +00009716 NewAttrs.reserve(Attrs.getNumSlots() + 1);
Duncan Sandsb5ca2e92008-01-14 19:52:09 +00009717
Duncan Sands6d5da712007-09-17 10:26:40 +00009718 // Insert the nest argument into the call argument list, which may
Duncan Sandsb5ca2e92008-01-14 19:52:09 +00009719 // mean appending it. Likewise for attributes.
9720
Devang Patela05633e2008-09-26 22:53:05 +00009721 // Add any result attributes.
9722 if (Attributes Attr = Attrs.getRetAttributes())
Devang Patel4c758ea2008-09-25 21:00:45 +00009723 NewAttrs.push_back(AttributeWithIndex::get(0, Attr));
Duncan Sandsb5ca2e92008-01-14 19:52:09 +00009724
Duncan Sands6d5da712007-09-17 10:26:40 +00009725 {
9726 unsigned Idx = 1;
9727 CallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
9728 do {
9729 if (Idx == NestIdx) {
Duncan Sandsb5ca2e92008-01-14 19:52:09 +00009730 // Add the chain argument and attributes.
Duncan Sands6d5da712007-09-17 10:26:40 +00009731 Value *NestVal = Tramp->getOperand(3);
9732 if (NestVal->getType() != NestTy)
9733 NestVal = new BitCastInst(NestVal, NestTy, "nest", Caller);
9734 NewArgs.push_back(NestVal);
Devang Patel4c758ea2008-09-25 21:00:45 +00009735 NewAttrs.push_back(AttributeWithIndex::get(NestIdx, NestAttr));
Duncan Sands6d5da712007-09-17 10:26:40 +00009736 }
9737
9738 if (I == E)
9739 break;
9740
Duncan Sandsb5ca2e92008-01-14 19:52:09 +00009741 // Add the original argument and attributes.
Duncan Sands6d5da712007-09-17 10:26:40 +00009742 NewArgs.push_back(*I);
Devang Patela05633e2008-09-26 22:53:05 +00009743 if (Attributes Attr = Attrs.getParamAttributes(Idx))
Duncan Sandsb5ca2e92008-01-14 19:52:09 +00009744 NewAttrs.push_back
Devang Patel4c758ea2008-09-25 21:00:45 +00009745 (AttributeWithIndex::get(Idx + (Idx >= NestIdx), Attr));
Duncan Sands6d5da712007-09-17 10:26:40 +00009746
9747 ++Idx, ++I;
9748 } while (1);
9749 }
9750
Devang Patela05633e2008-09-26 22:53:05 +00009751 // Add any function attributes.
9752 if (Attributes Attr = Attrs.getFnAttributes())
9753 NewAttrs.push_back(AttributeWithIndex::get(~0, Attr));
9754
Duncan Sands6d5da712007-09-17 10:26:40 +00009755 // The trampoline may have been bitcast to a bogus type (FTy).
9756 // Handle this by synthesizing a new function type, equal to FTy
Duncan Sandsb5ca2e92008-01-14 19:52:09 +00009757 // with the chain parameter inserted.
Duncan Sands6d5da712007-09-17 10:26:40 +00009758
Duncan Sands6d5da712007-09-17 10:26:40 +00009759 std::vector<const Type*> NewTypes;
Duncan Sands6d5da712007-09-17 10:26:40 +00009760 NewTypes.reserve(FTy->getNumParams()+1);
9761
Duncan Sands6d5da712007-09-17 10:26:40 +00009762 // Insert the chain's type into the list of parameter types, which may
Duncan Sandsb5ca2e92008-01-14 19:52:09 +00009763 // mean appending it.
Duncan Sands6d5da712007-09-17 10:26:40 +00009764 {
9765 unsigned Idx = 1;
9766 FunctionType::param_iterator I = FTy->param_begin(),
9767 E = FTy->param_end();
9768
9769 do {
Duncan Sandsb5ca2e92008-01-14 19:52:09 +00009770 if (Idx == NestIdx)
9771 // Add the chain's type.
Duncan Sands6d5da712007-09-17 10:26:40 +00009772 NewTypes.push_back(NestTy);
Duncan Sands6d5da712007-09-17 10:26:40 +00009773
9774 if (I == E)
9775 break;
9776
Duncan Sandsb5ca2e92008-01-14 19:52:09 +00009777 // Add the original type.
Duncan Sands6d5da712007-09-17 10:26:40 +00009778 NewTypes.push_back(*I);
Duncan Sands6d5da712007-09-17 10:26:40 +00009779
9780 ++Idx, ++I;
9781 } while (1);
9782 }
9783
9784 // Replace the trampoline call with a direct call. Let the generic
9785 // code sort out any function type mismatches.
9786 FunctionType *NewFTy =
Duncan Sandsad0ea2d2007-11-27 13:23:08 +00009787 FunctionType::get(FTy->getReturnType(), NewTypes, FTy->isVarArg());
Christopher Lambedf07882007-12-17 01:12:55 +00009788 Constant *NewCallee = NestF->getType() == PointerType::getUnqual(NewFTy) ?
9789 NestF : ConstantExpr::getBitCast(NestF, PointerType::getUnqual(NewFTy));
Devang Patel4c758ea2008-09-25 21:00:45 +00009790 const AttrListPtr &NewPAL = AttrListPtr::get(NewAttrs.begin(),NewAttrs.end());
Duncan Sands6d5da712007-09-17 10:26:40 +00009791
9792 Instruction *NewCaller;
9793 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Gabor Greife9ecc682008-04-06 20:25:17 +00009794 NewCaller = InvokeInst::Create(NewCallee,
9795 II->getNormalDest(), II->getUnwindDest(),
9796 NewArgs.begin(), NewArgs.end(),
9797 Caller->getName(), Caller);
Duncan Sands6d5da712007-09-17 10:26:40 +00009798 cast<InvokeInst>(NewCaller)->setCallingConv(II->getCallingConv());
Devang Patel4c758ea2008-09-25 21:00:45 +00009799 cast<InvokeInst>(NewCaller)->setAttributes(NewPAL);
Duncan Sands6d5da712007-09-17 10:26:40 +00009800 } else {
Gabor Greife9ecc682008-04-06 20:25:17 +00009801 NewCaller = CallInst::Create(NewCallee, NewArgs.begin(), NewArgs.end(),
9802 Caller->getName(), Caller);
Duncan Sands6d5da712007-09-17 10:26:40 +00009803 if (cast<CallInst>(Caller)->isTailCall())
9804 cast<CallInst>(NewCaller)->setTailCall();
9805 cast<CallInst>(NewCaller)->
9806 setCallingConv(cast<CallInst>(Caller)->getCallingConv());
Devang Patel4c758ea2008-09-25 21:00:45 +00009807 cast<CallInst>(NewCaller)->setAttributes(NewPAL);
Duncan Sands6d5da712007-09-17 10:26:40 +00009808 }
9809 if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
9810 Caller->replaceAllUsesWith(NewCaller);
9811 Caller->eraseFromParent();
9812 RemoveFromWorkList(Caller);
9813 return 0;
9814 }
9815 }
9816
9817 // Replace the trampoline call with a direct call. Since there is no 'nest'
9818 // parameter, there is no need to adjust the argument list. Let the generic
9819 // code sort out any function type mismatches.
9820 Constant *NewCallee =
9821 NestF->getType() == PTy ? NestF : ConstantExpr::getBitCast(NestF, PTy);
9822 CS.setCalledFunction(NewCallee);
9823 return CS.getInstruction();
9824}
9825
Chris Lattnercadac0c2006-11-01 04:51:18 +00009826/// FoldPHIArgBinOpIntoPHI - If we have something like phi [add (a,b), add(c,d)]
9827/// and if a/b/c/d and the add's all have a single use, turn this into two phi's
9828/// and a single binop.
9829Instruction *InstCombiner::FoldPHIArgBinOpIntoPHI(PHINode &PN) {
9830 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
Reid Spencer2341c222007-02-02 02:16:23 +00009831 assert(isa<BinaryOperator>(FirstInst) || isa<GetElementPtrInst>(FirstInst) ||
9832 isa<CmpInst>(FirstInst));
Chris Lattnercadac0c2006-11-01 04:51:18 +00009833 unsigned Opc = FirstInst->getOpcode();
Chris Lattnercd62f112006-11-08 19:29:23 +00009834 Value *LHSVal = FirstInst->getOperand(0);
9835 Value *RHSVal = FirstInst->getOperand(1);
9836
9837 const Type *LHSType = LHSVal->getType();
9838 const Type *RHSType = RHSVal->getType();
Chris Lattnercadac0c2006-11-01 04:51:18 +00009839
9840 // Scan to see if all operands are the same opcode, all have one use, and all
9841 // kill their operands (i.e. the operands have one use).
Chris Lattnerdc826fc2006-11-01 04:55:47 +00009842 for (unsigned i = 0; i != PN.getNumIncomingValues(); ++i) {
Chris Lattnercadac0c2006-11-01 04:51:18 +00009843 Instruction *I = dyn_cast<Instruction>(PN.getIncomingValue(i));
Chris Lattnerdc826fc2006-11-01 04:55:47 +00009844 if (!I || I->getOpcode() != Opc || !I->hasOneUse() ||
Reid Spencer266e42b2006-12-23 06:05:41 +00009845 // Verify type of the LHS matches so we don't fold cmp's of different
Chris Lattnereebea432006-11-01 07:43:41 +00009846 // types or GEP's with different index types.
9847 I->getOperand(0)->getType() != LHSType ||
9848 I->getOperand(1)->getType() != RHSType)
Chris Lattnercadac0c2006-11-01 04:51:18 +00009849 return 0;
Reid Spencer266e42b2006-12-23 06:05:41 +00009850
9851 // If they are CmpInst instructions, check their predicates
9852 if (Opc == Instruction::ICmp || Opc == Instruction::FCmp)
9853 if (cast<CmpInst>(I)->getPredicate() !=
9854 cast<CmpInst>(FirstInst)->getPredicate())
9855 return 0;
Chris Lattnercd62f112006-11-08 19:29:23 +00009856
9857 // Keep track of which operand needs a phi node.
9858 if (I->getOperand(0) != LHSVal) LHSVal = 0;
9859 if (I->getOperand(1) != RHSVal) RHSVal = 0;
Chris Lattnercadac0c2006-11-01 04:51:18 +00009860 }
9861
Chris Lattner4f218d52006-11-08 19:42:28 +00009862 // Otherwise, this is safe to transform, determine if it is profitable.
9863
9864 // If this is a GEP, and if the index (not the pointer) needs a PHI, bail out.
9865 // Indexes are often folded into load/store instructions, so we don't want to
9866 // hide them behind a phi.
9867 if (isa<GetElementPtrInst>(FirstInst) && RHSVal == 0)
9868 return 0;
9869
Chris Lattnercadac0c2006-11-01 04:51:18 +00009870 Value *InLHS = FirstInst->getOperand(0);
Chris Lattnercadac0c2006-11-01 04:51:18 +00009871 Value *InRHS = FirstInst->getOperand(1);
Chris Lattner4f218d52006-11-08 19:42:28 +00009872 PHINode *NewLHS = 0, *NewRHS = 0;
Chris Lattnercd62f112006-11-08 19:29:23 +00009873 if (LHSVal == 0) {
Gabor Greif697e94c2008-05-15 10:04:30 +00009874 NewLHS = PHINode::Create(LHSType,
9875 FirstInst->getOperand(0)->getName() + ".pn");
Chris Lattnercd62f112006-11-08 19:29:23 +00009876 NewLHS->reserveOperandSpace(PN.getNumOperands()/2);
9877 NewLHS->addIncoming(InLHS, PN.getIncomingBlock(0));
Chris Lattnereebea432006-11-01 07:43:41 +00009878 InsertNewInstBefore(NewLHS, PN);
9879 LHSVal = NewLHS;
9880 }
Chris Lattnercd62f112006-11-08 19:29:23 +00009881
9882 if (RHSVal == 0) {
Gabor Greif697e94c2008-05-15 10:04:30 +00009883 NewRHS = PHINode::Create(RHSType,
9884 FirstInst->getOperand(1)->getName() + ".pn");
Chris Lattnercd62f112006-11-08 19:29:23 +00009885 NewRHS->reserveOperandSpace(PN.getNumOperands()/2);
9886 NewRHS->addIncoming(InRHS, PN.getIncomingBlock(0));
Chris Lattnereebea432006-11-01 07:43:41 +00009887 InsertNewInstBefore(NewRHS, PN);
9888 RHSVal = NewRHS;
9889 }
9890
Chris Lattnercd62f112006-11-08 19:29:23 +00009891 // Add all operands to the new PHIs.
9892 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
9893 if (NewLHS) {
9894 Value *NewInLHS =cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
9895 NewLHS->addIncoming(NewInLHS, PN.getIncomingBlock(i));
9896 }
9897 if (NewRHS) {
9898 Value *NewInRHS =cast<Instruction>(PN.getIncomingValue(i))->getOperand(1);
9899 NewRHS->addIncoming(NewInRHS, PN.getIncomingBlock(i));
9900 }
9901 }
9902
Chris Lattnercadac0c2006-11-01 04:51:18 +00009903 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Gabor Greife1f6e4b2008-05-16 19:29:10 +00009904 return BinaryOperator::Create(BinOp->getOpcode(), LHSVal, RHSVal);
Reid Spencer266e42b2006-12-23 06:05:41 +00009905 else if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
Gabor Greife1f6e4b2008-05-16 19:29:10 +00009906 return CmpInst::Create(CIOp->getOpcode(), CIOp->getPredicate(), LHSVal,
Reid Spencer266e42b2006-12-23 06:05:41 +00009907 RHSVal);
Chris Lattnereebea432006-11-01 07:43:41 +00009908 else {
9909 assert(isa<GetElementPtrInst>(FirstInst));
Gabor Greife9ecc682008-04-06 20:25:17 +00009910 return GetElementPtrInst::Create(LHSVal, RHSVal);
Chris Lattnereebea432006-11-01 07:43:41 +00009911 }
Chris Lattnercadac0c2006-11-01 04:51:18 +00009912}
9913
Chris Lattner14f82c72006-11-01 07:13:54 +00009914/// isSafeToSinkLoad - Return true if we know that it is safe sink the load out
9915/// of the block that defines it. This means that it must be obvious the value
9916/// of the load is not changed from the point of the load to the end of the
9917/// block it is in.
Chris Lattnerc9042052007-02-01 22:30:07 +00009918///
9919/// Finally, it is safe, but not profitable, to sink a load targetting a
9920/// non-address-taken alloca. Doing so will cause us to not promote the alloca
9921/// to a register.
Chris Lattner14f82c72006-11-01 07:13:54 +00009922static bool isSafeToSinkLoad(LoadInst *L) {
9923 BasicBlock::iterator BBI = L, E = L->getParent()->end();
9924
9925 for (++BBI; BBI != E; ++BBI)
9926 if (BBI->mayWriteToMemory())
9927 return false;
Chris Lattnerc9042052007-02-01 22:30:07 +00009928
9929 // Check for non-address taken alloca. If not address-taken already, it isn't
9930 // profitable to do this xform.
9931 if (AllocaInst *AI = dyn_cast<AllocaInst>(L->getOperand(0))) {
9932 bool isAddressTaken = false;
9933 for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end();
9934 UI != E; ++UI) {
9935 if (isa<LoadInst>(UI)) continue;
9936 if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
9937 // If storing TO the alloca, then the address isn't taken.
9938 if (SI->getOperand(1) == AI) continue;
9939 }
9940 isAddressTaken = true;
9941 break;
9942 }
9943
9944 if (!isAddressTaken)
9945 return false;
9946 }
9947
Chris Lattner14f82c72006-11-01 07:13:54 +00009948 return true;
9949}
9950
Chris Lattner970c33a2003-06-19 17:00:31 +00009951
Chris Lattner7515cab2004-11-14 19:13:23 +00009952// FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
9953// operator and they all are only used by the PHI, PHI together their
9954// inputs, and do the operation once, to the result of the PHI.
9955Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
9956 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
9957
9958 // Scan the instruction, looking for input operations that can be folded away.
9959 // If all input operands to the phi are the same instruction (e.g. a cast from
9960 // the same type or "+42") we can pull the operation through the PHI, reducing
9961 // code size and simplifying code.
9962 Constant *ConstantOp = 0;
9963 const Type *CastSrcTy = 0;
Chris Lattner14f82c72006-11-01 07:13:54 +00009964 bool isVolatile = false;
Chris Lattner7515cab2004-11-14 19:13:23 +00009965 if (isa<CastInst>(FirstInst)) {
9966 CastSrcTy = FirstInst->getOperand(0)->getType();
Reid Spencer2341c222007-02-02 02:16:23 +00009967 } else if (isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst)) {
Reid Spencer266e42b2006-12-23 06:05:41 +00009968 // Can fold binop, compare or shift here if the RHS is a constant,
9969 // otherwise call FoldPHIArgBinOpIntoPHI.
Chris Lattner7515cab2004-11-14 19:13:23 +00009970 ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
Chris Lattnercadac0c2006-11-01 04:51:18 +00009971 if (ConstantOp == 0)
9972 return FoldPHIArgBinOpIntoPHI(PN);
Chris Lattner14f82c72006-11-01 07:13:54 +00009973 } else if (LoadInst *LI = dyn_cast<LoadInst>(FirstInst)) {
9974 isVolatile = LI->isVolatile();
9975 // We can't sink the load if the loaded value could be modified between the
9976 // load and the PHI.
9977 if (LI->getParent() != PN.getIncomingBlock(0) ||
9978 !isSafeToSinkLoad(LI))
9979 return 0;
Chris Lattner501d78f2008-07-08 17:18:32 +00009980
9981 // If the PHI is of volatile loads and the load block has multiple
9982 // successors, sinking it would remove a load of the volatile value from
9983 // the path through the other successor.
9984 if (isVolatile &&
9985 LI->getParent()->getTerminator()->getNumSuccessors() != 1)
9986 return 0;
9987
Chris Lattnereebea432006-11-01 07:43:41 +00009988 } else if (isa<GetElementPtrInst>(FirstInst)) {
Chris Lattner4f218d52006-11-08 19:42:28 +00009989 if (FirstInst->getNumOperands() == 2)
Chris Lattnereebea432006-11-01 07:43:41 +00009990 return FoldPHIArgBinOpIntoPHI(PN);
9991 // Can't handle general GEPs yet.
9992 return 0;
Chris Lattner7515cab2004-11-14 19:13:23 +00009993 } else {
9994 return 0; // Cannot fold this operation.
9995 }
9996
9997 // Check to see if all arguments are the same operation.
9998 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
9999 if (!isa<Instruction>(PN.getIncomingValue(i))) return 0;
10000 Instruction *I = cast<Instruction>(PN.getIncomingValue(i));
Reid Spencer266e42b2006-12-23 06:05:41 +000010001 if (!I->hasOneUse() || !I->isSameOperationAs(FirstInst))
Chris Lattner7515cab2004-11-14 19:13:23 +000010002 return 0;
10003 if (CastSrcTy) {
10004 if (I->getOperand(0)->getType() != CastSrcTy)
10005 return 0; // Cast operation must match.
Chris Lattner14f82c72006-11-01 07:13:54 +000010006 } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Reid Spencer266e42b2006-12-23 06:05:41 +000010007 // We can't sink the load if the loaded value could be modified between
10008 // the load and the PHI.
Chris Lattner14f82c72006-11-01 07:13:54 +000010009 if (LI->isVolatile() != isVolatile ||
10010 LI->getParent() != PN.getIncomingBlock(i) ||
10011 !isSafeToSinkLoad(LI))
10012 return 0;
Chris Lattnerd9e3b5c2008-04-29 17:28:22 +000010013
Chris Lattner501d78f2008-07-08 17:18:32 +000010014 // If the PHI is of volatile loads and the load block has multiple
10015 // successors, sinking it would remove a load of the volatile value from
10016 // the path through the other successor.
Chris Lattnerd9e3b5c2008-04-29 17:28:22 +000010017 if (isVolatile &&
10018 LI->getParent()->getTerminator()->getNumSuccessors() != 1)
10019 return 0;
10020
10021
Chris Lattner7515cab2004-11-14 19:13:23 +000010022 } else if (I->getOperand(1) != ConstantOp) {
10023 return 0;
10024 }
10025 }
10026
10027 // Okay, they are all the same operation. Create a new PHI node of the
10028 // correct type, and PHI together all of the LHS's of the instructions.
Gabor Greife9ecc682008-04-06 20:25:17 +000010029 PHINode *NewPN = PHINode::Create(FirstInst->getOperand(0)->getType(),
10030 PN.getName()+".in");
Chris Lattnerd8e20182005-01-29 00:39:08 +000010031 NewPN->reserveOperandSpace(PN.getNumOperands()/2);
Chris Lattner46dd5a62004-11-14 19:29:34 +000010032
10033 Value *InVal = FirstInst->getOperand(0);
10034 NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
Chris Lattner7515cab2004-11-14 19:13:23 +000010035
10036 // Add all operands to the new PHI.
Chris Lattner46dd5a62004-11-14 19:29:34 +000010037 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10038 Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
10039 if (NewInVal != InVal)
10040 InVal = 0;
10041 NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
10042 }
10043
10044 Value *PhiVal;
10045 if (InVal) {
10046 // The new PHI unions all of the same values together. This is really
10047 // common, so we handle it intelligently here for compile-time speed.
10048 PhiVal = InVal;
10049 delete NewPN;
10050 } else {
10051 InsertNewInstBefore(NewPN, PN);
10052 PhiVal = NewPN;
10053 }
Misha Brukmanb1c93172005-04-21 23:48:37 +000010054
Chris Lattner7515cab2004-11-14 19:13:23 +000010055 // Insert and return the new operation.
Reid Spencer6c38f0b2006-11-27 01:05:10 +000010056 if (CastInst* FirstCI = dyn_cast<CastInst>(FirstInst))
Gabor Greife1f6e4b2008-05-16 19:29:10 +000010057 return CastInst::Create(FirstCI->getOpcode(), PhiVal, PN.getType());
Chris Lattner9233c122008-04-29 17:13:43 +000010058 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Gabor Greife1f6e4b2008-05-16 19:29:10 +000010059 return BinaryOperator::Create(BinOp->getOpcode(), PhiVal, ConstantOp);
Chris Lattner9233c122008-04-29 17:13:43 +000010060 if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
Gabor Greife1f6e4b2008-05-16 19:29:10 +000010061 return CmpInst::Create(CIOp->getOpcode(), CIOp->getPredicate(),
Reid Spencer266e42b2006-12-23 06:05:41 +000010062 PhiVal, ConstantOp);
Chris Lattner9233c122008-04-29 17:13:43 +000010063 assert(isa<LoadInst>(FirstInst) && "Unknown operation");
10064
10065 // If this was a volatile load that we are merging, make sure to loop through
10066 // and mark all the input loads as non-volatile. If we don't do this, we will
10067 // insert a new volatile load and the old ones will not be deletable.
10068 if (isVolatile)
10069 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
10070 cast<LoadInst>(PN.getIncomingValue(i))->setVolatile(false);
10071
10072 return new LoadInst(PhiVal, "", isVolatile);
Chris Lattner7515cab2004-11-14 19:13:23 +000010073}
Chris Lattner48a44f72002-05-02 17:06:02 +000010074
Chris Lattner71536432005-01-17 05:10:15 +000010075/// DeadPHICycle - Return true if this PHI node is only used by a PHI node cycle
10076/// that is dead.
Chris Lattnerd2602d52007-03-26 20:40:50 +000010077static bool DeadPHICycle(PHINode *PN,
10078 SmallPtrSet<PHINode*, 16> &PotentiallyDeadPHIs) {
Chris Lattner71536432005-01-17 05:10:15 +000010079 if (PN->use_empty()) return true;
10080 if (!PN->hasOneUse()) return false;
10081
10082 // Remember this node, and if we find the cycle, return.
Chris Lattnerd2602d52007-03-26 20:40:50 +000010083 if (!PotentiallyDeadPHIs.insert(PN))
Chris Lattner71536432005-01-17 05:10:15 +000010084 return true;
Chris Lattner0e258b82007-08-28 04:23:55 +000010085
10086 // Don't scan crazily complex things.
10087 if (PotentiallyDeadPHIs.size() == 16)
10088 return false;
Chris Lattner71536432005-01-17 05:10:15 +000010089
10090 if (PHINode *PU = dyn_cast<PHINode>(PN->use_back()))
10091 return DeadPHICycle(PU, PotentiallyDeadPHIs);
Misha Brukmanb1c93172005-04-21 23:48:37 +000010092
Chris Lattner71536432005-01-17 05:10:15 +000010093 return false;
10094}
10095
Chris Lattnerd8515f82007-11-06 21:52:06 +000010096/// PHIsEqualValue - Return true if this phi node is always equal to
10097/// NonPhiInVal. This happens with mutually cyclic phi nodes like:
10098/// z = some value; x = phi (y, z); y = phi (x, z)
10099static bool PHIsEqualValue(PHINode *PN, Value *NonPhiInVal,
10100 SmallPtrSet<PHINode*, 16> &ValueEqualPHIs) {
10101 // See if we already saw this PHI node.
10102 if (!ValueEqualPHIs.insert(PN))
10103 return true;
10104
10105 // Don't scan crazily complex things.
10106 if (ValueEqualPHIs.size() == 16)
10107 return false;
10108
10109 // Scan the operands to see if they are either phi nodes or are equal to
10110 // the value.
10111 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
10112 Value *Op = PN->getIncomingValue(i);
10113 if (PHINode *OpPN = dyn_cast<PHINode>(Op)) {
10114 if (!PHIsEqualValue(OpPN, NonPhiInVal, ValueEqualPHIs))
10115 return false;
10116 } else if (Op != NonPhiInVal)
10117 return false;
10118 }
10119
10120 return true;
10121}
10122
10123
Chris Lattnerbbbdd852002-05-06 18:06:38 +000010124// PHINode simplification
10125//
Chris Lattner113f4f42002-06-25 16:13:24 +000010126Instruction *InstCombiner::visitPHINode(PHINode &PN) {
Owen Andersonbbf89902006-07-10 22:15:25 +000010127 // If LCSSA is around, don't mess with Phi nodes
Chris Lattner8258b442007-03-04 04:27:24 +000010128 if (MustPreserveLCSSA) return 0;
Owen Andersona6968f82006-07-10 19:03:49 +000010129
Owen Andersonae8aa642006-07-10 22:03:18 +000010130 if (Value *V = PN.hasConstantValue())
10131 return ReplaceInstUsesWith(PN, V);
10132
Owen Andersonae8aa642006-07-10 22:03:18 +000010133 // If all PHI operands are the same operation, pull them through the PHI,
10134 // reducing code size.
10135 if (isa<Instruction>(PN.getIncomingValue(0)) &&
10136 PN.getIncomingValue(0)->hasOneUse())
10137 if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
10138 return Result;
10139
10140 // If this is a trivial cycle in the PHI node graph, remove it. Basically, if
10141 // this PHI only has a single use (a PHI), and if that PHI only has one use (a
10142 // PHI)... break the cycle.
Chris Lattnerc8dcede2007-01-15 07:30:06 +000010143 if (PN.hasOneUse()) {
10144 Instruction *PHIUser = cast<Instruction>(PN.use_back());
10145 if (PHINode *PU = dyn_cast<PHINode>(PHIUser)) {
Chris Lattnerd2602d52007-03-26 20:40:50 +000010146 SmallPtrSet<PHINode*, 16> PotentiallyDeadPHIs;
Owen Andersonae8aa642006-07-10 22:03:18 +000010147 PotentiallyDeadPHIs.insert(&PN);
10148 if (DeadPHICycle(PU, PotentiallyDeadPHIs))
10149 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
10150 }
Chris Lattnerc8dcede2007-01-15 07:30:06 +000010151
10152 // If this phi has a single use, and if that use just computes a value for
10153 // the next iteration of a loop, delete the phi. This occurs with unused
10154 // induction variables, e.g. "for (int j = 0; ; ++j);". Detecting this
10155 // common case here is good because the only other things that catch this
10156 // are induction variable analysis (sometimes) and ADCE, which is only run
10157 // late.
10158 if (PHIUser->hasOneUse() &&
10159 (isa<BinaryOperator>(PHIUser) || isa<GetElementPtrInst>(PHIUser)) &&
10160 PHIUser->use_back() == &PN) {
10161 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
10162 }
10163 }
Owen Andersonae8aa642006-07-10 22:03:18 +000010164
Chris Lattnerd8515f82007-11-06 21:52:06 +000010165 // We sometimes end up with phi cycles that non-obviously end up being the
10166 // same value, for example:
10167 // z = some value; x = phi (y, z); y = phi (x, z)
10168 // where the phi nodes don't necessarily need to be in the same block. Do a
10169 // quick check to see if the PHI node only contains a single non-phi value, if
10170 // so, scan to see if the phi cycle is actually equal to that value.
10171 {
10172 unsigned InValNo = 0, NumOperandVals = PN.getNumIncomingValues();
10173 // Scan for the first non-phi operand.
10174 while (InValNo != NumOperandVals &&
10175 isa<PHINode>(PN.getIncomingValue(InValNo)))
10176 ++InValNo;
10177
10178 if (InValNo != NumOperandVals) {
10179 Value *NonPhiInVal = PN.getOperand(InValNo);
10180
10181 // Scan the rest of the operands to see if there are any conflicts, if so
10182 // there is no need to recursively scan other phis.
10183 for (++InValNo; InValNo != NumOperandVals; ++InValNo) {
10184 Value *OpVal = PN.getIncomingValue(InValNo);
10185 if (OpVal != NonPhiInVal && !isa<PHINode>(OpVal))
10186 break;
10187 }
10188
10189 // If we scanned over all operands, then we have one unique value plus
10190 // phi values. Scan PHI nodes to see if they all merge in each other or
10191 // the value.
10192 if (InValNo == NumOperandVals) {
10193 SmallPtrSet<PHINode*, 16> ValueEqualPHIs;
10194 if (PHIsEqualValue(&PN, NonPhiInVal, ValueEqualPHIs))
10195 return ReplaceInstUsesWith(PN, NonPhiInVal);
10196 }
10197 }
10198 }
Chris Lattner91daeb52003-12-19 05:58:40 +000010199 return 0;
Chris Lattnerbbbdd852002-05-06 18:06:38 +000010200}
10201
Reid Spencer13bc5d72006-12-12 09:18:51 +000010202static Value *InsertCastToIntPtrTy(Value *V, const Type *DTy,
10203 Instruction *InsertPoint,
10204 InstCombiner *IC) {
Reid Spencer8f166b02007-01-08 16:32:00 +000010205 unsigned PtrSize = DTy->getPrimitiveSizeInBits();
10206 unsigned VTySize = V->getType()->getPrimitiveSizeInBits();
Reid Spencer13bc5d72006-12-12 09:18:51 +000010207 // We must cast correctly to the pointer type. Ensure that we
10208 // sign extend the integer value if it is smaller as this is
10209 // used for address computation.
10210 Instruction::CastOps opcode =
10211 (VTySize < PtrSize ? Instruction::SExt :
10212 (VTySize == PtrSize ? Instruction::BitCast : Instruction::Trunc));
10213 return IC->InsertCastBefore(opcode, V, DTy, *InsertPoint);
Chris Lattner69193f92004-04-05 01:30:19 +000010214}
10215
Chris Lattner48a44f72002-05-02 17:06:02 +000010216
Chris Lattner113f4f42002-06-25 16:13:24 +000010217Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
Chris Lattner5f667a62004-05-07 22:09:22 +000010218 Value *PtrOp = GEP.getOperand(0);
Chris Lattneracbf6a42007-04-28 00:57:34 +000010219 // Is it 'getelementptr %P, i32 0' or 'getelementptr %P'
Chris Lattner113f4f42002-06-25 16:13:24 +000010220 // If so, eliminate the noop.
Chris Lattner8d0bacb2004-02-22 05:25:17 +000010221 if (GEP.getNumOperands() == 1)
Chris Lattner5f667a62004-05-07 22:09:22 +000010222 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattner8d0bacb2004-02-22 05:25:17 +000010223
Chris Lattner81a7a232004-10-16 18:11:37 +000010224 if (isa<UndefValue>(GEP.getOperand(0)))
10225 return ReplaceInstUsesWith(GEP, UndefValue::get(GEP.getType()));
10226
Chris Lattner8d0bacb2004-02-22 05:25:17 +000010227 bool HasZeroPointerIndex = false;
10228 if (Constant *C = dyn_cast<Constant>(GEP.getOperand(1)))
10229 HasZeroPointerIndex = C->isNullValue();
10230
10231 if (GEP.getNumOperands() == 2 && HasZeroPointerIndex)
Chris Lattner5f667a62004-05-07 22:09:22 +000010232 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattner48a44f72002-05-02 17:06:02 +000010233
Chris Lattner69193f92004-04-05 01:30:19 +000010234 // Eliminate unneeded casts for indices.
10235 bool MadeChange = false;
Chris Lattner9bf53ff2007-03-25 20:43:09 +000010236
Chris Lattner2b2412d2004-04-07 18:38:20 +000010237 gep_type_iterator GTI = gep_type_begin(GEP);
Gabor Greiff6d8e772008-06-12 21:37:33 +000010238 for (User::op_iterator i = GEP.op_begin() + 1, e = GEP.op_end();
10239 i != e; ++i, ++GTI) {
Chris Lattner2b2412d2004-04-07 18:38:20 +000010240 if (isa<SequentialType>(*GTI)) {
Gabor Greiff6d8e772008-06-12 21:37:33 +000010241 if (CastInst *CI = dyn_cast<CastInst>(*i)) {
Chris Lattner27df1db2007-01-15 07:02:54 +000010242 if (CI->getOpcode() == Instruction::ZExt ||
10243 CI->getOpcode() == Instruction::SExt) {
10244 const Type *SrcTy = CI->getOperand(0)->getType();
10245 // We can eliminate a cast from i32 to i64 iff the target
10246 // is a 32-bit pointer target.
10247 if (SrcTy->getPrimitiveSizeInBits() >= TD->getPointerSizeInBits()) {
10248 MadeChange = true;
Gabor Greiff6d8e772008-06-12 21:37:33 +000010249 *i = CI->getOperand(0);
Chris Lattner69193f92004-04-05 01:30:19 +000010250 }
10251 }
10252 }
Chris Lattner2b2412d2004-04-07 18:38:20 +000010253 // If we are using a wider index than needed for this platform, shrink it
Dan Gohmaneff71f22008-09-11 23:06:38 +000010254 // to what we need. If narrower, sign-extend it to what we need.
10255 // If the incoming value needs a cast instruction,
Chris Lattner2b2412d2004-04-07 18:38:20 +000010256 // insert it. This explicit cast can make subsequent optimizations more
10257 // obvious.
Gabor Greiff6d8e772008-06-12 21:37:33 +000010258 Value *Op = *i;
Anton Korobeynikov1bfd1212008-02-20 11:26:25 +000010259 if (TD->getTypeSizeInBits(Op->getType()) > TD->getPointerSizeInBits()) {
Chris Lattner1e9ac1a2004-04-17 18:16:10 +000010260 if (Constant *C = dyn_cast<Constant>(Op)) {
Gabor Greiff6d8e772008-06-12 21:37:33 +000010261 *i = ConstantExpr::getTrunc(C, TD->getIntPtrType());
Chris Lattner1e9ac1a2004-04-17 18:16:10 +000010262 MadeChange = true;
10263 } else {
Reid Spencer13bc5d72006-12-12 09:18:51 +000010264 Op = InsertCastBefore(Instruction::Trunc, Op, TD->getIntPtrType(),
10265 GEP);
Gabor Greiff6d8e772008-06-12 21:37:33 +000010266 *i = Op;
Chris Lattner2b2412d2004-04-07 18:38:20 +000010267 MadeChange = true;
10268 }
Dan Gohmaneff71f22008-09-11 23:06:38 +000010269 } else if (TD->getTypeSizeInBits(Op->getType()) < TD->getPointerSizeInBits()) {
10270 if (Constant *C = dyn_cast<Constant>(Op)) {
10271 *i = ConstantExpr::getSExt(C, TD->getIntPtrType());
10272 MadeChange = true;
10273 } else {
10274 Op = InsertCastBefore(Instruction::SExt, Op, TD->getIntPtrType(),
10275 GEP);
10276 *i = Op;
10277 MadeChange = true;
10278 }
Anton Korobeynikov1bfd1212008-02-20 11:26:25 +000010279 }
Chris Lattner69193f92004-04-05 01:30:19 +000010280 }
Chris Lattner9bf53ff2007-03-25 20:43:09 +000010281 }
Chris Lattner69193f92004-04-05 01:30:19 +000010282 if (MadeChange) return &GEP;
10283
Chris Lattner9bf53ff2007-03-25 20:43:09 +000010284 // If this GEP instruction doesn't move the pointer, and if the input operand
10285 // is a bitcast of another pointer, just replace the GEP with a bitcast of the
10286 // real input to the dest type.
Chris Lattnerd8675e42007-10-12 05:30:59 +000010287 if (GEP.hasAllZeroIndices()) {
10288 if (BitCastInst *BCI = dyn_cast<BitCastInst>(GEP.getOperand(0))) {
10289 // If the bitcast is of an allocation, and the allocation will be
10290 // converted to match the type of the cast, don't touch this.
10291 if (isa<AllocationInst>(BCI->getOperand(0))) {
10292 // See if the bitcast simplifies, if so, don't nuke this GEP yet.
Chris Lattnerad618f62007-10-12 18:05:47 +000010293 if (Instruction *I = visitBitCast(*BCI)) {
10294 if (I != BCI) {
10295 I->takeName(BCI);
10296 BCI->getParent()->getInstList().insert(BCI, I);
10297 ReplaceInstUsesWith(*BCI, I);
10298 }
Chris Lattnerd8675e42007-10-12 05:30:59 +000010299 return &GEP;
Chris Lattnerad618f62007-10-12 18:05:47 +000010300 }
Chris Lattnerd8675e42007-10-12 05:30:59 +000010301 }
10302 return new BitCastInst(BCI->getOperand(0), GEP.getType());
10303 }
10304 }
10305
Chris Lattnerae7a0d32002-08-02 19:29:35 +000010306 // Combine Indices - If the source pointer to this getelementptr instruction
10307 // is a getelementptr instruction, combine the indices of the two
10308 // getelementptr instructions into a single instruction.
10309 //
Chris Lattneraf6094f2007-02-15 22:48:32 +000010310 SmallVector<Value*, 8> SrcGEPOperands;
Chris Lattner0798af32005-01-13 20:14:25 +000010311 if (User *Src = dyn_castGetElementPtr(PtrOp))
Chris Lattneraf6094f2007-02-15 22:48:32 +000010312 SrcGEPOperands.append(Src->op_begin(), Src->op_end());
Chris Lattner57c67b02004-03-25 22:59:29 +000010313
10314 if (!SrcGEPOperands.empty()) {
Chris Lattner5f667a62004-05-07 22:09:22 +000010315 // Note that if our source is a gep chain itself that we wait for that
10316 // chain to be resolved before we perform this transformation. This
10317 // avoids us creating a TON of code in some cases.
10318 //
10319 if (isa<GetElementPtrInst>(SrcGEPOperands[0]) &&
10320 cast<Instruction>(SrcGEPOperands[0])->getNumOperands() == 2)
10321 return 0; // Wait until our source is folded to completion.
10322
Chris Lattneraf6094f2007-02-15 22:48:32 +000010323 SmallVector<Value*, 8> Indices;
Chris Lattner5f667a62004-05-07 22:09:22 +000010324
10325 // Find out whether the last index in the source GEP is a sequential idx.
10326 bool EndsWithSequential = false;
10327 for (gep_type_iterator I = gep_type_begin(*cast<User>(PtrOp)),
10328 E = gep_type_end(*cast<User>(PtrOp)); I != E; ++I)
Chris Lattner8ec5f882004-05-08 22:41:42 +000010329 EndsWithSequential = !isa<StructType>(*I);
Misha Brukmanb1c93172005-04-21 23:48:37 +000010330
Chris Lattnerae7a0d32002-08-02 19:29:35 +000010331 // Can we combine the two pointer arithmetics offsets?
Chris Lattner5f667a62004-05-07 22:09:22 +000010332 if (EndsWithSequential) {
Chris Lattner235af562003-03-05 22:33:14 +000010333 // Replace: gep (gep %P, long B), long A, ...
10334 // With: T = long A+B; gep %P, T, ...
10335 //
Chris Lattner5f667a62004-05-07 22:09:22 +000010336 Value *Sum, *SO1 = SrcGEPOperands.back(), *GO1 = GEP.getOperand(1);
Chris Lattner69193f92004-04-05 01:30:19 +000010337 if (SO1 == Constant::getNullValue(SO1->getType())) {
10338 Sum = GO1;
10339 } else if (GO1 == Constant::getNullValue(GO1->getType())) {
10340 Sum = SO1;
10341 } else {
10342 // If they aren't the same type, convert both to an integer of the
10343 // target's pointer size.
10344 if (SO1->getType() != GO1->getType()) {
10345 if (Constant *SO1C = dyn_cast<Constant>(SO1)) {
Reid Spencer13bc5d72006-12-12 09:18:51 +000010346 SO1 = ConstantExpr::getIntegerCast(SO1C, GO1->getType(), true);
Chris Lattner69193f92004-04-05 01:30:19 +000010347 } else if (Constant *GO1C = dyn_cast<Constant>(GO1)) {
Reid Spencer13bc5d72006-12-12 09:18:51 +000010348 GO1 = ConstantExpr::getIntegerCast(GO1C, SO1->getType(), true);
Chris Lattner69193f92004-04-05 01:30:19 +000010349 } else {
Duncan Sands44b87212007-11-01 20:53:16 +000010350 unsigned PS = TD->getPointerSizeInBits();
10351 if (TD->getTypeSizeInBits(SO1->getType()) == PS) {
Chris Lattner69193f92004-04-05 01:30:19 +000010352 // Convert GO1 to SO1's type.
Reid Spencer13bc5d72006-12-12 09:18:51 +000010353 GO1 = InsertCastToIntPtrTy(GO1, SO1->getType(), &GEP, this);
Chris Lattner69193f92004-04-05 01:30:19 +000010354
Duncan Sands44b87212007-11-01 20:53:16 +000010355 } else if (TD->getTypeSizeInBits(GO1->getType()) == PS) {
Chris Lattner69193f92004-04-05 01:30:19 +000010356 // Convert SO1 to GO1's type.
Reid Spencer13bc5d72006-12-12 09:18:51 +000010357 SO1 = InsertCastToIntPtrTy(SO1, GO1->getType(), &GEP, this);
Chris Lattner69193f92004-04-05 01:30:19 +000010358 } else {
10359 const Type *PT = TD->getIntPtrType();
Reid Spencer13bc5d72006-12-12 09:18:51 +000010360 SO1 = InsertCastToIntPtrTy(SO1, PT, &GEP, this);
10361 GO1 = InsertCastToIntPtrTy(GO1, PT, &GEP, this);
Chris Lattner69193f92004-04-05 01:30:19 +000010362 }
10363 }
10364 }
Chris Lattner5f667a62004-05-07 22:09:22 +000010365 if (isa<Constant>(SO1) && isa<Constant>(GO1))
10366 Sum = ConstantExpr::getAdd(cast<Constant>(SO1), cast<Constant>(GO1));
10367 else {
Gabor Greife1f6e4b2008-05-16 19:29:10 +000010368 Sum = BinaryOperator::CreateAdd(SO1, GO1, PtrOp->getName()+".sum");
Chris Lattnerdf20a4d2004-06-10 02:07:29 +000010369 InsertNewInstBefore(cast<Instruction>(Sum), GEP);
Chris Lattner5f667a62004-05-07 22:09:22 +000010370 }
Chris Lattner69193f92004-04-05 01:30:19 +000010371 }
Chris Lattner5f667a62004-05-07 22:09:22 +000010372
10373 // Recycle the GEP we already have if possible.
10374 if (SrcGEPOperands.size() == 2) {
10375 GEP.setOperand(0, SrcGEPOperands[0]);
10376 GEP.setOperand(1, Sum);
10377 return &GEP;
10378 } else {
10379 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
10380 SrcGEPOperands.end()-1);
10381 Indices.push_back(Sum);
10382 Indices.insert(Indices.end(), GEP.op_begin()+2, GEP.op_end());
10383 }
Misha Brukmanb1c93172005-04-21 23:48:37 +000010384 } else if (isa<Constant>(*GEP.idx_begin()) &&
Chris Lattner69193f92004-04-05 01:30:19 +000010385 cast<Constant>(*GEP.idx_begin())->isNullValue() &&
Misha Brukmanb1c93172005-04-21 23:48:37 +000010386 SrcGEPOperands.size() != 1) {
Chris Lattnerae7a0d32002-08-02 19:29:35 +000010387 // Otherwise we can do the fold if the first index of the GEP is a zero
Chris Lattner57c67b02004-03-25 22:59:29 +000010388 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
10389 SrcGEPOperands.end());
Chris Lattnerae7a0d32002-08-02 19:29:35 +000010390 Indices.insert(Indices.end(), GEP.idx_begin()+1, GEP.idx_end());
10391 }
10392
10393 if (!Indices.empty())
Gabor Greife9ecc682008-04-06 20:25:17 +000010394 return GetElementPtrInst::Create(SrcGEPOperands[0], Indices.begin(),
10395 Indices.end(), GEP.getName());
Chris Lattnerc59af1d2002-08-17 22:21:59 +000010396
Chris Lattner5f667a62004-05-07 22:09:22 +000010397 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(PtrOp)) {
Chris Lattnerc59af1d2002-08-17 22:21:59 +000010398 // GEP of global variable. If all of the indices for this GEP are
10399 // constants, we can promote this to a constexpr instead of an instruction.
10400
10401 // Scan for nonconstants...
Chris Lattnerf96f4a82007-01-31 04:40:53 +000010402 SmallVector<Constant*, 8> Indices;
Chris Lattnerc59af1d2002-08-17 22:21:59 +000010403 User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end();
10404 for (; I != E && isa<Constant>(*I); ++I)
10405 Indices.push_back(cast<Constant>(*I));
10406
10407 if (I == E) { // If they are all constants...
Chris Lattnerf96f4a82007-01-31 04:40:53 +000010408 Constant *CE = ConstantExpr::getGetElementPtr(GV,
10409 &Indices[0],Indices.size());
Chris Lattnerc59af1d2002-08-17 22:21:59 +000010410
10411 // Replace all uses of the GEP with the new constexpr...
10412 return ReplaceInstUsesWith(GEP, CE);
10413 }
Reid Spencer6c38f0b2006-11-27 01:05:10 +000010414 } else if (Value *X = getBitCastOperand(PtrOp)) { // Is the operand a cast?
Chris Lattner567b81f2005-09-13 00:40:14 +000010415 if (!isa<PointerType>(X->getType())) {
10416 // Not interesting. Source pointer must be a cast from pointer.
10417 } else if (HasZeroPointerIndex) {
Wojciech Matyjewicz309e5a72007-12-12 15:21:32 +000010418 // transform: GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ...
10419 // into : GEP [10 x i8]* X, i32 0, ...
Chris Lattner567b81f2005-09-13 00:40:14 +000010420 //
10421 // This occurs when the program declares an array extern like "int X[];"
10422 //
10423 const PointerType *CPTy = cast<PointerType>(PtrOp->getType());
10424 const PointerType *XTy = cast<PointerType>(X->getType());
10425 if (const ArrayType *XATy =
10426 dyn_cast<ArrayType>(XTy->getElementType()))
10427 if (const ArrayType *CATy =
10428 dyn_cast<ArrayType>(CPTy->getElementType()))
10429 if (CATy->getElementType() == XATy->getElementType()) {
10430 // At this point, we know that the cast source type is a pointer
10431 // to an array of the same type as the destination pointer
10432 // array. Because the array type is never stepped over (there
10433 // is a leading zero) we can fold the cast into this GEP.
10434 GEP.setOperand(0, X);
10435 return &GEP;
10436 }
10437 } else if (GEP.getNumOperands() == 2) {
10438 // Transform things like:
Wojciech Matyjewicz309e5a72007-12-12 15:21:32 +000010439 // %t = getelementptr i32* bitcast ([2 x i32]* %str to i32*), i32 %V
10440 // into: %t1 = getelementptr [2 x i32]* %str, i32 0, i32 %V; bitcast
Chris Lattner567b81f2005-09-13 00:40:14 +000010441 const Type *SrcElTy = cast<PointerType>(X->getType())->getElementType();
10442 const Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
10443 if (isa<ArrayType>(SrcElTy) &&
Duncan Sands44b87212007-11-01 20:53:16 +000010444 TD->getABITypeSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
10445 TD->getABITypeSize(ResElTy)) {
David Greenec656cbb2007-09-04 15:46:09 +000010446 Value *Idx[2];
10447 Idx[0] = Constant::getNullValue(Type::Int32Ty);
10448 Idx[1] = GEP.getOperand(1);
Chris Lattner567b81f2005-09-13 00:40:14 +000010449 Value *V = InsertNewInstBefore(
Gabor Greife9ecc682008-04-06 20:25:17 +000010450 GetElementPtrInst::Create(X, Idx, Idx + 2, GEP.getName()), GEP);
Reid Spencer6c38f0b2006-11-27 01:05:10 +000010451 // V and GEP are both pointer types --> BitCast
10452 return new BitCastInst(V, GEP.getType());
Chris Lattner8d0bacb2004-02-22 05:25:17 +000010453 }
Chris Lattner2a893292005-09-13 18:36:04 +000010454
10455 // Transform things like:
Wojciech Matyjewicz309e5a72007-12-12 15:21:32 +000010456 // getelementptr i8* bitcast ([100 x double]* X to i8*), i32 %tmp
Chris Lattner2a893292005-09-13 18:36:04 +000010457 // (where tmp = 8*tmp2) into:
Wojciech Matyjewicz309e5a72007-12-12 15:21:32 +000010458 // getelementptr [100 x double]* %arr, i32 0, i32 %tmp2; bitcast
Chris Lattner2a893292005-09-13 18:36:04 +000010459
Wojciech Matyjewicz309e5a72007-12-12 15:21:32 +000010460 if (isa<ArrayType>(SrcElTy) && ResElTy == Type::Int8Ty) {
Chris Lattner2a893292005-09-13 18:36:04 +000010461 uint64_t ArrayEltSize =
Duncan Sands44b87212007-11-01 20:53:16 +000010462 TD->getABITypeSize(cast<ArrayType>(SrcElTy)->getElementType());
Chris Lattner2a893292005-09-13 18:36:04 +000010463
10464 // Check to see if "tmp" is a scale by a multiple of ArrayEltSize. We
10465 // allow either a mul, shift, or constant here.
10466 Value *NewIdx = 0;
10467 ConstantInt *Scale = 0;
10468 if (ArrayEltSize == 1) {
10469 NewIdx = GEP.getOperand(1);
10470 Scale = ConstantInt::get(NewIdx->getType(), 1);
10471 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) {
Chris Lattnera393e4d2005-09-14 17:32:56 +000010472 NewIdx = ConstantInt::get(CI->getType(), 1);
Chris Lattner2a893292005-09-13 18:36:04 +000010473 Scale = CI;
10474 } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){
10475 if (Inst->getOpcode() == Instruction::Shl &&
10476 isa<ConstantInt>(Inst->getOperand(1))) {
Zhou Shengb25806f2007-03-30 09:29:48 +000010477 ConstantInt *ShAmt = cast<ConstantInt>(Inst->getOperand(1));
10478 uint32_t ShAmtVal = ShAmt->getLimitedValue(64);
10479 Scale = ConstantInt::get(Inst->getType(), 1ULL << ShAmtVal);
Chris Lattner2a893292005-09-13 18:36:04 +000010480 NewIdx = Inst->getOperand(0);
10481 } else if (Inst->getOpcode() == Instruction::Mul &&
10482 isa<ConstantInt>(Inst->getOperand(1))) {
10483 Scale = cast<ConstantInt>(Inst->getOperand(1));
10484 NewIdx = Inst->getOperand(0);
10485 }
10486 }
Wojciech Matyjewicz309e5a72007-12-12 15:21:32 +000010487
Chris Lattner2a893292005-09-13 18:36:04 +000010488 // If the index will be to exactly the right offset with the scale taken
Wojciech Matyjewicz309e5a72007-12-12 15:21:32 +000010489 // out, perform the transformation. Note, we don't know whether Scale is
10490 // signed or not. We'll use unsigned version of division/modulo
10491 // operation after making sure Scale doesn't have the sign bit set.
10492 if (Scale && Scale->getSExtValue() >= 0LL &&
10493 Scale->getZExtValue() % ArrayEltSize == 0) {
10494 Scale = ConstantInt::get(Scale->getType(),
10495 Scale->getZExtValue() / ArrayEltSize);
Reid Spencere0fc4df2006-10-20 07:07:24 +000010496 if (Scale->getZExtValue() != 1) {
Reid Spencer13bc5d72006-12-12 09:18:51 +000010497 Constant *C = ConstantExpr::getIntegerCast(Scale, NewIdx->getType(),
Wojciech Matyjewicz309e5a72007-12-12 15:21:32 +000010498 false /*ZExt*/);
Gabor Greife1f6e4b2008-05-16 19:29:10 +000010499 Instruction *Sc = BinaryOperator::CreateMul(NewIdx, C, "idxscale");
Chris Lattner2a893292005-09-13 18:36:04 +000010500 NewIdx = InsertNewInstBefore(Sc, GEP);
10501 }
10502
10503 // Insert the new GEP instruction.
David Greenec656cbb2007-09-04 15:46:09 +000010504 Value *Idx[2];
10505 Idx[0] = Constant::getNullValue(Type::Int32Ty);
10506 Idx[1] = NewIdx;
Reid Spencer6c38f0b2006-11-27 01:05:10 +000010507 Instruction *NewGEP =
Gabor Greife9ecc682008-04-06 20:25:17 +000010508 GetElementPtrInst::Create(X, Idx, Idx + 2, GEP.getName());
Reid Spencer6c38f0b2006-11-27 01:05:10 +000010509 NewGEP = InsertNewInstBefore(NewGEP, GEP);
10510 // The NewGEP must be pointer typed, so must the old one -> BitCast
10511 return new BitCastInst(NewGEP, GEP.getType());
Chris Lattner2a893292005-09-13 18:36:04 +000010512 }
10513 }
Chris Lattner8d0bacb2004-02-22 05:25:17 +000010514 }
Chris Lattnerca081252001-12-14 16:52:21 +000010515 }
10516
Chris Lattnerca081252001-12-14 16:52:21 +000010517 return 0;
10518}
10519
Chris Lattner1085bdf2002-11-04 16:18:53 +000010520Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
10521 // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
Anton Korobeynikov1bfd1212008-02-20 11:26:25 +000010522 if (AI.isArrayAllocation()) { // Check C != 1
Reid Spencere0fc4df2006-10-20 07:07:24 +000010523 if (const ConstantInt *C = dyn_cast<ConstantInt>(AI.getArraySize())) {
10524 const Type *NewTy =
10525 ArrayType::get(AI.getAllocatedType(), C->getZExtValue());
Chris Lattnera2620ac2002-11-09 00:49:43 +000010526 AllocationInst *New = 0;
Chris Lattner1085bdf2002-11-04 16:18:53 +000010527
10528 // Create and insert the replacement instruction...
10529 if (isa<MallocInst>(AI))
Nate Begeman848622f2005-11-05 09:21:28 +000010530 New = new MallocInst(NewTy, 0, AI.getAlignment(), AI.getName());
Chris Lattnera2620ac2002-11-09 00:49:43 +000010531 else {
10532 assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
Nate Begeman848622f2005-11-05 09:21:28 +000010533 New = new AllocaInst(NewTy, 0, AI.getAlignment(), AI.getName());
Chris Lattnera2620ac2002-11-09 00:49:43 +000010534 }
Chris Lattnerabb77c92004-03-19 06:08:10 +000010535
10536 InsertNewInstBefore(New, AI);
Misha Brukmanb1c93172005-04-21 23:48:37 +000010537
Chris Lattner1085bdf2002-11-04 16:18:53 +000010538 // Scan to the end of the allocation instructions, to skip over a block of
10539 // allocas if possible...
10540 //
10541 BasicBlock::iterator It = New;
10542 while (isa<AllocationInst>(*It)) ++It;
10543
10544 // Now that I is pointing to the first non-allocation-inst in the block,
10545 // insert our getelementptr instruction...
10546 //
Reid Spencerc635f472006-12-31 05:48:39 +000010547 Value *NullIdx = Constant::getNullValue(Type::Int32Ty);
David Greenec656cbb2007-09-04 15:46:09 +000010548 Value *Idx[2];
10549 Idx[0] = NullIdx;
10550 Idx[1] = NullIdx;
Gabor Greife9ecc682008-04-06 20:25:17 +000010551 Value *V = GetElementPtrInst::Create(New, Idx, Idx + 2,
10552 New->getName()+".sub", It);
Chris Lattner1085bdf2002-11-04 16:18:53 +000010553
10554 // Now make everything use the getelementptr instead of the original
10555 // allocation.
Chris Lattnerabb77c92004-03-19 06:08:10 +000010556 return ReplaceInstUsesWith(AI, V);
Chris Lattner81a7a232004-10-16 18:11:37 +000010557 } else if (isa<UndefValue>(AI.getArraySize())) {
10558 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
Chris Lattner1085bdf2002-11-04 16:18:53 +000010559 }
Anton Korobeynikov1bfd1212008-02-20 11:26:25 +000010560 }
Chris Lattnerabb77c92004-03-19 06:08:10 +000010561
10562 // If alloca'ing a zero byte object, replace the alloca with a null pointer.
10563 // Note that we only do this for alloca's, because malloc should allocate and
10564 // return a unique pointer, even for a zero byte allocation.
Misha Brukmanb1c93172005-04-21 23:48:37 +000010565 if (isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized() &&
Duncan Sands44b87212007-11-01 20:53:16 +000010566 TD->getABITypeSize(AI.getAllocatedType()) == 0)
Chris Lattnerabb77c92004-03-19 06:08:10 +000010567 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
10568
Chris Lattner1085bdf2002-11-04 16:18:53 +000010569 return 0;
10570}
10571
Chris Lattner8427bff2003-12-07 01:24:23 +000010572Instruction *InstCombiner::visitFreeInst(FreeInst &FI) {
10573 Value *Op = FI.getOperand(0);
10574
Chris Lattner8ba9ec92004-10-18 02:59:09 +000010575 // free undef -> unreachable.
10576 if (isa<UndefValue>(Op)) {
10577 // Insert a new store to null because we cannot modify the CFG here.
Zhou Sheng75b871f2007-01-11 12:24:14 +000010578 new StoreInst(ConstantInt::getTrue(),
Christopher Lambedf07882007-12-17 01:12:55 +000010579 UndefValue::get(PointerType::getUnqual(Type::Int1Ty)), &FI);
Chris Lattner8ba9ec92004-10-18 02:59:09 +000010580 return EraseInstFromFunction(FI);
10581 }
Chris Lattnerefb33d22007-04-14 00:20:02 +000010582
Chris Lattnerf3a36602004-02-28 04:57:37 +000010583 // If we have 'free null' delete the instruction. This can happen in stl code
10584 // when lots of inlining happens.
Chris Lattner8ba9ec92004-10-18 02:59:09 +000010585 if (isa<ConstantPointerNull>(Op))
Chris Lattner51ea1272004-02-28 05:22:00 +000010586 return EraseInstFromFunction(FI);
Chris Lattnerefb33d22007-04-14 00:20:02 +000010587
10588 // Change free <ty>* (cast <ty2>* X to <ty>*) into free <ty2>* X
10589 if (BitCastInst *CI = dyn_cast<BitCastInst>(Op)) {
10590 FI.setOperand(0, CI->getOperand(0));
10591 return &FI;
10592 }
10593
10594 // Change free (gep X, 0,0,0,0) into free(X)
10595 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
10596 if (GEPI->hasAllZeroIndices()) {
10597 AddToWorkList(GEPI);
10598 FI.setOperand(0, GEPI->getOperand(0));
10599 return &FI;
10600 }
10601 }
10602
10603 // Change free(malloc) into nothing, if the malloc has a single use.
10604 if (MallocInst *MI = dyn_cast<MallocInst>(Op))
10605 if (MI->hasOneUse()) {
10606 EraseInstFromFunction(FI);
10607 return EraseInstFromFunction(*MI);
10608 }
Chris Lattnerf3a36602004-02-28 04:57:37 +000010609
Chris Lattner8427bff2003-12-07 01:24:23 +000010610 return 0;
10611}
10612
10613
Chris Lattner72684fe2005-01-31 05:51:45 +000010614/// InstCombineLoadCast - Fold 'load (cast P)' -> cast (load P)' when possible.
Devang Pateldf49cf52007-10-18 19:52:32 +000010615static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI,
Bill Wendlingd188e032008-02-26 10:53:30 +000010616 const TargetData *TD) {
Chris Lattner35e24772004-07-13 01:49:43 +000010617 User *CI = cast<User>(LI.getOperand(0));
Chris Lattnerfe1b0b82005-01-31 04:50:46 +000010618 Value *CastOp = CI->getOperand(0);
Chris Lattner35e24772004-07-13 01:49:43 +000010619
Devang Pateldf49cf52007-10-18 19:52:32 +000010620 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(CI)) {
10621 // Instead of loading constant c string, use corresponding integer value
10622 // directly if string length is small enough.
Evan Chengda3db112008-06-30 07:31:25 +000010623 std::string Str;
10624 if (GetConstantStringInfo(CE->getOperand(0), Str) && !Str.empty()) {
Devang Pateldf49cf52007-10-18 19:52:32 +000010625 unsigned len = Str.length();
10626 const Type *Ty = cast<PointerType>(CE->getType())->getElementType();
10627 unsigned numBits = Ty->getPrimitiveSizeInBits();
10628 // Replace LI with immediate integer store.
10629 if ((numBits >> 3) == len + 1) {
Bill Wendlingd188e032008-02-26 10:53:30 +000010630 APInt StrVal(numBits, 0);
10631 APInt SingleChar(numBits, 0);
10632 if (TD->isLittleEndian()) {
10633 for (signed i = len-1; i >= 0; i--) {
10634 SingleChar = (uint64_t) Str[i];
10635 StrVal = (StrVal << 8) | SingleChar;
10636 }
10637 } else {
10638 for (unsigned i = 0; i < len; i++) {
10639 SingleChar = (uint64_t) Str[i];
10640 StrVal = (StrVal << 8) | SingleChar;
10641 }
10642 // Append NULL at the end.
10643 SingleChar = 0;
10644 StrVal = (StrVal << 8) | SingleChar;
10645 }
10646 Value *NL = ConstantInt::get(StrVal);
10647 return IC.ReplaceInstUsesWith(LI, NL);
Devang Pateldf49cf52007-10-18 19:52:32 +000010648 }
10649 }
10650 }
10651
Chris Lattner35e24772004-07-13 01:49:43 +000010652 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
Chris Lattnerfe1b0b82005-01-31 04:50:46 +000010653 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
Chris Lattner35e24772004-07-13 01:49:43 +000010654 const Type *SrcPTy = SrcTy->getElementType();
Chris Lattnerfe1b0b82005-01-31 04:50:46 +000010655
Reid Spencer31a4ef42007-01-22 05:51:25 +000010656 if (DestPTy->isInteger() || isa<PointerType>(DestPTy) ||
Reid Spencerd84d35b2007-02-15 02:26:10 +000010657 isa<VectorType>(DestPTy)) {
Chris Lattnerfe1b0b82005-01-31 04:50:46 +000010658 // If the source is an array, the code below will not succeed. Check to
10659 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
10660 // constants.
10661 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
10662 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
10663 if (ASrcTy->getNumElements() != 0) {
Chris Lattnerf96f4a82007-01-31 04:40:53 +000010664 Value *Idxs[2];
10665 Idxs[0] = Idxs[1] = Constant::getNullValue(Type::Int32Ty);
10666 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs, 2);
Chris Lattnerfe1b0b82005-01-31 04:50:46 +000010667 SrcTy = cast<PointerType>(CastOp->getType());
10668 SrcPTy = SrcTy->getElementType();
10669 }
10670
Reid Spencer31a4ef42007-01-22 05:51:25 +000010671 if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy) ||
Reid Spencerd84d35b2007-02-15 02:26:10 +000010672 isa<VectorType>(SrcPTy)) &&
Chris Lattnerecfa9b52005-03-29 06:37:47 +000010673 // Do not allow turning this into a load of an integer, which is then
10674 // casted to a pointer, this pessimizes pointer analysis a lot.
10675 (isa<PointerType>(SrcPTy) == isa<PointerType>(LI.getType())) &&
Reid Spencer31a4ef42007-01-22 05:51:25 +000010676 IC.getTargetData().getTypeSizeInBits(SrcPTy) ==
10677 IC.getTargetData().getTypeSizeInBits(DestPTy)) {
Misha Brukmanb1c93172005-04-21 23:48:37 +000010678
Chris Lattnerfe1b0b82005-01-31 04:50:46 +000010679 // Okay, we are casting from one integer or pointer type to another of
10680 // the same size. Instead of casting the pointer before the load, cast
10681 // the result of the loaded value.
10682 Value *NewLoad = IC.InsertNewInstBefore(new LoadInst(CastOp,
10683 CI->getName(),
10684 LI.isVolatile()),LI);
10685 // Now cast the result of the load.
Reid Spencerbb65ebf2006-12-12 23:36:14 +000010686 return new BitCastInst(NewLoad, LI.getType());
Chris Lattnerfe1b0b82005-01-31 04:50:46 +000010687 }
Chris Lattner35e24772004-07-13 01:49:43 +000010688 }
10689 }
10690 return 0;
10691}
10692
Chris Lattnerf62ea8e2004-09-19 18:43:46 +000010693/// isSafeToLoadUnconditionally - Return true if we know that executing a load
Chris Lattnere6f13092004-09-19 19:18:10 +000010694/// from this value cannot trap. If it is not obviously safe to load from the
10695/// specified pointer, we do a quick local scan of the basic block containing
10696/// ScanFrom, to determine if the address is already accessed.
10697static bool isSafeToLoadUnconditionally(Value *V, Instruction *ScanFrom) {
Duncan Sands56df7de2007-09-19 10:10:31 +000010698 // If it is an alloca it is always safe to load from.
10699 if (isa<AllocaInst>(V)) return true;
10700
Duncan Sandsd31649b2007-09-19 10:25:38 +000010701 // If it is a global variable it is mostly safe to load from.
Duncan Sands56df7de2007-09-19 10:10:31 +000010702 if (const GlobalValue *GV = dyn_cast<GlobalVariable>(V))
Duncan Sandsd31649b2007-09-19 10:25:38 +000010703 // Don't try to evaluate aliases. External weak GV can be null.
Duncan Sands56df7de2007-09-19 10:10:31 +000010704 return !isa<GlobalAlias>(GV) && !GV->hasExternalWeakLinkage();
Chris Lattnere6f13092004-09-19 19:18:10 +000010705
10706 // Otherwise, be a little bit agressive by scanning the local block where we
10707 // want to check to see if the pointer is already being loaded or stored
Alkis Evlogimenosd59cebf2004-09-20 06:42:58 +000010708 // from/to. If so, the previous load or store would have already trapped,
10709 // so there is no harm doing an extra load (also, CSE will later eliminate
10710 // the load entirely).
Chris Lattnere6f13092004-09-19 19:18:10 +000010711 BasicBlock::iterator BBI = ScanFrom, E = ScanFrom->getParent()->begin();
10712
Alkis Evlogimenosd59cebf2004-09-20 06:42:58 +000010713 while (BBI != E) {
Chris Lattnere6f13092004-09-19 19:18:10 +000010714 --BBI;
10715
Chris Lattnerf3ecd2d2008-06-20 05:12:56 +000010716 // If we see a free or a call (which might do a free) the pointer could be
10717 // marked invalid.
10718 if (isa<FreeInst>(BBI) || isa<CallInst>(BBI))
10719 return false;
10720
Chris Lattnere6f13092004-09-19 19:18:10 +000010721 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
10722 if (LI->getOperand(0) == V) return true;
Chris Lattnerf3ecd2d2008-06-20 05:12:56 +000010723 } else if (StoreInst *SI = dyn_cast<StoreInst>(BBI)) {
Chris Lattnere6f13092004-09-19 19:18:10 +000010724 if (SI->getOperand(1) == V) return true;
Chris Lattnerf3ecd2d2008-06-20 05:12:56 +000010725 }
Misha Brukmanb1c93172005-04-21 23:48:37 +000010726
Alkis Evlogimenosd59cebf2004-09-20 06:42:58 +000010727 }
Chris Lattnere6f13092004-09-19 19:18:10 +000010728 return false;
Chris Lattnerf62ea8e2004-09-19 18:43:46 +000010729}
10730
Dan Gohmanbc027842008-10-15 23:19:35 +000010731/// equivalentAddressValues - Test if A and B will obviously have the same
10732/// value. This includes recognizing that %t0 and %t1 will have the same
10733/// value in code like this:
10734/// %t0 = getelementptr @a, 0, 3
10735/// store i32 0, i32* %t0
10736/// %t1 = getelementptr @a, 0, 3
10737/// %t2 = load i32* %t1
10738///
10739static bool equivalentAddressValues(Value *A, Value *B) {
10740 // Test if the values are trivially equivalent.
10741 if (A == B) return true;
10742
10743 // Test if the values come form identical arithmetic instructions.
10744 if (isa<BinaryOperator>(A) ||
10745 isa<CastInst>(A) ||
10746 isa<PHINode>(A) ||
10747 isa<GetElementPtrInst>(A))
10748 if (Instruction *BI = dyn_cast<Instruction>(B))
10749 if (cast<Instruction>(A)->isIdenticalTo(BI))
10750 return true;
10751
10752 // Otherwise they may not be equivalent.
10753 return false;
10754}
10755
Chris Lattner0f1d8a32003-06-26 05:06:25 +000010756Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
10757 Value *Op = LI.getOperand(0);
Chris Lattner7e8af382004-01-12 04:13:56 +000010758
Dan Gohmane31a61e2007-07-20 16:34:21 +000010759 // Attempt to improve the alignment.
Dan Gohman99b7b3f2008-04-10 18:43:06 +000010760 unsigned KnownAlign = GetOrEnforceKnownAlignment(Op);
10761 if (KnownAlign >
10762 (LI.getAlignment() == 0 ? TD->getABITypeAlignment(LI.getType()) :
10763 LI.getAlignment()))
Dan Gohmane31a61e2007-07-20 16:34:21 +000010764 LI.setAlignment(KnownAlign);
10765
Chris Lattnera9d84e32005-05-01 04:24:53 +000010766 // load (cast X) --> cast (load X) iff safe
Reid Spencerde46e482006-11-02 20:25:50 +000010767 if (isa<CastInst>(Op))
Devang Pateldf49cf52007-10-18 19:52:32 +000010768 if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
Chris Lattnera9d84e32005-05-01 04:24:53 +000010769 return Res;
10770
10771 // None of the following transforms are legal for volatile loads.
10772 if (LI.isVolatile()) return 0;
Chris Lattnerb990f7d2005-09-12 22:00:15 +000010773
Dan Gohmanbc027842008-10-15 23:19:35 +000010774 // Do really simple store-to-load forwarding and load CSE, to catch cases
10775 // where there are several consequtive memory accesses to the same location,
10776 // separated by a few arithmetic operations.
10777 BasicBlock::iterator BBI = &LI;
10778 for (unsigned ScanInsts = 6; BBI != LI.getParent()->begin() && ScanInsts;
10779 --ScanInsts) {
10780 --BBI;
10781
10782 if (StoreInst *SI = dyn_cast<StoreInst>(BBI)) {
10783 if (equivalentAddressValues(SI->getOperand(1), LI.getOperand(0)))
Chris Lattnerb990f7d2005-09-12 22:00:15 +000010784 return ReplaceInstUsesWith(LI, SI->getOperand(0));
Dan Gohmanbc027842008-10-15 23:19:35 +000010785 } else if (LoadInst *LIB = dyn_cast<LoadInst>(BBI)) {
10786 if (equivalentAddressValues(LIB->getOperand(0), LI.getOperand(0)))
Chris Lattnere0bfdf12005-09-12 22:21:03 +000010787 return ReplaceInstUsesWith(LI, LIB);
Dan Gohmanbc027842008-10-15 23:19:35 +000010788 }
10789
10790 // Don't skip over things that can modify memory.
10791 if (BBI->mayWriteToMemory())
10792 break;
Chris Lattnerb990f7d2005-09-12 22:00:15 +000010793 }
Chris Lattnera9d84e32005-05-01 04:24:53 +000010794
Christopher Lambb053b802007-12-29 07:56:53 +000010795 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
10796 const Value *GEPI0 = GEPI->getOperand(0);
10797 // TODO: Consider a target hook for valid address spaces for this xform.
10798 if (isa<ConstantPointerNull>(GEPI0) &&
10799 cast<PointerType>(GEPI0->getType())->getAddressSpace() == 0) {
Chris Lattnera9d84e32005-05-01 04:24:53 +000010800 // Insert a new store to null instruction before the load to indicate
10801 // that this code is not reachable. We do this instead of inserting
10802 // an unreachable instruction directly because we cannot modify the
10803 // CFG.
10804 new StoreInst(UndefValue::get(LI.getType()),
10805 Constant::getNullValue(Op->getType()), &LI);
10806 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
10807 }
Christopher Lambb053b802007-12-29 07:56:53 +000010808 }
Chris Lattnera9d84e32005-05-01 04:24:53 +000010809
Chris Lattner81a7a232004-10-16 18:11:37 +000010810 if (Constant *C = dyn_cast<Constant>(Op)) {
Chris Lattnera9d84e32005-05-01 04:24:53 +000010811 // load null/undef -> undef
Christopher Lambb053b802007-12-29 07:56:53 +000010812 // TODO: Consider a target hook for valid address spaces for this xform.
10813 if (isa<UndefValue>(C) || (C->isNullValue() &&
10814 cast<PointerType>(Op->getType())->getAddressSpace() == 0)) {
Chris Lattner8ba9ec92004-10-18 02:59:09 +000010815 // Insert a new store to null instruction before the load to indicate that
10816 // this code is not reachable. We do this instead of inserting an
10817 // unreachable instruction directly because we cannot modify the CFG.
Chris Lattnera9d84e32005-05-01 04:24:53 +000010818 new StoreInst(UndefValue::get(LI.getType()),
10819 Constant::getNullValue(Op->getType()), &LI);
Chris Lattner81a7a232004-10-16 18:11:37 +000010820 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
Chris Lattner8ba9ec92004-10-18 02:59:09 +000010821 }
Chris Lattner0f1d8a32003-06-26 05:06:25 +000010822
Chris Lattner81a7a232004-10-16 18:11:37 +000010823 // Instcombine load (constant global) into the value loaded.
10824 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op))
Reid Spencer5301e7c2007-01-30 20:08:39 +000010825 if (GV->isConstant() && !GV->isDeclaration())
Chris Lattner81a7a232004-10-16 18:11:37 +000010826 return ReplaceInstUsesWith(LI, GV->getInitializer());
Misha Brukmanb1c93172005-04-21 23:48:37 +000010827
Chris Lattner81a7a232004-10-16 18:11:37 +000010828 // Instcombine load (constantexpr_GEP global, 0, ...) into the value loaded.
Anton Korobeynikov1bfd1212008-02-20 11:26:25 +000010829 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op)) {
Chris Lattner81a7a232004-10-16 18:11:37 +000010830 if (CE->getOpcode() == Instruction::GetElementPtr) {
10831 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
Reid Spencer5301e7c2007-01-30 20:08:39 +000010832 if (GV->isConstant() && !GV->isDeclaration())
Chris Lattner0b011ec2005-09-26 05:28:06 +000010833 if (Constant *V =
10834 ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE))
Chris Lattner81a7a232004-10-16 18:11:37 +000010835 return ReplaceInstUsesWith(LI, V);
Chris Lattnera9d84e32005-05-01 04:24:53 +000010836 if (CE->getOperand(0)->isNullValue()) {
10837 // Insert a new store to null instruction before the load to indicate
10838 // that this code is not reachable. We do this instead of inserting
10839 // an unreachable instruction directly because we cannot modify the
10840 // CFG.
10841 new StoreInst(UndefValue::get(LI.getType()),
10842 Constant::getNullValue(Op->getType()), &LI);
10843 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
10844 }
10845
Reid Spencer6c38f0b2006-11-27 01:05:10 +000010846 } else if (CE->isCast()) {
Devang Pateldf49cf52007-10-18 19:52:32 +000010847 if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
Chris Lattner81a7a232004-10-16 18:11:37 +000010848 return Res;
10849 }
Anton Korobeynikov1bfd1212008-02-20 11:26:25 +000010850 }
Chris Lattner81a7a232004-10-16 18:11:37 +000010851 }
Chris Lattner99c8ee22007-08-11 18:48:48 +000010852
10853 // If this load comes from anywhere in a constant global, and if the global
10854 // is all undef or zero, we know what it loads.
Duncan Sandsd65a4da2008-10-01 15:25:41 +000010855 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op->getUnderlyingObject())){
Chris Lattner99c8ee22007-08-11 18:48:48 +000010856 if (GV->isConstant() && GV->hasInitializer()) {
10857 if (GV->getInitializer()->isNullValue())
10858 return ReplaceInstUsesWith(LI, Constant::getNullValue(LI.getType()));
10859 else if (isa<UndefValue>(GV->getInitializer()))
10860 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
10861 }
10862 }
Chris Lattnere228ee52004-04-08 20:39:49 +000010863
Chris Lattnera9d84e32005-05-01 04:24:53 +000010864 if (Op->hasOneUse()) {
Chris Lattnerf62ea8e2004-09-19 18:43:46 +000010865 // Change select and PHI nodes to select values instead of addresses: this
10866 // helps alias analysis out a lot, allows many others simplifications, and
10867 // exposes redundancy in the code.
10868 //
10869 // Note that we cannot do the transformation unless we know that the
10870 // introduced loads cannot trap! Something like this is valid as long as
10871 // the condition is always false: load (select bool %C, int* null, int* %G),
10872 // but it would not be valid if we transformed it to load from null
10873 // unconditionally.
10874 //
10875 if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
10876 // load (select (Cond, &V1, &V2)) --> select(Cond, load &V1, load &V2).
Chris Lattnere6f13092004-09-19 19:18:10 +000010877 if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
10878 isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
Chris Lattnerf62ea8e2004-09-19 18:43:46 +000010879 Value *V1 = InsertNewInstBefore(new LoadInst(SI->getOperand(1),
Chris Lattner42618552004-09-20 10:15:10 +000010880 SI->getOperand(1)->getName()+".val"), LI);
Chris Lattnerf62ea8e2004-09-19 18:43:46 +000010881 Value *V2 = InsertNewInstBefore(new LoadInst(SI->getOperand(2),
Chris Lattner42618552004-09-20 10:15:10 +000010882 SI->getOperand(2)->getName()+".val"), LI);
Gabor Greife9ecc682008-04-06 20:25:17 +000010883 return SelectInst::Create(SI->getCondition(), V1, V2);
Chris Lattnerf62ea8e2004-09-19 18:43:46 +000010884 }
10885
Chris Lattnerbdcf41a2004-09-23 15:46:00 +000010886 // load (select (cond, null, P)) -> load P
10887 if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
10888 if (C->isNullValue()) {
10889 LI.setOperand(0, SI->getOperand(2));
10890 return &LI;
10891 }
10892
10893 // load (select (cond, P, null)) -> load P
10894 if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
10895 if (C->isNullValue()) {
10896 LI.setOperand(0, SI->getOperand(1));
10897 return &LI;
10898 }
Chris Lattnerf62ea8e2004-09-19 18:43:46 +000010899 }
10900 }
Chris Lattner0f1d8a32003-06-26 05:06:25 +000010901 return 0;
10902}
10903
Reid Spencere928a152007-01-19 21:20:31 +000010904/// InstCombineStoreToCast - Fold store V, (cast P) -> store (cast V), P
Chris Lattner72684fe2005-01-31 05:51:45 +000010905/// when possible.
10906static Instruction *InstCombineStoreToCast(InstCombiner &IC, StoreInst &SI) {
10907 User *CI = cast<User>(SI.getOperand(1));
10908 Value *CastOp = CI->getOperand(0);
10909
10910 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
10911 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
10912 const Type *SrcPTy = SrcTy->getElementType();
10913
Reid Spencer31a4ef42007-01-22 05:51:25 +000010914 if (DestPTy->isInteger() || isa<PointerType>(DestPTy)) {
Chris Lattner72684fe2005-01-31 05:51:45 +000010915 // If the source is an array, the code below will not succeed. Check to
10916 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
10917 // constants.
10918 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
10919 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
10920 if (ASrcTy->getNumElements() != 0) {
Chris Lattnerf96f4a82007-01-31 04:40:53 +000010921 Value* Idxs[2];
10922 Idxs[0] = Idxs[1] = Constant::getNullValue(Type::Int32Ty);
10923 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs, 2);
Chris Lattner72684fe2005-01-31 05:51:45 +000010924 SrcTy = cast<PointerType>(CastOp->getType());
10925 SrcPTy = SrcTy->getElementType();
10926 }
10927
Reid Spencer9a4bed02007-01-20 23:35:48 +000010928 if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy)) &&
10929 IC.getTargetData().getTypeSizeInBits(SrcPTy) ==
10930 IC.getTargetData().getTypeSizeInBits(DestPTy)) {
Chris Lattner72684fe2005-01-31 05:51:45 +000010931
10932 // Okay, we are casting from one integer or pointer type to another of
Reid Spencerc050af92007-01-18 18:54:33 +000010933 // the same size. Instead of casting the pointer before
10934 // the store, cast the value to be stored.
Chris Lattner72684fe2005-01-31 05:51:45 +000010935 Value *NewCast;
Reid Spencerbb65ebf2006-12-12 23:36:14 +000010936 Value *SIOp0 = SI.getOperand(0);
Reid Spencerc050af92007-01-18 18:54:33 +000010937 Instruction::CastOps opcode = Instruction::BitCast;
10938 const Type* CastSrcTy = SIOp0->getType();
10939 const Type* CastDstTy = SrcPTy;
10940 if (isa<PointerType>(CastDstTy)) {
10941 if (CastSrcTy->isInteger())
Reid Spencerbb65ebf2006-12-12 23:36:14 +000010942 opcode = Instruction::IntToPtr;
Reid Spencer9a4bed02007-01-20 23:35:48 +000010943 } else if (isa<IntegerType>(CastDstTy)) {
Reid Spencer74a528b2006-12-13 18:21:21 +000010944 if (isa<PointerType>(SIOp0->getType()))
Reid Spencerbb65ebf2006-12-12 23:36:14 +000010945 opcode = Instruction::PtrToInt;
10946 }
10947 if (Constant *C = dyn_cast<Constant>(SIOp0))
Reid Spencerc050af92007-01-18 18:54:33 +000010948 NewCast = ConstantExpr::getCast(opcode, C, CastDstTy);
Chris Lattner72684fe2005-01-31 05:51:45 +000010949 else
Reid Spencer6c38f0b2006-11-27 01:05:10 +000010950 NewCast = IC.InsertNewInstBefore(
Gabor Greife1f6e4b2008-05-16 19:29:10 +000010951 CastInst::Create(opcode, SIOp0, CastDstTy, SIOp0->getName()+".c"),
Reid Spencerc050af92007-01-18 18:54:33 +000010952 SI);
Chris Lattner72684fe2005-01-31 05:51:45 +000010953 return new StoreInst(NewCast, CastOp);
10954 }
10955 }
10956 }
10957 return 0;
10958}
10959
Chris Lattner31f486c2005-01-31 05:36:43 +000010960Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
10961 Value *Val = SI.getOperand(0);
10962 Value *Ptr = SI.getOperand(1);
10963
10964 if (isa<UndefValue>(Ptr)) { // store X, undef -> noop (even if volatile)
Chris Lattner5997cf92006-02-08 03:25:32 +000010965 EraseInstFromFunction(SI);
Chris Lattner31f486c2005-01-31 05:36:43 +000010966 ++NumCombined;
10967 return 0;
10968 }
Chris Lattnera4beeef2007-01-15 06:51:56 +000010969
10970 // If the RHS is an alloca with a single use, zapify the store, making the
10971 // alloca dead.
Chris Lattnere331a652008-04-29 04:58:38 +000010972 if (Ptr->hasOneUse() && !SI.isVolatile()) {
Chris Lattnera4beeef2007-01-15 06:51:56 +000010973 if (isa<AllocaInst>(Ptr)) {
10974 EraseInstFromFunction(SI);
10975 ++NumCombined;
10976 return 0;
10977 }
10978
10979 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr))
10980 if (isa<AllocaInst>(GEP->getOperand(0)) &&
10981 GEP->getOperand(0)->hasOneUse()) {
10982 EraseInstFromFunction(SI);
10983 ++NumCombined;
10984 return 0;
10985 }
10986 }
Chris Lattner31f486c2005-01-31 05:36:43 +000010987
Dan Gohmane31a61e2007-07-20 16:34:21 +000010988 // Attempt to improve the alignment.
Dan Gohman99b7b3f2008-04-10 18:43:06 +000010989 unsigned KnownAlign = GetOrEnforceKnownAlignment(Ptr);
10990 if (KnownAlign >
10991 (SI.getAlignment() == 0 ? TD->getABITypeAlignment(Val->getType()) :
10992 SI.getAlignment()))
Dan Gohmane31a61e2007-07-20 16:34:21 +000010993 SI.setAlignment(KnownAlign);
10994
Chris Lattner5997cf92006-02-08 03:25:32 +000010995 // Do really simple DSE, to catch cases where there are several consequtive
10996 // stores to the same location, separated by a few arithmetic operations. This
10997 // situation often occurs with bitfield accesses.
10998 BasicBlock::iterator BBI = &SI;
10999 for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts;
11000 --ScanInsts) {
11001 --BBI;
11002
11003 if (StoreInst *PrevSI = dyn_cast<StoreInst>(BBI)) {
11004 // Prev store isn't volatile, and stores to the same location?
Dan Gohmanbc027842008-10-15 23:19:35 +000011005 if (!PrevSI->isVolatile() && equivalentAddressValues(PrevSI->getOperand(1),
11006 SI.getOperand(1))) {
Chris Lattner5997cf92006-02-08 03:25:32 +000011007 ++NumDeadStore;
11008 ++BBI;
11009 EraseInstFromFunction(*PrevSI);
11010 continue;
11011 }
11012 break;
11013 }
11014
Chris Lattnerdab43b22006-05-26 19:19:20 +000011015 // If this is a load, we have to stop. However, if the loaded value is from
11016 // the pointer we're loading and is producing the pointer we're storing,
11017 // then *this* store is dead (X = load P; store X -> P).
11018 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
Dan Gohmanbc027842008-10-15 23:19:35 +000011019 if (LI == Val && equivalentAddressValues(LI->getOperand(0), Ptr) &&
11020 !SI.isVolatile()) {
Chris Lattnerdab43b22006-05-26 19:19:20 +000011021 EraseInstFromFunction(SI);
11022 ++NumCombined;
11023 return 0;
11024 }
11025 // Otherwise, this is a load from some other location. Stores before it
11026 // may not be dead.
11027 break;
11028 }
11029
Chris Lattner5997cf92006-02-08 03:25:32 +000011030 // Don't skip over loads or things that can modify memory.
Chris Lattner4fa09662008-05-08 17:20:30 +000011031 if (BBI->mayWriteToMemory() || BBI->mayReadFromMemory())
Chris Lattner5997cf92006-02-08 03:25:32 +000011032 break;
11033 }
11034
11035
11036 if (SI.isVolatile()) return 0; // Don't hack volatile stores.
Chris Lattner31f486c2005-01-31 05:36:43 +000011037
11038 // store X, null -> turns into 'unreachable' in SimplifyCFG
11039 if (isa<ConstantPointerNull>(Ptr)) {
11040 if (!isa<UndefValue>(Val)) {
11041 SI.setOperand(0, UndefValue::get(Val->getType()));
11042 if (Instruction *U = dyn_cast<Instruction>(Val))
Chris Lattnerb15e2b12007-03-02 21:28:56 +000011043 AddToWorkList(U); // Dropped a use.
Chris Lattner31f486c2005-01-31 05:36:43 +000011044 ++NumCombined;
11045 }
11046 return 0; // Do not modify these!
11047 }
11048
11049 // store undef, Ptr -> noop
11050 if (isa<UndefValue>(Val)) {
Chris Lattner5997cf92006-02-08 03:25:32 +000011051 EraseInstFromFunction(SI);
Chris Lattner31f486c2005-01-31 05:36:43 +000011052 ++NumCombined;
11053 return 0;
11054 }
11055
Chris Lattner72684fe2005-01-31 05:51:45 +000011056 // If the pointer destination is a cast, see if we can fold the cast into the
11057 // source instead.
Reid Spencerde46e482006-11-02 20:25:50 +000011058 if (isa<CastInst>(Ptr))
Chris Lattner72684fe2005-01-31 05:51:45 +000011059 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
11060 return Res;
11061 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
Reid Spencer6c38f0b2006-11-27 01:05:10 +000011062 if (CE->isCast())
Chris Lattner72684fe2005-01-31 05:51:45 +000011063 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
11064 return Res;
11065
Chris Lattner219175c2005-09-12 23:23:25 +000011066
11067 // If this store is the last instruction in the basic block, and if the block
11068 // ends with an unconditional branch, try to move it to the successor block.
Chris Lattner5997cf92006-02-08 03:25:32 +000011069 BBI = &SI; ++BBI;
Chris Lattner219175c2005-09-12 23:23:25 +000011070 if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
Chris Lattner14a251b2007-04-15 00:07:55 +000011071 if (BI->isUnconditional())
11072 if (SimplifyStoreAtEndOfBlock(SI))
11073 return 0; // xform done!
Chris Lattner219175c2005-09-12 23:23:25 +000011074
Chris Lattner31f486c2005-01-31 05:36:43 +000011075 return 0;
11076}
11077
Chris Lattner14a251b2007-04-15 00:07:55 +000011078/// SimplifyStoreAtEndOfBlock - Turn things like:
11079/// if () { *P = v1; } else { *P = v2 }
11080/// into a phi node with a store in the successor.
11081///
Chris Lattner4a6e0cb2007-04-15 01:02:18 +000011082/// Simplify things like:
11083/// *P = v1; if () { *P = v2; }
11084/// into a phi node with a store in the successor.
11085///
Chris Lattner14a251b2007-04-15 00:07:55 +000011086bool InstCombiner::SimplifyStoreAtEndOfBlock(StoreInst &SI) {
11087 BasicBlock *StoreBB = SI.getParent();
11088
11089 // Check to see if the successor block has exactly two incoming edges. If
11090 // so, see if the other predecessor contains a store to the same location.
11091 // if so, insert a PHI node (if needed) and move the stores down.
Chris Lattner4a6e0cb2007-04-15 01:02:18 +000011092 BasicBlock *DestBB = StoreBB->getTerminator()->getSuccessor(0);
Chris Lattner14a251b2007-04-15 00:07:55 +000011093
11094 // Determine whether Dest has exactly two predecessors and, if so, compute
11095 // the other predecessor.
Chris Lattner4a6e0cb2007-04-15 01:02:18 +000011096 pred_iterator PI = pred_begin(DestBB);
11097 BasicBlock *OtherBB = 0;
Chris Lattner14a251b2007-04-15 00:07:55 +000011098 if (*PI != StoreBB)
Chris Lattner4a6e0cb2007-04-15 01:02:18 +000011099 OtherBB = *PI;
Chris Lattner14a251b2007-04-15 00:07:55 +000011100 ++PI;
Chris Lattner4a6e0cb2007-04-15 01:02:18 +000011101 if (PI == pred_end(DestBB))
Chris Lattner14a251b2007-04-15 00:07:55 +000011102 return false;
11103
11104 if (*PI != StoreBB) {
Chris Lattner4a6e0cb2007-04-15 01:02:18 +000011105 if (OtherBB)
Chris Lattner14a251b2007-04-15 00:07:55 +000011106 return false;
Chris Lattner4a6e0cb2007-04-15 01:02:18 +000011107 OtherBB = *PI;
Chris Lattner14a251b2007-04-15 00:07:55 +000011108 }
Chris Lattner4a6e0cb2007-04-15 01:02:18 +000011109 if (++PI != pred_end(DestBB))
Chris Lattner14a251b2007-04-15 00:07:55 +000011110 return false;
Eli Friedman9833a1b2008-06-13 21:17:49 +000011111
11112 // Bail out if all the relevant blocks aren't distinct (this can happen,
11113 // for example, if SI is in an infinite loop)
11114 if (StoreBB == DestBB || OtherBB == DestBB)
11115 return false;
11116
Chris Lattner4a6e0cb2007-04-15 01:02:18 +000011117 // Verify that the other block ends in a branch and is not otherwise empty.
11118 BasicBlock::iterator BBI = OtherBB->getTerminator();
Chris Lattner14a251b2007-04-15 00:07:55 +000011119 BranchInst *OtherBr = dyn_cast<BranchInst>(BBI);
Chris Lattner4a6e0cb2007-04-15 01:02:18 +000011120 if (!OtherBr || BBI == OtherBB->begin())
Chris Lattner14a251b2007-04-15 00:07:55 +000011121 return false;
11122
Chris Lattner4a6e0cb2007-04-15 01:02:18 +000011123 // If the other block ends in an unconditional branch, check for the 'if then
11124 // else' case. there is an instruction before the branch.
11125 StoreInst *OtherStore = 0;
11126 if (OtherBr->isUnconditional()) {
11127 // If this isn't a store, or isn't a store to the same location, bail out.
11128 --BBI;
11129 OtherStore = dyn_cast<StoreInst>(BBI);
11130 if (!OtherStore || OtherStore->getOperand(1) != SI.getOperand(1))
11131 return false;
11132 } else {
Chris Lattner361e9812007-05-05 22:32:24 +000011133 // Otherwise, the other block ended with a conditional branch. If one of the
Chris Lattner4a6e0cb2007-04-15 01:02:18 +000011134 // destinations is StoreBB, then we have the if/then case.
11135 if (OtherBr->getSuccessor(0) != StoreBB &&
11136 OtherBr->getSuccessor(1) != StoreBB)
11137 return false;
11138
11139 // Okay, we know that OtherBr now goes to Dest and StoreBB, so this is an
Chris Lattner361e9812007-05-05 22:32:24 +000011140 // if/then triangle. See if there is a store to the same ptr as SI that
11141 // lives in OtherBB.
Chris Lattner4a6e0cb2007-04-15 01:02:18 +000011142 for (;; --BBI) {
11143 // Check to see if we find the matching store.
11144 if ((OtherStore = dyn_cast<StoreInst>(BBI))) {
11145 if (OtherStore->getOperand(1) != SI.getOperand(1))
11146 return false;
11147 break;
11148 }
Eli Friedman5de0a772008-06-13 22:02:12 +000011149 // If we find something that may be using or overwriting the stored
11150 // value, or if we run out of instructions, we can't do the xform.
11151 if (BBI->mayReadFromMemory() || BBI->mayWriteToMemory() ||
Chris Lattner4a6e0cb2007-04-15 01:02:18 +000011152 BBI == OtherBB->begin())
11153 return false;
11154 }
11155
11156 // In order to eliminate the store in OtherBr, we have to
Eli Friedman5de0a772008-06-13 22:02:12 +000011157 // make sure nothing reads or overwrites the stored value in
11158 // StoreBB.
Chris Lattner4a6e0cb2007-04-15 01:02:18 +000011159 for (BasicBlock::iterator I = StoreBB->begin(); &*I != &SI; ++I) {
11160 // FIXME: This should really be AA driven.
Eli Friedman5de0a772008-06-13 22:02:12 +000011161 if (I->mayReadFromMemory() || I->mayWriteToMemory())
Chris Lattner4a6e0cb2007-04-15 01:02:18 +000011162 return false;
11163 }
11164 }
Chris Lattner14a251b2007-04-15 00:07:55 +000011165
Chris Lattner4a6e0cb2007-04-15 01:02:18 +000011166 // Insert a PHI node now if we need it.
Chris Lattner14a251b2007-04-15 00:07:55 +000011167 Value *MergedVal = OtherStore->getOperand(0);
11168 if (MergedVal != SI.getOperand(0)) {
Gabor Greife9ecc682008-04-06 20:25:17 +000011169 PHINode *PN = PHINode::Create(MergedVal->getType(), "storemerge");
Chris Lattner14a251b2007-04-15 00:07:55 +000011170 PN->reserveOperandSpace(2);
11171 PN->addIncoming(SI.getOperand(0), SI.getParent());
Chris Lattner4a6e0cb2007-04-15 01:02:18 +000011172 PN->addIncoming(OtherStore->getOperand(0), OtherBB);
11173 MergedVal = InsertNewInstBefore(PN, DestBB->front());
Chris Lattner14a251b2007-04-15 00:07:55 +000011174 }
11175
11176 // Advance to a place where it is safe to insert the new store and
11177 // insert it.
Dan Gohmanf96e1372008-05-23 21:05:58 +000011178 BBI = DestBB->getFirstNonPHI();
Chris Lattner14a251b2007-04-15 00:07:55 +000011179 InsertNewInstBefore(new StoreInst(MergedVal, SI.getOperand(1),
11180 OtherStore->isVolatile()), *BBI);
11181
11182 // Nuke the old stores.
11183 EraseInstFromFunction(SI);
11184 EraseInstFromFunction(*OtherStore);
11185 ++NumCombined;
11186 return true;
11187}
11188
Chris Lattner31f486c2005-01-31 05:36:43 +000011189
Chris Lattner9eef8a72003-06-04 04:46:00 +000011190Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
11191 // Change br (not X), label True, label False to: br X, label False, True
Reid Spencer4fdd96c2005-06-18 17:37:34 +000011192 Value *X = 0;
Chris Lattnerd4252a72004-07-30 07:50:03 +000011193 BasicBlock *TrueDest;
11194 BasicBlock *FalseDest;
11195 if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
11196 !isa<Constant>(X)) {
11197 // Swap Destinations and condition...
11198 BI.setCondition(X);
11199 BI.setSuccessor(0, FalseDest);
11200 BI.setSuccessor(1, TrueDest);
11201 return &BI;
11202 }
11203
Reid Spencer266e42b2006-12-23 06:05:41 +000011204 // Cannonicalize fcmp_one -> fcmp_oeq
11205 FCmpInst::Predicate FPred; Value *Y;
11206 if (match(&BI, m_Br(m_FCmp(FPred, m_Value(X), m_Value(Y)),
11207 TrueDest, FalseDest)))
11208 if ((FPred == FCmpInst::FCMP_ONE || FPred == FCmpInst::FCMP_OLE ||
11209 FPred == FCmpInst::FCMP_OGE) && BI.getCondition()->hasOneUse()) {
11210 FCmpInst *I = cast<FCmpInst>(BI.getCondition());
Reid Spencer266e42b2006-12-23 06:05:41 +000011211 FCmpInst::Predicate NewPred = FCmpInst::getInversePredicate(FPred);
Chris Lattner6e0123b2007-02-11 01:23:03 +000011212 Instruction *NewSCC = new FCmpInst(NewPred, X, Y, "", I);
11213 NewSCC->takeName(I);
Reid Spencer266e42b2006-12-23 06:05:41 +000011214 // Swap Destinations and condition...
11215 BI.setCondition(NewSCC);
11216 BI.setSuccessor(0, FalseDest);
11217 BI.setSuccessor(1, TrueDest);
Chris Lattnerb15e2b12007-03-02 21:28:56 +000011218 RemoveFromWorkList(I);
Chris Lattner6e0123b2007-02-11 01:23:03 +000011219 I->eraseFromParent();
Chris Lattnerb15e2b12007-03-02 21:28:56 +000011220 AddToWorkList(NewSCC);
Reid Spencer266e42b2006-12-23 06:05:41 +000011221 return &BI;
11222 }
11223
11224 // Cannonicalize icmp_ne -> icmp_eq
11225 ICmpInst::Predicate IPred;
11226 if (match(&BI, m_Br(m_ICmp(IPred, m_Value(X), m_Value(Y)),
11227 TrueDest, FalseDest)))
11228 if ((IPred == ICmpInst::ICMP_NE || IPred == ICmpInst::ICMP_ULE ||
11229 IPred == ICmpInst::ICMP_SLE || IPred == ICmpInst::ICMP_UGE ||
11230 IPred == ICmpInst::ICMP_SGE) && BI.getCondition()->hasOneUse()) {
11231 ICmpInst *I = cast<ICmpInst>(BI.getCondition());
Reid Spencer266e42b2006-12-23 06:05:41 +000011232 ICmpInst::Predicate NewPred = ICmpInst::getInversePredicate(IPred);
Chris Lattner6e0123b2007-02-11 01:23:03 +000011233 Instruction *NewSCC = new ICmpInst(NewPred, X, Y, "", I);
11234 NewSCC->takeName(I);
Chris Lattnere967b342003-06-04 05:10:11 +000011235 // Swap Destinations and condition...
Chris Lattnerd4252a72004-07-30 07:50:03 +000011236 BI.setCondition(NewSCC);
Chris Lattnere967b342003-06-04 05:10:11 +000011237 BI.setSuccessor(0, FalseDest);
11238 BI.setSuccessor(1, TrueDest);
Chris Lattnerb15e2b12007-03-02 21:28:56 +000011239 RemoveFromWorkList(I);
Chris Lattner6e0123b2007-02-11 01:23:03 +000011240 I->eraseFromParent();;
Chris Lattnerb15e2b12007-03-02 21:28:56 +000011241 AddToWorkList(NewSCC);
Chris Lattnere967b342003-06-04 05:10:11 +000011242 return &BI;
11243 }
Misha Brukmanb1c93172005-04-21 23:48:37 +000011244
Chris Lattner9eef8a72003-06-04 04:46:00 +000011245 return 0;
11246}
Chris Lattner1085bdf2002-11-04 16:18:53 +000011247
Chris Lattner4c9c20a2004-07-03 00:26:11 +000011248Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
11249 Value *Cond = SI.getCondition();
11250 if (Instruction *I = dyn_cast<Instruction>(Cond)) {
11251 if (I->getOpcode() == Instruction::Add)
11252 if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
11253 // change 'switch (X+4) case 1:' into 'switch (X) case -3'
11254 for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
Chris Lattner81a7a232004-10-16 18:11:37 +000011255 SI.setOperand(i,ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)),
Chris Lattner4c9c20a2004-07-03 00:26:11 +000011256 AddRHS));
11257 SI.setOperand(0, I->getOperand(0));
Chris Lattnerb15e2b12007-03-02 21:28:56 +000011258 AddToWorkList(I);
Chris Lattner4c9c20a2004-07-03 00:26:11 +000011259 return &SI;
11260 }
11261 }
11262 return 0;
11263}
11264
Matthijs Kooijmanb2fc72b2008-06-11 14:05:05 +000011265Instruction *InstCombiner::visitExtractValueInst(ExtractValueInst &EV) {
Matthijs Kooijmanc1d74772008-07-16 12:55:45 +000011266 Value *Agg = EV.getAggregateOperand();
Matthijs Kooijmanb2fc72b2008-06-11 14:05:05 +000011267
Matthijs Kooijmanc1d74772008-07-16 12:55:45 +000011268 if (!EV.hasIndices())
11269 return ReplaceInstUsesWith(EV, Agg);
11270
11271 if (Constant *C = dyn_cast<Constant>(Agg)) {
11272 if (isa<UndefValue>(C))
11273 return ReplaceInstUsesWith(EV, UndefValue::get(EV.getType()));
11274
11275 if (isa<ConstantAggregateZero>(C))
11276 return ReplaceInstUsesWith(EV, Constant::getNullValue(EV.getType()));
11277
11278 if (isa<ConstantArray>(C) || isa<ConstantStruct>(C)) {
11279 // Extract the element indexed by the first index out of the constant
11280 Value *V = C->getOperand(*EV.idx_begin());
11281 if (EV.getNumIndices() > 1)
11282 // Extract the remaining indices out of the constant indexed by the
11283 // first index
11284 return ExtractValueInst::Create(V, EV.idx_begin() + 1, EV.idx_end());
11285 else
11286 return ReplaceInstUsesWith(EV, V);
11287 }
11288 return 0; // Can't handle other constants
11289 }
11290 if (InsertValueInst *IV = dyn_cast<InsertValueInst>(Agg)) {
11291 // We're extracting from an insertvalue instruction, compare the indices
11292 const unsigned *exti, *exte, *insi, *inse;
11293 for (exti = EV.idx_begin(), insi = IV->idx_begin(),
11294 exte = EV.idx_end(), inse = IV->idx_end();
11295 exti != exte && insi != inse;
11296 ++exti, ++insi) {
11297 if (*insi != *exti)
11298 // The insert and extract both reference distinctly different elements.
11299 // This means the extract is not influenced by the insert, and we can
11300 // replace the aggregate operand of the extract with the aggregate
11301 // operand of the insert. i.e., replace
11302 // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
11303 // %E = extractvalue { i32, { i32 } } %I, 0
11304 // with
11305 // %E = extractvalue { i32, { i32 } } %A, 0
11306 return ExtractValueInst::Create(IV->getAggregateOperand(),
11307 EV.idx_begin(), EV.idx_end());
11308 }
11309 if (exti == exte && insi == inse)
11310 // Both iterators are at the end: Index lists are identical. Replace
11311 // %B = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
11312 // %C = extractvalue { i32, { i32 } } %B, 1, 0
11313 // with "i32 42"
11314 return ReplaceInstUsesWith(EV, IV->getInsertedValueOperand());
11315 if (exti == exte) {
11316 // The extract list is a prefix of the insert list. i.e. replace
11317 // %I = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
11318 // %E = extractvalue { i32, { i32 } } %I, 1
11319 // with
11320 // %X = extractvalue { i32, { i32 } } %A, 1
11321 // %E = insertvalue { i32 } %X, i32 42, 0
11322 // by switching the order of the insert and extract (though the
11323 // insertvalue should be left in, since it may have other uses).
11324 Value *NewEV = InsertNewInstBefore(
11325 ExtractValueInst::Create(IV->getAggregateOperand(),
11326 EV.idx_begin(), EV.idx_end()),
11327 EV);
11328 return InsertValueInst::Create(NewEV, IV->getInsertedValueOperand(),
11329 insi, inse);
11330 }
11331 if (insi == inse)
11332 // The insert list is a prefix of the extract list
11333 // We can simply remove the common indices from the extract and make it
11334 // operate on the inserted value instead of the insertvalue result.
11335 // i.e., replace
11336 // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
11337 // %E = extractvalue { i32, { i32 } } %I, 1, 0
11338 // with
11339 // %E extractvalue { i32 } { i32 42 }, 0
11340 return ExtractValueInst::Create(IV->getInsertedValueOperand(),
11341 exti, exte);
11342 }
11343 // Can't simplify extracts from other values. Note that nested extracts are
11344 // already simplified implicitely by the above (extract ( extract (insert) )
11345 // will be translated into extract ( insert ( extract ) ) first and then just
11346 // the value inserted, if appropriate).
Matthijs Kooijmanb2fc72b2008-06-11 14:05:05 +000011347 return 0;
11348}
11349
Chris Lattner6bc98652006-03-05 00:22:33 +000011350/// CheapToScalarize - Return true if the value is cheaper to scalarize than it
11351/// is to leave as a vector operation.
11352static bool CheapToScalarize(Value *V, bool isConstant) {
11353 if (isa<ConstantAggregateZero>(V))
11354 return true;
Reid Spencerd84d35b2007-02-15 02:26:10 +000011355 if (ConstantVector *C = dyn_cast<ConstantVector>(V)) {
Chris Lattner6bc98652006-03-05 00:22:33 +000011356 if (isConstant) return true;
11357 // If all elts are the same, we can extract.
11358 Constant *Op0 = C->getOperand(0);
11359 for (unsigned i = 1; i < C->getNumOperands(); ++i)
11360 if (C->getOperand(i) != Op0)
11361 return false;
11362 return true;
11363 }
11364 Instruction *I = dyn_cast<Instruction>(V);
11365 if (!I) return false;
11366
11367 // Insert element gets simplified to the inserted element or is deleted if
11368 // this is constant idx extract element and its a constant idx insertelt.
11369 if (I->getOpcode() == Instruction::InsertElement && isConstant &&
11370 isa<ConstantInt>(I->getOperand(2)))
11371 return true;
11372 if (I->getOpcode() == Instruction::Load && I->hasOneUse())
11373 return true;
11374 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I))
11375 if (BO->hasOneUse() &&
11376 (CheapToScalarize(BO->getOperand(0), isConstant) ||
11377 CheapToScalarize(BO->getOperand(1), isConstant)))
11378 return true;
Reid Spencer266e42b2006-12-23 06:05:41 +000011379 if (CmpInst *CI = dyn_cast<CmpInst>(I))
11380 if (CI->hasOneUse() &&
11381 (CheapToScalarize(CI->getOperand(0), isConstant) ||
11382 CheapToScalarize(CI->getOperand(1), isConstant)))
11383 return true;
Chris Lattner6bc98652006-03-05 00:22:33 +000011384
11385 return false;
11386}
11387
Chris Lattner945e4372007-02-14 05:52:17 +000011388/// Read and decode a shufflevector mask.
11389///
11390/// It turns undef elements into values that are larger than the number of
11391/// elements in the input.
Chris Lattner12249be2006-05-25 23:48:38 +000011392static std::vector<unsigned> getShuffleMask(const ShuffleVectorInst *SVI) {
11393 unsigned NElts = SVI->getType()->getNumElements();
11394 if (isa<ConstantAggregateZero>(SVI->getOperand(2)))
11395 return std::vector<unsigned>(NElts, 0);
11396 if (isa<UndefValue>(SVI->getOperand(2)))
11397 return std::vector<unsigned>(NElts, 2*NElts);
11398
11399 std::vector<unsigned> Result;
Reid Spencerd84d35b2007-02-15 02:26:10 +000011400 const ConstantVector *CP = cast<ConstantVector>(SVI->getOperand(2));
Gabor Greiff6d8e772008-06-12 21:37:33 +000011401 for (User::const_op_iterator i = CP->op_begin(), e = CP->op_end(); i!=e; ++i)
11402 if (isa<UndefValue>(*i))
Chris Lattner12249be2006-05-25 23:48:38 +000011403 Result.push_back(NElts*2); // undef -> 8
11404 else
Gabor Greiff6d8e772008-06-12 21:37:33 +000011405 Result.push_back(cast<ConstantInt>(*i)->getZExtValue());
Chris Lattner12249be2006-05-25 23:48:38 +000011406 return Result;
11407}
11408
Chris Lattner8d1d8d32006-03-31 23:01:56 +000011409/// FindScalarElement - Given a vector and an element number, see if the scalar
11410/// value is already around as a register, for example if it were inserted then
11411/// extracted from the vector.
11412static Value *FindScalarElement(Value *V, unsigned EltNo) {
Reid Spencerd84d35b2007-02-15 02:26:10 +000011413 assert(isa<VectorType>(V->getType()) && "Not looking at a vector?");
11414 const VectorType *PTy = cast<VectorType>(V->getType());
Chris Lattner2d37f922006-04-10 23:06:36 +000011415 unsigned Width = PTy->getNumElements();
11416 if (EltNo >= Width) // Out of range access.
Chris Lattner8d1d8d32006-03-31 23:01:56 +000011417 return UndefValue::get(PTy->getElementType());
11418
11419 if (isa<UndefValue>(V))
11420 return UndefValue::get(PTy->getElementType());
11421 else if (isa<ConstantAggregateZero>(V))
11422 return Constant::getNullValue(PTy->getElementType());
Reid Spencerd84d35b2007-02-15 02:26:10 +000011423 else if (ConstantVector *CP = dyn_cast<ConstantVector>(V))
Chris Lattner8d1d8d32006-03-31 23:01:56 +000011424 return CP->getOperand(EltNo);
11425 else if (InsertElementInst *III = dyn_cast<InsertElementInst>(V)) {
11426 // If this is an insert to a variable element, we don't know what it is.
Reid Spencere0fc4df2006-10-20 07:07:24 +000011427 if (!isa<ConstantInt>(III->getOperand(2)))
11428 return 0;
11429 unsigned IIElt = cast<ConstantInt>(III->getOperand(2))->getZExtValue();
Chris Lattner8d1d8d32006-03-31 23:01:56 +000011430
11431 // If this is an insert to the element we are looking for, return the
11432 // inserted value.
Reid Spencere0fc4df2006-10-20 07:07:24 +000011433 if (EltNo == IIElt)
11434 return III->getOperand(1);
Chris Lattner8d1d8d32006-03-31 23:01:56 +000011435
11436 // Otherwise, the insertelement doesn't modify the value, recurse on its
11437 // vector input.
11438 return FindScalarElement(III->getOperand(0), EltNo);
Chris Lattner2d37f922006-04-10 23:06:36 +000011439 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(V)) {
Mon P Wang25f01062008-11-10 04:46:22 +000011440 unsigned LHSWidth =
11441 cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements();
Chris Lattner12249be2006-05-25 23:48:38 +000011442 unsigned InEl = getShuffleMask(SVI)[EltNo];
Mon P Wang25f01062008-11-10 04:46:22 +000011443 if (InEl < LHSWidth)
Chris Lattner12249be2006-05-25 23:48:38 +000011444 return FindScalarElement(SVI->getOperand(0), InEl);
Mon P Wang25f01062008-11-10 04:46:22 +000011445 else if (InEl < LHSWidth*2)
11446 return FindScalarElement(SVI->getOperand(1), InEl - LHSWidth);
Chris Lattner12249be2006-05-25 23:48:38 +000011447 else
11448 return UndefValue::get(PTy->getElementType());
Chris Lattner8d1d8d32006-03-31 23:01:56 +000011449 }
11450
11451 // Otherwise, we don't know.
11452 return 0;
11453}
11454
Robert Bocchinoa8352962006-01-13 22:48:06 +000011455Instruction *InstCombiner::visitExtractElementInst(ExtractElementInst &EI) {
Dan Gohman06c60b62007-07-16 14:29:03 +000011456 // If vector val is undef, replace extract with scalar undef.
Chris Lattner92346c32006-03-31 18:25:14 +000011457 if (isa<UndefValue>(EI.getOperand(0)))
11458 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
11459
Dan Gohman06c60b62007-07-16 14:29:03 +000011460 // If vector val is constant 0, replace extract with scalar 0.
Chris Lattner92346c32006-03-31 18:25:14 +000011461 if (isa<ConstantAggregateZero>(EI.getOperand(0)))
11462 return ReplaceInstUsesWith(EI, Constant::getNullValue(EI.getType()));
11463
Reid Spencerd84d35b2007-02-15 02:26:10 +000011464 if (ConstantVector *C = dyn_cast<ConstantVector>(EI.getOperand(0))) {
Matthijs Kooijman3453c7b2008-06-11 09:00:12 +000011465 // If vector val is constant with all elements the same, replace EI with
11466 // that element. When the elements are not identical, we cannot replace yet
11467 // (we do that below, but only when the index is constant).
Chris Lattner6bc98652006-03-05 00:22:33 +000011468 Constant *op0 = C->getOperand(0);
Robert Bocchinoa8352962006-01-13 22:48:06 +000011469 for (unsigned i = 1; i < C->getNumOperands(); ++i)
Chris Lattner6bc98652006-03-05 00:22:33 +000011470 if (C->getOperand(i) != op0) {
11471 op0 = 0;
11472 break;
11473 }
11474 if (op0)
11475 return ReplaceInstUsesWith(EI, op0);
Robert Bocchinoa8352962006-01-13 22:48:06 +000011476 }
Chris Lattner6bc98652006-03-05 00:22:33 +000011477
Chris Lattner8d1d8d32006-03-31 23:01:56 +000011478 // If extracting a specified index from the vector, see if we can recursively
11479 // find a previously computed scalar that was inserted into the vector.
Reid Spencere0fc4df2006-10-20 07:07:24 +000011480 if (ConstantInt *IdxC = dyn_cast<ConstantInt>(EI.getOperand(1))) {
Chris Lattnera87c9f62007-04-09 01:37:55 +000011481 unsigned IndexVal = IdxC->getZExtValue();
11482 unsigned VectorWidth =
11483 cast<VectorType>(EI.getOperand(0)->getType())->getNumElements();
11484
11485 // If this is extracting an invalid index, turn this into undef, to avoid
11486 // crashing the code below.
11487 if (IndexVal >= VectorWidth)
11488 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
11489
Chris Lattner2deeaea2006-10-05 06:55:50 +000011490 // This instruction only demands the single element from the input vector.
11491 // If the input vector has a single use, simplify it based on this use
11492 // property.
Chris Lattnera87c9f62007-04-09 01:37:55 +000011493 if (EI.getOperand(0)->hasOneUse() && VectorWidth != 1) {
Chris Lattner2deeaea2006-10-05 06:55:50 +000011494 uint64_t UndefElts;
11495 if (Value *V = SimplifyDemandedVectorElts(EI.getOperand(0),
Reid Spencere0fc4df2006-10-20 07:07:24 +000011496 1 << IndexVal,
Chris Lattner2deeaea2006-10-05 06:55:50 +000011497 UndefElts)) {
11498 EI.setOperand(0, V);
11499 return &EI;
11500 }
11501 }
11502
Reid Spencere0fc4df2006-10-20 07:07:24 +000011503 if (Value *Elt = FindScalarElement(EI.getOperand(0), IndexVal))
Chris Lattner8d1d8d32006-03-31 23:01:56 +000011504 return ReplaceInstUsesWith(EI, Elt);
Chris Lattner7bfdd0a2007-04-14 23:02:14 +000011505
11506 // If the this extractelement is directly using a bitcast from a vector of
11507 // the same number of elements, see if we can find the source element from
11508 // it. In this case, we will end up needing to bitcast the scalars.
11509 if (BitCastInst *BCI = dyn_cast<BitCastInst>(EI.getOperand(0))) {
11510 if (const VectorType *VT =
11511 dyn_cast<VectorType>(BCI->getOperand(0)->getType()))
11512 if (VT->getNumElements() == VectorWidth)
11513 if (Value *Elt = FindScalarElement(BCI->getOperand(0), IndexVal))
11514 return new BitCastInst(Elt, EI.getType());
11515 }
Chris Lattner2d37f922006-04-10 23:06:36 +000011516 }
Chris Lattner8d1d8d32006-03-31 23:01:56 +000011517
Chris Lattner83f65782006-05-25 22:53:38 +000011518 if (Instruction *I = dyn_cast<Instruction>(EI.getOperand(0))) {
Robert Bocchinoa8352962006-01-13 22:48:06 +000011519 if (I->hasOneUse()) {
11520 // Push extractelement into predecessor operation if legal and
11521 // profitable to do so
11522 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
Chris Lattner6bc98652006-03-05 00:22:33 +000011523 bool isConstantElt = isa<ConstantInt>(EI.getOperand(1));
11524 if (CheapToScalarize(BO, isConstantElt)) {
11525 ExtractElementInst *newEI0 =
11526 new ExtractElementInst(BO->getOperand(0), EI.getOperand(1),
11527 EI.getName()+".lhs");
11528 ExtractElementInst *newEI1 =
11529 new ExtractElementInst(BO->getOperand(1), EI.getOperand(1),
11530 EI.getName()+".rhs");
11531 InsertNewInstBefore(newEI0, EI);
11532 InsertNewInstBefore(newEI1, EI);
Gabor Greife1f6e4b2008-05-16 19:29:10 +000011533 return BinaryOperator::Create(BO->getOpcode(), newEI0, newEI1);
Chris Lattner6bc98652006-03-05 00:22:33 +000011534 }
Reid Spencerde46e482006-11-02 20:25:50 +000011535 } else if (isa<LoadInst>(I)) {
Christopher Lambedf07882007-12-17 01:12:55 +000011536 unsigned AS =
11537 cast<PointerType>(I->getOperand(0)->getType())->getAddressSpace();
Chris Lattner5a866122008-01-13 22:23:22 +000011538 Value *Ptr = InsertBitCastBefore(I->getOperand(0),
11539 PointerType::get(EI.getType(), AS),EI);
Gabor Greif697e94c2008-05-15 10:04:30 +000011540 GetElementPtrInst *GEP =
11541 GetElementPtrInst::Create(Ptr, EI.getOperand(1), I->getName()+".gep");
Robert Bocchinoa8352962006-01-13 22:48:06 +000011542 InsertNewInstBefore(GEP, EI);
11543 return new LoadInst(GEP);
Chris Lattner83f65782006-05-25 22:53:38 +000011544 }
11545 }
11546 if (InsertElementInst *IE = dyn_cast<InsertElementInst>(I)) {
11547 // Extracting the inserted element?
11548 if (IE->getOperand(2) == EI.getOperand(1))
11549 return ReplaceInstUsesWith(EI, IE->getOperand(1));
11550 // If the inserted and extracted elements are constants, they must not
11551 // be the same value, extract from the pre-inserted value instead.
11552 if (isa<Constant>(IE->getOperand(2)) &&
11553 isa<Constant>(EI.getOperand(1))) {
11554 AddUsesToWorkList(EI);
11555 EI.setOperand(0, IE->getOperand(0));
11556 return &EI;
11557 }
11558 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I)) {
11559 // If this is extracting an element from a shufflevector, figure out where
11560 // it came from and extract from the appropriate input element instead.
Reid Spencere0fc4df2006-10-20 07:07:24 +000011561 if (ConstantInt *Elt = dyn_cast<ConstantInt>(EI.getOperand(1))) {
11562 unsigned SrcIdx = getShuffleMask(SVI)[Elt->getZExtValue()];
Chris Lattner12249be2006-05-25 23:48:38 +000011563 Value *Src;
Mon P Wang25f01062008-11-10 04:46:22 +000011564 unsigned LHSWidth =
11565 cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements();
11566
11567 if (SrcIdx < LHSWidth)
Chris Lattner12249be2006-05-25 23:48:38 +000011568 Src = SVI->getOperand(0);
Mon P Wang25f01062008-11-10 04:46:22 +000011569 else if (SrcIdx < LHSWidth*2) {
11570 SrcIdx -= LHSWidth;
Chris Lattner12249be2006-05-25 23:48:38 +000011571 Src = SVI->getOperand(1);
11572 } else {
11573 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
Chris Lattner612fa8e2006-03-30 22:02:40 +000011574 }
Chris Lattner2deeaea2006-10-05 06:55:50 +000011575 return new ExtractElementInst(Src, SrcIdx);
Robert Bocchinoa8352962006-01-13 22:48:06 +000011576 }
11577 }
Chris Lattner83f65782006-05-25 22:53:38 +000011578 }
Robert Bocchinoa8352962006-01-13 22:48:06 +000011579 return 0;
11580}
11581
Chris Lattner90951862006-04-16 00:51:47 +000011582/// CollectSingleShuffleElements - If V is a shuffle of values that ONLY returns
11583/// elements from either LHS or RHS, return the shuffle mask and true.
11584/// Otherwise, return false.
11585static bool CollectSingleShuffleElements(Value *V, Value *LHS, Value *RHS,
11586 std::vector<Constant*> &Mask) {
11587 assert(V->getType() == LHS->getType() && V->getType() == RHS->getType() &&
11588 "Invalid CollectSingleShuffleElements");
Reid Spencerd84d35b2007-02-15 02:26:10 +000011589 unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
Chris Lattner90951862006-04-16 00:51:47 +000011590
11591 if (isa<UndefValue>(V)) {
Reid Spencerc635f472006-12-31 05:48:39 +000011592 Mask.assign(NumElts, UndefValue::get(Type::Int32Ty));
Chris Lattner90951862006-04-16 00:51:47 +000011593 return true;
11594 } else if (V == LHS) {
11595 for (unsigned i = 0; i != NumElts; ++i)
Reid Spencerc635f472006-12-31 05:48:39 +000011596 Mask.push_back(ConstantInt::get(Type::Int32Ty, i));
Chris Lattner90951862006-04-16 00:51:47 +000011597 return true;
11598 } else if (V == RHS) {
11599 for (unsigned i = 0; i != NumElts; ++i)
Reid Spencerc635f472006-12-31 05:48:39 +000011600 Mask.push_back(ConstantInt::get(Type::Int32Ty, i+NumElts));
Chris Lattner90951862006-04-16 00:51:47 +000011601 return true;
11602 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
11603 // If this is an insert of an extract from some other vector, include it.
11604 Value *VecOp = IEI->getOperand(0);
11605 Value *ScalarOp = IEI->getOperand(1);
11606 Value *IdxOp = IEI->getOperand(2);
11607
Chris Lattnerb6cb64b2006-04-27 21:14:21 +000011608 if (!isa<ConstantInt>(IdxOp))
11609 return false;
Reid Spencere0fc4df2006-10-20 07:07:24 +000011610 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattnerb6cb64b2006-04-27 21:14:21 +000011611
11612 if (isa<UndefValue>(ScalarOp)) { // inserting undef into vector.
11613 // Okay, we can handle this if the vector we are insertinting into is
11614 // transitively ok.
11615 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
11616 // If so, update the mask to reflect the inserted undef.
Reid Spencerc635f472006-12-31 05:48:39 +000011617 Mask[InsertedIdx] = UndefValue::get(Type::Int32Ty);
Chris Lattnerb6cb64b2006-04-27 21:14:21 +000011618 return true;
11619 }
11620 } else if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)){
11621 if (isa<ConstantInt>(EI->getOperand(1)) &&
Chris Lattner90951862006-04-16 00:51:47 +000011622 EI->getOperand(0)->getType() == V->getType()) {
11623 unsigned ExtractedIdx =
Reid Spencere0fc4df2006-10-20 07:07:24 +000011624 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
Chris Lattner90951862006-04-16 00:51:47 +000011625
11626 // This must be extracting from either LHS or RHS.
11627 if (EI->getOperand(0) == LHS || EI->getOperand(0) == RHS) {
11628 // Okay, we can handle this if the vector we are insertinting into is
11629 // transitively ok.
11630 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
11631 // If so, update the mask to reflect the inserted value.
11632 if (EI->getOperand(0) == LHS) {
Mon P Wang1b2c0612008-08-20 02:23:25 +000011633 Mask[InsertedIdx % NumElts] =
Reid Spencerc635f472006-12-31 05:48:39 +000011634 ConstantInt::get(Type::Int32Ty, ExtractedIdx);
Chris Lattner90951862006-04-16 00:51:47 +000011635 } else {
11636 assert(EI->getOperand(0) == RHS);
Mon P Wang1b2c0612008-08-20 02:23:25 +000011637 Mask[InsertedIdx % NumElts] =
Reid Spencerc635f472006-12-31 05:48:39 +000011638 ConstantInt::get(Type::Int32Ty, ExtractedIdx+NumElts);
Chris Lattner90951862006-04-16 00:51:47 +000011639
11640 }
11641 return true;
11642 }
11643 }
11644 }
11645 }
11646 }
11647 // TODO: Handle shufflevector here!
11648
11649 return false;
11650}
11651
11652/// CollectShuffleElements - We are building a shuffle of V, using RHS as the
11653/// RHS of the shuffle instruction, if it is not null. Return a shuffle mask
11654/// that computes V and the LHS value of the shuffle.
Chris Lattner39fac442006-04-15 01:39:45 +000011655static Value *CollectShuffleElements(Value *V, std::vector<Constant*> &Mask,
Chris Lattner90951862006-04-16 00:51:47 +000011656 Value *&RHS) {
Reid Spencerd84d35b2007-02-15 02:26:10 +000011657 assert(isa<VectorType>(V->getType()) &&
Chris Lattner90951862006-04-16 00:51:47 +000011658 (RHS == 0 || V->getType() == RHS->getType()) &&
Chris Lattner39fac442006-04-15 01:39:45 +000011659 "Invalid shuffle!");
Reid Spencerd84d35b2007-02-15 02:26:10 +000011660 unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
Chris Lattner39fac442006-04-15 01:39:45 +000011661
11662 if (isa<UndefValue>(V)) {
Reid Spencerc635f472006-12-31 05:48:39 +000011663 Mask.assign(NumElts, UndefValue::get(Type::Int32Ty));
Chris Lattner39fac442006-04-15 01:39:45 +000011664 return V;
11665 } else if (isa<ConstantAggregateZero>(V)) {
Reid Spencerc635f472006-12-31 05:48:39 +000011666 Mask.assign(NumElts, ConstantInt::get(Type::Int32Ty, 0));
Chris Lattner39fac442006-04-15 01:39:45 +000011667 return V;
11668 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
11669 // If this is an insert of an extract from some other vector, include it.
11670 Value *VecOp = IEI->getOperand(0);
11671 Value *ScalarOp = IEI->getOperand(1);
11672 Value *IdxOp = IEI->getOperand(2);
11673
11674 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
11675 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
11676 EI->getOperand(0)->getType() == V->getType()) {
11677 unsigned ExtractedIdx =
Reid Spencere0fc4df2006-10-20 07:07:24 +000011678 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
11679 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattner39fac442006-04-15 01:39:45 +000011680
11681 // Either the extracted from or inserted into vector must be RHSVec,
11682 // otherwise we'd end up with a shuffle of three inputs.
Chris Lattner90951862006-04-16 00:51:47 +000011683 if (EI->getOperand(0) == RHS || RHS == 0) {
11684 RHS = EI->getOperand(0);
11685 Value *V = CollectShuffleElements(VecOp, Mask, RHS);
Mon P Wang1b2c0612008-08-20 02:23:25 +000011686 Mask[InsertedIdx % NumElts] =
Reid Spencerc635f472006-12-31 05:48:39 +000011687 ConstantInt::get(Type::Int32Ty, NumElts+ExtractedIdx);
Chris Lattner39fac442006-04-15 01:39:45 +000011688 return V;
11689 }
11690
Chris Lattner90951862006-04-16 00:51:47 +000011691 if (VecOp == RHS) {
11692 Value *V = CollectShuffleElements(EI->getOperand(0), Mask, RHS);
Chris Lattner39fac442006-04-15 01:39:45 +000011693 // Everything but the extracted element is replaced with the RHS.
11694 for (unsigned i = 0; i != NumElts; ++i) {
11695 if (i != InsertedIdx)
Reid Spencerc635f472006-12-31 05:48:39 +000011696 Mask[i] = ConstantInt::get(Type::Int32Ty, NumElts+i);
Chris Lattner39fac442006-04-15 01:39:45 +000011697 }
11698 return V;
11699 }
Chris Lattner90951862006-04-16 00:51:47 +000011700
11701 // If this insertelement is a chain that comes from exactly these two
11702 // vectors, return the vector and the effective shuffle.
11703 if (CollectSingleShuffleElements(IEI, EI->getOperand(0), RHS, Mask))
11704 return EI->getOperand(0);
11705
Chris Lattner39fac442006-04-15 01:39:45 +000011706 }
11707 }
11708 }
Chris Lattner90951862006-04-16 00:51:47 +000011709 // TODO: Handle shufflevector here!
Chris Lattner39fac442006-04-15 01:39:45 +000011710
11711 // Otherwise, can't do anything fancy. Return an identity vector.
11712 for (unsigned i = 0; i != NumElts; ++i)
Reid Spencerc635f472006-12-31 05:48:39 +000011713 Mask.push_back(ConstantInt::get(Type::Int32Ty, i));
Chris Lattner39fac442006-04-15 01:39:45 +000011714 return V;
11715}
11716
11717Instruction *InstCombiner::visitInsertElementInst(InsertElementInst &IE) {
11718 Value *VecOp = IE.getOperand(0);
11719 Value *ScalarOp = IE.getOperand(1);
11720 Value *IdxOp = IE.getOperand(2);
11721
Chris Lattner4ca9cbb2007-04-09 01:11:16 +000011722 // Inserting an undef or into an undefined place, remove this.
11723 if (isa<UndefValue>(ScalarOp) || isa<UndefValue>(IdxOp))
11724 ReplaceInstUsesWith(IE, VecOp);
11725
Chris Lattner39fac442006-04-15 01:39:45 +000011726 // If the inserted element was extracted from some other vector, and if the
11727 // indexes are constant, try to turn this into a shufflevector operation.
11728 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
11729 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
11730 EI->getOperand(0)->getType() == IE.getType()) {
11731 unsigned NumVectorElts = IE.getType()->getNumElements();
Chris Lattner28d921d2007-04-14 23:32:02 +000011732 unsigned ExtractedIdx =
11733 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
Reid Spencere0fc4df2006-10-20 07:07:24 +000011734 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattner39fac442006-04-15 01:39:45 +000011735
11736 if (ExtractedIdx >= NumVectorElts) // Out of range extract.
11737 return ReplaceInstUsesWith(IE, VecOp);
11738
11739 if (InsertedIdx >= NumVectorElts) // Out of range insert.
11740 return ReplaceInstUsesWith(IE, UndefValue::get(IE.getType()));
11741
11742 // If we are extracting a value from a vector, then inserting it right
11743 // back into the same place, just use the input vector.
11744 if (EI->getOperand(0) == VecOp && ExtractedIdx == InsertedIdx)
11745 return ReplaceInstUsesWith(IE, VecOp);
11746
11747 // We could theoretically do this for ANY input. However, doing so could
11748 // turn chains of insertelement instructions into a chain of shufflevector
11749 // instructions, and right now we do not merge shufflevectors. As such,
11750 // only do this in a situation where it is clear that there is benefit.
11751 if (isa<UndefValue>(VecOp) || isa<ConstantAggregateZero>(VecOp)) {
11752 // Turn this into shuffle(EIOp0, VecOp, Mask). The result has all of
11753 // the values of VecOp, except then one read from EIOp0.
11754 // Build a new shuffle mask.
11755 std::vector<Constant*> Mask;
11756 if (isa<UndefValue>(VecOp))
Reid Spencerc635f472006-12-31 05:48:39 +000011757 Mask.assign(NumVectorElts, UndefValue::get(Type::Int32Ty));
Chris Lattner39fac442006-04-15 01:39:45 +000011758 else {
11759 assert(isa<ConstantAggregateZero>(VecOp) && "Unknown thing");
Reid Spencerc635f472006-12-31 05:48:39 +000011760 Mask.assign(NumVectorElts, ConstantInt::get(Type::Int32Ty,
Chris Lattner39fac442006-04-15 01:39:45 +000011761 NumVectorElts));
11762 }
Reid Spencerc635f472006-12-31 05:48:39 +000011763 Mask[InsertedIdx] = ConstantInt::get(Type::Int32Ty, ExtractedIdx);
Chris Lattner39fac442006-04-15 01:39:45 +000011764 return new ShuffleVectorInst(EI->getOperand(0), VecOp,
Reid Spencerd84d35b2007-02-15 02:26:10 +000011765 ConstantVector::get(Mask));
Chris Lattner39fac442006-04-15 01:39:45 +000011766 }
11767
11768 // If this insertelement isn't used by some other insertelement, turn it
11769 // (and any insertelements it points to), into one big shuffle.
11770 if (!IE.hasOneUse() || !isa<InsertElementInst>(IE.use_back())) {
11771 std::vector<Constant*> Mask;
Chris Lattner90951862006-04-16 00:51:47 +000011772 Value *RHS = 0;
11773 Value *LHS = CollectShuffleElements(&IE, Mask, RHS);
11774 if (RHS == 0) RHS = UndefValue::get(LHS->getType());
11775 // We now have a shuffle of LHS, RHS, Mask.
Reid Spencerd84d35b2007-02-15 02:26:10 +000011776 return new ShuffleVectorInst(LHS, RHS, ConstantVector::get(Mask));
Chris Lattner39fac442006-04-15 01:39:45 +000011777 }
11778 }
11779 }
11780
11781 return 0;
11782}
11783
11784
Chris Lattnerfbb77a42006-04-10 22:45:52 +000011785Instruction *InstCombiner::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
11786 Value *LHS = SVI.getOperand(0);
11787 Value *RHS = SVI.getOperand(1);
Chris Lattner12249be2006-05-25 23:48:38 +000011788 std::vector<unsigned> Mask = getShuffleMask(&SVI);
Chris Lattnerfbb77a42006-04-10 22:45:52 +000011789
11790 bool MadeChange = false;
Mon P Wang25f01062008-11-10 04:46:22 +000011791
Chris Lattner2deeaea2006-10-05 06:55:50 +000011792 // Undefined shuffle mask -> undefined value.
Chris Lattner12249be2006-05-25 23:48:38 +000011793 if (isa<UndefValue>(SVI.getOperand(2)))
Chris Lattnerfbb77a42006-04-10 22:45:52 +000011794 return ReplaceInstUsesWith(SVI, UndefValue::get(SVI.getType()));
Dan Gohman86fb5b42008-09-09 18:11:14 +000011795
11796 uint64_t UndefElts;
11797 unsigned VWidth = cast<VectorType>(SVI.getType())->getNumElements();
Mon P Wang25f01062008-11-10 04:46:22 +000011798
11799 if (VWidth != cast<VectorType>(LHS->getType())->getNumElements())
11800 return 0;
11801
Dan Gohman86fb5b42008-09-09 18:11:14 +000011802 uint64_t AllOnesEltMask = ~0ULL >> (64-VWidth);
11803 if (VWidth <= 64 &&
Dan Gohman7d01c062008-09-11 22:47:57 +000011804 SimplifyDemandedVectorElts(&SVI, AllOnesEltMask, UndefElts)) {
11805 LHS = SVI.getOperand(0);
11806 RHS = SVI.getOperand(1);
Dan Gohman86fb5b42008-09-09 18:11:14 +000011807 MadeChange = true;
Dan Gohman7d01c062008-09-11 22:47:57 +000011808 }
Chris Lattner39fac442006-04-15 01:39:45 +000011809
Chris Lattner12249be2006-05-25 23:48:38 +000011810 // Canonicalize shuffle(x ,x,mask) -> shuffle(x, undef,mask')
11811 // Canonicalize shuffle(undef,x,mask) -> shuffle(x, undef,mask').
11812 if (LHS == RHS || isa<UndefValue>(LHS)) {
11813 if (isa<UndefValue>(LHS) && LHS == RHS) {
Chris Lattnerfbb77a42006-04-10 22:45:52 +000011814 // shuffle(undef,undef,mask) -> undef.
11815 return ReplaceInstUsesWith(SVI, LHS);
11816 }
11817
Chris Lattner12249be2006-05-25 23:48:38 +000011818 // Remap any references to RHS to use LHS.
11819 std::vector<Constant*> Elts;
11820 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
Chris Lattner0e477162006-05-26 00:29:06 +000011821 if (Mask[i] >= 2*e)
Reid Spencerc635f472006-12-31 05:48:39 +000011822 Elts.push_back(UndefValue::get(Type::Int32Ty));
Chris Lattner0e477162006-05-26 00:29:06 +000011823 else {
11824 if ((Mask[i] >= e && isa<UndefValue>(RHS)) ||
Dan Gohmanac22cfc2008-08-06 18:17:32 +000011825 (Mask[i] < e && isa<UndefValue>(LHS))) {
Chris Lattner0e477162006-05-26 00:29:06 +000011826 Mask[i] = 2*e; // Turn into undef.
Dan Gohmanac22cfc2008-08-06 18:17:32 +000011827 Elts.push_back(UndefValue::get(Type::Int32Ty));
11828 } else {
Mon P Wang1b2c0612008-08-20 02:23:25 +000011829 Mask[i] = Mask[i] % e; // Force to LHS.
Dan Gohmanac22cfc2008-08-06 18:17:32 +000011830 Elts.push_back(ConstantInt::get(Type::Int32Ty, Mask[i]));
11831 }
Chris Lattner0e477162006-05-26 00:29:06 +000011832 }
Chris Lattnerfbb77a42006-04-10 22:45:52 +000011833 }
Chris Lattner12249be2006-05-25 23:48:38 +000011834 SVI.setOperand(0, SVI.getOperand(1));
Chris Lattnerfbb77a42006-04-10 22:45:52 +000011835 SVI.setOperand(1, UndefValue::get(RHS->getType()));
Reid Spencerd84d35b2007-02-15 02:26:10 +000011836 SVI.setOperand(2, ConstantVector::get(Elts));
Chris Lattner0e477162006-05-26 00:29:06 +000011837 LHS = SVI.getOperand(0);
11838 RHS = SVI.getOperand(1);
Chris Lattnerfbb77a42006-04-10 22:45:52 +000011839 MadeChange = true;
11840 }
11841
Chris Lattner0e477162006-05-26 00:29:06 +000011842 // Analyze the shuffle, are the LHS or RHS and identity shuffles?
Chris Lattner12249be2006-05-25 23:48:38 +000011843 bool isLHSID = true, isRHSID = true;
Chris Lattner34cebe72006-04-16 00:03:56 +000011844
Chris Lattner12249be2006-05-25 23:48:38 +000011845 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
11846 if (Mask[i] >= e*2) continue; // Ignore undef values.
11847 // Is this an identity shuffle of the LHS value?
11848 isLHSID &= (Mask[i] == i);
11849
11850 // Is this an identity shuffle of the RHS value?
11851 isRHSID &= (Mask[i]-e == i);
Chris Lattner34cebe72006-04-16 00:03:56 +000011852 }
Chris Lattnerfbb77a42006-04-10 22:45:52 +000011853
Chris Lattner12249be2006-05-25 23:48:38 +000011854 // Eliminate identity shuffles.
11855 if (isLHSID) return ReplaceInstUsesWith(SVI, LHS);
11856 if (isRHSID) return ReplaceInstUsesWith(SVI, RHS);
Chris Lattnerfbb77a42006-04-10 22:45:52 +000011857
Chris Lattner0e477162006-05-26 00:29:06 +000011858 // If the LHS is a shufflevector itself, see if we can combine it with this
11859 // one without producing an unusual shuffle. Here we are really conservative:
11860 // we are absolutely afraid of producing a shuffle mask not in the input
11861 // program, because the code gen may not be smart enough to turn a merged
11862 // shuffle into two specific shuffles: it may produce worse code. As such,
11863 // we only merge two shuffles if the result is one of the two input shuffle
11864 // masks. In this case, merging the shuffles just removes one instruction,
11865 // which we know is safe. This is good for things like turning:
11866 // (splat(splat)) -> splat.
11867 if (ShuffleVectorInst *LHSSVI = dyn_cast<ShuffleVectorInst>(LHS)) {
11868 if (isa<UndefValue>(RHS)) {
11869 std::vector<unsigned> LHSMask = getShuffleMask(LHSSVI);
11870
11871 std::vector<unsigned> NewMask;
11872 for (unsigned i = 0, e = Mask.size(); i != e; ++i)
11873 if (Mask[i] >= 2*e)
11874 NewMask.push_back(2*e);
11875 else
11876 NewMask.push_back(LHSMask[Mask[i]]);
11877
11878 // If the result mask is equal to the src shuffle or this shuffle mask, do
11879 // the replacement.
11880 if (NewMask == LHSMask || NewMask == Mask) {
11881 std::vector<Constant*> Elts;
11882 for (unsigned i = 0, e = NewMask.size(); i != e; ++i) {
11883 if (NewMask[i] >= e*2) {
Reid Spencerc635f472006-12-31 05:48:39 +000011884 Elts.push_back(UndefValue::get(Type::Int32Ty));
Chris Lattner0e477162006-05-26 00:29:06 +000011885 } else {
Reid Spencerc635f472006-12-31 05:48:39 +000011886 Elts.push_back(ConstantInt::get(Type::Int32Ty, NewMask[i]));
Chris Lattner0e477162006-05-26 00:29:06 +000011887 }
11888 }
11889 return new ShuffleVectorInst(LHSSVI->getOperand(0),
11890 LHSSVI->getOperand(1),
Reid Spencerd84d35b2007-02-15 02:26:10 +000011891 ConstantVector::get(Elts));
Chris Lattner0e477162006-05-26 00:29:06 +000011892 }
11893 }
11894 }
Chris Lattner4284f642007-01-30 22:32:46 +000011895
Chris Lattnerfbb77a42006-04-10 22:45:52 +000011896 return MadeChange ? &SVI : 0;
11897}
11898
11899
Robert Bocchinoa8352962006-01-13 22:48:06 +000011900
Chris Lattner39c98bb2004-12-08 23:43:58 +000011901
11902/// TryToSinkInstruction - Try to move the specified instruction from its
11903/// current block into the beginning of DestBlock, which can only happen if it's
11904/// safe to move the instruction past all of the instructions between it and the
11905/// end of its block.
11906static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
11907 assert(I->hasOneUse() && "Invariants didn't hold!");
11908
Chris Lattnerc4f67e62005-10-27 17:13:11 +000011909 // Cannot move control-flow-involving, volatile loads, vaarg, etc.
Chris Lattnera4ee1f52008-05-09 15:07:33 +000011910 if (isa<PHINode>(I) || I->mayWriteToMemory() || isa<TerminatorInst>(I))
11911 return false;
Misha Brukmanb1c93172005-04-21 23:48:37 +000011912
Chris Lattner39c98bb2004-12-08 23:43:58 +000011913 // Do not sink alloca instructions out of the entry block.
Dan Gohmandcb291f2007-03-22 16:38:57 +000011914 if (isa<AllocaInst>(I) && I->getParent() ==
11915 &DestBlock->getParent()->getEntryBlock())
Chris Lattner39c98bb2004-12-08 23:43:58 +000011916 return false;
11917
Chris Lattnerf17a2fb2004-12-09 07:14:34 +000011918 // We can only sink load instructions if there is nothing between the load and
11919 // the end of block that could change the value.
Chris Lattner49a594e2008-05-08 17:37:37 +000011920 if (I->mayReadFromMemory()) {
11921 for (BasicBlock::iterator Scan = I, E = I->getParent()->end();
Chris Lattnerf17a2fb2004-12-09 07:14:34 +000011922 Scan != E; ++Scan)
11923 if (Scan->mayWriteToMemory())
11924 return false;
Chris Lattnerf17a2fb2004-12-09 07:14:34 +000011925 }
Chris Lattner39c98bb2004-12-08 23:43:58 +000011926
Dan Gohmanf96e1372008-05-23 21:05:58 +000011927 BasicBlock::iterator InsertPos = DestBlock->getFirstNonPHI();
Chris Lattner39c98bb2004-12-08 23:43:58 +000011928
Chris Lattner9f269e42005-08-08 19:11:57 +000011929 I->moveBefore(InsertPos);
Chris Lattner39c98bb2004-12-08 23:43:58 +000011930 ++NumSunkInst;
11931 return true;
11932}
11933
Chris Lattnera36ee4e2006-05-10 19:00:36 +000011934
11935/// AddReachableCodeToWorklist - Walk the function in depth-first order, adding
11936/// all reachable code to the worklist.
11937///
11938/// This has a couple of tricks to make the code faster and more powerful. In
11939/// particular, we constant fold and DCE instructions as we go, to avoid adding
11940/// them to the worklist (this significantly speeds up instcombine on code where
11941/// many instructions are dead or constant). Additionally, if we find a branch
11942/// whose condition is a known constant, we only visit the reachable successors.
11943///
11944static void AddReachableCodeToWorklist(BasicBlock *BB,
Chris Lattner7907e5f2007-02-15 19:41:52 +000011945 SmallPtrSet<BasicBlock*, 64> &Visited,
Chris Lattnerb15e2b12007-03-02 21:28:56 +000011946 InstCombiner &IC,
Chris Lattner1443bc52006-05-11 17:11:52 +000011947 const TargetData *TD) {
Chris Lattner1d239152008-08-15 04:03:01 +000011948 SmallVector<BasicBlock*, 256> Worklist;
Chris Lattner12b89cc2007-03-23 19:17:18 +000011949 Worklist.push_back(BB);
Chris Lattnera36ee4e2006-05-10 19:00:36 +000011950
Chris Lattner12b89cc2007-03-23 19:17:18 +000011951 while (!Worklist.empty()) {
11952 BB = Worklist.back();
11953 Worklist.pop_back();
11954
11955 // We have now visited this block! If we've already been here, ignore it.
11956 if (!Visited.insert(BB)) continue;
11957
11958 for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
11959 Instruction *Inst = BBI++;
Chris Lattnera36ee4e2006-05-10 19:00:36 +000011960
Chris Lattner12b89cc2007-03-23 19:17:18 +000011961 // DCE instruction if trivially dead.
11962 if (isInstructionTriviallyDead(Inst)) {
11963 ++NumDeadInst;
11964 DOUT << "IC: DCE: " << *Inst;
11965 Inst->eraseFromParent();
11966 continue;
11967 }
11968
11969 // ConstantProp instruction if trivially constant.
11970 if (Constant *C = ConstantFoldInstruction(Inst, TD)) {
11971 DOUT << "IC: ConstFold to: " << *C << " from: " << *Inst;
11972 Inst->replaceAllUsesWith(C);
11973 ++NumConstProp;
11974 Inst->eraseFromParent();
11975 continue;
11976 }
Chris Lattnerd82e4a12007-07-20 22:06:41 +000011977
Chris Lattner12b89cc2007-03-23 19:17:18 +000011978 IC.AddToWorkList(Inst);
Chris Lattnera36ee4e2006-05-10 19:00:36 +000011979 }
Chris Lattner12b89cc2007-03-23 19:17:18 +000011980
11981 // Recursively visit successors. If this is a branch or switch on a
11982 // constant, only visit the reachable successor.
11983 TerminatorInst *TI = BB->getTerminator();
11984 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
11985 if (BI->isConditional() && isa<ConstantInt>(BI->getCondition())) {
11986 bool CondVal = cast<ConstantInt>(BI->getCondition())->getZExtValue();
Nick Lewycky271506f2008-03-09 08:50:23 +000011987 BasicBlock *ReachableBB = BI->getSuccessor(!CondVal);
Nick Lewycky4d43d3c2008-04-25 16:53:59 +000011988 Worklist.push_back(ReachableBB);
Chris Lattner12b89cc2007-03-23 19:17:18 +000011989 continue;
11990 }
11991 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
11992 if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
11993 // See if this is an explicit destination.
11994 for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
11995 if (SI->getCaseValue(i) == Cond) {
Nick Lewycky271506f2008-03-09 08:50:23 +000011996 BasicBlock *ReachableBB = SI->getSuccessor(i);
Nick Lewycky4d43d3c2008-04-25 16:53:59 +000011997 Worklist.push_back(ReachableBB);
Chris Lattner12b89cc2007-03-23 19:17:18 +000011998 continue;
11999 }
12000
12001 // Otherwise it is the default destination.
12002 Worklist.push_back(SI->getSuccessor(0));
12003 continue;
12004 }
12005 }
12006
12007 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
12008 Worklist.push_back(TI->getSuccessor(i));
Chris Lattnera36ee4e2006-05-10 19:00:36 +000012009 }
Chris Lattnera36ee4e2006-05-10 19:00:36 +000012010}
12011
Chris Lattner960a5432007-03-03 02:04:50 +000012012bool InstCombiner::DoOneIteration(Function &F, unsigned Iteration) {
Chris Lattner260ab202002-04-18 17:39:14 +000012013 bool Changed = false;
Chris Lattnerf4ad1652003-11-02 05:57:39 +000012014 TD = &getAnalysis<TargetData>();
Chris Lattner960a5432007-03-03 02:04:50 +000012015
12016 DEBUG(DOUT << "\n\nINSTCOMBINE ITERATION #" << Iteration << " on "
12017 << F.getNameStr() << "\n");
Chris Lattnerca081252001-12-14 16:52:21 +000012018
Chris Lattner4ed40f72005-07-07 20:40:38 +000012019 {
Chris Lattnera36ee4e2006-05-10 19:00:36 +000012020 // Do a depth-first traversal of the function, populate the worklist with
12021 // the reachable instructions. Ignore blocks that are not reachable. Keep
12022 // track of which blocks we visit.
Chris Lattner7907e5f2007-02-15 19:41:52 +000012023 SmallPtrSet<BasicBlock*, 64> Visited;
Chris Lattnerb15e2b12007-03-02 21:28:56 +000012024 AddReachableCodeToWorklist(F.begin(), Visited, *this, TD);
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +000012025
Chris Lattner4ed40f72005-07-07 20:40:38 +000012026 // Do a quick scan over the function. If we find any blocks that are
12027 // unreachable, remove any instructions inside of them. This prevents
12028 // the instcombine code from having to deal with some bad special cases.
12029 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
12030 if (!Visited.count(BB)) {
12031 Instruction *Term = BB->getTerminator();
12032 while (Term != BB->begin()) { // Remove instrs bottom-up
12033 BasicBlock::iterator I = Term; --I;
Chris Lattner2d3a7a62004-04-27 15:13:33 +000012034
Bill Wendling5dbf43c2006-11-26 09:46:52 +000012035 DOUT << "IC: DCE: " << *I;
Chris Lattner4ed40f72005-07-07 20:40:38 +000012036 ++NumDeadInst;
12037
12038 if (!I->use_empty())
12039 I->replaceAllUsesWith(UndefValue::get(I->getType()));
12040 I->eraseFromParent();
12041 }
12042 }
12043 }
Chris Lattnerca081252001-12-14 16:52:21 +000012044
Chris Lattnerb15e2b12007-03-02 21:28:56 +000012045 while (!Worklist.empty()) {
12046 Instruction *I = RemoveOneFromWorkList();
12047 if (I == 0) continue; // skip null values.
Chris Lattnerca081252001-12-14 16:52:21 +000012048
Chris Lattner1443bc52006-05-11 17:11:52 +000012049 // Check to see if we can DCE the instruction.
Chris Lattner99f48c62002-09-02 04:59:56 +000012050 if (isInstructionTriviallyDead(I)) {
Chris Lattner1443bc52006-05-11 17:11:52 +000012051 // Add operands to the worklist.
Chris Lattnere8ed4ef2003-10-06 17:11:01 +000012052 if (I->getNumOperands() < 4)
Chris Lattner51ea1272004-02-28 05:22:00 +000012053 AddUsesToWorkList(*I);
Chris Lattner99f48c62002-09-02 04:59:56 +000012054 ++NumDeadInst;
Chris Lattnere8ed4ef2003-10-06 17:11:01 +000012055
Bill Wendling5dbf43c2006-11-26 09:46:52 +000012056 DOUT << "IC: DCE: " << *I;
Chris Lattnercd517ff2005-01-28 19:32:01 +000012057
12058 I->eraseFromParent();
Chris Lattnerb15e2b12007-03-02 21:28:56 +000012059 RemoveFromWorkList(I);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +000012060 continue;
12061 }
Chris Lattner99f48c62002-09-02 04:59:56 +000012062
Chris Lattner1443bc52006-05-11 17:11:52 +000012063 // Instruction isn't dead, see if we can constant propagate it.
Chris Lattnere3eda252007-01-30 23:16:15 +000012064 if (Constant *C = ConstantFoldInstruction(I, TD)) {
Bill Wendling5dbf43c2006-11-26 09:46:52 +000012065 DOUT << "IC: ConstFold to: " << *C << " from: " << *I;
Chris Lattnercd517ff2005-01-28 19:32:01 +000012066
Chris Lattner1443bc52006-05-11 17:11:52 +000012067 // Add operands to the worklist.
Chris Lattner51ea1272004-02-28 05:22:00 +000012068 AddUsesToWorkList(*I);
Chris Lattnerc6509f42002-12-05 22:41:53 +000012069 ReplaceInstUsesWith(*I, C);
12070
Chris Lattner99f48c62002-09-02 04:59:56 +000012071 ++NumConstProp;
Chris Lattnera36ee4e2006-05-10 19:00:36 +000012072 I->eraseFromParent();
Chris Lattnerb15e2b12007-03-02 21:28:56 +000012073 RemoveFromWorkList(I);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +000012074 continue;
Chris Lattner99f48c62002-09-02 04:59:56 +000012075 }
Chris Lattnere8ed4ef2003-10-06 17:11:01 +000012076
Nick Lewyckyf6ccd252008-05-25 20:56:15 +000012077 if (TD && I->getType()->getTypeID() == Type::VoidTyID) {
12078 // See if we can constant fold its operands.
12079 for (User::op_iterator i = I->op_begin(), e = I->op_end(); i != e; ++i) {
12080 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(i)) {
12081 if (Constant *NewC = ConstantFoldConstantExpression(CE, TD))
12082 i->set(NewC);
12083 }
12084 }
12085 }
12086
Chris Lattner39c98bb2004-12-08 23:43:58 +000012087 // See if we can trivially sink this instruction to a successor basic block.
Dan Gohmanfa1211f2008-07-23 00:34:11 +000012088 if (I->hasOneUse()) {
Chris Lattner39c98bb2004-12-08 23:43:58 +000012089 BasicBlock *BB = I->getParent();
12090 BasicBlock *UserParent = cast<Instruction>(I->use_back())->getParent();
12091 if (UserParent != BB) {
12092 bool UserIsSuccessor = false;
12093 // See if the user is one of our successors.
12094 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
12095 if (*SI == UserParent) {
12096 UserIsSuccessor = true;
12097 break;
12098 }
12099
12100 // If the user is one of our immediate successors, and if that successor
12101 // only has us as a predecessors (we'd have to split the critical edge
12102 // otherwise), we can keep going.
12103 if (UserIsSuccessor && !isa<PHINode>(I->use_back()) &&
12104 next(pred_begin(UserParent)) == pred_end(UserParent))
12105 // Okay, the CFG is simple enough, try to sink this instruction.
12106 Changed |= TryToSinkInstruction(I, UserParent);
12107 }
12108 }
12109
Chris Lattnerca081252001-12-14 16:52:21 +000012110 // Now that we have an instruction, try combining it to simplify it...
Reid Spencer755d0e72007-03-26 17:44:01 +000012111#ifndef NDEBUG
12112 std::string OrigI;
12113#endif
12114 DEBUG(std::ostringstream SS; I->print(SS); OrigI = SS.str(););
Chris Lattnerae7a0d32002-08-02 19:29:35 +000012115 if (Instruction *Result = visit(*I)) {
Chris Lattner0b18c1d2002-05-10 15:38:35 +000012116 ++NumCombined;
Chris Lattner260ab202002-04-18 17:39:14 +000012117 // Should we replace the old instruction with a new one?
Chris Lattner053c0932002-05-14 15:24:07 +000012118 if (Result != I) {
Bill Wendling5dbf43c2006-11-26 09:46:52 +000012119 DOUT << "IC: Old = " << *I
12120 << " New = " << *Result;
Chris Lattner7d2a5392004-03-13 23:54:27 +000012121
Chris Lattner396dbfe2004-06-09 05:08:07 +000012122 // Everything uses the new instruction now.
12123 I->replaceAllUsesWith(Result);
12124
12125 // Push the new instruction and any users onto the worklist.
Chris Lattnerb15e2b12007-03-02 21:28:56 +000012126 AddToWorkList(Result);
Chris Lattner396dbfe2004-06-09 05:08:07 +000012127 AddUsersToWorkList(*Result);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +000012128
Chris Lattner6e0123b2007-02-11 01:23:03 +000012129 // Move the name to the new instruction first.
12130 Result->takeName(I);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +000012131
12132 // Insert the new instruction into the basic block...
12133 BasicBlock *InstParent = I->getParent();
Chris Lattner7515cab2004-11-14 19:13:23 +000012134 BasicBlock::iterator InsertPos = I;
12135
12136 if (!isa<PHINode>(Result)) // If combining a PHI, don't insert
12137 while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
12138 ++InsertPos;
12139
12140 InstParent->getInstList().insert(InsertPos, Result);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +000012141
Chris Lattner63d75af2004-05-01 23:27:23 +000012142 // Make sure that we reprocess all operands now that we reduced their
12143 // use counts.
Chris Lattnerb15e2b12007-03-02 21:28:56 +000012144 AddUsesToWorkList(*I);
Chris Lattnerb643a9e2004-05-01 23:19:52 +000012145
Chris Lattner396dbfe2004-06-09 05:08:07 +000012146 // Instructions can end up on the worklist more than once. Make sure
12147 // we do not process an instruction that has been deleted.
Chris Lattnerb15e2b12007-03-02 21:28:56 +000012148 RemoveFromWorkList(I);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +000012149
12150 // Erase the old instruction.
12151 InstParent->getInstList().erase(I);
Chris Lattner113f4f42002-06-25 16:13:24 +000012152 } else {
Evan Chenga4ed8a52007-03-27 16:44:48 +000012153#ifndef NDEBUG
Reid Spencer755d0e72007-03-26 17:44:01 +000012154 DOUT << "IC: Mod = " << OrigI
12155 << " New = " << *I;
Evan Chenga4ed8a52007-03-27 16:44:48 +000012156#endif
Chris Lattner7d2a5392004-03-13 23:54:27 +000012157
Chris Lattnerae7a0d32002-08-02 19:29:35 +000012158 // If the instruction was modified, it's possible that it is now dead.
12159 // if so, remove it.
Chris Lattner63d75af2004-05-01 23:27:23 +000012160 if (isInstructionTriviallyDead(I)) {
12161 // Make sure we process all operands now that we are reducing their
12162 // use counts.
Chris Lattner960a5432007-03-03 02:04:50 +000012163 AddUsesToWorkList(*I);
Misha Brukmanb1c93172005-04-21 23:48:37 +000012164
Chris Lattner63d75af2004-05-01 23:27:23 +000012165 // Instructions may end up in the worklist more than once. Erase all
Robert Bocchinoa8352962006-01-13 22:48:06 +000012166 // occurrences of this instruction.
Chris Lattnerb15e2b12007-03-02 21:28:56 +000012167 RemoveFromWorkList(I);
Chris Lattner31f486c2005-01-31 05:36:43 +000012168 I->eraseFromParent();
Chris Lattner396dbfe2004-06-09 05:08:07 +000012169 } else {
Chris Lattner960a5432007-03-03 02:04:50 +000012170 AddToWorkList(I);
12171 AddUsersToWorkList(*I);
Chris Lattnerae7a0d32002-08-02 19:29:35 +000012172 }
Chris Lattner053c0932002-05-14 15:24:07 +000012173 }
Chris Lattner260ab202002-04-18 17:39:14 +000012174 Changed = true;
Chris Lattnerca081252001-12-14 16:52:21 +000012175 }
12176 }
12177
Chris Lattner960a5432007-03-03 02:04:50 +000012178 assert(WorklistMap.empty() && "Worklist empty, but map not?");
Chris Lattnerf0da7972007-08-05 08:47:58 +000012179
12180 // Do an explicit clear, this shrinks the map if needed.
12181 WorklistMap.clear();
Chris Lattner260ab202002-04-18 17:39:14 +000012182 return Changed;
Chris Lattner04805fa2002-02-26 21:46:54 +000012183}
12184
Chris Lattner960a5432007-03-03 02:04:50 +000012185
12186bool InstCombiner::runOnFunction(Function &F) {
Chris Lattner8258b442007-03-04 04:27:24 +000012187 MustPreserveLCSSA = mustPreserveAnalysisID(LCSSAID);
12188
Chris Lattner960a5432007-03-03 02:04:50 +000012189 bool EverMadeChange = false;
12190
12191 // Iterate while there is work to do.
12192 unsigned Iteration = 0;
Bill Wendling37169522008-05-14 22:45:20 +000012193 while (DoOneIteration(F, Iteration++))
Chris Lattner960a5432007-03-03 02:04:50 +000012194 EverMadeChange = true;
12195 return EverMadeChange;
12196}
12197
Brian Gaeke38b79e82004-07-27 17:43:21 +000012198FunctionPass *llvm::createInstructionCombiningPass() {
Chris Lattner260ab202002-04-18 17:39:14 +000012199 return new InstCombiner();
Chris Lattner04805fa2002-02-26 21:46:54 +000012200}
Brian Gaeke960707c2003-11-11 22:41:34 +000012201
Chris Lattner2aa0ff22008-08-11 22:06:05 +000012202