blob: 232e504971c454c17f178fe89629b3a61a84c63d [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//
5// This file was developed by the LLVM research group and is distributed under
6// the University of Illinois Open Source 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
Chris Lattner99f48c62002-09-02 04:59:56 +000011// instructions. This pass does not modify the CFG This pass is where algebraic
12// simplification happens.
Chris Lattnerca081252001-12-14 16:52:21 +000013//
14// This pass combines things like:
Chris Lattnerdd1a86d2004-05-04 15:19:33 +000015// %Y = add int %X, 1
16// %Z = add int %Y, 1
Chris Lattnerca081252001-12-14 16:52:21 +000017// into:
Chris Lattnerdd1a86d2004-05-04 15:19:33 +000018// %Z = add int %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.
Chris Lattnerbfb1d032003-07-23 21:41:57 +000027// 3. SetCC instructions are converted from <,>,<=,>= to ==,!= if possible
28// 4. All SetCC 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 Lattnerf4ad1652003-11-02 05:57:39 +000042#include "llvm/Target/TargetData.h"
43#include "llvm/Transforms/Utils/BasicBlockUtils.h"
44#include "llvm/Transforms/Utils/Local.h"
Chris Lattner69193f92004-04-05 01:30:19 +000045#include "llvm/Support/CallSite.h"
Chris Lattner39c98bb2004-12-08 23:43:58 +000046#include "llvm/Support/Debug.h"
Chris Lattner69193f92004-04-05 01:30:19 +000047#include "llvm/Support/GetElementPtrTypeIterator.h"
Chris Lattner260ab202002-04-18 17:39:14 +000048#include "llvm/Support/InstVisitor.h"
Chris Lattner22d00a82005-08-02 19:16:58 +000049#include "llvm/Support/MathExtras.h"
Chris Lattnerd4252a72004-07-30 07:50:03 +000050#include "llvm/Support/PatternMatch.h"
Chris Lattner3d27be12006-08-27 12:54:02 +000051#include "llvm/Support/Compiler.h"
Reid Spencer7c16caa2004-09-01 22:55:40 +000052#include "llvm/ADT/Statistic.h"
Chris Lattner39c98bb2004-12-08 23:43:58 +000053#include "llvm/ADT/STLExtras.h"
Chris Lattner053c0932002-05-14 15:24:07 +000054#include <algorithm>
Chris Lattner8427bff2003-12-07 01:24:23 +000055using namespace llvm;
Chris Lattnerd4252a72004-07-30 07:50:03 +000056using namespace llvm::PatternMatch;
Brian Gaeke960707c2003-11-11 22:41:34 +000057
Chris Lattner260ab202002-04-18 17:39:14 +000058namespace {
Chris Lattner700b8732006-12-06 17:46:33 +000059 Statistic NumCombined ("instcombine", "Number of insts combined");
60 Statistic NumConstProp("instcombine", "Number of constant folds");
61 Statistic NumDeadInst ("instcombine", "Number of dead inst eliminated");
62 Statistic NumDeadStore("instcombine", "Number of dead stores eliminated");
63 Statistic NumSunkInst ("instcombine", "Number of instructions sunk");
Chris Lattnerbf3a0992002-10-01 22:38:41 +000064
Chris Lattner4a4c7fe2006-06-28 22:08:15 +000065 class VISIBILITY_HIDDEN InstCombiner
66 : public FunctionPass,
67 public InstVisitor<InstCombiner, Instruction*> {
Chris Lattner260ab202002-04-18 17:39:14 +000068 // Worklist of all of the instructions that need to be simplified.
69 std::vector<Instruction*> WorkList;
Chris Lattnerf4ad1652003-11-02 05:57:39 +000070 TargetData *TD;
Chris Lattner260ab202002-04-18 17:39:14 +000071
Chris Lattner51ea1272004-02-28 05:22:00 +000072 /// AddUsersToWorkList - When an instruction is simplified, add all users of
73 /// the instruction to the work lists because they might get more simplified
74 /// now.
75 ///
Chris Lattner2590e512006-02-07 06:56:34 +000076 void AddUsersToWorkList(Value &I) {
Chris Lattner113f4f42002-06-25 16:13:24 +000077 for (Value::use_iterator UI = I.use_begin(), UE = I.use_end();
Chris Lattner260ab202002-04-18 17:39:14 +000078 UI != UE; ++UI)
79 WorkList.push_back(cast<Instruction>(*UI));
80 }
81
Chris Lattner51ea1272004-02-28 05:22:00 +000082 /// AddUsesToWorkList - When an instruction is simplified, add operands to
83 /// the work lists because they might get more simplified now.
84 ///
85 void AddUsesToWorkList(Instruction &I) {
86 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
87 if (Instruction *Op = dyn_cast<Instruction>(I.getOperand(i)))
88 WorkList.push_back(Op);
89 }
Chris Lattner2deeaea2006-10-05 06:55:50 +000090
91 /// AddSoonDeadInstToWorklist - The specified instruction is about to become
92 /// dead. Add all of its operands to the worklist, turning them into
93 /// undef's to reduce the number of uses of those instructions.
94 ///
95 /// Return the specified operand before it is turned into an undef.
96 ///
97 Value *AddSoonDeadInstToWorklist(Instruction &I, unsigned op) {
98 Value *R = I.getOperand(op);
99
100 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
101 if (Instruction *Op = dyn_cast<Instruction>(I.getOperand(i))) {
102 WorkList.push_back(Op);
103 // Set the operand to undef to drop the use.
104 I.setOperand(i, UndefValue::get(Op->getType()));
105 }
106
107 return R;
108 }
Chris Lattner51ea1272004-02-28 05:22:00 +0000109
Chris Lattner99f48c62002-09-02 04:59:56 +0000110 // removeFromWorkList - remove all instances of I from the worklist.
111 void removeFromWorkList(Instruction *I);
Chris Lattner260ab202002-04-18 17:39:14 +0000112 public:
Chris Lattner113f4f42002-06-25 16:13:24 +0000113 virtual bool runOnFunction(Function &F);
Chris Lattner260ab202002-04-18 17:39:14 +0000114
Chris Lattnerf12cc842002-04-28 21:27:06 +0000115 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Chris Lattnerf4ad1652003-11-02 05:57:39 +0000116 AU.addRequired<TargetData>();
Owen Andersona6968f82006-07-10 19:03:49 +0000117 AU.addPreservedID(LCSSAID);
Chris Lattner820d9712002-10-21 20:00:28 +0000118 AU.setPreservesCFG();
Chris Lattnerf12cc842002-04-28 21:27:06 +0000119 }
120
Chris Lattner69193f92004-04-05 01:30:19 +0000121 TargetData &getTargetData() const { return *TD; }
122
Chris Lattner260ab202002-04-18 17:39:14 +0000123 // Visitation implementation - Implement instruction combining for different
124 // instruction types. The semantics are as follows:
125 // Return Value:
126 // null - No change was made
Chris Lattnere6794492002-08-12 21:17:25 +0000127 // I - Change was made, I is still valid, I may be dead though
Chris Lattner260ab202002-04-18 17:39:14 +0000128 // otherwise - Change was made, replace I with returned instruction
Misha Brukmanb1c93172005-04-21 23:48:37 +0000129 //
Chris Lattner113f4f42002-06-25 16:13:24 +0000130 Instruction *visitAdd(BinaryOperator &I);
131 Instruction *visitSub(BinaryOperator &I);
132 Instruction *visitMul(BinaryOperator &I);
Reid Spencer7eb55b32006-11-02 01:53:59 +0000133 Instruction *visitURem(BinaryOperator &I);
134 Instruction *visitSRem(BinaryOperator &I);
135 Instruction *visitFRem(BinaryOperator &I);
136 Instruction *commonRemTransforms(BinaryOperator &I);
137 Instruction *commonIRemTransforms(BinaryOperator &I);
Reid Spencer7e80b0b2006-10-26 06:15:43 +0000138 Instruction *commonDivTransforms(BinaryOperator &I);
139 Instruction *commonIDivTransforms(BinaryOperator &I);
140 Instruction *visitUDiv(BinaryOperator &I);
141 Instruction *visitSDiv(BinaryOperator &I);
142 Instruction *visitFDiv(BinaryOperator &I);
Chris Lattner113f4f42002-06-25 16:13:24 +0000143 Instruction *visitAnd(BinaryOperator &I);
144 Instruction *visitOr (BinaryOperator &I);
145 Instruction *visitXor(BinaryOperator &I);
Chris Lattnerd1f46d32005-04-24 06:59:08 +0000146 Instruction *visitSetCondInst(SetCondInst &I);
147 Instruction *visitSetCondInstWithCastAndCast(SetCondInst &SCI);
148
Chris Lattner0798af32005-01-13 20:14:25 +0000149 Instruction *FoldGEPSetCC(User *GEPLHS, Value *RHS,
150 Instruction::BinaryOps Cond, Instruction &I);
Chris Lattnere8d6c602003-03-10 19:16:08 +0000151 Instruction *visitShiftInst(ShiftInst &I);
Reid Spencere0fc4df2006-10-20 07:07:24 +0000152 Instruction *FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
Chris Lattner14553932006-01-06 07:12:35 +0000153 ShiftInst &I);
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000154 Instruction *commonCastTransforms(CastInst &CI);
155 Instruction *commonIntCastTransforms(CastInst &CI);
156 Instruction *visitTrunc(CastInst &CI);
157 Instruction *visitZExt(CastInst &CI);
158 Instruction *visitSExt(CastInst &CI);
159 Instruction *visitFPTrunc(CastInst &CI);
160 Instruction *visitFPExt(CastInst &CI);
161 Instruction *visitFPToUI(CastInst &CI);
162 Instruction *visitFPToSI(CastInst &CI);
163 Instruction *visitUIToFP(CastInst &CI);
164 Instruction *visitSIToFP(CastInst &CI);
165 Instruction *visitPtrToInt(CastInst &CI);
166 Instruction *visitIntToPtr(CastInst &CI);
167 Instruction *visitBitCast(CastInst &CI);
Chris Lattner411336f2005-01-19 21:50:18 +0000168 Instruction *FoldSelectOpOp(SelectInst &SI, Instruction *TI,
169 Instruction *FI);
Chris Lattnerb909e8b2004-03-12 05:52:32 +0000170 Instruction *visitSelectInst(SelectInst &CI);
Chris Lattner970c33a2003-06-19 17:00:31 +0000171 Instruction *visitCallInst(CallInst &CI);
172 Instruction *visitInvokeInst(InvokeInst &II);
Chris Lattner113f4f42002-06-25 16:13:24 +0000173 Instruction *visitPHINode(PHINode &PN);
174 Instruction *visitGetElementPtrInst(GetElementPtrInst &GEP);
Chris Lattner1085bdf2002-11-04 16:18:53 +0000175 Instruction *visitAllocationInst(AllocationInst &AI);
Chris Lattner8427bff2003-12-07 01:24:23 +0000176 Instruction *visitFreeInst(FreeInst &FI);
Chris Lattner0f1d8a32003-06-26 05:06:25 +0000177 Instruction *visitLoadInst(LoadInst &LI);
Chris Lattner31f486c2005-01-31 05:36:43 +0000178 Instruction *visitStoreInst(StoreInst &SI);
Chris Lattner9eef8a72003-06-04 04:46:00 +0000179 Instruction *visitBranchInst(BranchInst &BI);
Chris Lattner4c9c20a2004-07-03 00:26:11 +0000180 Instruction *visitSwitchInst(SwitchInst &SI);
Chris Lattner39fac442006-04-15 01:39:45 +0000181 Instruction *visitInsertElementInst(InsertElementInst &IE);
Robert Bocchinoa8352962006-01-13 22:48:06 +0000182 Instruction *visitExtractElementInst(ExtractElementInst &EI);
Chris Lattnerfbb77a42006-04-10 22:45:52 +0000183 Instruction *visitShuffleVectorInst(ShuffleVectorInst &SVI);
Chris Lattner260ab202002-04-18 17:39:14 +0000184
185 // visitInstruction - Specify what to return for unhandled instructions...
Chris Lattner113f4f42002-06-25 16:13:24 +0000186 Instruction *visitInstruction(Instruction &I) { return 0; }
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000187
Chris Lattner970c33a2003-06-19 17:00:31 +0000188 private:
Chris Lattneraec3d942003-10-07 22:32:43 +0000189 Instruction *visitCallSite(CallSite CS);
Chris Lattner970c33a2003-06-19 17:00:31 +0000190 bool transformConstExprCastCall(CallSite CS);
191
Chris Lattner69193f92004-04-05 01:30:19 +0000192 public:
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000193 // InsertNewInstBefore - insert an instruction New before instruction Old
194 // in the program. Add the new instruction to the worklist.
195 //
Chris Lattner623826c2004-09-28 21:48:02 +0000196 Instruction *InsertNewInstBefore(Instruction *New, Instruction &Old) {
Chris Lattner65217ff2002-08-23 18:32:43 +0000197 assert(New && New->getParent() == 0 &&
198 "New instruction already inserted into a basic block!");
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000199 BasicBlock *BB = Old.getParent();
200 BB->getInstList().insert(&Old, New); // Insert inst
201 WorkList.push_back(New); // Add to worklist
Chris Lattnere79e8542004-02-23 06:38:22 +0000202 return New;
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000203 }
204
Chris Lattner7e794272004-09-24 15:21:34 +0000205 /// InsertCastBefore - Insert a cast of V to TY before the instruction POS.
206 /// This also adds the cast to the worklist. Finally, this returns the
207 /// cast.
Reid Spencer13bc5d72006-12-12 09:18:51 +0000208 Value *InsertCastBefore(Instruction::CastOps opc, Value *V, const Type *Ty,
209 Instruction &Pos) {
Chris Lattner7e794272004-09-24 15:21:34 +0000210 if (V->getType() == Ty) return V;
Misha Brukmanb1c93172005-04-21 23:48:37 +0000211
Chris Lattnere79d2492006-04-06 19:19:17 +0000212 if (Constant *CV = dyn_cast<Constant>(V))
Reid Spencer13bc5d72006-12-12 09:18:51 +0000213 return ConstantExpr::getCast(opc, CV, Ty);
Chris Lattnere79d2492006-04-06 19:19:17 +0000214
Reid Spencer13bc5d72006-12-12 09:18:51 +0000215 Instruction *C = CastInst::create(opc, V, Ty, V->getName(), &Pos);
Chris Lattner7e794272004-09-24 15:21:34 +0000216 WorkList.push_back(C);
217 return C;
218 }
219
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000220 // ReplaceInstUsesWith - This method is to be used when an instruction is
221 // found to be dead, replacable with another preexisting expression. Here
222 // we add all uses of I to the worklist, replace all uses of I with the new
223 // value, then return I, so that the inst combiner will know that I was
224 // modified.
225 //
226 Instruction *ReplaceInstUsesWith(Instruction &I, Value *V) {
Chris Lattner51ea1272004-02-28 05:22:00 +0000227 AddUsersToWorkList(I); // Add all modified instrs to worklist
Chris Lattner8953b902004-04-05 02:10:19 +0000228 if (&I != V) {
229 I.replaceAllUsesWith(V);
230 return &I;
231 } else {
232 // If we are replacing the instruction with itself, this must be in a
233 // segment of unreachable code, so just clobber the instruction.
Chris Lattner8ba9ec92004-10-18 02:59:09 +0000234 I.replaceAllUsesWith(UndefValue::get(I.getType()));
Chris Lattner8953b902004-04-05 02:10:19 +0000235 return &I;
236 }
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000237 }
Chris Lattner51ea1272004-02-28 05:22:00 +0000238
Chris Lattner2590e512006-02-07 06:56:34 +0000239 // UpdateValueUsesWith - This method is to be used when an value is
240 // found to be replacable with another preexisting expression or was
241 // updated. Here we add all uses of I to the worklist, replace all uses of
242 // I with the new value (unless the instruction was just updated), then
243 // return true, so that the inst combiner will know that I was modified.
244 //
245 bool UpdateValueUsesWith(Value *Old, Value *New) {
246 AddUsersToWorkList(*Old); // Add all modified instrs to worklist
247 if (Old != New)
248 Old->replaceAllUsesWith(New);
249 if (Instruction *I = dyn_cast<Instruction>(Old))
250 WorkList.push_back(I);
Chris Lattner5b2edb12006-02-12 08:02:11 +0000251 if (Instruction *I = dyn_cast<Instruction>(New))
252 WorkList.push_back(I);
Chris Lattner2590e512006-02-07 06:56:34 +0000253 return true;
254 }
255
Chris Lattner51ea1272004-02-28 05:22:00 +0000256 // EraseInstFromFunction - When dealing with an instruction that has side
257 // effects or produces a void value, we can't rely on DCE to delete the
258 // instruction. Instead, visit methods should return the value returned by
259 // this function.
260 Instruction *EraseInstFromFunction(Instruction &I) {
261 assert(I.use_empty() && "Cannot erase instruction that is used!");
262 AddUsesToWorkList(I);
263 removeFromWorkList(&I);
Chris Lattner95307542004-11-18 21:41:39 +0000264 I.eraseFromParent();
Chris Lattner51ea1272004-02-28 05:22:00 +0000265 return 0; // Don't do anything with FI
266 }
267
Chris Lattner3ac7c262003-08-13 20:16:26 +0000268 private:
Chris Lattnerdfae8be2003-07-24 17:35:25 +0000269 /// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
270 /// InsertBefore instruction. This is specialized a bit to avoid inserting
271 /// casts that are known to not do anything...
272 ///
Reid Spencer13bc5d72006-12-12 09:18:51 +0000273 Value *InsertOperandCastBefore(Instruction::CastOps opcode,
274 Value *V, const Type *DestTy,
Chris Lattnerdfae8be2003-07-24 17:35:25 +0000275 Instruction *InsertBefore);
276
Chris Lattner7fb29e12003-03-11 00:12:48 +0000277 // SimplifyCommutative - This performs a few simplifications for commutative
Chris Lattner6a4adcd2004-09-29 05:07:12 +0000278 // operators.
Chris Lattner7fb29e12003-03-11 00:12:48 +0000279 bool SimplifyCommutative(BinaryOperator &I);
Chris Lattnerba1cb382003-09-19 17:17:26 +0000280
Chris Lattner0157e7f2006-02-11 09:31:47 +0000281 bool SimplifyDemandedBits(Value *V, uint64_t Mask,
282 uint64_t &KnownZero, uint64_t &KnownOne,
283 unsigned Depth = 0);
Chris Lattner6a4adcd2004-09-29 05:07:12 +0000284
Chris Lattner2deeaea2006-10-05 06:55:50 +0000285 Value *SimplifyDemandedVectorElts(Value *V, uint64_t DemandedElts,
286 uint64_t &UndefElts, unsigned Depth = 0);
287
Chris Lattner6a4adcd2004-09-29 05:07:12 +0000288 // FoldOpIntoPhi - Given a binary operator or cast instruction which has a
289 // PHI node as operand #0, see if we can fold the instruction into the PHI
290 // (which is only possible if all operands to the PHI are constants).
291 Instruction *FoldOpIntoPhi(Instruction &I);
292
Chris Lattner7515cab2004-11-14 19:13:23 +0000293 // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
294 // operator and they all are only used by the PHI, PHI together their
295 // inputs, and do the operation once, to the result of the PHI.
296 Instruction *FoldPHIArgOpIntoPHI(PHINode &PN);
Chris Lattnercadac0c2006-11-01 04:51:18 +0000297 Instruction *FoldPHIArgBinOpIntoPHI(PHINode &PN);
298
299
Chris Lattnerba1cb382003-09-19 17:17:26 +0000300 Instruction *OptAndOp(Instruction *Op, ConstantIntegral *OpRHS,
301 ConstantIntegral *AndRHS, BinaryOperator &TheAnd);
Chris Lattneraf517572005-09-18 04:24:45 +0000302
303 Value *FoldLogicalPlusAnd(Value *LHS, Value *RHS, ConstantIntegral *Mask,
304 bool isSub, Instruction &I);
Chris Lattner6862fbd2004-09-29 17:40:11 +0000305 Instruction *InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
306 bool Inside, Instruction &IB);
Chris Lattner216be912005-10-24 06:03:58 +0000307 Instruction *PromoteCastOfAllocation(CastInst &CI, AllocationInst &AI);
Chris Lattnerc482a9e2006-06-15 19:07:26 +0000308 Instruction *MatchBSwap(BinaryOperator &I);
309
Chris Lattner1ebbe6a2006-05-13 02:06:03 +0000310 Value *EvaluateInDifferentType(Value *V, const Type *Ty);
Chris Lattner260ab202002-04-18 17:39:14 +0000311 };
Chris Lattnerb28b6802002-07-23 18:06:35 +0000312
Chris Lattnerc2d3d312006-08-27 22:42:52 +0000313 RegisterPass<InstCombiner> X("instcombine", "Combine redundant instructions");
Chris Lattner260ab202002-04-18 17:39:14 +0000314}
315
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000316// getComplexity: Assign a complexity or rank value to LLVM Values...
Chris Lattner81a7a232004-10-16 18:11:37 +0000317// 0 -> undef, 1 -> Const, 2 -> Other, 3 -> Arg, 3 -> Unary, 4 -> OtherInst
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000318static unsigned getComplexity(Value *V) {
319 if (isa<Instruction>(V)) {
320 if (BinaryOperator::isNeg(V) || BinaryOperator::isNot(V))
Chris Lattner81a7a232004-10-16 18:11:37 +0000321 return 3;
322 return 4;
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000323 }
Chris Lattner81a7a232004-10-16 18:11:37 +0000324 if (isa<Argument>(V)) return 3;
325 return isa<Constant>(V) ? (isa<UndefValue>(V) ? 0 : 1) : 2;
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000326}
Chris Lattner260ab202002-04-18 17:39:14 +0000327
Chris Lattner7fb29e12003-03-11 00:12:48 +0000328// isOnlyUse - Return true if this instruction will be deleted if we stop using
329// it.
330static bool isOnlyUse(Value *V) {
Chris Lattnerf95d9b92003-10-15 16:48:29 +0000331 return V->hasOneUse() || isa<Constant>(V);
Chris Lattner7fb29e12003-03-11 00:12:48 +0000332}
333
Chris Lattnere79e8542004-02-23 06:38:22 +0000334// getPromotedType - Return the specified type promoted as it would be to pass
335// though a va_arg area...
336static const Type *getPromotedType(const Type *Ty) {
Chris Lattner97bfcea2004-06-17 18:16:02 +0000337 switch (Ty->getTypeID()) {
Chris Lattnere79e8542004-02-23 06:38:22 +0000338 case Type::SByteTyID:
339 case Type::ShortTyID: return Type::IntTy;
340 case Type::UByteTyID:
341 case Type::UShortTyID: return Type::UIntTy;
342 case Type::FloatTyID: return Type::DoubleTy;
343 default: return Ty;
344 }
345}
346
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000347/// getBitCastOperand - If the specified operand is a CastInst or a constant
348/// expression bitcast, return the operand value, otherwise return null.
349static Value *getBitCastOperand(Value *V) {
350 if (BitCastInst *I = dyn_cast<BitCastInst>(V))
Chris Lattner567b81f2005-09-13 00:40:14 +0000351 return I->getOperand(0);
352 else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000353 if (CE->getOpcode() == Instruction::BitCast)
Chris Lattner567b81f2005-09-13 00:40:14 +0000354 return CE->getOperand(0);
355 return 0;
356}
357
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000358/// This function is a wrapper around CastInst::isEliminableCastPair. It
359/// simply extracts arguments and returns what that function returns.
360/// @Determine if it is valid to eliminate a Convert pair
361static Instruction::CastOps
362isEliminableCastPair(
363 const CastInst *CI, ///< The first cast instruction
364 unsigned opcode, ///< The opcode of the second cast instruction
365 const Type *DstTy, ///< The target type for the second cast instruction
366 TargetData *TD ///< The target data for pointer size
367) {
368
369 const Type *SrcTy = CI->getOperand(0)->getType(); // A from above
370 const Type *MidTy = CI->getType(); // B from above
Chris Lattner1d441ad2006-05-06 09:00:16 +0000371
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000372 // Get the opcodes of the two Cast instructions
373 Instruction::CastOps firstOp = Instruction::CastOps(CI->getOpcode());
374 Instruction::CastOps secondOp = Instruction::CastOps(opcode);
Chris Lattner1d441ad2006-05-06 09:00:16 +0000375
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000376 return Instruction::CastOps(
377 CastInst::isEliminableCastPair(firstOp, secondOp, SrcTy, MidTy,
378 DstTy, TD->getIntPtrType()));
Chris Lattner1d441ad2006-05-06 09:00:16 +0000379}
380
381/// ValueRequiresCast - Return true if the cast from "V to Ty" actually results
382/// in any code being generated. It does not require codegen if V is simple
383/// enough or if the cast can be folded into other casts.
384static bool ValueRequiresCast(const Value *V, const Type *Ty, TargetData *TD) {
385 if (V->getType() == Ty || isa<Constant>(V)) return false;
386
387 // If this is a noop cast, it isn't real codegen.
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000388 if (V->getType()->canLosslesslyBitCastTo(Ty))
Chris Lattner1d441ad2006-05-06 09:00:16 +0000389 return false;
390
Chris Lattner99155be2006-05-25 23:24:33 +0000391 // If this is another cast that can be eliminated, it isn't codegen either.
Chris Lattner1d441ad2006-05-06 09:00:16 +0000392 if (const CastInst *CI = dyn_cast<CastInst>(V))
Reid Spencer14fbdd52006-12-04 02:48:01 +0000393 if (isEliminableCastPair(CI, CastInst::getCastOpcode(
394 V, V->getType()->isSigned(), Ty, Ty->isSigned()), Ty, TD))
Chris Lattner1d441ad2006-05-06 09:00:16 +0000395 return false;
396 return true;
397}
398
399/// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
400/// InsertBefore instruction. This is specialized a bit to avoid inserting
401/// casts that are known to not do anything...
402///
Reid Spencer13bc5d72006-12-12 09:18:51 +0000403Value *InstCombiner::InsertOperandCastBefore(Instruction::CastOps opcode,
404 Value *V, const Type *DestTy,
Chris Lattner1d441ad2006-05-06 09:00:16 +0000405 Instruction *InsertBefore) {
406 if (V->getType() == DestTy) return V;
407 if (Constant *C = dyn_cast<Constant>(V))
Reid Spencer13bc5d72006-12-12 09:18:51 +0000408 return ConstantExpr::getCast(opcode, C, DestTy);
Chris Lattner1d441ad2006-05-06 09:00:16 +0000409
Reid Spencer13bc5d72006-12-12 09:18:51 +0000410 return InsertCastBefore(opcode, V, DestTy, *InsertBefore);
Chris Lattner1d441ad2006-05-06 09:00:16 +0000411}
412
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000413// SimplifyCommutative - This performs a few simplifications for commutative
414// operators:
Chris Lattner260ab202002-04-18 17:39:14 +0000415//
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000416// 1. Order operands such that they are listed from right (least complex) to
417// left (most complex). This puts constants before unary operators before
418// binary operators.
419//
Chris Lattner7fb29e12003-03-11 00:12:48 +0000420// 2. Transform: (op (op V, C1), C2) ==> (op V, (op C1, C2))
421// 3. Transform: (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000422//
Chris Lattner7fb29e12003-03-11 00:12:48 +0000423bool InstCombiner::SimplifyCommutative(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000424 bool Changed = false;
425 if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1)))
426 Changed = !I.swapOperands();
Misha Brukmanb1c93172005-04-21 23:48:37 +0000427
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000428 if (!I.isAssociative()) return Changed;
429 Instruction::BinaryOps Opcode = I.getOpcode();
Chris Lattner7fb29e12003-03-11 00:12:48 +0000430 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(I.getOperand(0)))
431 if (Op->getOpcode() == Opcode && isa<Constant>(Op->getOperand(1))) {
432 if (isa<Constant>(I.getOperand(1))) {
Chris Lattner34428442003-05-27 16:40:51 +0000433 Constant *Folded = ConstantExpr::get(I.getOpcode(),
434 cast<Constant>(I.getOperand(1)),
435 cast<Constant>(Op->getOperand(1)));
Chris Lattner7fb29e12003-03-11 00:12:48 +0000436 I.setOperand(0, Op->getOperand(0));
437 I.setOperand(1, Folded);
438 return true;
439 } else if (BinaryOperator *Op1=dyn_cast<BinaryOperator>(I.getOperand(1)))
440 if (Op1->getOpcode() == Opcode && isa<Constant>(Op1->getOperand(1)) &&
441 isOnlyUse(Op) && isOnlyUse(Op1)) {
442 Constant *C1 = cast<Constant>(Op->getOperand(1));
443 Constant *C2 = cast<Constant>(Op1->getOperand(1));
444
445 // Fold (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Chris Lattner34428442003-05-27 16:40:51 +0000446 Constant *Folded = ConstantExpr::get(I.getOpcode(), C1, C2);
Chris Lattner7fb29e12003-03-11 00:12:48 +0000447 Instruction *New = BinaryOperator::create(Opcode, Op->getOperand(0),
448 Op1->getOperand(0),
449 Op1->getName(), &I);
450 WorkList.push_back(New);
451 I.setOperand(0, New);
452 I.setOperand(1, Folded);
453 return true;
Misha Brukmanb1c93172005-04-21 23:48:37 +0000454 }
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000455 }
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000456 return Changed;
Chris Lattner260ab202002-04-18 17:39:14 +0000457}
Chris Lattnerca081252001-12-14 16:52:21 +0000458
Chris Lattnerbb74e222003-03-10 23:06:50 +0000459// dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
460// if the LHS is a constant zero (which is the 'negate' form).
Chris Lattner9fa53de2002-05-06 16:49:18 +0000461//
Chris Lattnerbb74e222003-03-10 23:06:50 +0000462static inline Value *dyn_castNegVal(Value *V) {
463 if (BinaryOperator::isNeg(V))
Chris Lattnerd6f636a2005-04-24 07:30:14 +0000464 return BinaryOperator::getNegArgument(V);
Chris Lattnerbb74e222003-03-10 23:06:50 +0000465
Chris Lattner9ad0d552004-12-14 20:08:06 +0000466 // Constants can be considered to be negated values if they can be folded.
467 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
468 return ConstantExpr::getNeg(C);
Chris Lattnerbb74e222003-03-10 23:06:50 +0000469 return 0;
Chris Lattner9fa53de2002-05-06 16:49:18 +0000470}
471
Chris Lattnerbb74e222003-03-10 23:06:50 +0000472static inline Value *dyn_castNotVal(Value *V) {
473 if (BinaryOperator::isNot(V))
Chris Lattnerd6f636a2005-04-24 07:30:14 +0000474 return BinaryOperator::getNotArgument(V);
Chris Lattnerbb74e222003-03-10 23:06:50 +0000475
476 // Constants can be considered to be not'ed values...
Chris Lattnerdd65d862003-04-30 22:34:06 +0000477 if (ConstantIntegral *C = dyn_cast<ConstantIntegral>(V))
Chris Lattnerc8e7e292004-06-10 02:12:35 +0000478 return ConstantExpr::getNot(C);
Chris Lattnerbb74e222003-03-10 23:06:50 +0000479 return 0;
480}
481
Chris Lattner7fb29e12003-03-11 00:12:48 +0000482// dyn_castFoldableMul - If this value is a multiply that can be folded into
483// other computations (because it has a constant operand), return the
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000484// non-constant operand of the multiply, and set CST to point to the multiplier.
485// Otherwise, return null.
Chris Lattner7fb29e12003-03-11 00:12:48 +0000486//
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000487static inline Value *dyn_castFoldableMul(Value *V, ConstantInt *&CST) {
Chris Lattnerf95d9b92003-10-15 16:48:29 +0000488 if (V->hasOneUse() && V->getType()->isInteger())
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000489 if (Instruction *I = dyn_cast<Instruction>(V)) {
Chris Lattner7fb29e12003-03-11 00:12:48 +0000490 if (I->getOpcode() == Instruction::Mul)
Chris Lattner970136362004-11-15 05:54:07 +0000491 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1))))
Chris Lattner7fb29e12003-03-11 00:12:48 +0000492 return I->getOperand(0);
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000493 if (I->getOpcode() == Instruction::Shl)
Chris Lattner970136362004-11-15 05:54:07 +0000494 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1)))) {
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000495 // The multiplier is really 1 << CST.
496 Constant *One = ConstantInt::get(V->getType(), 1);
497 CST = cast<ConstantInt>(ConstantExpr::getShl(One, CST));
498 return I->getOperand(0);
499 }
500 }
Chris Lattner7fb29e12003-03-11 00:12:48 +0000501 return 0;
Chris Lattner3082c5a2003-02-18 19:28:33 +0000502}
Chris Lattner31ae8632002-08-14 17:51:49 +0000503
Chris Lattner0798af32005-01-13 20:14:25 +0000504/// dyn_castGetElementPtr - If this is a getelementptr instruction or constant
505/// expression, return it.
506static User *dyn_castGetElementPtr(Value *V) {
507 if (isa<GetElementPtrInst>(V)) return cast<User>(V);
508 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
509 if (CE->getOpcode() == Instruction::GetElementPtr)
510 return cast<User>(V);
511 return false;
512}
513
Chris Lattner623826c2004-09-28 21:48:02 +0000514// AddOne, SubOne - Add or subtract a constant one from an integer constant...
Chris Lattner6862fbd2004-09-29 17:40:11 +0000515static ConstantInt *AddOne(ConstantInt *C) {
516 return cast<ConstantInt>(ConstantExpr::getAdd(C,
517 ConstantInt::get(C->getType(), 1)));
Chris Lattner623826c2004-09-28 21:48:02 +0000518}
Chris Lattner6862fbd2004-09-29 17:40:11 +0000519static ConstantInt *SubOne(ConstantInt *C) {
520 return cast<ConstantInt>(ConstantExpr::getSub(C,
521 ConstantInt::get(C->getType(), 1)));
Chris Lattner623826c2004-09-28 21:48:02 +0000522}
523
Chris Lattner0157e7f2006-02-11 09:31:47 +0000524/// GetConstantInType - Return a ConstantInt with the specified type and value.
525///
Chris Lattneree0f2802006-02-12 02:07:56 +0000526static ConstantIntegral *GetConstantInType(const Type *Ty, uint64_t Val) {
Reid Spencere0fc4df2006-10-20 07:07:24 +0000527 if (Ty->isUnsigned())
528 return ConstantInt::get(Ty, Val);
Chris Lattneree0f2802006-02-12 02:07:56 +0000529 else if (Ty->getTypeID() == Type::BoolTyID)
530 return ConstantBool::get(Val);
Chris Lattner0157e7f2006-02-11 09:31:47 +0000531 int64_t SVal = Val;
532 SVal <<= 64-Ty->getPrimitiveSizeInBits();
533 SVal >>= 64-Ty->getPrimitiveSizeInBits();
Reid Spencere0fc4df2006-10-20 07:07:24 +0000534 return ConstantInt::get(Ty, SVal);
Chris Lattner0157e7f2006-02-11 09:31:47 +0000535}
536
537
Chris Lattner4534dd592006-02-09 07:38:58 +0000538/// ComputeMaskedBits - Determine which of the bits specified in Mask are
539/// known to be either zero or one and return them in the KnownZero/KnownOne
540/// bitsets. This code only analyzes bits in Mask, in order to short-circuit
541/// processing.
542static void ComputeMaskedBits(Value *V, uint64_t Mask, uint64_t &KnownZero,
543 uint64_t &KnownOne, unsigned Depth = 0) {
Chris Lattner0b3557f2005-09-24 23:43:33 +0000544 // Note, we cannot consider 'undef' to be "IsZero" here. The problem is that
545 // we cannot optimize based on the assumption that it is zero without changing
Chris Lattnerc3ebf402006-02-07 07:27:52 +0000546 // it to be an explicit zero. If we don't change it to zero, other code could
Chris Lattner0b3557f2005-09-24 23:43:33 +0000547 // optimized based on the contradictory assumption that it is non-zero.
548 // Because instcombine aggressively folds operations with undef args anyway,
549 // this won't lose us code quality.
Chris Lattner4534dd592006-02-09 07:38:58 +0000550 if (ConstantIntegral *CI = dyn_cast<ConstantIntegral>(V)) {
551 // We know all of the bits for a constant!
Chris Lattner0157e7f2006-02-11 09:31:47 +0000552 KnownOne = CI->getZExtValue() & Mask;
Chris Lattner4534dd592006-02-09 07:38:58 +0000553 KnownZero = ~KnownOne & Mask;
554 return;
555 }
556
557 KnownZero = KnownOne = 0; // Don't know anything.
Chris Lattner92a68652006-02-07 08:05:22 +0000558 if (Depth == 6 || Mask == 0)
Chris Lattner4534dd592006-02-09 07:38:58 +0000559 return; // Limit search depth.
560
561 uint64_t KnownZero2, KnownOne2;
Chris Lattner0157e7f2006-02-11 09:31:47 +0000562 Instruction *I = dyn_cast<Instruction>(V);
563 if (!I) return;
564
Chris Lattnerfb296922006-05-04 17:33:35 +0000565 Mask &= V->getType()->getIntegralTypeMask();
566
Chris Lattner0157e7f2006-02-11 09:31:47 +0000567 switch (I->getOpcode()) {
568 case Instruction::And:
569 // If either the LHS or the RHS are Zero, the result is zero.
570 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
571 Mask &= ~KnownZero;
572 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero2, KnownOne2, Depth+1);
573 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
574 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
575
576 // Output known-1 bits are only known if set in both the LHS & RHS.
577 KnownOne &= KnownOne2;
578 // Output known-0 are known to be clear if zero in either the LHS | RHS.
579 KnownZero |= KnownZero2;
580 return;
581 case Instruction::Or:
582 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
583 Mask &= ~KnownOne;
584 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero2, KnownOne2, Depth+1);
585 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
586 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
587
588 // Output known-0 bits are only known if clear in both the LHS & RHS.
589 KnownZero &= KnownZero2;
590 // Output known-1 are known to be set if set in either the LHS | RHS.
591 KnownOne |= KnownOne2;
592 return;
593 case Instruction::Xor: {
594 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
595 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero2, KnownOne2, Depth+1);
596 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
597 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
598
599 // Output known-0 bits are known if clear or set in both the LHS & RHS.
600 uint64_t KnownZeroOut = (KnownZero & KnownZero2) | (KnownOne & KnownOne2);
601 // Output known-1 are known to be set if set in only one of the LHS, RHS.
602 KnownOne = (KnownZero & KnownOne2) | (KnownOne & KnownZero2);
603 KnownZero = KnownZeroOut;
604 return;
605 }
606 case Instruction::Select:
607 ComputeMaskedBits(I->getOperand(2), Mask, KnownZero, KnownOne, Depth+1);
608 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero2, KnownOne2, Depth+1);
609 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
610 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
611
612 // Only known if known in both the LHS and RHS.
613 KnownOne &= KnownOne2;
614 KnownZero &= KnownZero2;
615 return;
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000616 case Instruction::FPTrunc:
617 case Instruction::FPExt:
618 case Instruction::FPToUI:
619 case Instruction::FPToSI:
620 case Instruction::SIToFP:
621 case Instruction::PtrToInt:
622 case Instruction::UIToFP:
623 case Instruction::IntToPtr:
624 return; // Can't work with floating point or pointers
625 case Instruction::Trunc:
626 // All these have integer operands
627 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
628 return;
629 case Instruction::BitCast: {
Chris Lattner0157e7f2006-02-11 09:31:47 +0000630 const Type *SrcTy = I->getOperand(0)->getType();
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000631 if (SrcTy->isIntegral()) {
Chris Lattner0157e7f2006-02-11 09:31:47 +0000632 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
Chris Lattner4534dd592006-02-09 07:38:58 +0000633 return;
634 }
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000635 break;
636 }
637 case Instruction::ZExt: {
638 // Compute the bits in the result that are not present in the input.
639 const Type *SrcTy = I->getOperand(0)->getType();
Chris Lattner0157e7f2006-02-11 09:31:47 +0000640 uint64_t NotIn = ~SrcTy->getIntegralTypeMask();
641 uint64_t NewBits = I->getType()->getIntegralTypeMask() & NotIn;
Chris Lattner62010c42005-10-09 06:36:35 +0000642
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000643 Mask &= SrcTy->getIntegralTypeMask();
644 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
645 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
646 // The top bits are known to be zero.
647 KnownZero |= NewBits;
648 return;
649 }
650 case Instruction::SExt: {
651 // Compute the bits in the result that are not present in the input.
652 const Type *SrcTy = I->getOperand(0)->getType();
653 uint64_t NotIn = ~SrcTy->getIntegralTypeMask();
654 uint64_t NewBits = I->getType()->getIntegralTypeMask() & NotIn;
655
656 Mask &= SrcTy->getIntegralTypeMask();
657 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
658 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
Chris Lattner92a68652006-02-07 08:05:22 +0000659
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000660 // If the sign bit of the input is known set or clear, then we know the
661 // top bits of the result.
662 uint64_t InSignBit = 1ULL << (SrcTy->getPrimitiveSizeInBits()-1);
663 if (KnownZero & InSignBit) { // Input sign bit known zero
664 KnownZero |= NewBits;
665 KnownOne &= ~NewBits;
666 } else if (KnownOne & InSignBit) { // Input sign bit known set
667 KnownOne |= NewBits;
668 KnownZero &= ~NewBits;
669 } else { // Input sign bit unknown
670 KnownZero &= ~NewBits;
671 KnownOne &= ~NewBits;
Chris Lattner0157e7f2006-02-11 09:31:47 +0000672 }
673 return;
674 }
675 case Instruction::Shl:
676 // (shl X, C1) & C2 == 0 iff (X & C2 >>u C1) == 0
Reid Spencere0fc4df2006-10-20 07:07:24 +0000677 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
678 uint64_t ShiftAmt = SA->getZExtValue();
679 Mask >>= ShiftAmt;
Chris Lattner0157e7f2006-02-11 09:31:47 +0000680 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
681 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
Reid Spencere0fc4df2006-10-20 07:07:24 +0000682 KnownZero <<= ShiftAmt;
683 KnownOne <<= ShiftAmt;
684 KnownZero |= (1ULL << ShiftAmt)-1; // low bits known zero.
Chris Lattner0157e7f2006-02-11 09:31:47 +0000685 return;
686 }
687 break;
Reid Spencerfdff9382006-11-08 06:47:33 +0000688 case Instruction::LShr:
Chris Lattner0157e7f2006-02-11 09:31:47 +0000689 // (ushr X, C1) & C2 == 0 iff (-1 >> C1) & C2 == 0
Reid Spencere0fc4df2006-10-20 07:07:24 +0000690 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
Chris Lattner0157e7f2006-02-11 09:31:47 +0000691 // Compute the new bits that are at the top now.
Reid Spencere0fc4df2006-10-20 07:07:24 +0000692 uint64_t ShiftAmt = SA->getZExtValue();
693 uint64_t HighBits = (1ULL << ShiftAmt)-1;
694 HighBits <<= I->getType()->getPrimitiveSizeInBits()-ShiftAmt;
Chris Lattner0157e7f2006-02-11 09:31:47 +0000695
Reid Spencerfdff9382006-11-08 06:47:33 +0000696 // Unsigned shift right.
697 Mask <<= ShiftAmt;
698 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero,KnownOne,Depth+1);
699 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
700 KnownZero >>= ShiftAmt;
701 KnownOne >>= ShiftAmt;
702 KnownZero |= HighBits; // high bits known zero.
703 return;
704 }
705 break;
706 case Instruction::AShr:
707 // (ushr X, C1) & C2 == 0 iff (-1 >> C1) & C2 == 0
708 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
709 // Compute the new bits that are at the top now.
710 uint64_t ShiftAmt = SA->getZExtValue();
711 uint64_t HighBits = (1ULL << ShiftAmt)-1;
712 HighBits <<= I->getType()->getPrimitiveSizeInBits()-ShiftAmt;
713
714 // Signed shift right.
715 Mask <<= ShiftAmt;
716 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero,KnownOne,Depth+1);
717 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
718 KnownZero >>= ShiftAmt;
719 KnownOne >>= ShiftAmt;
Chris Lattner0157e7f2006-02-11 09:31:47 +0000720
Reid Spencerfdff9382006-11-08 06:47:33 +0000721 // Handle the sign bits.
722 uint64_t SignBit = 1ULL << (I->getType()->getPrimitiveSizeInBits()-1);
723 SignBit >>= ShiftAmt; // Adjust to where it is now in the mask.
Chris Lattner0157e7f2006-02-11 09:31:47 +0000724
Reid Spencerfdff9382006-11-08 06:47:33 +0000725 if (KnownZero & SignBit) { // New bits are known zero.
726 KnownZero |= HighBits;
727 } else if (KnownOne & SignBit) { // New bits are known one.
728 KnownOne |= HighBits;
Chris Lattner4534dd592006-02-09 07:38:58 +0000729 }
730 return;
Chris Lattner62010c42005-10-09 06:36:35 +0000731 }
Chris Lattner0157e7f2006-02-11 09:31:47 +0000732 break;
Chris Lattner0b3557f2005-09-24 23:43:33 +0000733 }
Chris Lattner92a68652006-02-07 08:05:22 +0000734}
735
736/// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero. We use
737/// this predicate to simplify operations downstream. Mask is known to be zero
738/// for bits that V cannot have.
739static bool MaskedValueIsZero(Value *V, uint64_t Mask, unsigned Depth = 0) {
Chris Lattner4534dd592006-02-09 07:38:58 +0000740 uint64_t KnownZero, KnownOne;
741 ComputeMaskedBits(V, Mask, KnownZero, KnownOne, Depth);
742 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
743 return (KnownZero & Mask) == Mask;
Chris Lattner0b3557f2005-09-24 23:43:33 +0000744}
745
Chris Lattner0157e7f2006-02-11 09:31:47 +0000746/// ShrinkDemandedConstant - Check to see if the specified operand of the
747/// specified instruction is a constant integer. If so, check to see if there
748/// are any bits set in the constant that are not demanded. If so, shrink the
749/// constant and return true.
750static bool ShrinkDemandedConstant(Instruction *I, unsigned OpNo,
751 uint64_t Demanded) {
752 ConstantInt *OpC = dyn_cast<ConstantInt>(I->getOperand(OpNo));
753 if (!OpC) return false;
754
755 // If there are no bits set that aren't demanded, nothing to do.
756 if ((~Demanded & OpC->getZExtValue()) == 0)
757 return false;
758
759 // This is producing any bits that are not needed, shrink the RHS.
760 uint64_t Val = Demanded & OpC->getZExtValue();
761 I->setOperand(OpNo, GetConstantInType(OpC->getType(), Val));
762 return true;
763}
764
Chris Lattneree0f2802006-02-12 02:07:56 +0000765// ComputeSignedMinMaxValuesFromKnownBits - Given a signed integer type and a
766// set of known zero and one bits, compute the maximum and minimum values that
767// could have the specified known zero and known one bits, returning them in
768// min/max.
769static void ComputeSignedMinMaxValuesFromKnownBits(const Type *Ty,
770 uint64_t KnownZero,
771 uint64_t KnownOne,
772 int64_t &Min, int64_t &Max) {
773 uint64_t TypeBits = Ty->getIntegralTypeMask();
774 uint64_t UnknownBits = ~(KnownZero|KnownOne) & TypeBits;
775
776 uint64_t SignBit = 1ULL << (Ty->getPrimitiveSizeInBits()-1);
777
778 // The minimum value is when all unknown bits are zeros, EXCEPT for the sign
779 // bit if it is unknown.
780 Min = KnownOne;
781 Max = KnownOne|UnknownBits;
782
783 if (SignBit & UnknownBits) { // Sign bit is unknown
784 Min |= SignBit;
785 Max &= ~SignBit;
786 }
787
788 // Sign extend the min/max values.
789 int ShAmt = 64-Ty->getPrimitiveSizeInBits();
790 Min = (Min << ShAmt) >> ShAmt;
791 Max = (Max << ShAmt) >> ShAmt;
792}
793
794// ComputeUnsignedMinMaxValuesFromKnownBits - Given an unsigned integer type and
795// a set of known zero and one bits, compute the maximum and minimum values that
796// could have the specified known zero and known one bits, returning them in
797// min/max.
798static void ComputeUnsignedMinMaxValuesFromKnownBits(const Type *Ty,
799 uint64_t KnownZero,
800 uint64_t KnownOne,
801 uint64_t &Min,
802 uint64_t &Max) {
803 uint64_t TypeBits = Ty->getIntegralTypeMask();
804 uint64_t UnknownBits = ~(KnownZero|KnownOne) & TypeBits;
805
806 // The minimum value is when the unknown bits are all zeros.
807 Min = KnownOne;
808 // The maximum value is when the unknown bits are all ones.
809 Max = KnownOne|UnknownBits;
810}
Chris Lattner0157e7f2006-02-11 09:31:47 +0000811
812
813/// SimplifyDemandedBits - Look at V. At this point, we know that only the
814/// DemandedMask bits of the result of V are ever used downstream. If we can
815/// use this information to simplify V, do so and return true. Otherwise,
816/// analyze the expression and return a mask of KnownOne and KnownZero bits for
817/// the expression (used to simplify the caller). The KnownZero/One bits may
818/// only be accurate for those bits in the DemandedMask.
819bool InstCombiner::SimplifyDemandedBits(Value *V, uint64_t DemandedMask,
820 uint64_t &KnownZero, uint64_t &KnownOne,
Chris Lattner2590e512006-02-07 06:56:34 +0000821 unsigned Depth) {
Chris Lattner0157e7f2006-02-11 09:31:47 +0000822 if (ConstantIntegral *CI = dyn_cast<ConstantIntegral>(V)) {
823 // We know all of the bits for a constant!
824 KnownOne = CI->getZExtValue() & DemandedMask;
825 KnownZero = ~KnownOne & DemandedMask;
826 return false;
827 }
828
829 KnownZero = KnownOne = 0;
Chris Lattner2590e512006-02-07 06:56:34 +0000830 if (!V->hasOneUse()) { // Other users may use these bits.
Chris Lattner0157e7f2006-02-11 09:31:47 +0000831 if (Depth != 0) { // Not at the root.
832 // Just compute the KnownZero/KnownOne bits to simplify things downstream.
833 ComputeMaskedBits(V, DemandedMask, KnownZero, KnownOne, Depth);
Chris Lattner2590e512006-02-07 06:56:34 +0000834 return false;
Chris Lattner0157e7f2006-02-11 09:31:47 +0000835 }
Chris Lattner2590e512006-02-07 06:56:34 +0000836 // If this is the root being simplified, allow it to have multiple uses,
Chris Lattner0157e7f2006-02-11 09:31:47 +0000837 // just set the DemandedMask to all bits.
838 DemandedMask = V->getType()->getIntegralTypeMask();
839 } else if (DemandedMask == 0) { // Not demanding any bits from V.
Chris Lattner92a68652006-02-07 08:05:22 +0000840 if (V != UndefValue::get(V->getType()))
841 return UpdateValueUsesWith(V, UndefValue::get(V->getType()));
842 return false;
Chris Lattner2590e512006-02-07 06:56:34 +0000843 } else if (Depth == 6) { // Limit search depth.
844 return false;
845 }
846
847 Instruction *I = dyn_cast<Instruction>(V);
848 if (!I) return false; // Only analyze instructions.
849
Chris Lattnerfb296922006-05-04 17:33:35 +0000850 DemandedMask &= V->getType()->getIntegralTypeMask();
851
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000852 uint64_t KnownZero2 = 0, KnownOne2 = 0;
Chris Lattner2590e512006-02-07 06:56:34 +0000853 switch (I->getOpcode()) {
854 default: break;
855 case Instruction::And:
Chris Lattner0157e7f2006-02-11 09:31:47 +0000856 // If either the LHS or the RHS are Zero, the result is zero.
857 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
858 KnownZero, KnownOne, Depth+1))
859 return true;
860 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
861
862 // If something is known zero on the RHS, the bits aren't demanded on the
863 // LHS.
864 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask & ~KnownZero,
865 KnownZero2, KnownOne2, Depth+1))
866 return true;
867 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
868
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000869 // If all of the demanded bits are known 1 on one side, return the other.
Chris Lattner0157e7f2006-02-11 09:31:47 +0000870 // These bits cannot contribute to the result of the 'and'.
871 if ((DemandedMask & ~KnownZero2 & KnownOne) == (DemandedMask & ~KnownZero2))
872 return UpdateValueUsesWith(I, I->getOperand(0));
873 if ((DemandedMask & ~KnownZero & KnownOne2) == (DemandedMask & ~KnownZero))
874 return UpdateValueUsesWith(I, I->getOperand(1));
Chris Lattner5b2edb12006-02-12 08:02:11 +0000875
876 // If all of the demanded bits in the inputs are known zeros, return zero.
877 if ((DemandedMask & (KnownZero|KnownZero2)) == DemandedMask)
878 return UpdateValueUsesWith(I, Constant::getNullValue(I->getType()));
879
Chris Lattner0157e7f2006-02-11 09:31:47 +0000880 // If the RHS is a constant, see if we can simplify it.
Chris Lattner5b2edb12006-02-12 08:02:11 +0000881 if (ShrinkDemandedConstant(I, 1, DemandedMask & ~KnownZero2))
Chris Lattner0157e7f2006-02-11 09:31:47 +0000882 return UpdateValueUsesWith(I, I);
883
884 // Output known-1 bits are only known if set in both the LHS & RHS.
885 KnownOne &= KnownOne2;
886 // Output known-0 are known to be clear if zero in either the LHS | RHS.
887 KnownZero |= KnownZero2;
888 break;
889 case Instruction::Or:
890 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
891 KnownZero, KnownOne, Depth+1))
892 return true;
893 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
894 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask & ~KnownOne,
895 KnownZero2, KnownOne2, Depth+1))
896 return true;
897 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
898
899 // If all of the demanded bits are known zero on one side, return the other.
900 // These bits cannot contribute to the result of the 'or'.
Jeff Cohen0add83e2006-02-18 03:20:33 +0000901 if ((DemandedMask & ~KnownOne2 & KnownZero) == (DemandedMask & ~KnownOne2))
Chris Lattner0157e7f2006-02-11 09:31:47 +0000902 return UpdateValueUsesWith(I, I->getOperand(0));
Jeff Cohen0add83e2006-02-18 03:20:33 +0000903 if ((DemandedMask & ~KnownOne & KnownZero2) == (DemandedMask & ~KnownOne))
Chris Lattner0157e7f2006-02-11 09:31:47 +0000904 return UpdateValueUsesWith(I, I->getOperand(1));
Chris Lattner5b2edb12006-02-12 08:02:11 +0000905
906 // If all of the potentially set bits on one side are known to be set on
907 // the other side, just use the 'other' side.
908 if ((DemandedMask & (~KnownZero) & KnownOne2) ==
909 (DemandedMask & (~KnownZero)))
910 return UpdateValueUsesWith(I, I->getOperand(0));
Nate Begeman8a77efe2006-02-16 21:11:51 +0000911 if ((DemandedMask & (~KnownZero2) & KnownOne) ==
912 (DemandedMask & (~KnownZero2)))
913 return UpdateValueUsesWith(I, I->getOperand(1));
Chris Lattner0157e7f2006-02-11 09:31:47 +0000914
915 // If the RHS is a constant, see if we can simplify it.
916 if (ShrinkDemandedConstant(I, 1, DemandedMask))
917 return UpdateValueUsesWith(I, I);
918
919 // Output known-0 bits are only known if clear in both the LHS & RHS.
920 KnownZero &= KnownZero2;
921 // Output known-1 are known to be set if set in either the LHS | RHS.
922 KnownOne |= KnownOne2;
923 break;
924 case Instruction::Xor: {
925 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
926 KnownZero, KnownOne, Depth+1))
927 return true;
928 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
929 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
930 KnownZero2, KnownOne2, Depth+1))
931 return true;
932 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
933
934 // If all of the demanded bits are known zero on one side, return the other.
935 // These bits cannot contribute to the result of the 'xor'.
936 if ((DemandedMask & KnownZero) == DemandedMask)
937 return UpdateValueUsesWith(I, I->getOperand(0));
938 if ((DemandedMask & KnownZero2) == DemandedMask)
939 return UpdateValueUsesWith(I, I->getOperand(1));
940
941 // Output known-0 bits are known if clear or set in both the LHS & RHS.
942 uint64_t KnownZeroOut = (KnownZero & KnownZero2) | (KnownOne & KnownOne2);
943 // Output known-1 are known to be set if set in only one of the LHS, RHS.
944 uint64_t KnownOneOut = (KnownZero & KnownOne2) | (KnownOne & KnownZero2);
945
Chris Lattner8e9a7b72006-11-27 19:55:07 +0000946 // If all of the demanded bits are known to be zero on one side or the
947 // other, turn this into an *inclusive* or.
Chris Lattner5b2edb12006-02-12 08:02:11 +0000948 // e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
Chris Lattner8e9a7b72006-11-27 19:55:07 +0000949 if ((DemandedMask & ~KnownZero & ~KnownZero2) == 0) {
950 Instruction *Or =
951 BinaryOperator::createOr(I->getOperand(0), I->getOperand(1),
952 I->getName());
953 InsertNewInstBefore(Or, *I);
954 return UpdateValueUsesWith(I, Or);
Chris Lattner2590e512006-02-07 06:56:34 +0000955 }
Chris Lattner0157e7f2006-02-11 09:31:47 +0000956
Chris Lattner5b2edb12006-02-12 08:02:11 +0000957 // If all of the demanded bits on one side are known, and all of the set
958 // bits on that side are also known to be set on the other side, turn this
959 // into an AND, as we know the bits will be cleared.
960 // e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
961 if ((DemandedMask & (KnownZero|KnownOne)) == DemandedMask) { // all known
962 if ((KnownOne & KnownOne2) == KnownOne) {
963 Constant *AndC = GetConstantInType(I->getType(),
964 ~KnownOne & DemandedMask);
965 Instruction *And =
966 BinaryOperator::createAnd(I->getOperand(0), AndC, "tmp");
967 InsertNewInstBefore(And, *I);
968 return UpdateValueUsesWith(I, And);
969 }
970 }
971
Chris Lattner0157e7f2006-02-11 09:31:47 +0000972 // If the RHS is a constant, see if we can simplify it.
973 // FIXME: for XOR, we prefer to force bits to 1 if they will make a -1.
974 if (ShrinkDemandedConstant(I, 1, DemandedMask))
975 return UpdateValueUsesWith(I, I);
976
977 KnownZero = KnownZeroOut;
978 KnownOne = KnownOneOut;
979 break;
980 }
981 case Instruction::Select:
982 if (SimplifyDemandedBits(I->getOperand(2), DemandedMask,
983 KnownZero, KnownOne, Depth+1))
984 return true;
985 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
986 KnownZero2, KnownOne2, Depth+1))
987 return true;
988 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
989 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
990
991 // If the operands are constants, see if we can simplify them.
992 if (ShrinkDemandedConstant(I, 1, DemandedMask))
993 return UpdateValueUsesWith(I, I);
994 if (ShrinkDemandedConstant(I, 2, DemandedMask))
995 return UpdateValueUsesWith(I, I);
996
997 // Only known if known in both the LHS and RHS.
998 KnownOne &= KnownOne2;
999 KnownZero &= KnownZero2;
1000 break;
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001001 case Instruction::Trunc:
1002 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1003 KnownZero, KnownOne, Depth+1))
1004 return true;
1005 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1006 break;
1007 case Instruction::BitCast:
1008 if (!I->getOperand(0)->getType()->isIntegral())
1009 return false;
Chris Lattner850465d2006-09-16 03:14:10 +00001010
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001011 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1012 KnownZero, KnownOne, Depth+1))
1013 return true;
1014 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1015 break;
1016 case Instruction::ZExt: {
1017 // Compute the bits in the result that are not present in the input.
1018 const Type *SrcTy = I->getOperand(0)->getType();
Chris Lattner0157e7f2006-02-11 09:31:47 +00001019 uint64_t NotIn = ~SrcTy->getIntegralTypeMask();
1020 uint64_t NewBits = I->getType()->getIntegralTypeMask() & NotIn;
1021
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001022 DemandedMask &= SrcTy->getIntegralTypeMask();
1023 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1024 KnownZero, KnownOne, Depth+1))
1025 return true;
1026 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1027 // The top bits are known to be zero.
1028 KnownZero |= NewBits;
1029 break;
1030 }
1031 case Instruction::SExt: {
1032 // Compute the bits in the result that are not present in the input.
1033 const Type *SrcTy = I->getOperand(0)->getType();
1034 uint64_t NotIn = ~SrcTy->getIntegralTypeMask();
1035 uint64_t NewBits = I->getType()->getIntegralTypeMask() & NotIn;
1036
1037 // Get the sign bit for the source type
1038 uint64_t InSignBit = 1ULL << (SrcTy->getPrimitiveSizeInBits()-1);
1039 int64_t InputDemandedBits = DemandedMask & SrcTy->getIntegralTypeMask();
Chris Lattner7d852282006-02-13 22:41:07 +00001040
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001041 // If any of the sign extended bits are demanded, we know that the sign
1042 // bit is demanded.
1043 if (NewBits & DemandedMask)
1044 InputDemandedBits |= InSignBit;
Chris Lattner7d852282006-02-13 22:41:07 +00001045
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001046 if (SimplifyDemandedBits(I->getOperand(0), InputDemandedBits,
1047 KnownZero, KnownOne, Depth+1))
1048 return true;
1049 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
Chris Lattner0157e7f2006-02-11 09:31:47 +00001050
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001051 // If the sign bit of the input is known set or clear, then we know the
1052 // top bits of the result.
Chris Lattner2590e512006-02-07 06:56:34 +00001053
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001054 // If the input sign bit is known zero, or if the NewBits are not demanded
1055 // convert this into a zero extension.
1056 if ((KnownZero & InSignBit) || (NewBits & ~DemandedMask) == NewBits) {
1057 // Convert to ZExt cast
1058 CastInst *NewCast = CastInst::create(
1059 Instruction::ZExt, I->getOperand(0), I->getType(), I->getName(), I);
1060 return UpdateValueUsesWith(I, NewCast);
1061 } else if (KnownOne & InSignBit) { // Input sign bit known set
1062 KnownOne |= NewBits;
1063 KnownZero &= ~NewBits;
1064 } else { // Input sign bit unknown
1065 KnownZero &= ~NewBits;
1066 KnownOne &= ~NewBits;
Chris Lattner2590e512006-02-07 06:56:34 +00001067 }
Chris Lattner0157e7f2006-02-11 09:31:47 +00001068 break;
Chris Lattner2590e512006-02-07 06:56:34 +00001069 }
Chris Lattner6e2c15c2006-11-09 05:12:27 +00001070 case Instruction::Add:
1071 // If there is a constant on the RHS, there are a variety of xformations
1072 // we can do.
1073 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
1074 // If null, this should be simplified elsewhere. Some of the xforms here
1075 // won't work if the RHS is zero.
1076 if (RHS->isNullValue())
1077 break;
1078
1079 // Figure out what the input bits are. If the top bits of the and result
1080 // are not demanded, then the add doesn't demand them from its input
1081 // either.
1082
1083 // Shift the demanded mask up so that it's at the top of the uint64_t.
1084 unsigned BitWidth = I->getType()->getPrimitiveSizeInBits();
1085 unsigned NLZ = CountLeadingZeros_64(DemandedMask << (64-BitWidth));
1086
1087 // If the top bit of the output is demanded, demand everything from the
1088 // input. Otherwise, we demand all the input bits except NLZ top bits.
1089 uint64_t InDemandedBits = ~0ULL >> 64-BitWidth+NLZ;
1090
1091 // Find information about known zero/one bits in the input.
1092 if (SimplifyDemandedBits(I->getOperand(0), InDemandedBits,
1093 KnownZero2, KnownOne2, Depth+1))
1094 return true;
1095
1096 // If the RHS of the add has bits set that can't affect the input, reduce
1097 // the constant.
1098 if (ShrinkDemandedConstant(I, 1, InDemandedBits))
1099 return UpdateValueUsesWith(I, I);
1100
1101 // Avoid excess work.
1102 if (KnownZero2 == 0 && KnownOne2 == 0)
1103 break;
1104
1105 // Turn it into OR if input bits are zero.
1106 if ((KnownZero2 & RHS->getZExtValue()) == RHS->getZExtValue()) {
1107 Instruction *Or =
1108 BinaryOperator::createOr(I->getOperand(0), I->getOperand(1),
1109 I->getName());
1110 InsertNewInstBefore(Or, *I);
1111 return UpdateValueUsesWith(I, Or);
1112 }
1113
1114 // We can say something about the output known-zero and known-one bits,
1115 // depending on potential carries from the input constant and the
1116 // unknowns. For example if the LHS is known to have at most the 0x0F0F0
1117 // bits set and the RHS constant is 0x01001, then we know we have a known
1118 // one mask of 0x00001 and a known zero mask of 0xE0F0E.
1119
1120 // To compute this, we first compute the potential carry bits. These are
1121 // the bits which may be modified. I'm not aware of a better way to do
1122 // this scan.
1123 uint64_t RHSVal = RHS->getZExtValue();
1124
1125 bool CarryIn = false;
1126 uint64_t CarryBits = 0;
1127 uint64_t CurBit = 1;
1128 for (unsigned i = 0; i != BitWidth; ++i, CurBit <<= 1) {
1129 // Record the current carry in.
1130 if (CarryIn) CarryBits |= CurBit;
1131
1132 bool CarryOut;
1133
1134 // This bit has a carry out unless it is "zero + zero" or
1135 // "zero + anything" with no carry in.
1136 if ((KnownZero2 & CurBit) && ((RHSVal & CurBit) == 0)) {
1137 CarryOut = false; // 0 + 0 has no carry out, even with carry in.
1138 } else if (!CarryIn &&
1139 ((KnownZero2 & CurBit) || ((RHSVal & CurBit) == 0))) {
1140 CarryOut = false; // 0 + anything has no carry out if no carry in.
1141 } else {
1142 // Otherwise, we have to assume we have a carry out.
1143 CarryOut = true;
1144 }
1145
1146 // This stage's carry out becomes the next stage's carry-in.
1147 CarryIn = CarryOut;
1148 }
1149
1150 // Now that we know which bits have carries, compute the known-1/0 sets.
1151
1152 // Bits are known one if they are known zero in one operand and one in the
1153 // other, and there is no input carry.
1154 KnownOne = ((KnownZero2 & RHSVal) | (KnownOne2 & ~RHSVal)) & ~CarryBits;
1155
1156 // Bits are known zero if they are known zero in both operands and there
1157 // is no input carry.
1158 KnownZero = KnownZero2 & ~RHSVal & ~CarryBits;
1159 }
1160 break;
Chris Lattner2590e512006-02-07 06:56:34 +00001161 case Instruction::Shl:
Reid Spencere0fc4df2006-10-20 07:07:24 +00001162 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1163 uint64_t ShiftAmt = SA->getZExtValue();
1164 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask >> ShiftAmt,
Chris Lattner0157e7f2006-02-11 09:31:47 +00001165 KnownZero, KnownOne, Depth+1))
1166 return true;
1167 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
Reid Spencere0fc4df2006-10-20 07:07:24 +00001168 KnownZero <<= ShiftAmt;
1169 KnownOne <<= ShiftAmt;
1170 KnownZero |= (1ULL << ShiftAmt) - 1; // low bits known zero.
Chris Lattner0157e7f2006-02-11 09:31:47 +00001171 }
Chris Lattner2590e512006-02-07 06:56:34 +00001172 break;
Reid Spencerfdff9382006-11-08 06:47:33 +00001173 case Instruction::LShr:
1174 // For a logical shift right
1175 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1176 unsigned ShiftAmt = SA->getZExtValue();
1177
1178 // Compute the new bits that are at the top now.
1179 uint64_t HighBits = (1ULL << ShiftAmt)-1;
1180 HighBits <<= I->getType()->getPrimitiveSizeInBits() - ShiftAmt;
1181 uint64_t TypeMask = I->getType()->getIntegralTypeMask();
1182 // Unsigned shift right.
1183 if (SimplifyDemandedBits(I->getOperand(0),
1184 (DemandedMask << ShiftAmt) & TypeMask,
1185 KnownZero, KnownOne, Depth+1))
1186 return true;
1187 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1188 KnownZero &= TypeMask;
1189 KnownOne &= TypeMask;
1190 KnownZero >>= ShiftAmt;
1191 KnownOne >>= ShiftAmt;
1192 KnownZero |= HighBits; // high bits known zero.
1193 }
1194 break;
1195 case Instruction::AShr:
Chris Lattner420c4bc2006-09-18 04:31:40 +00001196 // If this is an arithmetic shift right and only the low-bit is set, we can
1197 // always convert this into a logical shr, even if the shift amount is
1198 // variable. The low bit of the shift cannot be an input sign bit unless
1199 // the shift amount is >= the size of the datatype, which is undefined.
Reid Spencerfdff9382006-11-08 06:47:33 +00001200 if (DemandedMask == 1) {
1201 // Perform the logical shift right.
1202 Value *NewVal = new ShiftInst(Instruction::LShr, I->getOperand(0),
1203 I->getOperand(1), I->getName());
Reid Spencer00c482b2006-10-26 19:19:06 +00001204 InsertNewInstBefore(cast<Instruction>(NewVal), *I);
Chris Lattner420c4bc2006-09-18 04:31:40 +00001205 return UpdateValueUsesWith(I, NewVal);
1206 }
1207
Reid Spencere0fc4df2006-10-20 07:07:24 +00001208 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1209 unsigned ShiftAmt = SA->getZExtValue();
Chris Lattner0157e7f2006-02-11 09:31:47 +00001210
1211 // Compute the new bits that are at the top now.
Reid Spencere0fc4df2006-10-20 07:07:24 +00001212 uint64_t HighBits = (1ULL << ShiftAmt)-1;
1213 HighBits <<= I->getType()->getPrimitiveSizeInBits() - ShiftAmt;
Chris Lattner68e74752006-02-13 06:09:08 +00001214 uint64_t TypeMask = I->getType()->getIntegralTypeMask();
Reid Spencerfdff9382006-11-08 06:47:33 +00001215 // Signed shift right.
1216 if (SimplifyDemandedBits(I->getOperand(0),
1217 (DemandedMask << ShiftAmt) & TypeMask,
1218 KnownZero, KnownOne, Depth+1))
1219 return true;
1220 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1221 KnownZero &= TypeMask;
1222 KnownOne &= TypeMask;
1223 KnownZero >>= ShiftAmt;
1224 KnownOne >>= ShiftAmt;
Chris Lattner0157e7f2006-02-11 09:31:47 +00001225
Reid Spencerfdff9382006-11-08 06:47:33 +00001226 // Handle the sign bits.
1227 uint64_t SignBit = 1ULL << (I->getType()->getPrimitiveSizeInBits()-1);
1228 SignBit >>= ShiftAmt; // Adjust to where it is now in the mask.
Chris Lattner0157e7f2006-02-11 09:31:47 +00001229
Reid Spencerfdff9382006-11-08 06:47:33 +00001230 // If the input sign bit is known to be zero, or if none of the top bits
1231 // are demanded, turn this into an unsigned shift right.
1232 if ((KnownZero & SignBit) || (HighBits & ~DemandedMask) == HighBits) {
1233 // Perform the logical shift right.
1234 Value *NewVal = new ShiftInst(Instruction::LShr, I->getOperand(0),
1235 SA, I->getName());
1236 InsertNewInstBefore(cast<Instruction>(NewVal), *I);
1237 return UpdateValueUsesWith(I, NewVal);
1238 } else if (KnownOne & SignBit) { // New bits are known one.
1239 KnownOne |= HighBits;
Chris Lattner2590e512006-02-07 06:56:34 +00001240 }
Chris Lattner0157e7f2006-02-11 09:31:47 +00001241 }
Chris Lattner2590e512006-02-07 06:56:34 +00001242 break;
1243 }
Chris Lattner0157e7f2006-02-11 09:31:47 +00001244
1245 // If the client is only demanding bits that we know, return the known
1246 // constant.
1247 if ((DemandedMask & (KnownZero|KnownOne)) == DemandedMask)
1248 return UpdateValueUsesWith(I, GetConstantInType(I->getType(), KnownOne));
Chris Lattner2590e512006-02-07 06:56:34 +00001249 return false;
1250}
1251
Chris Lattner2deeaea2006-10-05 06:55:50 +00001252
1253/// SimplifyDemandedVectorElts - The specified value producecs a vector with
1254/// 64 or fewer elements. DemandedElts contains the set of elements that are
1255/// actually used by the caller. This method analyzes which elements of the
1256/// operand are undef and returns that information in UndefElts.
1257///
1258/// If the information about demanded elements can be used to simplify the
1259/// operation, the operation is simplified, then the resultant value is
1260/// returned. This returns null if no change was made.
1261Value *InstCombiner::SimplifyDemandedVectorElts(Value *V, uint64_t DemandedElts,
1262 uint64_t &UndefElts,
1263 unsigned Depth) {
1264 unsigned VWidth = cast<PackedType>(V->getType())->getNumElements();
1265 assert(VWidth <= 64 && "Vector too wide to analyze!");
1266 uint64_t EltMask = ~0ULL >> (64-VWidth);
1267 assert(DemandedElts != EltMask && (DemandedElts & ~EltMask) == 0 &&
1268 "Invalid DemandedElts!");
1269
1270 if (isa<UndefValue>(V)) {
1271 // If the entire vector is undefined, just return this info.
1272 UndefElts = EltMask;
1273 return 0;
1274 } else if (DemandedElts == 0) { // If nothing is demanded, provide undef.
1275 UndefElts = EltMask;
1276 return UndefValue::get(V->getType());
1277 }
1278
1279 UndefElts = 0;
1280 if (ConstantPacked *CP = dyn_cast<ConstantPacked>(V)) {
1281 const Type *EltTy = cast<PackedType>(V->getType())->getElementType();
1282 Constant *Undef = UndefValue::get(EltTy);
1283
1284 std::vector<Constant*> Elts;
1285 for (unsigned i = 0; i != VWidth; ++i)
1286 if (!(DemandedElts & (1ULL << i))) { // If not demanded, set to undef.
1287 Elts.push_back(Undef);
1288 UndefElts |= (1ULL << i);
1289 } else if (isa<UndefValue>(CP->getOperand(i))) { // Already undef.
1290 Elts.push_back(Undef);
1291 UndefElts |= (1ULL << i);
1292 } else { // Otherwise, defined.
1293 Elts.push_back(CP->getOperand(i));
1294 }
1295
1296 // If we changed the constant, return it.
1297 Constant *NewCP = ConstantPacked::get(Elts);
1298 return NewCP != CP ? NewCP : 0;
1299 } else if (isa<ConstantAggregateZero>(V)) {
1300 // Simplify the CAZ to a ConstantPacked where the non-demanded elements are
1301 // set to undef.
1302 const Type *EltTy = cast<PackedType>(V->getType())->getElementType();
1303 Constant *Zero = Constant::getNullValue(EltTy);
1304 Constant *Undef = UndefValue::get(EltTy);
1305 std::vector<Constant*> Elts;
1306 for (unsigned i = 0; i != VWidth; ++i)
1307 Elts.push_back((DemandedElts & (1ULL << i)) ? Zero : Undef);
1308 UndefElts = DemandedElts ^ EltMask;
1309 return ConstantPacked::get(Elts);
1310 }
1311
1312 if (!V->hasOneUse()) { // Other users may use these bits.
1313 if (Depth != 0) { // Not at the root.
1314 // TODO: Just compute the UndefElts information recursively.
1315 return false;
1316 }
1317 return false;
1318 } else if (Depth == 10) { // Limit search depth.
1319 return false;
1320 }
1321
1322 Instruction *I = dyn_cast<Instruction>(V);
1323 if (!I) return false; // Only analyze instructions.
1324
1325 bool MadeChange = false;
1326 uint64_t UndefElts2;
1327 Value *TmpV;
1328 switch (I->getOpcode()) {
1329 default: break;
1330
1331 case Instruction::InsertElement: {
1332 // If this is a variable index, we don't know which element it overwrites.
1333 // demand exactly the same input as we produce.
Reid Spencere0fc4df2006-10-20 07:07:24 +00001334 ConstantInt *Idx = dyn_cast<ConstantInt>(I->getOperand(2));
Chris Lattner2deeaea2006-10-05 06:55:50 +00001335 if (Idx == 0) {
1336 // Note that we can't propagate undef elt info, because we don't know
1337 // which elt is getting updated.
1338 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1339 UndefElts2, Depth+1);
1340 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1341 break;
1342 }
1343
1344 // If this is inserting an element that isn't demanded, remove this
1345 // insertelement.
Reid Spencere0fc4df2006-10-20 07:07:24 +00001346 unsigned IdxNo = Idx->getZExtValue();
Chris Lattner2deeaea2006-10-05 06:55:50 +00001347 if (IdxNo >= VWidth || (DemandedElts & (1ULL << IdxNo)) == 0)
1348 return AddSoonDeadInstToWorklist(*I, 0);
1349
1350 // Otherwise, the element inserted overwrites whatever was there, so the
1351 // input demanded set is simpler than the output set.
1352 TmpV = SimplifyDemandedVectorElts(I->getOperand(0),
1353 DemandedElts & ~(1ULL << IdxNo),
1354 UndefElts, Depth+1);
1355 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1356
1357 // The inserted element is defined.
1358 UndefElts |= 1ULL << IdxNo;
1359 break;
1360 }
1361
1362 case Instruction::And:
1363 case Instruction::Or:
1364 case Instruction::Xor:
1365 case Instruction::Add:
1366 case Instruction::Sub:
1367 case Instruction::Mul:
1368 // div/rem demand all inputs, because they don't want divide by zero.
1369 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1370 UndefElts, Depth+1);
1371 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1372 TmpV = SimplifyDemandedVectorElts(I->getOperand(1), DemandedElts,
1373 UndefElts2, Depth+1);
1374 if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1375
1376 // Output elements are undefined if both are undefined. Consider things
1377 // like undef&0. The result is known zero, not undef.
1378 UndefElts &= UndefElts2;
1379 break;
1380
1381 case Instruction::Call: {
1382 IntrinsicInst *II = dyn_cast<IntrinsicInst>(I);
1383 if (!II) break;
1384 switch (II->getIntrinsicID()) {
1385 default: break;
1386
1387 // Binary vector operations that work column-wise. A dest element is a
1388 // function of the corresponding input elements from the two inputs.
1389 case Intrinsic::x86_sse_sub_ss:
1390 case Intrinsic::x86_sse_mul_ss:
1391 case Intrinsic::x86_sse_min_ss:
1392 case Intrinsic::x86_sse_max_ss:
1393 case Intrinsic::x86_sse2_sub_sd:
1394 case Intrinsic::x86_sse2_mul_sd:
1395 case Intrinsic::x86_sse2_min_sd:
1396 case Intrinsic::x86_sse2_max_sd:
1397 TmpV = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
1398 UndefElts, Depth+1);
1399 if (TmpV) { II->setOperand(1, TmpV); MadeChange = true; }
1400 TmpV = SimplifyDemandedVectorElts(II->getOperand(2), DemandedElts,
1401 UndefElts2, Depth+1);
1402 if (TmpV) { II->setOperand(2, TmpV); MadeChange = true; }
1403
1404 // If only the low elt is demanded and this is a scalarizable intrinsic,
1405 // scalarize it now.
1406 if (DemandedElts == 1) {
1407 switch (II->getIntrinsicID()) {
1408 default: break;
1409 case Intrinsic::x86_sse_sub_ss:
1410 case Intrinsic::x86_sse_mul_ss:
1411 case Intrinsic::x86_sse2_sub_sd:
1412 case Intrinsic::x86_sse2_mul_sd:
1413 // TODO: Lower MIN/MAX/ABS/etc
1414 Value *LHS = II->getOperand(1);
1415 Value *RHS = II->getOperand(2);
1416 // Extract the element as scalars.
1417 LHS = InsertNewInstBefore(new ExtractElementInst(LHS, 0U,"tmp"), *II);
1418 RHS = InsertNewInstBefore(new ExtractElementInst(RHS, 0U,"tmp"), *II);
1419
1420 switch (II->getIntrinsicID()) {
1421 default: assert(0 && "Case stmts out of sync!");
1422 case Intrinsic::x86_sse_sub_ss:
1423 case Intrinsic::x86_sse2_sub_sd:
1424 TmpV = InsertNewInstBefore(BinaryOperator::createSub(LHS, RHS,
1425 II->getName()), *II);
1426 break;
1427 case Intrinsic::x86_sse_mul_ss:
1428 case Intrinsic::x86_sse2_mul_sd:
1429 TmpV = InsertNewInstBefore(BinaryOperator::createMul(LHS, RHS,
1430 II->getName()), *II);
1431 break;
1432 }
1433
1434 Instruction *New =
1435 new InsertElementInst(UndefValue::get(II->getType()), TmpV, 0U,
1436 II->getName());
1437 InsertNewInstBefore(New, *II);
1438 AddSoonDeadInstToWorklist(*II, 0);
1439 return New;
1440 }
1441 }
1442
1443 // Output elements are undefined if both are undefined. Consider things
1444 // like undef&0. The result is known zero, not undef.
1445 UndefElts &= UndefElts2;
1446 break;
1447 }
1448 break;
1449 }
1450 }
1451 return MadeChange ? I : 0;
1452}
1453
Chris Lattner623826c2004-09-28 21:48:02 +00001454// isTrueWhenEqual - Return true if the specified setcondinst instruction is
1455// true when both operands are equal...
1456//
1457static bool isTrueWhenEqual(Instruction &I) {
1458 return I.getOpcode() == Instruction::SetEQ ||
1459 I.getOpcode() == Instruction::SetGE ||
1460 I.getOpcode() == Instruction::SetLE;
1461}
Chris Lattnerb8b97502003-08-13 19:01:45 +00001462
1463/// AssociativeOpt - Perform an optimization on an associative operator. This
1464/// function is designed to check a chain of associative operators for a
1465/// potential to apply a certain optimization. Since the optimization may be
1466/// applicable if the expression was reassociated, this checks the chain, then
1467/// reassociates the expression as necessary to expose the optimization
1468/// opportunity. This makes use of a special Functor, which must define
1469/// 'shouldApply' and 'apply' methods.
1470///
1471template<typename Functor>
1472Instruction *AssociativeOpt(BinaryOperator &Root, const Functor &F) {
1473 unsigned Opcode = Root.getOpcode();
1474 Value *LHS = Root.getOperand(0);
1475
1476 // Quick check, see if the immediate LHS matches...
1477 if (F.shouldApply(LHS))
1478 return F.apply(Root);
1479
1480 // Otherwise, if the LHS is not of the same opcode as the root, return.
1481 Instruction *LHSI = dyn_cast<Instruction>(LHS);
Chris Lattnerf95d9b92003-10-15 16:48:29 +00001482 while (LHSI && LHSI->getOpcode() == Opcode && LHSI->hasOneUse()) {
Chris Lattnerb8b97502003-08-13 19:01:45 +00001483 // Should we apply this transform to the RHS?
1484 bool ShouldApply = F.shouldApply(LHSI->getOperand(1));
1485
1486 // If not to the RHS, check to see if we should apply to the LHS...
1487 if (!ShouldApply && F.shouldApply(LHSI->getOperand(0))) {
1488 cast<BinaryOperator>(LHSI)->swapOperands(); // Make the LHS the RHS
1489 ShouldApply = true;
1490 }
1491
1492 // If the functor wants to apply the optimization to the RHS of LHSI,
1493 // reassociate the expression from ((? op A) op B) to (? op (A op B))
1494 if (ShouldApply) {
1495 BasicBlock *BB = Root.getParent();
Misha Brukmanb1c93172005-04-21 23:48:37 +00001496
Chris Lattnerb8b97502003-08-13 19:01:45 +00001497 // Now all of the instructions are in the current basic block, go ahead
1498 // and perform the reassociation.
1499 Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
1500
1501 // First move the selected RHS to the LHS of the root...
1502 Root.setOperand(0, LHSI->getOperand(1));
1503
1504 // Make what used to be the LHS of the root be the user of the root...
1505 Value *ExtraOperand = TmpLHSI->getOperand(1);
Chris Lattner284d3b02004-04-16 18:08:07 +00001506 if (&Root == TmpLHSI) {
Chris Lattner8953b902004-04-05 02:10:19 +00001507 Root.replaceAllUsesWith(Constant::getNullValue(TmpLHSI->getType()));
1508 return 0;
1509 }
Chris Lattner284d3b02004-04-16 18:08:07 +00001510 Root.replaceAllUsesWith(TmpLHSI); // Users now use TmpLHSI
Chris Lattnerb8b97502003-08-13 19:01:45 +00001511 TmpLHSI->setOperand(1, &Root); // TmpLHSI now uses the root
Chris Lattner284d3b02004-04-16 18:08:07 +00001512 TmpLHSI->getParent()->getInstList().remove(TmpLHSI);
1513 BasicBlock::iterator ARI = &Root; ++ARI;
1514 BB->getInstList().insert(ARI, TmpLHSI); // Move TmpLHSI to after Root
1515 ARI = Root;
Chris Lattnerb8b97502003-08-13 19:01:45 +00001516
1517 // Now propagate the ExtraOperand down the chain of instructions until we
1518 // get to LHSI.
1519 while (TmpLHSI != LHSI) {
1520 Instruction *NextLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
Chris Lattner284d3b02004-04-16 18:08:07 +00001521 // Move the instruction to immediately before the chain we are
1522 // constructing to avoid breaking dominance properties.
1523 NextLHSI->getParent()->getInstList().remove(NextLHSI);
1524 BB->getInstList().insert(ARI, NextLHSI);
1525 ARI = NextLHSI;
1526
Chris Lattnerb8b97502003-08-13 19:01:45 +00001527 Value *NextOp = NextLHSI->getOperand(1);
1528 NextLHSI->setOperand(1, ExtraOperand);
1529 TmpLHSI = NextLHSI;
1530 ExtraOperand = NextOp;
1531 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00001532
Chris Lattnerb8b97502003-08-13 19:01:45 +00001533 // Now that the instructions are reassociated, have the functor perform
1534 // the transformation...
1535 return F.apply(Root);
1536 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00001537
Chris Lattnerb8b97502003-08-13 19:01:45 +00001538 LHSI = dyn_cast<Instruction>(LHSI->getOperand(0));
1539 }
1540 return 0;
1541}
1542
1543
1544// AddRHS - Implements: X + X --> X << 1
1545struct AddRHS {
1546 Value *RHS;
1547 AddRHS(Value *rhs) : RHS(rhs) {}
1548 bool shouldApply(Value *LHS) const { return LHS == RHS; }
1549 Instruction *apply(BinaryOperator &Add) const {
1550 return new ShiftInst(Instruction::Shl, Add.getOperand(0),
1551 ConstantInt::get(Type::UByteTy, 1));
1552 }
1553};
1554
1555// AddMaskingAnd - Implements (A & C1)+(B & C2) --> (A & C1)|(B & C2)
1556// iff C1&C2 == 0
1557struct AddMaskingAnd {
1558 Constant *C2;
1559 AddMaskingAnd(Constant *c) : C2(c) {}
1560 bool shouldApply(Value *LHS) const {
Chris Lattnerd4252a72004-07-30 07:50:03 +00001561 ConstantInt *C1;
Misha Brukmanb1c93172005-04-21 23:48:37 +00001562 return match(LHS, m_And(m_Value(), m_ConstantInt(C1))) &&
Chris Lattnerd4252a72004-07-30 07:50:03 +00001563 ConstantExpr::getAnd(C1, C2)->isNullValue();
Chris Lattnerb8b97502003-08-13 19:01:45 +00001564 }
1565 Instruction *apply(BinaryOperator &Add) const {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001566 return BinaryOperator::createOr(Add.getOperand(0), Add.getOperand(1));
Chris Lattnerb8b97502003-08-13 19:01:45 +00001567 }
1568};
1569
Chris Lattner86102b82005-01-01 16:22:27 +00001570static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
Chris Lattner183b3362004-04-09 19:05:30 +00001571 InstCombiner *IC) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001572 if (CastInst *CI = dyn_cast<CastInst>(&I)) {
Chris Lattner86102b82005-01-01 16:22:27 +00001573 if (Constant *SOC = dyn_cast<Constant>(SO))
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001574 return ConstantExpr::getCast(CI->getOpcode(), SOC, I.getType());
Misha Brukmanb1c93172005-04-21 23:48:37 +00001575
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001576 return IC->InsertNewInstBefore(CastInst::create(
1577 CI->getOpcode(), SO, I.getType(), SO->getName() + ".cast"), I);
Chris Lattner86102b82005-01-01 16:22:27 +00001578 }
1579
Chris Lattner183b3362004-04-09 19:05:30 +00001580 // Figure out if the constant is the left or the right argument.
Chris Lattner86102b82005-01-01 16:22:27 +00001581 bool ConstIsRHS = isa<Constant>(I.getOperand(1));
1582 Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
Chris Lattnerb8b97502003-08-13 19:01:45 +00001583
Chris Lattner183b3362004-04-09 19:05:30 +00001584 if (Constant *SOC = dyn_cast<Constant>(SO)) {
1585 if (ConstIsRHS)
Chris Lattner86102b82005-01-01 16:22:27 +00001586 return ConstantExpr::get(I.getOpcode(), SOC, ConstOperand);
1587 return ConstantExpr::get(I.getOpcode(), ConstOperand, SOC);
Chris Lattner183b3362004-04-09 19:05:30 +00001588 }
1589
1590 Value *Op0 = SO, *Op1 = ConstOperand;
1591 if (!ConstIsRHS)
1592 std::swap(Op0, Op1);
1593 Instruction *New;
Chris Lattner86102b82005-01-01 16:22:27 +00001594 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
1595 New = BinaryOperator::create(BO->getOpcode(), Op0, Op1,SO->getName()+".op");
1596 else if (ShiftInst *SI = dyn_cast<ShiftInst>(&I))
1597 New = new ShiftInst(SI->getOpcode(), Op0, Op1, SO->getName()+".sh");
Chris Lattnerf9d96652004-04-10 19:15:56 +00001598 else {
Chris Lattner183b3362004-04-09 19:05:30 +00001599 assert(0 && "Unknown binary instruction type!");
Chris Lattnerf9d96652004-04-10 19:15:56 +00001600 abort();
1601 }
Chris Lattner86102b82005-01-01 16:22:27 +00001602 return IC->InsertNewInstBefore(New, I);
1603}
1604
1605// FoldOpIntoSelect - Given an instruction with a select as one operand and a
1606// constant as the other operand, try to fold the binary operator into the
1607// select arguments. This also works for Cast instructions, which obviously do
1608// not have a second operand.
1609static Instruction *FoldOpIntoSelect(Instruction &Op, SelectInst *SI,
1610 InstCombiner *IC) {
1611 // Don't modify shared select instructions
1612 if (!SI->hasOneUse()) return 0;
1613 Value *TV = SI->getOperand(1);
1614 Value *FV = SI->getOperand(2);
1615
1616 if (isa<Constant>(TV) || isa<Constant>(FV)) {
Chris Lattner374e6592005-04-21 05:43:13 +00001617 // Bool selects with constant operands can be folded to logical ops.
1618 if (SI->getType() == Type::BoolTy) return 0;
1619
Chris Lattner86102b82005-01-01 16:22:27 +00001620 Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, IC);
1621 Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, IC);
1622
1623 return new SelectInst(SI->getCondition(), SelectTrueVal,
1624 SelectFalseVal);
1625 }
1626 return 0;
Chris Lattner183b3362004-04-09 19:05:30 +00001627}
1628
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001629
1630/// FoldOpIntoPhi - Given a binary operator or cast instruction which has a PHI
1631/// node as operand #0, see if we can fold the instruction into the PHI (which
1632/// is only possible if all operands to the PHI are constants).
1633Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I) {
1634 PHINode *PN = cast<PHINode>(I.getOperand(0));
Chris Lattner7515cab2004-11-14 19:13:23 +00001635 unsigned NumPHIValues = PN->getNumIncomingValues();
Chris Lattner04689872006-09-09 22:02:56 +00001636 if (!PN->hasOneUse() || NumPHIValues == 0) return 0;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001637
Chris Lattner04689872006-09-09 22:02:56 +00001638 // Check to see if all of the operands of the PHI are constants. If there is
1639 // one non-constant value, remember the BB it is. If there is more than one
1640 // bail out.
1641 BasicBlock *NonConstBB = 0;
1642 for (unsigned i = 0; i != NumPHIValues; ++i)
1643 if (!isa<Constant>(PN->getIncomingValue(i))) {
1644 if (NonConstBB) return 0; // More than one non-const value.
1645 NonConstBB = PN->getIncomingBlock(i);
1646
1647 // If the incoming non-constant value is in I's block, we have an infinite
1648 // loop.
1649 if (NonConstBB == I.getParent())
1650 return 0;
1651 }
1652
1653 // If there is exactly one non-constant value, we can insert a copy of the
1654 // operation in that block. However, if this is a critical edge, we would be
1655 // inserting the computation one some other paths (e.g. inside a loop). Only
1656 // do this if the pred block is unconditionally branching into the phi block.
1657 if (NonConstBB) {
1658 BranchInst *BI = dyn_cast<BranchInst>(NonConstBB->getTerminator());
1659 if (!BI || !BI->isUnconditional()) return 0;
1660 }
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001661
1662 // Okay, we can do the transformation: create the new PHI node.
1663 PHINode *NewPN = new PHINode(I.getType(), I.getName());
1664 I.setName("");
Chris Lattnerd8e20182005-01-29 00:39:08 +00001665 NewPN->reserveOperandSpace(PN->getNumOperands()/2);
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001666 InsertNewInstBefore(NewPN, *PN);
1667
1668 // Next, add all of the operands to the PHI.
1669 if (I.getNumOperands() == 2) {
1670 Constant *C = cast<Constant>(I.getOperand(1));
Chris Lattner7515cab2004-11-14 19:13:23 +00001671 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattner04689872006-09-09 22:02:56 +00001672 Value *InV;
1673 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
1674 InV = ConstantExpr::get(I.getOpcode(), InC, C);
1675 } else {
1676 assert(PN->getIncomingBlock(i) == NonConstBB);
1677 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
1678 InV = BinaryOperator::create(BO->getOpcode(),
1679 PN->getIncomingValue(i), C, "phitmp",
1680 NonConstBB->getTerminator());
1681 else if (ShiftInst *SI = dyn_cast<ShiftInst>(&I))
1682 InV = new ShiftInst(SI->getOpcode(),
1683 PN->getIncomingValue(i), C, "phitmp",
1684 NonConstBB->getTerminator());
1685 else
1686 assert(0 && "Unknown binop!");
1687
1688 WorkList.push_back(cast<Instruction>(InV));
1689 }
1690 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001691 }
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001692 } else {
1693 CastInst *CI = cast<CastInst>(&I);
1694 const Type *RetTy = CI->getType();
Chris Lattner7515cab2004-11-14 19:13:23 +00001695 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattner04689872006-09-09 22:02:56 +00001696 Value *InV;
1697 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001698 InV = ConstantExpr::getCast(CI->getOpcode(), InC, RetTy);
Chris Lattner04689872006-09-09 22:02:56 +00001699 } else {
1700 assert(PN->getIncomingBlock(i) == NonConstBB);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001701 InV = CastInst::create(CI->getOpcode(), PN->getIncomingValue(i),
1702 I.getType(), "phitmp",
1703 NonConstBB->getTerminator());
Chris Lattner04689872006-09-09 22:02:56 +00001704 WorkList.push_back(cast<Instruction>(InV));
1705 }
1706 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001707 }
1708 }
1709 return ReplaceInstUsesWith(I, NewPN);
1710}
1711
Chris Lattner113f4f42002-06-25 16:13:24 +00001712Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00001713 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00001714 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
Chris Lattner9fa53de2002-05-06 16:49:18 +00001715
Chris Lattnercf4a9962004-04-10 22:01:55 +00001716 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
Chris Lattner81a7a232004-10-16 18:11:37 +00001717 // X + undef -> undef
1718 if (isa<UndefValue>(RHS))
1719 return ReplaceInstUsesWith(I, RHS);
1720
Chris Lattnercf4a9962004-04-10 22:01:55 +00001721 // X + 0 --> X
Chris Lattner7a002fe2006-12-02 00:13:08 +00001722 if (!I.getType()->isFPOrFPVector()) { // NOTE: -0 + +0 = +0.
Chris Lattner7fde91e2005-10-17 17:56:38 +00001723 if (RHSC->isNullValue())
1724 return ReplaceInstUsesWith(I, LHS);
Chris Lattnerda1b1522005-10-17 20:18:38 +00001725 } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
1726 if (CFP->isExactlyValue(-0.0))
1727 return ReplaceInstUsesWith(I, LHS);
Chris Lattner7fde91e2005-10-17 17:56:38 +00001728 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00001729
Chris Lattnercf4a9962004-04-10 22:01:55 +00001730 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHSC)) {
Chris Lattner6e2c15c2006-11-09 05:12:27 +00001731 // X + (signbit) --> X ^ signbit
Chris Lattner92a68652006-02-07 08:05:22 +00001732 uint64_t Val = CI->getZExtValue();
Chris Lattner77defba2006-02-07 07:00:41 +00001733 if (Val == (1ULL << (CI->getType()->getPrimitiveSizeInBits()-1)))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001734 return BinaryOperator::createXor(LHS, RHS);
Chris Lattner6e2c15c2006-11-09 05:12:27 +00001735
1736 // See if SimplifyDemandedBits can simplify this. This handles stuff like
1737 // (X & 254)+1 -> (X&254)|1
1738 uint64_t KnownZero, KnownOne;
1739 if (!isa<PackedType>(I.getType()) &&
1740 SimplifyDemandedBits(&I, I.getType()->getIntegralTypeMask(),
1741 KnownZero, KnownOne))
1742 return &I;
Chris Lattnercf4a9962004-04-10 22:01:55 +00001743 }
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001744
1745 if (isa<PHINode>(LHS))
1746 if (Instruction *NV = FoldOpIntoPhi(I))
1747 return NV;
Chris Lattner0b3557f2005-09-24 23:43:33 +00001748
Chris Lattner330628a2006-01-06 17:59:59 +00001749 ConstantInt *XorRHS = 0;
1750 Value *XorLHS = 0;
Chris Lattner0b3557f2005-09-24 23:43:33 +00001751 if (match(LHS, m_Xor(m_Value(XorLHS), m_ConstantInt(XorRHS)))) {
1752 unsigned TySizeBits = I.getType()->getPrimitiveSizeInBits();
1753 int64_t RHSSExt = cast<ConstantInt>(RHSC)->getSExtValue();
1754 uint64_t RHSZExt = cast<ConstantInt>(RHSC)->getZExtValue();
1755
1756 uint64_t C0080Val = 1ULL << 31;
1757 int64_t CFF80Val = -C0080Val;
1758 unsigned Size = 32;
1759 do {
1760 if (TySizeBits > Size) {
1761 bool Found = false;
1762 // If we have ADD(XOR(AND(X, 0xFF), 0x80), 0xF..F80), it's a sext.
1763 // If we have ADD(XOR(AND(X, 0xFF), 0xF..F80), 0x80), it's a sext.
1764 if (RHSSExt == CFF80Val) {
1765 if (XorRHS->getZExtValue() == C0080Val)
1766 Found = true;
1767 } else if (RHSZExt == C0080Val) {
1768 if (XorRHS->getSExtValue() == CFF80Val)
1769 Found = true;
1770 }
1771 if (Found) {
1772 // This is a sign extend if the top bits are known zero.
Chris Lattner4534dd592006-02-09 07:38:58 +00001773 uint64_t Mask = ~0ULL;
Chris Lattnerc3ebf402006-02-07 07:27:52 +00001774 Mask <<= 64-(TySizeBits-Size);
Chris Lattner4534dd592006-02-09 07:38:58 +00001775 Mask &= XorLHS->getType()->getIntegralTypeMask();
Chris Lattnerc3ebf402006-02-07 07:27:52 +00001776 if (!MaskedValueIsZero(XorLHS, Mask))
Chris Lattner0b3557f2005-09-24 23:43:33 +00001777 Size = 0; // Not a sign ext, but can't be any others either.
1778 goto FoundSExt;
1779 }
1780 }
1781 Size >>= 1;
1782 C0080Val >>= Size;
1783 CFF80Val >>= Size;
1784 } while (Size >= 8);
1785
1786FoundSExt:
1787 const Type *MiddleType = 0;
1788 switch (Size) {
1789 default: break;
1790 case 32: MiddleType = Type::IntTy; break;
1791 case 16: MiddleType = Type::ShortTy; break;
1792 case 8: MiddleType = Type::SByteTy; break;
1793 }
1794 if (MiddleType) {
Reid Spencerbb65ebf2006-12-12 23:36:14 +00001795 Instruction *NewTrunc = new TruncInst(XorLHS, MiddleType, "sext");
Chris Lattner0b3557f2005-09-24 23:43:33 +00001796 InsertNewInstBefore(NewTrunc, I);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001797 return new SExtInst(NewTrunc, I.getType());
Chris Lattner0b3557f2005-09-24 23:43:33 +00001798 }
1799 }
Chris Lattnercf4a9962004-04-10 22:01:55 +00001800 }
Chris Lattner9fa53de2002-05-06 16:49:18 +00001801
Chris Lattnerb8b97502003-08-13 19:01:45 +00001802 // X + X --> X << 1
Robert Bocchino7b5b86c2004-07-27 21:02:21 +00001803 if (I.getType()->isInteger()) {
Chris Lattnerb8b97502003-08-13 19:01:45 +00001804 if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS))) return Result;
Chris Lattner47060462005-04-07 17:14:51 +00001805
1806 if (Instruction *RHSI = dyn_cast<Instruction>(RHS)) {
1807 if (RHSI->getOpcode() == Instruction::Sub)
1808 if (LHS == RHSI->getOperand(1)) // A + (B - A) --> B
1809 return ReplaceInstUsesWith(I, RHSI->getOperand(0));
1810 }
1811 if (Instruction *LHSI = dyn_cast<Instruction>(LHS)) {
1812 if (LHSI->getOpcode() == Instruction::Sub)
1813 if (RHS == LHSI->getOperand(1)) // (B - A) + A --> B
1814 return ReplaceInstUsesWith(I, LHSI->getOperand(0));
1815 }
Robert Bocchino7b5b86c2004-07-27 21:02:21 +00001816 }
Chris Lattnerede3fe02003-08-13 04:18:28 +00001817
Chris Lattner147e9752002-05-08 22:46:53 +00001818 // -A + B --> B - A
Chris Lattnerbb74e222003-03-10 23:06:50 +00001819 if (Value *V = dyn_castNegVal(LHS))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001820 return BinaryOperator::createSub(RHS, V);
Chris Lattner9fa53de2002-05-06 16:49:18 +00001821
1822 // A + -B --> A - B
Chris Lattnerbb74e222003-03-10 23:06:50 +00001823 if (!isa<Constant>(RHS))
1824 if (Value *V = dyn_castNegVal(RHS))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001825 return BinaryOperator::createSub(LHS, V);
Chris Lattner260ab202002-04-18 17:39:14 +00001826
Misha Brukmanb1c93172005-04-21 23:48:37 +00001827
Chris Lattner8c3e7b92004-11-13 19:50:12 +00001828 ConstantInt *C2;
1829 if (Value *X = dyn_castFoldableMul(LHS, C2)) {
1830 if (X == RHS) // X*C + X --> X * (C+1)
1831 return BinaryOperator::createMul(RHS, AddOne(C2));
1832
1833 // X*C1 + X*C2 --> X * (C1+C2)
1834 ConstantInt *C1;
1835 if (X == dyn_castFoldableMul(RHS, C1))
1836 return BinaryOperator::createMul(X, ConstantExpr::getAdd(C1, C2));
Chris Lattner57c8d992003-02-18 19:57:07 +00001837 }
1838
1839 // X + X*C --> X * (C+1)
Chris Lattner8c3e7b92004-11-13 19:50:12 +00001840 if (dyn_castFoldableMul(RHS, C2) == LHS)
1841 return BinaryOperator::createMul(LHS, AddOne(C2));
1842
Chris Lattner57c8d992003-02-18 19:57:07 +00001843
Chris Lattnerb8b97502003-08-13 19:01:45 +00001844 // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
Chris Lattnerd4252a72004-07-30 07:50:03 +00001845 if (match(RHS, m_And(m_Value(), m_ConstantInt(C2))))
Chris Lattnerb8b97502003-08-13 19:01:45 +00001846 if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2))) return R;
Chris Lattner7fb29e12003-03-11 00:12:48 +00001847
Chris Lattnerb9cde762003-10-02 15:11:26 +00001848 if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
Chris Lattner330628a2006-01-06 17:59:59 +00001849 Value *X = 0;
Chris Lattnerd4252a72004-07-30 07:50:03 +00001850 if (match(LHS, m_Not(m_Value(X)))) { // ~X + C --> (C-1) - X
1851 Constant *C= ConstantExpr::getSub(CRHS, ConstantInt::get(I.getType(), 1));
1852 return BinaryOperator::createSub(C, X);
Chris Lattnerb9cde762003-10-02 15:11:26 +00001853 }
Chris Lattnerd4252a72004-07-30 07:50:03 +00001854
Chris Lattnerbff91d92004-10-08 05:07:56 +00001855 // (X & FF00) + xx00 -> (X+xx00) & FF00
1856 if (LHS->hasOneUse() && match(LHS, m_And(m_Value(X), m_ConstantInt(C2)))) {
1857 Constant *Anded = ConstantExpr::getAnd(CRHS, C2);
1858 if (Anded == CRHS) {
1859 // See if all bits from the first bit set in the Add RHS up are included
1860 // in the mask. First, get the rightmost bit.
Reid Spencere0fc4df2006-10-20 07:07:24 +00001861 uint64_t AddRHSV = CRHS->getZExtValue();
Chris Lattnerbff91d92004-10-08 05:07:56 +00001862
1863 // Form a mask of all bits from the lowest bit added through the top.
1864 uint64_t AddRHSHighBits = ~((AddRHSV & -AddRHSV)-1);
Chris Lattner77defba2006-02-07 07:00:41 +00001865 AddRHSHighBits &= C2->getType()->getIntegralTypeMask();
Chris Lattnerbff91d92004-10-08 05:07:56 +00001866
1867 // See if the and mask includes all of these bits.
Reid Spencere0fc4df2006-10-20 07:07:24 +00001868 uint64_t AddRHSHighBitsAnd = AddRHSHighBits & C2->getZExtValue();
Misha Brukmanb1c93172005-04-21 23:48:37 +00001869
Chris Lattnerbff91d92004-10-08 05:07:56 +00001870 if (AddRHSHighBits == AddRHSHighBitsAnd) {
1871 // Okay, the xform is safe. Insert the new add pronto.
1872 Value *NewAdd = InsertNewInstBefore(BinaryOperator::createAdd(X, CRHS,
1873 LHS->getName()), I);
1874 return BinaryOperator::createAnd(NewAdd, C2);
1875 }
1876 }
1877 }
1878
Chris Lattnerd4252a72004-07-30 07:50:03 +00001879 // Try to fold constant add into select arguments.
1880 if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
Chris Lattner86102b82005-01-01 16:22:27 +00001881 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattnerd4252a72004-07-30 07:50:03 +00001882 return R;
Chris Lattnerb9cde762003-10-02 15:11:26 +00001883 }
1884
Reid Spencer7e80b0b2006-10-26 06:15:43 +00001885 // add (cast *A to intptrtype) B ->
1886 // cast (GEP (cast *A to sbyte*) B) ->
1887 // intptrtype
Andrew Lenharth4f339be2006-09-19 18:24:51 +00001888 {
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001889 CastInst *CI = dyn_cast<CastInst>(LHS);
1890 Value *Other = RHS;
Andrew Lenharth4f339be2006-09-19 18:24:51 +00001891 if (!CI) {
1892 CI = dyn_cast<CastInst>(RHS);
1893 Other = LHS;
1894 }
Andrew Lenharth44cb67a2006-09-20 15:37:57 +00001895 if (CI && CI->getType()->isSized() &&
1896 (CI->getType()->getPrimitiveSize() ==
1897 TD->getIntPtrType()->getPrimitiveSize())
1898 && isa<PointerType>(CI->getOperand(0)->getType())) {
Reid Spencer13bc5d72006-12-12 09:18:51 +00001899 Value *I2 = InsertCastBefore(Instruction::BitCast, CI->getOperand(0),
Andrew Lenharth44cb67a2006-09-20 15:37:57 +00001900 PointerType::get(Type::SByteTy), I);
1901 I2 = InsertNewInstBefore(new GetElementPtrInst(I2, Other, "ctg2"), I);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001902 return new PtrToIntInst(I2, CI->getType());
Andrew Lenharth4f339be2006-09-19 18:24:51 +00001903 }
1904 }
1905
Chris Lattner113f4f42002-06-25 16:13:24 +00001906 return Changed ? &I : 0;
Chris Lattner260ab202002-04-18 17:39:14 +00001907}
1908
Chris Lattnerbdb0ce02003-07-22 21:46:59 +00001909// isSignBit - Return true if the value represented by the constant only has the
1910// highest order bit set.
1911static bool isSignBit(ConstantInt *CI) {
Chris Lattnerd1f46d32005-04-24 06:59:08 +00001912 unsigned NumBits = CI->getType()->getPrimitiveSizeInBits();
Reid Spencere0fc4df2006-10-20 07:07:24 +00001913 return (CI->getZExtValue() & (~0ULL >> (64-NumBits))) == (1ULL << (NumBits-1));
Chris Lattnerbdb0ce02003-07-22 21:46:59 +00001914}
1915
Chris Lattner022167f2004-03-13 00:11:49 +00001916/// RemoveNoopCast - Strip off nonconverting casts from the value.
1917///
1918static Value *RemoveNoopCast(Value *V) {
1919 if (CastInst *CI = dyn_cast<CastInst>(V)) {
1920 const Type *CTy = CI->getType();
1921 const Type *OpTy = CI->getOperand(0)->getType();
1922 if (CTy->isInteger() && OpTy->isInteger()) {
Chris Lattnerd1f46d32005-04-24 06:59:08 +00001923 if (CTy->getPrimitiveSizeInBits() == OpTy->getPrimitiveSizeInBits())
Chris Lattner022167f2004-03-13 00:11:49 +00001924 return RemoveNoopCast(CI->getOperand(0));
1925 } else if (isa<PointerType>(CTy) && isa<PointerType>(OpTy))
1926 return RemoveNoopCast(CI->getOperand(0));
1927 }
1928 return V;
1929}
1930
Chris Lattner113f4f42002-06-25 16:13:24 +00001931Instruction *InstCombiner::visitSub(BinaryOperator &I) {
Chris Lattner113f4f42002-06-25 16:13:24 +00001932 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001933
Chris Lattnere6794492002-08-12 21:17:25 +00001934 if (Op0 == Op1) // sub X, X -> 0
1935 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner260ab202002-04-18 17:39:14 +00001936
Chris Lattnere6794492002-08-12 21:17:25 +00001937 // If this is a 'B = x-(-A)', change to B = x+A...
Chris Lattnerbb74e222003-03-10 23:06:50 +00001938 if (Value *V = dyn_castNegVal(Op1))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001939 return BinaryOperator::createAdd(Op0, V);
Chris Lattner9fa53de2002-05-06 16:49:18 +00001940
Chris Lattner81a7a232004-10-16 18:11:37 +00001941 if (isa<UndefValue>(Op0))
1942 return ReplaceInstUsesWith(I, Op0); // undef - X -> undef
1943 if (isa<UndefValue>(Op1))
1944 return ReplaceInstUsesWith(I, Op1); // X - undef -> undef
1945
Chris Lattner8f2f5982003-11-05 01:06:05 +00001946 if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
1947 // Replace (-1 - A) with (~A)...
Chris Lattner3082c5a2003-02-18 19:28:33 +00001948 if (C->isAllOnesValue())
1949 return BinaryOperator::createNot(Op1);
Chris Lattnerad3c4952002-05-09 01:29:19 +00001950
Chris Lattner8f2f5982003-11-05 01:06:05 +00001951 // C - ~X == X + (1+C)
Reid Spencer4fdd96c2005-06-18 17:37:34 +00001952 Value *X = 0;
Chris Lattnerd4252a72004-07-30 07:50:03 +00001953 if (match(Op1, m_Not(m_Value(X))))
1954 return BinaryOperator::createAdd(X,
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001955 ConstantExpr::getAdd(C, ConstantInt::get(I.getType(), 1)));
Chris Lattner92295c52004-03-12 23:53:13 +00001956 // -((uint)X >> 31) -> ((int)X >> 31)
1957 // -((int)X >> 31) -> ((uint)X >> 31)
Chris Lattner022167f2004-03-13 00:11:49 +00001958 if (C->isNullValue()) {
1959 Value *NoopCastedRHS = RemoveNoopCast(Op1);
1960 if (ShiftInst *SI = dyn_cast<ShiftInst>(NoopCastedRHS))
Reid Spencerfdff9382006-11-08 06:47:33 +00001961 if (SI->getOpcode() == Instruction::LShr) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00001962 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
Chris Lattner92295c52004-03-12 23:53:13 +00001963 // Check to see if we are shifting out everything but the sign bit.
Reid Spencere0fc4df2006-10-20 07:07:24 +00001964 if (CU->getZExtValue() ==
1965 SI->getType()->getPrimitiveSizeInBits()-1) {
Reid Spencerfdff9382006-11-08 06:47:33 +00001966 // Ok, the transformation is safe. Insert AShr.
1967 return new ShiftInst(Instruction::AShr, SI->getOperand(0),
1968 CU, SI->getName());
Chris Lattner92295c52004-03-12 23:53:13 +00001969 }
1970 }
Reid Spencerfdff9382006-11-08 06:47:33 +00001971 }
1972 else if (SI->getOpcode() == Instruction::AShr) {
1973 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
1974 // Check to see if we are shifting out everything but the sign bit.
1975 if (CU->getZExtValue() ==
1976 SI->getType()->getPrimitiveSizeInBits()-1) {
1977 // Ok, the transformation is safe. Insert LShr.
1978 return new ShiftInst(Instruction::LShr, SI->getOperand(0),
1979 CU, SI->getName());
1980 }
1981 }
1982 }
Chris Lattner022167f2004-03-13 00:11:49 +00001983 }
Chris Lattner183b3362004-04-09 19:05:30 +00001984
1985 // Try to fold constant sub into select arguments.
1986 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner86102b82005-01-01 16:22:27 +00001987 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00001988 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001989
1990 if (isa<PHINode>(Op0))
1991 if (Instruction *NV = FoldOpIntoPhi(I))
1992 return NV;
Chris Lattner8f2f5982003-11-05 01:06:05 +00001993 }
1994
Chris Lattnera9be4492005-04-07 16:15:25 +00001995 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
1996 if (Op1I->getOpcode() == Instruction::Add &&
Chris Lattner7a002fe2006-12-02 00:13:08 +00001997 !Op0->getType()->isFPOrFPVector()) {
Chris Lattnerc7f3c1a2005-04-07 16:28:01 +00001998 if (Op1I->getOperand(0) == Op0) // X-(X+Y) == -Y
Chris Lattnera9be4492005-04-07 16:15:25 +00001999 return BinaryOperator::createNeg(Op1I->getOperand(1), I.getName());
Chris Lattnerc7f3c1a2005-04-07 16:28:01 +00002000 else if (Op1I->getOperand(1) == Op0) // X-(Y+X) == -Y
Chris Lattnera9be4492005-04-07 16:15:25 +00002001 return BinaryOperator::createNeg(Op1I->getOperand(0), I.getName());
Chris Lattnerc7f3c1a2005-04-07 16:28:01 +00002002 else if (ConstantInt *CI1 = dyn_cast<ConstantInt>(I.getOperand(0))) {
2003 if (ConstantInt *CI2 = dyn_cast<ConstantInt>(Op1I->getOperand(1)))
2004 // C1-(X+C2) --> (C1-C2)-X
2005 return BinaryOperator::createSub(ConstantExpr::getSub(CI1, CI2),
2006 Op1I->getOperand(0));
2007 }
Chris Lattnera9be4492005-04-07 16:15:25 +00002008 }
2009
Chris Lattnerf95d9b92003-10-15 16:48:29 +00002010 if (Op1I->hasOneUse()) {
Chris Lattner3082c5a2003-02-18 19:28:33 +00002011 // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
2012 // is not used by anyone else...
2013 //
Chris Lattnerc2f0aa52004-02-02 20:09:56 +00002014 if (Op1I->getOpcode() == Instruction::Sub &&
Chris Lattner7a002fe2006-12-02 00:13:08 +00002015 !Op1I->getType()->isFPOrFPVector()) {
Chris Lattner3082c5a2003-02-18 19:28:33 +00002016 // Swap the two operands of the subexpr...
2017 Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
2018 Op1I->setOperand(0, IIOp1);
2019 Op1I->setOperand(1, IIOp0);
Misha Brukmanb1c93172005-04-21 23:48:37 +00002020
Chris Lattner3082c5a2003-02-18 19:28:33 +00002021 // Create the new top level add instruction...
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002022 return BinaryOperator::createAdd(Op0, Op1);
Chris Lattner3082c5a2003-02-18 19:28:33 +00002023 }
2024
2025 // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
2026 //
2027 if (Op1I->getOpcode() == Instruction::And &&
2028 (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
2029 Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
2030
Chris Lattner396dbfe2004-06-09 05:08:07 +00002031 Value *NewNot =
2032 InsertNewInstBefore(BinaryOperator::createNot(OtherOp, "B.not"), I);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002033 return BinaryOperator::createAnd(Op0, NewNot);
Chris Lattner3082c5a2003-02-18 19:28:33 +00002034 }
Chris Lattner57c8d992003-02-18 19:57:07 +00002035
Reid Spencer3c514952006-10-16 23:08:08 +00002036 // 0 - (X sdiv C) -> (X sdiv -C)
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002037 if (Op1I->getOpcode() == Instruction::SDiv)
Reid Spencere0fc4df2006-10-20 07:07:24 +00002038 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002039 if (CSI->isNullValue())
Chris Lattner0aee4b72004-10-06 15:08:25 +00002040 if (Constant *DivRHS = dyn_cast<Constant>(Op1I->getOperand(1)))
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002041 return BinaryOperator::createSDiv(Op1I->getOperand(0),
Chris Lattner0aee4b72004-10-06 15:08:25 +00002042 ConstantExpr::getNeg(DivRHS));
2043
Chris Lattner57c8d992003-02-18 19:57:07 +00002044 // X - X*C --> X * (1-C)
Reid Spencer4fdd96c2005-06-18 17:37:34 +00002045 ConstantInt *C2 = 0;
Chris Lattner8c3e7b92004-11-13 19:50:12 +00002046 if (dyn_castFoldableMul(Op1I, C2) == Op0) {
Misha Brukmanb1c93172005-04-21 23:48:37 +00002047 Constant *CP1 =
Chris Lattner8c3e7b92004-11-13 19:50:12 +00002048 ConstantExpr::getSub(ConstantInt::get(I.getType(), 1), C2);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002049 return BinaryOperator::createMul(Op0, CP1);
Chris Lattner57c8d992003-02-18 19:57:07 +00002050 }
Chris Lattnerad3c4952002-05-09 01:29:19 +00002051 }
Chris Lattnera9be4492005-04-07 16:15:25 +00002052 }
Chris Lattner3082c5a2003-02-18 19:28:33 +00002053
Chris Lattner7a002fe2006-12-02 00:13:08 +00002054 if (!Op0->getType()->isFPOrFPVector())
Chris Lattner47060462005-04-07 17:14:51 +00002055 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
2056 if (Op0I->getOpcode() == Instruction::Add) {
Chris Lattner411336f2005-01-19 21:50:18 +00002057 if (Op0I->getOperand(0) == Op1) // (Y+X)-Y == X
2058 return ReplaceInstUsesWith(I, Op0I->getOperand(1));
2059 else if (Op0I->getOperand(1) == Op1) // (X+Y)-Y == X
2060 return ReplaceInstUsesWith(I, Op0I->getOperand(0));
Chris Lattner47060462005-04-07 17:14:51 +00002061 } else if (Op0I->getOpcode() == Instruction::Sub) {
2062 if (Op0I->getOperand(0) == Op1) // (X-Y)-X == -Y
2063 return BinaryOperator::createNeg(Op0I->getOperand(1), I.getName());
Chris Lattner411336f2005-01-19 21:50:18 +00002064 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00002065
Chris Lattner8c3e7b92004-11-13 19:50:12 +00002066 ConstantInt *C1;
2067 if (Value *X = dyn_castFoldableMul(Op0, C1)) {
2068 if (X == Op1) { // X*C - X --> X * (C-1)
2069 Constant *CP1 = ConstantExpr::getSub(C1, ConstantInt::get(I.getType(),1));
2070 return BinaryOperator::createMul(Op1, CP1);
2071 }
Chris Lattner57c8d992003-02-18 19:57:07 +00002072
Chris Lattner8c3e7b92004-11-13 19:50:12 +00002073 ConstantInt *C2; // X*C1 - X*C2 -> X * (C1-C2)
2074 if (X == dyn_castFoldableMul(Op1, C2))
2075 return BinaryOperator::createMul(Op1, ConstantExpr::getSub(C1, C2));
2076 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002077 return 0;
Chris Lattner260ab202002-04-18 17:39:14 +00002078}
2079
Chris Lattnere79e8542004-02-23 06:38:22 +00002080/// isSignBitCheck - Given an exploded setcc instruction, return true if it is
2081/// really just returns true if the most significant (sign) bit is set.
2082static bool isSignBitCheck(unsigned Opcode, Value *LHS, ConstantInt *RHS) {
2083 if (RHS->getType()->isSigned()) {
2084 // True if source is LHS < 0 or LHS <= -1
2085 return Opcode == Instruction::SetLT && RHS->isNullValue() ||
2086 Opcode == Instruction::SetLE && RHS->isAllOnesValue();
2087 } else {
Reid Spencere0fc4df2006-10-20 07:07:24 +00002088 ConstantInt *RHSC = cast<ConstantInt>(RHS);
Chris Lattnere79e8542004-02-23 06:38:22 +00002089 // True if source is LHS > 127 or LHS >= 128, where the constants depend on
2090 // the size of the integer type.
2091 if (Opcode == Instruction::SetGE)
Reid Spencere0fc4df2006-10-20 07:07:24 +00002092 return RHSC->getZExtValue() ==
Chris Lattnerd1f46d32005-04-24 06:59:08 +00002093 1ULL << (RHS->getType()->getPrimitiveSizeInBits()-1);
Chris Lattnere79e8542004-02-23 06:38:22 +00002094 if (Opcode == Instruction::SetGT)
Reid Spencere0fc4df2006-10-20 07:07:24 +00002095 return RHSC->getZExtValue() ==
Chris Lattnerd1f46d32005-04-24 06:59:08 +00002096 (1ULL << (RHS->getType()->getPrimitiveSizeInBits()-1))-1;
Chris Lattnere79e8542004-02-23 06:38:22 +00002097 }
2098 return false;
2099}
2100
Chris Lattner113f4f42002-06-25 16:13:24 +00002101Instruction *InstCombiner::visitMul(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00002102 bool Changed = SimplifyCommutative(I);
Chris Lattner3082c5a2003-02-18 19:28:33 +00002103 Value *Op0 = I.getOperand(0);
Chris Lattner260ab202002-04-18 17:39:14 +00002104
Chris Lattner81a7a232004-10-16 18:11:37 +00002105 if (isa<UndefValue>(I.getOperand(1))) // undef * X -> 0
2106 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2107
Chris Lattnere6794492002-08-12 21:17:25 +00002108 // Simplify mul instructions with a constant RHS...
Chris Lattner3082c5a2003-02-18 19:28:33 +00002109 if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
2110 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Chris Lattnerede3fe02003-08-13 04:18:28 +00002111
2112 // ((X << C1)*C2) == (X * (C2 << C1))
2113 if (ShiftInst *SI = dyn_cast<ShiftInst>(Op0))
2114 if (SI->getOpcode() == Instruction::Shl)
2115 if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002116 return BinaryOperator::createMul(SI->getOperand(0),
2117 ConstantExpr::getShl(CI, ShOp));
Misha Brukmanb1c93172005-04-21 23:48:37 +00002118
Chris Lattnercce81be2003-09-11 22:24:54 +00002119 if (CI->isNullValue())
2120 return ReplaceInstUsesWith(I, Op1); // X * 0 == 0
2121 if (CI->equalsInt(1)) // X * 1 == X
2122 return ReplaceInstUsesWith(I, Op0);
2123 if (CI->isAllOnesValue()) // X * -1 == 0 - X
Chris Lattner35236d82003-06-25 17:09:20 +00002124 return BinaryOperator::createNeg(Op0, I.getName());
Chris Lattner31ba1292002-04-29 22:24:47 +00002125
Reid Spencere0fc4df2006-10-20 07:07:24 +00002126 int64_t Val = (int64_t)cast<ConstantInt>(CI)->getZExtValue();
Chris Lattner22d00a82005-08-02 19:16:58 +00002127 if (isPowerOf2_64(Val)) { // Replace X*(2^C) with X << C
2128 uint64_t C = Log2_64(Val);
Chris Lattner3082c5a2003-02-18 19:28:33 +00002129 return new ShiftInst(Instruction::Shl, Op0,
Reid Spencere0fc4df2006-10-20 07:07:24 +00002130 ConstantInt::get(Type::UByteTy, C));
Chris Lattner22d00a82005-08-02 19:16:58 +00002131 }
Robert Bocchino7b5b86c2004-07-27 21:02:21 +00002132 } else if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1)) {
Chris Lattner3082c5a2003-02-18 19:28:33 +00002133 if (Op1F->isNullValue())
2134 return ReplaceInstUsesWith(I, Op1);
Chris Lattner31ba1292002-04-29 22:24:47 +00002135
Chris Lattner3082c5a2003-02-18 19:28:33 +00002136 // "In IEEE floating point, x*1 is not equivalent to x for nans. However,
2137 // ANSI says we can drop signals, so we can do this anyway." (from GCC)
2138 if (Op1F->getValue() == 1.0)
2139 return ReplaceInstUsesWith(I, Op0); // Eliminate 'mul double %X, 1.0'
2140 }
Chris Lattner32c01df2006-03-04 06:04:02 +00002141
2142 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
2143 if (Op0I->getOpcode() == Instruction::Add && Op0I->hasOneUse() &&
2144 isa<ConstantInt>(Op0I->getOperand(1))) {
2145 // Canonicalize (X+C1)*C2 -> X*C2+C1*C2.
2146 Instruction *Add = BinaryOperator::createMul(Op0I->getOperand(0),
2147 Op1, "tmp");
2148 InsertNewInstBefore(Add, I);
2149 Value *C1C2 = ConstantExpr::getMul(Op1,
2150 cast<Constant>(Op0I->getOperand(1)));
2151 return BinaryOperator::createAdd(Add, C1C2);
2152
2153 }
Chris Lattner183b3362004-04-09 19:05:30 +00002154
2155 // Try to fold constant mul into select arguments.
2156 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner86102b82005-01-01 16:22:27 +00002157 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00002158 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00002159
2160 if (isa<PHINode>(Op0))
2161 if (Instruction *NV = FoldOpIntoPhi(I))
2162 return NV;
Chris Lattner260ab202002-04-18 17:39:14 +00002163 }
2164
Chris Lattner934a64cf2003-03-10 23:23:04 +00002165 if (Value *Op0v = dyn_castNegVal(Op0)) // -X * -Y = X*Y
2166 if (Value *Op1v = dyn_castNegVal(I.getOperand(1)))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002167 return BinaryOperator::createMul(Op0v, Op1v);
Chris Lattner934a64cf2003-03-10 23:23:04 +00002168
Chris Lattner2635b522004-02-23 05:39:21 +00002169 // If one of the operands of the multiply is a cast from a boolean value, then
2170 // we know the bool is either zero or one, so this is a 'masking' multiply.
2171 // See if we can simplify things based on how the boolean was originally
2172 // formed.
2173 CastInst *BoolCast = 0;
2174 if (CastInst *CI = dyn_cast<CastInst>(I.getOperand(0)))
2175 if (CI->getOperand(0)->getType() == Type::BoolTy)
2176 BoolCast = CI;
2177 if (!BoolCast)
2178 if (CastInst *CI = dyn_cast<CastInst>(I.getOperand(1)))
2179 if (CI->getOperand(0)->getType() == Type::BoolTy)
2180 BoolCast = CI;
2181 if (BoolCast) {
2182 if (SetCondInst *SCI = dyn_cast<SetCondInst>(BoolCast->getOperand(0))) {
2183 Value *SCIOp0 = SCI->getOperand(0), *SCIOp1 = SCI->getOperand(1);
2184 const Type *SCOpTy = SCIOp0->getType();
2185
Chris Lattnere79e8542004-02-23 06:38:22 +00002186 // If the setcc is true iff the sign bit of X is set, then convert this
2187 // multiply into a shift/and combination.
2188 if (isa<ConstantInt>(SCIOp1) &&
2189 isSignBitCheck(SCI->getOpcode(), SCIOp0, cast<ConstantInt>(SCIOp1))) {
Chris Lattner2635b522004-02-23 05:39:21 +00002190 // Shift the X value right to turn it into "all signbits".
Reid Spencere0fc4df2006-10-20 07:07:24 +00002191 Constant *Amt = ConstantInt::get(Type::UByteTy,
Chris Lattnerd1f46d32005-04-24 06:59:08 +00002192 SCOpTy->getPrimitiveSizeInBits()-1);
Chris Lattnere79e8542004-02-23 06:38:22 +00002193 if (SCIOp0->getType()->isUnsigned()) {
Chris Lattner97bfcea2004-06-17 18:16:02 +00002194 const Type *NewTy = SCIOp0->getType()->getSignedVersion();
Reid Spencer13bc5d72006-12-12 09:18:51 +00002195 SCIOp0 = InsertCastBefore(Instruction::BitCast, SCIOp0, NewTy, I);
Chris Lattnere79e8542004-02-23 06:38:22 +00002196 }
2197
2198 Value *V =
Reid Spencerfdff9382006-11-08 06:47:33 +00002199 InsertNewInstBefore(new ShiftInst(Instruction::AShr, SCIOp0, Amt,
Chris Lattnere79e8542004-02-23 06:38:22 +00002200 BoolCast->getOperand(0)->getName()+
2201 ".mask"), I);
Chris Lattner2635b522004-02-23 05:39:21 +00002202
2203 // If the multiply type is not the same as the source type, sign extend
2204 // or truncate to the multiply type.
Reid Spencer13bc5d72006-12-12 09:18:51 +00002205 if (I.getType() != V->getType()) {
2206 unsigned SrcBits = V->getType()->getPrimitiveSizeInBits();
2207 unsigned DstBits = I.getType()->getPrimitiveSizeInBits();
2208 Instruction::CastOps opcode =
2209 (SrcBits == DstBits ? Instruction::BitCast :
2210 (SrcBits < DstBits ? Instruction::SExt : Instruction::Trunc));
2211 V = InsertCastBefore(opcode, V, I.getType(), I);
2212 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00002213
Chris Lattner2635b522004-02-23 05:39:21 +00002214 Value *OtherOp = Op0 == BoolCast ? I.getOperand(1) : Op0;
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002215 return BinaryOperator::createAnd(V, OtherOp);
Chris Lattner2635b522004-02-23 05:39:21 +00002216 }
2217 }
2218 }
2219
Chris Lattner113f4f42002-06-25 16:13:24 +00002220 return Changed ? &I : 0;
Chris Lattner260ab202002-04-18 17:39:14 +00002221}
2222
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002223/// This function implements the transforms on div instructions that work
2224/// regardless of the kind of div instruction it is (udiv, sdiv, or fdiv). It is
2225/// used by the visitors to those instructions.
2226/// @brief Transforms common to all three div instructions
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002227Instruction *InstCombiner::commonDivTransforms(BinaryOperator &I) {
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00002228 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner81a7a232004-10-16 18:11:37 +00002229
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002230 // undef / X -> 0
2231 if (isa<UndefValue>(Op0))
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00002232 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002233
2234 // X / undef -> undef
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00002235 if (isa<UndefValue>(Op1))
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002236 return ReplaceInstUsesWith(I, Op1);
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00002237
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002238 // Handle cases involving: div X, (select Cond, Y, Z)
Chris Lattnerd79dc792006-09-09 20:26:32 +00002239 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
2240 // div X, (Cond ? 0 : Y) -> div X, Y. If the div and the select are in the
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002241 // same basic block, then we replace the select with Y, and the condition
2242 // of the select with false (if the cond value is in the same BB). If the
Chris Lattnerd79dc792006-09-09 20:26:32 +00002243 // select has uses other than the div, this allows them to be simplified
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002244 // also. Note that div X, Y is just as good as div X, 0 (undef)
Chris Lattnerd79dc792006-09-09 20:26:32 +00002245 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
2246 if (ST->isNullValue()) {
2247 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2248 if (CondI && CondI->getParent() == I.getParent())
Chris Lattner6ab03f62006-09-28 23:35:22 +00002249 UpdateValueUsesWith(CondI, ConstantBool::getFalse());
Chris Lattnerd79dc792006-09-09 20:26:32 +00002250 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2251 I.setOperand(1, SI->getOperand(2));
2252 else
2253 UpdateValueUsesWith(SI, SI->getOperand(2));
2254 return &I;
2255 }
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002256
Chris Lattnerd79dc792006-09-09 20:26:32 +00002257 // Likewise for: div X, (Cond ? Y : 0) -> div X, Y
2258 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
2259 if (ST->isNullValue()) {
2260 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2261 if (CondI && CondI->getParent() == I.getParent())
Chris Lattner6ab03f62006-09-28 23:35:22 +00002262 UpdateValueUsesWith(CondI, ConstantBool::getTrue());
Chris Lattnerd79dc792006-09-09 20:26:32 +00002263 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2264 I.setOperand(1, SI->getOperand(1));
2265 else
2266 UpdateValueUsesWith(SI, SI->getOperand(1));
2267 return &I;
2268 }
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002269 }
Chris Lattnerd79dc792006-09-09 20:26:32 +00002270
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002271 return 0;
2272}
Misha Brukmanb1c93172005-04-21 23:48:37 +00002273
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002274/// This function implements the transforms common to both integer division
2275/// instructions (udiv and sdiv). It is called by the visitors to those integer
2276/// division instructions.
2277/// @brief Common integer divide transforms
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002278Instruction *InstCombiner::commonIDivTransforms(BinaryOperator &I) {
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002279 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2280
2281 if (Instruction *Common = commonDivTransforms(I))
2282 return Common;
2283
2284 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2285 // div X, 1 == X
2286 if (RHS->equalsInt(1))
2287 return ReplaceInstUsesWith(I, Op0);
2288
2289 // (X / C1) / C2 -> X / (C1*C2)
2290 if (Instruction *LHS = dyn_cast<Instruction>(Op0))
2291 if (Instruction::BinaryOps(LHS->getOpcode()) == I.getOpcode())
2292 if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
2293 return BinaryOperator::create(I.getOpcode(), LHS->getOperand(0),
2294 ConstantExpr::getMul(RHS, LHSRHS));
Chris Lattner42362612005-04-08 04:03:26 +00002295 }
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002296
2297 if (!RHS->isNullValue()) { // avoid X udiv 0
2298 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2299 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2300 return R;
2301 if (isa<PHINode>(Op0))
2302 if (Instruction *NV = FoldOpIntoPhi(I))
2303 return NV;
2304 }
Chris Lattnerd79dc792006-09-09 20:26:32 +00002305 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00002306
Chris Lattner3082c5a2003-02-18 19:28:33 +00002307 // 0 / X == 0, we don't need to preserve faults!
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00002308 if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
Chris Lattner3082c5a2003-02-18 19:28:33 +00002309 if (LHS->equalsInt(0))
2310 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2311
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002312 return 0;
2313}
2314
2315Instruction *InstCombiner::visitUDiv(BinaryOperator &I) {
2316 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2317
2318 // Handle the integer div common cases
2319 if (Instruction *Common = commonIDivTransforms(I))
2320 return Common;
2321
2322 // X udiv C^2 -> X >> C
2323 // Check to see if this is an unsigned division with an exact power of 2,
2324 // if so, convert to a right shift.
2325 if (ConstantInt *C = dyn_cast<ConstantInt>(Op1)) {
2326 if (uint64_t Val = C->getZExtValue()) // Don't break X / 0
2327 if (isPowerOf2_64(Val)) {
2328 uint64_t ShiftAmt = Log2_64(Val);
Reid Spencerfdff9382006-11-08 06:47:33 +00002329 return new ShiftInst(Instruction::LShr, Op0,
2330 ConstantInt::get(Type::UByteTy, ShiftAmt));
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002331 }
2332 }
2333
2334 // X udiv (C1 << N), where C1 is "1<<C2" --> X >> (N+C2)
2335 if (ShiftInst *RHSI = dyn_cast<ShiftInst>(I.getOperand(1))) {
2336 if (RHSI->getOpcode() == Instruction::Shl &&
2337 isa<ConstantInt>(RHSI->getOperand(0))) {
2338 uint64_t C1 = cast<ConstantInt>(RHSI->getOperand(0))->getZExtValue();
2339 if (isPowerOf2_64(C1)) {
2340 Value *N = RHSI->getOperand(1);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002341 const Type *NTy = N->getType();
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002342 if (uint64_t C2 = Log2_64(C1)) {
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002343 Constant *C2V = ConstantInt::get(NTy, C2);
2344 N = InsertNewInstBefore(BinaryOperator::createAdd(N, C2V, "tmp"), I);
Chris Lattner2e90b732006-02-05 07:54:04 +00002345 }
Reid Spencerfdff9382006-11-08 06:47:33 +00002346 return new ShiftInst(Instruction::LShr, Op0, N);
Chris Lattner2e90b732006-02-05 07:54:04 +00002347 }
2348 }
Chris Lattnerdd0c1742005-11-05 07:40:31 +00002349 }
2350
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002351 // udiv X, (Select Cond, C1, C2) --> Select Cond, (shr X, C1), (shr X, C2)
2352 // where C1&C2 are powers of two.
2353 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
2354 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
2355 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2)))
2356 if (!STO->isNullValue() && !STO->isNullValue()) {
2357 uint64_t TVA = STO->getZExtValue(), FVA = SFO->getZExtValue();
2358 if (isPowerOf2_64(TVA) && isPowerOf2_64(FVA)) {
2359 // Compute the shift amounts
2360 unsigned TSA = Log2_64(TVA), FSA = Log2_64(FVA);
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002361 // Construct the "on true" case of the select
2362 Constant *TC = ConstantInt::get(Type::UByteTy, TSA);
2363 Instruction *TSI =
Reid Spencerfdff9382006-11-08 06:47:33 +00002364 new ShiftInst(Instruction::LShr, Op0, TC, SI->getName()+".t");
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002365 TSI = InsertNewInstBefore(TSI, I);
2366
2367 // Construct the "on false" case of the select
2368 Constant *FC = ConstantInt::get(Type::UByteTy, FSA);
2369 Instruction *FSI =
Reid Spencerfdff9382006-11-08 06:47:33 +00002370 new ShiftInst(Instruction::LShr, Op0, FC, SI->getName()+".f");
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002371 FSI = InsertNewInstBefore(FSI, I);
2372
2373 // construct the select instruction and return it.
Reid Spencerfdff9382006-11-08 06:47:33 +00002374 return new SelectInst(SI->getOperand(0), TSI, FSI, SI->getName());
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002375 }
2376 }
2377 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002378 return 0;
2379}
2380
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002381Instruction *InstCombiner::visitSDiv(BinaryOperator &I) {
2382 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2383
2384 // Handle the integer div common cases
2385 if (Instruction *Common = commonIDivTransforms(I))
2386 return Common;
2387
2388 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2389 // sdiv X, -1 == -X
2390 if (RHS->isAllOnesValue())
2391 return BinaryOperator::createNeg(Op0);
2392
2393 // -X/C -> X/-C
2394 if (Value *LHSNeg = dyn_castNegVal(Op0))
2395 return BinaryOperator::createSDiv(LHSNeg, ConstantExpr::getNeg(RHS));
2396 }
2397
2398 // If the sign bits of both operands are zero (i.e. we can prove they are
2399 // unsigned inputs), turn this into a udiv.
2400 if (I.getType()->isInteger()) {
2401 uint64_t Mask = 1ULL << (I.getType()->getPrimitiveSizeInBits()-1);
2402 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
2403 return BinaryOperator::createUDiv(Op0, Op1, I.getName());
2404 }
2405 }
2406
2407 return 0;
2408}
2409
2410Instruction *InstCombiner::visitFDiv(BinaryOperator &I) {
2411 return commonDivTransforms(I);
2412}
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002413
Chris Lattner85dda9a2006-03-02 06:50:58 +00002414/// GetFactor - If we can prove that the specified value is at least a multiple
2415/// of some factor, return that factor.
2416static Constant *GetFactor(Value *V) {
2417 if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
2418 return CI;
2419
2420 // Unless we can be tricky, we know this is a multiple of 1.
2421 Constant *Result = ConstantInt::get(V->getType(), 1);
2422
2423 Instruction *I = dyn_cast<Instruction>(V);
2424 if (!I) return Result;
2425
2426 if (I->getOpcode() == Instruction::Mul) {
2427 // Handle multiplies by a constant, etc.
2428 return ConstantExpr::getMul(GetFactor(I->getOperand(0)),
2429 GetFactor(I->getOperand(1)));
2430 } else if (I->getOpcode() == Instruction::Shl) {
2431 // (X<<C) -> X * (1 << C)
2432 if (Constant *ShRHS = dyn_cast<Constant>(I->getOperand(1))) {
2433 ShRHS = ConstantExpr::getShl(Result, ShRHS);
2434 return ConstantExpr::getMul(GetFactor(I->getOperand(0)), ShRHS);
2435 }
2436 } else if (I->getOpcode() == Instruction::And) {
2437 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
2438 // X & 0xFFF0 is known to be a multiple of 16.
2439 unsigned Zeros = CountTrailingZeros_64(RHS->getZExtValue());
2440 if (Zeros != V->getType()->getPrimitiveSizeInBits())
2441 return ConstantExpr::getShl(Result,
Reid Spencere0fc4df2006-10-20 07:07:24 +00002442 ConstantInt::get(Type::UByteTy, Zeros));
Chris Lattner85dda9a2006-03-02 06:50:58 +00002443 }
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002444 } else if (CastInst *CI = dyn_cast<CastInst>(I)) {
Chris Lattner85dda9a2006-03-02 06:50:58 +00002445 // Only handle int->int casts.
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002446 if (!CI->isIntegerCast())
2447 return Result;
2448 Value *Op = CI->getOperand(0);
2449 return ConstantExpr::getCast(CI->getOpcode(), GetFactor(Op), V->getType());
Chris Lattner85dda9a2006-03-02 06:50:58 +00002450 }
2451 return Result;
2452}
2453
Reid Spencer7eb55b32006-11-02 01:53:59 +00002454/// This function implements the transforms on rem instructions that work
2455/// regardless of the kind of rem instruction it is (urem, srem, or frem). It
2456/// is used by the visitors to those instructions.
2457/// @brief Transforms common to all three rem instructions
2458Instruction *InstCombiner::commonRemTransforms(BinaryOperator &I) {
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00002459 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Reid Spencer7eb55b32006-11-02 01:53:59 +00002460
Chris Lattner0de4a8d2006-02-28 05:30:45 +00002461 // 0 % X == 0, we don't need to preserve faults!
2462 if (Constant *LHS = dyn_cast<Constant>(Op0))
2463 if (LHS->isNullValue())
2464 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2465
2466 if (isa<UndefValue>(Op0)) // undef % X -> 0
2467 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2468 if (isa<UndefValue>(Op1))
2469 return ReplaceInstUsesWith(I, Op1); // X % undef -> undef
Reid Spencer7eb55b32006-11-02 01:53:59 +00002470
2471 // Handle cases involving: rem X, (select Cond, Y, Z)
2472 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
2473 // rem X, (Cond ? 0 : Y) -> rem X, Y. If the rem and the select are in
2474 // the same basic block, then we replace the select with Y, and the
2475 // condition of the select with false (if the cond value is in the same
2476 // BB). If the select has uses other than the div, this allows them to be
2477 // simplified also.
2478 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
2479 if (ST->isNullValue()) {
2480 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2481 if (CondI && CondI->getParent() == I.getParent())
2482 UpdateValueUsesWith(CondI, ConstantBool::getFalse());
2483 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2484 I.setOperand(1, SI->getOperand(2));
2485 else
2486 UpdateValueUsesWith(SI, SI->getOperand(2));
Chris Lattner7fd5f072004-07-06 07:01:22 +00002487 return &I;
2488 }
Reid Spencer7eb55b32006-11-02 01:53:59 +00002489 // Likewise for: rem X, (Cond ? Y : 0) -> rem X, Y
2490 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
2491 if (ST->isNullValue()) {
2492 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2493 if (CondI && CondI->getParent() == I.getParent())
2494 UpdateValueUsesWith(CondI, ConstantBool::getTrue());
2495 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2496 I.setOperand(1, SI->getOperand(1));
2497 else
2498 UpdateValueUsesWith(SI, SI->getOperand(1));
2499 return &I;
2500 }
Chris Lattnere9ff0ea2005-11-05 07:28:37 +00002501 }
Chris Lattner7fd5f072004-07-06 07:01:22 +00002502
Reid Spencer7eb55b32006-11-02 01:53:59 +00002503 return 0;
2504}
2505
2506/// This function implements the transforms common to both integer remainder
2507/// instructions (urem and srem). It is called by the visitors to those integer
2508/// remainder instructions.
2509/// @brief Common integer remainder transforms
2510Instruction *InstCombiner::commonIRemTransforms(BinaryOperator &I) {
2511 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2512
2513 if (Instruction *common = commonRemTransforms(I))
2514 return common;
2515
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00002516 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner0de4a8d2006-02-28 05:30:45 +00002517 // X % 0 == undef, we don't need to preserve faults!
2518 if (RHS->equalsInt(0))
2519 return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
2520
Chris Lattner3082c5a2003-02-18 19:28:33 +00002521 if (RHS->equalsInt(1)) // X % 1 == 0
2522 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2523
Chris Lattnerb70f1412006-02-28 05:49:21 +00002524 if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
2525 if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
2526 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2527 return R;
2528 } else if (isa<PHINode>(Op0I)) {
2529 if (Instruction *NV = FoldOpIntoPhi(I))
2530 return NV;
Chris Lattnerb70f1412006-02-28 05:49:21 +00002531 }
Reid Spencer7eb55b32006-11-02 01:53:59 +00002532 // (X * C1) % C2 --> 0 iff C1 % C2 == 0
2533 if (ConstantExpr::getSRem(GetFactor(Op0I), RHS)->isNullValue())
Chris Lattner85dda9a2006-03-02 06:50:58 +00002534 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerb70f1412006-02-28 05:49:21 +00002535 }
Chris Lattner3082c5a2003-02-18 19:28:33 +00002536 }
2537
Reid Spencer7eb55b32006-11-02 01:53:59 +00002538 return 0;
2539}
2540
2541Instruction *InstCombiner::visitURem(BinaryOperator &I) {
2542 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2543
2544 if (Instruction *common = commonIRemTransforms(I))
2545 return common;
2546
2547 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2548 // X urem C^2 -> X and C
2549 // Check to see if this is an unsigned remainder with an exact power of 2,
2550 // if so, convert to a bitwise and.
2551 if (ConstantInt *C = dyn_cast<ConstantInt>(RHS))
2552 if (isPowerOf2_64(C->getZExtValue()))
2553 return BinaryOperator::createAnd(Op0, SubOne(C));
2554 }
2555
Chris Lattner2e90b732006-02-05 07:54:04 +00002556 if (Instruction *RHSI = dyn_cast<Instruction>(I.getOperand(1))) {
Reid Spencer7eb55b32006-11-02 01:53:59 +00002557 // Turn A % (C << N), where C is 2^k, into A & ((C << N)-1)
2558 if (RHSI->getOpcode() == Instruction::Shl &&
2559 isa<ConstantInt>(RHSI->getOperand(0))) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00002560 unsigned C1 = cast<ConstantInt>(RHSI->getOperand(0))->getZExtValue();
Chris Lattner2e90b732006-02-05 07:54:04 +00002561 if (isPowerOf2_64(C1)) {
2562 Constant *N1 = ConstantInt::getAllOnesValue(I.getType());
2563 Value *Add = InsertNewInstBefore(BinaryOperator::createAdd(RHSI, N1,
2564 "tmp"), I);
2565 return BinaryOperator::createAnd(Op0, Add);
2566 }
2567 }
Reid Spencer7eb55b32006-11-02 01:53:59 +00002568 }
Chris Lattnerd79dc792006-09-09 20:26:32 +00002569
Reid Spencer7eb55b32006-11-02 01:53:59 +00002570 // urem X, (select Cond, 2^C1, 2^C2) --> select Cond, (and X, C1), (and X, C2)
2571 // where C1&C2 are powers of two.
2572 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
2573 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
2574 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
2575 // STO == 0 and SFO == 0 handled above.
2576 if (isPowerOf2_64(STO->getZExtValue()) &&
2577 isPowerOf2_64(SFO->getZExtValue())) {
2578 Value *TrueAnd = InsertNewInstBefore(
2579 BinaryOperator::createAnd(Op0, SubOne(STO), SI->getName()+".t"), I);
2580 Value *FalseAnd = InsertNewInstBefore(
2581 BinaryOperator::createAnd(Op0, SubOne(SFO), SI->getName()+".f"), I);
2582 return new SelectInst(SI->getOperand(0), TrueAnd, FalseAnd);
2583 }
2584 }
Chris Lattner2e90b732006-02-05 07:54:04 +00002585 }
2586
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002587 return 0;
2588}
2589
Reid Spencer7eb55b32006-11-02 01:53:59 +00002590Instruction *InstCombiner::visitSRem(BinaryOperator &I) {
2591 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2592
2593 if (Instruction *common = commonIRemTransforms(I))
2594 return common;
2595
2596 if (Value *RHSNeg = dyn_castNegVal(Op1))
2597 if (!isa<ConstantInt>(RHSNeg) ||
2598 cast<ConstantInt>(RHSNeg)->getSExtValue() > 0) {
2599 // X % -Y -> X % Y
2600 AddUsesToWorkList(I);
2601 I.setOperand(1, RHSNeg);
2602 return &I;
2603 }
2604
2605 // If the top bits of both operands are zero (i.e. we can prove they are
2606 // unsigned inputs), turn this into a urem.
2607 uint64_t Mask = 1ULL << (I.getType()->getPrimitiveSizeInBits()-1);
2608 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
2609 // X srem Y -> X urem Y, iff X and Y don't have sign bit set
2610 return BinaryOperator::createURem(Op0, Op1, I.getName());
2611 }
2612
2613 return 0;
2614}
2615
2616Instruction *InstCombiner::visitFRem(BinaryOperator &I) {
Reid Spencer7eb55b32006-11-02 01:53:59 +00002617 return commonRemTransforms(I);
2618}
2619
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002620// isMaxValueMinusOne - return true if this is Max-1
Chris Lattnere6794492002-08-12 21:17:25 +00002621static bool isMaxValueMinusOne(const ConstantInt *C) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00002622 if (C->getType()->isUnsigned())
2623 return C->getZExtValue() == C->getType()->getIntegralTypeMask()-1;
Misha Brukmanb1c93172005-04-21 23:48:37 +00002624
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002625 // Calculate 0111111111..11111
Chris Lattnerd1f46d32005-04-24 06:59:08 +00002626 unsigned TypeBits = C->getType()->getPrimitiveSizeInBits();
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002627 int64_t Val = INT64_MAX; // All ones
2628 Val >>= 64-TypeBits; // Shift out unwanted 1 bits...
Reid Spencere0fc4df2006-10-20 07:07:24 +00002629 return C->getSExtValue() == Val-1;
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002630}
2631
2632// isMinValuePlusOne - return true if this is Min+1
Chris Lattnere6794492002-08-12 21:17:25 +00002633static bool isMinValuePlusOne(const ConstantInt *C) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00002634 if (C->getType()->isUnsigned())
2635 return C->getZExtValue() == 1;
Misha Brukmanb1c93172005-04-21 23:48:37 +00002636
2637 // Calculate 1111111111000000000000
Chris Lattnerd1f46d32005-04-24 06:59:08 +00002638 unsigned TypeBits = C->getType()->getPrimitiveSizeInBits();
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002639 int64_t Val = -1; // All ones
2640 Val <<= TypeBits-1; // Shift over to the right spot
Reid Spencere0fc4df2006-10-20 07:07:24 +00002641 return C->getSExtValue() == Val+1;
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002642}
2643
Chris Lattner35167c32004-06-09 07:59:58 +00002644// isOneBitSet - Return true if there is exactly one bit set in the specified
2645// constant.
2646static bool isOneBitSet(const ConstantInt *CI) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00002647 uint64_t V = CI->getZExtValue();
Chris Lattner35167c32004-06-09 07:59:58 +00002648 return V && (V & (V-1)) == 0;
2649}
2650
Chris Lattner8fc5af42004-09-23 21:46:38 +00002651#if 0 // Currently unused
2652// isLowOnes - Return true if the constant is of the form 0+1+.
2653static bool isLowOnes(const ConstantInt *CI) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00002654 uint64_t V = CI->getZExtValue();
Chris Lattner8fc5af42004-09-23 21:46:38 +00002655
2656 // There won't be bits set in parts that the type doesn't contain.
Reid Spencere0fc4df2006-10-20 07:07:24 +00002657 V &= ConstantInt::getAllOnesValue(CI->getType())->getZExtValue();
Chris Lattner8fc5af42004-09-23 21:46:38 +00002658
2659 uint64_t U = V+1; // If it is low ones, this should be a power of two.
2660 return U && V && (U & V) == 0;
2661}
2662#endif
2663
2664// isHighOnes - Return true if the constant is of the form 1+0+.
2665// This is the same as lowones(~X).
2666static bool isHighOnes(const ConstantInt *CI) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00002667 uint64_t V = ~CI->getZExtValue();
Chris Lattner2c14cf72005-08-07 07:03:10 +00002668 if (~V == 0) return false; // 0's does not match "1+"
Chris Lattner8fc5af42004-09-23 21:46:38 +00002669
2670 // There won't be bits set in parts that the type doesn't contain.
Reid Spencere0fc4df2006-10-20 07:07:24 +00002671 V &= ConstantInt::getAllOnesValue(CI->getType())->getZExtValue();
Chris Lattner8fc5af42004-09-23 21:46:38 +00002672
2673 uint64_t U = V+1; // If it is low ones, this should be a power of two.
2674 return U && V && (U & V) == 0;
2675}
2676
2677
Chris Lattner3ac7c262003-08-13 20:16:26 +00002678/// getSetCondCode - Encode a setcc opcode into a three bit mask. These bits
2679/// are carefully arranged to allow folding of expressions such as:
2680///
2681/// (A < B) | (A > B) --> (A != B)
2682///
2683/// Bit value '4' represents that the comparison is true if A > B, bit value '2'
2684/// represents that the comparison is true if A == B, and bit value '1' is true
2685/// if A < B.
2686///
2687static unsigned getSetCondCode(const SetCondInst *SCI) {
2688 switch (SCI->getOpcode()) {
2689 // False -> 0
2690 case Instruction::SetGT: return 1;
2691 case Instruction::SetEQ: return 2;
2692 case Instruction::SetGE: return 3;
2693 case Instruction::SetLT: return 4;
2694 case Instruction::SetNE: return 5;
2695 case Instruction::SetLE: return 6;
2696 // True -> 7
2697 default:
2698 assert(0 && "Invalid SetCC opcode!");
2699 return 0;
2700 }
2701}
2702
2703/// getSetCCValue - This is the complement of getSetCondCode, which turns an
2704/// opcode and two operands into either a constant true or false, or a brand new
2705/// SetCC instruction.
2706static Value *getSetCCValue(unsigned Opcode, Value *LHS, Value *RHS) {
2707 switch (Opcode) {
Chris Lattner6ab03f62006-09-28 23:35:22 +00002708 case 0: return ConstantBool::getFalse();
Chris Lattner3ac7c262003-08-13 20:16:26 +00002709 case 1: return new SetCondInst(Instruction::SetGT, LHS, RHS);
2710 case 2: return new SetCondInst(Instruction::SetEQ, LHS, RHS);
2711 case 3: return new SetCondInst(Instruction::SetGE, LHS, RHS);
2712 case 4: return new SetCondInst(Instruction::SetLT, LHS, RHS);
2713 case 5: return new SetCondInst(Instruction::SetNE, LHS, RHS);
2714 case 6: return new SetCondInst(Instruction::SetLE, LHS, RHS);
Chris Lattner6ab03f62006-09-28 23:35:22 +00002715 case 7: return ConstantBool::getTrue();
Chris Lattner3ac7c262003-08-13 20:16:26 +00002716 default: assert(0 && "Illegal SetCCCode!"); return 0;
2717 }
2718}
2719
2720// FoldSetCCLogical - Implements (setcc1 A, B) & (setcc2 A, B) --> (setcc3 A, B)
Chris Lattnere3a63d12006-11-15 04:53:24 +00002721namespace {
Chris Lattner3ac7c262003-08-13 20:16:26 +00002722struct FoldSetCCLogical {
2723 InstCombiner &IC;
2724 Value *LHS, *RHS;
2725 FoldSetCCLogical(InstCombiner &ic, SetCondInst *SCI)
2726 : IC(ic), LHS(SCI->getOperand(0)), RHS(SCI->getOperand(1)) {}
2727 bool shouldApply(Value *V) const {
2728 if (SetCondInst *SCI = dyn_cast<SetCondInst>(V))
2729 return (SCI->getOperand(0) == LHS && SCI->getOperand(1) == RHS ||
2730 SCI->getOperand(0) == RHS && SCI->getOperand(1) == LHS);
2731 return false;
2732 }
2733 Instruction *apply(BinaryOperator &Log) const {
2734 SetCondInst *SCI = cast<SetCondInst>(Log.getOperand(0));
2735 if (SCI->getOperand(0) != LHS) {
2736 assert(SCI->getOperand(1) == LHS);
2737 SCI->swapOperands(); // Swap the LHS and RHS of the SetCC
2738 }
2739
2740 unsigned LHSCode = getSetCondCode(SCI);
2741 unsigned RHSCode = getSetCondCode(cast<SetCondInst>(Log.getOperand(1)));
2742 unsigned Code;
2743 switch (Log.getOpcode()) {
2744 case Instruction::And: Code = LHSCode & RHSCode; break;
2745 case Instruction::Or: Code = LHSCode | RHSCode; break;
2746 case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
Chris Lattner2caaaba2003-09-22 20:33:34 +00002747 default: assert(0 && "Illegal logical opcode!"); return 0;
Chris Lattner3ac7c262003-08-13 20:16:26 +00002748 }
2749
2750 Value *RV = getSetCCValue(Code, LHS, RHS);
2751 if (Instruction *I = dyn_cast<Instruction>(RV))
2752 return I;
2753 // Otherwise, it's a constant boolean value...
2754 return IC.ReplaceInstUsesWith(Log, RV);
2755 }
2756};
Chris Lattnere3a63d12006-11-15 04:53:24 +00002757} // end anonymous namespace
Chris Lattner3ac7c262003-08-13 20:16:26 +00002758
Chris Lattnerba1cb382003-09-19 17:17:26 +00002759// OptAndOp - This handles expressions of the form ((val OP C1) & C2). Where
2760// the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'. Op is
2761// guaranteed to be either a shift instruction or a binary operator.
2762Instruction *InstCombiner::OptAndOp(Instruction *Op,
2763 ConstantIntegral *OpRHS,
2764 ConstantIntegral *AndRHS,
2765 BinaryOperator &TheAnd) {
2766 Value *X = Op->getOperand(0);
Chris Lattnerfcf21a72004-01-12 19:47:05 +00002767 Constant *Together = 0;
2768 if (!isa<ShiftInst>(Op))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002769 Together = ConstantExpr::getAnd(AndRHS, OpRHS);
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00002770
Chris Lattnerba1cb382003-09-19 17:17:26 +00002771 switch (Op->getOpcode()) {
2772 case Instruction::Xor:
Chris Lattner86102b82005-01-01 16:22:27 +00002773 if (Op->hasOneUse()) {
Chris Lattnerba1cb382003-09-19 17:17:26 +00002774 // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
2775 std::string OpName = Op->getName(); Op->setName("");
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002776 Instruction *And = BinaryOperator::createAnd(X, AndRHS, OpName);
Chris Lattnerba1cb382003-09-19 17:17:26 +00002777 InsertNewInstBefore(And, TheAnd);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002778 return BinaryOperator::createXor(And, Together);
Chris Lattnerba1cb382003-09-19 17:17:26 +00002779 }
2780 break;
2781 case Instruction::Or:
Chris Lattner86102b82005-01-01 16:22:27 +00002782 if (Together == AndRHS) // (X | C) & C --> C
2783 return ReplaceInstUsesWith(TheAnd, AndRHS);
Misha Brukmanb1c93172005-04-21 23:48:37 +00002784
Chris Lattner86102b82005-01-01 16:22:27 +00002785 if (Op->hasOneUse() && Together != OpRHS) {
2786 // (X | C1) & C2 --> (X | (C1&C2)) & C2
2787 std::string Op0Name = Op->getName(); Op->setName("");
2788 Instruction *Or = BinaryOperator::createOr(X, Together, Op0Name);
2789 InsertNewInstBefore(Or, TheAnd);
2790 return BinaryOperator::createAnd(Or, AndRHS);
Chris Lattnerba1cb382003-09-19 17:17:26 +00002791 }
2792 break;
2793 case Instruction::Add:
Chris Lattnerf95d9b92003-10-15 16:48:29 +00002794 if (Op->hasOneUse()) {
Chris Lattnerba1cb382003-09-19 17:17:26 +00002795 // Adding a one to a single bit bit-field should be turned into an XOR
2796 // of the bit. First thing to check is to see if this AND is with a
2797 // single bit constant.
Reid Spencere0fc4df2006-10-20 07:07:24 +00002798 uint64_t AndRHSV = cast<ConstantInt>(AndRHS)->getZExtValue();
Chris Lattnerba1cb382003-09-19 17:17:26 +00002799
2800 // Clear bits that are not part of the constant.
Chris Lattner77defba2006-02-07 07:00:41 +00002801 AndRHSV &= AndRHS->getType()->getIntegralTypeMask();
Chris Lattnerba1cb382003-09-19 17:17:26 +00002802
2803 // If there is only one bit set...
Chris Lattner35167c32004-06-09 07:59:58 +00002804 if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
Chris Lattnerba1cb382003-09-19 17:17:26 +00002805 // Ok, at this point, we know that we are masking the result of the
2806 // ADD down to exactly one bit. If the constant we are adding has
2807 // no bits set below this bit, then we can eliminate the ADD.
Reid Spencere0fc4df2006-10-20 07:07:24 +00002808 uint64_t AddRHS = cast<ConstantInt>(OpRHS)->getZExtValue();
Misha Brukmanb1c93172005-04-21 23:48:37 +00002809
Chris Lattnerba1cb382003-09-19 17:17:26 +00002810 // Check to see if any bits below the one bit set in AndRHSV are set.
2811 if ((AddRHS & (AndRHSV-1)) == 0) {
2812 // If not, the only thing that can effect the output of the AND is
2813 // the bit specified by AndRHSV. If that bit is set, the effect of
2814 // the XOR is to toggle the bit. If it is clear, then the ADD has
2815 // no effect.
2816 if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
2817 TheAnd.setOperand(0, X);
2818 return &TheAnd;
2819 } else {
2820 std::string Name = Op->getName(); Op->setName("");
2821 // Pull the XOR out of the AND.
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002822 Instruction *NewAnd = BinaryOperator::createAnd(X, AndRHS, Name);
Chris Lattnerba1cb382003-09-19 17:17:26 +00002823 InsertNewInstBefore(NewAnd, TheAnd);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002824 return BinaryOperator::createXor(NewAnd, AndRHS);
Chris Lattnerba1cb382003-09-19 17:17:26 +00002825 }
2826 }
2827 }
2828 }
2829 break;
Chris Lattner2da29172003-09-19 19:05:02 +00002830
2831 case Instruction::Shl: {
2832 // We know that the AND will not produce any of the bits shifted in, so if
2833 // the anded constant includes them, clear them now!
2834 //
2835 Constant *AllOne = ConstantIntegral::getAllOnesValue(AndRHS->getType());
Chris Lattner7e794272004-09-24 15:21:34 +00002836 Constant *ShlMask = ConstantExpr::getShl(AllOne, OpRHS);
2837 Constant *CI = ConstantExpr::getAnd(AndRHS, ShlMask);
Misha Brukmanb1c93172005-04-21 23:48:37 +00002838
Chris Lattner7e794272004-09-24 15:21:34 +00002839 if (CI == ShlMask) { // Masking out bits that the shift already masks
2840 return ReplaceInstUsesWith(TheAnd, Op); // No need for the and.
2841 } else if (CI != AndRHS) { // Reducing bits set in and.
Chris Lattner2da29172003-09-19 19:05:02 +00002842 TheAnd.setOperand(1, CI);
2843 return &TheAnd;
2844 }
2845 break;
Misha Brukmanb1c93172005-04-21 23:48:37 +00002846 }
Reid Spencerfdff9382006-11-08 06:47:33 +00002847 case Instruction::LShr:
2848 {
Chris Lattner2da29172003-09-19 19:05:02 +00002849 // We know that the AND will not produce any of the bits shifted in, so if
2850 // the anded constant includes them, clear them now! This only applies to
2851 // unsigned shifts, because a signed shr may bring in set bits!
2852 //
Reid Spencerfdff9382006-11-08 06:47:33 +00002853 Constant *AllOne = ConstantIntegral::getAllOnesValue(AndRHS->getType());
2854 Constant *ShrMask = ConstantExpr::getLShr(AllOne, OpRHS);
2855 Constant *CI = ConstantExpr::getAnd(AndRHS, ShrMask);
Chris Lattner7e794272004-09-24 15:21:34 +00002856
Reid Spencerfdff9382006-11-08 06:47:33 +00002857 if (CI == ShrMask) { // Masking out bits that the shift already masks.
2858 return ReplaceInstUsesWith(TheAnd, Op);
2859 } else if (CI != AndRHS) {
2860 TheAnd.setOperand(1, CI); // Reduce bits set in and cst.
2861 return &TheAnd;
2862 }
2863 break;
2864 }
2865 case Instruction::AShr:
2866 // Signed shr.
2867 // See if this is shifting in some sign extension, then masking it out
2868 // with an and.
2869 if (Op->hasOneUse()) {
2870 Constant *AllOne = ConstantIntegral::getAllOnesValue(AndRHS->getType());
2871 Constant *ShrMask = ConstantExpr::getLShr(AllOne, OpRHS);
2872 Constant *CI = ConstantExpr::getAnd(AndRHS, ShrMask);
2873 if (CI == AndRHS) { // Masking out bits shifted in.
Reid Spencer13bc5d72006-12-12 09:18:51 +00002874 // (Val ashr C1) & C2 -> (Val lshr C1) & C2
Reid Spencerfdff9382006-11-08 06:47:33 +00002875 // Make the argument unsigned.
2876 Value *ShVal = Op->getOperand(0);
2877 ShVal = InsertNewInstBefore(new ShiftInst(Instruction::LShr, ShVal,
2878 OpRHS, Op->getName()),
2879 TheAnd);
Reid Spencer13bc5d72006-12-12 09:18:51 +00002880 Value *AndRHS2 = ConstantExpr::getBitCast(AndRHS, ShVal->getType());
2881
Reid Spencerfdff9382006-11-08 06:47:33 +00002882 return BinaryOperator::createAnd(ShVal, AndRHS2, TheAnd.getName());
Chris Lattner7e794272004-09-24 15:21:34 +00002883 }
Chris Lattner2da29172003-09-19 19:05:02 +00002884 }
2885 break;
Chris Lattnerba1cb382003-09-19 17:17:26 +00002886 }
2887 return 0;
2888}
2889
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002890
Chris Lattner6862fbd2004-09-29 17:40:11 +00002891/// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
2892/// true, otherwise (V < Lo || V >= Hi). In pratice, we emit the more efficient
2893/// (V-Lo) <u Hi-Lo. This method expects that Lo <= Hi. IB is the location to
2894/// insert new instructions.
2895Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
2896 bool Inside, Instruction &IB) {
2897 assert(cast<ConstantBool>(ConstantExpr::getSetLE(Lo, Hi))->getValue() &&
2898 "Lo is not <= Hi in range emission code!");
2899 if (Inside) {
2900 if (Lo == Hi) // Trivially false.
2901 return new SetCondInst(Instruction::SetNE, V, V);
Reid Spencer4ae56f32006-12-06 20:39:57 +00002902 if (cast<ConstantIntegral>(Lo)->isMinValue(Lo->getType()->isSigned()))
Chris Lattner6862fbd2004-09-29 17:40:11 +00002903 return new SetCondInst(Instruction::SetLT, V, Hi);
Misha Brukmanb1c93172005-04-21 23:48:37 +00002904
Chris Lattner6862fbd2004-09-29 17:40:11 +00002905 Constant *AddCST = ConstantExpr::getNeg(Lo);
2906 Instruction *Add = BinaryOperator::createAdd(V, AddCST,V->getName()+".off");
2907 InsertNewInstBefore(Add, IB);
2908 // Convert to unsigned for the comparison.
2909 const Type *UnsType = Add->getType()->getUnsignedVersion();
Reid Spencer13bc5d72006-12-12 09:18:51 +00002910 Value *OffsetVal = InsertCastBefore(Instruction::BitCast, Add, UnsType, IB);
Chris Lattner6862fbd2004-09-29 17:40:11 +00002911 AddCST = ConstantExpr::getAdd(AddCST, Hi);
Reid Spencer13bc5d72006-12-12 09:18:51 +00002912 AddCST = ConstantExpr::getBitCast(AddCST, UnsType);
Chris Lattner6862fbd2004-09-29 17:40:11 +00002913 return new SetCondInst(Instruction::SetLT, OffsetVal, AddCST);
2914 }
2915
2916 if (Lo == Hi) // Trivially true.
2917 return new SetCondInst(Instruction::SetEQ, V, V);
2918
2919 Hi = SubOne(cast<ConstantInt>(Hi));
Reid Spencere0fc4df2006-10-20 07:07:24 +00002920
2921 // V < 0 || V >= Hi ->'V > Hi-1'
Reid Spencer4ae56f32006-12-06 20:39:57 +00002922 if (cast<ConstantIntegral>(Lo)->isMinValue(Lo->getType()->isSigned()))
Chris Lattner6862fbd2004-09-29 17:40:11 +00002923 return new SetCondInst(Instruction::SetGT, V, Hi);
2924
2925 // Emit X-Lo > Hi-Lo-1
2926 Constant *AddCST = ConstantExpr::getNeg(Lo);
2927 Instruction *Add = BinaryOperator::createAdd(V, AddCST, V->getName()+".off");
2928 InsertNewInstBefore(Add, IB);
2929 // Convert to unsigned for the comparison.
2930 const Type *UnsType = Add->getType()->getUnsignedVersion();
Reid Spencer13bc5d72006-12-12 09:18:51 +00002931 Value *OffsetVal = InsertCastBefore(Instruction::BitCast, Add, UnsType, IB);
Chris Lattner6862fbd2004-09-29 17:40:11 +00002932 AddCST = ConstantExpr::getAdd(AddCST, Hi);
Reid Spencer13bc5d72006-12-12 09:18:51 +00002933 AddCST = ConstantExpr::getBitCast(AddCST, UnsType);
Chris Lattner6862fbd2004-09-29 17:40:11 +00002934 return new SetCondInst(Instruction::SetGT, OffsetVal, AddCST);
2935}
2936
Chris Lattnerb4b25302005-09-18 07:22:02 +00002937// isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
2938// any number of 0s on either side. The 1s are allowed to wrap from LSB to
2939// MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs. 0x0F0F0000 is
2940// not, since all 1s are not contiguous.
2941static bool isRunOfOnes(ConstantIntegral *Val, unsigned &MB, unsigned &ME) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00002942 uint64_t V = Val->getZExtValue();
Chris Lattnerb4b25302005-09-18 07:22:02 +00002943 if (!isShiftedMask_64(V)) return false;
2944
2945 // look for the first zero bit after the run of ones
2946 MB = 64-CountLeadingZeros_64((V - 1) ^ V);
2947 // look for the first non-zero bit
2948 ME = 64-CountLeadingZeros_64(V);
2949 return true;
2950}
2951
2952
2953
2954/// FoldLogicalPlusAnd - This is part of an expression (LHS +/- RHS) & Mask,
2955/// where isSub determines whether the operator is a sub. If we can fold one of
2956/// the following xforms:
Chris Lattneraf517572005-09-18 04:24:45 +00002957///
2958/// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
2959/// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
2960/// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
2961///
2962/// return (A +/- B).
2963///
2964Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
2965 ConstantIntegral *Mask, bool isSub,
2966 Instruction &I) {
2967 Instruction *LHSI = dyn_cast<Instruction>(LHS);
2968 if (!LHSI || LHSI->getNumOperands() != 2 ||
2969 !isa<ConstantInt>(LHSI->getOperand(1))) return 0;
2970
2971 ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
2972
2973 switch (LHSI->getOpcode()) {
2974 default: return 0;
2975 case Instruction::And:
Chris Lattnerb4b25302005-09-18 07:22:02 +00002976 if (ConstantExpr::getAnd(N, Mask) == Mask) {
2977 // If the AndRHS is a power of two minus one (0+1+), this is simple.
Reid Spencere0fc4df2006-10-20 07:07:24 +00002978 if ((Mask->getZExtValue() & Mask->getZExtValue()+1) == 0)
Chris Lattnerb4b25302005-09-18 07:22:02 +00002979 break;
2980
2981 // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
2982 // part, we don't need any explicit masks to take them out of A. If that
2983 // is all N is, ignore it.
2984 unsigned MB, ME;
2985 if (isRunOfOnes(Mask, MB, ME)) { // begin/end bit of run, inclusive
Chris Lattnerc3ebf402006-02-07 07:27:52 +00002986 uint64_t Mask = RHS->getType()->getIntegralTypeMask();
2987 Mask >>= 64-MB+1;
2988 if (MaskedValueIsZero(RHS, Mask))
Chris Lattnerb4b25302005-09-18 07:22:02 +00002989 break;
2990 }
2991 }
Chris Lattneraf517572005-09-18 04:24:45 +00002992 return 0;
2993 case Instruction::Or:
2994 case Instruction::Xor:
Chris Lattnerb4b25302005-09-18 07:22:02 +00002995 // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
Reid Spencere0fc4df2006-10-20 07:07:24 +00002996 if ((Mask->getZExtValue() & Mask->getZExtValue()+1) == 0 &&
Chris Lattnerb4b25302005-09-18 07:22:02 +00002997 ConstantExpr::getAnd(N, Mask)->isNullValue())
Chris Lattneraf517572005-09-18 04:24:45 +00002998 break;
2999 return 0;
3000 }
3001
3002 Instruction *New;
3003 if (isSub)
3004 New = BinaryOperator::createSub(LHSI->getOperand(0), RHS, "fold");
3005 else
3006 New = BinaryOperator::createAdd(LHSI->getOperand(0), RHS, "fold");
3007 return InsertNewInstBefore(New, I);
3008}
3009
Chris Lattner113f4f42002-06-25 16:13:24 +00003010Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00003011 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00003012 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003013
Chris Lattner81a7a232004-10-16 18:11:37 +00003014 if (isa<UndefValue>(Op1)) // X & undef -> 0
3015 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3016
Chris Lattner86102b82005-01-01 16:22:27 +00003017 // and X, X = X
3018 if (Op0 == Op1)
Chris Lattnere6794492002-08-12 21:17:25 +00003019 return ReplaceInstUsesWith(I, Op1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003020
Chris Lattner5b2edb12006-02-12 08:02:11 +00003021 // See if we can simplify any instructions used by the instruction whose sole
Chris Lattner5997cf92006-02-08 03:25:32 +00003022 // purpose is to compute bits we don't care about.
Chris Lattner0157e7f2006-02-11 09:31:47 +00003023 uint64_t KnownZero, KnownOne;
Chris Lattnerd70d9f52006-03-25 21:58:26 +00003024 if (!isa<PackedType>(I.getType()) &&
3025 SimplifyDemandedBits(&I, I.getType()->getIntegralTypeMask(),
Chris Lattner0157e7f2006-02-11 09:31:47 +00003026 KnownZero, KnownOne))
Chris Lattner5997cf92006-02-08 03:25:32 +00003027 return &I;
3028
Chris Lattner86102b82005-01-01 16:22:27 +00003029 if (ConstantIntegral *AndRHS = dyn_cast<ConstantIntegral>(Op1)) {
Chris Lattnerab2dc4d2006-02-08 07:34:50 +00003030 uint64_t AndRHSMask = AndRHS->getZExtValue();
3031 uint64_t TypeMask = Op0->getType()->getIntegralTypeMask();
Chris Lattnerab2dc4d2006-02-08 07:34:50 +00003032 uint64_t NotAndRHS = AndRHSMask^TypeMask;
Chris Lattner86102b82005-01-01 16:22:27 +00003033
Chris Lattnerba1cb382003-09-19 17:17:26 +00003034 // Optimize a variety of ((val OP C1) & C2) combinations...
3035 if (isa<BinaryOperator>(Op0) || isa<ShiftInst>(Op0)) {
3036 Instruction *Op0I = cast<Instruction>(Op0);
Chris Lattner86102b82005-01-01 16:22:27 +00003037 Value *Op0LHS = Op0I->getOperand(0);
3038 Value *Op0RHS = Op0I->getOperand(1);
3039 switch (Op0I->getOpcode()) {
3040 case Instruction::Xor:
3041 case Instruction::Or:
Chris Lattner9e2c7fa2005-01-23 20:26:55 +00003042 // If the mask is only needed on one incoming arm, push it up.
3043 if (Op0I->hasOneUse()) {
3044 if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
3045 // Not masking anything out for the LHS, move to RHS.
3046 Instruction *NewRHS = BinaryOperator::createAnd(Op0RHS, AndRHS,
3047 Op0RHS->getName()+".masked");
3048 InsertNewInstBefore(NewRHS, I);
3049 return BinaryOperator::create(
3050 cast<BinaryOperator>(Op0I)->getOpcode(), Op0LHS, NewRHS);
Misha Brukmanb1c93172005-04-21 23:48:37 +00003051 }
Chris Lattnerc3ebf402006-02-07 07:27:52 +00003052 if (!isa<Constant>(Op0RHS) &&
Chris Lattner9e2c7fa2005-01-23 20:26:55 +00003053 MaskedValueIsZero(Op0RHS, NotAndRHS)) {
3054 // Not masking anything out for the RHS, move to LHS.
3055 Instruction *NewLHS = BinaryOperator::createAnd(Op0LHS, AndRHS,
3056 Op0LHS->getName()+".masked");
3057 InsertNewInstBefore(NewLHS, I);
3058 return BinaryOperator::create(
3059 cast<BinaryOperator>(Op0I)->getOpcode(), NewLHS, Op0RHS);
3060 }
3061 }
3062
Chris Lattner86102b82005-01-01 16:22:27 +00003063 break;
Chris Lattneraf517572005-09-18 04:24:45 +00003064 case Instruction::Add:
Chris Lattnerb4b25302005-09-18 07:22:02 +00003065 // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
3066 // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
3067 // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
3068 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
3069 return BinaryOperator::createAnd(V, AndRHS);
3070 if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
3071 return BinaryOperator::createAnd(V, AndRHS); // Add commutes
Chris Lattneraf517572005-09-18 04:24:45 +00003072 break;
3073
3074 case Instruction::Sub:
Chris Lattnerb4b25302005-09-18 07:22:02 +00003075 // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
3076 // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
3077 // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
3078 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
3079 return BinaryOperator::createAnd(V, AndRHS);
Chris Lattneraf517572005-09-18 04:24:45 +00003080 break;
Chris Lattner86102b82005-01-01 16:22:27 +00003081 }
3082
Chris Lattner16464b32003-07-23 19:25:52 +00003083 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
Chris Lattner86102b82005-01-01 16:22:27 +00003084 if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
Chris Lattnerba1cb382003-09-19 17:17:26 +00003085 return Res;
Chris Lattner86102b82005-01-01 16:22:27 +00003086 } else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
Chris Lattner2c14cf72005-08-07 07:03:10 +00003087 // If this is an integer truncation or change from signed-to-unsigned, and
3088 // if the source is an and/or with immediate, transform it. This
3089 // frequently occurs for bitfield accesses.
3090 if (Instruction *CastOp = dyn_cast<Instruction>(CI->getOperand(0))) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +00003091 if ((isa<TruncInst>(CI) || isa<BitCastInst>(CI)) &&
Chris Lattner2c14cf72005-08-07 07:03:10 +00003092 CastOp->getNumOperands() == 2)
Chris Lattnerab2dc4d2006-02-08 07:34:50 +00003093 if (ConstantInt *AndCI = dyn_cast<ConstantInt>(CastOp->getOperand(1)))
Chris Lattner2c14cf72005-08-07 07:03:10 +00003094 if (CastOp->getOpcode() == Instruction::And) {
3095 // Change: and (cast (and X, C1) to T), C2
Reid Spencer6c38f0b2006-11-27 01:05:10 +00003096 // into : and (cast X to T), trunc_or_bitcast(C1)&C2
3097 // This will fold the two constants together, which may allow
3098 // other simplifications.
Reid Spencerbb65ebf2006-12-12 23:36:14 +00003099 Instruction *NewCast = CastInst::createTruncOrBitCast(
3100 CastOp->getOperand(0), I.getType(),
3101 CastOp->getName()+".shrunk");
Chris Lattner2c14cf72005-08-07 07:03:10 +00003102 NewCast = InsertNewInstBefore(NewCast, I);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00003103 // trunc_or_bitcast(C1)&C2
Reid Spencerbb65ebf2006-12-12 23:36:14 +00003104 Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
Reid Spencer6c38f0b2006-11-27 01:05:10 +00003105 C3 = ConstantExpr::getAnd(C3, AndRHS);
Chris Lattner2c14cf72005-08-07 07:03:10 +00003106 return BinaryOperator::createAnd(NewCast, C3);
3107 } else if (CastOp->getOpcode() == Instruction::Or) {
3108 // Change: and (cast (or X, C1) to T), C2
3109 // into : trunc(C1)&C2 iff trunc(C1)&C2 == C2
Chris Lattner2dc148e2006-12-12 19:11:20 +00003110 Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
Chris Lattner2c14cf72005-08-07 07:03:10 +00003111 if (ConstantExpr::getAnd(C3, AndRHS) == AndRHS) // trunc(C1)&C2
3112 return ReplaceInstUsesWith(I, AndRHS);
3113 }
3114 }
Chris Lattner33217db2003-07-23 19:36:21 +00003115 }
Chris Lattner183b3362004-04-09 19:05:30 +00003116
3117 // Try to fold constant and into select arguments.
3118 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner86102b82005-01-01 16:22:27 +00003119 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00003120 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00003121 if (isa<PHINode>(Op0))
3122 if (Instruction *NV = FoldOpIntoPhi(I))
3123 return NV;
Chris Lattner49b47ae2003-07-23 17:57:01 +00003124 }
3125
Chris Lattnerbb74e222003-03-10 23:06:50 +00003126 Value *Op0NotVal = dyn_castNotVal(Op0);
3127 Value *Op1NotVal = dyn_castNotVal(Op1);
Chris Lattner3082c5a2003-02-18 19:28:33 +00003128
Chris Lattner023a4832004-06-18 06:07:51 +00003129 if (Op0NotVal == Op1 || Op1NotVal == Op0) // A & ~A == ~A & A == 0
3130 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3131
Misha Brukman9c003d82004-07-30 12:50:08 +00003132 // (~A & ~B) == (~(A | B)) - De Morgan's Law
Chris Lattnerbb74e222003-03-10 23:06:50 +00003133 if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003134 Instruction *Or = BinaryOperator::createOr(Op0NotVal, Op1NotVal,
3135 I.getName()+".demorgan");
Chris Lattner49b47ae2003-07-23 17:57:01 +00003136 InsertNewInstBefore(Or, I);
Chris Lattner3082c5a2003-02-18 19:28:33 +00003137 return BinaryOperator::createNot(Or);
3138 }
Chris Lattner8b10ab32006-02-13 23:07:23 +00003139
3140 {
3141 Value *A = 0, *B = 0;
Chris Lattner8b10ab32006-02-13 23:07:23 +00003142 if (match(Op0, m_Or(m_Value(A), m_Value(B))))
3143 if (A == Op1 || B == Op1) // (A | ?) & A --> A
3144 return ReplaceInstUsesWith(I, Op1);
3145 if (match(Op1, m_Or(m_Value(A), m_Value(B))))
3146 if (A == Op0 || B == Op0) // A & (A | ?) --> A
3147 return ReplaceInstUsesWith(I, Op0);
Chris Lattnerdcd07922006-04-01 08:03:55 +00003148
3149 if (Op0->hasOneUse() &&
3150 match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
3151 if (A == Op1) { // (A^B)&A -> A&(A^B)
3152 I.swapOperands(); // Simplify below
3153 std::swap(Op0, Op1);
3154 } else if (B == Op1) { // (A^B)&B -> B&(B^A)
3155 cast<BinaryOperator>(Op0)->swapOperands();
3156 I.swapOperands(); // Simplify below
3157 std::swap(Op0, Op1);
3158 }
3159 }
3160 if (Op1->hasOneUse() &&
3161 match(Op1, m_Xor(m_Value(A), m_Value(B)))) {
3162 if (B == Op0) { // B&(A^B) -> B&(B^A)
3163 cast<BinaryOperator>(Op1)->swapOperands();
3164 std::swap(A, B);
3165 }
3166 if (A == Op0) { // A&(A^B) -> A & ~B
3167 Instruction *NotB = BinaryOperator::createNot(B, "tmp");
3168 InsertNewInstBefore(NotB, I);
3169 return BinaryOperator::createAnd(A, NotB);
3170 }
3171 }
Chris Lattner8b10ab32006-02-13 23:07:23 +00003172 }
3173
Chris Lattner3082c5a2003-02-18 19:28:33 +00003174
Chris Lattner623826c2004-09-28 21:48:02 +00003175 if (SetCondInst *RHS = dyn_cast<SetCondInst>(Op1)) {
3176 // (setcc1 A, B) & (setcc2 A, B) --> (setcc3 A, B)
Chris Lattner3ac7c262003-08-13 20:16:26 +00003177 if (Instruction *R = AssociativeOpt(I, FoldSetCCLogical(*this, RHS)))
3178 return R;
3179
Chris Lattner623826c2004-09-28 21:48:02 +00003180 Value *LHSVal, *RHSVal;
3181 ConstantInt *LHSCst, *RHSCst;
3182 Instruction::BinaryOps LHSCC, RHSCC;
3183 if (match(Op0, m_SetCond(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
3184 if (match(RHS, m_SetCond(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
3185 if (LHSVal == RHSVal && // Found (X setcc C1) & (X setcc C2)
3186 // Set[GL]E X, CST is folded to Set[GL]T elsewhere.
Misha Brukmanb1c93172005-04-21 23:48:37 +00003187 LHSCC != Instruction::SetGE && LHSCC != Instruction::SetLE &&
Chris Lattner623826c2004-09-28 21:48:02 +00003188 RHSCC != Instruction::SetGE && RHSCC != Instruction::SetLE) {
3189 // Ensure that the larger constant is on the RHS.
3190 Constant *Cmp = ConstantExpr::getSetGT(LHSCst, RHSCst);
3191 SetCondInst *LHS = cast<SetCondInst>(Op0);
3192 if (cast<ConstantBool>(Cmp)->getValue()) {
3193 std::swap(LHS, RHS);
3194 std::swap(LHSCst, RHSCst);
3195 std::swap(LHSCC, RHSCC);
3196 }
3197
3198 // At this point, we know we have have two setcc instructions
3199 // comparing a value against two constants and and'ing the result
3200 // together. Because of the above check, we know that we only have
3201 // SetEQ, SetNE, SetLT, and SetGT here. We also know (from the
3202 // FoldSetCCLogical check above), that the two constants are not
3203 // equal.
3204 assert(LHSCst != RHSCst && "Compares not folded above?");
3205
3206 switch (LHSCC) {
3207 default: assert(0 && "Unknown integer condition code!");
3208 case Instruction::SetEQ:
3209 switch (RHSCC) {
3210 default: assert(0 && "Unknown integer condition code!");
3211 case Instruction::SetEQ: // (X == 13 & X == 15) -> false
3212 case Instruction::SetGT: // (X == 13 & X > 15) -> false
Chris Lattner6ab03f62006-09-28 23:35:22 +00003213 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
Chris Lattner623826c2004-09-28 21:48:02 +00003214 case Instruction::SetNE: // (X == 13 & X != 15) -> X == 13
3215 case Instruction::SetLT: // (X == 13 & X < 15) -> X == 13
3216 return ReplaceInstUsesWith(I, LHS);
3217 }
3218 case Instruction::SetNE:
3219 switch (RHSCC) {
3220 default: assert(0 && "Unknown integer condition code!");
3221 case Instruction::SetLT:
3222 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X < 14) -> X < 13
3223 return new SetCondInst(Instruction::SetLT, LHSVal, LHSCst);
3224 break; // (X != 13 & X < 15) -> no change
3225 case Instruction::SetEQ: // (X != 13 & X == 15) -> X == 15
3226 case Instruction::SetGT: // (X != 13 & X > 15) -> X > 15
3227 return ReplaceInstUsesWith(I, RHS);
3228 case Instruction::SetNE:
3229 if (LHSCst == SubOne(RHSCst)) {// (X != 13 & X != 14) -> X-13 >u 1
3230 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
3231 Instruction *Add = BinaryOperator::createAdd(LHSVal, AddCST,
3232 LHSVal->getName()+".off");
3233 InsertNewInstBefore(Add, I);
3234 const Type *UnsType = Add->getType()->getUnsignedVersion();
Reid Spencer13bc5d72006-12-12 09:18:51 +00003235 Value *OffsetVal = InsertCastBefore(Instruction::BitCast, Add,
3236 UnsType, I);
Chris Lattner623826c2004-09-28 21:48:02 +00003237 AddCST = ConstantExpr::getSub(RHSCst, LHSCst);
Reid Spencer13bc5d72006-12-12 09:18:51 +00003238 AddCST = ConstantExpr::getBitCast(AddCST, UnsType);
Chris Lattner623826c2004-09-28 21:48:02 +00003239 return new SetCondInst(Instruction::SetGT, OffsetVal, AddCST);
3240 }
3241 break; // (X != 13 & X != 15) -> no change
3242 }
3243 break;
3244 case Instruction::SetLT:
3245 switch (RHSCC) {
3246 default: assert(0 && "Unknown integer condition code!");
3247 case Instruction::SetEQ: // (X < 13 & X == 15) -> false
3248 case Instruction::SetGT: // (X < 13 & X > 15) -> false
Chris Lattner6ab03f62006-09-28 23:35:22 +00003249 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
Chris Lattner623826c2004-09-28 21:48:02 +00003250 case Instruction::SetNE: // (X < 13 & X != 15) -> X < 13
3251 case Instruction::SetLT: // (X < 13 & X < 15) -> X < 13
3252 return ReplaceInstUsesWith(I, LHS);
3253 }
3254 case Instruction::SetGT:
3255 switch (RHSCC) {
3256 default: assert(0 && "Unknown integer condition code!");
3257 case Instruction::SetEQ: // (X > 13 & X == 15) -> X > 13
3258 return ReplaceInstUsesWith(I, LHS);
3259 case Instruction::SetGT: // (X > 13 & X > 15) -> X > 15
3260 return ReplaceInstUsesWith(I, RHS);
3261 case Instruction::SetNE:
3262 if (RHSCst == AddOne(LHSCst)) // (X > 13 & X != 14) -> X > 14
3263 return new SetCondInst(Instruction::SetGT, LHSVal, RHSCst);
3264 break; // (X > 13 & X != 15) -> no change
Chris Lattner6862fbd2004-09-29 17:40:11 +00003265 case Instruction::SetLT: // (X > 13 & X < 15) -> (X-14) <u 1
3266 return InsertRangeTest(LHSVal, AddOne(LHSCst), RHSCst, true, I);
Chris Lattner623826c2004-09-28 21:48:02 +00003267 }
3268 }
3269 }
3270 }
3271
Chris Lattner3af10532006-05-05 06:39:07 +00003272 // fold (and (cast A), (cast B)) -> (cast (and A, B))
Reid Spencer799b5bf2006-12-13 08:27:15 +00003273 if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
3274 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
3275 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind ?
3276 const Type *SrcTy = Op0C->getOperand(0)->getType();
3277 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isIntegral() &&
3278 // Only do this if the casts both really cause code to be generated.
3279 ValueRequiresCast(Op0C->getOperand(0), I.getType(), TD) &&
3280 ValueRequiresCast(Op1C->getOperand(0), I.getType(), TD)) {
3281 Instruction *NewOp = BinaryOperator::createAnd(Op0C->getOperand(0),
3282 Op1C->getOperand(0),
3283 I.getName());
3284 InsertNewInstBefore(NewOp, I);
3285 return CastInst::create(Op0C->getOpcode(), NewOp, I.getType());
3286 }
Chris Lattner3af10532006-05-05 06:39:07 +00003287 }
Chris Lattnerf05d69a2006-11-14 07:46:50 +00003288
3289 // (X >> Z) & (Y >> Z) -> (X&Y) >> Z for all shifts.
3290 if (ShiftInst *SI1 = dyn_cast<ShiftInst>(Op1)) {
3291 if (ShiftInst *SI0 = dyn_cast<ShiftInst>(Op0))
3292 if (SI0->getOpcode() == SI1->getOpcode() &&
3293 SI0->getOperand(1) == SI1->getOperand(1) &&
3294 (SI0->hasOneUse() || SI1->hasOneUse())) {
3295 Instruction *NewOp =
3296 InsertNewInstBefore(BinaryOperator::createAnd(SI0->getOperand(0),
3297 SI1->getOperand(0),
3298 SI0->getName()), I);
3299 return new ShiftInst(SI1->getOpcode(), NewOp, SI1->getOperand(1));
3300 }
Chris Lattner3af10532006-05-05 06:39:07 +00003301 }
3302
Chris Lattner113f4f42002-06-25 16:13:24 +00003303 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003304}
3305
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003306/// CollectBSwapParts - Look to see if the specified value defines a single byte
3307/// in the result. If it does, and if the specified byte hasn't been filled in
3308/// yet, fill it in and return false.
3309static bool CollectBSwapParts(Value *V, std::vector<Value*> &ByteValues) {
3310 Instruction *I = dyn_cast<Instruction>(V);
3311 if (I == 0) return true;
3312
3313 // If this is an or instruction, it is an inner node of the bswap.
3314 if (I->getOpcode() == Instruction::Or)
3315 return CollectBSwapParts(I->getOperand(0), ByteValues) ||
3316 CollectBSwapParts(I->getOperand(1), ByteValues);
3317
3318 // If this is a shift by a constant int, and it is "24", then its operand
3319 // defines a byte. We only handle unsigned types here.
3320 if (isa<ShiftInst>(I) && isa<ConstantInt>(I->getOperand(1))) {
3321 // Not shifting the entire input by N-1 bytes?
Reid Spencere0fc4df2006-10-20 07:07:24 +00003322 if (cast<ConstantInt>(I->getOperand(1))->getZExtValue() !=
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003323 8*(ByteValues.size()-1))
3324 return true;
3325
3326 unsigned DestNo;
3327 if (I->getOpcode() == Instruction::Shl) {
3328 // X << 24 defines the top byte with the lowest of the input bytes.
3329 DestNo = ByteValues.size()-1;
3330 } else {
3331 // X >>u 24 defines the low byte with the highest of the input bytes.
3332 DestNo = 0;
3333 }
3334
3335 // If the destination byte value is already defined, the values are or'd
3336 // together, which isn't a bswap (unless it's an or of the same bits).
3337 if (ByteValues[DestNo] && ByteValues[DestNo] != I->getOperand(0))
3338 return true;
3339 ByteValues[DestNo] = I->getOperand(0);
3340 return false;
3341 }
3342
3343 // Otherwise, we can only handle and(shift X, imm), imm). Bail out of if we
3344 // don't have this.
3345 Value *Shift = 0, *ShiftLHS = 0;
3346 ConstantInt *AndAmt = 0, *ShiftAmt = 0;
3347 if (!match(I, m_And(m_Value(Shift), m_ConstantInt(AndAmt))) ||
3348 !match(Shift, m_Shift(m_Value(ShiftLHS), m_ConstantInt(ShiftAmt))))
3349 return true;
3350 Instruction *SI = cast<Instruction>(Shift);
3351
3352 // Make sure that the shift amount is by a multiple of 8 and isn't too big.
Reid Spencere0fc4df2006-10-20 07:07:24 +00003353 if (ShiftAmt->getZExtValue() & 7 ||
3354 ShiftAmt->getZExtValue() > 8*ByteValues.size())
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003355 return true;
3356
3357 // Turn 0xFF -> 0, 0xFF00 -> 1, 0xFF0000 -> 2, etc.
3358 unsigned DestByte;
3359 for (DestByte = 0; DestByte != ByteValues.size(); ++DestByte)
Reid Spencere0fc4df2006-10-20 07:07:24 +00003360 if (AndAmt->getZExtValue() == uint64_t(0xFF) << 8*DestByte)
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003361 break;
3362 // Unknown mask for bswap.
3363 if (DestByte == ByteValues.size()) return true;
3364
Reid Spencere0fc4df2006-10-20 07:07:24 +00003365 unsigned ShiftBytes = ShiftAmt->getZExtValue()/8;
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003366 unsigned SrcByte;
3367 if (SI->getOpcode() == Instruction::Shl)
3368 SrcByte = DestByte - ShiftBytes;
3369 else
3370 SrcByte = DestByte + ShiftBytes;
3371
3372 // If the SrcByte isn't a bswapped value from the DestByte, reject it.
3373 if (SrcByte != ByteValues.size()-DestByte-1)
3374 return true;
3375
3376 // If the destination byte value is already defined, the values are or'd
3377 // together, which isn't a bswap (unless it's an or of the same bits).
3378 if (ByteValues[DestByte] && ByteValues[DestByte] != SI->getOperand(0))
3379 return true;
3380 ByteValues[DestByte] = SI->getOperand(0);
3381 return false;
3382}
3383
3384/// MatchBSwap - Given an OR instruction, check to see if this is a bswap idiom.
3385/// If so, insert the new bswap intrinsic and return it.
3386Instruction *InstCombiner::MatchBSwap(BinaryOperator &I) {
3387 // We can only handle bswap of unsigned integers, and cannot bswap one byte.
3388 if (!I.getType()->isUnsigned() || I.getType() == Type::UByteTy)
3389 return 0;
3390
3391 /// ByteValues - For each byte of the result, we keep track of which value
3392 /// defines each byte.
3393 std::vector<Value*> ByteValues;
3394 ByteValues.resize(I.getType()->getPrimitiveSize());
3395
3396 // Try to find all the pieces corresponding to the bswap.
3397 if (CollectBSwapParts(I.getOperand(0), ByteValues) ||
3398 CollectBSwapParts(I.getOperand(1), ByteValues))
3399 return 0;
3400
3401 // Check to see if all of the bytes come from the same value.
3402 Value *V = ByteValues[0];
3403 if (V == 0) return 0; // Didn't find a byte? Must be zero.
3404
3405 // Check to make sure that all of the bytes come from the same value.
3406 for (unsigned i = 1, e = ByteValues.size(); i != e; ++i)
3407 if (ByteValues[i] != V)
3408 return 0;
3409
3410 // If they do then *success* we can turn this into a bswap. Figure out what
3411 // bswap to make it into.
3412 Module *M = I.getParent()->getParent()->getParent();
Chris Lattner091b6ea2006-07-11 18:31:26 +00003413 const char *FnName = 0;
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003414 if (I.getType() == Type::UShortTy)
3415 FnName = "llvm.bswap.i16";
3416 else if (I.getType() == Type::UIntTy)
3417 FnName = "llvm.bswap.i32";
3418 else if (I.getType() == Type::ULongTy)
3419 FnName = "llvm.bswap.i64";
3420 else
3421 assert(0 && "Unknown integer type!");
3422 Function *F = M->getOrInsertFunction(FnName, I.getType(), I.getType(), NULL);
3423
3424 return new CallInst(F, V);
3425}
3426
3427
Chris Lattner113f4f42002-06-25 16:13:24 +00003428Instruction *InstCombiner::visitOr(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00003429 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00003430 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003431
Chris Lattner81a7a232004-10-16 18:11:37 +00003432 if (isa<UndefValue>(Op1))
3433 return ReplaceInstUsesWith(I, // X | undef -> -1
3434 ConstantIntegral::getAllOnesValue(I.getType()));
3435
Chris Lattner5b2edb12006-02-12 08:02:11 +00003436 // or X, X = X
3437 if (Op0 == Op1)
Chris Lattnere6794492002-08-12 21:17:25 +00003438 return ReplaceInstUsesWith(I, Op0);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003439
Chris Lattner5b2edb12006-02-12 08:02:11 +00003440 // See if we can simplify any instructions used by the instruction whose sole
3441 // purpose is to compute bits we don't care about.
3442 uint64_t KnownZero, KnownOne;
Chris Lattnerd70d9f52006-03-25 21:58:26 +00003443 if (!isa<PackedType>(I.getType()) &&
3444 SimplifyDemandedBits(&I, I.getType()->getIntegralTypeMask(),
Chris Lattner5b2edb12006-02-12 08:02:11 +00003445 KnownZero, KnownOne))
3446 return &I;
3447
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003448 // or X, -1 == -1
Chris Lattner8f0d1562003-07-23 18:29:44 +00003449 if (ConstantIntegral *RHS = dyn_cast<ConstantIntegral>(Op1)) {
Chris Lattner330628a2006-01-06 17:59:59 +00003450 ConstantInt *C1 = 0; Value *X = 0;
Chris Lattnerd4252a72004-07-30 07:50:03 +00003451 // (X & C1) | C2 --> (X | C2) & (C1|C2)
3452 if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
Chris Lattnerb62f5082005-05-09 04:58:36 +00003453 Instruction *Or = BinaryOperator::createOr(X, RHS, Op0->getName());
3454 Op0->setName("");
Chris Lattnerd4252a72004-07-30 07:50:03 +00003455 InsertNewInstBefore(Or, I);
3456 return BinaryOperator::createAnd(Or, ConstantExpr::getOr(RHS, C1));
3457 }
Chris Lattner8f0d1562003-07-23 18:29:44 +00003458
Chris Lattnerd4252a72004-07-30 07:50:03 +00003459 // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
3460 if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
3461 std::string Op0Name = Op0->getName(); Op0->setName("");
3462 Instruction *Or = BinaryOperator::createOr(X, RHS, Op0Name);
3463 InsertNewInstBefore(Or, I);
3464 return BinaryOperator::createXor(Or,
3465 ConstantExpr::getAnd(C1, ConstantExpr::getNot(RHS)));
Chris Lattner8f0d1562003-07-23 18:29:44 +00003466 }
Chris Lattner183b3362004-04-09 19:05:30 +00003467
3468 // Try to fold constant and into select arguments.
3469 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner86102b82005-01-01 16:22:27 +00003470 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00003471 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00003472 if (isa<PHINode>(Op0))
3473 if (Instruction *NV = FoldOpIntoPhi(I))
3474 return NV;
Chris Lattner8f0d1562003-07-23 18:29:44 +00003475 }
3476
Chris Lattner330628a2006-01-06 17:59:59 +00003477 Value *A = 0, *B = 0;
3478 ConstantInt *C1 = 0, *C2 = 0;
Chris Lattner4294cec2005-05-07 23:49:08 +00003479
3480 if (match(Op0, m_And(m_Value(A), m_Value(B))))
3481 if (A == Op1 || B == Op1) // (A & ?) | A --> A
3482 return ReplaceInstUsesWith(I, Op1);
3483 if (match(Op1, m_And(m_Value(A), m_Value(B))))
3484 if (A == Op0 || B == Op0) // A | (A & ?) --> A
3485 return ReplaceInstUsesWith(I, Op0);
3486
Chris Lattnerb7845d62006-07-10 20:25:24 +00003487 // (A | B) | C and A | (B | C) -> bswap if possible.
3488 // (A >> B) | (C << D) and (A << B) | (B >> C) -> bswap if possible.
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003489 if (match(Op0, m_Or(m_Value(), m_Value())) ||
Chris Lattnerb7845d62006-07-10 20:25:24 +00003490 match(Op1, m_Or(m_Value(), m_Value())) ||
3491 (match(Op0, m_Shift(m_Value(), m_Value())) &&
3492 match(Op1, m_Shift(m_Value(), m_Value())))) {
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003493 if (Instruction *BSwap = MatchBSwap(I))
3494 return BSwap;
3495 }
3496
Chris Lattnerb62f5082005-05-09 04:58:36 +00003497 // (X^C)|Y -> (X|Y)^C iff Y&C == 0
3498 if (Op0->hasOneUse() && match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
Chris Lattnerc3ebf402006-02-07 07:27:52 +00003499 MaskedValueIsZero(Op1, C1->getZExtValue())) {
Chris Lattnerb62f5082005-05-09 04:58:36 +00003500 Instruction *NOr = BinaryOperator::createOr(A, Op1, Op0->getName());
3501 Op0->setName("");
3502 return BinaryOperator::createXor(InsertNewInstBefore(NOr, I), C1);
3503 }
3504
3505 // Y|(X^C) -> (X|Y)^C iff Y&C == 0
3506 if (Op1->hasOneUse() && match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
Chris Lattnerc3ebf402006-02-07 07:27:52 +00003507 MaskedValueIsZero(Op0, C1->getZExtValue())) {
Chris Lattnerb62f5082005-05-09 04:58:36 +00003508 Instruction *NOr = BinaryOperator::createOr(A, Op0, Op1->getName());
3509 Op0->setName("");
3510 return BinaryOperator::createXor(InsertNewInstBefore(NOr, I), C1);
3511 }
3512
Chris Lattner15212982005-09-18 03:42:07 +00003513 // (A & C1)|(B & C2)
Chris Lattnerd4252a72004-07-30 07:50:03 +00003514 if (match(Op0, m_And(m_Value(A), m_ConstantInt(C1))) &&
Chris Lattner15212982005-09-18 03:42:07 +00003515 match(Op1, m_And(m_Value(B), m_ConstantInt(C2)))) {
3516
3517 if (A == B) // (A & C1)|(A & C2) == A & (C1|C2)
3518 return BinaryOperator::createAnd(A, ConstantExpr::getOr(C1, C2));
3519
3520
Chris Lattner01f56c62005-09-18 06:02:59 +00003521 // If we have: ((V + N) & C1) | (V & C2)
3522 // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
3523 // replace with V+N.
3524 if (C1 == ConstantExpr::getNot(C2)) {
Chris Lattner330628a2006-01-06 17:59:59 +00003525 Value *V1 = 0, *V2 = 0;
Reid Spencere0fc4df2006-10-20 07:07:24 +00003526 if ((C2->getZExtValue() & (C2->getZExtValue()+1)) == 0 && // C2 == 0+1+
Chris Lattner01f56c62005-09-18 06:02:59 +00003527 match(A, m_Add(m_Value(V1), m_Value(V2)))) {
3528 // Add commutes, try both ways.
Chris Lattnerc3ebf402006-02-07 07:27:52 +00003529 if (V1 == B && MaskedValueIsZero(V2, C2->getZExtValue()))
Chris Lattner01f56c62005-09-18 06:02:59 +00003530 return ReplaceInstUsesWith(I, A);
Chris Lattnerc3ebf402006-02-07 07:27:52 +00003531 if (V2 == B && MaskedValueIsZero(V1, C2->getZExtValue()))
Chris Lattner01f56c62005-09-18 06:02:59 +00003532 return ReplaceInstUsesWith(I, A);
3533 }
3534 // Or commutes, try both ways.
Reid Spencere0fc4df2006-10-20 07:07:24 +00003535 if ((C1->getZExtValue() & (C1->getZExtValue()+1)) == 0 &&
Chris Lattner01f56c62005-09-18 06:02:59 +00003536 match(B, m_Add(m_Value(V1), m_Value(V2)))) {
3537 // Add commutes, try both ways.
Chris Lattnerc3ebf402006-02-07 07:27:52 +00003538 if (V1 == A && MaskedValueIsZero(V2, C1->getZExtValue()))
Chris Lattner01f56c62005-09-18 06:02:59 +00003539 return ReplaceInstUsesWith(I, B);
Chris Lattnerc3ebf402006-02-07 07:27:52 +00003540 if (V2 == A && MaskedValueIsZero(V1, C1->getZExtValue()))
Chris Lattner01f56c62005-09-18 06:02:59 +00003541 return ReplaceInstUsesWith(I, B);
Chris Lattner15212982005-09-18 03:42:07 +00003542 }
3543 }
3544 }
Chris Lattnerf05d69a2006-11-14 07:46:50 +00003545
3546 // (X >> Z) | (Y >> Z) -> (X|Y) >> Z for all shifts.
3547 if (ShiftInst *SI1 = dyn_cast<ShiftInst>(Op1)) {
3548 if (ShiftInst *SI0 = dyn_cast<ShiftInst>(Op0))
3549 if (SI0->getOpcode() == SI1->getOpcode() &&
3550 SI0->getOperand(1) == SI1->getOperand(1) &&
3551 (SI0->hasOneUse() || SI1->hasOneUse())) {
3552 Instruction *NewOp =
3553 InsertNewInstBefore(BinaryOperator::createOr(SI0->getOperand(0),
3554 SI1->getOperand(0),
3555 SI0->getName()), I);
3556 return new ShiftInst(SI1->getOpcode(), NewOp, SI1->getOperand(1));
3557 }
3558 }
Chris Lattner812aab72003-08-12 19:11:07 +00003559
Chris Lattnerd4252a72004-07-30 07:50:03 +00003560 if (match(Op0, m_Not(m_Value(A)))) { // ~A | Op1
3561 if (A == Op1) // ~A | A == -1
Misha Brukmanb1c93172005-04-21 23:48:37 +00003562 return ReplaceInstUsesWith(I,
Chris Lattnerd4252a72004-07-30 07:50:03 +00003563 ConstantIntegral::getAllOnesValue(I.getType()));
3564 } else {
3565 A = 0;
3566 }
Chris Lattner4294cec2005-05-07 23:49:08 +00003567 // Note, A is still live here!
Chris Lattnerd4252a72004-07-30 07:50:03 +00003568 if (match(Op1, m_Not(m_Value(B)))) { // Op0 | ~B
3569 if (Op0 == B)
Misha Brukmanb1c93172005-04-21 23:48:37 +00003570 return ReplaceInstUsesWith(I,
Chris Lattnerd4252a72004-07-30 07:50:03 +00003571 ConstantIntegral::getAllOnesValue(I.getType()));
Chris Lattner3e327a42003-03-10 23:13:59 +00003572
Misha Brukman9c003d82004-07-30 12:50:08 +00003573 // (~A | ~B) == (~(A & B)) - De Morgan's Law
Chris Lattnerd4252a72004-07-30 07:50:03 +00003574 if (A && isOnlyUse(Op0) && isOnlyUse(Op1)) {
3575 Value *And = InsertNewInstBefore(BinaryOperator::createAnd(A, B,
3576 I.getName()+".demorgan"), I);
3577 return BinaryOperator::createNot(And);
3578 }
Chris Lattner3e327a42003-03-10 23:13:59 +00003579 }
Chris Lattner3082c5a2003-02-18 19:28:33 +00003580
Chris Lattner3ac7c262003-08-13 20:16:26 +00003581 // (setcc1 A, B) | (setcc2 A, B) --> (setcc3 A, B)
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003582 if (SetCondInst *RHS = dyn_cast<SetCondInst>(I.getOperand(1))) {
Chris Lattner3ac7c262003-08-13 20:16:26 +00003583 if (Instruction *R = AssociativeOpt(I, FoldSetCCLogical(*this, RHS)))
3584 return R;
3585
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003586 Value *LHSVal, *RHSVal;
3587 ConstantInt *LHSCst, *RHSCst;
3588 Instruction::BinaryOps LHSCC, RHSCC;
3589 if (match(Op0, m_SetCond(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
3590 if (match(RHS, m_SetCond(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
3591 if (LHSVal == RHSVal && // Found (X setcc C1) | (X setcc C2)
3592 // Set[GL]E X, CST is folded to Set[GL]T elsewhere.
Misha Brukmanb1c93172005-04-21 23:48:37 +00003593 LHSCC != Instruction::SetGE && LHSCC != Instruction::SetLE &&
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003594 RHSCC != Instruction::SetGE && RHSCC != Instruction::SetLE) {
3595 // Ensure that the larger constant is on the RHS.
3596 Constant *Cmp = ConstantExpr::getSetGT(LHSCst, RHSCst);
3597 SetCondInst *LHS = cast<SetCondInst>(Op0);
3598 if (cast<ConstantBool>(Cmp)->getValue()) {
3599 std::swap(LHS, RHS);
3600 std::swap(LHSCst, RHSCst);
3601 std::swap(LHSCC, RHSCC);
3602 }
3603
3604 // At this point, we know we have have two setcc instructions
3605 // comparing a value against two constants and or'ing the result
3606 // together. Because of the above check, we know that we only have
3607 // SetEQ, SetNE, SetLT, and SetGT here. We also know (from the
3608 // FoldSetCCLogical check above), that the two constants are not
3609 // equal.
3610 assert(LHSCst != RHSCst && "Compares not folded above?");
3611
3612 switch (LHSCC) {
3613 default: assert(0 && "Unknown integer condition code!");
3614 case Instruction::SetEQ:
3615 switch (RHSCC) {
3616 default: assert(0 && "Unknown integer condition code!");
3617 case Instruction::SetEQ:
3618 if (LHSCst == SubOne(RHSCst)) {// (X == 13 | X == 14) -> X-13 <u 2
3619 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
3620 Instruction *Add = BinaryOperator::createAdd(LHSVal, AddCST,
3621 LHSVal->getName()+".off");
3622 InsertNewInstBefore(Add, I);
3623 const Type *UnsType = Add->getType()->getUnsignedVersion();
Reid Spencer13bc5d72006-12-12 09:18:51 +00003624 Value *OffsetVal = InsertCastBefore(Instruction::BitCast, Add,
3625 UnsType, I);
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003626 AddCST = ConstantExpr::getSub(AddOne(RHSCst), LHSCst);
Reid Spencer13bc5d72006-12-12 09:18:51 +00003627 AddCST = ConstantExpr::getBitCast(AddCST, UnsType);
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003628 return new SetCondInst(Instruction::SetLT, OffsetVal, AddCST);
3629 }
3630 break; // (X == 13 | X == 15) -> no change
3631
Chris Lattner5c219462005-04-19 06:04:18 +00003632 case Instruction::SetGT: // (X == 13 | X > 14) -> no change
3633 break;
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003634 case Instruction::SetNE: // (X == 13 | X != 15) -> X != 15
3635 case Instruction::SetLT: // (X == 13 | X < 15) -> X < 15
3636 return ReplaceInstUsesWith(I, RHS);
3637 }
3638 break;
3639 case Instruction::SetNE:
3640 switch (RHSCC) {
3641 default: assert(0 && "Unknown integer condition code!");
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003642 case Instruction::SetEQ: // (X != 13 | X == 15) -> X != 13
3643 case Instruction::SetGT: // (X != 13 | X > 15) -> X != 13
3644 return ReplaceInstUsesWith(I, LHS);
3645 case Instruction::SetNE: // (X != 13 | X != 15) -> true
Chris Lattner2ceb6ee2005-06-17 03:59:17 +00003646 case Instruction::SetLT: // (X != 13 | X < 15) -> true
Chris Lattner6ab03f62006-09-28 23:35:22 +00003647 return ReplaceInstUsesWith(I, ConstantBool::getTrue());
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003648 }
3649 break;
3650 case Instruction::SetLT:
3651 switch (RHSCC) {
3652 default: assert(0 && "Unknown integer condition code!");
3653 case Instruction::SetEQ: // (X < 13 | X == 14) -> no change
3654 break;
Chris Lattner6862fbd2004-09-29 17:40:11 +00003655 case Instruction::SetGT: // (X < 13 | X > 15) -> (X-13) > 2
3656 return InsertRangeTest(LHSVal, LHSCst, AddOne(RHSCst), false, I);
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003657 case Instruction::SetNE: // (X < 13 | X != 15) -> X != 15
3658 case Instruction::SetLT: // (X < 13 | X < 15) -> X < 15
3659 return ReplaceInstUsesWith(I, RHS);
3660 }
3661 break;
3662 case Instruction::SetGT:
3663 switch (RHSCC) {
3664 default: assert(0 && "Unknown integer condition code!");
3665 case Instruction::SetEQ: // (X > 13 | X == 15) -> X > 13
3666 case Instruction::SetGT: // (X > 13 | X > 15) -> X > 13
3667 return ReplaceInstUsesWith(I, LHS);
3668 case Instruction::SetNE: // (X > 13 | X != 15) -> true
3669 case Instruction::SetLT: // (X > 13 | X < 15) -> true
Chris Lattner6ab03f62006-09-28 23:35:22 +00003670 return ReplaceInstUsesWith(I, ConstantBool::getTrue());
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003671 }
3672 }
3673 }
3674 }
Chris Lattner3af10532006-05-05 06:39:07 +00003675
3676 // fold (or (cast A), (cast B)) -> (cast (or A, B))
Reid Spencer799b5bf2006-12-13 08:27:15 +00003677 if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
Chris Lattner3af10532006-05-05 06:39:07 +00003678 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
Reid Spencer799b5bf2006-12-13 08:27:15 +00003679 if (Op0C->getOpcode() == Op1C->getOpcode()) {// same cast kind ?
3680 const Type *SrcTy = Op0C->getOperand(0)->getType();
3681 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isIntegral() &&
3682 // Only do this if the casts both really cause code to be generated.
3683 ValueRequiresCast(Op0C->getOperand(0), I.getType(), TD) &&
3684 ValueRequiresCast(Op1C->getOperand(0), I.getType(), TD)) {
3685 Instruction *NewOp = BinaryOperator::createOr(Op0C->getOperand(0),
3686 Op1C->getOperand(0),
3687 I.getName());
3688 InsertNewInstBefore(NewOp, I);
3689 return CastInst::create(Op0C->getOpcode(), NewOp, I.getType());
3690 }
Chris Lattner3af10532006-05-05 06:39:07 +00003691 }
Chris Lattner3af10532006-05-05 06:39:07 +00003692
Chris Lattner15212982005-09-18 03:42:07 +00003693
Chris Lattner113f4f42002-06-25 16:13:24 +00003694 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003695}
3696
Chris Lattnerc2076352004-02-16 01:20:27 +00003697// XorSelf - Implements: X ^ X --> 0
3698struct XorSelf {
3699 Value *RHS;
3700 XorSelf(Value *rhs) : RHS(rhs) {}
3701 bool shouldApply(Value *LHS) const { return LHS == RHS; }
3702 Instruction *apply(BinaryOperator &Xor) const {
3703 return &Xor;
3704 }
3705};
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003706
3707
Chris Lattner113f4f42002-06-25 16:13:24 +00003708Instruction *InstCombiner::visitXor(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00003709 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00003710 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003711
Chris Lattner81a7a232004-10-16 18:11:37 +00003712 if (isa<UndefValue>(Op1))
3713 return ReplaceInstUsesWith(I, Op1); // X ^ undef -> undef
3714
Chris Lattnerc2076352004-02-16 01:20:27 +00003715 // xor X, X = 0, even if X is nested in a sequence of Xor's.
3716 if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1))) {
3717 assert(Result == &I && "AssociativeOpt didn't work?");
Chris Lattnere6794492002-08-12 21:17:25 +00003718 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerc2076352004-02-16 01:20:27 +00003719 }
Chris Lattner5b2edb12006-02-12 08:02:11 +00003720
3721 // See if we can simplify any instructions used by the instruction whose sole
3722 // purpose is to compute bits we don't care about.
3723 uint64_t KnownZero, KnownOne;
Chris Lattnerd70d9f52006-03-25 21:58:26 +00003724 if (!isa<PackedType>(I.getType()) &&
3725 SimplifyDemandedBits(&I, I.getType()->getIntegralTypeMask(),
Chris Lattner5b2edb12006-02-12 08:02:11 +00003726 KnownZero, KnownOne))
3727 return &I;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003728
Chris Lattner97638592003-07-23 21:37:07 +00003729 if (ConstantIntegral *RHS = dyn_cast<ConstantIntegral>(Op1)) {
Chris Lattner97638592003-07-23 21:37:07 +00003730 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
Chris Lattnerb8d6e402002-08-20 18:24:26 +00003731 // xor (setcc A, B), true = not (setcc A, B) = setncc A, B
Chris Lattner97638592003-07-23 21:37:07 +00003732 if (SetCondInst *SCI = dyn_cast<SetCondInst>(Op0I))
Chris Lattner6ab03f62006-09-28 23:35:22 +00003733 if (RHS == ConstantBool::getTrue() && SCI->hasOneUse())
Chris Lattnerb8d6e402002-08-20 18:24:26 +00003734 return new SetCondInst(SCI->getInverseCondition(),
3735 SCI->getOperand(0), SCI->getOperand(1));
Chris Lattnere5806662003-11-04 23:50:51 +00003736
Chris Lattner8f2f5982003-11-05 01:06:05 +00003737 // ~(c-X) == X-c-1 == X+(-c-1)
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00003738 if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
3739 if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003740 Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
3741 Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00003742 ConstantInt::get(I.getType(), 1));
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003743 return BinaryOperator::createAdd(Op0I->getOperand(1), ConstantRHS);
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00003744 }
Chris Lattner023a4832004-06-18 06:07:51 +00003745
3746 // ~(~X & Y) --> (X | ~Y)
3747 if (Op0I->getOpcode() == Instruction::And && RHS->isAllOnesValue()) {
3748 if (dyn_castNotVal(Op0I->getOperand(1))) Op0I->swapOperands();
3749 if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
3750 Instruction *NotY =
Misha Brukmanb1c93172005-04-21 23:48:37 +00003751 BinaryOperator::createNot(Op0I->getOperand(1),
Chris Lattner023a4832004-06-18 06:07:51 +00003752 Op0I->getOperand(1)->getName()+".not");
3753 InsertNewInstBefore(NotY, I);
3754 return BinaryOperator::createOr(Op0NotVal, NotY);
3755 }
3756 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00003757
Chris Lattner97638592003-07-23 21:37:07 +00003758 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
Chris Lattner5b2edb12006-02-12 08:02:11 +00003759 if (Op0I->getOpcode() == Instruction::Add) {
Chris Lattner0f68fa62003-11-04 23:37:10 +00003760 // ~(X-c) --> (-c-1)-X
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00003761 if (RHS->isAllOnesValue()) {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003762 Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
3763 return BinaryOperator::createSub(
3764 ConstantExpr::getSub(NegOp0CI,
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00003765 ConstantInt::get(I.getType(), 1)),
Chris Lattner0f68fa62003-11-04 23:37:10 +00003766 Op0I->getOperand(0));
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00003767 }
Chris Lattnerf78df7c2006-02-26 19:57:54 +00003768 } else if (Op0I->getOpcode() == Instruction::Or) {
3769 // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
3770 if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getZExtValue())) {
3771 Constant *NewRHS = ConstantExpr::getOr(Op0CI, RHS);
3772 // Anything in both C1 and C2 is known to be zero, remove it from
3773 // NewRHS.
3774 Constant *CommonBits = ConstantExpr::getAnd(Op0CI, RHS);
3775 NewRHS = ConstantExpr::getAnd(NewRHS,
3776 ConstantExpr::getNot(CommonBits));
3777 WorkList.push_back(Op0I);
3778 I.setOperand(0, Op0I->getOperand(0));
3779 I.setOperand(1, NewRHS);
3780 return &I;
3781 }
Chris Lattner97638592003-07-23 21:37:07 +00003782 }
Chris Lattnerb8d6e402002-08-20 18:24:26 +00003783 }
Chris Lattner183b3362004-04-09 19:05:30 +00003784
3785 // Try to fold constant and into select arguments.
3786 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner86102b82005-01-01 16:22:27 +00003787 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00003788 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00003789 if (isa<PHINode>(Op0))
3790 if (Instruction *NV = FoldOpIntoPhi(I))
3791 return NV;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003792 }
3793
Chris Lattnerbb74e222003-03-10 23:06:50 +00003794 if (Value *X = dyn_castNotVal(Op0)) // ~A ^ A == -1
Chris Lattner3082c5a2003-02-18 19:28:33 +00003795 if (X == Op1)
3796 return ReplaceInstUsesWith(I,
3797 ConstantIntegral::getAllOnesValue(I.getType()));
3798
Chris Lattnerbb74e222003-03-10 23:06:50 +00003799 if (Value *X = dyn_castNotVal(Op1)) // A ^ ~A == -1
Chris Lattner3082c5a2003-02-18 19:28:33 +00003800 if (X == Op0)
3801 return ReplaceInstUsesWith(I,
3802 ConstantIntegral::getAllOnesValue(I.getType()));
3803
Chris Lattnerdcd07922006-04-01 08:03:55 +00003804 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1))
Chris Lattnerb36d9082004-02-16 03:54:20 +00003805 if (Op1I->getOpcode() == Instruction::Or) {
Chris Lattner1bbb7b62003-03-10 18:24:17 +00003806 if (Op1I->getOperand(0) == Op0) { // B^(B|A) == (A|B)^B
Chris Lattnerdcd07922006-04-01 08:03:55 +00003807 Op1I->swapOperands();
Chris Lattner1bbb7b62003-03-10 18:24:17 +00003808 I.swapOperands();
3809 std::swap(Op0, Op1);
3810 } else if (Op1I->getOperand(1) == Op0) { // B^(A|B) == (A|B)^B
Chris Lattnerdcd07922006-04-01 08:03:55 +00003811 I.swapOperands(); // Simplified below.
Chris Lattner1bbb7b62003-03-10 18:24:17 +00003812 std::swap(Op0, Op1);
Misha Brukmanb1c93172005-04-21 23:48:37 +00003813 }
Chris Lattnerb36d9082004-02-16 03:54:20 +00003814 } else if (Op1I->getOpcode() == Instruction::Xor) {
3815 if (Op0 == Op1I->getOperand(0)) // A^(A^B) == B
3816 return ReplaceInstUsesWith(I, Op1I->getOperand(1));
3817 else if (Op0 == Op1I->getOperand(1)) // A^(B^A) == B
3818 return ReplaceInstUsesWith(I, Op1I->getOperand(0));
Chris Lattnerdcd07922006-04-01 08:03:55 +00003819 } else if (Op1I->getOpcode() == Instruction::And && Op1I->hasOneUse()) {
3820 if (Op1I->getOperand(0) == Op0) // A^(A&B) -> A^(B&A)
3821 Op1I->swapOperands();
3822 if (Op0 == Op1I->getOperand(1)) { // A^(B&A) -> (B&A)^A
3823 I.swapOperands(); // Simplified below.
3824 std::swap(Op0, Op1);
3825 }
Chris Lattnerb36d9082004-02-16 03:54:20 +00003826 }
Chris Lattner1bbb7b62003-03-10 18:24:17 +00003827
Chris Lattnerdcd07922006-04-01 08:03:55 +00003828 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
Chris Lattnerf95d9b92003-10-15 16:48:29 +00003829 if (Op0I->getOpcode() == Instruction::Or && Op0I->hasOneUse()) {
Chris Lattner1bbb7b62003-03-10 18:24:17 +00003830 if (Op0I->getOperand(0) == Op1) // (B|A)^B == (A|B)^B
Chris Lattnerdcd07922006-04-01 08:03:55 +00003831 Op0I->swapOperands();
Chris Lattnerdcf240a2003-03-10 21:43:22 +00003832 if (Op0I->getOperand(1) == Op1) { // (A|B)^B == A & ~B
Chris Lattnerdcd07922006-04-01 08:03:55 +00003833 Instruction *NotB = BinaryOperator::createNot(Op1, "tmp");
3834 InsertNewInstBefore(NotB, I);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003835 return BinaryOperator::createAnd(Op0I->getOperand(0), NotB);
Chris Lattner1bbb7b62003-03-10 18:24:17 +00003836 }
Chris Lattnerb36d9082004-02-16 03:54:20 +00003837 } else if (Op0I->getOpcode() == Instruction::Xor) {
3838 if (Op1 == Op0I->getOperand(0)) // (A^B)^A == B
3839 return ReplaceInstUsesWith(I, Op0I->getOperand(1));
3840 else if (Op1 == Op0I->getOperand(1)) // (B^A)^A == B
3841 return ReplaceInstUsesWith(I, Op0I->getOperand(0));
Chris Lattnerdcd07922006-04-01 08:03:55 +00003842 } else if (Op0I->getOpcode() == Instruction::And && Op0I->hasOneUse()) {
3843 if (Op0I->getOperand(0) == Op1) // (A&B)^A -> (B&A)^A
3844 Op0I->swapOperands();
Chris Lattner6cf49142006-04-01 22:05:01 +00003845 if (Op0I->getOperand(1) == Op1 && // (B&A)^A == ~B & A
3846 !isa<ConstantInt>(Op1)) { // Canonical form is (B&C)^C
Chris Lattnerdcd07922006-04-01 08:03:55 +00003847 Instruction *N = BinaryOperator::createNot(Op0I->getOperand(0), "tmp");
3848 InsertNewInstBefore(N, I);
3849 return BinaryOperator::createAnd(N, Op1);
3850 }
Chris Lattner1bbb7b62003-03-10 18:24:17 +00003851 }
3852
Chris Lattner3ac7c262003-08-13 20:16:26 +00003853 // (setcc1 A, B) ^ (setcc2 A, B) --> (setcc3 A, B)
3854 if (SetCondInst *RHS = dyn_cast<SetCondInst>(I.getOperand(1)))
3855 if (Instruction *R = AssociativeOpt(I, FoldSetCCLogical(*this, RHS)))
3856 return R;
3857
Chris Lattner3af10532006-05-05 06:39:07 +00003858 // fold (xor (cast A), (cast B)) -> (cast (xor A, B))
Reid Spencer799b5bf2006-12-13 08:27:15 +00003859 if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
Chris Lattner3af10532006-05-05 06:39:07 +00003860 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
Reid Spencer799b5bf2006-12-13 08:27:15 +00003861 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind?
3862 const Type *SrcTy = Op0C->getOperand(0)->getType();
3863 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isIntegral() &&
3864 // Only do this if the casts both really cause code to be generated.
3865 ValueRequiresCast(Op0C->getOperand(0), I.getType(), TD) &&
3866 ValueRequiresCast(Op1C->getOperand(0), I.getType(), TD)) {
3867 Instruction *NewOp = BinaryOperator::createXor(Op0C->getOperand(0),
3868 Op1C->getOperand(0),
3869 I.getName());
3870 InsertNewInstBefore(NewOp, I);
3871 return CastInst::create(Op0C->getOpcode(), NewOp, I.getType());
3872 }
Chris Lattner3af10532006-05-05 06:39:07 +00003873 }
Chris Lattnerf05d69a2006-11-14 07:46:50 +00003874
3875 // (X >> Z) ^ (Y >> Z) -> (X^Y) >> Z for all shifts.
3876 if (ShiftInst *SI1 = dyn_cast<ShiftInst>(Op1)) {
3877 if (ShiftInst *SI0 = dyn_cast<ShiftInst>(Op0))
3878 if (SI0->getOpcode() == SI1->getOpcode() &&
3879 SI0->getOperand(1) == SI1->getOperand(1) &&
3880 (SI0->hasOneUse() || SI1->hasOneUse())) {
3881 Instruction *NewOp =
3882 InsertNewInstBefore(BinaryOperator::createXor(SI0->getOperand(0),
3883 SI1->getOperand(0),
3884 SI0->getName()), I);
3885 return new ShiftInst(SI1->getOpcode(), NewOp, SI1->getOperand(1));
3886 }
3887 }
Chris Lattner3af10532006-05-05 06:39:07 +00003888
Chris Lattner113f4f42002-06-25 16:13:24 +00003889 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003890}
3891
Chris Lattner6862fbd2004-09-29 17:40:11 +00003892static bool isPositive(ConstantInt *C) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00003893 return C->getSExtValue() >= 0;
Chris Lattner6862fbd2004-09-29 17:40:11 +00003894}
3895
3896/// AddWithOverflow - Compute Result = In1+In2, returning true if the result
3897/// overflowed for this type.
3898static bool AddWithOverflow(ConstantInt *&Result, ConstantInt *In1,
3899 ConstantInt *In2) {
3900 Result = cast<ConstantInt>(ConstantExpr::getAdd(In1, In2));
3901
3902 if (In1->getType()->isUnsigned())
Reid Spencere0fc4df2006-10-20 07:07:24 +00003903 return cast<ConstantInt>(Result)->getZExtValue() <
3904 cast<ConstantInt>(In1)->getZExtValue();
Chris Lattner6862fbd2004-09-29 17:40:11 +00003905 if (isPositive(In1) != isPositive(In2))
3906 return false;
3907 if (isPositive(In1))
Reid Spencere0fc4df2006-10-20 07:07:24 +00003908 return cast<ConstantInt>(Result)->getSExtValue() <
3909 cast<ConstantInt>(In1)->getSExtValue();
3910 return cast<ConstantInt>(Result)->getSExtValue() >
3911 cast<ConstantInt>(In1)->getSExtValue();
Chris Lattner6862fbd2004-09-29 17:40:11 +00003912}
3913
Chris Lattner0798af32005-01-13 20:14:25 +00003914/// EmitGEPOffset - Given a getelementptr instruction/constantexpr, emit the
3915/// code necessary to compute the offset from the base pointer (without adding
3916/// in the base pointer). Return the result as a signed integer of intptr size.
3917static Value *EmitGEPOffset(User *GEP, Instruction &I, InstCombiner &IC) {
3918 TargetData &TD = IC.getTargetData();
3919 gep_type_iterator GTI = gep_type_begin(GEP);
3920 const Type *UIntPtrTy = TD.getIntPtrType();
3921 const Type *SIntPtrTy = UIntPtrTy->getSignedVersion();
3922 Value *Result = Constant::getNullValue(SIntPtrTy);
3923
3924 // Build a mask for high order bits.
Chris Lattner77defba2006-02-07 07:00:41 +00003925 uint64_t PtrSizeMask = ~0ULL >> (64-TD.getPointerSize()*8);
Chris Lattner0798af32005-01-13 20:14:25 +00003926
Chris Lattner0798af32005-01-13 20:14:25 +00003927 for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i, ++GTI) {
3928 Value *Op = GEP->getOperand(i);
Chris Lattnerd35d2102005-01-13 23:26:48 +00003929 uint64_t Size = TD.getTypeSize(GTI.getIndexedType()) & PtrSizeMask;
Reid Spencer13bc5d72006-12-12 09:18:51 +00003930 Constant *Scale = ConstantExpr::getBitCast(ConstantInt::get(UIntPtrTy, Size),
Chris Lattner0798af32005-01-13 20:14:25 +00003931 SIntPtrTy);
3932 if (Constant *OpC = dyn_cast<Constant>(Op)) {
3933 if (!OpC->isNullValue()) {
Reid Spencer13bc5d72006-12-12 09:18:51 +00003934 OpC = ConstantExpr::getIntegerCast(OpC, SIntPtrTy, true /*SExt*/);
Chris Lattner0798af32005-01-13 20:14:25 +00003935 Scale = ConstantExpr::getMul(OpC, Scale);
3936 if (Constant *RC = dyn_cast<Constant>(Result))
3937 Result = ConstantExpr::getAdd(RC, Scale);
3938 else {
3939 // Emit an add instruction.
3940 Result = IC.InsertNewInstBefore(
3941 BinaryOperator::createAdd(Result, Scale,
3942 GEP->getName()+".offs"), I);
3943 }
3944 }
3945 } else {
Chris Lattner7aa41cf2005-01-14 17:17:59 +00003946 // Convert to correct type.
Reid Spencerbb65ebf2006-12-12 23:36:14 +00003947 Op = IC.InsertNewInstBefore(CastInst::createSExtOrBitCast(Op, SIntPtrTy,
Chris Lattner7aa41cf2005-01-14 17:17:59 +00003948 Op->getName()+".c"), I);
3949 if (Size != 1)
Chris Lattner4cb9fa32005-01-13 20:40:58 +00003950 // We'll let instcombine(mul) convert this to a shl if possible.
3951 Op = IC.InsertNewInstBefore(BinaryOperator::createMul(Op, Scale,
3952 GEP->getName()+".idx"), I);
Chris Lattner0798af32005-01-13 20:14:25 +00003953
3954 // Emit an add instruction.
Chris Lattner4cb9fa32005-01-13 20:40:58 +00003955 Result = IC.InsertNewInstBefore(BinaryOperator::createAdd(Op, Result,
Chris Lattner0798af32005-01-13 20:14:25 +00003956 GEP->getName()+".offs"), I);
3957 }
3958 }
3959 return Result;
3960}
3961
3962/// FoldGEPSetCC - Fold comparisons between a GEP instruction and something
3963/// else. At this point we know that the GEP is on the LHS of the comparison.
3964Instruction *InstCombiner::FoldGEPSetCC(User *GEPLHS, Value *RHS,
3965 Instruction::BinaryOps Cond,
3966 Instruction &I) {
3967 assert(dyn_castGetElementPtr(GEPLHS) && "LHS is not a getelementptr!");
Chris Lattner81e84172005-01-13 22:25:21 +00003968
3969 if (CastInst *CI = dyn_cast<CastInst>(RHS))
3970 if (isa<PointerType>(CI->getOperand(0)->getType()))
3971 RHS = CI->getOperand(0);
3972
Chris Lattner0798af32005-01-13 20:14:25 +00003973 Value *PtrBase = GEPLHS->getOperand(0);
3974 if (PtrBase == RHS) {
3975 // As an optimization, we don't actually have to compute the actual value of
3976 // OFFSET if this is a seteq or setne comparison, just return whether each
3977 // index is zero or not.
Chris Lattner81e84172005-01-13 22:25:21 +00003978 if (Cond == Instruction::SetEQ || Cond == Instruction::SetNE) {
3979 Instruction *InVal = 0;
Chris Lattnercd517ff2005-01-28 19:32:01 +00003980 gep_type_iterator GTI = gep_type_begin(GEPLHS);
3981 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i, ++GTI) {
Chris Lattner81e84172005-01-13 22:25:21 +00003982 bool EmitIt = true;
3983 if (Constant *C = dyn_cast<Constant>(GEPLHS->getOperand(i))) {
3984 if (isa<UndefValue>(C)) // undef index -> undef.
3985 return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
3986 if (C->isNullValue())
3987 EmitIt = false;
Chris Lattnercd517ff2005-01-28 19:32:01 +00003988 else if (TD->getTypeSize(GTI.getIndexedType()) == 0) {
3989 EmitIt = false; // This is indexing into a zero sized array?
Misha Brukmanb1c93172005-04-21 23:48:37 +00003990 } else if (isa<ConstantInt>(C))
Chris Lattner81e84172005-01-13 22:25:21 +00003991 return ReplaceInstUsesWith(I, // No comparison is needed here.
3992 ConstantBool::get(Cond == Instruction::SetNE));
3993 }
3994
3995 if (EmitIt) {
Misha Brukmanb1c93172005-04-21 23:48:37 +00003996 Instruction *Comp =
Chris Lattner81e84172005-01-13 22:25:21 +00003997 new SetCondInst(Cond, GEPLHS->getOperand(i),
3998 Constant::getNullValue(GEPLHS->getOperand(i)->getType()));
3999 if (InVal == 0)
4000 InVal = Comp;
4001 else {
4002 InVal = InsertNewInstBefore(InVal, I);
4003 InsertNewInstBefore(Comp, I);
4004 if (Cond == Instruction::SetNE) // True if any are unequal
4005 InVal = BinaryOperator::createOr(InVal, Comp);
4006 else // True if all are equal
4007 InVal = BinaryOperator::createAnd(InVal, Comp);
4008 }
4009 }
4010 }
4011
4012 if (InVal)
4013 return InVal;
4014 else
4015 ReplaceInstUsesWith(I, // No comparison is needed here, all indexes = 0
4016 ConstantBool::get(Cond == Instruction::SetEQ));
4017 }
Chris Lattner0798af32005-01-13 20:14:25 +00004018
4019 // Only lower this if the setcc is the only user of the GEP or if we expect
4020 // the result to fold to a constant!
4021 if (isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) {
4022 // ((gep Ptr, OFFSET) cmp Ptr) ---> (OFFSET cmp 0).
4023 Value *Offset = EmitGEPOffset(GEPLHS, I, *this);
4024 return new SetCondInst(Cond, Offset,
4025 Constant::getNullValue(Offset->getType()));
4026 }
4027 } else if (User *GEPRHS = dyn_castGetElementPtr(RHS)) {
Chris Lattnera21bf8d2005-04-25 20:17:30 +00004028 // If the base pointers are different, but the indices are the same, just
4029 // compare the base pointer.
4030 if (PtrBase != GEPRHS->getOperand(0)) {
4031 bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00004032 IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
Chris Lattnerbd43b9d2005-04-26 14:40:41 +00004033 GEPRHS->getOperand(0)->getType();
Chris Lattnera21bf8d2005-04-25 20:17:30 +00004034 if (IndicesTheSame)
4035 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
4036 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
4037 IndicesTheSame = false;
4038 break;
4039 }
4040
4041 // If all indices are the same, just compare the base pointers.
4042 if (IndicesTheSame)
4043 return new SetCondInst(Cond, GEPLHS->getOperand(0),
4044 GEPRHS->getOperand(0));
4045
4046 // Otherwise, the base pointers are different and the indices are
4047 // different, bail out.
Chris Lattner0798af32005-01-13 20:14:25 +00004048 return 0;
Chris Lattnera21bf8d2005-04-25 20:17:30 +00004049 }
Chris Lattner0798af32005-01-13 20:14:25 +00004050
Chris Lattner81e84172005-01-13 22:25:21 +00004051 // If one of the GEPs has all zero indices, recurse.
4052 bool AllZeros = true;
4053 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
4054 if (!isa<Constant>(GEPLHS->getOperand(i)) ||
4055 !cast<Constant>(GEPLHS->getOperand(i))->isNullValue()) {
4056 AllZeros = false;
4057 break;
4058 }
4059 if (AllZeros)
4060 return FoldGEPSetCC(GEPRHS, GEPLHS->getOperand(0),
4061 SetCondInst::getSwappedCondition(Cond), I);
Chris Lattner4fa89822005-01-14 00:20:05 +00004062
4063 // If the other GEP has all zero indices, recurse.
Chris Lattner81e84172005-01-13 22:25:21 +00004064 AllZeros = true;
4065 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
4066 if (!isa<Constant>(GEPRHS->getOperand(i)) ||
4067 !cast<Constant>(GEPRHS->getOperand(i))->isNullValue()) {
4068 AllZeros = false;
4069 break;
4070 }
4071 if (AllZeros)
4072 return FoldGEPSetCC(GEPLHS, GEPRHS->getOperand(0), Cond, I);
4073
Chris Lattner4fa89822005-01-14 00:20:05 +00004074 if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
4075 // If the GEPs only differ by one index, compare it.
4076 unsigned NumDifferences = 0; // Keep track of # differences.
4077 unsigned DiffOperand = 0; // The operand that differs.
4078 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
4079 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
Chris Lattnerd1f46d32005-04-24 06:59:08 +00004080 if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
4081 GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
Chris Lattnerfc4429e2005-01-21 23:06:49 +00004082 // Irreconcilable differences.
Chris Lattner4fa89822005-01-14 00:20:05 +00004083 NumDifferences = 2;
4084 break;
4085 } else {
4086 if (NumDifferences++) break;
4087 DiffOperand = i;
4088 }
4089 }
4090
4091 if (NumDifferences == 0) // SAME GEP?
4092 return ReplaceInstUsesWith(I, // No comparison is needed here.
4093 ConstantBool::get(Cond == Instruction::SetEQ));
4094 else if (NumDifferences == 1) {
Chris Lattnerfc4429e2005-01-21 23:06:49 +00004095 Value *LHSV = GEPLHS->getOperand(DiffOperand);
4096 Value *RHSV = GEPRHS->getOperand(DiffOperand);
Chris Lattner247aef82005-07-18 23:07:33 +00004097
4098 // Convert the operands to signed values to make sure to perform a
4099 // signed comparison.
4100 const Type *NewTy = LHSV->getType()->getSignedVersion();
4101 if (LHSV->getType() != NewTy)
Reid Spencer13bc5d72006-12-12 09:18:51 +00004102 LHSV = InsertCastBefore(Instruction::BitCast, LHSV, NewTy, I);
Chris Lattner247aef82005-07-18 23:07:33 +00004103 if (RHSV->getType() != NewTy)
Reid Spencer13bc5d72006-12-12 09:18:51 +00004104 RHSV = InsertCastBefore(Instruction::BitCast, RHSV, NewTy, I);
Chris Lattner247aef82005-07-18 23:07:33 +00004105 return new SetCondInst(Cond, LHSV, RHSV);
Chris Lattner4fa89822005-01-14 00:20:05 +00004106 }
4107 }
4108
Chris Lattner0798af32005-01-13 20:14:25 +00004109 // Only lower this if the setcc is the only user of the GEP or if we expect
4110 // the result to fold to a constant!
4111 if ((isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
4112 (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
4113 // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2) ---> (OFFSET1 cmp OFFSET2)
4114 Value *L = EmitGEPOffset(GEPLHS, I, *this);
4115 Value *R = EmitGEPOffset(GEPRHS, I, *this);
4116 return new SetCondInst(Cond, L, R);
4117 }
4118 }
4119 return 0;
4120}
4121
4122
Chris Lattnerd1f46d32005-04-24 06:59:08 +00004123Instruction *InstCombiner::visitSetCondInst(SetCondInst &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00004124 bool Changed = SimplifyCommutative(I);
Chris Lattner6d14f2a2002-08-09 23:47:40 +00004125 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
4126 const Type *Ty = Op0->getType();
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00004127
4128 // setcc X, X
Chris Lattner6d14f2a2002-08-09 23:47:40 +00004129 if (Op0 == Op1)
4130 return ReplaceInstUsesWith(I, ConstantBool::get(isTrueWhenEqual(I)));
Chris Lattner1fc23f32002-05-09 20:11:54 +00004131
Chris Lattner81a7a232004-10-16 18:11:37 +00004132 if (isa<UndefValue>(Op1)) // X setcc undef -> undef
4133 return ReplaceInstUsesWith(I, UndefValue::get(Type::BoolTy));
4134
Chris Lattner15ff1e12004-11-14 07:33:16 +00004135 // setcc <global/alloca*/null>, <global/alloca*/null> - Global/Stack value
4136 // addresses never equal each other! We already know that Op0 != Op1.
Misha Brukmanb1c93172005-04-21 23:48:37 +00004137 if ((isa<GlobalValue>(Op0) || isa<AllocaInst>(Op0) ||
4138 isa<ConstantPointerNull>(Op0)) &&
4139 (isa<GlobalValue>(Op1) || isa<AllocaInst>(Op1) ||
Chris Lattner15ff1e12004-11-14 07:33:16 +00004140 isa<ConstantPointerNull>(Op1)))
Chris Lattner6d14f2a2002-08-09 23:47:40 +00004141 return ReplaceInstUsesWith(I, ConstantBool::get(!isTrueWhenEqual(I)));
4142
4143 // setcc's with boolean values can always be turned into bitwise operations
4144 if (Ty == Type::BoolTy) {
Chris Lattner4456da62004-08-11 00:50:51 +00004145 switch (I.getOpcode()) {
4146 default: assert(0 && "Invalid setcc instruction!");
4147 case Instruction::SetEQ: { // seteq bool %A, %B -> ~(A^B)
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00004148 Instruction *Xor = BinaryOperator::createXor(Op0, Op1, I.getName()+"tmp");
Chris Lattner6d14f2a2002-08-09 23:47:40 +00004149 InsertNewInstBefore(Xor, I);
Chris Lattner16930792003-11-03 04:25:02 +00004150 return BinaryOperator::createNot(Xor);
Chris Lattner6d14f2a2002-08-09 23:47:40 +00004151 }
Chris Lattner4456da62004-08-11 00:50:51 +00004152 case Instruction::SetNE:
4153 return BinaryOperator::createXor(Op0, Op1);
Chris Lattner6d14f2a2002-08-09 23:47:40 +00004154
Chris Lattner4456da62004-08-11 00:50:51 +00004155 case Instruction::SetGT:
4156 std::swap(Op0, Op1); // Change setgt -> setlt
4157 // FALL THROUGH
4158 case Instruction::SetLT: { // setlt bool A, B -> ~X & Y
4159 Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
4160 InsertNewInstBefore(Not, I);
4161 return BinaryOperator::createAnd(Not, Op1);
4162 }
4163 case Instruction::SetGE:
Chris Lattner6d14f2a2002-08-09 23:47:40 +00004164 std::swap(Op0, Op1); // Change setge -> setle
Chris Lattner4456da62004-08-11 00:50:51 +00004165 // FALL THROUGH
4166 case Instruction::SetLE: { // setle bool %A, %B -> ~A | B
4167 Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
4168 InsertNewInstBefore(Not, I);
4169 return BinaryOperator::createOr(Not, Op1);
4170 }
4171 }
Chris Lattner6d14f2a2002-08-09 23:47:40 +00004172 }
4173
Chris Lattner2dd01742004-06-09 04:24:29 +00004174 // See if we are doing a comparison between a constant and an instruction that
4175 // can be folded into the comparison.
Chris Lattner6d14f2a2002-08-09 23:47:40 +00004176 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner6862fbd2004-09-29 17:40:11 +00004177 // Check to see if we are comparing against the minimum or maximum value...
Reid Spencer4ae56f32006-12-06 20:39:57 +00004178 if (CI->isMinValue(CI->getType()->isSigned())) {
Chris Lattner6862fbd2004-09-29 17:40:11 +00004179 if (I.getOpcode() == Instruction::SetLT) // A < MIN -> FALSE
Chris Lattner6ab03f62006-09-28 23:35:22 +00004180 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
Chris Lattner6862fbd2004-09-29 17:40:11 +00004181 if (I.getOpcode() == Instruction::SetGE) // A >= MIN -> TRUE
Chris Lattner6ab03f62006-09-28 23:35:22 +00004182 return ReplaceInstUsesWith(I, ConstantBool::getTrue());
Chris Lattner6862fbd2004-09-29 17:40:11 +00004183 if (I.getOpcode() == Instruction::SetLE) // A <= MIN -> A == MIN
4184 return BinaryOperator::createSetEQ(Op0, Op1);
4185 if (I.getOpcode() == Instruction::SetGT) // A > MIN -> A != MIN
4186 return BinaryOperator::createSetNE(Op0, Op1);
4187
Reid Spencer4ae56f32006-12-06 20:39:57 +00004188 } else if (CI->isMaxValue(CI->getType()->isSigned())) {
Chris Lattner6862fbd2004-09-29 17:40:11 +00004189 if (I.getOpcode() == Instruction::SetGT) // A > MAX -> FALSE
Chris Lattner6ab03f62006-09-28 23:35:22 +00004190 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
Chris Lattner6862fbd2004-09-29 17:40:11 +00004191 if (I.getOpcode() == Instruction::SetLE) // A <= MAX -> TRUE
Chris Lattner6ab03f62006-09-28 23:35:22 +00004192 return ReplaceInstUsesWith(I, ConstantBool::getTrue());
Chris Lattner6862fbd2004-09-29 17:40:11 +00004193 if (I.getOpcode() == Instruction::SetGE) // A >= MAX -> A == MAX
4194 return BinaryOperator::createSetEQ(Op0, Op1);
4195 if (I.getOpcode() == Instruction::SetLT) // A < MAX -> A != MAX
4196 return BinaryOperator::createSetNE(Op0, Op1);
4197
4198 // Comparing against a value really close to min or max?
4199 } else if (isMinValuePlusOne(CI)) {
4200 if (I.getOpcode() == Instruction::SetLT) // A < MIN+1 -> A == MIN
4201 return BinaryOperator::createSetEQ(Op0, SubOne(CI));
4202 if (I.getOpcode() == Instruction::SetGE) // A >= MIN-1 -> A != MIN
4203 return BinaryOperator::createSetNE(Op0, SubOne(CI));
4204
4205 } else if (isMaxValueMinusOne(CI)) {
4206 if (I.getOpcode() == Instruction::SetGT) // A > MAX-1 -> A == MAX
4207 return BinaryOperator::createSetEQ(Op0, AddOne(CI));
4208 if (I.getOpcode() == Instruction::SetLE) // A <= MAX-1 -> A != MAX
4209 return BinaryOperator::createSetNE(Op0, AddOne(CI));
4210 }
4211
4212 // If we still have a setle or setge instruction, turn it into the
4213 // appropriate setlt or setgt instruction. Since the border cases have
4214 // already been handled above, this requires little checking.
4215 //
4216 if (I.getOpcode() == Instruction::SetLE)
4217 return BinaryOperator::createSetLT(Op0, AddOne(CI));
4218 if (I.getOpcode() == Instruction::SetGE)
4219 return BinaryOperator::createSetGT(Op0, SubOne(CI));
4220
Chris Lattneree0f2802006-02-12 02:07:56 +00004221
4222 // See if we can fold the comparison based on bits known to be zero or one
4223 // in the input.
4224 uint64_t KnownZero, KnownOne;
4225 if (SimplifyDemandedBits(Op0, Ty->getIntegralTypeMask(),
4226 KnownZero, KnownOne, 0))
4227 return &I;
4228
4229 // Given the known and unknown bits, compute a range that the LHS could be
4230 // in.
4231 if (KnownOne | KnownZero) {
4232 if (Ty->isUnsigned()) { // Unsigned comparison.
4233 uint64_t Min, Max;
4234 uint64_t RHSVal = CI->getZExtValue();
4235 ComputeUnsignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne,
4236 Min, Max);
4237 switch (I.getOpcode()) { // LE/GE have been folded already.
4238 default: assert(0 && "Unknown setcc opcode!");
4239 case Instruction::SetEQ:
4240 if (Max < RHSVal || Min > RHSVal)
Chris Lattner6ab03f62006-09-28 23:35:22 +00004241 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
Chris Lattneree0f2802006-02-12 02:07:56 +00004242 break;
4243 case Instruction::SetNE:
4244 if (Max < RHSVal || Min > RHSVal)
Chris Lattner6ab03f62006-09-28 23:35:22 +00004245 return ReplaceInstUsesWith(I, ConstantBool::getTrue());
Chris Lattneree0f2802006-02-12 02:07:56 +00004246 break;
4247 case Instruction::SetLT:
Chris Lattner6ab03f62006-09-28 23:35:22 +00004248 if (Max < RHSVal)
4249 return ReplaceInstUsesWith(I, ConstantBool::getTrue());
4250 if (Min > RHSVal)
4251 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
Chris Lattneree0f2802006-02-12 02:07:56 +00004252 break;
4253 case Instruction::SetGT:
Chris Lattner6ab03f62006-09-28 23:35:22 +00004254 if (Min > RHSVal)
4255 return ReplaceInstUsesWith(I, ConstantBool::getTrue());
4256 if (Max < RHSVal)
4257 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
Chris Lattneree0f2802006-02-12 02:07:56 +00004258 break;
4259 }
4260 } else { // Signed comparison.
4261 int64_t Min, Max;
4262 int64_t RHSVal = CI->getSExtValue();
4263 ComputeSignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne,
4264 Min, Max);
4265 switch (I.getOpcode()) { // LE/GE have been folded already.
4266 default: assert(0 && "Unknown setcc opcode!");
4267 case Instruction::SetEQ:
4268 if (Max < RHSVal || Min > RHSVal)
Chris Lattner6ab03f62006-09-28 23:35:22 +00004269 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
Chris Lattneree0f2802006-02-12 02:07:56 +00004270 break;
4271 case Instruction::SetNE:
4272 if (Max < RHSVal || Min > RHSVal)
Chris Lattner6ab03f62006-09-28 23:35:22 +00004273 return ReplaceInstUsesWith(I, ConstantBool::getTrue());
Chris Lattneree0f2802006-02-12 02:07:56 +00004274 break;
4275 case Instruction::SetLT:
Chris Lattner6ab03f62006-09-28 23:35:22 +00004276 if (Max < RHSVal)
4277 return ReplaceInstUsesWith(I, ConstantBool::getTrue());
4278 if (Min > RHSVal)
4279 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
Chris Lattneree0f2802006-02-12 02:07:56 +00004280 break;
4281 case Instruction::SetGT:
Chris Lattner6ab03f62006-09-28 23:35:22 +00004282 if (Min > RHSVal)
4283 return ReplaceInstUsesWith(I, ConstantBool::getTrue());
4284 if (Max < RHSVal)
4285 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
Chris Lattneree0f2802006-02-12 02:07:56 +00004286 break;
4287 }
4288 }
4289 }
4290
Reid Spencer7e80b0b2006-10-26 06:15:43 +00004291 // Since the RHS is a constantInt (CI), if the left hand side is an
4292 // instruction, see if that instruction also has constants so that the
4293 // instruction can be folded into the setcc
Chris Lattnere1e10e12004-05-25 06:32:08 +00004294 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00004295 switch (LHSI->getOpcode()) {
4296 case Instruction::And:
4297 if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
4298 LHSI->getOperand(0)->hasOneUse()) {
Chris Lattner4922a0e2006-09-18 05:27:43 +00004299 ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
4300
4301 // If an operand is an AND of a truncating cast, we can widen the
4302 // and/compare to be the input width without changing the value
4303 // produced, eliminating a cast.
4304 if (CastInst *Cast = dyn_cast<CastInst>(LHSI->getOperand(0))) {
4305 // We can do this transformation if either the AND constant does not
4306 // have its sign bit set or if it is an equality comparison.
4307 // Extending a relational comparison when we're checking the sign
4308 // bit would not work.
Reid Spencer6c38f0b2006-11-27 01:05:10 +00004309 if (Cast->hasOneUse() && isa<TruncInst>(Cast) &&
Chris Lattner4922a0e2006-09-18 05:27:43 +00004310 (I.isEquality() ||
4311 (AndCST->getZExtValue() == (uint64_t)AndCST->getSExtValue()) &&
4312 (CI->getZExtValue() == (uint64_t)CI->getSExtValue()))) {
4313 ConstantInt *NewCST;
4314 ConstantInt *NewCI;
4315 if (Cast->getOperand(0)->getType()->isSigned()) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00004316 NewCST = ConstantInt::get(Cast->getOperand(0)->getType(),
Chris Lattner4922a0e2006-09-18 05:27:43 +00004317 AndCST->getZExtValue());
Reid Spencere0fc4df2006-10-20 07:07:24 +00004318 NewCI = ConstantInt::get(Cast->getOperand(0)->getType(),
Chris Lattner4922a0e2006-09-18 05:27:43 +00004319 CI->getZExtValue());
4320 } else {
Reid Spencere0fc4df2006-10-20 07:07:24 +00004321 NewCST = ConstantInt::get(Cast->getOperand(0)->getType(),
Chris Lattner4922a0e2006-09-18 05:27:43 +00004322 AndCST->getZExtValue());
Reid Spencere0fc4df2006-10-20 07:07:24 +00004323 NewCI = ConstantInt::get(Cast->getOperand(0)->getType(),
Chris Lattner4922a0e2006-09-18 05:27:43 +00004324 CI->getZExtValue());
4325 }
4326 Instruction *NewAnd =
4327 BinaryOperator::createAnd(Cast->getOperand(0), NewCST,
4328 LHSI->getName());
4329 InsertNewInstBefore(NewAnd, I);
4330 return new SetCondInst(I.getOpcode(), NewAnd, NewCI);
4331 }
4332 }
4333
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00004334 // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
4335 // could exist), turn it into (X & (C2 << C1)) != (C3 << C1). This
4336 // happens a LOT in code produced by the C front-end, for bitfield
4337 // access.
4338 ShiftInst *Shift = dyn_cast<ShiftInst>(LHSI->getOperand(0));
Chris Lattneree0f2802006-02-12 02:07:56 +00004339
4340 // Check to see if there is a noop-cast between the shift and the and.
4341 if (!Shift) {
4342 if (CastInst *CI = dyn_cast<CastInst>(LHSI->getOperand(0)))
4343 if (CI->getOperand(0)->getType()->isIntegral() &&
4344 CI->getOperand(0)->getType()->getPrimitiveSizeInBits() ==
4345 CI->getType()->getPrimitiveSizeInBits())
4346 Shift = dyn_cast<ShiftInst>(CI->getOperand(0));
4347 }
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004348
Reid Spencere0fc4df2006-10-20 07:07:24 +00004349 ConstantInt *ShAmt;
4350 ShAmt = Shift ? dyn_cast<ConstantInt>(Shift->getOperand(1)) : 0;
Chris Lattneree0f2802006-02-12 02:07:56 +00004351 const Type *Ty = Shift ? Shift->getType() : 0; // Type of the shift.
4352 const Type *AndTy = AndCST->getType(); // Type of the and.
Misha Brukmanb1c93172005-04-21 23:48:37 +00004353
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00004354 // We can fold this as long as we can't shift unknown bits
4355 // into the mask. This can only happen with signed shift
4356 // rights, as they sign-extend.
4357 if (ShAmt) {
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004358 bool CanFold = Shift->isLogicalShift();
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00004359 if (!CanFold) {
4360 // To test for the bad case of the signed shr, see if any
4361 // of the bits shifted in could be tested after the mask.
Reid Spencere0fc4df2006-10-20 07:07:24 +00004362 int ShAmtVal = Ty->getPrimitiveSizeInBits()-ShAmt->getZExtValue();
Chris Lattnerc53cb9d2005-06-17 01:29:28 +00004363 if (ShAmtVal < 0) ShAmtVal = 0; // Out of range shift.
4364
Reid Spencere0fc4df2006-10-20 07:07:24 +00004365 Constant *OShAmt = ConstantInt::get(Type::UByteTy, ShAmtVal);
Misha Brukmanb1c93172005-04-21 23:48:37 +00004366 Constant *ShVal =
Chris Lattneree0f2802006-02-12 02:07:56 +00004367 ConstantExpr::getShl(ConstantInt::getAllOnesValue(AndTy),
4368 OShAmt);
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00004369 if (ConstantExpr::getAnd(ShVal, AndCST)->isNullValue())
4370 CanFold = true;
4371 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00004372
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00004373 if (CanFold) {
Chris Lattner6afc02f2004-09-28 17:54:07 +00004374 Constant *NewCst;
4375 if (Shift->getOpcode() == Instruction::Shl)
Reid Spencerfdff9382006-11-08 06:47:33 +00004376 NewCst = ConstantExpr::getLShr(CI, ShAmt);
Chris Lattner6afc02f2004-09-28 17:54:07 +00004377 else
4378 NewCst = ConstantExpr::getShl(CI, ShAmt);
Chris Lattnerbfff18a2004-09-27 19:29:18 +00004379
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00004380 // Check to see if we are shifting out any of the bits being
4381 // compared.
4382 if (ConstantExpr::get(Shift->getOpcode(), NewCst, ShAmt) != CI){
4383 // If we shifted bits out, the fold is not going to work out.
4384 // As a special case, check to see if this means that the
4385 // result is always true or false now.
4386 if (I.getOpcode() == Instruction::SetEQ)
Chris Lattner6ab03f62006-09-28 23:35:22 +00004387 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00004388 if (I.getOpcode() == Instruction::SetNE)
Chris Lattner6ab03f62006-09-28 23:35:22 +00004389 return ReplaceInstUsesWith(I, ConstantBool::getTrue());
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00004390 } else {
4391 I.setOperand(1, NewCst);
Chris Lattner6afc02f2004-09-28 17:54:07 +00004392 Constant *NewAndCST;
4393 if (Shift->getOpcode() == Instruction::Shl)
Reid Spencerfdff9382006-11-08 06:47:33 +00004394 NewAndCST = ConstantExpr::getLShr(AndCST, ShAmt);
Chris Lattner6afc02f2004-09-28 17:54:07 +00004395 else
4396 NewAndCST = ConstantExpr::getShl(AndCST, ShAmt);
4397 LHSI->setOperand(1, NewAndCST);
Chris Lattneree0f2802006-02-12 02:07:56 +00004398 if (AndTy == Ty)
4399 LHSI->setOperand(0, Shift->getOperand(0));
4400 else {
Reid Spencer13bc5d72006-12-12 09:18:51 +00004401 Value *NewCast = InsertCastBefore(Instruction::BitCast,
4402 Shift->getOperand(0), AndTy,
Chris Lattneree0f2802006-02-12 02:07:56 +00004403 *Shift);
4404 LHSI->setOperand(0, NewCast);
4405 }
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00004406 WorkList.push_back(Shift); // Shift is dead.
4407 AddUsesToWorkList(I);
4408 return &I;
Chris Lattner1638de42004-07-21 19:50:44 +00004409 }
4410 }
Chris Lattner35167c32004-06-09 07:59:58 +00004411 }
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004412
4413 // Turn ((X >> Y) & C) == 0 into (X & (C << Y)) == 0. The later is
4414 // preferable because it allows the C<<Y expression to be hoisted out
4415 // of a loop if Y is invariant and X is not.
4416 if (Shift && Shift->hasOneUse() && CI->isNullValue() &&
Chris Lattnerde077922006-09-18 18:27:05 +00004417 I.isEquality() && !Shift->isArithmeticShift() &&
4418 isa<Instruction>(Shift->getOperand(0))) {
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004419 // Compute C << Y.
4420 Value *NS;
Reid Spencerfdff9382006-11-08 06:47:33 +00004421 if (Shift->getOpcode() == Instruction::LShr) {
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004422 NS = new ShiftInst(Instruction::Shl, AndCST, Shift->getOperand(1),
4423 "tmp");
4424 } else {
4425 // Make sure we insert a logical shift.
Chris Lattner4922a0e2006-09-18 05:27:43 +00004426 Constant *NewAndCST = AndCST;
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004427 if (AndCST->getType()->isSigned())
Reid Spencer13bc5d72006-12-12 09:18:51 +00004428 NewAndCST = ConstantExpr::getBitCast(AndCST,
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004429 AndCST->getType()->getUnsignedVersion());
Reid Spencerfdff9382006-11-08 06:47:33 +00004430 NS = new ShiftInst(Instruction::LShr, NewAndCST,
Chris Lattner4922a0e2006-09-18 05:27:43 +00004431 Shift->getOperand(1), "tmp");
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004432 }
4433 InsertNewInstBefore(cast<Instruction>(NS), I);
4434
4435 // If C's sign doesn't agree with the and, insert a cast now.
4436 if (NS->getType() != LHSI->getType())
Reid Spencer13bc5d72006-12-12 09:18:51 +00004437 NS = InsertCastBefore(Instruction::BitCast, NS, LHSI->getType(),
4438 I);
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004439
4440 Value *ShiftOp = Shift->getOperand(0);
4441 if (ShiftOp->getType() != LHSI->getType())
Reid Spencer13bc5d72006-12-12 09:18:51 +00004442 ShiftOp = InsertCastBefore(Instruction::BitCast, ShiftOp,
4443 LHSI->getType(), I);
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004444
4445 // Compute X & (C << Y).
4446 Instruction *NewAnd =
4447 BinaryOperator::createAnd(ShiftOp, NS, LHSI->getName());
4448 InsertNewInstBefore(NewAnd, I);
4449
4450 I.setOperand(0, NewAnd);
4451 return &I;
4452 }
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00004453 }
4454 break;
Chris Lattnerbfff18a2004-09-27 19:29:18 +00004455
Chris Lattner272d5ca2004-09-28 18:22:15 +00004456 case Instruction::Shl: // (setcc (shl X, ShAmt), CI)
Reid Spencere0fc4df2006-10-20 07:07:24 +00004457 if (ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004458 if (I.isEquality()) {
Chris Lattner19b57f52005-06-15 20:53:31 +00004459 unsigned TypeBits = CI->getType()->getPrimitiveSizeInBits();
4460
4461 // Check that the shift amount is in range. If not, don't perform
4462 // undefined shifts. When the shift is visited it will be
4463 // simplified.
Reid Spencere0fc4df2006-10-20 07:07:24 +00004464 if (ShAmt->getZExtValue() >= TypeBits)
Chris Lattner19b57f52005-06-15 20:53:31 +00004465 break;
4466
Chris Lattner272d5ca2004-09-28 18:22:15 +00004467 // If we are comparing against bits always shifted out, the
4468 // comparison cannot succeed.
Misha Brukmanb1c93172005-04-21 23:48:37 +00004469 Constant *Comp =
Reid Spencerfdff9382006-11-08 06:47:33 +00004470 ConstantExpr::getShl(ConstantExpr::getLShr(CI, ShAmt), ShAmt);
Chris Lattner272d5ca2004-09-28 18:22:15 +00004471 if (Comp != CI) {// Comparing against a bit that we know is zero.
4472 bool IsSetNE = I.getOpcode() == Instruction::SetNE;
4473 Constant *Cst = ConstantBool::get(IsSetNE);
4474 return ReplaceInstUsesWith(I, Cst);
4475 }
4476
4477 if (LHSI->hasOneUse()) {
4478 // Otherwise strength reduce the shift into an and.
Reid Spencere0fc4df2006-10-20 07:07:24 +00004479 unsigned ShAmtVal = (unsigned)ShAmt->getZExtValue();
Chris Lattner272d5ca2004-09-28 18:22:15 +00004480 uint64_t Val = (1ULL << (TypeBits-ShAmtVal))-1;
4481
4482 Constant *Mask;
4483 if (CI->getType()->isUnsigned()) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00004484 Mask = ConstantInt::get(CI->getType(), Val);
Chris Lattner272d5ca2004-09-28 18:22:15 +00004485 } else if (ShAmtVal != 0) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00004486 Mask = ConstantInt::get(CI->getType(), Val);
Chris Lattner272d5ca2004-09-28 18:22:15 +00004487 } else {
4488 Mask = ConstantInt::getAllOnesValue(CI->getType());
4489 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00004490
Chris Lattner272d5ca2004-09-28 18:22:15 +00004491 Instruction *AndI =
4492 BinaryOperator::createAnd(LHSI->getOperand(0),
4493 Mask, LHSI->getName()+".mask");
4494 Value *And = InsertNewInstBefore(AndI, I);
4495 return new SetCondInst(I.getOpcode(), And,
Reid Spencerfdff9382006-11-08 06:47:33 +00004496 ConstantExpr::getLShr(CI, ShAmt));
Chris Lattner272d5ca2004-09-28 18:22:15 +00004497 }
4498 }
Chris Lattner272d5ca2004-09-28 18:22:15 +00004499 }
4500 break;
4501
Reid Spencerfdff9382006-11-08 06:47:33 +00004502 case Instruction::LShr: // (setcc (shr X, ShAmt), CI)
4503 case Instruction::AShr:
Reid Spencere0fc4df2006-10-20 07:07:24 +00004504 if (ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004505 if (I.isEquality()) {
Chris Lattner19b57f52005-06-15 20:53:31 +00004506 // Check that the shift amount is in range. If not, don't perform
4507 // undefined shifts. When the shift is visited it will be
4508 // simplified.
Chris Lattner104002b2005-06-16 01:52:07 +00004509 unsigned TypeBits = CI->getType()->getPrimitiveSizeInBits();
Reid Spencere0fc4df2006-10-20 07:07:24 +00004510 if (ShAmt->getZExtValue() >= TypeBits)
Chris Lattner19b57f52005-06-15 20:53:31 +00004511 break;
4512
Chris Lattner1023b872004-09-27 16:18:50 +00004513 // If we are comparing against bits always shifted out, the
4514 // comparison cannot succeed.
Reid Spencerfdff9382006-11-08 06:47:33 +00004515 Constant *Comp;
4516 if (CI->getType()->isUnsigned())
4517 Comp = ConstantExpr::getLShr(ConstantExpr::getShl(CI, ShAmt),
4518 ShAmt);
4519 else
4520 Comp = ConstantExpr::getAShr(ConstantExpr::getShl(CI, ShAmt),
4521 ShAmt);
Misha Brukmanb1c93172005-04-21 23:48:37 +00004522
Chris Lattner1023b872004-09-27 16:18:50 +00004523 if (Comp != CI) {// Comparing against a bit that we know is zero.
4524 bool IsSetNE = I.getOpcode() == Instruction::SetNE;
4525 Constant *Cst = ConstantBool::get(IsSetNE);
4526 return ReplaceInstUsesWith(I, Cst);
4527 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00004528
Chris Lattner1023b872004-09-27 16:18:50 +00004529 if (LHSI->hasOneUse() || CI->isNullValue()) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00004530 unsigned ShAmtVal = (unsigned)ShAmt->getZExtValue();
Chris Lattner272d5ca2004-09-28 18:22:15 +00004531
Chris Lattner1023b872004-09-27 16:18:50 +00004532 // Otherwise strength reduce the shift into an and.
4533 uint64_t Val = ~0ULL; // All ones.
4534 Val <<= ShAmtVal; // Shift over to the right spot.
4535
4536 Constant *Mask;
4537 if (CI->getType()->isUnsigned()) {
Chris Lattner2f1457f2005-04-24 17:46:05 +00004538 Val &= ~0ULL >> (64-TypeBits);
Reid Spencere0fc4df2006-10-20 07:07:24 +00004539 Mask = ConstantInt::get(CI->getType(), Val);
Chris Lattner1023b872004-09-27 16:18:50 +00004540 } else {
Reid Spencere0fc4df2006-10-20 07:07:24 +00004541 Mask = ConstantInt::get(CI->getType(), Val);
Chris Lattner1023b872004-09-27 16:18:50 +00004542 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00004543
Chris Lattner1023b872004-09-27 16:18:50 +00004544 Instruction *AndI =
4545 BinaryOperator::createAnd(LHSI->getOperand(0),
4546 Mask, LHSI->getName()+".mask");
4547 Value *And = InsertNewInstBefore(AndI, I);
4548 return new SetCondInst(I.getOpcode(), And,
4549 ConstantExpr::getShl(CI, ShAmt));
4550 }
Chris Lattner1023b872004-09-27 16:18:50 +00004551 }
4552 }
4553 break;
Chris Lattner7e794272004-09-24 15:21:34 +00004554
Reid Spencer7e80b0b2006-10-26 06:15:43 +00004555 case Instruction::SDiv:
4556 case Instruction::UDiv:
4557 // Fold: setcc ([us]div X, C1), C2 -> range test
4558 // Fold this div into the comparison, producing a range check.
4559 // Determine, based on the divide type, what the range is being
4560 // checked. If there is an overflow on the low or high side, remember
4561 // it, otherwise compute the range [low, hi) bounding the new value.
4562 // See: InsertRangeTest above for the kinds of replacements possible.
Chris Lattner6862fbd2004-09-29 17:40:11 +00004563 if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
Reid Spencer7e80b0b2006-10-26 06:15:43 +00004564 // FIXME: If the operand types don't match the type of the divide
4565 // then don't attempt this transform. The code below doesn't have the
4566 // logic to deal with a signed divide and an unsigned compare (and
4567 // vice versa). This is because (x /s C1) <s C2 produces different
4568 // results than (x /s C1) <u C2 or (x /u C1) <s C2 or even
4569 // (x /u C1) <u C2. Simply casting the operands and result won't
4570 // work. :( The if statement below tests that condition and bails
4571 // if it finds it.
Reid Spencer6c38f0b2006-11-27 01:05:10 +00004572 const Type *DivRHSTy = DivRHS->getType();
Reid Spencer7e80b0b2006-10-26 06:15:43 +00004573 unsigned DivOpCode = LHSI->getOpcode();
4574 if (I.isEquality() &&
4575 ((DivOpCode == Instruction::SDiv && DivRHSTy->isUnsigned()) ||
4576 (DivOpCode == Instruction::UDiv && DivRHSTy->isSigned())))
4577 break;
4578
4579 // Initialize the variables that will indicate the nature of the
4580 // range check.
4581 bool LoOverflow = false, HiOverflow = false;
Chris Lattner6862fbd2004-09-29 17:40:11 +00004582 ConstantInt *LoBound = 0, *HiBound = 0;
4583
Reid Spencer7e80b0b2006-10-26 06:15:43 +00004584 // Compute Prod = CI * DivRHS. We are essentially solving an equation
4585 // of form X/C1=C2. We solve for X by multiplying C1 (DivRHS) and
4586 // C2 (CI). By solving for X we can turn this into a range check
4587 // instead of computing a divide.
4588 ConstantInt *Prod =
4589 cast<ConstantInt>(ConstantExpr::getMul(CI, DivRHS));
Chris Lattner6862fbd2004-09-29 17:40:11 +00004590
Reid Spencer7e80b0b2006-10-26 06:15:43 +00004591 // Determine if the product overflows by seeing if the product is
4592 // not equal to the divide. Make sure we do the same kind of divide
4593 // as in the LHS instruction that we're folding.
4594 bool ProdOV = !DivRHS->isNullValue() &&
4595 (DivOpCode == Instruction::SDiv ?
4596 ConstantExpr::getSDiv(Prod, DivRHS) :
4597 ConstantExpr::getUDiv(Prod, DivRHS)) != CI;
4598
4599 // Get the SetCC opcode
Chris Lattnera92af962004-10-11 19:40:04 +00004600 Instruction::BinaryOps Opcode = I.getOpcode();
4601
Reid Spencer7e80b0b2006-10-26 06:15:43 +00004602 if (DivRHS->isNullValue()) {
4603 // Don't hack on divide by zeros!
4604 } else if (DivOpCode == Instruction::UDiv) { // udiv
Chris Lattner6862fbd2004-09-29 17:40:11 +00004605 LoBound = Prod;
4606 LoOverflow = ProdOV;
4607 HiOverflow = ProdOV || AddWithOverflow(HiBound, LoBound, DivRHS);
Reid Spencer7e80b0b2006-10-26 06:15:43 +00004608 } else if (isPositive(DivRHS)) { // Divisor is > 0.
Chris Lattner6862fbd2004-09-29 17:40:11 +00004609 if (CI->isNullValue()) { // (X / pos) op 0
4610 // Can't overflow.
4611 LoBound = cast<ConstantInt>(ConstantExpr::getNeg(SubOne(DivRHS)));
4612 HiBound = DivRHS;
4613 } else if (isPositive(CI)) { // (X / pos) op pos
4614 LoBound = Prod;
4615 LoOverflow = ProdOV;
4616 HiOverflow = ProdOV || AddWithOverflow(HiBound, Prod, DivRHS);
4617 } else { // (X / pos) op neg
4618 Constant *DivRHSH = ConstantExpr::getNeg(SubOne(DivRHS));
4619 LoOverflow = AddWithOverflow(LoBound, Prod,
4620 cast<ConstantInt>(DivRHSH));
4621 HiBound = Prod;
4622 HiOverflow = ProdOV;
4623 }
Reid Spencer7e80b0b2006-10-26 06:15:43 +00004624 } else { // Divisor is < 0.
Chris Lattner6862fbd2004-09-29 17:40:11 +00004625 if (CI->isNullValue()) { // (X / neg) op 0
4626 LoBound = AddOne(DivRHS);
4627 HiBound = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
Chris Lattner73bcba52005-06-17 02:05:55 +00004628 if (HiBound == DivRHS)
Reid Spencer7e80b0b2006-10-26 06:15:43 +00004629 LoBound = 0; // - INTMIN = INTMIN
Chris Lattner6862fbd2004-09-29 17:40:11 +00004630 } else if (isPositive(CI)) { // (X / neg) op pos
4631 HiOverflow = LoOverflow = ProdOV;
4632 if (!LoOverflow)
4633 LoOverflow = AddWithOverflow(LoBound, Prod, AddOne(DivRHS));
4634 HiBound = AddOne(Prod);
4635 } else { // (X / neg) op neg
4636 LoBound = Prod;
4637 LoOverflow = HiOverflow = ProdOV;
4638 HiBound = cast<ConstantInt>(ConstantExpr::getSub(Prod, DivRHS));
4639 }
Chris Lattner0b41e862004-10-08 19:15:44 +00004640
Chris Lattnera92af962004-10-11 19:40:04 +00004641 // Dividing by a negate swaps the condition.
4642 Opcode = SetCondInst::getSwappedCondition(Opcode);
Chris Lattner6862fbd2004-09-29 17:40:11 +00004643 }
4644
4645 if (LoBound) {
4646 Value *X = LHSI->getOperand(0);
Chris Lattnera92af962004-10-11 19:40:04 +00004647 switch (Opcode) {
Chris Lattner6862fbd2004-09-29 17:40:11 +00004648 default: assert(0 && "Unhandled setcc opcode!");
4649 case Instruction::SetEQ:
4650 if (LoOverflow && HiOverflow)
Chris Lattner6ab03f62006-09-28 23:35:22 +00004651 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
Chris Lattner6862fbd2004-09-29 17:40:11 +00004652 else if (HiOverflow)
4653 return new SetCondInst(Instruction::SetGE, X, LoBound);
4654 else if (LoOverflow)
4655 return new SetCondInst(Instruction::SetLT, X, HiBound);
4656 else
4657 return InsertRangeTest(X, LoBound, HiBound, true, I);
4658 case Instruction::SetNE:
4659 if (LoOverflow && HiOverflow)
Chris Lattner6ab03f62006-09-28 23:35:22 +00004660 return ReplaceInstUsesWith(I, ConstantBool::getTrue());
Chris Lattner6862fbd2004-09-29 17:40:11 +00004661 else if (HiOverflow)
4662 return new SetCondInst(Instruction::SetLT, X, LoBound);
4663 else if (LoOverflow)
4664 return new SetCondInst(Instruction::SetGE, X, HiBound);
4665 else
4666 return InsertRangeTest(X, LoBound, HiBound, false, I);
4667 case Instruction::SetLT:
4668 if (LoOverflow)
Chris Lattner6ab03f62006-09-28 23:35:22 +00004669 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
Chris Lattner6862fbd2004-09-29 17:40:11 +00004670 return new SetCondInst(Instruction::SetLT, X, LoBound);
4671 case Instruction::SetGT:
4672 if (HiOverflow)
Chris Lattner6ab03f62006-09-28 23:35:22 +00004673 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
Chris Lattner6862fbd2004-09-29 17:40:11 +00004674 return new SetCondInst(Instruction::SetGE, X, HiBound);
4675 }
4676 }
4677 }
4678 break;
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00004679 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00004680
Chris Lattnera7942b72006-11-29 05:02:16 +00004681 // Simplify seteq and setne instructions with integer constant RHS.
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004682 if (I.isEquality()) {
Chris Lattnerd492a0b2003-07-23 17:02:11 +00004683 bool isSetNE = I.getOpcode() == Instruction::SetNE;
4684
Reid Spencere0fc4df2006-10-20 07:07:24 +00004685 // If the first operand is (add|sub|and|or|xor|rem) with a constant, and
4686 // the second operand is a constant, simplify a bit.
Chris Lattnerc992add2003-08-13 05:33:12 +00004687 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0)) {
4688 switch (BO->getOpcode()) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00004689 case Instruction::SRem:
4690 // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
4691 if (CI->isNullValue() && isa<ConstantInt>(BO->getOperand(1)) &&
4692 BO->hasOneUse()) {
4693 int64_t V = cast<ConstantInt>(BO->getOperand(1))->getSExtValue();
4694 if (V > 1 && isPowerOf2_64(V)) {
Reid Spencer7eb55b32006-11-02 01:53:59 +00004695 Value *NewRem = InsertNewInstBefore(BinaryOperator::createURem(
4696 BO->getOperand(0), BO->getOperand(1), BO->getName()), I);
Chris Lattner23b47b62004-07-06 07:38:18 +00004697 return BinaryOperator::create(I.getOpcode(), NewRem,
Reid Spencer7eb55b32006-11-02 01:53:59 +00004698 Constant::getNullValue(BO->getType()));
Chris Lattner23b47b62004-07-06 07:38:18 +00004699 }
Chris Lattner22d00a82005-08-02 19:16:58 +00004700 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00004701 break;
Chris Lattnerc992add2003-08-13 05:33:12 +00004702 case Instruction::Add:
Chris Lattner6e079362004-06-27 22:51:36 +00004703 // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
4704 if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
Chris Lattnerb121ae12004-09-21 21:35:23 +00004705 if (BO->hasOneUse())
4706 return new SetCondInst(I.getOpcode(), BO->getOperand(0),
4707 ConstantExpr::getSub(CI, BOp1C));
Chris Lattner6e079362004-06-27 22:51:36 +00004708 } else if (CI->isNullValue()) {
Chris Lattnerc992add2003-08-13 05:33:12 +00004709 // Replace ((add A, B) != 0) with (A != -B) if A or B is
4710 // efficiently invertible, or if the add has just this one use.
4711 Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
Misha Brukmanb1c93172005-04-21 23:48:37 +00004712
Chris Lattnerc992add2003-08-13 05:33:12 +00004713 if (Value *NegVal = dyn_castNegVal(BOp1))
4714 return new SetCondInst(I.getOpcode(), BOp0, NegVal);
4715 else if (Value *NegVal = dyn_castNegVal(BOp0))
4716 return new SetCondInst(I.getOpcode(), NegVal, BOp1);
Chris Lattnerf95d9b92003-10-15 16:48:29 +00004717 else if (BO->hasOneUse()) {
Chris Lattnerc992add2003-08-13 05:33:12 +00004718 Instruction *Neg = BinaryOperator::createNeg(BOp1, BO->getName());
4719 BO->setName("");
4720 InsertNewInstBefore(Neg, I);
4721 return new SetCondInst(I.getOpcode(), BOp0, Neg);
4722 }
4723 }
4724 break;
4725 case Instruction::Xor:
4726 // For the xor case, we can xor two constants together, eliminating
4727 // the explicit xor.
4728 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
4729 return BinaryOperator::create(I.getOpcode(), BO->getOperand(0),
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00004730 ConstantExpr::getXor(CI, BOC));
Chris Lattnerc992add2003-08-13 05:33:12 +00004731
4732 // FALLTHROUGH
4733 case Instruction::Sub:
4734 // Replace (([sub|xor] A, B) != 0) with (A != B)
4735 if (CI->isNullValue())
4736 return new SetCondInst(I.getOpcode(), BO->getOperand(0),
4737 BO->getOperand(1));
4738 break;
4739
4740 case Instruction::Or:
4741 // If bits are being or'd in that are not present in the constant we
4742 // are comparing against, then the comparison could never succeed!
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00004743 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
Chris Lattnerc8e7e292004-06-10 02:12:35 +00004744 Constant *NotCI = ConstantExpr::getNot(CI);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00004745 if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
Chris Lattnerd492a0b2003-07-23 17:02:11 +00004746 return ReplaceInstUsesWith(I, ConstantBool::get(isSetNE));
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00004747 }
Chris Lattnerc992add2003-08-13 05:33:12 +00004748 break;
4749
4750 case Instruction::And:
4751 if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
Chris Lattnerd492a0b2003-07-23 17:02:11 +00004752 // If bits are being compared against that are and'd out, then the
4753 // comparison can never succeed!
Chris Lattnerc8e7e292004-06-10 02:12:35 +00004754 if (!ConstantExpr::getAnd(CI,
4755 ConstantExpr::getNot(BOC))->isNullValue())
Chris Lattnerd492a0b2003-07-23 17:02:11 +00004756 return ReplaceInstUsesWith(I, ConstantBool::get(isSetNE));
Chris Lattnerc992add2003-08-13 05:33:12 +00004757
Chris Lattner35167c32004-06-09 07:59:58 +00004758 // If we have ((X & C) == C), turn it into ((X & C) != 0).
Chris Lattneree59d4b2004-06-10 02:33:20 +00004759 if (CI == BOC && isOneBitSet(CI))
Chris Lattner35167c32004-06-09 07:59:58 +00004760 return new SetCondInst(isSetNE ? Instruction::SetEQ :
4761 Instruction::SetNE, Op0,
4762 Constant::getNullValue(CI->getType()));
Chris Lattner35167c32004-06-09 07:59:58 +00004763
Chris Lattnerc992add2003-08-13 05:33:12 +00004764 // Replace (and X, (1 << size(X)-1) != 0) with x < 0, converting X
4765 // to be a signed value as appropriate.
4766 if (isSignBit(BOC)) {
4767 Value *X = BO->getOperand(0);
4768 // If 'X' is not signed, insert a cast now...
4769 if (!BOC->getType()->isSigned()) {
Chris Lattner97bfcea2004-06-17 18:16:02 +00004770 const Type *DestTy = BOC->getType()->getSignedVersion();
Reid Spencer13bc5d72006-12-12 09:18:51 +00004771 X = InsertCastBefore(Instruction::BitCast, X, DestTy, I);
Chris Lattnerc992add2003-08-13 05:33:12 +00004772 }
4773 return new SetCondInst(isSetNE ? Instruction::SetLT :
4774 Instruction::SetGE, X,
4775 Constant::getNullValue(X->getType()));
4776 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00004777
Chris Lattnerbfff18a2004-09-27 19:29:18 +00004778 // ((X & ~7) == 0) --> X < 8
Chris Lattner8fc5af42004-09-23 21:46:38 +00004779 if (CI->isNullValue() && isHighOnes(BOC)) {
4780 Value *X = BO->getOperand(0);
Chris Lattnerbfff18a2004-09-27 19:29:18 +00004781 Constant *NegX = ConstantExpr::getNeg(BOC);
Chris Lattner8fc5af42004-09-23 21:46:38 +00004782
4783 // If 'X' is signed, insert a cast now.
Chris Lattnerbfff18a2004-09-27 19:29:18 +00004784 if (NegX->getType()->isSigned()) {
4785 const Type *DestTy = NegX->getType()->getUnsignedVersion();
Reid Spencer13bc5d72006-12-12 09:18:51 +00004786 X = InsertCastBefore(Instruction::BitCast, X, DestTy, I);
4787 NegX = ConstantExpr::getBitCast(NegX, DestTy);
Chris Lattner8fc5af42004-09-23 21:46:38 +00004788 }
4789
4790 return new SetCondInst(isSetNE ? Instruction::SetGE :
Chris Lattnerbfff18a2004-09-27 19:29:18 +00004791 Instruction::SetLT, X, NegX);
Chris Lattner8fc5af42004-09-23 21:46:38 +00004792 }
4793
Chris Lattnerd492a0b2003-07-23 17:02:11 +00004794 }
Chris Lattnerc992add2003-08-13 05:33:12 +00004795 default: break;
4796 }
Chris Lattnera7942b72006-11-29 05:02:16 +00004797 } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(Op0)) {
4798 // Handle set{eq|ne} <intrinsic>, intcst.
4799 switch (II->getIntrinsicID()) {
4800 default: break;
4801 case Intrinsic::bswap_i16: // seteq (bswap(x)), c -> seteq(x,bswap(c))
4802 WorkList.push_back(II); // Dead?
4803 I.setOperand(0, II->getOperand(1));
4804 I.setOperand(1, ConstantInt::get(Type::UShortTy,
4805 ByteSwap_16(CI->getZExtValue())));
4806 return &I;
4807 case Intrinsic::bswap_i32: // seteq (bswap(x)), c -> seteq(x,bswap(c))
4808 WorkList.push_back(II); // Dead?
4809 I.setOperand(0, II->getOperand(1));
4810 I.setOperand(1, ConstantInt::get(Type::UIntTy,
4811 ByteSwap_32(CI->getZExtValue())));
4812 return &I;
4813 case Intrinsic::bswap_i64: // seteq (bswap(x)), c -> seteq(x,bswap(c))
4814 WorkList.push_back(II); // Dead?
4815 I.setOperand(0, II->getOperand(1));
4816 I.setOperand(1, ConstantInt::get(Type::ULongTy,
4817 ByteSwap_64(CI->getZExtValue())));
4818 return &I;
4819 }
Chris Lattnerc992add2003-08-13 05:33:12 +00004820 }
Chris Lattner2b55ea32004-02-23 07:16:20 +00004821 } else { // Not a SetEQ/SetNE
Misha Brukmanb1c93172005-04-21 23:48:37 +00004822 // If the LHS is a cast from an integral value of the same size,
Chris Lattner2b55ea32004-02-23 07:16:20 +00004823 if (CastInst *Cast = dyn_cast<CastInst>(Op0)) {
4824 Value *CastOp = Cast->getOperand(0);
4825 const Type *SrcTy = CastOp->getType();
Chris Lattnerd1f46d32005-04-24 06:59:08 +00004826 unsigned SrcTySize = SrcTy->getPrimitiveSizeInBits();
Chris Lattner2b55ea32004-02-23 07:16:20 +00004827 if (SrcTy != Cast->getType() && SrcTy->isInteger() &&
Chris Lattnerd1f46d32005-04-24 06:59:08 +00004828 SrcTySize == Cast->getType()->getPrimitiveSizeInBits()) {
Misha Brukmanb1c93172005-04-21 23:48:37 +00004829 assert((SrcTy->isSigned() ^ Cast->getType()->isSigned()) &&
Chris Lattner2b55ea32004-02-23 07:16:20 +00004830 "Source and destination signednesses should differ!");
4831 if (Cast->getType()->isSigned()) {
4832 // If this is a signed comparison, check for comparisons in the
4833 // vicinity of zero.
4834 if (I.getOpcode() == Instruction::SetLT && CI->isNullValue())
4835 // X < 0 => x > 127
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00004836 return BinaryOperator::createSetGT(CastOp,
Reid Spencere0fc4df2006-10-20 07:07:24 +00004837 ConstantInt::get(SrcTy, (1ULL << (SrcTySize-1))-1));
Chris Lattner2b55ea32004-02-23 07:16:20 +00004838 else if (I.getOpcode() == Instruction::SetGT &&
Reid Spencere0fc4df2006-10-20 07:07:24 +00004839 cast<ConstantInt>(CI)->getSExtValue() == -1)
Chris Lattner2b55ea32004-02-23 07:16:20 +00004840 // X > -1 => x < 128
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00004841 return BinaryOperator::createSetLT(CastOp,
Reid Spencere0fc4df2006-10-20 07:07:24 +00004842 ConstantInt::get(SrcTy, 1ULL << (SrcTySize-1)));
Chris Lattner2b55ea32004-02-23 07:16:20 +00004843 } else {
Reid Spencere0fc4df2006-10-20 07:07:24 +00004844 ConstantInt *CUI = cast<ConstantInt>(CI);
Chris Lattner2b55ea32004-02-23 07:16:20 +00004845 if (I.getOpcode() == Instruction::SetLT &&
Reid Spencere0fc4df2006-10-20 07:07:24 +00004846 CUI->getZExtValue() == 1ULL << (SrcTySize-1))
Chris Lattner2b55ea32004-02-23 07:16:20 +00004847 // X < 128 => X > -1
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00004848 return BinaryOperator::createSetGT(CastOp,
Reid Spencere0fc4df2006-10-20 07:07:24 +00004849 ConstantInt::get(SrcTy, -1));
Chris Lattner2b55ea32004-02-23 07:16:20 +00004850 else if (I.getOpcode() == Instruction::SetGT &&
Reid Spencere0fc4df2006-10-20 07:07:24 +00004851 CUI->getZExtValue() == (1ULL << (SrcTySize-1))-1)
Chris Lattner2b55ea32004-02-23 07:16:20 +00004852 // X > 127 => X < 0
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00004853 return BinaryOperator::createSetLT(CastOp,
4854 Constant::getNullValue(SrcTy));
Chris Lattner2b55ea32004-02-23 07:16:20 +00004855 }
4856 }
4857 }
Chris Lattnere967b342003-06-04 05:10:11 +00004858 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00004859 }
4860
Chris Lattner77c32c32005-04-23 15:31:55 +00004861 // Handle setcc with constant RHS's that can be integer, FP or pointer.
4862 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
4863 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
4864 switch (LHSI->getOpcode()) {
Chris Lattnera816eee2005-05-01 04:42:15 +00004865 case Instruction::GetElementPtr:
4866 if (RHSC->isNullValue()) {
4867 // Transform setcc GEP P, int 0, int 0, int 0, null -> setcc P, null
4868 bool isAllZeros = true;
4869 for (unsigned i = 1, e = LHSI->getNumOperands(); i != e; ++i)
4870 if (!isa<Constant>(LHSI->getOperand(i)) ||
4871 !cast<Constant>(LHSI->getOperand(i))->isNullValue()) {
4872 isAllZeros = false;
4873 break;
4874 }
4875 if (isAllZeros)
4876 return new SetCondInst(I.getOpcode(), LHSI->getOperand(0),
4877 Constant::getNullValue(LHSI->getOperand(0)->getType()));
4878 }
4879 break;
4880
Chris Lattner77c32c32005-04-23 15:31:55 +00004881 case Instruction::PHI:
4882 if (Instruction *NV = FoldOpIntoPhi(I))
4883 return NV;
4884 break;
4885 case Instruction::Select:
4886 // If either operand of the select is a constant, we can fold the
4887 // comparison into the select arms, which will cause one to be
4888 // constant folded and the select turned into a bitwise or.
4889 Value *Op1 = 0, *Op2 = 0;
4890 if (LHSI->hasOneUse()) {
4891 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
4892 // Fold the known value into the constant operand.
4893 Op1 = ConstantExpr::get(I.getOpcode(), C, RHSC);
4894 // Insert a new SetCC of the other select operand.
4895 Op2 = InsertNewInstBefore(new SetCondInst(I.getOpcode(),
4896 LHSI->getOperand(2), RHSC,
4897 I.getName()), I);
4898 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
4899 // Fold the known value into the constant operand.
4900 Op2 = ConstantExpr::get(I.getOpcode(), C, RHSC);
4901 // Insert a new SetCC of the other select operand.
4902 Op1 = InsertNewInstBefore(new SetCondInst(I.getOpcode(),
4903 LHSI->getOperand(1), RHSC,
4904 I.getName()), I);
4905 }
4906 }
Jeff Cohen82639852005-04-23 21:38:35 +00004907
Chris Lattner77c32c32005-04-23 15:31:55 +00004908 if (Op1)
4909 return new SelectInst(LHSI->getOperand(0), Op1, Op2);
4910 break;
4911 }
4912 }
4913
Chris Lattner0798af32005-01-13 20:14:25 +00004914 // If we can optimize a 'setcc GEP, P' or 'setcc P, GEP', do so now.
4915 if (User *GEP = dyn_castGetElementPtr(Op0))
4916 if (Instruction *NI = FoldGEPSetCC(GEP, Op1, I.getOpcode(), I))
4917 return NI;
4918 if (User *GEP = dyn_castGetElementPtr(Op1))
4919 if (Instruction *NI = FoldGEPSetCC(GEP, Op0,
4920 SetCondInst::getSwappedCondition(I.getOpcode()), I))
4921 return NI;
4922
Chris Lattner16930792003-11-03 04:25:02 +00004923 // Test to see if the operands of the setcc are casted versions of other
4924 // values. If the cast can be stripped off both arguments, we do so now.
Chris Lattner6444c372003-11-03 05:17:03 +00004925 if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
4926 Value *CastOp0 = CI->getOperand(0);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00004927 if (CI->isLosslessCast() && I.isEquality() &&
4928 (isa<Constant>(Op1) || isa<CastInst>(Op1))) {
Chris Lattner16930792003-11-03 04:25:02 +00004929 // We keep moving the cast from the left operand over to the right
4930 // operand, where it can often be eliminated completely.
Chris Lattner6444c372003-11-03 05:17:03 +00004931 Op0 = CastOp0;
Misha Brukmanb1c93172005-04-21 23:48:37 +00004932
Chris Lattner16930792003-11-03 04:25:02 +00004933 // If operand #1 is a cast instruction, see if we can eliminate it as
4934 // well.
Reid Spencer6c38f0b2006-11-27 01:05:10 +00004935 if (CastInst *CI2 = dyn_cast<CastInst>(Op1)) {
4936 Value *CI2Op0 = CI2->getOperand(0);
4937 if (CI2Op0->getType()->canLosslesslyBitCastTo(Op0->getType()))
4938 Op1 = CI2Op0;
4939 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00004940
Chris Lattner16930792003-11-03 04:25:02 +00004941 // If Op1 is a constant, we can fold the cast into the constant.
4942 if (Op1->getType() != Op0->getType())
4943 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
Reid Spencerbb65ebf2006-12-12 23:36:14 +00004944 Op1 = ConstantExpr::getBitCast(Op1C, Op0->getType());
Chris Lattner16930792003-11-03 04:25:02 +00004945 } else {
4946 // Otherwise, cast the RHS right before the setcc
Reid Spencer13bc5d72006-12-12 09:18:51 +00004947 Op1 = InsertCastBefore(Instruction::BitCast, Op1, Op0->getType(), I);
Chris Lattner16930792003-11-03 04:25:02 +00004948 }
4949 return BinaryOperator::create(I.getOpcode(), Op0, Op1);
4950 }
4951
Chris Lattner6444c372003-11-03 05:17:03 +00004952 // Handle the special case of: setcc (cast bool to X), <cst>
4953 // This comes up when you have code like
4954 // int X = A < B;
4955 // if (X) ...
4956 // For generality, we handle any zero-extension of any operand comparison
Chris Lattnerd1f46d32005-04-24 06:59:08 +00004957 // with a constant or another cast from the same type.
4958 if (isa<ConstantInt>(Op1) || isa<CastInst>(Op1))
4959 if (Instruction *R = visitSetCondInstWithCastAndCast(I))
4960 return R;
Chris Lattner6444c372003-11-03 05:17:03 +00004961 }
Chris Lattnerf5c8a0b2006-02-27 01:44:11 +00004962
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004963 if (I.isEquality()) {
Chris Lattnerf5c8a0b2006-02-27 01:44:11 +00004964 Value *A, *B;
4965 if (match(Op0, m_Xor(m_Value(A), m_Value(B))) &&
4966 (A == Op1 || B == Op1)) {
4967 // (A^B) == A -> B == 0
4968 Value *OtherVal = A == Op1 ? B : A;
4969 return BinaryOperator::create(I.getOpcode(), OtherVal,
4970 Constant::getNullValue(A->getType()));
4971 } else if (match(Op1, m_Xor(m_Value(A), m_Value(B))) &&
4972 (A == Op0 || B == Op0)) {
4973 // A == (A^B) -> B == 0
4974 Value *OtherVal = A == Op0 ? B : A;
4975 return BinaryOperator::create(I.getOpcode(), OtherVal,
4976 Constant::getNullValue(A->getType()));
4977 } else if (match(Op0, m_Sub(m_Value(A), m_Value(B))) && A == Op1) {
4978 // (A-B) == A -> B == 0
4979 return BinaryOperator::create(I.getOpcode(), B,
4980 Constant::getNullValue(B->getType()));
4981 } else if (match(Op1, m_Sub(m_Value(A), m_Value(B))) && A == Op0) {
4982 // A == (A-B) -> B == 0
4983 return BinaryOperator::create(I.getOpcode(), B,
4984 Constant::getNullValue(B->getType()));
4985 }
Chris Lattnerd12a4bf2006-11-14 06:06:06 +00004986
4987 Value *C, *D;
4988 // (X&Z) == (Y&Z) -> (X^Y) & Z == 0
4989 if (Op0->hasOneUse() && Op1->hasOneUse() &&
4990 match(Op0, m_And(m_Value(A), m_Value(B))) &&
4991 match(Op1, m_And(m_Value(C), m_Value(D)))) {
4992 Value *X = 0, *Y = 0, *Z = 0;
4993
4994 if (A == C) {
4995 X = B; Y = D; Z = A;
4996 } else if (A == D) {
4997 X = B; Y = C; Z = A;
4998 } else if (B == C) {
4999 X = A; Y = D; Z = B;
5000 } else if (B == D) {
5001 X = A; Y = C; Z = B;
5002 }
5003
5004 if (X) { // Build (X^Y) & Z
5005 Op1 = InsertNewInstBefore(BinaryOperator::createXor(X, Y, "tmp"), I);
5006 Op1 = InsertNewInstBefore(BinaryOperator::createAnd(Op1, Z, "tmp"), I);
5007 I.setOperand(0, Op1);
5008 I.setOperand(1, Constant::getNullValue(Op1->getType()));
5009 return &I;
5010 }
5011 }
Chris Lattnerf5c8a0b2006-02-27 01:44:11 +00005012 }
Chris Lattner113f4f42002-06-25 16:13:24 +00005013 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00005014}
5015
Chris Lattnerd1f46d32005-04-24 06:59:08 +00005016// visitSetCondInstWithCastAndCast - Handle setcond (cast x to y), (cast/cst).
5017// We only handle extending casts so far.
5018//
5019Instruction *InstCombiner::visitSetCondInstWithCastAndCast(SetCondInst &SCI) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +00005020 const CastInst *LHSCI = cast<CastInst>(SCI.getOperand(0));
5021 Value *LHSCIOp = LHSCI->getOperand(0);
5022 const Type *SrcTy = LHSCIOp->getType();
5023 const Type *DestTy = SCI.getOperand(0)->getType();
Chris Lattnerd1f46d32005-04-24 06:59:08 +00005024 Value *RHSCIOp;
5025
5026 if (!DestTy->isIntegral() || !SrcTy->isIntegral())
Chris Lattner03f06f12005-01-17 03:20:02 +00005027 return 0;
5028
Chris Lattnerd1f46d32005-04-24 06:59:08 +00005029 unsigned SrcBits = SrcTy->getPrimitiveSizeInBits();
5030 unsigned DestBits = DestTy->getPrimitiveSizeInBits();
5031 if (SrcBits >= DestBits) return 0; // Only handle extending cast.
5032
5033 // Is this a sign or zero extension?
5034 bool isSignSrc = SrcTy->isSigned();
5035 bool isSignDest = DestTy->isSigned();
5036
5037 if (CastInst *CI = dyn_cast<CastInst>(SCI.getOperand(1))) {
5038 // Not an extension from the same type?
5039 RHSCIOp = CI->getOperand(0);
5040 if (RHSCIOp->getType() != LHSCIOp->getType()) return 0;
5041 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(SCI.getOperand(1))) {
5042 // Compute the constant that would happen if we truncated to SrcTy then
5043 // reextended to DestTy.
Reid Spencer6c38f0b2006-11-27 01:05:10 +00005044 Constant *Res1 = ConstantExpr::getTrunc(CI, SrcTy);
5045 Constant *Res2 = ConstantExpr::getCast(LHSCI->getOpcode(), Res1, DestTy);
Chris Lattnerd1f46d32005-04-24 06:59:08 +00005046
Reid Spencer6c38f0b2006-11-27 01:05:10 +00005047 if (Res2 == CI) {
Devang Patelb42aef42006-10-19 18:54:08 +00005048 // Make sure that src sign and dest sign match. For example,
5049 //
5050 // %A = cast short %X to uint
5051 // %B = setgt uint %A, 1330
5052 //
Devang Patel88afd002006-10-19 19:21:36 +00005053 // It is incorrect to transform this into
Devang Patelb42aef42006-10-19 18:54:08 +00005054 //
5055 // %B = setgt short %X, 1330
5056 //
5057 // because %A may have negative value.
Devang Patel5d6df952006-10-19 20:59:13 +00005058 // However, it is OK if SrcTy is bool (See cast-set.ll testcase)
5059 // OR operation is EQ/NE.
5060 if (isSignSrc == isSignDest || SrcTy == Type::BoolTy || SCI.isEquality())
Reid Spencer6c38f0b2006-11-27 01:05:10 +00005061 RHSCIOp = Res1;
Devang Patelb42aef42006-10-19 18:54:08 +00005062 else
5063 return 0;
Chris Lattnerd1f46d32005-04-24 06:59:08 +00005064 } else {
5065 // If the value cannot be represented in the shorter type, we cannot emit
5066 // a simple comparison.
5067 if (SCI.getOpcode() == Instruction::SetEQ)
Chris Lattner6ab03f62006-09-28 23:35:22 +00005068 return ReplaceInstUsesWith(SCI, ConstantBool::getFalse());
Chris Lattnerd1f46d32005-04-24 06:59:08 +00005069 if (SCI.getOpcode() == Instruction::SetNE)
Chris Lattner6ab03f62006-09-28 23:35:22 +00005070 return ReplaceInstUsesWith(SCI, ConstantBool::getTrue());
Chris Lattnerd1f46d32005-04-24 06:59:08 +00005071
Chris Lattnerd1f46d32005-04-24 06:59:08 +00005072 // Evaluate the comparison for LT.
5073 Value *Result;
5074 if (DestTy->isSigned()) {
5075 // We're performing a signed comparison.
5076 if (isSignSrc) {
5077 // Signed extend and signed comparison.
Reid Spencere0fc4df2006-10-20 07:07:24 +00005078 if (cast<ConstantInt>(CI)->getSExtValue() < 0)// X < (small) --> false
Chris Lattner6ab03f62006-09-28 23:35:22 +00005079 Result = ConstantBool::getFalse();
Chris Lattnerd1f46d32005-04-24 06:59:08 +00005080 else
Reid Spencere0fc4df2006-10-20 07:07:24 +00005081 Result = ConstantBool::getTrue(); // X < (large) --> true
Chris Lattnerd1f46d32005-04-24 06:59:08 +00005082 } else {
5083 // Unsigned extend and signed comparison.
Reid Spencere0fc4df2006-10-20 07:07:24 +00005084 if (cast<ConstantInt>(CI)->getSExtValue() < 0)
Chris Lattner6ab03f62006-09-28 23:35:22 +00005085 Result = ConstantBool::getFalse();
Chris Lattnerd1f46d32005-04-24 06:59:08 +00005086 else
Chris Lattner6ab03f62006-09-28 23:35:22 +00005087 Result = ConstantBool::getTrue();
Chris Lattnerd1f46d32005-04-24 06:59:08 +00005088 }
5089 } else {
5090 // We're performing an unsigned comparison.
5091 if (!isSignSrc) {
5092 // Unsigned extend & compare -> always true.
Chris Lattner6ab03f62006-09-28 23:35:22 +00005093 Result = ConstantBool::getTrue();
Chris Lattnerd1f46d32005-04-24 06:59:08 +00005094 } else {
5095 // We're performing an unsigned comp with a sign extended value.
5096 // This is true if the input is >= 0. [aka >s -1]
5097 Constant *NegOne = ConstantIntegral::getAllOnesValue(SrcTy);
5098 Result = InsertNewInstBefore(BinaryOperator::createSetGT(LHSCIOp,
5099 NegOne, SCI.getName()), SCI);
5100 }
Reid Spencer279fa252004-11-28 21:31:15 +00005101 }
Chris Lattner03f06f12005-01-17 03:20:02 +00005102
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00005103 // Finally, return the value computed.
Chris Lattnerd1f46d32005-04-24 06:59:08 +00005104 if (SCI.getOpcode() == Instruction::SetLT) {
5105 return ReplaceInstUsesWith(SCI, Result);
5106 } else {
5107 assert(SCI.getOpcode()==Instruction::SetGT &&"SetCC should be folded!");
5108 if (Constant *CI = dyn_cast<Constant>(Result))
5109 return ReplaceInstUsesWith(SCI, ConstantExpr::getNot(CI));
5110 else
5111 return BinaryOperator::createNot(Result);
5112 }
Chris Lattner03f06f12005-01-17 03:20:02 +00005113 }
Chris Lattnerd1f46d32005-04-24 06:59:08 +00005114 } else {
5115 return 0;
Reid Spencer279fa252004-11-28 21:31:15 +00005116 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00005117
Chris Lattner252a8452005-06-16 03:00:08 +00005118 // Okay, just insert a compare of the reduced operands now!
Chris Lattnerd1f46d32005-04-24 06:59:08 +00005119 return BinaryOperator::create(SCI.getOpcode(), LHSCIOp, RHSCIOp);
5120}
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00005121
Chris Lattnere8d6c602003-03-10 19:16:08 +00005122Instruction *InstCombiner::visitShiftInst(ShiftInst &I) {
Chris Lattner113f4f42002-06-25 16:13:24 +00005123 assert(I.getOperand(1)->getType() == Type::UByteTy);
5124 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00005125 bool isLeftShift = I.getOpcode() == Instruction::Shl;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00005126
5127 // shl X, 0 == X and shr X, 0 == X
5128 // shl 0, X == 0 and shr 0, X == 0
5129 if (Op1 == Constant::getNullValue(Type::UByteTy) ||
Chris Lattnere6794492002-08-12 21:17:25 +00005130 Op0 == Constant::getNullValue(Op0->getType()))
5131 return ReplaceInstUsesWith(I, Op0);
Chris Lattnerf5b4ef72006-02-12 08:07:37 +00005132
Chris Lattner81a7a232004-10-16 18:11:37 +00005133 if (isa<UndefValue>(Op0)) { // undef >>s X -> undef
5134 if (!isLeftShift && I.getType()->isSigned())
Chris Lattner67f05452004-10-16 23:28:04 +00005135 return ReplaceInstUsesWith(I, Op0);
Chris Lattner81a7a232004-10-16 18:11:37 +00005136 else // undef << X -> 0 AND undef >>u X -> 0
5137 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
5138 }
5139 if (isa<UndefValue>(Op1)) {
Chris Lattner18aa4d82005-07-20 18:49:28 +00005140 if (isLeftShift || I.getType()->isUnsigned())// X << undef, X >>u undef -> 0
Chris Lattner81a7a232004-10-16 18:11:37 +00005141 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
5142 else
5143 return ReplaceInstUsesWith(I, Op0); // X >>s undef -> X
5144 }
5145
Chris Lattnerd4dee402006-11-10 23:38:52 +00005146 // ashr int -1, X = -1 (for any arithmetic shift rights of ~0)
5147 if (I.getOpcode() == Instruction::AShr)
Reid Spencere0fc4df2006-10-20 07:07:24 +00005148 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
Chris Lattnerd4dee402006-11-10 23:38:52 +00005149 if (CSI->isAllOnesValue())
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00005150 return ReplaceInstUsesWith(I, CSI);
5151
Chris Lattner183b3362004-04-09 19:05:30 +00005152 // Try to fold constant and into select arguments.
5153 if (isa<Constant>(Op0))
5154 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner86102b82005-01-01 16:22:27 +00005155 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00005156 return R;
5157
Chris Lattnerb18dbbf2005-05-08 17:34:56 +00005158 // See if we can turn a signed shr into an unsigned shr.
Chris Lattnerb3f24c92006-09-18 04:22:48 +00005159 if (I.isArithmeticShift()) {
Chris Lattnerc3ebf402006-02-07 07:27:52 +00005160 if (MaskedValueIsZero(Op0,
5161 1ULL << (I.getType()->getPrimitiveSizeInBits()-1))) {
Reid Spencerfdff9382006-11-08 06:47:33 +00005162 return new ShiftInst(Instruction::LShr, Op0, Op1, I.getName());
Chris Lattnerb18dbbf2005-05-08 17:34:56 +00005163 }
5164 }
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00005165
Reid Spencere0fc4df2006-10-20 07:07:24 +00005166 if (ConstantInt *CUI = dyn_cast<ConstantInt>(Op1))
5167 if (CUI->getType()->isUnsigned())
5168 if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
5169 return Res;
Chris Lattner14553932006-01-06 07:12:35 +00005170 return 0;
5171}
5172
Reid Spencere0fc4df2006-10-20 07:07:24 +00005173Instruction *InstCombiner::FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
Chris Lattner14553932006-01-06 07:12:35 +00005174 ShiftInst &I) {
5175 bool isLeftShift = I.getOpcode() == Instruction::Shl;
Reid Spencerfdff9382006-11-08 06:47:33 +00005176 bool isSignedShift = isLeftShift ? Op0->getType()->isSigned() :
5177 I.getOpcode() == Instruction::AShr;
Chris Lattnerb3309392006-01-06 07:22:22 +00005178 bool isUnsignedShift = !isSignedShift;
Chris Lattner14553932006-01-06 07:12:35 +00005179
Chris Lattnerf5b4ef72006-02-12 08:07:37 +00005180 // See if we can simplify any instructions used by the instruction whose sole
5181 // purpose is to compute bits we don't care about.
5182 uint64_t KnownZero, KnownOne;
5183 if (SimplifyDemandedBits(&I, I.getType()->getIntegralTypeMask(),
5184 KnownZero, KnownOne))
5185 return &I;
5186
Chris Lattner14553932006-01-06 07:12:35 +00005187 // shl uint X, 32 = 0 and shr ubyte Y, 9 = 0, ... just don't eliminate shr
5188 // of a signed value.
5189 //
5190 unsigned TypeBits = Op0->getType()->getPrimitiveSizeInBits();
Reid Spencere0fc4df2006-10-20 07:07:24 +00005191 if (Op1->getZExtValue() >= TypeBits) {
Chris Lattnerb3309392006-01-06 07:22:22 +00005192 if (isUnsignedShift || isLeftShift)
Chris Lattner14553932006-01-06 07:12:35 +00005193 return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
5194 else {
Reid Spencere0fc4df2006-10-20 07:07:24 +00005195 I.setOperand(1, ConstantInt::get(Type::UByteTy, TypeBits-1));
Chris Lattner14553932006-01-06 07:12:35 +00005196 return &I;
Chris Lattnerf5ce2542004-02-23 20:30:06 +00005197 }
Chris Lattner14553932006-01-06 07:12:35 +00005198 }
5199
5200 // ((X*C1) << C2) == (X * (C1 << C2))
5201 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
5202 if (BO->getOpcode() == Instruction::Mul && isLeftShift)
5203 if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
5204 return BinaryOperator::createMul(BO->getOperand(0),
5205 ConstantExpr::getShl(BOOp, Op1));
5206
5207 // Try to fold constant and into select arguments.
5208 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
5209 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
5210 return R;
5211 if (isa<PHINode>(Op0))
5212 if (Instruction *NV = FoldOpIntoPhi(I))
5213 return NV;
5214
5215 if (Op0->hasOneUse()) {
Chris Lattner14553932006-01-06 07:12:35 +00005216 if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
5217 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
5218 Value *V1, *V2;
5219 ConstantInt *CC;
5220 switch (Op0BO->getOpcode()) {
Chris Lattner27cb9db2005-09-18 05:12:10 +00005221 default: break;
5222 case Instruction::Add:
5223 case Instruction::And:
5224 case Instruction::Or:
5225 case Instruction::Xor:
5226 // These operators commute.
5227 // Turn (Y + (X >> C)) << C -> (X + (Y << C)) & (~0 << C)
Chris Lattner797dee72005-09-18 06:30:59 +00005228 if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
5229 match(Op0BO->getOperand(1),
Chris Lattner14553932006-01-06 07:12:35 +00005230 m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
Chris Lattner797dee72005-09-18 06:30:59 +00005231 Instruction *YS = new ShiftInst(Instruction::Shl,
Chris Lattner14553932006-01-06 07:12:35 +00005232 Op0BO->getOperand(0), Op1,
Chris Lattner797dee72005-09-18 06:30:59 +00005233 Op0BO->getName());
5234 InsertNewInstBefore(YS, I); // (Y << C)
Chris Lattner24cd2fa2006-02-09 07:41:14 +00005235 Instruction *X =
5236 BinaryOperator::create(Op0BO->getOpcode(), YS, V1,
5237 Op0BO->getOperand(1)->getName());
Chris Lattner797dee72005-09-18 06:30:59 +00005238 InsertNewInstBefore(X, I); // (X + (Y << C))
5239 Constant *C2 = ConstantInt::getAllOnesValue(X->getType());
Chris Lattner14553932006-01-06 07:12:35 +00005240 C2 = ConstantExpr::getShl(C2, Op1);
Chris Lattner797dee72005-09-18 06:30:59 +00005241 return BinaryOperator::createAnd(X, C2);
5242 }
Chris Lattner14553932006-01-06 07:12:35 +00005243
Chris Lattner797dee72005-09-18 06:30:59 +00005244 // Turn (Y + ((X >> C) & CC)) << C -> ((X & (CC << C)) + (Y << C))
5245 if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
5246 match(Op0BO->getOperand(1),
5247 m_And(m_Shr(m_Value(V1), m_Value(V2)),
Chris Lattner14553932006-01-06 07:12:35 +00005248 m_ConstantInt(CC))) && V2 == Op1 &&
Chris Lattner24cd2fa2006-02-09 07:41:14 +00005249 cast<BinaryOperator>(Op0BO->getOperand(1))->getOperand(0)->hasOneUse()) {
Chris Lattner797dee72005-09-18 06:30:59 +00005250 Instruction *YS = new ShiftInst(Instruction::Shl,
Chris Lattner14553932006-01-06 07:12:35 +00005251 Op0BO->getOperand(0), Op1,
Chris Lattner797dee72005-09-18 06:30:59 +00005252 Op0BO->getName());
5253 InsertNewInstBefore(YS, I); // (Y << C)
5254 Instruction *XM =
Chris Lattner14553932006-01-06 07:12:35 +00005255 BinaryOperator::createAnd(V1, ConstantExpr::getShl(CC, Op1),
Chris Lattner797dee72005-09-18 06:30:59 +00005256 V1->getName()+".mask");
5257 InsertNewInstBefore(XM, I); // X & (CC << C)
5258
5259 return BinaryOperator::create(Op0BO->getOpcode(), YS, XM);
5260 }
Chris Lattner14553932006-01-06 07:12:35 +00005261
Chris Lattner797dee72005-09-18 06:30:59 +00005262 // FALL THROUGH.
Chris Lattner27cb9db2005-09-18 05:12:10 +00005263 case Instruction::Sub:
5264 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
Chris Lattner797dee72005-09-18 06:30:59 +00005265 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
5266 match(Op0BO->getOperand(0),
Chris Lattner14553932006-01-06 07:12:35 +00005267 m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
Chris Lattner797dee72005-09-18 06:30:59 +00005268 Instruction *YS = new ShiftInst(Instruction::Shl,
Chris Lattner14553932006-01-06 07:12:35 +00005269 Op0BO->getOperand(1), Op1,
Chris Lattner797dee72005-09-18 06:30:59 +00005270 Op0BO->getName());
5271 InsertNewInstBefore(YS, I); // (Y << C)
Chris Lattner24cd2fa2006-02-09 07:41:14 +00005272 Instruction *X =
Chris Lattner1df0e982006-05-31 21:14:00 +00005273 BinaryOperator::create(Op0BO->getOpcode(), V1, YS,
Chris Lattner24cd2fa2006-02-09 07:41:14 +00005274 Op0BO->getOperand(0)->getName());
Chris Lattner797dee72005-09-18 06:30:59 +00005275 InsertNewInstBefore(X, I); // (X + (Y << C))
5276 Constant *C2 = ConstantInt::getAllOnesValue(X->getType());
Chris Lattner14553932006-01-06 07:12:35 +00005277 C2 = ConstantExpr::getShl(C2, Op1);
Chris Lattner797dee72005-09-18 06:30:59 +00005278 return BinaryOperator::createAnd(X, C2);
5279 }
Chris Lattner14553932006-01-06 07:12:35 +00005280
Chris Lattner1df0e982006-05-31 21:14:00 +00005281 // Turn (((X >> C)&CC) + Y) << C -> (X + (Y << C)) & (CC << C)
Chris Lattner797dee72005-09-18 06:30:59 +00005282 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
5283 match(Op0BO->getOperand(0),
5284 m_And(m_Shr(m_Value(V1), m_Value(V2)),
Chris Lattner14553932006-01-06 07:12:35 +00005285 m_ConstantInt(CC))) && V2 == Op1 &&
Chris Lattner24cd2fa2006-02-09 07:41:14 +00005286 cast<BinaryOperator>(Op0BO->getOperand(0))
5287 ->getOperand(0)->hasOneUse()) {
Chris Lattner797dee72005-09-18 06:30:59 +00005288 Instruction *YS = new ShiftInst(Instruction::Shl,
Chris Lattner14553932006-01-06 07:12:35 +00005289 Op0BO->getOperand(1), Op1,
Chris Lattner797dee72005-09-18 06:30:59 +00005290 Op0BO->getName());
5291 InsertNewInstBefore(YS, I); // (Y << C)
5292 Instruction *XM =
Chris Lattner14553932006-01-06 07:12:35 +00005293 BinaryOperator::createAnd(V1, ConstantExpr::getShl(CC, Op1),
Chris Lattner797dee72005-09-18 06:30:59 +00005294 V1->getName()+".mask");
5295 InsertNewInstBefore(XM, I); // X & (CC << C)
5296
Chris Lattner1df0e982006-05-31 21:14:00 +00005297 return BinaryOperator::create(Op0BO->getOpcode(), XM, YS);
Chris Lattner797dee72005-09-18 06:30:59 +00005298 }
Chris Lattner14553932006-01-06 07:12:35 +00005299
Chris Lattner27cb9db2005-09-18 05:12:10 +00005300 break;
Chris Lattner14553932006-01-06 07:12:35 +00005301 }
5302
5303
5304 // If the operand is an bitwise operator with a constant RHS, and the
5305 // shift is the only use, we can pull it out of the shift.
5306 if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
5307 bool isValid = true; // Valid only for And, Or, Xor
5308 bool highBitSet = false; // Transform if high bit of constant set?
5309
5310 switch (Op0BO->getOpcode()) {
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00005311 default: isValid = false; break; // Do not perform transform!
Chris Lattner44bd3922004-10-08 03:46:20 +00005312 case Instruction::Add:
5313 isValid = isLeftShift;
5314 break;
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00005315 case Instruction::Or:
5316 case Instruction::Xor:
5317 highBitSet = false;
5318 break;
5319 case Instruction::And:
5320 highBitSet = true;
5321 break;
Chris Lattner14553932006-01-06 07:12:35 +00005322 }
5323
5324 // If this is a signed shift right, and the high bit is modified
5325 // by the logical operation, do not perform the transformation.
5326 // The highBitSet boolean indicates the value of the high bit of
5327 // the constant which would cause it to be modified for this
5328 // operation.
5329 //
Chris Lattnerb3309392006-01-06 07:22:22 +00005330 if (isValid && !isLeftShift && isSignedShift) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00005331 uint64_t Val = Op0C->getZExtValue();
Chris Lattner14553932006-01-06 07:12:35 +00005332 isValid = ((Val & (1 << (TypeBits-1))) != 0) == highBitSet;
5333 }
5334
5335 if (isValid) {
5336 Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, Op1);
5337
5338 Instruction *NewShift =
5339 new ShiftInst(I.getOpcode(), Op0BO->getOperand(0), Op1,
5340 Op0BO->getName());
5341 Op0BO->setName("");
5342 InsertNewInstBefore(NewShift, I);
5343
5344 return BinaryOperator::create(Op0BO->getOpcode(), NewShift,
5345 NewRHS);
5346 }
5347 }
5348 }
5349 }
5350
Chris Lattnereb372a02006-01-06 07:52:12 +00005351 // Find out if this is a shift of a shift by a constant.
5352 ShiftInst *ShiftOp = 0;
Chris Lattner14553932006-01-06 07:12:35 +00005353 if (ShiftInst *Op0SI = dyn_cast<ShiftInst>(Op0))
Chris Lattnereb372a02006-01-06 07:52:12 +00005354 ShiftOp = Op0SI;
Reid Spencer6c38f0b2006-11-27 01:05:10 +00005355 else if (BitCastInst *CI = dyn_cast<BitCastInst>(Op0)) {
5356 // If this is a noop-integer cast of a shift instruction, use the shift.
5357 if (isa<ShiftInst>(CI->getOperand(0))) {
Chris Lattnereb372a02006-01-06 07:52:12 +00005358 ShiftOp = cast<ShiftInst>(CI->getOperand(0));
5359 }
5360 }
5361
Reid Spencere0fc4df2006-10-20 07:07:24 +00005362 if (ShiftOp && isa<ConstantInt>(ShiftOp->getOperand(1))) {
Chris Lattnereb372a02006-01-06 07:52:12 +00005363 // Find the operands and properties of the input shift. Note that the
5364 // signedness of the input shift may differ from the current shift if there
5365 // is a noop cast between the two.
5366 bool isShiftOfLeftShift = ShiftOp->getOpcode() == Instruction::Shl;
Reid Spencerfdff9382006-11-08 06:47:33 +00005367 bool isShiftOfSignedShift = isShiftOfLeftShift ?
5368 ShiftOp->getType()->isSigned() :
5369 ShiftOp->getOpcode() == Instruction::AShr;
Chris Lattner9cbfbc22006-01-07 01:32:28 +00005370 bool isShiftOfUnsignedShift = !isShiftOfSignedShift;
Chris Lattnereb372a02006-01-06 07:52:12 +00005371
Reid Spencere0fc4df2006-10-20 07:07:24 +00005372 ConstantInt *ShiftAmt1C = cast<ConstantInt>(ShiftOp->getOperand(1));
Chris Lattnereb372a02006-01-06 07:52:12 +00005373
Reid Spencere0fc4df2006-10-20 07:07:24 +00005374 unsigned ShiftAmt1 = (unsigned)ShiftAmt1C->getZExtValue();
5375 unsigned ShiftAmt2 = (unsigned)Op1->getZExtValue();
Chris Lattnereb372a02006-01-06 07:52:12 +00005376
5377 // Check for (A << c1) << c2 and (A >> c1) >> c2.
5378 if (isLeftShift == isShiftOfLeftShift) {
5379 // Do not fold these shifts if the first one is signed and the second one
5380 // is unsigned and this is a right shift. Further, don't do any folding
5381 // on them.
5382 if (isShiftOfSignedShift && isUnsignedShift && !isLeftShift)
5383 return 0;
Chris Lattner14553932006-01-06 07:12:35 +00005384
Chris Lattnereb372a02006-01-06 07:52:12 +00005385 unsigned Amt = ShiftAmt1+ShiftAmt2; // Fold into one big shift.
5386 if (Amt > Op0->getType()->getPrimitiveSizeInBits())
5387 Amt = Op0->getType()->getPrimitiveSizeInBits();
Chris Lattner14553932006-01-06 07:12:35 +00005388
Chris Lattnereb372a02006-01-06 07:52:12 +00005389 Value *Op = ShiftOp->getOperand(0);
5390 if (isShiftOfSignedShift != isSignedShift)
Reid Spencerbb65ebf2006-12-12 23:36:14 +00005391 Op = InsertNewInstBefore(new BitCastInst(Op, I.getType(), "tmp"), I);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00005392 ShiftInst *ShiftResult = new ShiftInst(I.getOpcode(), Op,
Reid Spencere0fc4df2006-10-20 07:07:24 +00005393 ConstantInt::get(Type::UByteTy, Amt));
Reid Spencerfdff9382006-11-08 06:47:33 +00005394 if (I.getType() == ShiftResult->getType())
5395 return ShiftResult;
5396 InsertNewInstBefore(ShiftResult, I);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00005397 return CastInst::create(Instruction::BitCast, ShiftResult, I.getType());
Chris Lattnereb372a02006-01-06 07:52:12 +00005398 }
5399
5400 // Check for (A << c1) >> c2 or (A >> c1) << c2. If we are dealing with
5401 // signed types, we can only support the (A >> c1) << c2 configuration,
5402 // because it can not turn an arbitrary bit of A into a sign bit.
5403 if (isUnsignedShift || isLeftShift) {
5404 // Calculate bitmask for what gets shifted off the edge.
5405 Constant *C = ConstantIntegral::getAllOnesValue(I.getType());
5406 if (isLeftShift)
5407 C = ConstantExpr::getShl(C, ShiftAmt1C);
5408 else
Reid Spencerfdff9382006-11-08 06:47:33 +00005409 C = ConstantExpr::getLShr(C, ShiftAmt1C);
Chris Lattnereb372a02006-01-06 07:52:12 +00005410
5411 Value *Op = ShiftOp->getOperand(0);
Reid Spencerfdff9382006-11-08 06:47:33 +00005412 if (Op->getType() != C->getType())
Reid Spencer13bc5d72006-12-12 09:18:51 +00005413 Op = InsertCastBefore(Instruction::BitCast, Op, I.getType(), I);
Chris Lattnereb372a02006-01-06 07:52:12 +00005414
5415 Instruction *Mask =
5416 BinaryOperator::createAnd(Op, C, Op->getName()+".mask");
5417 InsertNewInstBefore(Mask, I);
5418
5419 // Figure out what flavor of shift we should use...
Chris Lattner9cbfbc22006-01-07 01:32:28 +00005420 if (ShiftAmt1 == ShiftAmt2) {
Chris Lattnereb372a02006-01-06 07:52:12 +00005421 return ReplaceInstUsesWith(I, Mask); // (A << c) >> c === A & c2
Chris Lattner9cbfbc22006-01-07 01:32:28 +00005422 } else if (ShiftAmt1 < ShiftAmt2) {
Chris Lattnereb372a02006-01-06 07:52:12 +00005423 return new ShiftInst(I.getOpcode(), Mask,
Reid Spencere0fc4df2006-10-20 07:07:24 +00005424 ConstantInt::get(Type::UByteTy, ShiftAmt2-ShiftAmt1));
Chris Lattner9cbfbc22006-01-07 01:32:28 +00005425 } else if (isShiftOfUnsignedShift || isShiftOfLeftShift) {
5426 if (isShiftOfUnsignedShift && !isShiftOfLeftShift && isSignedShift) {
Reid Spencerfdff9382006-11-08 06:47:33 +00005427 return new ShiftInst(Instruction::LShr, Mask,
5428 ConstantInt::get(Type::UByteTy, ShiftAmt1-ShiftAmt2));
Chris Lattner9cbfbc22006-01-07 01:32:28 +00005429 } else {
5430 return new ShiftInst(ShiftOp->getOpcode(), Mask,
Reid Spencere0fc4df2006-10-20 07:07:24 +00005431 ConstantInt::get(Type::UByteTy, ShiftAmt1-ShiftAmt2));
Chris Lattner9cbfbc22006-01-07 01:32:28 +00005432 }
5433 } else {
5434 // (X >>s C1) << C2 where C1 > C2 === (X >>s (C1-C2)) & mask
Reid Spencer13bc5d72006-12-12 09:18:51 +00005435 Op = InsertCastBefore(Instruction::BitCast, Mask,
5436 I.getType()->getSignedVersion(), I);
Chris Lattner9cbfbc22006-01-07 01:32:28 +00005437 Instruction *Shift =
5438 new ShiftInst(ShiftOp->getOpcode(), Op,
Reid Spencere0fc4df2006-10-20 07:07:24 +00005439 ConstantInt::get(Type::UByteTy, ShiftAmt1-ShiftAmt2));
Chris Lattner9cbfbc22006-01-07 01:32:28 +00005440 InsertNewInstBefore(Shift, I);
5441
5442 C = ConstantIntegral::getAllOnesValue(Shift->getType());
5443 C = ConstantExpr::getShl(C, Op1);
5444 Mask = BinaryOperator::createAnd(Shift, C, Op->getName()+".mask");
5445 InsertNewInstBefore(Mask, I);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00005446 return CastInst::create(Instruction::BitCast, Mask, I.getType());
Chris Lattnereb372a02006-01-06 07:52:12 +00005447 }
5448 } else {
Chris Lattner9cbfbc22006-01-07 01:32:28 +00005449 // We can handle signed (X << C1) >>s C2 if it's a sign extend. In
Chris Lattnereb372a02006-01-06 07:52:12 +00005450 // this case, C1 == C2 and C1 is 8, 16, or 32.
5451 if (ShiftAmt1 == ShiftAmt2) {
5452 const Type *SExtType = 0;
Chris Lattner655d08f2006-04-28 22:21:41 +00005453 switch (Op0->getType()->getPrimitiveSizeInBits() - ShiftAmt1) {
Chris Lattnereb372a02006-01-06 07:52:12 +00005454 case 8 : SExtType = Type::SByteTy; break;
5455 case 16: SExtType = Type::ShortTy; break;
5456 case 32: SExtType = Type::IntTy; break;
5457 }
5458
5459 if (SExtType) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +00005460 Instruction *NewTrunc =
5461 new TruncInst(ShiftOp->getOperand(0), SExtType, "sext");
Chris Lattnereb372a02006-01-06 07:52:12 +00005462 InsertNewInstBefore(NewTrunc, I);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00005463 return new SExtInst(NewTrunc, I.getType());
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00005464 }
Chris Lattner27cb9db2005-09-18 05:12:10 +00005465 }
Chris Lattner86102b82005-01-01 16:22:27 +00005466 }
Chris Lattnereb372a02006-01-06 07:52:12 +00005467 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00005468 return 0;
5469}
5470
Chris Lattner48a44f72002-05-02 17:06:02 +00005471
Chris Lattner8f663e82005-10-29 04:36:15 +00005472/// DecomposeSimpleLinearExpr - Analyze 'Val', seeing if it is a simple linear
5473/// expression. If so, decompose it, returning some value X, such that Val is
5474/// X*Scale+Offset.
5475///
5476static Value *DecomposeSimpleLinearExpr(Value *Val, unsigned &Scale,
5477 unsigned &Offset) {
5478 assert(Val->getType() == Type::UIntTy && "Unexpected allocation size type!");
Reid Spencere0fc4df2006-10-20 07:07:24 +00005479 if (ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
5480 if (CI->getType()->isUnsigned()) {
5481 Offset = CI->getZExtValue();
5482 Scale = 1;
5483 return ConstantInt::get(Type::UIntTy, 0);
5484 }
Chris Lattner8f663e82005-10-29 04:36:15 +00005485 } else if (Instruction *I = dyn_cast<Instruction>(Val)) {
5486 if (I->getNumOperands() == 2) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00005487 if (ConstantInt *CUI = dyn_cast<ConstantInt>(I->getOperand(1))) {
5488 if (CUI->getType()->isUnsigned()) {
5489 if (I->getOpcode() == Instruction::Shl) {
5490 // This is a value scaled by '1 << the shift amt'.
5491 Scale = 1U << CUI->getZExtValue();
5492 Offset = 0;
5493 return I->getOperand(0);
5494 } else if (I->getOpcode() == Instruction::Mul) {
5495 // This value is scaled by 'CUI'.
5496 Scale = CUI->getZExtValue();
5497 Offset = 0;
5498 return I->getOperand(0);
5499 } else if (I->getOpcode() == Instruction::Add) {
5500 // We have X+C. Check to see if we really have (X*C2)+C1,
5501 // where C1 is divisible by C2.
5502 unsigned SubScale;
5503 Value *SubVal =
5504 DecomposeSimpleLinearExpr(I->getOperand(0), SubScale, Offset);
5505 Offset += CUI->getZExtValue();
5506 if (SubScale > 1 && (Offset % SubScale == 0)) {
5507 Scale = SubScale;
5508 return SubVal;
5509 }
Chris Lattner8f663e82005-10-29 04:36:15 +00005510 }
5511 }
5512 }
5513 }
5514 }
5515
5516 // Otherwise, we can't look past this.
5517 Scale = 1;
5518 Offset = 0;
5519 return Val;
5520}
5521
5522
Chris Lattner216be912005-10-24 06:03:58 +00005523/// PromoteCastOfAllocation - If we find a cast of an allocation instruction,
5524/// try to eliminate the cast by moving the type information into the alloc.
5525Instruction *InstCombiner::PromoteCastOfAllocation(CastInst &CI,
5526 AllocationInst &AI) {
5527 const PointerType *PTy = dyn_cast<PointerType>(CI.getType());
Chris Lattnerbb171802005-10-27 05:53:56 +00005528 if (!PTy) return 0; // Not casting the allocation to a pointer type.
Chris Lattner216be912005-10-24 06:03:58 +00005529
Chris Lattnerac87beb2005-10-24 06:22:12 +00005530 // Remove any uses of AI that are dead.
5531 assert(!CI.use_empty() && "Dead instructions should be removed earlier!");
5532 std::vector<Instruction*> DeadUsers;
5533 for (Value::use_iterator UI = AI.use_begin(), E = AI.use_end(); UI != E; ) {
5534 Instruction *User = cast<Instruction>(*UI++);
5535 if (isInstructionTriviallyDead(User)) {
5536 while (UI != E && *UI == User)
5537 ++UI; // If this instruction uses AI more than once, don't break UI.
5538
5539 // Add operands to the worklist.
5540 AddUsesToWorkList(*User);
5541 ++NumDeadInst;
Bill Wendling5dbf43c2006-11-26 09:46:52 +00005542 DOUT << "IC: DCE: " << *User;
Chris Lattnerac87beb2005-10-24 06:22:12 +00005543
5544 User->eraseFromParent();
5545 removeFromWorkList(User);
5546 }
5547 }
5548
Chris Lattner216be912005-10-24 06:03:58 +00005549 // Get the type really allocated and the type casted to.
5550 const Type *AllocElTy = AI.getAllocatedType();
5551 const Type *CastElTy = PTy->getElementType();
5552 if (!AllocElTy->isSized() || !CastElTy->isSized()) return 0;
Chris Lattner355ecc02005-10-24 06:26:18 +00005553
Chris Lattner7d190672006-10-01 19:40:58 +00005554 unsigned AllocElTyAlign = TD->getTypeAlignment(AllocElTy);
5555 unsigned CastElTyAlign = TD->getTypeAlignment(CastElTy);
Chris Lattner355ecc02005-10-24 06:26:18 +00005556 if (CastElTyAlign < AllocElTyAlign) return 0;
5557
Chris Lattner46705b22005-10-24 06:35:18 +00005558 // If the allocation has multiple uses, only promote it if we are strictly
5559 // increasing the alignment of the resultant allocation. If we keep it the
5560 // same, we open the door to infinite loops of various kinds.
5561 if (!AI.hasOneUse() && CastElTyAlign == AllocElTyAlign) return 0;
5562
Chris Lattner216be912005-10-24 06:03:58 +00005563 uint64_t AllocElTySize = TD->getTypeSize(AllocElTy);
5564 uint64_t CastElTySize = TD->getTypeSize(CastElTy);
Chris Lattnerbb171802005-10-27 05:53:56 +00005565 if (CastElTySize == 0 || AllocElTySize == 0) return 0;
Chris Lattner355ecc02005-10-24 06:26:18 +00005566
Chris Lattner8270c332005-10-29 03:19:53 +00005567 // See if we can satisfy the modulus by pulling a scale out of the array
5568 // size argument.
Chris Lattner8f663e82005-10-29 04:36:15 +00005569 unsigned ArraySizeScale, ArrayOffset;
5570 Value *NumElements = // See if the array size is a decomposable linear expr.
5571 DecomposeSimpleLinearExpr(AI.getOperand(0), ArraySizeScale, ArrayOffset);
5572
Chris Lattner8270c332005-10-29 03:19:53 +00005573 // If we can now satisfy the modulus, by using a non-1 scale, we really can
5574 // do the xform.
Chris Lattner8f663e82005-10-29 04:36:15 +00005575 if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 ||
5576 (AllocElTySize*ArrayOffset ) % CastElTySize != 0) return 0;
Chris Lattnerb3ecf962005-10-27 06:12:00 +00005577
Chris Lattner8270c332005-10-29 03:19:53 +00005578 unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize;
5579 Value *Amt = 0;
5580 if (Scale == 1) {
5581 Amt = NumElements;
5582 } else {
Reid Spencere0fc4df2006-10-20 07:07:24 +00005583 // If the allocation size is constant, form a constant mul expression
5584 Amt = ConstantInt::get(Type::UIntTy, Scale);
5585 if (isa<ConstantInt>(NumElements) && NumElements->getType()->isUnsigned())
5586 Amt = ConstantExpr::getMul(
5587 cast<ConstantInt>(NumElements), cast<ConstantInt>(Amt));
5588 // otherwise multiply the amount and the number of elements
Chris Lattner8270c332005-10-29 03:19:53 +00005589 else if (Scale != 1) {
5590 Instruction *Tmp = BinaryOperator::createMul(Amt, NumElements, "tmp");
5591 Amt = InsertNewInstBefore(Tmp, AI);
Chris Lattnerb3ecf962005-10-27 06:12:00 +00005592 }
Chris Lattnerbb171802005-10-27 05:53:56 +00005593 }
5594
Chris Lattner8f663e82005-10-29 04:36:15 +00005595 if (unsigned Offset = (AllocElTySize*ArrayOffset)/CastElTySize) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00005596 Value *Off = ConstantInt::get(Type::UIntTy, Offset);
Chris Lattner8f663e82005-10-29 04:36:15 +00005597 Instruction *Tmp = BinaryOperator::createAdd(Amt, Off, "tmp");
5598 Amt = InsertNewInstBefore(Tmp, AI);
5599 }
5600
Chris Lattner216be912005-10-24 06:03:58 +00005601 std::string Name = AI.getName(); AI.setName("");
5602 AllocationInst *New;
5603 if (isa<MallocInst>(AI))
Nate Begeman848622f2005-11-05 09:21:28 +00005604 New = new MallocInst(CastElTy, Amt, AI.getAlignment(), Name);
Chris Lattner216be912005-10-24 06:03:58 +00005605 else
Nate Begeman848622f2005-11-05 09:21:28 +00005606 New = new AllocaInst(CastElTy, Amt, AI.getAlignment(), Name);
Chris Lattner216be912005-10-24 06:03:58 +00005607 InsertNewInstBefore(New, AI);
Chris Lattner46705b22005-10-24 06:35:18 +00005608
5609 // If the allocation has multiple uses, insert a cast and change all things
5610 // that used it to use the new cast. This will also hack on CI, but it will
5611 // die soon.
5612 if (!AI.hasOneUse()) {
5613 AddUsesToWorkList(AI);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00005614 // New is the allocation instruction, pointer typed. AI is the original
5615 // allocation instruction, also pointer typed. Thus, cast to use is BitCast.
5616 CastInst *NewCast = new BitCastInst(New, AI.getType(), "tmpcast");
Chris Lattner46705b22005-10-24 06:35:18 +00005617 InsertNewInstBefore(NewCast, AI);
5618 AI.replaceAllUsesWith(NewCast);
5619 }
Chris Lattner216be912005-10-24 06:03:58 +00005620 return ReplaceInstUsesWith(CI, New);
5621}
5622
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00005623/// CanEvaluateInDifferentType - Return true if we can take the specified value
5624/// and return it without inserting any new casts. This is used by code that
5625/// tries to decide whether promoting or shrinking integer operations to wider
5626/// or smaller types will allow us to eliminate a truncate or extend.
5627static bool CanEvaluateInDifferentType(Value *V, const Type *Ty,
5628 int &NumCastsRemoved) {
5629 if (isa<Constant>(V)) return true;
5630
5631 Instruction *I = dyn_cast<Instruction>(V);
5632 if (!I || !I->hasOneUse()) return false;
5633
5634 switch (I->getOpcode()) {
5635 case Instruction::And:
5636 case Instruction::Or:
5637 case Instruction::Xor:
5638 // These operators can all arbitrarily be extended or truncated.
5639 return CanEvaluateInDifferentType(I->getOperand(0), Ty, NumCastsRemoved) &&
5640 CanEvaluateInDifferentType(I->getOperand(1), Ty, NumCastsRemoved);
Chris Lattner960acb02006-11-29 07:18:39 +00005641 case Instruction::AShr:
5642 case Instruction::LShr:
5643 case Instruction::Shl:
5644 // If this is just a bitcast changing the sign of the operation, we can
5645 // convert if the operand can be converted.
5646 if (V->getType()->getPrimitiveSizeInBits() == Ty->getPrimitiveSizeInBits())
5647 return CanEvaluateInDifferentType(I->getOperand(0), Ty, NumCastsRemoved);
5648 break;
Reid Spencer6c38f0b2006-11-27 01:05:10 +00005649 case Instruction::Trunc:
5650 case Instruction::ZExt:
5651 case Instruction::SExt:
5652 case Instruction::BitCast:
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00005653 // If this is a cast from the destination type, we can trivially eliminate
5654 // it, and this will remove a cast overall.
5655 if (I->getOperand(0)->getType() == Ty) {
Chris Lattner3fda3862006-06-28 17:34:50 +00005656 // If the first operand is itself a cast, and is eliminable, do not count
5657 // this as an eliminable cast. We would prefer to eliminate those two
5658 // casts first.
Reid Spencerde46e482006-11-02 20:25:50 +00005659 if (isa<CastInst>(I->getOperand(0)))
Chris Lattner3fda3862006-06-28 17:34:50 +00005660 return true;
5661
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00005662 ++NumCastsRemoved;
5663 return true;
5664 }
Reid Spencer6c38f0b2006-11-27 01:05:10 +00005665 break;
5666 default:
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00005667 // TODO: Can handle more cases here.
5668 break;
5669 }
5670
5671 return false;
5672}
5673
5674/// EvaluateInDifferentType - Given an expression that
5675/// CanEvaluateInDifferentType returns true for, actually insert the code to
5676/// evaluate the expression.
5677Value *InstCombiner::EvaluateInDifferentType(Value *V, const Type *Ty) {
5678 if (Constant *C = dyn_cast<Constant>(V))
Reid Spencerbb65ebf2006-12-12 23:36:14 +00005679 return ConstantExpr::getIntegerCast(C, Ty, C->getType()->isSigned());
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00005680
5681 // Otherwise, it must be an instruction.
5682 Instruction *I = cast<Instruction>(V);
Chris Lattnerd0622b62006-05-20 23:14:03 +00005683 Instruction *Res = 0;
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00005684 switch (I->getOpcode()) {
5685 case Instruction::And:
5686 case Instruction::Or:
5687 case Instruction::Xor: {
5688 Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty);
5689 Value *RHS = EvaluateInDifferentType(I->getOperand(1), Ty);
5690 Res = BinaryOperator::create((Instruction::BinaryOps)I->getOpcode(),
5691 LHS, RHS, I->getName());
5692 break;
5693 }
Chris Lattner960acb02006-11-29 07:18:39 +00005694 case Instruction::AShr:
5695 case Instruction::LShr:
5696 case Instruction::Shl: {
5697 Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty);
5698 Res = new ShiftInst((Instruction::OtherOps)I->getOpcode(), LHS,
5699 I->getOperand(1), I->getName());
5700 break;
5701 }
Reid Spencer6c38f0b2006-11-27 01:05:10 +00005702 case Instruction::Trunc:
5703 case Instruction::ZExt:
5704 case Instruction::SExt:
5705 case Instruction::BitCast:
5706 // If the source type of the cast is the type we're trying for then we can
5707 // just return the source. There's no need to insert it because its not new.
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00005708 if (I->getOperand(0)->getType() == Ty)
5709 return I->getOperand(0);
5710
Reid Spencer6c38f0b2006-11-27 01:05:10 +00005711 // Some other kind of cast, which shouldn't happen, so just ..
5712 // FALL THROUGH
5713 default:
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00005714 // TODO: Can handle more cases here.
5715 assert(0 && "Unreachable!");
5716 break;
5717 }
5718
5719 return InsertNewInstBefore(Res, *I);
5720}
5721
Reid Spencer6c38f0b2006-11-27 01:05:10 +00005722/// @brief Implement the transforms common to all CastInst visitors.
5723Instruction *InstCombiner::commonCastTransforms(CastInst &CI) {
Chris Lattner55d4bda2003-06-23 21:59:52 +00005724 Value *Src = CI.getOperand(0);
5725
Reid Spencer6c38f0b2006-11-27 01:05:10 +00005726 // Casting undef to anything results in undef so might as just replace it and
5727 // get rid of the cast.
Chris Lattner81a7a232004-10-16 18:11:37 +00005728 if (isa<UndefValue>(Src)) // cast undef -> undef
5729 return ReplaceInstUsesWith(CI, UndefValue::get(CI.getType()));
5730
Reid Spencer6c38f0b2006-11-27 01:05:10 +00005731 // Many cases of "cast of a cast" are eliminable. If its eliminable we just
5732 // eliminate it now.
Chris Lattner86102b82005-01-01 16:22:27 +00005733 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
Reid Spencer6c38f0b2006-11-27 01:05:10 +00005734 if (Instruction::CastOps opc =
5735 isEliminableCastPair(CSrc, CI.getOpcode(), CI.getType(), TD)) {
5736 // The first cast (CSrc) is eliminable so we need to fix up or replace
5737 // the second cast (CI). CSrc will then have a good chance of being dead.
5738 return CastInst::create(opc, CSrc->getOperand(0), CI.getType());
Chris Lattner650b6da2002-08-02 20:00:25 +00005739 }
5740 }
Chris Lattner03841652004-05-25 04:29:21 +00005741
Chris Lattnerd0d51602003-06-21 23:12:02 +00005742 // If casting the result of a getelementptr instruction with no offset, turn
5743 // this into a cast of the original pointer!
5744 //
Chris Lattner55d4bda2003-06-23 21:59:52 +00005745 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
Chris Lattnerd0d51602003-06-21 23:12:02 +00005746 bool AllZeroOperands = true;
5747 for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i)
5748 if (!isa<Constant>(GEP->getOperand(i)) ||
5749 !cast<Constant>(GEP->getOperand(i))->isNullValue()) {
5750 AllZeroOperands = false;
5751 break;
5752 }
5753 if (AllZeroOperands) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +00005754 // Changing the cast operand is usually not a good idea but it is safe
5755 // here because the pointer operand is being replaced with another
5756 // pointer operand so the opcode doesn't need to change.
Chris Lattnerd0d51602003-06-21 23:12:02 +00005757 CI.setOperand(0, GEP->getOperand(0));
5758 return &CI;
5759 }
5760 }
Chris Lattnerec45a4c2006-11-21 17:05:13 +00005761
Chris Lattnerf4ad1652003-11-02 05:57:39 +00005762 // If we are casting a malloc or alloca to a pointer to a type of the same
5763 // size, rewrite the allocation instruction to allocate the "right" type.
Chris Lattnerf4ad1652003-11-02 05:57:39 +00005764 if (AllocationInst *AI = dyn_cast<AllocationInst>(Src))
Chris Lattner216be912005-10-24 06:03:58 +00005765 if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
5766 return V;
Chris Lattnerf4ad1652003-11-02 05:57:39 +00005767
Reid Spencer6c38f0b2006-11-27 01:05:10 +00005768 // If we are casting a select then fold the cast into the select
Chris Lattner86102b82005-01-01 16:22:27 +00005769 if (SelectInst *SI = dyn_cast<SelectInst>(Src))
5770 if (Instruction *NV = FoldOpIntoSelect(CI, SI, this))
5771 return NV;
Reid Spencer6c38f0b2006-11-27 01:05:10 +00005772
5773 // If we are casting a PHI then fold the cast into the PHI
Chris Lattner6a4adcd2004-09-29 05:07:12 +00005774 if (isa<PHINode>(Src))
5775 if (Instruction *NV = FoldOpIntoPhi(CI))
5776 return NV;
Chris Lattnerb19a5c62006-04-12 18:09:35 +00005777
Reid Spencer6c38f0b2006-11-27 01:05:10 +00005778 return 0;
5779}
5780
5781/// Only the TRUNC, ZEXT, SEXT, and BITCONVERT can have both operands as
5782/// integers. This function implements the common transforms for all those
5783/// cases.
5784/// @brief Implement the transforms common to CastInst with integer operands
5785Instruction *InstCombiner::commonIntCastTransforms(CastInst &CI) {
5786 if (Instruction *Result = commonCastTransforms(CI))
5787 return Result;
5788
5789 Value *Src = CI.getOperand(0);
5790 const Type *SrcTy = Src->getType();
5791 const Type *DestTy = CI.getType();
5792 unsigned SrcBitSize = SrcTy->getPrimitiveSizeInBits();
5793 unsigned DestBitSize = DestTy->getPrimitiveSizeInBits();
5794
Reid Spencer6c38f0b2006-11-27 01:05:10 +00005795 // See if we can simplify any instructions used by the LHS whose sole
5796 // purpose is to compute bits we don't care about.
5797 uint64_t KnownZero = 0, KnownOne = 0;
5798 if (SimplifyDemandedBits(&CI, DestTy->getIntegralTypeMask(),
5799 KnownZero, KnownOne))
5800 return &CI;
5801
5802 // If the source isn't an instruction or has more than one use then we
5803 // can't do anything more.
5804 if (!isa<Instruction>(Src) || !Src->hasOneUse())
5805 return 0;
5806
5807 // Attempt to propagate the cast into the instruction.
5808 Instruction *SrcI = cast<Instruction>(Src);
5809 int NumCastsRemoved = 0;
5810 if (CanEvaluateInDifferentType(SrcI, DestTy, NumCastsRemoved)) {
5811 // If this cast is a truncate, evaluting in a different type always
5812 // eliminates the cast, so it is always a win. If this is a noop-cast
5813 // this just removes a noop cast which isn't pointful, but simplifies
5814 // the code. If this is a zero-extension, we need to do an AND to
5815 // maintain the clear top-part of the computation, so we require that
5816 // the input have eliminated at least one cast. If this is a sign
5817 // extension, we insert two new casts (to do the extension) so we
5818 // require that two casts have been eliminated.
5819 bool DoXForm = CI.isNoopCast(TD->getIntPtrType());
5820 if (!DoXForm) {
5821 switch (CI.getOpcode()) {
5822 case Instruction::Trunc:
5823 DoXForm = true;
5824 break;
5825 case Instruction::ZExt:
5826 DoXForm = NumCastsRemoved >= 1;
5827 break;
5828 case Instruction::SExt:
5829 DoXForm = NumCastsRemoved >= 2;
5830 break;
5831 case Instruction::BitCast:
5832 DoXForm = false;
5833 break;
5834 default:
5835 // All the others use floating point so we shouldn't actually
5836 // get here because of the check above.
5837 assert(!"Unknown cast type .. unreachable");
5838 break;
5839 }
5840 }
5841
5842 if (DoXForm) {
5843 Value *Res = EvaluateInDifferentType(SrcI, DestTy);
5844 assert(Res->getType() == DestTy);
5845 switch (CI.getOpcode()) {
5846 default: assert(0 && "Unknown cast type!");
5847 case Instruction::Trunc:
5848 case Instruction::BitCast:
5849 // Just replace this cast with the result.
5850 return ReplaceInstUsesWith(CI, Res);
5851 case Instruction::ZExt: {
5852 // We need to emit an AND to clear the high bits.
5853 assert(SrcBitSize < DestBitSize && "Not a zext?");
5854 Constant *C =
5855 ConstantInt::get(Type::ULongTy, (1ULL << SrcBitSize)-1);
5856 if (DestBitSize < 64)
5857 C = ConstantExpr::getTrunc(C, DestTy);
5858 else {
5859 assert(DestBitSize == 64);
5860 C = ConstantExpr::getBitCast(C, DestTy);
5861 }
5862 return BinaryOperator::createAnd(Res, C);
5863 }
5864 case Instruction::SExt:
5865 // We need to emit a cast to truncate, then a cast to sext.
5866 return CastInst::create(Instruction::SExt,
Reid Spencer13bc5d72006-12-12 09:18:51 +00005867 InsertCastBefore(Instruction::Trunc, Res, Src->getType(),
5868 CI), DestTy);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00005869 }
5870 }
5871 }
5872
5873 Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
5874 Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
5875
5876 switch (SrcI->getOpcode()) {
5877 case Instruction::Add:
5878 case Instruction::Mul:
5879 case Instruction::And:
5880 case Instruction::Or:
5881 case Instruction::Xor:
5882 // If we are discarding information, or just changing the sign,
5883 // rewrite.
5884 if (DestBitSize <= SrcBitSize && DestBitSize != 1) {
5885 // Don't insert two casts if they cannot be eliminated. We allow
5886 // two casts to be inserted if the sizes are the same. This could
5887 // only be converting signedness, which is a noop.
5888 if (DestBitSize == SrcBitSize ||
5889 !ValueRequiresCast(Op1, DestTy,TD) ||
5890 !ValueRequiresCast(Op0, DestTy, TD)) {
Reid Spencer13bc5d72006-12-12 09:18:51 +00005891 unsigned Op0BitSize = Op0->getType()->getPrimitiveSizeInBits();
5892 Instruction::CastOps opcode =
5893 (Op0BitSize > DestBitSize ? Instruction::Trunc :
5894 (Op0BitSize == DestBitSize ? Instruction::BitCast :
5895 Op0->getType()->isSigned() ? Instruction::SExt :Instruction::ZExt));
5896 Value *Op0c = InsertOperandCastBefore(opcode, Op0, DestTy, SrcI);
5897 Value *Op1c = InsertOperandCastBefore(opcode, Op1, DestTy, SrcI);
5898 return BinaryOperator::create(
5899 cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00005900 }
5901 }
5902
5903 // cast (xor bool X, true) to int --> xor (cast bool X to int), 1
5904 if (isa<ZExtInst>(CI) && SrcBitSize == 1 &&
5905 SrcI->getOpcode() == Instruction::Xor &&
5906 Op1 == ConstantBool::getTrue() &&
5907 (!Op0->hasOneUse() || !isa<SetCondInst>(Op0))) {
Reid Spencer13bc5d72006-12-12 09:18:51 +00005908 Value *New = InsertOperandCastBefore(Instruction::ZExt, Op0, DestTy, &CI);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00005909 return BinaryOperator::createXor(New, ConstantInt::get(CI.getType(), 1));
5910 }
5911 break;
5912 case Instruction::SDiv:
5913 case Instruction::UDiv:
5914 case Instruction::SRem:
5915 case Instruction::URem:
5916 // If we are just changing the sign, rewrite.
5917 if (DestBitSize == SrcBitSize) {
5918 // Don't insert two casts if they cannot be eliminated. We allow
5919 // two casts to be inserted if the sizes are the same. This could
5920 // only be converting signedness, which is a noop.
5921 if (!ValueRequiresCast(Op1, DestTy,TD) ||
5922 !ValueRequiresCast(Op0, DestTy, TD)) {
Reid Spencer13bc5d72006-12-12 09:18:51 +00005923 Value *Op0c = InsertOperandCastBefore(Instruction::BitCast,
5924 Op0, DestTy, SrcI);
5925 Value *Op1c = InsertOperandCastBefore(Instruction::BitCast,
5926 Op1, DestTy, SrcI);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00005927 return BinaryOperator::create(
5928 cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
5929 }
5930 }
5931 break;
5932
5933 case Instruction::Shl:
5934 // Allow changing the sign of the source operand. Do not allow
5935 // changing the size of the shift, UNLESS the shift amount is a
5936 // constant. We must not change variable sized shifts to a smaller
5937 // size, because it is undefined to shift more bits out than exist
5938 // in the value.
5939 if (DestBitSize == SrcBitSize ||
5940 (DestBitSize < SrcBitSize && isa<Constant>(Op1))) {
Reid Spencer13bc5d72006-12-12 09:18:51 +00005941 Instruction::CastOps opcode = (DestBitSize == SrcBitSize ?
5942 Instruction::BitCast : Instruction::Trunc);
5943 Value *Op0c = InsertOperandCastBefore(opcode, Op0, DestTy, SrcI);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00005944 return new ShiftInst(Instruction::Shl, Op0c, Op1);
5945 }
5946 break;
5947 case Instruction::AShr:
5948 // If this is a signed shr, and if all bits shifted in are about to be
5949 // truncated off, turn it into an unsigned shr to allow greater
5950 // simplifications.
5951 if (DestBitSize < SrcBitSize &&
5952 isa<ConstantInt>(Op1)) {
5953 unsigned ShiftAmt = cast<ConstantInt>(Op1)->getZExtValue();
5954 if (SrcBitSize > ShiftAmt && SrcBitSize-ShiftAmt >= DestBitSize) {
5955 // Insert the new logical shift right.
5956 return new ShiftInst(Instruction::LShr, Op0, Op1);
5957 }
5958 }
5959 break;
5960
5961 case Instruction::SetEQ:
5962 case Instruction::SetNE:
5963 // If we are just checking for a seteq of a single bit and casting it
5964 // to an integer. If so, shift the bit to the appropriate place then
5965 // cast to integer to avoid the comparison.
5966 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(Op1)) {
5967 uint64_t Op1CV = Op1C->getZExtValue();
5968 // cast (X == 0) to int --> X^1 iff X has only the low bit set.
5969 // cast (X == 0) to int --> (X>>1)^1 iff X has only the 2nd bit set.
5970 // cast (X == 1) to int --> X iff X has only the low bit set.
5971 // cast (X == 2) to int --> X>>1 iff X has only the 2nd bit set.
5972 // cast (X != 0) to int --> X iff X has only the low bit set.
5973 // cast (X != 0) to int --> X>>1 iff X has only the 2nd bit set.
5974 // cast (X != 1) to int --> X^1 iff X has only the low bit set.
5975 // cast (X != 2) to int --> (X>>1)^1 iff X has only the 2nd bit set.
5976 if (Op1CV == 0 || isPowerOf2_64(Op1CV)) {
5977 // If Op1C some other power of two, convert:
5978 uint64_t KnownZero, KnownOne;
5979 uint64_t TypeMask = Op1->getType()->getIntegralTypeMask();
5980 ComputeMaskedBits(Op0, TypeMask, KnownZero, KnownOne);
5981
5982 if (isPowerOf2_64(KnownZero^TypeMask)) { // Exactly 1 possible 1?
5983 bool isSetNE = SrcI->getOpcode() == Instruction::SetNE;
5984 if (Op1CV && (Op1CV != (KnownZero^TypeMask))) {
5985 // (X&4) == 2 --> false
5986 // (X&4) != 2 --> true
5987 Constant *Res = ConstantBool::get(isSetNE);
Reid Spencerbb65ebf2006-12-12 23:36:14 +00005988 Res = ConstantExpr::getZExt(Res, CI.getType());
Reid Spencer6c38f0b2006-11-27 01:05:10 +00005989 return ReplaceInstUsesWith(CI, Res);
5990 }
5991
5992 unsigned ShiftAmt = Log2_64(KnownZero^TypeMask);
5993 Value *In = Op0;
5994 if (ShiftAmt) {
5995 // Perform a logical shr by shiftamt.
5996 // Insert the shift to put the result in the low bit.
5997 In = InsertNewInstBefore(
5998 new ShiftInst(Instruction::LShr, In,
5999 ConstantInt::get(Type::UByteTy, ShiftAmt),
6000 In->getName()+".lobit"), CI);
6001 }
6002
6003 if ((Op1CV != 0) == isSetNE) { // Toggle the low bit.
6004 Constant *One = ConstantInt::get(In->getType(), 1);
6005 In = BinaryOperator::createXor(In, One, "tmp");
6006 InsertNewInstBefore(cast<Instruction>(In), CI);
6007 }
6008
6009 if (CI.getType() == In->getType())
6010 return ReplaceInstUsesWith(CI, In);
6011 else
Reid Spencerbb65ebf2006-12-12 23:36:14 +00006012 return CastInst::createIntegerCast(In, CI.getType(), false/*ZExt*/);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006013 }
6014 }
6015 }
6016 break;
6017 }
6018 return 0;
6019}
6020
6021Instruction *InstCombiner::visitTrunc(CastInst &CI) {
Chris Lattnerd747f012006-11-29 07:04:07 +00006022 if (Instruction *Result = commonIntCastTransforms(CI))
6023 return Result;
6024
6025 Value *Src = CI.getOperand(0);
6026 const Type *Ty = CI.getType();
6027 unsigned DestBitWidth = Ty->getPrimitiveSizeInBits();
6028
6029 if (Instruction *SrcI = dyn_cast<Instruction>(Src)) {
6030 switch (SrcI->getOpcode()) {
6031 default: break;
6032 case Instruction::LShr:
6033 // We can shrink lshr to something smaller if we know the bits shifted in
6034 // are already zeros.
6035 if (ConstantInt *ShAmtV = dyn_cast<ConstantInt>(SrcI->getOperand(1))) {
6036 unsigned ShAmt = ShAmtV->getZExtValue();
6037
6038 // Get a mask for the bits shifting in.
6039 uint64_t Mask = (~0ULL >> (64-ShAmt)) << DestBitWidth;
Reid Spencer13bc5d72006-12-12 09:18:51 +00006040 Value* SrcIOp0 = SrcI->getOperand(0);
6041 if (SrcI->hasOneUse() && MaskedValueIsZero(SrcIOp0, Mask)) {
Chris Lattnerd747f012006-11-29 07:04:07 +00006042 if (ShAmt >= DestBitWidth) // All zeros.
6043 return ReplaceInstUsesWith(CI, Constant::getNullValue(Ty));
6044
6045 // Okay, we can shrink this. Truncate the input, then return a new
6046 // shift.
Reid Spencer13bc5d72006-12-12 09:18:51 +00006047 Instruction::CastOps opcode =
6048 (SrcIOp0->getType()->getPrimitiveSizeInBits() ==
6049 Ty->getPrimitiveSizeInBits() ? Instruction::BitCast :
6050 Instruction::Trunc);
6051 Value *V = InsertCastBefore(opcode, SrcIOp0, Ty, CI);
Chris Lattnerd747f012006-11-29 07:04:07 +00006052 return new ShiftInst(Instruction::LShr, V, SrcI->getOperand(1));
6053 }
Chris Lattnerc209b582006-12-05 01:26:29 +00006054 } else { // This is a variable shr.
6055
6056 // Turn 'trunc (lshr X, Y) to bool' into '(X & (1 << Y)) != 0'. This is
6057 // more LLVM instructions, but allows '1 << Y' to be hoisted if
6058 // loop-invariant and CSE'd.
6059 if (CI.getType() == Type::BoolTy && SrcI->hasOneUse()) {
6060 Value *One = ConstantInt::get(SrcI->getType(), 1);
6061
6062 Value *V = InsertNewInstBefore(new ShiftInst(Instruction::Shl, One,
6063 SrcI->getOperand(1),
6064 "tmp"), CI);
6065 V = InsertNewInstBefore(BinaryOperator::createAnd(V,
6066 SrcI->getOperand(0),
6067 "tmp"), CI);
6068 Value *Zero = Constant::getNullValue(V->getType());
6069 return BinaryOperator::createSetNE(V, Zero);
6070 }
Chris Lattnerd747f012006-11-29 07:04:07 +00006071 }
6072 break;
6073 }
6074 }
6075
6076 return 0;
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006077}
6078
6079Instruction *InstCombiner::visitZExt(CastInst &CI) {
6080 // If one of the common conversion will work ..
6081 if (Instruction *Result = commonIntCastTransforms(CI))
6082 return Result;
6083
6084 Value *Src = CI.getOperand(0);
6085
6086 // If this is a cast of a cast
6087 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006088 // If this is a TRUNC followed by a ZEXT then we are dealing with integral
6089 // types and if the sizes are just right we can convert this into a logical
6090 // 'and' which will be much cheaper than the pair of casts.
6091 if (isa<TruncInst>(CSrc)) {
6092 // Get the sizes of the types involved
6093 Value *A = CSrc->getOperand(0);
6094 unsigned SrcSize = A->getType()->getPrimitiveSizeInBits();
6095 unsigned MidSize = CSrc->getType()->getPrimitiveSizeInBits();
6096 unsigned DstSize = CI.getType()->getPrimitiveSizeInBits();
6097 // If we're actually extending zero bits and the trunc is a no-op
6098 if (MidSize < DstSize && SrcSize == DstSize) {
6099 // Replace both of the casts with an And of the type mask.
6100 uint64_t AndValue = CSrc->getType()->getIntegralTypeMask();
6101 Constant *AndConst = ConstantInt::get(A->getType(), AndValue);
6102 Instruction *And =
6103 BinaryOperator::createAnd(CSrc->getOperand(0), AndConst);
6104 // Unfortunately, if the type changed, we need to cast it back.
6105 if (And->getType() != CI.getType()) {
6106 And->setName(CSrc->getName()+".mask");
6107 InsertNewInstBefore(And, CI);
Reid Spencerbb65ebf2006-12-12 23:36:14 +00006108 And = CastInst::createIntegerCast(And, CI.getType(), false/*ZExt*/);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006109 }
6110 return And;
6111 }
6112 }
6113 }
6114
6115 return 0;
6116}
6117
6118Instruction *InstCombiner::visitSExt(CastInst &CI) {
6119 return commonIntCastTransforms(CI);
6120}
6121
6122Instruction *InstCombiner::visitFPTrunc(CastInst &CI) {
6123 return commonCastTransforms(CI);
6124}
6125
6126Instruction *InstCombiner::visitFPExt(CastInst &CI) {
6127 return commonCastTransforms(CI);
6128}
6129
6130Instruction *InstCombiner::visitFPToUI(CastInst &CI) {
Reid Spencerad05ee92006-11-30 23:13:36 +00006131 return commonCastTransforms(CI);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006132}
6133
6134Instruction *InstCombiner::visitFPToSI(CastInst &CI) {
Reid Spencerad05ee92006-11-30 23:13:36 +00006135 return commonCastTransforms(CI);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006136}
6137
6138Instruction *InstCombiner::visitUIToFP(CastInst &CI) {
6139 return commonCastTransforms(CI);
6140}
6141
6142Instruction *InstCombiner::visitSIToFP(CastInst &CI) {
6143 return commonCastTransforms(CI);
6144}
6145
6146Instruction *InstCombiner::visitPtrToInt(CastInst &CI) {
Reid Spencerad05ee92006-11-30 23:13:36 +00006147 return commonCastTransforms(CI);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006148}
6149
6150Instruction *InstCombiner::visitIntToPtr(CastInst &CI) {
6151 return commonCastTransforms(CI);
6152}
6153
6154Instruction *InstCombiner::visitBitCast(CastInst &CI) {
6155
6156 // If the operands are integer typed then apply the integer transforms,
6157 // otherwise just apply the common ones.
6158 Value *Src = CI.getOperand(0);
6159 const Type *SrcTy = Src->getType();
6160 const Type *DestTy = CI.getType();
6161
6162 if (SrcTy->isInteger() && DestTy->isInteger()) {
6163 if (Instruction *Result = commonIntCastTransforms(CI))
6164 return Result;
6165 } else {
6166 if (Instruction *Result = commonCastTransforms(CI))
6167 return Result;
6168 }
6169
6170
6171 // Get rid of casts from one type to the same type. These are useless and can
6172 // be replaced by the operand.
6173 if (DestTy == Src->getType())
6174 return ReplaceInstUsesWith(CI, Src);
6175
Chris Lattnerb19a5c62006-04-12 18:09:35 +00006176 // If the source and destination are pointers, and this cast is equivalent to
6177 // a getelementptr X, 0, 0, 0... turn it into the appropriate getelementptr.
6178 // This can enhance SROA and other transforms that want type-safe pointers.
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006179 if (const PointerType *DstPTy = dyn_cast<PointerType>(DestTy)) {
6180 if (const PointerType *SrcPTy = dyn_cast<PointerType>(SrcTy)) {
6181 const Type *DstElTy = DstPTy->getElementType();
6182 const Type *SrcElTy = SrcPTy->getElementType();
Chris Lattnerb19a5c62006-04-12 18:09:35 +00006183
6184 Constant *ZeroUInt = Constant::getNullValue(Type::UIntTy);
6185 unsigned NumZeros = 0;
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006186 while (SrcElTy != DstElTy &&
6187 isa<CompositeType>(SrcElTy) && !isa<PointerType>(SrcElTy) &&
6188 SrcElTy->getNumContainedTypes() /* not "{}" */) {
6189 SrcElTy = cast<CompositeType>(SrcElTy)->getTypeAtIndex(ZeroUInt);
Chris Lattnerb19a5c62006-04-12 18:09:35 +00006190 ++NumZeros;
6191 }
Chris Lattner6a4adcd2004-09-29 05:07:12 +00006192
Chris Lattnerb19a5c62006-04-12 18:09:35 +00006193 // If we found a path from the src to dest, create the getelementptr now.
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006194 if (SrcElTy == DstElTy) {
Chris Lattnerb19a5c62006-04-12 18:09:35 +00006195 std::vector<Value*> Idxs(NumZeros+1, ZeroUInt);
6196 return new GetElementPtrInst(Src, Idxs);
6197 }
6198 }
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006199 }
Chris Lattnerdfae8be2003-07-24 17:35:25 +00006200
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006201 if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(Src)) {
6202 if (SVI->hasOneUse()) {
6203 // Okay, we have (bitconvert (shuffle ..)). Check to see if this is
6204 // a bitconvert to a vector with the same # elts.
6205 if (isa<PackedType>(DestTy) &&
6206 cast<PackedType>(DestTy)->getNumElements() ==
6207 SVI->getType()->getNumElements()) {
6208 CastInst *Tmp;
6209 // If either of the operands is a cast from CI.getType(), then
6210 // evaluating the shuffle in the casted destination's type will allow
6211 // us to eliminate at least one cast.
6212 if (((Tmp = dyn_cast<CastInst>(SVI->getOperand(0))) &&
6213 Tmp->getOperand(0)->getType() == DestTy) ||
6214 ((Tmp = dyn_cast<CastInst>(SVI->getOperand(1))) &&
6215 Tmp->getOperand(0)->getType() == DestTy)) {
Reid Spencer13bc5d72006-12-12 09:18:51 +00006216 Value *LHS = InsertOperandCastBefore(Instruction::BitCast,
6217 SVI->getOperand(0), DestTy, &CI);
6218 Value *RHS = InsertOperandCastBefore(Instruction::BitCast,
6219 SVI->getOperand(1), DestTy, &CI);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006220 // Return a new shuffle vector. Use the same element ID's, as we
6221 // know the vector types match #elts.
6222 return new ShuffleVectorInst(LHS, RHS, SVI->getOperand(2));
Chris Lattner99155be2006-05-25 23:24:33 +00006223 }
6224 }
6225 }
6226 }
Chris Lattner260ab202002-04-18 17:39:14 +00006227 return 0;
Chris Lattnerca081252001-12-14 16:52:21 +00006228}
6229
Chris Lattner56e4d3d2004-04-09 23:46:01 +00006230/// GetSelectFoldableOperands - We want to turn code that looks like this:
6231/// %C = or %A, %B
6232/// %D = select %cond, %C, %A
6233/// into:
6234/// %C = select %cond, %B, 0
6235/// %D = or %A, %C
6236///
6237/// Assuming that the specified instruction is an operand to the select, return
6238/// a bitmask indicating which operands of this instruction are foldable if they
6239/// equal the other incoming value of the select.
6240///
6241static unsigned GetSelectFoldableOperands(Instruction *I) {
6242 switch (I->getOpcode()) {
6243 case Instruction::Add:
6244 case Instruction::Mul:
6245 case Instruction::And:
6246 case Instruction::Or:
6247 case Instruction::Xor:
6248 return 3; // Can fold through either operand.
6249 case Instruction::Sub: // Can only fold on the amount subtracted.
6250 case Instruction::Shl: // Can only fold on the shift amount.
Reid Spencerfdff9382006-11-08 06:47:33 +00006251 case Instruction::LShr:
6252 case Instruction::AShr:
Misha Brukmanb1c93172005-04-21 23:48:37 +00006253 return 1;
Chris Lattner56e4d3d2004-04-09 23:46:01 +00006254 default:
6255 return 0; // Cannot fold
6256 }
6257}
6258
6259/// GetSelectFoldableConstant - For the same transformation as the previous
6260/// function, return the identity constant that goes into the select.
6261static Constant *GetSelectFoldableConstant(Instruction *I) {
6262 switch (I->getOpcode()) {
6263 default: assert(0 && "This cannot happen!"); abort();
6264 case Instruction::Add:
6265 case Instruction::Sub:
6266 case Instruction::Or:
6267 case Instruction::Xor:
6268 return Constant::getNullValue(I->getType());
6269 case Instruction::Shl:
Reid Spencerfdff9382006-11-08 06:47:33 +00006270 case Instruction::LShr:
6271 case Instruction::AShr:
Chris Lattner56e4d3d2004-04-09 23:46:01 +00006272 return Constant::getNullValue(Type::UByteTy);
6273 case Instruction::And:
6274 return ConstantInt::getAllOnesValue(I->getType());
6275 case Instruction::Mul:
6276 return ConstantInt::get(I->getType(), 1);
6277 }
6278}
6279
Chris Lattner411336f2005-01-19 21:50:18 +00006280/// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI
6281/// have the same opcode and only one use each. Try to simplify this.
6282Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
6283 Instruction *FI) {
6284 if (TI->getNumOperands() == 1) {
6285 // If this is a non-volatile load or a cast from the same type,
6286 // merge.
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006287 if (TI->isCast()) {
Chris Lattner411336f2005-01-19 21:50:18 +00006288 if (TI->getOperand(0)->getType() != FI->getOperand(0)->getType())
6289 return 0;
6290 } else {
6291 return 0; // unknown unary op.
6292 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00006293
Chris Lattner411336f2005-01-19 21:50:18 +00006294 // Fold this by inserting a select from the input values.
6295 SelectInst *NewSI = new SelectInst(SI.getCondition(), TI->getOperand(0),
6296 FI->getOperand(0), SI.getName()+".v");
6297 InsertNewInstBefore(NewSI, SI);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006298 return CastInst::create(Instruction::CastOps(TI->getOpcode()), NewSI,
6299 TI->getType());
Chris Lattner411336f2005-01-19 21:50:18 +00006300 }
6301
6302 // Only handle binary operators here.
6303 if (!isa<ShiftInst>(TI) && !isa<BinaryOperator>(TI))
6304 return 0;
6305
6306 // Figure out if the operations have any operands in common.
6307 Value *MatchOp, *OtherOpT, *OtherOpF;
6308 bool MatchIsOpZero;
6309 if (TI->getOperand(0) == FI->getOperand(0)) {
6310 MatchOp = TI->getOperand(0);
6311 OtherOpT = TI->getOperand(1);
6312 OtherOpF = FI->getOperand(1);
6313 MatchIsOpZero = true;
6314 } else if (TI->getOperand(1) == FI->getOperand(1)) {
6315 MatchOp = TI->getOperand(1);
6316 OtherOpT = TI->getOperand(0);
6317 OtherOpF = FI->getOperand(0);
6318 MatchIsOpZero = false;
6319 } else if (!TI->isCommutative()) {
6320 return 0;
6321 } else if (TI->getOperand(0) == FI->getOperand(1)) {
6322 MatchOp = TI->getOperand(0);
6323 OtherOpT = TI->getOperand(1);
6324 OtherOpF = FI->getOperand(0);
6325 MatchIsOpZero = true;
6326 } else if (TI->getOperand(1) == FI->getOperand(0)) {
6327 MatchOp = TI->getOperand(1);
6328 OtherOpT = TI->getOperand(0);
6329 OtherOpF = FI->getOperand(1);
6330 MatchIsOpZero = true;
6331 } else {
6332 return 0;
6333 }
6334
6335 // If we reach here, they do have operations in common.
6336 SelectInst *NewSI = new SelectInst(SI.getCondition(), OtherOpT,
6337 OtherOpF, SI.getName()+".v");
6338 InsertNewInstBefore(NewSI, SI);
6339
6340 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
6341 if (MatchIsOpZero)
6342 return BinaryOperator::create(BO->getOpcode(), MatchOp, NewSI);
6343 else
6344 return BinaryOperator::create(BO->getOpcode(), NewSI, MatchOp);
6345 } else {
6346 if (MatchIsOpZero)
6347 return new ShiftInst(cast<ShiftInst>(TI)->getOpcode(), MatchOp, NewSI);
6348 else
6349 return new ShiftInst(cast<ShiftInst>(TI)->getOpcode(), NewSI, MatchOp);
6350 }
6351}
6352
Chris Lattnerb909e8b2004-03-12 05:52:32 +00006353Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
Chris Lattner533bc492004-03-30 19:37:13 +00006354 Value *CondVal = SI.getCondition();
6355 Value *TrueVal = SI.getTrueValue();
6356 Value *FalseVal = SI.getFalseValue();
6357
6358 // select true, X, Y -> X
6359 // select false, X, Y -> Y
6360 if (ConstantBool *C = dyn_cast<ConstantBool>(CondVal))
Chris Lattner6ab03f62006-09-28 23:35:22 +00006361 return ReplaceInstUsesWith(SI, C->getValue() ? TrueVal : FalseVal);
Chris Lattner533bc492004-03-30 19:37:13 +00006362
6363 // select C, X, X -> X
6364 if (TrueVal == FalseVal)
6365 return ReplaceInstUsesWith(SI, TrueVal);
6366
Chris Lattner81a7a232004-10-16 18:11:37 +00006367 if (isa<UndefValue>(TrueVal)) // select C, undef, X -> X
6368 return ReplaceInstUsesWith(SI, FalseVal);
6369 if (isa<UndefValue>(FalseVal)) // select C, X, undef -> X
6370 return ReplaceInstUsesWith(SI, TrueVal);
6371 if (isa<UndefValue>(CondVal)) { // select undef, X, Y -> X or Y
6372 if (isa<Constant>(TrueVal))
6373 return ReplaceInstUsesWith(SI, TrueVal);
6374 else
6375 return ReplaceInstUsesWith(SI, FalseVal);
6376 }
6377
Chris Lattner1c631e82004-04-08 04:43:23 +00006378 if (SI.getType() == Type::BoolTy)
6379 if (ConstantBool *C = dyn_cast<ConstantBool>(TrueVal)) {
Chris Lattner6ab03f62006-09-28 23:35:22 +00006380 if (C->getValue()) {
Chris Lattner1c631e82004-04-08 04:43:23 +00006381 // Change: A = select B, true, C --> A = or B, C
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00006382 return BinaryOperator::createOr(CondVal, FalseVal);
Chris Lattner1c631e82004-04-08 04:43:23 +00006383 } else {
6384 // Change: A = select B, false, C --> A = and !B, C
6385 Value *NotCond =
6386 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
6387 "not."+CondVal->getName()), SI);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00006388 return BinaryOperator::createAnd(NotCond, FalseVal);
Chris Lattner1c631e82004-04-08 04:43:23 +00006389 }
6390 } else if (ConstantBool *C = dyn_cast<ConstantBool>(FalseVal)) {
Chris Lattner6ab03f62006-09-28 23:35:22 +00006391 if (C->getValue() == false) {
Chris Lattner1c631e82004-04-08 04:43:23 +00006392 // Change: A = select B, C, false --> A = and B, C
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00006393 return BinaryOperator::createAnd(CondVal, TrueVal);
Chris Lattner1c631e82004-04-08 04:43:23 +00006394 } else {
6395 // Change: A = select B, C, true --> A = or !B, C
6396 Value *NotCond =
6397 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
6398 "not."+CondVal->getName()), SI);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00006399 return BinaryOperator::createOr(NotCond, TrueVal);
Chris Lattner1c631e82004-04-08 04:43:23 +00006400 }
6401 }
6402
Chris Lattner183b3362004-04-09 19:05:30 +00006403 // Selecting between two integer constants?
6404 if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
6405 if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
6406 // select C, 1, 0 -> cast C to int
Reid Spencere0fc4df2006-10-20 07:07:24 +00006407 if (FalseValC->isNullValue() && TrueValC->getZExtValue() == 1) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006408 return CastInst::create(Instruction::ZExt, CondVal, SI.getType());
Reid Spencere0fc4df2006-10-20 07:07:24 +00006409 } else if (TrueValC->isNullValue() && FalseValC->getZExtValue() == 1) {
Chris Lattner183b3362004-04-09 19:05:30 +00006410 // select C, 0, 1 -> cast !C to int
6411 Value *NotCond =
6412 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
Chris Lattnercf7baf32004-04-09 18:19:44 +00006413 "not."+CondVal->getName()), SI);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006414 return CastInst::create(Instruction::ZExt, NotCond, SI.getType());
Chris Lattnercf7baf32004-04-09 18:19:44 +00006415 }
Chris Lattner35167c32004-06-09 07:59:58 +00006416
Chris Lattner380c7e92006-09-20 04:44:59 +00006417 if (SetCondInst *IC = dyn_cast<SetCondInst>(SI.getCondition())) {
6418
6419 // (x <s 0) ? -1 : 0 -> sra x, 31
6420 // (x >u 2147483647) ? -1 : 0 -> sra x, 31
6421 if (TrueValC->isAllOnesValue() && FalseValC->isNullValue())
6422 if (ConstantInt *CmpCst = dyn_cast<ConstantInt>(IC->getOperand(1))) {
6423 bool CanXForm = false;
6424 if (CmpCst->getType()->isSigned())
6425 CanXForm = CmpCst->isNullValue() &&
6426 IC->getOpcode() == Instruction::SetLT;
6427 else {
6428 unsigned Bits = CmpCst->getType()->getPrimitiveSizeInBits();
Reid Spencere0fc4df2006-10-20 07:07:24 +00006429 CanXForm = (CmpCst->getZExtValue() == ~0ULL >> (64-Bits+1)) &&
Chris Lattner380c7e92006-09-20 04:44:59 +00006430 IC->getOpcode() == Instruction::SetGT;
6431 }
6432
6433 if (CanXForm) {
6434 // The comparison constant and the result are not neccessarily the
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006435 // same width. Make an all-ones value by inserting a AShr.
Chris Lattner380c7e92006-09-20 04:44:59 +00006436 Value *X = IC->getOperand(0);
Chris Lattner380c7e92006-09-20 04:44:59 +00006437 unsigned Bits = X->getType()->getPrimitiveSizeInBits();
Reid Spencere0fc4df2006-10-20 07:07:24 +00006438 Constant *ShAmt = ConstantInt::get(Type::UByteTy, Bits-1);
Reid Spencerfdff9382006-11-08 06:47:33 +00006439 Instruction *SRA = new ShiftInst(Instruction::AShr, X,
Chris Lattner380c7e92006-09-20 04:44:59 +00006440 ShAmt, "ones");
6441 InsertNewInstBefore(SRA, SI);
6442
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006443 // Finally, convert to the type of the select RHS. We figure out
6444 // if this requires a SExt, Trunc or BitCast based on the sizes.
6445 Instruction::CastOps opc = Instruction::BitCast;
6446 unsigned SRASize = SRA->getType()->getPrimitiveSizeInBits();
6447 unsigned SISize = SI.getType()->getPrimitiveSizeInBits();
6448 if (SRASize < SISize)
6449 opc = Instruction::SExt;
6450 else if (SRASize > SISize)
6451 opc = Instruction::Trunc;
6452 return CastInst::create(opc, SRA, SI.getType());
Chris Lattner380c7e92006-09-20 04:44:59 +00006453 }
6454 }
6455
6456
6457 // If one of the constants is zero (we know they can't both be) and we
6458 // have a setcc instruction with zero, and we have an 'and' with the
6459 // non-constant value, eliminate this whole mess. This corresponds to
6460 // cases like this: ((X & 27) ? 27 : 0)
6461 if (TrueValC->isNullValue() || FalseValC->isNullValue())
Chris Lattnerb3f24c92006-09-18 04:22:48 +00006462 if (IC->isEquality() && isa<ConstantInt>(IC->getOperand(1)) &&
Chris Lattner35167c32004-06-09 07:59:58 +00006463 cast<Constant>(IC->getOperand(1))->isNullValue())
6464 if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
6465 if (ICA->getOpcode() == Instruction::And &&
Misha Brukmanb1c93172005-04-21 23:48:37 +00006466 isa<ConstantInt>(ICA->getOperand(1)) &&
6467 (ICA->getOperand(1) == TrueValC ||
6468 ICA->getOperand(1) == FalseValC) &&
Chris Lattner35167c32004-06-09 07:59:58 +00006469 isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
6470 // Okay, now we know that everything is set up, we just don't
6471 // know whether we have a setne or seteq and whether the true or
6472 // false val is the zero.
6473 bool ShouldNotVal = !TrueValC->isNullValue();
6474 ShouldNotVal ^= IC->getOpcode() == Instruction::SetNE;
6475 Value *V = ICA;
6476 if (ShouldNotVal)
6477 V = InsertNewInstBefore(BinaryOperator::create(
6478 Instruction::Xor, V, ICA->getOperand(1)), SI);
6479 return ReplaceInstUsesWith(SI, V);
6480 }
Chris Lattner380c7e92006-09-20 04:44:59 +00006481 }
Chris Lattner533bc492004-03-30 19:37:13 +00006482 }
Chris Lattner623fba12004-04-10 22:21:27 +00006483
6484 // See if we are selecting two values based on a comparison of the two values.
6485 if (SetCondInst *SCI = dyn_cast<SetCondInst>(CondVal)) {
6486 if (SCI->getOperand(0) == TrueVal && SCI->getOperand(1) == FalseVal) {
6487 // Transform (X == Y) ? X : Y -> Y
6488 if (SCI->getOpcode() == Instruction::SetEQ)
6489 return ReplaceInstUsesWith(SI, FalseVal);
6490 // Transform (X != Y) ? X : Y -> X
6491 if (SCI->getOpcode() == Instruction::SetNE)
6492 return ReplaceInstUsesWith(SI, TrueVal);
6493 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
6494
6495 } else if (SCI->getOperand(0) == FalseVal && SCI->getOperand(1) == TrueVal){
6496 // Transform (X == Y) ? Y : X -> X
6497 if (SCI->getOpcode() == Instruction::SetEQ)
Chris Lattner24cf0202004-04-11 01:39:19 +00006498 return ReplaceInstUsesWith(SI, FalseVal);
Chris Lattner623fba12004-04-10 22:21:27 +00006499 // Transform (X != Y) ? Y : X -> Y
6500 if (SCI->getOpcode() == Instruction::SetNE)
Chris Lattner24cf0202004-04-11 01:39:19 +00006501 return ReplaceInstUsesWith(SI, TrueVal);
Chris Lattner623fba12004-04-10 22:21:27 +00006502 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
6503 }
6504 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00006505
Chris Lattnera04c9042005-01-13 22:52:24 +00006506 if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
6507 if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
6508 if (TI->hasOneUse() && FI->hasOneUse()) {
Chris Lattnera04c9042005-01-13 22:52:24 +00006509 Instruction *AddOp = 0, *SubOp = 0;
6510
Chris Lattner411336f2005-01-19 21:50:18 +00006511 // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
6512 if (TI->getOpcode() == FI->getOpcode())
6513 if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
6514 return IV;
6515
6516 // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))). This is
6517 // even legal for FP.
Chris Lattnera04c9042005-01-13 22:52:24 +00006518 if (TI->getOpcode() == Instruction::Sub &&
6519 FI->getOpcode() == Instruction::Add) {
6520 AddOp = FI; SubOp = TI;
6521 } else if (FI->getOpcode() == Instruction::Sub &&
6522 TI->getOpcode() == Instruction::Add) {
6523 AddOp = TI; SubOp = FI;
6524 }
6525
6526 if (AddOp) {
6527 Value *OtherAddOp = 0;
6528 if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
6529 OtherAddOp = AddOp->getOperand(1);
6530 } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
6531 OtherAddOp = AddOp->getOperand(0);
6532 }
6533
6534 if (OtherAddOp) {
Chris Lattnerb580d262006-02-24 18:05:58 +00006535 // So at this point we know we have (Y -> OtherAddOp):
6536 // select C, (add X, Y), (sub X, Z)
6537 Value *NegVal; // Compute -Z
6538 if (Constant *C = dyn_cast<Constant>(SubOp->getOperand(1))) {
6539 NegVal = ConstantExpr::getNeg(C);
6540 } else {
6541 NegVal = InsertNewInstBefore(
6542 BinaryOperator::createNeg(SubOp->getOperand(1), "tmp"), SI);
Chris Lattnera04c9042005-01-13 22:52:24 +00006543 }
Chris Lattnerb580d262006-02-24 18:05:58 +00006544
6545 Value *NewTrueOp = OtherAddOp;
6546 Value *NewFalseOp = NegVal;
6547 if (AddOp != TI)
6548 std::swap(NewTrueOp, NewFalseOp);
6549 Instruction *NewSel =
6550 new SelectInst(CondVal, NewTrueOp,NewFalseOp,SI.getName()+".p");
6551
6552 NewSel = InsertNewInstBefore(NewSel, SI);
6553 return BinaryOperator::createAdd(SubOp->getOperand(0), NewSel);
Chris Lattnera04c9042005-01-13 22:52:24 +00006554 }
6555 }
6556 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00006557
Chris Lattner56e4d3d2004-04-09 23:46:01 +00006558 // See if we can fold the select into one of our operands.
6559 if (SI.getType()->isInteger()) {
6560 // See the comment above GetSelectFoldableOperands for a description of the
6561 // transformation we are doing here.
6562 if (Instruction *TVI = dyn_cast<Instruction>(TrueVal))
6563 if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
6564 !isa<Constant>(FalseVal))
6565 if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
6566 unsigned OpToFold = 0;
6567 if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
6568 OpToFold = 1;
6569 } else if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
6570 OpToFold = 2;
6571 }
6572
6573 if (OpToFold) {
6574 Constant *C = GetSelectFoldableConstant(TVI);
6575 std::string Name = TVI->getName(); TVI->setName("");
6576 Instruction *NewSel =
6577 new SelectInst(SI.getCondition(), TVI->getOperand(2-OpToFold), C,
6578 Name);
6579 InsertNewInstBefore(NewSel, SI);
6580 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
6581 return BinaryOperator::create(BO->getOpcode(), FalseVal, NewSel);
6582 else if (ShiftInst *SI = dyn_cast<ShiftInst>(TVI))
6583 return new ShiftInst(SI->getOpcode(), FalseVal, NewSel);
6584 else {
6585 assert(0 && "Unknown instruction!!");
6586 }
6587 }
6588 }
Chris Lattner6862fbd2004-09-29 17:40:11 +00006589
Chris Lattner56e4d3d2004-04-09 23:46:01 +00006590 if (Instruction *FVI = dyn_cast<Instruction>(FalseVal))
6591 if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
6592 !isa<Constant>(TrueVal))
6593 if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
6594 unsigned OpToFold = 0;
6595 if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
6596 OpToFold = 1;
6597 } else if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
6598 OpToFold = 2;
6599 }
6600
6601 if (OpToFold) {
6602 Constant *C = GetSelectFoldableConstant(FVI);
6603 std::string Name = FVI->getName(); FVI->setName("");
6604 Instruction *NewSel =
6605 new SelectInst(SI.getCondition(), C, FVI->getOperand(2-OpToFold),
6606 Name);
6607 InsertNewInstBefore(NewSel, SI);
6608 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
6609 return BinaryOperator::create(BO->getOpcode(), TrueVal, NewSel);
6610 else if (ShiftInst *SI = dyn_cast<ShiftInst>(FVI))
6611 return new ShiftInst(SI->getOpcode(), TrueVal, NewSel);
6612 else {
6613 assert(0 && "Unknown instruction!!");
6614 }
6615 }
6616 }
6617 }
Chris Lattnerd6f636a2005-04-24 07:30:14 +00006618
6619 if (BinaryOperator::isNot(CondVal)) {
6620 SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
6621 SI.setOperand(1, FalseVal);
6622 SI.setOperand(2, TrueVal);
6623 return &SI;
6624 }
6625
Chris Lattnerb909e8b2004-03-12 05:52:32 +00006626 return 0;
6627}
6628
Chris Lattner82f2ef22006-03-06 20:18:44 +00006629/// GetKnownAlignment - If the specified pointer has an alignment that we can
6630/// determine, return it, otherwise return 0.
6631static unsigned GetKnownAlignment(Value *V, TargetData *TD) {
6632 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V)) {
6633 unsigned Align = GV->getAlignment();
6634 if (Align == 0 && TD)
6635 Align = TD->getTypeAlignment(GV->getType()->getElementType());
6636 return Align;
6637 } else if (AllocationInst *AI = dyn_cast<AllocationInst>(V)) {
6638 unsigned Align = AI->getAlignment();
6639 if (Align == 0 && TD) {
6640 if (isa<AllocaInst>(AI))
6641 Align = TD->getTypeAlignment(AI->getType()->getElementType());
6642 else if (isa<MallocInst>(AI)) {
6643 // Malloc returns maximally aligned memory.
6644 Align = TD->getTypeAlignment(AI->getType()->getElementType());
6645 Align = std::max(Align, (unsigned)TD->getTypeAlignment(Type::DoubleTy));
6646 Align = std::max(Align, (unsigned)TD->getTypeAlignment(Type::LongTy));
6647 }
6648 }
6649 return Align;
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006650 } else if (isa<BitCastInst>(V) ||
Chris Lattner53ef5a02006-03-07 01:28:57 +00006651 (isa<ConstantExpr>(V) &&
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006652 cast<ConstantExpr>(V)->getOpcode() == Instruction::BitCast)) {
Chris Lattner53ef5a02006-03-07 01:28:57 +00006653 User *CI = cast<User>(V);
Chris Lattner82f2ef22006-03-06 20:18:44 +00006654 if (isa<PointerType>(CI->getOperand(0)->getType()))
6655 return GetKnownAlignment(CI->getOperand(0), TD);
6656 return 0;
Chris Lattner53ef5a02006-03-07 01:28:57 +00006657 } else if (isa<GetElementPtrInst>(V) ||
6658 (isa<ConstantExpr>(V) &&
6659 cast<ConstantExpr>(V)->getOpcode()==Instruction::GetElementPtr)) {
6660 User *GEPI = cast<User>(V);
Chris Lattner82f2ef22006-03-06 20:18:44 +00006661 unsigned BaseAlignment = GetKnownAlignment(GEPI->getOperand(0), TD);
6662 if (BaseAlignment == 0) return 0;
6663
6664 // If all indexes are zero, it is just the alignment of the base pointer.
6665 bool AllZeroOperands = true;
6666 for (unsigned i = 1, e = GEPI->getNumOperands(); i != e; ++i)
6667 if (!isa<Constant>(GEPI->getOperand(i)) ||
6668 !cast<Constant>(GEPI->getOperand(i))->isNullValue()) {
6669 AllZeroOperands = false;
6670 break;
6671 }
6672 if (AllZeroOperands)
6673 return BaseAlignment;
6674
6675 // Otherwise, if the base alignment is >= the alignment we expect for the
6676 // base pointer type, then we know that the resultant pointer is aligned at
6677 // least as much as its type requires.
6678 if (!TD) return 0;
6679
6680 const Type *BasePtrTy = GEPI->getOperand(0)->getType();
6681 if (TD->getTypeAlignment(cast<PointerType>(BasePtrTy)->getElementType())
Chris Lattner53ef5a02006-03-07 01:28:57 +00006682 <= BaseAlignment) {
6683 const Type *GEPTy = GEPI->getType();
6684 return TD->getTypeAlignment(cast<PointerType>(GEPTy)->getElementType());
6685 }
Chris Lattner82f2ef22006-03-06 20:18:44 +00006686 return 0;
6687 }
6688 return 0;
6689}
6690
Chris Lattnerb909e8b2004-03-12 05:52:32 +00006691
Chris Lattnerc66b2232006-01-13 20:11:04 +00006692/// visitCallInst - CallInst simplification. This mostly only handles folding
6693/// of intrinsic instructions. For normal calls, it allows visitCallSite to do
6694/// the heavy lifting.
6695///
Chris Lattner970c33a2003-06-19 17:00:31 +00006696Instruction *InstCombiner::visitCallInst(CallInst &CI) {
Chris Lattnerc66b2232006-01-13 20:11:04 +00006697 IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
6698 if (!II) return visitCallSite(&CI);
6699
Chris Lattner51ea1272004-02-28 05:22:00 +00006700 // Intrinsics cannot occur in an invoke, so handle them here instead of in
6701 // visitCallSite.
Chris Lattnerc66b2232006-01-13 20:11:04 +00006702 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
Chris Lattner00648e12004-10-12 04:52:52 +00006703 bool Changed = false;
6704
6705 // memmove/cpy/set of zero bytes is a noop.
6706 if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
6707 if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
6708
Chris Lattner00648e12004-10-12 04:52:52 +00006709 if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
Reid Spencere0fc4df2006-10-20 07:07:24 +00006710 if (CI->getZExtValue() == 1) {
Chris Lattner00648e12004-10-12 04:52:52 +00006711 // Replace the instruction with just byte operations. We would
6712 // transform other cases to loads/stores, but we don't know if
6713 // alignment is sufficient.
6714 }
Chris Lattner51ea1272004-02-28 05:22:00 +00006715 }
6716
Chris Lattner00648e12004-10-12 04:52:52 +00006717 // If we have a memmove and the source operation is a constant global,
6718 // then the source and dest pointers can't alias, so we can change this
6719 // into a call to memcpy.
Chris Lattner82f2ef22006-03-06 20:18:44 +00006720 if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(II)) {
Chris Lattner00648e12004-10-12 04:52:52 +00006721 if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
6722 if (GVSrc->isConstant()) {
6723 Module *M = CI.getParent()->getParent()->getParent();
Chris Lattner681ef2f2006-03-03 01:34:17 +00006724 const char *Name;
Andrew Lenharth0ebb0b02006-11-03 22:45:50 +00006725 if (CI.getCalledFunction()->getFunctionType()->getParamType(2) ==
Chris Lattner681ef2f2006-03-03 01:34:17 +00006726 Type::UIntTy)
6727 Name = "llvm.memcpy.i32";
6728 else
6729 Name = "llvm.memcpy.i64";
6730 Function *MemCpy = M->getOrInsertFunction(Name,
Chris Lattner00648e12004-10-12 04:52:52 +00006731 CI.getCalledFunction()->getFunctionType());
6732 CI.setOperand(0, MemCpy);
6733 Changed = true;
6734 }
Chris Lattner82f2ef22006-03-06 20:18:44 +00006735 }
Chris Lattner00648e12004-10-12 04:52:52 +00006736
Chris Lattner82f2ef22006-03-06 20:18:44 +00006737 // If we can determine a pointer alignment that is bigger than currently
6738 // set, update the alignment.
6739 if (isa<MemCpyInst>(MI) || isa<MemMoveInst>(MI)) {
6740 unsigned Alignment1 = GetKnownAlignment(MI->getOperand(1), TD);
6741 unsigned Alignment2 = GetKnownAlignment(MI->getOperand(2), TD);
6742 unsigned Align = std::min(Alignment1, Alignment2);
Reid Spencere0fc4df2006-10-20 07:07:24 +00006743 if (MI->getAlignment()->getZExtValue() < Align) {
6744 MI->setAlignment(ConstantInt::get(Type::UIntTy, Align));
Chris Lattner82f2ef22006-03-06 20:18:44 +00006745 Changed = true;
6746 }
6747 } else if (isa<MemSetInst>(MI)) {
6748 unsigned Alignment = GetKnownAlignment(MI->getDest(), TD);
Reid Spencere0fc4df2006-10-20 07:07:24 +00006749 if (MI->getAlignment()->getZExtValue() < Alignment) {
6750 MI->setAlignment(ConstantInt::get(Type::UIntTy, Alignment));
Chris Lattner82f2ef22006-03-06 20:18:44 +00006751 Changed = true;
6752 }
6753 }
6754
Chris Lattnerc66b2232006-01-13 20:11:04 +00006755 if (Changed) return II;
Chris Lattner503221f2006-01-13 21:28:09 +00006756 } else {
6757 switch (II->getIntrinsicID()) {
6758 default: break;
Chris Lattnerf42d0ae2006-04-02 05:30:25 +00006759 case Intrinsic::ppc_altivec_lvx:
6760 case Intrinsic::ppc_altivec_lvxl:
Chris Lattner36dd7c92006-04-17 22:26:56 +00006761 case Intrinsic::x86_sse_loadu_ps:
6762 case Intrinsic::x86_sse2_loadu_pd:
6763 case Intrinsic::x86_sse2_loadu_dq:
6764 // Turn PPC lvx -> load if the pointer is known aligned.
6765 // Turn X86 loadups -> load if the pointer is known aligned.
Chris Lattnerf42d0ae2006-04-02 05:30:25 +00006766 if (GetKnownAlignment(II->getOperand(1), TD) >= 16) {
Reid Spencer13bc5d72006-12-12 09:18:51 +00006767 Value *Ptr = InsertCastBefore(Instruction::BitCast, II->getOperand(1),
Chris Lattnere79d2492006-04-06 19:19:17 +00006768 PointerType::get(II->getType()), CI);
Chris Lattnerf42d0ae2006-04-02 05:30:25 +00006769 return new LoadInst(Ptr);
6770 }
6771 break;
6772 case Intrinsic::ppc_altivec_stvx:
6773 case Intrinsic::ppc_altivec_stvxl:
6774 // Turn stvx -> store if the pointer is known aligned.
6775 if (GetKnownAlignment(II->getOperand(2), TD) >= 16) {
Chris Lattnere79d2492006-04-06 19:19:17 +00006776 const Type *OpPtrTy = PointerType::get(II->getOperand(1)->getType());
Reid Spencer13bc5d72006-12-12 09:18:51 +00006777 Value *Ptr = InsertCastBefore(Instruction::BitCast, II->getOperand(2),
6778 OpPtrTy, CI);
Chris Lattnerf42d0ae2006-04-02 05:30:25 +00006779 return new StoreInst(II->getOperand(1), Ptr);
6780 }
6781 break;
Chris Lattner36dd7c92006-04-17 22:26:56 +00006782 case Intrinsic::x86_sse_storeu_ps:
6783 case Intrinsic::x86_sse2_storeu_pd:
6784 case Intrinsic::x86_sse2_storeu_dq:
6785 case Intrinsic::x86_sse2_storel_dq:
6786 // Turn X86 storeu -> store if the pointer is known aligned.
6787 if (GetKnownAlignment(II->getOperand(1), TD) >= 16) {
6788 const Type *OpPtrTy = PointerType::get(II->getOperand(2)->getType());
Reid Spencer13bc5d72006-12-12 09:18:51 +00006789 Value *Ptr = InsertCastBefore(Instruction::BitCast, II->getOperand(1),
6790 OpPtrTy, CI);
Chris Lattner36dd7c92006-04-17 22:26:56 +00006791 return new StoreInst(II->getOperand(2), Ptr);
6792 }
6793 break;
Chris Lattner2deeaea2006-10-05 06:55:50 +00006794
6795 case Intrinsic::x86_sse_cvttss2si: {
6796 // These intrinsics only demands the 0th element of its input vector. If
6797 // we can simplify the input based on that, do so now.
6798 uint64_t UndefElts;
6799 if (Value *V = SimplifyDemandedVectorElts(II->getOperand(1), 1,
6800 UndefElts)) {
6801 II->setOperand(1, V);
6802 return II;
6803 }
6804 break;
6805 }
6806
Chris Lattnere79d2492006-04-06 19:19:17 +00006807 case Intrinsic::ppc_altivec_vperm:
6808 // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant.
6809 if (ConstantPacked *Mask = dyn_cast<ConstantPacked>(II->getOperand(3))) {
6810 assert(Mask->getNumOperands() == 16 && "Bad type for intrinsic!");
6811
6812 // Check that all of the elements are integer constants or undefs.
6813 bool AllEltsOk = true;
6814 for (unsigned i = 0; i != 16; ++i) {
6815 if (!isa<ConstantInt>(Mask->getOperand(i)) &&
6816 !isa<UndefValue>(Mask->getOperand(i))) {
6817 AllEltsOk = false;
6818 break;
6819 }
6820 }
6821
6822 if (AllEltsOk) {
6823 // Cast the input vectors to byte vectors.
Reid Spencer13bc5d72006-12-12 09:18:51 +00006824 Value *Op0 = InsertCastBefore(Instruction::BitCast,
6825 II->getOperand(1), Mask->getType(), CI);
6826 Value *Op1 = InsertCastBefore(Instruction::BitCast,
6827 II->getOperand(2), Mask->getType(), CI);
Chris Lattnere79d2492006-04-06 19:19:17 +00006828 Value *Result = UndefValue::get(Op0->getType());
6829
6830 // Only extract each element once.
6831 Value *ExtractedElts[32];
6832 memset(ExtractedElts, 0, sizeof(ExtractedElts));
6833
6834 for (unsigned i = 0; i != 16; ++i) {
6835 if (isa<UndefValue>(Mask->getOperand(i)))
6836 continue;
Reid Spencere0fc4df2006-10-20 07:07:24 +00006837 unsigned Idx =cast<ConstantInt>(Mask->getOperand(i))->getZExtValue();
Chris Lattnere79d2492006-04-06 19:19:17 +00006838 Idx &= 31; // Match the hardware behavior.
6839
6840 if (ExtractedElts[Idx] == 0) {
6841 Instruction *Elt =
Chris Lattner2deeaea2006-10-05 06:55:50 +00006842 new ExtractElementInst(Idx < 16 ? Op0 : Op1, Idx&15, "tmp");
Chris Lattnere79d2492006-04-06 19:19:17 +00006843 InsertNewInstBefore(Elt, CI);
6844 ExtractedElts[Idx] = Elt;
6845 }
6846
6847 // Insert this value into the result vector.
Chris Lattner2deeaea2006-10-05 06:55:50 +00006848 Result = new InsertElementInst(Result, ExtractedElts[Idx], i,"tmp");
Chris Lattnere79d2492006-04-06 19:19:17 +00006849 InsertNewInstBefore(cast<Instruction>(Result), CI);
6850 }
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006851 return CastInst::create(Instruction::BitCast, Result, CI.getType());
Chris Lattnere79d2492006-04-06 19:19:17 +00006852 }
6853 }
6854 break;
6855
Chris Lattner503221f2006-01-13 21:28:09 +00006856 case Intrinsic::stackrestore: {
6857 // If the save is right next to the restore, remove the restore. This can
6858 // happen when variable allocas are DCE'd.
6859 if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getOperand(1))) {
6860 if (SS->getIntrinsicID() == Intrinsic::stacksave) {
6861 BasicBlock::iterator BI = SS;
6862 if (&*++BI == II)
6863 return EraseInstFromFunction(CI);
6864 }
6865 }
6866
6867 // If the stack restore is in a return/unwind block and if there are no
6868 // allocas or calls between the restore and the return, nuke the restore.
6869 TerminatorInst *TI = II->getParent()->getTerminator();
6870 if (isa<ReturnInst>(TI) || isa<UnwindInst>(TI)) {
6871 BasicBlock::iterator BI = II;
6872 bool CannotRemove = false;
6873 for (++BI; &*BI != TI; ++BI) {
6874 if (isa<AllocaInst>(BI) ||
6875 (isa<CallInst>(BI) && !isa<IntrinsicInst>(BI))) {
6876 CannotRemove = true;
6877 break;
6878 }
6879 }
6880 if (!CannotRemove)
6881 return EraseInstFromFunction(CI);
6882 }
6883 break;
6884 }
6885 }
Chris Lattner00648e12004-10-12 04:52:52 +00006886 }
6887
Chris Lattnerc66b2232006-01-13 20:11:04 +00006888 return visitCallSite(II);
Chris Lattner970c33a2003-06-19 17:00:31 +00006889}
6890
6891// InvokeInst simplification
6892//
6893Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
Chris Lattneraec3d942003-10-07 22:32:43 +00006894 return visitCallSite(&II);
Chris Lattner970c33a2003-06-19 17:00:31 +00006895}
6896
Chris Lattneraec3d942003-10-07 22:32:43 +00006897// visitCallSite - Improvements for call and invoke instructions.
6898//
6899Instruction *InstCombiner::visitCallSite(CallSite CS) {
Chris Lattner75b4d1d2003-10-07 22:54:13 +00006900 bool Changed = false;
6901
6902 // If the callee is a constexpr cast of a function, attempt to move the cast
6903 // to the arguments of the call/invoke.
Chris Lattneraec3d942003-10-07 22:32:43 +00006904 if (transformConstExprCastCall(CS)) return 0;
6905
Chris Lattner75b4d1d2003-10-07 22:54:13 +00006906 Value *Callee = CS.getCalledValue();
Chris Lattner81a7a232004-10-16 18:11:37 +00006907
Chris Lattner61d9d812005-05-13 07:09:09 +00006908 if (Function *CalleeF = dyn_cast<Function>(Callee))
6909 if (CalleeF->getCallingConv() != CS.getCallingConv()) {
6910 Instruction *OldCall = CS.getInstruction();
6911 // If the call and callee calling conventions don't match, this call must
6912 // be unreachable, as the call is undefined.
Chris Lattner6ab03f62006-09-28 23:35:22 +00006913 new StoreInst(ConstantBool::getTrue(),
Chris Lattner61d9d812005-05-13 07:09:09 +00006914 UndefValue::get(PointerType::get(Type::BoolTy)), OldCall);
6915 if (!OldCall->use_empty())
6916 OldCall->replaceAllUsesWith(UndefValue::get(OldCall->getType()));
6917 if (isa<CallInst>(OldCall)) // Not worth removing an invoke here.
6918 return EraseInstFromFunction(*OldCall);
6919 return 0;
6920 }
6921
Chris Lattner8ba9ec92004-10-18 02:59:09 +00006922 if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
6923 // This instruction is not reachable, just remove it. We insert a store to
6924 // undef so that we know that this code is not reachable, despite the fact
6925 // that we can't modify the CFG here.
Chris Lattner6ab03f62006-09-28 23:35:22 +00006926 new StoreInst(ConstantBool::getTrue(),
Chris Lattner8ba9ec92004-10-18 02:59:09 +00006927 UndefValue::get(PointerType::get(Type::BoolTy)),
6928 CS.getInstruction());
6929
6930 if (!CS.getInstruction()->use_empty())
6931 CS.getInstruction()->
6932 replaceAllUsesWith(UndefValue::get(CS.getInstruction()->getType()));
6933
6934 if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
6935 // Don't break the CFG, insert a dummy cond branch.
6936 new BranchInst(II->getNormalDest(), II->getUnwindDest(),
Chris Lattner6ab03f62006-09-28 23:35:22 +00006937 ConstantBool::getTrue(), II);
Chris Lattner81a7a232004-10-16 18:11:37 +00006938 }
Chris Lattner8ba9ec92004-10-18 02:59:09 +00006939 return EraseInstFromFunction(*CS.getInstruction());
6940 }
Chris Lattner81a7a232004-10-16 18:11:37 +00006941
Chris Lattner75b4d1d2003-10-07 22:54:13 +00006942 const PointerType *PTy = cast<PointerType>(Callee->getType());
6943 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
6944 if (FTy->isVarArg()) {
6945 // See if we can optimize any arguments passed through the varargs area of
6946 // the call.
6947 for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
6948 E = CS.arg_end(); I != E; ++I)
6949 if (CastInst *CI = dyn_cast<CastInst>(*I)) {
6950 // If this cast does not effect the value passed through the varargs
6951 // area, we can eliminate the use of the cast.
6952 Value *Op = CI->getOperand(0);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006953 if (CI->isLosslessCast()) {
Chris Lattner75b4d1d2003-10-07 22:54:13 +00006954 *I = Op;
6955 Changed = true;
6956 }
6957 }
6958 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00006959
Chris Lattner75b4d1d2003-10-07 22:54:13 +00006960 return Changed ? CS.getInstruction() : 0;
Chris Lattneraec3d942003-10-07 22:32:43 +00006961}
6962
Chris Lattner970c33a2003-06-19 17:00:31 +00006963// transformConstExprCastCall - If the callee is a constexpr cast of a function,
6964// attempt to move the cast to the arguments of the call/invoke.
6965//
6966bool InstCombiner::transformConstExprCastCall(CallSite CS) {
6967 if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
6968 ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006969 if (CE->getOpcode() != Instruction::BitCast ||
6970 !isa<Function>(CE->getOperand(0)))
Chris Lattner970c33a2003-06-19 17:00:31 +00006971 return false;
Reid Spencer87436872004-07-18 00:38:32 +00006972 Function *Callee = cast<Function>(CE->getOperand(0));
Chris Lattner970c33a2003-06-19 17:00:31 +00006973 Instruction *Caller = CS.getInstruction();
6974
6975 // Okay, this is a cast from a function to a different type. Unless doing so
6976 // would cause a type conversion of one of our arguments, change this call to
6977 // be a direct call with arguments casted to the appropriate types.
6978 //
6979 const FunctionType *FT = Callee->getFunctionType();
6980 const Type *OldRetTy = Caller->getType();
6981
Chris Lattner1f7942f2004-01-14 06:06:08 +00006982 // Check to see if we are changing the return type...
6983 if (OldRetTy != FT->getReturnType()) {
6984 if (Callee->isExternal() &&
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006985 !Caller->use_empty() &&
6986 !(OldRetTy->canLosslesslyBitCastTo(FT->getReturnType()) ||
Andrew Lenharth61eae292006-04-20 14:56:47 +00006987 (isa<PointerType>(FT->getReturnType()) &&
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006988 TD->getIntPtrType()->canLosslesslyBitCastTo(OldRetTy)))
6989 )
Chris Lattner1f7942f2004-01-14 06:06:08 +00006990 return false; // Cannot transform this return value...
6991
6992 // If the callsite is an invoke instruction, and the return value is used by
6993 // a PHI node in a successor, we cannot change the return type of the call
6994 // because there is no place to put the cast instruction (without breaking
6995 // the critical edge). Bail out in this case.
6996 if (!Caller->use_empty())
6997 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
6998 for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
6999 UI != E; ++UI)
7000 if (PHINode *PN = dyn_cast<PHINode>(*UI))
7001 if (PN->getParent() == II->getNormalDest() ||
Chris Lattnerfae8ab32004-02-08 21:44:31 +00007002 PN->getParent() == II->getUnwindDest())
Chris Lattner1f7942f2004-01-14 06:06:08 +00007003 return false;
7004 }
Chris Lattner970c33a2003-06-19 17:00:31 +00007005
7006 unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
7007 unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
Misha Brukmanb1c93172005-04-21 23:48:37 +00007008
Chris Lattner970c33a2003-06-19 17:00:31 +00007009 CallSite::arg_iterator AI = CS.arg_begin();
7010 for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
7011 const Type *ParamTy = FT->getParamType(i);
Andrew Lenharthebfa24e2006-06-28 01:01:52 +00007012 const Type *ActTy = (*AI)->getType();
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007013 ConstantInt *c = dyn_cast<ConstantInt>(*AI);
Andrew Lenharthebfa24e2006-06-28 01:01:52 +00007014 //Either we can cast directly, or we can upconvert the argument
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007015 bool isConvertible = ActTy->canLosslesslyBitCastTo(ParamTy) ||
Andrew Lenharthebfa24e2006-06-28 01:01:52 +00007016 (ParamTy->isIntegral() && ActTy->isIntegral() &&
7017 ParamTy->isSigned() == ActTy->isSigned() &&
7018 ParamTy->getPrimitiveSize() >= ActTy->getPrimitiveSize()) ||
7019 (c && ParamTy->getPrimitiveSize() >= ActTy->getPrimitiveSize() &&
Reid Spencere0fc4df2006-10-20 07:07:24 +00007020 c->getSExtValue() > 0);
Misha Brukmanb1c93172005-04-21 23:48:37 +00007021 if (Callee->isExternal() && !isConvertible) return false;
Chris Lattner970c33a2003-06-19 17:00:31 +00007022 }
7023
7024 if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
7025 Callee->isExternal())
7026 return false; // Do not delete arguments unless we have a function body...
7027
7028 // Okay, we decided that this is a safe thing to do: go ahead and start
7029 // inserting cast instructions as necessary...
7030 std::vector<Value*> Args;
7031 Args.reserve(NumActualArgs);
7032
7033 AI = CS.arg_begin();
7034 for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
7035 const Type *ParamTy = FT->getParamType(i);
7036 if ((*AI)->getType() == ParamTy) {
7037 Args.push_back(*AI);
7038 } else {
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007039 CastInst *NewCast = CastInst::createInferredCast(*AI, ParamTy, "tmp");
7040 Args.push_back(InsertNewInstBefore(NewCast, *Caller));
Chris Lattner970c33a2003-06-19 17:00:31 +00007041 }
7042 }
7043
7044 // If the function takes more arguments than the call was taking, add them
7045 // now...
7046 for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
7047 Args.push_back(Constant::getNullValue(FT->getParamType(i)));
7048
7049 // If we are removing arguments to the function, emit an obnoxious warning...
7050 if (FT->getNumParams() < NumActualArgs)
7051 if (!FT->isVarArg()) {
Bill Wendlingf3baad32006-12-07 01:30:32 +00007052 cerr << "WARNING: While resolving call to function '"
7053 << Callee->getName() << "' arguments were dropped!\n";
Chris Lattner970c33a2003-06-19 17:00:31 +00007054 } else {
7055 // Add all of the arguments in their promoted form to the arg list...
7056 for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
7057 const Type *PTy = getPromotedType((*AI)->getType());
7058 if (PTy != (*AI)->getType()) {
7059 // Must promote to pass through va_arg area!
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007060 Instruction *Cast = CastInst::createInferredCast(*AI, PTy, "tmp");
Chris Lattner970c33a2003-06-19 17:00:31 +00007061 InsertNewInstBefore(Cast, *Caller);
7062 Args.push_back(Cast);
7063 } else {
7064 Args.push_back(*AI);
7065 }
7066 }
7067 }
7068
7069 if (FT->getReturnType() == Type::VoidTy)
7070 Caller->setName(""); // Void type should not have a name...
7071
7072 Instruction *NC;
7073 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Chris Lattnerfae8ab32004-02-08 21:44:31 +00007074 NC = new InvokeInst(Callee, II->getNormalDest(), II->getUnwindDest(),
Chris Lattner970c33a2003-06-19 17:00:31 +00007075 Args, Caller->getName(), Caller);
Chris Lattner05c703e2005-05-14 12:25:32 +00007076 cast<InvokeInst>(II)->setCallingConv(II->getCallingConv());
Chris Lattner970c33a2003-06-19 17:00:31 +00007077 } else {
7078 NC = new CallInst(Callee, Args, Caller->getName(), Caller);
Chris Lattner6aacb0f2005-05-06 06:48:21 +00007079 if (cast<CallInst>(Caller)->isTailCall())
7080 cast<CallInst>(NC)->setTailCall();
Chris Lattner05c703e2005-05-14 12:25:32 +00007081 cast<CallInst>(NC)->setCallingConv(cast<CallInst>(Caller)->getCallingConv());
Chris Lattner970c33a2003-06-19 17:00:31 +00007082 }
7083
7084 // Insert a cast of the return type as necessary...
7085 Value *NV = NC;
7086 if (Caller->getType() != NV->getType() && !Caller->use_empty()) {
7087 if (NV->getType() != Type::VoidTy) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007088 NV = NC = CastInst::createInferredCast(NC, Caller->getType(), "tmp");
Chris Lattner686767f2003-10-30 00:46:41 +00007089
7090 // If this is an invoke instruction, we should insert it after the first
7091 // non-phi, instruction in the normal successor block.
7092 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
7093 BasicBlock::iterator I = II->getNormalDest()->begin();
7094 while (isa<PHINode>(I)) ++I;
7095 InsertNewInstBefore(NC, *I);
7096 } else {
7097 // Otherwise, it's a call, just insert cast right after the call instr
7098 InsertNewInstBefore(NC, *Caller);
7099 }
Chris Lattner51ea1272004-02-28 05:22:00 +00007100 AddUsersToWorkList(*Caller);
Chris Lattner970c33a2003-06-19 17:00:31 +00007101 } else {
Chris Lattnere29d6342004-10-17 21:22:38 +00007102 NV = UndefValue::get(Caller->getType());
Chris Lattner970c33a2003-06-19 17:00:31 +00007103 }
7104 }
7105
7106 if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
7107 Caller->replaceAllUsesWith(NV);
7108 Caller->getParent()->getInstList().erase(Caller);
7109 removeFromWorkList(Caller);
7110 return true;
7111}
7112
Chris Lattnercadac0c2006-11-01 04:51:18 +00007113/// FoldPHIArgBinOpIntoPHI - If we have something like phi [add (a,b), add(c,d)]
7114/// and if a/b/c/d and the add's all have a single use, turn this into two phi's
7115/// and a single binop.
7116Instruction *InstCombiner::FoldPHIArgBinOpIntoPHI(PHINode &PN) {
7117 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
Chris Lattnereebea432006-11-01 07:43:41 +00007118 assert(isa<BinaryOperator>(FirstInst) || isa<ShiftInst>(FirstInst) ||
7119 isa<GetElementPtrInst>(FirstInst));
Chris Lattnercadac0c2006-11-01 04:51:18 +00007120 unsigned Opc = FirstInst->getOpcode();
Chris Lattnercd62f112006-11-08 19:29:23 +00007121 Value *LHSVal = FirstInst->getOperand(0);
7122 Value *RHSVal = FirstInst->getOperand(1);
7123
7124 const Type *LHSType = LHSVal->getType();
7125 const Type *RHSType = RHSVal->getType();
Chris Lattnercadac0c2006-11-01 04:51:18 +00007126
7127 // Scan to see if all operands are the same opcode, all have one use, and all
7128 // kill their operands (i.e. the operands have one use).
Chris Lattnerdc826fc2006-11-01 04:55:47 +00007129 for (unsigned i = 0; i != PN.getNumIncomingValues(); ++i) {
Chris Lattnercadac0c2006-11-01 04:51:18 +00007130 Instruction *I = dyn_cast<Instruction>(PN.getIncomingValue(i));
Chris Lattnerdc826fc2006-11-01 04:55:47 +00007131 if (!I || I->getOpcode() != Opc || !I->hasOneUse() ||
7132 // Verify type of the LHS matches so we don't fold setcc's of different
Chris Lattnereebea432006-11-01 07:43:41 +00007133 // types or GEP's with different index types.
7134 I->getOperand(0)->getType() != LHSType ||
7135 I->getOperand(1)->getType() != RHSType)
Chris Lattnercadac0c2006-11-01 04:51:18 +00007136 return 0;
Chris Lattnercd62f112006-11-08 19:29:23 +00007137
7138 // Keep track of which operand needs a phi node.
7139 if (I->getOperand(0) != LHSVal) LHSVal = 0;
7140 if (I->getOperand(1) != RHSVal) RHSVal = 0;
Chris Lattnercadac0c2006-11-01 04:51:18 +00007141 }
7142
Chris Lattner4f218d52006-11-08 19:42:28 +00007143 // Otherwise, this is safe to transform, determine if it is profitable.
7144
7145 // If this is a GEP, and if the index (not the pointer) needs a PHI, bail out.
7146 // Indexes are often folded into load/store instructions, so we don't want to
7147 // hide them behind a phi.
7148 if (isa<GetElementPtrInst>(FirstInst) && RHSVal == 0)
7149 return 0;
7150
Chris Lattnercadac0c2006-11-01 04:51:18 +00007151 Value *InLHS = FirstInst->getOperand(0);
Chris Lattnercadac0c2006-11-01 04:51:18 +00007152 Value *InRHS = FirstInst->getOperand(1);
Chris Lattner4f218d52006-11-08 19:42:28 +00007153 PHINode *NewLHS = 0, *NewRHS = 0;
Chris Lattnercd62f112006-11-08 19:29:23 +00007154 if (LHSVal == 0) {
7155 NewLHS = new PHINode(LHSType, FirstInst->getOperand(0)->getName()+".pn");
7156 NewLHS->reserveOperandSpace(PN.getNumOperands()/2);
7157 NewLHS->addIncoming(InLHS, PN.getIncomingBlock(0));
Chris Lattnereebea432006-11-01 07:43:41 +00007158 InsertNewInstBefore(NewLHS, PN);
7159 LHSVal = NewLHS;
7160 }
Chris Lattnercd62f112006-11-08 19:29:23 +00007161
7162 if (RHSVal == 0) {
7163 NewRHS = new PHINode(RHSType, FirstInst->getOperand(1)->getName()+".pn");
7164 NewRHS->reserveOperandSpace(PN.getNumOperands()/2);
7165 NewRHS->addIncoming(InRHS, PN.getIncomingBlock(0));
Chris Lattnereebea432006-11-01 07:43:41 +00007166 InsertNewInstBefore(NewRHS, PN);
7167 RHSVal = NewRHS;
7168 }
7169
Chris Lattnercd62f112006-11-08 19:29:23 +00007170 // Add all operands to the new PHIs.
7171 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
7172 if (NewLHS) {
7173 Value *NewInLHS =cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
7174 NewLHS->addIncoming(NewInLHS, PN.getIncomingBlock(i));
7175 }
7176 if (NewRHS) {
7177 Value *NewInRHS =cast<Instruction>(PN.getIncomingValue(i))->getOperand(1);
7178 NewRHS->addIncoming(NewInRHS, PN.getIncomingBlock(i));
7179 }
7180 }
7181
Chris Lattnercadac0c2006-11-01 04:51:18 +00007182 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Chris Lattnereebea432006-11-01 07:43:41 +00007183 return BinaryOperator::create(BinOp->getOpcode(), LHSVal, RHSVal);
7184 else if (ShiftInst *SI = dyn_cast<ShiftInst>(FirstInst))
7185 return new ShiftInst(SI->getOpcode(), LHSVal, RHSVal);
7186 else {
7187 assert(isa<GetElementPtrInst>(FirstInst));
7188 return new GetElementPtrInst(LHSVal, RHSVal);
7189 }
Chris Lattnercadac0c2006-11-01 04:51:18 +00007190}
7191
Chris Lattner14f82c72006-11-01 07:13:54 +00007192/// isSafeToSinkLoad - Return true if we know that it is safe sink the load out
7193/// of the block that defines it. This means that it must be obvious the value
7194/// of the load is not changed from the point of the load to the end of the
7195/// block it is in.
7196static bool isSafeToSinkLoad(LoadInst *L) {
7197 BasicBlock::iterator BBI = L, E = L->getParent()->end();
7198
7199 for (++BBI; BBI != E; ++BBI)
7200 if (BBI->mayWriteToMemory())
7201 return false;
7202 return true;
7203}
7204
Chris Lattner970c33a2003-06-19 17:00:31 +00007205
Chris Lattner7515cab2004-11-14 19:13:23 +00007206// FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
7207// operator and they all are only used by the PHI, PHI together their
7208// inputs, and do the operation once, to the result of the PHI.
7209Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
7210 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
7211
7212 // Scan the instruction, looking for input operations that can be folded away.
7213 // If all input operands to the phi are the same instruction (e.g. a cast from
7214 // the same type or "+42") we can pull the operation through the PHI, reducing
7215 // code size and simplifying code.
7216 Constant *ConstantOp = 0;
7217 const Type *CastSrcTy = 0;
Chris Lattner14f82c72006-11-01 07:13:54 +00007218 bool isVolatile = false;
Chris Lattner7515cab2004-11-14 19:13:23 +00007219 if (isa<CastInst>(FirstInst)) {
7220 CastSrcTy = FirstInst->getOperand(0)->getType();
7221 } else if (isa<BinaryOperator>(FirstInst) || isa<ShiftInst>(FirstInst)) {
Chris Lattnercadac0c2006-11-01 04:51:18 +00007222 // Can fold binop or shift here if the RHS is a constant, otherwise call
7223 // FoldPHIArgBinOpIntoPHI.
Chris Lattner7515cab2004-11-14 19:13:23 +00007224 ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
Chris Lattnercadac0c2006-11-01 04:51:18 +00007225 if (ConstantOp == 0)
7226 return FoldPHIArgBinOpIntoPHI(PN);
Chris Lattner14f82c72006-11-01 07:13:54 +00007227 } else if (LoadInst *LI = dyn_cast<LoadInst>(FirstInst)) {
7228 isVolatile = LI->isVolatile();
7229 // We can't sink the load if the loaded value could be modified between the
7230 // load and the PHI.
7231 if (LI->getParent() != PN.getIncomingBlock(0) ||
7232 !isSafeToSinkLoad(LI))
7233 return 0;
Chris Lattnereebea432006-11-01 07:43:41 +00007234 } else if (isa<GetElementPtrInst>(FirstInst)) {
Chris Lattner4f218d52006-11-08 19:42:28 +00007235 if (FirstInst->getNumOperands() == 2)
Chris Lattnereebea432006-11-01 07:43:41 +00007236 return FoldPHIArgBinOpIntoPHI(PN);
7237 // Can't handle general GEPs yet.
7238 return 0;
Chris Lattner7515cab2004-11-14 19:13:23 +00007239 } else {
7240 return 0; // Cannot fold this operation.
7241 }
7242
7243 // Check to see if all arguments are the same operation.
7244 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
7245 if (!isa<Instruction>(PN.getIncomingValue(i))) return 0;
7246 Instruction *I = cast<Instruction>(PN.getIncomingValue(i));
7247 if (!I->hasOneUse() || I->getOpcode() != FirstInst->getOpcode())
7248 return 0;
7249 if (CastSrcTy) {
7250 if (I->getOperand(0)->getType() != CastSrcTy)
7251 return 0; // Cast operation must match.
Chris Lattner14f82c72006-11-01 07:13:54 +00007252 } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
7253 // We can't sink the load if the loaded value could be modified between the
7254 // load and the PHI.
7255 if (LI->isVolatile() != isVolatile ||
7256 LI->getParent() != PN.getIncomingBlock(i) ||
7257 !isSafeToSinkLoad(LI))
7258 return 0;
Chris Lattner7515cab2004-11-14 19:13:23 +00007259 } else if (I->getOperand(1) != ConstantOp) {
7260 return 0;
7261 }
7262 }
7263
7264 // Okay, they are all the same operation. Create a new PHI node of the
7265 // correct type, and PHI together all of the LHS's of the instructions.
7266 PHINode *NewPN = new PHINode(FirstInst->getOperand(0)->getType(),
7267 PN.getName()+".in");
Chris Lattnerd8e20182005-01-29 00:39:08 +00007268 NewPN->reserveOperandSpace(PN.getNumOperands()/2);
Chris Lattner46dd5a62004-11-14 19:29:34 +00007269
7270 Value *InVal = FirstInst->getOperand(0);
7271 NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
Chris Lattner7515cab2004-11-14 19:13:23 +00007272
7273 // Add all operands to the new PHI.
Chris Lattner46dd5a62004-11-14 19:29:34 +00007274 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
7275 Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
7276 if (NewInVal != InVal)
7277 InVal = 0;
7278 NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
7279 }
7280
7281 Value *PhiVal;
7282 if (InVal) {
7283 // The new PHI unions all of the same values together. This is really
7284 // common, so we handle it intelligently here for compile-time speed.
7285 PhiVal = InVal;
7286 delete NewPN;
7287 } else {
7288 InsertNewInstBefore(NewPN, PN);
7289 PhiVal = NewPN;
7290 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00007291
Chris Lattner7515cab2004-11-14 19:13:23 +00007292 // Insert and return the new operation.
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007293 if (CastInst* FirstCI = dyn_cast<CastInst>(FirstInst))
7294 return CastInst::create(FirstCI->getOpcode(), PhiVal, PN.getType());
Reid Spencerde46e482006-11-02 20:25:50 +00007295 else if (isa<LoadInst>(FirstInst))
Chris Lattner14f82c72006-11-01 07:13:54 +00007296 return new LoadInst(PhiVal, "", isVolatile);
Chris Lattner7515cab2004-11-14 19:13:23 +00007297 else if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Chris Lattner46dd5a62004-11-14 19:29:34 +00007298 return BinaryOperator::create(BinOp->getOpcode(), PhiVal, ConstantOp);
Chris Lattner7515cab2004-11-14 19:13:23 +00007299 else
7300 return new ShiftInst(cast<ShiftInst>(FirstInst)->getOpcode(),
Chris Lattner46dd5a62004-11-14 19:29:34 +00007301 PhiVal, ConstantOp);
Chris Lattner7515cab2004-11-14 19:13:23 +00007302}
Chris Lattner48a44f72002-05-02 17:06:02 +00007303
Chris Lattner71536432005-01-17 05:10:15 +00007304/// DeadPHICycle - Return true if this PHI node is only used by a PHI node cycle
7305/// that is dead.
7306static bool DeadPHICycle(PHINode *PN, std::set<PHINode*> &PotentiallyDeadPHIs) {
7307 if (PN->use_empty()) return true;
7308 if (!PN->hasOneUse()) return false;
7309
7310 // Remember this node, and if we find the cycle, return.
7311 if (!PotentiallyDeadPHIs.insert(PN).second)
7312 return true;
7313
7314 if (PHINode *PU = dyn_cast<PHINode>(PN->use_back()))
7315 return DeadPHICycle(PU, PotentiallyDeadPHIs);
Misha Brukmanb1c93172005-04-21 23:48:37 +00007316
Chris Lattner71536432005-01-17 05:10:15 +00007317 return false;
7318}
7319
Chris Lattnerbbbdd852002-05-06 18:06:38 +00007320// PHINode simplification
7321//
Chris Lattner113f4f42002-06-25 16:13:24 +00007322Instruction *InstCombiner::visitPHINode(PHINode &PN) {
Owen Andersonbbf89902006-07-10 22:15:25 +00007323 // If LCSSA is around, don't mess with Phi nodes
7324 if (mustPreserveAnalysisID(LCSSAID)) return 0;
Owen Andersona6968f82006-07-10 19:03:49 +00007325
Owen Andersonae8aa642006-07-10 22:03:18 +00007326 if (Value *V = PN.hasConstantValue())
7327 return ReplaceInstUsesWith(PN, V);
7328
Owen Andersonae8aa642006-07-10 22:03:18 +00007329 // If all PHI operands are the same operation, pull them through the PHI,
7330 // reducing code size.
7331 if (isa<Instruction>(PN.getIncomingValue(0)) &&
7332 PN.getIncomingValue(0)->hasOneUse())
7333 if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
7334 return Result;
7335
7336 // If this is a trivial cycle in the PHI node graph, remove it. Basically, if
7337 // this PHI only has a single use (a PHI), and if that PHI only has one use (a
7338 // PHI)... break the cycle.
7339 if (PN.hasOneUse())
7340 if (PHINode *PU = dyn_cast<PHINode>(PN.use_back())) {
7341 std::set<PHINode*> PotentiallyDeadPHIs;
7342 PotentiallyDeadPHIs.insert(&PN);
7343 if (DeadPHICycle(PU, PotentiallyDeadPHIs))
7344 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
7345 }
7346
Chris Lattner91daeb52003-12-19 05:58:40 +00007347 return 0;
Chris Lattnerbbbdd852002-05-06 18:06:38 +00007348}
7349
Reid Spencer13bc5d72006-12-12 09:18:51 +00007350static Value *InsertCastToIntPtrTy(Value *V, const Type *DTy,
7351 Instruction *InsertPoint,
7352 InstCombiner *IC) {
7353 unsigned PtrSize = IC->getTargetData().getPointerSize();
7354 unsigned VTySize = V->getType()->getPrimitiveSize();
7355 // We must cast correctly to the pointer type. Ensure that we
7356 // sign extend the integer value if it is smaller as this is
7357 // used for address computation.
7358 Instruction::CastOps opcode =
7359 (VTySize < PtrSize ? Instruction::SExt :
7360 (VTySize == PtrSize ? Instruction::BitCast : Instruction::Trunc));
7361 return IC->InsertCastBefore(opcode, V, DTy, *InsertPoint);
Chris Lattner69193f92004-04-05 01:30:19 +00007362}
7363
Chris Lattner48a44f72002-05-02 17:06:02 +00007364
Chris Lattner113f4f42002-06-25 16:13:24 +00007365Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
Chris Lattner5f667a62004-05-07 22:09:22 +00007366 Value *PtrOp = GEP.getOperand(0);
Chris Lattner471bd762003-05-22 19:07:21 +00007367 // Is it 'getelementptr %P, long 0' or 'getelementptr %P'
Chris Lattner113f4f42002-06-25 16:13:24 +00007368 // If so, eliminate the noop.
Chris Lattner8d0bacb2004-02-22 05:25:17 +00007369 if (GEP.getNumOperands() == 1)
Chris Lattner5f667a62004-05-07 22:09:22 +00007370 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattner8d0bacb2004-02-22 05:25:17 +00007371
Chris Lattner81a7a232004-10-16 18:11:37 +00007372 if (isa<UndefValue>(GEP.getOperand(0)))
7373 return ReplaceInstUsesWith(GEP, UndefValue::get(GEP.getType()));
7374
Chris Lattner8d0bacb2004-02-22 05:25:17 +00007375 bool HasZeroPointerIndex = false;
7376 if (Constant *C = dyn_cast<Constant>(GEP.getOperand(1)))
7377 HasZeroPointerIndex = C->isNullValue();
7378
7379 if (GEP.getNumOperands() == 2 && HasZeroPointerIndex)
Chris Lattner5f667a62004-05-07 22:09:22 +00007380 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattner48a44f72002-05-02 17:06:02 +00007381
Chris Lattner69193f92004-04-05 01:30:19 +00007382 // Eliminate unneeded casts for indices.
7383 bool MadeChange = false;
Chris Lattner2b2412d2004-04-07 18:38:20 +00007384 gep_type_iterator GTI = gep_type_begin(GEP);
7385 for (unsigned i = 1, e = GEP.getNumOperands(); i != e; ++i, ++GTI)
7386 if (isa<SequentialType>(*GTI)) {
7387 if (CastInst *CI = dyn_cast<CastInst>(GEP.getOperand(i))) {
7388 Value *Src = CI->getOperand(0);
7389 const Type *SrcTy = Src->getType();
7390 const Type *DestTy = CI->getType();
7391 if (Src->getType()->isInteger()) {
Chris Lattnerd1f46d32005-04-24 06:59:08 +00007392 if (SrcTy->getPrimitiveSizeInBits() ==
7393 DestTy->getPrimitiveSizeInBits()) {
Chris Lattner2b2412d2004-04-07 18:38:20 +00007394 // We can always eliminate a cast from ulong or long to the other.
7395 // We can always eliminate a cast from uint to int or the other on
7396 // 32-bit pointer platforms.
Chris Lattnerd1f46d32005-04-24 06:59:08 +00007397 if (DestTy->getPrimitiveSizeInBits() >= TD->getPointerSizeInBits()){
Chris Lattner2b2412d2004-04-07 18:38:20 +00007398 MadeChange = true;
7399 GEP.setOperand(i, Src);
7400 }
7401 } else if (SrcTy->getPrimitiveSize() < DestTy->getPrimitiveSize() &&
7402 SrcTy->getPrimitiveSize() == 4) {
7403 // We can always eliminate a cast from int to [u]long. We can
7404 // eliminate a cast from uint to [u]long iff the target is a 32-bit
7405 // pointer target.
Misha Brukmanb1c93172005-04-21 23:48:37 +00007406 if (SrcTy->isSigned() ||
Chris Lattnerd1f46d32005-04-24 06:59:08 +00007407 SrcTy->getPrimitiveSizeInBits() >= TD->getPointerSizeInBits()) {
Chris Lattner2b2412d2004-04-07 18:38:20 +00007408 MadeChange = true;
7409 GEP.setOperand(i, Src);
7410 }
Chris Lattner69193f92004-04-05 01:30:19 +00007411 }
7412 }
7413 }
Chris Lattner2b2412d2004-04-07 18:38:20 +00007414 // If we are using a wider index than needed for this platform, shrink it
7415 // to what we need. If the incoming value needs a cast instruction,
7416 // insert it. This explicit cast can make subsequent optimizations more
7417 // obvious.
7418 Value *Op = GEP.getOperand(i);
7419 if (Op->getType()->getPrimitiveSize() > TD->getPointerSize())
Chris Lattner1e9ac1a2004-04-17 18:16:10 +00007420 if (Constant *C = dyn_cast<Constant>(Op)) {
Reid Spencer13bc5d72006-12-12 09:18:51 +00007421 GEP.setOperand(i, ConstantExpr::getTrunc(C,
Chris Lattner44d0b952004-07-20 01:48:15 +00007422 TD->getIntPtrType()->getSignedVersion()));
Chris Lattner1e9ac1a2004-04-17 18:16:10 +00007423 MadeChange = true;
7424 } else {
Reid Spencer13bc5d72006-12-12 09:18:51 +00007425 Op = InsertCastBefore(Instruction::Trunc, Op, TD->getIntPtrType(),
7426 GEP);
Chris Lattner2b2412d2004-04-07 18:38:20 +00007427 GEP.setOperand(i, Op);
7428 MadeChange = true;
7429 }
Chris Lattner44d0b952004-07-20 01:48:15 +00007430
7431 // If this is a constant idx, make sure to canonicalize it to be a signed
7432 // operand, otherwise CSE and other optimizations are pessimized.
Reid Spencere0fc4df2006-10-20 07:07:24 +00007433 if (ConstantInt *CUI = dyn_cast<ConstantInt>(Op))
7434 if (CUI->getType()->isUnsigned()) {
7435 GEP.setOperand(i,
Reid Spencer13bc5d72006-12-12 09:18:51 +00007436 ConstantExpr::getBitCast(CUI, CUI->getType()->getSignedVersion()));
Reid Spencere0fc4df2006-10-20 07:07:24 +00007437 MadeChange = true;
7438 }
Chris Lattner69193f92004-04-05 01:30:19 +00007439 }
7440 if (MadeChange) return &GEP;
7441
Chris Lattnerae7a0d32002-08-02 19:29:35 +00007442 // Combine Indices - If the source pointer to this getelementptr instruction
7443 // is a getelementptr instruction, combine the indices of the two
7444 // getelementptr instructions into a single instruction.
7445 //
Chris Lattner57c67b02004-03-25 22:59:29 +00007446 std::vector<Value*> SrcGEPOperands;
Chris Lattner0798af32005-01-13 20:14:25 +00007447 if (User *Src = dyn_castGetElementPtr(PtrOp))
Chris Lattner57c67b02004-03-25 22:59:29 +00007448 SrcGEPOperands.assign(Src->op_begin(), Src->op_end());
Chris Lattner57c67b02004-03-25 22:59:29 +00007449
7450 if (!SrcGEPOperands.empty()) {
Chris Lattner5f667a62004-05-07 22:09:22 +00007451 // Note that if our source is a gep chain itself that we wait for that
7452 // chain to be resolved before we perform this transformation. This
7453 // avoids us creating a TON of code in some cases.
7454 //
7455 if (isa<GetElementPtrInst>(SrcGEPOperands[0]) &&
7456 cast<Instruction>(SrcGEPOperands[0])->getNumOperands() == 2)
7457 return 0; // Wait until our source is folded to completion.
7458
Chris Lattnerae7a0d32002-08-02 19:29:35 +00007459 std::vector<Value *> Indices;
Chris Lattner5f667a62004-05-07 22:09:22 +00007460
7461 // Find out whether the last index in the source GEP is a sequential idx.
7462 bool EndsWithSequential = false;
7463 for (gep_type_iterator I = gep_type_begin(*cast<User>(PtrOp)),
7464 E = gep_type_end(*cast<User>(PtrOp)); I != E; ++I)
Chris Lattner8ec5f882004-05-08 22:41:42 +00007465 EndsWithSequential = !isa<StructType>(*I);
Misha Brukmanb1c93172005-04-21 23:48:37 +00007466
Chris Lattnerae7a0d32002-08-02 19:29:35 +00007467 // Can we combine the two pointer arithmetics offsets?
Chris Lattner5f667a62004-05-07 22:09:22 +00007468 if (EndsWithSequential) {
Chris Lattner235af562003-03-05 22:33:14 +00007469 // Replace: gep (gep %P, long B), long A, ...
7470 // With: T = long A+B; gep %P, T, ...
7471 //
Chris Lattner5f667a62004-05-07 22:09:22 +00007472 Value *Sum, *SO1 = SrcGEPOperands.back(), *GO1 = GEP.getOperand(1);
Chris Lattner69193f92004-04-05 01:30:19 +00007473 if (SO1 == Constant::getNullValue(SO1->getType())) {
7474 Sum = GO1;
7475 } else if (GO1 == Constant::getNullValue(GO1->getType())) {
7476 Sum = SO1;
7477 } else {
7478 // If they aren't the same type, convert both to an integer of the
7479 // target's pointer size.
7480 if (SO1->getType() != GO1->getType()) {
7481 if (Constant *SO1C = dyn_cast<Constant>(SO1)) {
Reid Spencer13bc5d72006-12-12 09:18:51 +00007482 SO1 = ConstantExpr::getIntegerCast(SO1C, GO1->getType(), true);
Chris Lattner69193f92004-04-05 01:30:19 +00007483 } else if (Constant *GO1C = dyn_cast<Constant>(GO1)) {
Reid Spencer13bc5d72006-12-12 09:18:51 +00007484 GO1 = ConstantExpr::getIntegerCast(GO1C, SO1->getType(), true);
Chris Lattner69193f92004-04-05 01:30:19 +00007485 } else {
7486 unsigned PS = TD->getPointerSize();
Chris Lattner69193f92004-04-05 01:30:19 +00007487 if (SO1->getType()->getPrimitiveSize() == PS) {
7488 // Convert GO1 to SO1's type.
Reid Spencer13bc5d72006-12-12 09:18:51 +00007489 GO1 = InsertCastToIntPtrTy(GO1, SO1->getType(), &GEP, this);
Chris Lattner69193f92004-04-05 01:30:19 +00007490
7491 } else if (GO1->getType()->getPrimitiveSize() == PS) {
7492 // Convert SO1 to GO1's type.
Reid Spencer13bc5d72006-12-12 09:18:51 +00007493 SO1 = InsertCastToIntPtrTy(SO1, GO1->getType(), &GEP, this);
Chris Lattner69193f92004-04-05 01:30:19 +00007494 } else {
7495 const Type *PT = TD->getIntPtrType();
Reid Spencer13bc5d72006-12-12 09:18:51 +00007496 SO1 = InsertCastToIntPtrTy(SO1, PT, &GEP, this);
7497 GO1 = InsertCastToIntPtrTy(GO1, PT, &GEP, this);
Chris Lattner69193f92004-04-05 01:30:19 +00007498 }
7499 }
7500 }
Chris Lattner5f667a62004-05-07 22:09:22 +00007501 if (isa<Constant>(SO1) && isa<Constant>(GO1))
7502 Sum = ConstantExpr::getAdd(cast<Constant>(SO1), cast<Constant>(GO1));
7503 else {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00007504 Sum = BinaryOperator::createAdd(SO1, GO1, PtrOp->getName()+".sum");
7505 InsertNewInstBefore(cast<Instruction>(Sum), GEP);
Chris Lattner5f667a62004-05-07 22:09:22 +00007506 }
Chris Lattner69193f92004-04-05 01:30:19 +00007507 }
Chris Lattner5f667a62004-05-07 22:09:22 +00007508
7509 // Recycle the GEP we already have if possible.
7510 if (SrcGEPOperands.size() == 2) {
7511 GEP.setOperand(0, SrcGEPOperands[0]);
7512 GEP.setOperand(1, Sum);
7513 return &GEP;
7514 } else {
7515 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
7516 SrcGEPOperands.end()-1);
7517 Indices.push_back(Sum);
7518 Indices.insert(Indices.end(), GEP.op_begin()+2, GEP.op_end());
7519 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00007520 } else if (isa<Constant>(*GEP.idx_begin()) &&
Chris Lattner69193f92004-04-05 01:30:19 +00007521 cast<Constant>(*GEP.idx_begin())->isNullValue() &&
Misha Brukmanb1c93172005-04-21 23:48:37 +00007522 SrcGEPOperands.size() != 1) {
Chris Lattnerae7a0d32002-08-02 19:29:35 +00007523 // Otherwise we can do the fold if the first index of the GEP is a zero
Chris Lattner57c67b02004-03-25 22:59:29 +00007524 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
7525 SrcGEPOperands.end());
Chris Lattnerae7a0d32002-08-02 19:29:35 +00007526 Indices.insert(Indices.end(), GEP.idx_begin()+1, GEP.idx_end());
7527 }
7528
7529 if (!Indices.empty())
Chris Lattner57c67b02004-03-25 22:59:29 +00007530 return new GetElementPtrInst(SrcGEPOperands[0], Indices, GEP.getName());
Chris Lattnerc59af1d2002-08-17 22:21:59 +00007531
Chris Lattner5f667a62004-05-07 22:09:22 +00007532 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(PtrOp)) {
Chris Lattnerc59af1d2002-08-17 22:21:59 +00007533 // GEP of global variable. If all of the indices for this GEP are
7534 // constants, we can promote this to a constexpr instead of an instruction.
7535
7536 // Scan for nonconstants...
7537 std::vector<Constant*> Indices;
7538 User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end();
7539 for (; I != E && isa<Constant>(*I); ++I)
7540 Indices.push_back(cast<Constant>(*I));
7541
7542 if (I == E) { // If they are all constants...
Chris Lattnerf3edc492004-07-18 18:59:44 +00007543 Constant *CE = ConstantExpr::getGetElementPtr(GV, Indices);
Chris Lattnerc59af1d2002-08-17 22:21:59 +00007544
7545 // Replace all uses of the GEP with the new constexpr...
7546 return ReplaceInstUsesWith(GEP, CE);
7547 }
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007548 } else if (Value *X = getBitCastOperand(PtrOp)) { // Is the operand a cast?
Chris Lattner567b81f2005-09-13 00:40:14 +00007549 if (!isa<PointerType>(X->getType())) {
7550 // Not interesting. Source pointer must be a cast from pointer.
7551 } else if (HasZeroPointerIndex) {
7552 // transform: GEP (cast [10 x ubyte]* X to [0 x ubyte]*), long 0, ...
7553 // into : GEP [10 x ubyte]* X, long 0, ...
7554 //
7555 // This occurs when the program declares an array extern like "int X[];"
7556 //
7557 const PointerType *CPTy = cast<PointerType>(PtrOp->getType());
7558 const PointerType *XTy = cast<PointerType>(X->getType());
7559 if (const ArrayType *XATy =
7560 dyn_cast<ArrayType>(XTy->getElementType()))
7561 if (const ArrayType *CATy =
7562 dyn_cast<ArrayType>(CPTy->getElementType()))
7563 if (CATy->getElementType() == XATy->getElementType()) {
7564 // At this point, we know that the cast source type is a pointer
7565 // to an array of the same type as the destination pointer
7566 // array. Because the array type is never stepped over (there
7567 // is a leading zero) we can fold the cast into this GEP.
7568 GEP.setOperand(0, X);
7569 return &GEP;
7570 }
7571 } else if (GEP.getNumOperands() == 2) {
7572 // Transform things like:
Chris Lattner2a893292005-09-13 18:36:04 +00007573 // %t = getelementptr ubyte* cast ([2 x int]* %str to uint*), uint %V
7574 // into: %t1 = getelementptr [2 x int*]* %str, int 0, uint %V; cast
Chris Lattner567b81f2005-09-13 00:40:14 +00007575 const Type *SrcElTy = cast<PointerType>(X->getType())->getElementType();
7576 const Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
7577 if (isa<ArrayType>(SrcElTy) &&
7578 TD->getTypeSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
7579 TD->getTypeSize(ResElTy)) {
7580 Value *V = InsertNewInstBefore(
7581 new GetElementPtrInst(X, Constant::getNullValue(Type::IntTy),
7582 GEP.getOperand(1), GEP.getName()), GEP);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007583 // V and GEP are both pointer types --> BitCast
7584 return new BitCastInst(V, GEP.getType());
Chris Lattner8d0bacb2004-02-22 05:25:17 +00007585 }
Chris Lattner2a893292005-09-13 18:36:04 +00007586
7587 // Transform things like:
7588 // getelementptr sbyte* cast ([100 x double]* X to sbyte*), int %tmp
7589 // (where tmp = 8*tmp2) into:
7590 // getelementptr [100 x double]* %arr, int 0, int %tmp.2
7591
7592 if (isa<ArrayType>(SrcElTy) &&
7593 (ResElTy == Type::SByteTy || ResElTy == Type::UByteTy)) {
7594 uint64_t ArrayEltSize =
7595 TD->getTypeSize(cast<ArrayType>(SrcElTy)->getElementType());
7596
7597 // Check to see if "tmp" is a scale by a multiple of ArrayEltSize. We
7598 // allow either a mul, shift, or constant here.
7599 Value *NewIdx = 0;
7600 ConstantInt *Scale = 0;
7601 if (ArrayEltSize == 1) {
7602 NewIdx = GEP.getOperand(1);
7603 Scale = ConstantInt::get(NewIdx->getType(), 1);
7604 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) {
Chris Lattnera393e4d2005-09-14 17:32:56 +00007605 NewIdx = ConstantInt::get(CI->getType(), 1);
Chris Lattner2a893292005-09-13 18:36:04 +00007606 Scale = CI;
7607 } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){
7608 if (Inst->getOpcode() == Instruction::Shl &&
7609 isa<ConstantInt>(Inst->getOperand(1))) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00007610 unsigned ShAmt =
7611 cast<ConstantInt>(Inst->getOperand(1))->getZExtValue();
Chris Lattner2a893292005-09-13 18:36:04 +00007612 if (Inst->getType()->isSigned())
Reid Spencere0fc4df2006-10-20 07:07:24 +00007613 Scale = ConstantInt::get(Inst->getType(), 1ULL << ShAmt);
Chris Lattner2a893292005-09-13 18:36:04 +00007614 else
Reid Spencere0fc4df2006-10-20 07:07:24 +00007615 Scale = ConstantInt::get(Inst->getType(), 1ULL << ShAmt);
Chris Lattner2a893292005-09-13 18:36:04 +00007616 NewIdx = Inst->getOperand(0);
7617 } else if (Inst->getOpcode() == Instruction::Mul &&
7618 isa<ConstantInt>(Inst->getOperand(1))) {
7619 Scale = cast<ConstantInt>(Inst->getOperand(1));
7620 NewIdx = Inst->getOperand(0);
7621 }
7622 }
7623
7624 // If the index will be to exactly the right offset with the scale taken
7625 // out, perform the transformation.
Reid Spencere0fc4df2006-10-20 07:07:24 +00007626 if (Scale && Scale->getZExtValue() % ArrayEltSize == 0) {
Reid Spencerde46e482006-11-02 20:25:50 +00007627 if (isa<ConstantInt>(Scale))
Reid Spencere0fc4df2006-10-20 07:07:24 +00007628 Scale = ConstantInt::get(Scale->getType(),
7629 Scale->getZExtValue() / ArrayEltSize);
7630 if (Scale->getZExtValue() != 1) {
Reid Spencer13bc5d72006-12-12 09:18:51 +00007631 Constant *C = ConstantExpr::getIntegerCast(Scale, NewIdx->getType(),
7632 true /*SExt*/);
Chris Lattner2a893292005-09-13 18:36:04 +00007633 Instruction *Sc = BinaryOperator::createMul(NewIdx, C, "idxscale");
7634 NewIdx = InsertNewInstBefore(Sc, GEP);
7635 }
7636
7637 // Insert the new GEP instruction.
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007638 Instruction *NewGEP =
Chris Lattner2a893292005-09-13 18:36:04 +00007639 new GetElementPtrInst(X, Constant::getNullValue(Type::IntTy),
7640 NewIdx, GEP.getName());
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007641 NewGEP = InsertNewInstBefore(NewGEP, GEP);
7642 // The NewGEP must be pointer typed, so must the old one -> BitCast
7643 return new BitCastInst(NewGEP, GEP.getType());
Chris Lattner2a893292005-09-13 18:36:04 +00007644 }
7645 }
Chris Lattner8d0bacb2004-02-22 05:25:17 +00007646 }
Chris Lattnerca081252001-12-14 16:52:21 +00007647 }
7648
Chris Lattnerca081252001-12-14 16:52:21 +00007649 return 0;
7650}
7651
Chris Lattner1085bdf2002-11-04 16:18:53 +00007652Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
7653 // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
7654 if (AI.isArrayAllocation()) // Check C != 1
Reid Spencere0fc4df2006-10-20 07:07:24 +00007655 if (const ConstantInt *C = dyn_cast<ConstantInt>(AI.getArraySize())) {
7656 const Type *NewTy =
7657 ArrayType::get(AI.getAllocatedType(), C->getZExtValue());
Chris Lattnera2620ac2002-11-09 00:49:43 +00007658 AllocationInst *New = 0;
Chris Lattner1085bdf2002-11-04 16:18:53 +00007659
7660 // Create and insert the replacement instruction...
7661 if (isa<MallocInst>(AI))
Nate Begeman848622f2005-11-05 09:21:28 +00007662 New = new MallocInst(NewTy, 0, AI.getAlignment(), AI.getName());
Chris Lattnera2620ac2002-11-09 00:49:43 +00007663 else {
7664 assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
Nate Begeman848622f2005-11-05 09:21:28 +00007665 New = new AllocaInst(NewTy, 0, AI.getAlignment(), AI.getName());
Chris Lattnera2620ac2002-11-09 00:49:43 +00007666 }
Chris Lattnerabb77c92004-03-19 06:08:10 +00007667
7668 InsertNewInstBefore(New, AI);
Misha Brukmanb1c93172005-04-21 23:48:37 +00007669
Chris Lattner1085bdf2002-11-04 16:18:53 +00007670 // Scan to the end of the allocation instructions, to skip over a block of
7671 // allocas if possible...
7672 //
7673 BasicBlock::iterator It = New;
7674 while (isa<AllocationInst>(*It)) ++It;
7675
7676 // Now that I is pointing to the first non-allocation-inst in the block,
7677 // insert our getelementptr instruction...
7678 //
Chris Lattner809dfac2005-05-04 19:10:26 +00007679 Value *NullIdx = Constant::getNullValue(Type::IntTy);
7680 Value *V = new GetElementPtrInst(New, NullIdx, NullIdx,
7681 New->getName()+".sub", It);
Chris Lattner1085bdf2002-11-04 16:18:53 +00007682
7683 // Now make everything use the getelementptr instead of the original
7684 // allocation.
Chris Lattnerabb77c92004-03-19 06:08:10 +00007685 return ReplaceInstUsesWith(AI, V);
Chris Lattner81a7a232004-10-16 18:11:37 +00007686 } else if (isa<UndefValue>(AI.getArraySize())) {
7687 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
Chris Lattner1085bdf2002-11-04 16:18:53 +00007688 }
Chris Lattnerabb77c92004-03-19 06:08:10 +00007689
7690 // If alloca'ing a zero byte object, replace the alloca with a null pointer.
7691 // Note that we only do this for alloca's, because malloc should allocate and
7692 // return a unique pointer, even for a zero byte allocation.
Misha Brukmanb1c93172005-04-21 23:48:37 +00007693 if (isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized() &&
Chris Lattner49df6ce2004-07-02 22:55:47 +00007694 TD->getTypeSize(AI.getAllocatedType()) == 0)
Chris Lattnerabb77c92004-03-19 06:08:10 +00007695 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
7696
Chris Lattner1085bdf2002-11-04 16:18:53 +00007697 return 0;
7698}
7699
Chris Lattner8427bff2003-12-07 01:24:23 +00007700Instruction *InstCombiner::visitFreeInst(FreeInst &FI) {
7701 Value *Op = FI.getOperand(0);
7702
7703 // Change free <ty>* (cast <ty2>* X to <ty>*) into free <ty2>* X
7704 if (CastInst *CI = dyn_cast<CastInst>(Op))
7705 if (isa<PointerType>(CI->getOperand(0)->getType())) {
7706 FI.setOperand(0, CI->getOperand(0));
7707 return &FI;
7708 }
7709
Chris Lattner8ba9ec92004-10-18 02:59:09 +00007710 // free undef -> unreachable.
7711 if (isa<UndefValue>(Op)) {
7712 // Insert a new store to null because we cannot modify the CFG here.
Chris Lattner6ab03f62006-09-28 23:35:22 +00007713 new StoreInst(ConstantBool::getTrue(),
Chris Lattner8ba9ec92004-10-18 02:59:09 +00007714 UndefValue::get(PointerType::get(Type::BoolTy)), &FI);
7715 return EraseInstFromFunction(FI);
7716 }
7717
Chris Lattnerf3a36602004-02-28 04:57:37 +00007718 // If we have 'free null' delete the instruction. This can happen in stl code
7719 // when lots of inlining happens.
Chris Lattner8ba9ec92004-10-18 02:59:09 +00007720 if (isa<ConstantPointerNull>(Op))
Chris Lattner51ea1272004-02-28 05:22:00 +00007721 return EraseInstFromFunction(FI);
Chris Lattnerf3a36602004-02-28 04:57:37 +00007722
Chris Lattner8427bff2003-12-07 01:24:23 +00007723 return 0;
7724}
7725
7726
Chris Lattner72684fe2005-01-31 05:51:45 +00007727/// InstCombineLoadCast - Fold 'load (cast P)' -> cast (load P)' when possible.
Chris Lattner35e24772004-07-13 01:49:43 +00007728static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI) {
7729 User *CI = cast<User>(LI.getOperand(0));
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00007730 Value *CastOp = CI->getOperand(0);
Chris Lattner35e24772004-07-13 01:49:43 +00007731
7732 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00007733 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
Chris Lattner35e24772004-07-13 01:49:43 +00007734 const Type *SrcPTy = SrcTy->getElementType();
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00007735
Chris Lattnerebca4762006-04-02 05:37:12 +00007736 if (DestPTy->isInteger() || isa<PointerType>(DestPTy) ||
7737 isa<PackedType>(DestPTy)) {
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00007738 // If the source is an array, the code below will not succeed. Check to
7739 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
7740 // constants.
7741 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
7742 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
7743 if (ASrcTy->getNumElements() != 0) {
7744 std::vector<Value*> Idxs(2, Constant::getNullValue(Type::IntTy));
7745 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs);
7746 SrcTy = cast<PointerType>(CastOp->getType());
7747 SrcPTy = SrcTy->getElementType();
7748 }
7749
Chris Lattnerebca4762006-04-02 05:37:12 +00007750 if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy) ||
7751 isa<PackedType>(SrcPTy)) &&
Chris Lattnerecfa9b52005-03-29 06:37:47 +00007752 // Do not allow turning this into a load of an integer, which is then
7753 // casted to a pointer, this pessimizes pointer analysis a lot.
7754 (isa<PointerType>(SrcPTy) == isa<PointerType>(LI.getType())) &&
Misha Brukmanb1c93172005-04-21 23:48:37 +00007755 IC.getTargetData().getTypeSize(SrcPTy) ==
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00007756 IC.getTargetData().getTypeSize(DestPTy)) {
Misha Brukmanb1c93172005-04-21 23:48:37 +00007757
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00007758 // Okay, we are casting from one integer or pointer type to another of
7759 // the same size. Instead of casting the pointer before the load, cast
7760 // the result of the loaded value.
7761 Value *NewLoad = IC.InsertNewInstBefore(new LoadInst(CastOp,
7762 CI->getName(),
7763 LI.isVolatile()),LI);
7764 // Now cast the result of the load.
Reid Spencerbb65ebf2006-12-12 23:36:14 +00007765 return new BitCastInst(NewLoad, LI.getType());
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00007766 }
Chris Lattner35e24772004-07-13 01:49:43 +00007767 }
7768 }
7769 return 0;
7770}
7771
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00007772/// isSafeToLoadUnconditionally - Return true if we know that executing a load
Chris Lattnere6f13092004-09-19 19:18:10 +00007773/// from this value cannot trap. If it is not obviously safe to load from the
7774/// specified pointer, we do a quick local scan of the basic block containing
7775/// ScanFrom, to determine if the address is already accessed.
7776static bool isSafeToLoadUnconditionally(Value *V, Instruction *ScanFrom) {
7777 // If it is an alloca or global variable, it is always safe to load from.
7778 if (isa<AllocaInst>(V) || isa<GlobalVariable>(V)) return true;
7779
7780 // Otherwise, be a little bit agressive by scanning the local block where we
7781 // want to check to see if the pointer is already being loaded or stored
Alkis Evlogimenosd59cebf2004-09-20 06:42:58 +00007782 // from/to. If so, the previous load or store would have already trapped,
7783 // so there is no harm doing an extra load (also, CSE will later eliminate
7784 // the load entirely).
Chris Lattnere6f13092004-09-19 19:18:10 +00007785 BasicBlock::iterator BBI = ScanFrom, E = ScanFrom->getParent()->begin();
7786
Alkis Evlogimenosd59cebf2004-09-20 06:42:58 +00007787 while (BBI != E) {
Chris Lattnere6f13092004-09-19 19:18:10 +00007788 --BBI;
7789
7790 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
7791 if (LI->getOperand(0) == V) return true;
7792 } else if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
7793 if (SI->getOperand(1) == V) return true;
Misha Brukmanb1c93172005-04-21 23:48:37 +00007794
Alkis Evlogimenosd59cebf2004-09-20 06:42:58 +00007795 }
Chris Lattnere6f13092004-09-19 19:18:10 +00007796 return false;
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00007797}
7798
Chris Lattner0f1d8a32003-06-26 05:06:25 +00007799Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
7800 Value *Op = LI.getOperand(0);
Chris Lattner7e8af382004-01-12 04:13:56 +00007801
Chris Lattnera9d84e32005-05-01 04:24:53 +00007802 // load (cast X) --> cast (load X) iff safe
Reid Spencerde46e482006-11-02 20:25:50 +00007803 if (isa<CastInst>(Op))
Chris Lattnera9d84e32005-05-01 04:24:53 +00007804 if (Instruction *Res = InstCombineLoadCast(*this, LI))
7805 return Res;
7806
7807 // None of the following transforms are legal for volatile loads.
7808 if (LI.isVolatile()) return 0;
Chris Lattnerb990f7d2005-09-12 22:00:15 +00007809
Chris Lattnerb990f7d2005-09-12 22:00:15 +00007810 if (&LI.getParent()->front() != &LI) {
7811 BasicBlock::iterator BBI = &LI; --BBI;
Chris Lattnere0bfdf12005-09-12 22:21:03 +00007812 // If the instruction immediately before this is a store to the same
7813 // address, do a simple form of store->load forwarding.
Chris Lattnerb990f7d2005-09-12 22:00:15 +00007814 if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
7815 if (SI->getOperand(1) == LI.getOperand(0))
7816 return ReplaceInstUsesWith(LI, SI->getOperand(0));
Chris Lattnere0bfdf12005-09-12 22:21:03 +00007817 if (LoadInst *LIB = dyn_cast<LoadInst>(BBI))
7818 if (LIB->getOperand(0) == LI.getOperand(0))
7819 return ReplaceInstUsesWith(LI, LIB);
Chris Lattnerb990f7d2005-09-12 22:00:15 +00007820 }
Chris Lattnera9d84e32005-05-01 04:24:53 +00007821
7822 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op))
7823 if (isa<ConstantPointerNull>(GEPI->getOperand(0)) ||
7824 isa<UndefValue>(GEPI->getOperand(0))) {
7825 // Insert a new store to null instruction before the load to indicate
7826 // that this code is not reachable. We do this instead of inserting
7827 // an unreachable instruction directly because we cannot modify the
7828 // CFG.
7829 new StoreInst(UndefValue::get(LI.getType()),
7830 Constant::getNullValue(Op->getType()), &LI);
7831 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
7832 }
7833
Chris Lattner81a7a232004-10-16 18:11:37 +00007834 if (Constant *C = dyn_cast<Constant>(Op)) {
Chris Lattnera9d84e32005-05-01 04:24:53 +00007835 // load null/undef -> undef
7836 if ((C->isNullValue() || isa<UndefValue>(C))) {
Chris Lattner8ba9ec92004-10-18 02:59:09 +00007837 // Insert a new store to null instruction before the load to indicate that
7838 // this code is not reachable. We do this instead of inserting an
7839 // unreachable instruction directly because we cannot modify the CFG.
Chris Lattnera9d84e32005-05-01 04:24:53 +00007840 new StoreInst(UndefValue::get(LI.getType()),
7841 Constant::getNullValue(Op->getType()), &LI);
Chris Lattner81a7a232004-10-16 18:11:37 +00007842 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
Chris Lattner8ba9ec92004-10-18 02:59:09 +00007843 }
Chris Lattner0f1d8a32003-06-26 05:06:25 +00007844
Chris Lattner81a7a232004-10-16 18:11:37 +00007845 // Instcombine load (constant global) into the value loaded.
7846 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op))
7847 if (GV->isConstant() && !GV->isExternal())
7848 return ReplaceInstUsesWith(LI, GV->getInitializer());
Misha Brukmanb1c93172005-04-21 23:48:37 +00007849
Chris Lattner81a7a232004-10-16 18:11:37 +00007850 // Instcombine load (constantexpr_GEP global, 0, ...) into the value loaded.
7851 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op))
7852 if (CE->getOpcode() == Instruction::GetElementPtr) {
7853 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
7854 if (GV->isConstant() && !GV->isExternal())
Chris Lattner0b011ec2005-09-26 05:28:06 +00007855 if (Constant *V =
7856 ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE))
Chris Lattner81a7a232004-10-16 18:11:37 +00007857 return ReplaceInstUsesWith(LI, V);
Chris Lattnera9d84e32005-05-01 04:24:53 +00007858 if (CE->getOperand(0)->isNullValue()) {
7859 // Insert a new store to null instruction before the load to indicate
7860 // that this code is not reachable. We do this instead of inserting
7861 // an unreachable instruction directly because we cannot modify the
7862 // CFG.
7863 new StoreInst(UndefValue::get(LI.getType()),
7864 Constant::getNullValue(Op->getType()), &LI);
7865 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
7866 }
7867
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007868 } else if (CE->isCast()) {
Chris Lattner81a7a232004-10-16 18:11:37 +00007869 if (Instruction *Res = InstCombineLoadCast(*this, LI))
7870 return Res;
7871 }
7872 }
Chris Lattnere228ee52004-04-08 20:39:49 +00007873
Chris Lattnera9d84e32005-05-01 04:24:53 +00007874 if (Op->hasOneUse()) {
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00007875 // Change select and PHI nodes to select values instead of addresses: this
7876 // helps alias analysis out a lot, allows many others simplifications, and
7877 // exposes redundancy in the code.
7878 //
7879 // Note that we cannot do the transformation unless we know that the
7880 // introduced loads cannot trap! Something like this is valid as long as
7881 // the condition is always false: load (select bool %C, int* null, int* %G),
7882 // but it would not be valid if we transformed it to load from null
7883 // unconditionally.
7884 //
7885 if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
7886 // load (select (Cond, &V1, &V2)) --> select(Cond, load &V1, load &V2).
Chris Lattnere6f13092004-09-19 19:18:10 +00007887 if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
7888 isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00007889 Value *V1 = InsertNewInstBefore(new LoadInst(SI->getOperand(1),
Chris Lattner42618552004-09-20 10:15:10 +00007890 SI->getOperand(1)->getName()+".val"), LI);
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00007891 Value *V2 = InsertNewInstBefore(new LoadInst(SI->getOperand(2),
Chris Lattner42618552004-09-20 10:15:10 +00007892 SI->getOperand(2)->getName()+".val"), LI);
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00007893 return new SelectInst(SI->getCondition(), V1, V2);
7894 }
7895
Chris Lattnerbdcf41a2004-09-23 15:46:00 +00007896 // load (select (cond, null, P)) -> load P
7897 if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
7898 if (C->isNullValue()) {
7899 LI.setOperand(0, SI->getOperand(2));
7900 return &LI;
7901 }
7902
7903 // load (select (cond, P, null)) -> load P
7904 if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
7905 if (C->isNullValue()) {
7906 LI.setOperand(0, SI->getOperand(1));
7907 return &LI;
7908 }
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00007909 }
7910 }
Chris Lattner0f1d8a32003-06-26 05:06:25 +00007911 return 0;
7912}
7913
Chris Lattner72684fe2005-01-31 05:51:45 +00007914/// InstCombineStoreToCast - Fold 'store V, (cast P)' -> store (cast V), P'
7915/// when possible.
7916static Instruction *InstCombineStoreToCast(InstCombiner &IC, StoreInst &SI) {
7917 User *CI = cast<User>(SI.getOperand(1));
7918 Value *CastOp = CI->getOperand(0);
7919
7920 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
7921 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
7922 const Type *SrcPTy = SrcTy->getElementType();
7923
7924 if (DestPTy->isInteger() || isa<PointerType>(DestPTy)) {
7925 // If the source is an array, the code below will not succeed. Check to
7926 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
7927 // constants.
7928 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
7929 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
7930 if (ASrcTy->getNumElements() != 0) {
7931 std::vector<Value*> Idxs(2, Constant::getNullValue(Type::IntTy));
7932 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs);
7933 SrcTy = cast<PointerType>(CastOp->getType());
7934 SrcPTy = SrcTy->getElementType();
7935 }
7936
7937 if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy)) &&
Misha Brukmanb1c93172005-04-21 23:48:37 +00007938 IC.getTargetData().getTypeSize(SrcPTy) ==
Chris Lattner72684fe2005-01-31 05:51:45 +00007939 IC.getTargetData().getTypeSize(DestPTy)) {
7940
7941 // Okay, we are casting from one integer or pointer type to another of
7942 // the same size. Instead of casting the pointer before the store, cast
7943 // the value to be stored.
7944 Value *NewCast;
Reid Spencerbb65ebf2006-12-12 23:36:14 +00007945 Instruction::CastOps opcode = Instruction::BitCast;
7946 Value *SIOp0 = SI.getOperand(0);
7947 if (SrcPTy->getTypeID() == Type::PointerTyID) {
7948 if (SIOp0->getType()->isIntegral())
7949 opcode = Instruction::IntToPtr;
7950 } else if (SrcPTy->isIntegral()) {
7951 if (SIOp0->getType()->getTypeID() == Type::PointerTyID)
7952 opcode = Instruction::PtrToInt;
7953 }
7954 if (Constant *C = dyn_cast<Constant>(SIOp0))
7955 NewCast = ConstantExpr::getCast(opcode, C, SrcPTy);
Chris Lattner72684fe2005-01-31 05:51:45 +00007956 else
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007957 NewCast = IC.InsertNewInstBefore(
Reid Spencerbb65ebf2006-12-12 23:36:14 +00007958 CastInst::create(opcode, SIOp0, SrcPTy, SIOp0->getName()+".c"), SI);
Chris Lattner72684fe2005-01-31 05:51:45 +00007959 return new StoreInst(NewCast, CastOp);
7960 }
7961 }
7962 }
7963 return 0;
7964}
7965
Chris Lattner31f486c2005-01-31 05:36:43 +00007966Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
7967 Value *Val = SI.getOperand(0);
7968 Value *Ptr = SI.getOperand(1);
7969
7970 if (isa<UndefValue>(Ptr)) { // store X, undef -> noop (even if volatile)
Chris Lattner5997cf92006-02-08 03:25:32 +00007971 EraseInstFromFunction(SI);
Chris Lattner31f486c2005-01-31 05:36:43 +00007972 ++NumCombined;
7973 return 0;
7974 }
7975
Chris Lattner5997cf92006-02-08 03:25:32 +00007976 // Do really simple DSE, to catch cases where there are several consequtive
7977 // stores to the same location, separated by a few arithmetic operations. This
7978 // situation often occurs with bitfield accesses.
7979 BasicBlock::iterator BBI = &SI;
7980 for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts;
7981 --ScanInsts) {
7982 --BBI;
7983
7984 if (StoreInst *PrevSI = dyn_cast<StoreInst>(BBI)) {
7985 // Prev store isn't volatile, and stores to the same location?
7986 if (!PrevSI->isVolatile() && PrevSI->getOperand(1) == SI.getOperand(1)) {
7987 ++NumDeadStore;
7988 ++BBI;
7989 EraseInstFromFunction(*PrevSI);
7990 continue;
7991 }
7992 break;
7993 }
7994
Chris Lattnerdab43b22006-05-26 19:19:20 +00007995 // If this is a load, we have to stop. However, if the loaded value is from
7996 // the pointer we're loading and is producing the pointer we're storing,
7997 // then *this* store is dead (X = load P; store X -> P).
7998 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
7999 if (LI == Val && LI->getOperand(0) == Ptr) {
8000 EraseInstFromFunction(SI);
8001 ++NumCombined;
8002 return 0;
8003 }
8004 // Otherwise, this is a load from some other location. Stores before it
8005 // may not be dead.
8006 break;
8007 }
8008
Chris Lattner5997cf92006-02-08 03:25:32 +00008009 // Don't skip over loads or things that can modify memory.
Chris Lattnerdab43b22006-05-26 19:19:20 +00008010 if (BBI->mayWriteToMemory())
Chris Lattner5997cf92006-02-08 03:25:32 +00008011 break;
8012 }
8013
8014
8015 if (SI.isVolatile()) return 0; // Don't hack volatile stores.
Chris Lattner31f486c2005-01-31 05:36:43 +00008016
8017 // store X, null -> turns into 'unreachable' in SimplifyCFG
8018 if (isa<ConstantPointerNull>(Ptr)) {
8019 if (!isa<UndefValue>(Val)) {
8020 SI.setOperand(0, UndefValue::get(Val->getType()));
8021 if (Instruction *U = dyn_cast<Instruction>(Val))
8022 WorkList.push_back(U); // Dropped a use.
8023 ++NumCombined;
8024 }
8025 return 0; // Do not modify these!
8026 }
8027
8028 // store undef, Ptr -> noop
8029 if (isa<UndefValue>(Val)) {
Chris Lattner5997cf92006-02-08 03:25:32 +00008030 EraseInstFromFunction(SI);
Chris Lattner31f486c2005-01-31 05:36:43 +00008031 ++NumCombined;
8032 return 0;
8033 }
8034
Chris Lattner72684fe2005-01-31 05:51:45 +00008035 // If the pointer destination is a cast, see if we can fold the cast into the
8036 // source instead.
Reid Spencerde46e482006-11-02 20:25:50 +00008037 if (isa<CastInst>(Ptr))
Chris Lattner72684fe2005-01-31 05:51:45 +00008038 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
8039 return Res;
8040 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
Reid Spencer6c38f0b2006-11-27 01:05:10 +00008041 if (CE->isCast())
Chris Lattner72684fe2005-01-31 05:51:45 +00008042 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
8043 return Res;
8044
Chris Lattner219175c2005-09-12 23:23:25 +00008045
8046 // If this store is the last instruction in the basic block, and if the block
8047 // ends with an unconditional branch, try to move it to the successor block.
Chris Lattner5997cf92006-02-08 03:25:32 +00008048 BBI = &SI; ++BBI;
Chris Lattner219175c2005-09-12 23:23:25 +00008049 if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
8050 if (BI->isUnconditional()) {
8051 // Check to see if the successor block has exactly two incoming edges. If
8052 // so, see if the other predecessor contains a store to the same location.
8053 // if so, insert a PHI node (if needed) and move the stores down.
8054 BasicBlock *Dest = BI->getSuccessor(0);
8055
8056 pred_iterator PI = pred_begin(Dest);
8057 BasicBlock *Other = 0;
8058 if (*PI != BI->getParent())
8059 Other = *PI;
8060 ++PI;
8061 if (PI != pred_end(Dest)) {
8062 if (*PI != BI->getParent())
8063 if (Other)
8064 Other = 0;
8065 else
8066 Other = *PI;
8067 if (++PI != pred_end(Dest))
8068 Other = 0;
8069 }
8070 if (Other) { // If only one other pred...
8071 BBI = Other->getTerminator();
8072 // Make sure this other block ends in an unconditional branch and that
8073 // there is an instruction before the branch.
8074 if (isa<BranchInst>(BBI) && cast<BranchInst>(BBI)->isUnconditional() &&
8075 BBI != Other->begin()) {
8076 --BBI;
8077 StoreInst *OtherStore = dyn_cast<StoreInst>(BBI);
8078
8079 // If this instruction is a store to the same location.
8080 if (OtherStore && OtherStore->getOperand(1) == SI.getOperand(1)) {
8081 // Okay, we know we can perform this transformation. Insert a PHI
8082 // node now if we need it.
8083 Value *MergedVal = OtherStore->getOperand(0);
8084 if (MergedVal != SI.getOperand(0)) {
8085 PHINode *PN = new PHINode(MergedVal->getType(), "storemerge");
8086 PN->reserveOperandSpace(2);
8087 PN->addIncoming(SI.getOperand(0), SI.getParent());
8088 PN->addIncoming(OtherStore->getOperand(0), Other);
8089 MergedVal = InsertNewInstBefore(PN, Dest->front());
8090 }
8091
8092 // Advance to a place where it is safe to insert the new store and
8093 // insert it.
8094 BBI = Dest->begin();
8095 while (isa<PHINode>(BBI)) ++BBI;
8096 InsertNewInstBefore(new StoreInst(MergedVal, SI.getOperand(1),
8097 OtherStore->isVolatile()), *BBI);
8098
8099 // Nuke the old stores.
Chris Lattner5997cf92006-02-08 03:25:32 +00008100 EraseInstFromFunction(SI);
8101 EraseInstFromFunction(*OtherStore);
Chris Lattner219175c2005-09-12 23:23:25 +00008102 ++NumCombined;
8103 return 0;
8104 }
8105 }
8106 }
8107 }
8108
Chris Lattner31f486c2005-01-31 05:36:43 +00008109 return 0;
8110}
8111
8112
Chris Lattner9eef8a72003-06-04 04:46:00 +00008113Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
8114 // Change br (not X), label True, label False to: br X, label False, True
Reid Spencer4fdd96c2005-06-18 17:37:34 +00008115 Value *X = 0;
Chris Lattnerd4252a72004-07-30 07:50:03 +00008116 BasicBlock *TrueDest;
8117 BasicBlock *FalseDest;
8118 if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
8119 !isa<Constant>(X)) {
8120 // Swap Destinations and condition...
8121 BI.setCondition(X);
8122 BI.setSuccessor(0, FalseDest);
8123 BI.setSuccessor(1, TrueDest);
8124 return &BI;
8125 }
8126
8127 // Cannonicalize setne -> seteq
8128 Instruction::BinaryOps Op; Value *Y;
8129 if (match(&BI, m_Br(m_SetCond(Op, m_Value(X), m_Value(Y)),
8130 TrueDest, FalseDest)))
8131 if ((Op == Instruction::SetNE || Op == Instruction::SetLE ||
8132 Op == Instruction::SetGE) && BI.getCondition()->hasOneUse()) {
8133 SetCondInst *I = cast<SetCondInst>(BI.getCondition());
8134 std::string Name = I->getName(); I->setName("");
8135 Instruction::BinaryOps NewOpcode = SetCondInst::getInverseCondition(Op);
8136 Value *NewSCC = BinaryOperator::create(NewOpcode, X, Y, Name, I);
Chris Lattnere967b342003-06-04 05:10:11 +00008137 // Swap Destinations and condition...
Chris Lattnerd4252a72004-07-30 07:50:03 +00008138 BI.setCondition(NewSCC);
Chris Lattnere967b342003-06-04 05:10:11 +00008139 BI.setSuccessor(0, FalseDest);
8140 BI.setSuccessor(1, TrueDest);
Chris Lattnerd4252a72004-07-30 07:50:03 +00008141 removeFromWorkList(I);
8142 I->getParent()->getInstList().erase(I);
8143 WorkList.push_back(cast<Instruction>(NewSCC));
Chris Lattnere967b342003-06-04 05:10:11 +00008144 return &BI;
8145 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00008146
Chris Lattner9eef8a72003-06-04 04:46:00 +00008147 return 0;
8148}
Chris Lattner1085bdf2002-11-04 16:18:53 +00008149
Chris Lattner4c9c20a2004-07-03 00:26:11 +00008150Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
8151 Value *Cond = SI.getCondition();
8152 if (Instruction *I = dyn_cast<Instruction>(Cond)) {
8153 if (I->getOpcode() == Instruction::Add)
8154 if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
8155 // change 'switch (X+4) case 1:' into 'switch (X) case -3'
8156 for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
Chris Lattner81a7a232004-10-16 18:11:37 +00008157 SI.setOperand(i,ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)),
Chris Lattner4c9c20a2004-07-03 00:26:11 +00008158 AddRHS));
8159 SI.setOperand(0, I->getOperand(0));
8160 WorkList.push_back(I);
8161 return &SI;
8162 }
8163 }
8164 return 0;
8165}
8166
Chris Lattner6bc98652006-03-05 00:22:33 +00008167/// CheapToScalarize - Return true if the value is cheaper to scalarize than it
8168/// is to leave as a vector operation.
8169static bool CheapToScalarize(Value *V, bool isConstant) {
8170 if (isa<ConstantAggregateZero>(V))
8171 return true;
8172 if (ConstantPacked *C = dyn_cast<ConstantPacked>(V)) {
8173 if (isConstant) return true;
8174 // If all elts are the same, we can extract.
8175 Constant *Op0 = C->getOperand(0);
8176 for (unsigned i = 1; i < C->getNumOperands(); ++i)
8177 if (C->getOperand(i) != Op0)
8178 return false;
8179 return true;
8180 }
8181 Instruction *I = dyn_cast<Instruction>(V);
8182 if (!I) return false;
8183
8184 // Insert element gets simplified to the inserted element or is deleted if
8185 // this is constant idx extract element and its a constant idx insertelt.
8186 if (I->getOpcode() == Instruction::InsertElement && isConstant &&
8187 isa<ConstantInt>(I->getOperand(2)))
8188 return true;
8189 if (I->getOpcode() == Instruction::Load && I->hasOneUse())
8190 return true;
8191 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I))
8192 if (BO->hasOneUse() &&
8193 (CheapToScalarize(BO->getOperand(0), isConstant) ||
8194 CheapToScalarize(BO->getOperand(1), isConstant)))
8195 return true;
8196
8197 return false;
8198}
8199
Chris Lattner12249be2006-05-25 23:48:38 +00008200/// getShuffleMask - Read and decode a shufflevector mask. It turns undef
8201/// elements into values that are larger than the #elts in the input.
8202static std::vector<unsigned> getShuffleMask(const ShuffleVectorInst *SVI) {
8203 unsigned NElts = SVI->getType()->getNumElements();
8204 if (isa<ConstantAggregateZero>(SVI->getOperand(2)))
8205 return std::vector<unsigned>(NElts, 0);
8206 if (isa<UndefValue>(SVI->getOperand(2)))
8207 return std::vector<unsigned>(NElts, 2*NElts);
8208
8209 std::vector<unsigned> Result;
8210 const ConstantPacked *CP = cast<ConstantPacked>(SVI->getOperand(2));
8211 for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
8212 if (isa<UndefValue>(CP->getOperand(i)))
8213 Result.push_back(NElts*2); // undef -> 8
8214 else
Reid Spencere0fc4df2006-10-20 07:07:24 +00008215 Result.push_back(cast<ConstantInt>(CP->getOperand(i))->getZExtValue());
Chris Lattner12249be2006-05-25 23:48:38 +00008216 return Result;
8217}
8218
Chris Lattner8d1d8d32006-03-31 23:01:56 +00008219/// FindScalarElement - Given a vector and an element number, see if the scalar
8220/// value is already around as a register, for example if it were inserted then
8221/// extracted from the vector.
8222static Value *FindScalarElement(Value *V, unsigned EltNo) {
8223 assert(isa<PackedType>(V->getType()) && "Not looking at a vector?");
8224 const PackedType *PTy = cast<PackedType>(V->getType());
Chris Lattner2d37f922006-04-10 23:06:36 +00008225 unsigned Width = PTy->getNumElements();
8226 if (EltNo >= Width) // Out of range access.
Chris Lattner8d1d8d32006-03-31 23:01:56 +00008227 return UndefValue::get(PTy->getElementType());
8228
8229 if (isa<UndefValue>(V))
8230 return UndefValue::get(PTy->getElementType());
8231 else if (isa<ConstantAggregateZero>(V))
8232 return Constant::getNullValue(PTy->getElementType());
8233 else if (ConstantPacked *CP = dyn_cast<ConstantPacked>(V))
8234 return CP->getOperand(EltNo);
8235 else if (InsertElementInst *III = dyn_cast<InsertElementInst>(V)) {
8236 // If this is an insert to a variable element, we don't know what it is.
Reid Spencere0fc4df2006-10-20 07:07:24 +00008237 if (!isa<ConstantInt>(III->getOperand(2)))
8238 return 0;
8239 unsigned IIElt = cast<ConstantInt>(III->getOperand(2))->getZExtValue();
Chris Lattner8d1d8d32006-03-31 23:01:56 +00008240
8241 // If this is an insert to the element we are looking for, return the
8242 // inserted value.
Reid Spencere0fc4df2006-10-20 07:07:24 +00008243 if (EltNo == IIElt)
8244 return III->getOperand(1);
Chris Lattner8d1d8d32006-03-31 23:01:56 +00008245
8246 // Otherwise, the insertelement doesn't modify the value, recurse on its
8247 // vector input.
8248 return FindScalarElement(III->getOperand(0), EltNo);
Chris Lattner2d37f922006-04-10 23:06:36 +00008249 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(V)) {
Chris Lattner12249be2006-05-25 23:48:38 +00008250 unsigned InEl = getShuffleMask(SVI)[EltNo];
8251 if (InEl < Width)
8252 return FindScalarElement(SVI->getOperand(0), InEl);
8253 else if (InEl < Width*2)
8254 return FindScalarElement(SVI->getOperand(1), InEl - Width);
8255 else
8256 return UndefValue::get(PTy->getElementType());
Chris Lattner8d1d8d32006-03-31 23:01:56 +00008257 }
8258
8259 // Otherwise, we don't know.
8260 return 0;
8261}
8262
Robert Bocchinoa8352962006-01-13 22:48:06 +00008263Instruction *InstCombiner::visitExtractElementInst(ExtractElementInst &EI) {
Chris Lattner8d1d8d32006-03-31 23:01:56 +00008264
Chris Lattner92346c32006-03-31 18:25:14 +00008265 // If packed val is undef, replace extract with scalar undef.
8266 if (isa<UndefValue>(EI.getOperand(0)))
8267 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
8268
8269 // If packed val is constant 0, replace extract with scalar 0.
8270 if (isa<ConstantAggregateZero>(EI.getOperand(0)))
8271 return ReplaceInstUsesWith(EI, Constant::getNullValue(EI.getType()));
8272
Robert Bocchinoa8352962006-01-13 22:48:06 +00008273 if (ConstantPacked *C = dyn_cast<ConstantPacked>(EI.getOperand(0))) {
8274 // If packed val is constant with uniform operands, replace EI
8275 // with that operand
Chris Lattner6bc98652006-03-05 00:22:33 +00008276 Constant *op0 = C->getOperand(0);
Robert Bocchinoa8352962006-01-13 22:48:06 +00008277 for (unsigned i = 1; i < C->getNumOperands(); ++i)
Chris Lattner6bc98652006-03-05 00:22:33 +00008278 if (C->getOperand(i) != op0) {
8279 op0 = 0;
8280 break;
8281 }
8282 if (op0)
8283 return ReplaceInstUsesWith(EI, op0);
Robert Bocchinoa8352962006-01-13 22:48:06 +00008284 }
Chris Lattner6bc98652006-03-05 00:22:33 +00008285
Chris Lattner8d1d8d32006-03-31 23:01:56 +00008286 // If extracting a specified index from the vector, see if we can recursively
8287 // find a previously computed scalar that was inserted into the vector.
Reid Spencere0fc4df2006-10-20 07:07:24 +00008288 if (ConstantInt *IdxC = dyn_cast<ConstantInt>(EI.getOperand(1))) {
Chris Lattner2deeaea2006-10-05 06:55:50 +00008289 // This instruction only demands the single element from the input vector.
8290 // If the input vector has a single use, simplify it based on this use
8291 // property.
Reid Spencere0fc4df2006-10-20 07:07:24 +00008292 uint64_t IndexVal = IdxC->getZExtValue();
Chris Lattner2deeaea2006-10-05 06:55:50 +00008293 if (EI.getOperand(0)->hasOneUse()) {
8294 uint64_t UndefElts;
8295 if (Value *V = SimplifyDemandedVectorElts(EI.getOperand(0),
Reid Spencere0fc4df2006-10-20 07:07:24 +00008296 1 << IndexVal,
Chris Lattner2deeaea2006-10-05 06:55:50 +00008297 UndefElts)) {
8298 EI.setOperand(0, V);
8299 return &EI;
8300 }
8301 }
8302
Reid Spencere0fc4df2006-10-20 07:07:24 +00008303 if (Value *Elt = FindScalarElement(EI.getOperand(0), IndexVal))
Chris Lattner8d1d8d32006-03-31 23:01:56 +00008304 return ReplaceInstUsesWith(EI, Elt);
Chris Lattner2d37f922006-04-10 23:06:36 +00008305 }
Chris Lattner8d1d8d32006-03-31 23:01:56 +00008306
Chris Lattner83f65782006-05-25 22:53:38 +00008307 if (Instruction *I = dyn_cast<Instruction>(EI.getOperand(0))) {
Robert Bocchinoa8352962006-01-13 22:48:06 +00008308 if (I->hasOneUse()) {
8309 // Push extractelement into predecessor operation if legal and
8310 // profitable to do so
8311 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
Chris Lattner6bc98652006-03-05 00:22:33 +00008312 bool isConstantElt = isa<ConstantInt>(EI.getOperand(1));
8313 if (CheapToScalarize(BO, isConstantElt)) {
8314 ExtractElementInst *newEI0 =
8315 new ExtractElementInst(BO->getOperand(0), EI.getOperand(1),
8316 EI.getName()+".lhs");
8317 ExtractElementInst *newEI1 =
8318 new ExtractElementInst(BO->getOperand(1), EI.getOperand(1),
8319 EI.getName()+".rhs");
8320 InsertNewInstBefore(newEI0, EI);
8321 InsertNewInstBefore(newEI1, EI);
8322 return BinaryOperator::create(BO->getOpcode(), newEI0, newEI1);
8323 }
Reid Spencerde46e482006-11-02 20:25:50 +00008324 } else if (isa<LoadInst>(I)) {
Reid Spencer13bc5d72006-12-12 09:18:51 +00008325 Value *Ptr = InsertCastBefore(Instruction::BitCast, I->getOperand(0),
Robert Bocchinoa8352962006-01-13 22:48:06 +00008326 PointerType::get(EI.getType()), EI);
8327 GetElementPtrInst *GEP =
Reid Spencera736fdf2006-11-29 01:11:01 +00008328 new GetElementPtrInst(Ptr, EI.getOperand(1), I->getName() + ".gep");
Robert Bocchinoa8352962006-01-13 22:48:06 +00008329 InsertNewInstBefore(GEP, EI);
8330 return new LoadInst(GEP);
Chris Lattner83f65782006-05-25 22:53:38 +00008331 }
8332 }
8333 if (InsertElementInst *IE = dyn_cast<InsertElementInst>(I)) {
8334 // Extracting the inserted element?
8335 if (IE->getOperand(2) == EI.getOperand(1))
8336 return ReplaceInstUsesWith(EI, IE->getOperand(1));
8337 // If the inserted and extracted elements are constants, they must not
8338 // be the same value, extract from the pre-inserted value instead.
8339 if (isa<Constant>(IE->getOperand(2)) &&
8340 isa<Constant>(EI.getOperand(1))) {
8341 AddUsesToWorkList(EI);
8342 EI.setOperand(0, IE->getOperand(0));
8343 return &EI;
8344 }
8345 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I)) {
8346 // If this is extracting an element from a shufflevector, figure out where
8347 // it came from and extract from the appropriate input element instead.
Reid Spencere0fc4df2006-10-20 07:07:24 +00008348 if (ConstantInt *Elt = dyn_cast<ConstantInt>(EI.getOperand(1))) {
8349 unsigned SrcIdx = getShuffleMask(SVI)[Elt->getZExtValue()];
Chris Lattner12249be2006-05-25 23:48:38 +00008350 Value *Src;
8351 if (SrcIdx < SVI->getType()->getNumElements())
8352 Src = SVI->getOperand(0);
8353 else if (SrcIdx < SVI->getType()->getNumElements()*2) {
8354 SrcIdx -= SVI->getType()->getNumElements();
8355 Src = SVI->getOperand(1);
8356 } else {
8357 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
Chris Lattner612fa8e2006-03-30 22:02:40 +00008358 }
Chris Lattner2deeaea2006-10-05 06:55:50 +00008359 return new ExtractElementInst(Src, SrcIdx);
Robert Bocchinoa8352962006-01-13 22:48:06 +00008360 }
8361 }
Chris Lattner83f65782006-05-25 22:53:38 +00008362 }
Robert Bocchinoa8352962006-01-13 22:48:06 +00008363 return 0;
8364}
8365
Chris Lattner90951862006-04-16 00:51:47 +00008366/// CollectSingleShuffleElements - If V is a shuffle of values that ONLY returns
8367/// elements from either LHS or RHS, return the shuffle mask and true.
8368/// Otherwise, return false.
8369static bool CollectSingleShuffleElements(Value *V, Value *LHS, Value *RHS,
8370 std::vector<Constant*> &Mask) {
8371 assert(V->getType() == LHS->getType() && V->getType() == RHS->getType() &&
8372 "Invalid CollectSingleShuffleElements");
8373 unsigned NumElts = cast<PackedType>(V->getType())->getNumElements();
8374
8375 if (isa<UndefValue>(V)) {
8376 Mask.assign(NumElts, UndefValue::get(Type::UIntTy));
8377 return true;
8378 } else if (V == LHS) {
8379 for (unsigned i = 0; i != NumElts; ++i)
Reid Spencere0fc4df2006-10-20 07:07:24 +00008380 Mask.push_back(ConstantInt::get(Type::UIntTy, i));
Chris Lattner90951862006-04-16 00:51:47 +00008381 return true;
8382 } else if (V == RHS) {
8383 for (unsigned i = 0; i != NumElts; ++i)
Reid Spencere0fc4df2006-10-20 07:07:24 +00008384 Mask.push_back(ConstantInt::get(Type::UIntTy, i+NumElts));
Chris Lattner90951862006-04-16 00:51:47 +00008385 return true;
8386 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
8387 // If this is an insert of an extract from some other vector, include it.
8388 Value *VecOp = IEI->getOperand(0);
8389 Value *ScalarOp = IEI->getOperand(1);
8390 Value *IdxOp = IEI->getOperand(2);
8391
Chris Lattnerb6cb64b2006-04-27 21:14:21 +00008392 if (!isa<ConstantInt>(IdxOp))
8393 return false;
Reid Spencere0fc4df2006-10-20 07:07:24 +00008394 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattnerb6cb64b2006-04-27 21:14:21 +00008395
8396 if (isa<UndefValue>(ScalarOp)) { // inserting undef into vector.
8397 // Okay, we can handle this if the vector we are insertinting into is
8398 // transitively ok.
8399 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
8400 // If so, update the mask to reflect the inserted undef.
8401 Mask[InsertedIdx] = UndefValue::get(Type::UIntTy);
8402 return true;
8403 }
8404 } else if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)){
8405 if (isa<ConstantInt>(EI->getOperand(1)) &&
Chris Lattner90951862006-04-16 00:51:47 +00008406 EI->getOperand(0)->getType() == V->getType()) {
8407 unsigned ExtractedIdx =
Reid Spencere0fc4df2006-10-20 07:07:24 +00008408 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
Chris Lattner90951862006-04-16 00:51:47 +00008409
8410 // This must be extracting from either LHS or RHS.
8411 if (EI->getOperand(0) == LHS || EI->getOperand(0) == RHS) {
8412 // Okay, we can handle this if the vector we are insertinting into is
8413 // transitively ok.
8414 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
8415 // If so, update the mask to reflect the inserted value.
8416 if (EI->getOperand(0) == LHS) {
8417 Mask[InsertedIdx & (NumElts-1)] =
Reid Spencere0fc4df2006-10-20 07:07:24 +00008418 ConstantInt::get(Type::UIntTy, ExtractedIdx);
Chris Lattner90951862006-04-16 00:51:47 +00008419 } else {
8420 assert(EI->getOperand(0) == RHS);
8421 Mask[InsertedIdx & (NumElts-1)] =
Reid Spencere0fc4df2006-10-20 07:07:24 +00008422 ConstantInt::get(Type::UIntTy, ExtractedIdx+NumElts);
Chris Lattner90951862006-04-16 00:51:47 +00008423
8424 }
8425 return true;
8426 }
8427 }
8428 }
8429 }
8430 }
8431 // TODO: Handle shufflevector here!
8432
8433 return false;
8434}
8435
8436/// CollectShuffleElements - We are building a shuffle of V, using RHS as the
8437/// RHS of the shuffle instruction, if it is not null. Return a shuffle mask
8438/// that computes V and the LHS value of the shuffle.
Chris Lattner39fac442006-04-15 01:39:45 +00008439static Value *CollectShuffleElements(Value *V, std::vector<Constant*> &Mask,
Chris Lattner90951862006-04-16 00:51:47 +00008440 Value *&RHS) {
8441 assert(isa<PackedType>(V->getType()) &&
8442 (RHS == 0 || V->getType() == RHS->getType()) &&
Chris Lattner39fac442006-04-15 01:39:45 +00008443 "Invalid shuffle!");
8444 unsigned NumElts = cast<PackedType>(V->getType())->getNumElements();
8445
8446 if (isa<UndefValue>(V)) {
8447 Mask.assign(NumElts, UndefValue::get(Type::UIntTy));
8448 return V;
8449 } else if (isa<ConstantAggregateZero>(V)) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00008450 Mask.assign(NumElts, ConstantInt::get(Type::UIntTy, 0));
Chris Lattner39fac442006-04-15 01:39:45 +00008451 return V;
8452 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
8453 // If this is an insert of an extract from some other vector, include it.
8454 Value *VecOp = IEI->getOperand(0);
8455 Value *ScalarOp = IEI->getOperand(1);
8456 Value *IdxOp = IEI->getOperand(2);
8457
8458 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
8459 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
8460 EI->getOperand(0)->getType() == V->getType()) {
8461 unsigned ExtractedIdx =
Reid Spencere0fc4df2006-10-20 07:07:24 +00008462 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
8463 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattner39fac442006-04-15 01:39:45 +00008464
8465 // Either the extracted from or inserted into vector must be RHSVec,
8466 // otherwise we'd end up with a shuffle of three inputs.
Chris Lattner90951862006-04-16 00:51:47 +00008467 if (EI->getOperand(0) == RHS || RHS == 0) {
8468 RHS = EI->getOperand(0);
8469 Value *V = CollectShuffleElements(VecOp, Mask, RHS);
Chris Lattner39fac442006-04-15 01:39:45 +00008470 Mask[InsertedIdx & (NumElts-1)] =
Reid Spencere0fc4df2006-10-20 07:07:24 +00008471 ConstantInt::get(Type::UIntTy, NumElts+ExtractedIdx);
Chris Lattner39fac442006-04-15 01:39:45 +00008472 return V;
8473 }
8474
Chris Lattner90951862006-04-16 00:51:47 +00008475 if (VecOp == RHS) {
8476 Value *V = CollectShuffleElements(EI->getOperand(0), Mask, RHS);
Chris Lattner39fac442006-04-15 01:39:45 +00008477 // Everything but the extracted element is replaced with the RHS.
8478 for (unsigned i = 0; i != NumElts; ++i) {
8479 if (i != InsertedIdx)
Reid Spencere0fc4df2006-10-20 07:07:24 +00008480 Mask[i] = ConstantInt::get(Type::UIntTy, NumElts+i);
Chris Lattner39fac442006-04-15 01:39:45 +00008481 }
8482 return V;
8483 }
Chris Lattner90951862006-04-16 00:51:47 +00008484
8485 // If this insertelement is a chain that comes from exactly these two
8486 // vectors, return the vector and the effective shuffle.
8487 if (CollectSingleShuffleElements(IEI, EI->getOperand(0), RHS, Mask))
8488 return EI->getOperand(0);
8489
Chris Lattner39fac442006-04-15 01:39:45 +00008490 }
8491 }
8492 }
Chris Lattner90951862006-04-16 00:51:47 +00008493 // TODO: Handle shufflevector here!
Chris Lattner39fac442006-04-15 01:39:45 +00008494
8495 // Otherwise, can't do anything fancy. Return an identity vector.
8496 for (unsigned i = 0; i != NumElts; ++i)
Reid Spencere0fc4df2006-10-20 07:07:24 +00008497 Mask.push_back(ConstantInt::get(Type::UIntTy, i));
Chris Lattner39fac442006-04-15 01:39:45 +00008498 return V;
8499}
8500
8501Instruction *InstCombiner::visitInsertElementInst(InsertElementInst &IE) {
8502 Value *VecOp = IE.getOperand(0);
8503 Value *ScalarOp = IE.getOperand(1);
8504 Value *IdxOp = IE.getOperand(2);
8505
8506 // If the inserted element was extracted from some other vector, and if the
8507 // indexes are constant, try to turn this into a shufflevector operation.
8508 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
8509 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
8510 EI->getOperand(0)->getType() == IE.getType()) {
8511 unsigned NumVectorElts = IE.getType()->getNumElements();
Reid Spencere0fc4df2006-10-20 07:07:24 +00008512 unsigned ExtractedIdx=cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
8513 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattner39fac442006-04-15 01:39:45 +00008514
8515 if (ExtractedIdx >= NumVectorElts) // Out of range extract.
8516 return ReplaceInstUsesWith(IE, VecOp);
8517
8518 if (InsertedIdx >= NumVectorElts) // Out of range insert.
8519 return ReplaceInstUsesWith(IE, UndefValue::get(IE.getType()));
8520
8521 // If we are extracting a value from a vector, then inserting it right
8522 // back into the same place, just use the input vector.
8523 if (EI->getOperand(0) == VecOp && ExtractedIdx == InsertedIdx)
8524 return ReplaceInstUsesWith(IE, VecOp);
8525
8526 // We could theoretically do this for ANY input. However, doing so could
8527 // turn chains of insertelement instructions into a chain of shufflevector
8528 // instructions, and right now we do not merge shufflevectors. As such,
8529 // only do this in a situation where it is clear that there is benefit.
8530 if (isa<UndefValue>(VecOp) || isa<ConstantAggregateZero>(VecOp)) {
8531 // Turn this into shuffle(EIOp0, VecOp, Mask). The result has all of
8532 // the values of VecOp, except then one read from EIOp0.
8533 // Build a new shuffle mask.
8534 std::vector<Constant*> Mask;
8535 if (isa<UndefValue>(VecOp))
8536 Mask.assign(NumVectorElts, UndefValue::get(Type::UIntTy));
8537 else {
8538 assert(isa<ConstantAggregateZero>(VecOp) && "Unknown thing");
Reid Spencere0fc4df2006-10-20 07:07:24 +00008539 Mask.assign(NumVectorElts, ConstantInt::get(Type::UIntTy,
Chris Lattner39fac442006-04-15 01:39:45 +00008540 NumVectorElts));
8541 }
Reid Spencere0fc4df2006-10-20 07:07:24 +00008542 Mask[InsertedIdx] = ConstantInt::get(Type::UIntTy, ExtractedIdx);
Chris Lattner39fac442006-04-15 01:39:45 +00008543 return new ShuffleVectorInst(EI->getOperand(0), VecOp,
8544 ConstantPacked::get(Mask));
8545 }
8546
8547 // If this insertelement isn't used by some other insertelement, turn it
8548 // (and any insertelements it points to), into one big shuffle.
8549 if (!IE.hasOneUse() || !isa<InsertElementInst>(IE.use_back())) {
8550 std::vector<Constant*> Mask;
Chris Lattner90951862006-04-16 00:51:47 +00008551 Value *RHS = 0;
8552 Value *LHS = CollectShuffleElements(&IE, Mask, RHS);
8553 if (RHS == 0) RHS = UndefValue::get(LHS->getType());
8554 // We now have a shuffle of LHS, RHS, Mask.
8555 return new ShuffleVectorInst(LHS, RHS, ConstantPacked::get(Mask));
Chris Lattner39fac442006-04-15 01:39:45 +00008556 }
8557 }
8558 }
8559
8560 return 0;
8561}
8562
8563
Chris Lattnerfbb77a42006-04-10 22:45:52 +00008564Instruction *InstCombiner::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
8565 Value *LHS = SVI.getOperand(0);
8566 Value *RHS = SVI.getOperand(1);
Chris Lattner12249be2006-05-25 23:48:38 +00008567 std::vector<unsigned> Mask = getShuffleMask(&SVI);
Chris Lattnerfbb77a42006-04-10 22:45:52 +00008568
8569 bool MadeChange = false;
8570
Chris Lattner2deeaea2006-10-05 06:55:50 +00008571 // Undefined shuffle mask -> undefined value.
Chris Lattner12249be2006-05-25 23:48:38 +00008572 if (isa<UndefValue>(SVI.getOperand(2)))
Chris Lattnerfbb77a42006-04-10 22:45:52 +00008573 return ReplaceInstUsesWith(SVI, UndefValue::get(SVI.getType()));
8574
Chris Lattner39fac442006-04-15 01:39:45 +00008575 // TODO: If we have shuffle(x, undef, mask) and any elements of mask refer to
8576 // the undef, change them to undefs.
8577
Chris Lattner12249be2006-05-25 23:48:38 +00008578 // Canonicalize shuffle(x ,x,mask) -> shuffle(x, undef,mask')
8579 // Canonicalize shuffle(undef,x,mask) -> shuffle(x, undef,mask').
8580 if (LHS == RHS || isa<UndefValue>(LHS)) {
8581 if (isa<UndefValue>(LHS) && LHS == RHS) {
Chris Lattnerfbb77a42006-04-10 22:45:52 +00008582 // shuffle(undef,undef,mask) -> undef.
8583 return ReplaceInstUsesWith(SVI, LHS);
8584 }
8585
Chris Lattner12249be2006-05-25 23:48:38 +00008586 // Remap any references to RHS to use LHS.
8587 std::vector<Constant*> Elts;
8588 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
Chris Lattner0e477162006-05-26 00:29:06 +00008589 if (Mask[i] >= 2*e)
Chris Lattner12249be2006-05-25 23:48:38 +00008590 Elts.push_back(UndefValue::get(Type::UIntTy));
Chris Lattner0e477162006-05-26 00:29:06 +00008591 else {
8592 if ((Mask[i] >= e && isa<UndefValue>(RHS)) ||
8593 (Mask[i] < e && isa<UndefValue>(LHS)))
8594 Mask[i] = 2*e; // Turn into undef.
8595 else
8596 Mask[i] &= (e-1); // Force to LHS.
Reid Spencere0fc4df2006-10-20 07:07:24 +00008597 Elts.push_back(ConstantInt::get(Type::UIntTy, Mask[i]));
Chris Lattner0e477162006-05-26 00:29:06 +00008598 }
Chris Lattnerfbb77a42006-04-10 22:45:52 +00008599 }
Chris Lattner12249be2006-05-25 23:48:38 +00008600 SVI.setOperand(0, SVI.getOperand(1));
Chris Lattnerfbb77a42006-04-10 22:45:52 +00008601 SVI.setOperand(1, UndefValue::get(RHS->getType()));
Chris Lattner12249be2006-05-25 23:48:38 +00008602 SVI.setOperand(2, ConstantPacked::get(Elts));
Chris Lattner0e477162006-05-26 00:29:06 +00008603 LHS = SVI.getOperand(0);
8604 RHS = SVI.getOperand(1);
Chris Lattnerfbb77a42006-04-10 22:45:52 +00008605 MadeChange = true;
8606 }
8607
Chris Lattner0e477162006-05-26 00:29:06 +00008608 // Analyze the shuffle, are the LHS or RHS and identity shuffles?
Chris Lattner12249be2006-05-25 23:48:38 +00008609 bool isLHSID = true, isRHSID = true;
Chris Lattner34cebe72006-04-16 00:03:56 +00008610
Chris Lattner12249be2006-05-25 23:48:38 +00008611 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
8612 if (Mask[i] >= e*2) continue; // Ignore undef values.
8613 // Is this an identity shuffle of the LHS value?
8614 isLHSID &= (Mask[i] == i);
8615
8616 // Is this an identity shuffle of the RHS value?
8617 isRHSID &= (Mask[i]-e == i);
Chris Lattner34cebe72006-04-16 00:03:56 +00008618 }
Chris Lattnerfbb77a42006-04-10 22:45:52 +00008619
Chris Lattner12249be2006-05-25 23:48:38 +00008620 // Eliminate identity shuffles.
8621 if (isLHSID) return ReplaceInstUsesWith(SVI, LHS);
8622 if (isRHSID) return ReplaceInstUsesWith(SVI, RHS);
Chris Lattnerfbb77a42006-04-10 22:45:52 +00008623
Chris Lattner0e477162006-05-26 00:29:06 +00008624 // If the LHS is a shufflevector itself, see if we can combine it with this
8625 // one without producing an unusual shuffle. Here we are really conservative:
8626 // we are absolutely afraid of producing a shuffle mask not in the input
8627 // program, because the code gen may not be smart enough to turn a merged
8628 // shuffle into two specific shuffles: it may produce worse code. As such,
8629 // we only merge two shuffles if the result is one of the two input shuffle
8630 // masks. In this case, merging the shuffles just removes one instruction,
8631 // which we know is safe. This is good for things like turning:
8632 // (splat(splat)) -> splat.
8633 if (ShuffleVectorInst *LHSSVI = dyn_cast<ShuffleVectorInst>(LHS)) {
8634 if (isa<UndefValue>(RHS)) {
8635 std::vector<unsigned> LHSMask = getShuffleMask(LHSSVI);
8636
8637 std::vector<unsigned> NewMask;
8638 for (unsigned i = 0, e = Mask.size(); i != e; ++i)
8639 if (Mask[i] >= 2*e)
8640 NewMask.push_back(2*e);
8641 else
8642 NewMask.push_back(LHSMask[Mask[i]]);
8643
8644 // If the result mask is equal to the src shuffle or this shuffle mask, do
8645 // the replacement.
8646 if (NewMask == LHSMask || NewMask == Mask) {
8647 std::vector<Constant*> Elts;
8648 for (unsigned i = 0, e = NewMask.size(); i != e; ++i) {
8649 if (NewMask[i] >= e*2) {
8650 Elts.push_back(UndefValue::get(Type::UIntTy));
8651 } else {
Reid Spencere0fc4df2006-10-20 07:07:24 +00008652 Elts.push_back(ConstantInt::get(Type::UIntTy, NewMask[i]));
Chris Lattner0e477162006-05-26 00:29:06 +00008653 }
8654 }
8655 return new ShuffleVectorInst(LHSSVI->getOperand(0),
8656 LHSSVI->getOperand(1),
8657 ConstantPacked::get(Elts));
8658 }
8659 }
8660 }
8661
Chris Lattnerfbb77a42006-04-10 22:45:52 +00008662 return MadeChange ? &SVI : 0;
8663}
8664
8665
Robert Bocchinoa8352962006-01-13 22:48:06 +00008666
Chris Lattner99f48c62002-09-02 04:59:56 +00008667void InstCombiner::removeFromWorkList(Instruction *I) {
8668 WorkList.erase(std::remove(WorkList.begin(), WorkList.end(), I),
8669 WorkList.end());
8670}
8671
Chris Lattner39c98bb2004-12-08 23:43:58 +00008672
8673/// TryToSinkInstruction - Try to move the specified instruction from its
8674/// current block into the beginning of DestBlock, which can only happen if it's
8675/// safe to move the instruction past all of the instructions between it and the
8676/// end of its block.
8677static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
8678 assert(I->hasOneUse() && "Invariants didn't hold!");
8679
Chris Lattnerc4f67e62005-10-27 17:13:11 +00008680 // Cannot move control-flow-involving, volatile loads, vaarg, etc.
8681 if (isa<PHINode>(I) || I->mayWriteToMemory()) return false;
Misha Brukmanb1c93172005-04-21 23:48:37 +00008682
Chris Lattner39c98bb2004-12-08 23:43:58 +00008683 // Do not sink alloca instructions out of the entry block.
8684 if (isa<AllocaInst>(I) && I->getParent() == &DestBlock->getParent()->front())
8685 return false;
8686
Chris Lattnerf17a2fb2004-12-09 07:14:34 +00008687 // We can only sink load instructions if there is nothing between the load and
8688 // the end of block that could change the value.
8689 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Chris Lattnerf17a2fb2004-12-09 07:14:34 +00008690 for (BasicBlock::iterator Scan = LI, E = LI->getParent()->end();
8691 Scan != E; ++Scan)
8692 if (Scan->mayWriteToMemory())
8693 return false;
Chris Lattnerf17a2fb2004-12-09 07:14:34 +00008694 }
Chris Lattner39c98bb2004-12-08 23:43:58 +00008695
8696 BasicBlock::iterator InsertPos = DestBlock->begin();
8697 while (isa<PHINode>(InsertPos)) ++InsertPos;
8698
Chris Lattner9f269e42005-08-08 19:11:57 +00008699 I->moveBefore(InsertPos);
Chris Lattner39c98bb2004-12-08 23:43:58 +00008700 ++NumSunkInst;
8701 return true;
8702}
8703
Chris Lattner1443bc52006-05-11 17:11:52 +00008704/// OptimizeConstantExpr - Given a constant expression and target data layout
Reid Spencer13bc5d72006-12-12 09:18:51 +00008705/// information, symbolically evaluate the constant expr to something simpler
Chris Lattner1443bc52006-05-11 17:11:52 +00008706/// if possible.
8707static Constant *OptimizeConstantExpr(ConstantExpr *CE, const TargetData *TD) {
8708 if (!TD) return CE;
8709
8710 Constant *Ptr = CE->getOperand(0);
8711 if (CE->getOpcode() == Instruction::GetElementPtr && Ptr->isNullValue() &&
8712 cast<PointerType>(Ptr->getType())->getElementType()->isSized()) {
8713 // If this is a constant expr gep that is effectively computing an
8714 // "offsetof", fold it into 'cast int Size to T*' instead of 'gep 0, 0, 12'
8715 bool isFoldableGEP = true;
8716 for (unsigned i = 1, e = CE->getNumOperands(); i != e; ++i)
8717 if (!isa<ConstantInt>(CE->getOperand(i)))
8718 isFoldableGEP = false;
8719 if (isFoldableGEP) {
8720 std::vector<Value*> Ops(CE->op_begin()+1, CE->op_end());
8721 uint64_t Offset = TD->getIndexedOffset(Ptr->getType(), Ops);
Reid Spencere0fc4df2006-10-20 07:07:24 +00008722 Constant *C = ConstantInt::get(Type::ULongTy, Offset);
Reid Spencer13bc5d72006-12-12 09:18:51 +00008723 C = ConstantExpr::getIntegerCast(C, TD->getIntPtrType(), true /*SExt*/);
8724 return ConstantExpr::getIntToPtr(C, CE->getType());
Chris Lattner1443bc52006-05-11 17:11:52 +00008725 }
8726 }
8727
8728 return CE;
8729}
8730
Chris Lattnera36ee4e2006-05-10 19:00:36 +00008731
8732/// AddReachableCodeToWorklist - Walk the function in depth-first order, adding
8733/// all reachable code to the worklist.
8734///
8735/// This has a couple of tricks to make the code faster and more powerful. In
8736/// particular, we constant fold and DCE instructions as we go, to avoid adding
8737/// them to the worklist (this significantly speeds up instcombine on code where
8738/// many instructions are dead or constant). Additionally, if we find a branch
8739/// whose condition is a known constant, we only visit the reachable successors.
8740///
8741static void AddReachableCodeToWorklist(BasicBlock *BB,
8742 std::set<BasicBlock*> &Visited,
Chris Lattner1443bc52006-05-11 17:11:52 +00008743 std::vector<Instruction*> &WorkList,
8744 const TargetData *TD) {
Chris Lattnera36ee4e2006-05-10 19:00:36 +00008745 // We have now visited this block! If we've already been here, bail out.
8746 if (!Visited.insert(BB).second) return;
8747
8748 for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
8749 Instruction *Inst = BBI++;
8750
8751 // DCE instruction if trivially dead.
8752 if (isInstructionTriviallyDead(Inst)) {
8753 ++NumDeadInst;
Bill Wendling5dbf43c2006-11-26 09:46:52 +00008754 DOUT << "IC: DCE: " << *Inst;
Chris Lattnera36ee4e2006-05-10 19:00:36 +00008755 Inst->eraseFromParent();
8756 continue;
8757 }
8758
8759 // ConstantProp instruction if trivially constant.
8760 if (Constant *C = ConstantFoldInstruction(Inst)) {
Chris Lattner1443bc52006-05-11 17:11:52 +00008761 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C))
8762 C = OptimizeConstantExpr(CE, TD);
Bill Wendling5dbf43c2006-11-26 09:46:52 +00008763 DOUT << "IC: ConstFold to: " << *C << " from: " << *Inst;
Chris Lattnera36ee4e2006-05-10 19:00:36 +00008764 Inst->replaceAllUsesWith(C);
8765 ++NumConstProp;
8766 Inst->eraseFromParent();
8767 continue;
8768 }
8769
8770 WorkList.push_back(Inst);
8771 }
8772
8773 // Recursively visit successors. If this is a branch or switch on a constant,
8774 // only visit the reachable successor.
8775 TerminatorInst *TI = BB->getTerminator();
8776 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
8777 if (BI->isConditional() && isa<ConstantBool>(BI->getCondition())) {
8778 bool CondVal = cast<ConstantBool>(BI->getCondition())->getValue();
Chris Lattner1443bc52006-05-11 17:11:52 +00008779 AddReachableCodeToWorklist(BI->getSuccessor(!CondVal), Visited, WorkList,
8780 TD);
Chris Lattnera36ee4e2006-05-10 19:00:36 +00008781 return;
8782 }
8783 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
8784 if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
8785 // See if this is an explicit destination.
8786 for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
8787 if (SI->getCaseValue(i) == Cond) {
Chris Lattner1443bc52006-05-11 17:11:52 +00008788 AddReachableCodeToWorklist(SI->getSuccessor(i), Visited, WorkList,TD);
Chris Lattnera36ee4e2006-05-10 19:00:36 +00008789 return;
8790 }
8791
8792 // Otherwise it is the default destination.
Chris Lattner1443bc52006-05-11 17:11:52 +00008793 AddReachableCodeToWorklist(SI->getSuccessor(0), Visited, WorkList, TD);
Chris Lattnera36ee4e2006-05-10 19:00:36 +00008794 return;
8795 }
8796 }
8797
8798 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
Chris Lattner1443bc52006-05-11 17:11:52 +00008799 AddReachableCodeToWorklist(TI->getSuccessor(i), Visited, WorkList, TD);
Chris Lattnera36ee4e2006-05-10 19:00:36 +00008800}
8801
Chris Lattner113f4f42002-06-25 16:13:24 +00008802bool InstCombiner::runOnFunction(Function &F) {
Chris Lattner260ab202002-04-18 17:39:14 +00008803 bool Changed = false;
Chris Lattnerf4ad1652003-11-02 05:57:39 +00008804 TD = &getAnalysis<TargetData>();
Chris Lattnerca081252001-12-14 16:52:21 +00008805
Chris Lattner4ed40f72005-07-07 20:40:38 +00008806 {
Chris Lattnera36ee4e2006-05-10 19:00:36 +00008807 // Do a depth-first traversal of the function, populate the worklist with
8808 // the reachable instructions. Ignore blocks that are not reachable. Keep
8809 // track of which blocks we visit.
Chris Lattner4ed40f72005-07-07 20:40:38 +00008810 std::set<BasicBlock*> Visited;
Chris Lattner1443bc52006-05-11 17:11:52 +00008811 AddReachableCodeToWorklist(F.begin(), Visited, WorkList, TD);
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00008812
Chris Lattner4ed40f72005-07-07 20:40:38 +00008813 // Do a quick scan over the function. If we find any blocks that are
8814 // unreachable, remove any instructions inside of them. This prevents
8815 // the instcombine code from having to deal with some bad special cases.
8816 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
8817 if (!Visited.count(BB)) {
8818 Instruction *Term = BB->getTerminator();
8819 while (Term != BB->begin()) { // Remove instrs bottom-up
8820 BasicBlock::iterator I = Term; --I;
Chris Lattner2d3a7a62004-04-27 15:13:33 +00008821
Bill Wendling5dbf43c2006-11-26 09:46:52 +00008822 DOUT << "IC: DCE: " << *I;
Chris Lattner4ed40f72005-07-07 20:40:38 +00008823 ++NumDeadInst;
8824
8825 if (!I->use_empty())
8826 I->replaceAllUsesWith(UndefValue::get(I->getType()));
8827 I->eraseFromParent();
8828 }
8829 }
8830 }
Chris Lattnerca081252001-12-14 16:52:21 +00008831
8832 while (!WorkList.empty()) {
8833 Instruction *I = WorkList.back(); // Get an instruction from the worklist
8834 WorkList.pop_back();
8835
Chris Lattner1443bc52006-05-11 17:11:52 +00008836 // Check to see if we can DCE the instruction.
Chris Lattner99f48c62002-09-02 04:59:56 +00008837 if (isInstructionTriviallyDead(I)) {
Chris Lattner1443bc52006-05-11 17:11:52 +00008838 // Add operands to the worklist.
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00008839 if (I->getNumOperands() < 4)
Chris Lattner51ea1272004-02-28 05:22:00 +00008840 AddUsesToWorkList(*I);
Chris Lattner99f48c62002-09-02 04:59:56 +00008841 ++NumDeadInst;
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00008842
Bill Wendling5dbf43c2006-11-26 09:46:52 +00008843 DOUT << "IC: DCE: " << *I;
Chris Lattnercd517ff2005-01-28 19:32:01 +00008844
8845 I->eraseFromParent();
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00008846 removeFromWorkList(I);
8847 continue;
8848 }
Chris Lattner99f48c62002-09-02 04:59:56 +00008849
Chris Lattner1443bc52006-05-11 17:11:52 +00008850 // Instruction isn't dead, see if we can constant propagate it.
Chris Lattner99f48c62002-09-02 04:59:56 +00008851 if (Constant *C = ConstantFoldInstruction(I)) {
Chris Lattner1443bc52006-05-11 17:11:52 +00008852 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C))
8853 C = OptimizeConstantExpr(CE, TD);
Bill Wendling5dbf43c2006-11-26 09:46:52 +00008854 DOUT << "IC: ConstFold to: " << *C << " from: " << *I;
Chris Lattnercd517ff2005-01-28 19:32:01 +00008855
Chris Lattner1443bc52006-05-11 17:11:52 +00008856 // Add operands to the worklist.
Chris Lattner51ea1272004-02-28 05:22:00 +00008857 AddUsesToWorkList(*I);
Chris Lattnerc6509f42002-12-05 22:41:53 +00008858 ReplaceInstUsesWith(*I, C);
8859
Chris Lattner99f48c62002-09-02 04:59:56 +00008860 ++NumConstProp;
Chris Lattnera36ee4e2006-05-10 19:00:36 +00008861 I->eraseFromParent();
Chris Lattner800aaaf2003-10-07 15:17:02 +00008862 removeFromWorkList(I);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00008863 continue;
Chris Lattner99f48c62002-09-02 04:59:56 +00008864 }
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00008865
Chris Lattner39c98bb2004-12-08 23:43:58 +00008866 // See if we can trivially sink this instruction to a successor basic block.
8867 if (I->hasOneUse()) {
8868 BasicBlock *BB = I->getParent();
8869 BasicBlock *UserParent = cast<Instruction>(I->use_back())->getParent();
8870 if (UserParent != BB) {
8871 bool UserIsSuccessor = false;
8872 // See if the user is one of our successors.
8873 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
8874 if (*SI == UserParent) {
8875 UserIsSuccessor = true;
8876 break;
8877 }
8878
8879 // If the user is one of our immediate successors, and if that successor
8880 // only has us as a predecessors (we'd have to split the critical edge
8881 // otherwise), we can keep going.
8882 if (UserIsSuccessor && !isa<PHINode>(I->use_back()) &&
8883 next(pred_begin(UserParent)) == pred_end(UserParent))
8884 // Okay, the CFG is simple enough, try to sink this instruction.
8885 Changed |= TryToSinkInstruction(I, UserParent);
8886 }
8887 }
8888
Chris Lattnerca081252001-12-14 16:52:21 +00008889 // Now that we have an instruction, try combining it to simplify it...
Chris Lattnerae7a0d32002-08-02 19:29:35 +00008890 if (Instruction *Result = visit(*I)) {
Chris Lattner0b18c1d2002-05-10 15:38:35 +00008891 ++NumCombined;
Chris Lattner260ab202002-04-18 17:39:14 +00008892 // Should we replace the old instruction with a new one?
Chris Lattner053c0932002-05-14 15:24:07 +00008893 if (Result != I) {
Bill Wendling5dbf43c2006-11-26 09:46:52 +00008894 DOUT << "IC: Old = " << *I
8895 << " New = " << *Result;
Chris Lattner7d2a5392004-03-13 23:54:27 +00008896
Chris Lattner396dbfe2004-06-09 05:08:07 +00008897 // Everything uses the new instruction now.
8898 I->replaceAllUsesWith(Result);
8899
8900 // Push the new instruction and any users onto the worklist.
8901 WorkList.push_back(Result);
8902 AddUsersToWorkList(*Result);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00008903
8904 // Move the name to the new instruction first...
8905 std::string OldName = I->getName(); I->setName("");
Chris Lattner950fc782003-10-07 22:58:41 +00008906 Result->setName(OldName);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00008907
8908 // Insert the new instruction into the basic block...
8909 BasicBlock *InstParent = I->getParent();
Chris Lattner7515cab2004-11-14 19:13:23 +00008910 BasicBlock::iterator InsertPos = I;
8911
8912 if (!isa<PHINode>(Result)) // If combining a PHI, don't insert
8913 while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
8914 ++InsertPos;
8915
8916 InstParent->getInstList().insert(InsertPos, Result);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00008917
Chris Lattner63d75af2004-05-01 23:27:23 +00008918 // Make sure that we reprocess all operands now that we reduced their
8919 // use counts.
Chris Lattnerb643a9e2004-05-01 23:19:52 +00008920 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
8921 if (Instruction *OpI = dyn_cast<Instruction>(I->getOperand(i)))
8922 WorkList.push_back(OpI);
8923
Chris Lattner396dbfe2004-06-09 05:08:07 +00008924 // Instructions can end up on the worklist more than once. Make sure
8925 // we do not process an instruction that has been deleted.
8926 removeFromWorkList(I);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00008927
8928 // Erase the old instruction.
8929 InstParent->getInstList().erase(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00008930 } else {
Bill Wendling5dbf43c2006-11-26 09:46:52 +00008931 DOUT << "IC: MOD = " << *I;
Chris Lattner7d2a5392004-03-13 23:54:27 +00008932
Chris Lattnerae7a0d32002-08-02 19:29:35 +00008933 // If the instruction was modified, it's possible that it is now dead.
8934 // if so, remove it.
Chris Lattner63d75af2004-05-01 23:27:23 +00008935 if (isInstructionTriviallyDead(I)) {
8936 // Make sure we process all operands now that we are reducing their
8937 // use counts.
8938 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
8939 if (Instruction *OpI = dyn_cast<Instruction>(I->getOperand(i)))
8940 WorkList.push_back(OpI);
Misha Brukmanb1c93172005-04-21 23:48:37 +00008941
Chris Lattner63d75af2004-05-01 23:27:23 +00008942 // Instructions may end up in the worklist more than once. Erase all
Robert Bocchinoa8352962006-01-13 22:48:06 +00008943 // occurrences of this instruction.
Chris Lattner99f48c62002-09-02 04:59:56 +00008944 removeFromWorkList(I);
Chris Lattner31f486c2005-01-31 05:36:43 +00008945 I->eraseFromParent();
Chris Lattner396dbfe2004-06-09 05:08:07 +00008946 } else {
8947 WorkList.push_back(Result);
8948 AddUsersToWorkList(*Result);
Chris Lattnerae7a0d32002-08-02 19:29:35 +00008949 }
Chris Lattner053c0932002-05-14 15:24:07 +00008950 }
Chris Lattner260ab202002-04-18 17:39:14 +00008951 Changed = true;
Chris Lattnerca081252001-12-14 16:52:21 +00008952 }
8953 }
8954
Chris Lattner260ab202002-04-18 17:39:14 +00008955 return Changed;
Chris Lattner04805fa2002-02-26 21:46:54 +00008956}
8957
Brian Gaeke38b79e82004-07-27 17:43:21 +00008958FunctionPass *llvm::createInstructionCombiningPass() {
Chris Lattner260ab202002-04-18 17:39:14 +00008959 return new InstCombiner();
Chris Lattner04805fa2002-02-26 21:46:54 +00008960}
Brian Gaeke960707c2003-11-11 22:41:34 +00008961